#!/usr/bin/env python3 """ Batch fix all traces with missing or invalid bbox. Steps: 1. Query all traces with missing/invalid bbox from PostgreSQL 2. Get best_bbox from Qdrant _faces 3. Update PostgreSQL trace_profiles 4. Generate key_face.jpg 5. Draw bbox on key_frame.jpg Usage: python3 batch_fix_traces.py [--file-uuid UUID] [--dry-run] """ import argparse import json import os import subprocess import sys import urllib.request import psycopg2 import cv2 from pathlib import Path from collections import defaultdict OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output") QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333") QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") def get_traces_needing_fix(file_uuid=None): """Get traces with missing or invalid bbox.""" conn = psycopg2.connect( host="localhost", database="momentry", user="accusys" ) cur = conn.cursor() if file_uuid: cur.execute(""" SELECT file_uuid, trace_id FROM trace_profiles WHERE file_uuid = %s AND (best_bbox IS NULL OR best_bbox->>'x' = '0' OR best_bbox->>'x' IS NULL) ORDER BY trace_id """, (file_uuid,)) else: cur.execute(""" SELECT file_uuid, trace_id FROM trace_profiles WHERE best_bbox IS NULL OR best_bbox->>'x' = '0' OR best_bbox->>'x' IS NULL ORDER BY file_uuid, trace_id """) traces = cur.fetchall() conn.close() return traces def get_best_bbox_from_qdrant(file_uuid, trace_id): """Get best bbox for a trace from Qdrant.""" body = { "limit": 100, "with_payload": True, "with_vector": False, "filter": { "must": [ {"key": "file_uuid", "match": {"value": file_uuid}}, {"key": "trace_id", "match": {"value": trace_id}} ] } } req = urllib.request.Request( f"{QDRANT_URL}/collections/_faces/points/scroll", data=json.dumps(body).encode(), method="POST" ) req.add_header("Content-Type", "application/json") req.add_header("Api-Key", QDRANT_API_KEY) try: with urllib.request.urlopen(req, timeout=10) as resp: result = json.loads(resp.read()) points = result.get("result", {}).get("points", []) if not points: return None # Find best bbox best_point = max(points, key=lambda p: p["payload"].get("confidence", 0)) payload = best_point["payload"] x = payload.get("x", 0) y = payload.get("y", 0) w = payload.get("width", 0) h = payload.get("height", 0) if x <= 0 or y <= 0 or w <= 0 or h <= 0: return None return { "x": x, "y": y, "width": w, "height": h, "confidence": payload.get("confidence", 0), "frame": payload.get("frame", 0) } except Exception as e: print(f" ❌ Qdrant query failed: {e}", file=sys.stderr) return None def update_trace_bbox(file_uuid, trace_id, best_bbox): """Update trace_profiles with best_bbox.""" conn = psycopg2.connect( host="localhost", database="momentry", user="accusys" ) cur = conn.cursor() bbox_json = { "x": best_bbox["x"], "y": best_bbox["y"], "width": best_bbox["width"], "height": best_bbox["height"] } cur.execute(""" UPDATE trace_profiles SET best_bbox = %s, best_confidence = %s WHERE file_uuid = %s AND trace_id = %s """, (json.dumps(bbox_json), best_bbox["confidence"], file_uuid, trace_id)) conn.commit() conn.close() def generate_key_face(trace_dir, best_bbox): """Generate key_face.jpg from key_frame.jpg.""" key_frame_path = trace_dir / "key_frame.jpg" key_face_path = trace_dir / "key_face.jpg" if not key_frame_path.exists(): return False x = best_bbox["x"] y = best_bbox["y"] w = best_bbox["width"] h = best_bbox["height"] cmd = [ "ffmpeg", "-y", "-i", str(key_frame_path), "-vf", f"crop={w}:{h}:{x}:{y},scale=256:256", "-q:v", "2", str(key_face_path) ] result = subprocess.run(cmd, capture_output=True, text=True) return result.returncode == 0 def draw_bbox_on_keyframe(trace_dir, best_bbox): """Draw bbox on key_frame.jpg.""" key_frame_path = trace_dir / "key_frame.jpg" if not key_frame_path.exists(): return False img = cv2.imread(str(key_frame_path)) if img is None: return False x = best_bbox["x"] y = best_bbox["y"] w = best_bbox["width"] h = best_bbox["height"] cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4) cv2.imwrite(str(key_frame_path), img) return True def fix_trace(file_uuid, trace_id, dry_run=False): """Fix a single trace.""" trace_dir = Path(f"{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}") print(f" Trace {trace_id}:") # Step 1: Get best_bbox from Qdrant print(f" 1. 查詢 Qdrant...") best_bbox = get_best_bbox_from_qdrant(file_uuid, trace_id) if not best_bbox: print(f" ❌ 沒有找到 bbox") return False print(f" ✅ bbox=[{best_bbox['x']}, {best_bbox['y']}, {best_bbox['width']}, {best_bbox['height']}]") if dry_run: print(f" (dry-run) 跳過更新") return True # Step 2: Update PostgreSQL print(f" 2. 更新 PostgreSQL...") update_trace_bbox(file_uuid, trace_id, best_bbox) # Step 3: Generate key_face.jpg print(f" 3. 生成 key_face.jpg...") if generate_key_face(trace_dir, best_bbox): print(f" ✅ key_face.jpg 已生成") else: print(f" ⚠️ key_face.jpg 生成失敗") # Step 4: Draw bbox print(f" 4. 繪製 bbox...") if draw_bbox_on_keyframe(trace_dir, best_bbox): print(f" ✅ bbox 已繪製") else: print(f" ⚠️ bbox 繪製失敗") return True def main(): parser = argparse.ArgumentParser(description="Batch fix traces with missing bbox") parser.add_argument("--file-uuid", help="Fix specific file") parser.add_argument("--dry-run", action="store_true", help="Show what would be done") args = parser.parse_args() print("=== 批量修復 Traces ===\n") # Get traces needing fix traces = get_traces_needing_fix(args.file_uuid) print(f"找到 {len(traces)} 個需要修復的 traces\n") if not traces: print("✅ 沒有需要修復的 traces") return # Group by file_uuid traces_by_file = defaultdict(list) for file_uuid, trace_id in traces: traces_by_file[file_uuid].append(trace_id) print(f"涉及 {len(traces_by_file)} 個文件\n") # Fix each file total_fixed = 0 total_failed = 0 for i, (file_uuid, trace_ids) in enumerate(traces_by_file.items(), 1): print(f"\n--- 文件 {i}/{len(traces_by_file)}: {file_uuid[:16]}... ---") print(f"需要修復 {len(trace_ids)} 個 traces\n") for trace_id in trace_ids: if fix_trace(file_uuid, trace_id, args.dry_run): total_fixed += 1 else: total_failed += 1 print(f"\n=== 完成 ===") print(f"成功: {total_fixed}/{len(traces)}") print(f"失敗: {total_failed}/{len(traces)}") if __name__ == "__main__": main()