#!/opt/homebrew/bin/python3.11 """ Repair missing tkg_nodes face_track entries by reconciling Qdrant _faces with PostgreSQL tkg_nodes. For each file_uuid: 1. Scroll all face points from Qdrant _faces 2. Aggregate by trace_id (frame_count, start/end_frame, avg_bbox, best_frame, etc.) 3. Compare with existing tkg_nodes face_track rows 4. INSERT missing face_track nodes + UPSERT trace_profiles Usage: python3 scripts/repair_tkg_face_tracks.py --uuid python3 scripts/repair_tkg_face_tracks.py --all """ import argparse import json import os import sys import requests from collections import defaultdict QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333") QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") DATABASE_URL = os.environ.get("DATABASE_URL", "postgres://accusys@localhost:5432/momentry") DATABASE_SCHEMA = os.environ.get("DATABASE_SCHEMA", "public") PSQL = os.environ.get("PSQL_PATH", "/opt/homebrew/Cellar/libpq/18.4/bin/psql") def scroll_qdrant_faces(file_uuid: str) -> list: """Scroll all face points from Qdrant _faces collection.""" 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": False, "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, ) resp.raise_for_status() data = resp.json() batch = data.get("result", {}).get("points", []) all_points.extend(batch) offset = data.get("result", {}).get("next_page_offset") if not offset: break return all_points def aggregate_traces(points: list) -> dict: """Aggregate face points by trace_id, computing stats per trace.""" traces = defaultdict(lambda: { "frames": [], "best_confidence": 0.0, "best_frame": 0, "best_point_id": None, "sum_x": 0.0, "sum_y": 0.0, "sum_w": 0.0, "sum_h": 0.0, }) for p in points: payload = p.get("payload", {}) trace_id = payload.get("trace_id") if trace_id is None or trace_id < 0: continue frame = payload.get("frame") if frame is None: continue conf = payload.get("confidence", 0.5) bbox = payload.get("bbox", {}) x, y = bbox.get("x", 0), bbox.get("y", 0) w, h = bbox.get("width", 0), bbox.get("height", 0) t = traces[trace_id] t["frames"].append(frame) t["sum_x"] += x t["sum_y"] += y t["sum_w"] += w t["sum_h"] += h if conf > t["best_confidence"]: t["best_confidence"] = conf t["best_frame"] = frame t["best_point_id"] = p.get("id") result = {} for tid, t in traces.items(): n = len(t["frames"]) result[tid] = { "frame_count": n, "start_frame": min(t["frames"]), "end_frame": max(t["frames"]), "avg_x": round(t["sum_x"] / n) if n else 0, "avg_y": round(t["sum_y"] / n) if n else 0, "avg_w": round(t["sum_w"] / n) if n else 0, "avg_h": round(t["sum_h"] / n) if n else 0, "best_frame": t["best_frame"], "best_point_id": t["best_point_id"], "avg_confidence": round(t["best_confidence"], 3), } return result def get_existing_tkg_traces(file_uuid: str) -> set: """Get existing trace_ids from tkg_nodes face_track rows.""" import subprocess schema = DATABASE_SCHEMA table = f"{schema}.tkg_nodes" if schema != "public" else "tkg_nodes" query = ( f"SELECT (properties->>'trace_id')::int FROM {table} " f"WHERE file_uuid = '{file_uuid}' AND node_type = 'face_track' " f"AND properties->>'trace_id' IS NOT NULL;" ) result = subprocess.run( [PSQL, "-d", DATABASE_URL, "-t", "-A", "-c", query], capture_output=True, text=True, timeout=30, ) existing = set() for line in result.stdout.strip().split("\n"): line = line.strip() if line: try: existing.add(int(line)) except ValueError: pass return existing def insert_tkg_node(file_uuid: str, trace_id: int, stats: dict): """INSERT a missing face_track node into tkg_nodes.""" import subprocess schema = DATABASE_SCHEMA table = f"{schema}.tkg_nodes" if schema != "public" else "tkg_nodes" external_id = f"trace_{trace_id}" label = f"Face Trace {trace_id}" props = json.dumps({ "trace_id": trace_id, "frame_count": stats["frame_count"], "start_frame": stats["start_frame"], "end_frame": stats["end_frame"], "key_frame": stats["best_frame"], "key_face": stats["best_point_id"] or "", "avg_bbox": { "x": stats["avg_x"], "y": stats["avg_y"], "width": stats["avg_w"], "height": stats["avg_h"], }, "avg_yaw": 0.0, "avg_pitch": 0.0, "avg_roll": 0.0, "pose_count": 0, "avg_confidence": stats["avg_confidence"], "status": "pending", }) query = ( f"INSERT INTO {table} (node_type, external_id, file_uuid, label, properties) " f"VALUES ('face_track', '{external_id}', '{file_uuid}', '{label}', '{props}'::jsonb) " f"ON CONFLICT (file_uuid, node_type, external_id) DO UPDATE SET " f" properties = EXCLUDED.properties;" ) result = subprocess.run( [PSQL, "-d", DATABASE_URL, "-t", "-A", "-c", query], capture_output=True, text=True, timeout=30, ) if result.returncode != 0: print(f" ❌ INSERT failed for trace {trace_id}: {result.stderr.strip()}") return False return True def upsert_trace_profile(file_uuid: str, trace_id: int, stats: dict): """UPSERT trace_profiles row for the missing trace.""" import subprocess schema = DATABASE_SCHEMA table = f"{schema}.trace_profiles" if schema != "public" else "trace_profiles" name = f"Face Trace {trace_id}" query = ( f"INSERT INTO {table} (file_uuid, trace_id, name, start_frame, end_frame, " f"frame_count, key_frame, key_face, status, avg_confidence, properties) " f"VALUES ('{file_uuid}', {trace_id}, '{name}', {stats['start_frame']}, " f"{stats['end_frame']}, {stats['frame_count']}, 'key_frame.jpg', 'key_face.jpg', " f"'pending', {stats['avg_confidence']}, '{{\"trace_id\":{trace_id}}}'::jsonb) " f"ON CONFLICT (file_uuid, trace_id) DO UPDATE SET " f" start_frame = COALESCE(EXCLUDED.start_frame, {table}.start_frame), " f" end_frame = COALESCE(EXCLUDED.end_frame, {table}.end_frame), " f" frame_count = COALESCE(EXCLUDED.frame_count, {table}.frame_count), " f" key_frame = COALESCE(EXCLUDED.key_frame, {table}.key_frame), " f" key_face = COALESCE(EXCLUDED.key_face, {table}.key_face), " f" avg_confidence = COALESCE(EXCLUDED.avg_confidence, {table}.avg_confidence), " f" updated_at = NOW();" ) subprocess.run( [PSQL, "-d", DATABASE_URL, "-t", "-A", "-c", query], capture_output=True, text=True, timeout=30, ) def get_all_file_uuids_with_faces() -> list: """Get all file_uuids that have face points in Qdrant.""" headers = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {} # Scroll a few points to extract unique file_uuids # This is a heuristic - we just need some points to discover uuids resp = requests.post( f"{QDRANT_URL}/collections/_faces/points/scroll", json={"limit": 50000, "with_payload": True, "with_vector": False}, headers=headers, timeout=60, ) resp.raise_for_status() points = resp.json().get("result", {}).get("points", []) uuids = set() for p in points: fid = p.get("payload", {}).get("file_uuid") if fid: uuids.add(fid) return sorted(uuids) def repair_file(file_uuid: str, dry_run: bool = False) -> dict: """Repair missing face_track nodes for a single file_uuid.""" print(f"\n{'='*60}") print(f"Repairing: {file_uuid}") print(f"{'='*60}") # Step 1: Scroll Qdrant print(" Scrolling Qdrant _faces...") points = scroll_qdrant_faces(file_uuid) if not points: print(" No face points found. Skipping.") return {"file_uuid": file_uuid, "qdrant_points": 0, "missing": 0, "repaired": 0} # Step 2: Aggregate traces traces = aggregate_traces(points) qdrant_traces = set(traces.keys()) print(f" Qdrant: {len(points)} points, {len(qdrant_traces)} unique traces") # Step 3: Get existing tkg_nodes existing = get_existing_tkg_traces(file_uuid) print(f" tkg_nodes: {len(existing)} existing face_track rows") # Step 4: Find missing missing = qdrant_traces - existing print(f" Missing: {len(missing)} traces") if not missing: print(" ✅ No missing traces.") return { "file_uuid": file_uuid, "qdrant_points": len(points), "qdrant_traces": len(qdrant_traces), "existing": len(existing), "missing": 0, "repaired": 0, } # Step 5: Insert missing repaired = 0 if not dry_run: for tid in sorted(missing): stats = traces[tid] print(f" INSERT trace {tid} (frames={stats['frame_count']})...") if insert_tkg_node(file_uuid, tid, stats): upsert_trace_profile(file_uuid, tid, stats) repaired += 1 print(f" ✅ Repaired {repaired}/{len(missing)} missing traces") else: print(f" [DRY RUN] Would repair {len(missing)} traces:") for tid in sorted(missing): stats = traces[tid] print(f" trace {tid}: frames={stats['frame_count']}, " f"range=[{stats['start_frame']}-{stats['end_frame']}]") return { "file_uuid": file_uuid, "qdrant_points": len(points), "qdrant_traces": len(qdrant_traces), "existing": len(existing), "missing": len(missing), "repaired": repaired if not dry_run else 0, } def main(): parser = argparse.ArgumentParser(description="Repair missing tkg_nodes face_track entries") parser.add_argument("--uuid", help="Repair a single file_uuid") parser.add_argument("--all", action="store_true", help="Scan all files with face points") parser.add_argument("--dry-run", action="store_true", help="Show what would be repaired without inserting") args = parser.parse_args() if args.uuid: results = [repair_file(args.uuid, args.dry_run)] elif args.all: print("Discovering file_uuids with face points in Qdrant...") uuids = get_all_file_uuids_with_faces() print(f"Found {len(uuids)} file_uuids") results = [] for uuid in uuids: results.append(repair_file(uuid, args.dry_run)) else: parser.print_help() sys.exit(1) # Summary print(f"\n{'='*60}") print("SUMMARY") print(f"{'='*60}") total_missing = sum(r["missing"] for r in results) total_repaired = sum(r["repaired"] for r in results) for r in results: if r["missing"] > 0: print(f" {r['file_uuid'][:16]}... missing={r['missing']}, repaired={r['repaired']}") print(f"\n Total missing: {total_missing}") print(f" Total repaired: {total_repaired}") if __name__ == "__main__": main()