42 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
Accusys a57e0bb433 fix: scan.rs stats API 使用 per-library 路徑 — 修復 Scene VLM 數量不顯示
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- get_file_stats_inner: output_dir 改 per-library(scene_vlm/face_cluster/vlm_summary stats)
- get_pipeline_progress_handler: output_dir 改 per-library
- get_ingestion_status: scene_meta_path 改 per-library
- get_scene_vlm_stats: output_dir 改 per-library
- 驗證: test library scene-vlm-stats 回傳 18 scenes, 18/18 done
2026-11-19 15:43:17 +08:00
Accusys 02ef25d4e7 fix: face/trace 縮圖 API 使用 per-library 路徑
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- face_thumbnail: .faces cache + trace_{id}/key_face.jpg 改 per-library + global fallback
- trace_thumbnail: key_face.jpg 改 per-library + global fallback
- 驗證: test library face 縮圖 HTTP 200 (422x422 JPEG), demo 也正常
2026-11-19 15:30:25 +08:00
Accusys f5363ca862 fix: Scene VLM 全流程 per-library 路徑
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- job_worker: cut.json 檢查 + output_dir + scenes_path 改用 get_output_dir_for_file
- media_api: scene_thumbnail 改用 per-library + global fallback
- 確保 test library 的 scenes.json 與 scene jpg 寫到 output/test/
- 已搬移舊 scene jpg 從 demo 到 test
2026-11-19 15:06:10 +08:00
Accusys 0be345eb24 fix: Unregister sync mode 清除 per-library output — rust_unregister 只刪全域 OUTPUT_DIR
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- UI Unregister 走 sync mode → rust_unregister binary
- rust_unregister 只用 config::OUTPUT_DIR(demo),不考慮 library → test output 殘留
- 修復: rust_unregister 成功後補呼叫 delete_output_files (掃描全域+per-lib+所有 upload_paths)
- 驗證: test 目錄 8 個 output 檔案全清除
2026-11-19 14:37:01 +08:00
Accusys e0d09ed7b3 fix: swift_ocr 使用已廢棄的 -vsync vfr(ffmpeg 9 移除)
Cross-Project Integration / integration (push) Has been cancelled
- ffmpeg 9 移除 -vsync 選項 → swift_ocr frame extraction 完全失敗(0 幀)
- 改為 -fps_mode vfr(ffmpeg 9 新語法)
- 重新編譯 swift_ocr binary 並部署
- 結果: OCR 從 0 幀 → 494 幀有文字
2026-11-19 14:06:33 +08:00
Accusys 2df98eb31c fix: output-completeness 檢查改用 per-library 路徑 — 修復 test library 誤報缺項
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- 原本用全域 OUTPUT_DIR(demo) 檢查所有影片
- test 檔案的 json 在 output/test → 誤報 6 項 missing
- 改用 get_output_dir_for_file(uuid) + global fallback
2026-11-19 13:51:32 +08:00
Accusys a4e176c682 fix: download_json 使用 per-library 路徑 — 修復 test library 卡片 detail 查看 json 失敗
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- proxy /api/v1/processor-json 實際呼叫 POST /api/v1/file/:uuid/json/:processor (download_json)
- download_json 原本用全域 OUTPUT_DIR(demo),test 檔案在 output/test → 404
- 改用 get_output_dir_for_file + global fallback
- face_trace → face_traced.json 映射
2026-11-19 13:46:06 +08:00
Accusys c4fbbfda4a fix: pipeline log 寫入 output root + processor-counts/json 使用 per-library 路徑
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- write_pipeline_timeline: log 寫到 ~/momentry/output (parent of per-lib dir)
- get_processor_counts: 用 get_output_dir_for_file + global fallback
- get_processor_json: 加 State, per-library 優先 + global fallback
- delete_output_files_for_uuid: 同時掃 output root 清 pipeline log
2026-11-19 13:35:24 +08:00
Accusys 36f4dcf807 fix: unregister 刪除 output 時使用 per-library 路徑(videos 刪除前解析)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- 根因: get_output_dir_for_file JOIN videos,但 unregister 先刪 videos 再刪 output
  → 解析失敗回退全域 OUTPUT_DIR(demo),沒刪到 test 目錄舊檔
  → re-scan 時 AUTO-REPAIR 看到舊 asrx.json 就標 completed(無 status/chunks)→ 卡住
