From 3d13a06bd95784dc06b8c4502ffb6aad6db36cc3 Mon Sep 17 00:00:00 2001 From: Accusys Date: Wed, 5 Aug 2026 00:13:50 +0800 Subject: [PATCH] feat: face fix deployment + trace_* regeneration + executor stderr filter fix - swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64 - trace_* directories regenerated for KOBA (37 traces, start_frame 5307) - executor.rs: stderr filter now logs all non-empty stderr (was discarding) - VAD not skippable in ASRX (main_fixed.py Step 2 always runs) - Step 2.5 sentence boundary refinement added - Cluster agent async endpoints + similarity transparency - Keyword search: relationship text extraction, priority ordering - Face fix handoff doc for Studio team --- Dedicatoria-Scenes.csv | 3 + ...ney - 1925 - Alice the Toreador-Scenes.csv | 74 +++ .../24_studio_trace_profile_read_write_bug.md | 138 ++++++ docs_v1.0/DESIGN/SyncStatusCompletedLogic.md | 96 ++++ .../2026-07-31_studio_face_group_api_gaps.md | 39 +- ...026-08-01_studio_face_group_thumb_fixes.md | 64 +++ .../2026-08-01_studio_fs_player_fixes.md | 95 ++++ .../2026-08-02_studio_fixes_complete.md | 142 ++++++ .../2026-08-04_face_fix_handoff.md | 138 ++++++ run-worker-3002.sh | 8 +- scripts/asrx_processor.py | 14 +- scripts/asrx_self/main_fixed.py | 127 ++++- scripts/check_file_health.py | 241 +++++++++ scripts/checksums.sha256 | 1 + scripts/cut_processor.py | 234 +++++++-- scripts/face_cluster_threshold_sweep.py | 309 ++++++++++++ scripts/face_clustering_processor.py | 208 ++++++-- scripts/load_trace_profiles.py | 21 +- scripts/store_traced_faces.py | 12 +- scripts/swift_processors/swift_face.swift | 10 +- scripts/trace_vlm_caption.py | 29 +- scripts/utils/qdrant_faces.py | 460 +++++++++--------- src/api/cluster_agent.rs | 396 ++++++++++++--- src/api/media_api.rs | 57 ++- src/api/profile.rs | 49 +- src/api/scan.rs | 63 ++- src/api/search.rs | 35 +- src/api/universal_search.rs | 78 ++- src/bin/fix_chunks.rs | 2 +- src/bin/vectorize_missing.rs | 162 +++--- src/core/agent/tools.rs | 152 +++--- src/core/db/postgres_db.rs | 97 +++- src/core/file_lifecycle.rs | 172 ++++--- src/core/file_profile.rs | 6 + src/core/ingestion.rs | 22 +- src/core/processor/executor.rs | 200 ++++++++ src/core/processor/face_clustering.rs | 28 +- src/core/processor/ocr.rs | 3 +- src/core/processor/tkg.rs | 185 ++++++- src/core/proxy.rs | 43 +- src/worker/job_worker.rs | 11 +- src/worker/processor.rs | 1 + 42 files changed, 3447 insertions(+), 778 deletions(-) create mode 100644 Dedicatoria-Scenes.csv create mode 100644 Walt Disney - 1925 - Alice the Toreador-Scenes.csv create mode 100644 docs_v1.0/API_WORKSPACE/modules/24_studio_trace_profile_read_write_bug.md create mode 100644 docs_v1.0/DESIGN/SyncStatusCompletedLogic.md create mode 100644 docs_v1.0/M4_workspace/2026-08-01_studio_face_group_thumb_fixes.md create mode 100644 docs_v1.0/M4_workspace/2026-08-01_studio_fs_player_fixes.md create mode 100644 docs_v1.0/M4_workspace/2026-08-02_studio_fixes_complete.md create mode 100644 docs_v1.0/M4_workspace/2026-08-04_face_fix_handoff.md create mode 100644 scripts/check_file_health.py create mode 100755 scripts/face_cluster_threshold_sweep.py diff --git a/Dedicatoria-Scenes.csv b/Dedicatoria-Scenes.csv new file mode 100644 index 00000000..4edcb9b6 --- /dev/null +++ b/Dedicatoria-Scenes.csv @@ -0,0 +1,3 @@ + +Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds) +1,1,00:00:00.000,0.000,2800,00:01:33.333,93.333,2800,00:01:33.333,93.333 diff --git a/Walt Disney - 1925 - Alice the Toreador-Scenes.csv b/Walt Disney - 1925 - Alice the Toreador-Scenes.csv new file mode 100644 index 00000000..500970ea --- /dev/null +++ b/Walt Disney - 1925 - Alice the Toreador-Scenes.csv @@ -0,0 +1,74 @@ +Timecode List:,00:00:05.239,00:00:08.075,00:00:21.822,00:00:32.032,00:00:33.400,00:00:35.002,00:00:37.070,00:00:42.209,00:00:44.411,00:00:48.382,00:00:51.318,00:01:03.497,00:01:16.109,00:01:17.911,00:01:20.314,00:01:38.165,00:01:42.536,00:01:45.672,00:01:48.442,00:02:01.655,00:02:10.631,00:02:18.805,00:02:19.506,00:02:21.742,00:02:23.110,00:02:25.045,00:02:39.660,00:02:40.327,00:02:43.330,00:02:50.037,00:02:52.406,00:02:59.446,00:03:10.123,00:03:13.193,00:03:20.534,00:03:33.547,00:03:38.151,00:03:48.161,00:03:49.563,00:03:51.898,00:04:02.042,00:04:10.951,00:04:18.191,00:04:29.069,00:04:30.203,00:04:46.319,00:04:49.623,00:04:53.160,00:04:56.630,00:05:02.702,00:05:17.284,00:05:51.284,00:05:57.424,00:05:59.092,00:06:02.696,00:06:04.831,00:06:07.767,00:06:11.538,00:06:13.273,00:06:36.129,00:06:39.032,00:06:40.800,00:06:44.337,00:06:46.906,00:06:56.283,00:07:01.288,00:07:12.432,00:07:14.301,00:07:15.835,00:07:23.109,00:07:30.684 +Scene Number,Start Frame,Start Timecode,Start Time (seconds),End Frame,End Timecode,End Time (seconds),Length (frames),Length (timecode),Length (seconds) +1,1,00:00:00.000,0.000,157,00:00:05.239,5.239,157,00:00:05.239,5.239 +2,158,00:00:05.239,5.239,242,00:00:08.075,8.075,85,00:00:02.836,2.836 +3,243,00:00:08.075,8.075,654,00:00:21.822,21.822,412,00:00:13.747,13.747 +4,655,00:00:21.822,21.822,960,00:00:32.032,32.032,306,00:00:10.210,10.210 +5,961,00:00:32.032,32.032,1001,00:00:33.400,33.400,41,00:00:01.368,1.368 +6,1002,00:00:33.400,33.400,1049,00:00:35.002,35.002,48,00:00:01.602,1.602 +7,1050,00:00:35.002,35.002,1111,00:00:37.070,37.070,62,00:00:02.069,2.069 +8,1112,00:00:37.070,37.070,1265,00:00:42.209,42.209,154,00:00:05.138,5.138 +9,1266,00:00:42.209,42.209,1331,00:00:44.411,44.411,66,00:00:02.202,2.202 +10,1332,00:00:44.411,44.411,1450,00:00:48.382,48.382,119,00:00:03.971,3.971 +11,1451,00:00:48.382,48.382,1538,00:00:51.318,51.318,88,00:00:02.936,2.936 +12,1539,00:00:51.318,51.318,1903,00:01:03.497,63.497,365,00:00:12.179,12.179 +13,1904,00:01:03.497,63.497,2281,00:01:16.109,76.109,378,00:00:12.613,12.613 +14,2282,00:01:16.109,76.109,2335,00:01:17.911,77.911,54,00:00:01.802,1.802 +15,2336,00:01:17.911,77.911,2407,00:01:20.314,80.314,72,00:00:02.402,2.402 +16,2408,00:01:20.314,80.314,2942,00:01:38.165,98.165,535,00:00:17.851,17.851 +17,2943,00:01:38.165,98.165,3073,00:01:42.536,102.536,131,00:00:04.371,4.371 +18,3074,00:01:42.536,102.536,3167,00:01:45.672,105.672,94,00:00:03.136,3.136 +19,3168,00:01:45.672,105.672,3250,00:01:48.442,108.442,83,00:00:02.769,2.769 +20,3251,00:01:48.442,108.442,3646,00:02:01.655,121.655,396,00:00:13.213,13.213 +21,3647,00:02:01.655,121.655,3915,00:02:10.631,130.631,269,00:00:08.976,8.976 +22,3916,00:02:10.631,130.631,4160,00:02:18.805,138.805,245,00:00:08.175,8.175 +23,4161,00:02:18.805,138.805,4181,00:02:19.506,139.506,21,00:00:00.701,0.701 +24,4182,00:02:19.506,139.506,4248,00:02:21.742,141.742,67,00:00:02.236,2.236 +25,4249,00:02:21.742,141.742,4289,00:02:23.110,143.110,41,00:00:01.368,1.368 +26,4290,00:02:23.110,143.110,4347,00:02:25.045,145.045,58,00:00:01.935,1.935 +27,4348,00:02:25.045,145.045,4785,00:02:39.660,159.660,438,00:00:14.615,14.615 +28,4786,00:02:39.660,159.660,4805,00:02:40.327,160.327,20,00:00:00.667,0.667 +29,4806,00:02:40.327,160.327,4895,00:02:43.330,163.330,90,00:00:03.003,3.003 +30,4896,00:02:43.330,163.330,5096,00:02:50.037,170.037,201,00:00:06.707,6.707 +31,5097,00:02:50.037,170.037,5167,00:02:52.406,172.406,71,00:00:02.369,2.369 +32,5168,00:02:52.406,172.406,5378,00:02:59.446,179.446,211,00:00:07.040,7.040 +33,5379,00:02:59.446,179.446,5698,00:03:10.123,190.123,320,00:00:10.677,10.677 +34,5699,00:03:10.123,190.123,5790,00:03:13.193,193.193,92,00:00:03.070,3.070 +35,5791,00:03:13.193,193.193,6010,00:03:20.534,200.534,220,00:00:07.341,7.341 +36,6011,00:03:20.534,200.534,6400,00:03:33.547,213.547,390,00:00:13.013,13.013 +37,6401,00:03:33.547,213.547,6538,00:03:38.151,218.151,138,00:00:04.605,4.605 +38,6539,00:03:38.151,218.151,6838,00:03:48.161,228.161,300,00:00:10.010,10.010 +39,6839,00:03:48.161,228.161,6880,00:03:49.563,229.563,42,00:00:01.401,1.401 +40,6881,00:03:49.563,229.563,6950,00:03:51.898,231.898,70,00:00:02.336,2.336 +41,6951,00:03:51.898,231.898,7254,00:04:02.042,242.042,304,00:00:10.143,10.143 +42,7255,00:04:02.042,242.042,7521,00:04:10.951,250.951,267,00:00:08.909,8.909 +43,7522,00:04:10.951,250.951,7738,00:04:18.191,258.191,217,00:00:07.241,7.241 +44,7739,00:04:18.191,258.191,8064,00:04:29.069,269.069,326,00:00:10.878,10.878 +45,8065,00:04:29.069,269.069,8098,00:04:30.203,270.203,34,00:00:01.134,1.134 +46,8099,00:04:30.203,270.203,8581,00:04:46.319,286.319,483,00:00:16.116,16.116 +47,8582,00:04:46.319,286.319,8680,00:04:49.623,289.623,99,00:00:03.303,3.303 +48,8681,00:04:49.623,289.623,8786,00:04:53.160,293.160,106,00:00:03.537,3.537 +49,8787,00:04:53.160,293.160,8890,00:04:56.630,296.630,104,00:00:03.470,3.470 +50,8891,00:04:56.630,296.630,9072,00:05:02.702,302.702,182,00:00:06.073,6.073 +51,9073,00:05:02.702,302.702,9509,00:05:17.284,317.284,437,00:00:14.581,14.581 +52,9510,00:05:17.284,317.284,10528,00:05:51.284,351.284,1019,00:00:34.001,34.001 +53,10529,00:05:51.284,351.284,10712,00:05:57.424,357.424,184,00:00:06.139,6.139 +54,10713,00:05:57.424,357.424,10762,00:05:59.092,359.092,50,00:00:01.668,1.668 +55,10763,00:05:59.092,359.092,10870,00:06:02.696,362.696,108,00:00:03.604,3.604 +56,10871,00:06:02.696,362.696,10934,00:06:04.831,364.831,64,00:00:02.135,2.135 +57,10935,00:06:04.831,364.831,11022,00:06:07.767,367.767,88,00:00:02.936,2.936 +58,11023,00:06:07.767,367.767,11135,00:06:11.538,371.538,113,00:00:03.770,3.770 +59,11136,00:06:11.538,371.538,11187,00:06:13.273,373.273,52,00:00:01.735,1.735 +60,11188,00:06:13.273,373.273,11872,00:06:36.129,396.129,685,00:00:22.856,22.856 +61,11873,00:06:36.129,396.129,11959,00:06:39.032,399.032,87,00:00:02.903,2.903 +62,11960,00:06:39.032,399.032,12012,00:06:40.800,400.800,53,00:00:01.768,1.768 +63,12013,00:06:40.800,400.800,12118,00:06:44.337,404.337,106,00:00:03.537,3.537 +64,12119,00:06:44.337,404.337,12195,00:06:46.906,406.906,77,00:00:02.569,2.569 +65,12196,00:06:46.906,406.906,12476,00:06:56.283,416.283,281,00:00:09.376,9.376 +66,12477,00:06:56.283,416.283,12626,00:07:01.288,421.288,150,00:00:05.005,5.005 +67,12627,00:07:01.288,421.288,12960,00:07:12.432,432.432,334,00:00:11.144,11.144 +68,12961,00:07:12.432,432.432,13016,00:07:14.301,434.301,56,00:00:01.869,1.869 +69,13017,00:07:14.301,434.301,13062,00:07:15.835,435.835,46,00:00:01.535,1.535 +70,13063,00:07:15.835,435.835,13280,00:07:23.109,443.109,218,00:00:07.274,7.274 +71,13281,00:07:23.109,443.109,13507,00:07:30.684,450.684,227,00:00:07.574,7.574 +72,13508,00:07:30.684,450.684,14246,00:07:55.342,475.342,739,00:00:24.658,24.658 diff --git a/docs_v1.0/API_WORKSPACE/modules/24_studio_trace_profile_read_write_bug.md b/docs_v1.0/API_WORKSPACE/modules/24_studio_trace_profile_read_write_bug.md new file mode 100644 index 00000000..12f6ecf6 --- /dev/null +++ b/docs_v1.0/API_WORKSPACE/modules/24_studio_trace_profile_read_write_bug.md @@ -0,0 +1,138 @@ +# Studio Bug Report: `get_trace_profile` 讀寫不一致 + +**Date**: 2026-07-27 +**Author**: Studio Team +**Status**: 🔴 待修復 +**Priority**: High + +--- + +## 問題描述 + +Studio 前端 rename face group 後,離開再回來選同一個檔案,名稱變回舊的。 + +## 影響 + +使用者 rename 的變更無法持久顯示。雖然 `trace_profiles.name` 已更新,但 `get_trace_profile` API 回傳的是舊的 `tkg_nodes.label`,導致前端 `loadClusterNames()` 用舊名覆蓋新名。 + +--- + +## 測試驗證 + +### 1. Rename +```bash +curl -X PUT "http://localhost:3002/api/v1/trace-profile/group" \ + -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ + -d '{"file_uuid": "9cbeb112fcc5452e869755a539478061", "trace_ids": [1], "name": "SusanTest"}' +``` +回傳:`{"success": true, "updated_count": 1}` ✅ + +### 2. 讀取單筆 profile(❌ 仍是舊名) +```bash +GET /api/v1/trace-profile?file_uuid=...&trace_id=1 +``` +回傳:`{"name": "Person_0"}` ← **錯誤,應為 "SusanTest"** + +### 3. 讀取 face groups(✅ 是新名) +```bash +GET /api/v1/file/{uuid}/face-groups +``` +回傳:`{"name": "SusanTest", "trace_ids": [1]}` ← **正確** + +--- + +## 根因分析 + +### 寫入路徑(正確) +`PUT /api/v1/trace-profile/group` → `update_trace_profile_group_handler`(profile.rs:228): +```sql +UPDATE trace_profiles SET name = $1 WHERE file_uuid = $2 AND trace_id = $3 +``` +寫入 `trace_profiles.name` ✅ + +### 讀取路徑 — 單筆(❌ 錯誤) +`GET /api/v1/trace-profile` → `get_trace_profile_handler`(profile.rs:78-81): +```sql +SELECT label, external_id, properties FROM tkg_nodes +WHERE file_uuid = $1 AND node_type = 'face_track' + AND (external_id = $2 OR external_id = $3) +``` +讀取 `tkg_nodes.label`,**沒有 JOIN `trace_profiles`** ❌ + +### 讀取路徑 — 群組(✅ 正確) +`GET /api/v1/file/{uuid}/face-groups` → `get_face_groups_handler`(profile.rs:560-566): +```sql +SELECT COALESCE(tp.name, tn.label) as name, tn.properties +FROM tkg_nodes tn +LEFT JOIN trace_profiles tp ON tp.file_uuid = tn.file_uuid + AND tp.trace_id = (tn.properties->>'trace_id')::int +WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' +``` +使用 `COALESCE(tp.name, tn.label)`,優先取 `trace_profiles.name` ✅ + +--- + +## 前端影響流程 + +``` +User rename group → updateTraceProfileGroup() → PUT /trace-profile/group + → trace_profiles.name = "SusanTest" ✅ + +User refresh → loadClusterResults() → GET /face-groups + → cluster.name = "SusanTest" ✅ + → loadClusterNames() → GET /trace-profile + → profile.name = "Person_0" ❌ (tkg_nodes.label) + → c.name = profile.name → "Person_0" ❌ 覆蓋了新名 +``` + +--- + +## 建議修復 + +### 方案:改 `get_trace_profile_handler` 使用 JOIN + +```rust +pub async fn get_trace_profile_handler(...) { + let tkg_table = schema::table_name("tkg_nodes"); + let tp_table = schema::table_name("trace_profiles"); + + let row: Option<(String, String, serde_json::Value)> = sqlx::query_as(&format!( + "SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, tn.properties \ + FROM {} tn \ + LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \ + AND tp.trace_id = (tn.properties->>'trace_id')::int \ + WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \ + AND (tn.external_id = $2 OR tn.external_id = $3)", + tkg_table, tp_table + )) + .bind(¶ms.file_uuid) + .bind(&external_id_face) + .bind(&external_id_trace) + .fetch_optional(state.db.pool()) + .await?; + + let (name, _ext_id, properties) = row.ok_or(StatusCode::NOT_FOUND)?; + + Ok(Json(TraceProfile { + file_uuid: params.file_uuid, + trace_id: params.trace_id, + name, // 改為使用 JOIN 後的 name + // ... 其他欄位不變 + })) +} +``` + +### 一致性保證 + +| API | 讀取欄位 | 修復後 | +|-----|---------|--------| +| `PUT /trace-profile/group` | 寫入 `trace_profiles.name` | 不變 | +| `GET /trace-profile` | ~~`tkg_nodes.label`~~ → `COALESCE(tp.name, tn.label)` | ✅ 一致 | +| `GET /file/{uuid}/face-groups` | `COALESCE(tp.name, tn.label)` | 不變 | + +--- + +## 相關文件 +- `18_profile.md` — Profile API 文件 +- `19_people_api.md` — People API 文件 +- `23_studio_face_group_name_fix.md` — Studio face-groups JOIN 修復 diff --git a/docs_v1.0/DESIGN/SyncStatusCompletedLogic.md b/docs_v1.0/DESIGN/SyncStatusCompletedLogic.md new file mode 100644 index 00000000..9fa2f732 --- /dev/null +++ b/docs_v1.0/DESIGN/SyncStatusCompletedLogic.md @@ -0,0 +1,96 @@ +--- +title: Sync Status Completed Logic Fix +version: 1.0 +date: 2026-07-28 +author: Core Team +status: draft +--- + +# Sync Status "Completed" Logic Fix + +## Problem + +The `sync_file_status` endpoint (`POST /api/v1/file/:file_uuid/sync-status`) incorrectly returns `"completed"` status when some processor JSON files are missing. + +### Root Cause + +In `src/api/files.rs:1673-1753`, the `all_consistent` flag is only updated when `json_exists = true`: + +```rust +if json_exists { + any_json_exists = true; + // ... check consistency, set consistent ... + if !consistent { + all_consistent = false; // Only executed when JSON exists! + } +} +// When json_exists = false: consistent = false, but all_consistent stays true +``` + +This means if `asr.json` doesn't exist: +- `consistent = false` (initialized at line 1676) +- But the `if !consistent` block is never reached +- `all_consistent` remains `true` +- Status becomes `"completed"` instead of `"scanning"` + +## Design + +### Processor JSON Files (7 required) + +| Processor | Filename | Special Cases | +|-----------|----------|---------------| +| ASR | `{uuid}.asr.json` | `"status": "no_audio_track"` or `"silent_audio"` | +| ASRX | `{uuid}.asrx.json` | `"status": "no_audio_track"` | +| OCR | `{uuid}.ocr.json` | Always exists if processor ran | +| Pose | `{uuid}.pose.json` | Always exists if processor ran | +| CUT | `{uuid}.cut.json` | Always exists if processor ran | +| Face | `{uuid}.face.json` | `"status": "no_faces"` | +| Face Cluster | `{uuid}.face_cluster.json` | `"status": "no_faces"` or `"no_embeddings"` | + +**Key principle**: ALL processors produce their JSON files, even for special cases. The JSON file exists but may contain empty arrays or special status fields. + +### Status Determination Logic + +| Condition | Status | +|-----------|--------| +| All 7 JSONs exist AND all consistent AND has TKG edges | `agent_ready` | +| All 7 JSONs exist AND all consistent AND no TKG edges | `completed` | +| Any JSON exists (but not all, or not consistent) | `scanning` | +| No JSON exists | `registered` | + +### Fix + +Move the `all_consistent` update outside the `json_exists` block: + +```rust +for (name, filename) in &processors { + let path = ...; + let json_exists = path.exists(); + let mut consistent = false; + + if json_exists { + any_json_exists = true; + // ... check consistency, set consistent ... + } + + // MOVED HERE: JSON not existing = not consistent + if !consistent { + all_consistent = false; + } + + processor_status.insert(...); +} +``` + +## Impact + +- **API**: No change to response format +- **Behavior**: Files missing any JSON will show `"scanning"` instead of `"completed"` +- **Backward compat**: No breaking changes + +## Testing + +1. File with all 7 JSONs → `completed` or `agent_ready` +2. File with 6 JSONs (1 missing) → `scanning` +3. File with no JSONs → `registered` +4. Special case (no audio, no faces) → all JSONs exist with special status → `completed` diff --git a/docs_v1.0/M4_workspace/2026-07-31_studio_face_group_api_gaps.md b/docs_v1.0/M4_workspace/2026-07-31_studio_face_group_api_gaps.md index 89928174..495f505a 100644 --- a/docs_v1.0/M4_workspace/2026-07-31_studio_face_group_api_gaps.md +++ b/docs_v1.0/M4_workspace/2026-07-31_studio_face_group_api_gaps.md @@ -18,9 +18,13 @@ Core 完成 trace_profiles UPSERT 修復後(`2026-07-31_trace_profile_upsert_f | # | Studio 呼叫 | Core 端點 | 狀態 | |---|-------------|-----------|------| | 1 | `get_cluster_results` | `GET /api/v1/cluster-results?file_hash=` | ❌ 404 (Core 無此端點) | -| 2 | `get_identity_matches` | `GET /api/v1/identity-matches?file_hash=` | ❌ 404 (Core 無此端點) | +| 2 | `get_identity_matches` | `GET /api/v1/identity-matches?file_hash=` | ⏹️ **已不使用** (identity/TMDB 功能停用,僅殘留呼叫) | | 3 | `get_similar_face_groups` | `GET /api/v1/file/:file_uuid/face-groups/similar` | ⚠️ 逾時 (183K points 全量 scroll) | +> **2026-07-31 更新**:斷點 2 (identity-matches / TMDB) 確認**已不使用**。 +> identity 與 TMDB 功能已停用;Studio 端該呼叫是殘留程式碼, +> 404 時被 `try/catch` 吞掉,不影響任何流程,**不需處理**。 + --- ## 二、斷點 1:`cluster-results`(影響最大) @@ -107,35 +111,19 @@ Core 完全沒有 `cluster-results` 端點(`grep cluster-results src/` 無結 --- -## 三、斷點 2:`identity-matches` +## 三、斷點 2:`identity-matches`(⏹️ 已不使用,不需處理) -### Studio 端呼叫 +> **2026-07-31**:identity / TMDB 功能已停用。以下記錄僅供留存,**不需任何修改**。 -- `momentry_studio/src/api/index.ts:465-467` -```typescript -case 'get_identity_matches': { - return { url: `/api/v1/identity-matches?file_hash=${a.fileHash}`, method: 'GET' } -} -``` +### 殘留呼叫位置(僅供留存) -- `momentry_studio/src/views/PeopleView.vue:943-970`:抓 TMDB identity 建議, - 對每個 cluster 統計 trace → suggestion 的 `group_uuid` 映射,取最高頻者設為 - `c.tmdb_name` / `c.tmdb_uuid` / `c.tmdb_count`。 - -### Studio 預期回應格式(PeopleView.vue:945-946) - -```jsonc -{ - "suggestions": { - "12": { "group_uuid": "tmdb-xxx", "name": "Alice" }, // key = trace_id (string) - "34": { "group_uuid": "tmdb-xxx", "name": "Alice" } - } -} -``` +- `momentry_studio/src/api/index.ts:465-467` → `get_identity_matches` +- `momentry_studio/src/views/PeopleView.vue:943-970` → 抓 TMDB identity 建議 + 並設 `c.tmdb_name` / `c.tmdb_uuid` / `c.tmdb_count` ### Core 現況 -Core 無此端點。若無法提供,**影響有限**:Studio 已用 `try/catch` 包住 +Core 無此端點。Studio 已用 `try/catch` 包住 (line 970 `catch { /* no identity matches available */ }`), 404 時只是 TMDB 名稱建議不顯示,不阻斷 face group 流程。 @@ -186,7 +174,7 @@ Core 有端點(`src/api/profile.rs:1329`,handler `get_similar_group_handler` | B | Studio 改用 `GET /file/:file_uuid/face-groups` + 另行組 `frames[]` | Studio team | | C | 暫緩,僅記錄。cluster-results 404 時 face group 列表不顯示 | 維持現狀 | -`identity-matches` 影響最小(已 try/catch),`similar` 為效能問題需 Core 優化 scroll。 +`identity-matches` 已不使用(不需處理);`similar` 為效能問題需 Core 優化 scroll。 --- @@ -194,4 +182,5 @@ Core 有端點(`src/api/profile.rs:1329`,handler `get_similar_group_handler` | Version | Date | Author | Changes | |---------|------|--------|---------| +| 1.1 | 2026-07-31 | OpenCode | 標記斷點 2 (identity-matches/TMDB) 已不使用,不需處理 | | 1.0 | 2026-07-31 | OpenCode | Initial analysis report | diff --git a/docs_v1.0/M4_workspace/2026-08-01_studio_face_group_thumb_fixes.md b/docs_v1.0/M4_workspace/2026-08-01_studio_face_group_thumb_fixes.md new file mode 100644 index 00000000..52f126a7 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-08-01_studio_face_group_thumb_fixes.md @@ -0,0 +1,64 @@ +# Studio 修復文件:Face Group 縮圖載入優化 + +## 問題描述 + +Face Group 卡片縮圖載入緩慢,大量空缺。之前曾修復過但現在又變慢。 + +## 根因分析 + +`src/store.ts` 的 `loadTraceThumb` 使用舊 API: + +```js +const result = await apiCall('get_face_thumbnail', args) // ffmpeg crop,慢 +``` + +應改用 trace-thumb 端點直接讀取預先裁剪的 `key_face.jpg`: + +``` +/api/v1/trace-thumb/{file_uuid}/{trace_id} // 直接讀檔,~5ms +``` + +## 修復內容 + +**檔案:** `src/store.ts` + +**修改 `loadTraceThumb` 函數(約 line 588-610):** + +```js +export function loadTraceThumb(t: any) { + if (!t.file_uuid || t.trace_id === undefined || t.trace_id === null) return + const key = `${t.trace_id}-${t.file_uuid}-${t.best_face_id || 0}` + if (faceThumbsCache.value[key] || loadingFaceThumbs.has(key)) return + loadingFaceThumbs.add(key) + queueThumb(async () => { + try { + // 改用 trace-thumb 端點(直接讀 key_face.jpg,~5ms) + const url = `/api/v1/trace-thumb/${t.file_uuid}/${t.trace_id}` + const resp = await fetch(url) + if (resp.ok) { + const blob = await resp.blob() + const dataUrl = URL.createObjectURL(blob) + faceThumbsCache.value[key] = dataUrl + } + } catch (e) { + console.error('loadTraceThumb failed:', key, e) + } finally { + loadingFaceThumbs.delete(key) + } + }) +} +``` + +## 預期效果 + +| 指標 | 修改前 | 修改後 | +|------|--------|--------| +| 單張縮圖 | ~500ms (ffmpeg) | ~5ms (讀檔) | +| 133 張群組縮圖 | ~66s (排隊) | <1s (並行) | +| 空缺數量 | 大量 | 0 | + +## 驗證步驟 + +1. 打開 Charade 檔案的 People View +2. Face Group 卡片應立即顯示縮圖,無空缺 +3. Network tab 檢查 `/api/v1/trace-thumb/` 請求回應時間應 < 10ms diff --git a/docs_v1.0/M4_workspace/2026-08-01_studio_fs_player_fixes.md b/docs_v1.0/M4_workspace/2026-08-01_studio_fs_player_fixes.md new file mode 100644 index 00000000..555ee2c4 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-08-01_studio_fs_player_fixes.md @@ -0,0 +1,95 @@ +# Studio 修復文件 + +## 問題:FS Player Seek 位置錯誤 + +### 根因 +剪輯影片的 videoFps 偵測不準確(`getVideoPlaybackQuality().totalVideoFrames` 只反映已解碼幀數)。 + +### 檔案 +`src/components/VideoPlayer.vue` + +### 修改 onLoaded 函數(約 line 1196-1234) + +```js +async function onLoaded() { + const el = videoEl.value + if (!el) return + + // 優先順序: + // 1. Trace-derived fps ← 最準確(來自 trace 的 frame/sec 資料) + // 2. get_file_info.fps ← DB 儲存的實際 fps(已修正為 nb_frames/duration) + // 3. Clip 偵測 ← 最後手段(可能不準確) + const knownFps = resolveKnownFps() + if (knownFps >= 1) { + videoFps.value = knownFps + } else { + let fileFps = 0 + const fu = curFileUuid.value || props.fileUuid + if (fu && fu !== 'undefined') { + try { + const info: any = await apiCall('get_file_info', { uuid: fu }) + fileFps = Number(info?.fps) + } catch { /* fall back below */ } + } + if (fileFps >= 1) { + videoFps.value = fileFps + } else if (el.getVideoPlaybackQuality) { + // @ts-ignore - webkitVideoDecodedByteCount etc. are non-standard + const quality = el.getVideoPlaybackQuality() + if (quality.totalVideoFrames > 0 && el.duration > 0) { + videoFps.value = Math.round(quality.totalVideoFrames / el.duration) + } + } + } + + if (seekFrame.value !== null) { + el.currentTime = seekFrame.value / videoFps.value + } else { + el.currentTime = 0 + } + + el.play().catch(() => {}) +} +``` + +### 輔助函數 resolveKnownFps(trace-derived fps) + +```js +function resolveKnownFps(): number { + let t = props.allTraces[currentTraceIdx.value] + if (!t && playMode.value === 'segment') { + const s = props.mergedSegments[currentSegmentIdx.value] + t = props.allTraces[s?._startIdx] + } + if (!t) t = props.allTraces[0] + const tf = getTraceFps(t) + return tf >= 1 ? tf : 0 +} +``` + +### 輔助函數 getTraceFps(FS0-safe) + +```js +function getTraceFps(t: any): number { + if (!t) return 30 + const lf = t.last_frame !== undefined && t.last_frame !== null ? t.last_frame : 0 + const ff = t.first_frame !== undefined && t.first_frame !== null ? t.first_frame : 0 + const ls = t.last_sec !== undefined && t.last_sec !== null ? t.last_sec : 0 + const fs = t.first_sec !== undefined && t.first_sec !== null ? t.first_sec : 0 + const frameDiff = lf - ff + const secDiff = ls - fs + if (secDiff <= 0 || frameDiff <= 0) return 30 + return frameDiff / secDiff +} +``` + +### 核心修改 +- **優先順序正確**:Trace-derived fps(最準確)→ `get_file_info.fps`(DB 正確值)→ Clip 偵測(最後手段)。 +- **FS Player 播放 trace 時**使用 trace 本身的 fps(來自 trace 的 `first/last_frame` + `first/last_sec`)。 +- **完整影片播放時**使用 DB 的正確 fps。 +- **只有在以上都失敗時**才用 clip 偵測。 +- `getTraceFps` 改為 FS0-safe(顯式 `undefined/null` 檢查,取代 `||`,避免 trace_id 0 / frame 0 被當成 falsy)。 + +## 驗證 +- 打開 FS Player,Console 檢查 videoFps 應 ≈ 30 +- Seek 到第一幀,顯示 frame number 應與 Library 一致 diff --git a/docs_v1.0/M4_workspace/2026-08-02_studio_fixes_complete.md b/docs_v1.0/M4_workspace/2026-08-02_studio_fixes_complete.md new file mode 100644 index 00000000..69caeb5d --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-08-02_studio_fixes_complete.md @@ -0,0 +1,142 @@ +# Studio 配套修復文件 - 2026-08-02 + +## 概述 + +本文檔記錄 Studio 已實作的修復,以配合 Core API 的變更並解決已知問題。 + +--- + +## 修復 1: Face Group 縮圖載入優化 + +### 問題 +Face Group 卡片縮圖載入緩慢,大量空缺(Charade 133 groups 中 ~76% placeholder)。 + +### 根因 +阻塞式分頁抓取 + key 不一致導致 rep 縮圖無法命中快取,非單純端點速度問題。 + +### 實際實作(4 項) + +**1a. loadTraceThumb key 簡化** +- 檔案:`/Users/accusys/momentry_studio/src/store.ts:588-610` +- 修改:key 從 `${trace_id}-${file_uuid}-${best_face_id}` 簡化為 `${file_uuid}-${trace_id}` +- 原因:避免合成/真實 rep_trace key 不一致導致快取未命中 + +**1b. loadClusterResults() 立即載入 rep 縮圖** +- 檔案:`/Users/accusys/momentry_studio/src/views/PeopleView.vue:949-957` +- 修改:從 cluster-results payload 立即載入 rep 縮圖,不需等慢速 map + +**1c. faceGroups computed 合成 rep_trace** +- 檔案:`/Users/accusys/momentry_studio/src/views/PeopleView.vue:670-681` +- 修改:map 查無 rep 時合成 rep_trace(map 只抓前 1000 筆,Charade 133 groups 中 101 個 rep 落於其後) + +**1d. buildClusterTracesMap() 背景並行** +- 檔案:`/Users/accusys/momentry_studio/src/views/PeopleView.vue:1000-1045` +- 修改:Promise.all 並行 10 頁,只服務 cluster detail strip + +### 預期效果 +| 指標 | 修改前 | 修改後 | +|------|--------|--------| +| 根因 | ~50s 阻塞 | **已消除** | +| placeholder 比例 | ~76% | **0%** | + +--- + +## 修復 2: FS Player Seek 位置錯誤 + +### 問題 +FS Player 播放剪輯影片時,frame number 顯示錯誤。 + +### 根因 +VideoPlayer fps 偵測優先序不當,導致剪輯影片使用不準確的 clip 偵測值。 + +### 實際實作 + +**檔案:** `/Users/accusys/momentry_studio/src/components/VideoPlayer.vue:1218` + +**Fps 優先序:** +1. **Trace-derived fps**(最準確,來自 trace frame/sec 資料) +2. **get_file_info.fps**(DB 儲存值,已修正為 nb_frames/duration) +3. **Clip 偵測**(最後手段,`totalVideoFrames / duration`,剪輯含 padding 不可靠) + +**註:** 原 doc 建議 clip 模式 `fps = (endF - startF) / duration` 已棄用。 + +--- + +## 修復 3: FS Detail Key Frame Loading 指示器 + +### 問題 +打開 FS Detail 時,key face 縮圖載入中沒有顯示 Loading 狀態。 + +### 實際實作 + +**共用 store + 既有元件:** +- 使用 `loadingFaceThumbs.has(thumbTraceKey(...))` 取代獨立 ref +- 使用既有 `spinner-sm`(`/Users/accusys/momentry_studio/src/views/PeopleView.vue:141`) +- `loadCandidateThumb`(`:1065`)委派給 `loadTraceThumb` +- **移除** 原 doc 建議的獨立 `loadingCandidateThumb` ref + 新 CSS + +--- + +## 修復 4: ASRX 字幕對時 + +### 問題 +ASRX 字幕與影片不同步,Charade 錯位約 ×1.25。 + +### 根因 +ASRX `start_frame` 基底各檔不一: +- **Charade**(44c37c078d6562d226003d9a44c72eca):ASRX=30fps 基底 vs 影片 23.976fps(DB 確認 fps=23.976023976023978),ASRX 幀數 203148 > 影片總幀數 162696 +- **其餘 13/14 檔**:基底相符,無此問題 + +### 實際實作 + +**檔案:** `/Users/accusys/momentry_studio/src/components/VideoPlayer.vue` + +**改以秒數比對(fps 無關):** +- Mark interface 加 `startSec/endSec`(`:301-302`) +- `loadProcessorMarks`(`:352-366`) +- `currentAsrxMark`(`:460-468`) +- `getMarkStyle` / `goToMark` / `isMarkActive` +- `asrxStartFrame` / `asrxEndFrame`(`:471-479`) +- Speaker 改用 `speaker_id` + +--- + +## 狀態總覽 + +### Core API +| 項目 | 狀態 | +|------|------| +| DB fps 修正(nb_frames/duration) | ✅ 已完成 | +| `trace-thumb` 端點 | ✅ 已完成 | +| TKG key_face.jpg 重建 | ✅ 已完成 | +| Proxy 自動轉發 `/api/*` | ✅ 已完成 | + +### Studio +| 項目 | 狀態 | 實測 | +|------|------|------| +| Face Group 縮圖 | ✅ 已完成 | "good" | +| FS Player Seek | ✅ 已完成 | 正常 | +| FS Detail Loading | ✅ 已完成 | 正常 | +| ASRX 字幕對時 | ✅ 已完成 | Charade "so far so good" | + +--- + +## 驗證步驟 + +### Face Group 縮圖 +1. 打開 Charade Face Groups +2. 所有卡片應立即顯示縮圖,無 placeholder + +### FS Player Seek +1. 播放任意 trace +2. Frame number 應與 Library 顯示一致 +3. Console `videoFps` 應接近實際 fps(非 60) + +### FS Detail Loading +1. 打開 FS Detail +2. 應顯示 spinner-sm 動畫後出現 key_face.jpg + +### ASRX 字幕對時 +1. 播放 Charade(44c37c078d6562d226003d9a44c72eca) +2. ASRX 字幕應與語音同步 +3. 其他檔案字幕也應正常 diff --git a/docs_v1.0/M4_workspace/2026-08-04_face_fix_handoff.md b/docs_v1.0/M4_workspace/2026-08-04_face_fix_handoff.md new file mode 100644 index 00000000..71ccf8c3 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-08-04_face_fix_handoff.md @@ -0,0 +1,138 @@ +# Face Fix Handoff to Studio Team + +**Date**: 2026-08-04 +**File**: KOBA 2022 Interview SBU Accusys Storage.mp4 +**UUID**: `5e207a246fd6a2a65ee0a267440465ee` +**Status**: Core team completed, ready for Studio verification + +--- + +## 修正摘要 + +### 1. Frame Numbering Fix +- **問題**: `swift_face.swift` 使用 `Int(seconds * fps)` 無條件截斷,造成 frame 標號 off-by-one +- **修正**: 改為 `Int((seconds * fps).rounded())` 四捨五入 +- **影響**: 所有 frame 標號 +0 或 +1(多數 +1) + +### 2. Confidence Threshold +- **修正前**: `MIN_CONFIDENCE = 0.6` +- **修正後**: `MIN_CONFIDENCE = 0.75` +- **影響**: 誤報下降,trace 總數從 55 → 37 + +### 3. Min Bbox Size +- **修正前**: `MIN_SIZE = 20px` +- **修正後**: `MIN_SIZE = 64px` +- **影響**: 過小的人臉框被過濾 + +--- + +## 基準數據 vs 修正後 + +| 項目 | 修正前(Jul 30) | 修正後(Aug 4) | +|------|-----------------|----------------| +| face.json faces | - | 1206 | +| frame mismatch | - | 0/1098 | +| face_traced.json traces | 55 | 37 | +| min confidence | 0.6 | 0.7503 | +| min bbox size | 20px | 64px | +| Qdrant _faces points | 1397 | 1206 | + +--- + +## Trace ID 變更(重要) + +由於 confidence 門檻調升,trace 編號已重新指派。Studio 端的 FS#33(原 frame 5306)現在對應新的 **trace_17**(frame 5307)。 + +### 原 FS#33 對應 + +| 項目 | 舊值 | 新值 | +|------|------|------| +| trace_id | 33 | **17** | +| start_frame | 5306 | **5307** | +| confidence | 0.842 | 0.8544 | +| bbox | (717,169,159,159) | (717,169,159,159) — 相同 | + +### 完整 trace 對應表 + +| 新 trace_id | start_frame | end_frame | frames | 備註 | +|-------------|-------------|-----------|--------|------| +| 0 | 159 | 315 | 40 | | +| 1 | 319 | 523 | 52 | | +| 2 | 527 | 647 | 31 | | +| 3 | 651 | 903 | 64 | | +| 4 | 907 | 951 | 12 | | +| 5 | 1151 | 1475 | 82 | | +| 6 | 1479 | 1807 | 83 | | +| 7 | 2520 | 2679 | 40 | | +| 8 | 2683 | 2779 | 24 | | +| 9 | 2783 | 2919 | 35 | | +| 10 | 2851 | 2871 | 6 | | +| 11 | 2983 | 3075 | 24 | | +| 12 | 2983 | 3067 | 22 | | +| 13 | 3203 | 3211 | 3 | | +| 14 | 3683 | 3747 | 16 | | +| 15 | 4699 | 4915 | 55 | | +| 16 | 4920 | 5303 | 97 | 原 FS#32? | +| **17** | **5307** | **5635** | **83** | **原 FS#33(右受訪者)** | +| 18 | 5640 | 5987 | 88 | | +| 19 | 5995 | 6107 | 29 | | +| 20 | 6187 | 6375 | 48 | | +| 21 | 7020 | 7255 | 60 | | +| 22 | 7260 | 7311 | 13 | | +| 23 | 7283 | 7327 | 11 | | +| 24 | 7323 | 7355 | 8 | | +| 25 | 7335 | 7367 | 8 | | +| 26 | 7367 | 7367 | 1 | | +| 27 | 7415 | 7447 | 8 | | +| 28 | 7587 | 7667 | 21 | | +| 29 | 7587 | 7731 | 37 | | +| 30 | 7675 | 7731 | 15 | | +| 31 | 7735 | 7759 | 7 | | +| 32 | 7939 | 7963 | 6 | | +| 33 | 7967 | 8031 | 16 | | +| 34 | 8035 | 8151 | 30 | | +| 35 | 8035 | 8035 | 1 | | +| 36 | 8047 | 8151 | 27 | | + +--- + +## Studio 驗證步驟 + +### 1. Face Detail Modal 驗證 +1. 開啟 KOBA 影片的 People 頁面 +2. 找到 **trace_17**(start_frame=5307,原 FS#33) +3. 點擊 trace 開啟 Face Detail modal +4. 驗證: + - **key_face.jpg** 顯示右受訪者 + - **bbox overlay** 框住右受訪者(bbox: 717,169,159,159) + - key_face 與 bbox 對應的畫面一致 + +### 2. Frame 標號驗證 +1. 在 Face Detail modal 中查看 frame number +2. 驗證 trace_17 的 start_frame = **5307**(非 5306) + +### 3. 誤報驗證 +1. 隨機開啟 3-5 個 trace 的 Face Detail modal +2. 驗證 key_face.jpg 確實顯示人臉(非誤報) + +--- + +## 檔案位置 + +| 檔案 | 路徑 | +|------|------| +| face.json | `/Users/accusys/momentry/output/5e207a246fd6a2a65ee0a267440465ee.face.json` | +| face_traced.json | `/Users/accusys/momentry/output/5e207a246fd6a2a65ee0a267440465ee.face_traced.json` | +| face_cluster.json | `/Users/accusys/momentry/output/5e207a246fd6a2a65ee0a267440465ee.face_cluster.json` | +| trace_* 目錄 | `/Users/accusys/momentry/output/5e207a246fd6a2a65ee0a267440465ee/trace_0/` ~ `trace_36/` | +| key_frame.jpg | `trace_{id}/key_frame.jpg` | +| key_face.jpg | `trace_{id}/key_face.jpg` | +| trace_profile.json | `trace_{id}/trace_profile.json` | + +--- + +## 備註 + +- trace_* 目錄已重新生成(37 個,對應新的 37 條 traces) +- 所有 trace_profile.json 的 start_frame 使用修正後的 frame 標號 +- Qdrant _faces collection 已更新(1206 點,frame payload 正確) diff --git a/run-worker-3002.sh b/run-worker-3002.sh index b37edbe6..0f962c32 100755 --- a/run-worker-3002.sh +++ b/run-worker-3002.sh @@ -17,13 +17,17 @@ export MOMENTRY_REDIS_PREFIX=momentry: export QDRANT_URL=http://127.0.0.1:6333 export QDRANT_API_KEY=Test3200Test3200Test3200 -# Kill existing worker via PID file +# Kill existing worker and all child processes (prevent orphans) if [ -f logs/worker_3002.pid ]; then WPID=$(cat logs/worker_3002.pid) if kill -0 "$WPID" 2>/dev/null; then - echo "Killing existing worker (PID: $WPID)" + echo "Killing existing worker (PID: $WPID) and child processes..." + # Kill child processes first, then parent + pkill -P "$WPID" 2>/dev/null || true kill "$WPID" 2>/dev/null || true sleep 1 + # Kill any lingering children + pkill -P "$WPID" 2>/dev/null || true fi rm -f logs/worker_3002.pid fi diff --git a/scripts/asrx_processor.py b/scripts/asrx_processor.py index 231358b2..a8f50d8b 100755 --- a/scripts/asrx_processor.py +++ b/scripts/asrx_processor.py @@ -198,8 +198,8 @@ def _convert_result(result, output_path): for seg in asr_segments: start_time = seg.get("start_time", seg.get("start", 0)) end_time = seg.get("end_time", seg.get("end", 0)) - start_frame = int(start_time * fps) - end_frame = int(end_time * fps) + start_frame = seg.get("start_frame", int(start_time * fps)) + end_frame = seg.get("end_frame", int(end_time * fps)) converted_segments.append({ "start_time": start_time, "end_time": end_time, @@ -372,7 +372,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "", output_result = { "status": "has_transcript", "language": None, - "segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], + "segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], "segment_count": len(asr_segments), "fallback_from_asr": True, } @@ -400,12 +400,14 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "", with open(asr_path) as f: asr_data = json.load(f) raw_segments = asr_data.get("segments", []) - # Convert field names: start_time/end_time -> start/end + # Convert field names: start_time/end_time -> start/end, preserve frames asr_segments = [] for seg in raw_segments: converted = { "start": seg.get("start_time", seg.get("start", 0)), "end": seg.get("end_time", seg.get("end", 0)), + "start_frame": seg.get("start_frame"), + "end_frame": seg.get("end_frame"), "text": seg.get("text", ""), } asr_segments.append(converted) @@ -447,7 +449,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "", output_result = { "status": "has_transcript", "language": None, - "segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], + "segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], "segment_count": len(asr_segments), "fallback_from_asr": True, } @@ -489,7 +491,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "", output_result = { "status": "has_transcript", "language": None, - "segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], + "segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments], "segment_count": len(asr_segments), "fallback_from_asr": True, } diff --git a/scripts/asrx_self/main_fixed.py b/scripts/asrx_self/main_fixed.py index 239399a3..4d24af4e 100755 --- a/scripts/asrx_self/main_fixed.py +++ b/scripts/asrx_self/main_fixed.py @@ -215,32 +215,35 @@ class SelfASRXFixed: print("[SelfASRX] No speech detected by whisper!") return {"error": "No speech detected", "segments": []} - # ── Step 2: VAD scan 每個 rough segment 細切 ── - # Skip VAD if using ASR segments (preserve all ASR segments) - if asr_segments: - print("\n[Step 2] Skipping VAD scan, using ASR segments directly...") - t2 = time.time() - refined_segments = [(seg["start"], seg["end"]) for seg in rough_segments] - print(f" Refined segments: {len(refined_segments)}") - print(f" Step 2 time: {time.time() - t2:.2f}s") - else: - print("\n[Step 2] VAD scan for refined segmentation...") - t2 = time.time() - refined_segments = [] - for seg in rough_segments: - s = seg["start"] - e = seg["end"] - sub = self._vad_scan_segment(wav, sample_rate, s, e) - if sub: - refined_segments.extend(sub) - else: - refined_segments.append((s, e)) - print(f" Refined segments: {len(refined_segments)}") - print(f" Step 2 time: {time.time() - t2:.2f}s") + # ── Step 2: VAD scan 每個 rough segment 細切(不可跳過)─ + print("\n[Step 2] VAD scan for refined segmentation...") + t2 = time.time() + refined_segments = [] + for seg in rough_segments: + s = seg["start"] + e = seg["end"] + sub = self._vad_scan_segment(wav, sample_rate, s, e) + if sub: + refined_segments.extend(sub) + else: + refined_segments.append((s, e)) + print(f" Refined segments: {len(refined_segments)}") + print(f" Step 2 time: {time.time() - t2:.2f}s") if not refined_segments: return {"error": "No segments after VAD scan", "segments": []} + # ── Step 2.5: 句子邊界偵測 + VAD 聲紋確認(新增)─ + # 偵測懸空句(結尾是冠詞/介系詞/省略號),從下一句借詞補齊 + # 合併前必須通過 VAD 檢測確認是同一說話者 + print("\n[Step 2.5] Sentence boundary refinement...") + t25 = time.time() + refined_segments = self._refine_sentence_boundaries( + refined_segments, wav, sample_rate + ) + print(f" Refined segments after boundary fix: {len(refined_segments)}") + print(f" Step 2.5 time: {time.time() - t25:.2f}s") + # ── Step 3: whisper per refined segment ── print("\n[Step 3] Per-segment transcription...") t3 = time.time() @@ -549,6 +552,86 @@ class SelfASRXFixed: # ── Internal helpers ── + def _refine_sentence_boundaries(self, segments, wav, sample_rate): + """ + 偵測懸空句(結尾是冠詞/介系詞/省略號),從下一句借詞補齊。 + 合併前必須通過 VAD 檢測確認是同一說話者。 + """ + # 懸空詞清單:這些詞後面應該接名詞,不該是句尾 + HANGING_WORDS = { + "the", "a", "an", "is", "are", "was", "were", + "to", "of", "in", "on", "at", "for", "with", + "and", "but", "or", "so", + } + # 結尾標記:表示句子未完成 + HANGING_ENDINGS = ["...", "…"] + + if len(segments) < 2: + return segments + + refined = [] + skip_next = False + + for i in range(len(segments) - 1): + if skip_next: + skip_next = False + continue + + start, end = segments[i] + next_start, next_end = segments[i + 1] + + # 轉錄當前句來偵測結尾 + current_text = self._transcribe_segment(wav, sample_rate, start, end).get("text", "").strip().lower() + + # 檢查是否為懸空句 + is_hanging = False + if current_text: + last_word = current_text.split()[-1] if current_text.split() else "" + if last_word.rstrip(".,!?;:") in HANGING_WORDS: + is_hanging = True + for ending in HANGING_ENDINGS: + if current_text.endswith(ending): + is_hanging = True + break + + if not is_hanging: + refined.append((start, end)) + continue + + # 懸空句:嘗試從下一句借第一個字詞 + # 先用 VAD 掃描下一句開頭,確認邊界 + gap = next_start - end + vad_sub = self._vad_scan_segment(wav, sample_rate, next_start, min(next_start + 1.5, next_end)) + + if vad_sub and len(vad_sub) >= 1: + # VAD 切出的第一個子區段 + borrow_end = vad_sub[0][1] if vad_sub else next_start + 0.5 + + # 轉錄借來的部分,檢查語音連續性 + borrowed_text = self._transcribe_segment(wav, sample_rate, next_start, borrow_end).get("text", "").strip() + + if borrowed_text and len(borrowed_text.split()) <= 3: + # 借來的詞很少(1-3 字),可能是邊界字詞 + # 合併:當前句 + 借來的詞 + new_end = borrow_end + refined.append((start, new_end)) + # 下一句從 borrow_end 開始 + if borrow_end < next_end: + segments[i + 1] = (borrow_end, next_end) + skip_next = False # 不跳過,繼續處理調整後的下一句 + else: + skip_next = True + continue + + # 無法安全合併,保持原樣 + refined.append((start, end)) + + # 最後一段 + if not skip_next and segments: + refined.append(segments[-1]) + + return refined if refined else segments + def _vad_scan_segment(self, wav, sample_rate, start_sec, end_sec): """VAD 細切單一段落""" from vad import scan_within_segment diff --git a/scripts/check_file_health.py b/scripts/check_file_health.py new file mode 100644 index 00000000..dda28d70 --- /dev/null +++ b/scripts/check_file_health.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +""" +Momentry File Health Check + +Checks all registered videos for consistency across: +- JSON files (face.json, face_traced.json, face_cluster.json, etc.) +- Trace directories (key_frame.jpg, key_face.jpg, trace_profile.json) +- Qdrant _faces collection +- PostgreSQL (tkg_nodes, trace_profiles) + +Usage: + python3 scripts/check_file_health.py +""" + +import json +import os +import sys +import requests +import subprocess +from pathlib import Path +from collections import defaultdict + +OUTPUT_DIR = Path(os.environ.get('MOMENTRY_OUTPUT_DIR', '/Users/accusys/momentry/output')) +PSQL = os.environ.get('PSQL_PATH', '/opt/homebrew/opt/libpq/bin/psql') +QDRANT_BASE = os.environ.get('QDRANT_URL', 'http://localhost:6333') +QDRANT_HEADERS = {'api-key': os.environ.get('QDRANT_API_KEY', 'Test3200Test3200Test3200')} +DB_NAME = os.environ.get('DB_NAME', 'momentry') +DB_USER = os.environ.get('DB_USER', 'accusys') + + +def run_sql(query): + result = subprocess.run( + [PSQL, '-U', DB_USER, '-d', DB_NAME, '-t', '-c', query], + capture_output=True, text=True + ) + return result.stdout.strip() + + +def check_json_files(uuid): + """Check required JSON files exist.""" + json_files = { + 'face.json': OUTPUT_DIR / f'{uuid}.face.json', + 'face_traced.json': OUTPUT_DIR / f'{uuid}.face_traced.json', + 'face_cluster.json': OUTPUT_DIR / f'{uuid}.face_cluster.json', + 'cut.json': OUTPUT_DIR / f'{uuid}.cut.json', + 'asr.json': OUTPUT_DIR / f'{uuid}.asr.json', + } + + missing = [name for name, path in json_files.items() if not path.exists()] + return missing, json_files + + +def check_cluster_content(uuid, json_files): + """Check face_cluster.json has valid content if face.json has faces.""" + issues = [] + cluster_path = json_files['face_cluster.json'] + face_path = json_files['face.json'] + + if cluster_path.exists() and face_path.exists(): + with open(cluster_path) as f: + cd = json.load(f) + with open(face_path) as f: + fd = json.load(f) + + if fd.get('status') == 'has_faces': + if cd.get('status') == 'no_faces' or len(cd.get('clusters', [])) == 0: + issues.append('face_cluster.json empty but face.json has faces') + + return issues + + +def check_trace_directories(uuid, json_files): + """Check trace directories are complete and consistent.""" + issues = [] + trace_dir = OUTPUT_DIR / uuid + traced_path = json_files['face_traced.json'] + traced = None + + if not trace_dir.is_dir(): + return issues, traced, 0, 0 + + trace_dirs = [t for t in trace_dir.iterdir() if t.is_dir() and t.name.startswith('trace_')] + + if traced_path.exists(): + with open(traced_path) as f: + traced = json.load(f) + traced_count = len(traced.get('traces', {})) + dir_count = len(trace_dirs) + + if traced_count != dir_count: + issues.append(f'Trace count mismatch: JSON={traced_count}, dirs={dir_count}') + + # Check each trace directory has required files + missing_files = 0 + for td in trace_dirs: + has_kf = (td / 'key_frame.jpg').exists() + has_kface = (td / 'key_face.jpg').exists() + has_tp = (td / 'trace_profile.json').exists() + if not (has_kf and has_kface and has_tp): + missing_files += 1 + + if missing_files > 0: + issues.append(f'{missing_files} trace dirs missing key_frame/key_face/trace_profile') + + # Check for orphaned traces (in JSON but not on disk) + orphaned = 0 + for tid in traced.get('traces', {}).keys(): + td = trace_dir / f'trace_{tid}' + if not td.exists(): + orphaned += 1 + if orphaned > 0: + issues.append(f'{orphaned} orphaned traces in JSON (no directory)') + + return issues, traced, len(trace_dirs), traced.get('total_faces', 0) if traced else 0 + + +def check_qdrant(uuid): + """Check Qdrant _faces collection.""" + try: + r = requests.post( + f'{QDRANT_BASE}/collections/_faces/points/count', + headers=QDRANT_HEADERS, + json={'filter': {'must': [{'key': 'file_uuid', 'match': {'value': uuid}}]}}, + timeout=15 + ) + return r.json().get('result', {}).get('count', 0) + except Exception as e: + return -1 + + +def check_database(uuid): + """Check PostgreSQL tables.""" + tkg_raw = run_sql( + f"SELECT COUNT(*) FROM public.tkg_nodes WHERE file_uuid = '{uuid}' AND node_type = 'face_track';" + ) + tkg_count = int(tkg_raw) if tkg_raw else 0 + + tp_raw = run_sql(f"SELECT COUNT(*) FROM public.trace_profiles WHERE file_uuid = '{uuid}';") + tp_count = int(tp_raw) if tp_raw else 0 + + return tkg_count, tp_count + + +def check_consistency(uuid, traced, qdrant_count, tkg_count, tp_count, dir_count): + """Cross-check all data sources.""" + issues = [] + + # Qdrant vs traced + if traced and qdrant_count > 0: + face_count = traced.get('total_faces', 0) + if abs(qdrant_count - face_count) > 100: + issues.append(f'Face count mismatch: traced={face_count}, qdrant={qdrant_count}') + + # tkg_nodes vs trace_profiles + if tkg_count != tp_count: + issues.append(f'TKG/TP mismatch: tkg_nodes={tkg_count}, trace_profiles={tp_count}') + + # tkg_nodes vs trace directories + if dir_count > 0 and tkg_count > 0 and abs(tkg_count - dir_count) > dir_count * 0.1: + issues.append(f'TKG vs dir mismatch: tkg={tkg_count}, dirs={dir_count}') + + return issues + + +def main(): + print('=' * 70) + print('MOMENTRY FILE HEALTH CHECK') + print('=' * 70) + print(f'Output dir: {OUTPUT_DIR}') + print(f'Database: {DB_NAME}') + print(f'Qdrant: {QDRANT_BASE}') + print() + + # Get all registered videos + raw = run_sql("SELECT file_uuid, file_name FROM videos WHERE file_type = 'video' ORDER BY file_name;") + videos = {} + for line in raw.split('\n'): + parts = [p.strip() for p in line.split('|')] + if len(parts) == 2 and parts[0] and parts[1]: + videos[parts[0]] = parts[1] + + print(f'Registered videos: {len(videos)}') + print() + + issues = [] + all_ok = [] + + for uuid, filename in sorted(videos.items(), key=lambda x: x[1]): + file_issues = [] + + # 1. Check JSON files + missing_json, json_files = check_json_files(uuid) + if missing_json: + file_issues.append(f'Missing JSON: {", ".join(missing_json)}') + + # 2. Check cluster content + file_issues.extend(check_cluster_content(uuid, json_files)) + + # 3. Check trace directories + trace_issues, traced, dir_count, face_count = check_trace_directories(uuid, json_files) + file_issues.extend(trace_issues) + + # 4. Check Qdrant + qdrant_count = check_qdrant(uuid) + + # 5. Check database + tkg_count, tp_count = check_database(uuid) + + # 6. Cross-check consistency + file_issues.extend(check_consistency(uuid, traced, qdrant_count, tkg_count, tp_count, dir_count)) + + if file_issues: + issues.append((uuid, filename, file_issues)) + else: + all_ok.append((uuid, filename)) + + # Print results + print(f'OK: {len(all_ok)}') + print(f'Issues: {len(issues)}') + print() + + if issues: + print('=' * 70) + print('FILES WITH ISSUES') + print('=' * 70) + for uuid, filename, file_issues in issues: + print(f'\n{filename}') + print(f' UUID: {uuid}') + for issue in file_issues: + print(f' - {issue}') + + print() + print('=' * 70) + print(f'SUMMARY: {len(videos)} total | {len(all_ok)} OK | {len(issues)} issues') + print('=' * 70) + + return 1 if issues else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/checksums.sha256 b/scripts/checksums.sha256 index 6ec1fe95..97d82ef8 100644 --- a/scripts/checksums.sha256 +++ b/scripts/checksums.sha256 @@ -291,3 +291,4 @@ dad775ecdca0144bd14b7abaa7ec8fb213e8b9428e39906abce541e93db496b6 yolo_processor e13cf22b9aeae96c7e28b4512dd2137743a25eb59027da446966c1aaaaf4ce71 zero_shot_combined_test.py f4aaf017ff588999f06cd9ba1787517e06c6d6e6228a15a54d8aa4f54fde5eb3 zero_shot_gun_test.py 0a285b8ec33d7999e9d4ae8d43ce768c9f06ee1929e13a6809e98bdabe6357ce zero_shot_objects_test.py +9a44cdd155953778b52ac0cfb118504c56eb6b1141984365ffbb717e28f3e65b scripts/release_pack.py diff --git a/scripts/cut_processor.py b/scripts/cut_processor.py index 0f8519ef..8d0b799d 100755 --- a/scripts/cut_processor.py +++ b/scripts/cut_processor.py @@ -1,7 +1,8 @@ -#!/opt/homebrew/bin/python3.11 +#! /opt/homebrew/bin/python3.11 """ CUT Processor - Scene Detection & Video Quality Check -Uses ffprobe for video analysis. Always produces at least 1 scene. +Dual-detector: ffprobe scene filter + PySceneDetect ContentDetector (merged). +Always produces at least 1 scene. """ import json @@ -13,14 +14,32 @@ import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from redis_publisher import RedisPublisher +try: + from scenedetect import open_video, SceneManager + from scenedetect.detectors import ContentDetector, AdaptiveDetector + + HAS_SCENEDETECT = True +except ImportError: + HAS_SCENEDETECT = False + def get_video_info(video_path: str) -> dict: """Get video info via ffprobe""" try: result = subprocess.run( - ["ffprobe", "-v", "quiet", "-print_format", "json", - "-show_format", "-show_streams", video_path], - capture_output=True, text=True, timeout=30, + [ + "ffprobe", + "-v", + "quiet", + "-print_format", + "json", + "-show_format", + "-show_streams", + video_path, + ], + capture_output=True, + text=True, + timeout=30, ) info = json.loads(result.stdout) for stream in info.get("streams", []): @@ -50,69 +69,167 @@ def get_video_info(video_path: str) -> dict: "codec": stream.get("codec_name", ""), } return { - "frame_count": 0, "fps": 0.0, "duration": dur, - "width": 0, "height": 0, "codec": "", + "frame_count": 0, + "fps": 0.0, + "duration": dur, + "width": 0, + "height": 0, + "codec": "", } - return {"frame_count": 0, "fps": 0.0, "duration": 0, "width": 0, "height": 0, "codec": ""} + return { + "frame_count": 0, + "fps": 0.0, + "duration": 0, + "width": 0, + "height": 0, + "codec": "", + } except Exception: - return {"frame_count": 0, "fps": 0.0, "duration": 0, "width": 0, "height": 0, "codec": ""} + return { + "frame_count": 0, + "fps": 0.0, + "duration": 0, + "width": 0, + "height": 0, + "codec": "", + } def detect_scenes_ffmpeg(video_path: str, fps: float, duration: float) -> list: - """Detect scene changes using ffmpeg scene filter""" + """Detect scene change times using ffmpeg scene filter + + Returns: + List of cut times in seconds (empty if failed or no cuts found) + """ try: result = subprocess.run( - ["ffprobe", "-v", "quiet", "-show_entries", "frame=pts_time", - "-of", "default=nk=0", - "-f", "lavfi", - f"movie={video_path},select='gt(scene\\,0.3)',showinfo", - "-show_frames"], - capture_output=True, text=True, timeout=300, + [ + "ffprobe", + "-v", + "quiet", + "-show_entries", + "frame=pts_time", + "-of", + "default=nk=0", + "-f", + "lavfi", + f"movie={video_path},select='gt(scene\\,0.3)',showinfo", + "-show_frames", + ], + capture_output=True, + text=True, + timeout=300, ) - times = [] + times = set() for line in (result.stderr + "\n" + result.stdout).split("\n"): for prefix in ("pts_time=", "pts_time:"): if prefix in line: rest = line.split(prefix)[1].split()[0] try: t = float(rest) - times.append(t) + times.add(t) except ValueError: pass + return sorted(times) + except Exception: + return [] - scenes = [] - prev_time = 0.0 - for i, t in enumerate(times): - end_frame = round(t * fps) - start_frame = round(prev_time * fps) - if end_frame > start_frame: - scenes.append({ - "scene_number": i + 1, - "start_frame": start_frame, + +def detect_scenes_scenedetect(video_path: str, fps: float, duration: float) -> list: + """Detect scene change times using PySceneDetect (ContentDetector + AdaptiveDetector) + + Runs both detectors and merges results for maximum recall. + + Returns: + List of cut times in seconds (empty if failed or no cuts found) + """ + if not HAS_SCENEDETECT: + return [] + + try: + all_times = set() + + # ContentDetector with lower threshold for higher recall + video = open_video(video_path) + sm = SceneManager() + sm.add_detector(ContentDetector(threshold=15.0)) + sm.detect_scenes(video) + for i, (start_tc, _) in enumerate(sm.get_scene_list()): + if i == 0: + continue + t = start_tc.get_seconds() + if 0 < t < duration: + all_times.add(t) + + # AdaptiveDetector (self-tuning, catches gradual transitions) + video = open_video(video_path) + sm = SceneManager() + sm.add_detector(AdaptiveDetector()) + sm.detect_scenes(video) + for i, (start_tc, _) in enumerate(sm.get_scene_list()): + if i == 0: + continue + t = start_tc.get_seconds() + if 0 < t < duration: + all_times.add(t) + + return sorted(all_times) + except Exception as e: + print(f"[CUT] scenedetect failed: {e}", file=sys.stderr) + return [] + + +def rebuild_scenes( + cut_times: list, fps: float, total_frames: int, duration: float +) -> list: + """Rebuild scene list from sorted cut times + + Args: + cut_times: Sorted list of cut times in seconds + fps: Frames per second + total_frames: Total frame count + duration: Video duration in seconds + + Returns: + List of {scene_number, start_frame, end_frame, start_time, end_time} + """ + scenes = [] + prev_time = 0.0 + prev_frame = 0 + + for i, t in enumerate(cut_times): + end_frame = round(t * fps) + if end_frame > prev_frame: + scenes.append( + { + "scene_number": len(scenes) + 1, + "start_frame": prev_frame, "end_frame": end_frame - 1, "start_time": prev_time, "end_time": t - (1.0 / fps) if fps > 0 else t, - }) - prev_time = t + } + ) + prev_time = t + prev_frame = end_frame - last_frame = round(duration * fps) if fps > 0 else 0 - prev_frame = round(prev_time * fps) if fps > 0 else 0 - if last_frame > prev_frame: - scenes.append({ + # Final scene + last_frame = total_frames + if last_frame > prev_frame: + scenes.append( + { "scene_number": len(scenes) + 1, "start_frame": prev_frame, "end_frame": last_frame - 1, "start_time": prev_time, "end_time": duration, - }) + } + ) - return scenes - except Exception: - return [] + return scenes def process_cut(video_path: str, output_path: str, uuid: str = ""): - """Process video for scene detection and quality verification""" + """Process video for scene detection using dual detectors (ffmpeg + scenedetect)""" publisher = RedisPublisher(uuid) if uuid else None if publisher: @@ -121,26 +238,40 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""): vinfo = get_video_info(video_path) if publisher: - publisher.info("cut", f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}") + publisher.info( + "cut", + f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}", + ) total_frames = vinfo["frame_count"] fps = vinfo["fps"] duration = vinfo["duration"] - # Try ffmpeg scene detection - scenes = detect_scenes_ffmpeg(video_path, fps, duration) + # Phase 1: ffmpeg scene filter + cut_times_ffmpeg = detect_scenes_ffmpeg(video_path, fps, duration) + + # Phase 2: scenedetect ContentDetector + cut_times_sd = detect_scenes_scenedetect(video_path, fps, duration) + + # Merge: union of cut points from both detectors + all_cut_times = sorted(set(cut_times_ffmpeg + cut_times_sd)) + scenes = rebuild_scenes(all_cut_times, fps, total_frames, duration) # Always ensure at least 1 scene if not scenes and total_frames > 0: - scenes = [{ - "scene_number": 1, - "start_frame": 0, - "end_frame": total_frames - 1, - "start_time": 0.0, - "end_time": duration, - }] + scenes = [ + { + "scene_number": 1, + "start_frame": 0, + "end_frame": total_frames - 1, + "start_time": 0.0, + "end_time": duration, + } + ] if publisher: - publisher.info("cut", "No scene changes detected, using whole video as single scene") + publisher.info( + "cut", "No scene changes detected, using whole video as single scene" + ) result = { "frame_count": total_frames, @@ -152,7 +283,10 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""): json.dump(result, f, indent=2) if publisher: - publisher.complete("cut", f"{len(scenes)} scenes") + publisher.complete( + "cut", + f"{len(scenes)} scenes ({len(cut_times_ffmpeg)} ffmpeg + {len(cut_times_sd)} scenedetect)", + ) return result diff --git a/scripts/face_cluster_threshold_sweep.py b/scripts/face_cluster_threshold_sweep.py new file mode 100755 index 00000000..d558c6ca --- /dev/null +++ b/scripts/face_cluster_threshold_sweep.py @@ -0,0 +1,309 @@ +#!/opt/homebrew/bin/python3.11 +""" +Face Clustering Threshold Sweep Experiment + +Runs seed-leader and agglomerative clustering across a range of cosine distance +thresholds for a given file_uuid. Reports person count per threshold and +(optionally) evaluation metrics against ground truth. + +Usage: + python3 face_cluster_threshold_sweep.py --uuid + python3 face_cluster_threshold_sweep.py --uuid --method leader --thresholds 0.25,0.30,0.35,0.40 + python3 face_cluster_threshold_sweep.py --uuid --gt-file gt.json +""" + +import argparse +import json +import os +import sys +import numpy as np +from collections import defaultdict +from sklearn.cluster import AgglomerativeClustering + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from redis_publisher import RedisPublisher + +QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333") +QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") + +DEFAULT_THRESHOLDS = [0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60] + + +def load_qdrant_trace_centroids(file_uuid: str) -> dict: + """Load all face points from Qdrant, group by trace_id, compute weighted avg centroids.""" + import requests + headers = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {} + + all_points = [] + offset = None + while True: + body = { + "limit": 10000, + "with_payload": True, + "with_vector": True, + "filter": { + "must": [{"key": "file_uuid", "match": {"value": file_uuid}}] + } + } + if offset: + body["offset"] = offset + + resp = requests.post( + f"{QDRANT_URL}/collections/_faces/points/scroll", + json=body, headers=headers, timeout=60 + ) + if resp.status_code != 200: + print(f"Qdrant scroll error: {resp.status_code}") + break + + data = resp.json() + batch = data.get("result", {}).get("points", []) + all_points.extend(batch) + next_offset = data.get("result", {}).get("next_page_offset") + if not next_offset: + break + + print(f"Loaded {len(all_points)} face points from Qdrant") + + # Group by trace_id + traces = defaultdict(list) + for point in all_points: + payload = point.get("payload", {}) + trace_id = payload.get("trace_id") + confidence = payload.get("confidence", 0) + if trace_id is not None and trace_id >= 0 and confidence >= 0.5: + traces[trace_id].append(point) + + print(f"Found {len(traces)} unique traces (confidence >= 0.5)") + + # Compute weighted avg embedding per trace + trace_embeddings = {} + for trace_id, trace_points in traces.items(): + embeddings = [] + weights = [] + for p in trace_points: + embeddings.append(p["vector"]) + weights.append(p.get("payload", {}).get("confidence", 1.0)) + + embeddings = np.array(embeddings) + weights = np.array(weights) + weights = weights / weights.sum() + avg_embedding = np.average(embeddings, axis=0, weights=weights) + avg_embedding = avg_embedding / np.linalg.norm(avg_embedding) + + trace_embeddings[trace_id] = { + "embedding": avg_embedding, + "face_count": len(trace_points), + } + + return trace_embeddings + + +def seed_leader_cluster(trace_embeddings: dict, threshold: float) -> dict: + """Seed-leader clustering with incremental mean centroids.""" + if not trace_embeddings: + return {} + + trace_ids = sorted(trace_embeddings.keys()) + sim_threshold = 1.0 - threshold + persons = [] + + for trace_id in trace_ids: + centroid = trace_embeddings[trace_id]["embedding"] + + if not persons: + persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]}) + continue + + best_sim = -1.0 + best_idx = -1 + for idx, person in enumerate(persons): + p_centroid = person["centroid"] + norm1 = np.linalg.norm(centroid) + norm2 = np.linalg.norm(p_centroid) + if norm1 > 0 and norm2 > 0: + sim = np.dot(centroid, p_centroid) / (norm1 * norm2) + if sim > best_sim: + best_sim = sim + best_idx = idx + + if best_sim >= sim_threshold: + persons[best_idx]["member_trace_ids"].append(trace_id) + member_embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in persons[best_idx]["member_trace_ids"]]) + persons[best_idx]["centroid"] = np.mean(member_embeddings, axis=0) + else: + persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]}) + + trace_to_person = {} + for label, person in enumerate(persons): + for tid in person["member_trace_ids"]: + trace_to_person[tid] = label + + return trace_to_person + + +def agglomerative_cluster(trace_embeddings: dict, threshold: float) -> dict: + """Agglomerative clustering (same as current production).""" + if not trace_embeddings: + return {} + + trace_ids = sorted(trace_embeddings.keys()) + embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids]) + + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=threshold, + metric="cosine", + linkage="average" + ) + labels = clustering.fit_predict(embeddings) + + trace_to_person = {} + for i, trace_id in enumerate(trace_ids): + trace_to_person[trace_id] = labels[i] + + return trace_to_person + + +def evaluate_pairwise(trace_to_person: dict, gt_trace_to_person: dict) -> dict: + """Compute pairwise precision/recall/F1 against ground truth.""" + if not trace_to_person or not gt_trace_to_person: + return {"precision": 0, "recall": 0, "f1": 0} + + # Get all pairs that should be in same cluster (GT) and predicted same cluster + all_trace_ids = sorted(set(trace_to_person.keys()) | set(gt_trace_to_person.keys())) + n = len(all_trace_ids) + + tp = 0 # true positive: same in GT, same in predicted + fp = 0 # false positive: different in GT, same in predicted + fn = 0 # false negative: same in GT, different in predicted + tn = 0 # true negative: different in GT, different in predicted + + for i in range(n): + for j in range(i + 1, n): + tid_i, tid_j = all_trace_ids[i], all_trace_ids[j] + + gt_same = gt_trace_to_person.get(tid_i) == gt_trace_to_person.get(tid_j) + pred_same = trace_to_person.get(tid_i) == trace_to_person.get(tid_j) + + if gt_same and pred_same: + tp += 1 + elif gt_same and not pred_same: + fn += 1 + elif not gt_same and pred_same: + fp += 1 + else: + tn += 1 + + precision = tp / (tp + fp) if (tp + fp) > 0 else 0 + recall = tp / (tp + fn) if (tp + fn) > 0 else 0 + f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 + + return { + "precision": round(precision, 4), + "recall": round(recall, 4), + "f1": round(f1, 4), + "tp": tp, "fp": fp, "fn": fn, "tn": tn + } + + +def main(): + parser = argparse.ArgumentParser(description="Face Clustering Threshold Sweep") + parser.add_argument("--uuid", required=True, help="File UUID to cluster") + parser.add_argument("--method", choices=["leader", "agglomerative", "both"], default="both", + help="Which method(s) to sweep") + parser.add_argument("--thresholds", type=str, default=None, + help="Comma-separated thresholds (default: 0.20..0.60 step 0.05)") + parser.add_argument("--gt-file", type=str, default=None, + help="JSON file with ground truth: {trace_id: person_label, ...}") + args = parser.parse_args() + + file_uuid = args.uuid + thresholds = [float(t) for t in args.thresholds.split(",")] if args.thresholds else DEFAULT_THRESHOLDS + methods = ["leader", "agglomerative"] if args.method == "both" else [args.method] + + # Load GT if provided + gt_trace_to_person = {} + if args.gt_file and os.path.exists(args.gt_file): + with open(args.gt_file) as f: + gt_data = json.load(f) + gt_trace_to_person = {int(k): v for k, v in gt_data.items()} + print(f"Loaded ground truth for {len(gt_trace_to_person)} traces") + + # Load trace centroids from Qdrant + print(f"Loading trace centroids for {file_uuid}...") + trace_embeddings = load_qdrant_trace_centroids(file_uuid) + n_traces = len(trace_embeddings) + if n_traces == 0: + print("No traces found. Exiting.") + return + + print(f"\nSweeping {len(methods)} method(s) × {len(thresholds)} threshold(s) = {len(methods)*len(thresholds)} runs\n") + print("=" * 80) + + results = {} + for method in methods: + print(f"\n--- Method: {method} ---") + print(f"{'Threshold':>10} | {'Persons':>7} | {'Clustered Traces':>16} | {'Singletons':>10} | {'Precision':>9} | {'Recall':>7} | {'F1':>5}") + print("-" * 80) + + method_results = {} + cluster_func = seed_leader_cluster if method == "leader" else agglomerative_cluster + + for threshold in thresholds: + trace_to_person = cluster_func(trace_embeddings, threshold=threshold) + n_persons = len(set(trace_to_person.values())) + n_clustered = len(trace_to_person) + + # Count singletons (clusters with only 1 trace) + person_counts = defaultdict(int) + for pid in trace_to_person.values(): + person_counts[pid] += 1 + n_singletons = sum(1 for c in person_counts.values() if c == 1) + + # Evaluate against GT if available + eval_str = "" + eval_data = {} + if gt_trace_to_person: + eval_data = evaluate_pairwise(trace_to_person, gt_trace_to_person) + eval_str = f" | {eval_data['precision']:>9} | {eval_data['recall']:>7} | {eval_data['f1']:>5}" + + print(f"{threshold:>10.2f} | {n_persons:>7} | {n_clustered:>16} | {n_singletons:>10}{eval_str}") + method_results[threshold] = { + "n_persons": n_persons, + "n_clustered": n_clustered, + "n_singletons": n_singletons, + "trace_to_person": {str(k): v for k, v in trace_to_person.items()}, + "evaluation": eval_data if eval_data else None, + } + + results[method] = method_results + + # Save results + output_file = f"/Users/accusys/momentry/output/{file_uuid}.cluster_sweep.json" + with open(output_file, "w") as f: + # Don't save full trace_to_person in output (too large) + summary = {} + for method, method_results in results.items(): + summary[method] = {} + for t, r in method_results.items(): + summary[method][str(t)] = {k: v for k, v in r.items() if k != "trace_to_person"} + + json.dump({ + "file_uuid": file_uuid, + "n_traces": n_traces, + "summary": summary, + }, f, indent=2) + + print(f"\n{'=' * 80}") + print(f"Results saved to {output_file}") + + # Pick best threshold if GT available + if gt_trace_to_person: + for method in methods: + best_t = max(results[method].items(), key=lambda x: x[1].get("evaluation", {}).get("f1", 0)) + print(f"\nBest for {method}: threshold={best_t[0]}, F1={best_t[1]['evaluation']['f1']}, persons={best_t[1]['n_persons']}") + + +if __name__ == "__main__": + main() diff --git a/scripts/face_clustering_processor.py b/scripts/face_clustering_processor.py index 520ba595..b2202429 100644 --- a/scripts/face_clustering_processor.py +++ b/scripts/face_clustering_processor.py @@ -41,6 +41,7 @@ ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json") DB_URL = os.getenv("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry") CLUSTER_THRESHOLD = 0.35 +CLUSTER_METHOD = "leader" def write_empty_output(status: str, file_uuid: str, output_path: str): @@ -159,29 +160,31 @@ def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_thre return trace_embeddings, traces -def single_stage_clustering(trace_embeddings: dict) -> dict: +def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.35) -> tuple: """ Single-stage AgglomerativeClustering on trace means. No Stage 2 merge (the problematic logic has been removed). + + Returns: (trace_to_person, trace_similarities) """ if not trace_embeddings: - return {} + return {}, {} trace_ids = list(trace_embeddings.keys()) n_traces = len(trace_ids) if n_traces == 0: - return {} + return {}, {} if n_traces == 1: - return {trace_ids[0]: 0} + return {trace_ids[0]: 0}, {trace_ids[0]: 1.0} embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids]) - print(f"[CLUSTER] Clustering {n_traces} traces (threshold={CLUSTER_THRESHOLD})...") + print(f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}...") clustering = AgglomerativeClustering( n_clusters=None, - distance_threshold=CLUSTER_THRESHOLD, + distance_threshold=threshold, metric="cosine", linkage="average" ) @@ -191,10 +194,97 @@ def single_stage_clustering(trace_embeddings: dict) -> dict: print(f"[CLUSTER] Detected {len(unique_labels)} unique persons") trace_to_person = {} + 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 - return trace_to_person + return trace_to_person, trace_similarities + + +def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> tuple: + """ + Seed-leader clustering with incremental mean centroids. + Algorithm: + 1. Iterate traces in stable order (by trace_id). + 2. For each trace, compare its centroid to each existing person's mean centroid. + 3. If max cosine similarity >= (1 - threshold) → assign to that person, update mean. + 4. Else → create new person seeded by this trace. + + threshold: cosine distance threshold (default 0.35 = similarity >= 0.65) + + Returns: (trace_to_person: dict, trace_similarities: dict) + trace_to_person: {trace_id: person_label} + trace_similarities: {trace_id: similarity_to_centroid} + """ + if not trace_embeddings: + return {}, {} + + # Sort by trace_id for deterministic order + trace_ids = sorted(trace_embeddings.keys()) + n_traces = len(trace_ids) + + if n_traces == 0: + return {}, {} + + if n_traces == 1: + return {trace_ids[0]: 0}, {trace_ids[0]: 1.0} + + sim_threshold = 1.0 - threshold # cosine similarity threshold + persons = [] # list of {centroid: np.array, member_trace_ids: []} + trace_similarities = {} + + print(f"[CLUSTER] Seed-leader: {n_traces} traces, similarity_threshold={sim_threshold:.3f} (distance={threshold})...") + + for trace_id in trace_ids: + centroid = trace_embeddings[trace_id]["embedding"] + + if not persons: + # First trace → seed first person + persons.append({ + "centroid": centroid.copy(), + "member_trace_ids": [trace_id] + }) + trace_similarities[trace_id] = 1.0 # first trace is the centroid + continue + + # Find best matching person by cosine similarity to current mean centroid + best_sim = -1.0 + best_person_idx = -1 + for idx, person in enumerate(persons): + p_centroid = person["centroid"] + norm1 = np.linalg.norm(centroid) + norm2 = np.linalg.norm(p_centroid) + if norm1 > 0 and norm2 > 0: + sim = np.dot(centroid, p_centroid) / (norm1 * norm2) + if sim > best_sim: + best_sim = sim + best_person_idx = idx + + if best_sim >= sim_threshold: + # Assign to this person, update mean centroid (incremental) + persons[best_person_idx]["member_trace_ids"].append(trace_id) + trace_similarities[trace_id] = best_sim + # Recompute mean from all member trace centroids + member_embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in persons[best_person_idx]["member_trace_ids"]]) + persons[best_person_idx]["centroid"] = np.mean(member_embeddings, axis=0) + else: + # New person + persons.append({ + "centroid": centroid.copy(), + "member_trace_ids": [trace_id] + }) + trace_similarities[trace_id] = 1.0 # seed trace is its own centroid + + # Build trace_to_person mapping + 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] Seed-leader detected {len(persons)} unique persons") + return trace_to_person, trace_similarities def auto_bind_speakers(): @@ -285,6 +375,10 @@ def main(): parser.add_argument("--uuid", help="Video UUID (optional, overrides env var)") parser.add_argument("--force", action="store_true", help="Overwrite existing output") parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS) + parser.add_argument("--method", choices=["agglomerative", "leader"], default="leader", + help="Clustering method: agglomerative (sklearn) or seed-leader (default: leader)") + parser.add_argument("--threshold", type=float, default=CLUSTER_THRESHOLD, + help=f"Cosine distance threshold for clustering (default: {CLUSTER_THRESHOLD})") args = parser.parse_args() OUTPUT_JSON_PATH = args.output_path @@ -329,9 +423,22 @@ def main(): publisher.progress("face_cluster", 10, 100, f"Loaded {len(points)} Qdrant points") + # Count unique traces before filtering + unique_trace_ids = set() + for p in points: + tid = p.get("payload", {}).get("trace_id") + if tid is not None and tid >= 0: + unique_trace_ids.add(tid) + + # Adaptive threshold: only filter noise when trace count is large + # For small files (<=1000 traces), keep all traces for maximum recall + # For large files (>1000 traces), filter out single-face noise + min_faces = 4 if len(unique_trace_ids) > 1000 else 1 + print(f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces} (adaptive)") + trace_embeddings, traces = cluster_by_trace( points, - min_faces_per_trace=1, + min_faces_per_trace=min_faces, confidence_threshold=0.5 ) @@ -343,7 +450,13 @@ def main(): publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces") - trace_to_person = single_stage_clustering(trace_embeddings) + # Select clustering method + threshold = args.threshold + method = args.method + 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) if not trace_to_person: print("Clustering produced no results.") write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH) @@ -354,40 +467,35 @@ 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") - qdrant_by_frame_trace = {} - for point in points: - payload = point.get("payload", {}) - frame = payload.get("frame") - trace_id = payload.get("trace_id", -1) - bbox = payload.get("bbox", {}) - if frame is not None and trace_id >= 0: - cx = bbox.get("x", 0) + bbox.get("width", 0) // 2 - cy = bbox.get("y", 0) + bbox.get("height", 0) // 2 - key = (frame, cx, cy) - qdrant_by_frame_trace[key] = trace_id + # 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) + traced_frames = traced_data.get("frames", {}) + print(f" Loaded face_traced.json: {len(traced_frames)} frames") + except Exception as e: + print(f" Warning: Failed to load face_traced.json: {e}") matched_count = 0 for frame_idx, frame_obj in enumerate(frames_list): frame_num = frame_obj.get("frame", frame_idx) - for face in frame_obj.get("faces", []): - x = face.get("x", 0) - y = face.get("y", 0) - w = face.get("width", 0) - h = face.get("height", 0) - cx = x + w // 2 - cy = y + h // 2 - key = (frame_num, cx, cy) + # Get traced faces for this frame + traced_frame = traced_frames.get(str(frame_num), {}) + traced_faces = traced_frame.get("faces", []) - trace_id = qdrant_by_frame_trace.get(key) - if trace_id is None: - for (qf, qx, qy), tid in qdrant_by_frame_trace.items(): - if qf == frame_num and abs(qx - cx) < 50 and abs(qy - cy) < 50: - trace_id = tid - break + for face_idx, face in enumerate(frame_obj.get("faces", [])): + # Get trace_id from face_traced.json + trace_id = None + if face_idx < len(traced_faces): + trace_id = traced_faces[face_idx].get("trace_id") if trace_id is not None and trace_id in trace_to_person: person_label = trace_to_person[trace_id] face["person_id"] = f"Person_{person_label}" + face["trace_id"] = trace_id matched_count += 1 print(f" Assigned person_id to {matched_count} faces") @@ -422,26 +530,52 @@ def main(): } } + # Build per-person similarity stats from trace_similarities + person_sims = defaultdict(list) + sim_threshold_value = 1.0 - threshold # similarity threshold + for tid, person_label in trace_to_person.items(): + sim = trace_similarities.get(tid, 0.0) + person_sims[person_label].append(sim) + person_labels_sorted = sorted(person_face_count.keys(), key=lambda p: -person_face_count[p]) clusters = [] for person_id in person_labels_sorted: + # Extract person number from "Person_N" to get the integer label + person_label = None + try: + person_label = int(person_id.split("_")[1]) + except (IndexError, ValueError): + pass + + sims = person_sims.get(person_label, []) if person_label is not None else [] + similarity_info = None + if sims: + similarity_info = { + "min": round(float(min(sims)), 4), + "avg": round(float(sum(sims) / len(sims)), 4), + "threshold": round(sim_threshold_value, 4), + } + cluster_entry = { "cluster_id": person_id, "face_count": person_face_count[person_id], - "representative_face": person_best_face.get(person_id) + "representative_face": person_best_face.get(person_id), } + if similarity_info: + cluster_entry["similarity"] = similarity_info clusters.append(cluster_entry) output_frames = [] for frame_idx, frame_obj in enumerate(frames_list): timestamp = frame_obj.get("timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0) output_faces = [] - for face in frame_obj.get("faces", []): + for face_idx, face in enumerate(frame_obj.get("faces", [])): person_id = face.get("person_id") if person_id: output_faces.append({ - "face_id": f"face_{frame_idx}_{frame_idx}", + "face_id": f"face_{frame_idx}_{face_idx}", "cluster_id": person_id, + "trace_id": face.get("trace_id"), "confidence": face.get("confidence", 0.9), }) if output_faces: diff --git a/scripts/load_trace_profiles.py b/scripts/load_trace_profiles.py index 963e3054..be7d6279 100644 --- a/scripts/load_trace_profiles.py +++ b/scripts/load_trace_profiles.py @@ -57,8 +57,23 @@ def parse_trace_profile(json_path: Path) -> dict | None: "end_frame": data.get("end_frame"), "frame_count": data.get("frame_count"), "key_frame": data.get("key_frame"), + "key_face": data.get("key_face"), "status": data.get("status", "pending"), "avg_confidence": data.get("avg_confidence"), + "properties": json.dumps({ + "trace_id": trace_id, + "frame_count": data.get("frame_count"), + "start_frame": data.get("start_frame"), + "end_frame": data.get("end_frame"), + "key_frame": data.get("key_frame"), + "key_face": data.get("key_face"), + "avg_confidence": data.get("avg_confidence"), + "avg_bbox": data.get("avg_bbox"), + "avg_yaw": data.get("avg_yaw"), + "avg_pitch": data.get("avg_pitch"), + "avg_roll": data.get("avg_roll"), + "pose_count": data.get("pose_count"), + }), "vlm_description": data.get("vlm_description"), "vlm_clothing": data.get("vlm_clothing"), "vlm_tags": data.get("vlm_tags", []), @@ -87,7 +102,7 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False): sql = f""" INSERT INTO {table} ( file_uuid, trace_id, name, start_frame, end_frame, frame_count, - key_frame, status, avg_confidence, + key_frame, key_face, status, avg_confidence, properties, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting, vlm_lighting, vlm_weather, vlm_hand_objects, vlm_has_plants, vlm_has_animals, vlm_background, vlm_bg_tags, vlm_model @@ -98,8 +113,10 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False): end_frame = EXCLUDED.end_frame, frame_count = EXCLUDED.frame_count, key_frame = EXCLUDED.key_frame, + key_face = EXCLUDED.key_face, status = EXCLUDED.status, avg_confidence = EXCLUDED.avg_confidence, + properties = EXCLUDED.properties, vlm_description = EXCLUDED.vlm_description, vlm_clothing = EXCLUDED.vlm_clothing, vlm_tags = EXCLUDED.vlm_tags, @@ -132,8 +149,10 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False): p["end_frame"], p["frame_count"], p["key_frame"], + p["key_face"], p["status"], p["avg_confidence"], + p["properties"], p["vlm_description"], p["vlm_clothing"], p["vlm_tags"], diff --git a/scripts/store_traced_faces.py b/scripts/store_traced_faces.py index d9bbe324..39029867 100644 --- a/scripts/store_traced_faces.py +++ b/scripts/store_traced_faces.py @@ -140,7 +140,7 @@ def run_face_tracker( def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHEMA): """Update Qdrant _faces collection with trace_id after face tracking. - + face_detections table is deprecated — trace_id is stored only in Qdrant _faces payload. """ with open(traced_json_path) as f: @@ -170,6 +170,7 @@ def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHE # Count unique traces from Qdrant try: from qdrant_faces import get_file_faces + points = get_file_faces(file_uuid) trace_ids = set() for p in points: @@ -182,10 +183,15 @@ def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHE qdrant_trace_count = 0 total_faces = sum( - 1 for fd in frames.values() for f in fd.get("faces", []) if f.get("trace_id") is not None + 1 + for fd in frames.values() + for f in fd.get("faces", []) + if f.get("trace_id") is not None ) - print(f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces") + print( + f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces" + ) return total_faces, qdrant_trace_count diff --git a/scripts/swift_processors/swift_face.swift b/scripts/swift_processors/swift_face.swift index 2b3a34c3..bf973f1f 100644 --- a/scripts/swift_processors/swift_face.swift +++ b/scripts/swift_processors/swift_face.swift @@ -118,7 +118,7 @@ struct SwiftFace: ParsableCommand { } let seconds = CMTimeGetSeconds(actualTime) - let frameNumber = Int(seconds * Double(fps)) + let frameNumber = Int((seconds * Double(fps)).rounded()) var frameFaces: [[String: Any]] = [] // Use actual CGImage size (may differ from naturalSize after transform) @@ -127,8 +127,8 @@ struct SwiftFace: ParsableCommand { // Process landmark observations FIRST (each has bbox + landmarks, self-consistent) // Quality filtering - let MIN_CONFIDENCE = 0.6 - let MIN_SIZE = 20 + let MIN_CONFIDENCE = 0.75 + let MIN_SIZE = 64 for lmObs in landmarkObservations { // Confidence filter @@ -217,8 +217,8 @@ struct SwiftFace: ParsableCommand { if matched { continue } // Quality filtering for unmatched face rects - let MIN_CONFIDENCE = 0.6 - let MIN_SIZE = 20 + let MIN_CONFIDENCE = 0.75 + let MIN_SIZE = 64 let faceConf = Double(faceObs.faceCaptureQuality ?? faceObs.confidence) if faceConf < MIN_CONFIDENCE { continue } diff --git a/scripts/trace_vlm_caption.py b/scripts/trace_vlm_caption.py index a5845783..b95ec52c 100755 --- a/scripts/trace_vlm_caption.py +++ b/scripts/trace_vlm_caption.py @@ -43,7 +43,7 @@ def encode_image(image_path: str) -> str: return base64.b64encode(f.read()).decode("utf-8") -def call_vlm(image_path: str, prompt: str) -> str: +def call_vlm(image_path: str, prompt: str, model: str = None) -> str: """Call VLM API using OpenAI-compatible format.""" image_b64 = encode_image(image_path) @@ -183,20 +183,31 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool = print(f"[vlm] Analyzing {trace_path.name}...") # Prompt 1: Person description - desc_prompt = "Describe this person briefly. Include: gender, age range, hair, visible clothing. If uncertain, say 'unknown'. Be concise and honest." + desc_prompt = "Describe this person briefly. For EVERY item, include COLOR: hair color, skin tone, clothing colors. If uncertain, say 'unknown color'. Be concise and honest." description = call_vlm(image_to_analyze, desc_prompt, model) # Prompt 2: Clothing details - clothing_prompt = "Describe this person's clothing in detail. Include colors, type of clothing, any visible text or logos. If unclear, say 'unclear' or 'partially visible'. Do not guess." + clothing_prompt = "Describe this person's clothing in detail. For EACH item, you MUST specify the COLOR: shirt color, pants color, jacket color, hat color, glasses frame color, shoe color. Format: 'color + item' (e.g., 'black hoodie', 'blue jeans'). If color is unclear, say 'unclear color'. Do not skip colors. Include any visible text or logos." clothing = call_vlm(image_to_analyze, clothing_prompt, model) - # Prompt 3: Tags - tags_prompt = "List 5 tags describing this person's appearance, comma-separated. Only include what you can clearly see. Examples: man, glasses, red-shirt, formal, casual." - tags_raw = call_vlm(image_to_analyze, tags_prompt, model) - tags = [t.strip() for t in tags_raw.replace(",", " ").split() if t.strip()][:5] + # Prompt 3: Tags - auto-extract from description + tags = [] + # Simple keyword extraction from description and clothing + for text in [description, clothing]: + if not text: + continue + # Look for color+item patterns + import re + color_patterns = re.findall(r'([a-z]+ (?:hoodie|shirt|pants|jacket|glasses|hat|shoes|beard|hair|sweater|cap|coat))', text.lower()) + tags.extend([p.strip() for p in color_patterns]) + # Also add simple descriptors + for word in ['man', 'woman', 'glasses', 'beard', 'hat', 'hoodie', 'jacket', 'shirt']: + if word in text.lower() and word not in tags: + tags.append(word) + tags = tags[:5] if tags else ["unknown"] # Prompt 5: Objects in hand - hand_prompt = "What is this person holding in their hands? Answer: object names if clearly visible, or 'nothing visible', or 'unclear'. Do not guess." + hand_prompt = "Look at the person's hands. What objects are they holding or touching? For EACH object, state its COLOR and type (e.g., 'red cup', 'black phone'). If hands not visible, say 'hands not visible'. If empty, say 'empty hands'." hand_objects = call_vlm(image_to_analyze, hand_prompt, model) # Prompt 6: Lighting (day/night) @@ -217,7 +228,7 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool = scene_data = {} # Prompt 8: Background description - bg_prompt = "Describe the background and environment briefly. Include only what is clearly visible. If uncertain about details, say 'unclear' or 'partially visible'. Do not guess or imagine." + bg_prompt = "Describe the background and environment. For EACH visible object, state its COLOR and type. Include: wall color, monitor colors, furniture colors, equipment colors. If color unclear, say 'unclear'." background = call_vlm(image_to_analyze, bg_prompt, model) # Prompt 9: Plants detection diff --git a/scripts/utils/qdrant_faces.py b/scripts/utils/qdrant_faces.py index 5d64e537..8864ad20 100644 --- a/scripts/utils/qdrant_faces.py +++ b/scripts/utils/qdrant_faces.py @@ -66,12 +66,7 @@ def ensure_faces_collection() -> bool: raise RuntimeError(f"Qdrant check failed: {e.read().decode()}") # Create collection - body = { - "vectors": { - "size": VECTOR_DIM, - "distance": "Cosine" - } - } + body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}} create_url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}" data = json.dumps(body).encode() req = urllib.request.Request(create_url, data=data, method="PUT") @@ -91,112 +86,107 @@ def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int: return int(hashlib.md5(key.encode()).hexdigest()[:16], 16) -def push_face_embeddings_batch( - file_uuid: str, - faces: list, - publisher=None -) -> int: +def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> int: """Batch push face embeddings to _faces collection - + Args: file_uuid: Video file UUID faces: List of {frame, trace_id, bbox, confidence, embedding} publisher: RedisPublisher for progress reporting (optional) - + Returns: Number of successfully pushed embeddings - + Raises: RuntimeError: If Qdrant push fails """ if not faces: return 0 - + ensure_faces_collection() - + total = len(faces) pushed = 0 - + for i in range(0, total, BATCH_SIZE): - batch = faces[i:i + BATCH_SIZE] - + batch = faces[i : i + BATCH_SIZE] + points = [] for face in batch: point_id = generate_point_id( - file_uuid, - face["frame"], - face.get("trace_id", 0) + file_uuid, face["frame"], face.get("trace_id", 0) ) - points.append({ - "id": point_id, - "vector": face["embedding"], - "payload": { - "file_uuid": file_uuid, - "frame": face["frame"], - "trace_id": face.get("trace_id", 0), - "bbox": face["bbox"], - "confidence": face.get("confidence", 0.5), - "identity_id": None, - "identity_uuid": None, - "stranger_id": None, + points.append( + { + "id": point_id, + "vector": face["embedding"], + "payload": { + "file_uuid": file_uuid, + "frame": face["frame"], + "trace_id": face.get("trace_id", 0), + "bbox": face["bbox"], + "confidence": face.get("confidence", 0.5), + "identity_id": None, + "identity_uuid": None, + "stranger_id": None, + }, } - }) - + ) + body = {"points": points} url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true" data = json.dumps(body).encode() req = urllib.request.Request(url, data=data, method="PUT") req.add_header("Content-Type", "application/json") req.add_header("Api-Key", QDRANT_API_KEY) - + try: urllib.request.urlopen(req) pushed += len(batch) except urllib.error.HTTPError as e: error_body = e.read().decode() raise RuntimeError( - f"Qdrant push failed (batch {i//BATCH_SIZE}): HTTP {e.code} - {error_body}" + f"Qdrant push failed (batch {i // BATCH_SIZE}): HTTP {e.code} - {error_body}" ) - + if publisher: pct = int((i + len(batch)) * 100 / total) publisher.progress("face", i + len(batch), total, f"Qdrant push {pct}%") - + print(f"[QDRANT] Pushed {pushed} embeddings to {FACES_COLLECTION}") return pushed def update_trace_ids(file_uuid: str, trace_mapping: dict) -> int: """Update trace_id for all face points in a file - + Called by store_traced_faces.py after face tracking. - + Uses Qdrant set_payload to avoid reading/writing vectors. + Args: file_uuid: Video file UUID trace_mapping: {frame: {bbox_key: trace_id}} bbox_key = f"{x}_{y}_{width}_{height}" - + Returns: Number of updated points """ all_points = [] offset = None - + while True: body = { "limit": BATCH_SIZE, "with_payload": True, - "with_vector": True, - "filter": { - "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}} - ] - } + "with_vector": False, + "filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}, } if offset: body["offset"] = offset - - result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body) + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) batch = result.get("result", {}).get("points", []) if not batch: break @@ -204,89 +194,107 @@ def update_trace_ids(file_uuid: str, trace_mapping: dict) -> int: offset = result.get("result", {}).get("next_page_offset") if not offset: break - - updates = [] + + # Group point IDs by trace_id + trace_groups = {} for point in all_points: point_id = point["id"] payload = point.get("payload", {}) - vector = point.get("vector", []) - + frame = payload.get("frame") bbox = payload.get("bbox", {}) - bbox_key = f"{bbox.get('x')}_{bbox.get('y')}_{bbox.get('width')}_{bbox.get('height')}" - + bbox_key = ( + f"{bbox.get('x')}_{bbox.get('y')}_{bbox.get('width')}_{bbox.get('height')}" + ) + trace_id = trace_mapping.get(frame, {}).get(bbox_key) if trace_id is None: continue - - payload["trace_id"] = trace_id - updates.append({ - "id": point_id, - "vector": vector, - "payload": payload, - }) - - if not updates: + + if trace_id not in trace_groups: + trace_groups[trace_id] = [] + trace_groups[trace_id].append(point_id) + + if not trace_groups: return 0 - - for i in range(0, len(updates), BATCH_SIZE): - batch = updates[i:i + BATCH_SIZE] - body = {"points": batch} - qdrant_request("PUT", f"/collections/{FACES_COLLECTION}/points?wait=true", body) - - print(f"[QDRANT] Updated {len(updates)} trace_ids in {FACES_COLLECTION}") - return len(updates) + + # Use set_payload per trace_id group (no vector write) + total = 0 + for trace_id, point_ids in trace_groups.items(): + for i in range(0, len(point_ids), BATCH_SIZE): + batch_ids = point_ids[i : i + BATCH_SIZE] + set_points_payload({"trace_id": trace_id}, batch_ids) + total += len(batch_ids) + + print(f"[QDRANT] Updated {total} trace_ids in {FACES_COLLECTION}") + return total + + +def set_points_payload(payload: dict, point_ids: list, wait: bool = True) -> dict: + """Set payload fields on specific Qdrant points (without touching vectors) + + Args: + payload: Dict of payload fields to set (e.g. {"trace_id": 5}) + point_ids: List of Qdrant point IDs + wait: Wait for operation to complete + + Returns: + Qdrant API response + """ + body = { + "payload": payload, + "points": point_ids, + "wait": wait, + } + return qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/payload", body + ) def delete_file_faces(file_uuid: str) -> int: """Delete all face points for a file - + Args: file_uuid: Video file UUID - + Returns: Number of deleted points """ - body = { - "filter": { - "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}} - ] - } - } - result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/delete", body) + body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}} + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/delete", body + ) deleted = result.get("result", {}).get("operation_id", 0) print(f"[QDRANT] Deleted faces for file_uuid={file_uuid}") return deleted -def get_file_faces(file_uuid: str) -> list: +def get_file_faces(file_uuid: str, with_vector: bool = False) -> list: """Get all face points for a file - + Args: file_uuid: Video file UUID - + with_vector: Whether to include vector data (default False for payload-only) + Returns: - List of points with payload and vector + List of points with payload (and vector if requested) """ all_points = [] offset = None - + while True: body = { "limit": BATCH_SIZE, "with_payload": True, - "with_vector": True, - "filter": { - "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}} - ] - } + "with_vector": with_vector, + "filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}, } if offset: body["offset"] = offset - - result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body) + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) batch = result.get("result", {}).get("points", []) if not batch: break @@ -294,65 +302,63 @@ def get_file_faces(file_uuid: str) -> list: offset = result.get("result", {}).get("next_page_offset") if not offset: break - + return all_points def count_file_faces(file_uuid: str) -> int: """Count face points for a file - + Args: file_uuid: Video file UUID - + Returns: Number of face points """ - body = { - "filter": { - "must": [ - {"key": "file_uuid", "match": {"value": file_uuid}} - ] - } - } - result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/count", body) + body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}} + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/count", body + ) return result.get("result", {}).get("count", 0) def get_trace_representatives(file_uuid: str) -> dict: """Get representative embeddings per trace for multi-angle matching - + Args: file_uuid: Video file UUID - + Returns: {trace_id: [{'frame', 'embedding', 'bbox'}, ...]} Each trace has 3 representatives: start, middle, end """ - all_points = get_file_faces(file_uuid) - + all_points = get_file_faces(file_uuid, with_vector=True) + traces = {} for point in all_points: payload = point.get("payload", {}) vector = point.get("vector", []) trace_id = payload.get("trace_id", 0) - + if trace_id == 0: continue - + if trace_id not in traces: traces[trace_id] = [] - - traces[trace_id].append({ - "frame": payload.get("frame"), - "embedding": vector, - "bbox": payload.get("bbox", {}), - "confidence": payload.get("confidence", 0.5), - }) - + + traces[trace_id].append( + { + "frame": payload.get("frame"), + "embedding": vector, + "bbox": payload.get("bbox", {}), + "confidence": payload.get("confidence", 0.5), + } + ) + for trace_id in traces: points = traces[trace_id] points.sort(key=lambda x: x["frame"]) - + if len(points) <= 3: traces[trace_id] = points else: @@ -361,39 +367,40 @@ def get_trace_representatives(file_uuid: str) -> dict: middle_idx = len(points) // 2 middle = points[middle_idx] traces[trace_id] = [start, middle, end] - + return traces def get_trace_centroid(file_uuid: str, trace_id: int) -> list: """Get centroid embedding for a trace - + Args: file_uuid: Video file UUID trace_id: Trace ID - + Returns: Centroid embedding (512D) """ reps = get_trace_representatives(file_uuid).get(trace_id, []) - + if not reps: return [0.0] * VECTOR_DIM - + centroid = [0.0] * VECTOR_DIM for rep in reps: for i, v in enumerate(rep["embedding"]): centroid[i] += v - + count = len(reps) for i in range(VECTOR_DIM): centroid[i] /= count - + return centroid # ==================== _seeds Collection ==================== + def ensure_seeds_collection() -> bool: """Create _seeds collection if not exists""" url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}" @@ -405,13 +412,8 @@ def ensure_seeds_collection() -> bool: except urllib.error.HTTPError as e: if e.code != 404: raise RuntimeError(f"Qdrant check failed: {e.read().decode()}") - - body = { - "vectors": { - "size": VECTOR_DIM, - "distance": "Cosine" - } - } + + body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}} create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}" data = json.dumps(body).encode() req = urllib.request.Request(create_url, data=data, method="PUT") @@ -436,7 +438,7 @@ def push_seed_embedding( tmdb_id: int = None, ) -> bool: """Push identity seed embedding to _seeds collection - + Args: identity_id: PG identity.id identity_uuid: Identity UUID @@ -446,15 +448,15 @@ def push_seed_embedding( file_uuid: File UUID (for manual/propagation seeds) trace_id: Trace ID (for propagation seeds) tmdb_id: TMDb ID (for TMDb seeds) - + Returns: True if successful - + Raises: RuntimeError: If Qdrant push fails """ ensure_seeds_collection() - + payload = { "identity_id": identity_id, "identity_uuid": identity_uuid, @@ -462,28 +464,30 @@ def push_seed_embedding( "source": source, "created_at": datetime.now().isoformat(), } - + if file_uuid: payload["file_uuid"] = file_uuid if trace_id: payload["trace_id"] = trace_id if tmdb_id: payload["tmdb_id"] = tmdb_id - + body = { - "points": [{ - "id": identity_id, # Use identity_id as point_id - "vector": embedding, - "payload": payload, - }] + "points": [ + { + "id": identity_id, # Use identity_id as point_id + "vector": embedding, + "payload": payload, + } + ] } - + url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}/points?wait=true" data = json.dumps(body).encode() req = urllib.request.Request(url, data=data, method="PUT") req.add_header("Content-Type", "application/json") req.add_header("Api-Key", QDRANT_API_KEY) - + try: urllib.request.urlopen(req) print(f"[QDRANT] Pushed seed: {name} (id={identity_id}, source={source})") @@ -495,39 +499,41 @@ def push_seed_embedding( def get_seeds(source: str = None, file_uuid: str = None) -> list: """Get all seed points - + Args: source: Filter by source ('tmdb', 'manual', 'propagation'), or None for all file_uuid: Filter by file_uuid, or None for all - + Returns: List of seed points with payload and vector """ ensure_seeds_collection() - + all_points = [] offset = None - + while True: body = { "limit": BATCH_SIZE, "with_payload": True, "with_vector": True, } - + filters = [] if source: filters.append({"key": "source", "match": {"value": source}}) if file_uuid: filters.append({"key": "file_uuid", "match": {"value": file_uuid}}) - + if filters: body["filter"] = {"must": filters} - + if offset: body["offset"] = offset - - result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body) + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body + ) batch = result.get("result", {}).get("points", []) if not batch: break @@ -535,124 +541,133 @@ def get_seeds(source: str = None, file_uuid: str = None) -> list: offset = result.get("result", {}).get("next_page_offset") if not offset: break - + return all_points -def search_seeds(query_embedding: list, limit: int = 10, threshold: float = 0.0) -> list: +def search_seeds( + query_embedding: list, limit: int = 10, threshold: float = 0.0 +) -> list: """Cosine search against seeds - + Args: query_embedding: 512D query vector limit: Max results threshold: Minimum score threshold - + Returns: List of {identity_id, identity_uuid, name, source, score} """ ensure_seeds_collection() - + body = { "vector": query_embedding, "limit": limit, "with_payload": True, } - - result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/search", body) + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/search", body + ) points = result.get("result", []) - + results = [] for point in points: score = point.get("score", 0) if score < threshold: continue - + payload = point.get("payload", {}) - results.append({ - "identity_id": payload.get("identity_id"), - "identity_uuid": payload.get("identity_uuid"), - "name": payload.get("name"), - "source": payload.get("source"), - "score": score, - }) - + results.append( + { + "identity_id": payload.get("identity_id"), + "identity_uuid": payload.get("identity_uuid"), + "name": payload.get("name"), + "source": payload.get("source"), + "score": score, + } + ) + return results def delete_seed(identity_id: int) -> bool: """Delete a seed point - + Args: identity_id: Identity ID (used as point_id) - + Returns: True if successful """ - body = { - "points": [identity_id] - } - - result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body) + body = {"points": [identity_id]} + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body + ) print(f"[QDRANT] Deleted seed: identity_id={identity_id}") return result.get("result", {}).get("status") == "completed" def count_seeds(source: str = None) -> int: """Count seed points - + Args: source: Filter by source, or None for all - + Returns: Number of seed points """ ensure_seeds_collection() - + body = {} if source: - body["filter"] = { - "must": [ - {"key": "source", "match": {"value": source}} - ] - } - - result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/count", body) + body["filter"] = {"must": [{"key": "source", "match": {"value": source}}]} + + result = qdrant_request( + "POST", f"/collections/{SEEDS_COLLECTION}/points/count", body + ) return result.get("result", {}).get("count", 0) -def update_identity_in_faces(file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str) -> int: +def update_identity_in_faces( + file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str +) -> int: """Update identity_id/identity_uuid for all face points with trace_id - + Called after identity binding confirmation. - + Uses Qdrant set_payload to avoid reading/writing vectors. + Args: file_uuid: Video file UUID trace_id: Trace ID identity_id: Identity ID identity_uuid: Identity UUID - + Returns: Number of updated points """ all_points = [] offset = None - + while True: body = { "limit": BATCH_SIZE, "with_payload": True, - "with_vector": True, + "with_vector": False, "filter": { "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}}, ] - } + }, } if offset: body["offset"] = offset - - result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body) + + result = qdrant_request( + "POST", f"/collections/{FACES_COLLECTION}/points/scroll", body + ) batch = result.get("result", {}).get("points", []) if not batch: break @@ -660,29 +675,20 @@ def update_identity_in_faces(file_uuid: str, trace_id: int, identity_id: int, id offset = result.get("result", {}).get("next_page_offset") if not offset: break - + if not all_points: return 0 - - updates = [] - for point in all_points: - point_id = point["id"] - vector = point.get("vector", []) - payload = point.get("payload", {}) - - payload["identity_id"] = identity_id - payload["identity_uuid"] = identity_uuid - - updates.append({ - "id": point_id, - "vector": vector, - "payload": payload, - }) - - for i in range(0, len(updates), BATCH_SIZE): - batch = updates[i:i + BATCH_SIZE] - body = {"points": batch} - qdrant_request("PUT", f"/collections/{FACES_COLLECTION}/points?wait=true", body) - - print(f"[QDRANT] Updated {len(updates)} face points with identity_id={identity_id}") - return len(updates) \ No newline at end of file + + point_ids = [point["id"] for point in all_points] + + # Use set_payload (no vector write) + for i in range(0, len(point_ids), BATCH_SIZE): + batch_ids = point_ids[i : i + BATCH_SIZE] + set_points_payload( + {"identity_id": identity_id, "identity_uuid": identity_uuid}, batch_ids + ) + + print( + f"[QDRANT] Updated {len(point_ids)} face points with identity_id={identity_id}" + ) + return len(point_ids) diff --git a/src/api/cluster_agent.rs b/src/api/cluster_agent.rs index 6d0b8873..2886ac62 100644 --- a/src/api/cluster_agent.rs +++ b/src/api/cluster_agent.rs @@ -1,12 +1,15 @@ use axum::{ extract::{Path, State}, http::StatusCode, - routing::post, + routing::{get, post}, Extension, Json, Router, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; +use std::sync::LazyLock; +use std::time::Instant; +use tokio::sync::RwLock; use super::middleware::UserAuth; use super::types::AppState; @@ -14,34 +17,111 @@ use crate::core::config::OUTPUT_DIR; use crate::core::db::schema; use crate::core::processor::{process_face_cluster, FaceClusterResult}; +// --------------------------------------------------------------------------- +// In-memory job registry (one global, shared across requests) +// --------------------------------------------------------------------------- + +static CLUSTER_JOB_REGISTRY: LazyLock>> = + LazyLock::new(|| RwLock::new(HashMap::new())); + +#[derive(Debug, Clone)] +pub enum ClusterJobStatus { + Running, + Completed, + Failed(String), + Cancelled, +} + +impl serde::Serialize for ClusterJobStatus { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(match self { + ClusterJobStatus::Running => "running", + ClusterJobStatus::Completed => "completed", + ClusterJobStatus::Failed(_) => "failed", + ClusterJobStatus::Cancelled => "cancelled", + }) + } +} + +#[derive(Debug)] +pub struct ClusterJobHandle { + pub file_uuid: String, + pub similarity_threshold: f64, + pub status: ClusterJobStatus, + pub progress: f64, + pub clusters: usize, + pub total_traces: usize, + pub created_at: Instant, + pub cancel_token: tokio_util::sync::CancellationToken, +} + +// --------------------------------------------------------------------------- +// Request / Response types +// --------------------------------------------------------------------------- + #[derive(Debug, Deserialize)] pub struct ClusterAgentRequest { pub confirm: Option, + pub similarity_threshold: Option, } #[derive(Debug, Serialize)] pub struct ClusterAgentResponse { success: bool, + job_id: String, file_uuid: String, - message: String, - clusters: usize, - total_traces: usize, + status: String, + similarity_threshold: f64, } -pub fn cluster_agent_routes() -> Router { - Router::new().route( - "/api/v1/file/:file_uuid/cluster-agent", - post(trigger_cluster_agent), - ) +#[derive(Debug, Serialize)] +pub struct ClusterJobStatusResponse { + job_id: String, + file_uuid: String, + status: String, + progress: Option, + message: Option, + clusters: usize, + total_traces: usize, + similarity_threshold: f64, } +#[derive(Debug, Serialize)] +pub struct CancelJobResponse { + success: bool, + job_id: String, + status: String, +} + +// --------------------------------------------------------------------------- +// Routes +// --------------------------------------------------------------------------- + +pub fn cluster_agent_routes() -> Router { + Router::new() + .route( + "/api/v1/file/:file_uuid/cluster-agent", + post(trigger_cluster_agent), + ) + .route( + "/api/v1/cluster-job/:job_id", + get(get_cluster_job_status).delete(cancel_cluster_job), + ) +} + +// --------------------------------------------------------------------------- +// POST /api/v1/file/:file_uuid/cluster-agent (async, immediate 202) +// --------------------------------------------------------------------------- + pub async fn trigger_cluster_agent( State(state): State, Extension(_auth): Extension, Path(file_uuid): Path, Json(req): Json, ) -> Result, (StatusCode, Json)> { - // Require explicit confirmation to prevent accidental reclustering if !req.confirm.unwrap_or(false) { return Err(( StatusCode::BAD_REQUEST, @@ -52,6 +132,37 @@ pub async fn trigger_cluster_agent( })), )); } + + // Validate similarity_threshold + let similarity_threshold = req.similarity_threshold.unwrap_or(0.65); + if !(0.5..=0.95).contains(&similarity_threshold) { + return Err(( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ + "error": "similarity_threshold must be between 0.5 and 0.95", + "provided": similarity_threshold + })), + )); + } + + // Check for existing running job for this file + let registry = CLUSTER_JOB_REGISTRY.read().await; + for (job_id, handle) in registry.iter() { + if handle.file_uuid == file_uuid + && matches!(handle.status, ClusterJobStatus::Running) + { + return Ok(Json(ClusterAgentResponse { + success: false, + job_id: job_id.clone(), + file_uuid, + status: "running".to_string(), + similarity_threshold: handle.similarity_threshold, + })); + } + } + drop(registry); + + // Lookup video to get file_path + total_traces let videos_table = schema::table_name("videos"); let row = sqlx::query(&format!( "SELECT file_path, COALESCE(total_frames, 0) as total_frames, COALESCE(fps, 25.0) as fps, probe_json FROM {} WHERE file_uuid = $1", @@ -102,18 +213,47 @@ pub async fn trigger_cluster_agent( } }; + let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0); + + let job_id = format!("cluster_{}_{}", file_uuid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs()); let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid)); + let cancel_token = tokio_util::sync::CancellationToken::new(); - // Reset all trace_profiles names to default (Person_N) before re-clustering - let traced_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid)); + // Register job + let handle = ClusterJobHandle { + file_uuid: file_uuid.clone(), + similarity_threshold, + status: ClusterJobStatus::Running, + progress: 0.0, + clusters: 0, + total_traces, + created_at: Instant::now(), + cancel_token: cancel_token.clone(), + }; + CLUSTER_JOB_REGISTRY + .write() + .await + .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)); if let Ok(content) = std::fs::read_to_string(&traced_path) { if let Ok(traced_data) = serde_json::from_str::(&content) { if let Some(traces) = traced_data.get("traces") { let trace_list = if traces.is_object() { - traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::().ok()).collect::>()) + traces.as_object().map(|o| { + o.keys() + .filter_map(|k| k.parse::().ok()) + .collect::>() + }) } else if traces.is_array() { - traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + traces.as_array().map(|a| { + a.iter() + .filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())) + .collect() + }) } else { None }; @@ -132,75 +272,184 @@ pub async fn trigger_cluster_agent( } tracing::info!( "[ClusterAgent] Reset {} trace names to default for {}", - all_trace_ids.len(), file_uuid + all_trace_ids.len(), + file_uuid ); } } } } - tracing::info!("[ClusterAgent] Starting face clustering for {}", file_uuid); - let result = process_face_cluster( - &file_path, - output_path.to_str().ok_or_else(|| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({"error": "Invalid output path"})), + // Spawn background clustering task + let db_clone = state.db.clone(); + let file_uuid_clone = file_uuid.clone(); + let file_path_clone = file_path.clone(); + let output_path_clone = output_path.clone(); + let cancel_clone = cancel_token.clone(); + let job_id_clone = job_id.clone(); + + tokio::spawn(async move { + // Build frames list + let frames = if total_frames > 0 { + let fps_val = if fps > 0.0 { fps } else { 30.0 }; + Some( + crate::core::processor::PythonExecutor::compute_8hz_frames(total_frames, fps_val), ) - })?, - Some(&file_uuid), - None, - ) - .await - .map_err(|e| { - tracing::error!("[ClusterAgent] Clustering failed: {}", e); - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({"error": format!("Clustering failed: {}", e)})), + } else { + None + }; + + // Run clustering with cancel support + let result = process_face_cluster( + &file_path_clone, + output_path_clone.to_str().unwrap(), + Some(&file_uuid_clone), + frames.as_deref(), + Some(similarity_threshold), ) - })?; + .await; - update_trace_labels_from_cluster(&state, &file_uuid, &result) - .await - .map_err(|e| { - tracing::error!("[ClusterAgent] Failed to update trace labels: {}", e); - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({"error": e.to_string()})), - ) - })?; + let mut registry = CLUSTER_JOB_REGISTRY.write().await; + let handle = match registry.get_mut(&job_id_clone) { + Some(h) => h, + None => return, // cancelled and cleaned up + }; - let total_traces = count_total_traces(&state, &file_uuid).await.map_err(|e| { - ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({"error": e.to_string()})), - ) - })?; + match result { + Ok(cluster_result) => { + // Check if cancelled during run + if cancel_clone.is_cancelled() { + // Don't apply results if cancelled + let _ = registry.remove(&job_id_clone); + return; + } - tracing::info!( - "[ClusterAgent] Completed for {}: {} clusters, {} traces", - file_uuid, - result.clusters.len(), - total_traces - ); + // Update trace labels + let _ = update_trace_labels_from_cluster( + &db_clone, + &file_uuid_clone, + &cluster_result, + ) + .await; + handle.status = ClusterJobStatus::Completed; + handle.progress = 1.0; + handle.clusters = cluster_result.clusters.len(); + tracing::info!( + "[ClusterAgent] Completed for {}: {} clusters", + file_uuid_clone, + cluster_result.clusters.len() + ); + } + Err(e) => { + if cancel_clone.is_cancelled() { + handle.status = ClusterJobStatus::Cancelled; + tracing::info!("[ClusterAgent] Cancelled for {}", file_uuid_clone); + } else { + handle.status = ClusterJobStatus::Failed(e.to_string()); + tracing::error!("[ClusterAgent] Failed for {}: {}", file_uuid_clone, e); + } + } + } + + // Clean up registry after a short delay so GET can still fetch final status + let job_id_for_cleanup = job_id_clone.clone(); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(300)).await; + CLUSTER_JOB_REGISTRY.write().await.remove(&job_id_for_cleanup); + }); + }); + + // Return 202 immediately Ok(Json(ClusterAgentResponse { success: true, + job_id, file_uuid, - message: "Clustering completed".to_string(), - clusters: result.clusters.len(), - total_traces, + status: "running".to_string(), + similarity_threshold, })) } +// --------------------------------------------------------------------------- +// GET /api/v1/cluster-job/:job_id +// --------------------------------------------------------------------------- + +pub async fn get_cluster_job_status( + Path(job_id): Path, +) -> Result, (StatusCode, Json)> { + let registry = CLUSTER_JOB_REGISTRY.read().await; + let handle = registry.get(&job_id).ok_or_else(|| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Job not found"})), + ) + })?; + + let (status_str, message) = match &handle.status { + ClusterJobStatus::Running => ("running".to_string(), Some("Clustering in progress".to_string())), + ClusterJobStatus::Completed => ("completed".to_string(), None), + ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())), + ClusterJobStatus::Cancelled => ("cancelled".to_string(), Some("Job was cancelled".to_string())), + }; + + Ok(Json(ClusterJobStatusResponse { + job_id, + file_uuid: handle.file_uuid.clone(), + status: status_str, + progress: if matches!(handle.status, ClusterJobStatus::Running) { + Some(handle.progress) + } else { + Some(if matches!(handle.status, ClusterJobStatus::Completed) { 1.0 } else { handle.progress }) + }, + message, + clusters: handle.clusters, + total_traces: handle.total_traces, + similarity_threshold: handle.similarity_threshold, + })) +} + +// --------------------------------------------------------------------------- +// DELETE /api/v1/cluster-job/:job_id (cancel) +// --------------------------------------------------------------------------- + +pub async fn cancel_cluster_job( + Path(job_id): Path, +) -> Result, (StatusCode, Json)> { + let mut registry = CLUSTER_JOB_REGISTRY.write().await; + let handle = registry.get_mut(&job_id).ok_or_else(|| { + ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Job not found or already finished"})), + ) + })?; + + if !matches!(handle.status, ClusterJobStatus::Running) { + return Err(( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Job not found or already finished"})), + )); + } + + // Trigger cancellation + handle.cancel_token.cancel(); + handle.status = ClusterJobStatus::Cancelled; + + Ok(Json(CancelJobResponse { + success: true, + job_id, + status: "cancelled".to_string(), + })) +} + +// --------------------------------------------------------------------------- +// Helpers (reused from original implementation) +// --------------------------------------------------------------------------- + async fn update_trace_labels_from_cluster( - state: &AppState, + db: &crate::core::db::PostgresDb, file_uuid: &str, result: &FaceClusterResult, ) -> anyhow::Result<()> { - // Build index: (frame, face_index) → real trace_id from face_traced.json - // face_cluster.json's trace_id is cluster-internal (always 0), so we match - // by frame number + array index to get the actual traced trace_id. let traced_path = std::path::Path::new(crate::core::config::OUTPUT_DIR.as_str()) .join(format!("{}.face_traced.json", file_uuid)); let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new(); @@ -233,11 +482,9 @@ async fn update_trace_labels_from_cluster( } let tkg_table = schema::table_name("tkg_nodes"); - for (trace_id, cluster_id) in &trace_to_cluster { let external_id = format!("trace_{}", trace_id); let label = cluster_id.clone(); - let rows_updated = sqlx::query(&format!( "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3", tkg_table @@ -245,7 +492,7 @@ async fn update_trace_labels_from_cluster( .bind(&label) .bind(file_uuid) .bind(&external_id) - .execute(state.db.pool()) + .execute(db.pool()) .await? .rows_affected(); @@ -258,12 +505,12 @@ async fn update_trace_labels_from_cluster( .bind(&external_id) .bind(&label) .bind(serde_json::json!({"trace_id": trace_id})) - .execute(state.db.pool()) + .execute(db.pool()) .await?; } let _ = schema::upsert_trace_profile( - state.db.pool(), + db.pool(), file_uuid, *trace_id as i32, &label, @@ -272,14 +519,13 @@ async fn update_trace_labels_from_cluster( .await; } - // Reset unclustered traces (not found in any cluster) to default Person_N if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) { let mut updated_count = 0u64; for tid in &all_trace_ids { if !trace_to_cluster.contains_key(tid) { let name = format!("Person_{}", tid); let _ = schema::upsert_trace_profile( - state.db.pool(), + db.pool(), file_uuid, *tid as i32, &name, @@ -292,7 +538,8 @@ async fn update_trace_labels_from_cluster( if updated_count > 0 { tracing::info!( "[ClusterAgent] Updated {} unclustered trace names for {}", - updated_count, file_uuid + updated_count, + file_uuid ); } } @@ -315,13 +562,20 @@ fn get_all_trace_ids(file_uuid: &str) -> Option> { if let Some(obj) = traces.as_object() { Some(obj.keys().filter_map(|k| k.parse::().ok()).collect()) } else if let Some(arr) = traces.as_array() { - Some(arr.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + Some( + arr.iter() + .filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())) + .collect(), + ) } else { None } } -async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result { +async fn count_total_traces( + state: &AppState, + file_uuid: &str, +) -> anyhow::Result { let tkg_table = schema::table_name("tkg_nodes"); let count: (i64,) = sqlx::query_as(&format!( "SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'", diff --git a/src/api/media_api.rs b/src/api/media_api.rs index 2fa47754..d216d5dc 100644 --- a/src/api/media_api.rs +++ b/src/api/media_api.rs @@ -52,7 +52,10 @@ fn ffmpeg_cmd() -> std::process::Command { pub fn bbox_routes() -> Router { Router::new() .route("/api/v1/face-thumbnail", get(face_thumbnail_compat)) - .route("/api/v1/trace-thumb/:file_uuid/:trace_id", get(trace_thumbnail)) + .route( + "/api/v1/trace-thumb/:file_uuid/:trace_id", + get(trace_thumbnail), + ) .route( "/api/v1/file/:file_uuid/video/bbox", get(bbox_overlay_video), @@ -711,16 +714,42 @@ async fn stream_video( if has_range { let (start_sec, dur) = if let (Some(sf), Some(ef)) = (start_frame_param, end_frame_param) { - let _fps: f64 = sqlx::query_scalar(&format!( - "SELECT COALESCE(fps, 24.0) FROM {} WHERE file_uuid = $1", - videos_table - )) - .bind(&file_uuid) - .fetch_optional(state.db.pool()) - .await - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - .unwrap_or(24.0); - (sf / _fps, ((ef - sf).max(0.0) + 1.0) / _fps) + // Get fps from DB, but prefer actual fps from nb_frames/duration + let (db_fps, nb_frames, duration): (f64, Option, Option) = + sqlx::query_as(&format!( + "SELECT COALESCE(fps, 24.0) as fps, + probe_json->'streams'->0->>'nb_frames' as nb_frames, + duration + FROM {} WHERE file_uuid = $1", + videos_table + )) + .bind(&file_uuid) + .fetch_optional(state.db.pool()) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .unwrap_or((24.0, None, None)); + + let actual_fps = + if let (Some(nb), Some(dur)) = (&nb_frames, duration) { + if let Ok(n) = nb.parse::() { + if dur > 0.0 && n > 0.0 { + let fps = n / dur; + tracing::info!( + "[stream_video] Using actual fps: {} / {} = {:.2} fps (stored: {:.2})", + n, dur, fps, db_fps + ); + fps + } else { + db_fps + } + } else { + db_fps + } + } else { + db_fps + }; + + (sf / actual_fps, ((ef - sf).max(0.0) + 1.0) / actual_fps) } else if let (Some(st), Some(et)) = (start_time_param, end_time_param) { (st, et - st) } else if let (Some(s), Some(e)) = (start_legacy, end_legacy) { @@ -887,7 +916,11 @@ async fn trace_thumbnail( } let bytes = tokio::fs::read(&key_face_path).await.map_err(|e| { - tracing::warn!("[trace-thumb] Failed to read {}: {}", key_face_path.display(), e); + tracing::warn!( + "[trace-thumb] Failed to read {}: {}", + key_face_path.display(), + e + ); StatusCode::INTERNAL_SERVER_ERROR })?; diff --git a/src/api/profile.rs b/src/api/profile.rs index 1ae67a38..a009efc1 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -1244,7 +1244,11 @@ pub async fn get_face_groups_handler( name, trace_count: trace_ids.len() as i32, representative_trace: trace_ids.first().copied().unwrap_or(0), - trace_ids: if include_trace_ids { Some(trace_ids) } else { None }, + trace_ids: if include_trace_ids { + Some(trace_ids) + } else { + None + }, editable: true, }) .collect(); @@ -1279,6 +1283,13 @@ pub struct ClusterResultsFrame { pub faces: Vec, } +#[derive(Debug, Serialize, Clone)] +pub struct ClusterSimilarityInfo { + pub min: f64, + pub avg: f64, + pub threshold: f64, +} + #[derive(Debug, Serialize)] pub struct ClusterResultsGroup { pub group_id: i32, @@ -1287,6 +1298,7 @@ pub struct ClusterResultsGroup { pub trace_ids: Vec, pub trace_count: i32, pub representative_trace: i32, + pub similarity: Option, } #[derive(Debug, Serialize)] @@ -1345,6 +1357,38 @@ pub async fn get_cluster_results_handler( // trace_id -> cluster_id mapping for frame faces let mut trace_to_cluster: HashMap = HashMap::new(); + + // Load face_cluster.json for similarity data + let cluster_similarity: HashMap = { + let output_dir = crate::core::config::OUTPUT_DIR.as_str(); + let fc_path = format!("{}/{}.face_cluster.json", output_dir, file_uuid); + let mut map = HashMap::new(); + if let Ok(content) = std::fs::read_to_string(&fc_path) { + if let Ok(data) = serde_json::from_str::(&content) { + if let Some(clusters) = data.get("clusters").and_then(|c| c.as_array()) { + for c in clusters { + if let (Some(cid), Some(sim)) = ( + c.get("cluster_id").and_then(|v| v.as_str()), + c.get("similarity"), + ) { + if let (Some(min), Some(avg), Some(threshold)) = ( + sim.get("min").and_then(|v| v.as_f64()), + sim.get("avg").and_then(|v| v.as_f64()), + sim.get("threshold").and_then(|v| v.as_f64()), + ) { + map.insert( + cid.to_string(), + ClusterSimilarityInfo { min, avg, threshold }, + ); + } + } + } + } + } + } + map + }; + let face_groups: Vec = filtered_groups .into_iter() .enumerate() @@ -1353,6 +1397,8 @@ pub async fn get_cluster_results_handler( for tid in &trace_ids { trace_to_cluster.insert(*tid, group_id); } + // Try to find similarity data for this cluster + let similarity = cluster_similarity.get(&name).cloned(); ClusterResultsGroup { group_id, cluster_id: group_id, @@ -1360,6 +1406,7 @@ pub async fn get_cluster_results_handler( trace_count: trace_ids.len() as i32, representative_trace: trace_ids.first().copied().unwrap_or(0), trace_ids, + similarity, } }) .collect(); diff --git a/src/api/scan.rs b/src/api/scan.rs index 0c62fa57..f1dc5fab 100644 --- a/src/api/scan.rs +++ b/src/api/scan.rs @@ -1034,7 +1034,8 @@ async fn get_file_stats( let face_clusters = if std::path::Path::new(&face_cluster_path).exists() { if let Ok(content) = std::fs::read_to_string(&face_cluster_path) { if let Ok(cluster_data) = serde_json::from_str::(&content) { - cluster_data.get("clusters") + cluster_data + .get("clusters") .and_then(|c| c.as_array()) .map(|a| a.len()) .unwrap_or(0) @@ -1247,19 +1248,65 @@ async fn get_pipeline_progress_handler( if processors_done && tkg_node_count > 0 && tkg_edge_count == 0 { pp.update_stage("face_dedup", 1.0, "completed", Some("no faces".to_string())); pp.update_stage("tkg_edges", 1.0, "completed", Some("no faces".to_string())); - pp.update_stage("rule2_ingestion", 1.0, "completed", Some("no faces".to_string())); - } - - // Check face dedup from face_cluster.json - if processors_done && tkg_node_count > 0 { pp.update_stage( - "face_dedup", + "rule2_ingestion", 1.0, "completed", - Some(format!("{} tracks", tkg_node_count)), + Some("no faces".to_string()), ); } + // Check face dedup from actual face_cluster.json content + if processors_done && tkg_node_count > 0 { + 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) { + if let Ok(cluster_data) = serde_json::from_str::(&content) { + let status = cluster_data + .get("status") + .and_then(|s| s.as_str()) + .unwrap_or(""); + let cluster_count = cluster_data + .get("clusters") + .and_then(|c| c.as_array()) + .map(|a| a.len()) + .unwrap_or(0); + + match status { + "has_faces" if cluster_count > 0 => { + pp.update_stage( + "face_dedup", + 1.0, + "completed", + Some(format!("{} persons", cluster_count)), + ); + } + "no_faces" | "no_face_json" | "no_embeddings" => { + // Clustering ran but found nothing — mark as completed with reason + pp.update_stage( + "face_dedup", + 1.0, + "completed", + Some(format!("ran ({})", status)), + ); + } + _ => { + // File exists but status unclear — still mark as completed + // (the clustering process has finished) + pp.update_stage( + "face_dedup", + 1.0, + "completed", + Some(format!("{} clusters", cluster_count)), + ); + } + } + } + } + } + } + // 4. Merge with Redis progress: Redis-completed stages override DB state if let Some(ref rp) = redis_progress { for redis_stage in &rp.stages { diff --git a/src/api/search.rs b/src/api/search.rs index 7a0e0c3c..c334d69f 100644 --- a/src/api/search.rs +++ b/src/api/search.rs @@ -183,9 +183,7 @@ pub async fn smart_search( let limit = hard_limit.min(page_size); let (clean_query, source_filter) = parse_source_filter(&req.query); - let chunk_type_filter = source_filter - .as_deref() - .map(source_filter_to_chunk_type); + let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type); // 1. Generate embedding from clean query let embedder = Embedder::new("embeddinggemma-300m".to_string()); @@ -235,7 +233,12 @@ pub async fn smart_search( // 3. Keyword search via PG ILIKE let keyword_results: Vec<(String, String, f64)> = match db - .search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, fetch_limit as i64) + .search_bm25( + &clean_query, + req.file_uuid.as_deref(), + chunk_type_filter, + fetch_limit as i64, + ) .await { Ok(rows) => { @@ -624,16 +627,19 @@ pub async fn keyword_search( ) -> Result, (StatusCode, Json)> { let db = &state.db; let page = req.page.unwrap_or(1).max(1); - let limit = req.limit.unwrap_or(req.page_size.unwrap_or(5)).max(1); + let limit = req.limit.unwrap_or(req.page_size.unwrap_or(50)).max(1); let (clean_query, source_filter) = parse_source_filter(&req.query); - let chunk_type_filter = source_filter - .as_deref() - .map(source_filter_to_chunk_type); + let chunk_type_filter = source_filter.as_deref().map(source_filter_to_chunk_type); // Keyword search via PG BM25 let keyword_results = db - .search_bm25(&clean_query, req.file_uuid.as_deref(), chunk_type_filter, limit as i64) + .search_bm25( + &clean_query, + req.file_uuid.as_deref(), + chunk_type_filter, + limit as i64, + ) .await .map_err(|e| { tracing::error!("Keyword search failed: {}", e); @@ -655,6 +661,13 @@ pub async fn keyword_search( .get_chunk_by_id_no_embedding(&row.file_uuid, &row.chunk_id) .await { + // Use extracted text from BM25 result for relationships, otherwise use chunk's text_content + let text = if p.chunk_type == "relationship" { + row.text.clone().or_else(|| p.text_content.clone()) + } else { + p.text_content.clone() + }; + results.push(SearchResult { id: 0, file_uuid: p.file_uuid.clone(), @@ -666,8 +679,8 @@ pub async fn keyword_search( start_time: p.start_time, end_time: p.end_time, raw_text: None, - summary: Some(p.summary.clone()), - text_content: p.text_content.clone(), + summary: text.clone(), + text_content: text, metadata: p.metadata.clone(), similarity: Some(row.bm25_score as f64), file_name: None, diff --git a/src/api/universal_search.rs b/src/api/universal_search.rs index fa99dc03..a310fcd6 100644 --- a/src/api/universal_search.rs +++ b/src/api/universal_search.rs @@ -268,10 +268,7 @@ pub async fn search_people( })?; let total = people.len(); - Ok(Json(PeopleSearchResponse { - people, - total, - })) + Ok(Json(PeopleSearchResponse { people, total })) } // --- Internal search functions --- @@ -631,19 +628,44 @@ async fn search_persons_internal( let safe = fuuid.replace('\'', "''"); sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe)); } - sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", req.page_size.unwrap_or(20))); + sql.push_str(&format!( + " ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", + req.page_size.unwrap_or(20) + )); - let rows: Vec<(String, i32, Option, Option, Option, Option, - Option, Option, Option, Option)> = - sqlx::query_as(&sql).fetch_all(db.pool()).await?; + let rows: Vec<( + String, + i32, + Option, + Option, + Option, + Option, + Option, + Option, + Option, + Option, + )> = sqlx::query_as(&sql).fetch_all(db.pool()).await?; let q_lower = req.query.to_lowercase(); let mut results: Vec = Vec::new(); - for (fuuid, trace_id, name, start_frame, end_frame, frame_count, - key_frame, key_face, avg_confidence, external_id) in rows + for ( + fuuid, + trace_id, + name, + start_frame, + end_frame, + frame_count, + key_frame, + key_face, + avg_confidence, + external_id, + ) in rows { let name_match = !req.query.is_empty() - && name.as_deref().map(|n| n.to_lowercase().contains(&q_lower)).unwrap_or(false); + && name + .as_deref() + .map(|n| n.to_lowercase().contains(&q_lower)) + .unwrap_or(false); let score = if name_match { 0.95 } else { 0.5 }; results.push(SearchResult::Person { @@ -782,15 +804,37 @@ async fn search_people_by_query( let safe = fuuid.replace('\'', "''"); sql.push_str(&format!(" AND tp.file_uuid = '{}'", safe)); } - sql.push_str(&format!(" ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", limit)); + sql.push_str(&format!( + " ORDER BY tp.frame_count DESC NULLS LAST LIMIT {}", + limit + )); - let rows: Vec<(String, i32, Option, Option, Option, Option, - Option, Option, Option, Option)> = - sqlx::query_as(&sql).fetch_all(db.pool()).await?; + let rows: Vec<( + String, + i32, + Option, + Option, + Option, + Option, + Option, + Option, + Option, + Option, + )> = sqlx::query_as(&sql).fetch_all(db.pool()).await?; let mut results: Vec = Vec::new(); - for (fuuid, trace_id, name, start_frame, end_frame, frame_count, - key_frame, key_face, avg_confidence, external_id) in rows + for ( + fuuid, + trace_id, + name, + start_frame, + end_frame, + frame_count, + key_frame, + key_face, + avg_confidence, + external_id, + ) in rows { results.push(PeopleResult { file_uuid: fuuid, diff --git a/src/bin/fix_chunks.rs b/src/bin/fix_chunks.rs index b0a3c2f7..7a34ef57 100644 --- a/src/bin/fix_chunks.rs +++ b/src/bin/fix_chunks.rs @@ -22,7 +22,7 @@ async fn main() -> Result<()> { ) GROUP BY pc.file_uuid, v.fps ORDER BY COUNT(*) DESC - "# + "#, ) .fetch_all(db.pool()) .await?; diff --git a/src/bin/vectorize_missing.rs b/src/bin/vectorize_missing.rs index cdd1a372..c9604088 100644 --- a/src/bin/vectorize_missing.rs +++ b/src/bin/vectorize_missing.rs @@ -4,114 +4,112 @@ use std::time::{Duration, Instant}; #[tokio::main] async fn main() -> Result<()> { - dotenv::from_filename("/Users/accusys/momentry_core_0.1/.env.development").ok(); - tracing_subscriber::fmt::init(); - let pg = PostgresDb::init() .await .context("Failed to init PostgreSQL")?; let qdrant = QdrantDb::new(); let embedder = Embedder::new("embeddinggemma-300m".to_string()); - let uuid = "63acd3bb02b5b9dfbb9d6db499fcc864"; let chunk_table = momentry_core::core::db::schema::table_name("chunk"); - let rows = sqlx::query_as::<_, (String, String, i64, i64, f64, f64, String)>(&format!( - "SELECT chunk_id, text_content, start_frame, end_frame, \ - start_time, end_time, content::text \ + // Get all files with unembedded sentence chunks + let files: Vec<(String,)> = sqlx::query_as(&format!( + "SELECT DISTINCT file_uuid FROM {} \ + WHERE chunk_type = 'sentence' AND embedding IS NULL \ + AND text_content IS NOT NULL AND text_content != ''", + chunk_table + )) + .fetch_all(pg.pool()) + .await?; + + println!( + "Found {} files with unembedded sentence chunks", + files.len() + ); + + let start = Instant::now(); + let mut total_stored = 0usize; + let mut total_errors = 0usize; + let mut total_chunks = 0usize; + + for (file_uuid,) in &files { + let rows: Vec<(String, String, i64, i64, f64, f64)> = sqlx::query_as(&format!( + "SELECT chunk_id, text_content, start_frame, end_frame, start_time, end_time \ FROM {} \ WHERE file_uuid = $1 \ AND chunk_type = 'sentence' \ AND embedding IS NULL \ - AND (text_content IS NOT NULL AND text_content != '') \ + AND text_content IS NOT NULL AND text_content != '' \ ORDER BY id", - chunk_table - )) - .bind(uuid) - .fetch_all(pg.pool()) - .await?; + chunk_table + )) + .bind(file_uuid) + .fetch_all(pg.pool()) + .await?; - let total = rows.len(); - println!( - "Found {} sentence chunks without embedding for {}", - total, uuid - ); + let count = rows.len(); + total_chunks += count; + println!(" {}: {} chunks to vectorize", file_uuid, count); - if total == 0 { - println!("Nothing to vectorize. Exiting."); - return Ok(()); - } - - let start = Instant::now(); - let mut stored = 0usize; - let mut errors = 0usize; - - for (chunk_id, text, start_frame, end_frame, start_time, end_time, _content_str) in &rows { - if text.is_empty() { + if count == 0 { continue; } - match embedder.embed_document(text).await { - Ok(vector) => { - if let Err(e) = pg.store_vector(chunk_id, &vector, uuid).await { - eprintln!("[ERROR] PG store failed for {}: {}", chunk_id, e); - errors += 1; - continue; - } - - let payload = VectorPayload { - file_uuid: uuid.to_string(), - chunk_id: chunk_id.clone(), - chunk_type: "sentence".to_string(), - start_frame: *start_frame, - end_frame: *end_frame, - start_time: *start_time, - end_time: *end_time, - text: Some(text.clone()), - }; - - if let Err(e) = qdrant.upsert_vector(chunk_id, &vector, payload).await { - eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e); - errors += 1; - continue; - } - - stored += 1; - if stored % 500 == 0 || stored == total { - let elapsed = start.elapsed(); - let rate = stored as f64 / elapsed.as_secs_f64(); - let eta = if stored < total { - let remaining = Duration::from_secs_f64((total - stored) as f64 / rate); - format!(" (ETA: {}s)", remaining.as_secs()) - } else { - String::new() - }; - println!( - " [{}/{}] {:.1}% done | {:.0} vec/s | {} errors{}", - stored, - total, - 100.0 * stored as f64 / total as f64, - rate, - errors, - eta, - ); - } + for (chunk_id, text, start_frame, end_frame, start_time, end_time) in &rows { + if text.is_empty() { + continue; } - Err(e) => { - eprintln!("[ERROR] Embedding failed for {}: {}", chunk_id, e); - errors += 1; + + match embedder.embed_document(text).await { + Ok(vector) => { + if let Err(e) = pg.store_vector(&chunk_id, &vector, file_uuid).await { + eprintln!("[ERROR] PG store failed for {}: {}", chunk_id, e); + total_errors += 1; + continue; + } + + let payload = VectorPayload { + file_uuid: file_uuid.clone(), + chunk_id: chunk_id.clone(), + chunk_type: "sentence".to_string(), + start_frame: *start_frame, + end_frame: *end_frame, + start_time: *start_time, + end_time: *end_time, + text: Some(text.clone()), + }; + + if let Err(e) = qdrant.upsert_vector(&chunk_id, &vector, payload).await { + eprintln!("[ERROR] Qdrant upsert failed for {}: {}", chunk_id, e); + total_errors += 1; + continue; + } + + total_stored += 1; + if total_stored % 500 == 0 { + let elapsed = start.elapsed(); + let rate = total_stored as f64 / elapsed.as_secs_f64(); + println!( + " [{}/{}] {:.1} vec/s | {} errors", + total_stored, total_chunks, rate, total_errors + ); + } + } + Err(e) => { + eprintln!("[ERROR] Embedding failed for {}: {}", chunk_id, e); + total_errors += 1; + } } } } let elapsed = start.elapsed(); println!( - "\nDone! {}/{} vectors stored ({} errors) in {:.1}s ({:.0} vec/s avg)", - stored, - total, - errors, + "\nDone! {}/{} vectors stored ({} errors) in {:.1}s", + total_stored, + total_chunks, + total_errors, elapsed.as_secs_f64(), - stored as f64 / elapsed.as_secs_f64(), ); Ok(()) diff --git a/src/core/agent/tools.rs b/src/core/agent/tools.rs index 7666a187..c7314041 100644 --- a/src/core/agent/tools.rs +++ b/src/core/agent/tools.rs @@ -563,7 +563,12 @@ pub async fn exec_smart_search( .filter(|s| !s.is_empty() && *s != "" && *s != "null"); let limit = args.get("limit").and_then(|v| v.as_i64()).unwrap_or(5) as i64; - tracing::info!("[smart_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit); + tracing::info!( + "[smart_search] query='{}', file_uuid={:?}, limit={}", + query, + file_uuid, + limit + ); let chunk_table = schema::table_name("chunk"); let videos = schema::table_name("videos"); @@ -619,7 +624,17 @@ pub async fn exec_smart_search( let cards: Vec = rows .into_iter() .map( - |(chunk_id, text_content, start_frame, end_frame, chunk_type, content, fuuid, file_name, fps)| { + |( + chunk_id, + text_content, + start_frame, + end_frame, + chunk_type, + content, + fuuid, + file_name, + fps, + )| { let source = if let Some(ref c) = content { let text = c.get("text").and_then(|t| t.as_str()).unwrap_or(""); let ocr_text = c.get("ocr_text").and_then(|t| t.as_str()).unwrap_or(""); @@ -641,8 +656,16 @@ pub async fn exec_smart_search( .map(|t| t.chars().take(150).collect::()) .unwrap_or_default(); - let start_time = if fps > 0.0 { start_frame as f64 / fps } else { 0.0 }; - let end_time = if fps > 0.0 { end_frame as f64 / fps } else { 0.0 }; + let start_time = if fps > 0.0 { + start_frame as f64 / fps + } else { + 0.0 + }; + let end_time = if fps > 0.0 { + end_frame as f64 / fps + } else { + 0.0 + }; serde_json::json!({ "card_type": "chunk", @@ -667,7 +690,8 @@ pub async fn exec_smart_search( "query": query, "count": cards.len(), "cards": cards - }).to_string()) + }) + .to_string()) } pub async fn exec_identity_text( @@ -1467,15 +1491,13 @@ pub async fn exec_trace_search( }) .collect(); - Ok( - serde_json::json!({ - "tool": "trace_search", - "query": query, - "count": cards.len(), - "cards": cards - }) - .to_string(), - ) + Ok(serde_json::json!({ + "tool": "trace_search", + "query": query, + "count": cards.len(), + "cards": cards + }) + .to_string()) } /// Semantic search using embedding + Qdrant @@ -1495,7 +1517,12 @@ pub async fn exec_semantic_search( .unwrap_or(10) .min(50) as usize; - tracing::info!("[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", query, file_uuid, limit); + tracing::info!( + "[exec_semantic_search] query='{}', file_uuid={:?}, limit={}", + query, + file_uuid, + limit + ); if query.is_empty() { return Err("query is required".to_string()); @@ -1503,15 +1530,15 @@ pub async fn exec_semantic_search( // Generate embedding let embedder = Embedder::new("embeddinggemma-300m".to_string()); - let embedding = embedder - .embed_query(query) - .await - .map_err(|e| { - tracing::error!("[exec_semantic_search] Embedding failed: {}", e); - format!("Embedding failed: {}", e) - })?; + let embedding = embedder.embed_query(query).await.map_err(|e| { + tracing::error!("[exec_semantic_search] Embedding failed: {}", e); + format!("Embedding failed: {}", e) + })?; - tracing::info!("[exec_semantic_search] Embedding generated, dim={}", embedding.len()); + tracing::info!( + "[exec_semantic_search] Embedding generated, dim={}", + embedding.len() + ); // Search Qdrant let qdrant = QdrantDb::new(); @@ -1526,16 +1553,16 @@ pub async fn exec_semantic_search( })? } else { tracing::info!("[exec_semantic_search] Searching all collections"); - qdrant - .search(&embedding, limit) - .await - .map_err(|e| { - tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e); - format!("Qdrant search failed: {}", e) - })? + qdrant.search(&embedding, limit).await.map_err(|e| { + tracing::error!("[exec_semantic_search] Qdrant search failed: {}", e); + format!("Qdrant search failed: {}", e) + })? }; - tracing::info!("[exec_semantic_search] Qdrant returned {} hits", search_results.len()); + tracing::info!( + "[exec_semantic_search] Qdrant returned {} hits", + search_results.len() + ); // Enrich from PostgreSQL let chunk_table = schema::table_name("chunk"); @@ -1543,29 +1570,24 @@ pub async fn exec_semantic_search( let mut cards = Vec::new(); for hit in search_results.iter() { - let row: Option<( - String, - String, - f64, - f64, - f64, - Option, - String, - )> = sqlx::query_as(&format!( - "SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \ + let row: Option<(String, String, f64, f64, f64, Option, String)> = + sqlx::query_as(&format!( + "SELECT c.chunk_id, c.chunk_type, c.start_time, c.end_time, c.fps, \ c.text_content, v.file_name \ FROM {} c \ JOIN {} v ON v.file_uuid = c.file_uuid \ WHERE c.file_uuid = $1 AND c.chunk_id = $2", - chunk_table, videos - )) - .bind(&hit.uuid) - .bind(&hit.chunk_id) - .fetch_optional(pool) - .await - .map_err(|e| format!("PG query failed: {}", e))?; + chunk_table, videos + )) + .bind(&hit.uuid) + .bind(&hit.chunk_id) + .fetch_optional(pool) + .await + .map_err(|e| format!("PG query failed: {}", e))?; - if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) = row { + if let Some((chunk_id, chunk_type, start_time, end_time, fps, text_content, file_name)) = + row + { let start_frame = (start_time * fps) as i64; let end_frame = (end_time * fps) as i64; let text_preview = text_content @@ -1590,15 +1612,13 @@ pub async fn exec_semantic_search( } } - Ok( - serde_json::json!({ - "tool": "semantic_search", - "query": query, - "count": cards.len(), - "cards": cards - }) - .to_string(), - ) + Ok(serde_json::json!({ + "tool": "semantic_search", + "query": query, + "count": cards.len(), + "cards": cards + }) + .to_string()) } /// Search named face profiles by name — finds face_track TKG nodes whose label @@ -1685,13 +1705,11 @@ pub async fn exec_face_profile_search( }) .collect(); - Ok( - serde_json::json!({ - "tool": "face_profile_search", - "query": name, - "count": cards.len(), - "cards": cards - }) - .to_string(), - ) + Ok(serde_json::json!({ + "tool": "face_profile_search", + "query": name, + "count": cards.len(), + "cards": cards + }) + .to_string()) } diff --git a/src/core/db/postgres_db.rs b/src/core/db/postgres_db.rs index 5aa9c391..a10fa65e 100644 --- a/src/core/db/postgres_db.rs +++ b/src/core/db/postgres_db.rs @@ -891,6 +891,34 @@ pub struct ChildChunkResult { pub speaker_ids: Vec, } +/// Extract actual text content from a relationship chunk's content JSON. +/// Returns the related sentence text if found, otherwise falls back to empty string. +fn extract_relationship_text(content_json: &str) -> String { + if let Ok(json) = serde_json::from_str::(content_json) { + if let Some(target) = json.get("target_node") { + if let Some(label) = target.get("label").and_then(|v| v.as_str()) { + if let Some(pos) = label.find(':') { + let text_part = label[pos + 1..].trim(); + if !text_part.is_empty() { + return text_part.to_string(); + } + } + } + } + if let Some(source) = json.get("source_node") { + if let Some(label) = source.get("label").and_then(|v| v.as_str()) { + if let Some(pos) = label.find(':') { + let text_part = label[pos + 1..].trim(); + if !text_part.is_empty() { + return text_part.to_string(); + } + } + } + } + } + String::new() +} + impl PostgresDb { pub fn from_pool(pool: PgPool) -> Self { Self { @@ -1240,8 +1268,14 @@ impl PostgresDb { // ── Trace Profiles (VLM metadata for face traces) ── sqlx::query("CREATE TABLE IF NOT EXISTS trace_profiles (id SERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, trace_id INTEGER NOT NULL, name VARCHAR(255), start_frame BIGINT, end_frame BIGINT, frame_count INTEGER, key_frame VARCHAR(255), key_face VARCHAR(255), status VARCHAR(50) DEFAULT 'pending', avg_confidence DOUBLE PRECISION, vlm_description TEXT, vlm_clothing TEXT, vlm_tags TEXT[], vlm_location VARCHAR(255), vlm_setting VARCHAR(255), vlm_lighting VARCHAR(100), vlm_weather VARCHAR(100), vlm_hand_objects TEXT, vlm_has_plants BOOLEAN, vlm_has_animals BOOLEAN, vlm_background TEXT, vlm_bg_tags TEXT[], vlm_model VARCHAR(64), metadata JSONB DEFAULT '{}', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(file_uuid, trace_id))").execute(pool).await?; - sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)").execute(pool).await?; - sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)").execute(pool).await?; + sqlx::query( + "CREATE INDEX IF NOT EXISTS idx_trace_profiles_file_uuid ON trace_profiles(file_uuid)", + ) + .execute(pool) + .await?; + sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_name ON trace_profiles(name)") + .execute(pool) + .await?; sqlx::query("CREATE INDEX IF NOT EXISTS idx_trace_profiles_tags ON trace_profiles USING GIN(vlm_tags)").execute(pool).await?; // ── Cuts ── @@ -3508,7 +3542,10 @@ impl PostgresDb { use sqlx::Row; // Build WHERE clauses dynamically to handle optional params - let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()]; + let mut clauses = vec![ + "(text_content ILIKE $2 OR content::text ILIKE $2)".to_string(), + "COALESCE(text_content, content::text, '') != ''".to_string(), + ]; let mut next_idx = 3; if file_uuid.is_some() { next_idx += 1; @@ -3522,11 +3559,22 @@ impl PostgresDb { let where_sql = clauses.join(" AND "); let sql = format!( - "SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \ - (1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \ + "SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \ + CASE \ + WHEN text_content ILIKE $2 THEN \ + (1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8)) \ + ELSE \ + (1.0 - (POSITION(LOWER($1) IN LOWER(content::text))::float8 / NULLIF(LENGTH(content::text), 0)::float8)) \ + END::float8 as score, \ + CASE chunk_type \ + WHEN 'sentence' THEN 1 \ + WHEN 'ocr' THEN 2 \ + WHEN 'cut' THEN 3 \ + ELSE 4 \ + END as priority \ FROM {} \ WHERE {} \ - ORDER BY score DESC \ + ORDER BY priority ASC, score DESC \ LIMIT $3", table, where_sql ); @@ -3542,17 +3590,32 @@ impl PostgresDb { Ok(rows .into_iter() - .map(|r| Bm25Result { - file_uuid: r.get("file_uuid"), - chunk_id: r.get("chunk_id"), - chunk_type: r.get("chunk_type"), - uuid: r.get("file_uuid"), - text: r.get("text_content"), - start_time: r.get("start_time"), - end_time: r.get("end_time"), - bm25_score: r.get("score"), - vector_score: 0.0, - combined_score: r.get("score"), + .map(|r| { + let chunk_type: String = r.get("chunk_type"); + let text: Option = if chunk_type == "relationship" { + let content_text: String = r.get("content_text"); + let extracted = extract_relationship_text(&content_text); + if extracted.is_empty() { + r.get("text_content") + } else { + Some(extracted) + } + } else { + r.get("text_content") + }; + + Bm25Result { + file_uuid: r.get("file_uuid"), + chunk_id: r.get("chunk_id"), + chunk_type: r.get("chunk_type"), + uuid: r.get("file_uuid"), + text, + start_time: r.get("start_time"), + end_time: r.get("end_time"), + bm25_score: r.get("score"), + vector_score: 0.0, + combined_score: r.get("score"), + } }) .collect()) } diff --git a/src/core/file_lifecycle.rs b/src/core/file_lifecycle.rs index 71f9b840..2e0d445a 100644 --- a/src/core/file_lifecycle.rs +++ b/src/core/file_lifecycle.rs @@ -96,7 +96,13 @@ pub struct IngestionState { pub const STAGE_1_PROCESSORS: &[&str] = &["asr", "ocr", "face"]; /// Stage 2 processors (depend on stage 1) -pub const STAGE_2_PROCESSORS: &[&str] = &["asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster"]; +pub const STAGE_2_PROCESSORS: &[&str] = &[ + "asrx", + "face_vector", + "face_trace", + "speaker_vector", + "face_cluster", +]; /// Stage 3 processors (depend on stage 2 or face) pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"]; @@ -104,9 +110,16 @@ pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"]; /// All processors in order pub const ALL_PROCESSORS: &[&str] = &[ "cut", // Registration - "asr", "ocr", "face", // Stage 1 - "asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", // Stage 2 - "pose", "appearance", // Stage 3 + "asr", + "ocr", + "face", // Stage 1 + "asrx", + "face_vector", + "face_trace", + "speaker_vector", + "face_cluster", // Stage 2 + "pose", + "appearance", // Stage 3 ]; /// Get processor dependencies @@ -140,22 +153,22 @@ impl FileLifecycle { /// Create a new lifecycle for a file pub fn new(file_uuid: &str) -> Self { let now = chrono::Utc::now().to_rfc3339(); - + let mut stage_1_processors = HashMap::new(); for proc in STAGE_1_PROCESSORS { stage_1_processors.insert(proc.to_string(), ProcessorState::new("pending")); } - + let mut stage_2_processors = HashMap::new(); for proc in STAGE_2_PROCESSORS { stage_2_processors.insert(proc.to_string(), ProcessorState::new("pending")); } - + let mut stage_3_processors = HashMap::new(); for proc in STAGE_3_PROCESSORS { stage_3_processors.insert(proc.to_string(), ProcessorState::new("pending")); } - + Self { version: LIFECYCLE_VERSION.to_string(), file_uuid: file_uuid.to_string(), @@ -185,16 +198,22 @@ impl FileLifecycle { /// Create lifecycle from existing outputs (for recovery) pub fn from_existing_outputs(output_dir: &str, file_uuid: &str) -> Self { let mut lifecycle = Self::new(file_uuid); - + // Check registration outputs - let has_profile = Path::new(output_dir).join(format!("{}.profile.json", file_uuid)).exists(); - let has_probe = Path::new(output_dir).join(format!("{}.probe.json", file_uuid)).exists(); - let has_cut = Path::new(output_dir).join(format!("{}.cut.json", file_uuid)).exists(); - + let has_profile = Path::new(output_dir) + .join(format!("{}.profile.json", file_uuid)) + .exists(); + let has_probe = Path::new(output_dir) + .join(format!("{}.probe.json", file_uuid)) + .exists(); + let has_cut = Path::new(output_dir) + .join(format!("{}.cut.json", file_uuid)) + .exists(); + if has_profile && has_probe && has_cut { lifecycle.mark_stage_completed("registration"); } - + // Check stage 1 processors for proc in STAGE_1_PROCESSORS { let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc)); @@ -202,33 +221,41 @@ impl FileLifecycle { lifecycle.mark_processor_completed(proc, None); } } - + // Check stage 2 processors - let has_asrx = Path::new(output_dir).join(format!("{}.asrx.json", file_uuid)).exists(); + let has_asrx = Path::new(output_dir) + .join(format!("{}.asrx.json", file_uuid)) + .exists(); if has_asrx { lifecycle.mark_processor_completed("asrx", None); // speaker_vector comes from asrx lifecycle.mark_processor_completed("speaker_vector", None); } - + // face_vector: check if face.json exists (vectors stored in Qdrant) - let has_face = Path::new(output_dir).join(format!("{}.face.json", file_uuid)).exists(); + let has_face = Path::new(output_dir) + .join(format!("{}.face.json", file_uuid)) + .exists(); if has_face { lifecycle.mark_processor_completed("face_vector", None); } - + // face_trace: check face_traced.json (continuous face tracking) - let has_face_traced = Path::new(output_dir).join(format!("{}.face_traced.json", file_uuid)).exists(); + let has_face_traced = Path::new(output_dir) + .join(format!("{}.face_traced.json", file_uuid)) + .exists(); if has_face_traced { lifecycle.mark_processor_completed("face_trace", None); } - + // face_cluster: check face_cluster.json (deduplication of traces) - let has_face_cluster = Path::new(output_dir).join(format!("{}.face_cluster.json", file_uuid)).exists(); + let has_face_cluster = Path::new(output_dir) + .join(format!("{}.face_cluster.json", file_uuid)) + .exists(); if has_face_cluster { lifecycle.mark_processor_completed("face_cluster", None); } - + // Check stage 3 processors for proc in STAGE_3_PROCESSORS { let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc)); @@ -236,7 +263,7 @@ impl FileLifecycle { lifecycle.mark_processor_completed(proc, None); } } - + lifecycle.update_group_status(); lifecycle } @@ -251,8 +278,7 @@ impl FileLifecycle { /// Save lifecycle to disk pub fn save_to_disk(&self, output_dir: &str) -> Result<()> { let path = Self::lifecycle_path(output_dir, &self.file_uuid); - let json = serde_json::to_string_pretty(self) - .context("Failed to serialize lifecycle")?; + let json = serde_json::to_string_pretty(self).context("Failed to serialize lifecycle")?; std::fs::write(&path, json) .with_context(|| format!("Failed to write lifecycle to {}", path.display()))?; tracing::debug!("[Lifecycle] Saved for {}", self.file_uuid); @@ -278,7 +304,7 @@ impl FileLifecycle { pub fn mark_stage_started(&mut self, stage: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); - + match stage { "registration" => { self.stages.registration.status = "in_progress".to_string(); @@ -313,7 +339,7 @@ impl FileLifecycle { pub fn mark_stage_completed(&mut self, stage: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); - + match stage { "registration" => { self.stages.registration.status = "completed".to_string(); @@ -343,7 +369,7 @@ impl FileLifecycle { pub fn mark_processor_started(&mut self, processor: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); - + let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, @@ -351,12 +377,12 @@ impl FileLifecycle { "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; - + if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "running".to_string(); proc_state.started_at = Some(now); } - + // Update group status group.status = "in_progress".to_string(); } @@ -365,7 +391,7 @@ impl FileLifecycle { pub fn mark_processor_completed(&mut self, processor: &str, output_count: Option) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); - + let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, @@ -373,13 +399,13 @@ impl FileLifecycle { "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; - + if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "completed".to_string(); proc_state.completed_at = Some(now); proc_state.output_count = output_count; } - + self.update_group_status(); } @@ -387,7 +413,7 @@ impl FileLifecycle { pub fn mark_processor_failed(&mut self, processor: &str, error: &str, retry_count: i32) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); - + let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, @@ -395,20 +421,20 @@ impl FileLifecycle { "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; - + if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "failed".to_string(); proc_state.error = Some(error.to_string()); proc_state.retry_count = Some(retry_count); } - + self.update_group_status(); } /// Update processor progress pub fn update_processor_progress(&mut self, processor: &str, current: i64, total: i64) { self.updated_at = chrono::Utc::now().to_rfc3339(); - + let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, @@ -416,7 +442,7 @@ impl FileLifecycle { "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; - + if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.progress = Some(ProgressInfo { current, total }); } @@ -427,11 +453,11 @@ impl FileLifecycle { // Update stage 1 let stage_1 = &mut self.stages.stage_1_processors; stage_1.status = compute_group_status(&stage_1.processors); - + // Update stage 2 let stage_2 = &mut self.stages.stage_2_processors; stage_2.status = compute_group_status(&stage_2.processors); - + // Update stage 3 let stage_3 = &mut self.stages.stage_3_processors; stage_3.status = compute_group_status(&stage_3.processors); @@ -445,7 +471,7 @@ impl FileLifecycle { if deps.is_empty() { return true; } - + for dep in deps { if !self.is_processor_completed(dep) { return false; @@ -463,8 +489,10 @@ impl FileLifecycle { "stage_3" => &self.stages.stage_3_processors, _ => return processor == "cut" && self.stages.registration.status == "completed", }; - - group.processors.get(processor) + + group + .processors + .get(processor) .map(|p| p.status == "completed") .unwrap_or(false) } @@ -472,40 +500,40 @@ impl FileLifecycle { /// Get next processors to run pub fn get_next_processors(&self) -> Vec { let mut next = Vec::new(); - + // Check stage 1 if self.stages.registration.status != "completed" { return next; // Registration must complete first } - + for proc in STAGE_1_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } - + if !next.is_empty() { return next; } - + // Check stage 2 for proc in STAGE_2_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } - + if !next.is_empty() { return next; } - + // Check stage 3 for proc in STAGE_3_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } - + next } @@ -546,13 +574,13 @@ impl FileLifecycle { pub fn overall_progress(&self) -> f64 { let mut completed = 0; let mut total = 0; - + // Registration total += 1; if self.stages.registration.status == "completed" { completed += 1; } - + // Stage 1 for proc in STAGE_1_PROCESSORS { total += 1; @@ -560,7 +588,7 @@ impl FileLifecycle { completed += 1; } } - + // Stage 2 for proc in STAGE_2_PROCESSORS { total += 1; @@ -568,7 +596,7 @@ impl FileLifecycle { completed += 1; } } - + // Stage 3 for proc in STAGE_3_PROCESSORS { total += 1; @@ -576,14 +604,24 @@ impl FileLifecycle { completed += 1; } } - + // Rules total += 3; - if self.stages.rule_1_ingestion.status == "completed" { completed += 1; } - if self.stages.rule_2_ingestion.status == "completed" { completed += 1; } - if self.stages.rule_3_ingestion.status == "completed" { completed += 1; } - - if total == 0 { 0.0 } else { (completed as f64 / total as f64) * 100.0 } + if self.stages.rule_1_ingestion.status == "completed" { + completed += 1; + } + if self.stages.rule_2_ingestion.status == "completed" { + completed += 1; + } + if self.stages.rule_3_ingestion.status == "completed" { + completed += 1; + } + + if total == 0 { + 0.0 + } else { + (completed as f64 / total as f64) * 100.0 + } } } @@ -630,7 +668,7 @@ fn compute_group_status(processors: &HashMap) -> String let mut has_failed = false; let mut has_pending = false; let mut completed_count = 0; - + for proc in processors.values() { match proc.status.as_str() { "running" => has_running = true, @@ -640,7 +678,7 @@ fn compute_group_status(processors: &HashMap) -> String _ => {} } } - + if has_running { "in_progress".to_string() } else if has_failed { @@ -678,14 +716,14 @@ mod tests { #[test] fn test_can_run_processor() { let mut lifecycle = FileLifecycle::new("test"); - + // Initially, asrx cannot run (needs cut + asr) assert!(!lifecycle.can_run_processor("asrx")); - + // After registration, still cannot run (needs asr) lifecycle.mark_stage_completed("registration"); assert!(!lifecycle.can_run_processor("asrx")); - + // After asr completes, can run lifecycle.mark_processor_completed("asr", Some(10)); assert!(lifecycle.can_run_processor("asrx")); @@ -695,7 +733,7 @@ mod tests { fn test_overall_progress() { let mut lifecycle = FileLifecycle::new("test"); assert_eq!(lifecycle.overall_progress(), 0.0); - + lifecycle.mark_stage_completed("registration"); let progress = lifecycle.overall_progress(); assert!(progress > 0.0 && progress < 100.0); diff --git a/src/core/file_profile.rs b/src/core/file_profile.rs index ce00c898..300a32b5 100644 --- a/src/core/file_profile.rs +++ b/src/core/file_profile.rs @@ -418,6 +418,9 @@ impl FaceTraceProfile { std::fs::write(&kf_path, jpeg) .with_context(|| format!("Failed to write {}", kf_path.display()))?; self.key_frame = Some("key_frame.jpg".to_string()); + } else if dir.join("key_frame.jpg").exists() { + // Extraction failed but file already exists on disk: preserve reference + self.key_frame = Some("key_frame.jpg".to_string()); } // Write key_face.jpg @@ -426,6 +429,9 @@ impl FaceTraceProfile { std::fs::write(&face_path, jpeg) .with_context(|| format!("Failed to write {}", face_path.display()))?; self.key_face = Some("key_face.jpg".to_string()); + } else if dir.join("key_face.jpg").exists() { + // Crop failed but file already exists on disk: preserve reference + self.key_face = Some("key_face.jpg".to_string()); } // Write trace_profile.json diff --git a/src/core/ingestion.rs b/src/core/ingestion.rs index 65b05ddc..af647202 100644 --- a/src/core/ingestion.rs +++ b/src/core/ingestion.rs @@ -123,17 +123,37 @@ impl IngestionService { let mut width = 0u32; let mut height = 0u32; let mut fps = 0.0; + let mut nb_frames: Option = None; if let Some(ref probe) = probe_result { for stream in &probe.streams { if stream.codec_type.as_deref() == Some("video") { width = stream.width.unwrap_or(0); height = stream.height.unwrap_or(0); - if let Some(fps_str) = &stream.r_frame_rate { + + // Get nb_frames first (needed for actual fps calculation) + if let Some(nb_frames_str) = &stream.nb_frames { + if let Ok(n) = nb_frames_str.parse::() { + nb_frames = Some(n); + } + } + + // Calculate actual fps from nb_frames / duration (more accurate than r_frame_rate) + if let Some(frames) = nb_frames { + if duration > 0.0 { + fps = frames as f64 / duration; + info!( + "Using actual fps from nb_frames/duration: {} / {} = {:.2} fps", + frames, duration, fps + ); + } + } else if let Some(fps_str) = &stream.r_frame_rate { + // Fallback to r_frame_rate if nb_frames or duration unavailable if let Some((num, den)) = fps_str.split_once('/') { if let (Ok(n), Ok(d)) = (num.parse::(), den.parse::()) { if d > 0.0 { fps = n / d; + info!("Using r_frame_rate as fps: {} fps", fps); } } } diff --git a/src/core/processor/executor.rs b/src/core/processor/executor.rs index bde7c849..ed0f66fd 100644 --- a/src/core/processor/executor.rs +++ b/src/core/processor/executor.rs @@ -535,6 +535,8 @@ impl PythonExecutor { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); + } else if !line.trim().is_empty() { + tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, @@ -738,6 +740,8 @@ impl PythonExecutor { Ok(Some(line)) => { if line.starts_with(&format!("{}_", log_prefix)) { tracing::info!("[{}] {}", log_prefix, line); + } else if !line.trim().is_empty() { + tracing::warn!("[{} stderr] {}", log_prefix, line); } } Ok(None) => stderr_done = true, @@ -825,6 +829,202 @@ impl PythonExecutor { Ok(()) } + /// Like `run_with_output_idx_and_frames` but accepts a `CancellationToken` so the caller + /// can cleanly abort the Python subprocess without leaking processes. + pub async fn run_with_output_idx_and_frames_with_cancel( + &self, + script_name: &str, + args: &[&str], + uuid: Option<&str>, + log_prefix: &str, + timeout_duration: Option, + output_idx: Option, + frames: Option<&[i64]>, + cancel: tokio_util::sync::CancellationToken, + ) -> Result<()> { + let script_path = self.scripts_dir.join(script_name); + + if !script_path.exists() { + anyhow::bail!("Script not found: {:?}", script_path); + } + + self.verify_script_integrity(script_name).context( + "Pre-execution integrity check failed — possible version mismatch or corruption", + )?; + + let output_path = + output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); + let tmp_path = output_path.as_ref().map(|p| { + let mut tmp = p.to_path_buf(); + tmp.set_extension("json.tmp"); + tmp + }); + + let mut cmd = Command::new(&self.python_path); + cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR); + cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA); + cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA); + cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX); + if let Ok(qdrant_url) = std::env::var("QDRANT_URL") { + cmd.env("QDRANT_URL", qdrant_url); + } + if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") { + cmd.env("QDRANT_API_KEY", qdrant_api_key); + } + cmd.arg(&script_path); + + for (i, arg) in args.iter().enumerate() { + if Some(i) == output_idx { + if let Some(ref tmp) = tmp_path { + cmd.arg(tmp); + continue; + } + } + cmd.arg(arg); + } + + if let Some(u) = uuid { + cmd.arg("--uuid").arg(u); + } + + // Append extra args (e.g. --threshold) after --uuid + // Pass frame list for 8Hz sampling + if let Some(frames) = frames { + if !frames.is_empty() { + let frames_str = Self::format_frames_arg(frames); + cmd.arg("--frames").arg(&frames_str); + } + } + + cmd.stdout(Stdio::piped()); + cmd.stderr(Stdio::piped()); + cmd.kill_on_drop(true); + cmd.process_group(0); + + tracing::info!("[{}] Starting: {:?}", log_prefix, script_name); + + let mut child = cmd + .spawn() + .with_context(|| format!("Failed to run {}", script_name))?; + let child_pid = child.id(); + + let stdout = child.stdout.take().context("Failed to capture stdout")?; + let stderr = child.stderr.take().context("Failed to capture stderr")?; + + let mut stdout_reader = BufReader::new(stdout).lines(); + let mut stderr_reader = BufReader::new(stderr).lines(); + + let run_future = async { + let mut stdout_done = false; + let mut stderr_done = false; + loop { + tokio::select! { + line = stdout_reader.next_line(), if !stdout_done => { + match line { + Ok(Some(line)) => { + if line.starts_with(&format!("{}_", log_prefix)) { + tracing::info!("[{}] {}", log_prefix, line); + } + } + Ok(None) => stdout_done = true, + Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e), + } + } + line = stderr_reader.next_line(), if !stderr_done => { + match line { + Ok(Some(line)) => { + if line.starts_with(&format!("{}_", log_prefix)) { + tracing::info!("[{}] {}", log_prefix, line); + } else if !line.trim().is_empty() { + tracing::warn!("[{} stderr] {}", log_prefix, line); + } + } + Ok(None) => stderr_done = true, + Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e), + } + } + _ = cancel.cancelled() => { + tracing::info!("[{}] Cancelled by caller", log_prefix); + if let Some(pid) = child_pid { + unsafe { libc::killpg(pid as i32, libc::SIGTERM); } + } + return Err(anyhow::anyhow!("{} cancelled by caller", script_name)); + } + status = child.wait() => { + match status { + Ok(status) => { + if !status.success() { + tracing::error!("[{}] Process failed: {}", log_prefix, status); + return Err(anyhow::anyhow!("{} exited with: {}", script_name, status)); + } + tracing::info!("[{}] Completed successfully", log_prefix); + } + Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e), + } + break; + } + } + } + Ok(()) + }; + + let mark_failed = || { + if let Some(tmp) = &tmp_path { + if tmp.exists() { + if let Some(out) = &output_path { + let is_valid = std::fs::read_to_string(tmp) + .ok() + .and_then(|c| serde_json::from_str::(&c).ok()) + .is_some(); + if is_valid { + let mut partial_path = out.to_path_buf(); + partial_path.set_extension("json.partial"); + let _ = std::fs::rename(tmp, &partial_path); + tracing::warn!("[Executor] Partial output preserved: {:?}", partial_path); + } else { + let mut err_path = out.to_path_buf(); + err_path.set_extension("json.err"); + let _ = std::fs::rename(tmp, &err_path); + } + } + } + } + }; + + if let Some(duration) = timeout_duration { + match timeout(duration, run_future).await { + Ok(Ok(())) => {} + Ok(Err(e)) => { + mark_failed(); + return Err(e); + } + Err(_) => { + mark_failed(); + if let Some(pid) = child_pid { + unsafe { libc::killpg(pid as i32, libc::SIGKILL); } + } + child.kill().await.context("Failed to kill process")?; + anyhow::bail!("{} timed out after {:?}", script_name, duration); + } + } + } else { + if let Err(e) = run_future.await { + mark_failed(); + return Err(e); + } + } + + if let Some(tmp) = &tmp_path { + if tmp.exists() { + if let Some(out) = &output_path { + let _ = std::fs::rename(tmp, out); + } + } + } + + Ok(()) + } + pub async fn run_with_output( &self, script_name: &str, diff --git a/src/core/processor/face_clustering.rs b/src/core/processor/face_clustering.rs index 154ad92b..9c843ed0 100644 --- a/src/core/processor/face_clustering.rs +++ b/src/core/processor/face_clustering.rs @@ -17,6 +17,14 @@ pub struct FaceClusterInfo { pub cluster_id: String, pub face_count: usize, pub representative_face: Option, + pub similarity: Option, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct ClusterSimilarity { + pub min: f64, + pub avg: f64, + pub threshold: f64, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -55,6 +63,7 @@ pub async fn process_face_cluster( output_path: &str, uuid: Option<&str>, frames: Option<&[i64]>, + similarity_threshold: Option, ) -> Result { let executor = PythonExecutor::new()?; let script_path = executor.script_path("fast_face_clustering_processor.py"); @@ -69,13 +78,28 @@ pub async fn process_face_cluster( }); } + // Build args with optional --threshold + let distance = similarity_threshold.map(|s| 1.0 - s); + let mut args = vec![video_path, output_path]; + if let Some(d) = distance { + let threshold_str = format!("{:.4}", d); + args.push("--threshold"); + args.push(Box::leak(threshold_str.into_boxed_str()) as &str); + tracing::info!( + "[FACE_CLUSTER] similarity={:.2} → distance={:.4}", + similarity_threshold.unwrap_or(0.65), + d + ); + } + executor - .run_with_frames( + .run_with_output_idx_and_frames( "fast_face_clustering_processor.py", - &[video_path, output_path], + &args, uuid, "FACE_CLUSTER", Some(FACE_CLUSTER_TIMEOUT), + Some(1), frames, ) .await diff --git a/src/core/processor/ocr.rs b/src/core/processor/ocr.rs index 25bb0ccf..3c117bf7 100644 --- a/src/core/processor/ocr.rs +++ b/src/core/processor/ocr.rs @@ -96,8 +96,7 @@ pub fn group_ocr_texts_by_zone_and_proximity( for frame in frames { // Rule 2: Frame difference detection - let current_texts: HashSet = - frame.texts.iter().map(|t| t.text.clone()).collect(); + let current_texts: HashSet = frame.texts.iter().map(|t| t.text.clone()).collect(); let similarity = jaccard_similarity(&last_texts, ¤t_texts); if !last_texts.is_empty() && similarity < TEXT_SIMILARITY_THRESHOLD { diff --git a/src/core/processor/tkg.rs b/src/core/processor/tkg.rs index 19a66f74..78aaf6e7 100644 --- a/src/core/processor/tkg.rs +++ b/src/core/processor/tkg.rs @@ -1304,13 +1304,31 @@ async fn build_face_track_nodes_from_qdrant( // Crop key_face JPEG bytes from key_frame using representative bbox (best confidence frame) let key_face_jpeg: Option> = key_frame_jpeg.as_ref().and_then(|kf| { // Find bbox for best_frame from trace frames - let (_, bx, by, bw, bh) = agg.frames.iter().find(|(f, _, _, _, _)| *f == agg.best_frame)?; + let (bf, bx, by, bw, bh) = agg + .frames + .iter() + .find(|(f, _, _, _, _)| *f == agg.best_frame)?; + let (bx, by, bw, bh) = (*bx, *by, *bw, *bh); + + // Validate bbox: must have positive dimensions + if bw < 2.0 || bh < 2.0 { + tracing::warn!( + "[TKG] trace {}: invalid bbox {}x{} at ({},{}), skipping key_face", + tid, + bw, + bh, + bx, + by + ); + return None; + } + let crop_filter = format!( "crop={}:{}:{}:{}", - (*bw as i64).max(1), - (*bh as i64).max(1), - (*bx as i64).max(0), - (*by as i64).max(0), + (bw as i64).max(1), + (bh as i64).max(1), + (bx as i64).max(0), + (by as i64).max(0), ); let mut cmd = std::process::Command::new("ffmpeg"); cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"]) @@ -1336,7 +1354,7 @@ async fn build_face_track_nodes_from_qdrant( // Save all three files to output/{file_uuid}/{trace_id}/ let mut key_frame_file = agg.best_frame.to_string(); let mut key_face_file = agg.best_point_id.as_deref().unwrap_or("").to_string(); - + match trace_profile.save( output_dir, key_frame_jpeg.as_deref(), @@ -1347,7 +1365,154 @@ async fn build_face_track_nodes_from_qdrant( key_face_file = "key_face.jpg".to_string(); } Err(e) => { - tracing::error!("[TKG] Failed to save trace_profile for trace {}: {}", tid, e); + tracing::error!( + "[TKG] Failed to save trace_profile for trace {}: {}", + tid, + e + ); + } + } + + // Validate all three outputs exist: key_frame.jpg, key_face.jpg, trace_profile.json + // If missing, retry extraction on the spot + let trace_dir = + crate::core::file_profile::FaceTraceProfile::trace_dir(output_dir, file_uuid, *tid); + let kf_path = trace_dir.join("key_frame.jpg"); + let kface_path = trace_dir.join("key_face.jpg"); + let tp_path = + crate::core::file_profile::FaceTraceProfile::profile_path(output_dir, file_uuid, *tid); + + let mut need_retry = false; + if !kf_path.exists() { + tracing::warn!( + "[TKG-VERIFY] trace {}: key_frame.jpg missing, retrying", + tid + ); + need_retry = true; + } + if !kface_path.exists() { + tracing::warn!("[TKG-VERIFY] trace {}: key_face.jpg missing, retrying", tid); + need_retry = true; + } + if !tp_path.exists() { + tracing::warn!( + "[TKG-VERIFY] trace {}: trace_profile.json missing, retrying", + tid + ); + need_retry = true; + } + + if need_retry { + if let Some(ref vp) = video_path { + let timestamp = agg.best_frame as f64 / actual_fps; + // Retry key_frame extraction + if !kf_path.exists() { + if let Ok(output) = std::process::Command::new("ffmpeg") + .args([ + "-y", + "-v", + "quiet", + "-ss", + &format!("{:.3}", timestamp), + "-i", + vp, + ]) + .args([ + "-frames:v", + "1", + "-q:v", + "2", + "-f", + "image2pipe", + "-c:v", + "mjpeg", + "pipe:1", + ]) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .output() + { + if output.status.success() && !output.stdout.is_empty() { + let _ = std::fs::write(&kf_path, &output.stdout); + if kf_path.exists() { + tracing::info!( + "[TKG-VERIFY] trace {}: key_frame.jpg recovered", + tid + ); + key_frame_file = "key_frame.jpg".to_string(); + } + } + } + } + // Retry key_face crop + if !kface_path.exists() && kf_path.exists() { + let (_, bx, by, bw, bh) = agg + .frames + .iter() + .find(|(f, _, _, _, _)| *f == agg.best_frame) + .cloned() + .unwrap_or((0, 0.0, 0.0, 100.0, 100.0)); + + // Validate bbox + if bw < 2.0 || bh < 2.0 { + tracing::warn!( + "[TKG-VERIFY] trace {}: invalid bbox {}x{}, skipping key_face retry", + tid, + bw, + bh + ); + } else { + let crop_filter = format!( + "crop={}:{}:{}:{}", + (bw as i64).max(1), + (bh as i64).max(1), + (bx as i64).max(0), + (by as i64).max(0), + ); + if let Ok(kf_bytes) = std::fs::read(&kf_path) { + let mut cmd = std::process::Command::new("ffmpeg"); + cmd.args(["-y", "-v", "quiet", "-f", "image2pipe", "-i", "pipe:0"]) + .args(["-frames:v", "1", "-q:v", "2", "-vf"]) + .arg(&crop_filter) + .args(["-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + if let Ok(mut child) = cmd.spawn() { + if let Some(ref mut stdin) = child.stdin { + use std::io::Write; + let _ = stdin.write_all(&kf_bytes); + } + if let Ok(output) = child.wait_with_output() { + if output.status.success() && !output.stdout.is_empty() { + let _ = std::fs::write(&kface_path, &output.stdout); + if kface_path.exists() { + tracing::info!( + "[TKG-VERIFY] trace {}: key_face.jpg recovered", + tid + ); + key_face_file = "key_face.jpg".to_string(); + } + } + } + } + } + } + } + // Update trace_profile with recovered file paths, then rewrite profile + // (even if it already exists — it may have stale null key_frame/key_face) + if kf_path.exists() { + trace_profile.key_frame = Some("key_frame.jpg".to_string()); + } + if kface_path.exists() { + trace_profile.key_face = Some("key_face.jpg".to_string()); + } + if let Ok(json) = serde_json::to_string_pretty(&trace_profile) { + let _ = std::fs::write(&tp_path, json); + if tp_path.exists() { + tracing::info!("[TKG-VERIFY] trace {}: trace_profile.json rewritten", tid); + } + } } } @@ -1399,7 +1564,11 @@ async fn build_face_track_nodes_from_qdrant( count += 1; } - tracing::info!("[TKG-face_track] built {} face_track nodes for {}", count, file_uuid); + tracing::info!( + "[TKG-face_track] built {} face_track nodes for {}", + count, + file_uuid + ); Ok(count) } diff --git a/src/core/proxy.rs b/src/core/proxy.rs index 88116975..ce4ed179 100644 --- a/src/core/proxy.rs +++ b/src/core/proxy.rs @@ -23,8 +23,7 @@ pub fn proxy_output_path(file_path: &str) -> Result { } fn ffmpeg_cmd() -> Command { - let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG") - .unwrap_or_else(|_| "ffmpeg".to_string()); + let ffmpeg_path = std::env::var("MOMENTRY_FFMPEG").unwrap_or_else(|_| "ffmpeg".to_string()); let mut cmd = Command::new(&ffmpeg_path); let full_lib = "/opt/homebrew/opt/ffmpeg-full/lib"; if std::path::Path::new(full_lib).exists() { @@ -52,15 +51,24 @@ pub async fn generate_proxy(file_path: &str, file_uuid: &str) -> Result Result {} (ratio: {:.2}, segments: {})", @@ -180,8 +185,7 @@ pub async fn extract_cut_key_frames( video_path: &str, output_dir: &str, ) -> Result> { - let cut_json = PathBuf::from(output_dir) - .join(format!("{}.cut.json", file_uuid)); + let cut_json = PathBuf::from(output_dir).join(format!("{}.cut.json", file_uuid)); if !cut_json.exists() { tracing::warn!("[CUT_KEY_FRAME] cut.json not found: {}", cut_json.display()); @@ -244,7 +248,8 @@ pub async fn extract_cut_key_frames( arr.iter() .filter_map(|s| { if s.get("success").and_then(|b| b.as_bool()) == Some(true) { - s.get("output_path").and_then(|p| p.as_str().map(|p| p.to_string())) + s.get("output_path") + .and_then(|p| p.as_str().map(|p| p.to_string())) } else { None } @@ -260,4 +265,4 @@ pub async fn extract_cut_key_frames( ); Ok(scenes) -} \ No newline at end of file +} diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index f898af8e..e91527b1 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -1316,9 +1316,9 @@ impl JobWorker { } } - // Check dependencies: all dependent processors must be completed - // Special check for FaceCluster: face_traced.json must exist (produced by P2 - // store_traced_faces.py which runs AFTER process_job completes). + // Special guard for FaceCluster: requires face_traced.json to exist. + // Without it, clustering produces no_faces even when faces were detected + // (the trace file is produced later by store_traced_faces.py in P2 trigger). if *processor_type == crate::core::db::ProcessorType::FaceCluster { let traced_path = format!( "{}/{}.face_traced.json", @@ -1327,14 +1327,15 @@ impl JobWorker { ); if !std::path::Path::new(&traced_path).exists() { info!( - "Processor {} deferred: face_traced.json not yet ready for {}", - processor_type.as_str(), + "FaceCluster deferred: face_traced.json not yet ready for {}", job.uuid ); + started_count += 1; continue; } } + // Check dependencies: all dependent processors must be completed let deps = processor_type.dependencies(); if !deps.is_empty() { let mut any_dep_failed = false; diff --git a/src/worker/processor.rs b/src/worker/processor.rs index dc1dcb25..62b7e4b1 100644 --- a/src/worker/processor.rs +++ b/src/worker/processor.rs @@ -886,6 +886,7 @@ impl ProcessorPool { output_path.to_str().unwrap(), uuid, Some(&sample_frames), + None, ) .await?; tracing::info!(