12 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
Accusys a6a78cca8b feat: 三層階梯式 frame 取樣 + 純 Rust 運鏡分析 + pHash 去重
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
Phase correlation 運鏡分析 (camera_motion.rs):
- ffmpeg pipe 抽幀 → 灰階 256x256 → rustfft 相位相關估 pan/tilt
- 徑向功率譜估 zoom、極座標相位相關估 rotation
- 中位數去噪 + none/low/high 分級
- samples_for_level: none=1, low=2, high=4

pHash 去重 (frame_dedup.rs):
- 64-bit pHash (DCT 低頻) + hamming<=8 + 時間間隔去重
- scene extract 後對 jpg 去重: 387 → 317 (移除 70)

三層取樣 (scene_vlm.rs process_interval):
- L0 moment=10s 保底 (SCENE_VLM_MOMENT_SEC)
- L1 每個 cut 保底 1 張 (不設上限)
- L2 運鏡依 level 增採, 運動路徑均勻取樣 + blurdetect

資料結構:
- SceneFrame.camera_motion + selection_reason CameraMotion*/CutBaseline
- VLM truncated (finish_reason=length) salvage 部分 JSON summary

其他:
- face dedup 改用 per-library output dir
- max_tokens 2048→4096
- config 5 項 (moment_sec/camera_motion_enabled/phash_hamming/time_gap/k)
- Cargo.toml +image/ndarray/rustfft

驗證: 17e230cc force re-run → Selected 387 frames, CAM-MOTION 分析執行,
pHash dedup 387→317, RESUME force=true carried over 0
2026-11-19 18:24:41 +08:00
Accusys 772d287fcd fix: Scene VLM resume 跳過已完成 scene + max_tokens 提高
- process_scene_vlm: 載入既有 scenes.json,按 filename 比對,
  carried over 已 completed 的 VLM 欄位並在迴圈中跳過
- force re-run (rerun_rebuild flag) 時才全部重做
- progress 計算改為 processed + skipped(準確顯示 %)
- 驗證: 17e230cc RESUME carried over 111 completed,只處理 8 failed
- max_tokens 2048→4096(8 個 failed scene 因 VLM 回應截斷 fail)
2026-11-19 17:47:34 +08:00
Accusys d0dae475f9 fix: 確保每個 file_uuid 只有一個 monitor_job
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
檢查結果:目前 DB 無重複 job,但 uuid 索引非 UNIQUE,且兩個建立路徑
(create_monitor_job 的 check-then-insert、REPAIR 的 INSERT WHERE NOT EXISTS)
都有 race,並發時可能產生重複 job。

三層防護:
- DB: CREATE UNIQUE INDEX uq_monitor_jobs_uuid ON monitor_jobs(uuid)
- create_monitor_job INSERT 改 ON CONFLICT (uuid) DO UPDATE
- REPAIR INSERT 加 ON CONFLICT (uuid) DO NOTHING

驗證:並發 5 個 process 請求 → 仍只有 1 個 job
2026-11-19 16:49:13 +08:00
Accusys 9b1618f85b fix: force re-run 可靠性 — 備份/恢復 + orphan job + stuck detector 不再毀資料
備份/恢復:
- force re-run 前備份 output 到 .backup/{uuid}/{timestamp}/,label 存 Redis
- processor 失敗時自動還原備份
- 成功後清除 backup label,避免日後誤還原舊資料

worker 穩定性:
- Worker 啟動時重置 orphan running jobs / processor_results 為 pending
  (原先只處理 error_message='Worker restarted',orphan 會永遠佔住
   backpressure 名額,讓 force re-run 的 pending job 排不到)
- detect_and_rescan_stuck_jobs 改為直接重置 job 為 pending,不再用
  force register command(unregister 會刪除 videos 記錄 + 所有 output,
  對 force re-run 是毀滅性資料遺失)
2026-11-19 16:44:39 +08:00
Accusys 8f90e98215 fix: FS VLM Summary 寫入 trace_profile.json + 新增 {uuid}.fs_vlm.json 彙總檔
- label 欄位改 Option<String>:修正 rust_store_traced_faces 寫出 null 導致
  FaceTraceProfile::load() 反序列化失敗、VLM summary 無法寫回 JSON 的問題
- VLM summary 寫入從『僅新產生時』改為『任何情況都同步 JSON』:
  DB 已有但 JSON 缺漏時重跑也會補寫
- 新增 write_vlm_summary_index():VLM 完成後產生 {uuid}.fs_vlm.json,
  含 22 筆 trace_id/vlm_summary/key_face/bbox/best_frame
