Files
momentry_core/src/core/config.rs
T

507 lines
19 KiB
Rust

use once_cell::sync::Lazy;
use std::env;
use std::sync::RwLock;
// ─────────────────────────────────────────────────────────────
// Execution mode for processors (Python, CLI, or Hybrid)
// ─────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionMode {
Python, // Use Python scripts (default)
Cli, // Use Swift/Rust CLI tools
Hybrid, // Use CLI for performance-critical processors, Python for others
}
pub static EXECUTION_MODE: Lazy<ExecutionMode> = Lazy::new(|| {
match env::var("MOMENTRY_EXECUTION_MODE")
.unwrap_or_else(|_| "hybrid".to_string())
.to_lowercase()
.as_str()
{
"cli" => ExecutionMode::Cli,
"python" => ExecutionMode::Python,
_ => ExecutionMode::Hybrid,
}
});
pub fn get_execution_mode() -> ExecutionMode {
*EXECUTION_MODE
}
// ─────────────────────────────────────────────────────────────
// 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")
.map(|v| v == "true" || v == "1")
.unwrap_or(true);
RwLock::new(initial)
});
pub fn get_cache_enabled() -> bool {
*RUNTIME_CACHE_ENABLED.read().unwrap()
}
pub fn set_cache_enabled(enabled: bool) {
*RUNTIME_CACHE_ENABLED.write().unwrap() = enabled;
tracing::info!("Cache enabled set to: {}", enabled);
}
pub static RUNTIME_WATCHER_AUTO_REGISTER: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub fn get_watcher_auto_register() -> bool {
*RUNTIME_WATCHER_AUTO_REGISTER.read().unwrap()
}
pub fn set_watcher_auto_register(enabled: bool) {
*RUNTIME_WATCHER_AUTO_REGISTER.write().unwrap() = enabled;
tracing::info!("Watcher auto-register set to: {}", enabled);
}
pub static RUNTIME_AUTO_PIPELINE_ENABLED: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false));
pub fn get_auto_pipeline_enabled() -> bool {
*RUNTIME_AUTO_PIPELINE_ENABLED.read().unwrap()
}
pub fn set_auto_pipeline_enabled(enabled: bool) {
*RUNTIME_AUTO_PIPELINE_ENABLED.write().unwrap() = enabled;
tracing::info!("Auto-pipeline enabled set to: {}", enabled);
}
pub static RUNTIME_PREFERRED_LANGUAGE: Lazy<RwLock<String>> = Lazy::new(|| {
let initial = env::var("MOMENTRY_PREFERRED_LANGUAGE").unwrap_or_else(|_| "zh-TW".to_string());
RwLock::new(initial)
});
pub fn get_preferred_language() -> String {
RUNTIME_PREFERRED_LANGUAGE.read().unwrap().clone()
}
pub fn set_preferred_language(language: String) {
*RUNTIME_PREFERRED_LANGUAGE.write().unwrap() = language.clone();
tracing::info!("Preferred language set to: {}", language);
}
// ─────────────────────────────────────────────────────────────
// Sensitive configs (always from ENV, never in JSON)
// ─────────────────────────────────────────────────────────────
pub static USE_RUST_PROCESSORS: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_USE_RUST_PROCESSORS")
.map(|v| v == "true" || v == "1")
.unwrap_or(false)
});
pub static DATABASE_URL: Lazy<String> = Lazy::new(|| {
env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string())
});
pub static MONGODB_URL: Lazy<String> = Lazy::new(|| {
env::var("MONGODB_URL").unwrap_or_else(|_| "mongodb://localhost:27017".to_string())
});
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://default:{}@localhost:6379", password)
})
});
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())
});
pub static SCENE_VLM_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(true) // Default: true (Scene VLM is mandatory, not optional)
});
pub static SCENE_VLM_INTERVAL: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_INTERVAL")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub static SCENE_VLM_SAMPLES: Lazy<usize> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_SAMPLES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub static SCENE_VLM_USE_CUTS: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_USE_CUTS")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
pub static SCENE_VLM_MAX_WORKERS: Lazy<usize> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_MAX_WORKERS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
(
*SCENE_VLM_ENABLED,
*SCENE_VLM_INTERVAL,
*SCENE_VLM_SAMPLES,
*SCENE_VLM_USE_CUTS,
*SCENE_VLM_MAX_WORKERS,
)
}
// ─────────────────────────────────────────────────────────────
// JSON-backed configs (paths, concurrency, feature flags)
// These read from admin_config.json with ENV fallback
// ─────────────────────────────────────────────────────────────
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_output_dir());
/// Get the per-library output directory for a file based on its upload_path
pub async fn get_output_dir_for_file(file_uuid: &str, pool: &sqlx::PgPool) -> String {
let videos_table = crate::core::db::schema::table_name("videos");
let upload_paths_table = crate::core::db::schema::table_name("upload_paths");
let result: Option<(Option<String>,)> = sqlx::query_as(
&format!(
"SELECT up.output_path FROM {} v
LEFT JOIN {} up ON v.file_path LIKE up.full_path || '%%'
WHERE v.file_uuid = $1
AND up.output_path IS NOT NULL AND up.output_path != ''
LIMIT 1",
videos_table, upload_paths_table
)
)
.bind(file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten();
if let Some((Some(output_path),)) = result {
return output_path;
}
OUTPUT_DIR.to_string()
}
pub fn get_output_dir_for_file_sync(_file_uuid: &str, _pool: &sqlx::PgPool) -> String {
// Sync context cannot easily query DB - use global OUTPUT_DIR
// Use async version `get_output_dir_for_file()` for proper per-library paths
OUTPUT_DIR.to_string()
}
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_backup_dir());
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_scripts_dir());
pub static CLI_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_cli_dir());
pub static PYTHON_PATH: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_python_path());
pub static MEDIA_BASE_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_MEDIA_BASE_URL")
.unwrap_or_else(|_| "https://wp.momentry.ddns.net".to_string())
});
pub static STORAGE_ROOT: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_STORAGE_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data".to_string())
})
});
pub static SERVE_BASE_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_SERVE_BASE_URL")
.unwrap_or_else(|_| "https://m5wp.momentry.ddns.net/files".to_string())
});
pub static SERVER_PORT: Lazy<u16> = Lazy::new(|| {
env::var("MOMENTRY_SERVER_PORT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3002)
});
// ─────────────────────────────────────────────────────────────
// Face detection thresholds (single source of truth)
// ─────────────────────────────────────────────────────────────
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;
// ─────────────────────────────────────────────────────────────
// Cache TTLs
// ─────────────────────────────────────────────────────────────
pub mod cache {
use super::*;
pub static MONGODB_CACHE_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MONGODB_CACHE_ENABLED")
.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")
.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")
.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")
.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")
.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")
.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")
.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::*;
pub static CHAT_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_CHAT_URL")
.or_else(|_| env::var("MOMENTRY_LLM_SUMMARY_URL"))
.or_else(|_| env::var("MOMENTRY_LLM_URL"))
.unwrap_or_else(|_| "http://127.0.0.1:8080/v1/chat/completions".to_string())
});
pub static CHAT_MODEL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_CHAT_MODEL")
.or_else(|_| env::var("MOMENTRY_LLM_SUMMARY_MODEL"))
.or_else(|_| env::var("MOMENTRY_LLM_MODEL"))
.unwrap_or_else(|_| "gemma-4-12b-it".to_string())
});
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()));
pub static SUMMARY_URL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_URL")
.ok()
.or_else(|| Some(CHAT_URL.clone()))
.unwrap()
});
pub static SUMMARY_MODEL: Lazy<String> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_MODEL")
.ok()
.or_else(|| Some(CHAT_MODEL.clone()))
.unwrap()
});
pub static SUMMARY_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120)
});
pub static SUMMARY_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_LLM_SUMMARY_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
pub static CHAT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_LLM_CHAT_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(120)
});
}
// ─────────────────────────────────────────────────────────────
// Processor timeouts
// ─────────────────────────────────────────────────────────────
pub mod processor {
use super::*;
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 CUT_TIMEOUT_SECS: Lazy<u64> = Lazy::new(|| {
env::var("MOMENTRY_CUT_TIMEOUT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(3600)
});
/// Face clustering distance threshold (for Facenet-pytorch)
/// Lower = more strict (require smaller distance to cluster together)
/// Recommended: 0.15 for Facenet-pytorch to correctly separate male/female faces
/// Value 0.35 caused male/female to merge into one person
pub static FACE_CLUSTER_DISTANCE_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.15)
});
/// Face clustering similarity threshold (inverse of distance)
/// Higher = more strict (require higher similarity to cluster together)
/// Recommended: 0.85 for Facenet-pytorch to correctly separate male/female faces
/// Value 0.65 caused male/female to merge into one person
pub static FACE_CLUSTER_SIMILARITY_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_SIMILARITY_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.85)
});
/// Enable Stage 2 merge for face clustering
/// Merges over-split clusters based on centroid similarity
pub static FACE_CLUSTER_STAGE2_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_STAGE2")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
/// Face clustering Stage 2 merge threshold
/// More conservative than cluster threshold to avoid over-merging
/// Recommended: 0.30 (conservative), lower values = less merging
pub static FACE_CLUSTER_MERGE_THRESHOLD: Lazy<f64> = Lazy::new(|| {
env::var("MOMENTRY_FACE_CLUSTER_MERGE_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0.30)
});
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)
});
}