6 Commits

Author SHA1 Message Date
Accusys c7521f0e2b fix: face cluster 過濾低品質單幀誤檢(如手/物體)+ 傳遞性同幀約束
Cross-Project Integration / integration (push) Has been cancelled
- 新增單幀品質過濾:若 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 (正確)
2026-11-20 01:43:01 +08:00
Accusys 2f15cb639c fix: face cluster over-merge — merge_small_clusters 遵守同幀約束
Cross-Project Integration / integration (push) Has been cancelled
根因 (bd9ebfc):
- 影片實際 2 人(戴眼鏡男性 16 trace + 年輕女性 5 trace)
- seed-leader clustering 用 0.65 閾值把所有人合成 1-2 群
- apply_cooccurrence_constraints 正確拆出同幀女性 trace([SPLIT])
- 但 merge_small_clusters 用單純 embedding similarity (0.7) 又把拆出的
  女性 trace 合回男性群(女性小脸 90x90 embedding 不準,sim 高達 0.98)
- 結果: frame 3 的男性 t2 和女性 t3 被標同一 Person_1 → over-merge

修復:
- merge_small_clusters 加入 cooccurrence_constraints 參數
- 改為迭代式合併:每輪重新計算 centroid,選最相似且無同幀衝突的群對合併
- 合併前檢查兩群的 trace 是否有 co-occurrence(同幀 bbox 不重疊)衝突,
  有則拒絕合併([KEEP])

驗證: bd9ebfc re-run → frame 3 男性 t2=Person_1, 女性 t3=Person_7,
不同人不再合併;clusters 2→3(過度分割可接受,優於 over-merge)
2026-11-19 23:23:47 +08:00
Accusys 49b02c2d4f fix: scene frame 越界導致 jpg 提取失敗、job 卡 ingestion
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
根因 (090.mp4):
- 影片 total_frames=300 (frame 0~299),但最後 moment 的 end=300 被選為
  scene_004 的 frame_number → 越界 → ffmpeg 提取失敗 → scene_004.jpg 不存在
- extract_scene_frames 跳過失敗的 frame,但 profile.scenes 仍保留 →
  scenes.json 有 5 scene 但只有 4 張 jpg → scene_vlm_done 判定 4≠5 → false
  → job 永遠卡在 ingestion 等待

修復:
1. generate_scene_profile: clamp 所有 frame_number 到 total_frames-1
2. process_scene_vlm: extract 後若 jpg 缺失,按 filename 比對移除對應 scene,
   確保 scenes.json 與磁碟 jpg 一致
驗證: 090.mp4 re-run → scenes.json 4 scene 全 completed, 4 張 jpg,
      ingestion all_ok=true, job completed
2026-11-19 21:53:56 +08:00
Accusys 532a2287c5 fix: Face Trace 完成時同步 videos.processing_status JSON
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
根因: FaceTrace 走獨立 pipeline(非 processor pool),當 face_traced.json
已存在而 skip spawn、或實際執行完成時,只更新 processor_results 表,
沒有更新 videos.processing_status 的 FACE_TRACE progress。

結果: 前端讀 processing_status 顯示 FACE_TRACE=running/0,
但 FACE_CLUSTER(走 processor pool)已 completed → 看起來違反依賴規則。

修復: 兩個完成路徑都補上 update_processor_progress('face_trace', completed):
- skip 路徑(already done)
- 實際執行成功路徑
手動修正 090.mp4 的 processing_status(先前 jsonb_set 路徑錯誤清空,
已重建完整 progress)。
2026-11-19 21:44:02 +08:00
Accusys 36fc4d0360 fix: pHash dedup 後刪除孤立 scene jpg(jpg 數 = scenes 數)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
根因: extract_scene_frames 先寫出全部 jpg,pHash dedup 後只調整
profile.scenes,但被移除 scene 的 jpg 沒刪除 → 磁碟 5 張 jpg
但 scenes.json 只有 4 個 scene(如 1c6f40 scene_003.jpg 孤立)。

修復: dedup 時對被移除的 scene 呼叫 std::fs::remove_file 刪除 jpg。
已清理 1c6f40 的孤立 scene_003.jpg。
2026-11-19 19:18:17 +08:00
Accusys 797f4c61f6 fix: 運鏡分析對往復/多角度運鏡誤判 Static 的問題
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
根因: 相位相關正確偵測到每段位移 (022.mp4 pans=[-1,-17,16,20,-1],
tilts=[0,7,-16,30,-47]),但取『有符號中位數』後正負抵消 → pan=-1 tilt=0
→ 誤判 Static,只選 1 張。

