feat: face clustering pipeline improvements and Rust/Swift face processing

- Add Rust face processor module (detection, embedding, tracking, qdrant)
- Add Facenet CoreML/ONNX conversion scripts and tests
- Refactor swift_face into Sources/swift_face with ArgumentParser support
- Update store_traced_faces to handle face.json correctly
- Fix ASRX parsing and TKG bbox reading from Qdrant
- Improve admin_config and trace_agent APIs
- Add M4 workspace docs for face clustering, dedup, and Facenet validation
- Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
This commit is contained in:
Accusys
2026-10-02 12:24:55 +08:00
parent e987fb8119
commit e0d04e242f
87 changed files with 11668 additions and 302 deletions
+39 -2
View File
@@ -223,13 +223,31 @@ async fn list_traces_sorted(
entry.best_confidence = confidence;
entry.best_point_id = point_id;
entry.best_frame = frame;
entry.best_bbox = payload.get("bbox").cloned();
// 先嘗試從 Qdrant 讀取 bbox
let bbox = payload.get("bbox").cloned();
if bbox.is_some() {
entry.best_bbox = bbox;
} else {
// 如果 Qdrant 沒有,從 trace_profile.json 讀取
if let Some(profile) = read_trace_profile(&file_uuid, trace_id) {
entry.best_bbox = profile.get("best_bbox").cloned();
}
}
}
if capture_quality > entry.best_capture_quality {
entry.best_capture_quality = capture_quality;
entry.best_capture_point_id = point_id;
entry.best_capture_frame = frame;
entry.best_capture_bbox = payload.get("bbox").cloned();
// 先嘗試從 Qdrant 讀取 bbox
let bbox = payload.get("bbox").cloned();
if bbox.is_some() {
entry.best_capture_bbox = bbox;
} else {
// 如果 Qdrant 沒有,從 trace_profile.json 讀取
if let Some(profile) = read_trace_profile(&file_uuid, trace_id) {
entry.best_capture_bbox = profile.get("best_bbox").cloned();
}
}
}
}
@@ -2690,3 +2708,22 @@ fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize {
.map(|a| a.len())
.unwrap_or(0)
}
/// Read trace_profile.json for a given file_uuid and trace_id.
fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Value> {
use std::path::PathBuf;
let profile_path: PathBuf = [
crate::core::config::OUTPUT_DIR.as_str(),
file_uuid,
&format!("trace_{}", trace_id),
"trace_profile.json"
].iter().collect();
if let Ok(content) = std::fs::read_to_string(&profile_path) {
if let Ok(profile) = serde_json::from_str::<serde_json::Value>(&content) {
return Some(profile);
}
}
None
}
+22
View File
@@ -185,6 +185,28 @@ pub struct AdminSettings {
pub preferred_language: String,
}
/// Get FS VLM enabled setting from admin_config
/// Returns false by default (FS VLM disabled)
pub async fn get_fs_vlm_enabled(pool: &sqlx::PgPool) -> bool {
use tracing::warn;
let key = "fs_vlm_enabled";
let sql = "SELECT value FROM admin_config WHERE key = $1";
match sqlx::query_scalar::<_, String>(sql)
.bind(key)
.fetch_optional(pool)
.await
{
Ok(Some(value)) => value == "true" || value == "1",
Ok(None) => false, // Default: disabled
Err(e) => {
warn!("[AdminConfig] Failed to get fs_vlm_enabled: {}, using default (false)", e);
false
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchConfig {
#[serde(default = "default_vlm_min_score")]
+3 -3
View File
@@ -684,9 +684,9 @@ impl ProcessorType {
ProcessorType::Ocr,
ProcessorType::Face,
ProcessorType::FaceCluster,
ProcessorType::Pose,
ProcessorType::Hand,
ProcessorType::Appearance,
// ProcessorType::Pose, // Disabled in production pipeline
// ProcessorType::Hand, // Disabled in production pipeline
// ProcessorType::Appearance, // Disabled in production pipeline
]
}
+3 -46
View File
@@ -69,53 +69,10 @@ pub async fn process_asrx(
output_path: &str,
uuid: Option<&str>,
) -> Result<AsrxResult> {
tracing::info!("[ASRX] Starting hybrid speaker diarization: {}", video_path);
let swift_asrx_path = std::path::Path::new("/Users/accusys/momentry_core/scripts/swift_processors/.build/release/asrx_swift");
tracing::info!("[ASRX] Starting speaker diarization: {}", video_path);
if swift_asrx_path.exists() {
tracing::info!("[ASRX] Using Swift processor: {:?}", swift_asrx_path);
let mut args = vec![video_path.to_string(), output_path.to_string()];
if let Some(u) = uuid {
args.push("--uuid".to_string());
args.push(u.to_string());
}
let output = tokio::process::Command::new(swift_asrx_path)
.args(&args)
.output()
.await
.context("Failed to execute asrx_swift")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[ASRX] Swift processor failed: {}", stderr);
tracing::warn!("[ASRX] Falling back to Python processor");
return process_asrx_python(video_path, output_path, uuid).await;
}
tracing::info!("[ASRX] Swift processor completed successfully");
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read ASRX output")?;
let mut result: AsrxResult = serde_json::from_str(&json_str)
.context("Failed to parse ASRX output")?;
result.compute_status();
tracing::info!(
"[ASRX] Swift result: status={}, {} segments",
result.status.as_ref().map(|s| s.to_string()).unwrap_or_default(),
result.segment_count
);
return Ok(result);
}
tracing::warn!("[ASRX] Swift binary not found, using Python processor");
// Use Python processor (Swift ASRX disabled - requires GUI authorization)
tracing::info!("[ASRX] Using Python processor");
process_asrx_python(video_path, output_path, uuid).await
}
+8 -1
View File
@@ -1209,7 +1209,14 @@ impl PythonExecutor {
/// Looks under `<scripts_dir>/rust_processors/target/release/` first, falling
/// back to `target/debug/` (mirrors the swift_processors layout convention).
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
let base = self.scripts_dir.join("rust_processors").join("target");
// Use tools/cli/rust/ instead of scripts/rust_processors/
let cli_dir = std::env::var("MOMENTRY_CLI_DIR")
.unwrap_or_else(|_| {
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
manifest.join("tools/cli").to_string_lossy().to_string()
});
let base = PathBuf::from(cli_dir).join("rust").join("target");
for profile in ["release", "debug"] {
let p = base.join(profile).join(bin_name);
if p.exists() {
+14 -13
View File
@@ -78,19 +78,20 @@ pub async fn process_face_cluster(
});
}
// Build args with optional --threshold
let distance = similarity_threshold.map(|s| 1.0 - s);
let mut args = vec![video_path, output_path];
if let Some(d) = distance {
let threshold_str = format!("{:.4}", d);
args.push("--threshold");
args.push(Box::leak(threshold_str.into_boxed_str()) as &str);
tracing::info!(
"[FACE_CLUSTER] similarity={:.2} → distance={:.4}",
similarity_threshold.unwrap_or(0.65),
d
);
}
// Build args with --threshold (always pass, default 0.15)
let threshold = similarity_threshold.unwrap_or(0.85);
let distance = 1.0 - threshold;
let threshold_str = format!("{:.4}", distance);
let mut args = vec![
video_path,
output_path,
"--threshold",
Box::leak(threshold_str.into_boxed_str()) as &str,
];
tracing::info!(
"[FACE_CLUSTER] Using threshold: similarity={:.2}, distance={:.4}",
threshold, distance
);
// Try Rust binary first (preferred), fallback to Python if unavailable
if let Some(rust_bin) = executor.rust_binary_path("rust_face_cluster") {
+6 -2
View File
@@ -278,12 +278,16 @@ async fn populate_face_detections_from_face_json(
publish_tkg_progress(&r, file_uuid, &progress).await;
}
// Use Rust binary for face trace (V3 config: priority 0)
let rust_binary = "tools/cli/rust/target/release/rust_store_traced_faces";
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let executor = crate::core::processor::executor::PythonExecutor::new()?;
let result = executor
.run_with_output_idx(
"store_traced_faces.py",
&["--file-uuid", file_uuid],
rust_binary,
&[file_uuid, "--output-dir", output_dir],
Some(file_uuid),
"TKG_PHASE0",
Some(std::time::Duration::from_secs(600)),
+83 -70
View File
@@ -11,8 +11,9 @@ use tracing::{debug, error, info, warn};
/// Bounds the number of concurrent heavy face-I/O Python tasks (store_traced_faces.py /
/// TKG build). These spawns bypass ProcessorPool (raw tokio::spawn) and each loads the
/// full face.json into numpy + scrolls all Qdrant face points, which previously caused
/// unbounded pile-up and OOM. Capacity mirrors FRAME_SLOT_MAX in processor.rs.
static FACE_IO_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(2));
/// unbounded pile-up and OOM. Increased from 2 to 4 to match FRAME_SLOT_MAX and avoid
/// resource starvation when multiple videos are processed in parallel.
static FACE_IO_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
/// Max time a spawn task waits for a FACE_IO_SEM permit before backing off.
/// A stuck task holding a permit would otherwise block every queued spawn
@@ -253,8 +254,9 @@ impl JobWorker {
.query_async(&mut conn)
.await
.ok();
// Set TTL = 3x poll_interval so stale entries expire
let ttl_secs = (self.config.poll_interval_secs * 3) as i64;
// Set TTL = max(3x poll_interval, 60s) so long-running poll iterations
// (heavy jobs, VLM, release packing) do not let the heartbeat expire
let ttl_secs = (self.config.poll_interval_secs * 3).max(60) as i64;
let _: Result<(), _> = redis::cmd("EXPIRE")
.arg(&[health_key.as_str(), &ttl_secs.to_string()])
.query_async(&mut conn)
@@ -2335,76 +2337,87 @@ impl JobWorker {
let mut created_deferred = false;
// [RE-ENABLED] FS VLM Summary with Gemma4 + Parallel processing (2026-09-22)
// Check VLM summary progress — if incomplete, trigger/restart
let tp_table = schema::table_name("trace_profiles");
let vlm_total: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let vlm_done: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
// [DISABLED] FS VLM Summary - controlled by admin_config
// System now only uses Scene VLM (10 sec moment vlm)
// To enable: set fs_vlm_enabled=true in admin_config table
let fs_vlm_enabled = crate::core::admin_config::get_fs_vlm_enabled(self.db.pool()).await;
if fs_vlm_enabled {
// [ORIGINAL FS VLM CODE - DISABLED BY DEFAULT]
// Check VLM summary progress — if incomplete, trigger/restart
let tp_table = schema::table_name("trace_profiles");
let vlm_total: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let vlm_done: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
if vlm_total > 0 && vlm_done < vlm_total {
// VLM incomplete — check if we should trigger it
let face_cluster_done = job_processors.iter().any(|p| p == "face_cluster")
&& results.iter().any(|r| {
r.processor_type.as_str() == "face_cluster"
&& matches!(r.status, ProcessorJobStatus::Completed)
});
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);
let key_frame_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
.map(|entries| {
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().join("key_frame.jpg").exists())
.count() as i64
})
.unwrap_or(0)
} else {
0
};
if key_frame_count >= vlm_total {
info!(
"[VLM-poll] {}/{} done, {}/{} key_frames ready — triggering VLM",
vlm_done, vlm_total, key_frame_count, vlm_total
);
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();
tokio::spawn(async move {
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_clone,
&uuid_clone,
&output_dir_clone,
Some(redis_clone),
)
.await;
if vlm_total > 0 && vlm_done < vlm_total {
// VLM incomplete — check if we should trigger it
let face_cluster_done = job_processors.iter().any(|p| p == "face_cluster")
&& results.iter().any(|r| {
r.processor_type.as_str() == "face_cluster"
&& matches!(r.status, ProcessorJobStatus::Completed)
});
} else {
info!(
"[VLM-poll] Waiting for key_frame.jpg: {}/{} ready",
key_frame_count, vlm_total
);
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);
let key_frame_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
.map(|entries| {
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().join("key_frame.jpg").exists())
.count() as i64
})
.unwrap_or(0)
} else {
0
};
if key_frame_count >= vlm_total {
info!(
"[VLM-poll] {}/{} done, {}/{} key_frames ready — triggering VLM",
vlm_done, vlm_total, key_frame_count, vlm_total
);
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();
tokio::spawn(async move {
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_clone,
&uuid_clone,
&output_dir_clone,
Some(redis_clone),
)
.await;
});
} else {
info!(
"[VLM-poll] Waiting for key_frame.jpg: {}/{} ready",
key_frame_count, vlm_total
);
}
}
}
}
} // end if fs_vlm_enabled
// Initialize vlm_done for moment check (always 0 since FS VLM is disabled)
let vlm_done: i64 = 0;
let chunk_t = schema::table_name("chunk");
let moment_exists: bool = sqlx::query_scalar(&format!(
"SELECT EXISTS(SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'moment')"
+31 -26
View File
@@ -23,39 +23,42 @@ struct ProcessorCleanupGuard {
impl Drop for ProcessorCleanupGuard {
fn drop(&mut self) {
use tokio::sync::TryLockError;
if let Ok(mut guard) = self.running.try_write() {
guard.remove(&self.job_id);
} else {
warn!("[ProcessorCleanupGuard] running lock contended");
// Release running map
match self.running.try_write() {
Ok(mut guard) => { guard.remove(&self.job_id); }
Err(_) => error!("[ProcessorCleanupGuard] Failed to acquire running lock for job {} - resource may leak", self.job_id),
}
if let Ok(mut guard) = self.running_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
// Release running count
match self.running_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release running_count for job {}", self.job_id),
}
if let Ok(mut guard) = self.running_per_job.try_write() {
if let Some(c) = guard.get_mut(&self.job_id) {
if *c > 0 {
*c -= 1;
}
if *c == 0 {
guard.remove(&self.job_id);
// Release per-job count
match self.running_per_job.try_write() {
Ok(mut guard) => {
if let Some(c) = guard.get_mut(&self.job_id) {
if *c > 0 { *c -= 1; }
if *c == 0 { guard.remove(&self.job_id); }
}
}
Err(_) => error!("[ProcessorCleanupGuard] Failed to release running_per_job for job {}", self.job_id),
}
// Release pipeline-specific slot
match self.pipeline {
PipelineType::Frame => {
if let Ok(mut guard) = self.frame_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
match self.frame_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release frame slot for job {}", self.job_id),
}
}
PipelineType::Time => {
if let Ok(mut guard) = self.time_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
match self.time_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release time slot for job {}", self.job_id),
}
}
PipelineType::Cross => {}
@@ -109,9 +112,11 @@ pub struct ProcessorTask {
}
/// Frame pipeline max concurrent processors (hard limit).
const FRAME_SLOT_MAX: usize = 2;
/// Time pipeline max concurrent processors (audio is heavy, run 1 at a time).
const TIME_SLOT_MAX: usize = 1;
/// Increased from 2 to 4 to match max_concurrent and avoid resource starvation.
const FRAME_SLOT_MAX: usize = 4;
/// Time pipeline max concurrent processors (audio is heavy, run 2 at a time).
/// Increased from 1 to 2 to improve throughput.
const TIME_SLOT_MAX: usize = 2;
pub struct ProcessorPool {
db: Arc<PostgresDb>,