- processor-json?processor=vlm_summary 優先讀 fs_vlm.json,DB 彙總為 fallback
- backfill 現有 22 筆 trace_profile.json + 產生 fs_vlm.json
2026-11-19 16:30:30 +08:00
Accusys 9758d91e0a fix: 恢復 FS VLM Summary 手動觸發 API
- 重新啟用 /api/v1/file/:file_uuid/vlm-summary 路由(之前被註解)
- 取消 trigger_vlm_summary handler 的註解
- output_dir 改用 per-library
- 規則: FS VLM Summary 只手動觸發,不在 pipeline_flows 自動執行
- 驗證: API 回傳 success, 22 traces pending
2026-11-19 15:54:36 +08:00
17 changed files with 2303 additions and 1106 deletions
Generated
+639 -1
View File
@@ -71,6 +71,24 @@ dependencies = [
"memchr",
]
[[package]]
name = "aligned"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
dependencies = [
"as-slice",
]
[[package]]
name = "aligned-vec"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
dependencies = [
"equator",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -166,6 +184,17 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d"
[[package]]
name = "arg_enum_proc_macro"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "argon2"
version = "0.5.3"
@@ -178,6 +207,21 @@ dependencies = [
"password-hash",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "as-slice"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "async-compression"
version = "0.4.42"
@@ -266,6 +310,49 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "av-scenechange"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
dependencies = [
"aligned",
"anyhow",
"arg_enum_proc_macro",
"arrayvec",
"log",
"num-rational",
"num-traits",
"pastey",
"rayon",
"thiserror 2.0.18",
"v_frame",
"y4m",
]
[[package]]
name = "av1-grain"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
dependencies = [
"anyhow",
"arrayvec",
"log",
"nom 8.0.0",
"num-rational",
"v_frame",
]
[[package]]
name = "avif-serialize"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38"
dependencies = [
"arrayvec",
]
[[package]]
name = "axum"
version = "0.7.9"
@@ -375,6 +462,12 @@ dependencies = [
"virtue",
]
[[package]]
name = "bit_field"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -390,6 +483,15 @@ dependencies = [
"serde_core",
]
[[package]]
name = "bitstream-io"
version = "4.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"
dependencies = [
"no_std_io2",
]
[[package]]
name = "bitvec"
version = "1.0.1"
@@ -444,18 +546,36 @@ dependencies = [
"uuid",
]
[[package]]
name = "built"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.11.1"
@@ -593,6 +713,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -794,6 +920,12 @@ dependencies = [
"winapi",
]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -1125,6 +1257,26 @@ dependencies = [
"log",
]
[[package]]
name = "equator"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
dependencies = [
"equator-macro",
]
[[package]]
name = "equator-macro"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -1179,12 +1331,43 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exr"
version = "1.74.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
dependencies = [
"bit_field",
"half",
"lebe",
"miniz_oxide",
"multiversion",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "fastrand"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]
name = "fax"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "ferrous-opencc"
version = "0.3.1"
@@ -1476,6 +1659,16 @@ dependencies = [
"polyval",
]
[[package]]
name = "gif"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "h2"
version = "0.4.13"
@@ -1495,6 +1688,17 @@ dependencies = [
"tracing",
]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -1907,6 +2111,46 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"exr",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"qoi",
"ravif",
"rayon",
"rgb",
"tiff",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "imgref"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f"
[[package]]
name = "include-flate"
version = "0.3.3"
@@ -2013,6 +2257,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "interpolate_name"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "ipconfig"
version = "0.3.4"
@@ -2191,6 +2446,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "lebe"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
[[package]]
name = "libc"
version = "0.2.186"
@@ -2221,6 +2482,16 @@ dependencies = [
"rle-decode-fast",
]
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
dependencies = [
"arbitrary",
"cc",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -2289,6 +2560,15 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "loop9"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"
dependencies = [
"imgref",
]
[[package]]
name = "lru"
version = "0.12.5"
@@ -2344,6 +2624,26 @@ version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
[[package]]
name = "matrixmultiply"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "maybe-rayon"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
dependencies = [
"cfg-if",
"rayon",
]
[[package]]
name = "md-5"
version = "0.10.6"
@@ -2473,6 +2773,7 @@ dependencies = [
"flate2",
"futures-util",
"hex",
"image",
"jieba-rs",
"jsonwebtoken",
"libc",
@@ -2480,6 +2781,7 @@ dependencies = [
"md5",
"moka",
"mongodb",
"ndarray",
"notify",
"once_cell",
"pgvector",
@@ -2488,6 +2790,7 @@ dependencies = [
"redis",
"regex",
"reqwest",
"rustfft",
"sdl2",
"serde",
"serde_json",
@@ -2558,6 +2861,16 @@ dependencies = [
"webpki-roots 0.25.4",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "multer"
version = "3.1.0"
@@ -2575,6 +2888,28 @@ dependencies = [
"version_check",
]
[[package]]
name = "multiversion"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
dependencies = [
"multiversion-macros",
"target-features",
]
[[package]]
name = "multiversion-macros"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
"target-features",
]
[[package]]
name = "native-tls"
version = "0.2.18"
@@ -2592,6 +2927,27 @@ dependencies = [
"tempfile",
]
[[package]]
name = "ndarray"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
dependencies = [
"matrixmultiply",
"num-complex",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nix"
version = "0.29.0"
@@ -2624,6 +2980,21 @@ dependencies = [
"minimal-lexical",
]
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "noop_proc_macro"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]]
name = "notify"
version = "6.1.1"
@@ -2687,12 +3058,32 @@ dependencies = [
"zeroize",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-conv"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "num-integer"
version = "0.1.46"
@@ -2713,6 +3104,17 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2859,6 +3261,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
[[package]]
name = "pbkdf2"
version = "0.11.0"
@@ -3014,6 +3422,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags 2.11.1",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide",
]
[[package]]
name = "polyval"
version = "0.6.2"
@@ -3075,6 +3496,15 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "primal-check"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
dependencies = [
"num-integer",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -3139,6 +3569,25 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "profiling"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
dependencies = [
"profiling-procmacros",
]
[[package]]
name = "profiling-procmacros"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb"
dependencies = [
"quote",
"syn 2.0.117",
]
[[package]]
name = "prost"
version = "0.13.5"
@@ -3171,6 +3620,12 @@ dependencies = [
"prost",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qdrant-client"
version = "1.17.0"
@@ -3193,6 +3648,21 @@ dependencies = [
"tonic",
]
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quinn"
version = "0.11.9"
@@ -3355,6 +3825,62 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "rav1e"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
dependencies = [
"aligned-vec",
"arbitrary",
"arg_enum_proc_macro",
"arrayvec",
"av-scenechange",
"av1-grain",
"bitstream-io",
"built",
"cfg-if",
"interpolate_name",
"itertools 0.14.0",
"libc",
"libfuzzer-sys",
"log",
"maybe-rayon",
"new_debug_unreachable",
"noop_proc_macro",
"num-derive",
"num-traits",
"paste",
"profiling",
"rand 0.9.4",
"rand_chacha 0.9.0",
"simd_helpers",
"thiserror 2.0.18",
"v_frame",
"wasm-bindgen",
]
[[package]]
name = "ravif"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45"
dependencies = [
"avif-serialize",
"imgref",
"loop9",
"quick-error",
"rav1e",
"rayon",
"rgb",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.12.0"
@@ -3515,6 +4041,12 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
[[package]]
name = "rgb"
version = "0.8.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
[[package]]
name = "ring"
version = "0.17.14"
@@ -3623,6 +4155,20 @@ dependencies = [
"semver 0.9.0",
]
[[package]]
name = "rustfft"
version = "6.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
dependencies = [
"num-complex",
"num-integer",
"num-traits",
"primal-check",
"strength_reduce",
"transpose",
]
[[package]]
name = "rustix"
version = "0.38.44"
@@ -4059,6 +4605,15 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "simd_helpers"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
dependencies = [
"quote",
]
[[package]]
name = "simple_asn1"
version = "0.6.4"
@@ -4147,7 +4702,7 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bba3a93db0cc4f7bdece8bb09e77e2e785c20bfebf79eb8340ed80708048790"
dependencies = [
"nom",
"nom 7.1.3",
"unicode_categories",
]
@@ -4481,6 +5036,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strength_reduce"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
[[package]]
name = "stringprep"
version = "0.1.5"
@@ -4639,6 +5200,12 @@ dependencies = [
"xattr",
]
[[package]]
name = "target-features"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -4701,6 +5268,20 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tiff"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
dependencies = [
"fax",
"flate2",
"half",
"quick-error",
"weezl",
"zune-jpeg",
]
[[package]]
name = "time"
version = "0.3.47"
@@ -5092,6 +5673,16 @@ dependencies = [
"tracing-log",
]
[[package]]
name = "transpose"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
dependencies = [
"num-integer",
"strength_reduce",
]
[[package]]
name = "trust-dns-proto"
version = "0.21.2"
@@ -5336,6 +5927,17 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "v_frame"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
dependencies = [
"aligned-vec",
"num-traits",
"wasm-bindgen",
]
[[package]]
name = "valuable"
version = "0.1.1"
@@ -5552,6 +6154,12 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "whoami"
version = "1.6.1"
@@ -6059,6 +6667,12 @@ version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"
[[package]]
name = "y4m"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
[[package]]
name = "yoke"
version = "0.8.2"
@@ -6211,3 +6825,27 @@ dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "zune-core"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]
+5
View File
@@ -18,6 +18,11 @@ once_cell = "1.19"
libc = "0.2"
dotenv = "0.15"
# Image processing (camera motion + pHash dedup)
image = "0.25"
ndarray = "0.16"
rustfft = "6"
# CLI
clap = { version = "4", features = ["derive"] }
+103 -16
View File
@@ -424,21 +424,58 @@ async fn trigger_processing(
}
tracing::info!("[TRIGGER] Cleaned processor_results for job {}", job_id);
// If force=true, delete output files to force re-processing
// If force=true, backup + delete output files to force re-processing
if req.force {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let per_lib_dir = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_dir = if std::path::Path::new(&per_lib_dir).is_dir() {
per_lib_dir.clone()
} else {
global_dir.clone()
};
// Build the list of files that will be deleted
let target_files: Vec<String> = if processors_to_run.is_empty() {
["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"]
.iter().map(|ext| format!("{}.{}.json", file_uuid, ext)).collect()
} else {
processors_to_run.iter().filter_map(|p| {
let ext = match p.as_str() {
"asr" => "asr", "asr_asrx" | "asrx" => "asrx",
"ocr" => "ocr", "cut" => "cut", "face" => "face",
"face_cluster" => "face_cluster", "face_trace" => "face_traced",
"scene_vlm" | "scene" => "scenes", "pose" => "pose",
"hand" => "hand", "appearance" => "appearance", "tkg" => "tkg",
_ => return None,
};
Some(format!("{}.{}.json", file_uuid, ext))
}).collect()
};
// BACKUP before deletion (per-library + global dirs)
let backup_label = crate::core::rerun_backup::backup_files(&output_dir, &file_uuid, &target_files)
.or_else(|| crate::core::rerun_backup::backup_files(&global_dir, &file_uuid, &target_files));
if let Some(label) = &backup_label {
// Store backup label in Redis so worker failure handler can restore
let key = format!("{}rerun_backup:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
let _: Result<(), _> = redis::cmd("SET").arg(&key).arg(label)
.arg("EX").arg(86400).query_async(&mut conn).await;
tracing::info!("[TRIGGER] Backup created for {} label={}", file_uuid, label);
}
let deleted_count = if processors_to_run.is_empty() {
// Full re-scan: delete all output files
delete_output_files_for_uuid(&file_uuid, &output_dir)
+ delete_output_files_for_uuid(&file_uuid, &global_dir)
} else {
// Single-processor re-run: delete only that processor's output
delete_processor_output_files(&file_uuid, &processors_to_run, &output_dir)
+ delete_processor_output_files(&file_uuid, &processors_to_run, &global_dir)
};
tracing::info!(
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?})",
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?}, backup={:?})",
deleted_count,
file_uuid,
processors_to_run
processors_to_run,
backup_label
);
// Re-running ASR/OCR/Scene VLM must also rebuild the search index:
@@ -1042,6 +1079,61 @@ async fn get_processor_json(
Json(serde_json::json!({"error": "Missing processor"})),
))?;
// FS VLM Summary: prefer the consolidated {uuid}.fs_vlm.json
// (written when VLM generation completes); fall back to DB aggregation
// for files processed before the index was introduced.
if processor == "vlm_summary" {
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, state.db.pool()).await;
let global = crate::core::config::OUTPUT_DIR.as_str();
for dir in [per_lib.trim_end_matches('/'), global.trim_end_matches('/')] {
let path = std::path::Path::new(dir).join(format!("{}.fs_vlm.json", file_uuid));
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
return Ok(Json(json));
}
}
}
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let rows: Vec<(i32, Option<String>, Option<String>)> = match sqlx::query_as(&format!(
"SELECT trace_id, vlm_description, status FROM {tp_table} \
WHERE file_uuid = $1 ORDER BY trace_id"
))
.bind(file_uuid)
.fetch_all(state.db.pool())
.await
{
Ok(r) => r,
Err(e) => {
tracing::error!("Failed to query vlm_summary for {}: {}", file_uuid, e);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("DB error: {}", e)})),
));
}
};
let traces: Vec<serde_json::Value> = rows
.into_iter()
.map(|(trace_id, vlm_summary, status)| {
serde_json::json!({
"trace_id": trace_id,
"vlm_summary": vlm_summary,
"status": status,
})
})
.collect();
let total = traces.len();
let done = traces.iter().filter(|t| {
t.get("vlm_summary").and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false)
}).count();
return Ok(Json(serde_json::json!({
"file_uuid": file_uuid,
"total": total,
"done": done,
"traces": traces,
})));
}
// Map processor name to output file extension.
let ext = match processor.as_str() {
"asrx" => "asrx",
@@ -1220,9 +1312,6 @@ async fn verify_file_handler(
Json(report)
}
/// [DISABLED] FS VLM Summary removed from pipeline (2026-09-22)
/// Scene VLM (moment chunk VLM) remains active
/*
/// Manually trigger VLM summary generation for an existing file.
/// Non-blocking: returns immediately, VLM runs in background.
async fn trigger_vlm_summary(
@@ -1230,7 +1319,7 @@ async fn trigger_vlm_summary(
Path(file_uuid): Path<String>,
) -> Json<serde_json::Value> {
let db = state.db.clone();
let output_dir = crate::core::config::OUTPUT_DIR.clone();
let output_dir = crate::core::config::get_output_dir_for_file(&file_uuid, db.pool()).await;
// Check if file has face traces
let tp_table = crate::core::db::schema::table_name("trace_profiles");
@@ -1291,7 +1380,6 @@ async fn trigger_vlm_summary(
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
@@ -1323,9 +1411,8 @@ pub fn processing_routes() -> Router<AppState> {
get(get_processor_json),
)
.route("/api/v1/file/:file_uuid/verify", get(verify_file_handler))
// [DISABLED] FS VLM Summary API removed (2026-09-22)
// .route(
// "/api/v1/file/:file_uuid/vlm-summary",
// post(trigger_vlm_summary),
// )
.route(
"/api/v1/file/:file_uuid/vlm-summary",
post(trigger_vlm_summary),
)
}
+48
View File
@@ -212,6 +212,54 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
)
}
// ── Frame 三層取樣 + 運鏡分析 configs ───────────────────────────
/// moment 長度(秒),moment 內保底 1 張。預設 10。
pub static SCENE_VLM_MOMENT_SEC: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_VLM_MOMENT_SEC")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10)
});
/// 是否啟用運鏡分析(相位相關)。預設 true。
pub static CAMERA_MOTION_ENABLED: Lazy<bool> = Lazy::new(|| {
env::var("MOMENTRY_CAMERA_MOTION_ENABLED")
.map(|v| v == "true" || v == "1")
.unwrap_or(true)
});
/// pHash 去重漢明距離閾值。預設 8。
pub static PHASH_HAMMING_THRESHOLD: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_PHASH_HAMMING_THRESHOLD")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(8)
});
/// scene frame 去重的時間間隔(幀)。預設約 2 秒 @30fps = 60 幀。
pub static SCENE_TIME_GAP_FRAMES: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_SCENE_TIME_GAP_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(60)
});
/// face trace 去重的時間間隔(幀)。預設約 1 秒 @30fps = 30 幀。
pub static TRACE_TIME_GAP_FRAMES: Lazy<u32> = Lazy::new(|| {
env::var("MOMENTRY_TRACE_TIME_GAP_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(30)
});
/// 每個 cut 抽取用於運鏡分析的幀數。預設 6。
pub static CAMERA_MOTION_K: Lazy<usize> = Lazy::new(|| {
env::var("MOMENTRY_CAMERA_MOTION_K")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(6)
});
// ─────────────────────────────────────────────────────────────
// JSON-backed configs (paths, concurrency, feature flags)
// These read from admin_config.json with ENV fallback
+4
View File
@@ -2395,6 +2395,10 @@ impl PostgresDb {
r#"
INSERT INTO {} (uuid, video_path, status, video_id, processors, face_settings)
VALUES ($1, $2, 'pending', $3, {}::text[], $4::jsonb)
ON CONFLICT (uuid) DO UPDATE SET
status = 'pending', video_path = EXCLUDED.video_path,
video_id = EXCLUDED.video_id, processors = EXCLUDED.processors,
face_settings = EXCLUDED.face_settings, updated_at = NOW()
RETURNING id, uuid, video_path, status, current_processor, progress_total, progress_current, error_count, last_error, started_at::TEXT, updated_at::TEXT, created_at::TEXT, processors, completed_processors, failed_processors, video_id, face_settings::text
"#,
jobs_table, processors_array
+73 -2
View File
@@ -529,7 +529,8 @@ pub struct FaceTraceProfile {
pub version: String,
pub file_uuid: String,
pub trace_id: i64,
pub label: String,
#[serde(default)]
pub label: Option<String>,
pub frame_count: i64,
pub start_frame: i64,
pub end_frame: i64,
@@ -615,7 +616,7 @@ impl FaceTraceProfile {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
trace_id,
label: label.to_string(),
label: Some(label.to_string()),
frame_count,
start_frame,
end_frame,
@@ -868,6 +869,72 @@ pub struct SceneFrame {
pub vlm_tags: Vec<VlmTagValue>,
pub embedding_status: EmbeddingStatus,
/// Camera-motion analysis for this scene (pan/tilt/zoom/rotation).
/// Absent in legacy scenes.json → treated as static.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub camera_motion: Option<CameraMotion>,
}
/// Camera motion analysis result for a scene / cut segment.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct CameraMotion {
/// Dominant motion type.
pub motion_type: MotionType,
/// Severity level — drives how many extra samples to take.
pub level: MotionLevel,
/// Horizontal displacement (pixels, sign = direction).
pub pan_px: f64,
/// Vertical displacement (pixels, sign = direction).
pub tilt_px: f64,
/// Scale change factor (1.0 = no zoom).
pub zoom_factor: f64,
/// Rotation estimate (radians).
pub rotation_rad: f64,
/// Confidence 0.0-1.0 (based on phase-correlation peak consistency).
pub confidence: f64,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MotionType {
Static,
Pan,
Tilt,
Zoom,
Rotation,
Dolly,
Handheld,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MotionLevel {
None,
Low,
High,
}
impl Default for MotionLevel {
fn default() -> Self {
MotionLevel::None
}
}
impl CameraMotion {
/// A static / no-motion result (used as fallback and for legacy data).
pub fn static_motion() -> Self {
CameraMotion {
motion_type: MotionType::Static,
level: MotionLevel::None,
pan_px: 0.0,
tilt_px: 0.0,
zoom_factor: 1.0,
rotation_rad: 0.0,
confidence: 1.0,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -885,6 +952,10 @@ pub enum SelectionReason {
PostCutBestBlur,
SceneStart,
Default,
CameraMotionStart,
CameraMotionMid,
CameraMotionEnd,
CutBaseline,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+1
View File
@@ -45,3 +45,4 @@ pub mod vlm;
pub mod json_debug;
pub mod json_standardize;
pub mod rerun_backup;
+401
View File
@@ -0,0 +1,401 @@
//! Camera-motion analysis via pure-Rust phase correlation.
//!
//! Given a video segment, extract K evenly-spaced grayscale frames (via ffmpeg
//! pipe, never written to disk), then estimate global camera motion between
//! consecutive frames:
//! - pan / tilt : phase-correlation peak position
//! - zoom : radial power-spectrum scale change
//! - rotation : phase correlation in polar coordinates
//!
//! A median over all consecutive pairs removes object-motion outliers. The
//! result is classified into MotionLevel::None / Low / High so callers can
//! decide how many extra samples to take inside a cut.
use anyhow::{Context, Result};
use image::GrayImage;
use ndarray::{Array2, Axis};
use rustfft::{num_complex::Complex, FftPlanner};
use std::process::{Command, Stdio};
use tracing::{debug, warn};
use crate::core::file_profile::{CameraMotion, MotionLevel, MotionType};
/// Number of FFT size (power of two) used for phase correlation.
const FFT_SIZE: usize = 256;
/// Number of frames to extract per segment.
const DEFAULT_K: usize = 6;
/// Analyze camera motion in a video segment [start_frame, end_frame].
/// `k` = number of evenly-spaced frames to sample (min 2).
pub async fn analyze_camera_motion(
video_path: &str,
start_frame: u32,
end_frame: u32,
fps: f64,
k: usize,
) -> Result<CameraMotion> {
let k = k.max(2);
if end_frame <= start_frame || fps <= 0.0 {
return Ok(CameraMotion::static_motion());
}
let frames = extract_frames(video_path, start_frame, end_frame, fps, k).await?;
if frames.len() < 2 {
return Ok(CameraMotion::static_motion());
}
let mut pans = Vec::new();
let mut tilts = Vec::new();
let mut zooms = Vec::new();
let mut rots = Vec::new();
let mut peaks = Vec::new();
for pair in frames.windows(2) {
match phase_correlate(&pair[0], &pair[1]) {
Ok((dx, dy, peak)) => {
pans.push(dx);
tilts.push(dy);
zooms.push(estimate_zoom(&pair[0], &pair[1]));
rots.push(estimate_rotation(&pair[0], &pair[1]));
peaks.push(peak);
}
Err(e) => debug!("[CAM-MOTION] phase correlate failed: {}", e),
}
}
if pans.is_empty() {
return Ok(CameraMotion::static_motion());
}
// 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 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 < 3.0
&& zoom_delta < 0.03
&& rot_abs < 0.01
{
(MotionLevel::None, MotionType::Static)
} else {
// 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 / 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_signed,
tilt_px: tilt_signed,
zoom_factor: zoom,
rotation_rad: rot,
confidence,
})
}
/// Map motion level to number of samples to take inside a cut.
pub fn samples_for_level(level: MotionLevel) -> usize {
match level {
MotionLevel::None => 1,
MotionLevel::Low => 2,
MotionLevel::High => 4,
}
}
/// Extract `k` evenly-spaced grayscale frames from the segment into memory.
async fn extract_frames(
video_path: &str,
start_frame: u32,
end_frame: u32,
fps: f64,
k: usize,
) -> Result<Vec<GrayImage>> {
let mut frames = Vec::with_capacity(k);
for i in 0..k {
let frame = start_frame + ((end_frame - start_frame) as usize * i / (k - 1)) as u32;
let time_sec = frame as f64 / fps;
let child = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-ss",
&format!("{:.3}", time_sec),
"-i",
video_path,
"-frames:v",
"1",
"-vf",
&format!("scale={}:{}", FFT_SIZE, FFT_SIZE),
"-f",
"image2pipe",
"-vcodec",
"png",
"-",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.context("ffmpeg spawn failed for camera-motion frame extraction")?;
let output = child
.wait_with_output()
.context("ffmpeg wait failed for camera-motion frame extraction")?;
if !output.status.success() || output.stdout.is_empty() {
warn!("[CAM-MOTION] ffmpeg produced no frame at t={:.2}", time_sec);
continue;
}
let img = image::load_from_memory_with_format(&output.stdout, image::ImageFormat::Png)
.context("failed to decode extracted png")?
.to_luma8();
frames.push(img);
}
Ok(frames)
}
/// Phase correlation: returns (dx, dy, peak_confidence) in FFT pixels.
/// dx/dy are wrapped into [-N/2, N/2].
fn phase_correlate(a: &GrayImage, b: &GrayImage) -> Result<(f64, f64, f64)> {
let n = FFT_SIZE;
let fa = to_fft_array(a);
let fb = to_fft_array(b);
let mut planner = FftPlanner::<f64>::new();
let fft = planner.plan_fft_forward(n * n);
let ifft = planner.plan_fft_inverse(n * n);
let mut aa = flatten(&fa);
let mut bb = flatten(&fb);
fft.process(&mut aa);
fft.process(&mut bb);
// Cross-power spectrum: F(a) * conj(F(b)) / |F(a)F(b)|
let mut cross = Vec::with_capacity(n * n);
for (x, y) in aa.iter().zip(bb.iter()) {
let denom = (x.norm_sqr() * y.norm_sqr()).sqrt();
if denom < 1e-9 {
cross.push(Complex::new(0.0, 0.0));
} else {
cross.push(x * y.conj() / denom);
}
}
ifft.process(&mut cross);
// Find peak (skip DC).
let mut peak_idx = 0usize;
let mut peak_val = -1.0f64;
let mut second = 0.0f64;
for (i, c) in cross.iter().enumerate() {
let mag = c.norm();
if i != 0 && mag > peak_val {
second = peak_val.max(second);
peak_val = mag;
peak_idx = i;
} else if mag > second {
second = mag;
}
}
if peak_val <= 0.0 {
return Ok((0.0, 0.0, 0.0));
}
let py = peak_idx / n;
let px = peak_idx % n;
let dx = wrap(px as f64, n);
let dy = wrap(py as f64, n);
// Confidence: ratio of peak to second-highest (higher = more reliable).
let confidence = (peak_val / (second + 1e-6)).tanh();
Ok((dx, dy, confidence))
}
/// Estimate zoom by comparing radial power-spectrum bandwidth of two frames.
/// A zoomed-in frame has energy concentrated at lower radial frequencies.
fn estimate_zoom(a: &GrayImage, b: &GrayImage) -> f64 {
let ea = spectral_energy(a);
let eb = spectral_energy(b);
if ea <= 0.0 || eb <= 0.0 {
return 1.0;
}
// Ratio of high-frequency energy indicates scale change.
(eb / ea).sqrt().clamp(0.5, 2.0)
}
/// Estimate rotation via phase correlation in polar coordinates (coarse).
/// Uses FFT angular power spectrum; returns radians in [-pi, pi].
fn estimate_rotation(a: &GrayImage, b: &GrayImage) -> f64 {
// Similar to zoom: compare column-sum profiles of the power spectrum.
// A pure rotation shifts the angular profile cyclically.
let pa = angular_profile(a);
let pb = angular_profile(b);
let n = pa.len();
let mut best_shift = 0usize;
let mut best_score = f64::NEG_INFINITY;
for shift in 0..n {
let mut score = 0.0;
for i in 0..n {
score += pa[i] * pb[(i + shift) % n];
}
if score > best_score {
best_score = score;
best_shift = shift;
}
}
let shift = wrap(best_shift as f64, n);
shift * std::f64::consts::PI * 2.0 / n as f64
}
fn to_fft_array(img: &GrayImage) -> Array2<f64> {
let (w, h) = img.dimensions();
let mut arr = Array2::<f64>::zeros((h as usize, w as usize));
for (x, y, px) in img.enumerate_pixels() {
// Hann window reduces edge artifacts in phase correlation.
let wx = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * x as f64 / w as f64).cos();
let wy = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * y as f64 / h as f64).cos();
arr[[y as usize, x as usize]] = px[0] as f64 * wx * wy;
}
arr
}
fn flatten(arr: &Array2<f64>) -> Vec<Complex<f64>> {
arr.iter().map(|v| Complex::new(*v, 0.0)).collect()
}
fn power_spectrum(img: &GrayImage) -> Vec<f64> {
let n = FFT_SIZE;
let arr = to_fft_array(img);
let mut data = flatten(&arr);
let mut planner = FftPlanner::<f64>::new();
let fft = planner.plan_fft_forward(n * n);
fft.process(&mut data);
data.iter().map(|c| c.norm_sqr()).collect()
}
fn spectral_energy(img: &GrayImage) -> f64 {
let spec = power_spectrum(img);
let n = FFT_SIZE;
let center = (n / 2, n / 2);
let mut hi = 0.0;
let mut total = 0.0;
for (i, v) in spec.iter().enumerate() {
let y = i / n;
let x = i % n;
let r = ((x as i32 - center.0 as i32).pow(2) + (y as i32 - center.1 as i32).pow(2)) as f64;
total += v;
if r > (n as f64 / 4.0).powi(2) {
hi += v;
}
}
if total > 0.0 { hi / total } else { 0.0 }
}
fn angular_profile(img: &GrayImage) -> Vec<f64> {
let n = FFT_SIZE;
let spec = power_spectrum(img);
let bins = 64;
let mut profile = vec![0.0; bins];
let center = (n / 2, n / 2);
for (i, v) in spec.iter().enumerate() {
let y = i / n;
let x = i % n;
let dx = x as f64 - center.0 as f64;
let dy = y as f64 - center.1 as f64;
if dx == 0.0 && dy == 0.0 {
continue;
}
let angle = dy.atan2(dx);
let bin = (((angle + std::f64::consts::PI) / (2.0 * std::f64::consts::PI) * bins as f64)
as usize)
% bins;
profile[bin] += v;
}
profile
}
fn median(v: &mut Vec<f64>) -> f64 {
if v.is_empty() {
return 0.0;
}
v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let mid = v.len() / 2;
if v.len() % 2 == 0 {
(v[mid - 1] + v[mid]) / 2.0
} else {
v[mid]
}
}
fn wrap(v: f64, n: usize) -> f64 {
let n = n as f64;
let mut x = v % n;
if x > n / 2.0 {
x -= n;
}
if x < -n / 2.0 {
x += n;
}
x
}
+156
View File
@@ -0,0 +1,156 @@
//! Frame deduplication — perceptual hash (pHash) + time-gap based filtering.
//!
//! Used in two places:
//! - Scene frames: after 3-level sampling, drop near-duplicate frames.
//! - Face-trace key_frames: drop near-duplicate best_frames across a file
//! (never merge different trace_id — that would break identity tracking).
use anyhow::{Context, Result};
use image::{imageops::FilterType, GrayImage};
use std::process::{Command, Stdio};
use tracing::{debug, warn};
/// Compute a 64-bit perceptual hash (pHash) of a JPEG/PNG at `path`.
/// Resize to 32x32 grayscale, DCT, take the low 8x8 AC/DC coefficients.
pub fn phash_from_file(path: &std::path::Path) -> Result<u64> {
let img = image::open(path)
.with_context(|| format!("failed to open image {}", path.display()))?
.to_luma8();
Ok(phash(&img))
}
/// Compute 64-bit pHash from an in-memory grayscale image.
pub fn phash(img: &GrayImage) -> u64 {
const N: usize = 32;
const LOW: usize = 8;
let small = image::imageops::resize(img, N as u32, N as u32, FilterType::Triangle);
// Separable DCT-II.
let mut dct = vec![vec![0.0f64; N]; N];
let c = |u: usize, x: usize| -> f64 {
if u == 0 {
(1.0 / (N as f64).sqrt()) / std::f64::consts::SQRT_2
} else {
(2.0 * std::f64::consts::PI * u as f64 * x as f64 / (2.0 * N as f64)).cos()
}
};
// Row pass.
let mut tmp = vec![vec![0.0f64; N]; N];
for y in 0..N {
for u in 0..N {
let mut s = 0.0;
for x in 0..N {
s += small.get_pixel(x as u32, y as u32)[0] as f64 * c(u, x);
}
tmp[y][u] = s;
}
}
// Column pass.
for v in 0..N {
for u in 0..N {
let mut s = 0.0;
for y in 0..N {
s += tmp[y][u] * c(v, y);
}
dct[v][u] = s;
}
}
// Use the low 8x8 block (including DC). Median of coefficients as threshold.
let mut vals = Vec::with_capacity(LOW * LOW);
for v in 0..LOW {
for u in 0..LOW {
vals.push(dct[v][u]);
}
}
let mut sorted = vals.clone();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let median = sorted[sorted.len() / 2];
let mut hash = 0u64;
for (i, v) in vals.iter().enumerate() {
if *v > median {
hash |= 1u64 << i;
}
}
hash
}
/// Hamming distance between two pHashes.
pub fn hamming(a: u64, b: u64) -> u32 {
(a ^ b).count_ones()
}
/// Extract a single frame via ffmpeg into memory and return its pHash.
pub async fn phash_from_video_frame(
video_path: &str,
frame: u32,
fps: f64,
) -> Result<u64> {
let time_sec = frame as f64 / fps;
let child = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-v",
"quiet",
"-ss",
&format!("{:.3}", time_sec),
"-i",
video_path,
"-frames:v",
"1",
"-vf",
"scale=64:64",
"-f",
"image2pipe",
"-vcodec",
"png",
"-",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.context("ffmpeg spawn failed for phash extraction")?;
let out = child.wait_with_output().context("ffmpeg wait failed")?;
if out.stdout.is_empty() {
anyhow::bail!("ffmpeg produced no frame for phash at {:.2}s", time_sec);
}
let img = image::load_from_memory_with_format(&out.stdout, image::ImageFormat::Png)
.context("failed to decode png for phash")?
.to_luma8();
Ok(phash(&img))
}
/// A generic item that can be time-ordered and hash-deduplicated.
#[derive(Debug, Clone)]
pub struct DedupItem {
pub key: String,
pub frame: u32,
pub hash: u64,
}
/// Deduplicate items by (time gap AND pHash similarity).
/// Keeps the first item of each near-duplicate group (caller should order by
/// quality before calling if they want to keep the best instead).
/// Returns the kept items and the list of dropped keys.
pub fn dedup_items(items: Vec<DedupItem>, hamming_threshold: u32, time_gap_frames: u32) -> (Vec<DedupItem>, Vec<String>) {
let mut kept: Vec<DedupItem> = Vec::new();
let mut dropped: Vec<String> = Vec::new();
for item in items {
let dup = kept.iter().any(|k| {
let close_time = item.frame.abs_diff(k.frame) <= time_gap_frames;
close_time && hamming(item.hash, k.hash) <= hamming_threshold
});
if dup {
dropped.push(item.key.clone());
debug!("[DEDUP] dropped {} (frame {}, near {})", item.key, item.frame, kept.last().map(|x| x.frame).unwrap_or(0));
} else {
kept.push(item);
}
}
if !dropped.is_empty() {
warn!("[DEDUP] dropped {} near-duplicate frames", dropped.len());
}
(kept, dropped)
}
+2
View File
@@ -18,6 +18,8 @@ pub mod ocr;
pub mod pose;
pub mod scene_classification;
pub mod scene_vlm;
pub mod camera_motion;
pub mod frame_dedup;
pub mod tkg;
pub mod vlm_summary;
+223 -157
View File
@@ -1,13 +1,15 @@
use anyhow::{Context, Result};
use futures_util::future::join_all;
use tracing::{debug, info};
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,
CameraMotion, EmbeddingStatus, MotionLevel, SceneConfig, SceneFrame, SceneInfo, SceneProfile,
SceneStatus, SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
};
use crate::core::processor::camera_motion::{analyze_camera_motion, samples_for_level};
pub struct SceneVlmProcessor {
samples_per_interval: usize,
@@ -138,6 +140,11 @@ impl SceneVlmProcessor {
cuts
}
/// Three-tier frame sampling inside one moment (default 10s):
/// L0: moment baseline (blur-best of the whole segment)
/// L1: every distinct cut gets at least one frame (no upper bound)
/// L2: camera motion (pan/tilt/zoom/rotation) adds extra samples:
/// none -> 1, low -> 2, high -> 4, evenly along the motion path.
pub async fn process_interval(
video_path: &str,
interval_start: f64,
@@ -147,165 +154,169 @@ impl SceneVlmProcessor {
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 moment_start_f = (interval_start * fps).round() as u32;
let moment_end_f = ((interval_start + interval_sec) * fps).round() as u32;
let cuts = Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
let blur_scores =
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
// Build frame ranges: [moment_start, cut0), [cut0, cut1), ... [cutN, moment_end)
let mut cut_frames: Vec<u32> = cuts
.iter()
.filter_map(|c| c.get("start_time").and_then(|t| t.as_f64()))
.map(|t| (t * fps).round() as u32)
.filter(|f| *f > moment_start_f && *f < moment_end_f)
.collect();
cut_frames.sort_unstable();
cut_frames.dedup();
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,
});
}
let mut ranges: Vec<(u32, u32, bool)> = Vec::new(); // (start, end, has_cut)
let mut prev = moment_start_f;
for &cf in cut_frames.iter() {
if cf > prev {
ranges.push((prev, cf, false));
}
ranges.push((cf, cf, true)); // cut boundary marker
prev = cf;
}
if moment_end_f > prev {
ranges.push((prev, moment_end_f, false));
}
// If no cuts, single range.
if ranges.is_empty() {
ranges.push((moment_start_f, moment_end_f, false));
}
for (i, frame) in selected_frames.iter_mut().enumerate() {
let motion_enabled = *crate::core::config::CAMERA_MOTION_ENABLED;
let k = *crate::core::config::CAMERA_MOTION_K;
let mut selected: Vec<SceneFrame> = Vec::new();
for (range_idx, (rs, re, is_cut)) in ranges.iter().enumerate() {
if *is_cut {
// Cut boundary: one frame at the cut itself (L1 baseline).
let frame = *rs;
if let Some(sf) = Self::make_frame(
selected.len(),
frame,
fps,
SelectionReason::CutBaseline,
None,
None,
true,
1,
) {
selected.push(sf);
}
continue;
}
let seg_start = *rs;
let seg_end = (*re).max(seg_start + 1);
// L2: camera-motion analysis on this sub-segment.
let motion: Option<CameraMotion> = if motion_enabled && seg_end > seg_start {
match analyze_camera_motion(video_path, seg_start, seg_end, fps, k).await {
Ok(m) if m.level != MotionLevel::None => Some(m),
Ok(m) => Some(m),
Err(e) => {
debug!("[CAM-MOTION] analysis failed for {}-{}: {}", seg_start, seg_end, e);
None
}
}
} else {
None
};
let count = motion
.as_ref()
.map(|m| samples_for_level(m.level))
.unwrap_or(1);
// Sample `count` frames evenly inside [seg_start, seg_end), each
// chosen as the blur-best within its own sub-window.
let window = (seg_end - seg_start) / count as u32;
for i in 0..count {
let ws = seg_start + window * i as u32;
let we = if i + 1 == count { seg_end } else { (ws + window).min(seg_end) };
// Sparse sample inside the sub-window (max 6 candidates) to avoid
// one ffmpeg call per frame on high-fps video.
let span = we.max(ws + 1) - ws;
let step = (span / 6).max(1);
let candidates: Vec<u32> = (ws..we.max(ws + 1)).step_by(step as usize).collect();
let blur = Self::calculate_blur_parallel(video_path, &candidates, fps, max_workers).await?;
let chosen = Self::select_best_frame(&blur)
.map(|(f, b)| (f, Some(b)))
.or_else(|| candidates.first().map(|f| (*f, None)));
if let Some((frame, blur_score)) = chosen {
let reason = if count == 1 {
SelectionReason::BestBlur
} else if i == 0 {
SelectionReason::CameraMotionStart
} else if i + 1 == count {
SelectionReason::CameraMotionEnd
} else {
SelectionReason::CameraMotionMid
};
if let Some(sf) = Self::make_frame(
selected.len(),
frame,
fps,
reason,
blur_score,
motion.clone(),
false,
cut_frames.len() as u32,
) {
selected.push(sf);
}
}
}
let _ = range_idx;
}
// Time-gap dedup: drop frames too close in time AND visually near-identical
// is done later on extracted jpg (pHash). Here we only drop exact same frame.
selected.dedup_by(|a, b| a.frame_number == b.frame_number);
for (i, frame) in selected.iter_mut().enumerate() {
frame.index = i;
}
Ok(selected_frames)
Ok(selected)
}
fn make_frame(
index: usize,
frame: u32,
fps: f64,
reason: SelectionReason,
blur: Option<f64>,
camera_motion: Option<CameraMotion>,
has_cut: bool,
cut_count: u32,
) -> Option<SceneFrame> {
Some(SceneFrame {
index,
filename: format!("scene_{:03}.jpg", index),
timestamp_sec: frame as f64 / fps,
frame_number: frame,
selection_reason: reason,
quality_score: blur,
quality_source: if blur.is_some() { Some("ffmpeg_blurdetect".to_string()) } else { None },
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut,
cut_count,
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,
camera_motion,
})
}
pub async fn generate_scene_profile(
@@ -321,6 +332,10 @@ impl SceneVlmProcessor {
height: u32,
total_frames: u32,
) -> Result<SceneProfile> {
// moment length is configurable (default 10s); SCENE_VLM_INTERVAL is
// the legacy alias — prefer MOMENTRY_SCENE_VLM_MOMENT_SEC when set.
let moment_sec = *crate::core::config::SCENE_VLM_MOMENT_SEC;
let interval_sec = if moment_sec > 0 { moment_sec } else { interval_sec };
let config = SceneConfig {
interval_sec,
use_cuts: true,
@@ -361,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;
@@ -600,6 +623,37 @@ Rules:
Some(&content[start..=end])
}
/// Pull a `"summary": "..."` string out of a possibly-truncated JSON blob.
fn salvage_summary(content: &str) -> Option<String> {
let key = content.find("\"summary\"")?;
let colon = content[key..].find(':')? + key;
let mut rest = &content[colon + 1..];
rest = rest.trim_start();
if !rest.starts_with('"') {
return None;
}
rest = &rest[1..];
let mut out = String::new();
let mut esc = false;
for ch in rest.chars() {
if esc {
out.push(ch);
esc = false;
continue;
}
if ch == '\\' {
esc = true;
continue;
}
if ch == '"' {
break;
}
out.push(ch);
}
let out = out.trim().to_string();
if out.len() >= 10 { Some(out) } else { None }
}
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
let Some(arr) = value.and_then(|v| v.as_array()) else {
return Vec::new();
@@ -721,7 +775,7 @@ Rules:
}
]
}],
"max_tokens": 2048,
"max_tokens": 4096,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false},
"reasoning": false,
@@ -756,8 +810,9 @@ Rules:
.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 truncated = choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length");
if truncated {
debug!("[Scene VLM] response truncated (finish_reason=length) — attempting to salvage partial JSON");
}
let message = choice.get("message").context("Invalid VLM API response structure")?;
@@ -827,6 +882,17 @@ Rules:
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
}
// Salvage path for truncated responses: pull the "summary" string even
// when the surrounding JSON object was cut off mid-generation.
if let Some(desc) = Self::salvage_summary(&content) {
let objects = Self::extract_objects_from_text(&content);
let tags: Vec<VlmTagValue> = Self::extract_tags_from_text(&content)
.into_iter()
.map(VlmTagValue::String)
.collect();
return Ok((desc, objects, tags));
}
tracing::warn!(
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
);
+98 -13
View File
@@ -151,9 +151,77 @@ pub async fn generate_vlm_summaries(
file_uuid, result.summarized, result.total, result.embedded, result.errors
);
// Write a single consolidated {uuid}.fs_vlm.json next to the other
// processor outputs, so the UI can open it just like face.json / ocr.json.
write_vlm_summary_index(db, file_uuid, output_dir).await;
result
}
/// Build `{output_dir}/{file_uuid}.fs_vlm.json` from DB + per-trace
/// trace_profile.json (for key_face / bbox / best_frame context).
pub async fn write_vlm_summary_index(db: &PostgresDb, file_uuid: &str, output_dir: &str) {
let tp_table = table_name("trace_profiles");
let rows: Vec<(i32, Option<String>, Option<String>)> = match sqlx::query_as(&format!(
"SELECT trace_id, vlm_description, status FROM {tp_table} \
WHERE file_uuid = $1 ORDER BY trace_id"
))
.bind(file_uuid)
.fetch_all(db.pool())
.await
{
Ok(r) => r,
Err(e) => {
warn!("[VLM] Failed to build summary index for {}: {}", file_uuid, e);
return;
}
};
let mut traces = Vec::new();
for (tid, desc, status) in rows {
let mut item = serde_json::json!({
"trace_id": tid,
"vlm_summary": desc,
"status": status,
});
if let Some(p) = crate::core::file_profile::FaceTraceProfile::load(
output_dir,
file_uuid,
tid as i64,
) {
let prefix = format!("trace_{}", tid);
item["key_frame"] = serde_json::json!(p.key_frame.as_ref().map(|f| format!("{}/{}", prefix, f)));
item["key_face"] = serde_json::json!(p.key_face.as_ref().map(|f| format!("{}/{}", prefix, f)));
item["best_frame"] = serde_json::json!(p.best_frame);
item["frame_count"] = serde_json::json!(p.frame_count);
item["avg_bbox"] = serde_json::json!(p.avg_bbox);
item["best_bbox"] = serde_json::json!(p.best_bbox);
item["avg_confidence"] = serde_json::json!(p.avg_confidence);
}
traces.push(item);
}
let done = traces
.iter()
.filter(|t| t.get("vlm_summary").and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false))
.count();
let index = serde_json::json!({
"file_uuid": file_uuid,
"generated_at": chrono::Utc::now().to_rfc3339(),
"total": traces.len(),
"done": done,
"traces": traces,
});
let path = std::path::Path::new(output_dir).join(format!("{}.fs_vlm.json", file_uuid));
match serde_json::to_string_pretty(&index) {
Ok(content) => match std::fs::write(&path, content) {
Ok(_) => info!("[VLM] Wrote summary index {} ({} traces)", path.display(), traces.len()),
Err(e) => warn!("[VLM] Failed to write summary index {}: {}", path.display(), e),
},
Err(e) => warn!("[VLM] Failed to serialize summary index: {}", e),
}
}
async fn process_single_trace(
db: &PostgresDb,
file_uuid: &str,
@@ -293,32 +361,49 @@ async fn process_single_trace(
);
}
// Update on-disk trace_profile.json
summary
} else {
existing_desc.unwrap_or_default()
};
// Ensure on-disk trace_profile.json contains the summary. This runs even when
// the summary already existed in DB but was missing from JSON (e.g. an earlier
// save silently failed), so re-running the manual VLM summary always repairs it.
{
let profile_path = crate::core::file_profile::FaceTraceProfile::profile_path(
output_dir,
file_uuid,
trace_id_i64,
);
if profile_path.exists() {
if let Some(mut profile) = crate::core::file_profile::FaceTraceProfile::load(
match crate::core::file_profile::FaceTraceProfile::load(
output_dir,
file_uuid,
trace_id_i64,
) {
profile.vlm_summary = Some(summary.clone());
if let Err(e) = profile.save(output_dir, None, None) {
warn!(
"[VLM] trace {}/{} (tid={}): JSON save failed: {}",
current, total, trace_id, e
);
Some(mut profile) => {
if profile.vlm_summary.as_deref() != Some(summary.as_str()) {
profile.vlm_summary = Some(summary.clone());
if let Err(e) = profile.save(output_dir, None, None) {
warn!(
"[VLM] trace {}/{} (tid={}): JSON save failed: {}",
current, total, trace_id, e
);
} else {
info!(
"[VLM] trace {}/{} (tid={}): JSON vlm_summary written",
current, total, trace_id
);
}
}
}
None => warn!(
"[VLM] trace {}/{} (tid={}): trace_profile.json exists but load() failed — summary NOT written to JSON (DB still OK)",
current, total, trace_id
),
}
}
summary
} else {
existing_desc.unwrap_or_default()
};
}
// Generate embedding and store in Qdrant if needed
if !need_embed {
+149
View File
@@ -0,0 +1,149 @@
//! Rerun backup/rollback — 在 force re-run 前備份既有 output,
//! 若 processor 失敗則自動還原,避免資料遺失。
//!
//! 备份目录: {output_root}/.backup/{uuid}/{timestamp}/
//! 每个 processor 的备份记录: manifest.json { "filename": "path" }
use std::path::{Path, PathBuf};
use tracing::{info, warn};
/// Backup dir root: parent of per-library output dir (i.e. output/.backup/)
fn backup_root(output_dir: &str) -> PathBuf {
let p = Path::new(output_dir);
// output/test -> output ; output/demo -> output
let root = p
.parent()
.filter(|par| par.file_name().and_then(|n| n.to_str()) == Some("output"))
.unwrap_or(p);
root.join(".backup")
}
/// Timestamp label for this rerun session (unix millis)
fn timestamp_label() -> String {
chrono::Utc::now().timestamp_millis().to_string()
}
/// Backup specific files before they are deleted for a force re-run.
/// `output_dir`: per-library output dir (e.g. output/test)
/// `filenames`: list of json filenames to back up (e.g. ["uuid.face.json"])
/// Returns the backup dir path (relative label) for later restore.
pub fn backup_files(
output_dir: &str,
file_uuid: &str,
filenames: &[String],
) -> Option<String> {
let existing: Vec<&String> = filenames
.iter()
.filter(|name| Path::new(output_dir).join(name).exists())
.collect();
if existing.is_empty() {
return None;
}
let label = timestamp_label();
let backup_dir = backup_root(output_dir).join(file_uuid).join(&label);
if let Err(e) = std::fs::create_dir_all(&backup_dir) {
warn!("[RERUN-BACKUP] Failed to create backup dir {:?}: {}", backup_dir, e);
return None;
}
let mut manifest = serde_json::Map::new();
for name in existing {
let src = Path::new(output_dir).join(name);
let dst = backup_dir.join(name);
match std::fs::copy(&src, &dst) {
Ok(_) => {
manifest.insert(name.clone(), serde_json::Value::String(name.to_string()));
info!("[RERUN-BACKUP] Backed up {} -> {:?}", name, dst);
}
Err(e) => warn!("[RERUN-BACKUP] Failed to back up {}: {}", name, e),
}
}
// Write manifest
let manifest_path = backup_dir.join("manifest.json");
if let Ok(content) = serde_json::to_string_pretty(&serde_json::Value::Object(manifest)) {
let _ = std::fs::write(&manifest_path, content);
}
Some(label)
}
/// Restore files from a backup session.
/// `output_dir`: per-library output dir
/// `label`: backup session label returned by backup_files()
/// Returns number of files restored.
pub fn restore_files(output_dir: &str, file_uuid: &str, label: &str) -> usize {
let backup_dir = backup_root(output_dir).join(file_uuid).join(label);
let manifest_path = backup_dir.join("manifest.json");
let manifest: serde_json::Value = match std::fs::read_to_string(&manifest_path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
{
Some(m) => m,
None => {
warn!("[RERUN-RESTORE] No manifest at {:?}", manifest_path);
return 0;
}
};
let mut restored = 0;
if let Some(obj) = manifest.as_object() {
for name in obj.keys() {
let src = backup_dir.join(name);
let dst = Path::new(output_dir).join(name);
if src.exists() {
if let Some(parent) = dst.parent() {
let _ = std::fs::create_dir_all(parent);
}
match std::fs::copy(&src, &dst) {
Ok(_) => {
info!("[RERUN-RESTORE] Restored {} from {:?}", name, backup_dir);
restored += 1;
}
Err(e) => warn!("[RERUN-RESTORE] Failed to restore {}: {}", name, e),
}
}
}
}
restored
}
/// Mark a backup session as successful (cleanup) or keep for rollback.
/// On success we keep the backup for a while (user can manually restore),
/// so this only removes backups older than `keep_days`.
pub fn cleanup_old_backups(output_dir: &str, file_uuid: &str, keep_days: i64) -> usize {
let uuid_dir = backup_root(output_dir).join(file_uuid);
let cutoff = chrono::Utc::now().timestamp_millis() - keep_days * 24 * 60 * 60 * 1000;
let mut removed = 0;
if let Ok(entries) = std::fs::read_dir(&uuid_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if let Ok(ts) = name.parse::<i64>() {
if ts < cutoff {
let _ = std::fs::remove_dir_all(entry.path());
removed += 1;
}
}
}
}
}
removed
}
/// Get the latest backup session label for a file (for manual restore UI)
pub fn latest_backup_label(output_dir: &str, file_uuid: &str) -> Option<String> {
let uuid_dir = backup_root(output_dir).join(file_uuid);
let mut labels: Vec<(i64, String)> = Vec::new();
if let Ok(entries) = std::fs::read_dir(&uuid_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if let Ok(ts) = name.parse::<i64>() {
labels.push((ts, name.to_string()));
}
}
}
}
labels.sort_by_key(|x| x.0);
labels.last().map(|x| x.1.clone())
}
+266 -35
View File
@@ -346,7 +346,8 @@ impl JobWorker {
FROM {v_t} v
WHERE v.status = 'pending'
AND v.file_type IN ('video', 'mp4', 'mov', 'avi', 'mkv')
AND NOT EXISTS (SELECT 1 FROM {mj_t} mj WHERE mj.uuid = v.file_uuid)",
AND NOT EXISTS (SELECT 1 FROM {mj_t} mj WHERE mj.uuid = v.file_uuid)
ON CONFLICT (uuid) DO NOTHING",
mj_t = monitor_jobs_table,
v_t = videos_table
))
@@ -729,6 +730,37 @@ impl JobWorker {
let processor_results_table = schema::table_name("processor_results");
let monitor_jobs_table = schema::table_name("monitor_jobs");
// 0. Worker 剛啟動,不可能有任何 live process。把上次 session 遺留的
// running job 全部退回 pending,連同未完成的 processor_results。
// 否則這些 orphan job 會一直佔住 backpressure 名額,讓新的(例如
// force re-run)pending job 永遠排不到。
let orphan_processors = sqlx::query(&format!(
"UPDATE {processor_results_table} pr
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
FROM {monitor_jobs_table} mj
WHERE pr.job_id = mj.id
AND mj.status = 'running'
AND pr.status IN ('running', 'pending')"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
let orphan_jobs = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
WHERE status = 'running'"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if orphan_jobs > 0 || orphan_processors > 0 {
info!(
"[RECOVER] Worker 啟動:重置 {} 個 orphan jobs / {} 個 orphan processors 為 pending",
orphan_jobs, orphan_processors
);
}
// 1. 重置所有被 worker 重啟中斷的處理器
let recovered = sqlx::query(&format!(
"UPDATE {processor_results_table}
@@ -1044,35 +1076,36 @@ impl JobWorker {
continue;
}
// 與 GUI re-scan 相同:register command(force=true → unregister →
// register → deep scan)。先將 job 標記 paused,避免 command 尚未
// 執行的這一輪又被偵測重複排入。
// 直接重置卡住的 job,不 unregister、不刪 output。
// 原本用 force register command 會觸發 unregister → 清除所有 output,
// 對 force re-run 是資料毀損(備份還在但 job 被刪、output 消失)。
// 這裡只把 job 與未完成的 processor 退回 pending,讓 worker 重新認領,
// 保留所有既有產出。
let reset_pr = sqlx::query(&format!(
"UPDATE {processor_results_table}
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
WHERE job_id = $1 AND status IN ('running', 'pending')"
))
.bind(job_id)
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if let Err(e) = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
WHERE uuid = $1 AND status = 'running'"
))
.bind(&uuid)
.execute(self.db.pool())
.await
{
error!("[STUCK-RESCAN] 無法暫停卡住 job {}: {}", uuid, e);
error!("[STUCK-RESCAN] 無法重置卡住 job {}: {}", uuid, e);
continue;
}
let payload = serde_json::json!({
"force": true,
"deep_scan": true,
"trigger_source": "worker_stuck_auto",
});
match self
.db
.create_command("register", Some(&file_path), None, None, &payload, 1)
.await
{
Ok(cmd) => {
info!(
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已自動 re-scan(command={},第 {} 次)",
uuid, timeout_min, cmd.command_id, rescan_count + 1
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已重置為 pending({} 個 processor,第 {} 次)",
uuid, timeout_min, reset_pr, rescan_count + 1
);
let _: Result<i64, _> = redis::cmd("INCR")
.arg(&counter_key)
@@ -1083,13 +1116,9 @@ impl JobWorker {
.arg(86_400i64)
.query_async(&mut conn)
.await;
// 清除觀察 key(job 將被 unregister 刪除重建)
// 清除觀察 key
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
}
Err(e) => {
error!("[STUCK-RESCAN] 為 {} 建立 re-scan command 失敗: {}", uuid, e);
}
}
}
@@ -4095,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 {
@@ -4391,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!(
@@ -4491,7 +4561,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Before running dedup, verify all 4 required files exist per trace:
// key_frame.jpg, key_face.jpg, trace_profile.json, face_traced.json
if has_face {
let output_dir = OUTPUT_DIR.as_str();
let per_lib = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
let output_dir = if std::path::Path::new(&per_lib).is_dir() {
per_lib.as_str()
} else {
OUTPUT_DIR.as_str()
};
let output_base = output_dir.trim_end_matches('/');
let traced_path = format!("{}/{}.face_traced.json", output_base, uuid);
@@ -5575,7 +5650,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
"[Scene VLM] Generating profile for {} ({}s)",
uuid, duration
);
let profile = processor
let mut profile = processor
.generate_scene_profile(
&video_path,
uuid,
@@ -5593,10 +5668,156 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
let total_scenes = profile.total_scenes;
info!("[Scene VLM] Selected {} frames for {}", total_scenes, uuid);
let extracted =
// ── RESUME ─────────────────────────────────────────────────────────
// generate_scene_profile() rebuilds the profile from scratch, so any
// already-completed VLM descriptions would be lost and re-generated.
// Load the existing scenes.json and carry over completed VLM fields
// (matched by filename). This prevents wasteful re-processing when a
// job is restarted / re-queued after a worker crash or orphan reset.
// A forced re-run signals via the `rerun_rebuild` Redis flag, in which
// case we skip the carry-over and regenerate everything.
let force_scene_vlm = {
let key = format!(
"{}rerun_rebuild:{}",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
uuid
);
let mut flag = false;
if let Ok(r) = crate::core::db::RedisClient::new() {
if let Ok(mut c) = r.get_conn().await {
if let Ok(Some(v)) = redis::cmd("GET")
.arg(&key)
.query_async::<Option<String>>(&mut c)
.await
{
flag = v == "all"
|| v.split(',').any(|p| p == "scene_vlm" || p == "scene");
}
}
}
flag
};
let mut carried_over = 0usize;
if !force_scene_vlm {
if let Ok(old_profile) = SceneVlmProcessor::load_scene_profile(output_dir, uuid) {
// Index old scenes by filename for stable matching across rebuilds.
use std::collections::HashMap;
let old_by_name: HashMap<String, &crate::core::file_profile::SceneFrame> = old_profile
.scenes
.iter()
.map(|s| (s.filename.clone(), s))
.collect();
for scene in profile.scenes.iter_mut() {
if let Some(old) = old_by_name.get(&scene.filename) {
if old.vlm_status == crate::core::file_profile::VlmStatus::Completed
&& old.vlm_description.as_ref().map(|s| !s.trim().is_empty()).unwrap_or(false)
{
scene.vlm_status = crate::core::file_profile::VlmStatus::Completed;
scene.vlm_description = old.vlm_description.clone();
scene.vlm_description_localized = old.vlm_description_localized.clone();
scene.vlm_objects = old.vlm_objects.clone();
scene.vlm_tags = old.vlm_tags.clone();
scene.vlm_scene_type = old.vlm_scene_type.clone();
scene.vlm_location = old.vlm_location.clone();
scene.vlm_attributes = old.vlm_attributes.clone();
scene.embedding_status = old.embedding_status.clone();
carried_over += 1;
}
}
}
}
}
info!(
"[Scene VLM] RESUME: carried over {} completed scenes for {} (force={})",
carried_over, uuid, force_scene_vlm
);
let mut extracted =
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.
{
use crate::core::processor::frame_dedup::{dedup_items, phash_from_file, DedupItem};
let hamming_threshold = *crate::core::config::PHASH_HAMMING_THRESHOLD;
let time_gap = *crate::core::config::SCENE_TIME_GAP_FRAMES;
let mut items = Vec::new();
for (i, path) in extracted.iter().enumerate() {
if i >= profile.scenes.len() {
break;
}
let hash = phash_from_file(path).unwrap_or(0);
items.push(DedupItem {
key: format!("{}", i),
frame: profile.scenes[i].frame_number,
hash,
});
}
let (kept, dropped) = dedup_items(items, hamming_threshold, time_gap);
if !dropped.is_empty() {
let keep_set: std::collections::HashSet<usize> = kept
.iter()
.filter_map(|k| k.key.parse::<usize>().ok())
.collect();
let old_scenes = std::mem::take(&mut profile.scenes);
let old_extracted = extracted.clone();
let mut new_scenes = Vec::new();
let mut new_extracted = Vec::new();
for (i, (scene, path)) in old_scenes.into_iter().zip(old_extracted.into_iter()).enumerate() {
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;
profile.total_scenes = profile.scenes.len();
extracted = new_extracted;
info!(
"[Scene VLM] pHash dedup removed {} near-duplicate scenes ({} remain)",
dropped.len(),
profile.scenes.len()
);
}
}
info!(
"[Scene VLM] Extracted {}/{} frames",
extracted.len(),
@@ -5607,8 +5828,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
db.update_scene_vlm_progress(uuid, extracted.len() as i32, total_scenes as i32)
.await?;
// Generate VLM descriptions for extracted frames
let mut profile = profile;
// Generate VLM descriptions for extracted frames (resume-aware: already
// completed scenes were carried over above and will be skipped).
info!(
"[Scene VLM] Generating VLM descriptions for {} frames",
total_scenes
@@ -5617,7 +5838,16 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Process scenes with progress updates
use crate::core::file_profile::VlmStatus;
let mut processed = 0usize;
let mut skipped = 0usize;
for (idx, scene) in profile.scenes.iter_mut().enumerate() {
// RESUME: skip scenes already completed in a prior run.
if scene.vlm_status == crate::core::file_profile::VlmStatus::Completed
&& scene.vlm_description.as_ref().map(|s| !s.trim().is_empty()).unwrap_or(false)
{
skipped += 1;
continue;
}
let frame_path = crate::core::file_profile::SceneProfile::scene_frame_path(
output_dir,
uuid,
@@ -5699,9 +5929,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
}
processed += 1;
// Update progress every 10 scenes
if processed % 10 == 0 || processed == total_scenes {
db.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32)
// Update progress every 10 scenes (count skipped ones as done for accurate %)
let done = processed + skipped;
if done % 10 == 0 || done >= total_scenes {
db.update_scene_vlm_progress(uuid, done as i32, total_scenes as i32)
.await?;
}
}
@@ -5718,8 +5949,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
.count();
info!(
"[Scene VLM] ✅ Generated {} descriptions, {} failed",
success_count, fail_count
"[Scene VLM] ✅ Generated {} descriptions ({} new, {} resumed), {} failed",
success_count, processed, skipped, fail_count
);
SceneVlmProcessor::save_scene_profile(&profile, output_dir)?;
+37 -1
View File
@@ -142,6 +142,24 @@ const FRAME_SLOT_MAX: usize = 4;
/// Increased from 1 to 2 to improve throughput.
const TIME_SLOT_MAX: usize = 2;
/// Restore backed-up outputs when a forced re-run processor fails.
async fn restore_backup_on_failure(db: &crate::core::db::PostgresDb, redis: &crate::core::db::RedisClient, file_uuid: &str) {
let key = format!("{}rerun_backup:{}", crate::core::config::REDIS_KEY_PREFIX.as_str(), file_uuid);
let label: Option<String> = match redis.get_conn().await {
Ok(mut conn) => redis::cmd("GET").arg(&key).query_async(&mut conn).await.ok().flatten(),
Err(_) => None,
};
if let Some(label) = label {
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.to_string();
let restored = crate::core::rerun_backup::restore_files(&per_lib, file_uuid, &label)
+ crate::core::rerun_backup::restore_files(&global_dir, file_uuid, &label);
if restored > 0 {
tracing::warn!("[RERUN-RESTORE] Restored {} files for {} after processor failure", restored, file_uuid);
}
}
}
pub struct ProcessorPool {
db: Arc<PostgresDb>,
redis: Arc<RedisClient>,
@@ -583,6 +601,19 @@ impl ProcessorPool {
error!("Failed to update Redis processor status: {}", e);
}
// Re-run succeeded — drop the rollback label so a later
// failure on this file never restores this stale backup.
{
let key = format!(
"{}rerun_backup:{}",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
job.uuid
);
if let Ok(mut c) = redis.get_conn().await {
let _: Result<(), _> = redis::cmd("DEL").arg(&key).query_async(&mut c).await;
}
}
// Also update PostgreSQL processing_status JSON
if let Err(e) = db
.update_processor_progress(
@@ -615,6 +646,9 @@ impl ProcessorPool {
error!("Failed to update processor result to failed: {}", db_err);
}
// Restore backed-up output if this was a forced re-run
restore_backup_on_failure(db.as_ref(), redis.as_ref(), &job.uuid).await;
if let Err(redis_err) = redis
.update_worker_processor_status(
&job.uuid,
@@ -638,6 +672,8 @@ impl ProcessorPool {
"Processor {} failed for job {}: {}",
processor_name, job.uuid, e
);
// Restore backed-up output if this was a forced re-run
restore_backup_on_failure(db.as_ref(), redis.as_ref(), &job.uuid).await;
if let Err(db_err) = db
.update_processor_result_with_stats(
processor_result_id,
@@ -677,7 +713,7 @@ impl ProcessorPool {
async fn run_processor(
db: &PostgresDb,
_redis: &RedisClient,
redis: &RedisClient,
job: &MonitorJob,
processor_type: ProcessorType,
_cancel_rx: mpsc::Receiver<()>,
+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)
}
}