修復:
- level 判斷改用『所有 pair 位移絕對值的最大值』(fold max),
  不再用有符號中位數;多角度/往復運鏡不會再被抵消
- confidence<0.15 的 pair 過濾(原本 tanh(peak/second) 全 0.77 不可信)
- 閾值下調: high >10px (256 圖), zoom>0.15, rot>0.05
- pan_px/tilt_px 回傳最大位移的 signed 值(真實振幅)

驗證: 022.mp4 (10s 單鏡頭大角度 tilt)
  修復前: Static/None → 1 張
  修復後: Tilt/High (tilt=-47px) → 4 張 (Start/Mid/Mid/End)
2026-11-19 18:44:46 +08:00
5 changed files with 248 additions and 905 deletions
+63 -22
View File
@@ -67,47 +67,88 @@ pub async fn analyze_camera_motion(
return Ok(CameraMotion::static_motion());
}
let pan = median(&mut pans);
let tilt = median(&mut tilts);
let zoom = median(&mut zooms);
let rot = median(&mut rots);
let confidence = median(&mut peaks).clamp(0.0, 1.0);
// Filter out unreliable pairs (low phase-correlation peak). A large-angle
// camera move breaks phase correlation on some pairs; those produce bogus
// displacements that would poison the median. Keep only confident pairs.
let mut good: Vec<(f64, f64, f64, f64, f64)> = Vec::new(); // (pan,tilt,zoom,rot,conf)
for i in 0..pans.len() {
if peaks[i] >= 0.15 {
good.push((pans[i], tilts[i], zooms[i], rots[i], peaks[i]));
}
}
debug!(
"[CAM-MOTION] pairs={} confident={} pans={:?} tilts={:?} zooms={:?} peaks={:?}",
pans.len(), good.len(), pans, tilts, zooms, peaks
);
if good.is_empty() {
// All phase-correlation pairs unreliable — this itself indicates a
// large, fast camera move (or heavy scene change). Fall back to raw
// median but flag low confidence so caller can still add samples.
let pan = median(&mut pans);
let tilt = median(&mut tilts);
let zoom = median(&mut zooms);
let rot = median(&mut rots);
return Ok(CameraMotion {
motion_type: if pan.abs() > tilt.abs() { MotionType::Pan } else { MotionType::Tilt },
level: if pan.abs() > 8.0 || tilt.abs() > 8.0 { MotionLevel::High } else { MotionLevel::Low },
pan_px: pan, tilt_px: tilt, zoom_factor: zoom, rotation_rad: rot,
confidence: 0.2,
});
}
let mut pans_g: Vec<f64> = good.iter().map(|x| x.0).collect();
let mut tilts_g: Vec<f64> = good.iter().map(|x| x.1).collect();
let mut zooms_g: Vec<f64> = good.iter().map(|x| x.2).collect();
let mut rots_g: Vec<f64> = good.iter().map(|x| x.3).collect();
let pan = median(&mut pans_g);
let tilt = median(&mut tilts_g);
let zoom = median(&mut zooms_g);
let rot = median(&mut rots_g);
let confidence = median(&mut good.iter().map(|x| x.4).collect()).clamp(0.0, 1.0);
// Classify: displacement relative to frame width, zoom/rotation thresholds.
let pan_abs = pan.abs();
let tilt_abs = tilt.abs();
let zoom_delta = (zoom - 1.0).abs();
let rot_abs = rot.abs();
// Classify using the LARGEST per-pair displacement magnitude, not the
// median of signed values. A pan/tilt that reverses direction (or a
// multi-angle sweep) cancels out in a signed median but is still real
// camera motion — we must not classify it as Static.
let pan_abs = good.iter().map(|x| x.0.abs()).fold(0.0f64, f64::max);
let tilt_abs = good.iter().map(|x| x.1.abs()).fold(0.0f64, f64::max);
let zoom_delta = good.iter().map(|x| (x.2 - 1.0).abs()).fold(0.0f64, f64::max);
let rot_abs = good.iter().map(|x| x.3.abs()).fold(0.0f64, f64::max);
let max_shift = pan_abs.max(tilt_abs);
let (level, motion_type) = if max_shift < FFT_SIZE as f64 * 0.05
&& zoom_delta < 0.05
&& rot_abs < 0.02
let (level, motion_type) = if max_shift < 3.0
&& zoom_delta < 0.03
&& rot_abs < 0.01
{
(MotionLevel::None, MotionType::Static)
} else {
let high = max_shift > FFT_SIZE as f64 * 0.20
|| zoom_delta > 0.30
|| rot_abs > 0.08;
// 256px frame: >10px shift is already a clearly visible camera move.
let high = max_shift > 10.0 || zoom_delta > 0.15 || rot_abs > 0.05;
let level = if high { MotionLevel::High } else { MotionLevel::Low };
// Dominant type by normalized magnitude.
let mut candidates = vec![
(pan_abs / (FFT_SIZE as f64 * 0.2), MotionType::Pan),
(tilt_abs / (FFT_SIZE as f64 * 0.2), MotionType::Tilt),
(zoom_delta / 0.3, MotionType::Zoom),
(rot_abs / 0.08, MotionType::Rotation),
(pan_abs / 12.0, MotionType::Pan),
(tilt_abs / 12.0, MotionType::Tilt),
(zoom_delta / 0.15, MotionType::Zoom),
(rot_abs / 0.05, MotionType::Rotation),
];
candidates.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
let motion_type = candidates.first().map(|x| x.1).unwrap_or(MotionType::Pan);
(level, motion_type)
};
// Report the largest observed displacement per axis (signed from the pair
// with largest magnitude) so callers see the real camera-move amplitude.
let pan_signed = good.iter().max_by(|a, b| a.0.abs().partial_cmp(&b.0.abs()).unwrap())
.map(|x| x.0).unwrap_or(pan);
let tilt_signed = good.iter().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
.map(|x| x.1).unwrap_or(tilt);
Ok(CameraMotion {
motion_type,
level,
pan_px: pan,
tilt_px: tilt,
pan_px: pan_signed,
tilt_px: tilt_signed,
zoom_factor: zoom,
rotation_rad: rot,
confidence,
+9 -1
View File
@@ -376,10 +376,18 @@ impl SceneVlmProcessor {
all_frames.extend(frames);
}
// Fix indices
// Fix indices and clamp frame numbers to the valid range.
// The last interval's end can equal total_frames (exclusive bound);
// sampling it would pick frame == total_frames, which is out of range
// and makes ffmpeg extraction fail → missing jpg → permanent failed scene.
let max_frame = total_frames.saturating_sub(1) as u32;
for (i, frame) in all_frames.iter_mut().enumerate() {
frame.index = i;
frame.filename = format!("scene_{:03}.jpg", i);
if frame.frame_number > max_frame {
frame.frame_number = max_frame;
frame.timestamp_sec = frame.frame_number as f64 / fps.max(0.001);
}
}
profile.scenes = all_frames;
+78 -1
View File
@@ -4124,7 +4124,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
if trace_complete {
info!("✅ Face trace already done for {}, skipping spawn", uuid);
// Keep videos.processing_status JSON in sync: mark FACE_TRACE
// completed with full frame count. Without this, the UI shows
// FACE_TRACE stuck at running/0 while FACE_CLUSTER is completed
// (which looks like a broken dependency).
let tf = self
.db
.get_video_by_uuid(uuid)
.await
.ok()
.flatten()
.map(|v| v.total_frames as u64)
.unwrap_or(0);
if let Err(e) = self
.db
.update_processor_progress(uuid, "face_trace", tf, tf, "completed")
.await
{
warn!("[FACE_TRACE] failed to mark progress completed for {}: {}", uuid, e);
}
// ✅ Ensure processor_results record exists for dependency checks
let mut success = false;
for attempt in 1..=3 {
@@ -4420,6 +4440,27 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
&pp,
)
.await;
// Sync videos.processing_status JSON (UI source of truth)
let tf = db_clone
.get_video_by_uuid(&uuid_clone)
.await
.ok()
.flatten()
.map(|v| v.total_frames as u64)
.unwrap_or(0);
if let Err(e) = db_clone
.update_processor_progress(
&uuid_clone,
"face_trace",
tf,
tf,
"completed",
)
.await
{
warn!("[FACE_TRACE] failed to mark progress completed for {}: {}", uuid_clone, e);
}
}
Err(e) => {
error!(
@@ -5695,6 +5736,37 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
SceneVlmProcessor::extract_scene_frames(&video_path, output_dir, uuid, &profile.scenes)
.await?;
// Guard: extract_scene_frames skips frames it cannot decode, which can
// desync extracted[] from profile.scenes[]. Drop any scene whose jpg is
// missing so scenes.json always matches the on-disk frames.
if extracted.len() != profile.scenes.len() {
// Match by filename so a failed extraction in the middle cannot
// shift the alignment of subsequent scenes.
let existing: std::collections::HashSet<String> = extracted
.iter()
.filter(|p| p.exists())
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
.collect();
let old_scenes = std::mem::take(&mut profile.scenes);
let mut aligned = Vec::new();
let mut paths = Vec::new();
for scene in old_scenes {
if existing.contains(&scene.filename) {
if let Some(p) = extracted.iter().find(|p| {
p.file_name().map(|n| n.to_string_lossy() == scene.filename).unwrap_or(false)
}) {
paths.push(p.clone());
}
aligned.push(scene);
} else {
warn!("[Scene VLM] dropping scene with missing jpg: {}", scene.filename);
}
}
profile.scenes = aligned;
profile.total_scenes = profile.scenes.len();
extracted = paths;
}
// Second-pass dedup: pHash + time-gap over the extracted jpgs.
// Drop a scene when it is visually near-identical to a previously kept
// one within the time-gap window. Resume-carried scenes are kept as-is.
@@ -5728,6 +5800,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
if keep_set.contains(&i) {
new_scenes.push(scene);
new_extracted.push(path);
} else {
// Remove the now-orphaned scene jpg so disk matches scenes.json.
if let Err(e) = std::fs::remove_file(&path) {
debug!("[DEDUP] failed to remove orphan scene jpg {:?}: {}", path, e);
}
}
}
profile.scenes = new_scenes;
+98 -77
View File
@@ -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::<f64>() / 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::<f64>() / 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<f64> = Vec::new();
for p in trace_points {
@@ -578,94 +593,99 @@ fn apply_cooccurrence_constraints(
fn merge_small_clusters(
trace_to_person: std::collections::BTreeMap<i64, i64>,
trace_embeddings: &std::collections::BTreeMap<i64, Vec<f64>>,
trace_similarities: &std::collections::BTreeMap<i64, f64>,
min_large_cluster_size: usize,
_trace_similarities: &std::collections::BTreeMap<i64, f64>,
_min_large_cluster_size: usize,
merge_similarity_threshold: f64,
cooccurrence: &std::collections::HashSet<(i64, i64)>,
) -> std::collections::BTreeMap<i64, i64> {
let mut trace_to_person = trace_to_person;
// Count traces per person
let mut person_trace_count: std::collections::HashMap<i64, usize> = std::collections::HashMap::new();
for (_, pid) in &trace_to_person {
*person_trace_count.entry(*pid).or_insert(0) += 1;
}
// Identify large clusters (seeds) and small clusters
let mut large_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
let mut small_clusters: std::collections::HashSet<i64> = std::collections::HashSet::new();
for (pid, count) in &person_trace_count {
if *count >= min_large_cluster_size {
large_clusters.insert(*pid);
} else {
small_clusters.insert(*pid);
}
}
if small_clusters.is_empty() || large_clusters.is_empty() {
return trace_to_person;
}
eprintln!("[MERGE] Large clusters: {:?}, Small clusters: {:?}", large_clusters, small_clusters);
// Compute mean embedding for each person
let mut person_embeddings: std::collections::HashMap<i64, Vec<f64>> = std::collections::HashMap::new();
for (tid, pid) in &trace_to_person {
if let Some(emb) = trace_embeddings.get(tid) {
person_embeddings.entry(*pid).or_insert_with(|| vec![0.0; emb.len()]);
let pe = person_embeddings.get_mut(pid).unwrap();
for (i, &v) in emb.iter().enumerate() {
pe[i] += v;
// 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<i64, std::collections::HashSet<i64>> = std::collections::BTreeMap::new();
for &pid in trace_to_person.values().collect::<std::collections::HashSet<_>>().iter() {
let mut conflicting: std::collections::HashSet<i64> = std::collections::HashSet::new();
let member_traces: Vec<i64> = 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);
}
// Normalize
for (pid, traces) in &person_trace_count {
if let Some(pe) = person_embeddings.get_mut(pid) {
let count = *traces as f64;
for v in pe.iter_mut() {
*v /= count;
}
let merge_sim = merge_similarity_threshold;
loop {
let mut cur_traces: std::collections::BTreeMap<i64, Vec<i64>> = std::collections::BTreeMap::new();
for (tid, pid) in &trace_to_person {
cur_traces.entry(*pid).or_default().push(*tid);
}
}
// Merge each small cluster into most similar large cluster
for small_pid in small_clusters {
let mut best_sim = -1.0;
let mut best_large_pid: Option<i64> = None;
for large_pid in &large_clusters {
if let (Some(emb_small), Some(emb_large)) = (person_embeddings.get(&small_pid), person_embeddings.get(large_pid)) {
let sim = cosine_similarity(emb_small, emb_large);
if sim > best_sim {
best_sim = sim;
best_large_pid = Some(*large_pid);
}
}
}
if let Some(target_pid) = best_large_pid {
if best_sim >= merge_similarity_threshold {
eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})",
small_pid, person_trace_count.get(&small_pid).unwrap_or(&0), target_pid, best_sim);
// Reassign all traces from small to large
for (tid, pid) in trace_to_person.iter_mut() {
if *pid == small_pid {
*pid = target_pid;
let mut centroids: std::collections::BTreeMap<i64, Vec<f64>> = std::collections::BTreeMap::new();
for (pid, tids) in &cur_traces {
let mut mean: Option<Vec<f64>> = None;
for tid in tids {
if let Some(e) = trace_embeddings.get(tid) {
if let Some(m) = mean.as_mut() {
for (i, &v) in e.iter().enumerate() { m[i] += v; }
} else {
mean = Some(vec![0.0; e.len()]);
for (i, &v) in e.iter().enumerate() { mean.as_mut().unwrap()[i] += v; }
}
}
} else {
eprintln!(" [SKIP] Person_{} not similar enough to any large cluster (best sim={:.3})", small_pid, best_sim);
}
if let Some(mut m) = mean {
let n = tids.len() as f64;
for v in m.iter_mut() { *v /= n; }
centroids.insert(*pid, m);
}
}
let pids: Vec<i64> = cur_traces.keys().copied().collect();
let mut best: Option<(f64, i64, i64)> = None;
for (i, &pa) in pids.iter().enumerate() {
for &pb in pids.iter().skip(i + 1) {
let (ea, eb) = match (centroids.get(&pa), centroids.get(&pb)) {
(Some(a), Some(b)) => (a, b),
_ => continue,
};
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)))
})
});
// 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));
}
}
}
match best {
Some((sim, from, to)) => {
eprintln!(" [MERGE] Person_{} ({} traces) -> Person_{} (sim={:.3})",
from, cur_traces[&from].len(), to, sim);
for (tid, pid) in trace_to_person.iter_mut() {
if *pid == from { *pid = to; }
}
}
None => break,
}
}
// Re-index person IDs
let unique_pids: std::collections::BTreeSet<i64> = trace_to_person.values().copied().collect();
let pid_map: std::collections::HashMap<i64, i64> = unique_pids.into_iter().enumerate().map(|(new, old)| (old, new as i64)).collect();
trace_to_person = trace_to_person.into_iter().map(|(tid, pid)| (tid, *pid_map.get(&pid).unwrap())).collect();
trace_to_person
}
@@ -844,7 +864,8 @@ fn main() {
&trace_embeddings,
&trace_similarities,
5, // min traces to be considered a "large" cluster
0.7 // similarity threshold for merging
0.7, // similarity threshold for merging
&cooccurrence_constraints, // never merge same-frame (different-person) traces
);
let n_persons: usize = trace_to_person.values().collect::<std::collections::HashSet<_>>().len();
@@ -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<String>,
#[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<f64>,
}
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<FacePoint> {
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<FacePoint> = Vec::new();
let mut offset: Option<Value> = 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::<Vec<f64>>()
})
.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::<f64>().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<trace_id, Vec<f64>>).
fn cluster_by_trace(
points: &[FacePoint],
min_faces_per_trace: usize,
confidence_threshold: f64,
) -> BTreeMap<i64, Vec<f64>> {
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<i64, Vec<&FacePoint>> = 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<i64, Vec<f64>> = 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<f64> = 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<i64, Vec<f64>>,
threshold: f64,
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
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<f64>, Vec<i64>)> = Vec::new(); // (centroid, member_trace_ids)
let mut trace_similarities: BTreeMap<i64, f64> = 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<usize> = None;
for (idx, person) in persons.iter().enumerate() {
let sim = cosine_similarity(&centroid, &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<Vec<f64>> = 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<i64, i64> = 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<i64, Vec<f64>>,
threshold: f64,
) -> (BTreeMap<i64, i64>, BTreeMap<i64, f64>) {
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<Vec<usize>> = (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<i64, i64> = 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<i64, f64> = 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::<Vec<_>>()));
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::<std::collections::HashSet<_>>().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::<Value>(&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<String, u64> = BTreeMap::new();
let mut person_best_face: BTreeMap<String, Value> = 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<i64, Vec<f64>> = 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<Value> = Vec::new();
for (person_id, count) in sorted_persons {
let person_label: Option<i64> = person_id
.split('_')
.nth(1)
.and_then(|s| s.parse::<i64>().ok());
let mut similarity_info: Option<Value> = 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::<f64>() / 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<Value> = 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<Value> = 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<String, BTreeMap<String, i64>> = 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<String, i64> = 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<String, String> = 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)
}
}