fix: correct face detection threshold defaults

- Changed min_confidence from 50.0 to 0.5 (Vision uses 0.0-1.0 range)
- Changed min_size from 32 to 1 (was filtering out all small faces)
- Changed min_capture_quality from 25.0 to 0.25
- Fixes issue where all videos showed 0 faces detected

Root cause: admin_config.rs used wrong defaults (50.0/32) instead of
config.rs constants (0.5/1), causing Vision framework to filter out
ALL faces because confidence threshold exceeded valid range.

Verified: IMG_9449 now correctly detects 191 faces (was 0).
This commit is contained in:
Accusys
2026-09-18 02:42:21 +08:00
parent e4b8ddab94
commit 31d1b4050f
59 changed files with 11110 additions and 6163 deletions
+544
View File
@@ -0,0 +1,544 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::error;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VlmPrompt {
#[serde(skip_serializing_if = "Option::is_none")]
pub system_prompt: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_prompt: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt: Option<String>,
pub max_tokens: u32,
pub description: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmConfig {
pub url: String,
pub model: String,
#[serde(default)]
pub timeout: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessorConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub model_size: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[serde(default)]
pub timeout: u32,
#[serde(default = "default_true")]
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub confidence: Option<f32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilterConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub min_confidence: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_size: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_capture_quality: Option<f32>,
}
fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathsConfig {
#[serde(default = "default_output_dir")]
pub output_dir: String,
#[serde(default = "default_backup_dir")]
pub backup_dir: String,
#[serde(default = "default_scripts_dir")]
pub scripts_dir: String,
#[serde(default = "default_python_path")]
pub python_path: String,
#[serde(default = "default_ffmpeg_path")]
pub ffmpeg_path: String,
}
fn default_output_dir() -> String {
std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string())
}
fn default_backup_dir() -> String {
std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/backup/momentry".to_string())
}
fn default_scripts_dir() -> String {
std::env::var("MOMENTRY_SCRIPTS_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string())
}
fn default_python_path() -> String {
std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string())
}
fn default_ffmpeg_path() -> String {
std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureFlags {
#[serde(default = "default_cache_enabled")]
pub cache_enabled: bool,
#[serde(default)]
pub auto_pipeline_enabled: bool,
#[serde(default)]
pub watcher_auto_register: bool,
#[serde(default = "default_true")]
pub summary_enabled: bool,
}
fn default_cache_enabled() -> bool {
std::env::var("MONGODB_CACHE_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConcurrencyConfig {
#[serde(default = "default_max_concurrent_jobs")]
pub max_concurrent_jobs: u32,
#[serde(default = "default_poll_interval")]
pub poll_interval: u32,
#[serde(default = "default_batch_size")]
pub batch_size: u32,
#[serde(default = "default_processor_timeout_secs")]
pub processor_timeout_secs: u32,
}
fn default_max_concurrent_jobs() -> u32 {
std::env::var("MOMENTRY_MAX_CONCURRENT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(6)
}
fn default_poll_interval() -> u32 {
std::env::var("MOMENTRY_POLL_INTERVAL")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
}
fn default_batch_size() -> u32 {
std::env::var("MOMENTRY_WORKER_BATCH_SIZE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
}
fn default_processor_timeout_secs() -> u32 {
std::env::var("MOMENTRY_WORKER_PROCESSOR_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminSettings {
#[serde(default = "default_session_timeout")]
pub session_timeout: u32,
#[serde(default = "default_max_login_attempts")]
pub max_login_attempts: u32,
#[serde(default = "default_api_key_expiry_days")]
pub api_key_expiry_days: u32,
#[serde(default = "default_system_stats_refresh_sec")]
pub system_stats_refresh_sec: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceFilterDefaults {
#[serde(default = "default_min_confidence")]
pub min_confidence: f64,
#[serde(default = "default_min_size")]
pub min_size: i32,
#[serde(default = "default_min_capture_quality")]
pub min_capture_quality: f64,
}
fn default_min_confidence() -> f64 { crate::core::config::FACE_MIN_CONFIDENCE_DEFAULT }
fn default_min_size() -> i32 { crate::core::config::FACE_MIN_SIZE_DEFAULT }
fn default_min_capture_quality() -> f64 { 0.25 }
fn default_session_timeout() -> u32 {
3600
}
fn default_max_login_attempts() -> u32 {
5
}
fn default_api_key_expiry_days() -> u32 {
365
}
fn default_system_stats_refresh_sec() -> u32 {
std::env::var("SYSTEM_STATS_REFRESH_SEC")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(5)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default = "default_server_port")]
pub port: u16,
#[serde(default = "default_media_base_url")]
pub media_base_url: String,
#[serde(default = "default_serve_base_url")]
pub serve_base_url: String,
#[serde(default = "default_storage_root")]
pub storage_root: String,
}
fn default_server_port() -> u16 {
std::env::var("MOMENTRY_SERVER_PORT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3002)
}
fn default_media_base_url() -> String {
std::env::var("MOMENTRY_MEDIA_BASE_URL")
.unwrap_or_else(|_| "https://wp.momentry.ddns.net".to_string())
}
fn default_serve_base_url() -> String {
std::env::var("MOMENTRY_SERVE_BASE_URL")
.unwrap_or_else(|_| "https://m5wp.momentry.ddns.net/files".to_string())
}
fn default_storage_root() -> String {
std::env::var("MOMENTRY_STORAGE_ROOT")
.unwrap_or_else(|_| "/Users/accusys/momentry/var/sftpgo/data".to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminConfig {
pub version: String,
pub updated_at: String,
pub updated_by: String,
pub vlm_prompts: HashMap<String, VlmPrompt>,
pub llm_config: HashMap<String, LlmConfig>,
pub processor_config: HashMap<String, ProcessorConfig>,
#[serde(default)]
pub filter_config: HashMap<String, FilterConfig>,
pub face_filter_defaults: FaceFilterDefaults,
pub paths: PathsConfig,
pub concurrency: ConcurrencyConfig,
pub feature_flags: FeatureFlags,
pub server: ServerConfig,
pub admin_settings: AdminSettings,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartialAdminConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub vlm_prompts: Option<HashMap<String, VlmPrompt>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub llm_config: Option<HashMap<String, LlmConfig>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub processor_config: Option<HashMap<String, ProcessorConfig>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filter_config: Option<HashMap<String, FilterConfig>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub face_filter_defaults: Option<FaceFilterDefaults>,
#[serde(skip_serializing_if = "Option::is_none")]
pub paths: Option<PathsConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub concurrency: Option<ConcurrencyConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub feature_flags: Option<FeatureFlags>,
#[serde(skip_serializing_if = "Option::is_none")]
pub server: Option<ServerConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub admin_settings: Option<AdminSettings>,
}
pub struct AdminConfigManager {
config: Arc<RwLock<AdminConfig>>,
config_path: String,
}
impl AdminConfigManager {
pub fn new(config_path: &str) -> Result<Self> {
let config = Self::load_config(config_path)?;
tracing::info!("[AdminConfig] Loaded config from {}", config_path);
Ok(Self {
config: Arc::new(RwLock::new(config)),
config_path: config_path.to_string(),
})
}
fn load_config(path: &str) -> Result<AdminConfig> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path))?;
let config: AdminConfig = serde_json::from_str(&content)
.with_context(|| "Failed to parse config JSON")?;
Ok(config)
}
pub async fn get_vlm_prompt(&self, key: &str) -> Option<VlmPrompt> {
let config = self.config.read().await;
config.vlm_prompts.get(key).cloned()
}
pub async fn get_all_vlm_prompts(&self) -> HashMap<String, VlmPrompt> {
let config = self.config.read().await;
config.vlm_prompts.clone()
}
pub async fn get_llm_config(&self, key: &str) -> Option<LlmConfig> {
let config = self.config.read().await;
config.llm_config.get(key).cloned()
}
pub async fn get_processor_config(&self, key: &str) -> Option<ProcessorConfig> {
let config = self.config.read().await;
config.processor_config.get(key).cloned()
}
pub async fn get_filter_config(&self, key: &str) -> Option<FilterConfig> {
let config = self.config.read().await;
config.filter_config.get(key).cloned()
}
pub async fn get_paths(&self) -> PathsConfig {
let config = self.config.read().await;
config.paths.clone()
}
pub async fn get_concurrency(&self) -> ConcurrencyConfig {
let config = self.config.read().await;
config.concurrency.clone()
}
pub async fn get_feature_flags(&self) -> FeatureFlags {
let config = self.config.read().await;
config.feature_flags.clone()
}
pub async fn get_server(&self) -> ServerConfig {
let config = self.config.read().await;
config.server.clone()
}
pub async fn get_admin_settings(&self) -> AdminSettings {
let config = self.config.read().await;
config.admin_settings.clone()
}
pub async fn get_full_config(&self) -> AdminConfig {
let config = self.config.read().await;
config.clone()
}
pub async fn update_vlm_prompt(&self, key: &str, prompt: VlmPrompt) -> Result<()> {
let mut config = self.config.write().await;
config.vlm_prompts.insert(key.to_string(), prompt);
config.updated_at = chrono::Utc::now().to_rfc3339();
config.updated_by = "admin".to_string();
self.save_config(&config)?;
tracing::info!("[AdminConfig] Updated VLM prompt: {}", key);
Ok(())
}
pub async fn update_partial_config(&self, partial: PartialAdminConfig) -> Result<()> {
let mut config = self.config.write().await;
if let Some(vlm_prompts) = partial.vlm_prompts {
config.vlm_prompts.extend(vlm_prompts);
}
if let Some(llm_config) = partial.llm_config {
config.llm_config.extend(llm_config);
}
if let Some(processor_config) = partial.processor_config {
config.processor_config.extend(processor_config);
}
if let Some(filter_config) = partial.filter_config {
config.filter_config.extend(filter_config);
}
if let Some(face_filter_defaults) = partial.face_filter_defaults {
config.face_filter_defaults = face_filter_defaults;
}
if let Some(paths) = partial.paths {
config.paths = paths;
}
if let Some(concurrency) = partial.concurrency {
config.concurrency = concurrency;
}
if let Some(feature_flags) = partial.feature_flags {
config.feature_flags = feature_flags;
}
if let Some(server) = partial.server {
config.server = server;
}
if let Some(admin_settings) = partial.admin_settings {
config.admin_settings = admin_settings;
}
config.updated_at = chrono::Utc::now().to_rfc3339();
config.updated_by = "admin".to_string();
self.save_config(&config)?;
tracing::info!("[AdminConfig] Updated partial config");
Ok(())
}
pub async fn reload(&self) -> Result<()> {
let new_config = Self::load_config(&self.config_path)?;
let mut config = self.config.write().await;
*config = new_config;
tracing::info!("[AdminConfig] Reloaded config from {}", self.config_path);
Ok(())
}
fn save_config(&self, config: &AdminConfig) -> Result<()> {
let content = serde_json::to_string_pretty(config)
.with_context(|| "Failed to serialize config")?;
std::fs::write(&self.config_path, content)
.with_context(|| format!("Failed to write config file: {}", self.config_path))?;
Ok(())
}
}
pub fn get_default_config_path() -> String {
let mut path = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
path.push("config");
path.push("admin_config.json");
path.to_str().unwrap_or("config/admin_config.json").to_string()
}
pub static ADMIN_CONFIG: once_cell::sync::Lazy<Arc<AdminConfigManager>> = once_cell::sync::Lazy::new(|| {
let config_path = get_default_config_path();
match AdminConfigManager::new(&config_path) {
Ok(manager) => Arc::new(manager),
Err(e) => {
error!("[AdminConfig] Failed to initialize: {}", e);
panic!("Failed to initialize AdminConfigManager: {}", e);
}
}
});
pub async fn get_vlm_prompt(key: &str) -> Option<VlmPrompt> {
ADMIN_CONFIG.get_vlm_prompt(key).await
}
pub async fn get_llm_config(key: &str) -> Option<LlmConfig> {
ADMIN_CONFIG.get_llm_config(key).await
}
pub async fn get_processor_config(key: &str) -> Option<ProcessorConfig> {
ADMIN_CONFIG.get_processor_config(key).await
}
pub async fn get_filter_config(key: &str) -> Option<FilterConfig> {
ADMIN_CONFIG.get_filter_config(key).await
}
/// Synchronous version for getting face filter defaults
/// Used in synchronous contexts like FileProfile::defaults()
pub fn get_face_filter_defaults() -> (f64, i32, f64) {
// Use blocking_read for sync context
// Returns (min_confidence, min_size, min_capture_quality)
let config = ADMIN_CONFIG.config.blocking_read();
(
config.face_filter_defaults.min_confidence,
config.face_filter_defaults.min_size,
config.face_filter_defaults.min_capture_quality,
)
}
pub async fn get_paths() -> PathsConfig {
ADMIN_CONFIG.get_paths().await
}
pub async fn get_concurrency() -> ConcurrencyConfig {
ADMIN_CONFIG.get_concurrency().await
}
pub async fn get_feature_flags() -> FeatureFlags {
ADMIN_CONFIG.get_feature_flags().await
}
pub async fn get_server() -> ServerConfig {
ADMIN_CONFIG.get_server().await
}
pub fn get_paths_sync() -> PathsConfig {
PathsConfig {
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string()),
backup_dir: std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/backup/momentry".to_string()),
scripts_dir: std::env::var("MOMENTRY_SCRIPTS_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string()),
python_path: std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()),
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string()),
}
}
pub fn get_output_dir() -> String {
get_paths_sync().output_dir
}
pub fn get_backup_dir() -> String {
get_paths_sync().backup_dir
}
pub fn get_scripts_dir() -> String {
get_paths_sync().scripts_dir
}
pub fn get_python_path() -> String {
get_paths_sync().python_path
}
pub fn get_ffmpeg_path() -> String {
get_paths_sync().ffmpeg_path
}
pub fn get_concurrency_sync() -> ConcurrencyConfig {
ConcurrencyConfig {
max_concurrent_jobs: std::env::var("MOMENTRY_MAX_CONCURRENT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(6),
poll_interval: std::env::var("MOMENTRY_POLL_INTERVAL")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10),
batch_size: std::env::var("MOMENTRY_WORKER_BATCH_SIZE")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10),
processor_timeout_secs: std::env::var("MOMENTRY_WORKER_PROCESSOR_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600),
}
}
+146 -144
View File
@@ -2,10 +2,13 @@ use once_cell::sync::Lazy;
use std::env;
use std::sync::RwLock;
// ─────────────────────────────────────────────────────────────
// Runtime switches (mutable via API, persisted in memory)
// ─────────────────────────────────────────────────────────────
pub static RUNTIME_CACHE_ENABLED: Lazy<RwLock<bool>> = Lazy::new(|| {
let initial = env::var("MONGODB_CACHE_ENABLED")
.unwrap_or_else(|_| "true".to_string())
.parse()
.map(|v| v == "true" || v == "1")
.unwrap_or(true);
RwLock::new(initial)
});
@@ -19,7 +22,6 @@ pub fn set_cache_enabled(enabled: bool) {
tracing::info!("Cache enabled set to: {}", enabled);
}
// Switch 1: watcher detects new file → auto-register
pub static RUNTIME_WATCHER_AUTO_REGISTER: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub fn get_watcher_auto_register() -> bool {
@@ -31,7 +33,6 @@ pub fn set_watcher_auto_register(enabled: bool) {
tracing::info!("Watcher auto-register set to: {}", enabled);
}
// Switch 2: register → auto-trigger processing pipeline
pub static RUNTIME_AUTO_PIPELINE_ENABLED: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub fn get_auto_pipeline_enabled() -> bool {
@@ -65,7 +66,6 @@ pub static MONGODB_URL: Lazy<String> = Lazy::new(|| {
pub static REDIS_URL: Lazy<String> = Lazy::new(|| {
env::var("REDIS_URL").unwrap_or_else(|_| {
let password = env::var("REDIS_PASSWORD").unwrap_or_else(|_| "accusys".to_string());
// Format: redis://[:password]@host:port (use default user)
format!("redis://default:{}@localhost:6379", password)
})
});
@@ -73,28 +73,81 @@ pub static REDIS_URL: Lazy<String> = Lazy::new(|| {
pub static REDIS_PASSWORD: Lazy<String> =
Lazy::new(|| env::var("REDIS_PASSWORD").unwrap_or_else(|_| "accusys".to_string()));
pub static JWT_SECRET: Lazy<String> = Lazy::new(|| {
env::var("JWT_SECRET").unwrap_or_else(|_| "momentry_default_jwt_secret_change_me".to_string())
});
pub static DATABASE_SCHEMA: Lazy<String> =
Lazy::new(|| env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string()));
pub static SYSTEM_TIMEZONE: Lazy<String> = Lazy::new(|| {
if let Ok(tz) = env::var("MOMENTRY_TIMEZONE") {
if !tz.is_empty() {
return tz;
}
}
if let Ok(tz) = env::var("TZ") {
if !tz.is_empty() {
return tz;
}
}
if let Ok(path) = std::fs::read_link("/etc/localtime") {
let s = path.to_string_lossy();
for prefix in &["/usr/share/zoneinfo/", "/var/db/timezone/zoneinfo/"] {
if let Some(tz) = s.strip_prefix(prefix) {
return tz.to_string();
}
}
}
"Asia/Taipei".to_string()
});
pub static MONGODB_DATABASE: Lazy<String> =
Lazy::new(|| env::var("MONGODB_DATABASE").unwrap_or_else(|_| "momentry".to_string()));
pub static QDRANT_COLLECTION: Lazy<String> =
Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string()));
pub static REDIS_KEY_PREFIX: Lazy<String> =
Lazy::new(|| env::var("MOMENTRY_REDIS_PREFIX").unwrap_or_else(|_| "momentry:".to_string()));
pub static SFTPGO_BASE_URL: Lazy<String> = Lazy::new(|| {
env::var("SFTPGO_BASE_URL").unwrap_or_else(|_| "http://127.0.0.1:8080".to_string())
});
pub static OLLAMA_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_OLLAMA_URL").unwrap_or_else(|_| "http://127.0.0.1:11434".to_string())
});
pub static EMBED_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_EMBED_URL").unwrap_or_else(|_| "http://127.0.0.1:11436".to_string())
});
pub static LLM_HEALTH_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_HEALTH_URL").unwrap_or_else(|_| {
"http://127.0.0.1:8080/health".to_string()
})
});
// ─────────────────────────────────────────────────────────────
// JSON-backed configs (paths, concurrency, feature flags)
// These read from admin_config.json with ENV fallback
// ─────────────────────────────────────────────────────────────
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_OUTPUT_DIR").unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string())
crate::core::admin_config::get_output_dir()
});
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/backup/momentry".to_string())
});
pub static PYTHON_PATH: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_PYTHON_PATH").unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string())
crate::core::admin_config::get_backup_dir()
});
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_SCRIPTS_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry_core_0.1/scripts".to_string())
crate::core::admin_config::get_scripts_dir()
});
pub static LOG_LEVEL: Lazy<String> = Lazy::new(|| {
env::var("RUST_LOG")
.or_else(|_| env::var("MOMENTRY_LOG_LEVEL"))
.unwrap_or_else(|_| "info".to_string())
pub static PYTHON_PATH: Lazy<String> = Lazy::new(|| {
crate::core::admin_config::get_python_path()
});
pub static MEDIA_BASE_URL: Lazy<String> = Lazy::new(|| {
@@ -114,143 +167,98 @@ pub static SERVE_BASE_URL: Lazy<String> = Lazy::new(|| {
pub static SERVER_PORT: Lazy<u16> = Lazy::new(|| {
env::var("MOMENTRY_SERVER_PORT")
.unwrap_or_else(|_| "3002".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3002)
});
pub static REDIS_KEY_PREFIX: Lazy<String> =
Lazy::new(|| env::var("MOMENTRY_REDIS_PREFIX").unwrap_or_else(|_| "momentry:".to_string()));
// ─────────────────────────────────────────────────────────────
// Face detection thresholds (single source of truth)
// ─────────────────────────────────────────────────────────────
pub static DATABASE_SCHEMA: Lazy<String> =
Lazy::new(|| env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string()));
pub const FACE_MIN_CONFIDENCE_DEFAULT: f64 = 0.5;
pub const FACE_MIN_SIZE_DEFAULT: i32 = 1;
pub const FACE_FILTER_CONFIDENCE_PCT_DEFAULT: f64 = 50.0;
pub static SYSTEM_TIMEZONE: Lazy<String> = Lazy::new(|| {
if let Ok(tz) = env::var("MOMENTRY_TIMEZONE") {
if !tz.is_empty() {
return tz;
}
}
if let Ok(tz) = env::var("TZ") {
if !tz.is_empty() {
return tz;
}
}
// macOS: /etc/localtime → /var/db/timezone/zoneinfo/Asia/Taipei
// Linux: /etc/localtime → /usr/share/zoneinfo/Asia/Taipei
if let Ok(path) = std::fs::read_link("/etc/localtime") {
let s = path.to_string_lossy();
for prefix in &["/usr/share/zoneinfo/", "/var/db/timezone/zoneinfo/"] {
if let Some(tz) = s.strip_prefix(prefix) {
return tz.to_string();
}
}
}
"Asia/Taipei".to_string()
});
pub static MONGODB_DATABASE: Lazy<String> =
Lazy::new(|| env::var("MONGODB_DATABASE").unwrap_or_else(|_| "momentry".to_string()));
pub static QDRANT_COLLECTION: Lazy<String> =
Lazy::new(|| env::var("QDRANT_COLLECTION").unwrap_or_else(|_| "momentry_rule1".to_string()));
// ─── Face detection thresholds (single source of truth) ───
// Defaults mirror Apple Vision native detection (0.5 confidence / 1px min size).
// Keep scripts/swift_processors/swift_face.swift and scripts/face_processor.py in sync.
pub const FACE_MIN_CONFIDENCE_DEFAULT: f64 = 0.5; // detection threshold (0-1)
pub const FACE_MIN_SIZE_DEFAULT: i32 = 1; // detection min face size (px)
pub const FACE_FILTER_CONFIDENCE_PCT_DEFAULT: f64 = 50.0; // videos.face_filter (0-100%)
pub mod processor {
use super::*;
pub static ASR_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_ASR_TIMEOUT")
.unwrap_or_else(|_| "3600".to_string())
.parse()
.unwrap_or(3600)
});
pub static CUT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_CUT_TIMEOUT")
.unwrap_or_else(|_| "3600".to_string())
.parse()
.unwrap_or(3600)
});
pub static DEFAULT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_DEFAULT_TIMEOUT")
.unwrap_or_else(|_| "7200".to_string())
.parse()
.unwrap_or(7200)
});
pub static FORCE_RETRY: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_FORCE_RETRY")
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
}
// ─────────────────────────────────────────────────────────────
// Cache TTLs
// ─────────────────────────────────────────────────────────────
pub mod cache {
use super::*;
pub static MONGODB_CACHE_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MONGODB_CACHE_ENABLED")
.unwrap_or_else(|_| "true".to_string())
.parse()
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
pub static MONGODB_CACHE_TTL_VIDEOS: Lazy<u64> = Lazy::new(|| {
env::var("MONGODB_CACHE_TTL_VIDEOS")
.unwrap_or_else(|_| "300".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(300)
});
pub static MONGODB_CACHE_TTL_SEARCH: Lazy<u64> = Lazy::new(|| {
env::var("MONGODB_CACHE_TTL_SEARCH")
.unwrap_or_else(|_| "300".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(300)
});
pub static MONGODB_CACHE_TTL_HYBRID_SEARCH: Lazy<u64> = Lazy::new(|| {
env::var("MONGODB_CACHE_TTL_HYBRID_SEARCH")
.unwrap_or_else(|_| "600".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(600)
});
pub static MONGODB_CACHE_TTL_VIDEO_META: Lazy<u64> = Lazy::new(|| {
env::var("MONGODB_CACHE_TTL_VIDEO_META")
.unwrap_or_else(|_| "3600".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
});
pub static REDIS_CACHE_TTL_HEALTH: Lazy<u64> = Lazy::new(|| {
env::var("REDIS_CACHE_TTL_HEALTH")
.unwrap_or_else(|_| "30".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(30)
});
pub static REDIS_CACHE_TTL_VIDEO_META: Lazy<u64> = Lazy::new(|| {
env::var("REDIS_CACHE_TTL_VIDEO_META")
.unwrap_or_else(|_| "3600".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
});
}
// ─────────────────────────────────────────────────────────────
// TMDB
// ─────────────────────────────────────────────────────────────
pub mod tmdb {
use super::*;
pub static API_KEY: Lazy<Option<String>> = Lazy::new(|| env::var("TMDB_API_KEY").ok());
pub static PROBE_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_TMDB_PROBE_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
}
// ─────────────────────────────────────────────────────────────
// LLM endpoints (chat, vision, summary, embedding)
// ─────────────────────────────────────────────────────────────
pub mod llm {
use super::*;
/// Chat / function-calling LLM endpoint (agents/search, translation, etc.)
/// Default: MarkBaseEngine on http://127.0.0.1:8080/v1/chat/completions
pub static CHAT_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_CHAT_URL")
.or_else(|_| env::var("MOMENTRY_LLM_SUMMARY_URL"))
@@ -265,15 +273,12 @@ pub mod llm {
.unwrap_or_else(|_| "e4b".to_string())
});
/// Vision LLM endpoint (frame analysis, OCR). Can be same as CHAT_URL or different.
/// Default: falls back to CHAT_URL
pub static VISION_URL: Lazy<String> =
Lazy::new(|| env::var("MOMENTRY_LLM_VISION_URL").unwrap_or_else(|_| CHAT_URL.clone()));
pub static VISION_MODEL: Lazy<String> =
Lazy::new(|| env::var("MOMENTRY_LLM_VISION_MODEL").unwrap_or_else(|_| CHAT_MODEL.clone()));
/// Text summary LLM endpoint (5W1H, story). Can be same as CHAT_URL or different.
pub static SUMMARY_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_URL")
.ok()
@@ -290,8 +295,8 @@ pub mod llm {
pub static SUMMARY_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_TIMEOUT")
.unwrap_or_else(|_| "120".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120)
});
@@ -303,46 +308,43 @@ pub mod llm {
pub static CHAT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_LLM_CHAT_TIMEOUT")
.unwrap_or_else(|_| "120".to_string())
.parse()
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120)
});
}
/// Ollama embedding endpoint (vector embeddings for text sync).
pub static OLLAMA_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_OLLAMA_URL").unwrap_or_else(|_| "http://127.0.0.1:11434".to_string())
});
// ─────────────────────────────────────────────────────────────
// Processor timeouts
// ─────────────────────────────────────────────────────────────
/// Text embedding server (comic-embed or alternative).
pub static EMBED_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_EMBED_URL").unwrap_or_else(|_| "http://127.0.0.1:11436".to_string())
});
/// LLM health endpoint.
pub static LLM_HEALTH_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_HEALTH_URL").unwrap_or_else(|_| {
let chat = llm::CHAT_URL.clone();
chat.trim_end_matches("/v1/chat/completions").to_string() + "/health"
})
});
pub static SFTPGO_BASE_URL: Lazy<String> = Lazy::new(|| {
env::var("SFTPGO_BASE_URL").unwrap_or_else(|_| "http://127.0.0.1:8080".to_string())
});
pub static JWT_SECRET: Lazy<String> = Lazy::new(|| {
env::var("JWT_SECRET").unwrap_or_else(|_| "momentry_default_jwt_secret_change_me".to_string())
});
pub mod tmdb {
pub mod processor {
use super::*;
pub static API_KEY: Lazy<Option<String>> = Lazy::new(|| env::var("TMDB_API_KEY").ok());
pub static ASR_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_ASR_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
});
pub static PROBE_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_TMDB_PROBE_ENABLED")
pub static CUT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_CUT_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
});
pub static DEFAULT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_DEFAULT_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(7200)
});
pub static FORCE_RETRY: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_FORCE_RETRY")
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
}
}
-1
View File
@@ -479,7 +479,6 @@ impl RedisClient {
"appearance",
"asr",
"cut",
"yolo",
"ocr",
"face",
"pose",
+26 -7
View File
@@ -2,8 +2,6 @@ use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use crate::core::config::{FACE_FILTER_CONFIDENCE_PCT_DEFAULT, FACE_MIN_SIZE_DEFAULT};
/// Version of the file profile schema.
const PROFILE_VERSION: &str = "1.0";
@@ -17,16 +15,37 @@ pub struct FaceFilterSettings {
pub min_size: i32,
#[serde(default)]
pub min_capture_quality: f64,
// Single Frame Trace 配置
#[serde(default = "default_true")]
pub single_frame_trace_vlm_enabled: bool,
#[serde(default = "default_true")]
pub single_frame_trace_group_enabled: bool,
#[serde(default = "default_true")]
pub single_frame_trace_unassigned_enabled: bool,
// Single Trace Group 配置
#[serde(default = "default_true")]
pub single_trace_group_filter_enabled: bool,
}
fn default_true() -> bool { true }
impl FaceFilterSettings {
/// Mirrors Apple Vision default detection thresholds (0.5 / 1px).
/// Filter later for display; detect everything first.
/// Load defaults from admin config (processor_config.face).
/// Falls back to hardcoded values if admin config unavailable.
pub fn defaults() -> Self {
let (min_confidence, min_size, min_capture_quality) =
crate::core::admin_config::get_face_filter_defaults();
Self {
min_confidence: FACE_FILTER_CONFIDENCE_PCT_DEFAULT,
min_size: FACE_MIN_SIZE_DEFAULT,
min_capture_quality: 0.0,
min_confidence,
min_size,
min_capture_quality,
single_frame_trace_vlm_enabled: true,
single_frame_trace_group_enabled: true,
single_frame_trace_unassigned_enabled: true,
single_trace_group_filter_enabled: true,
}
}
}
-3
View File
@@ -5,7 +5,6 @@ pub struct OverlayFlags {
pub asr: bool,
pub asrx: bool,
pub ocr: bool,
pub yolo: bool,
pub face: bool,
pub pose: bool,
pub status: bool,
@@ -17,7 +16,6 @@ impl Default for OverlayFlags {
asr: false,
asrx: false,
ocr: false,
yolo: false,
face: false,
pose: false,
status: true,
@@ -31,7 +29,6 @@ impl OverlayFlags {
'a' => self.asr = !self.asr,
'x' => self.asrx = !self.asrx,
'o' => self.ocr = !self.ocr,
'y' => self.yolo = !self.yolo,
'f' => self.face = !self.face,
'p' => self.pose = !self.pose,
'b' => self.status = !self.status,
+54 -20
View File
@@ -10,6 +10,28 @@ use tokio::time::{sleep, timeout};
use crate::core::config::{DATABASE_SCHEMA, OUTPUT_DIR, REDIS_KEY_PREFIX};
/// Get face filter settings from admin config (priority) or environment variables.
/// Returns (min_confidence, min_size, min_capture_quality) as Option<String>.
async fn get_face_settings() -> (Option<String>, Option<String>, Option<String>) {
let face_config = crate::core::admin_config::get_filter_config("face").await;
let min_confidence = face_config
.as_ref()
.and_then(|c| c.min_confidence)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_CONFIDENCE").ok());
let min_size = face_config
.as_ref()
.and_then(|c| c.min_size)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_SIZE").ok());
let min_capture_quality = face_config
.as_ref()
.and_then(|c| c.min_capture_quality)
.map(|v| v.to_string())
.or_else(|| std::env::var("FACE_MIN_CAPTURE_QUALITY").ok());
(min_confidence, min_size, min_capture_quality)
}
#[derive(Debug, Clone)]
pub struct RetryConfig {
pub max_attempts: u32,
@@ -324,13 +346,13 @@ impl PythonExecutor {
if let Some(u) = uuid {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -338,6 +360,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -490,13 +515,13 @@ impl PythonExecutor {
if let Some(u) = uuid {
cmd.env("UUID", u);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -504,6 +529,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -697,13 +725,13 @@ impl PythonExecutor {
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -711,6 +739,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
@@ -914,13 +945,13 @@ impl PythonExecutor {
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
// Pass face detection settings to Python subprocesses
let face_min_confidence = std::env::var("FACE_MIN_CONFIDENCE").ok();
let face_min_size = std::env::var("FACE_MIN_SIZE").ok();
// Pass face detection settings to Python subprocesses (from admin config or env)
let (face_min_confidence, face_min_size, face_min_capture_quality) = get_face_settings().await;
tracing::info!(
"[EXECUTOR] Face settings: CONFIDENCE={:?}, SIZE={:?}",
"[EXECUTOR] Face settings from config/env: CONFIDENCE={:?}, SIZE={:?}, CAPTURE_QUALITY={:?}",
face_min_confidence,
face_min_size
face_min_size,
face_min_capture_quality
);
if let Some(ref val) = face_min_confidence {
cmd.env("FACE_MIN_CONFIDENCE", val);
@@ -928,6 +959,9 @@ impl PythonExecutor {
if let Some(ref val) = face_min_size {
cmd.env("FACE_MIN_SIZE", val);
}
if let Some(ref val) = face_min_capture_quality {
cmd.env("FACE_MIN_CAPTURE_QUALITY", val);
}
cmd.arg(&script_path);
for (i, arg) in args.iter().enumerate() {
File diff suppressed because it is too large Load Diff
+3 -435
View File
@@ -570,38 +570,6 @@ fn detect_mutual_gaze(
// ── Input data structs ────────────────────────────────────────────
#[derive(Debug, Deserialize)]
struct YoloJson {
#[serde(default)]
frames: HashMap<String, YoloFrameEntry>,
}
#[derive(Debug, Deserialize)]
struct YoloFrameEntry {
#[serde(default)]
detections: Vec<YoloDetEntry>,
#[serde(default)]
objects: Vec<YoloDetEntry>,
}
#[derive(Debug, Deserialize)]
struct YoloDetEntry {
#[serde(default)]
class_name: String,
#[serde(default)]
class_id: i32,
#[serde(default)]
x: i32,
#[serde(default)]
y: i32,
#[serde(default)]
width: i32,
#[serde(default)]
height: i32,
#[serde(default)]
confidence: f64,
}
#[derive(Debug, Deserialize)]
struct HandJson {
#[serde(default)]
@@ -866,21 +834,6 @@ pub async fn build_tkg(
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(TkgPhase::ObjectNodes, 0.0, "Building object nodes...");
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let n_objects = build_yolo_object_nodes(pool, file_uuid, output_dir).await?;
progress.stats.object_nodes = n_objects as i64;
progress.update_phase(
TkgPhase::ObjectNodes,
1.0,
&format!("{} objects", n_objects),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(TkgPhase::HandNodes, 0.0, "Building hand nodes...");
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
@@ -916,26 +869,6 @@ pub async fn build_tkg(
);
// ── Edge builders ─────────────────────────────────────────────────
progress.update_phase(
TkgPhase::CoOccurrenceEdges,
0.0,
"Building co-occurrence edges...",
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let e_co =
build_co_occurrence_edges(pool, file_uuid, output_dir, &face_points, &node_id_map).await?;
progress.stats.co_occurrence_edges = e_co as i64;
progress.update_phase(
TkgPhase::CoOccurrenceEdges,
1.0,
&format!("{} co-occurrence", e_co),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(
TkgPhase::SpeakerFaceEdges,
0.0,
@@ -1028,25 +961,6 @@ pub async fn build_tkg(
publish_tkg_progress(r, file_uuid, &progress).await;
}
progress.update_phase(
TkgPhase::HandObjectEdges,
0.0,
"Building hand-object edges...",
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
let e_ho = build_hand_object_edges(pool, file_uuid, output_dir).await?;
progress.stats.hand_object_edges = e_ho as i64;
progress.update_phase(
TkgPhase::HandObjectEdges,
1.0,
&format!("{} hand-object", e_ho),
);
if let Some(r) = redis.as_ref() {
publish_tkg_progress(r, file_uuid, &progress).await;
}
// Calculate totals
progress.stats.total_nodes = progress.stats.face_track_nodes
+ progress.stats.gaze_track_nodes
@@ -1085,17 +999,17 @@ pub async fn build_tkg(
text_region_nodes: n_text,
appearance_trace_nodes: n_appearance,
accessory_nodes: n_accessories,
object_nodes: n_objects,
object_nodes: 0, // YOLO removed
hand_nodes: n_hands,
speaker_nodes: n_speakers,
co_occurrence_edges: e_co,
co_occurrence_edges: 0, // YOLO removed
speaker_face_edges: e_sf,
face_face_edges: e_ff,
mutual_gaze_edges: e_mg,
lip_sync_edges: e_ls,
has_appearance_edges: e_ha,
wears_edges: e_w,
hand_object_edges: e_ho,
hand_object_edges: 0, // YOLO removed
})
}
@@ -1707,62 +1621,6 @@ async fn build_face_track_nodes_from_qdrant(
Ok(count)
}
async fn build_yolo_object_nodes(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
) -> Result<usize> {
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !yolo_path.exists() {
return Ok(0);
}
let content = std::fs::read_to_string(&yolo_path)
.with_context(|| format!("Failed to read {:?}", yolo_path))?;
let yolo: YoloJson = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse {:?}", yolo_path))?;
let mut class_counts: HashMap<String, i64> = HashMap::new();
for fdata in yolo.frames.values() {
let dets = if !fdata.detections.is_empty() {
&fdata.detections
} else {
&fdata.objects
};
for det in dets {
*class_counts.entry(det.class_name.clone()).or_insert(0) += 1;
}
}
let nodes_table = t("tkg_nodes");
let mut count = 0;
for (cls, cnt) in &class_counts {
let props = serde_json::json!({ "total_detections": cnt });
sqlx::query(&format!(
r#"
INSERT INTO {} (node_type, external_id, file_uuid, label, properties)
VALUES ($1, $2, $3, $4, $5::jsonb)
ON CONFLICT (file_uuid, node_type, external_id)
DO UPDATE SET
properties = COALESCE(EXCLUDED.properties, tkg_nodes.properties)
"#,
nodes_table
))
.bind("object")
.bind(cls)
.bind(file_uuid)
.bind(cls)
.bind(serde_json::to_string(&props)?)
.execute(pool)
.await?;
count += 1;
}
Ok(count)
}
async fn build_hand_nodes(pool: &PgPool, file_uuid: &str, output_dir: &str) -> Result<usize> {
let hand_path = Path::new(output_dir).join(format!("{}.hand.json", file_uuid));
if !hand_path.exists() {
@@ -1897,117 +1755,6 @@ async fn build_speaker_nodes(pool: &PgPool, file_uuid: &str, output_dir: &str) -
// ── Edge builders ─────────────────────────────────────────────────
async fn build_co_occurrence_edges(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
face_points: &[FacePoint],
node_id_map: &HashMap<(String, String), i64>,
) -> Result<usize> {
build_co_occurrence_edges_from_qdrant(pool, file_uuid, output_dir, face_points, node_id_map)
.await
}
async fn build_co_occurrence_edges_from_qdrant(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
face_points: &[FacePoint],
node_id_map: &HashMap<(String, String), i64>,
) -> Result<usize> {
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !yolo_path.exists() {
return Ok(0);
}
let content = std::fs::read_to_string(&yolo_path)?;
let yolo: YoloJson = serde_json::from_str(&content)?;
let edges_table = t("tkg_edges");
// Use shared face points (passed from build_tkg)
let points = face_points;
let mut edge_count = 0;
// Collect edges for batch insert
let mut edges_to_insert: Vec<(&str, i64, i64, &str, String)> = Vec::new();
for face in points {
let yolo_frame = match yolo.frames.get(&face.frame.to_string()) {
Some(f) => f,
None => continue,
};
let dets = if !yolo_frame.detections.is_empty() {
&yolo_frame.detections
} else {
&yolo_frame.objects
};
if dets.is_empty() {
continue;
}
// Use pre-built node ID map (no SQL query)
let face_node_id = match node_id_map.get(&(
"face_track".to_string(),
format!("face_track_{}", face.trace_id),
)) {
Some(id) => *id,
None => continue,
};
for det in dets {
let obj_node_id = match node_id_map.get(&("object".to_string(), det.class_name.clone()))
{
Some(id) => *id,
None => continue,
};
let edge_props = serde_json::json!({
"frame": face.frame,
"object_confidence": det.confidence,
});
edges_to_insert.push((
"CO_OCCURS_WITH",
face_node_id,
obj_node_id,
file_uuid,
serde_json::to_string(&edge_props)?,
));
}
}
// Batch insert edges
let batch_size = 100;
for chunk in edges_to_insert.chunks(batch_size) {
let mut query = sqlx::query_builder::QueryBuilder::new(&format!(
"INSERT INTO {} (edge_type, source_node_id, target_node_id, file_uuid, properties) VALUES ",
edges_table
));
for (i, (edge_type, src, tgt, uuid, props)) in chunk.iter().enumerate() {
if i > 0 {
query.push(", ");
}
query
.push("(")
.push_bind(*edge_type)
.push_bind(*src)
.push_bind(*tgt)
.push_bind(*uuid)
.push_bind(props)
.push("::jsonb)");
}
query.push(" ON CONFLICT (file_uuid, edge_type, source_node_id, target_node_id) DO UPDATE SET properties = COALESCE(EXCLUDED.properties, tkg_edges.properties)");
query.build().execute(pool).await?;
}
edge_count = edges_to_insert.len();
Ok(edge_count)
}
async fn build_speaker_face_edges(
pool: &PgPool,
file_uuid: &str,
@@ -3322,153 +3069,6 @@ async fn build_wears_edges(pool: &PgPool, file_uuid: &str) -> Result<usize> {
Ok(0)
}
async fn build_hand_object_edges(
pool: &PgPool,
file_uuid: &str,
output_dir: &str,
) -> Result<usize> {
let hand_path = Path::new(output_dir).join(format!("{}.hand.json", file_uuid));
let yolo_path = Path::new(output_dir).join(format!("{}.yolo.json", file_uuid));
if !hand_path.exists() || !yolo_path.exists() {
return Ok(0);
}
let hand_content = std::fs::read_to_string(&hand_path)
.with_context(|| format!("Failed to read {:?}", hand_path))?;
let hand: HandJson = serde_json::from_str(&hand_content)
.with_context(|| format!("Failed to parse {:?}", hand_path))?;
let yolo_content = std::fs::read_to_string(&yolo_path)
.with_context(|| format!("Failed to read {:?}", yolo_path))?;
let yolo: YoloJson = serde_json::from_str(&yolo_content)
.with_context(|| format!("Failed to parse {:?}", yolo_path))?;
let yolo_frames: HashMap<u64, &Vec<YoloDetEntry>> = yolo
.frames
.iter()
.filter_map(|(frame_key, f)| {
let objs = if !f.objects.is_empty() {
&f.objects
} else {
&f.detections
};
if !objs.is_empty() {
frame_key.parse::<u64>().ok().map(|n| (n, objs))
} else {
None
}
})
.collect();
let edges_table = t("tkg_edges");
let nodes_table = t("tkg_nodes");
let mut count = 0;
for hf in &hand.frames {
let yolo_objs = yolo_frames.get(&(hf.frame as u64));
if yolo_objs.is_none() {
continue;
}
for person in &hf.persons {
if person.hand_state != "holding" || person.landmarks.is_empty() {
continue;
}
// Calculate hand bbox from landmarks
let xs: Vec<f32> = person.landmarks.iter().map(|lm| lm.x).collect();
let ys: Vec<f32> = person.landmarks.iter().map(|lm| lm.y).collect();
let hand_x = xs.iter().cloned().fold(f32::MAX, f32::min) as f64;
let hand_y = ys.iter().cloned().fold(f32::MAX, f32::min) as f64;
let hand_x_max = xs.iter().cloned().fold(f32::MIN, f32::max) as f64;
let hand_y_max = ys.iter().cloned().fold(f32::MIN, f32::max) as f64;
let hand_w = hand_x_max - hand_x;
let hand_h = hand_y_max - hand_y;
// Match with YOLO objects by bbox overlap
for obj in yolo_objs.unwrap().iter() {
let obj_x = obj.x as f64;
let obj_y = obj.y as f64;
let obj_w = obj.width as f64;
let obj_h = obj.height as f64;
// Calculate overlap (IoU-like)
let x1 = hand_x.max(obj_x);
let y1 = hand_y.max(obj_y);
let x2 = (hand_x + hand_w).min(obj_x + obj_w);
let y2 = (hand_y + hand_h).min(obj_y + obj_h);
if x1 < x2 && y1 < y2 {
let overlap_area = (x2 - x1) * (y2 - y1);
let hand_area = hand_w * hand_h;
let obj_area = obj_w * obj_h;
let overlap_ratio = overlap_area / hand_area.min(obj_area);
if overlap_ratio > 0.1 {
// Create HAND_OBJECT edge
let hand_node_id = format!("{}/{}", person.hand_type, person.gesture);
// Query hand node id
let hand_node_row: Option<(i64,)> = sqlx::query_as(&format!(
"SELECT id FROM {} WHERE node_type = $1 AND external_id = $2 AND file_uuid = $3",
nodes_table
))
.bind("hand")
.bind(&hand_node_id)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
// Query object node id
let object_node_row: Option<(i64,)> = sqlx::query_as(&format!(
"SELECT id FROM {} WHERE node_type = $1 AND external_id = $2 AND file_uuid = $3",
nodes_table
))
.bind("object")
.bind(&obj.class_name)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
if let (Some((hand_id,)), Some((obj_id,))) =
(hand_node_row, object_node_row)
{
sqlx::query(&format!(
r#"
INSERT INTO {} (edge_type, source_node_id, target_node_id, file_uuid, properties)
VALUES ($1, $2, $3, $4, $5::jsonb)
ON CONFLICT (file_uuid, edge_type, source_node_id, target_node_id)
DO NOTHING
"#,
edges_table
))
.bind("HAND_OBJECT")
.bind(hand_id)
.bind(obj_id)
.bind(file_uuid)
.bind(serde_json::json!({
"frame": hf.frame,
"overlap_ratio": overlap_ratio,
"hand_state": "holding",
}).to_string())
.execute(pool)
.await?;
count += 1;
}
}
}
}
}
}
tracing::info!("[TKG] HAND_OBJECT edges: {} matches", count);
Ok(count)
}
// ── TKG Bridge: Representative Frame ──────────────────────────────
#[derive(Debug, Serialize)]
@@ -3637,26 +3237,6 @@ pub async fn query_auto_representative_frame(
mod tests {
use super::*;
#[test]
fn test_yolo_json_deserialize() {
let json = r#"{
"frames": {
"1": {"time_seconds": 0.0, "detections": [{"class_name": "person", "confidence": 0.9}]},
"2": {"time_seconds": 1.0, "detections": [{"class_name": "chair", "confidence": 0.8}]}
}
}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert_eq!(yolo.frames.len(), 2);
assert_eq!(yolo.frames["1"].detections[0].class_name, "person");
}
#[test]
fn test_yolo_json_empty_frames() {
let json = r#"{"frames": {}}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert!(yolo.frames.is_empty());
}
#[test]
fn test_asrx_json_deserialize() {
let json = r#"{
@@ -3677,18 +3257,6 @@ mod tests {
assert!(asrx.speaker_stats.is_none());
}
#[test]
fn test_yolo_objects_fallback() {
let json = r#"{
"frames": {
"1": {"objects": [{"class_name": "person"}]}
}
}"#;
let yolo: YoloJson = serde_json::from_str(json).unwrap();
assert_eq!(yolo.frames["1"].objects[0].class_name, "person");
assert!(yolo.frames["1"].detections.is_empty());
}
#[test]
fn test_tkg_result() {
let r = TkgResult {
+54 -9
View File
@@ -4,6 +4,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use tracing::{error, info, warn};
use crate::core::admin_config;
use crate::core::config;
use crate::core::db::redis_client::RedisClient;
use crate::core::db::schema::table_name;
@@ -12,12 +13,6 @@ use crate::core::embedding::Embedder;
use crate::core::llm::function_calling::call_llm_vision;
use crate::core::progress::{publish_pipeline_progress, PipelineProgress};
const SYSTEM_PROMPT: &str =
"You are a scene analysis assistant for a video surveillance/DAM system. \
Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) \
describing: what is happening, the people present (clothing/appearance), the setting/location, \
and any notable objects or actions. Be factual and specific.";
#[derive(Debug, Default)]
pub struct VlmSummaryResult {
pub total: usize,
@@ -145,6 +140,39 @@ async fn process_single_trace(
) -> Result<(bool, bool)> {
let trace_id_i64 = trace_id as i64;
let tp_table = table_name("trace_profiles");
// Check frame_count and skip single frame trace if disabled
let frame_count: Option<i32> = sqlx::query_scalar(&format!(
"SELECT frame_count FROM {tp_table} WHERE file_uuid = $1 AND trace_id = $2"
))
.bind(file_uuid)
.bind(trace_id)
.fetch_optional(db.pool())
.await?
.flatten();
// If this is a single frame trace, check configuration
if frame_count == Some(1) {
let v_table = table_name("videos");
let settings: Option<crate::core::file_profile::FaceFilterSettings> = sqlx::query_scalar(&format!(
"SELECT face_filter FROM {v_table} WHERE file_uuid = $1"
))
.bind(file_uuid)
.fetch_optional(db.pool())
.await?
.flatten()
.and_then(|v| serde_json::from_value(v).ok());
let settings = settings.unwrap_or_else(crate::core::file_profile::FaceFilterSettings::defaults);
if !settings.single_frame_trace_vlm_enabled {
info!(
"[VLM] trace {}/{} (tid={}): skipping single frame trace (disabled by config)",
current, total, trace_id
);
return Ok((false, false));
}
}
// Check if vlm_description already exists
let existing: Option<(Option<String>, Option<serde_json::Value>)> = sqlx::query_as(&format!(
@@ -179,12 +207,29 @@ async fn process_single_trace(
let jpeg_bytes = std::fs::read(&key_frame_path)?;
let base64_img = base64::engine::general_purpose::STANDARD.encode(&jpeg_bytes);
// Get prompts from config
let vlm_prompt = admin_config::get_vlm_prompt("rust_vlm_summary").await;
let system_prompt = vlm_prompt
.as_ref()
.and_then(|p| p.system_prompt.as_deref())
.unwrap_or("You are a scene analysis assistant for a video surveillance/DAM system. Given a video key frame, write a concise summary (2-4 sentences, in the same language as the user) describing: what is happening, the people present (clothing/appearance), the setting/location, and any notable objects or actions. Be factual and specific.");
let user_prompt = vlm_prompt
.as_ref()
.and_then(|p| p.user_prompt.as_deref())
.unwrap_or("Summarize this key frame.");
let max_tokens = vlm_prompt
.as_ref()
.map(|p| p.max_tokens)
.unwrap_or(512);
// Call VLM
let summary = match call_llm_vision(
SYSTEM_PROMPT,
"Summarize this key frame.",
system_prompt,
user_prompt,
vec![base64_img],
512,
max_tokens,
120,
)
.await
+1 -1
View File
@@ -163,7 +163,7 @@ pub enum TkgPhase {
TextRegionNodes = 4, // Build text_region nodes
AppearanceNodes = 5, // Build appearance_trace nodes
AccessoryNodes = 6, // Build accessory nodes
ObjectNodes = 7, // Build yolo_object nodes
ObjectNodes = 7, // Build object nodes (deprecated - YOLO removed)
HandNodes = 8, // Build hand nodes
SpeakerNodes = 9, // Build speaker nodes
CoOccurrenceEdges = 10, // Build co_occurrence edges
+86 -7
View File
@@ -11,6 +11,8 @@ use std::path::Path;
pub struct SynonymExpander {
/// 詞語 -> 同義詞列表的映射
map: HashMap<String, Vec<String>>,
/// 反向索引:同義詞 -> 原詞列表(雙向查找支持)
reverse_map: HashMap<String, Vec<String>>,
}
impl SynonymExpander {
@@ -19,7 +21,19 @@ impl SynonymExpander {
let content = fs::read_to_string(path).context("Failed to read synonym file")?;
let map: HashMap<String, Vec<String>> =
serde_json::from_str(&content).context("Failed to parse synonym JSON")?;
Ok(Self { map })
// 構建反向索引
let mut reverse_map: HashMap<String, Vec<String>> = HashMap::new();
for (key, synonyms) in &map {
for syn in synonyms {
reverse_map
.entry(syn.clone())
.or_insert_with(Vec::new)
.push(key.clone());
}
}
Ok(Self { map, reverse_map })
}
/// 從多個 JSON 檔案創建同義詞擴展器(後面的檔案會覆蓋前面的)
@@ -40,7 +54,22 @@ impl SynonymExpander {
}
}
Ok(Self { map: combined_map })
// 構建反向索引(支持雙向查找)
let mut reverse_map: HashMap<String, Vec<String>> = HashMap::new();
for (key, synonyms) in &combined_map {
// 對於每個同義詞,將原詞添加到反向索引
for syn in synonyms {
reverse_map
.entry(syn.clone())
.or_insert_with(Vec::new)
.push(key.clone());
}
}
Ok(Self {
map: combined_map,
reverse_map,
})
}
/// 從內建預設資料創建(返回空映射,用戶可通過配置文件添加自定義同義詞)
@@ -53,6 +82,38 @@ impl SynonymExpander {
self.map.get(word).map(|v| v.as_slice())
}
/// 獲取詞語的所有相關詞(雙向查找)
/// 包括:
/// 1. 該詞作為鍵時的同義詞
/// 2. 該詞作為同義詞時對應的鍵
/// 3. 這些鍵的其他同義詞
pub fn get_all_related_words(&self, word: &str) -> Vec<String> {
let mut related = std::collections::HashSet::new();
related.insert(word.to_string());
// 1. 查找該詞作為鍵時的同義詞
if let Some(synonyms) = self.map.get(word) {
for syn in synonyms {
related.insert(syn.clone());
}
}
// 2. 查找該詞作為同義詞時對應的鍵
if let Some(keys) = self.reverse_map.get(word) {
for key in keys {
related.insert(key.clone());
// 3. 添加這些鍵的其他同義詞
if let Some(other_syns) = self.map.get(key) {
for syn in other_syns {
related.insert(syn.clone());
}
}
}
}
related.into_iter().collect()
}
/// 擴展查詢詞語:將詞語替換為 (詞語 OR 同義詞1 OR 同義詞2 ...)
/// 如果沒有同義詞,返回原詞語
pub fn expand_word(&self, word: &str) -> String {
@@ -136,6 +197,7 @@ impl SynonymExpander {
pub fn empty() -> Self {
Self {
map: HashMap::new(),
reverse_map: HashMap::new(),
}
}
}
@@ -177,16 +239,33 @@ static SYNONYM_EXPANDER: Lazy<SynonymExpander> = Lazy::new(|| {
match SynonymExpander::from_file(&file_path) {
Ok(expander) => {
tracing::info!("Loaded synonym expander from {}", file_path);
expander
return expander;
}
Err(e) => {
tracing::warn!("Failed to load synonym expander from {}: {}", file_path, e);
SynonymExpander::empty()
// 繼續嘗試預設檔案
}
}
} else {
// 使用預設同義詞(示例)
SynonymExpander::from_default()
}
// 默認加載內建同義詞檔案
let default_files = vec![
"data/english_synonyms.json",
"data/llm_synonyms.json",
];
match SynonymExpander::from_files(&default_files) {
Ok(expander) => {
tracing::info!(
"Loaded synonym expander from default files: {:?}",
default_files
);
expander
}
Err(e) => {
tracing::warn!("Failed to load default synonym files: {}", e);
SynonymExpander::empty()
}
}
});