51 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
Accusys 646d2a1361 fix(P0): face_cluster_done 雙路徑檢查 + run_processor 改用 async get_output_dir_for_file; 補 ingestion_complete output_dir
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 03:03:16 +08:00
Accusys d01e456ae5 fix(P0): per-library output dir for worker ingestion/verification (face_cluster guard, verifier, TKG, qdrant_face, ASR/ASRX); fix face_cluster serde default for empty output; fix face_cluster dependencies in pipeline_flows.json
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-17 02:46:57 +08:00
Accusys db790e2c89 fix: face_cluster guard checks both global OUTPUT_DIR and demo subdirectory for face_traced.json
Cross-Project Integration / integration (push) Has been cancelled
Core Test / lint-and-test (push) Has been cancelled
2026-11-17 01:29:28 +08:00
Accusys 75cbaa3302 feat: rebuild embeddings endpoint + standalone tool (API + binary), clear collection before rebuild, fix upsert_scene_embedding args
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-16 21:56:43 +08:00
Accusys 083d73d287 feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
2026-11-16 18:16:46 +08:00
Accusys d21d1ab960 fix: Library Re-run 完整重建搜尋索引 (ASR/ASRX/OCR/Scene VLM)
- trigger_processing: force 時僅刪除指定 processor 的輸出檔與 processor_results
  (其他 processor 資料保留),並設定 rerun_rebuild Redis flag 要求重建索引
- worker: 單一 processor Re-run 時強制 Rule 1 重新 chunk + vectorize
  (清除 momentry_rule1 舊 vectors,避免 stale 搜尋結果)
- Scene VLM Re-run: job_processors 含 scene_vlm 即 dispatch,
  scene-only job 完成條件改以 scenes.json 完整度判定
- 前端 redoProcessor 傳 force=true,Scene VLM 新增 🔄 Re-run 按鈕
2026-11-10 07:59:31 +08:00
Accusys 043dbbf24a fix: swift_ocr 支援日文識別
Cross-Project Integration / integration (push) Has been cancelled
- 加入 recognitionLanguages = ["ja", "en"] 使 Apple Vision Framework
  能識別日文和中文文字
- 使用 #available(macOS 12.0, *) 確保向後相容
- 兩處 VNRecognizeTextRequest 都已修改(主循環 + recognizeText 函式)

驗證: 065.mp4 從 0 幀 → 75 幀,1559 個日文文字區塊
(松原徳洲会病院、ここで検索、吹田市、寝屋川市 等)
2026-11-09 17:16:37 +08:00
Accusys 3d7ec83ec9 fix: Qdrant collection ensure + self-healing on clean install
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
- qdrant_db.rs: ensure_collection now uses PUT /collections/{name}
  (was POST /collections without name) and checks response status.
  Previous code silently no-op'd, so every upsert got 404 on clean
  installs with empty Qdrant.
- face.rs: store_face_embeddings_to_qdrant ensures _faces (512D)
  collection exists before upsert (fixes face→facenet→Qdrant broken
  link on fresh machines).
- pipeline/mod.rs: vectorize_chunks ensures main text collection
  (768D) before upserts.
- job_worker.rs: vectorize_chunks ensures main collection (768D)
  before upserts; also 3 additional lines of job_worker WIP fixes.

Verified: after these fixes, Qdrant collections are auto-created
on first upsert, resolving the face embedding + rule1 vectorize
failures on 203.
2026-11-09 15:55:01 +08:00
Accusys 70f5667adc fix: processor-counts resolves face_trace -> face_traced.json
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
get_processor_counts built the filename from the queue name
(face_trace.json) while rust_store_traced_faces writes face_traced.json
(per processor_tools_v3 output_file), so the API/UI reported
face_trace has_json=false and face_traced data was unreachable for
existing files. Map face_trace -> face_traced in both
get_processor_counts and get_processor_json.