- 修復: 在 unregister_internal 開頭(videos 還在時)解析 output_dir
- delete_output_files 掃描 全域 + pre-resolved per-library + 所有 upload_paths
- 同步修復 unregister_api.rs
- 結果: re-scan 真正清掉舊檔 → ASRX 重跑 → has_transcript + 28 chunks ✓
2026-11-19 13:23:10 +08:00
Accusys 3d56151787 fix: ASRX legacy 檔無 status 時推導 has_transcript + 補 segment_count
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- AUTO-REPAIR: asrx.json 無 status 但有 segments → 推導 has_transcript 並回寫
- 修正 has_transcript 被誤映射為 SilentAudio 的 bug
- segment_count 正確帶入
2026-11-19 12:54:26 +08:00
Accusys 3a6f9b0044 feat: Queue 管理 API — list/cancel/priority/clear + job_status 回傳
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- GET /api/v1/jobs/queue — 列出所有 job + processor 狀態 + summary
- POST /api/v1/jobs/:uuid/cancel — 取消單一 job
- POST /api/v1/jobs/:uuid/priority — 調整優先順序
- POST /api/v1/jobs/queue/clear — 批次清除 pending/paused/all jobs
- files API 回傳 job_status
- 修正 queue API panic (型別錯誤)
2026-11-19 10:53:47 +08:00
Accusys 8ab7bbaea7 fix: _debug output_dir 改為從實際路徑推導 + executor 使用 per-library output dir
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- json_standardize.rs: create_debug() 從檔案路徑推導 output_dir
- executor.rs: resolve_output_dir() 優先使用 env var 或從 output_path 推導
- 修復 output_dir 永遠顯示 output/demo 的問題
2026-11-19 02:12:38 +08:00
Accusys 9a7528d49b fix: worker 自動補遺漏的 monitor_jobs(repair 機制)
Cross-Project Integration / integration (push) Has been cancelled
Core Test / lint-and-test (push) Has been cancelled
- Sync mode register 不會建立 monitor_jobs
- Worker poll 迴圈自動為 pending videos 建立 monitor_jobs
- 修正 file_type 判斷(video/mp4/mov/avi/mkv)
2026-11-19 01:44:10 +08:00
Accusys b583946f7e fix: per-library output path for face_trace spawn check + completeness check
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- face_trace spawn 改用 get_output_dir_for_file 檢查 face_traced.json
- completeness check 改用 per-library dir + global fallback
- rust_store_traced_faces output_dir 改用 get_output_dir_for_file
2026-11-18 16:08:33 +08:00
Accusys 8101ff0cb4 fix: face processor 讀取 .with_embedding 檔案當 copy 失敗時(確保 facenet embeddings 不會遺失)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-18 01:05:38 +08:00
Accusys 18aa0130a7 fix: 檔案列表 name matching fallback — path 不匹配時改用 name 比對(處理 symlink 路徑差異)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 23:38:01 +08:00
Accusys 1d3c86c56c fix: upload_paths output_path 自動設定 + settings save 不覆蓋既有 full_path
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- 新增 upload_path 時自動設定 output_path = /Users/accusys/momentry/output/{name}
- ON CONFLICT 只設 enabled=true,不再覆蓋 full_path
2026-11-17 22:11:54 +08:00
Accusys 2a8bd88a3e fix: appearance API per-library output path(與 trace_profile/face_cluster 同樣的 per-library fallback 模式)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 19:46:13 +08:00
Accusys be16a588c2 feat: 自動產生 face_id(face_{frame}_{idx})於 face.json 儲存前
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 19:29:14 +08:00
Accusys 4100d5c77a fix: per-library output path for cluster_agent, profile, trace_agent
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- cluster_agent: resolve_output_path per-library + fallback
- profile.rs: materialize_auto_groups + get_cluster_results + trace_profile filesystem fallback
- trace_agent_api.rs: read_trace_profile per-library + fallback
All now check output/demo/ before falling back to global output/
2026-11-17 19:14:15 +08:00
Accusys a16a2981e1 fix: unregistered 卡片確保有 size/mdate — MarkBase fallback + 磁碟掃描補齊 + formatSize/formatDate 顯示 '—' 替代空白
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 18:12:21 +08:00
Accusys 953d677c8e feat: DELETE API /api/v1/file/delete-unregistered — 永久刪除殘留 entry(磁碟檔 + DB + Qdrant + Redis),路徑限縮 storage root
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 17:56:06 +08:00
Accusys 5b5c1d9563 fix: face pipeline 三項修復
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
1. face_clustering: 先試 Rust binary,Python script 缺失不再提前返回空結果
2. face.rs: facenet model 查找加 fallback ( -> momentry_core/models),config 路徑補 --model 參數
3. rust_store_traced_faces: embedding 缺失時退回純 IoU 追蹤(不再強制要求 similarity);trace_profile.json 補上真實 avg_bbox/best_bbox/capture_quality
2026-11-17 17:26:00 +08:00
Accusys 5056c20667 fix: embedding port 全部改為 11436(plist + svc_def + server_type + test-embedding) 2026-11-17 13:31:20 +08:00
Accusys 8f0315e588 fix: embedding port 11437 → 11436 (correct system port)
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 13:26:56 +08:00
Accusys 6ba4ee1e06 fix: Redis service label sh.brew.redis → com.momentry.redis
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 12:48:51 +08:00
Accusys b4b84dc797 feat: composite scoring for best face selection (0.4 frontal + 0.4 confidence + 0.2 quality)
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 10:56:42 +08:00
Accusys 7fd7df2913 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts'); embedding port 11436→11437
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 08:41:34 +08:00
Accusys eac827d932 fix: scripts_dir() 恢復正確路徑 resolve_asset_path('MOMENTRY_SCRIPTS_DIR', 'scripts') → ~/momentry/scripts/ 2026-11-17 04:31:03 +08:00
Accusys a85e31ff16 fix: embedding default port 11436 → 11437 (llama-server GGUF) 2026-11-17 04:26:33 +08:00
662 changed files with 8239 additions and 4841 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"] }
@@ -2,109 +2,77 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.n8n.main</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>start</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>DOMAIN_NAME</key>
<string>n8n.momentry.ddns.net</string>
<key>WEBHOOK_URL</key>
<string>https://n8n.momentry.ddns.net/</string>
<key>N8N_PORT</key>
<string>5678</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LISTEN_ADDRESS</key>
<string>0.0.0.0</string>
<key>N8N_USER_MANAGEMENT_JWT_DURATION</key>
<string>1h</string>
<key>N8N_RUNNERS_ENABLED</key>
<string>false</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PUBLIC_API_ENABLED</key>
<string>true</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/n8n-main.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/n8n-main.error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DOMAIN_NAME</key>
<string>n8n.momentry.ddns.net</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LISTEN_ADDRESS</key>
<string>0.0.0.0</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PORT</key>
<string>5678</string>
<key>N8N_PUBLIC_API_ENABLED</key>
<string>true</string>
<key>N8N_RUNNERS_ENABLED</key>
<string>false</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_USER_MANAGEMENT_JWT_DURATION</key>
<string>1h</string>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>WEBHOOK_URL</key>
<string>https://n8n.momentry.ddns.net/</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.n8n.main</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>start</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/n8n-main.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/n8n-main.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
</dict>
</plist>
@@ -2,103 +2,73 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.n8n.worker</string>
<key>UserName</key>
<string>accusys</string>
<key>GroupName</key>
<string>staff</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>worker</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_PORT</key>
<string>5681</string>
<key>QUEUE_HEALTH_CHECK_PORT</key>
<string>5682</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>TZ</key>
<string>Asia/Taipei</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_RUNNERS_BROKER_PORT</key>
<string>5690</string>
<key>N8N_RUNNERS_LAUNCHER_HEALTH_CHECK_PORT</key>
<string>5691</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/n8n-worker.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/n8n-worker.error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>DB_POSTGRESDB_DATABASE</key>
<string>n8n</string>
<key>DB_POSTGRESDB_HOST</key>
<string>127.0.0.1</string>
<key>DB_POSTGRESDB_PASSWORD</key>
<string>accusys</string>
<key>DB_POSTGRESDB_PORT</key>
<string>5432</string>
<key>DB_POSTGRESDB_USER</key>
<string>n8n</string>
<key>DB_TYPE</key>
<string>postgresdb</string>
<key>EXECUTIONS_MODE</key>
<string>queue</string>
<key>GENERIC_TIMEZONE</key>
<string>Asia/Taipei</string>
<key>N8N_ENCRYPTION_KEY</key>
<string>Test3200Test3200Test3200</string>
<key>N8N_HOST</key>
<string>127.0.0.1</string>
<key>N8N_LOG_LEVEL</key>
<string>info</string>
<key>N8N_METRICS</key>
<string>true</string>
<key>N8N_PORT</key>
<string>5681</string>
<key>N8N_RUNNERS_BROKER_PORT</key>
<string>5690</string>
<key>N8N_RUNNERS_LAUNCHER_HEALTH_CHECK_PORT</key>
<string>5691</string>
<key>N8N_USER_FOLDER</key>
<string>/Users/accusys/momentry/var/n8n</string>
<key>PATH</key>
<string>/opt/homebrew/opt/node@22/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>QUEUE_BULL_REDIS_HOST</key>
<string>127.0.0.1</string>
<key>QUEUE_BULL_REDIS_PASSWORD</key>
<string>accusys</string>
<key>QUEUE_BULL_REDIS_PORT</key>
<string>6379</string>
<key>QUEUE_HEALTH_CHECK_PORT</key>
<string>5682</string>
<key>TZ</key>
<string>Asia/Taipei</string>
</dict>
<key>GroupName</key>
<string>staff</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.n8n.worker</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry/scripts/start_n8n.sh</string>
<string>worker</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/n8n-worker.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/n8n-worker.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/n8n</string>
</dict>
</plist>
@@ -2,32 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.rustdesk.hbbr</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbr</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbr.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbr.error.log</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.rustdesk.hbbr</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbr</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbr.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbr.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
</dict>
</plist>
@@ -2,32 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.momentry.rustdesk.hbbs</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbs</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbs.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/rustdesk-hbbs.error.log</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.rustdesk.hbbs</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/hbbs</string>
<string>-k</string>
<string>_</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbs.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/rustdesk-hbbs.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/rustdesk</string>
</dict>
</plist>
+19 -10
View File
@@ -14,6 +14,18 @@ use tokio::sync::RwLock;
use super::middleware::UserAuth;
use super::types::AppState;
use crate::core::config::OUTPUT_DIR;
/// Resolve output path for a per-library file, falling back to global OUTPUT_DIR.
/// Used by both cluster_agent and profile (get_cluster_results).
pub(crate) async fn resolve_output_path(pool: &sqlx::PgPool, file_uuid: &str, ext: &str) -> std::path::PathBuf {
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await;
let candidate = std::path::PathBuf::from(&per_lib).join(format!("{}.{ext}", file_uuid));
if candidate.exists() {
return candidate;
}
// Fallback: global output dir (legacy)
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.{ext}", file_uuid))
}
use crate::core::db::schema;
use crate::core::processor::{process_face_cluster, FaceClusterResult};
@@ -221,8 +233,8 @@ pub async fn trigger_cluster_agent(
.unwrap_or_default()
.as_secs()
);
let output_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
// Resolve output paths (per-library with global fallback)
let output_path = resolve_output_path(state.db.pool(), &file_uuid, "face_cluster.json").await;
let cancel_token = tokio_util::sync::CancellationToken::new();
// Register job
@@ -242,8 +254,7 @@ pub async fn trigger_cluster_agent(
.insert(job_id.clone(), handle);
// Reset trace names before re-clustering
let traced_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
let traced_path = resolve_output_path(state.db.pool(), &file_uuid, "face_traced.json").await;
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(traces) = traced_data.get("traces") {
@@ -502,8 +513,7 @@ async fn update_trace_labels_from_cluster(
file_uuid: &str,
result: &FaceClusterResult,
) -> anyhow::Result<()> {
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.face_traced.json", file_uuid));
let traced_path = resolve_output_path(db.pool(), file_uuid, "face_traced.json").await;
let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new();
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
@@ -565,7 +575,7 @@ async fn update_trace_labels_from_cluster(
.await;
}
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
if let Some(all_trace_ids) = get_all_trace_ids(db.pool(), file_uuid).await {
let mut updated_count = 0u64;
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
@@ -594,9 +604,8 @@ async fn update_trace_labels_from_cluster(
Ok(())
}
fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.face_traced.json", file_uuid));
async fn get_all_trace_ids(pool: &sqlx::PgPool, file_uuid: &str) -> Option<Vec<i64>> {
let traced_path = resolve_output_path(pool, file_uuid, "face_traced.json").await;
let content = std::fs::read_to_string(&traced_path).ok()?;
let traced_data: serde_json::Value = serde_json::from_str(&content).ok()?;
let traces = traced_data.get("traces")?;
+35 -5
View File
@@ -1297,10 +1297,28 @@ struct ReScanResponse {
process_command_id: Option<String>,
}
fn delete_output_files(uuid: &str) -> u64 {
async fn delete_output_files(uuid: &str, pool: &sqlx::PgPool, pre_resolved_dir: Option<&str>) -> u64 {
let mut deleted_count = 0u64;
// Check multiple output directories
let output_dirs = [config::OUTPUT_DIR.to_string()];
// Build output dirs: global OUTPUT_DIR + pre-resolved per-library dir + all upload_paths
let mut output_dirs: Vec<String> = vec![config::OUTPUT_DIR.to_string()];
if let Some(dir) = pre_resolved_dir {
if !dir.is_empty() && !output_dirs.contains(&dir.to_string()) {
output_dirs.push(dir.to_string());
}
}
// All enabled upload_paths output paths (covers all libraries regardless of videos row)
if let Ok(rows) = sqlx::query_scalar::<_, String>(
"SELECT output_path FROM upload_paths WHERE enabled = true AND output_path IS NOT NULL"
).fetch_all(pool).await {
for dir in rows {
if !dir.is_empty() && !output_dirs.contains(&dir) {
output_dirs.push(dir);
}
}
}
tracing::info!("[UNREGISTER] Scanning output dirs for {}: {:?}", uuid, output_dirs);
for output_dir in &output_dirs {
if let Ok(entries) = std::fs::read_dir(output_dir) {
@@ -1445,6 +1463,13 @@ async fn unregister(
})?;
if output.status.success() {
// rust_unregister only clears the global OUTPUT_DIR (demo).
// Also clear per-library output dirs (test, etc.) which it doesn't know about.
let extra_deleted = delete_output_files(&uuid, state.db.pool(), None).await;
if extra_deleted > 0 {
tracing::info!("[UNREGISTER] Sync mode: additionally deleted {} output files across libraries for {}", extra_deleted, uuid);
}
Ok(Json(UnregisterResponse {
success: true,
message: "Unregister completed (sync mode)".to_string(),
@@ -1659,6 +1684,11 @@ async fn re_scan(
/// Internal unregister function - can be called from both API and register
pub(crate) async fn unregister_internal(db: &PostgresDb, uuid: &str) -> Result<(), StatusCode> {
// Resolve per-library output dir BEFORE deleting the videos row
// (get_output_dir_for_file JOINs videos → must run while the row still exists)
let resolved_output_dir = crate::core::config::get_output_dir_for_file(uuid, db.pool()).await;
tracing::info!("[UNREGISTER] Resolved output dir for {}: {}", uuid, resolved_output_dir);
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
let chunks_table = schema::table_name("chunk");
@@ -1783,8 +1813,8 @@ pub(crate) async fn unregister_internal(db: &PostgresDb, uuid: &str) -> Result<(
tracing::info!("[UNREGISTER] Deleted all data for {}", uuid);
// Delete output files
delete_output_files(uuid);
// Delete output files (pass pre-resolved dir since videos row is already deleted)
delete_output_files(uuid, db.pool(), Some(&resolved_output_dir)).await;
// Delete Qdrant vectors — iterate all collections that carry per-file points.
// The main collection holds text/trace chunks (incl. vlm_summary); `_faces` (face
+94 -3
View File
@@ -129,6 +129,7 @@ async fn list_files(
file_size: None,
modified_time: None,
thumbnail_url: None,
job_status: None,
}]
} else {
vec![]
@@ -202,8 +203,10 @@ async fn list_files(
let name = mb_file.name;
let mb_path = mb_file.file_path.clone().unwrap_or_default();
// Try path match first, then fall back to name match
// (handles symlink paths where MarkBase returns different path than registered)
let matched = if !mb_path.is_empty() {
registered_by_path.get(&mb_path)
registered_by_path.get(&mb_path).or_else(|| registered_by_name.get(&name))
} else {
registered_by_name.get(&name)
};
@@ -221,6 +224,7 @@ async fn list_files(
file_size,
modified_time,
thumbnail_url: None,
job_status: None,
});
} else {
// Not registered: use MarkBase file_path if available
@@ -236,6 +240,19 @@ async fn list_files(
format!("{}/{}", default_root, name)
})
});
// Fallback: use filesystem metadata when MarkBase data is unavailable
let file_size = if mb_file.size > 0 {
Some(mb_file.size)
} else {
std::fs::metadata(&file_path).ok().map(|m| m.len())
};
let modified_time = if !mb_file.modified.is_empty() {
Some(mb_file.modified)
} else {
std::fs::metadata(&file_path).ok()
.and_then(|m| m.modified().ok())
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339())
};
all_files.push(FileItem {
file_uuid: mb_file.file_uuid.unwrap_or_default(),
file_name: name,
@@ -243,9 +260,10 @@ async fn list_files(
status: "unregistered".to_string(),
is_registered: false,
total_chunks: 0,
file_size: Some(mb_file.size),
modified_time: Some(mb_file.modified),
file_size,
modified_time,
thumbnail_url: None,
job_status: None,
});
}
}
@@ -274,10 +292,41 @@ async fn list_files(
file_size,
modified_time,
thumbnail_url: None,
job_status: None,
});
}
}
// Scan filesystem for files not in MarkBase AND not in DB (true unregistered)
for (_, dir_path) in &upload_paths {
if let Ok(entries) = std::fs::read_dir(dir_path) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() { continue }
let name = entry.file_name().to_string_lossy().to_string();
let name_lower = name.to_lowercase();
if name_lower == ".ds_store" || name_lower.ends_with(".sqlite") { continue }
if all_names.contains(&name) { continue }
// Check all paths (including MarkBase paths)
if all_paths.contains(&path.to_string_lossy().to_string()) { continue }
let meta = entry.metadata().ok();
all_files.push(FileItem {
file_uuid: String::new(),
file_name: name,
file_path: path.to_string_lossy().to_string(),
status: "unregistered".to_string(),
is_registered: false,
total_chunks: 0,
file_size: meta.as_ref().map(|m| m.len()),
modified_time: meta.and_then(|m| m.modified().ok())
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339()),
thumbnail_url: None,
job_status: None,
});
}
}
}
// Add thumbnail URLs for all video files
for file in &mut all_files {
@@ -318,11 +367,50 @@ async fn list_files(
count_map = chunk_counts.into_iter().collect();
}
// Fetch job status counts for all files
let monitor_jobs_table = crate::core::db::schema::table_name("monitor_jobs");
let mut job_status_map: std::collections::HashMap<String, serde_json::Value> = std::collections::HashMap::new();
if !uuids.is_empty() {
// Build query with proper bindings
let placeholders: Vec<String> = (1..=uuids.len()).map(|i| format!("${}", i)).collect();
let job_query = format!(
"SELECT uuid, status, COUNT(*) as cnt FROM {mj_t} WHERE uuid IN ({}) GROUP BY uuid, status",
placeholders.join(", "),
mj_t = monitor_jobs_table
);
let mut query = sqlx::query_as::<_, (String, String, i64)>(&job_query);
for uuid in &uuids {
query = query.bind(uuid);
}
let job_counts: Vec<(String, String, i64)> = query
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
// Group by uuid: {pending: N, running: N, completed: N}
let mut temp_map: std::collections::HashMap<String, serde_json::Map<String, serde_json::Value>> = std::collections::HashMap::new();
for (uuid, status, cnt) in job_counts {
let entry = temp_map.entry(uuid).or_default();
entry.insert(status, serde_json::Value::Number(serde_json::Number::from(cnt)));
}
for (uuid, map) in temp_map {
job_status_map.insert(uuid, serde_json::Value::Object(map));
}
}
let mut data = data;
for item in &mut data {
if let Some(cnt) = count_map.get(&item.file_uuid) {
item.total_chunks = *cnt;
}
if let Some(js) = job_status_map.get(&item.file_uuid) {
item.job_status = Some(js.clone());
}
}
Ok(Json(FilesResponse {
@@ -368,6 +456,9 @@ pub struct FileItem {
pub modified_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<String>,
/// Job status summary: {pending: N, running: N, completed: N}
#[serde(skip_serializing_if = "Option::is_none")]
pub job_status: Option<serde_json::Value>,
}
#[derive(Debug, Serialize)]
+333
View File
@@ -9,6 +9,7 @@ use axum::{
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use sqlx::Row;
use super::types::AppState;
use crate::core::db::schema;
@@ -20,6 +21,10 @@ pub fn job_management_routes() -> Router<AppState> {
.route("/api/v1/jobs/paused", get(list_paused_jobs))
.route("/api/v1/jobs/:uuid/status", get(get_job_status))
.route("/api/v1/admin/sync-status", post(sync_all_statuses))
.route("/api/v1/jobs/queue", get(list_queue_jobs))
.route("/api/v1/jobs/:uuid/cancel", post(cancel_job))
.route("/api/v1/jobs/:uuid/priority", post(set_job_priority))
.route("/api/v1/jobs/queue/clear", post(clear_queue_jobs))
}
#[derive(Debug, Serialize)]
@@ -362,3 +367,331 @@ async fn sync_all_statuses(
message: format!("Found {} mismatches, fixed {}", mismatch_count, fixed),
}))
}
// ─── Queue Management: list, cancel, priority ─────────────────────────────────
#[derive(Debug, Serialize)]
pub struct QueueJob {
pub job_id: i32,
pub uuid: String,
pub file_name: String,
pub status: String,
pub created_at: Option<String>,
pub updated_at: Option<String>,
/// Processor completion summary from processor_results
pub processors_total: i64,
pub processors_completed: i64,
pub processors_running: i64,
pub processors_pending: i64,
pub processors_failed: i64,
}
#[derive(Debug, Serialize)]
pub struct QueueResponse {
pub jobs: Vec<QueueJob>,
pub summary: serde_json::Value,
}
/// GET /api/v1/jobs/queue
/// List all jobs in the queue with their processor status.
/// Query params: status (filter), limit (default 100)
async fn list_queue_jobs(
State(state): State<AppState>,
axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Result<Json<QueueResponse>, (StatusCode, String)> {
let monitor_jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let pr_table = schema::table_name("processor_results");
let status_filter = params.get("status").cloned().unwrap_or_default();
let limit: i64 = params.get("limit").and_then(|v| v.parse().ok()).unwrap_or(100);
let status_clause = if status_filter.is_empty() {
String::new()
} else {
format!("WHERE mj.status = '{}'", status_filter.replace('\'', ""))
};
let rows = sqlx::query(&format!(
"SELECT mj.id::text, mj.uuid, v.file_name, mj.status,
mj.created_at::text, COALESCE(mj.updated_at::text, ''),
COALESCE(pr.total, 0), COALESCE(pr.completed, 0),
COALESCE(pr.running, 0), COALESCE(pr.pending, 0), COALESCE(pr.failed, 0)
FROM {mj_t} mj
LEFT JOIN {v_t} v ON v.file_uuid = mj.uuid
LEFT JOIN (
SELECT job_id,
COUNT(*) as total,
COUNT(*) FILTER (WHERE status = 'completed') as completed,
COUNT(*) FILTER (WHERE status = 'running') as running,
COUNT(*) FILTER (WHERE status = 'pending') as pending,
COUNT(*) FILTER (WHERE status = 'failed') as failed
FROM {pr_t}
GROUP BY job_id
) pr ON pr.job_id = mj.id
{status_clause}
ORDER BY mj.created_at DESC
LIMIT $1",
mj_t = monitor_jobs_table,
v_t = videos_table,
pr_t = pr_table,
status_clause = status_clause,
))
.bind(limit)
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[Queue] query failed: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
})?;
let mut jobs = Vec::new();
for row in rows {
jobs.push(QueueJob {
job_id: row.try_get::<String, _>("id").unwrap_or_default().parse().unwrap_or(0),
uuid: row.try_get::<String, _>("uuid").unwrap_or_default(),
file_name: row.try_get::<String, _>("file_name").unwrap_or_else(|_| "(unknown)".to_string()),
status: row.try_get::<String, _>("status").unwrap_or_default(),
created_at: row.try_get::<String, _>("created_at").ok(),
updated_at: row.try_get::<String, _>("updated_at").ok(),
processors_total: row.try_get::<i64, _>("total").unwrap_or(0),
processors_completed: row.try_get::<i64, _>("completed").unwrap_or(0),
processors_running: row.try_get::<i64, _>("running").unwrap_or(0),
processors_pending: row.try_get::<i64, _>("pending").unwrap_or(0),
processors_failed: row.try_get::<i64, _>("failed").unwrap_or(0),
});
}
// Summary counts
let summary_rows: Vec<(String, i64)> = sqlx::query_as(&format!(
"SELECT status, COUNT(*) FROM {mj_t} GROUP BY status",
mj_t = monitor_jobs_table
))
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let mut summary = serde_json::Map::new();
for (status, count) in summary_rows {
summary.insert(status, serde_json::Value::Number(serde_json::Number::from(count)));
}
Ok(Json(QueueResponse {
jobs,
summary: serde_json::Value::Object(summary),
}))
}
/// POST /api/v1/jobs/:uuid/cancel
/// Cancel a pending/paused job: delete monitor_jobs + processor_results, reset video status.
async fn cancel_job(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let monitor_jobs_table = schema::table_name("monitor_jobs");
let pr_table = schema::table_name("processor_results");
let videos_table = schema::table_name("videos");
// Check current status — only pending/paused/running jobs can be cancelled
let status: Option<String> = sqlx::query_scalar(&format!(
"SELECT status FROM {mj_t} WHERE uuid = $1",
mj_t = monitor_jobs_table
))
.bind(&uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?
.flatten();
let status = match status {
Some(s) => s,
None => {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Job not found"})),
))
}
};
if status == "completed" {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Cannot cancel a completed job"})),
));
}
// Delete processor_results
sqlx::query(&format!(
"DELETE FROM {pr_t} WHERE job_id IN (SELECT id FROM {mj_t} WHERE uuid = $1)",
pr_t = pr_table,
mj_t = monitor_jobs_table
))
.bind(&uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
// Delete monitor_jobs
sqlx::query(&format!(
"DELETE FROM {mj_t} WHERE uuid = $1",
mj_t = monitor_jobs_table
))
.bind(&uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
// Reset video status
sqlx::query(&format!(
"UPDATE {v_t} SET status = 'registered', updated_at = NOW() WHERE file_uuid = $1",
v_t = videos_table
))
.bind(&uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
tracing::info!("[Queue] Cancelled job for {} (was {})", uuid, status);
Ok(Json(serde_json::json!({
"success": true,
"message": format!("Job cancelled (was {})", status),
"uuid": uuid
})))
}
/// POST /api/v1/jobs/:uuid/priority
/// Move a pending job to the front of the queue (oldest created_at).
async fn set_job_priority(
State(state): State<AppState>,
Path(uuid): Path<String>,
axum::Json(body): axum::Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let monitor_jobs_table = schema::table_name("monitor_jobs");
let action = body.get("action").and_then(|v| v.as_str()).unwrap_or("front");
let result = sqlx::query(&format!(
"UPDATE {mj_t} SET created_at = CASE WHEN $1 = 'front' THEN NOW() - INTERVAL '1 hour' ELSE NOW() END, updated_at = NOW() WHERE uuid = $2 AND status = 'pending'",
mj_t = monitor_jobs_table
))
.bind(action)
.bind(&uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
if result.rows_affected() == 0 {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Pending job not found"})),
));
}
tracing::info!("[Queue] Job {} priority set to {}", uuid, action);
Ok(Json(serde_json::json!({
"success": true,
"message": format!("Job priority: {}", action),
"uuid": uuid
})))
}
/// POST /api/v1/jobs/queue/clear
/// Bulk-clear queued jobs by status: delete monitor_jobs + processor_results,
/// reset video status to 'registered'. Body: { status: "pending" | "paused" | "all" }
async fn clear_queue_jobs(
State(state): State<AppState>,
axum::Json(body): axum::Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let monitor_jobs_table = schema::table_name("monitor_jobs");
let pr_table = schema::table_name("processor_results");
let videos_table = schema::table_name("videos");
let target = body.get("status").and_then(|v| v.as_str()).unwrap_or("pending");
let status_clause = match target {
"pending" => "WHERE mj.status = 'pending'".to_string(),
"paused" => "WHERE mj.status = 'paused'".to_string(),
"all" => "WHERE mj.status != 'completed'".to_string(),
_ => {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "status must be pending/paused/all"})),
))
}
};
// Collect affected uuids first
let uuids: Vec<String> = sqlx::query_scalar(&format!(
"SELECT mj.uuid FROM {mj_t} mj {sc}",
mj_t = monitor_jobs_table,
sc = status_clause
))
.fetch_all(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
if uuids.is_empty() {
return Ok(Json(serde_json::json!({
"success": true, "cleared": 0, "message": "No matching jobs"
})));
}
// Delete processor_results
sqlx::query(&format!(
"DELETE FROM {pr_t} WHERE job_id IN (SELECT id FROM {mj_t} WHERE uuid = ANY($1))",
pr_t = pr_table,
mj_t = monitor_jobs_table
))
.bind(&uuids)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
// Delete monitor_jobs
sqlx::query(&format!(
"DELETE FROM {mj_t} WHERE uuid = ANY($1)",
mj_t = monitor_jobs_table
))
.bind(&uuids)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
// Reset video status
sqlx::query(&format!(
"UPDATE {v_t} SET status = 'registered', updated_at = NOW() WHERE file_uuid = ANY($1) AND status NOT IN ('completed')",
v_t = videos_table
))
.bind(&uuids)
.execute(state.db.pool())
.await
.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error": e.to_string()})))
})?;
let cleared = uuids.len();
tracing::info!("[Queue] Cleared {} {} jobs", cleared, target);
Ok(Json(serde_json::json!({
"success": true,
"cleared": cleared,
"message": format!("Cleared {} {} jobs", cleared, target)
})))
}
+53 -29
View File
@@ -1058,14 +1058,18 @@ async fn thumbnail_by_path(
/// Direct access to trace key_face.jpg — bypasses ffmpeg, reads pre-cached file.
/// Used by Studio for fast face group thumbnail loading.
async fn trace_thumbnail(
State(_state): State<crate::api::types::AppState>,
State(state): State<crate::api::types::AppState>,
Path((file_uuid, trace_id)): Path<(String, i32)>,
) -> Result<impl IntoResponse, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let key_face_path = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
// Try per-library dir first, then global OUTPUT_DIR (legacy)
let per_lib = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let rel = std::path::PathBuf::from(&file_uuid)
.join(format!("trace_{}", trace_id))
.join("key_face.jpg");
let candidate1 = std::path::PathBuf::from(&per_lib).join(&rel);
let candidate2 = std::path::PathBuf::from(global_dir).join(&rel);
let key_face_path = if candidate1.exists() { candidate1 } else { candidate2 };
if !key_face_path.exists() {
return Err(StatusCode::NOT_FOUND);
@@ -1102,10 +1106,11 @@ async fn trace_thumbnail(
/// Path mirrors `thumbnail_url` produced by the VLM scene search API.
/// e.g. /api/v1/file/{file_uuid}/scenes/scene_000.jpg
pub async fn scene_thumbnail(
State(_state): State<crate::api::types::AppState>,
State(state): State<crate::api::types::AppState>,
Path((file_uuid, filename)): Path<(String, String)>,
) -> Result<impl IntoResponse, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
// Try per-library output dir first (test files live in output/test)
let per_lib = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
// Security: validate file_uuid to prevent path traversal
if !crate::core::thumbnail::validator::is_valid_file_uuid(&file_uuid) {
@@ -1120,10 +1125,16 @@ pub async fn scene_thumbnail(
.map(|_| filename.clone())
.ok_or(StatusCode::NOT_FOUND)?;
let file_path = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
.join("scenes")
.join(&safe_name);
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let candidate1 = std::path::PathBuf::from(&per_lib)
.join(&file_uuid).join("scenes").join(&safe_name);
let candidate2 = std::path::PathBuf::from(global_dir)
.join(&file_uuid).join("scenes").join(&safe_name);
let file_path = if candidate1.exists() {
candidate1
} else {
candidate2
};
if !file_path.exists() {
return Err(StatusCode::NOT_FOUND);
@@ -1178,14 +1189,17 @@ async fn face_thumbnail(
// Step 1: Check for pre-stored face crop if trace_id is provided
if let Some(trace_id) = q.trace_id {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
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.as_str();
// Check .faces cache first
let cached_path = std::path::PathBuf::from(output_dir)
.join(".faces")
// Check .faces cache first (per-library + global)
let rel_cache = std::path::PathBuf::from(".faces")
.join(&file_uuid)
.join(trace_id.to_string())
.join(format!("{}.jpg", frame));
let cached_path_c1 = std::path::PathBuf::from(&per_lib_dir).join(&rel_cache);
let cached_path_c2 = std::path::PathBuf::from(global_dir).join(&rel_cache);
let cached_path = if cached_path_c1.exists() { cached_path_c1 } else { cached_path_c2.clone() };
if cached_path.exists() {
tracing::debug!(
@@ -1205,11 +1219,13 @@ async fn face_thumbnail(
return Ok(image_response(bytes));
}
// Fallback: check trace directory for key_face.jpg
let trace_key_face = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
// Fallback: check trace directory for key_face.jpg (per-library + global)
let rel_trace = std::path::PathBuf::from(&file_uuid)
.join(format!("trace_{}", trace_id))
.join("key_face.jpg");
let tc1 = std::path::PathBuf::from(&per_lib_dir).join(&rel_trace);
let tc2 = std::path::PathBuf::from(global_dir).join(&rel_trace);
let trace_key_face = if tc1.exists() { tc1 } else { tc2 };
if trace_key_face.exists() {
tracing::debug!(
@@ -1888,21 +1904,29 @@ async fn get_appearance_handler(
Path(file_uuid): Path<String>,
Query(params): Query<AppearanceQuery>,
) -> Result<axum::Json<AppearanceResponse>, StatusCode> {
use crate::core::config::OUTPUT_DIR;
let output_dir = OUTPUT_DIR.as_str();
// Try per-library dir first, fallback to global OUTPUT_DIR
let per_lib = crate::core::config::get_output_dir_for_file(&file_uuid, _state.db.pool()).await;
let appearance_path =
std::path::Path::new(output_dir).join(format!("{}.appearance.json", file_uuid));
std::path::Path::new(&per_lib).join(format!("{}.appearance.json", file_uuid));
if !appearance_path.exists() {
tracing::error!(
"[get_appearance] File not found: {}",
appearance_path.display()
);
// Fallback: global OUTPUT_DIR
let global = crate::core::config::OUTPUT_DIR.as_str();
let global_path = std::path::Path::new(global).join(format!("{}.appearance.json", file_uuid));
if global_path.exists() {
// use global_path
return read_appearance(&global_path, params.frame).await;
}
return Err(StatusCode::NOT_FOUND);
}
let content = std::fs::read_to_string(&appearance_path).map_err(|e| {
read_appearance(&appearance_path, params.frame).await
}
async fn read_appearance(
path: &std::path::Path,
frame: i64,
) -> Result<axum::Json<AppearanceResponse>, StatusCode> {
let content = std::fs::read_to_string(path).map_err(|e| {
tracing::error!("[get_appearance] Failed to read appearance.json: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
@@ -1919,7 +1943,7 @@ async fn get_appearance_handler(
let frame_data = frames
.iter()
.find(|f| f.get("frame").and_then(|v| v.as_i64()) == Some(params.frame))
.find(|f| f.get("frame").and_then(|v| v.as_i64()) == Some(frame))
.ok_or(StatusCode::NOT_FOUND)?;
let hsv_histogram = frame_data
@@ -1937,7 +1961,7 @@ async fn get_appearance_handler(
.unwrap_or_default();
Ok(axum::Json(AppearanceResponse {
frame: params.frame,
frame,
dominant_colors: vec![],
hsv_histogram,
}))
+160 -31
View File
@@ -25,6 +25,14 @@ use crate::{Embedder, FileManager};
fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
let mut deleted_count = 0u64;
// Also scan output root (parent of per-library dir) for pipeline logs
let mut dirs = vec![output_dir.to_string()];
if let Some(parent) = std::path::Path::new(output_dir).parent() {
if parent.file_name().and_then(|n| n.to_str()) == Some("output") {
dirs.push(parent.to_string_lossy().to_string());
}
}
for output_dir in &dirs {
if let Ok(entries) = std::fs::read_dir(output_dir) {
for entry in entries.flatten() {
let path = entry.path();
@@ -41,6 +49,7 @@ fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
}
}
}
}
deleted_count
}
@@ -415,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:
@@ -578,8 +624,18 @@ async fn download_json(
State(state): State<AppState>,
Path((file_uuid, processor)): Path<(String, String)>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let path = std::path::Path::new(&output_dir).join(format!("{}.{}.json", file_uuid, processor));
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.as_str();
// face_trace processor writes as face_traced.json
let ext = if processor == "face_trace" { "face_traced" } else { processor.as_str() };
let filename = format!("{}.{}.json", file_uuid, ext);
let candidates = [
std::path::Path::new(&per_lib_dir).join(&filename),
std::path::Path::new(global_dir).join(&filename),
];
let path = candidates.iter().find(|p| p.exists())
.cloned()
.unwrap_or_else(|| candidates[0].clone());
let content = tokio::fs::read_to_string(&path)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
@@ -916,7 +972,7 @@ struct OutputCompletenessItem {
async fn get_output_completeness(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let videos_table = schema::table_name("videos");
let rows: Vec<(String, String, String)> = sqlx::query_as(&format!(
@@ -937,13 +993,25 @@ async fn get_output_completeness(
continue; // 只檢查 completed 的影片
}
// Per-library output dir with global fallback (test files live in output/test)
let per_lib = crate::core::config::get_output_dir_for_file(&uuid, state.db.pool()).await;
let output_dir = if std::path::Path::new(&per_lib).is_dir() {
per_lib
} else {
global_dir.to_string()
};
let mut missing = Vec::new();
// 檢查 JSON 產出
for ext in ["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"] {
let path = format!("{}/{}.{}.json", output_dir, uuid, ext);
if !std::path::Path::new(&path).exists() {
missing.push(format!("{}.json", ext));
// fallback to global dir
let global_path = format!("{}/{}.{}.json", global_dir, uuid, ext);
if !std::path::Path::new(&global_path).exists() {
missing.push(format!("{}.json", ext));
}
}
}
@@ -999,6 +1067,7 @@ async fn get_output_completeness(
}
async fn get_processor_json(
State(state): State<AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let file_uuid = params.get("file_hash").ok_or((
@@ -1010,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",
@@ -1023,8 +1147,16 @@ async fn get_processor_json(
"tkg" => "tkg",
other => other,
};
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let path = format!("{}/{}.{}.json", output_dir.trim_end_matches('/'), file_uuid, ext);
// Try per-library dir first, then global OUTPUT_DIR (legacy)
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.as_str();
let candidates = [
format!("{}/{}.{}.json", per_lib_dir.trim_end_matches('/'), file_uuid, ext),
format!("{}/{}.{}.json", global_dir.trim_end_matches('/'), file_uuid, ext),
];
let path = candidates.iter().find(|p| std::path::Path::new(p).exists())
.cloned()
.unwrap_or_else(|| candidates[0].clone());
match std::fs::read_to_string(&path) {
Ok(content) => match serde_json::from_str(&content) {
@@ -1067,37 +1199,39 @@ async fn get_processor_counts(
});
let file_uuid = full_uuid.ok_or(StatusCode::NOT_FOUND)?;
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
// Use per-library output dir (test files live in output/test, not output/demo)
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.as_str();
let processors = crate::core::db::ProcessorType::all();
let mut results = Vec::new();
for processor in &processors {
let proc_name = processor.as_str();
// resolve output filename: some processors write under a different
// extension than their queue name (face_trace → face_traced.json).
let json_ext = match proc_name {
"face_trace" => "face_traced",
other => other,
};
let json_path =
std::path::Path::new(&output_dir).join(format!("{}.{}.json", file_uuid, json_ext));
let filename = format!("{}.{}.json", file_uuid, json_ext);
let json_path = std::path::Path::new(&per_lib_dir).join(&filename);
let fallback_path = std::path::Path::new(global_dir).join(&filename);
let effective_path = if json_path.exists() { json_path } else { fallback_path };
let has_json = json_path.exists();
let has_json = effective_path.exists();
let mut frame_count = None;
let mut segment_count = None;
let mut chunk_count = None;
let mut last_modified = None;
if has_json {
if let Ok(metadata) = std::fs::metadata(&json_path) {
if let Ok(metadata) = std::fs::metadata(&effective_path) {
if let Ok(modified) = metadata.modified() {
let chrono_dt: chrono::DateTime<chrono::Utc> = modified.into();
last_modified = Some(chrono_dt.to_rfc3339());
}
}
if let Ok(content) = std::fs::read_to_string(&json_path) {
if let Ok(content) = std::fs::read_to_string(&effective_path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
// CUT: prioritize scenes count over frame_count
if proc_name == "cut" {
@@ -1166,7 +1300,7 @@ async fn get_processor_counts(
Ok(Json(ProcessorCountsResponse {
file_uuid,
output_dir,
output_dir: per_lib_dir,
processors: results,
}))
}
@@ -1178,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(
@@ -1188,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");
@@ -1249,7 +1380,6 @@ async fn trigger_vlm_summary(
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
@@ -1281,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),
)
}
+17 -7
View File
@@ -9,6 +9,7 @@ use std::collections::HashMap;
use crate::api::middleware::UserAuth;
use crate::api::types::AppState;
use crate::api::cluster_agent::resolve_output_path;
use crate::core::db::schema;
use crate::core::file_profile::FaceFilterSettings;
@@ -47,8 +48,8 @@ async fn materialize_auto_groups(pool: &PgPool, file_uuid: &str) -> Result<(), S
.into_iter()
.collect();
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
// Try per-library dir first, fallback to global OUTPUT_DIR
let fc_path = resolve_output_path(pool, file_uuid, "face_cluster.json").await;
let Ok(content) = std::fs::read_to_string(&fc_path) else {
return Ok(()); // no auto clusters yet — done
};
@@ -355,12 +356,22 @@ let row: Option<(
file_uuid, trace_id);
// Construct path: {output_dir}/{file_uuid}/trace_{trace_id}/trace_profile.json
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| crate::core::config::OUTPUT_DIR.to_string().to_string());
let profile_path = std::path::Path::new(&output_dir)
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await;
let candidate = std::path::Path::new(&per_lib)
.join(file_uuid)
.join(format!("trace_{}", trace_id))
.join("trace_profile.json");
let profile_path = if candidate.exists() {
candidate
} else {
// Fallback: global OUTPUT_DIR (legacy)
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| crate::core::config::OUTPUT_DIR.to_string());
std::path::PathBuf::from(&output_dir)
.join(file_uuid)
.join(format!("trace_{}", trace_id))
.join("trace_profile.json")
};
// Read from filesystem
if profile_path.exists() {
@@ -2013,8 +2024,7 @@ pub async fn get_cluster_results_handler(
// Load face_cluster.json for similarity data only (not for adding clusters)
let cluster_similarity: HashMap<String, ClusterSimilarityInfo> = {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
let fc_path = resolve_output_path(state.db.pool(), &file_uuid, "face_cluster.json").await;
let mut map = HashMap::new();
if let Ok(content) = std::fs::read_to_string(&fc_path) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
+32 -9
View File
@@ -544,11 +544,14 @@ async fn get_ingestion_status(
let identity_count = identity_ids.len() as i64;
let strangers = stranger_traces.len() as i64;
let scene_meta_path = format!(
"{}/{}.scene_meta.json",
crate::core::config::OUTPUT_DIR.as_str(),
file_uuid
);
let per_lib_dir = crate::core::config::get_output_dir_for_file(&file_uuid, pool).await;
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let scene_meta_base = if std::path::Path::new(&per_lib_dir).is_dir() {
per_lib_dir
} else {
global_dir.to_string()
};
let scene_meta_path = format!("{}/{}.scene_meta.json", scene_meta_base, file_uuid);
let scene_meta_ok = std::path::Path::new(&scene_meta_path).exists();
macro_rules! count_sql {
@@ -1153,8 +1156,15 @@ async fn get_file_stats_inner(
..Default::default()
};
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let per_lib_dir = crate::core::config::get_output_dir_for_file(&file_uuid, pool).await;
let output_dir: &str = if std::path::Path::new(&per_lib_dir).is_dir() {
&per_lib_dir
} else {
global_dir
};
// 6. Get Face Dedup stats
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
let face_clusters = if std::path::Path::new(&face_cluster_path).exists() {
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
@@ -1330,6 +1340,15 @@ async fn get_pipeline_progress_handler(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<crate::core::progress::PipelineProgress>, StatusCode> {
// Per-library output dir (test files live in output/test)
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.as_str();
let output_dir: &str = if std::path::Path::new(&per_lib_dir).is_dir() {
&per_lib_dir
} else {
global_dir
};
// 1. Try to read existing progress from Redis first
let redis_progress: Option<crate::core::progress::PipelineProgress> = {
use crate::core::db::RedisClient;
@@ -1521,7 +1540,6 @@ async fn get_pipeline_progress_handler(
// Check scene_vlm progress from scenes.json
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
if std::path::Path::new(&scenes_path).exists() {
if let Ok(scenes_json) = std::fs::read_to_string(&scenes_path) {
@@ -1578,7 +1596,6 @@ async fn get_pipeline_progress_handler(
// Check face dedup from actual face_cluster.json content
// Always check if processors_done, regardless of tkg_node_count (A-10 fix)
if processors_done {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid);
if std::path::Path::new(&face_cluster_path).exists() {
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
@@ -1649,7 +1666,13 @@ pub async fn get_scene_vlm_stats(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
) -> Result<Json<SceneVlmStats>, StatusCode> {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let per_lib = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.as_str();
let output_dir = if std::path::Path::new(&per_lib).is_dir() {
per_lib
} else {
global_dir.to_string()
};
let scenes_path = format!("{}/{}.scenes.json", output_dir, file_uuid);
if !std::path::Path::new(&scenes_path).exists() {
+217
View File
@@ -0,0 +1,217 @@
use std::time::Duration;
use axum::{Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
use tower_http::services::ServeDir;
use crate::core::cache::{MongoCache, RedisCache};
use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::agent_api;
use super::agent_search;
use super::auth;
use super::billing;
use super::checkin_api;
use super::clip_api;
use super::cluster_agent;
use super::docs;
use super::face_filter;
use super::file_progress;
use super::files;
use super::health;
use super::health::{health, health_consistency, health_detailed, health_queue};
use super::identities;
use super::identity_api;
use super::identity_binding;
use super::llm_search;
use super::markbase_compat;
use super::media_api;
use super::middleware::unified_auth;
use super::pipeline;
use super::processing;
use super::profile;
use super::scan;
use super::search::search_routes;
use super::service_management;
use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::monitor;
use super::universal_search::universal_search_routes;
use super::vlm_search;
use super::job_management;
pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
health::init_server_state(host, port);
let embedder = std::sync::Arc::new(Embedder::new("embeddinggemma-300m".to_string()));
// ── ⚠️ WARNING: DO NOT move MongoCache::init() back to critical path ──
//
// MongoDB is ONLY a cache layer — if unavailable, the server MUST still
// start with Redis cache alone. This keeps 3002 bootable on machines
// without MongoDB installed. If you add a new dependency here, ask:
// "Can this service degrade gracefully if the dependant is missing?"
//
// See also: MongoCache::disabled() in mongo_cache.rs
let mongo_cache = match timeout(Duration::from_secs(5), MongoCache::init()).await {
Ok(Ok(cache)) => cache,
Ok(Err(e)) => {
tracing::warn!("MongoDB cache unavailable (continuing without): {e}");
MongoCache::disabled().await
}
Err(_) => {
tracing::warn!("MongoDB init timed out (continuing without cache)");
MongoCache::disabled().await
}
};
let redis_cache = RedisCache::new()?;
let db = PostgresDb::init().await?;
// Run migrations (create identity_history table if not exists)
PostgresDb::run_migrations(db.pool()).await?;
let schema_health = health::check_schema_migrations(db.pool()).await;
if schema_health.ok {
tracing::info!(
"[SCHEMA] All {}/{} required migrations applied ✓",
schema_health.required.len(),
schema_health.required.len()
);
} else if !schema_health.table_exists {
tracing::warn!("[SCHEMA] schema_migrations table not found!");
} else {
let missing: Vec<&str> = schema_health
.required
.iter()
.filter(|req| {
!schema_health
.applied
.iter()
.any(|app| app.filename == req.filename && app.checksum == req.checksum)
})
.map(|m| m.filename.as_str())
.collect();
tracing::warn!(
"[SCHEMA] {}/{} migrations match. Missing: {}",
schema_health.applied.len(),
schema_health.required.len(),
missing.join(", ")
);
}
let db = std::sync::Arc::new(db);
let api_state = super::middleware::ApiState { db: db.clone() };
let qdrant = std::sync::Arc::new(QdrantDb::new());
// Initialize AdminConfigManager
let admin_config_manager = std::sync::Arc::new(
crate::core::admin_config::AdminConfigManager::new(
&crate::core::admin_config::get_default_config_path(),
)
.expect("Failed to initialize AdminConfigManager"),
);
// Ensure trash collection exists for trace hard-delete undo
if let Err(e) = qdrant.ensure_collection("_faces_trash", 512).await {
tracing::warn!("[Server] Failed to ensure _faces_trash collection: {}", e);
}
let state = AppState {
db,
qdrant,
embedder,
embedder_model: "nomic-embed-text-v2-moe:latest".to_string(),
mongo_cache,
redis_cache,
api_state,
admin_config_manager,
};
let protected_routes = Router::new()
.merge(files::file_routes())
.merge(markbase_compat::markbase_routes())
.merge(scan::scan_routes())
.merge(identity_binding::identity_binding_routes())
.merge(identities::identity_routes())
.merge(tmdb_api::tmdb_routes())
.merge(identity_api::identity_routes())
.merge(agent_api::agent_routes())
.merge(agent_search::agent_search_routes())
.merge(processing::processing_routes())
.merge(file_progress::file_progress_routes())
.merge(media_api::bbox_routes())
.merge(media_api::media_proxy_routes())
.merge(media_api::pose_appearance_routes())
.merge(trace_agent_api::trace_agent_routes())
.merge(clip_api::clip_routes())
.merge(search_routes())
.merge(llm_search::llm_smart_routes())
.merge(universal_search_routes())
.merge(pipeline::pipeline_routes())
.merge(checkin_api::checkin_routes())
.merge(cluster_agent::cluster_agent_routes())
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.merge(job_management::job_management_routes())
.merge(service_management::router())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
))
.with_state(state.clone());
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let public_health_routes = Router::new()
.route("/api/v1/health", axum::routing::get(health))
.route(
"/api/v1/health/detailed",
axum::routing::get(health_detailed),
)
.route(
"/api/v1/health/consistency",
axum::routing::get(health_consistency),
)
.route(
"/api/v1/health/queue",
axum::routing::get(health_queue),
)
.route(
"/api/v1/mbe/health",
axum::routing::get(service_management::mbe_health),
);
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(docs::doc_routes())
.merge(monitor::monitor_routes())
.nest_service("/monitor", ServeDir::new("static/monitor"))
.merge(protected_routes)
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.layer(axum::middleware::from_fn(
super::middleware::concurrency_limit,
))
.with_state(state);
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse().unwrap();
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}
+5 -5
View File
@@ -60,13 +60,13 @@ fn svc_def(name: &str) -> Option<(&'static str, u16, Option<&'static str>)> {
"markbase" | "mb" => ("markbase", 11438, Some("com.momentry.markbase")),
"mbe" | "markbaseengine" | "vlm" => ("mbe", 8082, Some("com.momentry.llm")), // MBE = markbaseengine service; spawns VLM llama-server (8082)
"chat" | "llama" => ("chat", 8080, Some("com.momentry.chat-llamacpp")), // Chat llama-server instance (8080)
"embedding" => ("embedding", 11437, Some("com.momentry.embedding-gguf")),
"embedding" => ("embedding", 11436, Some("com.momentry.embedding-gguf")),
"proxy" => ("proxy", 8888, Some("com.momentry.proxy")),
"worker" => ("worker", 0, Some("com.momentry.worker")),
"postgres" | "postgresql" | "pg" => ("postgres", 5432, Some("com.momentry.postgresql")),
// NOTE: the redis actually serving 127.0.0.1:6379 is brew-services' launchd agent,
// not com.momentry.redis (which can't bind while brew's owns the port).
"redis" => ("redis", 6379, Some("sh.brew.redis")),
"redis" => ("redis", 6379, Some("com.momentry.redis")),
"qdrant" => ("qdrant", 6333, Some("com.momentry.qdrant")),
_ => return None,
};
@@ -1102,10 +1102,10 @@ pub async fn test_embedding(
.unwrap_or_else(|_| "http://localhost:11436".to_string());
// Detect server type from URL port
let server_type = if url.contains("11437") {
let server_type = if url.contains("11436") {
"llama.cpp GGUF Q8"
} else if url.contains("11436") {
"Python Flask (safetensors fp32)"
} else if url.contains("11437") {
"llama.cpp GGUF Q8 (alt)"
} else {
"unknown"
};
+19 -5
View File
@@ -237,7 +237,7 @@ async fn list_traces_sorted(
entry.best_bbox = bbox;
} else {
// 如果 Qdrant 沒有,從 trace_profile.json 讀取
if let Some(profile) = read_trace_profile(&file_uuid, trace_id) {
if let Some(profile) = read_trace_profile(state.db.pool(), &file_uuid, trace_id).await {
entry.best_bbox = profile.get("best_bbox").cloned();
}
}
@@ -252,7 +252,7 @@ async fn list_traces_sorted(
entry.best_capture_bbox = bbox;
} else {
// 如果 Qdrant 沒有,從 trace_profile.json 讀取
if let Some(profile) = read_trace_profile(&file_uuid, trace_id) {
if let Some(profile) = read_trace_profile(state.db.pool(), &file_uuid, trace_id).await {
entry.best_capture_bbox = profile.get("best_bbox").cloned();
}
}
@@ -2805,9 +2805,23 @@ fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize {
}
/// Read trace_profile.json for a given file_uuid and trace_id.
fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Value> {
/// Tries per-library output dir first, falls back to global OUTPUT_DIR.
async fn read_trace_profile(pool: &sqlx::PgPool, file_uuid: &str, trace_id: i32) -> Option<serde_json::Value> {
use std::path::PathBuf;
// Try per-library output dir first
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, pool).await;
let candidate: PathBuf = PathBuf::from(&per_lib)
.join(file_uuid)
.join(format!("trace_{}", trace_id))
.join("trace_profile.json");
if let Ok(content) = std::fs::read_to_string(&candidate) {
if let Ok(profile) = serde_json::from_str::<serde_json::Value>(&content) {
return Some(profile);
}
}
// Fallback: global OUTPUT_DIR (legacy)
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let profile_path: PathBuf = [
output_dir,
@@ -2817,7 +2831,6 @@ fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Valu
]
.iter()
.collect();
if let Ok(content) = std::fs::read_to_string(&profile_path) {
if let Ok(profile) = serde_json::from_str::<serde_json::Value>(&content) {
return Some(profile);
@@ -2829,6 +2842,7 @@ fn read_trace_profile(file_uuid: &str, trace_id: i32) -> Option<serde_json::Valu
/// GET /api/v1/trace-profile-file?file_uuid=...&trace_id=...
/// Returns the trace_profile.json for a given file and trace.
async fn get_trace_profile_file(
State(state): State<crate::api::types::AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> impl IntoResponse {
let file_uuid = match params.get("file_uuid") {
@@ -2840,7 +2854,7 @@ async fn get_trace_profile_file(
None => return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error": "Missing or invalid trace_id"}))),
};
match read_trace_profile(&file_uuid, trace_id) {
match read_trace_profile(state.db.pool(), &file_uuid, trace_id).await {
Some(profile) => (StatusCode::OK, Json(profile)),
None => {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
+166 -3
View File
@@ -146,8 +146,21 @@ async fn unregister_file_from_system(
// 1. Delete from Qdrant (best effort)
// TODO: Implement Qdrant deletion
// 2. Delete output files
delete_output_files(uuid, output_dir);
// 2. Delete output files (all libraries: per-library + global + all upload_paths)
delete_output_files(uuid, output_dir).await;
let per_lib = crate::core::config::get_output_dir_for_file(uuid, pool).await;
if !per_lib.is_empty() && per_lib != output_dir {
delete_output_files(uuid, &per_lib).await;
}
if let Ok(rows) = sqlx::query_scalar::<_, String>(
"SELECT output_path FROM upload_paths WHERE enabled = true AND output_path IS NOT NULL"
).fetch_all(pool).await {
for dir in rows {
if !dir.is_empty() && dir != output_dir && dir != per_lib {
delete_output_files(uuid, &dir).await;
}
}
}
// 3. Delete original video (if not keeping)
if !keep_video {
@@ -218,7 +231,7 @@ async fn unregister_file_from_system(
Ok(deleted)
}
fn delete_output_files(uuid: &str, output_dir: &str) {
async fn delete_output_files(uuid: &str, output_dir: &str) {
let dir = std::path::PathBuf::from(output_dir);
// Delete JSON files: {uuid}.*.json
@@ -240,9 +253,159 @@ fn delete_output_files(uuid: &str, output_dir: &str) {
}
}
// ─── Delete API (true delete, not unregister) ────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct DeleteUnregisteredRequest {
pub path: String,
}
#[derive(Debug, Serialize)]
pub struct DeleteUnregisteredResponse {
pub success: bool,
pub deleted_file: bool,
pub deleted_db: bool,
pub file_uuid: Option<String>,
pub message: String,
}
/// Resolve the rust_unregister binary the same way files.rs unregister does.
fn resolve_rust_unregister_binary() -> std::path::PathBuf {
std::env::var_os("MOMENTRY_RUST_UNREGISTER")
.map(std::path::PathBuf::from)
.filter(|p| p.is_file())
.or_else(|| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("rust_unregister")))
.filter(|p| p.is_file())
})
.unwrap_or_else(|| std::path::PathBuf::from("target/release/rust_unregister"))
}
/// Storage root for path validation (prevent arbitrary file deletion).
fn storage_roots() -> Vec<std::path::PathBuf> {
let home = std::env::var("HOME").unwrap_or_default();
let mut roots = vec![];
if let Ok(r) = std::env::var("MOMENTRY_STORAGE_ROOT") {
roots.push(std::path::PathBuf::from(r));
}
roots.push(std::path::PathBuf::from(format!(
"{}/momentry/var/sftpgo/data",
home
)));
roots
}
/// POST /api/v1/file/delete-unregistered
/// Permanently delete an unregistered/leftover entry:
/// - disk file (if still present)
/// - videos row + all related records + outputs + Qdrant + Redis (via rust_unregister)
pub async fn delete_unregistered_handler(
State(_state): State<AppState>,
Json(req): Json<DeleteUnregisteredRequest>,
) -> Result<Json<DeleteUnregisteredResponse>, (StatusCode, Json<serde_json::Value>)> {
let path = std::path::PathBuf::from(&req.path);
// Security: only allow deletion inside the storage roots
let canonical = path
.canonicalize()
.unwrap_or_else(|_| std::path::PathBuf::from(&req.path));
let allowed = storage_roots()
.iter()
.filter_map(|r| r.canonicalize().ok())
.any(|r| canonical.starts_with(&r));
if !allowed {
return Err((
StatusCode::FORBIDDEN,
Json(serde_json::json!({
"error": "Path is outside the storage root",
"path": req.path
})),
));
}
// 1. Delete disk file (if still present)
let mut deleted_file = false;
if canonical.exists() {
match std::fs::remove_file(&canonical) {
Ok(()) => {
deleted_file = true;
tracing::info!("[DELETE] Removed file: {}", canonical.display());
}
Err(e) => {
tracing::warn!("[DELETE] Failed to remove file {}: {}", canonical.display(), e);
}
}
}
// 2. Find a leftover DB row by file_path → full cleanup via rust_unregister
let uuid: Option<String> = sqlx::query_scalar("SELECT file_uuid FROM videos WHERE file_path = $1")
.bind(&req.path)
.fetch_optional(_state.db.pool())
.await
.ok()
.flatten();
let mut deleted_db = false;
if let Some(ref uuid) = uuid {
let binary_path = resolve_rust_unregister_binary();
if !binary_path.is_file() {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("rust_unregister binary not found at {:?}", binary_path)
})),
));
}
let output = std::process::Command::new(&binary_path)
.args(["--uuid", &uuid])
.output()
.map_err(|e| {
tracing::error!("[DELETE] Failed to execute rust_unregister: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("rust_unregister failed: {}", e)})),
)
})?;
if output.status.success() {
deleted_db = true;
tracing::info!("[DELETE] rust_unregister cleaned DB/Qdrant/Redis for {}", uuid);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!("[DELETE] rust_unregister failed for {}: {}", uuid, stderr);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("rust_unregister exit {:?}: {}", output.status.code(), stderr.trim())
})),
));
}
}
let message = match (deleted_file, deleted_db) {
(true, true) => "File and database records deleted".to_string(),
(true, false) => "File deleted".to_string(),
(false, true) => "Database records deleted".to_string(),
(false, false) => "Nothing to delete (entry not found)".to_string(),
};
Ok(Json(DeleteUnregisteredResponse {
success: true,
deleted_file,
deleted_db,
file_uuid: uuid,
message,
}))
}
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn unregister_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/file/:uuid/unregister", post(unregister_file_handler))
.route(
"/api/v1/file/delete-unregistered",
post(delete_unregistered_handler),
)
}
+87
View File
@@ -66,12 +66,15 @@ pub struct UpdateUploadPathRequest {
// ── Routes ──────────────────────────────────────────────────────────
pub fn upload_path_routes() -> Router<AppState> {
use axum::routing::post;
Router::new()
.route("/api/v1/admin/upload-paths", get(list_upload_paths))
.route("/api/v1/admin/upload-paths", post(create_upload_path))
.route("/api/v1/admin/upload-paths/:id", get(get_upload_path))
.route("/api/v1/admin/upload-paths/:id", put(update_upload_path))
.route("/api/v1/admin/upload-paths/:id", delete(delete_upload_path))
.route("/api/v2/settings", post(save_legacy_settings))
.route("/api/v2/settings/validate", post(validate_legacy_settings))
}
// ── Handlers ────────────────────────────────────────────────────────
@@ -253,3 +256,87 @@ async fn delete_upload_path(
info!("[upload_paths] deleted id={}", id);
Ok(Json(serde_json::json!({"success": true})))
}
// ── Legacy settings compatibility (/api/v2/settings) ─────────────────
#[derive(Debug, Deserialize)]
struct LegacySettingsRequest {
server: Option<LegacyServerSettings>,
}
#[derive(Debug, Deserialize)]
struct LegacyServerSettings {
upload_path: Option<String>,
}
/// POST /api/v2/settings — legacy compatibility for admin upload path
pub async fn save_legacy_settings(
State(state): State<AppState>,
Json(req): Json<LegacySettingsRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let upload_path = req.server.and_then(|s| s.upload_path).unwrap_or_default();
if upload_path.is_empty() {
return Ok(Json(serde_json::json!({
"success": false,
"error": "upload_path is required"
})));
}
let pool = state.db.pool();
let name = std::path::Path::new(&upload_path)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| upload_path.replace('/', "_"));
// Check if already exists
let existing: Option<i32> = sqlx::query_scalar(
"SELECT id FROM upload_paths WHERE full_path = $1"
)
.bind(&upload_path)
.fetch_optional(pool)
.await
.map_err(|e| {
error!("[settings] query failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
if let Some(id) = existing {
let _ = sqlx::query("UPDATE upload_paths SET enabled = true, updated_at = NOW() WHERE id = $1")
.bind(id)
.execute(pool)
.await;
} else {
let output_path = format!("/Users/accusys/momentry/output/{}", name);
let _ = sqlx::query(
"INSERT INTO upload_paths (name, base_path, sub_path, full_path, output_path, enabled)
VALUES ($1, $2, '', $3, $4, true) ON CONFLICT (name) DO UPDATE SET enabled = true, updated_at = NOW()"
)
.bind(&name)
.bind(&upload_path)
.bind(&upload_path)
.bind(&output_path)
.execute(pool)
.await;
}
info!("[settings] saved upload_path: {}", upload_path);
Ok(Json(serde_json::json!({
"success": true,
"message": "Upload path saved successfully"
})))
}
/// POST /api/v2/settings/validate — always valid (no restrictions)
pub async fn validate_legacy_settings(
Json(req): Json<LegacySettingsRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let upload_path = req.server.and_then(|s| s.upload_path).unwrap_or_default();
Ok(Json(serde_json::json!({
"success": true,
"valid": true,
"message": format!("Path is valid: {}", upload_path),
"details": {
"absolute_path": upload_path
}
})))
}
+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
+12 -2
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
@@ -3976,8 +3980,14 @@ pub async fn get_session_by_id(
"processor": processor,
"status": status,
});
let path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("pipeline_{}.log", uuid));
// Pipeline timeline logs go to the output ROOT (parent of per-library dir).
// OUTPUT_DIR may be a per-library dir like output/demo — strip it to output/.
let output_root = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str())
.parent()
.filter(|p| p.file_name().and_then(|n| n.to_str()) == Some("output"))
.map(|p| p.to_path_buf())
.unwrap_or_else(|| std::path::PathBuf::from(crate::core::config::OUTPUT_DIR.as_str()));
let path = output_root.join(format!("pipeline_{}.log", uuid));
if let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
+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)]
+27 -2
View File
@@ -126,14 +126,39 @@ pub fn create_meta(
/// 建立 _debug 區塊
pub fn create_debug(path: &Path) -> DebugFooter {
// 從實際路徑推導 output_dir(取父目錄或上兩層)
let output_dir = if let Some(parent) = path.parent() {
// 如果路徑是 /output/test/uuid/trace_N/trace_profile.json → /output/test
// 如果路徑是 /output/test/uuid.face.json → /output/test
let path_str = parent.to_string_lossy();
if path_str.contains("/output/") {
// 找出 /output/ 之後的 library 目錄
if let Some(pos) = path_str.find("/output/") {
let after_output = &path_str[pos + 8..]; // skip "/output/"
if let Some(first_slash) = after_output.find('/') {
path_str[..pos + 8 + first_slash].to_string()
} else {
// 沒有更多層級,就用整個 parent
parent.to_string_lossy().to_string()
}
} else {
parent.to_string_lossy().to_string()
}
} else {
parent.to_string_lossy().to_string()
}
} else {
std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "output".to_string())
};
DebugFooter {
absolute_path: absolute_path_string(path),
written_at_unix: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
output_dir: std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "output/demo".to_string()),
output_dir,
}
}
+1
View File
@@ -45,3 +45,4 @@ pub mod vlm;
pub mod json_debug;
pub mod json_standardize;
pub mod rerun_backup;
+1 -3
View File
@@ -73,9 +73,7 @@ pub fn demo_dir() -> PathBuf {
/// Get scripts directory
pub fn scripts_dir() -> PathBuf {
env::var("MOMENTRY_SCRIPTS_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| momentry_core_dir().join("tools/script"))
resolve_asset_path("MOMENTRY_SCRIPTS_DIR", "scripts")
}
/// Get CLI tools directory
+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
}
+29 -6
View File
@@ -157,6 +157,29 @@ pub struct PythonExecutor {
}
impl PythonExecutor {
/// Determine the correct output directory for a processor execution.
/// Uses MOMENTRY_OUTPUT_DIR env var if set, otherwise derives from output_path
/// or falls back to the global OUTPUT_DIR.
fn resolve_output_dir(&self, uuid: Option<&str>, output_path: Option<&std::path::PathBuf>) -> String {
// Priority: env var > derived from output_path > global OUTPUT_DIR
if let Ok(dir) = std::env::var("MOMENTRY_OUTPUT_DIR") {
return dir;
}
if let Some(path) = output_path {
if let Some(parent) = path.parent() {
return parent.to_string_lossy().to_string();
}
}
// Fallback: use uuid to look up per-library dir (sync call)
if let Some(u) = uuid {
// Try to derive from known patterns
if let Ok(dir) = std::env::var("MOMENTRY_OUTPUT_DIR_PER_LIB") {
return dir;
}
}
OUTPUT_DIR.to_string()
}
pub fn new() -> Result<Self> {
let python_path = std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string());
@@ -335,7 +358,7 @@ impl PythonExecutor {
let mut cmd = Command::new(&self.python_path);
cmd.env("PYTHONPATH", &self.scripts_dir);
cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
@@ -507,7 +530,7 @@ impl PythonExecutor {
let mut cmd = Command::new(&self.python_path);
cmd.env("PYTHONPATH", &self.scripts_dir);
cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
@@ -723,7 +746,7 @@ impl PythonExecutor {
let mut cmd = Command::new(&self.python_path);
cmd.env("PYTHONPATH", &self.scripts_dir);
cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
@@ -947,7 +970,7 @@ impl PythonExecutor {
let mut cmd = Command::new(&self.python_path);
cmd.env("PYTHONPATH", &self.scripts_dir);
cmd.env("PATH", "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
@@ -1249,7 +1272,7 @@ impl PythonExecutor {
});
let mut cmd = Command::new(bin_path);
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
@@ -1475,7 +1498,7 @@ mod tests {
let executor = PythonExecutor::new().unwrap();
let mut cmd = Command::new(&executor.python_path);
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("MOMENTRY_OUTPUT_DIR", self.resolve_output_dir(uuid, output_path.as_ref()));
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
+59 -13
View File
@@ -8,6 +8,24 @@ use super::FaceStatus;
const FACE_TIMEOUT: Duration = Duration::from_secs(7200);
/// Resolve the FaceNet512 CoreML model path.
/// Priority: $MOMENTRY_MODELS_DIR/facenet512.mlpackage -> momentry_core/models/facenet512.mlpackage
pub fn facenet_model_path() -> Option<std::path::PathBuf> {
use std::path::PathBuf;
let env_dir = std::env::var("MOMENTRY_MODELS_DIR")
.ok()
.map(PathBuf::from);
let candidates = [
env_dir.map(|d| d.join("facenet512.mlpackage")),
Some(
crate::core::path_utils::momentry_core_dir()
.join("models")
.join("facenet512.mlpackage"),
),
];
candidates.into_iter().flatten().find(|p| p.exists())
}
pub fn swift_processor_path(bin: &str) -> std::path::PathBuf {
use std::path::PathBuf;
let rel = format!(".build/release/{}", bin);
@@ -98,6 +116,19 @@ impl FaceResult {
self.metadata = Some(metadata);
}
/// Generate face_id for faces that don't have one.
/// Format: face_{frame}_{index_within_frame}
pub fn ensure_face_ids(&mut self) {
for frame in &mut self.frames {
let frame_num = frame.frame;
for (idx, face) in frame.faces.iter_mut().enumerate() {
if face.face_id.is_none() {
face.face_id = Some(format!("face_{}_{}", frame_num, idx));
}
}
}
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
self.save_to_file_with_source(path, None, None)
}
@@ -263,6 +294,7 @@ pub async fn process_face(
result.compute_status();
result.add_metadata("face", "swift_face", uuid);
result.ensure_face_ids();
result.save_to_file(output_path)?;
tracing::info!(
@@ -323,16 +355,14 @@ pub async fn process_face(
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
// Resolve model path
let models_dir =
crate::core::path_utils::resolve_asset_path("MOMENTRY_MODELS_DIR", "models");
let model_path = models_dir.join("facenet512.mlpackage");
if !model_path.exists() {
tracing::error!("[FACE] FaceNet model not found at {:?}", model_path);
tracing::error!("[FACE] Set MOMENTRY_MODELS_DIR environment variable or ensure models/facenet512.mlpackage exists");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
// Resolve model path (env dir -> momentry_core/models fallback)
let model_path = match facenet_model_path() {
Some(p) => p,
None => {
tracing::error!("[FACE] FaceNet model not found (checked $MOMENTRY_MODELS_DIR and momentry_core/models)");
anyhow::bail!("FaceNet model not found - cannot generate embeddings");
}
};
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
@@ -415,6 +445,7 @@ pub async fn process_face(
tracing::info!("[FACE] Face tracking completed successfully");
}
result.ensure_face_ids();
result.save_to_file(output_path)?;
tracing::info!(
@@ -470,6 +501,7 @@ pub async fn process_face(
tracing::info!("[FACE] Face tracking completed successfully");
}
result.ensure_face_ids();
result.save_to_file(output_path)?;
tracing::info!(
@@ -544,16 +576,22 @@ async fn run_face_with_config(
// Generate embeddings with FaceNet CoreML
let facenet_path = swift_processor_path("facenet_embedding");
let facenet_output = format!("{}.with_embedding", output_path);
if facenet_path.exists() {
tracing::info!("[FACE] Generating embeddings with FaceNet CoreML");
let facenet_output = format!("{}.with_embedding", output_path);
let facenet_args = vec![
let mut facenet_args = vec![
video_path.to_string(),
output_path.to_string(),
facenet_output.clone(),
];
// Explicit --model (the binary otherwise derives the path from
// MOMENTRY_MODELS_DIR, which may not contain facenet512)
if let Some(model_path) = facenet_model_path() {
facenet_args.push("--model".to_string());
facenet_args.push(model_path.to_string_lossy().to_string());
}
let facenet_result = tokio::process::Command::new(facenet_path)
.args(&facenet_args)
@@ -576,12 +614,19 @@ async fn run_face_with_config(
}
}
let json_str = std::fs::read_to_string(output_path)
// Read face.json (prefer .with_embedding if copy failed)
let json_path = if std::path::Path::new(&facenet_output).exists() {
&facenet_output
} else {
output_path
};
let json_str = std::fs::read_to_string(json_path)
.context("Failed to read Swift FACE output")?;
let mut result: FaceResult =
serde_json::from_str(&json_str).context("Failed to parse Swift FACE output")?;
result.compute_status();
result.add_metadata("face", "swift_face", uuid);
result.ensure_face_ids();
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
@@ -625,6 +670,7 @@ async fn run_face_with_config(
.context("Failed to parse Python FACE output")?;
result.compute_status();
result.add_metadata("face", "python_face_processor", uuid);
result.ensure_face_ids();
result.save_to_file(output_path)?;
if let Some(uid) = uuid {
+5 -2
View File
@@ -159,11 +159,14 @@ pub async fn process_face_cluster(
similarity_threshold: Option<f64>,
) -> Result<FaceClusterResult> {
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("fast_face_clustering_processor.py");
tracing::info!("[FACE_CLUSTER] Starting face clustering: {}", video_path);
if !script_path.exists() {
// Try Rust binary first (preferred); legacy Python script is only a fallback.
// Do NOT bail early just because the Python script is missing — that would
// skip the Rust binary even when it exists.
let script_path = executor.script_path("fast_face_clustering_processor.py");
if executor.rust_binary_path("rust_face_cluster").is_none() && !script_path.exists() {
tracing::warn!("[FACE_CLUSTER] Script not found, returning empty result");
return Ok(FaceClusterResult {
schema_version: "2.0".to_string(),
+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"
);
@@ -0,0 +1,859 @@
use anyhow::{Context, Result};
use futures_util::future::join_all;
use std::collections::HashMap;
use std::path::Path;
use tokio::process::Command;
use crate::core::file_profile::{
EmbeddingStatus, SceneConfig, SceneFrame, SceneInfo, SceneProfile, SceneStatus,
SelectionReason, VideoInfo, VlmStatus, VlmTag, VlmTagValue,
};
pub struct SceneVlmProcessor {
samples_per_interval: usize,
use_cuts: bool,
max_workers: usize,
}
impl SceneVlmProcessor {
pub fn new(samples_per_interval: usize, use_cuts: bool, max_workers: usize) -> Self {
Self {
samples_per_interval,
use_cuts,
max_workers,
}
}
pub fn compute_sample_frames(
interval_start_sec: f64,
interval_sec: f64,
fps: f64,
samples: usize,
) -> Vec<u32> {
if samples == 0 {
return vec![];
}
let sample_interval = interval_sec / samples as f64;
let frames: Vec<u32> = (0..samples)
.map(|i| {
let time = interval_start_sec + (i as f64 + 0.5) * sample_interval;
(time * fps).round() as u32
})
.collect();
// Ensure at least frame 0 is included for short videos
if frames.is_empty() || frames.iter().all(|&f| f > 0) {
let mut result = vec![0u32];
result.extend(frames.into_iter().filter(|&f| f > 0));
result
} else {
frames
}
}
pub async fn calculate_blur_single(video_path: &str, frame: u32, fps: f64) -> Result<f64> {
let time_sec = frame as f64 / fps;
let output = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-vf",
"blurdetect",
"-f",
"null",
"-",
])
.output()
.await
.context("FFmpeg blurdetect failed")?;
let stderr = String::from_utf8_lossy(&output.stderr);
for line in stderr.lines() {
if let Some(blur_str) = line.split("blur mean: ").nth(1) {
if let Ok(blur) = blur_str.trim().parse::<f64>() {
return Ok(blur);
}
}
}
Ok(f64::NAN)
}
pub async fn calculate_blur_parallel(
video_path: &str,
frames: &[u32],
fps: f64,
max_workers: usize,
) -> Result<Vec<(u32, f64)>> {
let tasks: Vec<_> = frames
.iter()
.map(|frame| Self::calculate_blur_single(video_path, *frame, fps))
.collect();
let results = join_all(tasks).await;
let mut combined = Vec::new();
for (frame, result) in frames.iter().zip(results.into_iter()) {
if let Ok(blur) = result {
combined.push((*frame, blur));
} else {
combined.push((*frame, f64::NAN));
}
}
Ok(combined)
}
pub fn select_best_frame(blur_scores: &[(u32, f64)]) -> Option<(u32, f64)> {
blur_scores
.iter()
.filter(|(_, blur)| !blur.is_nan())
.min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(frame, blur)| (*frame, *blur))
}
pub fn find_cuts_in_interval(
interval_start: f64,
interval_end: f64,
cut_data: &serde_json::Value,
) -> Vec<serde_json::Value> {
let mut cuts = Vec::new();
if let Some(scenes) = cut_data.get("scenes").and_then(|s| s.as_array()) {
for scene in scenes {
if let Some(start_time) = scene.get("start_time").and_then(|t| t.as_f64()) {
if start_time > interval_start && start_time < interval_end {
cuts.push(scene.clone());
}
}
}
}
cuts
}
pub async fn process_interval(
video_path: &str,
interval_start: f64,
interval_sec: f64,
fps: f64,
cut_data: &serde_json::Value,
samples_per_interval: usize,
max_workers: usize,
) -> Result<Vec<SceneFrame>> {
let sample_frames =
Self::compute_sample_frames(interval_start, interval_sec, fps, samples_per_interval);
let blur_scores =
Self::calculate_blur_parallel(video_path, &sample_frames, fps, max_workers).await?;
let cuts =
Self::find_cuts_in_interval(interval_start, interval_start + interval_sec, cut_data);
let mut selected_frames = Vec::new();
if cuts.is_empty() {
if let Some((frame, blur)) = Self::select_best_frame(&blur_scores) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::BestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
} else if let Some(&frame) = sample_frames.first() {
// Fallback: use first sample frame when blur detection yields no scores
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", 0),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::Default,
quality_score: None,
quality_source: None,
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: false,
cut_count: 0,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
} else {
let cut = &cuts[0];
let cut_time = cut
.get("start_time")
.and_then(|t| t.as_f64())
.unwrap_or(interval_start);
let cut_frame = (cut_time * fps).round() as u32;
let pre_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f < cut_frame)
.cloned()
.collect();
let post_frames: Vec<u32> = sample_frames
.iter()
.filter(|f| **f >= cut_frame)
.cloned()
.collect();
if !pre_frames.is_empty() {
let pre_blur =
Self::calculate_blur_parallel(video_path, &pre_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&pre_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PreCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
if !post_frames.is_empty() {
let post_blur =
Self::calculate_blur_parallel(video_path, &post_frames, fps, max_workers)
.await?;
if let Some((frame, blur)) = Self::select_best_frame(&post_blur) {
let timestamp = frame as f64 / fps;
selected_frames.push(SceneFrame {
index: 0,
filename: format!("scene_{:03}.jpg", selected_frames.len()),
timestamp_sec: timestamp,
frame_number: frame,
selection_reason: SelectionReason::PostCutBestBlur,
quality_score: Some(blur),
quality_source: Some("ffmpeg_blurdetect".to_string()),
scene_info: None,
face_count: 0,
person_traces: Vec::new(),
has_cut: true,
cut_count: cuts.len() as u32,
vlm_status: VlmStatus::Pending,
vlm_description: None,
vlm_description_localized: None,
vlm_scene_type: None,
vlm_location: None,
vlm_objects: Vec::new(),
vlm_attributes: None,
vlm_tags: Vec::new(),
embedding_status: EmbeddingStatus::Pending,
});
}
}
}
for (i, frame) in selected_frames.iter_mut().enumerate() {
frame.index = i;
}
Ok(selected_frames)
}
pub async fn generate_scene_profile(
&self,
video_path: &str,
file_uuid: &str,
output_dir: &str,
interval_sec: u32,
cut_data: &serde_json::Value,
fps: f64,
duration: f64,
width: u32,
height: u32,
total_frames: u32,
) -> Result<SceneProfile> {
let config = SceneConfig {
interval_sec,
use_cuts: true,
use_faces: false,
quality_metric: "ffmpeg_blurdetect".to_string(),
samples_per_interval: self.samples_per_interval,
};
let video_info = VideoInfo {
duration_sec: duration,
fps,
width,
height,
total_frames,
};
let mut profile = SceneProfile::new(file_uuid, video_info, config);
let mut all_frames = Vec::new();
let total_intervals = (duration / interval_sec as f64).ceil() as usize;
for i in 0..total_intervals {
let interval_start = i as f64 * interval_sec as f64;
let interval_end = (interval_start + interval_sec as f64).min(duration);
let actual_interval_sec = interval_end - interval_start;
let frames = Self::process_interval(
video_path,
interval_start,
actual_interval_sec,
fps,
cut_data,
self.samples_per_interval,
self.max_workers,
)
.await?;
all_frames.extend(frames);
}
// Fix indices
for (i, frame) in all_frames.iter_mut().enumerate() {
frame.index = i;
frame.filename = format!("scene_{:03}.jpg", i);
}
profile.scenes = all_frames;
profile.total_scenes = profile.scenes.len();
profile.status = SceneStatus::Ready;
profile.updated_at = chrono::Utc::now();
Ok(profile)
}
pub fn save_scene_profile(profile: &SceneProfile, output_dir: &str) -> Result<()> {
let path = SceneProfile::scenes_path(output_dir, &profile.file_uuid);
let json =
serde_json::to_string_pretty(profile).context("Failed to serialize SceneProfile")?;
std::fs::write(&path, json).context("Failed to write scenes.json")?;
Ok(())
}
pub fn load_scene_profile(output_dir: &str, file_uuid: &str) -> Result<SceneProfile> {
let path = SceneProfile::scenes_path(output_dir, file_uuid);
let json = std::fs::read_to_string(&path).context("Failed to read scenes.json")?;
let profile: SceneProfile =
serde_json::from_str(&json).context("Failed to parse scenes.json")?;
Ok(profile)
}
pub async fn extract_scene_frames(
video_path: &str,
output_dir: &str,
file_uuid: &str,
scenes: &[SceneFrame],
) -> Result<Vec<std::path::PathBuf>> {
let scenes_dir = SceneProfile::scenes_dir(output_dir, file_uuid);
std::fs::create_dir_all(&scenes_dir).context("Failed to create scenes directory")?;
let mut extracted_paths = Vec::new();
for scene in scenes {
let output_path =
SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
let time_sec = scene.timestamp_sec;
let status = Command::new("/opt/homebrew/bin/ffmpeg")
.args([
"-y",
"-ss",
&format!("{:.2}", time_sec),
"-i",
video_path,
"-vframes",
"1",
"-q:v",
"5",
&output_path.to_string_lossy(),
])
.status()
.await
.context("FFmpeg frame extraction failed")?;
if status.success() && output_path.exists() {
extracted_paths.push(output_path);
}
}
Ok(extracted_paths)
}
/// Helper function to extract scene info from parsed JSON
fn extract_scene_info(
parsed: &serde_json::Value,
fallback: &str,
) -> (String, Vec<String>, Vec<String>) {
let desc = parsed
.get("description")
.and_then(|d| d.as_str())
.unwrap_or(fallback)
.to_string();
let objs = parsed
.get("objects")
.and_then(|o| o.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tgs = parsed
.get("tags")
.and_then(|t| t.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
(desc, objs, tgs)
}
/// Extract objects from text (simple keyword matching)
fn extract_objects_from_text(text: &str) -> Vec<String> {
let keywords = [
"river", "tree", "forest", "mountain", "building", "person", "text", "water", "sky",
"cloud", "road", "car", "house", "flower", "grass", "rock", "bridge", "boat", "animal",
"bird",
];
keywords
.iter()
.filter(|&k| text.to_lowercase().contains(k))
.map(|k| k.to_string())
.collect()
}
/// Extract tags from text (category inference)
fn extract_tags_from_text(text: &str) -> Vec<String> {
let mut tags = vec![];
let lower = text.to_lowercase();
if lower.contains("landscape") || lower.contains("nature") {
tags.push("nature".to_string());
}
if lower.contains("indoor") || lower.contains("room") {
tags.push("indoor".to_string());
}
if lower.contains("outdoor") {
tags.push("outdoor".to_string());
}
if lower.contains("presentation") || lower.contains("slide") {
tags.push("presentation".to_string());
}
if lower.contains("text") || lower.contains("title") {
tags.push("text".to_string());
}
if lower.contains("water") || lower.contains("river") {
tags.push("water".to_string());
}
tags
}
fn language_display_name(language: &str) -> &'static str {
match language {
"zh-TW" => "Traditional Chinese (zh-TW)",
"zh-CN" => "Simplified Chinese (zh-CN)",
"ja" => "Japanese (ja)",
"ko" => "Korean (ko)",
"es" => "Spanish (es)",
"fr" => "French (fr)",
"de" => "German (de)",
_ => "English (en)",
}
}
/// Build the structured scene analysis prompt.
fn build_scene_prompt(local_language: &str) -> String {
let local_name = Self::language_display_name(local_language);
format!(
r#"You are an expert visual analyst for a multimodal video search system.
Analyze the attached image frame and return ONLY valid JSON with NO markdown, NO explanations, NO reasoning, NO thinking.
Use this exact schema:
{{
"summary": "Concise English summary of the core content (1-2 sentences). Factual, avoid superlatives like beautiful/stunning/amazing.",
"category": "Single highest-level category. Choose ONE from: landscape|architecture|interior|people|event|nature|urban|transport|food|animal|product|other",
"scene_type": "Environment/background. Choose ONE from: indoor|outdoor|city street|resort|nature|mountain|beach|forest|building exterior|building interior|road|park|unknown",
"objects": ["3-5 most prominent objects or subjects in English. Concrete and specific."],
"actions": ["Main actions/events or static state if no motion. Use English (e.g. 'static scene', 'driving', 'walking')."],
"visual_attributes": {{
"lighting": "e.g. natural daylight, golden hour, overcast, artificial, backlit, mixed lighting",
"composition": "e.g. aerial view, wide angle, eye level, low angle, close-up, drone shot, street level",
"color_palette": ["3-5 dominant colors in English (e.g. gray, green, blue, orange)"]
}},
"detected_text": ["Exact visible signs, logos, plaques, or printed text. Only if legible. Empty array if none."],
"tags": [
{{"en": "english_tag", "local": "localized_tag"}}
]
}}
Rules:
- summary must be English only
- objects, actions, visual_attributes must use concrete English terms. Avoid generic words like "photo", "image", "view", "scene"
- tags: 5-10 items. Each item MUST be an object with both "en" and "local" keys
- Use {local_name} for "local". If the preferred language is English, set "local" equal to "en" but keep both keys
- Prioritize search-relevant terms (environment type, key structures/objects). Do NOT just copy the full summary into tags
- Do NOT duplicate objects 1:1 unless genuinely useful as search tags
- Keep tags concise (1-3 words). Avoid redundancy between tags
- detected_text: only extract text actually visible, do not guess or infer
- Output ONLY the JSON object"#
)
}
/// Extract the first JSON object from a VLM response (tolerates markdown fences).
fn extract_json_object(content: &str) -> Option<&str> {
let start = content.find('{')?;
let end = content.rfind('}')?;
if end <= start {
return None;
}
Some(&content[start..=end])
}
fn parse_tags(value: Option<&serde_json::Value>) -> Vec<VlmTagValue> {
let Some(arr) = value.and_then(|v| v.as_array()) else {
return Vec::new();
};
arr.iter()
.filter_map(|tag| {
if let Some(en) = tag.get("en").and_then(|v| v.as_str()) {
let local = tag
.get("local")
.and_then(|v| v.as_str())
.unwrap_or(en)
.to_string();
Some(VlmTagValue::Structured(VlmTag {
en: en.to_string(),
local,
}))
} else {
tag.as_str().map(|s| VlmTagValue::String(s.to_string()))
}
})
.collect()
}
/// Call VLM API to generate structured scene info.
/// Returns (english_description, objects, bilingual_tags).
pub async fn generate_scene_description(
image_path: &std::path::Path,
local_language: &str,
) -> Result<(String, Vec<String>, Vec<VlmTagValue>)> {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use std::time::Duration;
// Read image
let jpeg_bytes = std::fs::read(image_path)
.with_context(|| format!("Failed to read image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
// VLM API config
let vlm_url = crate::core::config::llm::VISION_URL.clone();
let vlm_model = crate::core::config::llm::VISION_MODEL.clone();
let prompt = Self::build_scene_prompt(local_language);
tracing::debug!(
"[VLM API] Calling {} with model {} (local language: {})",
vlm_url,
vlm_model,
local_language
);
let body = serde_json::json!({
"model": vlm_model,
"messages": [{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
},
{
"type": "image_url",
"image_url": {
"url": format!("data:image/jpeg;base64,{}", base64_img)
}
}
]
}],
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(120))
.build()
.context("Failed to create HTTP client")?;
let resp = client
.post(&vlm_url)
.json(&body)
.send()
.await
.context("VLM API request failed")?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("VLM API returned {}: {}", status, body);
}
let resp_json: serde_json::Value = resp
.json()
.await
.context("Failed to parse VLM API response")?;
// Parse response
let choice = resp_json
.get("choices")
.and_then(|c| c.get(0))
.context("Invalid VLM API response structure")?;
if choice.get("finish_reason").and_then(|v| v.as_str()) == Some("length") {
anyhow::bail!("VLM returned truncated response (finish_reason=length)");
}
let message = choice.get("message").context("Invalid VLM API response structure")?;
let content = match message
.get("content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => s.trim().to_string(),
None => anyhow::bail!("VLM returned empty content"),
};
tracing::debug!(
"[Scene VLM] VLM response content (first 500 chars): {}",
&content[..content.len().min(500)]
);
// Parse structured JSON; fall back to heuristic extraction if it fails.
if let Some(json_str) = Self::extract_json_object(&content) {
tracing::debug!("[Scene VLM] Extracted JSON object ({} chars)", json_str.len());
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(json_str) {
tracing::debug!("[Scene VLM] Successfully parsed JSON");
let description = parsed
.get("summary")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if let Some(description) = description {
let objects = parsed
.get("objects")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let tags = Self::parse_tags(parsed.get("tags"));
tracing::info!(
"[Scene VLM] Parsed {} objects, {} tags from JSON",
objects.len(),
tags.len()
);
return Ok((description, objects, tags));
} else {
tracing::warn!("[Scene VLM] JSON missing 'summary' field or summary is empty");
}
} else {
tracing::warn!("[Scene VLM] Failed to parse extracted JSON: {}", json_str);
}
} else {
tracing::warn!("[Scene VLM] Failed to extract JSON object from VLM response");
}
tracing::warn!(
"[Scene VLM] Failed to parse structured JSON, falling back to text heuristics"
);
let objects = Self::extract_objects_from_text(&content);
let tags = Self::extract_tags_from_text(&content)
.into_iter()
.map(VlmTagValue::String)
.collect();
Ok((content, objects, tags))
}
/// Generate VLM descriptions for all scene frames
pub async fn generate_vlm_descriptions(
output_dir: &str,
file_uuid: &str,
scenes: &mut [SceneFrame],
max_workers: usize,
) -> Result<()> {
tracing::info!(
"[Scene VLM] Generating descriptions for {} scenes",
scenes.len()
);
// Get preferred language from admin config
let preferred_language = crate::core::admin_config::ADMIN_CONFIG
.get_full_config()
.await
.search
.vlm_output_language
.clone();
crate::core::config::set_preferred_language(preferred_language.clone());
tracing::info!("[Scene VLM] Preferred language: {}", preferred_language);
// Process scenes sequentially to avoid issues
for (idx, scene) in scenes.iter_mut().enumerate() {
let frame_path = SceneProfile::scene_frame_path(output_dir, file_uuid, &scene.filename);
// Generate English description (for indexing)
match Self::generate_scene_description(&frame_path, &preferred_language).await {
Ok((description_en, objects, tags)) => {
scene.vlm_description = Some(description_en.clone());
scene.vlm_objects = objects.clone();
scene.vlm_tags = tags.clone();
tracing::info!(
"[Scene VLM] Scene {}: Generated {} tags: {:?}",
idx,
tags.len(),
tags
);
// Generate localized description by translation if needed
if preferred_language != "en" {
let system_prompt = "You are a professional translator. Translate accurately. Return ONLY the translated text, no explanations or notes.";
let prompt = format!("Translate the following scene description into {}. Do not summarize, add, or omit any details. Keep the same number of sentences.\n\n{}", preferred_language, description_en);
let body = serde_json::json!({
"model": crate::core::config::llm::CHAT_MODEL.as_str(),
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"stream": false,
"max_tokens": 1024,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
});
let client = reqwest::Client::builder().timeout(std::time::Duration::from_secs(120)).build()?;
match client.post(&*crate::core::config::llm::CHAT_URL).json(&body).send().await {
Ok(resp) => {
if resp.status().is_success() {
if let Ok(v) = resp.json::<serde_json::Value>().await {
if let Some(choice) = v["choices"].get(0) {
if choice.get("finish_reason").and_then(|x| x.as_str()) != Some("length") {
if let Some(tr) = choice["message"]["content"].as_str() {
let tr = tr.trim();
if !tr.is_empty() && !tr.contains("thinking") && !tr.contains("I need to") && !tr.contains("* Task") && !tr.contains("* Scene:") && tr.len() > 10 {
scene.vlm_description_localized = Some(tr.to_string());
tracing::info!("[Scene VLM] ✅ Scene {}: EN + {} (translated)", idx, preferred_language);
scene.vlm_status = VlmStatus::Completed;
continue;
}
}
}
}
}
}
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed", idx);
}
Err(e) => {
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized translation failed: {}", idx, e);
}
}
} else {
tracing::info!("[Scene VLM] ✅ Scene {}: EN only", idx);
}
scene.vlm_status = VlmStatus::Completed;
}
Err(e) => {
tracing::error!("[Scene VLM] ❌ Scene {}: {}", idx, e);
scene.vlm_status = VlmStatus::Failed;
}
}
}
let success_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Completed)
.count();
let fail_count = scenes
.iter()
.filter(|s| s.vlm_status == VlmStatus::Failed)
.count();
tracing::info!(
"[Scene VLM] ✅ Generated {} descriptions, {} failed",
success_count,
fail_count
);
Ok(())
}
}
+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())
}
+342 -52
View File
@@ -335,6 +335,31 @@ impl JobWorker {
error!("Failed to reset stale running jobs: {}", e);
}
// ── Layer 3b: 補遺漏的 monitor_jobs(repair 機制)───────────────────
// Sync mode register 不會建立 monitor_jobs,這裡自動補上
// 只針對 status='pending' 且 file_type 為影片格式的檔案
let monitor_jobs_table = schema::table_name("monitor_jobs");
let videos_table = schema::table_name("videos");
let created = sqlx::query(&format!(
"INSERT INTO {mj_t} (uuid, status, created_at, updated_at)
SELECT v.file_uuid, 'pending', NOW(), NOW()
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)
ON CONFLICT (uuid) DO NOTHING",
mj_t = monitor_jobs_table,
v_t = videos_table
))
.execute(self.db.pool())
.await;
if let Ok(r) = created {
let n = r.rows_affected();
if n > 0 {
info!("[REPAIR] Created {} monitor_jobs for pending videos", n);
}
}
// ── Layer 3c: Job 併發上限(backpressure)─────────────────────────────
// 同時執行 deep scan 的 job 數不得超過上限;超出的 running jobs 自動
// 轉為 paused(video 退回 registered),名額釋出時自動恢復。
@@ -589,7 +614,7 @@ impl JobWorker {
async fn periodic_completeness_check(&self) -> Result<()> {
info!("[COMPLETENESS] Starting periodic output completeness check");
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let global_output_dir = crate::core::config::OUTPUT_DIR.to_string();
let videos_table = schema::table_name("videos");
let rows: Vec<(String, String)> = sqlx::query_as(&format!(
@@ -606,18 +631,31 @@ impl JobWorker {
for (uuid, file_name) in &rows {
let mut missing: Vec<String> = Vec::new();
// Use per-library output dir with fallback to global
let per_lib_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
// 檢查 JSON 產出
for ext in ["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"] {
let path = format!("{}/{}.{}.json", output_dir, uuid, ext);
if !std::path::Path::new(&path).exists() {
let filename = format!("{}.{}.json", uuid, ext);
let per_lib_path = format!("{}/{}", per_lib_dir.trim_end_matches('/'), filename);
let global_path = format!("{}/{}", global_output_dir.trim_end_matches('/'), filename);
if !std::path::Path::new(&per_lib_path).exists() && !std::path::Path::new(&global_path).exists() {
missing.push(format!("{}.json", ext));
}
}
// 檢查 trace 目錄
let trace_base = std::path::Path::new(&output_dir).join(uuid);
if trace_base.is_dir() {
if let Ok(entries) = std::fs::read_dir(&trace_base) {
let trace_base = std::path::Path::new(&per_lib_dir).join(uuid);
let trace_base_global = std::path::Path::new(&global_output_dir).join(uuid);
let effective_trace_base = if trace_base.is_dir() {
trace_base
} else if trace_base_global.is_dir() {
trace_base_global
} else {
std::path::PathBuf::new()
};
if effective_trace_base.is_dir() {
if let Ok(entries) = std::fs::read_dir(&effective_trace_base) {
for entry in entries.filter_map(|e| e.ok()) {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("trace_") && entry.path().is_dir() {
@@ -692,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}
@@ -1007,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)
@@ -1046,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);
}
}
}
@@ -1117,6 +1183,7 @@ impl JobWorker {
);
// Special handling for ASR: read status from output JSON
// Fallback: if no status field but has segments, infer "has_transcript"
let mut asr_status_value: Option<String> = None;
if processor_type == crate::core::db::ProcessorType::Asrx {
if let Ok(json_str) = std::fs::read_to_string(&output_path) {
@@ -1127,6 +1194,26 @@ impl JobWorker {
"[AUTO-REPAIR] ASR status from file: {}",
status
);
} else {
// Legacy file without status: infer from segments
let seg_count = json_val.get("segments")
.and_then(|s| s.as_array())
.map(|a| a.len())
.unwrap_or(0);
if seg_count > 0 {
asr_status_value = Some("has_transcript".to_string());
info!(
"[AUTO-REPAIR] ASR status inferred from {} segments: has_transcript",
seg_count
);
// Backfill the status into the JSON file
let mut patched = json_val.clone();
patched["status"] = serde_json::Value::String("has_transcript".to_string());
patched["segment_count"] = serde_json::Value::Number(seg_count.into());
if let Ok(updated) = serde_json::to_string_pretty(&patched) {
let _ = std::fs::write(&output_path, updated);
}
}
}
}
}
@@ -1145,12 +1232,13 @@ impl JobWorker {
crate::core::db::ProcessorType::Asrx => {
// Update asr_status from JSON
if let Some(asr_status) = asr_status_value.clone() {
let status_enum = match asr_status.as_str() {
"no_audio_track" => crate::core::processor::AsrStatus::NoAudioTrack,
"silent_audio" => crate::core::processor::AsrStatus::SilentAudio,
_ => crate::core::processor::AsrStatus::SilentAudio,
let (status_enum, seg_count) = match asr_status.as_str() {
"no_audio_track" => (crate::core::processor::AsrStatus::NoAudioTrack, 0),
"silent_audio" => (crate::core::processor::AsrStatus::SilentAudio, 0),
"has_transcript" => (crate::core::processor::AsrStatus::HasTranscript, 1),
_ => (crate::core::processor::AsrStatus::SilentAudio, 0),
};
if let Err(e) = self.db.update_asr_status(result_id, &status_enum, 0).await {
if let Err(e) = self.db.update_asr_status(result_id, &status_enum, seg_count).await {
warn!("[AUTO-REPAIR] Failed to update asr_status for {}: {}", job.uuid, e);
} else {
info!("[AUTO-REPAIR] Updated asr_status to '{}' for {}", asr_status, job.uuid);
@@ -3714,13 +3802,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
.all(|p| p == "scene_vlm" || p == "scene");
let cut_json_exists = std::path::Path::new(&format!(
"{}/{}.cut.json",
crate::core::config::OUTPUT_DIR.as_str(),
crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await.trim_end_matches('/'),
uuid
))
.exists();
if has_cut || (wants_scene_vlm && cut_json_exists) {
let output_dir = crate::core::config::OUTPUT_DIR.clone();
let scenes_path = format!("{}/{}.scenes.json", output_dir, uuid);
let output_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
let scenes_path = format!("{}/{}.scenes.json", output_dir.trim_end_matches('/'), uuid);
// 重跑條件:scenes.json 不存在 或 未完整完成(vlm completed 數 < total_scenes)
let scene_vlm_complete = if std::path::Path::new(&scenes_path).exists() {
@@ -4017,11 +4105,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Note: trigger is gated on face alone (not has_asrx) so no-face videos still
// get face_traced.json written via the fast-path, unblocking FaceCluster.
if has_face {
let per_lib_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await;
let traced_path = format!(
"{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
per_lib_dir.trim_end_matches('/'),
uuid
);
// ✅ V2: Check data integrity, not just file existence
@@ -4037,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 {
@@ -4215,7 +4322,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
}
};
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let output_dir = crate::core::config::get_output_dir_for_file(&uuid_clone, db_clone.pool()).await;
let output_dir = output_dir.as_str();
// Get video path from DB for face crop extraction
let video_path: Option<String> = db_clone
@@ -4332,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!(
@@ -4432,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);
@@ -5516,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,
@@ -5534,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(),
@@ -5548,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
@@ -5558,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,
@@ -5640,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?;
}
}
@@ -5659,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<()>,
+161 -90
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();
@@ -891,9 +912,40 @@ fn main() {
return;
}
// Person face counts + best face (representative).
// Person face counts + best face (representative) using composite scoring.
// Composite score: 0.4 × frontal + 0.4 × confidence + 0.2 × quality
let mut person_face_count: BTreeMap<String, u64> = BTreeMap::new();
let mut person_best_face: BTreeMap<String, Value> = BTreeMap::new();
let mut person_best_score: BTreeMap<String, f64> = BTreeMap::new();
// Pre-compute min/max for normalization within each person
let mut person_stats: BTreeMap<String, (f64, f64, f64, f64, f64, f64)> = BTreeMap::new();
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let frame_num = frame_obj.get("frame")
.and_then(|f| f.as_u64())
.unwrap_or(frame_idx as u64);
let faces = frame_obj.get("faces").and_then(|f| f.as_array()).cloned().unwrap_or_default();
for face in faces.iter() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(pid) = person_id {
let conf = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.5);
let quality = face.get("captureQuality").and_then(|c| c.as_f64()).unwrap_or(0.0);
let pose = face.get("pose_angle").or_else(|| face.get("pose")).and_then(|p| p.as_object());
let yaw_rad = pose.and_then(|p| p.get("yaw").and_then(|y| y.as_f64())).unwrap_or(0.0);
let yaw_deg = yaw_rad * 57.2958;
let frontal = (1.0 - yaw_deg.abs() / 60.0).max(0.0);
let entry = person_stats.entry(pid.to_string()).or_insert((conf, conf, quality, quality, frontal, frontal));
entry.0 = entry.0.min(conf);
entry.1 = entry.1.max(conf);
entry.2 = entry.2.min(quality);
entry.3 = entry.3.max(quality);
entry.4 = entry.4.min(frontal);
entry.5 = entry.5.max(frontal);
}
}
}
for (frame_idx, frame_obj) in frames_list.iter().enumerate() {
let frame_num = frame_obj.get("frame")
.and_then(|f| f.as_u64())
@@ -903,18 +955,37 @@ fn main() {
let person_id = face.get("person_id").and_then(|p| p.as_str());
if let Some(person_id) = person_id {
*person_face_count.entry(person_id.to_string()).or_insert(0) += 1;
let confidence = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.9);
let entry = person_best_face
.entry(person_id.to_string())
.or_insert_with(|| {
json!({
"confidence": f64::NEG_INFINITY,
})
});
if confidence > entry.get("confidence").and_then(|c| c.as_f64()).unwrap_or(f64::NEG_INFINITY) {
*entry = json!({
// Calculate composite score
let conf = face.get("confidence").and_then(|c| c.as_f64()).unwrap_or(0.5);
let quality = face.get("captureQuality").and_then(|c| c.as_f64()).unwrap_or(0.0);
let pose = face.get("pose_angle").or_else(|| face.get("pose")).and_then(|p| p.as_object());
let yaw_rad = pose.and_then(|p| p.get("yaw").and_then(|y| y.as_f64())).unwrap_or(0.0);
let yaw_deg = yaw_rad * 57.2958;
let frontal = (1.0 - yaw_deg.abs() / 60.0).max(0.0);
// Normalize within person
let stats = person_stats.get(person_id).unwrap();
let conf_range = stats.1 - stats.0;
let quality_range = stats.3 - stats.2;
let frontal_range = stats.5 - stats.4;
let conf_norm = if conf_range > 0.001 { (conf - stats.0) / conf_range } else { 0.5 };
let quality_norm = if quality_range > 0.001 { (quality - stats.2) / quality_range } else { 0.5 };
let frontal_norm = if frontal_range > 0.001 { (frontal - stats.4) / frontal_range } else { 0.5 };
// Composite: 0.4 frontal + 0.4 confidence + 0.2 quality
let composite_score = 0.4 * frontal_norm + 0.4 * conf_norm + 0.2 * quality_norm;
let current_best = person_best_score.get(person_id).copied().unwrap_or(-1.0);
if composite_score > current_best {
person_best_score.insert(person_id.to_string(), composite_score);
person_best_face.insert(person_id.to_string(), json!({
"face_id": format!("face_{}_{}", frame_num, face_idx),
"confidence": confidence,
"confidence": conf,
"capture_quality": quality,
"yaw_deg": round_digits(yaw_deg, 2),
"composite_score": round_digits(composite_score, 4),
"frame": frame_num,
"bbox": {
"x": face.get("x").cloned().unwrap_or(Value::Null),
@@ -922,7 +993,7 @@ fn main() {
"width": face.get("width").cloned().unwrap_or(Value::Null),
"height": face.get("height").cloned().unwrap_or(Value::Null),
}
});
}));
}
}
}
@@ -1,804 +0,0 @@
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;
use clap::Parser;
use serde_json::{json, Value};
/// Face Clustering Processor (Rust port of fast_face_clustering_processor.py)
///
/// Loads face embeddings from Qdrant `_faces`, groups by trace_id, computes
/// weighted-average embeddings per trace, then clusters traces with either the
/// seed-leader method (default, deterministic) or average-linkage agglomerative.
#[derive(Parser)]
#[command(name = "rust_face_cluster", about = "Face Clustering Processor (Rust port)")]
struct Args {
video_path: String,
output_path: PathBuf,
#[arg(short = 'u', long = "uuid", default_value = "")]
uuid: String,
#[arg(long = "frames", default_value = None)]
frames: Option<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)
}
}
@@ -349,9 +349,64 @@ fn extract_full_frame(video_path: &str, frame_num: usize, output: &std::path::Pa
fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::Path) {
use std::io::Write;
let best_confidence = trace.best_confidence;
let avg_confidence = trace.avg_confidence;
let best_frame = trace.best_frame;
// Compute real stats from face instances (fallback to path when instances empty)
let instances: &Vec<TracePoint> = if !trace.face_instances.is_empty() {
&trace.face_instances
} else {
&trace.path
};
let avg_confidence = if !instances.is_empty() {
instances.iter().map(|p| p.confidence as f64).sum::<f64>() / instances.len() as f64
} else {
trace.avg_confidence
};
let best = instances.iter().max_by(|a, b| {
a.confidence
.partial_cmp(&b.confidence)
.unwrap_or(std::cmp::Ordering::Equal)
});
let best_frame = best.map(|p| p.frame as u64).unwrap_or(trace.best_frame as u64);
let best_confidence = best.map(|p| p.confidence as f64).unwrap_or(trace.best_confidence);
let best_capture_quality = instances
.iter()
.map(|p| p.capture_quality as f64)
.fold(0.0f64, |acc, q| if q > acc { q } else { acc });
let avg_capture_quality = if !instances.is_empty() {
instances.iter().map(|p| p.capture_quality as f64).sum::<f64>() / instances.len() as f64
} else {
0.0
};
let best_bbox = best.map(|p| {
serde_json::json!({
"x": p.bbox.x, "y": p.bbox.y,
"width": p.bbox.width, "height": p.bbox.height,
"x2": p.bbox.x2, "y2": p.bbox.y2,
"center_x": p.bbox.center_x, "center_y": p.bbox.center_y,
})
});
let avg_bbox = if !instances.is_empty() {
let mut b = trace.avg_bbox.clone();
let n = instances.len() as i32;
b.x = instances.iter().map(|p| p.bbox.x).sum::<i32>() / n;
b.y = instances.iter().map(|p| p.bbox.y).sum::<i32>() / n;
b.width = instances.iter().map(|p| p.bbox.width).sum::<i32>() / n;
b.height = instances.iter().map(|p| p.bbox.height).sum::<i32>() / n;
b.compute_derived();
serde_json::json!({
"x": b.x, "y": b.y,
"width": b.width, "height": b.height,
"x2": b.x2, "y2": b.y2,
"center_x": b.center_x, "center_y": b.center_y,
})
} else {
serde_json::Value::Null
};
let profile = serde_json::json!({
"version": "1.0",
@@ -364,10 +419,10 @@ fn write_trace_profile(trace: &TraceInfo, file_uuid: &str, output: &std::path::P
"best_frame": best_frame,
"avg_confidence": avg_confidence,
"best_confidence": best_confidence,
"avg_capture_quality": null,
"best_capture_quality": null,
"avg_bbox": null,
"best_bbox": null,
"avg_capture_quality": avg_capture_quality,
"best_capture_quality": best_capture_quality,
"avg_bbox": avg_bbox,
"best_bbox": best_bbox,
"key_frame": "key_frame.jpg",
"key_face": "key_face.jpg",
"status": "pending",
@@ -789,11 +844,19 @@ fn run_face_tracking(
(Some(curr), Some(prev)) => calculate_cosine_similarity(curr, prev),
_ => 0.0,
};
// Match if IoU AND similarity meet thresholds
if iou > best_iou
&& iou > iou_threshold
&& similarity > similarity_threshold {
// Match if IoU AND similarity meet thresholds.
// When embeddings are unavailable (either face missing its
// vector), fall back to IoU-only geometric continuation:
// consecutive frames of the same face have overlapping bboxes.
let matched = if current_embedding.is_none() || prev_embedding.is_none() {
iou > best_iou && iou > iou_threshold
} else {
iou > best_iou
&& iou > iou_threshold
&& similarity > similarity_threshold
};
if matched {
best_iou = iou;
best_match = Some((prev_trace_id, iou, similarity));
}
+1 -1
View File
@@ -1 +1 @@
27744
35478
+128 -7
View File
@@ -5,12 +5,12 @@
"name" : "swift_processors",
"path" : "/Users/accusys/momentry_core/tools/cli/swift",
"projects" : [
"4bb951680c7a5f5d226b6a3b0d2453f90e35844d52f94b5dc0d359d3d568b372",
"a6496b512993faa30402e6518bde4e4b69bd2427f8d64cf41ee7f5bc28d67be3",
"afba80c4dbe0096fd6d93282d3148df1eb86d6b5b3d68aa4e57be69d20f77b41",
"d8df0460d8830dd1bb13d74c609cd5c7f1e55863be9670a7a624932593afd537"
]
},
"signature" : "fcd9b0e36d2713de6dd4d629dacae1f5407953bc27259d7dd3226d7ac263d5a9",
"signature" : "ac12913d02bc1781a2fb24346b9ff7e318fca309870a0d5aae6d838c8f5d9499",
"type" : "workspace"
},
{
@@ -1664,12 +1664,13 @@
"projectIsPackage" : "true",
"projectName" : "swift-argument-parser",
"targets" : [
"c39fb450e72e228c87a5fd1779b08c540b490df0be13beb8c47198e94bce40d4",
"feb414f4b920fe466ce2562be7158dc040eefd827ea4bd81b50c64522737bac5",
"6e0f63d50477fed3ee9576e6dcdfa21371c8937cb4ca9d9a4ead97e57b36c845",
"62e3757020fe9abcbcf9560154a74c692658afed4cc2d56aac07665eae590a60",
"336477e6ce4166cc8665edb239411e1c2d61d3b8de49393a479b59c51985ee6d",
"4422a602fd4ba6358980ab18b61b6cd83ba2ddc5942a3c45076548f2c6c17f91",
"eddc80fc5d9cbc2e9bc74e7f0fe4466479359aa7253d71fa5d21d70274526e6c",
"35012d84eab8c4a916b260a25ca44ca9671450315d261b046b39ca3d660e35f3",
"2931340a6f32f4a5286ab1ab347d840ffcf96e4846cb36f32332444123663ad4",
"399ecfcd48ab3231c78332b8a2c9f519716dbe91ad6518c5fb3095f6ab1430b4",
"408cf308c0ee52b99b2202371b3c3f81a2fbc8cdbc0fc9dd846b0804d912b123",
"ec0da54fd80b82fba969e690109a420dba92e8a573f4f2b928c02b4c5ab49d7e",
@@ -1680,7 +1681,7 @@
"14bda589fb95cd2e7da33e3335ef51859afaea06e8edf316e72a885bb4a9af25"
]
},
"signature" : "4bb951680c7a5f5d226b6a3b0d2453f90e35844d52f94b5dc0d359d3d568b372",
"signature" : "a6496b512993faa30402e6518bde4e4b69bd2427f8d64cf41ee7f5bc28d67be3",
"type" : "project"
},
{
@@ -1735,6 +1736,7 @@
]
}
],
"dynamicTargetVariantGuid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic",
"frameworksBuildPhase" : {
"buildFiles" : [
{
@@ -1759,7 +1761,7 @@
"name" : "ArgumentParser-product",
"type" : "packageProduct"
},
"signature" : "c39fb450e72e228c87a5fd1779b08c540b490df0be13beb8c47198e94bce40d4",
"signature" : "feb414f4b920fe466ce2562be7158dc040eefd827ea4bd81b50c64522737bac5",
"type" : "target"
},
{
@@ -2518,6 +2520,9 @@
"$(inherited)",
"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE"
],
"SWIFT_DISABLE_COMPILATION_FOR_STATIC_LINKING_WHEN_ANY_TARGET_IS_PROMOTED_TO_DYNAMIC[__platform_filter=windows-msvc]" : [
"PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser"
],
"SWIFT_DISABLE_PARSE_AS_LIBRARY" : "NO",
"SWIFT_ENABLE_BARE_SLASH_REGEX" : "NO",
"SWIFT_LIBRARIES_ONLY" : "YES",
@@ -2572,6 +2577,9 @@
"$(inherited)",
"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE"
],
"SWIFT_DISABLE_COMPILATION_FOR_STATIC_LINKING_WHEN_ANY_TARGET_IS_PROMOTED_TO_DYNAMIC[__platform_filter=windows-msvc]" : [
"PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser"
],
"SWIFT_DISABLE_PARSE_AS_LIBRARY" : "NO",
"SWIFT_ENABLE_BARE_SLASH_REGEX" : "NO",
"SWIFT_LIBRARIES_ONLY" : "YES",
@@ -3108,7 +3116,7 @@
"productTypeIdentifier" : "org.swift.product-type.library.static",
"type" : "standard"
},
"signature" : "35012d84eab8c4a916b260a25ca44ca9671450315d261b046b39ca3d660e35f3",
"signature" : "2931340a6f32f4a5286ab1ab347d840ffcf96e4846cb36f32332444123663ad4",
"type" : "target"
},
{
@@ -4115,6 +4123,119 @@
"signature" : "14bda589fb95cd2e7da33e3335ef51859afaea06e8edf316e72a885bb4a9af25",
"type" : "target"
},
{
"contents" : {
"approvedByUser" : "true",
"buildConfigurations" : [
{
"buildSettings" : {
"EXECUTABLE_PREFIX" : "lib",
"EXECUTABLE_PREFIX[__platform_filter=windows-msvc]" : "",
"PRODUCT_BUNDLE_IDENTIFIER" : "swift-argument-parser.ArgumentParser",
"PRODUCT_MODULE_NAME" : "ArgumentParser",
"PRODUCT_NAME" : "ArgumentParser",
"SDKROOT" : "auto",
"SDK_VARIANT" : "auto",
"SWIFT_PACKAGE_NAME" : "swift_argument_parser",
"SWIFT_USER_MODULE_VERSION" : "1.8.2",
"TARGET_NAME" : "ArgumentParser-product",
"TARGET_TEMP_DIR_SUFFIX" : "-t",
"USES_SWIFTPM_UNSAFE_FLAGS" : "NO"
},
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDCONFIG_0",
"impartedBuildProperties" : {
"buildSettings" : {
}
},
"name" : "Debug"
},
{
"buildSettings" : {
"EXECUTABLE_PREFIX" : "lib",
"EXECUTABLE_PREFIX[__platform_filter=windows-msvc]" : "",
"PRODUCT_BUNDLE_IDENTIFIER" : "swift-argument-parser.ArgumentParser",
"PRODUCT_MODULE_NAME" : "ArgumentParser",
"PRODUCT_NAME" : "ArgumentParser",
"SDKROOT" : "auto",
"SDK_VARIANT" : "auto",
"SWIFT_PACKAGE_NAME" : "swift_argument_parser",
"SWIFT_USER_MODULE_VERSION" : "1.8.2",
"TARGET_NAME" : "ArgumentParser-product",
"TARGET_TEMP_DIR_SUFFIX" : "-t",
"USES_SWIFTPM_UNSAFE_FLAGS" : "NO"
},
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDCONFIG_1",
"impartedBuildProperties" : {
"buildSettings" : {
}
},
"name" : "Release"
}
],
"buildPhases" : [
{
"buildFiles" : [
{
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDPHASE_0::0",
"platformFilters" : [
],
"targetReference" : "PACKAGE-TARGET:ArgumentParser"
},
{
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDPHASE_0::1",
"platformFilters" : [
],
"targetReference" : "PACKAGE-TARGET:ArgumentParserToolInfo"
}
],
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDPHASE_0",
"type" : "com.apple.buildphase.frameworks"
},
{
"buildFiles" : [
],
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic::BUILDPHASE_1",
"type" : "com.apple.buildphase.sources"
}
],
"buildRules" : [
],
"customTasks" : [
],
"dependencies" : [
{
"guid" : "PACKAGE-TARGET:ArgumentParser",
"platformFilters" : [
]
},
{
"guid" : "PACKAGE-TARGET:ArgumentParserToolInfo",
"platformFilters" : [
]
}
],
"guid" : "PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic",
"name" : "ArgumentParserdynamic-product",
"productReference" : {
"guid" : "PRODUCTREF-PACKAGE-PRODUCT:swift-argument-parser_ArgumentParser.ArgumentParser-39B7DAEE4DD359BE-dynamic",
"name" : "$(EXECUTABLE_NAME)",
"type" : "file"
},
"productTypeIdentifier" : "com.apple.product-type.library.dynamic",
"type" : "standard"
},
"signature" : "6e0f63d50477fed3ee9576e6dcdfa21371c8937cb4ca9d9a4ead97e57b36c845",
"type" : "target"
},
{
"contents" : {
"approvedByUser" : "true",
@@ -1,6 +1,6 @@
#if 0
#elif defined(__arm64__) && __arm64__
// Generated by Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)
// Generated by Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1)
#ifndef ARGUMENTPARSER_SWIFT_H
#define ARGUMENTPARSER_SWIFT_H
#pragma clang diagnostic push
@@ -1,6 +1,6 @@
#if 0
#elif defined(__arm64__) && __arm64__
// Generated by Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)
// Generated by Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1)
#ifndef ARGUMENTPARSERTOOLINFO_SWIFT_H
#define ARGUMENTPARSERTOOLINFO_SWIFT_H
#pragma clang diagnostic push
@@ -1,16 +0,0 @@
{
"" : {
"const-values" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary.swiftconstvalues",
"dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary.d",
"diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary.dia",
"emit-module-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary-emit-module.d",
"emit-module-diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary-emit-module.dia",
"pch" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary-Bridging-header.pch",
"swift-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/swift_scene_detector-primary.swiftdeps"
},
"/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_scene_detector/main.swift" : {
"index-unit-output-path" : "/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/main.o",
"llvm-bc" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/main.bc",
"object" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/main.o"
}
}
@@ -1 +0,0 @@
/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_scene_detector-p.build/Objects-normal/arm64/main.o
@@ -1 +0,0 @@
/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/main.o /Users/accusys/momentry_core/tools/cli/swift/.build/out/Products/Release/ArgumentParser.o /Users/accusys/momentry_core/tools/cli/swift/.build/out/Products/Release/ArgumentParserToolInfo.o
@@ -1 +0,0 @@
/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_scene_detector/main.swift
@@ -1 +0,0 @@
/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_face/main.swift
@@ -0,0 +1 @@
/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/main.o /Users/accusys/momentry_core/tools/cli/swift/.build/out/Products/Release/ArgumentParser.o /Users/accusys/momentry_core/tools/cli/swift/.build/out/Products/Release/ArgumentParserToolInfo.o
@@ -1,16 +1,16 @@
{
"" : {
"const-values" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary.swiftconstvalues",
"dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary.d",
"diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary.dia",
"emit-module-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary-emit-module.d",
"emit-module-diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary-emit-module.dia",
"pch" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary-Bridging-header.pch",
"swift-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/swift_face-primary.swiftdeps"
"const-values" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary.swiftconstvalues",
"dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary.d",
"diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary.dia",
"emit-module-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary-emit-module.d",
"emit-module-diagnostics" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary-emit-module.dia",
"pch" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary-Bridging-header.pch",
"swift-dependencies" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/swift_ocr-primary.swiftdeps"
},
"/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_face/main.swift" : {
"index-unit-output-path" : "/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/main.o",
"llvm-bc" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/main.bc",
"object" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_face-p.build/Objects-normal/arm64/main.o"
"/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_ocr/main.swift" : {
"index-unit-output-path" : "/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/main.o",
"llvm-bc" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/main.bc",
"object" : "/Users/accusys/momentry_core/tools/cli/swift/.build/out/Intermediates.noindex/swift_processors.build/Release/swift_ocr-p.build/Objects-normal/arm64/main.o"
}
}
@@ -0,0 +1 @@
/Users/accusys/momentry_core/tools/cli/swift/Sources/swift_ocr/main.swift
@@ -6,7 +6,7 @@
},
"configuredTargets" : [
{
"guid" : "ALL-EXCLUDING-TESTS",
"guid" : "PACKAGE-PRODUCT:swift_swift_ocr.swift_ocr",
"parameters" : {
"action" : "build",
"activeRunDestination" : {
@@ -53,7 +53,7 @@
"OTHER_SWIFT_FLAGS[__destination_platform=YES]" : "$(inherited)",
"STRIP_INSTALLED_PRODUCT" : "NO",
"SWIFT_FORCE_STATIC_LINK_STDLIB" : "NO",
"TOOLCHAINS" : "org.swift.CommandLineTools $(inherited)"
"TOOLCHAINS" : "com.apple.dt.toolchain.XcodeDefault $(inherited)"
}
}
}
@@ -110,7 +110,7 @@
"OTHER_SWIFT_FLAGS[__destination_platform=YES]" : "$(inherited)",
"STRIP_INSTALLED_PRODUCT" : "NO",
"SWIFT_FORCE_STATIC_LINK_STDLIB" : "NO",
"TOOLCHAINS" : "org.swift.CommandLineTools $(inherited)"
"TOOLCHAINS" : "com.apple.dt.toolchain.XcodeDefault $(inherited)"
}
}
}
@@ -1,13 +1,9 @@
Target dependency graph (6 targets)
Target 'AllExcludingTests' in project 'Aggregate'
➜ Explicit dependency on target 'swift_scene_detector-product' in project 'swift_processors'
➜ Explicit dependency on target 'swift_face-product' in project 'swift_processors'
Target 'swift_face-product' in project 'swift_processors'
Target dependency graph (4 targets)
Target 'swift_ocr-product' in project 'swift_processors'
➜ Explicit dependency on target 'ArgumentParser-product' in project 'swift-argument-parser'
Target 'ArgumentParser-product' in project 'swift-argument-parser'
➜ Explicit dependency on target 'ArgumentParser' in project 'swift-argument-parser'
➜ Explicit dependency on target 'ArgumentParserToolInfo' in project 'swift-argument-parser'
Target 'ArgumentParser' in project 'swift-argument-parser'
➜ Explicit dependency on target 'ArgumentParserToolInfo' in project 'swift-argument-parser'
Target 'ArgumentParserToolInfo' in project 'swift-argument-parser' (no dependencies)
Target 'swift_scene_detector-product' in project 'swift_processors' (no dependencies)
Target 'ArgumentParserToolInfo' in project 'swift-argument-parser' (no dependencies)
@@ -6,3 +6,4 @@ e82b9b1fa6e2155ecd5d48e4eafb0de6
b560b6c95d5323089188c41bce087705
0c65646c2030f5b7157b378e289d7935
3ca87f1a3cf69ca4254ec37726e9054e
9d5c9831f7a032439fc2527a4921bbc1
@@ -1,4 +1,4 @@
// Generated by Apple Swift version 6.4 (swiftlang-6.4.0.34.1 clang-2100.3.34.1)
// Generated by Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1)
#ifndef ARGUMENTPARSER_SWIFT_H
#define ARGUMENTPARSER_SWIFT_H
#pragma clang diagnostic push
@@ -7,341 +7,341 @@
{
"isFramework" : true,
"moduleName" : "Combine",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Combine-HZXIDVRS1RHS.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Combine-1MQD19MFP7YP0.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "CoreFoundation",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreFoundation-1ZR84FL6049EO.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreFoundation-1XA0K2EAORYIG.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "Darwin",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Darwin-2YURQ1NTTP12G.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Darwin-1TESJRJ3CHXJX.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "Dispatch",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Dispatch-1AFJ8KY8MJUVZ.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Dispatch-E3QYKUOWATEB.swiftmodule"
},
{
"isFramework" : true,
"moduleName" : "Foundation",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Foundation-33L54W4MUI10Q.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Foundation-1HKRN7SGCE3ZL.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "IOKit",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/IOKit-CSC23YYAC90H.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/IOKit-18QTH2K2O8UW3.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "ObjectiveC",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ObjectiveC-GA4NBN3Y5M3X.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ObjectiveC-32IVS8Z36XT4E.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "Observation",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Observation-1ULOIXFMMWT2Z.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Observation-2Z0R48LOYDWT9.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "Swift",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Swift-1BDYYDYC90NDQ.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Swift-KU4R36X95208.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "System",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/System-12GM73T8YN3SE.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/System-319KKF0UNM77U.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "XPC",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/XPC-LSET5NHDQUSS.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/XPC-2TIKMEBVUZIGP.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_Builtin_float",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_float-2DVAU8LXVIX6C.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_float-2KG30KIN06N76.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_Concurrency",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Concurrency-X4L7DUWFQ224.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Concurrency-3B41COEBYAOHN.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_DarwinFoundation1",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation1-3EKSPSYJ3B5WF.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation1-TN0JMYD3KX8G.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_DarwinFoundation2",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation2-YJE2XKP3QD6F.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation2-1Q22QAOQ6KBAI.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_DarwinFoundation3",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation3-TUEGO3SZ71SU.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation3-2J9L00U6N633O.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "_StringProcessing",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_StringProcessing-MGC1BQR57F9B.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_StringProcessing-3L7V9645RLKMA.swiftmodule"
},
{
"isFramework" : false,
"moduleName" : "os",
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os-15CPJ0X72EZHL.swiftmodule"
"modulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os-1S9410INZSSGD.swiftmodule"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/CFNetwork.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CFNetwork-8SWLSMUO8ZDLAVV0RXI64MZJW.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/CFNetwork.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CFNetwork-A6FB0NO27TMQ8W89N9I8OTURS.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "CFNetwork"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/CoreFoundation.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreFoundation-3VPXEWXZT7QL1D0IK0FCN623T.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/CoreFoundation.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreFoundation-F3H63C1DPQDP17ANIJ8UHMS4D.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "CoreFoundation"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/CoreServices.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreServices-8Y8XLWTRUVX92SOVAUCDHP566.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/CoreServices.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/CoreServices-8YAM1RTUB5D81GT30XFOO7SGS.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "CoreServices"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/Darwin.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Darwin-1PO333ST3ZHUE3CMDK11CYMRD.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/Darwin.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Darwin-D6MYOFGYMIB6Y8OKZ0RI1X0SB.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "Darwin"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/DiskArbitration.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/DiskArbitration-7V03GTHCIWJ4GC6S2YJK0PM9O.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/DiskArbitration.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/DiskArbitration-1HTA4IBSL1WWZ6VXU8E2DH4BO.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "DiskArbitration"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/dispatch.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Dispatch-13GWP0VO5YFASGFHV7FSBUUUN.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/dispatch.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Dispatch-5VU17F24X73A3FCCTI84ZPC7N.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "Dispatch"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/Foundation.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Foundation-CCQ97L9JPBHIMYMW51LOTRROG.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/Foundation.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Foundation-ACKVOFYRXRR50KGW4XV4OQ7RD.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "Foundation"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/IOKit.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/IOKit-4U6UIC9VEH6ZAE5X5MUIA0CD0.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/IOKit.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/IOKit-E5TXC7GF2H1H8GPUA4US05D6O.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "IOKit"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinBasic.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/MachO-3RUAM0ENCPOLY5X85F3O4MPD4.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinBasic.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/MachO-39MAC48JWYT2QDPJFHVK2FNYY.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "MachO"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/ObjectiveC.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ObjectiveC-6K4BZG6FL62FHH4YW7YO7ZRW9.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/ObjectiveC.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ObjectiveC-9T7BP113LI8SHW9ONPSCQEP5Z.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "ObjectiveC"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/System\/Library\/Frameworks\/Security.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Security-6022BI0SK4FDX6AUP1ZQQ1MYK.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/System\/Library\/Frameworks\/Security.framework\/Modules\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/Security-D3IH07DNM01CQA47X3PBC2O87.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "Security"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/lib\/swift\/shims\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/SwiftShims-5OVPMYW11HC3ZP1UM41DL1107.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/lib\/swift\/shims\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/SwiftShims-908JTSCB9N7VPIJMQJ1PZNYZR.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "SwiftShims"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/xpc.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/XPC-8S45JAQAI29K7FUVCQGP2E0WA.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/xpc.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/XPC-8LKV8SPA6LS03KXKU4WCZNHF0.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "XPC"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinFoundation1.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_AvailabilityInternal-CRU4IMFDXL4VC3IECO7AA9V92.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinFoundation1.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_AvailabilityInternal-7NMM7DAXX6A7IR8XY05UPZTOL.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_AvailabilityInternal"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_float-4FZH66PFDZMZBFAF7SUEA7LV6.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_float-61XD6D0QTECFXZZS24CDL1MJ7.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_float"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_inttypes-HM5QYS9QSMKEW1AGU6690N4L.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_inttypes-2SINIPEZYXB8UWTOMW8YQOIGO.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_inttypes"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_limits-4G0NQA5GK9Z713ELX38ZI3992.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_limits-7XFXMEX4HUG5WP1H8CF8N1EE2.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_limits"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdarg-838CZFRMP7CJQMTHHI2CESB8N.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdarg-1XQOITE4V1BBP2BJ7M5OTBU94.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_stdarg"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdatomic-8SS4V6YRZHBVXKZHEMJ7831TJ.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdatomic-5UL9X0N5TNKD0RYFBBEFYNUW7.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_stdatomic"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdbool-BK1A1AW1Z68Y0W1PX9ZO4PWT1.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdbool-9C0R5SFJMCGOG1OPBWARSG8RZ.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_stdbool"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stddef-78083T9YAQ2I3Y38AMA1XZ06H.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stddef-8HWLOIBNZ6CQAH1699BKPMNO4.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_stddef"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdint-4RHBWNI18KU9MI7Q2DQN83RJ8.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_Builtin_stdint-3AD0O3PS20TS854ZDUWJKQ829.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_Builtin_stdint"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinFoundation1.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation1-953JXDK1NE54C20WWJ2RBZ4I9.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinFoundation1.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation1-AU0YCCBBXI8HDDMQS2FFWE7G9.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_DarwinFoundation1"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinFoundation2.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation2-AVXB2H3XJ4O9L9X3WKK6Y8L4G.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinFoundation2.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation2-ACMDPTTH3YTUE8UJZ5UR68HU8.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_DarwinFoundation2"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinFoundation3.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation3-BQY27OGUP2M9UHIQQR15BGTJI.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinFoundation3.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_DarwinFoundation3-CORBOAAT9E5AWFEZDD6ZRTRX7.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_DarwinFoundation3"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/lib\/swift\/shims\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_SwiftConcurrencyShims-4GGTDYVZN9IK9W9BO3FQUMZ9B.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/lib\/swift\/shims\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/_SwiftConcurrencyShims-75EIVSEIU91LXJI1CFUUIK8UW.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "_SwiftConcurrencyShims"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/launch.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/launch-7J3E8HS4VVB3UD6CK61ZEB89C.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/launch.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/launch-G3RR0PY71UETBDB34FLUY6K0.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "launch"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/libDER\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/libDER-1BHGOP3QNX4AE7ETI40RXOUCB.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/libDER\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/libDER-ATOCQG69Z41COA5423P9J2R03.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "libDER"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/libkern.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/libkern-3P8RWJSXAQD33E5688RBYXXG.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/libkern.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/libkern-5GEE2D3ZYF3C33NC0SF2DQF8O.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "libkern"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os-6PTMFPW6JVF1UEQ62TLJ7P5WL.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os-BH0OXYTQKY0V39J3TJRC5ZHE7.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "os"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os_object-1PDILO1CXHP8L6RRM9NBF8FA3.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os_object-CTNCVH9V0QE2GFSL4WH8XGNPJ.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "os_object"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os_workgroup-DQLHTOZ1KJ4SPSCA4FJB4PUQT.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/os.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/os_workgroup-EFGFZHMQQVHEBFYKJM9TTS283.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "os_workgroup"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ptrauth-EXZ29ESNLUGAEIVCR2VR64YLY.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ptrauth-2K7KNTSPGDZJ6K86MU9BKE1WU.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "ptrauth"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/usr\/lib\/clang\/21\/include\/module.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ptrcheck-5SOYM7XO9J48444O7BU8LKZG8.pcm",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/ptrcheck-1YKDMD4KC8BCY1TVZ8BMLXBUC.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "ptrcheck"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/c_standard_library.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/string_h-CKYTK6OTWEC0DZ7NUUQS7Q961.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/c_standard_library.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/string_h-4RYRGWNKE50AN10N3ETPZFLS8.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "string_h"
},
{
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.0.sdk\/usr\/include\/DarwinFoundation2.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/sys_types-47ERAGTYA98Z5MRSBBKMJNL74.pcm",
"clangModuleMapPath" : "\/Library\/Developer\/CommandLineTools\/SDKs\/MacOSX27.2.sdk\/usr\/include\/DarwinFoundation2.modulemap",
"clangModulePath" : "\/Users\/accusys\/momentry_core\/tools\/cli\/swift\/.build\/out\/SDKExplicitPrecompiledModules\/sys_types-EFKODKC7EBOACNANX52AC9PIN.pcm",
"isBridgingHeaderDependency" : false,
"isFramework" : false,
"moduleName" : "sys_types"

Some files were not shown because too many files have changed in this diff Show More