From 696ede86963fec776ce8e1baf709888b695b5fed Mon Sep 17 00:00:00 2001 From: Accusys Date: Sun, 27 Sep 2026 01:14:28 +0800 Subject: [PATCH] fix: face_tracker.py now supports list format for frames --- .../2026-09-27_face_tracker_analysis.md | 390 ++++++++++++++++++ ...6-09-27_ingestion_020mp4_stuck_analysis.md | 189 +++++++++ scripts/utils/face_tracker.py | 19 +- scripts/utils/qdrant_faces.py | 24 +- 4 files changed, 618 insertions(+), 4 deletions(-) create mode 100644 docs_v1.0/M4_workspace/2026-09-27_face_tracker_analysis.md create mode 100644 docs_v1.0/M4_workspace/2026-09-27_ingestion_020mp4_stuck_analysis.md diff --git a/docs_v1.0/M4_workspace/2026-09-27_face_tracker_analysis.md b/docs_v1.0/M4_workspace/2026-09-27_face_tracker_analysis.md new file mode 100644 index 00000000..205eab40 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-09-27_face_tracker_analysis.md @@ -0,0 +1,390 @@ +# face_tracker.py 功能及結構分析 + +**文件路徑**: `/Users/accusys/momentry_core/scripts/utils/face_tracker.py` +**行數**: 573 +**語言**: Python 3.11 +**最後更新**: 2026-09-27 + +--- + +## 概述 + +**用途**: 跨幀追蹤人臉,為每個檢測到的人臉分配唯一的 `trace_id`。 + +**核心功能**: +1. 人臉追蹤(跨幀匹配) +2. trace_id 分配 +3. 軌跡統計生成 +4. 姿態分析 + +--- + +## 輸入/輸出 + +### 輸入 + +| 文件 | 格式 | 用途 | +|------|------|------| +| `face.json` | JSON | 人臉檢測結果(來自 Face 處理器) | +| `cut.json` (可選) | JSON | 場景切割邊界 | + +### 輸出 + +| 文件 | 格式 | 內容 | +|------|------|------| +| `face_traced.json` | JSON | 人臉檢測結果 + trace_id + traces 統計 | + +--- + +## 數據結構 + +### 輸入結構 (face.json) + +```json +{ + "frames": { + "0": { + "faces": [ + { + "x": 1377, + "y": 219, + "width": 62, + "height": 62, + "confidence": 0.68, + "embedding": [0.123, ...], // 512 維向量 + "pose_angle": { + "angle": "frontal", + "pitch": "neutral", + "confidence": 0.85 + } + } + ] + } + }, + "metadata": { + "fps": 30.0 + } +} +``` + +### 輸出結構 (face_traced.json) + +```json +{ + "frames": { + "0": { + "faces": [ + { + "x": 1377, + "y": 219, + "width": 62, + "height": 62, + "confidence": 0.68, + "trace_id": 0 // ✅ 新增:每個 face 都有 trace_id + } + ] + } + }, + "traces": { + "0": { + "trace_id": 0, + "start_frame": 0, + "end_frame": 66, + "duration_frames": 67, + "duration_seconds": 2.23, + "total_appearances": 17, + "avg_confidence": 0.64, + "pose_angles": ["frontal", "frontal", ...], + "pose_trace": [...], + "pose_statistics": { + "distribution": {"frontal": 10, "left": 7}, + "dominant_angle": "frontal", + "pose_count": 2 + }, + "pose_transitions": [...], + "path": [...] + } + }, + "metadata": { + "fps": 30.0, + "trace_stats": { + "total_traces": 9, + "active_traces": 9, + "long_traces": 7 + } + } +} +``` + +--- + +## 核心函數 + +### 1. `track_faces()` (Line 291-458) + +**用途**: 主追蹤函數,處理所有幀並分配 trace_id + +**流程**: +``` +1. 遍歷所有幀(按幀號排序) +2. 對每個幀: + a. 獲取當前幀的所有 faces + b. 調用 match_faces() 匹配前一幀的 faces + c. 根據匹配結果分配 trace_id: + - 匹配成功:使用前一幀的 trace_id + - 匹配失敗:分配新的 trace_id + d. 將 trace_id 寫入 face 字典 +3. 構建 traces 統計 +4. 返回更新後的 face_data +``` + +**關鍵代碼** (Line 365): +```python +faces[curr_idx]["trace_id"] = trace_id +``` + +這行代碼將 trace_id 寫入每個 face 字典中。 + +### 2. `match_faces()` (Line 128-288) + +**用途**: 匹配當前幀的 faces 到前一幀的 faces + +**參數**: +- `current_faces`: 當前幀的 faces +- `previous_faces`: 前一幀的 faces +- `iou_threshold`: IoU 閾值(預設 0.3) +- `similarity_threshold`: 嵌入相似度閾值(預設 0.7) +- `distance_threshold`: 距離閾值(預設 100.0) +- `use_embedding`: 是否使用嵌入相似度 +- `frame_gap`: 幀間距 +- `cut_boundaries`: 場景切割邊界 + +**返回**: `{curr_idx: prev_idx}` 映射字典 + +**匹配邏輯**: +1. **IoU + 嵌入相似度**: + ```python + if iou > 0.3 and similarity > 0.7: + score = iou + similarity + ``` +2. **單條件強匹配**: + ```python + elif iou > 0.5 and similarity > 0.65: + score = iou * 1.5 + similarity * 0.5 + ``` +3. **高相似度**: + ```python + elif similarity > 0.85: + score = similarity * 2 + ``` + +**拒絕條件**: +- 嵌入相似度 < 0.5 且 IoU < 0.3(不同人 + 不同位置) +- bbox 大小變化 > 5x(遠景 → 特寫) +- 前一幀在邊緣退出,當前幀不在邊緣 + +### 3. `calculate_bbox_iou()` (Line 56-88) + +**用途**: 計算兩個 bbox 的 IoU(Intersection over Union) + +**公式**: +``` +IoU = inter_area / (area1 + area2 - inter_area) +``` + +### 4. `calculate_embedding_similarity()` (Line 106-125) + +**用途**: 計算兩個嵌入向量的餘弦相似度 + +**公式**: +``` +similarity = dot(v1, v2) / (norm(v1) * norm(v2)) +``` + +### 5. `strip_embeddings_and_round()` (Line 33-51) + +**用途**: 從 face_traced.json 中移除嵌入向量,減小文件大小 + +**原因**: 嵌入向量存儲在 Qdrant(512 維),JSON 中不需要重複存儲 + +--- + +## 追蹤算法 + +### 第一步:第一幀處理 + +``` +對於第一幀的所有 faces: + 為每個 face 分配新的 trace_id(從 0 開始) +``` + +### 第二步:後續幀處理 + +``` +對於每個後續幀: + 1. 計算當前幀每個 face 與前一幀所有 face 的: + - IoU + - 嵌入相似度 + - bbox 距離 + + 2. 選擇最佳匹配: + - 綜合評分最高的前一幀 face + - 評分 = IoU + 相似度(或其他組合) + + 3. 分配 trace_id: + - 如果匹配成功:使用前一幀的 trace_id + - 如果匹配失敗:分配新的 trace_id +``` + +### 第三步:統計生成 + +``` +對於每個 trace: + 1. 計算持續時間(start_frame → end_frame) + 2. 計算平均置信度 + 3. 分析姿態分佈 + 4. 記錄軌跡路徑 +``` + +--- + +## 場景切割處理 + +**問題**: 場景切割可能導致追蹤錯誤(同一人在不同場景出現) + +**解決方案**: +```python +if prev_frame < cut_frame <= curr_frame: + # 場景切割發生 + # 只匹配高 IoU 的 faces(同一人在同一位置) + if iou > 0.5: + match + else: + new_trace +``` + +--- + +## 關鍵發現:trace_id 寫入 + +**在 line 365**: +```python +faces[curr_idx]["trace_id"] = trace_id +``` + +**這行代碼確保**: +- ✅ 每個 face 字典都有 `trace_id` 字段 +- ✅ trace_id 被寫入 `face_traced.json` 的 `frames` 中 + +**驗證**: +```python +# 在 track_faces() 函數中 +for curr_idx, prev_idx in matches.items(): + if prev_idx >= 0: + trace_id = prev_trace_ids[prev_idx] + else: + trace_id = next_trace_id + next_trace_id += 1 + + faces[curr_idx]["trace_id"] = trace_id # ✅ 寫入 trace_id + trace_ids.append(trace_id) +``` + +--- + +## 問題根源分析 + +### 發現的問題 + +**檢查 020.mp4 的 face_traced.json**: +```json +{ + "frames": { + "0": { + "faces": [ + { + "x": 1377, + "y": 219, + // ❌ 沒有 trace_id 字段! + } + ] + } + } +} +``` + +### 可能的原因 + +1. **face_tracker.py 沒有正確運行**: + - 可能被跳過 + - 可能運行失敗 + +2. **文件被錯誤處理**: + - face_traced.json 被其他腳本覆蓋 + - trace_id 被移除 + +3. **store_traced_faces.py 問題**: + - 調用 face_tracker.py 時參數錯誤 + - 輸出文件路徑錯誤 + +--- + +## 驗證步驟 + +### 1. 檢查 face_tracker.py 是否正確寫入 + +**測試命令**: +```bash +python3 scripts/utils/face_tracker.py \ + --face-json /Users/accusys/momentry/output/b496a68800f90770aa7246c877f38985.face.json \ + --output /tmp/test_face_traced.json +``` + +**預期結果**: +- `frames[0].faces[0]` 應該有 `trace_id` 字段 + +### 2. 檢查 store_traced_faces.py 調用 + +**檢查日誌**: +```bash +grep "face_tracker" logs/worker_3002.log +``` + +### 3. 手動運行完整流程 + +```bash +# 1. 運行 face_tracker.py +python3 scripts/utils/face_tracker.py --face-json .../face.json --output .../face_traced.json + +# 2. 檢查 face_traced.json 中是否有 trace_id +python3 -c "import json; data=json.load(open('.../face_traced.json')); print(data['frames']['0']['faces'][0].get('trace_id'))" +``` + +--- + +## 結論 + +### face_tracker.py 功能完整 ✅ + +1. ✅ **正確的數據結構**: 每個 face 都有 trace_id 字段 +2. ✅ **完整的追蹤算法**: IoU + 嵌入相似度 + 距離 +3. ✅ **豐富的統計**: 持續時間、置信度、姿態分析 + +### 問題不在 face_tracker.py 本身 ❌ + +**問題可能在**: +1. 調用鏈中的其他腳本 +2. 文件路徑錯誤 +3. 輸出被覆蓋 + +--- + +## 下一步 + +1. ✅ 驗證 face_tracker.py 輸出 +2. ✅ 檢查 store_traced_faces.py 的調用 +3. ✅ 確認完整的調用鏈 + +--- + +**分析完成時間**: 2026-09-27 01:00:00 UTC diff --git a/docs_v1.0/M4_workspace/2026-09-27_ingestion_020mp4_stuck_analysis.md b/docs_v1.0/M4_workspace/2026-09-27_ingestion_020mp4_stuck_analysis.md new file mode 100644 index 00000000..3b71e432 --- /dev/null +++ b/docs_v1.0/M4_workspace/2026-09-27_ingestion_020mp4_stuck_analysis.md @@ -0,0 +1,189 @@ +# 020.mp4 Ingestion 卡住問題分析 + +**日期**: 2026-09-27 +**視頻**: 020.mp4 (UUID: b496a68800f90770aa7246c877f38985) +**狀態**: ❌ Ingestion 卡在 40% + +--- + +## 問題現象 + +**Ingestion 狀態**: +``` +asr=true, trace=true, tkg=false, face_cluster=true, rule3=false, +scene_meta=true, qdrant_face=true, vlm=true, moment=true, scene_vlm=false +``` + +**卡在**: `tkg=false`, `rule3=false`, `scene_vlm=false` + +--- + +## 問題鏈分析 + +### 1. TKG 沒有構建 + +**日誌**: +``` +[TKG-Qdrant] parsed 0 FacePoints for b496a68800f90770aa7246c877f38985 +[TKG] No traced faces in Qdrant for b496a68800f90770aa7246c877f38985 +✅ TKG build completed for b496a68800f90770aa7246c877f38985: 0 nodes, 0 edges +``` + +**原因**: Qdrant 中沒有 traced faces (trace_id > 0 的 faces) + +### 2. Qdrant 中 trace_id 都是 -1 + +**檢查**: +```bash +curl -X POST -H "api-key: Test3200Test3200Test3200" \ + "http://127.0.0.1:6333/collections/_faces/points/scroll" \ + -d '{"limit": 1, "filter": {"must": [{"key": "file_uuid", "match": {"value": "b496a68800f90770aa7246c877f38985"}}]}}' +``` + +**結果**: +```json +{ + "payload": { + "file_uuid": "b496a68800f90770aa7246c877f38985", + "frame": 480, + "trace_id": -1, // ❌ 所有 trace_id 都是 -1 + "x": 0, "y": 0, "width": 0, "height": 0 + } +} +``` + +### 3. store_traced_faces.py 沒有更新 trace_id + +**日誌**: +``` +[TRACE] Updated 0 Qdrant points with trace_id, 0 unique traces +``` + +**原因**: `update_trace_ids()` 函數返回 0,沒有更新任何 points + +### 4. trace_mapping 為空 + +**檢查代碼**: +```python +trace_mapping = {} +for frame_num_str, frame_data in sorted(frames.items(), key=lambda x: int(x[0])): + frame_num = int(frame_num_str) + trace_mapping[frame_num] = {} + for face in frame_data.get("faces", []): + trace_id = face.get("trace_id") # ❌ face 中沒有 trace_id 字段 + if trace_id is None: + continue + bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}" + trace_mapping[frame_num][bbox_key] = trace_id +``` + +**問題**: `face.get("trace_id")` 返回 None,因為 face 字典中沒有 `trace_id` 字段 + +### 5. face_traced.json 結構問題 + +**檢查 face_traced.json**: +```json +{ + "frames": { + "0": { + "faces": [ + { + "x": 1377, + "y": 219, + "width": 62, + "height": 62, + // ❌ 沒有 trace_id 字段! + } + ] + } + }, + "traces": { + "0": { + "trace_id": 0, + "start_frame": 0, + "end_frame": 66 + } + } +} +``` + +**問題**: +- `traces` 字典有 trace_id +- 但 `frames` 中的每個 face 沒有 trace_id 字段 +- `trace_mapping` 構建時找不到 trace_id + +--- + +## 根本原因 + +**Face tracking 完成後**: +1. ✅ 生成了 `face_traced.json` +2. ✅ `traces` 字典中有 9 個 traces +3. ❌ 但每個 face 沒有 `trace_id` 字段 +4. ❌ `update_trace_ids()` 無法匹配 faces 和 traces +5. ❌ Qdrant 中的 trace_id 沒有更新 +6. ❌ TKG builder 找不到 traced faces +7. ❌ TKG 構建失敗 + +--- + +## 修復方案 + +### 方案 1: 修改 face_traced.json 結構 + +**在 face_tracker.py 中**: +- 將 trace_id 寫入每個 face 字典中 +- 確保 `frames[frame_num]["faces"][i]["trace_id"]` 存在 + +### 方案 2: 修改 store_traced_faces.py + +**從 traces 字典重建 trace_mapping**: +```python +trace_mapping = {} +for trace_id_str, trace_data in traces.items(): + trace_id = int(trace_id_str) + for frame_num in range(trace_data["start_frame"], trace_data["end_frame"] + 1): + if frame_num not in trace_mapping: + trace_mapping[frame_num] = {} + # 需要找到該 frame 中對應 trace_id 的 face + # 這需要從 face_traced.json 的 frames 中查找 +``` + +### 方案 3: 修改 update_trace_ids() + +**支持從 traces 字典查找 trace_id**: +- 不依賴 face 中的 trace_id 字段 +- 從 traces 字典反向查找每個 frame 的 trace_id + +--- + +## 臨時解決方案 + +**手動更新 Qdrant trace_id**: +1. 從 face_traced.json 讀取 traces +2. 根據 start_frame/end_frame 確定每個 frame 的 trace_id +3. 直接調用 Qdrant API 更新 trace_id + +--- + +## 優先級 + +**緊急**: ✅ 高優先級 + +**影響**: +- 所有使用 FaceNet CoreML 的視頻 +- TKG 無法構建 +- Face clustering 無法完成 +- Ingestion 卡在 40% + +--- + +## 下一步 + +1. ✅ 修改 face_tracker.py,將 trace_id 寫入每個 face +2. ✅ 測試修復 +3. ✅ 部署到生產環境 + +--- + +**分析完成時間**: 2026-09-27 00:35:00 UTC diff --git a/scripts/utils/face_tracker.py b/scripts/utils/face_tracker.py index 52c7c937..182576ca 100755 --- a/scripts/utils/face_tracker.py +++ b/scripts/utils/face_tracker.py @@ -315,6 +315,19 @@ def track_faces( print("No frames found in face.json") return face_data + # Support both list and dict formats + if isinstance(frames, list): + # List format: [{frame: 0, faces: [...]}, ...] + sorted_frames = sorted(frames, key=lambda x: x.get("frame", 0)) + # Convert to dict format for consistency + frames_dict = {} + for frame_data in sorted_frames: + frame_num = frame_data.get("frame") + if frame_num is not None: + frames_dict[str(frame_num)] = {"faces": frame_data.get("faces", [])} + frames = frames_dict + face_data["frames"] = frames + sorted_frames = sorted(frames.items(), key=lambda x: int(x[0])) next_trace_id = 0 @@ -439,7 +452,7 @@ def track_faces( "start_frame": path[0]["frame"], "end_frame": path[-1]["frame"], "duration_frames": duration_frames, - "duration_seconds": duration_frames / face_data["metadata"]["fps"], + "duration_seconds": duration_frames / face_data.get("metadata", {}).get("fps", face_data.get("fps", 30.0)), "total_appearances": len(path), "avg_confidence": avg_confidence, "pose_angles": pose_angles, @@ -449,6 +462,10 @@ def track_faces( "path": path, } + # Ensure metadata exists + if "metadata" not in face_data: + face_data["metadata"] = {} + face_data["metadata"]["trace_stats"] = { "total_traces": next_trace_id, "active_traces": len(traces), diff --git a/scripts/utils/qdrant_faces.py b/scripts/utils/qdrant_faces.py index 25336649..e702957d 100644 --- a/scripts/utils/qdrant_faces.py +++ b/scripts/utils/qdrant_faces.py @@ -210,10 +210,28 @@ def update_trace_ids( payload = point.get("payload", {}) frame = payload.get("frame") + + # Support two bbox formats: + # 1. Nested bbox field + # 2. Direct x, y, width, height fields bbox = payload.get("bbox", {}) - bbox_key = ( - f"{bbox.get('x')}_{bbox.get('y')}_{bbox.get('width')}_{bbox.get('height')}" - ) + if bbox: + # Format 1: has bbox field + x = bbox.get('x') + y = bbox.get('y') + width = bbox.get('width') + height = bbox.get('height') + else: + # Format 2: direct fields + x = payload.get('x') + y = payload.get('y') + width = payload.get('width') + height = payload.get('height') + + if x is None or y is None or width is None or height is None: + continue + + bbox_key = f"{x}_{y}_{width}_{height}" trace_id = trace_mapping.get(frame, {}).get(bbox_key) if trace_id is None: