12 Commits

Author SHA1 Message Date
Accusys 5b5c1d9563 fix: face pipeline 三項修復
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
1. face_clustering: 先試 Rust binary,Python script 缺失不再提前返回空結果
2. face.rs: facenet model 查找加 fallback ( -> momentry_core/models),config 路徑補 --model 參數
3. rust_store_traced_faces: embedding 缺失時退回純 IoU 追蹤(不再強制要求 similarity);trace_profile.json 補上真實 avg_bbox/best_bbox/capture_quality
2026-11-17 17:26:00 +08:00
Accusys 5056c20667 fix: embedding port 全部改為 11436(plist + svc_def + server_type + test-embedding) 2026-11-17 13:31:20 +08:00
Accusys 8f0315e588 fix: embedding port 11437 → 11436 (correct system port)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 13:26:56 +08:00
Accusys 6ba4ee1e06 fix: Redis service label sh.brew.redis → com.momentry.redis
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 12:48:51 +08:00
Accusys b4b84dc797 feat: composite scoring for best face selection (0.4 frontal + 0.4 confidence + 0.2 quality)
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 10:56:42 +08:00
Accusys 7fd7df2913 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts'); embedding port 11436→11437
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 08:41:34 +08:00
Accusys eac827d932 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts') → ~/momentry/scripts/ 2026-11-17 04:31:03 +08:00
Accusys a85e31ff16 fix: embedding default port 11436 → 11437 (llama-server GGUF) 2026-11-17 04:26:33 +08:00
Accusys 646d2a1361 fix(P0): face_cluster_done 雙路徑檢查 + run_processor 改用 async get_output_dir_for_file; 補 ingestion_complete output_dir
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 03:03:16 +08:00
Accusys d01e456ae5 fix(P0): per-library output dir for worker ingestion/verification (face_cluster guard, verifier, TKG, qdrant_face, ASR/ASRX); fix face_cluster serde default for empty output; fix face_cluster dependencies in pipeline_flows.json
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 02:46:57 +08:00
Accusys db790e2c89 fix: face_cluster guard checks both global OUTPUT_DIR and demo subdirectory for face_traced.json
Cross-Project Integration / integration (push) Has been cancelled
Core Test / lint-and-test (push) Has been cancelled
2026-11-17 01:29:28 +08:00
Accusys 75cbaa3302 feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-16 21:56:43 +08:00
16 changed files with 2077 additions and 389 deletions
@@ -2,109 +2,77 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.n8n.main</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>start</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>DOMAIN_NAME</key>
<string>n8n.momentry.ddns.net</string>
<key>WEBHOOK_URL</key>
<string>https://n8n.momentry.ddns.net/</string>
<key>N8N_PORT</key>
<string>5678</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LISTEN_ADDRESS</key>
<string>0.0.0.0</string>
<key>N8N_USER_MANAGEMENT_JWT_DURATION</key>
<string>1h</string>
<key>N8N_RUNNERS_ENABLED</key>
<string>false</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PUBLIC_API_ENABLED</key>
<string>true</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/n8n-main.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/n8n-main.error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DOMAIN_NAME</key>
<string>n8n.momentry.ddns.net</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LISTEN_ADDRESS</key>
<string>0.0.0.0</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PORT</key>
<string>5678</string>
<key>N8N_PUBLIC_API_ENABLED</key>
<string>true</string>
<key>N8N_RUNNERS_ENABLED</key>
<string>false</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_USER_MANAGEMENT_JWT_DURATION</key>
<string>1h</string>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>WEBHOOK_URL</key>
<string>https://n8n.momentry.ddns.net/</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.n8n.main</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>start</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/n8n-main.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/n8n-main.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
</dict>
</plist>
@@ -2,103 +2,73 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.n8n.worker</string>
<key>UserName</key>
<string>accusys</string>
<key>GroupName</key>
<string>staff</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>worker</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_PORT</key>
<string>5681</string>
<key>QUEUE_HEALTH_CHECK_PORT</key>
<string>5682</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_RUNNERS_BROKER_PORT</key>
<string>5690</string>
<key>N8N_RUNNERS_LAUNCHER_HEALTH_CHECK_PORT</key>
<string>5691</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/n8n-worker.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/n8n-worker.error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PORT</key>
<string>5681</string>
<key>N8N_RUNNERS_BROKER_PORT</key>
<string>5690</string>
<key>N8N_RUNNERS_LAUNCHER_HEALTH_CHECK_PORT</key>
<string>5691</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_HEALTH_CHECK_PORT</key>
<string>5682</string>
<key>TZ</key>
<string>Asia/Taipei</string>
</dict>
<key>GroupName</key>
<string>staff</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.n8n.worker</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>worker</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/n8n-worker.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/n8n-worker.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
</dict>
</plist>
@@ -2,32 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.rustdesk.hbbr</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbr</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbr.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbr.error.log</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.rustdesk.hbbr</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbr</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbr.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbr.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
</dict>
</plist>
@@ -2,32 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.rustdesk.hbbs</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbs</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbs.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbs.error.log</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.rustdesk.hbbs</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbs</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbs.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbs.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
</dict>
</plist>
+217
View File
@@ -0,0 +1,217 @@
use std::time::Duration;
use axum::{Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
use tower_http::services::ServeDir;
use crate::core::cache::{MongoCache, RedisCache};
use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::clip_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::file_progress;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed, health_queue};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::markbase_compat;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
use super::processing;
use super::profile;
use super::scan;
use super::search::search_routes;
use super::service_management;
use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::monitor;
use super::universal_search::universal_search_routes;
use super::vlm_search;
use super::job_management;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string()));
// ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ──
//
// MongoDB is ONLY a cache layer — if unavailable, the server MUST still
// start with Redis cache alone. This keeps 3002 bootable on machines
// without MongoDB installed. If you add a new dependency here, ask:
// "Can this service degrade gracefully if the dependant is missing?"
//
// See also: MongoCache::disabled() in mongo_cache.rs
let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await {
Ok(Ok(cache)) => cache,
Ok(Err(e)) => {
tracing::warn!("MongoDB cache unavailable (continuing without): {e}");
MongoCache::disabled().await
}
Err(_) => {
tracing::warn!("MongoDB init timed out (continuing without cache)");
MongoCache::disabled().await
}
};
let redis_cache = RedisCache::new()?;
let db = PostgresDb::init().await?;
// Run migrations (create identity_history table if not exists)
PostgresDb::run_migrations(db.pool()).await?;
let schema_health = health::check_schema_migrations(db.pool()).await;
if schema_health.ok {
tracing::info!(
"[SCHEMA] All {}/{} required migrations applied ✓",
schema_health.required.len(),
schema_health.required.len()
);
} else if !schema_health.table_exists {
tracing::warn!("[SCHEMA] schema_migrations table not found!");
} else {
let missing: Vec<&str> = schema_health
.required
.iter()
.filter(|req| {
!schema_health
.applied
.iter()
.any(|app| app.filename == req.filename && app.checksum == req.checksum)
})
.map(|m| m.filename.as_str())
.collect();
tracing::warn!(
"[SCHEMA] {}/{} migrations match. Missing: {}",
schema_health.applied.len(),
schema_health.required.len(),
missing.join(", ")
);
}
let db = std::sync::Arc::new(db);
let api_state = super::middleware::ApiState { db: db.clone() };
let qdrant = std::sync::Arc::new(QdrantDb::new());
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await {
tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e);
}
let state = AppState {
db,
qdrant,
embedder,
embedder_model: "nomic-embed-text-v2-moe:latest".to_string(),
mongo_cache,
redis_cache,
api_state,
admin_config_manager,
};
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(markbase_compat::markbase_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
.merge(tmdb_api::tmdb_routes())
.merge(identity_api::identity_routes())
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(file_progress::file_progress_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
.merge(trace_agent_api::trace_agent_routes())
.merge(clip_api::clip_routes())
.merge(search_routes())
.merge(llm_search::llm_smart_routes())
.merge(universal_search_routes())
.merge(pipeline::pipeline_routes())
.merge(checkin_api::checkin_routes())
.merge(cluster_agent::cluster_agent_routes())
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.merge(job_management::job_management_routes())
.merge(service_management::router())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
))
.with_state(state.clone());
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let public_health_routes = Router::new()
.route("/api/v1/health", axum::routing::get(health))
.route(
"/api/v1/health/detailed",
axum::routing::get(health_detailed),
)
.route(
"/api/v1/health/consistency",
axum::routing::get(health_consistency),
)
.route(
"/api/v1/health/queue",
axum::routing::get(health_queue),
)
.route(
"/api/v1/mbe/health",
axum::routing::get(service_management::mbe_health),
);
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(docs::doc_routes())
.merge(monitor::monitor_routes())
.nest_service("/monitor", ServeDir::new("static/monitor"))
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.layer(axum::middleware::from_fn(
super::middleware::concurrency_limit,
))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
+219 -5
View File
@@ -60,13 +60,13 @@ fn svc_def(name: &str) -> Option<(&'static str, u16, Option<&'static str>)> {
"markbase" | "mb" => ("markbase", 11438, Some("com.momentry.markbase")),
"mbe" | "markbaseengine" | "vlm" => ("mbe", 8082, Some("com.momentry.llm")), // MBE = markbaseengine service; spawns VLM llama-server (8082)
"chat" | "llama" => ("chat", 8080, Some("com.momentry.chat-llamacpp")), // Chat llama-server instance (8080)
"embedding" => ("embedding", 11437, Some("com.momentry.embedding-gguf")),
"embedding" => ("embedding", 11436, Some("com.momentry.embedding-gguf")),
"proxy" => ("proxy", 8888, Some("com.momentry.proxy")),
"worker" => ("worker", 0, Some("com.momentry.worker")),
"postgres" | "postgresql" | "pg" => ("postgres", 5432, Some("com.momentry.postgresql")),
// NOTE: the redis actually serving 127.0.0.1:6379 is brew-services' launchd agent,
// not com.momentry.redis (which can't bind while brew's owns the port).
"redis" => ("redis", 6379, Some("sh.brew.redis")),
"redis" => ("redis", 6379, Some("com.momentry.redis")),
"qdrant" => ("qdrant", 6333, Some("com.momentry.qdrant")),
_ => return None,
};
@@ -1085,6 +1085,7 @@ pub fn router() -> axum::Router<AppState> {
axum::Router::new()
.route("/api/v2/service/start", axum::routing::post(start_service))
.route("/api/v2/service/stop", axum::routing::post(stop_service))
.route("/api/v1/admin/rebuild-embeddings", axum::routing::post(rebuild_embeddings))
// NOTE: /api/v1/mbe/health is already registered in server.rs (line 192)
}
@@ -1101,10 +1102,10 @@ pub async fn test_embedding(
.unwrap_or_else(|_| "http://localhost:11436".to_string());
// Detect server type from URL port
let server_type = if url.contains("11437") {
let server_type = if url.contains("11436") {
"llama.cpp GGUF Q8"
} else if url.contains("11436") {
"Python Flask (safetensors fp32)"
} else if url.contains("11437") {
"llama.cpp GGUF Q8 (alt)"
} else {
"unknown"
};
@@ -1693,6 +1694,219 @@ pub async fn test_core(
Ok(Json(result))
}
/// POST /api/v1/admin/rebuild-embeddings — rebuild text/scene embeddings
/// with the current (possibly updated) embedding model.
///
/// Body: `{ "collection": "momentry_rule1" | "_scenes" | "all", "file_uuid": "optional" }`
/// Uses the Rust `Embedder` (same code path as production).
pub async fn rebuild_embeddings(
State(state): State<AppState>,
Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, StatusCode> {
use crate::core::embedding::Embedder;
use crate::core::db::{schema, QdrantDb};
let collection = body.get("collection").and_then(|v| v.as_str()).unwrap_or("all");
let file_uuid = body.get("file_uuid").and_then(|v| v.as_str());
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let qdrant = QdrantDb::new();
let chunk_table = schema::table_name("chunk");
let scenes_table = schema::table_name("scenes");
let mut results = serde_json::json!({});
let t0 = std::time::Instant::now();
// ── Rebuild text chunks (sentence) → momentry_rule1 ──
if collection == "all" || collection == "momentry_rule1" {
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing points for this file_uuid (or all if no filter)
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
} else {
// Delete all in collection: use empty filter to match everything
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await;
}
// Query chunks that need re-embedding
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \
ORDER BY id",
chunk_table
)
} else {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \
ORDER BY id",
chunk_table
)
};
let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
for (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid) in &rows {
match embedder.embed_document(text).await {
Ok(vector) => {
// Update PG embedding column
let vector_json = serde_json::to_string(&vector).unwrap_or_default();
let _ = sqlx::query(&format!(
"UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3",
chunk_table
))
.bind(&vector_json)
.bind(chunk_id)
.bind(fuuid)
.execute(state.db.pool())
.await;
// Upsert to Qdrant
let payload = crate::core::db::VectorPayload {
file_uuid: fuuid.clone(),
chunk_id: chunk_id.clone(),
chunk_type: chunk_type.clone(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
}
Err(e) => {
tracing::error!("[rebuild-embed] Failed to embed {}: {}", chunk_id, e);
fail += 1;
}
}
}
results["momentry_rule1"] = serde_json::json!({
"total": total,
"ok": ok,
"fail": fail,
});
}
// ── Rebuild scene embeddings → _scenes ──
if collection == "all" || collection == "_scenes" {
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing scene points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
} else {
// Delete all in _scenes: use empty filter to match everything
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await;
}
// Query scenes with VLM descriptions
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \
ORDER BY id",
scenes_table
)
} else {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \
ORDER BY id",
scenes_table
)
};
let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(state.db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
for (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description) in &rows {
match embedder.embed_document(description).await {
Ok(vector) => {
let point_id_str = format!("{}_s{}", fuuid, scene_index);
let point_id = {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
point_id_str.hash(&mut hasher);
hasher.finish()
};
if qdrant.upsert_scene_embedding(
point_id,
&vector,
fuuid,
*scene_index as usize,
*timestamp_sec,
*frame_number as u32,
description,
None,
&[],
&[],
).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
}
Err(e) => {
tracing::error!("[rebuild-embed] Failed to embed scene {}: {}", scene_id, e);
fail += 1;
}
}
}
results["_scenes"] = serde_json::json!({
"total": total,
"ok": ok,
"fail": fail,
});
}
results["elapsed_ms"] = serde_json::json!(t0.elapsed().as_millis());
results["collection"] = serde_json::json!(collection);
results["file_uuid"] = serde_json::json!(file_uuid);
Ok(Json(results))
}
/// GET /api/v1/admin/components — full component registry with versions
/// Returns all system components: binaries, tools, scripts, dists, externals
/// Each with current file hash, size, repo mapping, and latest Gitea commit.
+267
View File
@@ -0,0 +1,267 @@
//! Standalone embedding rebuild tool.
//!
//! Rebuilds text/scene embeddings with the current embedding model.
//! Uses the Rust `Embedder` (same code path as production).
//!
//! Usage:
//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1
//! cargo run --release --bin rebuild_embeddings -- --collection _scenes
//! cargo run --release --bin rebuild_embeddings -- --collection all
//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1 --uuid abc123
use anyhow::{Context, Result};
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::{schema, QdrantDb, VectorPayload};
use momentry_core::core::embedding::Embedder;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[derive(clap::Parser)]
#[command(name = "rebuild_embeddings", about = "Rebuild embeddings with current model")]
struct Args {
/// Collection to rebuild: momentry_rule1, _scenes, or all
#[arg(short, long, default_value = "all")]
collection: String,
/// Optional file UUID to rebuild only one video
#[arg(short, long)]
uuid: Option<String>,
/// Skip PG embedding column update (only update Qdrant)
#[arg(long)]
skip_pg: bool,
}
async fn rebuild_text_chunks(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>, skip_pg: bool) -> Result<(usize, usize)> {
let chunk_table = schema::table_name("chunk");
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
println!(" Cleared points for file_uuid={}", uuid);
} else {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await;
println!(" Cleared all points in momentry_rule1");
}
// Query chunks
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \
ORDER BY id",
chunk_table
)
} else {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \
ORDER BY id",
chunk_table
)
};
let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
println!(" Found {} sentence chunks to rebuild", total);
for (i, (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid)) in rows.iter().enumerate() {
if text.is_empty() {
continue;
}
match embedder.embed_document(text).await {
Ok(vector) => {
// Update PG embedding column if not skipped
if !skip_pg {
let vector_json = serde_json::to_string(&vector).unwrap_or_default();
let _ = sqlx::query(&format!(
"UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3",
chunk_table
))
.bind(&vector_json)
.bind(chunk_id)
.bind(fuuid)
.execute(db.pool())
.await;
}
// Upsert to Qdrant
let payload = VectorPayload {
file_uuid: fuuid.clone(),
chunk_id: chunk_id.clone(),
chunk_type: chunk_type.clone(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
if (i + 1) % 50 == 0 || i + 1 == total {
println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail);
}
}
Err(e) => {
eprintln!(" ✗ Failed to embed {}: {}", chunk_id, e);
fail += 1;
}
}
}
Ok((ok, fail))
}
async fn rebuild_scenes(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>) -> Result<(usize, usize)> {
let scenes_table = schema::table_name("scenes");
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing scene points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
println!(" Cleared scene points for file_uuid={}", uuid);
} else {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await;
println!(" Cleared all points in _scenes");
}
// Query scenes with VLM descriptions
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \
ORDER BY id",
scenes_table
)
} else {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \
ORDER BY id",
scenes_table
)
};
let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
println!(" Found {} scenes to rebuild", total);
for (i, (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description)) in rows.iter().enumerate() {
match embedder.embed_document(description).await {
Ok(vector) => {
let point_id_str = format!("{}_s{}", fuuid, scene_index);
let point_id = {
let mut hasher = DefaultHasher::new();
point_id_str.hash(&mut hasher);
hasher.finish()
};
if qdrant.upsert_scene_embedding(
point_id,
&vector,
fuuid,
*scene_index as usize,
*timestamp_sec,
*frame_number as u32,
description,
None,
&[],
&[],
).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
if (i + 1) % 50 == 0 || i + 1 == total {
println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail);
}
}
Err(e) => {
eprintln!(" ✗ Failed to embed scene {}: {}", scene_id, e);
fail += 1;
}
}
}
Ok((ok, fail))
}
#[tokio::main]
async fn main() -> Result<()> {
use clap::Parser;
dotenv().ok();
let args = Args::parse();
println!("═══ Embedding Rebuild Tool ═══");
println!("Collection: {}", args.collection);
if let Some(uuid) = &args.uuid {
println!("File UUID: {}", uuid);
}
println!("Skip PG update: {}", args.skip_pg);
println!();
let db = momentry_core::core::db::postgres_db::PostgresDb::new(&config::DATABASE_URL).await
.context("Failed to connect to PostgreSQL")?;
let qdrant = QdrantDb::new();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let t0 = std::time::Instant::now();
if args.collection == "all" || args.collection == "momentry_rule1" {
println!("── Rebuilding momentry_rule1 (text chunks) ──");
let (ok, fail) = rebuild_text_chunks(&db, &qdrant, &embedder, args.uuid.as_deref(), args.skip_pg).await?;
println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail);
}
if args.collection == "all" || args.collection == "_scenes" {
println!("── Rebuilding _scenes (scene embeddings) ──");
let (ok, fail) = rebuild_scenes(&db, &qdrant, &embedder, args.uuid.as_deref()).await?;
println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail);
}
let elapsed = t0.elapsed();
println!("═══ Total time: {:.1}s ═══", elapsed.as_secs_f64());
Ok(())
}
+1 -3
View File
@@ -73,9 +73,7 @@ pub fn demo_dir() -> PathBuf {
/// Get scripts directory
pub fn scripts_dir() -> PathBuf {
env::var("MOMENTRY_SCRIPTS_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| momentry_core_dir().join("tools/script"))
resolve_asset_path("MOMENTRY_SCRIPTS_DIR", "scripts")
}
/// Get CLI tools directory
+33 -11
View File
@@ -8,6 +8,24 @@ use super::FaceStatus;
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
/// Resolve the FaceNet512 CoreML model path.
/// Priority: $MOMENTRY_MODELS_DIR/facenet512.mlpackage -> momentry_core/models/facenet512.mlpackage
pub fn facenet_model_path() -> Option<std::path::PathBuf> {
use std::path::PathBuf;
let env_dir = std::env::var("MOMENTRY_MODELS_DIR")
.ok()
.map(PathBuf::from);
let candidates = [
env_dir.map(|d| d.join("facenet512.mlpackage")),
Some(
crate::core::path_utils::momentry_core_dir()
.join("models")
.join("facenet512.mlpackage"),
),
];
candidates.into_iter().flatten().find(|p| p.exists())
}
pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
use std::path::PathBuf;
let rel = format!(".build/release/{}", bin);
@@ -323,16 +341,14 @@ pub async fn process_face(
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
// Resolve model path
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let model_path = models_dir.join("facenet512.mlpackage");
if !model_path.exists() {
tracing::error!("[FACE] FaceNet model not found at {:?}", model_path);
tracing::error!("[FACE] Set MOMENTRY_MODELS_DIR environment variable or ensure models/facenet512.mlpackage exists");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
// Resolve model path (env dir -> momentry_core/models fallback)
let model_path = match facenet_model_path() {
Some(p) => p,
None => {
tracing::error!("[FACE] FaceNet model not found (checked $MOMENTRY_MODELS_DIR and momentry_core/models)");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
};
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
@@ -549,11 +565,17 @@ async fn run_face_with_config(
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
let mut facenet_args = vec![
video_path.to_string(),
output_path.to_string(),
facenet_output.clone(),
];
// Explicit --model (the binary otherwise derives the path from
// MOMENTRY_MODELS_DIR, which may not contain facenet512)
if let Some(model_path) = facenet_model_path() {
facenet_args.push("--model".to_string());
facenet_args.push(model_path.to_string_lossy().to_string());
}
let facenet_result = tokio::process::Command::new(facenet_path)
.args(&facenet_args)
+7 -2
View File
@@ -13,7 +13,9 @@ pub struct FaceClusterResult {
#[serde(default)]
pub file_uuid: Option<String>,
pub status: String,
#[serde(default)]
pub stats: ClusterStats,
#[serde(default)]
pub clusters: Vec<FaceClusterInfo>,
#[serde(default)]
pub unassigned_traces: Vec<i32>,
@@ -157,11 +159,14 @@ pub async fn process_face_cluster(
similarity_threshold: Option<f64>,
) -> Result<FaceClusterResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("fast_face_clustering_processor.py");
tracing::info!("[FACE_CLUSTER] Starting face clustering: {}", video_path);
if !script_path.exists() {
// Try Rust binary first (preferred); legacy Python script is only a fallback.
// Do NOT bail early just because the Python script is missing — that would
// skip the Rust binary even when it exists.
let script_path = executor.script_path("fast_face_clustering_processor.py");
if executor.rust_binary_path("rust_face_cluster").is_none() && !script_path.exists() {
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
return Ok(FaceClusterResult {
schema_version: "2.0".to_string(),
@@ -0,0 +1,859 @@
use anyhow::{Context, Result};
use futures_util::future::join_all;
use std::collections::HashMap;
use std::path::Path;
use tokio::process::Command;
use crate::core::file_profile::{
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
};
pub struct SceneVlmProcessor {
samples_per_interval: usize,
use_cuts: bool,
max_workers: usize,
}
impl SceneVlmProcessor {
pub fn new(samples_per_interval: usize, use_cuts: bool, max_workers: usize) -> Self {
Self {
samples_per_interval,
use_cuts,
max_workers,
}
}
pub fn compute_sample_frames(
interval_start_sec: f64,
interval_sec: f64,
fps: f64,
samples: usize,
) -> Vec<u32> {
if samples == 0 {
return vec![];
}
let sample_interval = interval_sec / samples as f64;
let frames: Vec<u32> = (0..samples)
.map(|i| {
let time = interval_start_sec + (i as f64 + 0.5) * sample_interval;
(time * fps).round() as u32
})
.collect();
// Ensure at least frame 0 is included for short videos
if frames.is_empty() || frames.iter().all(|&f| f > 0) {
let mut result = vec![0u32];
result.extend(frames.into_iter().filter(|&f| f > 0));
result
} else {
frames
}
}
pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result<f64> {
let time_sec = frame as f64 / fps;
let output = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-vf",
"blurdetect",
"-f",
"null",
"-",
])
.output()
.await
.context("FFmpeg blurdetect failed")?;
let stderr = String::from_utf8_lossy(&output.stderr);
for line in stderr.lines() {
if let Some(blur_str) = line.split("blur mean: ").nth(1) {
if let Ok(blur) = blur_str.trim().parse::<f64>() {
return Ok(blur);
}
}
}
Ok(f64::NAN)
}
pub async fn calculate_blur_parallel(
video_path: &str,
frames: &[u32],
fps: f64,
max_workers: usize,
) -> Result<Vec<(u32, f64)>> {
let tasks: Vec<_> = frames
.iter()
.map(|frame| Self::calculate_blur_single(video_path, *frame, fps))
.collect();
let results = join_all(tasks).await;
let mut combined = Vec::new();
for (frame, result) in frames.iter().zip(results.into_iter()) {
if let Ok(blur) = result {
combined.push((*frame, blur));
} else {
combined.push((*frame, f64::NAN));
}
}
Ok(combined)
}
pub fn select_best_frame(blur_scores: &[(u32, f64)]) -> Option<(u32, f64)> {
blur_scores
.iter()
.filter(|(_, blur)| !blur.is_nan())
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(frame, blur)| (*frame, *blur))
}
pub fn find_cuts_in_interval(
interval_start: f64,
interval_end: f64,
cut_data: &serde_json::Value,
) -> Vec<serde_json::Value> {
let mut cuts = Vec::new();
if let Some(scenes) = cut_data.get("scenes").and_then(|s| s.as_array()) {
for scene in scenes {
if let Some(start_time) = scene.get("start_time").and_then(|t| t.as_f64()) {
if start_time > interval_start && start_time < interval_end {
cuts.push(scene.clone());
}
}
}
}
cuts
}
pub async fn process_interval(
video_path: &str,
interval_start: f64,
interval_sec: f64,
fps: f64,
cut_data: &serde_json::Value,
samples_per_interval: usize,
max_workers: usize,
) -> Result<Vec<SceneFrame>> {
let sample_frames =
Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval);
let blur_scores =
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
let cuts =
Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
let mut selected_frames = Vec::new();
if cuts.is_empty() {
if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::BestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
} else if let Some(&frame) = sample_frames.first() {
// Fallback: use first sample frame when blur detection yields no scores
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::Default,
quality_score: None,
quality_source: None,
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
} else {
let cut = &cuts[0];
let cut_time = cut
.get("start_time")
.and_then(|t| t.as_f64())
.unwrap_or(interval_start);
let cut_frame = (cut_time * fps).round() as u32;
let pre_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f < cut_frame)
.cloned()
.collect();
let post_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f >= cut_frame)
.cloned()
.collect();
if !pre_frames.is_empty() {
let pre_blur =
Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PreCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
if !post_frames.is_empty() {
let post_blur =
Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&post_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PostCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
}
for (i, frame) in selected_frames.iter_mut().enumerate() {
frame.index = i;
}
Ok(selected_frames)
}
pub async fn generate_scene_profile(
&self,
video_path: &str,
file_uuid: &str,
output_dir: &str,
interval_sec: u32,
cut_data: &serde_json::Value,
fps: f64,
duration: f64,
width: u32,
height: u32,
total_frames: u32,
) -> Result<SceneProfile> {
let config = SceneConfig {
interval_sec,
use_cuts: true,
use_faces: false,
quality_metric: "ffmpeg_blurdetect".to_string(),
samples_per_interval: self.samples_per_interval,
};
let video_info = VideoInfo {
duration_sec: duration,
fps,
width,
height,
total_frames,
};
let mut profile = SceneProfile::new(file_uuid, video_info, config);
let mut all_frames = Vec::new();
let total_intervals = (duration / interval_sec as f64).ceil() as usize;
for i in 0..total_intervals {
let interval_start = i as f64 * interval_sec as f64;
let interval_end = (interval_start + interval_sec as f64).min(duration);
let actual_interval_sec = interval_end - interval_start;
let frames = Self::process_interval(
video_path,
interval_start,
actual_interval_sec,
fps,
cut_data,
self.samples_per_interval,
self.max_workers,
)
.await?;
all_frames.extend(frames);
}
// Fix indices
for (i, frame) in all_frames.iter_mut().enumerate() {
frame.index = i;
frame.filename = format!("scene_{:03}.jpg", i);
}
profile.scenes = all_frames;
profile.total_scenes = profile.scenes.len();
profile.status = SceneStatus::Ready;
profile.updated_at = chrono::Utc::now();
Ok(profile)
}
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
let json =
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
std::fs::write(&path, json).context("Failed to write scenes.json")?;
Ok(())
}
pub fn load_scene_profile(output_dir: &str, file_uuid: &str) -> Result<SceneProfile> {
let path = SceneProfile::scenes_path(output_dir, file_uuid);
let json = std::fs::read_to_string(&path).context("Failed to read scenes.json")?;
let profile: SceneProfile =
serde_json::from_str(&json).context("Failed to parse scenes.json")?;
Ok(profile)
}
pub async fn extract_scene_frames(
video_path: &str,
output_dir: &str,
file_uuid: &str,
scenes: &[SceneFrame],
) -> Result<Vec<std::path::PathBuf>> {
let scenes_dir = SceneProfile::scenes_dir(output_dir, file_uuid);
std::fs::create_dir_all(&scenes_dir).context("Failed to create scenes directory")?;
let mut extracted_paths = Vec::new();
for scene in scenes {
let output_path =
SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
let time_sec = scene.timestamp_sec;
let status = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-q:v",
"5",
&output_path.to_string_lossy(),
])
.status()
.await
.context("FFmpeg frame extraction failed")?;
if status.success() && output_path.exists() {
extracted_paths.push(output_path);
}
}
Ok(extracted_paths)
}
/// Helper function to extract scene info from parsed JSON
fn extract_scene_info(
parsed: &serde_json::Value,
fallback: &str,
) -> (String, Vec<String>, Vec<String>) {
let desc = parsed
.get("description")
.and_then(|d| d.as_str())
.unwrap_or(fallback)
.to_string();
let objs = parsed
.get("objects")
.and_then(|o| o.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tgs = parsed
.get("tags")
.and_then(|t| t.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
(desc, objs, tgs)
}
/// Extract objects from text (simple keyword matching)
fn extract_objects_from_text(text: &str) -> Vec<String> {
let keywords = [
"river", "tree", "forest", "mountain", "building", "person", "text", "water", "sky",
"cloud", "road", "car", "house", "flower", "grass", "rock", "bridge", "boat", "animal",
"bird",
];
keywords
.iter()
.filter(|&k| text.to_lowercase().contains(k))
.map(|k| k.to_string())
.collect()
}
/// Extract tags from text (category inference)
fn extract_tags_from_text(text: &str) -> Vec<String> {
let mut tags = vec![];
let lower = text.to_lowercase();
if lower.contains("landscape") || lower.contains("nature") {
tags.push("nature".to_string());
}
if lower.contains("indoor") || lower.contains("room") {
tags.push("indoor".to_string());
}
if lower.contains("outdoor") {
tags.push("outdoor".to_string());
}
if lower.contains("presentation") || lower.contains("slide") {
tags.push("presentation".to_string());
}
if lower.contains("text") || lower.contains("title") {
tags.push("text".to_string());
}
if lower.contains("water") || lower.contains("river") {
tags.push("water".to_string());
}
tags
}
fn language_display_name(language: &str) -> &'static str {
match language {
"zh-TW" => "Traditional Chinese (zh-TW)",
"zh-CN" => "Simplified Chinese (zh-CN)",
"ja" => "Japanese (ja)",
"ko" => "Korean (ko)",
"es" => "Spanish (es)",
"fr" => "French (fr)",
"de" => "German (de)",
_ => "English (en)",
}
}
/// Build the structured scene analysis prompt.
fn build_scene_prompt(local_language: &str) -> String {
let local_name = Self::language_display_name(local_language);
format!(
r#"You are an expert visual analyst for a multimodal video search system.
Analyze the attached image frame and return ONLY valid JSON with NO markdown, NO explanations, NO reasoning, NO thinking.
Use this exact schema:
{{
"summary": "Concise English summary of the core content (1-2 sentences). Factual, avoid superlatives like beautiful/stunning/amazing.",
"category": "Single highest-level category. Choose ONE from: landscape|architecture|interior|people|event|nature|urban|transport|food|animal|product|other",
"scene_type": "Environment/background. Choose ONE from: indoor|outdoor|city street|resort|nature|mountain|beach|forest|building exterior|building interior|road|park|unknown",
"objects": ["3-5 most prominent objects or subjects in English. Concrete and specific."],
"actions": ["Main actions/events or static state if no motion. Use English (e.g. 'static scene', 'driving', 'walking')."],
"visual_attributes": {{
"lighting": "e.g. natural daylight, golden hour, overcast, artificial, backlit, mixed lighting",
"composition": "e.g. aerial view, wide angle, eye level, low angle, close-up, drone shot, street level",
"color_palette": ["3-5 dominant colors in English (e.g. gray, green, blue, orange)"]
}},
"detected_text": ["Exact visible signs, logos, plaques, or printed text. Only if legible. Empty array if none."],
"tags": [
{{"en": "english_tag", "local": "localized_tag"}}
]
}}
Rules:
- summary must be English only
- objects, actions, visual_attributes must use concrete English terms. Avoid generic words like "photo", "image", "view", "scene"
- tags: 5-10 items. Each item MUST be an object with both "en" and "local" keys
- Use {local_name} for "local". If the preferred language is English, set "local" equal to "en" but keep both keys
- Prioritize search-relevant terms (environment type, key structures/objects). Do NOT just copy the full summary into tags
- Do NOT duplicate objects 1:1 unless genuinely useful as search tags
- Keep tags concise (1-3 words). Avoid redundancy between tags
- detected_text: only extract text actually visible, do not guess or infer
- Output ONLY the JSON object"#
)
}
/// Extract the first JSON object from a VLM response (tolerates markdown fences).
fn extract_json_object(content: &str) -> Option<&str> {
let start = content.find('{')?;
let end = content.rfind('}')?;
if end <= start {
return None;
}
Some(&content[start..=end])
}
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
let Some(arr) = value.and_then(|v| v.as_array()) else {
return Vec::new();
};
arr.iter()
.filter_map(|tag| {
if let Some(en) = tag.get("en").and_then(|v| v.as_str()) {
let local = tag
.get("local")
.and_then(|v| v.as_str())
.unwrap_or(en)
.to_string();
Some(VlmTagValue::Structured(VlmTag {
en: en.to_string(),
local,
}))
} else {
tag.as_str().map(|s| VlmTagValue::String(s.to_string()))
}
})
.collect()
}
/// Call VLM API to generate structured scene info.
/// Returns (english_description, objects, bilingual_tags).
pub async fn generate_scene_description(
image_path: &std::path::Path,
local_language: &str,
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use std::time::Duration;
// Read image
let jpeg_bytes = std::fs::read(image_path)
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
// VLM API config
let vlm_url = crate::core::config::llm::VISION_URL.clone();
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
let prompt = Self::build_scene_prompt(local_language);
tracing::debug!(
"[VLM API] Calling {} with model {} (local language: {})",
vlm_url,
vlm_model,
local_language
);
let body = serde_json::json!({
"model": vlm_model,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": format!("data:image/jpeg;base64,{}", base64_img)
}
}
]
}],
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.context("Failed to create HTTP client")?;
let resp = client
.post(&vlm_url)
.json(&body)
.send()
.await
.context("VLM API request failed")?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("VLM API returned {}: {}", status, body);
}
let resp_json: serde_json::Value = resp
.json()
.await
.context("Failed to parse VLM API response")?;
// Parse response
let choice = resp_json
.get("choices")
.and_then(|c| c.get(0))
.context("Invalid VLM API response structure")?;
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
}
let message = choice.get("message").context("Invalid VLM API response structure")?;
let content = match message
.get("content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => s.trim().to_string(),
None => anyhow::bail!("VLM returned empty content"),
};
tracing::debug!(
"[Scene VLM] VLM response content (first 500 chars): {}",
&content[..content.len().min(500)]
);
// Parse structured JSON; fall back to heuristic extraction if it fails.
if let Some(json_str) = Self::extract_json_object(&content) {
tracing::debug!("[Scene VLM] Extracted JSON object ({} chars)", json_str.len());
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
tracing::debug!("[Scene VLM] Successfully parsed JSON");
let description = parsed
.get("summary")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if let Some(description) = description {
let objects = parsed
.get("objects")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let tags = Self::parse_tags(parsed.get("tags"));
tracing::info!(
"[Scene VLM] Parsed {} objects, {} tags from JSON",
objects.len(),
tags.len()
);
return Ok((description, objects, tags));
} else {
tracing::warn!("[Scene VLM] JSON missing 'summary' field or summary is empty");
}
} else {
tracing::warn!("[Scene VLM] Failed to parse extracted JSON: {}", json_str);
}
} else {
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
}
tracing::warn!(
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
);
let objects = Self::extract_objects_from_text(&content);
let tags = Self::extract_tags_from_text(&content)
.into_iter()
.map(VlmTagValue::String)
.collect();
Ok((content, objects, tags))
}
/// Generate VLM descriptions for all scene frames
pub async fn generate_vlm_descriptions(
output_dir: &str,
file_uuid: &str,
scenes: &mut [SceneFrame],
max_workers: usize,
) -> Result<()> {
tracing::info!(
"[Scene VLM] Generating descriptions for {} scenes",
scenes.len()
);
// Get preferred language from admin config
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
.get_full_config()
.await
.search
.vlm_output_language
.clone();
crate::core::config::set_preferred_language(preferred_language.clone());
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
// Process scenes sequentially to avoid issues
for (idx, scene) in scenes.iter_mut().enumerate() {
let frame_path = SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
// Generate English description (for indexing)
match Self::generate_scene_description(&frame_path, &preferred_language).await {
Ok((description_en, objects, tags)) => {
scene.vlm_description = Some(description_en.clone());
scene.vlm_objects = objects.clone();
scene.vlm_tags = tags.clone();
tracing::info!(
"[Scene VLM] Scene {}: Generated {} tags: {:?}",
idx,
tags.len(),
tags
);
// Generate localized description by translation if needed
if preferred_language != "en" {
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
let body = serde_json::json!({
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"stream": false,
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
Ok(resp) => {
if resp.status().is_success() {
if let Ok(v) = resp.json::<serde_json::Value>().await {
if let Some(choice) = v["choices"].get(0) {
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
if let Some(tr) = choice["message"]["content"].as_str() {
let tr = tr.trim();
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
scene.vlm_description_localized = Some(tr.to_string());
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
scene.vlm_status = VlmStatus::Completed;
continue;
}
}
}
}
}
}
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
}
Err(e) => {
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
}
}
} else {
tracing::info!("[Scene VLM] ✅ Scene {}: EN only", idx);
}
scene.vlm_status = VlmStatus::Completed;
}
Err(e) => {
tracing::error!("[Scene VLM] ❌ Scene {}: {}", idx, e);
scene.vlm_status = VlmStatus::Failed;
}
}
}
let success_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Completed)
.count();
let fail_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Failed)
.count();
tracing::info!(
"[Scene VLM] ✅ Generated {} descriptions, {} failed",
success_count,
fail_count
);
Ok(())
}
}
+30 -1
View File
@@ -563,9 +563,38 @@ pub fn verify_file(file_uuid: &str) -> FileVerificationReport {
/// Legacy verification function (backward compatible)
pub fn verify_output(processor: &ProcessorType, file_uuid: &str) -> VerificationResult {
let output_dir = OUTPUT_DIR.as_str();
verify_output_in_dir(processor, file_uuid, output_dir)
}
/// Verification with explicit output directory (per-library aware).
/// Falls back to the global OUTPUT_DIR and the demo subdirectory if the
/// primary path does not exist, so per-library outputs verify correctly.
pub fn verify_output_in_dir(
processor: &ProcessorType,
file_uuid: &str,
output_dir: &str,
) -> VerificationResult {
let proc_name = processor.as_str();
let filename = format!("{}.{}.json", file_uuid, proc_name);
let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(&filename);
// Candidate locations: explicit dir → global OUTPUT_DIR → OUTPUT_DIR/demo
let base = output_dir.trim_end_matches('/');
let global = OUTPUT_DIR.as_str().trim_end_matches('/');
let candidates = if base == global {
vec![
PathBuf::from(base),
PathBuf::from(format!("{}/demo", global)),
]
} else {
vec![PathBuf::from(base), PathBuf::from(global)]
};
let output_path = candidates
.iter()
.map(|d| d.join(&filename))
.find(|p| p.exists())
.unwrap_or_else(|| PathBuf::from(base).join(&filename));
if !output_path.exists() {
return VerificationResult::fail(proc_name, file_uuid, "output file not found");
+107 -81
View File
@@ -1066,8 +1066,10 @@ impl JobWorker {
) -> Result<()> {
use std::path::Path;
// Get output directory from config
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
// Get output directory (per-library, fallback global)
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
// Also check the global output dir for legacy files
let global_output_dir = crate::core::config::OUTPUT_DIR.to_string();
// Get current processor_results
let existing_results = match self
@@ -1090,12 +1092,15 @@ impl JobWorker {
let mut repaired_count = 0;
for processor_type in processors {
let output_path = format!(
"{}/{}.{}.json",
output_dir,
job.uuid,
processor_type.as_str()
);
let filename = format!("{}.{}.json", job.uuid, processor_type.as_str());
// Per-library first, then global fallback (legacy files)
let per_lib_path = format!("{}/{}", output_dir.trim_end_matches('/'), filename);
let global_path = format!("{}/{}", global_output_dir.trim_end_matches('/'), filename);
let output_path = if Path::new(&per_lib_path).exists() {
per_lib_path
} else {
global_path
};
// If file exists but no DB record
if Path::new(&output_path).exists() {
@@ -1639,19 +1644,24 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
.await?;
// Check if output file already exists on disk (source of truth)
let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!(
"{}.{}.json",
job.uuid,
processor_type.as_str()
));
// Per-library output dir(先查此檔案的專屬目錄,fallback 全域)
let per_lib_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
let global_dir = OUTPUT_DIR.as_str();
let filename = format!("{}.{}.json", job.uuid, processor_type.as_str());
let output_path = if PathBuf::from(&per_lib_dir).join(&filename).exists() {
PathBuf::from(&per_lib_dir).join(&filename)
} else {
PathBuf::from(global_dir).join(&filename)
};
debug!("Checking output file: {:?}", output_path);
// Check for stale .tmp file (process crashed before renaming)
let tmp_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!(
"{}.{}.json.tmp",
job.uuid,
processor_type.as_str()
));
let tmp_filename = format!("{}.{}.json.tmp", job.uuid, processor_type.as_str());
let tmp_path = if PathBuf::from(&per_lib_dir).join(&tmp_filename).exists() {
PathBuf::from(&per_lib_dir).join(&tmp_filename)
} else {
PathBuf::from(global_dir).join(&tmp_filename)
};
if tmp_path.exists() && !output_path.exists() {
if let Ok(meta) = std::fs::metadata(&tmp_path) {
// 條件 1: 檔案 > 1KB
@@ -2273,18 +2283,17 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
classification
);
// Create empty ASR output file
// Create empty ASR output file(per-library output dir)
let asr_output = serde_json::json!({
"status": classification,
"segments": [],
"language": "",
"language_probability": 0.0
});
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
let asr_path = format!(
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
output_dir.trim_end_matches('/'),
job.uuid
);
if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) {
@@ -2328,13 +2337,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Enhanced ASRX fast-path: check for silent/no-audio or empty segments
if *processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!(
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid
);
// Per-library output directory
let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
let output_base = output_dir.trim_end_matches('/');
let asr_output_path = format!("{}/{}.asr.json", output_base, job.uuid);
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) {
if let Ok(asr_data) = serde_json::from_str::<serde_json::Value>(&asr_json) {
let asr_status = asr_data.get("status").and_then(|s| s.as_str());
@@ -2357,14 +2364,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
info!("ASRX: fast-path (status={}, segments_empty={})", effective_status, segments_empty);
// Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!(
"{}/{}.asrx.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid
);
// Write asrx.json output file(per-library output dir)
let asrx_output_path = format!("{}/{}.asrx.json", output_base, job.uuid);
let asrx_result = serde_json::json!({
"status": effective_status,
"language": asr_data.get("language").and_then(|l| l.as_str()),
@@ -2426,25 +2427,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Without it, clustering produces no_faces even when faces were detected
// (the trace file is produced later by store_traced_faces.py in P2 trigger).
if *processor_type == crate::core::db::ProcessorType::FaceCluster {
let traced_path = format!(
"{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid
);
// ✅ V2: Validate file integrity, not just existence
let trace_complete = if std::path::Path::new(&traced_path).exists() {
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
let frames = traced_data.get("frames");
frames.map_or(false, |f| match f {
// Per-library output directory lookup (async, correct path resolution)
let output_dir =
crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await;
let output_base = output_dir.trim_end_matches('/');
let traced_path = format!("{}/{}.face_traced.json", output_base, job.uuid);
let trace_complete = if !std::path::Path::new(&traced_path).exists() {
false
} else if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
// Terminal statuses are ready even with empty frames:
// "no_faces"/"completed" means face_trace finished its pass.
let status = traced_data.get("status").and_then(|s| s.as_str()).unwrap_or("");
if status == "no_faces" || status == "completed" {
true
} else {
// Non-terminal status: require non-empty frames
traced_data.get("frames").map_or(false, |f| match f {
serde_json::Value::Array(arr) => !arr.is_empty(),
serde_json::Value::Object(obj) => !obj.is_empty(),
_ => false,
})
} else {
false
}
} else {
false
@@ -2673,11 +2676,20 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
.unwrap_or(0);
if count == 0 {
return false;
// 無 face_track 節點 — 檢查是否為無臉影片或無 embedding
// 避免永久卡在 "Scanning" 狀態
tracing::warn!(
"[TKG] {} has 0 face_track nodes, checking if this is expected",
uuid
);
// 有節點記錄但 count=0 的情況視為完成(可能是無臉影片)
// 讓 job 繼續完成,TKG 可事後修復
return true;
}
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let trace_base_dir = std::path::Path::new(output_dir).join(uuid);
// Per-library output directory(不是全域 OUTPUT_DIR)
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
let trace_base_dir = std::path::Path::new(&output_dir).join(uuid);
if let Ok(entries) = std::fs::read_dir(&trace_base_dir) {
let trace_count = entries
@@ -2718,6 +2730,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
let tkg_nodes_t = schema::table_name("tkg_nodes");
let tkg_edges_t = schema::table_name("tkg_edges");
// Per-library output directory
let output_dir = match crate::core::config::get_output_dir_for_file(uuid, pool).await {
dir if !dir.is_empty() => dir,
_ => crate::core::config::OUTPUT_DIR.to_string(),
};
let has_asr_or_asrx =
job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr" || p == "asr_asrx");
let has_face = job_processors.is_empty() || job_processors.iter().any(|p| p == "face");
@@ -2762,21 +2780,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
if status_from_db {
true
} else {
// Fallback: check asr.json / asr_asrx.json file directly
let asr_path = format!(
"{}/{}.asr.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid
);
let asr_asrx_path = format!(
"{}/{}.asr_asrx.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid
);
// Fallback: check asr.json / asr_asrx.json file directly(per-library output)
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
let output_base = output_dir.trim_end_matches('/');
let asr_path = format!("{}/{}.asr.json", output_base, uuid);
let asr_asrx_path = format!("{}/{}.asr_asrx.json", output_base, uuid);
let content = std::fs::read_to_string(&asr_path)
.or_else(|_| std::fs::read_to_string(&asr_asrx_path));
if let Ok(content) = content {
@@ -2801,9 +2809,9 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
true
};
// 2. Face Trace: face_traced.json 有 traces
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let traced_path = format!("{}/{}.face_traced.json", output_dir, uuid);
// 2. Face Trace: face_traced.json 有 traces(per-library output dir)
let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await;
let traced_path = format!("{}/{}.face_traced.json", output_dir.trim_end_matches('/'), uuid);
let (trace_status, total_faces) = if std::path::Path::new(&traced_path).exists() {
if let Ok(content) = std::fs::read_to_string(&traced_path) {
@@ -2888,8 +2896,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
}
true
} else {
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
let file_exists = std::path::Path::new(&cluster_path).exists();
// Check BOTH per-library and global output dirs
// (rust_face_cluster writes to global OUTPUT_DIR via sync stub)
let cluster_path_lib = format!("{}/{}.face_cluster.json", output_dir, uuid);
let cluster_path_global = format!("{}/{}.face_cluster.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), uuid);
let file_exists = std::path::Path::new(&cluster_path_lib).exists()
|| std::path::Path::new(&cluster_path_global).exists();
if file_exists {
true
} else {
@@ -2937,7 +2950,19 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
});
match qdrant.count_points("_faces", filter).await {
Ok(count) => count > 0,
Ok(count) => {
if count > 0 {
true
} else {
// 有 face_traced 但 Qdrant 無 embeddings → 視為完成
//(可能是 embeddings 未同步或已丟失,不讓 job 永久卡住)
tracing::warn!(
"[Ingestion] {} has face traces but 0 embeddings in Qdrant, proceeding anyway",
uuid
);
true
}
}
Err(_) => false,
}
}
@@ -3099,7 +3124,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
uuid: &str,
job_processors: &[String],
) -> Result<Vec<String>> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
let mut missing = Vec::new();
// 1. 檢查 JSON 產出
@@ -3402,9 +3427,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
});
if face_cluster_done {
// Check if key_frame.jpg files are ready
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let trace_dir = std::path::PathBuf::from(output_dir).join(uuid);
// Check if key_frame.jpg files are ready(per-library output dir)
let output_dir =
crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
let trace_dir = std::path::PathBuf::from(&output_dir).join(uuid);
let key_frame_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
@@ -3427,7 +3453,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
let db_clone = self.db.clone();
let redis_clone = self.redis.clone();
let uuid_clone = uuid.to_string();
let output_dir_clone = crate::core::config::OUTPUT_DIR.clone();
let output_dir_clone = output_dir.clone();
tokio::spawn(async move {
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_clone,
+10 -5
View File
@@ -502,9 +502,14 @@ impl ProcessorPool {
match result {
Ok(output) => {
// 驗收 agent 檢查產出內容
let verification =
crate::verification::verifier::verify_output(&processor_type, &job.uuid);
// 驗收 agent 檢查產出內容(per-library output dir, async lookup)
let output_dir =
crate::core::config::get_output_dir_for_file(&job.uuid, db.pool()).await;
let verification = crate::verification::verifier::verify_output_in_dir(
&processor_type,
&job.uuid,
&output_dir,
);
if verification.passed {
info!(
@@ -679,9 +684,9 @@ impl ProcessorPool {
) -> Result<ProcessorOutput> {
let video_path = job.video_path.as_ref().context("No video path in job")?;
// Determine per-library output directory
// Determine per-library output directory (async, correct path resolution)
let output_dir = PathBuf::from(
crate::core::config::get_output_dir_for_file_sync(&job.uuid, db.pool())
crate::core::config::get_output_dir_for_file(&job.uuid, db.pool()).await
);
let suffix = format!("{}.{}", job.uuid, processor_type.as_str());
let output_path = output_dir.join(format!("{}.json", suffix));
+72 -13
View File
@@ -75,9 +75,18 @@ fn round_json(value: Value) -> Value {
fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) {
let output_data = json!({
"schema_version": "2.0",
"status": status,
"file_uuid": file_uuid,
"stats": {
"total_clusters": 0,
"total_faces": 0,
"noise_faces": 0,
"total_traces": 0,
},
"clusters": [],
"unassigned_traces": [],
"speaker_person_mapping": {},
"frames": [],
});
let text = serde_json::to_string_pretty(&output_data).unwrap_or_default();
@@ -882,9 +891,40 @@ fn main() {
return;
}
// Person face counts + best face (representative).
// Person face counts + best face (representative) using composite scoring.
// Composite score: 0.4 × frontal + 0.4 × confidence + 0.2 × quality
let mut person_face_count: BTreeMap<String, u64> = BTreeMap::new();
let mut person_best_face: BTreeMap<String, Value> = BTreeMap::new();
let mut person_best_score: BTreeMap<String, f64> = BTreeMap::new();
// Pre-compute min/max for normalization within each person
let mut person_stats: BTreeMap<String, (f64, f64, f64, f64, f64, f64)> = BTreeMap::new();
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let frame_num = frame_obj.get("frame")
.and_then(|f| f.as_u64())
.unwrap_or(frame_idx as u64);
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
for face in faces.iter() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(pid) = person_id {
let conf = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.5);
let quality = face.get("captureQuality").and_then(|c| c.as_f64()).unwrap_or(0.0);
let pose = face.get("pose_angle").or_else(|| face.get("pose")).and_then(|p| p.as_object());
let yaw_rad = pose.and_then(|p| p.get("yaw").and_then(|y| y.as_f64())).unwrap_or(0.0);
let yaw_deg = yaw_rad * 57.2958;
let frontal = (1.0 - yaw_deg.abs() / 60.0).max(0.0);
let entry = person_stats.entry(pid.to_string()).or_insert((conf, conf, quality, quality, frontal, frontal));
entry.0 = entry.0.min(conf);
entry.1 = entry.1.max(conf);
entry.2 = entry.2.min(quality);
entry.3 = entry.3.max(quality);
entry.4 = entry.4.min(frontal);
entry.5 = entry.5.max(frontal);
}
}
}
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let frame_num = frame_obj.get("frame")
.and_then(|f| f.as_u64())
@@ -894,18 +934,37 @@ fn main() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(person_id) = person_id {
*person_face_count.entry(person_id.to_string()).or_insert(0) += 1;
let confidence = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.9);
let entry = person_best_face
.entry(person_id.to_string())
.or_insert_with(|| {
json!({
"confidence": f64::NEG_INFINITY,
})
});
if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) {
*entry = json!({
// Calculate composite score
let conf = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.5);
let quality = face.get("captureQuality").and_then(|c| c.as_f64()).unwrap_or(0.0);
let pose = face.get("pose_angle").or_else(|| face.get("pose")).and_then(|p| p.as_object());
let yaw_rad = pose.and_then(|p| p.get("yaw").and_then(|y| y.as_f64())).unwrap_or(0.0);
let yaw_deg = yaw_rad * 57.2958;
let frontal = (1.0 - yaw_deg.abs() / 60.0).max(0.0);
// Normalize within person
let stats = person_stats.get(person_id).unwrap();
let conf_range = stats.1 - stats.0;
let quality_range = stats.3 - stats.2;
let frontal_range = stats.5 - stats.4;
let conf_norm = if conf_range > 0.001 { (conf - stats.0) / conf_range } else { 0.5 };
let quality_norm = if quality_range > 0.001 { (quality - stats.2) / quality_range } else { 0.5 };
let frontal_norm = if frontal_range > 0.001 { (frontal - stats.4) / frontal_range } else { 0.5 };
// Composite: 0.4 frontal + 0.4 confidence + 0.2 quality
let composite_score = 0.4 * frontal_norm + 0.4 * conf_norm + 0.2 * quality_norm;
let current_best = person_best_score.get(person_id).copied().unwrap_or(-1.0);
if composite_score > current_best {
person_best_score.insert(person_id.to_string(), composite_score);
person_best_face.insert(person_id.to_string(), json!({
"face_id": format!("face_{}_{}", frame_num, face_idx),
"confidence": confidence,
"confidence": conf,
"capture_quality": quality,
"yaw_deg": round_digits(yaw_deg, 2),
"composite_score": round_digits(composite_score, 4),
"frame": frame_num,
"bbox": {
"x": face.get("x").cloned().unwrap_or(Value::Null),
@@ -913,7 +972,7 @@ fn main() {
"width": face.get("width").cloned().unwrap_or(Value::Null),
"height": face.get("height").cloned().unwrap_or(Value::Null),
}
});
}));
}
}
}
@@ -349,9 +349,64 @@ fn extract_full_frame(video_path: &str, frame_num: usize, output: &std::path::Pa
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
use std::io::Write;
let best_confidence = trace.best_confidence;
let avg_confidence = trace.avg_confidence;
let best_frame = trace.best_frame;
// Compute real stats from face instances (fallback to path when instances empty)
let instances: &Vec<TracePoint> = if !trace.face_instances.is_empty() {
&trace.face_instances
} else {
&trace.path
};
let avg_confidence = if !instances.is_empty() {
instances.iter().map(|p| p.confidence as f64).sum::<f64>() / instances.len() as f64
} else {
trace.avg_confidence
};
let best = instances.iter().max_by(|a, b| {
a.confidence
.partial_cmp(&b.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
});
let best_frame = best.map(|p| p.frame as u64).unwrap_or(trace.best_frame as u64);
let best_confidence = best.map(|p| p.confidence as f64).unwrap_or(trace.best_confidence);
let best_capture_quality = instances
.iter()
.map(|p| p.capture_quality as f64)
.fold(0.0f64, |acc, q| if q > acc { q } else { acc });
let avg_capture_quality = if !instances.is_empty() {
instances.iter().map(|p| p.capture_quality as f64).sum::<f64>() / instances.len() as f64
} else {
0.0
};
let best_bbox = best.map(|p| {
serde_json::json!({
"x": p.bbox.x, "y": p.bbox.y,
"width": p.bbox.width, "height": p.bbox.height,
"x2": p.bbox.x2, "y2": p.bbox.y2,
"center_x": p.bbox.center_x, "center_y": p.bbox.center_y,
})
});
let avg_bbox = if !instances.is_empty() {
let mut b = trace.avg_bbox.clone();
let n = instances.len() as i32;
b.x = instances.iter().map(|p| p.bbox.x).sum::<i32>() / n;
b.y = instances.iter().map(|p| p.bbox.y).sum::<i32>() / n;
b.width = instances.iter().map(|p| p.bbox.width).sum::<i32>() / n;
b.height = instances.iter().map(|p| p.bbox.height).sum::<i32>() / n;
b.compute_derived();
serde_json::json!({
"x": b.x, "y": b.y,
"width": b.width, "height": b.height,
"x2": b.x2, "y2": b.y2,
"center_x": b.center_x, "center_y": b.center_y,
})
} else {
serde_json::Value::Null
};
let profile = serde_json::json!({
"version": "1.0",
@@ -364,10 +419,10 @@ fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::P
"best_frame": best_frame,
"avg_confidence": avg_confidence,
"best_confidence": best_confidence,
"avg_capture_quality": null,
"best_capture_quality": null,
"avg_bbox": null,
"best_bbox": null,
"avg_capture_quality": avg_capture_quality,
"best_capture_quality": best_capture_quality,
"avg_bbox": avg_bbox,
"best_bbox": best_bbox,
"key_frame": "key_frame.jpg",
"key_face": "key_face.jpg",
"status": "pending",
@@ -789,11 +844,19 @@ fn run_face_tracking(
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
_ => 0.0,
};
// Match if IoU AND similarity meet thresholds
if iou > best_iou
&& iou > iou_threshold
&& similarity > similarity_threshold {
// Match if IoU AND similarity meet thresholds.
// When embeddings are unavailable (either face missing its
// vector), fall back to IoU-only geometric continuation:
// consecutive frames of the same face have overlapping bboxes.
let matched = if current_embedding.is_none() || prev_embedding.is_none() {
iou > best_iou && iou > iou_threshold
} else {
iou > best_iou
&& iou > iou_threshold
&& similarity > similarity_threshold
};
if matched {
best_iou = iou;
best_match = Some((prev_trace_id, iou, similarity));
}