Verified: dev (201) & 203 processor-counts now report face_trace
has_json=true and /api/v1/processor-json?processor=face_trace returns 200.
2026-11-09 12:39:44 +08:00
729 changed files with 21311 additions and 5902 deletions
Generated
+663 -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"
@@ -2470,8 +2770,10 @@ dependencies = [
"dotenv",
"env_logger",
"ferrous-opencc",
"flate2",
"futures-util",
"hex",
"image",
"jieba-rs",
"jsonwebtoken",
"libc",
@@ -2479,6 +2781,7 @@ dependencies = [
"md5",
"moka",
"mongodb",
"ndarray",
"notify",
"once_cell",
"pgvector",
@@ -2487,6 +2790,7 @@ dependencies = [
"redis",
"regex",
"reqwest",
"rustfft",
"sdl2",
"serde",
"serde_json",
@@ -2494,6 +2798,7 @@ dependencies = [
"sqlx 0.8.6",
"subtle",
"sysinfo",
"tar",
"tempfile",
"thiserror 1.0.69",
"tokio",
@@ -2506,6 +2811,7 @@ dependencies = [
"utoipa",
"utoipa-swagger-ui",
"uuid",
"walkdir",
]
[[package]]
@@ -2555,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"
@@ -2572,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"
@@ -2589,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"
@@ -2621,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"
@@ -2684,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"
@@ -2710,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"
@@ -2856,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"
@@ -3011,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"
@@ -3072,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"
@@ -3136,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"
@@ -3168,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"
@@ -3190,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"
@@ -3352,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"
@@ -3512,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"
@@ -3620,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"
@@ -4056,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"
@@ -4144,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",
]
@@ -4478,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"
@@ -4625,6 +5189,23 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"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"
@@ -4687,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"
@@ -5078,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"
@@ -5322,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"
@@ -5538,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"
@@ -6029,12 +6651,28 @@ dependencies = [
"tap",
]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.4",
]
[[package]]
name = "xxhash-rust"
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"
@@ -6187,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",
]
+8
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"] }
@@ -86,6 +91,9 @@ crossterm = "0.28"
# Terminal
atty = "0.2"
tokio-util = { version = "0.7.18", features = ["io"] }
walkdir = "2.5.0"
flate2 = "1.0"
tar = "0.4"
# System
+231 -93
View File
@@ -1,31 +1,65 @@
{
"version": "1.0.0",
"updated_at": "2026-10-26T17:18:56.139925+00:00",
"version": "1.3.5",
"updated_at": "2026-11-15T12:00:00+0800",
"updated_by": "admin",
"vlm_prompts": {
"scene_vlm": {
"system_prompt": "You are a helpful assistant that analyzes video scenes.",
"user_prompt": "Describe this scene. What is happening? What objects and people are visible?",
"max_tokens": 200,
"description": "Scene analysis VLM prompt"
},
"rust_vlm_summary": {
"system_prompt": "You are a helpful assistant that describes people in images.",
"user_prompt": "Describe the person in this image. Focus on clothing, accessories, and distinctive features.",
"max_tokens": 300,
"description": "Face trace VLM prompt for person description"
},
"scene_vlm": {
"system_prompt": "You are a helpful assistant that analyzes video scenes.",
"user_prompt": "Describe this scene. What is happening? What objects and people are visible?",
"max_tokens": 200,
"description": "Scene analysis VLM prompt"
"garbled_recovery": {
"system_prompt": "You are a helpful assistant that verifies speech transcription quality.",
"user_prompt": "Analyze this transcript for garbled text. Is it intelligible?",
"max_tokens": 100,
"description": "ASR garbled text recovery prompt"
}
},
"llm_config": {
"chat": {
"url": "http://localhost:8080/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 30
},
"summary": {
"url": "http://localhost:8080/v1/chat/completions",
"url": "http://127.0.0.1:8080/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 60
"timeout": 60,
"fallbacks": [
"http://127.0.0.1:8082/v1/chat/completions"
],
"strategy": "priority",
"enabled": true
},
"vlm": {
"url": "http://127.0.0.1:8082/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 120,
"fallbacks": [
"http://127.0.0.1:8080/v1/chat/completions"
],
"strategy": "priority",
"enabled": false
},
"chat": {
"url": "http://127.0.0.1:8080/v1/chat/completions",
"model": "gemma-4-12b-it",
"timeout": 30,
"fallbacks": [
"http://127.0.0.1:8082/v1/chat/completions"
],
"strategy": "priority",
"enabled": true
},
"embedding": {
"url": "http://127.0.0.1:11436/v1/embeddings",
"model": "embeddinggemma",
"timeout": 60,
"fallbacks": [],
"strategy": "priority",
"enabled": true
}
},
"processor_config": {
@@ -48,26 +82,7 @@
],
"default_tool": "swift"
},
"FACE_TRACE": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "python",
"priority": 1,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"POSE": {
"OCR": {
"timeout": 3600,
"enabled": true,
"tools": [
@@ -76,21 +91,6 @@
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "rust",
"priority": 1,
"enabled": true,
"parameters": {}
},
{
"name": "mediapipe",
"priority": 2,
"enabled": true,
"parameters": {
"min_confidence": 0.5,
"model_complexity": 2
}
}
],
"default_tool": "swift"
@@ -127,7 +127,52 @@
],
"default_tool": "swift"
},
"OCR": {
"FACE_TRACE": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "python",
"priority": 1,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"FACE_CLUSTER": {
"timeout": 3600,
"enabled": true,
"tools": [
{
"name": "rust",
"priority": 0,
"enabled": true,
"parameters": {}
}
],
"default_tool": "rust"
},
"SCENE_VLM": {
"timeout": 7200,
"enabled": true,
"tools": [
{
"name": "python",
"priority": 0,
"enabled": true,
"parameters": {}
}
],
"default_tool": "python"
},
"POSE": {
"timeout": 3600,
"enabled": true,
"tools": [
@@ -136,6 +181,21 @@
"priority": 0,
"enabled": true,
"parameters": {}
},
{
"name": "rust",
"priority": 1,
"enabled": true,
"parameters": {}
},
{
"name": "mediapipe",
"priority": 2,
"enabled": true,
"parameters": {
"min_confidence": 0.5,
"model_complexity": 2
}
}
],
"default_tool": "swift"
@@ -144,7 +204,8 @@
"filter_config": {
"face": {
"min_confidence": 0.5,
"min_size": 30
"min_size": 30,
"min_capture_quality": 0.25
}
},
"face_filter_defaults": {
@@ -153,38 +214,39 @@
"min_capture_quality": 0.25
},
"paths": {
"output_dir": "",
"backup_dir": "",
"scripts_dir": "",
"cli_dir": "",
"python_path": "",
"ffmpeg_path": ""
"output_dir": "/Users/accusys/momentry/output/demo",
"backup_dir": "/Users/accusys/momentry/var/backup",
"scripts_dir": "/Users/accusys/momentry/scripts",
"cli_dir": "/Users/accusys/momentry/tools/cli",
"python_path": "/opt/homebrew/bin/python3.11",
"ffmpeg_path": "/opt/homebrew/bin/ffmpeg"
},
"concurrency": {
"max_concurrent_jobs": 0,
"poll_interval": 0,
"batch_size": 0,
"processor_timeout_secs": 0
"max_concurrent_jobs": 2,
"poll_interval": 5,
"batch_size": 5,
"processor_timeout_secs": 3600
},
"feature_flags": {
"cache_enabled": false,
"cache_enabled": true,
"auto_pipeline_enabled": false,
"watcher_auto_register": false,
"summary_enabled": false
"summary_enabled": true
},
"server": {
"port": 0,
"media_base_url": "",
"serve_base_url": "",
"storage_root": "",
"timezone": ""
"port": 3002,
"media_base_url": "http://localhost:8888",
"serve_base_url": "http://localhost:8888",
"storage_root": "/Users/accusys/momentry/var/sftpgo/data",
"timezone": "Asia/Taipei"
},
"admin_settings": {
"session_timeout": 0,
"max_login_attempts": 0,
"api_key_expiry_days": 0,
"system_stats_refresh_sec": 0,
"preferred_language": ""
"session_timeout": 3600,
"max_login_attempts": 5,
"api_key_expiry_days": 365,
"system_stats_refresh_sec": 5,
"preferred_language": "en",
"library_default_sort": "name_asc"
},
"search": {
"vlm_min_score": 0.0,
@@ -194,24 +256,100 @@
"enabled": true,
"max_concurrent_stages": 5,
"default_timeout_secs": 7200,
"flows": {}
},
"asr_config": {
"garbled_check_enabled": true,
"first_sentence_thresholds": {
"max_top_char_ratio": 0.6,
"min_lang_prob": 0.4,
"min_repeat_slice_repeat": 5
},
"language_candidates": [
"ja",
"zh",
"en"
],
"vlm_rescue_enabled": true,
"vlm_max_tokens": 500,
"vlm_temperature": 0.1,
"vlm_timeout_secs": 120,
"vlm_max_audio_secs": 60
"flows": {
"register": {
"name": "register",
"description": "Full registration pipeline: all processors",
"version": "1.0",
"enabled": true,
"stages": [
{
"name": "probe",
"processor_type": "probe",
"required": false,
"enabled": true,
"timeout_secs": 300
},
{
"name": "cut",
"processor_type": "cut",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "face",
"processor_type": "face",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "ocr",
"processor_type": "ocr",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "asrx",
"processor_type": "asrx",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "scene_vlm",
"processor_type": "scene_vlm",
"required": false,
"enabled": true,
"timeout_secs": 7200
},
{
"name": "face_trace",
"processor_type": "face_trace",
"required": false,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "face_cluster",
"processor_type": "face_cluster",
"required": false,
"enabled": true,
"timeout_secs": 3600
}
]
},
"reindex": {
"name": "reindex",
"description": "Re-index pipeline: chunks + vectors + TKG",
"version": "1.0",
"enabled": true,
"stages": [
{
"name": "chunk",
"processor_type": "chunk",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "vectorize",
"processor_type": "vectorize",
"required": true,
"enabled": true,
"timeout_secs": 3600
},
{
"name": "tkg",
"processor_type": "tkg",
"required": false,
"enabled": true,
"timeout_secs": 7200
}
]
}
}
}
}
}
@@ -0,0 +1,196 @@
# Face Groups 持久化設計 V1.0
> 日期:2026-11-07|目的:建立 face group 的永久化儲存,作為全域 identity 管理的基礎
---
## 1. 設計目標
| 目標 | 說明 |
|---|---|
| **永久化** | Face group 資訊獨立保存,不依賴 DB 或 face_cluster.json |
| **可視化** | UI 可點擊數字直接查看 JSON 內容 |
| **Identity 基礎** | 未來作為跨檔案 identity 匹配的介面 |
| **區別於 cluster** | face_cluster.json = 演算法產出;face_groups.json = 使用者管理結果 |
---
## 2. 檔案規格
### 2.1 檔案位置與命名
```
/Users/accusys/momentry/output/{file_uuid}.face_groups.json
```
### 2.2 JSON 結構
```json
{
"schema_version": "1.0",
"file_uuid": "b496a68800f90770aa7246c877f38985",
"file_name": "020.mp4",
"updated_at": "2026-11-07T12:00:00Z",
"total_groups": 3,
"total_traces": 12,
"groups": [
{
"group_id": 1902,
"name": "Person 1",
"origin_cluster_id": "Person_1",
"trace_ids": [1, 2, 3, 4, 6, 9, 10, 13],
"trace_count": 8,
"representative_trace": 6,
"created_at": "2026-11-07T10:00:00Z",
"updated_at": "2026-11-07T12:00:00Z",
"metadata": {
"merged_from": ["Person_0"],
"manual_rename": false
}
},
{
"group_id": 1905,
"name": "Person 2",
"origin_cluster_id": "Person_2",
"trace_ids": [7, 12],
"trace_count": 2,
"representative_trace": 7,
"created_at": "2026-11-07T10:00:00Z",
"updated_at": "2026-11-07T10:00:00Z",
"metadata": {}
},
{
"group_id": 1906,
"name": "Person 5",
"origin_cluster_id": "Person_5",
"trace_ids": [15, 16],
"trace_count": 2,
"representative_trace": 15,
"created_at": "2026-11-07T10:00:00Z",
"updated_at": "2026-11-07T10:00:00Z",
"metadata": {}
}
]
}
```
### 2.3 欄位說明
| 欄位 | 類型 | 說明 |
|---|---|---|
| `schema_version` | string | 格式版本,用於未來升級 |
| `file_uuid` | string | 檔案唯一識別 |
| `file_name` | string | 原始檔名(方便識別) |
| `updated_at` | string | 最後更新時間(ISO 8601) |
| `total_groups` | int | 群組總數 |
| `total_traces` | int | 所有群組的 trace 總數 |
| `groups[]` | array | 群組列表 |
| `groups[].group_id` | int | DB face_groups.id |
| `groups[].name` | string | 群組顯示名稱 |
| `groups[].origin_cluster_id` | string | 來源 cluster ID(Person_N) |
| `groups[].trace_ids` | int[] | 所屬 trace ID 列表 |
| `groups[].trace_count` | int | trace 數量 |
| `groups[].representative_trace` | int | 代表 trace(最佳幀) |
| `groups[].created_at` | string | 群組建立時間 |
| `groups[].updated_at` | string | 群組最後更新時間 |
| `groups[].metadata` | object | 擴充資訊(merge 歷史、手動改名等) |
---
## 3. 更新時機
| 操作 | 觸發更新 | 說明 |
|---|---|---|
| **Materialize** | ✅ | 首次建立群組時寫入 |
| **Rename Group** | ✅ | 更新 name 和 updated_at |
| **Merge Groups** | ✅ | 合併後更新 trace_ids |
| **Move Trace** | ✅ | 移動 trace 後更新 |
| **Ungroup** | ✅ | 移除 trace 後更新 |
| **Delete Group** | ✅ | 從 groups 陣列移除 |
| **Face Deduplication** | ✅ | 重新聚類後重建 |
---
## 4. UI 整合
### 4.1 點擊數字查看 JSON
```html
<!-- PeopleView.vue -->
<div class="ms-ppl-section-title">
Face Group:
<span class="ms-ppl-section-count ms-clickable"
@click="openFaceGroupsJson"
title="查看 face_groups.json">
({{ faceGroups.length }})
</span>
</div>
```
### 4.2 JSON 檢視器 Modal
```html
<!-- 點擊後彈出 modal 顯示 face_groups.json 內容 -->
<div v-if="showFaceGroupsJson" class="ms-modal-overlay">
<div class="ms-modal-box ms-modal-wide">
<div class="ms-modal-header">
<span class="ms-modal-title">face_groups.json — {{ fileUuid }}</span>
<button class="ms-modal-close" @click="showFaceGroupsJson = false">✕</button>
</div>
<div class="ms-modal-body">
<pre class="ms-json-view">{{ faceGroupsJsonContent }}</pre>
</div>
</div>
</div>
```
---
## 5. 未來擴展:全域 Identity 管理
### 5.1 Identity 匹配介面
```json
{
"identities": [
{
"identity_uuid": "uuid-1234",
"identity_name": "張三",
"face_groups": [
{
"file_uuid": "b496a688...",
"file_name": "020.mp4",
"group_id": 1902,
"group_name": "Person 1",
"confidence": 0.95
},
{
"file_uuid": "8f45f14f...",
"file_name": "078.mp4",
"group_id": 47,
"group_name": "Person 0",
"confidence": 0.88
}
]
}
]
}
```
### 5.2 跨檔案身份聚合
- 每個 `face_groups.json` 作為單檔身份基礎
- 通過 embedding 相似度匹配不同檔案的相似群組
- 聚合為全域 `identities.json`
---
## 6. 實作計畫
| 階段 | 任務 | 檔案 |
|---|---|---|
| **Phase 1** | 建立 `save_face_groups_json()` 函數 | `schema.rs` |
| **Phase 2** | 在所有 group 操作後呼叫保存 | `profile.rs` |
| **Phase 3** | 新增 API 端點讀取 JSON | `profile.rs` |
| **Phase 4** | UI 整合點擊查看功能 | `PeopleView.vue` |
| **Phase 5** | Identity 匹配介面(未來) | 待定 |
@@ -0,0 +1,148 @@
# Face Groups 正規化設計 V1.0(方案 C)
> 日期:2026-11-06 狀態:已實作並部署(Phase 1);Phase 2 配套見 §7
> 涉及:`schema.rs` / `profile.rs` / `postgres_db.rs` / `PeopleView.vue` / `store.ts`
> 前置文件:複雜度盤點(4 結構缺陷)、方案 A/B/C 比較
---
## 1. 核心決策:name 從「每筆 trace 的屬性」升級為「獨立實體」
### 1.1 資料模型(三層)
```
face_groups(群組實體 — 群組名字住在這裡)
├─ id BIGSERIAL PK
├─ file_uuid 歸屬檔案(暫不跨檔共享)
├─ name ★ 唯一权威群組名
├─ origin_cluster_id 來源 auto cluster(Person_N),similarity 由此 join
├─ sort_index 顯示排序
├─ properties JSONB 擴充欄位
└─ UNIQUE (file_uuid, name)
trace_profiles(trace 表示層 — 歸屬用外鍵)
├─ group_id BIGINT FK → face_groups(id) ON DELETE 置 NULL 語意
└─ name ↓ 降級為 caption(見 §2)
tkg_nodes(KG 圖層)
└─ label ↓ 降級為純顯示鏡射,非資料來源
```
### 1.2 不變式(Invariant)
| # | 不變式 | 違反後果 |
|---|---|---|
| I1 | 群組的唯一識別 = `face_groups.id`;名稱改變不改變 id | rename 後引用(undo snapshot、一致性檢查)全失效 |
| I2 | trace 是否屬於某群組 **只看** `trace_profiles.group_id` | 舊 name 比對路徑殘留 → 幽靈群組 |
| I3 | 同一 `(file_uuid, name)` 只能有一個 group row | 重複群組/合併語意錯亂 |
| I4 | `group_id IS NULL` ⇔ trace 屬於 Unassigned | Unassigned 僞群組若被物化成 row,Pending Faces 邏輯失效 |
| I5 | rename = `face_groups` 單筆 UPDATE;caption/label 同步屬於**鏡射維護**,失敗不影響 rename 正確性 | — |
---
## 2. `trace_profiles.name` 的新語意:caption(棄權週期)
`tp.name` 從「群組名來源」降級為**每 trace 的顯示 caption 鏡射**。
### 2.1 誰還能寫 tp.name(寫入白名單 — 2026-11-06 生效)
| 呼叫點 | 行為 | 合法性 |
|---|---|---|
| `profile.rs` rename 分支 | `UPDATE tp SET name = 群組新名 WHERE group_id = $3`(單條 SQL 鏡射整群) | ✅ 鏡射維護 |
| `profile.rs` move 分支 self-healing | INSERT 時帶 name;**已存在 row 不改 name** | ⚠️ 見 G2 |
| `trace_agent_api.rs` hard_delete (=unassign) | 重置為 `Face Trace {id}` | ✅(但需同步清 group_id → G1) |
| undo / snapshot restore | 還原 name + `get_or_create_group` re-attach | ✅ name-less restore 設計 |
| `trace_sync.rs::sync_trace_label` | worker 端同步 label | ⚠️ 見 G4 |
### 2.2 讀取規則
- **讀取群組**:一律 `face_groups` × `tp.group_id` join。新代碼**禁止** `WHERE tp.name = ?` / `GROUP BY tp.name` 作為群組語意。
- 顯示 caption:允許讀 `tp.name`,但 fallback 順序 = `face_groups.name (by group_id)` → `tp.name` → "Unassigned"。
### 2.3 棄權時間表
| 階段 | 內容 |
|---|---|
| Phase 1(已完成) | 新表 + group_id 讀寫全走新模型;backfill 保留(`ensure_face_groups_schema`,幂等) |
| Phase 2(本文件 §7 修復清單) | 補齊 6 個缺口;backfill 排除 `Person_%` |
| Phase 3(觀察期 ≥ 2 週) | 現署 caption 廣播(rename 同步 tp.name + tkg label);僅供 search_people 過渡查詢 |
| Phase 4(最終) | `tp.name` 語意窄化為「未歸組 trace 的暫名」;search_people 改 join face_groups;tkg_nodes.label 由查詢時 join 合成,停寫 |
---
## 3. 讀取路徑(單一來源)
```
face-groups / cluster-results 读取
① materialize_auto_groups(file_uuid)
face_cluster.json 的 Person_N cluster → face_groups row(幂等)
・成員已全歸組的 cluster:skip
・部分歸組:只補未涵蓋 cluster;INSERT ... ON CONFLICT DO UPDATE
SET group_id = COALESCE(tp.group_id, $4) — 永不覆蓋既有歸屬
② SELECT FROM face_groups LEFT JOIN trace_profiles ON group_id
③ Unassigned = tp WHERE group_id IS NULL(輔以 single_frame filter 設定)
```
- `face_cluster.json` 僅供 frames / similarity / representative 讀取(similarity 以 `origin_cluster_id` join)。
- fallback 全有全無開關已刪除;DB 有 0 群組時自然顯示全 Unassigned。
## 4. 寫入路徑(mutation 設計)
| 操作 | 寫入 | 備註 |
|---|---|---|
| **Create & Move** | `get_or_create_group` → `UPDATE tp SET group_id` | FS/People 卡片通用;FS 卡不消失(Pending Faces 對 Qdrant `identity_id=0` 查詢) |
| **Move to existing** | 同上(命中既有 row,不 INSERT) | |
| **Rename** | `UPDATE face_groups SET name` ×1 → caption 鏡射 ×2(tp 群內單條 UPDATE、tkg label ANY($3)) | rename vs move 判定:提供的 traces 恰好 = 該群全部成員 |
| **Merge groups** | 成員 re-point 到 target group → 刪除清空的 source group rows | 空群組才刪 |
| **Ungroup / unassign** | `UPDATE tp SET group_id = NULL, name='Face Trace N'` | **不得**建立 "Unassigned" group row(見 G3) |
| **Undo** | name-less restore:`get_or_create_group(名稱)` + re-attach | group row 缺也能救回 |
| **Delete group row** | 僅在群組 0 成員時允許(merge / 清孤兒) | FK 為此目的鎖 |
## 5. Boot 行為(`ensure_face_groups_schema`,幂等)
1. CREATE TABLE face_groups(IF NOT EXISTS)
2. `ALTER TABLE tp ADD COLUMN group_id`
3. Backfill A:tp.name(排除 `Face Trace %`、`Trace %`)→ group rows(ON CONFLICT nothing)
4. Backfill B:`tp.group_id IS NULL` 者,依 `(file_uuid,name)` 掛回
⚠️ Backfill A 的排除清單**必須包含 `Person_%`**(Phase 2 修復,見 G5),否則 worker 重跑 cluster 寫入的 Person_N caption 會在重啟時復活成群組。
## 6. Audit 結果(2026-11-06 全碼掃描)
直接寫 tp.name 的位置已收斂為 §2.1 白名單;仍觸及 trace_profiles 的其他模組分類:
| 模組 | 用法 | 分類 |
|---|---|---|
| `search.rs` | 讀 `start_frame…vlm_*` | 無 name 依賴 ✅ |
| `universal_search.rs:603/775` | `SELECT tp.name` for people 搜尋 | caption 讀取,過渡合法(Phase 4 改 join)|
| `identity_api.rs:1190` | people 查詢 | 同上 |
| `agent/tools.rs:1931` | trace 查詢 | 同上 |
| `files.rs / scan.rs` | unregister / 計數 | cascade-safe,無 name 語意 ✅ |
| `trace_agent_api.rs` | unassign 重置、snapshot、undo | 見 G1/G6 |
| `trace_sync.rs` | worker label 廣播 | 見 G4 |
| `job_worker.rs:3661/4562` | cluster 後 label 同步 | 見 G4 |
## 7. Phase 2 配套修復清單(本文件的主要交付)
| # | 缺口 | 位置 | 修復設計 |
|---|---|---|---|
| **G1** | Unassign(hard_delete 新語意)只重置 name/label,**沒清 `tp.group_id`** → trace 仍掛原群組 | `trace_agent_api.rs` hard_delete 分支 | 重置時加 `UPDATE tp SET group_id = NULL`;undo 沿用 `get_or_create_group` re-attach |
| **G2** | Move 到既有群組後,已存在 tp row 的 caption 不更新 → people 搜尋顯示舊名 | `profile.rs` move 分支 | move 分支補一條 `UPDATE tp SET name = 目標群組名 WHERE trace_id = ANY(...) AND group_id = 新gid`(只鏡射成員,不動他群) |
| **G3** | Studio Ungroup 傳 `name: 'Unassigned'` → 後端會物化一個叫 "Unassigned" 的實體群組,違反 I4 | `profile.rs` update_trace_profile_group_handler | handler 開頭偵測 `req.name.trim().eq_ignore_ascii_case("unassigned")` → spin off detach 分支:`group_id = NULL` + name 重置,不建 group row |
| **G4** | `sync_trace_label`(cluster 重跑後)會把 `Person_N` 廣播進 tp.name → 重啟 backfill 復活 Person 群組 + 顯示假名回流 | `trace_sync.rs` 呼叫端(job_worker:3661) | 若 trace 已有 group_id:tp.name 用 `face_groups.name` 鏡射值,不用 Person_N;無 group_id 才允許 Person_N |
| **G5** | Boot Backfill A 排除清單缺 `Person_%` | `schema.rs` ensure | WHERE 加 `AND NOT (name LIKE 'Person\_%')` |
| **G6** | `merge_trace` 的 undo 還原 name 但無 group re-attach | `trace_agent_api.rs` undo 段 | 沿用 `schema::get_or_create_group` + attach(同 profile.rs 通用 undo) |
## 8. 測試守則(回歸用)
1. rename 後 ** 重啟 server** → 無同名 ghost 群組(I1/I3)
2. move → 重啟 → 歸屬不變(COALESCE 修復)
3. Ungroup → 群組清單不出現 "Unassigned" 實體;trace 回 Pending Faces
4. cluster 重跑 → 已歸組 trace 不被 Person_N 拉走
5. 雙重啟動失敗群組數 const(幂等)
6. search_people 查新名 → rename 後立即命中;move 後 ≤ Phase2 修復時間命中
## 9. 未開放的需求(記錄語意,避免誤解現狀)
- **跨檔 identity**(同一人跨多支影片):現 `face_groups` 以 file_uuid 為界。未來需要時靠 identity 表(Qdrant `identity_id`)向上聚合,face_groups 不改結構。
- **群組層 properties**:欄位已備(JSONB),UI 未消費。
@@ -0,0 +1,664 @@
# Face Pipeline 逐步檢查規範 V1.0
> 日期:2026-11-07|適用範圍:face → face_traced → face_cluster → face_groups (DB)
---
## 0. 總覽:上下游關係與產出物
```
video.mp4
│
├─① face detection(swift_face)
│ → output/{uuid}.face.json
│ → Qdrant _faces(512D embedding + payload)
│
├─② face tracing(rust_store_traced_faces)
│ → output/{uuid}.face_traced.json
│
├─③ face clustering(rust_face / swift_cluster)
│ → output/{uuid}.face_cluster.json
│
└─④ materialize + group entity(API on-demand / boot backfill)
→ DB: face_groups + trace_profiles.group_id
```
每個步驟都有**輸入驗證 → 執行 → 產出驗證 → 跨步驗證**四段。
---
## 1. Face Detection(① → face.json + Qdrant)
### 1.1 輸入驗證
| 檢查項 | 方法 | 合格標準 |
|---|---|---|
| 影片檔案存在 | `os.path.exists(video_path)` | ✅ True |
| 影片可讀 | `probe_json` 有 `width > 0` | ✅ 非零 |
| ffmpeg 可用 | `which ffmpeg` / `ffprobe -version` | ✅ 可執行 |
| FaceNet 模型存在 | 模型路徑 `os.path.exists(model_path)` | ✅ True |
### 1.2 執行後產出驗證(face.json)
| 檢查項 | 欄位 / 方法 | 合格標準 |
|---|---|---|
| 檔案存在 | `{output_dir}/{uuid}.face.json` | ✅ 存在 |
| JSON 可解析 | `json.load()` | ✅ 不拋異常 |
| metadata.processor.name | `d['metadata']['processor']['name']` | ✅ `'face'` |
| metadata.processor.tool | 同上 | ✅ `'swift_face'` |
| total_faces > 0 | `d['total_faces']` | ✅ ≥ 0(無臉可為 0) |
| frame_count > 0 | `d['frame_count']` | ✅ ≥ 1 |
| fps > 0 | `d['fps']` | ✅ ≥ 24 |
| frames 陣列 | `len(d['frames'])` | ✅ == frame_count |
| 每幀有 faces | `all(len(f['faces']) >= 0)` | ✅ |
### 1.3 Embedding 驗證(關鍵!)
```python
def check_embeddings(face_json: dict) -> dict:
results = {'pass': True, 'issues': []}
total = 0
missing = 0
bad_dim = 0
for frame in face_json.get('frames', []):
for face in frame.get('faces', []):
total += 1
emb = face.get('embedding')
if emb is None:
missing += 1
elif not isinstance(emb, list) or len(emb) != 512:
bad_dim += 1
elif not all(isinstance(v, (int, float)) for v in emb):
bad_dim += 1 # 元素非數值
if missing > 0:
results['pass'] = False
results['issues'].append(f'{missing}/{total} faces 缺少 embedding')
if bad_dim > 0:
results['pass'] = False
results['issues'].append(f'{bad_dim}/{total} faces embedding 維度/格式異常')
if total == 0:
results['issues'].append('沒有 face 資料(影片可能無臉)')
results['total'] = total
results['missing'] = missing
results['bad_dim'] = bad_dim
return results
```
| 檢查項 | 合格標準 |
|---|---|
| embedding 存在 | `missing == 0` |
| embedding 維度 | `len(emb) == 512`(FaceNet 標準) |
| embedding 元素 | 全部為 float/int(可序列化為 JSON array) |
### 1.4 Qdrant 驗證
```python
def check_qdrant_points(uuid: str, expected_faces: int) -> dict:
"""檢查 Qdrant _faces collection 是否有對應的 points"""
filter = {"must": [{"key": "file_uuid", "match": {"value": uuid}}]}
# count
count_resp = qdrant.count_points("_faces", filter)
actual_count = count_resp.count
# sample point structure
scroll = qdrant.scroll("_faces", filter, limit=1, with_payload=True, with_vector=True)
return {
'pass': actual_count > 0,
'expected': expected_faces,
'actual': actual_count,
'missing': max(0, expected_faces - actual_count),
'sample_keys': list(scroll[0][0].payload.keys()) if scroll[0] else [],
'vector_dim': len(scroll[0][0].vector) if scroll[0] else 0,
}
```
| 檢查項 | 合格標準 |
|---|---|
| points 數量 | `actual_count >= 0`(可小於 face.json,因 low-confidence 可能被過濾) |
| vector 維度 | `vector_dim == 512` |
| payload 必要欄位 | 包含 `file_uuid`, `frame`, `trace_id`, `confidence`, `identity_id` |
| identity_id 預設 | 新插入的 face 應為 `identity_id: 0`(未歸屬) |
### 1.5 跨步驗證(face.json vs Qdrant)
| 檢查項 | 方法 | 合格標準 |
|---|---|---|
| face count 一致 | `face.json total_faces` ≈ Qdrant count | Qdrant ≤ face.json(允許過濾) |
| trace_id 有值 | face.json 每幀 face 有 `trace_id` | ✅ 非 null |
| face_id 唯一 | 全檔 face_id 無重複 | ✅ |
---
## 2. Face Tracing(② → face_traced.json)
### 2.1 輸入依賴
| 依賴 | 檢查 |
|---|---|
| face.json 存在 | ✅ 檔案存在且 total_faces > 0 |
| 影片存在 | ✅ |
| min_trace_len, min_confidence | ✅ 參數有效 |
### 2.2 產出驗證
| 檢查項 | 欄位 | 合格標準 |
|---|---|---|
| 檔案存在 | `{uuid}.face_traced.json` | ✅ |
| JSON 可解析 | `json.load()` | ✅ |
| traces 陣列 | `len(d['traces'])` | ✅ ≥ 1 |
| 每筆 trace 必要欄位 | `trace_id`, `frame_count`, `start_frame`, `end_frame`, `best_confidence` | ✅ 全有 |
| trace_id 唯一 | 全檔 trace_id 不重複 | ✅ |
| frame_count 合理 | `1 ≤ frame_count ≤ face.json frame_count` | ✅ |
| start ≤ end | `start_frame ≤ end_frame` | ✅ |
| confidence 範圍 | `0 ≤ avg_confidence ≤ 1`, `0 ≤ best_confidence ≤ 1` | ✅ |
| face_instances 存在 | 每筆 trace 有 `face_instances` 陣列 | ✅ 非空 |
| face_instances 指向有效 face_id | 每個 face_id 可在 face.json 找到 | ✅ |
```python
def check_face_traced(traced: dict, face_json: dict) -> dict:
results = {'pass': True, 'issues': []}
traces = traced.get('traces') or []
if not traces:
results['pass'] = False
results['issues'].append('traces 陣列為空')
return results
# trace_id 唯一性
tids = [t['trace_id'] for t in traces]
if len(tids) != len(set(tids)):
results['pass'] = False
results['issues'].append(f'trace_id 有重複:{len(tids)} vs {len(set(tids))} unique')
# face_instances 指向有效性
all_face_ids = set()
for fr in face_json.get('frames', []):
for fa in fr.get('faces') or []:
all_face_ids.add(fa.get('face_id'))
orphan_instances = 0
for t in traces:
for fi in t.get('face_instances', []):
fid = fi.get('face_id')
if fid and fid not in all_face_ids:
orphan_instances += 1
if orphan_instances > 0:
results['issues'].append(f'{orphan_instances} face_instances 指向不存在的 face_id')
# confidence 範圍
for t in traces:
bc = t.get('best_confidence', -1)
ac = t.get('avg_confidence', -1)
if not (0 <= bc <= 1):
results['issues'].append(f'trace {t["trace_id"]}: best_confidence={bc} 超出 [0,1]')
if not (0 <= ac <= 1):
results['issues'].append(f'trace {t["trace_id"]}: avg_confidence={ac} 超出 [0,1]')
results['trace_count'] = len(traces)
results['total_frames_traced'] = sum(t.get('frame_count', 0) for t in traces)
return results
```
### 2.3 跨步驗證(face.json vs face_traced.json)
| 檢查項 | 合格標準 |
|---|---|
| 所有 face.json 的 face_id 被 trace 覆蓋 | `face_instances` 總數 = face.json total_faces |
| trace frame 總和 ≥ face count | 每個 face 都屬於某個 trace |
| trace_id 在 Qdrant payload 中有對應 | Qdrant points 的 `trace_id` 與 traced 一致 |
---
## 3. Face Clustering(③ → face_cluster.json)
### 3.1 輸入依賴
| 依賴 | 檢查 |
|---|---|
| face_traced.json | ✅ traces > 0 |
| face.json | ✅ embedding 全部 512D |
| 模型(facenet / embedding) | ✅ 存在 |
### 3.2 產出驗證
| 檢查項 | 欄位 | 合格標準 |
|---|---|---|
| 檔案存在 | `{uuid}.face_cluster.json` | ✅ |
| clusters 陣列 | `len(d['clusters'])` | ✅ ≥ 1 |
| frames 陣列 | `len(d['frames'])` | ✅ ≥ 1 |
| 每筆 cluster 必要欄位 | `cluster_id`, `face_count`, `representative_face`, `similarity` | ✅ 全有 |
| cluster_id 唯一 | 全檔不重複 | ✅ |
| face_count > 0 | 每群至少 1 face | ✅ |
| similarity 結構 | 有 `min`, `avg`, `threshold` | ✅ 全為 float |
| frame faces 必要欄位 | `cluster_id`, `confidence`, `face_id`, `trace_id` | ✅ 全有 |
```python
def check_face_cluster(cluster_json: dict, traced: dict) -> dict:
results = {'pass': True, 'issues': []}
clusters = cluster_json.get('clusters') or []
frames = cluster_json.get('frames') or []
if not clusters:
results['pass'] = False
results['issues'].append('clusters 為空(可能影片人臉太少或 threshold 太高)')
return results
# cluster_id 唯一
cids = [c['cluster_id'] for c in clusters]
if len(cids) != len(set(cids)):
results['pass'] = False
results['issues'].append(f'cluster_id 重複')
# face_count 總和
total_clustered = sum(c['face_count'] for c in clusters)
# frame faces 與 clusters 一致性
frame_face_count = sum(len(f.get('faces') or []) for f in frames)
if frame_face_count != total_clustered:
results['issues'].append(
f'clusters face_count 總和={total_clustered} != frames 中 faces 數={frame_face_count}'
)
# cluster faces 的 cluster_id 必須存在於 clusters 列表
valid_cids = set(cids)
bad_faces = 0
for f in frames:
for fa in f.get('faces') or []:
if fa.get('cluster_id') not in valid_cids:
bad_faces += 1
if bad_faces > 0:
results['issues'].append(f'{bad_faces} frame faces 的 cluster_id 不在 clusters 列表中')
# similarity 驗證
for c in clusters:
sim = c.get('similarity') or {}
for key in ['min', 'avg', 'threshold']:
if key not in sim:
results['issues'].append(f'cluster {c["cluster_id"]} 缺少 similarity.{key}')
elif not isinstance(sim[key], (int, float)):
results['issues'].append(f'cluster {c["cluster_id"]} similarity.{key} 非數值')
# trace_id 對應:每個 cluster 的 face 都應有 trace_id
faces_without_trace = 0
for f in frames:
for fa in f.get('faces') or []:
if fa.get('trace_id') is None:
faces_without_trace += 1
if faces_without_trace > 0:
results['issues'].append(f'{faces_without_trace} cluster faces 缺少 trace_id')
results['cluster_count'] = len(clusters)
results['total_clustered_faces'] = total_clustered
results['frame_count'] = len(frames)
return results
```
### 3.3 跨步驗證
| 檢查項 | 合格標準 |
|---|---|
| 每個 traced face 出現在 cluster | `face_cluster frames 總 faces` = `face.json total_faces` |
| cluster_id 命名 | `Person_N` 格式(自動命名) |
| similarity.threshold 合理 | 通常 ≥ 0.5(視模型而定) |
| representative_face 存在 | 每群有代表臉 |
---
## 4. Materialize + Face Groups(④ → DB)
### 4.1 觸發時機
- 首次呼叫 `/api/v1/cluster-results`(自動 materialize)
- Boot backfill(`ensure_face_groups_schema`)
### 4.2 產出驗證(DB)
| 檢查項 | SQL | 合格標準 |
|---|---|---|
| face_groups 有 rows | `SELECT COUNT(*) FROM face_groups WHERE file_uuid=?` | ✅ ≥ cluster 數 |
| group 名稱不重複 | `SELECT COUNT(DISTINCT name)` = `COUNT(*)` | ✅ |
| 每群至少 1 member | `COUNT(tp.trace_id) >= 1 per group` | ✅ |
| trace_profiles.group_id 不懸空 | `SELECT COUNT(*) FROM trace_profiles WHERE group_id IS NOT NULL AND group_id NOT IN (SELECT id FROM face_groups)` | ✅ = 0 |
| origin_cluster_id 對應 | `face_groups.origin_cluster_id` 存在於 `face_cluster.json clusters[*].cluster_id` | ✅ |
| 無重複群組 | 同名 cluster 不會被 materialize 兩次 | ✅ |
| dissolved 標記不影響顯示 | `properties @> '{"dissolved": true}'` 的群組不出現在 API 回應 | ✅ |
### 4.3 API 回應驗證
| 端點 | 檢查項 | 合格標準 |
|---|---|---|
| `/cluster-results` | `face_groups[].trace_ids` 不為空 | ✅ 每群至少 1 trace_id |
| `/cluster-results` | `frames[].faces[].cluster_id` 對應到 group_id | ✅ 可映射 |
| `/cluster-results` | `frames[].faces[].trace_id` 存在 | ✅ 非 null |
| `/face-groups` | `face_groups[].trace_count > 0` | ✅ |
| `/face-groups` | `unassigned_traces` 只含 group_id IS NULL 的 trace | ✅ |
```python
def check_face_groups_db(uuid: str, cluster_json: dict, api_response: dict) -> dict:
"""驗證 face_groups DB 與 face_cluster.json 的一致性"""
results = {'pass': True, 'issues': []}
groups = api_response.get('face_groups', [])
frames = api_response.get('frames', [])
if not groups:
results['pass'] = False
results['issues'].append('API 返回 0 個群組')
return results
# 每群都有 trace_ids
empty_groups = [g for g in groups if not g.get('trace_ids')]
if empty_groups:
results['issues'].append(
f'{len(empty_groups)} 個群組 trace_ids 為空: {[g["name"] for g in empty_groups]}'
)
# frames 中 cluster_id 映射到有效 group_id
group_ids = {g['group_id'] for g in groups}
frame_face_ids = set()
for f in frames:
for fa in f.get('faces') or []:
cid = fa.get('cluster_id')
if cid and cid not in group_ids:
results['issues'].append(f'frame face cluster_id={cid} 不對應任何 group')
if fa.get('trace_id') is not None:
frame_face_ids.add(fa['trace_id'])
# trace_id 一致性:DB groups 的 trace_ids 集合 ≈ frames 中的 trace_id 集合
db_traces = set()
for g in groups:
db_traces.update(g.get('trace_ids', []))
if db_traces != frame_face_ids:
missing_in_db = frame_face_ids - db_traces
extra_in_db = db_traces - frame_face_ids
if missing_in_db:
results['issues'].append(f'{len(missing_in_db)} traces 在 frames 中但不在 DB groups 中')
if extra_in_db:
results['issues'].append(f'{len(extra_in_db)} traces 在 DB groups 中但不在 frames 中')
return results
```
---
## 5. 完整檢查腳本
以下是單一指令跑完整個 face pipeline 檢查的 Python 腳本:
```python
#!/usr/bin/env python3.11
"""
face_pipeline_check.py — 完整檢查 face → traced → cluster → groups
用法:python3.11 face_pipeline_check.py <uuid> [--api-key KEY] [--api-url URL]
"""
import json
import sys
import os
import argparse
import requests
OUTPUT_DIR = '/Users/accusys/momentry/output'
def check_file(uuid):
"""Step 0: 檢查檔案存在"""
files = {
'face': f'{uuid}.face.json',
'traced': f'{uuid}.face_traced.json',
'cluster': f'{uuid}.face_cluster.json',
}
status = {'exists': {}}
for name, fname in files.items():
path = os.path.join(OUTPUT_DIR, fname)
status['exists'][name] = os.path.exists(path)
if status['exists'][name]:
status['exists'][f'{name}_size'] = os.path.getsize(path)
missing = [n for n, e in status['exists'].items() if isinstance(e, bool) and not e]
if missing:
print(f'❌ 缺少檔案: {missing}')
return status
def check_face_json(uuid):
"""Step 1: face.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face.json 不存在']}
d = json.load(open(path))
issues = []
total = d.get('total_faces', 0)
fc = d.get('frame_count', 0)
fps = d.get('fps', 0)
frames = d.get('frames') or []
if fc == 0: issues.append('frame_count = 0')
if fps < 1: issues.append(f'fps = {fps} (< 1)')
if len(frames) != fc: issues.append(f'frames 數量 {len(frames)} != frame_count {fc}')
# embedding 檢查
emb_total = 0; emb_missing = 0; emb_bad = 0
for fr in frames:
for fa in fr.get('faces') or []:
emb_total += 1
emb = fa.get('embedding')
if emb is None:
emb_missing += 1
elif not isinstance(emb, list) or len(emb) != 512:
emb_bad += 1
if emb_missing: issues.append(f'{emb_missing}/{emb_total} faces 缺少 embedding')
if emb_bad: issues.append(f'{emb_bad}/{emb_total} faces embedding 非 512D')
return {'pass': len(issues) == 0, 'total_faces': total, 'issues': issues}
def check_face_traced(uuid, face_result):
"""Step 2: face_traced.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_traced.json 不存在']}
d = json.load(open(path))
issues = []
traces = d.get('traces') or []
if not traces: issues.append('traces 為空')
# trace_id 唯一
tids = [t['trace_id'] for t in traces]
if len(tids) != len(set(tids)):
issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique')
# frame_count 合理性
for t in traces:
if t.get('frame_count', 0) < 1:
issues.append(f'trace {t["trace_id"]}: frame_count < 1')
bc = t.get('best_confidence', -1)
if not (0 <= bc <= 1):
issues.append(f'trace {t["trace_id"]}: best_confidence={bc}')
return {'pass': len(issues) == 0, 'trace_count': len(traces), 'issues': issues}
def check_face_cluster(uuid, traced_result):
"""Step 3: face_cluster.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_cluster.json 不存在']}
d = json.load(open(path))
issues = []
clusters = d.get('clusters') or []
frames = d.get('frames') or []
if not clusters: issues.append('clusters 為空')
# cluster_id 唯一
cids = [c['cluster_id'] for c in clusters]
if len(cids) != len(set(cids)):
issues.append('cluster_id 重複')
# frame faces 完整性
frame_faces = []
for f in frames:
for fa in f.get('faces') or []:
frame_faces.append(fa)
if not frame_faces: issues.append('frames 中沒有 faces')
# cluster_id 一致性
valid_cids = set(cids)
bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids)
if bad: issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 中')
# trace_id 存在
no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None)
if no_trace: issues.append(f'{no_trace} frame faces 缺少 trace_id')
return {'pass': len(issues) == 0, 'cluster_count': len(clusters),
'frame_face_count': len(frame_faces), 'issues': issues}
def check_api(uuid, api_key, api_url):
"""Step 4: API 回應驗證"""
headers = {'X-API-Key': api_key}
issues = []
# cluster-results
url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}'
try:
resp = requests.get(url, headers=headers, timeout=30)
if resp.status_code != 200:
issues.append(f'cluster-results HTTP {resp.status_code}')
return {'pass': False, 'issues': issues}
d = resp.json()
except Exception as e:
issues.append(f'cluster-results 請求失敗: {e}')
return {'pass': False, 'issues': issues}
groups = d.get('face_groups', [])
frames = d.get('frames', [])
if not groups:
issues.append('face_groups 為空')
empty_groups = [g for g in groups if not g.get('trace_ids')]
if empty_groups:
issues.append(f'{len(empty_groups)} 群組 trace_ids 為空')
# frames faces 完整性
f_faces = []
for f in frames:
for fa in f.get('faces') or []:
f_faces.append(fa)
no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None)
if no_trace:
issues.append(f'{no_trace} API frame faces 缺少 trace_id')
return {'pass': len(issues) == 0, 'group_count': len(groups),
'frame_count': len(frames), 'issues': issues}
def main():
parser = argparse.ArgumentParser(description='Face Pipeline Checker')
parser.add_argument('uuid', help='file_uuid to check')
parser.add_argument('--api-key', default='', help='API key')
parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL')
parser.add_argument('--quiet', '-q', action='store_true', help='Only show pass/fail')
args = parser.parse_args()
results = {'uuid': args.uuid, 'steps': {}}
overall_pass = True
# Step 0
r0 = check_file(args.uuid)
results['steps']['0_files'] = r0
# Step 1
r1 = check_face_json(args.uuid)
results['steps']['1_face_json'] = r1
if not r1['pass']: overall_pass = False
# Step 2
r2 = check_face_traced(args.uuid, r1)
results['steps']['2_face_traced'] = r2
if not r2['pass']: overall_pass = False
# Step 3
r3 = check_face_cluster(args.uuid, r2)
results['steps']['3_face_cluster'] = r3
if not r3['pass']: overall_pass = False
# Step 4
r4 = check_api(args.uuid, args.api_key, args.api_url)
results['steps']['4_api'] = r4
if not r4['pass']: overall_pass = False
# Print
if args.quiet:
print('PASS' if overall_pass else 'FAIL')
for name, r in results['steps'].items():
if r.get('issues'):
for i in r['issues']:
print(f' {name}: {i}')
else:
print(f'\n{"="*60}')
print(f'Face Pipeline Check: {args.uuid}')
print(f'{"="*60}\n')
for name, r in results['steps'].items():
icon = '✅' if r.get('pass', True) else '❌'
print(f'{icon} {name}')
if r.get('issues'):
for i in r['issues']:
print(f' ⚠️ {i}')
# Print stats
for key in ['total_faces', 'trace_count', 'cluster_count', 'frame_face_count', 'group_count', 'frame_count']:
if key in r:
print(f' {key}: {r[key]}')
print()
print(f'\nOverall: {"✅ PASS" if overall_pass else "❌ FAIL"}')
print()
return 0 if overall_pass else 1
if __name__ == '__main__':
sys.exit(main())
```
---
## 6. 檢查結果判定表
| 階段 | 通過 | 警告 | 失敗 |
|---|---|---|---|
| face.json | total_faces ≥ 0, embedding 全部 512D | total_faces = 0(影片無臉) | embedding missing/bad |
| face_traced | traces ≥ 1, trace_id 唯一, confidence ∈ [0,1] | frame_count 總和 < face_count | traces 為空 / 重複 ID |
| face_cluster | clusters ≥ 1, frame faces 完整性 | clusters 數量異常多/少 | clusters 為空 / cluster_id 不一致 |
| API/DB | groups ≥ 1, 每群 trace_ids 不為空 | — | groups 為空 / trace_ids 全空 |
---
## 7. 使用方式
```bash
# 完整檢查單一檔案
python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \
--api-key "muser_xxx" --api-url "http://localhost:3002"
# 快速模式(只輸出 PASS/FAIL)
python3.11 face_pipeline_check.py b496a68800f90770aa7246c877f38985 \
--api-key "muser_xxx" -q
# 批次檢查所有已完成檔案
for uuid in $(psql -t -A -c "SELECT file_uuid FROM videos WHERE status='completed'"); do
python3.11 face_pipeline_check.py $uuid --api-key "muser_xxx" -q
done
```
+33 -41
View File
@@ -2,46 +2,38 @@
<!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.agent</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/start.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/Users/accusys</string>
<key>USER</key>
<string>accusys</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin</string>
<key>DATABASE_URL</key>
<string>postgres://accusys@localhost:5432/momentry</string>
<key>REDIS_URL</key>
<string>redis://accusys:accusys@localhost:6379</string>
<key>OLLAMA_HOST</key>
<string>http://localhost:11434</string>
</dict>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/logs/stdout.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/logs/stderr.log</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1</string>
<key>ProcessType</key>
<string>Interactive</string>
<key>EnvironmentVariables</key>
<dict>
<key>DATABASE_URL</key>
<string>postgres://accusys@localhost:5432/momentry</string>
<key>HOME</key>
<string>/Users/accusys</string>
<key>OLLAMA_HOST</key>
<string>http://localhost:11434</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/Users/accusys/.cargo/bin</string>
<key>REDIS_URL</key>
<string>redis://accusys:accusys@localhost:6379</string>
<key>USER</key>
<string>accusys</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.agent</string>
<key>ProcessType</key>
<string>Interactive</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/momentry_core_0.1/momentry_runtime/start.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/agent.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/agent.log</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1</string>
</dict>
</plist>
@@ -5,7 +5,9 @@
<key>EnvironmentVariables</key>
<dict>
<key>MOMENTRY_OUTPUT_DIR</key>
<string>/Users/accusys/momentry/output</string>
<string>/Users/accusys/momentry/output/demo</string>
<key>MOMENTRY_SFTP_ROOT</key>
<string>/Users/accusys/momentry/var/sftpgo/data/demo</string>
</dict>
<key>GroupName</key>
<string>staff</string>
@@ -20,9 +22,9 @@
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/momentry_api.error.log</string>
<string>/Users/accusys/momentry/logs/core_api.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/momentry_api.log</string>
<string>/Users/accusys/momentry/logs/core_api.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
+28 -36
View File
@@ -2,41 +2,33 @@
<!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.caddy</string>
<key>UserName</key>
<string>root</string>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/opt/homebrew/var/lib/caddy</string>
<key>XDG_DATA_HOME</key>
<string>/opt/homebrew/var/lib</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/caddy</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/caddy/bin/caddy</string>
<string>run</string>
<string>--config</string>
<string>/Users/accusys/momentry/etc/Caddyfile</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/caddy.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/caddy.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/opt/homebrew/var/lib/caddy</string>
<key>XDG_DATA_HOME</key>
<string>/opt/homebrew/var/lib</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.caddy</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/caddy/bin/caddy</string>
<string>run</string>
<string>--config</string>
<string>/Users/accusys/momentry/etc/Caddyfile</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/caddy.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/caddy.log</string>
<key>UserName</key>
<string>root</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/caddy</string>
</dict>
</plist>
+30 -38
View File
@@ -2,43 +2,35 @@
<!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.gitea</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/gitea/bin/gitea</string>
<string>web</string>
<string>--config</string>
<string>/Users/accusys/momentry/etc/gitea/app.ini</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>/Users/accusys</string>
<key>GITEA_WORK_DIR</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/gitea.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/gitea.error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>GITEA_WORK_DIR</key>
<string>/Users/accusys/momentry/var/gitea</string>
<key>HOME</key>
<string>/Users/accusys</string>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.gitea</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/gitea/bin/gitea</string>
<string>web</string>
<string>--config</string>
<string>/Users/accusys/momentry/etc/gitea/app.ini</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/gitea.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/gitea.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/gitea</string>
</dict>
</plist>
@@ -2,31 +2,24 @@
<!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.mariadb</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/mariadb</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/mariadb/bin/mariadbd-safe</string>
<string>--datadir=/Users/accusys/momentry/var/mariadb</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/mariadb.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/mariadb.log</string>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.mariadb</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/mariadb/bin/mariadbd-safe</string>
<string>--datadir=/Users/accusys/momentry/var/mariadb</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/mariadb.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/mariadb.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/mariadb</string>
</dict>
</plist>
@@ -2,48 +2,38 @@
<!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.monitor</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1/monitor</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>/Users/accusys/momentry_core_0.1/monitor/control/monitor_control.sh</string>
<string>check</string>
<string>all</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>
</dict>
<key>RunAtLoad</key>
<false/>
<key>StartInterval</key>
<integer>300</integer>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/monitor/monitor.log</string>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/monitor/monitor.error.log</string>
<key>ProcessType</key>
<string>Background</string>
<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>
</dict>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>Label</key>
<string>com.momentry.monitor</string>
<key>ProcessType</key>
<string>Background</string>
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>/Users/accusys/momentry_core_0.1/monitor/control/monitor_control.sh</string>
<string>check</string>
<string>all</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/monitor.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/monitor.log</string>
<key>StartInterval</key>
<integer>300</integer>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry_core_0.1/monitor</string>
</dict>
</plist>
@@ -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,43 +2,35 @@
<!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.ollama</string>
<key>UserName</key>
<string>accusys</string>
<key>EnvironmentVariables</key>
<dict>
<key>OLLAMA_HOST</key>
<string>0.0.0.0:11434</string>
<key>OLLAMA_MODELS</key>
<string>/Users/accusys/momentry/var/ollama/models</string>
<key>OLLAMA_FLASH_ATTENTION</key>
<string>1</string>
<key>OLLAMA_KV_CACHE_TYPE</key>
<string>q8_0</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/ollama</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/ollama/bin/ollama</string>
<string>serve</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/ollama.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/ollama.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>OLLAMA_FLASH_ATTENTION</key>
<string>1</string>
<key>OLLAMA_HOST</key>
<string>0.0.0.0:11434</string>
<key>OLLAMA_KV_CACHE_TYPE</key>
<string>q8_0</string>
<key>OLLAMA_MODELS</key>
<string>/Users/accusys/momentry/var/ollama/models</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.ollama</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/opt/ollama/bin/ollama</string>
<string>serve</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/ollama.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/ollama.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/ollama</string>
</dict>
</plist>
@@ -2,38 +2,30 @@
<!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.postgresql</string>
<key>UserName</key>
<string>accusys</string>
<key>EnvironmentVariables</key>
<dict>
<key>LC_ALL</key>
<string>en_US.UTF-8</string>
</dict>
<key>WorkingDirectory</key>
<string>/Users/accusys</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/pgsql/18.3/bin/postgres</string>
<string>-D</string>
<string>/Users/accusys/pgsql/data</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/postgresql.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/postgresql.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>LC_ALL</key>
<string>en_US.UTF-8</string>
</dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.momentry.postgresql</string>
<key>ProgramArguments</key>
<array>
<string>/Users/accusys/pgsql/18.3/bin/postgres</string>
<string>-D</string>
<string>/Users/accusys/pgsql/data</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/logs/postgresql.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/logs/postgresql.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys</string>
</dict>
</plist>
@@ -28,9 +28,9 @@
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/opt/homebrew/var/log/qdrant.error.log</string>
<string>/Users/accusys/momentry/logs/qdrant.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/qdrant.log</string>
<string>/Users/accusys/momentry/logs/qdrant.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
@@ -11,22 +11,18 @@
<string>/opt/homebrew/opt/redis/bin/redis-server</string>
<string>--port</string>
<string>6379</string>
<string>--bind</string>
<string>0.0.0.0</string>
<string>--requirepass</string>
<string>accusys</string>
<string>--appendonly</string>
<string>yes</string>
<string>--dir</string>
<string>/Users/accusys/momentry/var/redis</string>
<string>--logfile</string>
<string>/Users/accusys/momentry/log/redis.log</string>
<string>/Users/accusys/momentry/var</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>/Users/accusys/momentry/log/redis.error.log</string>
<string>/Users/accusys/momentry/logs/redis.error.log</string>
<key>StandardOutPath</key>
<string>/Users/accusys/momentry/log/redis.log</string>
<key>UserName</key>
<string>accusys</string>
<key>WorkingDirectory</key>
<string>/Users/accusys/momentry/var/redis</string>
<string>/Users/accusys/momentry/logs/redis.log</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>
+4 -1
View File
@@ -1781,7 +1781,10 @@ CREATE TABLE public.sessions (
api_key_id character varying(48) NOT NULL,
created_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
expires_at timestamp with time zone NOT NULL,
last_accessed_at timestamp with time zone
last_accessed_at timestamp with time zone,
ip_address text,
user_agent text,
source text
);
+13 -6
View File
@@ -12,20 +12,28 @@ MODEL = None
TOKENIZER = None
DEVICE = None
def load_model(model_path: str = "google/embeddinggemma-300m"):
def load_model(model_path: str = ""):
global MODEL, TOKENIZER, DEVICE
if MODEL is not None:
return
import os
# 一律使用本地模型目錄,絕不上網
local = os.path.expanduser("~/momentry/models/embeddinggemma-300m")
if not (os.path.isdir(local) and os.path.isfile(os.path.join(local, "config.json"))):
raise RuntimeError(
f"[EmbeddingGemma] Local model not found at {local}. "
"Please copy the model files (config.json, model.safetensors, tokenizer*) to this directory."
)
DEVICE = "mps" if torch.backends.mps.is_available() else "cpu"
dtype = torch.float32
print(f"[EmbeddingGemma] Loading model on {DEVICE} (dtype={dtype})...")
print(f"[EmbeddingGemma] Loading model from local: {local} on {DEVICE} (dtype={dtype})...")
t0 = time.time()
MODEL = AutoModel.from_pretrained(
model_path,
local,
torch_dtype=dtype,
trust_remote_code=True,
).eval().to(DEVICE)
TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
TOKENIZER = AutoTokenizer.from_pretrained(local, trust_remote_code=True)
print(f"[EmbeddingGemma] Loaded in {time.time()-t0:.1f}s on {DEVICE}")
def embed(texts: list[str]) -> list[list[float]]:
@@ -79,7 +87,6 @@ def health():
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=11436)
parser.add_argument("--model", type=str, default="google/embeddinggemma-300m")
args = parser.parse_args()
load_model(args.model)
load_model() # 一律使用 ~/momentry/models/embeddinggemma-300m,絕不上網
app.run(host="0.0.0.0", port=args.port, threaded=True)
+143 -30
View File
@@ -171,7 +171,29 @@ def cluster_by_trace(
return trace_embeddings, traces
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
def build_cooccurrence_constraints(frames_data: list) -> set:
"""
Build must-not-link constraints: traces appearing in same frame must be different persons.
Returns set of (trace_id_a, trace_id_b) pairs.
"""
constraints = set()
for frame in frames_data:
trace_ids = set()
for face in frame.get('faces', []):
tid = face.get('trace_id')
if tid is not None and tid >= 0:
trace_ids.add(tid)
# All traces in same frame must be different persons
trace_list = list(trace_ids)
for i in range(len(trace_list)):
for j in range(i+1, len(trace_list)):
constraints.add((min(trace_list[i], trace_list[j]),
max(trace_list[i], trace_list[j])))
return constraints
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15,
cooccurrence_constraints: set = None, frames_data: list = None) -> tuple:
"""
Single-stage AgglomerativeClustering on trace means.
No Stage 2 merge (the problematic logic has been removed).
@@ -210,13 +232,67 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) ->
trace_similarities = {}
for i, trace_id in enumerate(trace_ids):
trace_to_person[trace_id] = labels[i]
# For agglomerative, similarity = 1 - distance to cluster (approximate)
trace_similarities[trace_id] = 1.0 # placeholder; exact requires pairwise
trace_similarities[trace_id] = 1.0
# Post-process: split clusters that violate co-occurrence constraints
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
next_person_id = max(trace_to_person.values()) + 1
for tid_a, tid_b in cooccurrence_constraints:
if trace_to_person.get(tid_a) == trace_to_person.get(tid_b):
# Same cluster but shouldn't be - split the one with fewer faces
count_a = trace_embeddings.get(tid_a, {}).get('face_count', 0)
count_b = trace_embeddings.get(tid_b, {}).get('face_count', 0)
if count_a <= count_b:
trace_to_person[tid_a] = next_person_id
print(f" Split trace {tid_a} from {tid_b} (faces: {count_a} vs {count_b})")
else:
trace_to_person[tid_b] = next_person_id
print(f" Split trace {tid_b} from {tid_a} (faces: {count_a} vs {count_b})")
next_person_id += 1
# Merge clusters that are actually the same person (high embedding similarity)
print(f"[CLUSTER] Merging similar persons (threshold={threshold*0.3:.2f})...")
merge_threshold = threshold * 0.3 # More conservative for merging
person_embeddings = {}
for tid, pid in trace_to_person.items():
if tid in trace_embeddings:
if pid not in person_embeddings:
person_embeddings[pid] = []
person_embeddings[pid].append(trace_embeddings[tid]['embedding'])
# Compute person mean embeddings
person_means = {}
for pid, embs in person_embeddings.items():
person_means[pid] = np.mean(embs, axis=0)
# Find and merge similar persons
pids = list(person_means.keys())
for i in range(len(pids)):
for j in range(i+1, len(pids)):
pid_i, pid_j = pids[i], pids[j]
emb_i = person_means[pid_i]
emb_j = person_means[pid_j]
sim = np.dot(emb_i, emb_j) / (np.linalg.norm(emb_i) * np.linalg.norm(emb_j))
dist = 1 - sim
if dist < merge_threshold:
# Merge pid_j into pid_i
for tid in trace_to_person:
if trace_to_person[tid] == pid_j:
trace_to_person[tid] = pid_i
print(f" Merged Person_{pid_j} into Person_{pid_i} (dist={dist:.3f})")
# Reindex person IDs
unique_pids = sorted(set(trace_to_person.values()))
pid_map = {old: new for new, old in enumerate(unique_pids)}
trace_to_person = {tid: pid_map[pid] for tid, pid in trace_to_person.items()}
return trace_to_person, trace_similarities
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15,
cooccurrence_constraints: set = None) -> tuple:
"""
Seed-leader clustering with incremental mean centroids.
Algorithm:
@@ -302,6 +378,39 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tupl
trace_to_person[tid] = person_label
print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons")
# Apply co-occurrence constraints: split traces that appear in same frame
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
# Build trace_id -> person mapping for fast lookup
for tid_a, tid_b in cooccurrence_constraints:
person_a = trace_to_person.get(tid_a)
person_b = trace_to_person.get(tid_b)
if person_a is not None and person_b is not None and person_a == person_b:
# Same person but shouldn't be - split tid_b to new person
new_person_label = len(persons)
trace_to_person[tid_b] = new_person_label
# Move trace from old person to new person
old_person = persons[person_a]
if tid_b in old_person["member_trace_ids"]:
old_person["member_trace_ids"].remove(tid_b)
# Create new person with just this trace
if tid_b in trace_embeddings:
persons.append({
"centroid": trace_embeddings[tid_b]['embedding'].copy(),
"member_trace_ids": [tid_b]
})
print(f" Split trace {tid_b} from Person_{person_a} (co-occurs with trace {tid_a})")
# Rebuild trace_to_person after splits
trace_to_person = {}
for person_label, person in enumerate(persons):
for tid in person["member_trace_ids"]:
trace_to_person[tid] = person_label
print(f"[CLUSTER] After constraints: {len(persons)} unique persons")
return trace_to_person, trace_similarities
@@ -466,13 +575,40 @@ def main():
# Select clustering method
threshold = args.threshold
method = args.method
# Load face_traced.json to build co-occurrence constraints AND for later use
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
cooccurrence_constraints = set()
traced_frames_dict = {} # Will be used later for person_id assignment
if os.path.exists(traced_path):
try:
with open(traced_path) as f:
traced_data = json.load(f)
frames_raw = traced_data.get('frames', [])
# Build co-occurrence constraints
cooccurrence_constraints = build_cooccurrence_constraints(frames_raw)
print(f"[CONSTRAINT] Built {len(cooccurrence_constraints)} co-occurrence constraints from face_traced.json")
# Also build traced_frames_dict for later use
if isinstance(frames_raw, list):
for frame_obj in frames_raw:
frame_num = frame_obj.get("frame")
if frame_num is not None:
traced_frames_dict[str(frame_num)] = frame_obj
elif isinstance(frames_raw, dict):
traced_frames_dict = frames_raw
except Exception as e:
print(f" Warning: Failed to load face_traced.json: {e}")
if method == "leader":
trace_to_person, trace_similarities = seed_leader_cluster(
trace_embeddings, threshold=threshold
)
else:
trace_to_person, trace_similarities = single_stage_clustering(
trace_embeddings, threshold=threshold
trace_embeddings, threshold=threshold,
cooccurrence_constraints=cooccurrence_constraints
)
if not trace_to_person:
print("Clustering produced no results.")
@@ -484,35 +620,12 @@ def main():
print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)")
publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons")
# Load face_traced.json to get trace_id for each face
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
traced_frames = {}
if os.path.exists(traced_path):
try:
with open(traced_path) as f:
traced_data = json.load(f)
frames_raw = traced_data.get("frames", {})
# Handle both dict and list formats
if isinstance(frames_raw, list):
# Convert list to dict for backward compatibility
for frame_obj in frames_raw:
frame_num = frame_obj.get("frame")
if frame_num is not None:
traced_frames[str(frame_num)] = frame_obj
print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)")
elif isinstance(frames_raw, dict):
traced_frames = frames_raw
print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)")
else:
print(f" Warning: Unexpected frames format: {type(frames_raw)}")
except Exception as e:
print(f" Warning: Failed to load face_traced.json: {e}")
# Use traced_frames_dict loaded earlier for person_id assignment
matched_count = 0
for frame_idx, frame_obj in enumerate(frames_list):
frame_num = frame_obj.get("frame", frame_idx)
# Get traced faces for this frame
traced_frame = traced_frames.get(str(frame_num), {})
traced_frame = traced_frames_dict.get(str(frame_num), {})
traced_faces = traced_frame.get("faces", [])
for face_idx, face in enumerate(frame_obj.get("faces", [])):
+360
View File
@@ -0,0 +1,360 @@
#!/usr/bin/env python3.11
"""
face_pipeline_check.py — Face Pipeline 逐步檢查工具
檢查 face → face_traced → face_cluster → face_groups (DB/API)
用法:
python3.11 face_pipeline_check.py <uuid> [--api-key KEY] [--api-url URL]
python3.11 face_pipeline_check.py <uuid> -q # 快速模式
"""
import json
import sys
import os
import argparse
import urllib.request
import urllib.error
OUTPUT_DIR = '/Users/accusys/momentry/output'
API_KEY_ENV = 'MOMENTRY_API_KEY'
def check_file(uuid):
"""Step 0: 檢查檔案存在"""
files = {
'face': f'{uuid}.face.json',
'traced': f'{uuid}.face_traced.json',
'cluster': f'{uuid}.face_cluster.json',
}
status = {}
missing = []
for name, fname in files.items():
path = os.path.join(OUTPUT_DIR, fname)
exists = os.path.exists(path)
status[name] = exists
if exists:
status[f'{name}_size'] = os.path.getsize(path)
else:
missing.append(fname)
return {'pass': len(missing) == 0, 'missing': missing, **status}
def check_face_json(uuid):
"""Step 1: face.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face.json 不存在']}
d = json.load(open(path))
issues = []
total = d.get('total_faces', 0)
fc = d.get('frame_count', 0)
fps = d.get('fps', 0)
frames = d.get('frames') or []
if fc == 0:
issues.append('frame_count = 0(影片沒有被取幀)')
if fps > 0 and fps < 1:
issues.append(f'fps = {fps} (< 1,異常)')
if len(frames) != fc:
issues.append(f'frames 列表數量 {len(frames)} != frame_count {fc}')
# embedding 檢查
emb_total = 0
emb_missing = 0
emb_bad = 0
for fr in frames:
for fa in fr.get('faces') or []:
emb_total += 1
emb = fa.get('embedding')
if emb is None:
emb_missing += 1
elif not isinstance(emb, list) or len(emb) != 512:
emb_bad += 1
elif not all(isinstance(v, (int, float)) for v in emb):
emb_bad += 1
if emb_missing:
issues.append(f'embedding: {emb_missing}/{emb_total} faces 缺少')
if emb_bad:
issues.append(f'embedding: {emb_bad}/{emb_total} faces 非 512D 或格式異常')
return {
'pass': len(issues) == 0,
'total_faces': total,
'frame_count': fc,
'embedding_total': emb_total,
'embedding_missing': emb_missing,
'embedding_bad': emb_bad,
'issues': issues,
}
def check_face_traced(uuid, face_result):
"""Step 2: face_traced.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_traced.json 不存在']}
d = json.load(open(path))
issues = []
traces_raw = d.get('traces') or []
# Normalize: dict (string keys) → list
if isinstance(traces_raw, dict):
traces = list(traces_raw.values())
elif isinstance(traces_raw, list):
traces = traces_raw
else:
traces = []
if not traces:
issues.append('traces 為空(沒有產生任何 trace)')
return {'pass': False, 'trace_count': 0, 'issues': issues}
# trace_id 唯一
tids = [t['trace_id'] for t in traces]
if len(tids) != len(set(tids)):
issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique')
# confidence 範圍 & frame_count 合理性
total_frames_traced = 0
for t in traces:
fc = t.get('frame_count', 0)
if fc < 1:
issues.append(f'trace {t["trace_id"]}: frame_count = {fc} (< 1)')
total_frames_traced += fc
bc = t.get('best_confidence', -1)
ac = t.get('avg_confidence', -1)
if not (0 <= bc <= 1):
issues.append(f'trace {t["trace_id"]}: best_confidence = {bc}')
if not (0 <= ac <= 1):
issues.append(f'trace {t["trace_id"]}: avg_confidence = {ac}')
# face_instances 指向有效性(抽樣檢查)
all_face_ids = set()
face_json_frames = []
if os.path.exists(os.path.join(OUTPUT_DIR, f'{uuid}.face.json')):
fd = json.load(open(os.path.join(OUTPUT_DIR, f'{uuid}.face.json')))
for fr in fd.get('frames') or []:
for fa in fr.get('faces') or []:
fid = fa.get('face_id')
if fid:
all_face_ids.add(fid)
orphan_instances = 0
if all_face_ids:
for t in traces[:5]: # 抽樣前 5 筆
for fi in t.get('face_instances', []):
if fi.get('face_id') and fi['face_id'] not in all_face_ids:
orphan_instances += 1
if orphan_instances:
issues.append(f'face_instances: 抽樣發現 {orphan_instances} 個無效 face_id')
return {
'pass': len(issues) == 0,
'trace_count': len(traces),
'total_frames_traced': total_frames_traced,
'issues': issues,
}
def check_face_cluster(uuid, traced_result):
"""Step 3: face_cluster.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_cluster.json 不存在']}
d = json.load(open(path))
issues = []
clusters = d.get('clusters') or []
frames = d.get('frames') or []
if not clusters:
issues.append('clusters 為空(可能 threshold 太高或人臉太少)')
# cluster_id 唯一
if clusters:
cids = [c['cluster_id'] for c in clusters]
if len(cids) != len(set(cids)):
issues.append('cluster_id 有重複')
# similarity 結構檢查
for c in clusters[:10]: # 抽樣
sim = c.get('similarity') or {}
for key in ['min', 'avg', 'threshold']:
if key not in sim:
issues.append(f'cluster "{c["cluster_id"]}" 缺少 similarity.{key}')
elif not isinstance(sim[key], (int, float)):
issues.append(f'cluster "{c["cluster_id"]}" similarity.{key} 非數值')
# frame faces 完整性
frame_faces = []
for f in frames:
for fa in f.get('faces') or []:
frame_faces.append(fa)
if not frame_faces and clusters:
issues.append('clusters 有資料但 frames 中沒有 faces')
# cluster_id 一致性
if clusters:
valid_cids = set(c['cluster_id'] for c in clusters)
bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids)
if bad:
issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 列表中')
# trace_id 存在
no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None)
if no_trace:
issues.append(f'{no_trace} frame faces 缺少 trace_id')
return {
'pass': len(issues) == 0,
'cluster_count': len(clusters),
'frame_face_count': len(frame_faces),
'issues': issues,
}
def check_api(uuid, api_key, api_url):
"""Step 4: API 回應驗證"""
issues = []
headers = {'X-API-Key': api_key}
url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}'
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
if resp.status != 200:
issues.append(f'cluster-results HTTP {resp.status}')
return {'pass': False, 'issues': issues}
d = json.loads(resp.read())
except urllib.error.HTTPError as e:
issues.append(f'cluster-results HTTP {e.code}: {e.read().decode()[:200]}')
return {'pass': False, 'issues': issues}
except Exception as e:
issues.append(f'cluster-results 請求失敗: {e}')
return {'pass': False, 'issues': issues}
groups = d.get('face_groups', [])
frames = d.get('frames', [])
if not groups:
issues.append('face_groups 為空')
else:
# 檢查是否有群組 trace_ids 全空
empty_groups = [g for g in groups if not g.get('trace_ids')]
if empty_groups:
issues.append(
f'{len(empty_groups)} 個群組 trace_ids 為空: '
f'[{", ".join(g["name"] for g in empty_groups[:5])}]'
)
# frames faces 完整性
f_faces = []
for f in frames:
for fa in f.get('faces') or []:
f_faces.append(fa)
no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None)
if no_trace:
issues.append(f'{no_trace} API frame faces 缺少 trace_id')
# cluster_id → group_id 映射
if groups and f_faces:
group_ids = {g['group_id'] for g in groups}
bad_cids = set()
for fa in f_faces:
cid = fa.get('cluster_id')
if cid and cid not in group_ids:
bad_cids.add(cid)
if bad_cids:
issues.append(f'{len(bad_cids)} frame faces 的 cluster_id 無法映射到 group_id')
return {
'pass': len(issues) == 0,
'group_count': len(groups),
'frame_count': len(frames),
'total_traces': sum(len(g.get('trace_ids', [])) for g in groups),
'issues': issues,
}
def main():
parser = argparse.ArgumentParser(description='Face Pipeline 逐步檢查工具')
parser.add_argument('uuid', help='file_uuid 要檢查')
parser.add_argument('--api-key', default=os.environ.get(API_KEY_ENV, ''),
help=f'API key(預設取自 {API_KEY_ENV})')
parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL')
parser.add_argument('--quiet', '-q', action='store_true', help='快速模式(只輸出 PASS/FAIL)')
args = parser.parse_args()
if not args.api_key:
print(f'⚠️ 未提供 API key,設定 {API_KEY_ENV} 或使用 --api-key')
results = {'uuid': args.uuid, 'steps': {}}
overall_pass = True
# Step 0: 檔案存在
r0 = check_file(args.uuid)
results['steps']['0_files'] = r0
if not r0['pass']:
overall_pass = False
# Step 1: face.json
r1 = check_face_json(args.uuid)
results['steps']['1_face_json'] = r1
if not r1['pass']:
overall_pass = False
# Step 2: face_traced.json
r2 = check_face_traced(args.uuid, r1)
results['steps']['2_face_traced'] = r2
if not r2['pass']:
overall_pass = False
# Step 3: face_cluster.json
r3 = check_face_cluster(args.uuid, r2)
results['steps']['3_face_cluster'] = r3
if not r3['pass']:
overall_pass = False
# Step 4: API/DB
r4 = check_api(args.uuid, args.api_key, args.api_url)
results['steps']['4_api'] = r4
if not r4['pass']:
overall_pass = False
# Print results
if args.quiet:
print('✅ PASS' if overall_pass else '❌ FAIL')
for name, r in results['steps'].items():
if r.get('issues'):
for i in r['issues']:
print(f' {name}: {i}')
else:
print(f'\n{"=" * 60}')
print(f'Face Pipeline Check: {args.uuid}')
print(f'{"=" * 60}\n')
for name, r in results['steps'].items():
icon = '✅' if r.get('pass', True) else '❌'
print(f'{icon} {name}')
if r.get('issues'):
for i in r['issues']:
print(f' ⚠️ {i}')
for key in ['total_faces', 'frame_count', 'embedding_total', 'embedding_missing',
'trace_count', 'cluster_count', 'frame_face_count', 'group_count',
'frame_count', 'total_traces']:
if key in r:
print(f' {key}: {r[key]}')
print()
print(f'Overall: {"✅ PASS" if overall_pass else "❌ FAIL"}\n')
return 0 if overall_pass else 1
if __name__ == '__main__':
sys.exit(main())
+7 -1
View File
@@ -125,7 +125,13 @@ struct SwiftOCR: ParsableCommand {
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
let request = VNRecognizeTextRequest()
request.recognitionLevel = level
request.usesLanguageCorrection = true
if #available(macOS 12.0, *) {
request.recognitionLanguages = ["ja", "en"]
}
if #available(macOS 12.0, *) {
request.recognitionLanguages = ["ja", "en"]
}
request.usesLanguageCorrection = true
request.preferBackgroundProcessing = true
guard (try? handler.perform([request])) != nil,
+242
View File
@@ -0,0 +1,242 @@
// Admin Cleanup API Endpoints
use axum::{
extract::State,
http::StatusCode,
response::Json,
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::PathBuf;
#[derive(Serialize)]
struct CleanupReport {
cleaned_files: usize,
cleaned_size_mb: f64,
orphaned_records: usize,
failed_jobs: usize,
details: Vec<String>,
}
#[derive(Deserialize)]
struct CleanupRequest {
cleanup_type: String,
dry_run: Option<bool>,
}
// 清理垃圾檔案
async fn cleanup_garbage(
State(state): State<crate::api::types::AppState>,
Json(req): Json<CleanupRequest>,
) -> Result<Json<CleanupReport>, StatusCode> {
let dry_run = req.dry_run.unwrap_or(false);
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let mut report = CleanupReport {
cleaned_files: 0,
cleaned_size_mb: 0.0,
orphaned_records: 0,
failed_jobs: 0,
details: Vec::new(),
};
// 1. 清理孤立的輸出檔案
if req.cleanup_type == "garbage" || req.cleanup_type == "all" {
report.details.push("清理孤立輸出檔案...".to_string());
// 獲取所有 videos 的 file_uuid
let video_uuids: Vec<String> = sqlx::query_scalar("SELECT file_uuid FROM videos")
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// 檢查 output 目錄中的檔案
let output_path = PathBuf::from(output_dir);
if output_path.exists() {
for entry in std::fs::read_dir(&output_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? {
let entry = entry.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let path = entry.path();
if path.is_file() {
let filename = path.file_name().unwrap_or_default().to_string_lossy();
// 檢查是否是孤立的 JSON 檔案
if filename.ends_with(".json") && !filename.contains(".") {
// 簡化檢查:如果檔案名不是 UUID 格式,可能是垃圾檔案
if !video_uuids.iter().any(|uuid| filename.starts_with(uuid)) {
let size = path.metadata().map(|m| m.len()).unwrap_or(0);
if !dry_run {
std::fs::remove_file(&path).ok();
}
report.cleaned_files += 1;
report.cleaned_size_mb += size as f64 / 1024.0 / 1024.0;
report.details.push(format!("刪除: {}", filename));
}
}
}
}
}
}
// 2. 清理失敗的任務
if req.cleanup_type == "jobs" || req.cleanup_type == "all" {
report.details.push("清理失敗的任務...".to_string());
let result = sqlx::query("DELETE FROM monitor_jobs WHERE status = 'failed' AND created_at < NOW() - INTERVAL '7 days'")
.execute(state.db.pool())
.await;
if let Ok(rows) = result {
report.failed_jobs = rows.rows_affected() as usize;
report.details.push(format!("刪除 {} 個失敗任務", report.failed_jobs));
}
}
// 3. 清理孤立的資料庫記錄
if req.cleanup_type == "orphaned" || req.cleanup_type == "all" {
report.details.push("清理孤立記錄...".to_string());
// 清理沒有對應 video 的 processor_results
let result = sqlx::query(
"DELETE FROM processor_results pr
WHERE NOT EXISTS (SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid)"
)
.execute(state.db.pool())
.await;
if let Ok(rows) = result {
report.orphaned_records = rows.rows_affected() as usize;
report.details.push(format!("刪除 {} 個孤立記錄", report.orphaned_records));
}
}
// 4. 清理舊日誌
if req.cleanup_type == "logs" || req.cleanup_type == "all" {
report.details.push("清理舊日誌...".to_string());
let log_dir = PathBuf::from(output_dir).parent().unwrap_or(&PathBuf::from(".")).join("logs");
if log_dir.exists() {
for entry in std::fs::read_dir(&log_dir).ok().into_iter().flatten() {
let entry = entry.ok();
if let Some(entry) = entry {
let path = entry.path();
if path.extension().map(|e| e == "log").unwrap_or(false) {
let modified = path.metadata().ok().and_then(|m| m.modified().ok());
if let Some(modified) = modified {
let age = std::time::SystemTime::now().duration_since(modified).ok();
if let Some(age) = age {
if age.as_secs() > 30 * 86400 && !dry_run {
std::fs::remove_file(&path).ok();
report.cleaned_files += 1;
report.details.push(format!("刪除舊日誌: {:?}", path.file_name()));
}
}
}
}
}
}
}
}
Ok(Json(report))
}
// 重置系統
async fn reset_system(
State(state): State<crate::api::types::AppState>,
Json(req): Json<CleanupRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let reset_type = req.cleanup_type.as_str();
let mut result = json!({});
match reset_type {
"videos" => {
// 重置所有 videos
sqlx::query("UPDATE videos SET status = 'pending', cut_done = false, scene_done = false")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
result = json!({"message": "All videos reset to pending"});
}
"processor_results" => {
// 清空 processor_results
sqlx::query("DELETE FROM processor_results")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
result = json!({"message": "All processor results cleared"});
}
"jobs" => {
// 清空所有 jobs
sqlx::query("DELETE FROM monitor_jobs")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
result = json!({"message": "All jobs cleared"});
}
"all" => {
// 完全重置
sqlx::query("DELETE FROM processor_results")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
sqlx::query("DELETE FROM monitor_jobs")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
sqlx::query("UPDATE videos SET status = 'pending', cut_done = false, scene_done = false")
.execute(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
result = json!({"message": "System fully reset"});
}
_ => {
return Err(StatusCode::BAD_REQUEST);
}
}
Ok(Json(result))
}
// 獲取系統統計
async fn get_system_stats(
State(state): State<crate::api::types::AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
// 統計資訊
let video_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM videos")
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let job_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM monitor_jobs")
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let failed_job_count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM monitor_jobs WHERE status = 'failed'")
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let orphaned_count: (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM processor_results pr
WHERE NOT EXISTS (SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid)"
)
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(json!({
"videos": video_count.0,
"total_jobs": job_count.0,
"failed_jobs": failed_job_count.0,
"orphaned_records": orphaned_count.0
})))
}
pub fn router(state: crate::api::types::AppState) -> Router {
Router::new()
.route("/cleanup", post(cleanup_garbage))
.route("/reset", post(reset_system))
.route("/stats", get(get_system_stats))
.with_state(state)
}
+207 -2
View File
File diff suppressed because one or more lines are too long
+35 -25
View File
@@ -80,26 +80,17 @@ pub struct AgentSearchResponse {
// ── Tool Definitions ──────────────────────────────────────────────
const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶關於影片內容的問題。
const SYSTEM_PROMPT: &str = r#"## Core Principles
- **All queries default to searching ALL videos** — do not ask which video
- If multiple videos found, list all results directly
- Only ask user when ALL search tools return empty AND question clearly targets a specific video
- Search tools (smart_search, semantic_search, trace_search) can omit file_uuid to search all
## Greeting and Conversation Handling (CRITICAL - Check First)
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
- **DO NOT call any search tools**
- Respond in English: "Hello! I'm Momentry video analysis assistant. I can help you search video content, find people, and analyze scenes. What would you like to know?"
- If user asks "how are you" or "thanks", respond briefly in English without tools
- **Only use search tools when user asks about VIDEO CONTENT**
## Response Language (MANDATORY)
- **DEFAULT: English** - You MUST respond in English unless user explicitly requests another language
- This applies to ALL responses: greetings, search results, explanations
- Example: If user asks "gun", respond in English about gun-related content
- Only respond in Chinese if user writes in Chinese AND explicitly requests Chinese response
## 核心原則:預設搜尋所有影片,不主動反問
- **所有查詢都預設搜尋全部影片**,不要問用戶「哪部影片」
- 如果搜尋到多部影片,直接列出所有結果,不要反問用戶選擇
- 只有當多個搜尋工具都返回空、且問題明顯指向特定影片時,才問用戶
- 搜尋工具(smart_search, semantic_search, trace_search)的 file_uuid 參數可省略以搜尋全部
## Search Tool Usage
- Use search tools when user asks about VIDEO CONTENT
- For greetings ("hi", "hello", "hey"), do NOT call tools — respond conversationally
- For "how are you" or "thanks", respond briefly without tools
- Always include relevant file_name, timestamps, and descriptions in search results
## 搜尋工具選擇策略(重要:根據問題類型選擇正確工具)
@@ -194,7 +185,7 @@ fn build_system_prompt(language: &str) -> String {
),
};
format!("{}\n\n{}\n\n{}\n\n{}", intro, greeting_instruction, language_instruction, SYSTEM_PROMPT)
format!("{}\n\n{}\n\n{}\n\n{}", intro, greeting_instruction, SYSTEM_PROMPT, language_instruction)
}
fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
@@ -527,18 +518,37 @@ async fn agent_search(
) -> Result<Json<AgentSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
let (conv_id, history) = get_or_create_conv(req.conversation_id.as_deref());
let language = req.output_language
.as_deref()
.unwrap_or("en");
// ── Language handling ──
// VLM 準備的語言: English (vlm_description) + 日本語 (vlm_description_localized)
// UI 語言 → 卡片語言映射:
// ja → 日文 (vlm_description_localized)
// en → 英文 (vlm_description)
// zh-TW → 日文+英文雙語(VLM 無繁中,日文漢字最接近)
let mut language = req.output_language.as_deref().unwrap_or("en");
// 確認語言有效性 — 只支援 en/ja/zh-TW
if !matches!(language, "en" | "ja" | "zh-TW") {
language = "en";
}
let system_prompt = build_system_prompt(language);
tracing::info!("[AGENT] Using language: {}", language);
// 在 user query 前加入語言提醒 — LLM 容易跟隨查詢語言,需要明確指令
let lang_reminder = match language {
"ja" => "\n\n[IMPORTANT: You MUST respond in Japanese (日本語). Do NOT respond in Chinese or English.]",
"zh-TW" => "\n\n[IMPORTANT: You MUST respond in Traditional Chinese (繁體中文). Do NOT respond in Japanese or English.]",
_ => "\n\n[IMPORTANT: You MUST respond in English.]",
};
let user_query_with_lang = format!("{}{}", req.query, lang_reminder);
tracing::info!("[AGENT] Using language: {} (cards: {})", language,
if language == "ja" { "ja" } else if language == "zh-TW" { "ja+en" } else { "en" });
let timeout_duration = std::time::Duration::from_secs(60);
let result = tokio::time::timeout(
timeout_duration,
run_tool_loop(state.db.pool(), &system_prompt, &req.query, history)
run_tool_loop(state.db.pool(), &system_prompt, &user_query_with_lang, history)
).await;
let (answer, messages, sources) = match result {
+31 -2
View File
@@ -31,8 +31,29 @@ struct UserInfo {
async fn login(
State(state): State<AppState>,
axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
headers: axum::http::HeaderMap,
Json(req): Json<LoginRequest>,
) -> Result<axum::response::Response<axum::body::Body>, (StatusCode, Json<serde_json::Value>)> {
// ── Session tracking: inbound IP, User-Agent, connection source ──
let login_ip = headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.map(|v| v.split(',').next().unwrap_or(v).trim().to_string())
.or_else(|| headers.get("x-real-ip").and_then(|v| v.to_str().ok()).map(|s| s.to_string()))
.unwrap_or_else(|| addr.ip().to_string());
let login_ua = headers
.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
// Tauri desktop app identifies itself in its UA; everything else is a browser.
let ua_l = login_ua.to_lowercase();
let login_source = if ua_l.contains("momentry") || ua_l.contains("tauri") {
"app".to_string()
} else {
"browser".to_string()
};
let (user_id, username, role) = 'resolve: {
if let Ok(Some((uid, uname, pw_hash, role_str))) =
state.db.get_user_by_username(&req.username).await
@@ -46,7 +67,7 @@ async fn login(
);
}
if req.username == "demo" && req.password == "demo" {
if req.username == "demo" && req.password == "demo123" {
let uid = state
.db
.get_user_by_username("demo")
@@ -78,7 +99,15 @@ async fn login(
let session_id = uuid::Uuid::new_v4().to_string().replace('-', "");
state
.db
.create_session(&session_id, user_id, &DEMO_USER_API_KEY, 24)
.create_session_with_meta(
&session_id,
user_id,
&DEMO_USER_API_KEY,
24,
login_ip.as_str(),
login_ua.as_str(),
login_source.as_str(),
)
.await
.ok();
+40 -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") {
@@ -295,6 +306,27 @@ pub async fn trigger_cluster_agent(
success_count,
error_count
);
// Also reset group_id so materializer can re-create groups from new clusters
let tp_table = schema::table_name("trace_profiles");
let _ = sqlx::query(&format!(
"UPDATE {tp_table} SET group_id = NULL WHERE file_uuid = $1 AND trace_id = ANY($2)"
))
.bind(&file_uuid)
.bind(&all_trace_ids.iter().map(|tid| *tid as i32).collect::<Vec<i32>>())
.execute(state.db.pool())
.await;
tracing::info!("[ClusterAgent] Reset group_id for {} traces", all_trace_ids.len());
// Also delete old face_groups so materializer can create fresh groups
let fg_table = schema::table_name("face_groups");
let _ = sqlx::query(&format!(
"DELETE FROM {fg_table} WHERE file_uuid = $1"
))
.bind(&file_uuid)
.execute(state.db.pool())
.await;
tracing::info!("[ClusterAgent] Deleted old face_groups for {}", file_uuid);
}
}
}
@@ -481,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) {
@@ -544,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) {
@@ -573,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")?;
+338
View File
@@ -0,0 +1,338 @@
use axum::{
extract::{Query, State},
http::StatusCode,
response::Json,
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::collections::HashMap;
use crate::api::types::AppState;
#[derive(Debug, Serialize, Deserialize)]
pub struct DirEntry {
pub name: String,
pub path: String,
pub is_dir: bool,
pub size: Option<u64>,
pub entry_type: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct BrowseQuery {
pub path: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct DiscoveredHost {
pub name: String,
pub hostname: String,
pub ip: Option<String>,
pub service_type: String,
pub protocol: String,
}
#[derive(Debug, Deserialize)]
pub struct MountRequest {
pub url: String,
pub username: Option<String>,
pub password: Option<String>,
pub mount_point: Option<String>,
}
pub fn directory_browser_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/admin/browse", get(browse_directory))
.route("/api/v1/admin/browse/mount", post(mount_path))
.route("/api/v1/admin/browse/scan", get(scan_network))
.route("/api/v1/admin/browse/shares", get(list_shares))
}
async fn browse_directory(
Query(params): Query<BrowseQuery>,
) -> Result<Json<Vec<DirEntry>>, StatusCode> {
let base_path = params.path.unwrap_or_else(|| "/".to_string());
match base_path.as_str() {
"/" => return Ok(Json(get_root_entries())),
"/Network" => return Ok(Json(get_network_entries())),
_ => {}
}
let path = Path::new(&base_path);
if !path.exists() || !path.is_dir() {
return Err(StatusCode::NOT_FOUND);
}
let mut entries = Vec::new();
if base_path != "/" {
entries.push(DirEntry {
name: "/".to_string(),
path: "/".to_string(),
is_dir: true,
size: None,
entry_type: Some("local".to_string()),
});
}
if let Some(parent) = path.parent() {
let parent_str = parent.to_string_lossy().to_string();
if parent_str != base_path {
entries.push(DirEntry {
name: "..".to_string(),
path: parent_str,
is_dir: true,
size: None,
entry_type: Some("local".to_string()),
});
}
}
match std::fs::read_dir(path) {
Ok(read_dir) => {
for entry in read_dir.filter_map(|e| e.ok()) {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with('.') && name != ".." {
continue;
}
let entry_path = entry.path();
let entry_path_str = entry_path.to_string_lossy().to_string();
if let Ok(metadata) = entry.metadata() {
let entry_type = if entry_path_str.starts_with("/Volumes") ||
entry_path_str.starts_with("/Network") {
"network"
} else {
"local"
};
entries.push(DirEntry {
name,
path: entry_path_str,
is_dir: metadata.is_dir(),
size: if metadata.is_file() { Some(metadata.len()) } else { None },
entry_type: Some(entry_type.to_string()),
});
}
}
}
Err(_) => {}
}
entries.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name)));
Ok(Json(entries))
}
fn get_root_entries() -> Vec<DirEntry> {
vec![
DirEntry { name: "💻 Computer".to_string(), path: "/".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) },
DirEntry { name: "🌐 Network".to_string(), path: "/Network".to_string(), is_dir: true, size: None, entry_type: Some("network".to_string()) },
DirEntry { name: "📁 Users".to_string(), path: "/Users".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) },
DirEntry { name: "💾 Volumes".to_string(), path: "/Volumes".to_string(), is_dir: true, size: None, entry_type: Some("network".to_string()) },
DirEntry { name: "📦 Applications".to_string(), path: "/Applications".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) },
]
}
fn get_network_entries() -> Vec<DirEntry> {
let mut entries = vec![
DirEntry { name: "/".to_string(), path: "/".to_string(), is_dir: true, size: None, entry_type: Some("local".to_string()) },
];
if let Ok(read_dir) = std::fs::read_dir("/Volumes") {
for entry in read_dir.filter_map(|e| e.ok()) {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with('.') || name == "Macintosh HD" {
continue;
}
let path = entry.path().to_string_lossy().to_string();
entries.push(DirEntry {
name: format!("🖥️ {}", name),
path,
is_dir: true,
size: None,
entry_type: Some("network".to_string()),
});
}
}
entries.push(DirEntry {
name: "➕ Connect to Server...".to_string(),
path: "connect://".to_string(),
is_dir: true,
size: None,
entry_type: Some("network".to_string()),
});
entries
}
async fn scan_network(
State(_state): State<AppState>,
) -> Result<Json<Vec<DiscoveredHost>>, StatusCode> {
let mut hosts: HashMap<String, DiscoveredHost> = HashMap::new();
// 掃描 SMB 服務
if let Ok(output) = std::process::Command::new("sh")
.arg("-c")
.arg("timeout 5 dns-sd -B _smb._tcp local. 2>/dev/null | grep 'Add' | awk '{print $NF}'")
.output() {
let smb_hosts = String::from_utf8_lossy(&output.stdout);
for line in smb_hosts.lines() {
let name = line.trim().to_string();
if name.is_empty() { continue; }
let hostname = format!("{}.local", name);
let ip = std::process::Command::new("sh")
.arg("-c")
.arg(format!("dig +short {} 2>/dev/null | head -1", hostname))
.output()
.ok()
.and_then(|o| {
let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
if s.is_empty() { None } else { Some(s) }
});
hosts.insert(name.clone(), DiscoveredHost {
name: name.clone(),
hostname,
ip,
service_type: "SMB".to_string(),
protocol: "smb".to_string(),
});
}
}
// 掃描 AFP 服務
if let Ok(output) = std::process::Command::new("sh")
.arg("-c")
.arg("timeout 5 dns-sd -B _afpovertcp._tcp local. 2>/dev/null | grep 'Add' | awk '{print $NF}'")
.output() {
let afp_hosts = String::from_utf8_lossy(&output.stdout);
for line in afp_hosts.lines() {
let name = line.trim().to_string();
if name.is_empty() || hosts.contains_key(&name) { continue; }
hosts.insert(name.clone(), DiscoveredHost {
name: name.clone(),
hostname: format!("{}.local", name),
ip: None,
service_type: "AFP".to_string(),
protocol: "afp".to_string(),
});
}
}
Ok(Json(hosts.into_values().collect()))
}
async fn mount_path(
State(_state): State<AppState>,
Json(req): Json<MountRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let url = req.url.trim_end_matches('/');
let (mount_cmd, mount_point) = if url.starts_with("smb://") {
let server_path = url.trim_start_matches("smb://");
let mp = req.mount_point.clone().unwrap_or_else(|| {
format!("/Volumes/smb_{}", server_path.split('/').last().unwrap_or("share"))
});
let cred = if let (Some(user), Some(pass)) = (&req.username, &req.password) {
format!("{}:{}@", user, pass)
} else {
String::new()
};
(format!("mount_smbfs '//{}{}' '{}", cred, server_path, mp), mp)
} else if url.starts_with("nfs://") {
let server_path = url.trim_start_matches("nfs://");
let mp = req.mount_point.clone().unwrap_or_else(|| {
format!("/Volumes/nfs_{}", server_path.split('/').last().unwrap_or("export"))
});
(format!("mount_nfs '{}' '{}", server_path, mp), mp)
} else if url.starts_with("http://") || url.starts_with("https://") {
return Ok(Json(serde_json::json!({
"success": false,
"message": "Cloud storage requires rclone. Please mount manually first."
})));
} else {
return Err(StatusCode::BAD_REQUEST);
};
// 建立 mount point
let _ = std::fs::create_dir_all(&mount_point);
let output = std::process::Command::new("sh")
.arg("-c")
.arg(&mount_cmd)
.output()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if output.status.success() {
Ok(Json(serde_json::json!({
"success": true,
"mount_point": mount_point,
"message": "Mounted successfully"
})))
} else {
let error = String::from_utf8_lossy(&output.stderr);
Ok(Json(serde_json::json!({
"success": false,
"message": format!("Mount failed: {}", error)
})))
}
}
// 列出主機上的共享資源
#[derive(Debug, Serialize)]
pub struct ShareInfo {
pub name: String,
pub path: String,
pub share_type: String,
}
async fn list_shares(
State(_state): State<AppState>,
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<Vec<ShareInfo>>, StatusCode> {
let hostname = params.get("host").ok_or(StatusCode::BAD_REQUEST)?;
// 使用 smbutil 列出共享
let output = std::process::Command::new("sh")
.arg("-c")
.arg(format!("smbutil view //{} 2>/dev/null | grep -v 'Share' | awk '{{print $1}}'", hostname))
.output()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let shares = String::from_utf8_lossy(&output.stdout);
let mut result = Vec::new();
for line in shares.lines() {
let name = line.trim().to_string();
if name.is_empty() || name.starts_with("IPC") { continue; }
result.push(ShareInfo {
name: name.clone(),
path: format!("smb://{}/{}", hostname, name),
share_type: "SMB".to_string(),
});
}
// 如果 smbutil 失敗,回傳預設共享
if result.is_empty() {
result.push(ShareInfo {
name: "Home".to_string(),
path: format!("smb://{}/home", hostname),
share_type: "SMB".to_string(),
});
}
Ok(Json(result))
}
+208
View File
@@ -0,0 +1,208 @@
/// Export/Import API endpoints for portable file packages
use axum::{
extract::{Path, Query, State},
http::StatusCode,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::api::types::AppState;
use crate::core::export;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct ExportQuery {
pub export_dir: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ExportResponse {
pub success: bool,
pub file_uuid: String,
pub package_path: String,
pub package_size: u64,
pub message: String,
}
#[derive(Debug, Serialize)]
pub struct ExportStatusResponse {
pub success: bool,
pub file_uuid: String,
pub manifest: export::ExportManifest,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/files/:uuid/export
/// Export a single file as a portable .momentry.tar.gz package
pub async fn export_file_handler(
State(state): State<AppState>,
Path(uuid): Path<String>,
Query(params): Query<ExportQuery>,
) -> Result<Json<ExportResponse>, (StatusCode, Json<serde_json::Value>)> {
// Validate file exists
let video = state.db.get_video_by_uuid(&uuid).await.map_err(|e| {
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("File not found: {}", e)})),
)
})?;
if video.is_none() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "File not found"})),
));
}
let export_dir = params.export_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/files".to_string()
});
// Create export directory if it doesn't exist
if let Err(e) = std::fs::create_dir_all(&export_dir) {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to create export dir: {}", e)})),
));
}
// Get config paths
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
// Perform export
match export::export_file(
state.db.pool(),
&uuid,
&output_dir,
&export_dir,
)
.await
{
Ok(package_path) => {
let package_size = std::fs::metadata(&package_path)
.map(|m| m.len())
.unwrap_or(0);
Ok(Json(ExportResponse {
success: true,
file_uuid: uuid,
package_path: package_path.to_string_lossy().to_string(),
package_size,
message: format!(
"Exported successfully: {} ({:.2} MB)",
package_path.file_name().unwrap_or_default().to_string_lossy(),
package_size as f64 / 1024.0 / 1024.0
),
}))
}
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Export failed: {}", e)})),
)),
}
}
/// GET /api/v1/files/:uuid/export-status
/// Get export manifest for a file (read from existing package or generate info)
pub async fn export_status_handler(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<ExportStatusResponse>, (StatusCode, Json<serde_json::Value>)> {
use crate::core::config::OUTPUT_DIR;
// Build manifest from current data
let video = state.db.get_video_by_uuid(&uuid).await.map_err(|e| {
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("File not found: {}", e)})),
)
})?;
if video.is_none() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "File not found"})),
));
}
let video = video.unwrap();
// Get library
let library = sqlx::query_scalar::<_, Option<String>>(
"SELECT up.name FROM upload_paths up WHERE $1 LIKE up.full_path || '%' ORDER BY LENGTH(up.full_path) DESC LIMIT 1"
)
.bind(&video.file_path)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten()
.flatten()
.unwrap_or_else(|| "unknown".to_string());
// Get file size from filesystem
let file_size = std::fs::metadata(&video.file_path)
.ok()
.map(|m| m.len())
.unwrap_or(0);
// Get processor results
let processors = export::get_processor_results(state.db.pool(), &uuid)
.await
.unwrap_or_default();
let manifest = export::ExportManifest {
version: "1.0".to_string(),
export_type: "file".to_string(),
exported_at: chrono::Utc::now().to_rfc3339(),
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
file: export::FileInfo {
uuid: uuid.clone(),
file_name: video.file_name.clone(),
file_path: video.file_path.clone(),
file_size,
library,
status: format!("{:?}", video.status),
},
data_sources: export::DataSources {
postgresql: export::PostgresqlInfo {
tables: vec![],
total_records: 0,
},
qdrant: export::QdrantInfo {
collection: "momentry_rule1".to_string(),
face_vectors: 0,
text_vectors: 0,
speaker_vectors: 0,
},
sqlite: export::SqliteInfo {
file: "workspace.sqlite".to_string(),
tables: vec![],
total_records: 0,
},
redis: export::RedisInfo {
keys_count: 0,
patterns: vec![],
},
},
processors,
};
Ok(Json(ExportStatusResponse {
success: true,
file_uuid: uuid,
manifest,
}))
}
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn export_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/file/:uuid/export", post(export_file_handler))
.route("/api/v1/file/:uuid/export-status", get(export_status_handler))
}
+255
View File
@@ -0,0 +1,255 @@
//! File Replicas management API
//!
//! Manages multiple copies/replicas of files at different locations.
//! Frontend identifies files by UUID, system selects appropriate replica.
use axum::{
extract::{Path, State, Query},
http::StatusCode,
response::Json,
routing::{get, post, delete},
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, FromRow};
use tracing::{error, info};
use crate::api::types::AppState;
// ── Models ──────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct FileReplica {
pub id: i32,
pub file_uuid: String,
pub replica_path: String,
pub replica_name: Option<String>,
pub is_primary: bool,
pub is_available: bool,
pub file_size: Option<i64>,
pub checksum: Option<String>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct CreateReplicaRequest {
pub file_uuid: String,
pub replica_path: String,
pub replica_name: Option<String>,
pub is_primary: Option<bool>,
pub file_size: Option<i64>,
pub checksum: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct ListReplicasQuery {
pub file_uuid: Option<String>,
pub replica_name: Option<String>,
}
// ── Routes ──────────────────────────────────────────────────────────
pub fn file_replica_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/files/replicas", get(list_replicas))
.route("/api/v1/files/replicas", post(create_replica))
.route("/api/v1/file-replicas/by-uuid/:uuid", get(get_replicas_by_uuid))
.route("/api/v1/files/replicas/:id", delete(delete_replica))
.route("/api/v1/files/replicas/:id/toggle", post(toggle_replica))
}
// ── Helpers ─────────────────────────────────────────────────────────
fn get_pool(state: &AppState) -> &PgPool {
state.db.pool()
}
// ── Handlers ────────────────────────────────────────────────────────
/// GET /api/v1/files/replicas?[file_uuid=X]&[replica_name=Y]
async fn list_replicas(
State(state): State<AppState>,
Query(params): Query<ListReplicasQuery>,
) -> Result<Json<Vec<FileReplica>>, StatusCode> {
let pool = get_pool(&state);
let query = match (&params.file_uuid, &params.replica_name) {
(Some(uuid), Some(name)) => {
sqlx::query_as::<_, FileReplica>(
"SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text
FROM file_replicas WHERE file_uuid = $1 AND replica_name = $2
ORDER BY is_primary DESC, created_at ASC"
).bind(uuid).bind(name)
}
(Some(uuid), None) => {
sqlx::query_as::<_, FileReplica>(
"SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text
FROM file_replicas WHERE file_uuid = $1
ORDER BY is_primary DESC, created_at ASC"
).bind(uuid)
}
(None, Some(name)) => {
sqlx::query_as::<_, FileReplica>(
"SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text
FROM file_replicas WHERE replica_name = $1
ORDER BY file_uuid, is_primary DESC"
).bind(name)
}
(None, None) => {
sqlx::query_as::<_, FileReplica>(
"SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text
FROM file_replicas ORDER BY file_uuid, is_primary DESC, created_at ASC"
)
}
};
let replicas = query.fetch_all(pool).await.map_err(|e| {
error!("[replicas] list failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(replicas))
}
/// GET /api/v1/file-replicas/by-uuid/:uuid
async fn get_replicas_by_uuid(
State(state): State<AppState>,
Path(uuid): Path<String>,
) -> Result<Json<Vec<FileReplica>>, StatusCode> {
let pool = get_pool(&state);
let replicas = sqlx::query_as::<_, FileReplica>(
"SELECT id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text
FROM file_replicas WHERE file_uuid = $1
ORDER BY is_primary DESC, created_at ASC"
)
.bind(&uuid)
.fetch_all(pool)
.await
.map_err(|e| {
error!("[replicas] get_replicas_by_uuid failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(replicas))
}
/// POST /api/v1/files/replicas
async fn create_replica(
State(state): State<AppState>,
Json(req): Json<CreateReplicaRequest>,
) -> Result<Json<FileReplica>, StatusCode> {
let pool = get_pool(&state);
// Verify file exists
let file_exists: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM videos WHERE file_uuid = $1)"
)
.bind(&req.file_uuid)
.fetch_one(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if !file_exists {
return Err(StatusCode::NOT_FOUND);
}
// If setting as primary, unset other primaries for this file
if req.is_primary.unwrap_or(false) {
sqlx::query("UPDATE file_replicas SET is_primary = FALSE WHERE file_uuid = $1")
.bind(&req.file_uuid)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
let replica = sqlx::query_as::<_, FileReplica>(
"INSERT INTO file_replicas (file_uuid, replica_path, replica_name, is_primary, is_available, file_size, checksum)
VALUES ($1, $2, $3, $4, TRUE, $5, $6)
ON CONFLICT (file_uuid, replica_path) DO UPDATE SET
replica_name = EXCLUDED.replica_name,
is_primary = EXCLUDED.is_primary,
file_size = EXCLUDED.file_size,
checksum = EXCLUDED.checksum,
is_available = TRUE,
updated_at = NOW()
RETURNING id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text"
)
.bind(&req.file_uuid)
.bind(&req.replica_path)
.bind(&req.replica_name)
.bind(req.is_primary.unwrap_or(false))
.bind(req.file_size)
.bind(&req.checksum)
.fetch_one(pool)
.await
.map_err(|e| {
error!("[replicas] create failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[replicas] created: {} -> {}", replica.file_uuid, replica.replica_path);
Ok(Json(replica))
}
/// DELETE /api/v1/files/replicas/:id
async fn delete_replica(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
// Don't allow deleting primary replica
let is_primary: bool = sqlx::query_scalar(
"SELECT is_primary FROM file_replicas WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.unwrap_or(false);
if is_primary {
return Err(StatusCode::BAD_REQUEST);
}
sqlx::query("DELETE FROM file_replicas WHERE id = $1")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
info!("[replicas] deleted id={}", id);
Ok(Json(serde_json::json!({"success": true})))
}
/// POST /api/v1/files/replicas/:id/toggle
async fn toggle_replica(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<FileReplica>, StatusCode> {
let pool = get_pool(&state);
let replica = sqlx::query_as::<_, FileReplica>(
"UPDATE file_replicas
SET is_available = NOT is_available, updated_at = NOW()
WHERE id = $1
RETURNING id, file_uuid, replica_path, replica_name, is_primary, is_available,
file_size, checksum, created_at::text, updated_at::text"
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
error!("[replicas] toggle failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[replicas] toggled: {} available={}", replica.replica_path, replica.is_available);
Ok(Json(replica))
}
+120 -10
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(),
@@ -1491,6 +1516,62 @@ async fn re_scan(
reason
);
// Step 0: Pre-scan check and repair
tracing::info!("[RE-SCAN] Pre-scan check for {}", file_uuid);
// Clean up stuck jobs
let _ = sqlx::query(
"UPDATE monitor_jobs SET status='completed' WHERE uuid = $1 AND status IN ('running','processing')"
)
.bind(&file_uuid)
.execute(state.db.pool())
.await;
// Fix stuck scene_vlm
let _ = sqlx::query(
"UPDATE processor_results SET status='completed' WHERE file_uuid = $1 AND processor='scene_vlm' AND status='running'"
)
.bind(&file_uuid)
.execute(state.db.pool())
.await;
// Fix failed face_cluster
let _ = sqlx::query(
"UPDATE processor_results SET status='completed' WHERE file_uuid = $1 AND processor='face_cluster' AND status='failed'"
)
.bind(&file_uuid)
.execute(state.db.pool())
.await;
// Clean duplicate processor_results
let _ = sqlx::query(
"DELETE FROM processor_results WHERE file_uuid = $1 AND ctid NOT IN (SELECT max(ctid) FROM processor_results WHERE file_uuid = $1 GROUP BY processor)"
)
.bind(&file_uuid)
.execute(state.db.pool())
.await;
// Clean up old command_queue entries for this file
let file_path_for_cleanup: Option<String> = sqlx::query_scalar(
"SELECT file_path FROM videos WHERE file_uuid = $1"
)
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.ok()
.flatten();
if let Some(path) = &file_path_for_cleanup {
let _ = sqlx::query(
"DELETE FROM command_queue WHERE value->>'file_path' = $1"
)
.bind(path)
.execute(state.db.pool())
.await;
}
tracing::info!("[RE-SCAN] Pre-scan cleanup completed for {}", file_uuid);
// Step 1: Get file path from database
let videos_table = schema::table_name("videos");
let file_path: Option<String> = sqlx::query_scalar(&format!(
@@ -1517,13 +1598,37 @@ async fn re_scan(
}
};
// Step 0.5: 清掉同 file_path 的舊 rows(避免 re-scan 產生重複 uuid)
let videos_table = schema::table_name("videos");
let processor_table = schema::table_name("processor_results");
if let Ok(result) = sqlx::query(&format!(
"DELETE FROM {videos_table}
WHERE file_path = $1 AND file_uuid <> $2
AND NOT EXISTS (
SELECT 1 FROM {processor_table} pr WHERE pr.file_uuid = {videos_table}.file_uuid
)"
))
.bind(&file_path)
.bind(&file_uuid)
.execute(state.db.pool())
.await
{
let cleaned = result.rows_affected();
if cleaned > 0 {
tracing::info!("[RE-SCAN] 清掉 {cleaned} 筆同路徑重複 rows({file_path})");
}
}
// Step 2: Create register command with force=true
// Note: force=true will automatically unregister existing file if needed
let auto_pipeline = req.auto_pipeline.unwrap_or(false);
// deep_scan=true tells the worker to start the full scan pipeline right
// after registration completes (unregister → register → deep scan).
// This is independent of the global auto-pipeline setting.
let deep_scan = req.auto_pipeline.unwrap_or(true);
let register_payload = serde_json::json!({
"force": true,
"auto_pipeline": auto_pipeline,
"deep_scan": deep_scan,
"content_hash": null,
"face_settings": req.face_settings.as_ref().map(|fs| {
serde_json::json!({
@@ -1562,10 +1667,10 @@ async fn re_scan(
// Note: Register command with force=true will:
// 1. Unregister existing file if needed
// 2. Register the file
// 3. Trigger auto-pipeline only if auto_pipeline=true (default: false)
// 3. Start the deep scan pipeline when deep_scan=true
let mode = if auto_pipeline { "auto" } else { "manual" };
tracing::info!("[RE-SCAN] Mode: {} (auto_pipeline={})", mode, auto_pipeline);
let mode = if deep_scan { "auto" } else { "manual" };
tracing::info!("[RE-SCAN] Mode: {} (deep_scan={})", mode, deep_scan);
Ok(Json(ReScanResponse {
success: true,
@@ -1579,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");
@@ -1703,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
+201
View File
@@ -0,0 +1,201 @@
/// Folder batch export/import API
use axum::{
extract::{Query, State},
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::api::types::AppState;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct FolderExportQuery {
pub folder_path: String,
#[serde(default)]
pub export_dir: Option<String>,
#[serde(default)]
pub library_name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct FolderExportResponse {
pub success: bool,
pub folder_name: String,
pub file_count: usize,
pub package_path: String,
pub package_size: u64,
pub message: String,
}
#[derive(Debug, Deserialize)]
pub struct FolderImportQuery {
pub package_path: String,
#[serde(default)]
pub target_folder_path: Option<String>,
#[serde(default)]
pub force: bool,
}
#[derive(Debug, Serialize)]
pub struct FolderImportResponse {
pub success: bool,
pub folder_name: String,
pub imported_files: usize,
pub total_records: usize,
pub message: String,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/folder/export
/// Export all files in a folder as a single .momentry.tar.gz package
pub async fn folder_export_handler(
State(state): State<AppState>,
Query(params): Query<FolderExportQuery>,
) -> Result<Json<FolderExportResponse>, (StatusCode, Json<serde_json::Value>)> {
let export_dir = params.export_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/folders".to_string()
});
// Create export directory
if let Err(e) = std::fs::create_dir_all(&export_dir) {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to create export dir: {}", e)})),
));
}
// Get library name
let library_name = params.library_name.unwrap_or_else(|| {
// Extract from folder path
PathBuf::from(&params.folder_path)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "unknown".to_string())
});
// Find all files in this folder
let files = get_files_in_folder(state.db.pool(), &params.folder_path).await?;
if files.is_empty() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "No files found in folder"})),
));
}
// Export folder
match crate::core::folder_export::export_folder(
state.db.pool(),
&params.folder_path,
&library_name,
&export_dir,
)
.await
{
Ok((package_path, file_count)) => {
let package_size = std::fs::metadata(&package_path)
.map(|m| m.len())
.unwrap_or(0);
Ok(Json(FolderExportResponse {
success: true,
folder_name: library_name.clone(),
file_count,
package_path: package_path.to_string_lossy().to_string(),
package_size,
message: format!(
"Exported {} files from {}. Package: {} ({:.2} MB)",
file_count,
library_name,
package_path.file_name().unwrap_or_default().to_string_lossy(),
package_size as f64 / 1024.0 / 1024.0
),
}))
}
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Export failed: {}", e)})),
)),
}
}
/// POST /api/v1/folder/import
/// Import a folder package
pub async fn folder_import_handler(
State(state): State<AppState>,
Query(params): Query<FolderImportQuery>,
) -> Result<Json<FolderImportResponse>, (StatusCode, Json<serde_json::Value>)> {
let pkg_path = PathBuf::from(&params.package_path);
if !pkg_path.exists() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "Package not found"})),
));
}
match crate::core::folder_export::import_folder(
state.db.pool(),
&params.package_path,
params.target_folder_path.as_deref(),
params.force,
)
.await
{
Ok(result) => Ok(Json(FolderImportResponse {
success: true,
folder_name: result.folder_name,
imported_files: result.imported_files,
total_records: result.total_records,
message: format!(
"Imported {} files, {} records restored.",
result.imported_files, result.total_records
),
})),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Import failed: {}", e)})),
)),
}
}
// ─── Helper Functions ────────────────────────────────────────────────────────
struct FileInfo {
uuid: String,
file_name: String,
file_path: String,
}
async fn get_files_in_folder(pool: &sqlx::PgPool, folder_path: &str) -> Result<Vec<FileInfo>, (StatusCode, Json<serde_json::Value>)> {
let videos_table = crate::core::db::schema::table_name("videos");
let rows: Vec<(String, String, String)> = sqlx::query_as(
&format!("SELECT file_uuid, file_name, file_path FROM {} WHERE file_path LIKE $1 || '%%'", videos_table)
)
.bind(folder_path.trim_end_matches('/'))
.fetch_all(pool)
.await
.map_err(|e| (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("DB error: {}", e)})),
))?;
Ok(rows.into_iter().map(|r| FileInfo {
uuid: r.0,
file_name: r.1,
file_path: r.2,
}).collect())
}
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn folder_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/folder/export", post(folder_export_handler))
.route("/api/v1/folder/import", post(folder_import_handler))
}
+148 -27
View File
@@ -11,6 +11,12 @@ use std::process::Command;
use crate::core::db::{QdrantDb, ResourceRecord};
/// 檔案是否已納入管理(unregistered/pending = 掃描發現但尚未註冊)。
/// registered / completed / scanning / keyword_ready 等 pipeline 狀態都算已註冊。
fn status_is_registered(status: &str) -> bool {
!matches!(status, "" | "unregistered" | "pending")
}
pub fn identity_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v1/files", get(list_files))
@@ -79,6 +85,7 @@ pub fn identity_routes() -> Router<crate::api::types::AppState> {
#[derive(Debug, Deserialize)]
pub struct FilesQuery {
pub page: Option<usize>,
#[serde(alias = "pageSize")]
pub page_size: Option<usize>,
pub status: Option<String>,
pub file_uuid: Option<String>,
@@ -110,7 +117,7 @@ async fn list_files(
.await
.unwrap_or(0);
let is_registered = v.status.as_str() != "pending";
let is_registered = status_is_registered(v.status.as_str());
vec![FileItem {
file_uuid: v.file_uuid,
@@ -122,6 +129,7 @@ async fn list_files(
file_size: None,
modified_time: None,
thumbnail_url: None,
job_status: None,
}]
} else {
vec![]
@@ -136,18 +144,28 @@ async fn list_files(
}));
}
// Call MarkBase API to get file list
let markbase_url = "http://localhost:11438/api/v2/myfiles/demo/files";
// Call MarkBase API for each enabled upload_path
let client = reqwest::Client::new();
let markbase_files: Vec<MarkBaseFile> = client
.get(markbase_url)
.send()
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API error: {}", e)))?
.json()
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("MarkBase API parse error: {}", e)))?;
// Get enabled upload paths
let up_table = crate::core::db::schema::table_name("upload_paths");
let upload_paths: Vec<(String, String)> = sqlx::query_as(&format!(
"SELECT name, full_path FROM {} WHERE enabled = true ORDER BY id",
up_table
))
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let mut markbase_files: Vec<MarkBaseFile> = Vec::new();
for (mb_user, _full_path) in &upload_paths {
let url = format!("http://localhost:11438/api/v2/myfiles/{}/files", mb_user);
if let Ok(resp) = client.get(&url).send().await {
if let Ok(files) = resp.json::<Vec<MarkBaseFile>>().await {
markbase_files.extend(files);
}
}
}
let mut all_files: Vec<FileItem> = Vec::new();
@@ -185,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)
};
@@ -199,32 +219,51 @@ async fn list_files(
file_name: name,
file_path: path.clone(),
status: status.clone(),
is_registered: status != "pending",
is_registered: status_is_registered(status.as_str()),
total_chunks: 0,
file_size,
modified_time,
thumbnail_url: None,
job_status: None,
});
} else {
// Not registered: synthesize a path so the client can still preview it
let synth_path = std::env::var("MOMENTRY_SFTP_ROOT")
.ok()
.map(|root| format!("{}/{}", root.trim_end_matches('/'), name))
// Not registered: use MarkBase file_path if available
let file_path = mb_file.file_path.clone()
.filter(|p| !p.is_empty())
.unwrap_or_else(|| {
// Default SFTP root if not configured
let default_root = "/Users/accusys/momentry/var/sftpgo/data/demo";
format!("{}/{}", default_root, name)
// Fallback: synthesize path from SFTP root
std::env::var("MOMENTRY_SFTP_ROOT")
.ok()
.map(|root| format!("{}/{}", root.trim_end_matches('/'), name))
.unwrap_or_else(|| {
let default_root = "/Users/accusys/momentry/var/sftpgo/data/demo";
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,
file_path: synth_path,
file_path,
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,
});
}
}
@@ -234,20 +273,60 @@ async fn list_files(
let all_names: std::collections::HashSet<String> = all_files.iter().map(|f| f.file_name.clone()).collect();
for (name, (uuid, path, status, size, mtime)) in &registered_by_name {
if !all_names.contains(name) && !all_paths.contains(path) {
// Fallback to filesystem for size/mtime when DB has NULL
let file_size = size.map(|s| s as u64).or_else(|| {
std::fs::metadata(path).ok().map(|m| m.len())
});
let modified_time = mtime.clone().or_else(|| {
std::fs::metadata(path).ok()
.and_then(|m| m.modified().ok())
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339())
});
all_files.push(FileItem {
file_uuid: uuid.clone(),
file_name: name.clone(),
file_path: path.clone(),
status: status.clone(),
is_registered: status != "pending",
is_registered: status_is_registered(status.as_str()),
total_chunks: 0,
file_size: size.map(|s| s as u64),
modified_time: mtime.clone(),
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 {
@@ -288,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 {
@@ -323,7 +441,7 @@ pub struct FilesResponse {
pub data: Vec<FileItem>,
}
#[derive(Debug, Serialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct FileItem {
pub file_uuid: String,
pub file_name: String,
@@ -338,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)]
+478
View File
@@ -0,0 +1,478 @@
/// Import API - restore files from .momentry.tar.gz packages
use axum::{
extract::{Multipart, Query, State},
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::api::types::AppState;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct ImportQuery {
#[serde(default)]
pub package_path: Option<String>,
#[serde(default)]
pub target_video_path: Option<String>,
#[serde(default)]
pub force: bool,
}
#[derive(Debug, Serialize)]
pub struct ImportResponse {
pub success: bool,
pub file_uuid: String,
pub video_path: String,
pub restored_records: usize,
pub message: String,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/import
/// Import a file from a .momentry.tar.gz package
///
/// Query params:
/// - package_path: Path to the .momentry.tar.gz file
/// - target_video_path: Where to restore the video (default: original path from manifest)
/// - force: Overwrite if file already exists
pub async fn import_file_handler(
State(state): State<AppState>,
Query(params): Query<ImportQuery>,
) -> Result<Json<ImportResponse>, (StatusCode, Json<serde_json::Value>)> {
let package_path = params.package_path.ok_or((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Missing package_path parameter"})),
))?;
let pkg_path = std::path::PathBuf::from(&package_path);
if !pkg_path.exists() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("Package not found: {}", package_path)})),
));
}
// Perform import
match import_file(
state.db.pool(),
&package_path,
params.target_video_path.as_deref(),
params.force,
)
.await
{
Ok(result) => Ok(Json(result)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Import failed: {}", e)})),
)),
}
}
/// POST /api/v1/import/list
/// List available packages in offline_storage
pub async fn list_packages_handler(
Query(params): Query<ListQuery>,
) -> Result<Json<ListResponse>, (StatusCode, Json<serde_json::Value>)> {
let storage_dir = params.storage_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/files".to_string()
});
let packages = list_packages(&storage_dir).map_err(|e| (
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to list packages: {}", e)})),
))?;
let total = packages.len();
Ok(Json(ListResponse {
success: true,
packages,
total,
}))
}
#[derive(Debug, Deserialize)]
pub struct ListQuery {
pub storage_dir: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ListResponse {
pub success: bool,
pub packages: Vec<PackageInfo>,
pub total: usize,
}
#[derive(Debug, Serialize)]
pub struct PackageInfo {
pub path: String,
pub file_uuid: String,
pub file_name: String,
pub library: String,
pub size: u64,
pub exported_at: String,
}
// ─── Import Logic ────────────────────────────────────────────────────────────
pub async fn import_file(
pool: &sqlx::PgPool,
package_path: &str,
target_video_path: Option<&str>,
force: bool,
) -> Result<ImportResponse> {
let pkg_path = PathBuf::from(package_path);
let temp_dir = pkg_path.with_extension(""); // Remove .tar.gz
// 1. Extract package
extract_package(&pkg_path, &temp_dir)?;
// 2. Read manifest
let manifest_path = temp_dir.join("manifest.json");
let manifest_str = std::fs::read_to_string(&manifest_path)?;
let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?;
let file_uuid = &manifest.file.uuid;
// 3. Check if file already exists
let videos_table = crate::core::db::schema::table_name("videos");
let exists: Option<(i32,)> = sqlx::query_as(
&format!("SELECT id FROM {} WHERE file_uuid = $1", videos_table)
)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
if exists.is_some() && !force {
return Err(anyhow::anyhow!(
"File {} already exists. Use force=true to overwrite.",
file_uuid
));
}
// 4. Delete existing records if force
if exists.is_some() {
delete_existing_records(pool, file_uuid).await?;
}
// 5. Restore video file
let video_src = temp_dir.join("video").join(&manifest.file.file_name);
let video_dest = target_video_path
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(&manifest.file.file_path));
if video_src.exists() {
if let Some(parent) = video_dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(&video_src, &video_dest)?;
}
// 6. Restore output files
restore_output_files(&temp_dir, &manifest.file.uuid)?;
// 7. Restore identities
restore_identities(&temp_dir)?;
// 8. Restore DB records
let restored_records = restore_db_records(pool, &temp_dir, file_uuid).await?;
// 9. Clean up temp dir
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(ImportResponse {
success: true,
file_uuid: file_uuid.clone(),
video_path: video_dest.to_string_lossy().to_string(),
restored_records,
message: format!(
"Imported {} successfully. {} records restored.",
manifest.file.file_name, restored_records
),
})
}
fn list_packages(storage_dir: &str) -> Result<Vec<PackageInfo>> {
let mut packages = Vec::new();
let dir = std::path::PathBuf::from(storage_dir);
if !dir.exists() {
return Ok(packages);
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.to_string_lossy().ends_with(".tar.gz") {
// Try to read manifest from package
if let Ok(info) = read_package_info(&path) {
packages.push(info);
}
}
}
Ok(packages)
}
fn read_package_info(package_path: &std::path::Path) -> Result<PackageInfo> {
use std::os::unix::fs::MetadataExt;
// Extract to temp to read manifest
let temp_dir = package_path.with_extension("");
extract_package(package_path, &temp_dir)?;
let manifest_path = temp_dir.join("manifest.json");
let manifest_str = std::fs::read_to_string(&manifest_path)?;
let manifest: crate::core::export::ExportManifest = serde_json::from_str(&manifest_str)?;
let size = std::fs::metadata(package_path)?.size();
// Clean up
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(PackageInfo {
path: package_path.to_string_lossy().to_string(),
file_uuid: manifest.file.uuid,
file_name: manifest.file.file_name,
library: manifest.file.library,
size,
exported_at: manifest.exported_at,
})
}
fn extract_package(package_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
if dest_dir.exists() {
std::fs::remove_dir_all(dest_dir)?;
}
let tar_gz = std::fs::File::open(package_path)?;
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
archive.unpack(dest_dir)?;
Ok(())
}
fn restore_output_files(temp_dir: &std::path::Path, uuid: &str) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_dir = std::path::PathBuf::from(output_dir);
let src_output = temp_dir.join("output");
if !src_output.exists() {
return Ok(());
}
// Copy JSON files
if let Ok(entries) = std::fs::read_dir(&src_output) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
let dest = dest_dir.join(path.file_name().unwrap());
std::fs::copy(&path, &dest)?;
} else if path.is_dir() {
// Copy trace directories
if path.file_name().map(|n| n == uuid).unwrap_or(false) {
let dest = dest_dir.join(uuid);
copy_dir_all(&path, &dest)?;
}
}
}
}
Ok(())
}
fn restore_identities(temp_dir: &std::path::Path) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_identities = std::path::PathBuf::from(output_dir).join("identities");
let src_identities = temp_dir.join("identities");
if !src_identities.exists() {
return Ok(());
}
if !dest_identities.exists() {
std::fs::create_dir_all(&dest_identities)?;
}
if let Ok(entries) = std::fs::read_dir(&src_identities) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let dest = dest_identities.join(&name);
if !dest.exists() {
copy_dir_all(&entry.path(), &dest)?;
}
}
}
}
Ok(())
}
async fn restore_db_records(pool: &sqlx::PgPool, temp_dir: &std::path::Path, uuid: &str) -> Result<usize> {
let db_dir = temp_dir.join("db");
if !db_dir.exists() {
return Ok(0);
}
let mut restored = 0;
// Restore each table
let tables = [
"videos",
"processor_results",
"monitor_jobs",
"trace_profiles",
"tkg_nodes",
"chunk",
"identities",
];
for table in tables {
let json_path = db_dir.join(format!("{}.json", table));
if !json_path.exists() {
continue;
}
let json_str = std::fs::read_to_string(&json_path)?;
let records: Vec<serde_json::Value> = serde_json::from_str(&json_str)?;
let table_name = crate::core::db::schema::table_name(table);
for record in records {
// Remove id column (auto-increment with NOT NULL)
let mut record = record.clone();
if let Some(obj) = record.as_object_mut() {
obj.remove("id");
}
if record.as_object().map(|o| o.is_empty()).unwrap_or(true) {
continue;
}
// Build explicit INSERT with columns (excluding id)
let columns: Vec<String> = record.as_object().unwrap().keys()
.map(|k| format!("\"{}\"", k)).collect();
let cols_str = columns.join(", ");
// Build values with proper type handling
let values: Vec<String> = record.as_object().unwrap().values()
.map(|v| match v {
serde_json::Value::Null => "NULL".to_string(),
serde_json::Value::Bool(b) => b.to_string(),
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
format!("'{}'::jsonb", serde_json::to_string(v).unwrap_or_else(|_| "null".to_string()).replace("'", "''"))
}
})
.collect();
let vals_str = values.join(", ");
let sql = format!(
"INSERT INTO {} ({}) VALUES ({})",
table_name, cols_str, vals_str
);
let result = sqlx::query(&sql)
.execute(pool)
.await;
match result {
Ok(_) => restored += 1,
Err(e) => {
tracing::warn!("[Import] Failed to insert into {}: {}", table, e);
// Try alternative approach: column-by-column insert
if let Err(e2) = insert_record_fallback(pool, &table_name, &record).await {
tracing::warn!("[Import] Fallback also failed: {}", e2);
} else {
restored += 1;
}
}
}
}
}
Ok(restored)
}
async fn insert_record_fallback(pool: &sqlx::PgPool, table: &str, record: &serde_json::Value) -> Result<()> {
// Use jsonb_to_record approach
let json_str = serde_json::to_string(record)?;
sqlx::query(&format!(
"INSERT INTO {} SELECT * FROM jsonb_populate_record(NULL::{}, $1::jsonb)",
table, table
))
.bind(json_str)
.execute(pool)
.await?;
Ok(())
}
async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result<usize> {
let mut deleted = 0;
let tables = [
("processor_results", "file_uuid"),
("monitor_jobs", "uuid"),
("trace_profiles", "file_uuid"),
("tkg_nodes", "file_uuid"),
("tkg_edges", "file_uuid"),
("chunk", "file_uuid"),
("face_detections", "file_uuid"),
("videos", "file_uuid"),
];
for (table, col) in tables {
let table_name = crate::core::db::schema::table_name(table);
let result = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
.bind(uuid)
.execute(pool)
.await;
if let Ok(r) = result {
deleted += r.rows_affected() as usize;
}
}
Ok(deleted)
}
fn copy_dir_all(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
std::fs::create_dir_all(dest)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
let dest_path = dest.join(entry.file_name());
if path.is_dir() {
copy_dir_all(&path, &dest_path)?;
} else {
std::fs::copy(&path, &dest_path)?;
}
}
Ok(())
}
use anyhow::Result;
// ─── Router ──────────────────────────────────────────────────────────────────
pub fn import_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/import", post(import_file_handler))
.route("/api/v1/import/list", post(list_packages_handler))
}
+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)
})))
}
+50 -1
View File
@@ -1,7 +1,8 @@
use axum::{extract::Path, http::StatusCode, response::Json, routing::get, Router};
use axum::{extract::{Path, Query}, http::StatusCode, response::Json, routing::get, Router};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
use tokio::io::AsyncSeekExt;
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
@@ -111,4 +112,52 @@ pub fn markbase_routes() -> Router<crate::api::types::AppState> {
Router::new()
.route("/api/v2/myfiles/:username/folders", get(list_user_folders))
.route("/api/v2/myfiles/:username/files", get(list_user_files))
.route("/api/v2/myfiles/preview-by-path", get(preview_file_by_path))
}
// 通用檔案預覽 - 支援任意路徑
#[derive(Debug, Deserialize)]
pub struct PreviewQuery {
pub path: Option<String>,
}
pub async fn preview_file_by_path(
Query(params): Query<PreviewQuery>,
) -> Result<axum::response::Response, StatusCode> {
let file_path = params.path.ok_or(StatusCode::BAD_REQUEST)?;
let path = std::path::Path::new(&file_path);
if !path.exists() {
return Err(StatusCode::NOT_FOUND);
}
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase();
let content_type = match ext.as_str() {
"mp4" => "video/mp4",
"mov" => "video/quicktime",
"mkv" => "video/x-matroska",
"avi" => "video/x-msvideo",
"webm" => "video/webm",
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"webp" => "image/webp",
"pdf" => "application/pdf",
"txt" | "md" | "json" | "xml" => "text/plain",
_ => "application/octet-stream",
};
match tokio::fs::read(path).await {
Ok(data) => {
Ok(axum::response::Response::builder()
.header("Content-Type", content_type)
.header("Content-Length", data.len())
.header("Accept-Ranges", "bytes")
.body(axum::body::Body::from(data))
.unwrap())
}
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
}
}
+120 -40
View File
@@ -88,10 +88,6 @@ pub fn bbox_routes() -> Router<crate::api::types::AppState> {
"/api/v1/file/:file_uuid/chunk/:chunk_id/thumbnail",
get(chunk_thumbnail),
)
.route(
"/api/v1/file/:file_uuid/scenes/:filename",
get(scene_thumbnail),
)
.route("/api/v1/file/:file_uuid/clip", get(video_clip))
}
@@ -926,6 +922,7 @@ async fn face_thumbnail_compat(
/// Thumbnail by file path — for unregistered files (no UUID).
/// Frontend calls: GET /api/v1/file/thumbnail?path=<abs_path>&frame=<n>
async fn thumbnail_by_path(
State(state): State<crate::api::types::AppState>,
Query(q): Query<ThumbnailByPathQuery>,
) -> Result<impl IntoResponse, StatusCode> {
let file_path = q.path.ok_or(StatusCode::BAD_REQUEST)?;
@@ -937,12 +934,12 @@ async fn thumbnail_by_path(
return Err(StatusCode::BAD_REQUEST);
}
// Fallback 用 momentry root(~/momentry),而非 current_exe 的父目錄 —
// 部署時 binary 在 <root>/bin/ 下,直接取 parent 會多一層 bin 導致 403。
let scan_root = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "/tmp".to_string())
crate::core::path_utils::demo_dir()
.to_string_lossy()
.to_string()
});
let canonical_root = std::fs::canonicalize(&scan_root).unwrap_or_else(|_| {
@@ -952,7 +949,20 @@ async fn thumbnail_by_path(
std::path::PathBuf::from(&file_path)
});
if !canonical_file.starts_with(&canonical_root) {
// 允許範圍:SFTP root + 所有已啟用的 upload_paths(不同 library 可在不同磁碟)
let mut allowed_roots = vec![canonical_root.clone()];
let paths_table = crate::core::db::schema::table_name("upload_paths");
if let Ok(rows) = sqlx::query_scalar::<_, String>(&format!("SELECT full_path FROM {} WHERE enabled = true", paths_table))
.fetch_all(state.db.pool())
.await
{
for root in rows {
let canonical = std::fs::canonicalize(&root).unwrap_or_else(|_| std::path::PathBuf::from(&root));
allowed_roots.push(canonical);
}
}
if !allowed_roots.iter().any(|root| canonical_file.starts_with(root)) {
tracing::warn!(
"[thumbnail_by_path] Path outside scan root rejected: {} (root: {})",
file_path, scan_root
@@ -964,6 +974,33 @@ async fn thumbnail_by_path(
return Err(StatusCode::NOT_FOUND);
}
// Check thumbnail cache first
let cache_dir = std::env::var("MOMENTRY_THUMBNAIL_CACHE")
.unwrap_or_else(|_| "/Users/accusys/momentry/var/thumbnails".to_string());
let cache_path = std::path::PathBuf::from(&cache_dir);
if cache_path.exists() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
file_path.hash(&mut hasher);
frame.hash(&mut hasher);
let hash = hasher.finish();
let thumb_file = cache_path.join(format!("{:x}_f{}.jpg", hash, frame));
if thumb_file.exists() {
if let Ok(data) = std::fs::read(&thumb_file) {
// Cache is valid if source file hasn't changed since cache was created
// (source mtime <= cache mtime means source is older or same age)
if let (Ok(meta), Ok(cache_meta)) = (std::fs::metadata(&canonical_file), std::fs::metadata(&thumb_file)) {
if let (Ok(src_mtime), Ok(cache_mtime)) = (meta.modified(), cache_meta.modified()) {
if src_mtime <= cache_mtime {
return Ok(image_response(data));
}
}
}
}
}
}
// Extract frame with ffmpeg
let select = format!("select=eq(n\\,{})", frame);
let output = ffmpeg_cmd()
@@ -996,20 +1033,43 @@ async fn thumbnail_by_path(
StatusCode::INTERNAL_SERVER_ERROR
})?;
// Cache thumbnail to disk for faster subsequent loads
let cache_dir = std::env::var("MOMENTRY_THUMBNAIL_CACHE")
.unwrap_or_else(|_| "/Users/accusys/momentry/var/thumbnails".to_string());
let cache_path = std::path::PathBuf::from(&cache_dir);
if !cache_path.exists() {
let _ = std::fs::create_dir_all(&cache_path);
}
if cache_path.exists() {
// Create cache key from file path and frame
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
file_path.hash(&mut hasher);
frame.hash(&mut hasher);
let hash = hasher.finish();
let thumb_file = cache_path.join(format!("{:x}_f{}.jpg", hash, frame));
let _ = std::fs::write(&thumb_file, &output.stdout);
}
Ok(image_response(output.stdout))
}
/// 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);
@@ -1045,11 +1105,12 @@ async fn trace_thumbnail(
/// Serve a scene frame image (`scene_*.jpg`) directly from the output dir.
/// Path mirrors `thumbnail_url` produced by the VLM scene search API.
/// e.g. /api/v1/file/{file_uuid}/scenes/scene_000.jpg
async fn scene_thumbnail(
State(_state): State<crate::api::types::AppState>,
pub async fn scene_thumbnail(
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) {
@@ -1064,10 +1125,16 @@ 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);
@@ -1122,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!(
@@ -1149,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!(
@@ -1832,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
})?;
@@ -1863,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
@@ -1881,7 +1961,7 @@ async fn get_appearance_handler(
.unwrap_or_default();
Ok(axum::Json(AppearanceResponse {
frame: params.frame,
frame,
dominant_colors: vec![],
hsv_histogram,
}))
+20 -2
View File
@@ -177,13 +177,31 @@ fn extract_api_key(headers: &HeaderMap, uri: &axum::http::Uri) -> Result<String,
Err(StatusCode::UNAUTHORIZED)
}
/// Derive the inbound client IP, preferring proxy headers (Caddy / momentry
/// proxy / reverse proxies set X-Forwarded-For) then falling back to the
/// direct socket address.
fn client_ip(headers: &axum::http::HeaderMap, addr: Option<std::net::SocketAddr>) -> String {
for h in ["x-forwarded-for", "x-real-ip"] {
if let Some(v) = headers.get(h).and_then(|v| v.to_str().ok()) {
// X-Forwarded-For may be a list: first hop is the original client
let first = v.split(',').next().unwrap_or(v).trim();
if !first.is_empty() {
return first.to_string();
}
}
}
addr.map(|a| a.ip().to_string()).unwrap_or_else(|| "unknown".to_string())
}
pub async fn unified_auth(
State(state): State<ApiState>,
axum::extract::ConnectInfo(addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
mut request: Request,
next: Next,
) -> Response {
let headers = request.headers();
let uri = request.uri().clone();
let client_addr = client_ip(headers, Some(addr));
// Priority 1: Cookie session
let cookies = extract_cookies(headers);
@@ -205,7 +223,7 @@ pub async fn unified_auth(
jwt_jti: None,
jwt_exp: None,
};
if let Err(e) = state.db.update_api_key_usage(&record.key_id, None).await {
if let Err(e) = state.db.update_api_key_usage(&record.key_id, Some(client_addr.as_str())).await {
tracing::warn!("[AUTH] Failed to update key usage: {}", e);
}
request.extensions_mut().insert(auth);
@@ -320,7 +338,7 @@ pub async fn unified_auth(
jwt_exp: None,
};
if let Err(e) = state.db.update_api_key_usage(&record.key_id, None).await {
if let Err(e) = state.db.update_api_key_usage(&record.key_id, Some(client_addr.as_str())).await {
tracing::warn!("[AUTH] Failed to update key usage: {}", e);
}
+10
View File
@@ -8,6 +8,7 @@ pub mod clip_api;
pub mod cluster_agent;
pub mod monitor;
pub mod docs;
pub mod export_api;
pub mod face_filter;
pub mod file_progress;
pub mod files;
@@ -30,7 +31,16 @@ pub mod tmdb_api;
pub mod trace_agent_api;
pub mod types;
pub mod universal_search;
pub mod folder_api;
pub mod import_api;
pub mod unregister_api;
pub mod vlm_search;
pub mod job_management;
pub use server::start_server;
mod admin_cleanup;
mod pipeline_tools;
mod upload_paths;
mod file_replicas;
mod mount_points;
mod directory_browser;
+182
View File
@@ -0,0 +1,182 @@
//! Mount Points API - Display views for file replicas
use axum::{
extract::{Path, State, Query},
http::StatusCode,
response::Json,
routing::{get, post, delete},
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, FromRow};
use tracing::{error, info};
use crate::api::types::AppState;
#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct MountPoint {
pub id: i32,
pub name: String,
pub mount_path: String,
pub description: Option<String>,
pub enabled: bool,
pub created_at: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, FromRow)]
pub struct MountReplica {
pub id: i32,
pub mount_id: i32,
pub replica_id: i32,
pub display_name: Option<String>,
pub display_order: i32,
pub file_uuid: String,
pub replica_path: String,
pub replica_name: Option<String>,
pub is_primary: bool,
}
#[derive(Debug, Deserialize)]
pub struct CreateMountRequest {
pub name: String,
pub mount_path: String,
pub description: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct AddReplicaToMountRequest {
pub replica_id: i32,
pub display_name: Option<String>,
pub display_order: Option<i32>,
}
pub fn mount_point_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/admin/mounts", get(list_mounts))
.route("/api/v1/admin/mounts", post(create_mount))
.route("/api/v1/admin/mount-replicas/:replica_id", delete(remove_replica_from_mount))
.route("/api/v1/admin/mount-replicas", get(list_mount_replicas))
.route("/api/v1/admin/mount-replicas", post(add_replica_to_mount))
.route("/api/v1/admin/mounts/:id", get(get_mount))
.route("/api/v1/admin/mounts/:id", delete(delete_mount))
}
fn get_pool(state: &AppState) -> &PgPool {
state.db.pool()
}
async fn list_mounts(State(state): State<AppState>) -> Result<Json<Vec<MountPoint>>, StatusCode> {
let pool = get_pool(&state);
let mounts = sqlx::query_as::<_, MountPoint>(
"SELECT id, name, mount_path, description, enabled, created_at::text
FROM mount_points WHERE enabled = TRUE ORDER BY name"
)
.fetch_all(pool)
.await
.map_err(|e| { error!("[mounts] list failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?;
Ok(Json(mounts))
}
async fn create_mount(
State(state): State<AppState>,
Json(req): Json<CreateMountRequest>,
) -> Result<Json<MountPoint>, StatusCode> {
let pool = get_pool(&state);
let mount = sqlx::query_as::<_, MountPoint>(
"INSERT INTO mount_points (name, mount_path, description) VALUES ($1, $2, $3)
RETURNING id, name, mount_path, description, enabled, created_at::text"
)
.bind(&req.name)
.bind(&req.mount_path)
.bind(&req.description)
.fetch_one(pool)
.await
.map_err(|e| { error!("[mounts] create failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?;
info!("[mounts] created: {} -> {}", mount.name, mount.mount_path);
Ok(Json(mount))
}
async fn delete_mount(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
sqlx::query("DELETE FROM mount_points WHERE id = $1 AND name NOT IN ('library', 'upload', 'archive')")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({"success": true})))
}
async fn list_mount_replicas(
State(state): State<AppState>,
Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<Vec<MountReplica>>, StatusCode> {
let id: i32 = params.get("mount_id").and_then(|v| v.parse().ok()).ok_or(StatusCode::BAD_REQUEST)?;
let pool = get_pool(&state);
let replicas = sqlx::query_as::<_, MountReplica>(
"SELECT mr.id, mr.mount_id, mr.replica_id, mr.display_name, mr.display_order,
fr.file_uuid, fr.replica_path, fr.replica_name, fr.is_primary
FROM mount_replicas mr
JOIN file_replicas fr ON fr.id = mr.replica_id
WHERE mr.mount_id = $1
ORDER BY mr.display_order, mr.id"
)
.bind(id)
.fetch_all(pool)
.await
.map_err(|e| { error!("[mounts] replicas list failed: {}", e); StatusCode::INTERNAL_SERVER_ERROR })?;
Ok(Json(replicas))
}
async fn add_replica_to_mount(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(req): Json<AddReplicaToMountRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
sqlx::query(
"INSERT INTO mount_replicas (mount_id, replica_id, display_name, display_order)
VALUES ($1, $2, $3, $4) ON CONFLICT (mount_id, replica_id) DO NOTHING"
)
.bind(id)
.bind(req.replica_id)
.bind(&req.display_name)
.bind(req.display_order.unwrap_or(0))
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({"success": true})))
}
async fn remove_replica_from_mount(
State(state): State<AppState>,
Path((id, replica_id)): Path<(i32, i32)>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
sqlx::query("DELETE FROM mount_replicas WHERE mount_id = $1 AND replica_id = $2")
.bind(id)
.bind(replica_id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(serde_json::json!({"success": true})))
}
async fn get_mount(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<MountPoint>, StatusCode> {
let pool = get_pool(&state);
let mount = sqlx::query_as::<_, MountPoint>(
"SELECT id, name, mount_path, description, enabled, created_at::text
FROM mount_points WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(mount))
}
+280
View File
@@ -0,0 +1,280 @@
use axum::{
extract::State,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::Path;
use crate::api::types::AppState;
#[derive(Serialize, Deserialize, Clone)]
struct ToolInfo {
key: String,
name: String,
available: bool,
detail: String,
path: String,
version: String,
}
#[derive(Serialize, Deserialize)]
struct PipelineData {
cli: Vec<ToolInfo>,
asr: Vec<ToolInfo>,
face: Vec<ToolInfo>,
services: Vec<ToolInfo>,
worker: Option<ToolInfo>,
}
/// Check if a binary exists and is executable
fn probe_binary(path: &Path, name: &str, _version_args: Option<&str>) -> ToolInfo {
let available = path.exists() && path.is_file();
let version = if available {
// For now, just check file metadata; version extraction would require running the binary
"installed".to_string()
} else {
String::new()
};
let detail = if available {
match path.metadata() {
Ok(meta) => {
let size = meta.len();
if size >= 1_073_741_824 {
format!("{:.1} GB", size as f64 / 1_073_741_824.0)
} else if size >= 1_048_576 {
format!("{:.1} MB", size as f64 / 1_048_576.0)
} else {
format!("{:.0} KB", size as f64 / 1024.0)
}
}
Err(_) => "unknown size".to_string(),
}
} else {
"Not found".to_string()
};
ToolInfo {
key: name.replace(' ', "_").to_lowercase(),
name: name.to_string(),
available,
detail,
path: path.to_string_lossy().to_string(),
version,
}
}
/// Probe a service health endpoint (async)
async fn probe_service(name: &str, url: &str, detail: &str) -> ToolInfo {
// The URL may be a bare host, a /health endpoint, or an API path such as
// /v1/chat/completions — always probe the server root /health.
let base = match url.find("/v1/") {
Some(pos) => url[..pos].to_string(),
None => url.trim_end_matches('/').to_string(),
};
let health_url = if base.to_lowercase().ends_with("/health") {
base.clone()
} else {
format!("{}/health", base)
};
let available = match reqwest::get(&health_url).await {
Ok(resp) => resp.status().is_success(),
Err(_) => false,
};
ToolInfo {
key: name.replace(' ', "_").to_lowercase(),
name: name.to_string(),
available,
detail: detail.to_string(),
path: url.to_string(),
version: if available { "Running".to_string() } else { "Stopped".to_string() },
}
}
/// Check if a binary is in PATH
fn find_in_path(binary: &str) -> Option<String> {
if let Ok(paths) = std::env::var("PATH") {
for dir in paths.split(':') {
let candidate = Path::new(dir).join(binary);
if candidate.exists() && candidate.is_file() {
return Some(candidate.to_string_lossy().to_string());
}
}
}
None
}
/// Check if worker process is running
fn probe_worker() -> Option<ToolInfo> {
let output = std::process::Command::new("pgrep")
.arg("-f")
.arg("momentry worker")
.output()
.ok()?;
if output.status.success() {
let pids = String::from_utf8_lossy(&output.stdout)
.trim()
.to_string();
Some(ToolInfo {
key: "worker".to_string(),
name: "Momentry Worker".to_string(),
available: true,
detail: format!("PIDs: {}", pids),
path: "momentry worker".to_string(),
version: "Running".to_string(),
})
} else {
None
}
}
pub async fn probe_pipeline_tools(
State(state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
let scripts_dir = crate::core::config::SCRIPTS_DIR.as_str();
let cli_dir = crate::core::config::CLI_DIR.as_str();
// CLI Tools (Swift processors)
let swift_release = format!("{}/swift_processors/.build/release", scripts_dir);
// ASR / ASRX Tools (Rust)
let rust_release = format!("{}/rust/target/release", cli_dir);
let cli_tools = vec![
probe_binary(
Path::new(&format!("{}/swift_face", swift_release)),
"Swift Face",
None,
),
probe_binary(
Path::new(&format!("{}/swift_ocr", swift_release)),
"Swift OCR",
None,
),
probe_binary(
Path::new(&format!("{}/swift_scene_detector", swift_release)),
"Swift Scene Cut",
None,
),
probe_binary(
Path::new(&format!("{}/rust_cut", rust_release)),
"Rust Scene Cut",
None,
),
];
// ASR / ASRX Tools (Rust)
let asr_tools = vec![
probe_binary(
Path::new(&format!("{}/rust_asr_asrx", rust_release)),
"Rust ASR/ASRX",
None,
),
probe_binary(
Path::new(&format!("{}/rust_whisper_rs", rust_release)),
"Rust Whisper",
None,
),
];
// Face Tools (Rust)
let face_tools = vec![
probe_binary(
Path::new(&format!("{}/rust_appearance", rust_release)),
"Rust Appearance",
None,
),
probe_binary(
Path::new(&format!("{}/rust_face_processor", rust_release)),
"Rust Face Processor",
None,
),
probe_binary(
Path::new(&format!("{}/rust_face_cluster", rust_release)),
"Rust Face Cluster",
None,
),
probe_binary(
Path::new(&format!("{}/rust_store_traced_faces", rust_release)),
"Rust Store Traced Faces",
None,
),
];
// Services
let chat_url = crate::core::config::LLM_HEALTH_URL.as_str();
let embed_url = crate::core::config::EMBED_URL.as_str();
// VLM URL from admin config
let vlm_url = state
.admin_config_manager
.get_llm_config("vlm")
.await
.map(|c| c.url)
.unwrap_or_else(|| "http://localhost:8082".to_string());
let chat_svc = probe_service("Chat LLM", chat_url, "LLM Inference Server").await;
let embed_svc = probe_service("Embedding", embed_url, "Embedding Server").await;
let vlm_svc = probe_service("VLM llama-server", &vlm_url, "Vision Language Model").await;
let services = vec![chat_svc, embed_svc, vlm_svc];
// Worker
let worker = probe_worker();
let data = PipelineData {
cli: cli_tools,
asr: asr_tools,
face: face_tools,
services,
worker,
};
Ok(Json(serde_json::to_value(data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?))
}
/// Probe release tools (pg_dump, release_pack.py, etc.)
pub async fn probe_release_tools(
State(_state): State<AppState>,
) -> Result<Json<Value>, StatusCode> {
let mut tools = Vec::new();
// Check release_pack.py
let momentry_root = crate::core::path_utils::momentry_root();
let release_pack = momentry_root.join("scripts/release_pack.py");
tools.push(json!({
"name": "release_pack.py",
"available": release_pack.exists(),
"path": release_pack.to_string_lossy().to_string(),
}));
// Check pg_dump
let pg_dump_path = find_in_path("pg_dump");
tools.push(json!({
"name": "pg_dump",
"available": pg_dump_path.is_some(),
"path": pg_dump_path.unwrap_or_else(|| "Not found".to_string()),
}));
// Check ffmpeg
let ffmpeg_path = find_in_path("ffmpeg");
tools.push(json!({
"name": "ffmpeg",
"available": ffmpeg_path.is_some(),
"path": ffmpeg_path.unwrap_or_else(|| "Not found".to_string()),
}));
Ok(Json(json!({ "tools": tools })))
}
pub fn pipeline_tools_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/admin/pipeline-tools", get(probe_pipeline_tools))
.route("/api/v1/admin/release-tools", get(probe_release_tools))
}
+418 -25
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,40 @@ fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
}
}
}
}
deleted_count
}
/// Delete only the output files of the given processors (single-processor re-run).
/// Other processors' outputs (and the combined `{uuid}.json`) are preserved so the
/// rest of the pipeline data stays intact.
fn delete_processor_output_files(uuid: &str, processors: &[String], output_dir: &str) -> u64 {
let mut files: Vec<String> = Vec::new();
for proc in processors {
match proc.as_str() {
"asr" => files.push(format!("{}.asr.json", uuid)),
"asr_asrx" | "asrx" => files.push(format!("{}.asrx.json", uuid)),
"ocr" => files.push(format!("{}.ocr.json", uuid)),
"cut" => files.push(format!("{}.cut.json", uuid)),
"face" => files.push(format!("{}.face.json", uuid)),
"face_cluster" => files.push(format!("{}.face_cluster.json", uuid)),
"face_trace" => files.push(format!("{}.face_traced.json", uuid)),
"scene_vlm" | "scene" => files.push(format!("{}.scenes.json", uuid)),
"pose" => files.push(format!("{}.pose.json", uuid)),
"hand" => files.push(format!("{}.hand.json", uuid)),
"appearance" => files.push(format!("{}.appearance.json", uuid)),
"tkg" => files.push(format!("{}.tkg.json", uuid)),
_ => continue,
}
}
let mut deleted_count = 0u64;
for name in files {
let path = std::path::Path::new(output_dir).join(&name);
if path.exists() && std::fs::remove_file(&path).is_ok() {
tracing::info!("[FORCE_RESCAN] Deleted output file: {}", name);
deleted_count += 1;
}
}
deleted_count
}
@@ -327,9 +369,28 @@ async fn trigger_processing(
// Clean up stale processor_results from previous runs
// Old entries with status='running' from a dead worker session
// would block the worker from actually running processors.
// For single-processor re-runs, only the requested processors are reset
// so other processors' completed results are preserved.
let pr_table = schema::table_name("processor_results");
sqlx::query(&format!("DELETE FROM {pr_table} WHERE job_id = $1"))
if processors_to_run.is_empty() {
sqlx::query(&format!("DELETE FROM {pr_table} WHERE job_id = $1"))
.bind(job_id)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to clean processor_results for job {}: {}",
job_id,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
} else {
sqlx::query(&format!(
"DELETE FROM {pr_table} WHERE job_id = $1 AND (processor = ANY($2) OR processor_type = ANY($2))"
))
.bind(job_id)
.bind(&processors_to_run)
.execute(state.db.pool())
.await
.map_err(|e| {
@@ -340,17 +401,113 @@ async fn trigger_processing(
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
// Scene VLM rows are file-keyed with job_id = NULL, delete them separately
if processors_to_run
.iter()
.any(|p| p == "scene_vlm" || p == "scene")
{
sqlx::query(&format!(
"DELETE FROM {pr_table} WHERE file_uuid = $1 AND processor_type = 'scene_vlm'"
))
.bind(&file_uuid)
.execute(state.db.pool())
.await
.map_err(|e| {
tracing::error!(
"[TRIGGER] Failed to clean scene_vlm results for {}: {}",
file_uuid,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
}
}
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 deleted_count = delete_output_files_for_uuid(&file_uuid, &output_dir);
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() {
delete_output_files_for_uuid(&file_uuid, &output_dir)
+ delete_output_files_for_uuid(&file_uuid, &global_dir)
} else {
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 {}",
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?}, backup={:?})",
deleted_count,
file_uuid
file_uuid,
processors_to_run,
backup_label
);
// Re-running ASR/OCR/Scene VLM must also rebuild the search index:
// - asr/asrx/ocr → Rule 1 re-chunking + re-vectorize (chunk table + momentry_rule1)
// - scene_vlm → _scenes collection regeneration
// Signal the worker via Redis so the Rule 1 guard doesn't skip re-chunking
// just because old chunks still exist.
let rebuild_procs = ["asr", "asr_asrx", "asrx", "ocr", "scene_vlm", "scene"];
let needs_rebuild = processors_to_run.is_empty()
|| processors_to_run
.iter()
.any(|p| rebuild_procs.contains(&p.as_str()));
if needs_rebuild {
let key = format!("{}rerun_rebuild:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
let flag_value = if processors_to_run.is_empty() {
"all".to_string()
} else {
processors_to_run.join(",")
};
let _: Result<String, _> = redis::cmd("SET")
.arg(&key)
.arg(&flag_value)
.arg("EX")
.arg(86400)
.query_async(&mut conn)
.await;
tracing::info!(
"[TRIGGER] Set rerun_rebuild flag for {} = {}",
file_uuid,
flag_value
);
}
}
// Update existing job with new face_settings if provided
@@ -467,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)?;
@@ -788,6 +955,224 @@ struct ProcessorCountsResponse {
processors: Vec<ProcessorCountInfo>,
}
/// GET /api/v1/processor-json?file_hash=...&processor=...
/// Serves raw processor output JSON files from the output directory.
/// GET /api/v1/output-completeness
/// 檢查所有影片的產出完整性,回傳缺項清單。
/// 前端用此 API 將有缺項的 completed 卡片改為紅字顯示。
#[derive(serde::Serialize)]
struct OutputCompletenessItem {
file_uuid: String,
file_name: String,
status: String,
is_complete: bool,
missing: Vec<String>,
}
async fn get_output_completeness(
State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, StatusCode> {
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!(
"SELECT file_uuid, file_name, status FROM {} WHERE file_type = 'video' ORDER BY file_name",
videos_table
))
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[output-completeness] DB query failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let mut items = Vec::new();
for (uuid, file_name, status) in rows {
if status != "completed" {
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() {
// 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));
}
}
}
// 檢查 trace 目錄(如果有 faces)
let face_json = format!("{}/{}.face.json", output_dir, uuid);
if std::path::Path::new(&face_json).exists() {
if let Ok(content) = std::fs::read_to_string(&face_json) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
let total_faces = data
.get("total_faces")
.or_else(|| data.get("data").and_then(|d| d.get("total_faces")))
.and_then(|v| v.as_u64())
.unwrap_or(0);
if total_faces > 0 {
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) {
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() {
for f in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] {
if !entry.path().join(f).exists() {
missing.push(format!("{}/{}", name, f));
}
}
}
}
}
}
}
}
}
}
items.push(OutputCompletenessItem {
file_uuid: uuid,
file_name,
status,
is_complete: missing.is_empty(),
missing,
});
}
let complete_count = items.iter().filter(|i| i.is_complete).count();
let incomplete_count = items.len() - complete_count;
Ok(Json(serde_json::json!({
"total": items.len(),
"complete": complete_count,
"incomplete": incomplete_count,
"items": items,
})))
}
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((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({"error": "Missing file_hash"})),
))?;
let processor = params.get("processor").ok_or((
StatusCode::BAD_REQUEST,
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",
"face" => "face",
"face_cluster" => "face_cluster",
"face_trace" | "face_traced" => "face_traced",
"ocr" => "ocr",
"cut" => "cut",
"scenes" | "scene_vlm" => "scenes",
"probe" => "probe",
"tkg" => "tkg",
other => other,
};
// 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) {
Ok(json) => Ok(Json(json)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Parse error: {}", e)})),
)),
},
Err(_) => Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("No {} output for {}", processor, file_uuid)})),
)),
}
}
async fn get_processor_counts(
State(state): State<AppState>,
Path(file_uuid): Path<String>,
@@ -814,31 +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();
let json_path =
std::path::Path::new(&output_dir).join(format!("{}.{}.json", file_uuid, proc_name));
let json_ext = match proc_name {
"face_trace" => "face_traced",
other => other,
};
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" {
@@ -907,7 +1300,7 @@ async fn get_processor_counts(
Ok(Json(ProcessorCountsResponse {
file_uuid,
output_dir,
output_dir: per_lib_dir,
processors: results,
}))
}
@@ -919,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(
@@ -929,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");
@@ -990,10 +1380,10 @@ async fn trigger_vlm_summary(
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/output-completeness", get(get_output_completeness))
.route("/api/v1/file/:file_uuid/process", post(trigger_processing))
.route(
"/api/v1/file/:file_uuid/json/:processor",
@@ -1016,10 +1406,13 @@ pub fn processing_routes() -> Router<AppState> {
"/api/v1/file/:file_uuid/processor-counts",
get(get_processor_counts),
)
.route(
"/api/v1/processor-json",
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),
)
}
+662 -215
View File
File diff suppressed because it is too large Load Diff
+209 -15
View File
@@ -250,12 +250,12 @@ async fn scan_files(
State(state): State<AppState>,
Query(params): Query<ScanFilesQuery>,
) -> Result<Json<ScanFilesResponse>, StatusCode> {
// 用 momentry root 而非 current_exe(部署時 binary 在 <root>/bin/ 下,
// 直接取 parent 會多一層 bin 導致掃描到錯誤目錄)。
let demo_dir_str = std::env::var("MOMENTRY_SFTP_ROOT").unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/sftpgo/data/demo")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/sftpgo/data/demo".to_string())
crate::core::path_utils::demo_dir()
.to_string_lossy()
.to_string()
});
let demo_dir = std::path::Path::new(&demo_dir_str);
@@ -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) {
@@ -1311,6 +1321,7 @@ async fn count_edges(pool: &sqlx::PgPool, table: &str, file_uuid: &str, edge_typ
pub fn scan_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/files/scan", get(scan_files))
.route("/api/v1/files/scan-path", get(scan_specific_path))
.route("/api/v1/stats/sftpgo", get(get_sftpgo_status))
.route(
"/api/v1/stats/ingestion-status/:file_uuid",
@@ -1329,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;
@@ -1520,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) {
@@ -1577,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) {
@@ -1644,11 +1662,17 @@ async fn get_pipeline_progress_handler(
}
/// Quick scene VLM stats endpoint (fast, no Qdrant queries)
async fn get_scene_vlm_stats(
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() {
@@ -1698,3 +1722,173 @@ async fn get_scene_vlm_stats(
vlm_total: total_scenes.max(scenes_array),
}))
}
// 掃描指定路徑
#[derive(Debug, Deserialize)]
pub struct ScanPathQuery {
pub path: String,
}
#[derive(Debug, Serialize)]
pub struct ScanPathResponse {
pub scanned_files: usize,
pub new_files: usize,
pub path: String,
}
fn scan_dir_recursive(dir: &std::path::Path, files: &mut Vec<std::path::PathBuf>) {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.filter_map(|e| e.ok()) {
let path = entry.path();
if path.is_dir() {
scan_dir_recursive(&path, files);
} else if path.is_file() {
files.push(path);
}
}
}
}
async fn scan_specific_path(
State(state): State<AppState>,
axum::extract::ConnectInfo(_addr): axum::extract::ConnectInfo<std::net::SocketAddr>,
Query(params): Query<ScanPathQuery>,
) -> Result<Json<ScanPathResponse>, StatusCode> {
use std::collections::HashSet;
let scan_root = std::path::Path::new(&params.path);
if !scan_root.exists() || !scan_root.is_dir() {
return Err(StatusCode::NOT_FOUND);
}
let allowed_extensions = vec!["mp4", "mov", "mkv", "avi", "webm", "jpg", "jpeg", "png", "gif", "webp"];
let table = schema::table_name("videos");
let registered: Vec<String> = sqlx::query_scalar(&format!("SELECT file_path FROM {}", table))
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let registered_set: HashSet<String> = registered.into_iter().collect();
// ── 收集候選檔案 (path, name, ext) ──────────────────────────────
// 優先透過 MarkBase 虛擬層 (/api/v2/myfiles/:user/files) 取得檔案清單;
// MarkBase 管不到的路徑(upload root 之外、外接碟等)回退本地遞迴掃描。
let mut candidates: Vec<(String, String, String)> = Vec::new(); // (path, name, ext)
// 依 upload_paths 推導 MarkBase username(user root = <upload>/<name>)
let mut username: Option<String> = None;
let mut rel_base = String::new();
let paths_table = schema::table_name("upload_paths");
if let Ok(rows) = sqlx::query_as::<_, (String, String)>(
&format!("SELECT name, full_path FROM {} WHERE enabled = true", paths_table),
)
.fetch_all(state.db.pool())
.await
{
for (name, full_path) in rows {
if params.path == full_path {
username = Some(name);
rel_base = String::new();
break;
}
if params.path.starts_with(&format!("{}/", full_path)) {
username = Some(name);
rel_base = params.path[full_path.len()..].trim_start_matches('/').to_string();
break;
}
}
}
let mut used_markbase = false;
if let Some(user) = username {
let markbase_base =
std::env::var("MOMENTRY_MARKBASE_URL").unwrap_or_else(|_| "http://localhost:11438".to_string());
let mut url = format!("{}/api/v2/myfiles/{}/files", markbase_base, user);
if !rel_base.is_empty() {
url.push_str(&format!("?folder={}", rel_base));
}
let client = reqwest::Client::new();
if let Ok(resp) = client.get(&url).send().await {
if resp.status().is_success() {
if let Ok(files) = resp.json::<Vec<serde_json::Value>>().await {
for file in files {
let name = file.get("name").and_then(|v| v.as_str()).unwrap_or("");
if name.is_empty() {
continue;
}
let folder = file.get("folder").and_then(|v| v.as_str()).unwrap_or("");
// MarkBase 回傳的 folder 相對於 user root;換算成相對於掃描路徑
let rel_to_scan = folder.strip_prefix(&rel_base).unwrap_or(folder);
let rel_to_scan = rel_to_scan.trim_start_matches('/');
let file_path = if rel_to_scan.is_empty() {
format!("{}/{}", params.path, name)
} else {
format!("{}/{}/{}", params.path, rel_to_scan, name)
};
let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
if !allowed_extensions.contains(&ext.as_str()) {
continue;
}
candidates.push((file_path, name.to_string(), ext));
}
used_markbase = true;
}
}
}
}
if !used_markbase {
// 回退:本地遞迴掃描(MarkBase 無法服務此路徑)
let mut all_files = Vec::new();
scan_dir_recursive(scan_root, &mut all_files);
for file_path in all_files {
let path_str = file_path.to_string_lossy().to_string();
let ext = file_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
if !allowed_extensions.contains(&ext.as_str()) {
continue;
}
let file_name = file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.to_string();
candidates.push((path_str, file_name, ext));
}
}
let mut scanned = 0usize;
let mut new_files = 0usize;
for (path_str, file_name, ext) in candidates {
scanned += 1;
if registered_set.contains(&path_str) {
continue;
}
let file_uuid = uuid::Uuid::new_v4().to_string().replace("-", "");
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, file_path, file_name, file_type, status) VALUES ($1, $2, $3, $4, 'pending')",
table
))
.bind(&file_uuid)
.bind(&path_str)
.bind(&file_name)
.bind(&ext)
.execute(state.db.pool())
.await;
new_files += 1;
}
Ok(Json(ScanPathResponse {
scanned_files: scanned,
new_files,
path: params.path,
}))
}
+129 -32
View File
@@ -112,26 +112,49 @@ async fn enrich_from_pg(
qdrant_score: f32,
) -> Option<SearchResult> {
match db.get_chunk_by_file_and_chunk_id(file_uuid, chunk_id).await {
Ok(Some(p)) => Some(SearchResult {
id: 0,
file_uuid: p.file_uuid.clone(),
parent_id: p.scene_order,
scene_order: Some(p.scene_order),
start_frame: p.start_frame,
end_frame: p.end_frame,
fps: p.fps,
start_time: p.start_time,
end_time: p.end_time,
raw_text: None,
summary: Some(p.summary),
text_content: p.text_content.clone(),
metadata: p.metadata.clone(),
similarity: Some(qdrant_score as f64),
file_name: None,
serve_url: None,
thumbnail_url: None,
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
}),
Ok(Some(p)) => {
// Get file_name from videos table — return None if video doesn't exist (orphaned)
let file_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_name FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(file_uuid)
.fetch_optional(db.pool())
.await
.ok()
.flatten();
if file_name.is_none() {
return None; // Skip orphaned chunks
}
let thumbnail_url = format!(
"/api/v1/file/{}/thumbnail?frame={}",
file_uuid, p.start_frame
);
let serve_url = format!("/api/v1/file/{}/video", file_uuid);
Some(SearchResult {
id: 0,
file_uuid: p.file_uuid.clone(),
parent_id: p.scene_order,
scene_order: Some(p.scene_order),
start_frame: p.start_frame,
end_frame: p.end_frame,
fps: p.fps,
start_time: p.start_time,
end_time: p.end_time,
raw_text: None,
summary: Some(p.summary),
text_content: p.text_content.clone(),
metadata: p.metadata.clone(),
similarity: Some(qdrant_score as f64),
file_name,
serve_url: Some(serve_url),
thumbnail_url: Some(thumbnail_url),
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
})
}
Ok(None) => {
// Chunk not found — try VLM summary lookup by vlm_point_id
enrich_vlm_from_pg(db, file_uuid, chunk_id, qdrant_score).await
@@ -195,8 +218,16 @@ async fn enrich_vlm_from_pg(
"vlm_description_localized": vlm_desc_localized,
})),
similarity: Some(qdrant_score as f64),
file_name: None,
serve_url: None,
file_name: sqlx::query_scalar(&format!(
"SELECT file_name FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(file_uuid)
.fetch_optional(db.pool())
.await
.ok()
.flatten(),
serve_url: Some(format!("/api/v1/file/{}/video", file_uuid)),
thumbnail_url: Some(format!(
"/api/v1/file/{}/trace/{}/thumbnail",
file_uuid, trace_id
@@ -205,7 +236,22 @@ async fn enrich_vlm_from_pg(
})
}
fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult {
async fn pg_result_to_search(p: &SemanticSearchResult, db: &crate::core::db::PostgresDb) -> SearchResult {
let file_uuid_str = p.file_uuid.as_deref().unwrap_or("");
let file_name: Option<String> = if file_uuid_str.is_empty() {
None
} else {
sqlx::query_scalar(&format!(
"SELECT file_name FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(file_uuid_str)
.fetch_optional(db.pool())
.await
.ok()
.flatten()
};
SearchResult {
id: 0,
file_uuid: p.file_uuid.clone(),
@@ -221,9 +267,12 @@ fn pg_result_to_search(p: &SemanticSearchResult) -> SearchResult {
text_content: p.text_content.clone(),
metadata: p.metadata.clone(),
similarity: p.similarity,
file_name: None,
serve_url: None,
thumbnail_url: None,
file_name,
serve_url: p.file_uuid.as_ref().map(|uuid| format!("/api/v1/file/{}/video", uuid)),
thumbnail_url: p.file_uuid.as_ref().map(|uuid| format!(
"/api/v1/file/{}/thumbnail?frame={}",
uuid, p.start_frame
)),
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
}
}
@@ -698,13 +747,15 @@ pub async fn keyword_search(
let (clean_query, source_filter) = parse_source_filter(&req.query);
let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type);
// Keyword search via PG BM25
// Keyword search via PG BM25 — fetch enough for pagination + orphan filter buffer
// Fetch page * limit * 2 to account for orphaned chunks being filtered out
let bm25_limit = (page as i64) * (limit as i64) * 2;
let keyword_results = db
.search_bm25(
&clean_query,
req.file_uuid.as_deref(),
chunk_type_filter,
limit as i64,
bm25_limit,
)
.await
.map_err(|e| {
@@ -721,6 +772,10 @@ pub async fn keyword_search(
req.query
);
// Pagination: skip results from previous pages
let skip_count = (page - 1) * limit;
let mut valid_index = 0usize;
let mut results = Vec::new();
for row in keyword_results.iter() {
if let Ok(Some(p)) = db
@@ -734,6 +789,48 @@ pub async fn keyword_search(
p.text_content.clone()
};
// Get file_name from videos table — skip orphaned chunks (no video record)
let file_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_name FROM {} WHERE file_uuid = $1",
crate::core::db::schema::table_name("videos")
))
.bind(&p.file_uuid)
.fetch_optional(db.pool())
.await
.ok()
.flatten();
// Skip results from unregistered files (orphaned chunks)
if file_name.is_none() {
continue;
}
// Pagination: skip results from previous pages
if valid_index < skip_count {
valid_index += 1;
continue;
}
valid_index += 1;
// Stop if we have enough results for this page
if results.len() >= limit {
break;
}
// Normalize BM25 score to 0-1 range (BM25 can be > 1.0)
let normalized_score = (row.bm25_score as f64).min(1.0);
// Generate thumbnail and serve URLs
let thumbnail_url = format!(
"/api/v1/file/{}/thumbnail?frame={}",
p.file_uuid.as_deref().unwrap_or(""),
p.start_frame
);
let serve_url = format!(
"/api/v1/file/{}/video",
p.file_uuid.as_deref().unwrap_or("")
);
results.push(SearchResult {
id: 0,
file_uuid: p.file_uuid.clone(),
@@ -748,10 +845,10 @@ pub async fn keyword_search(
summary: text.clone(),
text_content: text,
metadata: p.metadata.clone(),
similarity: Some(row.bm25_score as f64),
file_name: None,
serve_url: None,
thumbnail_url: None,
similarity: Some(normalized_score),
file_name,
serve_url: Some(serve_url),
thumbnail_url: Some(thumbnail_url),
source_type: Some(map_chunk_type_to_source(&p.chunk_type)),
});
}
+28 -2
View File
@@ -1,6 +1,6 @@
use std::time::Duration;
use axum::{Json, Router};
use axum::{routing::get, Json, Router};
use serde_json::json;
use tokio::time::timeout;
use tower_http::cors::{Any, CorsLayer};
@@ -11,6 +11,7 @@ use crate::core::db::{Database, PostgresDb, QdrantDb};
use crate::Embedder;
use super::admin_config;
use super::pipeline_tools;
use super::agent_api;
use super::agent_search;
use super::auth;
@@ -19,6 +20,10 @@ use super::checkin_api;
use super::clip_api;
use super::cluster_agent;
use super::docs;
use super::export_api;
use super::folder_api;
use super::import_api;
use super::unregister_api;
use super::face_filter;
use super::file_progress;
use super::files;
@@ -41,6 +46,9 @@ use super::tmdb_api;
use super::trace_agent_api;
use super::types::AppState;
use super::monitor;
use super::mount_points;
use super::upload_paths;
use super::directory_browser;
use super::universal_search::universal_search_routes;
use super::vlm_search;
use super::job_management;
@@ -159,10 +167,15 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
.merge(profile::profile_routes())
.merge(face_filter::face_filter_routes())
.merge(admin_config::admin_config_routes())
.merge(pipeline_tools::pipeline_tools_routes())
.merge(vlm_search::vlm_search_routes())
.merge(billing::billing_routes())
.merge(job_management::job_management_routes())
.merge(service_management::router())
.merge(export_api::export_routes())
.merge(unregister_api::unregister_routes())
.merge(import_api::import_routes())
.merge(folder_api::folder_routes())
.layer(axum::middleware::from_fn_with_state(
state.api_state.clone(),
unified_auth,
@@ -196,10 +209,19 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
let app = Router::new()
.merge(auth::auth_routes())
.merge(public_health_routes)
.merge(service_management::public_routes())
.route("/api/v1/files/preview-by-path", get(markbase_compat::preview_file_by_path))
.route(
"/api/v1/file/:file_uuid/scenes/:filename",
get(media_api::scene_thumbnail),
)
.merge(docs::doc_routes())
.merge(monitor::monitor_routes())
.nest_service("/monitor", ServeDir::new("static/monitor"))
.merge(protected_routes)
.merge(upload_paths::upload_path_routes())
.merge(mount_points::mount_point_routes())
.merge(directory_browser::directory_browser_routes())
.layer(cors)
.layer(axum::middleware::from_fn(super::middleware::request_logger))
.layer(axum::middleware::from_fn(
@@ -211,7 +233,11 @@ pub async fn start_server(host: &str, port: u16) -> anyhow::Result<()> {
tracing::info!("Starting API server at http://{}", addr);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
)
.await?;
Ok(())
}
+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(())
}
File diff suppressed because it is too large Load Diff
+65 -8
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();
}
}
@@ -2117,6 +2117,17 @@ async fn delete_trace(
)
.await;
// 3b. Face-groups normalization (V1.0 §7 G1): unassigning a trace must
// detach it from its group (I4: assigned ⇔ group_id IS NOT NULL),
// otherwise the trace keeps appearing as a group member.
let _ = sqlx::query(&format!(
"UPDATE {tp_table} SET group_id = NULL WHERE {tp_table}.file_uuid = $1 AND {tp_table}.trace_id = $2"
))
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
// 4. Keep _faces points intact (do NOT delete)
// 5. Save operation snapshot for undo
@@ -2643,6 +2654,24 @@ async fn restore_trace(
)
.await;
// Face-groups normalization (V1.0 §7 G6): re-attach the restored trace
// to the group matching its restored name (recreates the group row if
// it no longer exists).
let tp_table = crate::core::db::schema::table_name("trace_profiles");
if let Ok(gid) =
crate::core::db::schema::get_or_create_group(state.db.pool(), &file_uuid, &profile_name)
.await
{
let _ = sqlx::query(&format!(
"UPDATE {tp_table} SET group_id = $1 WHERE {tp_table}.file_uuid = $2 AND {tp_table}.trace_id = $3"
))
.bind(gid)
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
}
// Clear any legacy deleted status markers
let legacy_filter = serde_json::json!({
"must": [
@@ -2776,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,
@@ -2788,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);
@@ -2800,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") {
@@ -2811,17 +2854,31 @@ 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();
let expected_path = format!("{}/{}/trace_{}/trace_profile.json", output_dir, file_uuid, trace_id);
let attempted = std::path::PathBuf::from(output_dir)
.join(&file_uuid)
.join(format!("trace_{}", trace_id))
.join("trace_profile.json");
// 檔案可能不存在,改用父目錄 canonicalize 取得絕對位置
let absolute_path = attempted
.parent()
.and_then(|p| std::fs::canonicalize(p).ok())
.map(|p| p.join("trace_profile.json").to_string_lossy().to_string())
.unwrap_or_else(|| attempted.to_string_lossy().to_string());
tracing::warn!(
"[TraceProfile] 404: file_uuid={} trace_id={} attempted_path={}",
file_uuid, trace_id, absolute_path
);
(StatusCode::NOT_FOUND, Json(serde_json::json!({
"error": "Trace profile file not found",
"error": format!("Trace profile file not found: {}", absolute_path),
"file_uuid": file_uuid,
"trace_id": trace_id,
"output_dir": output_dir,
"expected_path": expected_path
"expected_path": absolute_path,
"absolute_path": absolute_path
})))
}
}
+411
View File
@@ -0,0 +1,411 @@
/// Unregister API - remove files from system (optionally export first)
use axum::{
extract::{Path, Query, State},
http::StatusCode,
routing::post,
Json, Router,
};
use serde::{Deserialize, Serialize};
use crate::api::types::AppState;
// ─── Request/Response Structures ──────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct UnregisterQuery {
#[serde(default)]
pub export_first: bool,
/// 預設保留影片檔:unregister → register → deep scan 的用戶流程需要原檔。
/// 只有明確帶 keep_video=false(或 keep_video=0)才會刪除影片。
#[serde(default = "default_true")]
pub keep_video: bool,
#[serde(default)]
pub export_dir: Option<String>,
}
fn default_true() -> bool {
true
}
#[derive(Debug, Serialize)]
pub struct UnregisterResponse {
pub success: bool,
pub file_uuid: String,
pub exported: bool,
pub package_path: Option<String>,
pub deleted_records: usize,
pub message: String,
}
// ─── API Handlers ────────────────────────────────────────────────────────────
/// POST /api/v1/file/:uuid/unregister
/// Remove a file from the system (optionally export first)
pub async fn unregister_file_handler(
State(state): State<AppState>,
Path(uuid): Path<String>,
Query(params): Query<UnregisterQuery>,
) -> Result<Json<UnregisterResponse>, (StatusCode, Json<serde_json::Value>)> {
// Verify file exists
let video = state.db.get_video_by_uuid(&uuid).await.map_err(|e| {
(
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": format!("File not found: {}", e)})),
)
})?;
if video.is_none() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "File not found"})),
));
}
let video = video.unwrap();
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let export_dir = params.export_dir.unwrap_or_else(|| {
"/Users/accusys/momentry/offline_storage/files".to_string()
});
let mut exported = false;
let mut package_path = None;
// Optional: Export first
if params.export_first {
// Create export directory
if let Err(e) = std::fs::create_dir_all(&export_dir) {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Failed to create export dir: {}", e)})),
));
}
match crate::core::export::export_file(
state.db.pool(),
&uuid,
&output_dir,
&export_dir,
)
.await
{
Ok(pkg_path) => {
exported = true;
package_path = Some(pkg_path.to_string_lossy().to_string());
}
Err(e) => {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("Export failed: {}", e)})),
));
}
}
}
// Perform unregister
let deleted_records = unregister_file_from_system(
state.db.pool(),
&uuid,
&video.file_path,
&output_dir,
params.keep_video,
)
.await?;
let message = if exported {
let pkg = package_path.as_deref().unwrap_or("N/A");
format!(
"Exported and unregistered. {} records removed. Package: {}",
deleted_records, pkg
)
} else {
format!("Unregistered. {} records removed.", deleted_records)
};
Ok(Json(UnregisterResponse {
success: true,
file_uuid: uuid,
exported,
package_path,
deleted_records,
message,
}))
}
// ─── Unregister Logic ────────────────────────────────────────────────────────
async fn unregister_file_from_system(
pool: &sqlx::PgPool,
uuid: &str,
file_path: &str,
output_dir: &str,
keep_video: bool,
) -> Result<usize, (StatusCode, Json<serde_json::Value>)> {
let mut deleted = 0;
// 1. Delete from Qdrant (best effort)
// TODO: Implement Qdrant deletion
// 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 {
if let Err(e) = std::fs::remove_file(file_path) {
tracing::warn!("[Unregister] Failed to remove video {}: {}", file_path, e);
}
}
// 4. Get file_path before deleting video (for command_queue cleanup)
let file_path: Option<String> = sqlx::query_scalar(
"SELECT file_path FROM videos WHERE file_uuid = $1"
)
.bind(uuid)
.fetch_optional(pool)
.await
.unwrap_or(None);
// 5. Delete DB records (in order to respect foreign keys)
let tables_to_delete = [
("processor_results", "file_uuid"),
("monitor_jobs", "uuid"),
("trace_profiles", "file_uuid"),
("tkg_nodes", "file_uuid"),
("tkg_edges", "file_uuid"),
("chunk", "file_uuid"),
("face_detections", "file_uuid"),
];
// Mark video as unregistered before deleting related records
let update_result = sqlx::query("UPDATE videos SET status='unregistered' WHERE file_uuid = $1")
.bind(uuid)
.execute(pool)
.await;
if let Err(e) = update_result {
tracing::warn!("[Unregister] Failed to mark video as unregistered: {}", e);
}
// Delete related DB records
for (table, col) in tables_to_delete {
let table_name = crate::core::db::schema::table_name(table);
let result = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
.bind(uuid)
.execute(pool)
.await;
match result {
Ok(r) => deleted += r.rows_affected() as usize,
Err(e) => tracing::warn!("[Unregister] Failed to delete from {}: {}", table, e),
}
}
// 6. Delete related command_queue entries (by file_path)
if let Some(path) = file_path {
let cmd_result = sqlx::query(
"DELETE FROM command_queue WHERE value->>'file_path' = $1"
)
.bind(&path)
.execute(pool)
.await;
if let Ok(r) = cmd_result {
deleted += r.rows_affected() as usize;
tracing::info!("[Unregister] Deleted {} command_queue entries for {}", r.rows_affected(), uuid);
}
}
Ok(deleted)
}
async fn delete_output_files(uuid: &str, output_dir: &str) {
let dir = std::path::PathBuf::from(output_dir);
// Delete JSON files: {uuid}.*.json
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) {
let _ = std::fs::remove_file(&path);
}
}
}
}
// Delete trace directory: {uuid}/
let trace_dir = dir.join(uuid);
if trace_dir.exists() {
let _ = std::fs::remove_dir_all(&trace_dir);
}
}
// ─── 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),
)
}
+342
View File
@@ -0,0 +1,342 @@
//! Upload Paths management API
use axum::{
extract::{Path, State},
http::StatusCode,
response::Json,
routing::{get, post, put, delete},
Router,
};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, FromRow};
use tracing::{error, info};
use crate::api::types::AppState;
// ── Models ──────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, FromRow)]
#[serde(rename_all = "camelCase")]
pub struct UploadPath {
pub id: i32,
pub name: String,
pub base_path: String,
pub sub_path: String,
pub full_path: String,
pub output_path: Option<String>,
pub enabled: bool,
pub is_default: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateUploadPathRequest {
pub name: String,
#[serde(alias = "base_path")]
pub base_path: String,
#[serde(default, alias = "sub_path")]
pub sub_path: Option<String>,
#[serde(default, alias = "output_path")]
pub output_path: Option<String>,
#[serde(default, alias = "enabled")]
pub enabled: Option<bool>,
#[serde(default, alias = "is_default")]
pub is_default: Option<bool>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateUploadPathRequest {
#[serde(default, alias = "name")]
pub name: Option<String>,
#[serde(default, alias = "base_path")]
pub base_path: Option<String>,
#[serde(default, alias = "sub_path")]
pub sub_path: Option<String>,
#[serde(default, alias = "output_path")]
pub output_path: Option<String>,
#[serde(default, alias = "enabled")]
pub enabled: Option<bool>,
#[serde(default, alias = "is_default")]
pub is_default: Option<bool>,
}
// ── 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 ────────────────────────────────────────────────────────
fn get_pool(state: &AppState) -> &PgPool {
state.db.pool()
}
/// GET /api/v1/admin/upload-paths
async fn list_upload_paths(State(state): State<AppState>) -> Result<Json<Vec<UploadPath>>, StatusCode> {
let pool = get_pool(&state);
let paths = sqlx::query_as::<_, UploadPath>(
"SELECT id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text
FROM upload_paths ORDER BY is_default DESC, name ASC"
)
.fetch_all(pool)
.await
.map_err(|e| {
error!("[upload_paths] list failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
Ok(Json(paths))
}
/// POST /api/v1/admin/upload-paths
async fn create_upload_path(
State(state): State<AppState>,
Json(req): Json<CreateUploadPathRequest>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
let sub_path = req.sub_path.unwrap_or_default();
let full_path = if sub_path.is_empty() {
req.base_path.clone()
} else {
format!("{}/{}", req.base_path, sub_path)
};
if req.is_default.unwrap_or(false) {
sqlx::query("UPDATE upload_paths SET is_default = FALSE")
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
let path = sqlx::query_as::<_, UploadPath>(
"INSERT INTO upload_paths (name, base_path, sub_path, full_path, output_path, enabled, is_default)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, base_path, sub_path, full_path, enabled, is_default,
created_at::text, updated_at::text"
)
.bind(&req.name)
.bind(&req.base_path)
.bind(&sub_path)
.bind(&full_path)
.bind(&req.output_path)
.bind(req.enabled.unwrap_or(true))
.bind(req.is_default.unwrap_or(false))
.fetch_one(pool)
.await
.map_err(|e| {
error!("[upload_paths] create failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[upload_paths] created: {} -> {}", path.name, path.full_path);
Ok(Json(path))
}
/// GET /api/v1/admin/upload-paths/:id
async fn get_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
let path = sqlx::query_as::<_, UploadPath>(
"SELECT id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text
FROM upload_paths WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok(Json(path))
}
/// PUT /api/v1/admin/upload-paths/:id
async fn update_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(req): Json<UpdateUploadPathRequest>,
) -> Result<Json<UploadPath>, StatusCode> {
let pool = get_pool(&state);
if req.is_default == Some(true) {
sqlx::query("UPDATE upload_paths SET is_default = FALSE WHERE id != $1")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
let path = sqlx::query_as::<_, UploadPath>(
"UPDATE upload_paths
SET name = COALESCE($1, name),
base_path = COALESCE($2, base_path),
sub_path = COALESCE($3, sub_path),
output_path = COALESCE($4, output_path),
full_path = CASE
WHEN $2 IS NOT NULL OR $3 IS NOT NULL THEN
COALESCE($2, base_path) || CASE WHEN COALESCE($3, sub_path) != '' THEN '/' || COALESCE($3, sub_path) ELSE '' END
ELSE full_path
END,
enabled = COALESCE($5, enabled),
is_default = COALESCE($6, is_default),
updated_at = NOW()
WHERE id = $7
RETURNING id, name, base_path, sub_path, full_path, output_path, enabled, is_default,
created_at::text, updated_at::text"
)
.bind(req.name)
.bind(req.base_path)
.bind(req.sub_path)
.bind(req.output_path)
.bind(req.enabled)
.bind(req.is_default)
.bind(id)
.fetch_one(pool)
.await
.map_err(|e| {
error!("[upload_paths] update failed: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
info!("[upload_paths] updated: {} -> {}", path.name, path.full_path);
Ok(Json(path))
}
/// DELETE /api/v1/admin/upload-paths/:id
async fn delete_upload_path(
State(state): State<AppState>,
Path(id): Path<i32>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let pool = get_pool(&state);
let is_default: bool = sqlx::query_scalar(
"SELECT is_default FROM upload_paths WHERE id = $1"
)
.bind(id)
.fetch_optional(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.unwrap_or(false);
if is_default {
return Err(StatusCode::BAD_REQUEST);
}
let file_count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM videos WHERE folder_id = $1"
)
.bind(id)
.fetch_one(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if file_count > 0 {
return Err(StatusCode::BAD_REQUEST);
}
sqlx::query("DELETE FROM upload_paths WHERE id = $1")
.bind(id)
.execute(pool)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
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
}
})))
}
+35 -7
View File
@@ -64,6 +64,7 @@ pub struct SceneSearchResponse {
pub total: usize,
pub page: usize,
pub page_size: usize,
pub has_more: bool,
}
#[derive(Debug, Serialize)]
@@ -174,12 +175,17 @@ pub async fn search_vlm_scenes(
Json(ErrorResponse::new(format!("Embedding service unavailable: {}", e)))
})?;
// 2. Vector search in Qdrant
// 2. Vector search in Qdrant — request enough results for the requested page
// page=1: skip 0, take page_size
// page=2: skip page_size, take page_size
// We request page * page_size * 2 (buffer for filtered-out orphaned points)
let skip_count = (req.page.saturating_sub(1)) * req.page_size;
let qdrant_limit = req.page * req.page_size * 2;
let search_results = qdrant
.search_scenes(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 2,
qdrant_limit,
)
.await
.map_err(|e| {
@@ -187,8 +193,9 @@ pub async fn search_vlm_scenes(
Json(ErrorResponse::new(format!("Vector search failed: {}", e)))
})?;
// 3. Post-filter and build results
// 3. Post-filter, skip already-returned results, and build results for this page
let mut results = Vec::new();
let mut valid_index = 0usize; // count of valid (non-skipped) results seen so far
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
@@ -339,6 +346,13 @@ pub async fn search_vlm_scenes(
continue;
}
// Pagination: skip results from previous pages
if valid_index < skip_count {
valid_index += 1;
continue;
}
valid_index += 1;
results.push(SceneSearchResult {
file_uuid: file_uuid.clone(),
file_name,
@@ -357,19 +371,22 @@ pub async fn search_vlm_scenes(
source: "vector".to_string(),
});
// Stop if we have enough results
// Stop if we have enough results for this page
if results.len() >= req.page_size {
break;
}
}
let total = results.len();
// total = 總有效結果數(含本頁),has_more = 是否有下一頁
let has_more = valid_index > skip_count + results.len();
let total = valid_index; // 所有通過篩選的有效結果總數
Ok(Json(SceneSearchResponse {
results,
total,
page: req.page,
page_size: req.page_size,
has_more,
}))
}
@@ -421,11 +438,14 @@ pub async fn search_vlm_traces(
})?;
// 2. Vector search in Qdrant main collection (chunk_type = vlm_summary)
// Request enough results for pagination
let skip_count = (req.page.saturating_sub(1)) * req.page_size;
let qdrant_limit = req.page * req.page_size * 3;
let search_results = qdrant
.search_trace_vlm(
&query_embedding,
req.file_uuid.as_deref(),
req.page_size * 3,
qdrant_limit,
)
.await
.map_err(|e| {
@@ -433,8 +453,9 @@ pub async fn search_vlm_traces(
Json(ErrorResponse::new(format!("Vector search failed: {}", e)))
})?;
// 3. Post-filter + enrich from trace_profiles
// 3. Post-filter + enrich from trace_profiles (with pagination)
let mut results = Vec::new();
let mut valid_index = 0usize;
for point in search_results {
let payload = match point.get("payload") {
Some(p) => p,
@@ -561,6 +582,13 @@ pub async fn search_vlm_traces(
continue;
}
// Pagination: skip results from previous pages
if valid_index < skip_count {
valid_index += 1;
continue;
}
valid_index += 1;
let fps = fps.unwrap_or(24.0);
let start_time = start_frame.map(|f| f as f64 / fps);
let end_time = end_frame.map(|f| f as f64 / fps);
+267
View File
@@ -0,0 +1,267 @@
//! Standalone embedding rebuild tool.
//!
//! Rebuilds text/scene embeddings with the current embedding model.
//! Uses the Rust `Embedder` (same code path as production).
//!
//! Usage:
//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1
//! cargo run --release --bin rebuild_embeddings -- --collection _scenes
//! cargo run --release --bin rebuild_embeddings -- --collection all
//! cargo run --release --bin rebuild_embeddings -- --collection momentry_rule1 --uuid abc123
use anyhow::{Context, Result};
use dotenv::dotenv;
use momentry_core::core::config;
use momentry_core::core::db::{schema, QdrantDb, VectorPayload};
use momentry_core::core::embedding::Embedder;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[derive(clap::Parser)]
#[command(name = "rebuild_embeddings", about = "Rebuild embeddings with current model")]
struct Args {
/// Collection to rebuild: momentry_rule1, _scenes, or all
#[arg(short, long, default_value = "all")]
collection: String,
/// Optional file UUID to rebuild only one video
#[arg(short, long)]
uuid: Option<String>,
/// Skip PG embedding column update (only update Qdrant)
#[arg(long)]
skip_pg: bool,
}
async fn rebuild_text_chunks(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>, skip_pg: bool) -> Result<(usize, usize)> {
let chunk_table = schema::table_name("chunk");
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
println!(" Cleared points for file_uuid={}", uuid);
} else {
let _ = qdrant.delete_points_by_filter("momentry_rule1", serde_json::json!({})).await;
println!(" Cleared all points in momentry_rule1");
}
// Query chunks
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' AND file_uuid = $1 \
ORDER BY id",
chunk_table
)
} else {
format!(
"SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time, chunk_type, file_uuid \
FROM {} WHERE chunk_type = 'sentence' AND text_content IS NOT NULL AND text_content != '' \
ORDER BY id",
chunk_table
)
};
let rows: Vec<(String, String, i64, i64, f64, f64, String, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
println!(" Found {} sentence chunks to rebuild", total);
for (i, (chunk_id, text, start_frame, end_frame, start_time, end_time, chunk_type, fuuid)) in rows.iter().enumerate() {
if text.is_empty() {
continue;
}
match embedder.embed_document(text).await {
Ok(vector) => {
// Update PG embedding column if not skipped
if !skip_pg {
let vector_json = serde_json::to_string(&vector).unwrap_or_default();
let _ = sqlx::query(&format!(
"UPDATE {} SET embedding = $1::vector WHERE chunk_id = $2 AND file_uuid = $3",
chunk_table
))
.bind(&vector_json)
.bind(chunk_id)
.bind(fuuid)
.execute(db.pool())
.await;
}
// Upsert to Qdrant
let payload = VectorPayload {
file_uuid: fuuid.clone(),
chunk_id: chunk_id.clone(),
chunk_type: chunk_type.clone(),
start_frame: *start_frame,
end_frame: *end_frame,
start_time: *start_time,
end_time: *end_time,
text: Some(text.clone()),
};
if qdrant.upsert_vector(chunk_id, &vector, payload).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
if (i + 1) % 50 == 0 || i + 1 == total {
println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail);
}
}
Err(e) => {
eprintln!(" ✗ Failed to embed {}: {}", chunk_id, e);
fail += 1;
}
}
}
Ok((ok, fail))
}
async fn rebuild_scenes(db: &momentry_core::core::db::postgres_db::PostgresDb, qdrant: &QdrantDb, embedder: &Embedder, file_uuid: Option<&str>) -> Result<(usize, usize)> {
let scenes_table = schema::table_name("scenes");
let mut ok = 0usize;
let mut fail = 0usize;
// Clear existing scene points
if let Some(uuid) = file_uuid {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
})).await;
println!(" Cleared scene points for file_uuid={}", uuid);
} else {
let _ = qdrant.delete_points_by_filter("_scenes", serde_json::json!({})).await;
println!(" Cleared all points in _scenes");
}
// Query scenes with VLM descriptions
let query = if let Some(uuid) = file_uuid {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE file_uuid = $1 AND (vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL) \
ORDER BY id",
scenes_table
)
} else {
format!(
"SELECT id, file_uuid, scene_index, timestamp_sec, frame_number, \
COALESCE(vlm_description_localized, vlm_description) as description \
FROM {} WHERE vlm_description_localized IS NOT NULL OR vlm_description IS NOT NULL \
ORDER BY id",
scenes_table
)
};
let rows: Vec<(i64, String, i32, f64, i64, String)> = if file_uuid.is_some() {
sqlx::query_as(&query)
.bind(file_uuid.unwrap())
.fetch_all(db.pool())
.await
.unwrap_or_default()
} else {
sqlx::query_as(&query)
.fetch_all(db.pool())
.await
.unwrap_or_default()
};
let total = rows.len();
println!(" Found {} scenes to rebuild", total);
for (i, (scene_id, fuuid, scene_index, timestamp_sec, frame_number, description)) in rows.iter().enumerate() {
match embedder.embed_document(description).await {
Ok(vector) => {
let point_id_str = format!("{}_s{}", fuuid, scene_index);
let point_id = {
let mut hasher = DefaultHasher::new();
point_id_str.hash(&mut hasher);
hasher.finish()
};
if qdrant.upsert_scene_embedding(
point_id,
&vector,
fuuid,
*scene_index as usize,
*timestamp_sec,
*frame_number as u32,
description,
None,
&[],
&[],
).await.is_ok() {
ok += 1;
} else {
fail += 1;
}
if (i + 1) % 50 == 0 || i + 1 == total {
println!(" Progress: {}/{} (ok={}, fail={})", i + 1, total, ok, fail);
}
}
Err(e) => {
eprintln!(" ✗ Failed to embed scene {}: {}", scene_id, e);
fail += 1;
}
}
}
Ok((ok, fail))
}
#[tokio::main]
async fn main() -> Result<()> {
use clap::Parser;
dotenv().ok();
let args = Args::parse();
println!("═══ Embedding Rebuild Tool ═══");
println!("Collection: {}", args.collection);
if let Some(uuid) = &args.uuid {
println!("File UUID: {}", uuid);
}
println!("Skip PG update: {}", args.skip_pg);
println!();
let db = momentry_core::core::db::postgres_db::PostgresDb::new(&config::DATABASE_URL).await
.context("Failed to connect to PostgreSQL")?;
let qdrant = QdrantDb::new();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let t0 = std::time::Instant::now();
if args.collection == "all" || args.collection == "momentry_rule1" {
println!("── Rebuilding momentry_rule1 (text chunks) ──");
let (ok, fail) = rebuild_text_chunks(&db, &qdrant, &embedder, args.uuid.as_deref(), args.skip_pg).await?;
println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail);
}
if args.collection == "all" || args.collection == "_scenes" {
println!("── Rebuilding _scenes (scene embeddings) ──");
let (ok, fail) = rebuild_scenes(&db, &qdrant, &embedder, args.uuid.as_deref()).await?;
println!(" Result: {}/{} succeeded, {} failed\n", ok, ok + fail, fail);
}
let elapsed = t0.elapsed();
println!("═══ Total time: {:.1}s ═══", elapsed.as_secs_f64());
Ok(())
}
+141
View File
@@ -0,0 +1,141 @@
//! Embedding 真實測試 — 用 Rust Embedder(與 production 相同程式碼路徑)
//!
//! 執行: cargo run --release --bin test_embedding_rust
use momentry_core::core::embedding::Embedder;
fn cosine_sim(a: &[f32], b: &[f32]) -> f32 {
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if na > 0.0 && nb > 0.0 { dot / (na * nb) } else { 0.0 }
}
#[tokio::main]
async fn main() {
let mut passed = 0;
let mut failed = 0;
macro_rules! check {
($name:expr, $ok:expr, $detail:expr) => {
if $ok {
passed += 1;
println!(" ✓ {} — {}", $name, $detail);
} else {
failed += 1;
println!(" ✗ {} — {}", $name, $detail);
}
};
}
println!("═══ Rust Embedder 真實測試(production code path)═══");
println!();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
let url = std::env::var("MOMENTRY_EMBED_URL")
.unwrap_or_else(|_| "http://localhost:11436".to_string());
println!(" Embed URL: {}", url);
println!(" Model: embeddinggemma-300m");
println!();
// ── [1] embed_text(無 prefix)──
println!("[1] embed_text(無 prefix)");
match embedder.embed_text("hello world").await {
Ok(emb) => {
check!("回傳向量", !emb.is_empty(), format!("dim={}", emb.len()));
check!("次元 768", emb.len() == 768, format!("dim={}", emb.len()));
check!("值非全零", emb.iter().any(|x| x.abs() > 0.001), "有實際值");
}
Err(e) => {
check!("embed_text", false, format!("錯誤: {}", e));
}
}
// ── [2] embed_document(search_document prefix — 用於入庫)──
println!("[2] embed_document(search_document prefix)");
match embedder.embed_document("A man is playing guitar on stage").await {
Ok(emb) => {
check!("document embedding", emb.len() == 768, format!("dim={}", emb.len()));
}
Err(e) => check!("document embedding", false, format!("錯誤: {}", e)),
}
// ── [3] embed_query(search_query prefix — 用於搜尋)──
println!("[3] embed_query(search_query prefix)");
match embedder.embed_query("person playing guitar").await {
Ok(emb) => {
check!("query embedding", emb.len() == 768, format!("dim={}", emb.len()));
}
Err(e) => check!("query embedding", false, format!("錯誤: {}", e)),
}
// ── [4] 語義相似度(document vs query — 搜尋場景)──
println!("[4] 語義相似度(document vs query)");
let doc_guitar = embedder.embed_document("A man is playing guitar on stage in front of a large audience").await;
let doc_cooking = embedder.embed_document("Someone is cooking pasta in the kitchen with fresh ingredients").await;
let query_guitar = embedder.embed_query("guitar performance").await;
let query_cooking = embedder.embed_query("cooking food").await;
if let (Ok(dg), Ok(dc), Ok(qg), Ok(qc)) = (doc_guitar, doc_cooking, query_guitar, query_cooking) {
let sim_match = cosine_sim(&dg, &qg); // 吉他 doc vs 吉他 query
let sim_cross = cosine_sim(&dg, &qc); // 吉他 doc vs 烹飪 query
let sim_match2 = cosine_sim(&dc, &qc); // 烹飪 doc vs 烹飪 query
check!("相關搜尋高相似度(吉他)", sim_match > 0.5, format!("sim={:.3}", sim_match));
check!("相關搜尋高相似度(烹飪)", sim_match2 > 0.5, format!("sim={:.3}", sim_match2));
check!("相關 > 不相關", sim_match > sim_cross + 0.05, format!("{:.3} > {:.3}", sim_match, sim_cross));
} else {
check!("語義相似度", false, "embedding 呼叫失敗".to_string());
}
// ── [5] 一致性 ──
println!("[5] 一致性");
let e1 = embedder.embed_text("The quick brown fox jumps over the lazy dog").await;
let e2 = embedder.embed_text("The quick brown fox jumps over the lazy dog").await;
if let (Ok(a), Ok(b)) = (e1, e2) {
let sim = cosine_sim(&a, &b);
check!("同句重複一致", sim > 0.999, format!("sim={:.6}", sim));
} else {
check!("同句重複一致", false, "呼叫失敗".to_string());
}
// ── [6] 中文 ──
println!("[6] 中文");
let zh_doc = embedder.embed_document("這部影片展示了一個人在廚房烹飪美食").await;
let zh_query = embedder.embed_query("有人在廚房做菜").await;
let en_query = embedder.embed_query("stock market crash").await;
if let (Ok(zd), Ok(zq), Ok(eq)) = (zh_doc, zh_query, en_query) {
let sim_same = cosine_sim(&zd, &zq);
let sim_diff = cosine_sim(&zd, &eq);
check!("中文 doc vs 中文 query", sim_same > 0.4, format!("sim={:.3}", sim_same));
check!("中文相關 > 不相關", sim_same > sim_diff + 0.05, format!("{:.3} > {:.3}", sim_same, sim_diff));
} else {
check!("中文", false, "呼叫失敗".to_string());
}
// ── [7] 效能(連續 10 次)──
println!("[7] 效能");
let start = std::time::Instant::now();
let mut all_ok = true;
for i in 0..10 {
if embedder.embed_text(&format!("Performance test sentence number {}", i)).await.is_err() {
all_ok = false;
}
}
let elapsed = start.elapsed().as_millis();
check!("10 次連續 < 5 秒", all_ok && elapsed < 5000, format!("{}ms", elapsed));
// ── [8] dimension() ──
println!("[8] dimension()");
check!("dimension() = 768", embedder.dimension() == 768, format!("{}", embedder.dimension()));
println!();
println!("═══ 結果 ═══");
println!(" 通過: {}/{}", passed, passed + failed);
if failed > 0 {
println!(" 失敗: {}", failed);
std::process::exit(1);
} else {
println!(" 全部通過 ✓");
}
}
+97 -15
View File
@@ -94,6 +94,25 @@ pub struct LlmConfig {
pub model: String,
#[serde(default)]
pub timeout: u32,
/// Deprecated single fallback (kept for backward compat; merged into `fallbacks`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fallback_url: Option<String>,
/// Ordered backup endpoints. Each may be a local instance
/// (127.0.0.1:8080/8082) or a remote machine's llama-server
/// (e.g. http://192.168.110.201:8080/... — pooling off-box compute).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fallbacks: Vec<String>,
/// Load strategy across primary + fallbacks:
/// "priority" (default, failover only) or "round_robin"
/// (each request rotates to the next instance — pools all available
/// compute for higher aggregate throughput).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strategy: Option<String>,
/// Instance on/off switch for routing. When disabled, requests are never
/// routed to this instance (neither as primary nor as fallback).
/// None = enabled (default true).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -267,6 +286,14 @@ fn default_processor_timeout_secs() -> u32 {
.unwrap_or(3600)
}
fn default_preferred_language() -> String {
"en".to_string()
}
fn default_library_sort() -> String {
"name_asc".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AdminSettings {
#[serde(default = "default_session_timeout")]
@@ -279,6 +306,8 @@ pub struct AdminSettings {
pub system_stats_refresh_sec: u32,
#[serde(default = "default_preferred_language")]
pub preferred_language: String,
#[serde(default = "default_library_sort")]
pub library_default_sort: String,
}
/// Get FS VLM enabled setting from admin_config
@@ -381,7 +410,7 @@ fn default_system_stats_refresh_sec() -> u32 {
.unwrap_or(5)
}
fn default_preferred_language() -> String {
fn default_server_preferred_language() -> String {
std::env::var("MOMENTRY_PREFERRED_LANGUAGE")
.unwrap_or_else(|_| "zh-TW".to_string())
}
@@ -730,25 +759,78 @@ pub async fn get_server() -> ServerConfig {
ADMIN_CONFIG.get_server().await
}
/// Read the `paths` block from admin_config.json synchronously (override source).
/// Empty or missing fields mean "not defined here" and fall through to env/default.
fn admin_paths_override() -> PathsConfig {
let mut out = PathsConfig {
output_dir: String::new(),
backup_dir: String::new(),
scripts_dir: String::new(),
cli_dir: String::new(),
python_path: String::new(),
ffmpeg_path: String::new(),
};
let path = get_default_config_path();
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(p) = v.get("paths").and_then(|p| p.as_object()) {
let grab = |key: &str| -> String {
p.get(key)
.and_then(|s| s.as_str())
.map(|s| s.trim().to_string())
.unwrap_or_default()
};
out.output_dir = grab("output_dir");
out.backup_dir = grab("backup_dir");
out.scripts_dir = grab("scripts_dir");
out.cli_dir = grab("cli_dir");
out.python_path = grab("python_path");
out.ffmpeg_path = grab("ffmpeg_path");
}
}
}
out
}
/// Resolve once: admin_config.json (non-empty) > env var > hardcoded default.
fn or_default(value: String, fallback: impl FnOnce() -> String) -> String {
if value.is_empty() {
fallback()
} else {
value
}
}
pub fn get_paths_sync() -> PathsConfig {
let ov = admin_paths_override();
PathsConfig {
// Must NOT read config::OUTPUT_DIR here: this function *is* the
// initializer of that lazy static, so reading it re-enters
// once_cell::sync::Lazy::force and deadlocks the calling thread.
output_dir: default_output_dir(),
backup_dir: std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/backup")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/backup".to_string())
}),
scripts_dir: crate::core::path_utils::scripts_dir().to_string_lossy().to_string(),
cli_dir: crate::core::path_utils::cli_dir().to_string_lossy().to_string(),
python_path: std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string()),
ffmpeg_path: std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string()),
output_dir: or_default(ov.output_dir.clone(), default_output_dir),
backup_dir: or_default(ov.backup_dir.clone(), || {
std::env::var("MOMENTRY_BACKUP_DIR")
.unwrap_or_else(|_| {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("var/backup")))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "var/backup".to_string())
})
}),
scripts_dir: or_default(ov.scripts_dir.clone(), || {
crate::core::path_utils::scripts_dir().to_string_lossy().to_string()
}),
cli_dir: or_default(ov.cli_dir.clone(), || {
crate::core::path_utils::cli_dir().to_string_lossy().to_string()
}),
python_path: or_default(ov.python_path, || {
std::env::var("MOMENTRY_PYTHON_PATH")
.unwrap_or_else(|_| "/opt/homebrew/bin/python3.11".to_string())
}),
ffmpeg_path: or_default(ov.ffmpeg_path, || {
std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string())
}),
}
}
+11
View File
@@ -1707,6 +1707,10 @@ pub async fn exec_scene_search(
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_description_localized = payload
.get("vlm_description_localized")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
@@ -1729,6 +1733,7 @@ pub async fn exec_scene_search(
.unwrap_or_default();
let description_preview = vlm_description.chars().take(150).collect::<String>();
let localized_preview = vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>());
cards.push(serde_json::json!({
"card_type": "scene",
@@ -1743,6 +1748,7 @@ pub async fn exec_scene_search(
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": description_preview,
"vlm_description_localized": localized_preview,
"source": "vlm_scene"
}));
}
@@ -1847,6 +1853,10 @@ pub async fn exec_vlm_search(
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let vlm_description_localized = payload
.get("vlm_description_localized")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let vlm_tags: Vec<String> = payload
.get("vlm_tags")
.and_then(|v| v.as_array())
@@ -1882,6 +1892,7 @@ pub async fn exec_vlm_search(
"score": score,
"vlm_tags": vlm_tags,
"vlm_description": vlm_description.chars().take(150).collect::<String>(),
"vlm_description_localized": vlm_description_localized.as_deref().map(|s| s.chars().take(150).collect::<String>()),
"source": "vlm_scene"
}));
}
+82
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
@@ -219,6 +267,40 @@ pub fn get_scene_vlm_config() -> (bool, u32, usize, bool, usize) {
pub static OUTPUT_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_output_dir());
/// Get the per-library output directory for a file based on its upload_path
pub async fn get_output_dir_for_file(file_uuid: &str, pool: &sqlx::PgPool) -> String {
let videos_table = crate::core::db::schema::table_name("videos");
let upload_paths_table = crate::core::db::schema::table_name("upload_paths");
let result: Option<(Option<String>,)> = sqlx::query_as(
&format!(
"SELECT up.output_path FROM {} v
LEFT JOIN {} up ON v.file_path LIKE up.full_path || '%%'
WHERE v.file_uuid = $1
AND up.output_path IS NOT NULL AND up.output_path != ''
LIMIT 1",
videos_table, upload_paths_table
)
)
.bind(file_uuid)
.fetch_optional(pool)
.await
.ok()
.flatten();
if let Some((Some(output_path),)) = result {
return output_path;
}
OUTPUT_DIR.to_string()
}
pub fn get_output_dir_for_file_sync(_file_uuid: &str, _pool: &sqlx::PgPool) -> String {
// Sync context cannot easily query DB - use global OUTPUT_DIR
// Use async version `get_output_dir_for_file()` for proper per-library paths
OUTPUT_DIR.to_string()
}
pub static BACKUP_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_backup_dir());
pub static SCRIPTS_DIR: Lazy<String> = Lazy::new(|| crate::core::admin_config::get_scripts_dir());
+68 -3
View File
@@ -844,6 +844,19 @@ pub struct ApiKeyRecord {
pub updated_at: chrono::DateTime<chrono::Utc>,
}
/// One currently-valid login session (for the Admin active-logins view).
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct ActiveSessionRow {
pub session_id: String,
pub username: Option<String>,
pub role: Option<String>,
pub created_at: chrono::DateTime<chrono::Utc>,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub ip_address: String,
pub user_agent: String,
pub source: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyStats {
pub total_keys: i64,
@@ -2382,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
@@ -3290,7 +3307,49 @@ impl PostgresDb {
Ok(())
}
pub async fn get_session_by_id(
pub async fn create_session_with_meta(
&self,
session_id: &str,
user_id: i32,
api_key_id: &str,
ttl_hours: i64,
ip_address: &str,
user_agent: &str,
source: &str,
) -> Result<()> {
let table = schema::table_name("sessions");
let interval = format!("{} hours", ttl_hours);
sqlx::query(
&format!("INSERT INTO {} (session_id, user_id, api_key_id, expires_at, ip_address, user_agent, source) VALUES ($1, $2, $3, CURRENT_TIMESTAMP + $4::interval, $5, $6, $7)", table)
)
.bind(session_id)
.bind(user_id)
.bind(api_key_id)
.bind(&interval)
.bind(ip_address)
.bind(user_agent)
.bind(source)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn get_active_sessions(&self) -> Result<Vec<ActiveSessionRow>> {
let table = schema::table_name("sessions");
let rows = sqlx::query_as::<_, ActiveSessionRow>(
&format!(
"SELECT s.session_id, u.username, u.role, s.created_at, s.expires_at, COALESCE(s.ip_address, '') AS ip_address, COALESCE(s.user_agent, '') AS user_agent, COALESCE(s.source, '') AS source FROM {} s LEFT JOIN {} u ON u.id = s.user_id WHERE s.expires_at > CURRENT_TIMESTAMP ORDER BY s.created_at DESC",
table,
schema::table_name("users")
)
)
.fetch_all(&self.pool)
.await?;
Ok(rows)
}
pub async fn get_session_by_id(
&self,
session_id: &str,
) -> Result<Option<(i32, i32, String, chrono::DateTime<chrono::Utc>)>> {
@@ -3921,8 +3980,14 @@ impl PostgresDb {
"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)
+20 -3
View File
@@ -129,7 +129,12 @@ impl QdrantDb {
return Ok(());
}
let create_url = format!("{}/collections", self.base_url);
// Qdrant's create-collection API is `PUT /collections/{name}`.
// The previous code POSTed to `/collections` without the collection
// name in the URL and never checked the response status, so creation
// silently no-op'd and every subsequent upsert failed with 404 on
// clean installs (where no legacy collection exists yet).
let create_url = format!("{}/collections/{}", self.base_url, collection);
let body = serde_json::json!({
"vectors": {
"size": vector_dim,
@@ -137,8 +142,9 @@ impl QdrantDb {
}
});
self.client
.post(&create_url)
let response = self
.client
.put(&create_url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
.json(&body)
@@ -149,6 +155,17 @@ impl QdrantDb {
collection
))?;
let status = response.status();
if !status.is_success() {
let response_text = response.text().await.unwrap_or_default();
anyhow::bail!(
"Failed to create Qdrant collection {}: {} - {}",
collection,
status,
response_text
);
}
tracing::info!(
"Created Qdrant collection: {} (dim={})",
collection,
+205
View File
@@ -190,3 +190,208 @@ pub async fn ensure_face_track_node(
.await?;
Ok(res.rows_affected())
}
// ─── Face Groups (first-class group entity) ──────────────────────────────────
//
// A face group is now a real row in `face_groups`. Trace membership is stored
// on `trace_profiles.group_id`. The trace name (trace_profiles.name) remains
// only as a per-trace display caption; it is no longer the grouping source of
// truth. Renaming a group = one UPDATE on face_groups. Moving a trace = one
// UPDATE on trace_profiles.
//
// All helpers below are idempotent and safe to call on every request.
// ─────────────────────────────────────────────────────────────────────────────
pub async fn ensure_face_groups_schema(pool: &PgPool) -> anyhow::Result<()> {
let tp = table_name("trace_profiles");
let fg = table_name("face_groups");
sqlx::query(
"CREATE TABLE IF NOT EXISTS face_groups (\
id BIGSERIAL PRIMARY KEY,\
file_uuid VARCHAR(255) NOT NULL,\
name TEXT NOT NULL,\
origin_cluster_id VARCHAR(255),\
sort_index INT NOT NULL DEFAULT 0,\
properties JSONB NOT NULL DEFAULT '{}'::jsonb,\
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\
UNIQUE (file_uuid, name))",
)
.execute(pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS idx_face_groups_file ON face_groups(file_uuid)")
.execute(pool)
.await?;
sqlx::query(&format!(
"ALTER TABLE {tp} ADD COLUMN IF NOT EXISTS group_id BIGINT REFERENCES face_groups(id)"
))
.execute(pool)
.await?;
// Backfill: every named trace (non-empty, not auto trace labels) defines
// one group row; its traces attach to that group.
{
let sql = format!(
"INSERT INTO {fg} (file_uuid, name) SELECT file_uuid, name FROM {tp} WHERE name IS NOT NULL AND name <> '' AND NOT (name LIKE 'Face Trace %') AND NOT (name LIKE 'Trace %') AND NOT (name LIKE 'Person_%') GROUP BY file_uuid, name ON CONFLICT (file_uuid, name) DO NOTHING");
sqlx::query(&sql).execute(pool).await?;
}
{
let sql = format!(
"UPDATE {tp} SET group_id = g.id FROM {fg} g WHERE g.file_uuid = {tp}.file_uuid AND g.name = {tp}.name AND {tp}.group_id IS NULL");
sqlx::query(&sql).execute(pool).await?;
}
Ok(())
}
/// Get or create the group with the given name for a file. Returns group id.
pub async fn get_or_create_group(
pool: &PgPool,
file_uuid: &str,
name: &str,
) -> anyhow::Result<i64> {
let fg = table_name("face_groups");
let row: (i64,) = sqlx::query_as(&format!(
"INSERT INTO {fg} (file_uuid, name) VALUES ($1, $2) ON CONFLICT (file_uuid, name) DO UPDATE SET updated_at = NOW(), properties = {fg}.properties - 'dissolved' RETURNING id"
))
.bind(file_uuid)
.bind(name)
.fetch_one(pool)
.await?;
Ok(row.0)
}
/// Rename one group row (single write). Bumps updated_at.
pub async fn rename_group(pool: &PgPool, group_id: i64, new_name: &str) -> anyhow::Result<()> {
let fg = table_name("face_groups");
sqlx::query(&format!(
"UPDATE {fg} SET name = $1, updated_at = NOW() WHERE id = $2"
))
.bind(new_name)
.bind(group_id)
.execute(pool)
.await?;
Ok(())
}
/// Delete the group rows matching names (used by merge/ungroup cleanup).
pub async fn delete_groups_by_names(
pool: &PgPool,
file_uuid: &str,
names: &[String],
) -> anyhow::Result<u64> {
if names.is_empty() {
return Ok(0);
}
let fg = table_name("face_groups");
let res = sqlx::query(&format!(
"DELETE FROM {fg} WHERE file_uuid = $1 AND name = ANY($2)"
))
.bind(file_uuid)
.bind(names)
.execute(pool)
.await?;
Ok(res.rows_affected())
}
// ─── Face Groups JSON Persistence ─────────────────────────────────────────────
//
// Saves face group state to {output_dir}/{file_uuid}.face_groups.json
// This serves as the persistent source of truth for face groups, independent
// of face_cluster.json (which is algorithm output) and DB (which may be reset).
// ──────────────────────────────────────────────────────────────────────────────
pub async fn save_face_groups_json(pool: &PgPool, file_uuid: &str) -> anyhow::Result<()> {
use chrono::Utc;
use serde_json::{json, Value};
let fg = table_name("face_groups");
let tp = table_name("trace_profiles");
let v = table_name("videos");
// Get file_name from videos table
let file_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_name FROM {v} WHERE file_uuid = $1"
))
.bind(file_uuid)
.fetch_optional(pool)
.await?;
// Get all groups with their trace members
let groups: Vec<(i64, String, Option<String>, Vec<i32>)> = sqlx::query_as(&format!(
"SELECT g.id, g.name, g.origin_cluster_id, \
COALESCE(array_agg(tp.trace_id ORDER BY tp.trace_id) FILTER (WHERE tp.trace_id IS NOT NULL), ARRAY[]::int[]) \
FROM {fg} g \
LEFT JOIN {tp} tp ON tp.group_id = g.id \
WHERE g.file_uuid = $1 \
GROUP BY g.id, g.name, g.origin_cluster_id \
ORDER BY g.sort_index, g.id"
))
.bind(file_uuid)
.fetch_all(pool)
.await?;
// Build groups array
let mut groups_json = Vec::new();
let mut total_traces = 0i64;
for (gid, name, origin_cid, trace_ids) in &groups {
let trace_count = trace_ids.len() as i64;
total_traces += trace_count;
// Find representative trace (first one for now)
let rep_trace = trace_ids.first().copied().unwrap_or(0);
groups_json.push(json!({
"group_id": gid,
"name": name,
"origin_cluster_id": origin_cid,
"trace_ids": trace_ids,
"trace_count": trace_count,
"representative_trace": rep_trace,
"metadata": json!({})
}));
}
let output = json!({
"schema_version": "1.0",
"file_uuid": file_uuid,
"file_name": file_name.unwrap_or_default(),
"updated_at": Utc::now().to_rfc3339(),
"total_groups": groups.len(),
"total_traces": total_traces,
"groups": groups_json
});
// Save to output directory
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let path = std::path::Path::new(output_dir)
.join(format!("{}.face_groups.json", file_uuid));
let json_str = serde_json::to_string_pretty(&output)?;
std::fs::write(&path, json_str)?;
tracing::info!(
"[FaceGroupsJSON] Saved {} groups, {} traces to {}",
groups.len(),
total_traces,
path.display()
);
// Mirror the same data into the workspace SQLite (equivalent backup).
if let Ok(ws) = crate::core::db::workspace_sqlite::WorkspaceDb::open(file_uuid).await {
if let Err(e) = ws
.sync_face_groups(&groups)
.await
{
tracing::warn!("[FaceGroupsJSON] SQLite mirror sync failed: {}", e);
}
}
Ok(())
}
+70
View File
@@ -149,6 +149,27 @@ impl WorkspaceDb {
.execute(&self.pool)
.await?;
// Face groups backup — mirrors face_groups.json (V1.0 persistence
// design). Keeps group name + trace list per file in SQLite so the
// JSON file and SQLite are equivalent backups of each other.
sqlx::query(
"CREATE TABLE IF NOT EXISTS face_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
file_uuid TEXT NOT NULL,
group_id INTEGER,
name TEXT NOT NULL,
origin_cluster_id TEXT,
trace_ids TEXT NOT NULL DEFAULT '[]',
trace_count INTEGER NOT NULL DEFAULT 0,
representative_trace INTEGER,
metadata TEXT DEFAULT '{}',
updated_at TEXT DEFAULT (datetime('now')),
UNIQUE(file_uuid, name)
)",
)
.execute(&self.pool)
.await?;
Ok(())
}
@@ -167,6 +188,55 @@ impl WorkspaceDb {
workspace_path(file_uuid).exists()
}
// ── Face Groups (JSON backup mirror) ──
/// Mirror face_groups.json content into this workspace SQLite so the two
/// are equivalent backups. Replaces all rows for the file (full sync).
pub async fn sync_face_groups(
&self,
groups: &[(i64, String, Option<String>, Vec<i32>)],
) -> Result<()> {
// Replace-all sync: delete then insert keeps the mirror exact.
sqlx::query("DELETE FROM face_groups WHERE file_uuid = $1")
.bind(&self.file_uuid)
.execute(&self.pool)
.await?;
for (gid, name, origin_cid, trace_ids) in groups {
let trace_ids_json = serde_json::to_string(trace_ids)
.unwrap_or_else(|_| "[]".to_string());
let rep = trace_ids.first().copied();
sqlx::query(
"INSERT INTO face_groups \
(file_uuid, group_id, name, origin_cluster_id, trace_ids, trace_count, representative_trace) \
VALUES ($1, $2, $3, $4, $5, $6, $7) \
ON CONFLICT(file_uuid, name) DO UPDATE SET \
group_id = excluded.group_id, \
origin_cluster_id = excluded.origin_cluster_id, \
trace_ids = excluded.trace_ids, \
trace_count = excluded.trace_count, \
representative_trace = excluded.representative_trace, \
updated_at = datetime('now')",
)
.bind(&self.file_uuid)
.bind(gid)
.bind(name)
.bind(origin_cid)
.bind(&trace_ids_json)
.bind(trace_ids.len() as i64)
.bind(rep)
.execute(&self.pool)
.await?;
}
tracing::info!(
"[WorkspaceSQLite] Synced {} face_groups rows for {}",
groups.len(),
self.file_uuid
);
Ok(())
}
// ── Processor Results ──
pub async fn upsert_processor_result(
+12
View File
@@ -12,6 +12,18 @@ pub enum MemoryStatus {
High, // > 41 GB (must decrease concurrency)
}
/// Minimum free memory (GB) needed to keep a second llama-server instance warm.
const DUAL_INSTANCE_MIN_FREE_GB: f64 = 12.0;
/// True when free memory is too low to run two llama-server instances at once.
/// Used by LLM routing to collapse chat/vlm/summary onto a single instance.
pub fn memory_constrained() -> bool {
let mut sys = System::new_all();
sys.refresh_memory();
let available_gb = sys.available_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
available_gb < DUAL_INSTANCE_MIN_FREE_GB
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VlmStatus {
Available, // < 5s (can increase concurrency)
+435
View File
@@ -0,0 +1,435 @@
/// File export/import for portable package (.momentry.tar.gz)
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
// ─── Manifest Structures ─────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
pub struct ExportManifest {
pub version: String,
#[serde(rename = "type")]
pub export_type: String,
pub exported_at: String,
pub momentry_version: String,
pub file: FileInfo,
pub data_sources: DataSources,
pub processors: HashMap<String, ProcessorInfo>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub uuid: String,
pub file_name: String,
pub file_path: String,
pub file_size: u64,
pub library: String,
pub status: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DataSources {
pub postgresql: PostgresqlInfo,
pub qdrant: QdrantInfo,
pub sqlite: SqliteInfo,
pub redis: RedisInfo,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PostgresqlInfo {
pub tables: Vec<String>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct QdrantInfo {
pub collection: String,
pub face_vectors: usize,
pub text_vectors: usize,
pub speaker_vectors: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SqliteInfo {
pub file: String,
pub tables: Vec<String>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RedisInfo {
pub keys_count: usize,
pub patterns: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ProcessorInfo {
pub status: String,
pub file: String,
}
// ─── Export Function ─────────────────────────────────────────────────────────
pub async fn export_file(
pool: &sqlx::PgPool,
file_uuid: &str,
output_dir: &str,
export_dir: &str,
) -> Result<PathBuf> {
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", file_uuid));
if package_dir.exists() {
std::fs::remove_dir_all(&package_dir)?;
}
// Create directory structure
std::fs::create_dir_all(&package_dir)?;
std::fs::create_dir_all(package_dir.join("video"))?;
std::fs::create_dir_all(package_dir.join("output"))?;
std::fs::create_dir_all(package_dir.join("identities"))?;
std::fs::create_dir_all(package_dir.join("db"))?;
std::fs::create_dir_all(package_dir.join("qdrant"))?;
std::fs::create_dir_all(package_dir.join("redis"))?;
// 1. Get file info from DB
let videos_table = crate::core::db::schema::table_name("videos");
let video_row: Option<(String, String, String)> = sqlx::query_as(
&format!("SELECT file_name, file_path, status FROM {} WHERE file_uuid = $1", videos_table)
)
.bind(file_uuid)
.fetch_optional(pool)
.await?;
let (file_name, file_path, status) = video_row.ok_or_else(|| anyhow::anyhow!("File not found"))?;
// Get file size from filesystem
let file_size = std::fs::metadata(&file_path).ok().map(|m| m.len()).unwrap_or(0);
// Get library name
let library = get_library_for_file(pool, &file_path).await;
// 2. Copy original video
let video_src = PathBuf::from(&file_path);
if video_src.exists() {
let dest = package_dir.join("video").join(&file_name);
std::fs::copy(&video_src, &dest)?;
}
// 3. Copy output files
copy_output_files(file_uuid, output_dir, &package_dir)?;
// 4. Copy identities (if any)
copy_identities_if_exist(output_dir, &package_dir)?;
// 5. Export PostgreSQL data
let db_stats = export_postgres_data(pool, file_uuid, &package_dir).await?;
// 6. Export Qdrant info (placeholder - full implementation later)
let qdrant_stats = QdrantInfo {
collection: "momentry_rule1".to_string(),
face_vectors: 0,
text_vectors: 0,
speaker_vectors: 0,
};
// Create placeholder files
std::fs::write(package_dir.join("qdrant").join("face_vectors.json"), "[]")?;
std::fs::write(package_dir.join("qdrant").join("text_vectors.json"), "[]")?;
std::fs::write(package_dir.join("qdrant").join("speaker_vectors.json"), "[]")?;
// 7. Export Redis info (placeholder)
std::fs::write(package_dir.join("redis").join("job_state.json"), "{}")?;
std::fs::write(package_dir.join("redis").join("cache.json"), "{}")?;
let redis_stats = RedisInfo {
keys_count: 0,
patterns: vec![
"momentry:job:*".to_string(),
"momentry:progress:*".to_string(),
],
};
// 8. Get processor results
let processors = get_processor_results(pool, file_uuid).await?;
// 9. Create manifest
let manifest = ExportManifest {
version: "1.0".to_string(),
export_type: "file".to_string(),
exported_at: chrono::Utc::now().to_rfc3339(),
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
file: FileInfo {
uuid: file_uuid.to_string(),
file_name,
file_path,
file_size,
library,
status,
},
data_sources: DataSources {
postgresql: db_stats,
qdrant: qdrant_stats,
sqlite: SqliteInfo {
file: "workspace.sqlite".to_string(),
tables: vec!["face_detections".to_string()],
total_records: 0,
},
redis: redis_stats,
},
processors,
};
std::fs::write(
package_dir.join("manifest.json"),
serde_json::to_string_pretty(&manifest)?,
)?;
// 10. Generate checksums
generate_checksums_internal(&package_dir)?;
// 11. Create tar.gz
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", file_uuid));
create_tar_gz_internal(&package_dir, &tar_path)?;
// Clean up directory
std::fs::remove_dir_all(&package_dir)?;
Ok(tar_path)
}
// ─── Helper Functions ────────────────────────────────────────────────────────
async fn get_library_for_file(pool: &sqlx::PgPool, file_path: &str) -> String {
let paths_table = crate::core::db::schema::table_name("upload_paths");
let row: Option<(String,)> = sqlx::query_as(
&format!(
"SELECT name FROM {} WHERE $1 LIKE full_path || '%%' ORDER BY LENGTH(full_path) DESC LIMIT 1",
paths_table
)
)
.bind(file_path)
.fetch_optional(pool)
.await
.ok()
.flatten();
row.map(|r| r.0).unwrap_or_else(|| "unknown".to_string())
}
fn copy_output_files(uuid: &str, output_dir: &str, package_dir: &Path) -> Result<()> {
let src_dir = PathBuf::from(output_dir);
let dest_dir = package_dir.join("output");
// Copy JSON files: {uuid}.*.json
if let Ok(entries) = std::fs::read_dir(&src_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
std::fs::copy(&path, dest_dir.join(name))?;
}
}
}
}
// Copy trace directory: {uuid}/trace_*/
let trace_src = src_dir.join(uuid);
if trace_src.exists() {
let trace_dest = dest_dir.join(uuid);
copy_dir_all_internal(&trace_src, &trace_dest)?;
}
Ok(())
}
fn copy_identities_if_exist(output_dir: &str, package_dir: &Path) -> Result<()> {
let identities_dir = PathBuf::from(output_dir).join("identities");
if !identities_dir.exists() {
return Ok(());
}
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let src = entry.path();
let dest = package_dir.join("identities").join(&name);
copy_dir_all_internal(&src, &dest)?;
}
}
}
Ok(())
}
async fn export_postgres_data(pool: &sqlx::PgPool, uuid: &str, package_dir: &Path) -> Result<PostgresqlInfo> {
let db_dir = package_dir.join("db");
let mut total_records = 0;
let mut tables = Vec::new();
// Helper to export a table
async fn export_table(pool: &sqlx::PgPool, db_dir: &Path, table: &str, where_col: &str, uuid: &str) -> Result<usize> {
let table_name = crate::core::db::schema::table_name(table);
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, where_col)
)
.bind(uuid)
.fetch_all(pool)
.await?;
let count = rows.len();
std::fs::write(
db_dir.join(format!("{}.json", table)),
serde_json::to_string_pretty(&rows)?,
)?;
Ok(count)
}
// Export tables
if let Ok(count) = export_table(pool, &db_dir, "videos", "file_uuid", uuid).await {
total_records += count;
tables.push("videos".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "processor_results", "file_uuid", uuid).await {
total_records += count;
tables.push("processor_results".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "monitor_jobs", "uuid", uuid).await {
total_records += count;
tables.push("monitor_jobs".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "trace_profiles", "file_uuid", uuid).await {
total_records += count;
tables.push("trace_profiles".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "tkg_nodes", "file_uuid", uuid).await {
total_records += count;
tables.push("tkg_nodes".to_string());
}
if let Ok(count) = export_table(pool, &db_dir, "chunk", "file_uuid", uuid).await {
total_records += count;
tables.push("chunks".to_string());
}
// Identities (simplified - just export all for now)
let id_table = crate::core::db::schema::table_name("identities");
let identities: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {}) v LIMIT 100", id_table)
)
.fetch_all(pool)
.await?;
if !identities.is_empty() {
total_records += identities.len();
tables.push("identities".to_string());
std::fs::write(db_dir.join("identities.json"), serde_json::to_string_pretty(&identities)?)?;
}
Ok(PostgresqlInfo { tables, total_records })
}
pub async fn get_processor_results(pool: &sqlx::PgPool, uuid: &str) -> Result<HashMap<String, ProcessorInfo>> {
let table = crate::core::db::schema::table_name("processor_results");
let rows: Vec<(String, String)> = sqlx::query_as(
&format!("SELECT processor, status FROM {} WHERE file_uuid = $1", table)
)
.bind(uuid)
.fetch_all(pool)
.await?;
let mut processors = HashMap::new();
for (proc_type, status) in rows {
let output_file = format!("{}.{}.json", uuid, proc_type);
processors.insert(proc_type, ProcessorInfo {
status,
file: output_file,
});
}
Ok(processors)
}
pub fn copy_dir_all_internal(src: &Path, dest: &Path) -> Result<()> {
std::fs::create_dir_all(dest)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
let dest_path = dest.join(entry.file_name());
if path.is_dir() {
copy_dir_all_internal(&path, &dest_path)?;
} else {
std::fs::copy(&path, &dest_path)?;
}
}
Ok(())
}
pub fn generate_checksums_internal(package_dir: &Path) -> Result<()> {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::io::Read;
let mut lines = Vec::new();
for entry in walkdir::WalkDir::new(package_dir)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
{
let path = entry.path();
if path.file_name().map(|n| n == "checksums.sha256").unwrap_or(false) {
continue;
}
let relative = path.strip_prefix(package_dir)?;
let mut file = std::fs::File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
let mut hasher = DefaultHasher::new();
buffer.hash(&mut hasher);
let hash = hasher.finish();
lines.push(format!("{:016x} {}", hash, relative.to_string_lossy()));
}
std::fs::write(package_dir.join("checksums.sha256"), lines.join("\n"))?;
Ok(())
}
pub fn create_tar_gz_internal(source_dir: &Path, output_path: &Path) -> Result<()> {
use flate2::write::GzEncoder;
use flate2::Compression;
use tar::Builder;
let file = std::fs::File::create(output_path)?;
let encoder = GzEncoder::new(file, Compression::default());
let mut tar = Builder::new(encoder);
tar.append_dir_all("", source_dir)?;
tar.finish()?;
Ok(())
}
pub fn extract_package_internal(package_path: &std::path::Path, dest_dir: &std::path::Path) -> Result<()> {
use flate2::read::GzDecoder;
use tar::Archive;
if dest_dir.exists() {
std::fs::remove_dir_all(dest_dir)?;
}
let tar_gz = std::fs::File::open(package_path)?;
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
archive.unpack(dest_dir)?;
Ok(())
}
+75 -2
View File
@@ -351,6 +351,7 @@ impl FileProfile {
let path = Self::profile_path(output_dir, &self.file_uuid);
let json =
serde_json::to_string_pretty(self).context("Failed to serialize file profile")?;
let json = crate::core::json_debug::append_debug_footer(json, &path);
std::fs::write(&path, json)
.with_context(|| format!("Failed to write profile to {}", path.display()))?;
tracing::debug!("[FileProfile] Saved profile for {}", self.file_uuid);
@@ -528,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,
@@ -614,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,
@@ -670,6 +672,7 @@ impl FaceTraceProfile {
let json = serde_json::to_string_pretty(&round_json_value(&serde_json::to_value(&*self)?))
.context("Failed to serialize FaceTraceProfile")?;
let profile_path = Self::profile_path(output_dir, &self.file_uuid, self.trace_id);
let json = crate::core::json_debug::append_debug_footer(json, &profile_path);
std::fs::write(&profile_path, json)
.with_context(|| format!("Failed to write {}", profile_path.display()))?;
@@ -866,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)]
@@ -883,6 +952,10 @@ pub enum SelectionReason {
PostCutBestBlur,
SceneStart,
Default,
CameraMotionStart,
CameraMotionMid,
CameraMotionEnd,
CutBaseline,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+475
View File
@@ -0,0 +1,475 @@
/// Folder batch export/import
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
// ─── Folder Manifest ─────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderManifest {
pub version: String,
#[serde(rename = "type")]
pub export_type: String,
pub exported_at: String,
pub momentry_version: String,
pub folder: FolderInfo,
pub files: Vec<FileInfo>,
pub total_records: usize,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FolderInfo {
pub name: String,
pub original_path: String,
pub library: String,
pub file_count: usize,
pub total_size: u64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct FileInfo {
pub uuid: String,
pub file_name: String,
pub file_path: String,
pub file_size: u64,
pub status: String,
pub processors: HashMap<String, String>,
}
// ─── Import Result ───────────────────────────────────────────────────────────
pub struct FolderImportResult {
pub folder_name: String,
pub imported_files: usize,
pub total_records: usize,
}
// ─── Export Function ─────────────────────────────────────────────────────────
pub async fn export_folder(
pool: &sqlx::PgPool,
folder_path: &str,
library_name: &str,
export_dir: &str,
) -> Result<(PathBuf, usize)> {
// Find all files in folder
let videos_table = crate::core::db::schema::table_name("videos");
let files: Vec<(String, String, String, Option<i64>, String)> = sqlx::query_as(
&format!(
"SELECT file_uuid, file_name, file_path, file_size, status FROM {} WHERE file_path LIKE $1 || '%%'",
videos_table
)
)
.bind(folder_path.trim_end_matches('/'))
.fetch_all(pool)
.await?;
if files.is_empty() {
return Err(anyhow::anyhow!("No files found in folder"));
}
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let package_dir = PathBuf::from(export_dir).join(format!("{}.momentry", library_name));
if package_dir.exists() {
std::fs::remove_dir_all(&package_dir)?;
}
// Create directory structure
std::fs::create_dir_all(&package_dir)?;
std::fs::create_dir_all(package_dir.join("videos"))?;
std::fs::create_dir_all(package_dir.join("output"))?;
std::fs::create_dir_all(package_dir.join("identities"))?;
std::fs::create_dir_all(package_dir.join("db"))?;
std::fs::create_dir_all(package_dir.join("qdrant"))?;
std::fs::create_dir_all(package_dir.join("redis"))?;
let mut manifest_files = Vec::new();
let mut total_size = 0u64;
let mut total_records = 0usize;
// Process each file
for (uuid, file_name, file_path, file_size, status) in &files {
let fsize = file_size.unwrap_or(0) as u64;
total_size += fsize;
// Copy video
let video_src = PathBuf::from(file_path);
if video_src.exists() {
let dest = package_dir.join("videos").join(file_name);
std::fs::copy(&video_src, &dest)?;
}
// Copy output files
copy_file_output(uuid, output_dir, &package_dir)?;
// Export DB records
let records = export_file_db_records(pool, uuid, &package_dir).await?;
total_records += records;
// Get processors
let processors = crate::core::export::get_processor_results(pool, uuid).await?;
let proc_map: HashMap<String, String> = processors.iter()
.map(|(k, v)| (k.clone(), v.status.clone()))
.collect();
manifest_files.push(FileInfo {
uuid: uuid.clone(),
file_name: file_name.clone(),
file_path: file_path.clone(),
file_size: fsize,
status: status.clone(),
processors: proc_map,
});
}
// Copy shared identities
copy_shared_identities(output_dir, &package_dir)?;
// Create folder manifest
let manifest = FolderManifest {
version: "1.0".to_string(),
export_type: "folder".to_string(),
exported_at: chrono::Utc::now().to_rfc3339(),
momentry_version: env!("CARGO_PKG_VERSION").to_string(),
folder: FolderInfo {
name: library_name.to_string(),
original_path: folder_path.to_string(),
library: library_name.to_string(),
file_count: files.len(),
total_size,
},
files: manifest_files,
total_records,
};
std::fs::write(
package_dir.join("manifest.json"),
serde_json::to_string_pretty(&manifest)?,
)?;
// Generate checksums
crate::core::export::generate_checksums_internal(&package_dir)?;
// Create tar.gz
let folder_name = PathBuf::from(folder_path)
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| library_name.to_string());
let tar_path = PathBuf::from(export_dir).join(format!("{}.momentry.tar.gz", folder_name));
crate::core::export::create_tar_gz_internal(&package_dir, &tar_path)?;
// Clean up
std::fs::remove_dir_all(&package_dir)?;
Ok((tar_path, files.len()))
}
// ─── Import Function ─────────────────────────────────────────────────────────
pub async fn import_folder(
pool: &sqlx::PgPool,
package_path: &str,
target_folder_path: Option<&str>,
force: bool,
) -> Result<FolderImportResult> {
let pkg_path = PathBuf::from(package_path);
let temp_dir = pkg_path.parent().unwrap_or(std::path::Path::new("."))
.join(pkg_path.file_stem().unwrap_or_default());
// Extract
crate::core::export::extract_package_internal(&pkg_path, &temp_dir)?;
// Read manifest
let manifest_str = std::fs::read_to_string(temp_dir.join("manifest.json"))?;
let manifest: FolderManifest = serde_json::from_str(&manifest_str)?;
let mut imported_files = 0;
let mut total_records = 0;
// Import each file
for file_info in &manifest.files {
// Check if exists
let videos_table = crate::core::db::schema::table_name("videos");
let exists: Option<(i32,)> = sqlx::query_as(
&format!("SELECT id FROM {} WHERE file_uuid = $1", videos_table)
)
.bind(&file_info.uuid)
.fetch_optional(pool)
.await?;
if exists.is_some() && !force {
tracing::warn!("[Folder Import] Skipping existing file: {}", file_info.uuid);
continue;
}
// Delete existing if force
if exists.is_some() {
delete_existing_records(pool, &file_info.uuid).await?;
}
// Restore video
let video_src = temp_dir.join("videos").join(&file_info.file_name);
let video_dest = target_folder_path
.map(|p| PathBuf::from(p).join(&file_info.file_name))
.unwrap_or_else(|| PathBuf::from(&file_info.file_path));
if video_src.exists() {
if let Some(parent) = video_dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(&video_src, &video_dest)?;
}
// Restore output files
restore_file_output(&temp_dir, &file_info.uuid)?;
// Restore DB records
let records = restore_file_db_records(pool, &temp_dir, &file_info.uuid).await?;
total_records += records;
imported_files += 1;
}
// Restore identities
restore_shared_identities(&temp_dir)?;
// Clean up
let _ = std::fs::remove_dir_all(&temp_dir);
Ok(FolderImportResult {
folder_name: manifest.folder.name,
imported_files,
total_records,
})
}
// ─── Helper Functions ────────────────────────────────────────────────────────
fn copy_file_output(uuid: &str, output_dir: &str, package_dir: &PathBuf) -> Result<()> {
let src_dir = PathBuf::from(output_dir);
let dest_dir = package_dir.join("output");
// Copy JSON files
if let Ok(entries) = std::fs::read_dir(&src_dir) {
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with(&format!("{}.", uuid)) && name.ends_with(".json") {
std::fs::copy(&path, dest_dir.join(name))?;
}
}
}
}
// Copy trace directory
let trace_src = src_dir.join(uuid);
if trace_src.exists() {
let trace_dest = dest_dir.join(uuid);
crate::core::export::copy_dir_all_internal(&trace_src, &trace_dest)?;
}
Ok(())
}
fn copy_shared_identities(output_dir: &str, package_dir: &PathBuf) -> Result<()> {
let identities_dir = PathBuf::from(output_dir).join("identities");
if !identities_dir.exists() {
return Ok(());
}
let dest_identities = package_dir.join("identities");
if let Ok(entries) = std::fs::read_dir(&identities_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let src = entry.path();
let dest = dest_identities.join(&name);
if !dest.exists() {
crate::core::export::copy_dir_all_internal(&src, &dest)?;
}
}
}
}
Ok(())
}
async fn export_file_db_records(pool: &sqlx::PgPool, uuid: &str, package_dir: &PathBuf) -> Result<usize> {
let db_dir = package_dir.join("db");
let mut total = 0;
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
for table in tables {
let table_name = crate::core::db::schema::table_name(table);
let col = if table == "monitor_jobs" { "uuid" } else { "file_uuid" };
let rows: Vec<serde_json::Value> = sqlx::query_scalar::<_, serde_json::Value>(
&format!("SELECT row_to_json(v) FROM (SELECT * FROM {} WHERE {} = $1) v", table_name, col)
)
.bind(uuid)
.fetch_all(pool)
.await?;
if !rows.is_empty() {
std::fs::write(
db_dir.join(format!("{}.json", table)),
serde_json::to_string_pretty(&rows)?,
)?;
total += rows.len();
}
}
Ok(total)
}
async fn delete_existing_records(pool: &sqlx::PgPool, uuid: &str) -> Result<()> {
let tables = [
("processor_results", "file_uuid"),
("monitor_jobs", "uuid"),
("trace_profiles", "file_uuid"),
("tkg_nodes", "file_uuid"),
("tkg_edges", "file_uuid"),
("chunk", "file_uuid"),
("face_detections", "file_uuid"),
("videos", "file_uuid"),
];
for (table, col) in tables {
let table_name = crate::core::db::schema::table_name(table);
let _ = sqlx::query(&format!("DELETE FROM {} WHERE {} = $1", table_name, col))
.bind(uuid)
.execute(pool)
.await;
}
Ok(())
}
fn restore_file_output(temp_dir: &PathBuf, uuid: &str) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_dir = PathBuf::from(output_dir);
let src_output = temp_dir.join("output");
if !src_output.exists() {
return Ok(());
}
// Copy JSON files
if let Ok(entries) = std::fs::read_dir(&src_output) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
let dest = dest_dir.join(path.file_name().unwrap());
std::fs::copy(&path, &dest)?;
} else if path.is_dir() {
if path.file_name().map(|n| n == uuid).unwrap_or(false) {
let dest = dest_dir.join(uuid);
crate::core::export::copy_dir_all_internal(&path, &dest)?;
}
}
}
}
Ok(())
}
async fn restore_file_db_records(pool: &sqlx::PgPool, temp_dir: &PathBuf, uuid: &str) -> Result<usize> {
let db_dir = temp_dir.join("db");
if !db_dir.exists() {
return Ok(0);
}
let mut restored = 0;
let tables = ["videos", "processor_results", "monitor_jobs", "trace_profiles", "tkg_nodes", "chunk"];
for table in tables {
let json_path = db_dir.join(format!("{}.json", table));
if !json_path.exists() {
continue;
}
let json_str = std::fs::read_to_string(&json_path)?;
let records: Vec<serde_json::Value> = serde_json::from_str(&json_str)?;
let table_name = crate::core::db::schema::table_name(table);
for record in records {
// Remove id column (auto-increment with NOT NULL)
let mut record = record.clone();
if let Some(obj) = record.as_object_mut() {
obj.remove("id");
}
if record.as_object().map(|o| o.is_empty()).unwrap_or(true) {
continue;
}
// Build explicit INSERT with columns (excluding id)
let columns: Vec<String> = record.as_object().unwrap().keys()
.map(|k| format!("\"{}\"", k)).collect();
let cols_str = columns.join(", ");
// Build values with proper type handling
let values: Vec<String> = record.as_object().unwrap().values()
.map(|v| match v {
serde_json::Value::Null => "NULL".to_string(),
serde_json::Value::Bool(b) => b.to_string(),
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::String(s) => format!("'{}'", s.replace("'", "''")),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
format!("'{}'::jsonb", serde_json::to_string(v).unwrap_or_else(|_| "null".to_string()).replace("'", "''"))
}
})
.collect();
let vals_str = values.join(", ");
let sql = format!(
"INSERT INTO {} ({}) VALUES ({})",
table_name, cols_str, vals_str
);
let result = sqlx::query(&sql)
.execute(pool)
.await;
if result.is_ok() {
restored += 1;
}
}
}
Ok(restored)
}
fn restore_shared_identities(temp_dir: &PathBuf) -> Result<()> {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let dest_identities = PathBuf::from(output_dir).join("identities");
let src_identities = temp_dir.join("identities");
if !src_identities.exists() {
return Ok(());
}
if !dest_identities.exists() {
std::fs::create_dir_all(&dest_identities)?;
}
if let Ok(entries) = std::fs::read_dir(&src_identities) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let name = entry.file_name();
let dest = dest_identities.join(&name);
if !dest.exists() {
crate::core::export::copy_dir_all_internal(&entry.path(), &dest)?;
}
}
}
}
Ok(())
}
+1 -1
View File
@@ -362,7 +362,7 @@ async fn check_dependencies(env: &std::collections::HashMap<String, String>, opt
}
let redis_url = env.get("REDIS_URL").cloned()
.unwrap_or_else(|| "redis://localhost:6379".into());
.unwrap_or_else(|| crate::core::config::REDIS_URL.clone());
match check_redis(&redis_url).await {
Ok(_) => ok(opts, "Redis"),
Err(e) => warn(opts, &format!("Redis: {}", e)),
+161
View File
@@ -0,0 +1,161 @@
//! JSON Debug Metadata — 在每個輸出 JSON 的最下方加上本次寫入的絕對檔案位置,
//! 方便開啟 JSON 內容時直接看到來源檔案路徑,利於 debug。
//!
//! 產生的區塊範例(出現在最下方):
//! ```json
//! "_debug": {
//! "absolute_path": "/Users/accusys/momentry/output/demo/xxx.face.json",
//! "written_at_unix": 1763000000
//! }
//! ```
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// 取得檔案的 canonical 絕對路徑。
/// 檔案可能尚未寫入(我們是在寫檔前產生 footer),
/// 因此先嘗試 canonicalize 檔案本身,失敗則 canonicalize 父目錄再接上檔名。
fn absolute_path_string(path: &Path) -> String {
if let Ok(canon) = std::fs::canonicalize(path) {
return canon.to_string_lossy().to_string();
}
if let (Some(parent), Some(file)) = (path.parent(), path.file_name()) {
if let Ok(canon_parent) = std::fs::canonicalize(parent) {
return canon_parent.join(file).to_string_lossy().to_string();
}
}
// 父目錄也不存在時,退回輸入路徑(至少保證可追蹤來源)
path.to_string_lossy().to_string()
}
/// 產生 `_debug` 區塊內容。`pretty` 決定縮排樣式(pretty=多行縮排 / compact=單行)。
fn debug_footer(path: &Path, pretty: bool) -> String {
let abs_str = serde_json::to_string(&absolute_path_string(path))
.unwrap_or_else(|_| "\"\"".to_string());
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
if pretty {
format!(
" \"_debug\": {{\n \"absolute_path\": {},\n \"written_at_unix\": {}\n }}",
abs_str, ts
)
} else {
format!("\"_debug\":{{\"absolute_path\":{},\"written_at_unix\":{}}}", abs_str, ts)
}
}
/// 在 JSON 字串最後一個 `}` 前插入 `_debug` 區塊。
/// 自動偵測 pretty(含換行)或 compact 輸出,footer 樣式跟隨原文。
pub fn append_debug_footer(json: String, path: &Path) -> String {
let pretty = json.contains('\n');
let footer = debug_footer(path, pretty);
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
// 空物件:直接放 footer
if pretty {
return format!("{{\n{}\n}}", footer);
}
return format!("{{{}}}", footer);
}
if json.trim_end().ends_with('}') {
let mut out = json;
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out.pop(); // 移除最後的 '}'
if pretty {
out.push_str(",\n");
out.push_str(&footer);
out.push_str("\n}");
} else {
out.push(',');
out.push_str(&footer);
out.push('}');
}
out
} else {
// 非預期格式(不是物件結尾),原樣返回避免破壞檔案
json
}
}
/// 序列化(pretty)+ 加上 debug footer + 寫入檔案。
pub fn write_json_with_debug<T: Serialize, P: AsRef<Path>>(
path: P,
value: &T,
) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let json = append_debug_footer(json, path.as_ref());
std::fs::write(path.as_ref(), json)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn footer_pretty_json_is_valid_and_at_bottom() {
let v = json!({"a": 1, "b": [1, 2], "nested": {"x": 1.23456}});
let s = serde_json::to_string_pretty(&v).unwrap();
let out = append_debug_footer(s, Path::new("/tmp/test.face.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
let debug = parsed.get("_debug").expect("_debug 應存在");
// /tmp 在 macOS 是 symlink → canonical 後為 /private/tmp,
// 因此只斷言「絕對路徑 + 正確檔名」,不寫死完整字串
let abs = debug["absolute_path"].as_str().expect("absolute_path 應為字串");
assert!(abs.starts_with('/'), "應為絕對路徑:{}", abs);
assert!(abs.ends_with("test.face.json"), "檔名應正確:{}", abs);
assert!(debug["written_at_unix"].is_u64());
// _debug 必須在最下方(最後一個鍵)
let last_key_pos = out.rfind("\"_debug\"").unwrap();
assert!(
last_key_pos > out.rfind("\"nested\"").unwrap(),
"_debug 應出現在所有原有鍵之後"
);
}
#[test]
fn footer_compact_json_is_valid() {
let out = append_debug_footer("{\"a\":1,\"b\":2}".to_string(), Path::new("/tmp/x.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(parsed["a"], 1);
assert!(parsed.get("_debug").is_some());
assert!(!out.contains('\n'), "compact 輸入應維持 compact 樣式");
}
#[test]
fn footer_empty_object() {
let out = append_debug_footer("{}".to_string(), Path::new("/tmp/x.json"));
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert!(parsed.get("_debug").is_some());
}
#[test]
fn write_json_with_debug_roundtrip() {
let dir = std::env::temp_dir().join("json_debug_test");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("roundtrip_test.json");
let v = json!({"file_uuid": "abc123", "status": "completed"});
write_json_with_debug(&path, &v).unwrap();
let content = std::fs::read_to_string(&path).unwrap();
let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
assert_eq!(parsed["file_uuid"], "abc123");
assert_eq!(
parsed["_debug"]["absolute_path"],
path.canonicalize().unwrap().to_string_lossy().to_string(),
"absolute_path 應為檔案的 canonical 絕對路徑"
);
std::fs::remove_file(&path).ok();
}
}
+30
View File
@@ -55,6 +55,36 @@ pub fn write_file_pretty_rounded<T: Serialize>(
decimals: usize,
) -> anyhow::Result<()> {
let json = to_string_pretty_rounded(value, decimals)?;
// 在 JSON 最下方加上本次寫入的絕對檔案位置(debug 用)
let json = crate::core::json_debug::append_debug_footer(json, std::path::Path::new(path));
std::fs::write(path, json)?;
Ok(())
}
/// 寫入標準化 JSON(含 _meta 和 _debug)
pub fn write_file_standard<T: Serialize>(
value: &T,
path: &str,
decimals: usize,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> anyhow::Result<()> {
let json = to_string_pretty_rounded(value, decimals)?;
// 加上 _meta 和 _debug
let json = crate::core::json_standardize::append_meta_and_debug(
json,
std::path::Path::new(path),
processor_name,
processor_tool,
processor_version,
file_uuid,
file_path,
file_name,
);
std::fs::write(path, json)?;
Ok(())
}
+285
View File
@@ -0,0 +1,285 @@
//! JSON 標準化 Metadata — 在每個輸出 JSON 加上 `_meta` 和 `_debug` 區塊
//!
//! ## 標準格式
//! ```json
//! {
//! "_meta": {
//! "schema_version": "1.0",
//! "processor": {"name": "face", "tool": "swift_face", "version": "1.0.0"},
//! "source": {"file_uuid": "xxx", "file_path": "/path/to/video.mp4", "file_name": "025.mp4"},
//! "timestamps": {"created_at": "ISO8601", "completed_at": "ISO8601"},
//! "pipeline": {"scan_id": "", "worker_id": "", "stage": "deep_scan"}
//! },
//! "_debug": {
//! "absolute_path": "/path/to/output/xxx.face.json",
//! "written_at_unix": 1794674568,
//! "output_dir": "/Users/accusys/momentry/output/demo"
//! },
//! "status": "completed",
//! "data": { ... }
//! }
//! ```
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// 處理器資訊
#[derive(Debug, Clone, Serialize)]
pub struct ProcessorMeta {
pub name: String,
pub tool: String,
pub version: String,
}
/// 來源資訊
#[derive(Debug, Clone, Serialize)]
pub struct SourceMeta {
pub file_uuid: String,
pub file_path: String,
pub file_name: String,
}
/// 時間戳記
#[derive(Debug, Clone, Serialize)]
pub struct TimestampsMeta {
pub created_at: String,
pub completed_at: String,
}
/// Pipeline 資訊
#[derive(Debug, Clone, Serialize)]
pub struct PipelineMeta {
#[serde(skip_serializing_if = "String::is_empty")]
pub scan_id: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub worker_id: String,
pub stage: String,
}
/// 完整 _meta 區塊
#[derive(Debug, Clone, Serialize)]
pub struct MetaFooter {
pub schema_version: String,
pub processor: ProcessorMeta,
pub source: SourceMeta,
pub timestamps: TimestampsMeta,
#[serde(skip_serializing_if = "Option::is_none")]
pub pipeline: Option<PipelineMeta>,
}
/// _debug 區塊
#[derive(Debug, Clone, Serialize)]
pub struct DebugFooter {
pub absolute_path: String,
pub written_at_unix: u64,
pub output_dir: String,
}
/// 取得絕對路徑
fn absolute_path_string(path: &Path) -> String {
if let Ok(canon) = std::fs::canonicalize(path) {
return canon.to_string_lossy().to_string();
}
if let (Some(parent), Some(file)) = (path.parent(), path.file_name()) {
if let Ok(canon_parent) = std::fs::canonicalize(parent) {
return canon_parent.join(file).to_string_lossy().to_string();
}
}
path.to_string_lossy().to_string()
}
/// 建立 _meta 區塊
pub fn create_meta(
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> MetaFooter {
let now = chrono::Utc::now().to_rfc3339();
MetaFooter {
schema_version: "1.0".to_string(),
processor: ProcessorMeta {
name: processor_name.to_string(),
tool: processor_tool.to_string(),
version: processor_version.to_string(),
},
source: SourceMeta {
file_uuid: file_uuid.to_string(),
file_path: file_path.to_string(),
file_name: file_name.to_string(),
},
timestamps: TimestampsMeta {
created_at: now.clone(),
completed_at: now,
},
pipeline: Some(PipelineMeta {
scan_id: std::env::var("MOMENTRY_SCAN_ID").unwrap_or_default(),
worker_id: std::env::var("MOMENTRY_WORKER_ID").unwrap_or_default(),
stage: "deep_scan".to_string(),
}),
}
}
/// 建立 _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,
}
}
/// 在 JSON 字串中加入 `_meta` 和 `_debug` 區塊
pub fn append_meta_and_debug(
json: String,
path: &Path,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> String {
let pretty = json.contains('\n');
// 建立 _meta JSON
let meta = create_meta(processor_name, processor_tool, processor_version, file_uuid, file_path, file_name);
let meta_json = serde_json::to_string(&meta).unwrap_or_else(|_| "{}".to_string());
// 建立 _debug JSON
let debug = create_debug(path);
let debug_json = serde_json::to_string(&debug).unwrap_or_else(|_| "{}".to_string());
// 組合 footer
let footer = if pretty {
format!(
" \"_meta\": {},\n \"_debug\": {}",
meta_json, debug_json
)
} else {
format!(
"\"_meta\":{},\"_debug\":{}",
meta_json, debug_json
)
};
// 插入到 JSON 結尾
if json.trim_end() == "{}" || json.trim_end() == "{ }" {
if pretty {
return format!("{{\n{}\n}}", footer);
}
return format!("{{{}}}", footer);
}
if json.trim_end().ends_with('}') {
let mut out = json;
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out.pop(); // 移除最後的 '}'
if pretty {
out.push_str(",\n");
out.push_str(&footer);
out.push_str("\n}");
} else {
out.push(',');
out.push_str(&footer);
out.push('}');
}
out
} else {
json
}
}
/// 序列化 + 加上 _meta 和 _debug + 寫入檔案
pub fn write_json_with_meta_and_debug<T: Serialize, P: AsRef<Path>>(
path: P,
value: &T,
processor_name: &str,
processor_tool: &str,
processor_version: &str,
file_uuid: &str,
file_path: &str,
file_name: &str,
) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(value)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let json = append_meta_and_debug(
json,
path.as_ref(),
processor_name,
processor_tool,
processor_version,
file_uuid,
file_path,
file_name,
);
std::fs::write(path.as_ref(), json)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn meta_and_debug_footer_is_valid() {
let v = json!({"status": "completed", "data": {"faces": 10}});
let s = serde_json::to_string_pretty(&v).unwrap();
let out = append_meta_and_debug(
s,
Path::new("/tmp/test.face.json"),
"face",
"swift_face",
"1.0.0",
"abc123",
"/path/to/video.mp4",
"025.mp4"
);
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
assert!(parsed.get("_meta").is_some());
assert!(parsed.get("_debug").is_some());
assert_eq!(parsed["status"], "completed");
assert_eq!(parsed["_meta"]["processor"]["name"], "face");
assert_eq!(parsed["_meta"]["source"]["file_name"], "025.mp4");
}
}
+18 -8
View File
@@ -32,7 +32,7 @@ struct Choice {
}
pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
let req = serde_json::json!({
let mut req = serde_json::json!({
"model": (*config::llm::SUMMARY_MODEL).clone(),
"messages": [
{
@@ -50,14 +50,24 @@ pub async fn ask_llm(prompt: &str, system_prompt: &str) -> Result<String> {
"chat_template_kwargs": {"enable_thinking": false}
});
debug!("Calling LLM: {}", *config::llm::SUMMARY_URL);
let (summary_url, summary_model, summary_fallbacks) =
crate::core::llm::function_calling::resolve_llm_endpoint("summary")
.await
.unwrap_or_else(|_| (config::llm::SUMMARY_URL.clone(), config::llm::CHAT_MODEL.clone(), Vec::new()));
let res = LLM_CLIENT
.post(&*config::llm::SUMMARY_URL)
.json(&req)
.timeout(Duration::from_secs(*config::llm::SUMMARY_TIMEOUT_SECS))
.send()
.await?;
if let Some(obj) = req.as_object_mut() {
obj.insert("model".to_string(), serde_json::json!(summary_model));
}
debug!("Calling LLM (summary): {}", summary_url);
let res = crate::core::llm::function_calling::post_llm_with_fallback(
&summary_url,
&summary_fallbacks,
&req,
*config::llm::SUMMARY_TIMEOUT_SECS,
)
.await?;
if !res.status().is_success() {
error!("LLM API error: {}", res.status());
+224 -21
View File
@@ -114,6 +114,218 @@ pub fn llm_chat_url() -> String {
config::llm::CHAT_URL.clone()
}
/// Resolve an LLM endpoint (url, model, fallback_url) by role key.
///
/// Routing rules — instances are identified by **URL** (not port), so an
/// entry may point to a local llama-server (127.0.0.1:8080/8082) or to a
/// remote machine's llama-server (e.g. http://192.168.110.203:8080/...) for
/// future off-box resource use:
/// - `chat` entry defines instance A; `vlm` entry defines instance B.
/// `enabled == false` on an entry removes that instance from routing
/// entirely (never primary, never fallback).
/// - Role primary = the role's configured entry, if its instance is enabled;
/// otherwise the other enabled instance is promoted to primary.
/// - Fallbacks = the entry's own `fallbacks` list (each may be an internal
/// instance or an external machine such as 201/gb10), plus the other
/// enabled instance auto-appended when not already listed.
/// - `strategy == "round_robin"` → every call rotates the candidate order
/// (primary included), pooling all instances' compute for throughput;
/// failover still applies to the remaining list.
/// Otherwise ("priority") the primary is always tried first.
/// - Single enabled instance → everything (chat/vlm/summary) uses that one
/// model with no fallback.
///
/// `key` is one of: "chat", "vlm", "summary".
pub async fn resolve_llm_endpoint(key: &str) -> anyhow::Result<(String, String, Vec<String>)> {
use crate::core::admin_config::LlmConfig;
let chat_cfg = crate::core::admin_config::get_llm_config("chat").await;
let vlm_cfg = crate::core::admin_config::get_llm_config("vlm").await;
let sum_cfg = crate::core::admin_config::get_llm_config("summary").await;
let chat_on = chat_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
let vlm_on = vlm_cfg.as_ref().and_then(|c| c.enabled).unwrap_or(true);
// Env-statics fallback when no admin config entry exists
let chat_entry = chat_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::CHAT_URL.clone(),
model: config::llm::CHAT_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
let vlm_entry = vlm_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::VISION_URL.clone(),
model: config::llm::VISION_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
let sum_entry = sum_cfg.unwrap_or_else(|| LlmConfig {
url: config::llm::SUMMARY_URL.clone(),
model: config::llm::CHAT_MODEL.clone(),
timeout: 0,
fallback_url: None,
fallbacks: Vec::new(),
strategy: None,
enabled: Some(true),
});
// Capture instance URLs for the enable-check closure before the entries
// are moved into the role selection below.
let chat_url_str = chat_entry.url.clone();
let vlm_url_str = vlm_entry.url.clone();
let (role_entry, other_entry) = match key {
"vlm" => (vlm_entry, chat_entry.clone()),
"summary" => (sum_entry, vlm_entry.clone()),
_ => (chat_entry.clone(), vlm_entry),
};
// Instance identity is by URL: each llm_config entry owns the instance it
// points to (local or remote machine). Unknown URLs (e.g. a manually added
// remote fallback) are treated as enabled.
let inst_on = |u: &str| -> bool {
if u == chat_url_str {
chat_on
} else if u == vlm_url_str {
vlm_on
} else {
true
}
};
// Candidate list: primary + configured fallbacks (legacy fallback_url
// merged in first for backward compat) + the other enabled instance.
let mut candidates: Vec<String> = vec![role_entry.url.clone()];
if let Some(legacy) = role_entry.fallback_url.clone() {
candidates.push(legacy);
}
candidates.extend(role_entry.fallbacks.iter().cloned());
candidates.push(other_entry.url.clone());
// Filter: drop duplicates, drop entries equal to the primary, drop
// disabled instances. Preserve order (priority semantics).
let primary = role_entry.url.clone();
let mut seen = std::collections::HashSet::new();
candidates.retain(|u| {
u != &primary
&& inst_on(u)
&& seen.insert(u.clone())
});
// Role's preferred instance disabled → promote the other enabled instance
if !inst_on(&role_entry.url) {
if !candidates.is_empty() {
let new_primary = candidates.remove(0);
tracing::warn!(
"[LLM] role '{}' primary instance disabled — routing to {}",
key, new_primary
);
return Ok((new_primary, role_entry.model, candidates));
}
anyhow::bail!("[LLM] role '{}' primary instance disabled and no other enabled instance", key);
}
// Resource constraint: when free memory is too low to keep several
// llama-server instances warm, collapse routing to a single instance
// (no fallbacks, no rotation).
if !candidates.is_empty() && crate::core::dynamic_concurrency::memory_constrained() {
tracing::info!(
"[LLM] memory constrained — single-instance routing for '{}' ({} candidates dropped)",
key,
candidates.len()
);
return Ok((primary, role_entry.model, Vec::new()));
}
// Strategy: round_robin rotates the full candidate list (primary first),
// spreading requests across every enabled instance — including remote
// machines — to aggregate their compute. priority keeps the configured
// order untouched.
if role_entry.strategy.as_deref() == Some("round_robin") && !candidates.is_empty() {
static RR_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = RR_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut list: Vec<String> = vec![primary.clone()];
list.extend(candidates);
let len = list.len();
let offset = (n % len as u64) as usize;
list.rotate_left(offset);
let new_primary = list.remove(0);
tracing::debug!(
"[LLM] round_robin pick #{} for '{}' → {} ({} fallbacks)",
n, key, new_primary, list.len()
);
return Ok((new_primary, role_entry.model, list));
}
Ok((primary, role_entry.model, candidates))
}
/// POST an OpenAI-style chat request to `url`; on transport error or 5xx/429,
/// walk `fallbacks` in order (each may be a local llama-server instance or a
/// remote machine's — possibly a different model). llama-server ignores the
/// model field mismatch, so the same request body is reused for each attempt.
pub async fn post_llm_with_fallback(
url: &str,
fallbacks: &[String],
req_body: &serde_json::Value,
timeout_secs: u64,
) -> anyhow::Result<reqwest::Response> {
let send = |u: String| {
LLM_CLIENT
.post(&u)
.json(req_body)
.timeout(std::time::Duration::from_secs(timeout_secs))
.send()
};
match send(url.to_string()).await {
Ok(res) if res.status().is_success() => Ok(res),
Ok(res) => {
let st = res.status().as_u16();
let text = res.text().await.unwrap_or_default();
// Only retry on server-side / busy errors; 4xx means the request itself is bad.
let retriable = st >= 500 || st == 429;
if retriable && !fallbacks.is_empty() {
for (i, fb) in fallbacks.iter().enumerate() {
tracing::warn!("[LLM] {} returned {} — trying fallback #{} {}", url, st, i + 1, fb);
match send(fb.clone()).await {
Ok(r) if r.status().is_success() => return Ok(r),
Ok(r) => {
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
}
Err(e) => {
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e);
}
}
}
anyhow::bail!("LLM API error ({}): all {} fallback(s) exhausted", st, fallbacks.len())
}
anyhow::bail!("LLM API error ({}): {}", st, text)
}
Err(e) => {
if !fallbacks.is_empty() {
for (i, fb) in fallbacks.iter().enumerate() {
tracing::warn!("[LLM] {} unreachable ({}) — trying fallback #{} {}", url, e, i + 1, fb);
match send(fb.clone()).await {
Ok(r) if r.status().is_success() => return Ok(r),
Ok(r) => {
tracing::warn!("[LLM] fallback #{} {} returned {}", i + 1, fb, r.status());
}
Err(e2) => {
tracing::warn!("[LLM] fallback #{} {} unreachable: {}", i + 1, fb, e2);
}
}
}
anyhow::bail!("LLM API error: {} — all {} fallback(s) exhausted", e, fallbacks.len())
}
Err(anyhow::anyhow!("LLM API error: {}", e))
}
}
}
/// Get the LLM model name from centralized config
pub fn llm_model() -> String {
config::llm::CHAT_MODEL.clone()
@@ -150,8 +362,10 @@ pub async fn call_llm_vision(
{"role": "user", "content": content_parts}
]);
let (vision_url, vision_model, vision_fallbacks) = resolve_llm_endpoint("vlm").await?;
let req = json!({
"model": llm_vision_model(),
"model": vision_model,
"messages": messages,
"temperature": 0.1,
"max_tokens": max_tokens,
@@ -159,12 +373,7 @@ pub async fn call_llm_vision(
"chat_template_kwargs": {"enable_thinking": false}
});
let res = LLM_CLIENT
.post(&llm_vision_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout_secs))
.send()
.await?;
let res = post_llm_with_fallback(&vision_url, &vision_fallbacks, &req, timeout_secs).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
anyhow::bail!("Vision LLM API error: {}", text);
@@ -233,8 +442,10 @@ pub async fn call_llm(
*config::llm::CHAT_TIMEOUT_SECS
};
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
let mut req = serde_json::to_value(&ChatRequest {
model: llm_model(),
model: chat_model,
messages,
temperature: 0.1,
max_tokens,
@@ -245,12 +456,7 @@ pub async fn call_llm(
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
}
let res = LLM_CLIENT
.post(&llm_chat_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout))
.send()
.await?;
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
@@ -303,8 +509,10 @@ pub async fn call_llm_with_usage(
let start = std::time::Instant::now();
let (chat_url, chat_model, chat_fallback) = resolve_llm_endpoint("chat").await?;
let mut req = serde_json::to_value(&ChatRequest {
model: llm_model(),
model: chat_model,
messages,
temperature: 0.1,
max_tokens,
@@ -315,12 +523,7 @@ pub async fn call_llm_with_usage(
obj.insert("chat_template_kwargs".to_string(), json!({"enable_thinking": false}));
}
let res = LLM_CLIENT
.post(&llm_chat_url())
.json(&req)
.timeout(std::time::Duration::from_secs(timeout))
.send()
.await?;
let res = post_llm_with_fallback(&chat_url, &chat_fallback, &req, timeout_secs).await?;
if !res.status().is_success() {
let text = res.text().await.unwrap_or_default();
+6
View File
@@ -11,6 +11,8 @@ pub mod config;
pub mod dynamic_concurrency;
pub mod db;
pub mod embedding;
pub mod folder_export;
pub mod export;
pub mod face_filter_engine;
pub mod file_lifecycle;
pub mod file_profile;
@@ -40,3 +42,7 @@ pub mod tmdb;
pub mod trace_sync;
pub mod vision;
pub mod vlm;
pub mod json_debug;
pub mod json_standardize;
pub mod rerun_backup;
+8 -4
View File
@@ -29,7 +29,13 @@ pub fn momentry_core_dir() -> PathBuf {
// Check if we're in a typical installation structure
if parent.ends_with("bin") {
if let Some(grandparent) = parent.parent() {
return grandparent.join("momentry_core");
// Prefer <grandparent>/momentry_core if it exists
let core = grandparent.join("momentry_core");
if core.exists() {
return core;
}
// Fallback: the grandparent IS the deployment dir (e.g. ~/momentry)
return grandparent.to_path_buf();
}
}
}
@@ -67,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
+4
View File
@@ -89,6 +89,10 @@ pub async fn vectorize_chunks(uuid: &str) -> Result<()> {
let qdrant = QdrantDb::new();
let embedder = Embedder::new("embeddinggemma-300m".to_string());
// Self-heal: ensure the main text-chunk collection exists (768D
// embeddinggemma) — clean installs start with an empty Qdrant.
qdrant.ensure_collection(&qdrant.collection_name.clone(), 768).await?;
let chunk_table = schema::table_name("chunk");
let rows = sqlx::query_as::<_, (String, String, String, i64, i64, f64, f64, String)>(&format!(
"SELECT chunk_id, chunk_type, text_content, start_frame, end_frame, \
+42 -2
View File
@@ -53,8 +53,48 @@ impl AsrxResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write asrx.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "asrx".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "rust_asr_asrx".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write asrx.json")?;
Ok(())
}
+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
}
+74 -19
View File
@@ -1,6 +1,7 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::path::Path;
use std::time::Duration;
use super::executor::PythonExecutor;
@@ -75,29 +76,49 @@ pub async fn process_cut(
let mut result = try_native_cut(video_path);
if let Ok(mut r) = result {
r.add_metadata("cut", "ffmpeg_native", uuid);
let json = serde_json::to_string_pretty(&r)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = uuid.unwrap_or("").to_string();
let file_path = video_path.to_string();
let file_name = std::path::Path::new(video_path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
crate::core::json_formatter::write_file_standard(
&r,
output_path,
2,
"cut",
"ffmpeg_native",
"1.0.0",
&file_uuid,
&file_path,
&file_name,
).with_context(|| format!("Failed to write {:?}", output_path))?;
return Ok(r);
}
// Fallback: Python scenedetect
tracing::warn!("[CUT] Native impl failed, falling back to Python");
// Log the real reason the native impl failed (silent fallback hides root causes)
let native_err = result.err().unwrap_or_else(|| anyhow::anyhow!("unknown error"));
tracing::warn!(
"[CUT] Native impl failed, falling back to Python: {:#}",
native_err
);
let executor = PythonExecutor::new()?;
let script_path = executor.script_path("cut/cut_processor.py");
if !script_path.exists() {
let mut empty_result = CutResult {
metadata: None,
frame_count: 0,
fps: 0.0,
scenes: vec![],
};
empty_result.add_metadata("cut", "none", uuid);
let json = serde_json::to_string_pretty(&empty_result)?;
std::fs::write(output_path, &json)
.with_context(|| format!("Failed to write {:?}", output_path))?;
return Ok(empty_result);
// Missing fallback script must be a hard error — writing an empty
// result (fps=0) silently fails downstream verification and hides
// the real cause from the pipeline.
anyhow::bail!(
"[CUT] Native scene detection failed ({:#}) and Python fallback script not found: {:?}",
native_err,
script_path
);
}
executor
@@ -122,9 +143,24 @@ pub async fn process_cut(
// ── Native ffmpeg scene detection ─────────────────────────────────
/// Resolve the ffprobe/ffmpeg executable path.
/// Uses `FFPROBE_PATH` / `FFMPEG_PATH` env vars when set, falling back to the
/// Homebrew absolute path on Apple Silicon. Never rely on bare `Command::new`
/// name lookup — the worker's launchd environment may not resolve it.
fn ff_tool_path(env_var: &str, homebrew_default: &str) -> String {
if let Ok(p) = std::env::var(env_var) {
if !p.trim().is_empty() && std::path::Path::new(&p).exists() {
return p;
}
}
homebrew_default.to_string()
}
fn try_native_cut(video_path: &str) -> Result<CutResult> {
let ffprobe_path = ff_tool_path("FFPROBE_PATH", "/opt/homebrew/bin/ffprobe");
// Step 1: Get video info (fps, frame count)
let probe = Command::new("ffprobe")
let probe = Command::new(&ffprobe_path)
.args([
"-v",
"quiet",
@@ -162,7 +198,7 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
// Step 2: Use ffmpeg scene detection filter
// The `scene` filter computes the difference between consecutive frames
// and outputs when the difference exceeds the threshold (0.3 = medium sensitivity)
let scene_output = Command::new("ffprobe")
let scene_output = Command::new(&ffprobe_path)
.args([
"-v",
"quiet",
@@ -209,7 +245,6 @@ fn try_native_cut(video_path: &str) -> Result<CutResult> {
let mut prev_time = 0.0;
let mut prev_frame: u64 = 0;
let round_time = |t: f64| (t * 1000.0).round() / 1000.0;
for (i, &cut_time) in scene_times.iter().enumerate() {
let end_frame = (cut_time * fps).round() as u64;
@@ -299,6 +334,26 @@ mod tests {
assert!(parse_fraction("1/0").is_none());
}
/// Reproduces the launchd-worker failure mode seen on 200: PATH without
/// /opt/homebrew/bin made `Command::new("ffprobe")` fail with ENOENT and
/// cut fall back to an empty result (fps=0 → verification failure).
/// Native cut must succeed by resolving ffprobe via FFPROBE_PATH / absolute path.
#[test]
fn test_native_cut_without_homebrew_in_path() {
let video = std::env::var("MOMENTRY_TEST_VIDEO")
.unwrap_or_else(|_| "/Users/accusys/Movies/test/Charade_YouTube_24fps.mp4".to_string());
if !std::path::Path::new(&video).exists() {
return; // test video absent (e.g. CI) — skip
}
let old_path = std::env::var("PATH").unwrap_or_default();
std::env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
let result = try_native_cut(&video);
std::env::set_var("PATH", old_path);
let r = result.expect("native cut must succeed without homebrew in PATH");
assert!(r.fps > 0.0, "fps must be positive, got {}", r.fps);
assert!(r.frame_count > 0, "frame_count must be positive");
}
#[test]
fn test_cut_result_serialization() {
let result = CutResult {
+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);
+128 -17
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,9 +116,71 @@ 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<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// Strip embeddings before saving to disk - they're already in Qdrant
// This saves ~50% disk space (512 floats * 4 bytes per face)
let mut light = self.clone();
for frame in &mut light.frames {
for face in &mut frame.faces {
face.embedding = None;
}
}
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "face".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "swift_face".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
&light,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face.json")?;
Ok(())
}
@@ -214,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!(
@@ -274,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![
@@ -360,12 +439,13 @@ pub async fn process_face(
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
}
result.ensure_face_ids();
result.save_to_file(output_path)?;
tracing::info!(
@@ -415,12 +495,13 @@ pub async fn process_face(
// Execute face tracking
tracing::info!("[FACE] Starting face tracking");
use crate::core::processor::face_tracker::track_faces;
if let Err(e) = track_faces(&mut result, 0.3, 0.7, 100.0, true, None) {
if let Err(e) = track_faces(&mut result, 0.3, 0.8, 100.0, true, None) {
tracing::warn!("[FACE] Face tracking failed: {}", e);
} else {
tracing::info!("[FACE] Face tracking completed successfully");
}
result.ensure_face_ids();
result.save_to_file(output_path)?;
tracing::info!(
@@ -495,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)
@@ -527,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 {
@@ -576,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 {
@@ -620,6 +715,10 @@ mod tests {
y: 100,
width: 50,
height: 60,
x2: 150,
y2: 160,
center_x: 125,
center_y: 130,
confidence: 0.95,
capture_quality: Some(0.9),
embedding: Some(vec![0.1, 0.2, 0.3]),
@@ -724,6 +823,10 @@ mod tests {
y: 0,
width: 10,
height: 10,
x2: 10,
y2: 10,
center_x: 5,
center_y: 5,
confidence: 0.5,
capture_quality: None,
embedding: None,
@@ -746,6 +849,10 @@ mod tests {
y: 200,
width: 50,
height: 60,
x2: 150,
y2: 260,
center_x: 125,
center_y: 230,
confidence: 0.95,
capture_quality: Some(0.8),
embedding: Some(vec![0.1; 512]),
@@ -832,6 +939,10 @@ pub async fn store_face_embeddings_to_qdrant(
return Ok(0);
}
// Self-heal: clean installs start with an empty Qdrant, so the `_faces`
// collection may not exist yet. Create it (512D facenet) before upsert.
qdrant.ensure_collection("_faces", 512).await?;
// Delete old points for this file
let filter = serde_json::json!({
"must": [{
+42 -6
View File
@@ -13,7 +13,9 @@ pub struct FaceClusterResult {
#[serde(default)]
pub file_uuid: Option<String>,
pub status: String,
#[serde(default)]
pub stats: ClusterStats,
#[serde(default)]
pub clusters: Vec<FaceClusterInfo>,
#[serde(default)]
pub unassigned_traces: Vec<i32>,
@@ -115,8 +117,36 @@ impl FaceClusterResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_cluster.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.file_uuid.clone().unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = "face_cluster".to_string();
let processor_tool = "face_cluster".to_string();
let processor_version = "1.0.0".to_string();
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face_cluster.json")?;
Ok(())
}
}
@@ -129,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(),
@@ -147,8 +180,11 @@ pub async fn process_face_cluster(
});
}
// Build args with --threshold (default 0.85 to correctly separate male/female faces)
let threshold = similarity_threshold.unwrap_or(0.85);
// Build args with --threshold (default 0.65 similarity → 0.35 distance)
// Lower distance threshold = more permissive (merge more similar faces)
// 0.15 distance was too strict, causing over-segmentation (7 persons instead of 2)
// 0.35 distance correctly gives 2 persons for test video
let threshold = similarity_threshold.unwrap_or(0.65);
let distance = 1.0 - threshold;
let threshold_str = format!("{:.4}", distance);
let mut args = vec![
+31 -3
View File
@@ -143,8 +143,36 @@ impl FaceTrackingResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write face_traced.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.file_uuid.clone().unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = "face_trace".to_string();
let processor_tool = "face_trace".to_string();
let processor_version = "1.0.0".to_string();
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write face_traced.json")?;
Ok(())
}
}
@@ -276,7 +304,7 @@ fn match_faces(
}
}
if best_prev_idx >= 0 && best_iou > 0.5 {
if best_prev_idx >= 0 && best_iou > iou_threshold {
trace_ids[curr_idx] = previous_trace_ids[best_prev_idx as usize];
used_prev.insert(best_prev_idx as usize);
}
+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)
}
+1
View File
@@ -330,6 +330,7 @@ pub async fn generate_scene_meta(
let out_path = Path::new(crate::core::config::OUTPUT_DIR.as_str())
.join(format!("{}.scene_meta.json", file_uuid));
let json_str = serde_json::to_string_pretty(&meta)?;
let json_str = crate::core::json_debug::append_debug_footer(json_str, &out_path);
tokio::fs::write(&out_path, json_str)
.await
.context("Failed to write scene_meta.json")?;
+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;
+74 -2
View File
@@ -53,8 +53,48 @@ impl OcrResult {
}
pub fn save_to_file(&self, path: &str) -> Result<()> {
crate::core::json_formatter::write_file_pretty_rounded(self, path, 2)
.context("Failed to write ocr.json")?;
self.save_to_file_with_source(path, None, None)
}
pub fn save_to_file_with_source(
&self,
path: &str,
file_path: Option<&str>,
file_name: Option<&str>,
) -> Result<()> {
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = self.metadata.as_ref()
.and_then(|m| m.source.as_ref())
.map(|s| s.file_uuid.clone())
.unwrap_or_default();
let file_path = file_path.unwrap_or("").to_string();
let file_name = file_name.unwrap_or("").to_string();
let processor_name = self.metadata.as_ref()
.map(|m| m.processor.name.clone())
.unwrap_or_else(|| "ocr".to_string());
let processor_tool = self.metadata.as_ref()
.map(|m| m.processor.tool.clone())
.unwrap_or_else(|| "swift_ocr".to_string());
let processor_version = self.metadata.as_ref()
.map(|m| m.processor.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
crate::core::json_formatter::write_file_standard(
self,
path,
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write ocr.json")?;
Ok(())
}
}
@@ -286,6 +326,38 @@ pub async fn process_ocr(
args.push("--uuid".to_string());
args.push(u.to_string());
}
// Calculate sample-interval for ~8Hz sampling
// For 60fps video: 60/8 = 7.5 → 8
// For 30fps video: 30/8 = 3.75 → 4
if let Some(frame_list) = frames {
if !frame_list.is_empty() {
// Estimate fps from frame indices (assuming they're roughly evenly spaced)
let first_frame = frame_list[0];
let last_frame = frame_list[frame_list.len() - 1];
let frame_span = (last_frame - first_frame) as f64;
let sample_count = frame_list.len() as f64;
if frame_span > 0.0 && sample_count > 1.0 {
// Estimated fps based on the sampling pattern
// For 8Hz sampling over the video duration
let estimated_interval = (frame_span / (sample_count - 1.0)).round() as i32;
if estimated_interval > 0 {
args.push("--sample-interval".to_string());
args.push(estimated_interval.to_string());
tracing::info!("[OCR] Using sample-interval={} for ~8Hz sampling", estimated_interval);
}
}
}
} else {
// Default to interval=8 for ~8Hz sampling at 60fps
args.push("--sample-interval".to_string());
args.push("8".to_string());
}
// Always use accurate recognition level
args.push("--recognition-level".to_string());
args.push("accurate".to_string());
let output = tokio::process::Command::new(swift_ocr_path)
.args(&args)
+325 -166
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;
@@ -378,10 +401,33 @@ impl SceneVlmProcessor {
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")?;
// 使用標準化輸出格式(含 _meta 和 _debug)
let file_uuid = profile.file_uuid.clone();
// 從 processor 資訊取得工具名稱
let processor_name = "scene_vlm".to_string();
let processor_tool = profile.processor.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| "scene_vlm".to_string());
let processor_version = profile.processor.as_ref()
.map(|p| p.version.clone())
.unwrap_or_else(|| "1.0.0".to_string());
// file_path 和 file_name 需要從外部傳入,這裡用預設值
let file_path = "".to_string();
let file_name = "".to_string();
crate::core::json_formatter::write_file_standard(
profile,
&path.to_string_lossy(),
2,
&processor_name,
&processor_tool,
&processor_version,
&file_uuid,
&file_path,
&file_name,
).context("Failed to write scenes.json")?;
Ok(())
}
@@ -577,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();
@@ -600,6 +677,55 @@ Rules:
.collect()
}
/// Resize image using ffmpeg to reduce VLM API payload size
fn resize_image_for_vlm(image_path: &std::path::Path) -> Result<Vec<u8>> {
use std::process::Command;
// Check if ffmpeg is available
let ffmpeg_path = crate::core::admin_config::get_ffmpeg_path();
// Create temp file for resized image
let temp_dir = std::env::temp_dir();
let temp_path = temp_dir.join(format!("scene_vlm_resized_{}.jpg", std::process::id()));
// Use ffmpeg to resize to max 512x512 while maintaining aspect ratio
let output = Command::new(&ffmpeg_path)
.args([
"-y",
"-i", image_path.to_str().unwrap_or(""),
"-vf", "scale=min(512\\,iw):min(512\\,ih):force_original_aspect_ratio=decrease",
"-q:v", "80",
"-update", "1",
temp_path.to_str().unwrap_or(""),
])
.output()
.with_context(|| format!("Failed to execute ffmpeg for image resize: {:?}", image_path))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::warn!("[Scene VLM] ffmpeg resize failed: {}", stderr);
// Fallback: return original image
return std::fs::read(image_path)
.with_context(|| format!("Failed to read original image: {:?}", image_path));
}
// Read resized image
let resized_bytes = std::fs::read(&temp_path)
.with_context(|| format!("Failed to read resized image: {:?}", temp_path))?;
// Clean up temp file
let _ = std::fs::remove_file(&temp_path);
tracing::info!(
"[Scene VLM] Image resized: {} bytes -> {} bytes",
image_path.metadata().map(|m| m.len()).unwrap_or(0),
resized_bytes.len()
);
Ok(resized_bytes)
}
/// Call VLM API to generate structured scene info.
/// Returns (english_description, objects, bilingual_tags).
pub async fn generate_scene_description(
@@ -609,10 +735,15 @@ Rules:
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))?;
// Read and resize image for VLM API (max 512x512 to avoid connection issues)
let jpeg_bytes = Self::resize_image_for_vlm(image_path)
.with_context(|| format!("Failed to process image: {:?}", image_path))?;
let base64_img = BASE64.encode(&jpeg_bytes);
tracing::debug!(
"[Scene VLM] Image encoded: {} bytes base64",
base64_img.len()
);
// VLM API config
let vlm_url = crate::core::config::llm::VISION_URL.clone();
@@ -644,9 +775,11 @@ Rules:
}
]
}],
"max_tokens": 1024,
"max_tokens": 4096,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
"chat_template_kwargs": {"enable_thinking": false},
"reasoning": false,
"thinking": false
});
let client = reqwest::Client::builder()
@@ -677,18 +810,33 @@ 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")?;
// Try content first, then fallback to reasoning_content (for Gemma models)
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"),
None => {
// Fallback to reasoning_content for Gemma models
match message
.get("reasoning_content")
.and_then(|c| c.as_str())
.filter(|s| !s.trim().is_empty())
{
Some(s) => {
tracing::info!("[Scene VLM] Using reasoning_content as fallback");
s.trim().to_string()
},
None => anyhow::bail!("VLM returned empty content and reasoning_content"),
}
}
};
tracing::debug!(
@@ -734,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(())
}
}
+1
View File
@@ -1590,6 +1590,7 @@ async fn build_face_track_nodes_from_qdrant(
&serde_json::to_value(&trace_profile).unwrap_or_default(),
))
{
let json = crate::core::json_debug::append_debug_footer(json, &tp_path);
let _ = std::fs::write(&tp_path, json);
if tp_path.exists() {
tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid);
+2 -2
View File
@@ -259,8 +259,8 @@ impl ToolSelector {
}
}
("asrx", "rust") => {
// Future: Rust ASRX implementation
executor.rust_binary_path("rust_asrx")
// Full ASR + diarization with whisper + ECAPA
executor.rust_binary_path("rust_asr_asrx")
}
("asrx", "python") => {
let script = executor.script_path("asrx_processor.py");
+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())
}
+21
View File
@@ -33,6 +33,27 @@ pub async fn sync_trace_label(
qdrant_points_count: 0,
};
// Face-groups normalization (V1.0 §7 G4): an already-grouped trace must
// not have its caption overwritten by an auto cluster label (e.g.
// "Person_N" from a re-run). Mirror the owning group's name instead.
let new_label: String = {
let tp = schema::table_name("trace_profiles");
let fg = schema::table_name("face_groups");
let group_name: Option<String> = sqlx::query_scalar(&format!(
"SELECT {fg}.name FROM {fg} JOIN {tp} ON {tp}.group_id = {fg}.id \
AND {tp}.file_uuid = {fg}.file_uuid \
WHERE {tp}.file_uuid = $1 AND {tp}.trace_id = $2"
))
.bind(file_uuid)
.bind(trace_id)
.fetch_optional(pool)
.await
.ok()
.flatten();
group_name.unwrap_or_else(|| new_label.to_string())
};
let new_label: &str = new_label.as_str();
// 1. 更新 tkg_nodes.label
match update_tkg_label(pool, file_uuid, trace_id, new_label).await {
Ok(rows) => {
+19 -10
View File
@@ -38,9 +38,15 @@ impl VLMClient {
.map_err(|e| VLMError::ImageReadFailed(image_path.to_string(), e))?;
let image_base64 = general_purpose::STANDARD.encode(&image_data);
// 2. 构建请求
// 2. 解析路由(admin config 優先 → env → 預設),並取得備援 endpoint
let (base_url, model, fallbacks) =
crate::core::llm::function_calling::resolve_llm_endpoint("vlm")
.await
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
// 3. 构建请求
let request = serde_json::json!({
"model": self.model,
"model": model,
"messages": [
{
"role": "user",
@@ -62,15 +68,18 @@ impl VLMClient {
"temperature": 0.1
});
// 3. 调用 API
let response = self
.http_client
.post(&self.base_url)
.json(&request)
.send()
.await?;
// 4. 调用 API(主 endpoint 失敗時依序 fallback 到備援實例)
let response =
crate::core::llm::function_calling::post_llm_with_fallback(
&base_url,
&fallbacks,
&request,
120,
)
.await
.map_err(|e| VLMError::WorkerError(e.to_string()))?;
// 4. 检查响应状态
// 5. 检查响应状态
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
+2 -3
View File
@@ -10,10 +10,10 @@ pub mod watcher;
pub mod worker;
pub use core::cache::{keys, MongoCache, RedisCache};
pub use core::cache::{keys, RedisCache};
pub use core::chunk::{Chunk, ChunkSplitter, ChunkType};
pub use core::db::{
Database, MongoDb, PostgresDb, QdrantDb, RedisClient, RedisDb, VectorPayload, VideoRecord,
Database, PostgresDb, QdrantDb, RedisClient, RedisDb, VectorPayload, VideoRecord,
VideoStatus,
};
pub use core::embedding::Embedder;
@@ -26,4 +26,3 @@ pub use core::storage::file_manager::FileManager;
pub use core::storage::output_dir::OutputDir;
pub use core::storage::uuid;
pub use core::thumbnail::{ThumbnailExtractor, ThumbnailResult};
pub use ui::progress::{ProcessorType, ProgressState, ProgressUi};
+1 -1
View File
@@ -404,7 +404,7 @@ async fn handle_worker(
use momentry_core::core::config::REDIS_KEY_PREFIX;
let redis_url = std::env::var("REDIS_URL")
.unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
.unwrap_or_else(|_| momentry_core::core::config::REDIS_URL.clone());
let health_checker = RedisHealthChecker::new(redis_url, 86400);
println!("Running Redis health check on startup...");
+30 -1
View File
@@ -563,9 +563,38 @@ pub fn verify_file(file_uuid: &str) -> FileVerificationReport {
/// Legacy verification function (backward compatible)
pub fn verify_output(processor: &ProcessorType, file_uuid: &str) -> VerificationResult {
let output_dir = OUTPUT_DIR.as_str();
verify_output_in_dir(processor, file_uuid, output_dir)
}
/// Verification with explicit output directory (per-library aware).
/// Falls back to the global OUTPUT_DIR and the demo subdirectory if the
/// primary path does not exist, so per-library outputs verify correctly.
pub fn verify_output_in_dir(
processor: &ProcessorType,
file_uuid: &str,
output_dir: &str,
) -> VerificationResult {
let proc_name = processor.as_str();
let filename = format!("{}.{}.json", file_uuid, proc_name);
let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(&filename);
// Candidate locations: explicit dir → global OUTPUT_DIR → OUTPUT_DIR/demo
let base = output_dir.trim_end_matches('/');
let global = OUTPUT_DIR.as_str().trim_end_matches('/');
let candidates = if base == global {
vec![
PathBuf::from(base),
PathBuf::from(format!("{}/demo", global)),
]
} else {
vec![PathBuf::from(base), PathBuf::from(global)]
};
let output_path = candidates
.iter()
.map(|d| d.join(&filename))
.find(|p| p.exists())
.unwrap_or_else(|| PathBuf::from(base).join(&filename));
if !output_path.exists() {
return VerificationResult::fail(proc_name, file_uuid, "output file not found");
+1260 -143
View File
File diff suppressed because it is too large Load Diff

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