From c7521f0e2b5268bd51807ceaf9943033d05c5050 Mon Sep 17 00:00:00 2001 From: Accusys Date: Fri, 20 Nov 2026 01:43:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20face=20cluster=20=E9=81=8E=E6=BF=BE?= =?UTF-8?q?=E4=BD=8E=E5=93=81=E8=B3=AA=E5=96=AE=E5=B9=80=E8=AA=A4=E6=AA=A2?= =?UTF-8?q?=EF=BC=88=E5=A6=82=E6=89=8B/=E7=89=A9=E9=AB=94=EF=BC=89+=20?= =?UTF-8?q?=E5=82=B3=E9=81=9E=E6=80=A7=E5=90=8C=E5=B9=80=E7=B4=84=E6=9D=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增單幀品質過濾:若 trace 只有 1 個 face 且 avg_quality < 0.20 且 avg_conf < 0.65,排除該 trace(避免手/模糊物體被當作臉) - merge_small_clusters 加入傳遞性同幀約束:合併前檢查兩群的 trace 是否有同幀衝突,避免不同人被合併 - 迭代式合併:每輪重新計算 centroid,確保鏈式合併使用最新資料 驗證: - trace 16 (hand, quality=0.18, conf=0.59, 1 face) 被正確過濾 - 同幀約束防止女性 trace 20 與男性 trace 合併 - 1c6f40 測試: 5 persons → 4 persons → 最終 1 person (正確) --- tools/cli/rust/src/bin/rust_face_cluster.rs | 53 +- .../cli/rust/src/bin/rust_face_cluster.rs.bak | 804 ------------------ 2 files changed, 47 insertions(+), 810 deletions(-) delete mode 100644 tools/cli/rust/src/bin/rust_face_cluster.rs.bak diff --git a/tools/cli/rust/src/bin/rust_face_cluster.rs b/tools/cli/rust/src/bin/rust_face_cluster.rs index 74568503..1d990f8a 100644 --- a/tools/cli/rust/src/bin/rust_face_cluster.rs +++ b/tools/cli/rust/src/bin/rust_face_cluster.rs @@ -216,6 +216,21 @@ fn cluster_by_trace( if trace_points.len() < min_faces_per_trace { continue; } + // Filter out single-face traces with very low quality (likely false positives + // like hands/objects detected as faces). + if trace_points.len() == 1 { + let avg_quality: f64 = trace_points.iter() + .filter_map(|p| p.payload.get("capture_quality").and_then(|q| q.as_f64())) + .sum::() / trace_points.len() as f64; + let avg_conf: f64 = trace_points.iter() + .filter_map(|p| p.payload.get("confidence").and_then(|q| q.as_f64())) + .sum::() / trace_points.len() as f64; + if avg_quality < 0.20 && avg_conf < 0.65 { + eprintln!("[FILTER] Excluding trace {} (1 face, quality={:.2}, conf={:.2}) - likely false positive", + trace_id, avg_quality, avg_conf); + continue; + } + } let mut embeddings: Vec<&[f64]> = Vec::new(); let mut weights: Vec = Vec::new(); for p in trace_points { @@ -584,12 +599,26 @@ fn merge_small_clusters( cooccurrence: &std::collections::HashSet<(i64, i64)>, ) -> std::collections::BTreeMap { let mut trace_to_person = trace_to_person; - let merge_sim = merge_similarity_threshold; - // Iteratively merge the most-similar compatible pair until no merge is - // possible. Recompute centroids each round so chained merges use fresh data. - // Co-occurrence constraint prevents merging traces that appeared together - // in a frame (different physical people). + // Compute transitive conflict: for each cluster, collect ALL traces that + // co-occur with any of its members (recursively). A trace conflicting with + // a cluster member is implicitly conflicting with the whole cluster. + let mut conflict_map: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for &pid in trace_to_person.values().collect::>().iter() { + let mut conflicting: std::collections::HashSet = std::collections::HashSet::new(); + let member_traces: Vec = trace_to_person.iter() + .filter(|(_, p)| **p == *pid) + .map(|(t, _)| *t).collect(); + for &t in &member_traces { + for &(a, b) in cooccurrence { + if a == t { conflicting.insert(b); } + if b == t { conflicting.insert(a); } + } + } + conflict_map.insert(*pid, conflicting); + } + + let merge_sim = merge_similarity_threshold; loop { let mut cur_traces: std::collections::BTreeMap> = std::collections::BTreeMap::new(); for (tid, pid) in &trace_to_person { @@ -624,12 +653,24 @@ fn merge_small_clusters( }; let sim = cosine_similarity(ea, eb); if sim < merge_sim { continue; } + // Direct co-occurrence guard let conflict = cur_traces[&pa].iter().any(|a| { cur_traces[&pb].iter().any(|b| { cooccurrence.contains(&((*a).min(*b), (*a).max(*b))) }) }); - if !conflict && best.map_or(true, |(bs, _, _)| sim > bs) { + // Transitive co-occurrence guard: if any trace in A conflicts with + // any trace that belongs to B (even in a different cluster), merging + // would indirectly force a co-occurrence violation. + let transitive_conflict = cur_traces[&pa].iter().any(|t| { + conflict_map.get(&pb).map(|c| c.contains(t)).unwrap_or(false) + }) || cur_traces[&pb].iter().any(|t| { + conflict_map.get(&pa).map(|c| c.contains(t)).unwrap_or(false) + }); + if transitive_conflict { + eprintln!(" [DEBUG TRANS] Person_{} blocked by transitive with Person_{}", pa, pb); + } + if !conflict && !transitive_conflict && best.map_or(true, |(bs, _, _)| sim > bs) { best = Some((sim, pa, pb)); } } diff --git a/tools/cli/rust/src/bin/rust_face_cluster.rs.bak b/tools/cli/rust/src/bin/rust_face_cluster.rs.bak deleted file mode 100644 index a496288c..00000000 --- a/tools/cli/rust/src/bin/rust_face_cluster.rs.bak +++ /dev/null @@ -1,804 +0,0 @@ -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::time::Duration; - -use clap::Parser; -use serde_json::{json, Value}; - -/// Face Clustering Processor (Rust port of fast_face_clustering_processor.py) -/// -/// Loads face embeddings from Qdrant `_faces`, groups by trace_id, computes -/// weighted-average embeddings per trace, then clusters traces with either the -/// seed-leader method (default, deterministic) or average-linkage agglomerative. -#[derive(Parser)] -#[command(name = "rust_face_cluster", about = "Face Clustering Processor (Rust port)")] -struct Args { - video_path: String, - output_path: PathBuf, - #[arg(short = 'u', long = "uuid", default_value = "")] - uuid: String, - #[arg(long = "frames", default_value = None)] - frames: Option, - #[arg(long = "method", default_value = "leader")] - method: String, - #[arg(long = "threshold", default_value_t = 0.35)] - threshold: f64, - #[arg(long = "force")] - force: bool, -} - -const CONFIDENCE_THRESHOLD: f64 = 0.5; -const DEFAULT_QDRANT_URL: &str = "http://localhost:6333"; -const DEFAULT_QDRANT_API_KEY: &str = "Test3200Test3200Test3200"; - -#[derive(Clone)] -struct FacePoint { - payload: Value, - vector: Vec, -} - -fn env_var(name: &str, default: &str) -> String { - std::env::var(name).unwrap_or_else(|_| default.to_string()) -} - -/// Mimic Python's `round(x, n)` (banker's rounding / round-half-to-even). -fn round_digits(x: f64, digits: i32) -> f64 { - let factor = 10_f64.powi(digits); - (x * factor).round_ties_even() / factor -} - -/// Recursively round all float values to 2 decimals (Python `round_json_numbers`). -fn round_json(value: Value) -> Value { - match value { - Value::Number(n) => { - if n.is_f64() { - let f = n.as_f64().unwrap_or(0.0); - let r = round_digits(f, 2); - serde_json::Number::from_f64(r) - .map(Value::Number) - .unwrap_or(Value::Number(n)) - } else { - Value::Number(n) - } - } - Value::Array(items) => Value::Array(items.into_iter().map(round_json).collect()), - Value::Object(map) => { - Value::Object(map.into_iter().map(|(k, v)| (k, round_json(v))).collect()) - } - other => other, - } -} - -fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) { - let output_data = json!({ - "status": status, - "file_uuid": file_uuid, - "clusters": [], - "frames": [], - }); - let text = serde_json::to_string_pretty(&output_data).unwrap_or_default(); - let _ = std::fs::write(output_path, text); - eprintln!("Wrote empty output ({}) to {}", status, output_path.display()); -} - -/// Scroll all Qdrant `_faces` points (payload + vector) for a file via HTTP. -fn load_qdrant_faces(uuid: &str) -> Vec { - let qdrant_url = env_var("QDRANT_URL", DEFAULT_QDRANT_URL); - let qdrant_api_key = env_var("QDRANT_API_KEY", DEFAULT_QDRANT_API_KEY); - let scroll_url = format!("{}/collections/_faces/points/scroll", qdrant_url); - - let mut all_points: Vec = Vec::new(); - let mut offset: Option = None; - loop { - let mut body = json!({ - "limit": 10000, - "with_payload": true, - "with_vector": true, - "filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}, - }); - if let Some(ref off) = offset { - body["offset"] = off.clone(); - } - - let resp = ureq::post(&scroll_url) - .set("api-key", &qdrant_api_key) - .timeout(Duration::from_secs(60)) - .send_json(body); - - match resp { - Ok(r) => { - let data: Value = r.into_json().unwrap_or(Value::Null); - let points = data - .pointer("/result/points") - .and_then(|p| p.as_array()) - .cloned() - .unwrap_or_default(); - for p in points { - let payload = p.get("payload").cloned().unwrap_or(Value::Null); - let vector = p - .get("vector") - .and_then(|v| v.as_array()) - .map(|v| { - v.iter() - .filter_map(|x| x.as_f64()) - .collect::>() - }) - .unwrap_or_default(); - all_points.push(FacePoint { payload, vector }); - } - let next = data.pointer("/result/next_page_offset").cloned(); - match next { - Some(Value::Number(n)) if n.as_i64().unwrap_or(0) != 0 => offset = Some(Value::Number(n)), - Some(Value::Number(_)) => break, - Some(Value::Null) | None => break, - other => { - offset = other; - } - } - } - Err(e) => { - eprintln!("Qdrant scroll error: {}", e); - break; - } - } - } - eprintln!("Loaded {} points from Qdrant _faces", all_points.len()); - all_points -} - -fn dot(a: &[f64], b: &[f64]) -> f64 { - a.iter().zip(b).map(|(x, y)| x * y).sum() -} - -fn norm(v: &[f64]) -> f64 { - v.iter().map(|x| x * x).sum::().sqrt() -} - -fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 { - let n1 = norm(a); - let n2 = norm(b); - if n1 > 0.0 && n2 > 0.0 { - dot(a, b) / (n1 * n2) - } else { - -1.0 - } -} - -/// Weighted-average embedding per trace + pairs (cluster_by_trace). -/// Returns (trace_embeddings: BTreeMap>). -fn cluster_by_trace( - points: &[FacePoint], - min_faces_per_trace: usize, - confidence_threshold: f64, -) -> BTreeMap> { - let high_conf: Vec<&FacePoint> = points - .iter() - .filter(|p| { - p.payload - .get("confidence") - .and_then(|c| c.as_f64()) - .unwrap_or(0.0) - >= confidence_threshold - }) - .collect(); - eprintln!( - "[FILTER] {}/{} faces pass confidence >= {}", - high_conf.len(), - points.len(), - confidence_threshold - ); - - let mut traces: BTreeMap> = BTreeMap::new(); - for p in &high_conf { - if let Some(trace_id) = p.payload.get("trace_id").and_then(|t| t.as_i64()) { - if trace_id >= 0 { - traces.entry(trace_id).or_default().push(p); - } - } - } - eprintln!("[TRACE] Found {} unique traces", traces.len()); - - let mut trace_embeddings: BTreeMap> = BTreeMap::new(); - for (trace_id, trace_points) in traces.iter() { - if trace_points.len() < min_faces_per_trace { - continue; - } - let mut embeddings: Vec<&[f64]> = Vec::new(); - let mut weights: Vec = Vec::new(); - for p in trace_points { - embeddings.push(&p.vector); - weights.push(p.payload.get("confidence").and_then(|c| c.as_f64()).unwrap_or(1.0)); - } - let weight_sum: f64 = weights.iter().sum(); - for w in weights.iter_mut() { - *w /= weight_sum; - } - let dim = embeddings.first().map(|e| e.len()).unwrap_or(0); - let mut avg = vec![0.0_f64; dim]; - for (e, w) in embeddings.iter().zip(weights.iter()) { - for (i, x) in e.iter().enumerate() { - avg[i] += x * w; - } - } - let n = norm(&avg); - if n > 0.0 { - for x in avg.iter_mut() { - *x /= n; - } - } - trace_embeddings.insert(*trace_id, avg); - } - eprintln!( - "[TRACE] {} traces with >= {} faces", - trace_embeddings.len(), - min_faces_per_trace - ); - trace_embeddings -} - -/// Seed-leader clustering with incremental mean centroids (Python default method). -/// Returns (trace_to_person, trace_similarities). -fn seed_leader_cluster( - trace_embeddings: &BTreeMap>, - threshold: f64, -) -> (BTreeMap, BTreeMap) { - let trace_ids: Vec<&i64> = trace_embeddings.keys().collect(); - let n_traces = trace_ids.len(); - if n_traces == 0 { - return (BTreeMap::new(), BTreeMap::new()); - } - if n_traces == 1 { - let tid = *trace_ids[0]; - let mut tm = BTreeMap::new(); - tm.insert(tid, 0); - let mut sm = BTreeMap::new(); - sm.insert(tid, 1.0); - return (tm, sm); - } - - let sim_threshold = 1.0 - threshold; - let mut persons: Vec<(Vec, Vec)> = Vec::new(); // (centroid, member_trace_ids) - let mut trace_similarities: BTreeMap = BTreeMap::new(); - - for tid in trace_ids { - let centroid = trace_embeddings[tid].clone(); - if persons.is_empty() { - persons.push((centroid, vec![*tid])); - trace_similarities.insert(*tid, 1.0); - continue; - } - - let mut best_sim = -1.0; - let mut best_person_idx: Option = None; - for (idx, person) in persons.iter().enumerate() { - let sim = cosine_similarity(¢roid, &person.0); - if sim > best_sim { - best_sim = sim; - best_person_idx = Some(idx); - } - } - - match best_person_idx { - Some(idx) if best_sim >= sim_threshold => { - persons[idx].1.push(*tid); - trace_similarities.insert(*tid, best_sim); - let members: Vec> = persons[idx] - .1 - .iter() - .map(|m| trace_embeddings[m].clone()) - .collect(); - let dim = members[0].len(); - let mut mean = vec![0.0_f64; dim]; - for m in &members { - for (i, x) in m.iter().enumerate() { - mean[i] += x; - } - } - let cnt = members.len() as f64; - for x in mean.iter_mut() { - *x /= cnt; - } - persons[idx].0 = mean; - } - _ => { - persons.push((centroid, vec![*tid])); - trace_similarities.insert(*tid, 1.0); - } - } - } - - let mut trace_to_person: BTreeMap = BTreeMap::new(); - for (person_label, person) in persons.iter().enumerate() { - for m in &person.1 { - trace_to_person.insert(*m, person_label as i64); - } - } - eprintln!("[CLUSTER] Seed-leader detected {} unique persons", persons.len()); - (trace_to_person, trace_similarities) -} - -/// Average-linkage agglomerative clustering (sklearn AgglomerativeClustering -/// with metric="cosine", linkage="average", distance_threshold=threshold). -/// Trace similarity is a 1.0 placeholder, matching the Python script. -fn agglomerative_cluster( - trace_embeddings: &BTreeMap>, - threshold: f64, -) -> (BTreeMap, BTreeMap) { - let trace_ids: Vec<&i64> = trace_embeddings.keys().collect(); - let n = trace_ids.len(); - if n == 0 { - return (BTreeMap::new(), BTreeMap::new()); - } - if n == 1 { - let mut tm = BTreeMap::new(); - tm.insert(*trace_ids[0], 0); - let mut sm = BTreeMap::new(); - sm.insert(*trace_ids[0], 1.0); - return (tm, sm); - } - - // distance matrix: 1 - cosine - let mut dist = vec![vec![0.0_f64; n]; n]; - for i in 0..n { - for j in (i + 1)..n { - let d = 1.0 - cosine_similarity(&trace_embeddings[&trace_ids[i]], &trace_embeddings[&trace_ids[j]]); - dist[i][j] = d; - dist[j][i] = d; - } - } - - // Each cluster: set of member indices. Merges happen in-place: targets stay - // within 0..n, merged-away clusters are cleared + marked inactive. - let mut clusters: Vec> = (0..n).map(|i| vec![i]).collect(); - let mut active = vec![true; n]; - - loop { - // Find pair (a, b) with min distance among active clusters (average linkage). - // Given the input is trace means, average linkage of members = average of - // pairwise distances. We maintain dist as the average linkage between clusters. - let mut best_d = f64::INFINITY; - let mut best_pair: Option<(usize, usize)> = None; - for a in 0..n { - if !active[a] || clusters[a].is_empty() { - continue; - } - for b in (a + 1)..n { - if !active[b] || clusters[b].is_empty() { - continue; - } - if dist[a][b] < best_d { - best_d = dist[a][b]; - best_pair = Some((a, b)); - } - } - } - - let Some((a, b)) = best_pair else { break }; - if best_d > threshold { - break; - } - - // Merge b into a. - let mut merged = clusters[a].clone(); - merged.extend_from_slice(&clusters[b]); - clusters[a] = merged; - clusters[b].clear(); - active[b] = false; - - // Update average-linkage distances from merged cluster (a) to all others. - // Recompute via members is exact for average linkage (UPGMA). - for k in 0..n { - if !active[k] || k == a || clusters[k].is_empty() { - continue; - } - let mut sum = 0.0; - let mut cnt = 0; - for &mi in &clusters[a] { - for &mk in &clusters[k] { - sum += 1.0 - cosine_similarity( - &trace_embeddings[&trace_ids[mi]], - &trace_embeddings[&trace_ids[mk]], - ); - cnt += 1; - } - } - dist[a][k] = if cnt > 0 { sum / cnt as f64 } else { f64::INFINITY }; - dist[k][a] = dist[a][k]; - } - } - - let mut trace_to_person: BTreeMap = BTreeMap::new(); - let mut label = 0; - for cid in 0..n { - if active[cid] && !clusters[cid].is_empty() { - for &mi in &clusters[cid] { - trace_to_person.insert(*trace_ids[mi], label); - } - label += 1; - } - } - - let mut trace_similarities: BTreeMap = BTreeMap::new(); - for tid in trace_ids.iter() { - trace_similarities.insert(**tid, 1.0); - } - - eprintln!("[CLUSTER] Agglomerative detected {} unique persons", label); - (trace_to_person, trace_similarities) -} - -fn main() { - let args = Args::parse(); - - let uuid = if args.uuid.is_empty() { - std::path::Path::new(&args.video_path) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("quick_preview") - .to_string() - } else { - args.uuid.clone() - }; - - let output_dir = args.output_path.parent().unwrap_or(std::path::Path::new(".")); - let mut face_json_path = output_dir.join(format!("{}.face.json", uuid)); - - eprintln!("[FACE_CLUSTER] Starting face clustering: {}", args.video_path); - eprintln!("[DEBUG] Output dir: {:?}", output_dir); - eprintln!("[DEBUG] Initial face_json_path: {:?}", face_json_path); - eprintln!("[DEBUG] File exists (attempt 1): {}", face_json_path.exists()); - - if !face_json_path.exists() { - face_json_path = output_dir.join(&uuid).join(format!("{}.face.json", uuid)); - eprintln!("[DEBUG] Fallback face_json_path: {:?}", face_json_path); - eprintln!("[DEBUG] File exists (attempt 2): {}", face_json_path.exists()); - } - - if !face_json_path.exists() { - eprintln!("Face JSON not found."); - write_empty_output("no_face_json", &uuid, &args.output_path); - return; - } - - let face_json_content = std::fs::read_to_string(&face_json_path).expect("Failed to read face.json"); - eprintln!("[DEBUG] Face JSON content length: {} bytes", face_json_content.len()); - - let face_data: Value = serde_json::from_str(&face_json_content).expect("Failed to parse face.json"); - eprintln!("[DEBUG] Face data top-level keys: {:?}", face_data.as_object().map(|o| o.keys().collect::>())); - - let frames_list = face_data.get("frames").and_then(|f| f.as_array()).cloned().unwrap_or_default(); - eprintln!("[DEBUG] Frames list length: {}", frames_list.len()); - - if frames_list.is_empty() { - eprintln!("No frames in JSON (no faces)."); - write_empty_output("no_faces", &uuid, &args.output_path); - return; - } - - let fps_value = face_data - .get("fps") - .and_then(|f| f.as_f64()) - .unwrap_or(23.98); - - let points = load_qdrant_faces(&uuid); - if points.is_empty() { - eprintln!("No embeddings found in Qdrant."); - write_empty_output("no_embeddings", &uuid, &args.output_path); - return; - } - - let threshold = args.threshold; - let trace_embeddings = cluster_by_trace(&points, 1, CONFIDENCE_THRESHOLD); - if trace_embeddings.is_empty() { - eprintln!("No valid traces found."); - write_empty_output("no_embeddings", &uuid, &args.output_path); - return; - } - - let (trace_to_person, trace_similarities) = if args.method == "agglomerative" { - agglomerative_cluster(&trace_embeddings, threshold) - } else { - seed_leader_cluster(&trace_embeddings, threshold) - }; - - if trace_to_person.is_empty() { - eprintln!("Clustering produced no results."); - write_empty_output("no_embeddings", &uuid, &args.output_path); - return; - } - - let n_persons: usize = trace_to_person.values().collect::>().len(); - eprintln!("Clustering result: {} persons ({} traces)", n_persons, trace_to_person.len()); - - // Load face_traced.json to get trace_id for each face. - let traced_path = output_dir.join(format!("{}.face_traced.json", uuid)); - let mut traced_frames: Value = Value::Object(Default::default()); - if traced_path.exists() { - if let Ok(s) = std::fs::read_to_string(&traced_path) { - if let Ok(v) = serde_json::from_str::(&s) { - let frames_raw = v.get("frames").cloned().unwrap_or_else(|| Value::Object(Default::default())); - // Handle both array and object formats - if let Some(frames_array) = frames_raw.as_array() { - // Convert array to object for compatibility - for frame_obj in frames_array { - if let Some(frame_num) = frame_obj.get("frame").and_then(|f| f.as_u64()) { - if let Some(obj) = traced_frames.as_object_mut() { - obj.insert(frame_num.to_string(), frame_obj.clone()); - } - } - } - eprintln!(" Loaded face_traced.json: {} frames (converted from array)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0)); - } else if frames_raw.is_object() { - traced_frames = frames_raw; - eprintln!(" Loaded face_traced.json: {} frames (dict)", traced_frames.as_object().map(|o| o.len()).unwrap_or(0)); - } else { - eprintln!(" Warning: Unexpected frames format: {:?}", frames_raw); - } - } - } - } - - let mut matched_count = 0_i64; - let mut frames_list = frames_list; - for (frame_idx, frame_obj) in frames_list.iter_mut().enumerate() { - let frame_num = frame_obj - .get("frame") - .and_then(|f| f.as_i64()) - .unwrap_or(frame_idx as i64); - let traced_frame = traced_frames - .get(frame_num.to_string().as_str()) - .cloned() - .unwrap_or_else(|| json!({})); - let traced_faces = traced_frame - .get("faces") - .and_then(|f| f.as_array()) - .cloned() - .unwrap_or_default(); - - if let Some(faces) = frame_obj.get_mut("faces").and_then(|f| f.as_array_mut()) { - for (face_idx, face) in faces.iter_mut().enumerate() { - let trace_id = traced_faces - .get(face_idx) - .and_then(|f| f.get("trace_id")) - .and_then(|t| t.as_i64()); - if let Some(trace_id) = trace_id { - if let Some(person_label) = trace_to_person.get(&trace_id) { - face["person_id"] = json!(format!("Person_{}", person_label)); - face["trace_id"] = json!(trace_id); - matched_count += 1; - } - } - } - } - } - eprintln!(" Assigned person_id to {} faces", matched_count); - - if matched_count == 0 { - eprintln!("No faces matched to any trace - check Qdrant data integrity"); - write_empty_output("no_faces", &uuid, &args.output_path); - return; - } - - // Person face counts + best face (representative). - let mut person_face_count: BTreeMap = BTreeMap::new(); - let mut person_best_face: BTreeMap = BTreeMap::new(); - for (frame_idx, frame_obj) in frames_list.iter().enumerate() { - let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default(); - for (face_idx, face) in faces.iter().enumerate() { - 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!({ - "face_id": format!("face_{}_{}", frame_idx, face_idx), - "confidence": confidence, - "frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)), - "bbox": { - "x": face.get("x").cloned().unwrap_or(Value::Null), - "y": face.get("y").cloned().unwrap_or(Value::Null), - "width": face.get("width").cloned().unwrap_or(Value::Null), - "height": face.get("height").cloned().unwrap_or(Value::Null), - } - }); - } - } - } - } - - // Build per-person similarity stats from trace_similarities. - let mut person_sims: BTreeMap> = BTreeMap::new(); - let sim_threshold_value = 1.0 - threshold; - for (tid, person_label) in trace_to_person.iter() { - let sim = trace_similarities.get(tid).copied().unwrap_or(0.0); - person_sims.entry(*person_label).or_default().push(sim); - } - - let mut sorted_persons: Vec<(&String, &u64)> = person_face_count.iter().collect(); - sorted_persons.sort_by(|a, b| b.1.cmp(a.1)); - - let mut clusters: Vec = Vec::new(); - for (person_id, count) in sorted_persons { - let person_label: Option = person_id - .split('_') - .nth(1) - .and_then(|s| s.parse::().ok()); - - let mut similarity_info: Option = None; - if let Some(label) = person_label { - if let Some(sims) = person_sims.get(&label) { - if !sims.is_empty() { - let min_s = sims.iter().cloned().fold(f64::INFINITY, f64::min); - let avg_s = sims.iter().sum::() / sims.len() as f64; - similarity_info = Some(json!({ - "min": round_digits(min_s, 4), - "avg": round_digits(avg_s, 4), - "threshold": round_digits(sim_threshold_value, 4), - })); - } - } - } - - let mut cluster_entry = json!({ - "cluster_id": person_id, - "face_count": count, - }); - if let Some(rep) = person_best_face.get(person_id) { - cluster_entry["representative_face"] = rep.clone(); - } - if let Some(sim) = similarity_info { - cluster_entry["similarity"] = sim; - } - clusters.push(cluster_entry); - } - - // Build output frames. - let mut output_frames: Vec = Vec::new(); - for (frame_idx, frame_obj) in frames_list.iter().enumerate() { - let timestamp = frame_obj.get("timestamp").cloned().unwrap_or_else(|| { - if fps_value > 0.0 { - json!(frame_obj.get("frame").and_then(|f| f.as_i64()).unwrap_or(frame_idx as i64) as f64 / fps_value) - } else { - json!(0) - } - }); - let mut output_faces: Vec = Vec::new(); - let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default(); - for (face_idx, face) in faces.iter().enumerate() { - let person_id = face.get("person_id").and_then(|p| p.as_str()); - if let Some(person_id) = person_id { - output_faces.push(json!({ - "face_id": format!("face_{}_{}", frame_idx, face_idx), - "cluster_id": person_id, - "trace_id": face.get("trace_id").cloned().unwrap_or(Value::Null), - "confidence": face.get("confidence").cloned().unwrap_or(json!(0.9)), - })); - } - } - if !output_faces.is_empty() { - output_frames.push(json!({ - "frame": frame_obj.get("frame").cloned().unwrap_or(json!(frame_idx)), - "timestamp": timestamp, - "faces": output_faces, - })); - } - } - - let mut output_data = json!({ - "status": "has_faces", - "file_uuid": uuid, - "clusters": clusters, - "frames": output_frames, - }); - - // Auto-bind speakers from asrx.json. - let asrx_path = output_dir.join(format!("{}.asrx.json", uuid)); - let speaker_mapping = auto_bind_speakers(&output_frames, &asrx_path); - if !speaker_mapping.is_null() { - output_data["speaker_person_mapping"] = speaker_mapping; - } - - let rounded = round_json(output_data); - let text = serde_json::to_string_pretty(&rounded).map_err(|e| e.to_string()); - match text { - Ok(t) => { - std::fs::write(&args.output_path, t).expect("Failed to write output"); - eprintln!("Saved clustered data to {}", args.output_path.display()); - } - Err(e) => { - eprintln!("Failed to serialize output: {}", e); - std::process::exit(1); - } - } -} - -/// Compute speaker -> Person_N mapping by vote (Python auto_bind_speakers). -fn auto_bind_speakers(output_frames: &[Value], asrx_path: &std::path::Path) -> Value { - if !asrx_path.exists() { - eprintln!("Missing data for speaker binding."); - return Value::Null; - } - - let asrx_data: Value = match std::fs::read_to_string(asrx_path) { - Ok(s) => match serde_json::from_str(&s) { - Ok(v) => v, - Err(e) => { - eprintln!(" Failed to load ASRX: {}", e); - return Value::Null; - } - }, - Err(_) => return Value::Null, - }; - - eprintln!("Auto-binding Speakers to Persons..."); - - let mut face_spans: Vec<(f64, String)> = Vec::new(); - for frame_obj in output_frames { - if let Some(ts) = frame_obj.get("timestamp").and_then(|t| t.as_f64()) { - if let Some(faces) = frame_obj.get("faces").and_then(|f| f.as_array()) { - for face in faces { - if let Some(person_id) = face.get("cluster_id").and_then(|p| p.as_str()) { - face_spans.push((ts, person_id.to_string())); - } - } - } - } - } - - let mut speaker_person_counts: BTreeMap> = BTreeMap::new(); - let segments = asrx_data.get("segments").and_then(|s| s.as_array()).cloned().unwrap_or_default(); - for seg in &segments { - let start = seg.get("start_time").or_else(|| seg.get("start")).and_then(|x| x.as_f64()); - let end = seg.get("end_time").or_else(|| seg.get("end")).and_then(|x| x.as_f64()); - let speaker = seg.get("speaker_id").and_then(|x| x.as_str()); - if speaker.is_none() || start.is_none() || end.is_none() { - continue; - } - let speaker = speaker.unwrap(); - let start = start.unwrap(); - let end = end.unwrap(); - let candidates: Vec<&(f64, String)> = face_spans - .iter() - .filter(|(ts, _)| start <= *ts && *ts <= end) - .collect(); - if !candidates.is_empty() { - let mut person_counts: BTreeMap = BTreeMap::new(); - for (_, pid) in candidates.iter() { - *person_counts.entry(pid.clone()).or_insert(0) += 1; - } - let best_person = person_counts - .iter() - .max_by(|a, b| a.1.cmp(b.1)) - .map(|(p, _)| p.clone()); - if let Some(best) = best_person { - let entry = speaker_person_counts.entry(speaker.to_string()).or_default(); - *entry.entry(best).or_insert(0) += 1; - } - } - } - - let mut mapping: BTreeMap = BTreeMap::new(); - for (speaker, persons) in speaker_person_counts.iter() { - if persons.is_empty() { - continue; - } - let best_person = persons.iter().max_by(|a, b| a.1.cmp(b.1)).map(|(p, _)| p); - if let Some(best) = best_person { - mapping.insert(speaker.clone(), best.clone()); - eprintln!(" {} is likely {} ({} votes)", speaker, best, persons[best]); - } - } - - if mapping.is_empty() { - Value::Null - } else { - serde_json::to_value(mapping).unwrap_or(Value::Null) - } -} \ No newline at end of file