#!/usr/bin/env python3 """ Backfill trace profiles from Qdrant _faces collection (V2 - handles trace_id = 0). For each (file_uuid, trace_id) group in Qdrant: 1. Compute frame_count, start_frame, end_frame, avg_confidence 2. Pick representative frame (highest confidence) 3. Extract key_frame.jpg from video via ffmpeg 4. Crop key_face.jpg from key_frame using representative bbox 5. Write output/{file_uuid}/trace_{N}/trace_profile.json Changes from V1: - Handles trace_id = 0 (not just trace_id > 0) - Fixed trace_id filtering logic - Better error handling Usage: python3 backfill_trace_profiles_v2.py [--file-uuid UUID] [--dry-run] """ import argparse import json import os import subprocess import sys import urllib.request import urllib.error from collections import defaultdict from pathlib import Path 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") FACES_COLLECTION = "_faces" BATCH_SIZE = 1000 def scroll_all(filter_body, with_payload=None): """Scroll all points from Qdrant.""" all_points = [] offset = None while True: body = { "limit": BATCH_SIZE, "with_vector": False } if with_payload: body["with_payload"] = with_payload else: body["with_payload"] = True if offset: body["offset"] = offset if filter_body: body["filter"] = filter_body req = urllib.request.Request( f"{QDRANT_URL}/collections/{FACES_COLLECTION}/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=30) as resp: result = json.loads(resp.read()) points = result.get("result", {}).get("points", []) if not points: break all_points.extend(points) offset = result.get("result", {}).get("next_page_offset") if not offset: break except Exception as e: print(f"Error scrolling Qdrant: {e}", file=sys.stderr) break return all_points def get_video_path(file_uuid): """Get video file path from PostgreSQL.""" import psycopg2 try: conn = psycopg2.connect( host="localhost", database="momentry", user="accusys" ) cur = conn.cursor() cur.execute(""" SELECT file_path FROM videos WHERE file_uuid = %s """, (file_uuid,)) row = cur.fetchone() conn.close() return row[0] if row else None except Exception as e: print(f"Error getting video path: {e}", file=sys.stderr) return None def extract_key_frame(video_path, frame_num, output_path): """Extract a specific frame from video.""" if not os.path.exists(video_path): print(f" ⚠️ Video file not found: {video_path}") return False try: result = subprocess.run( ["ffmpeg", "-y", "-i", video_path, "-vf", f"select=eq(n\\,{frame_num})", "-vframes", "1", "-q:v", "5", output_path], capture_output=True, timeout=30 ) return result.returncode == 0 and os.path.exists(output_path) except Exception as e: print(f" ❌ Error extracting frame: {e}", file=sys.stderr) return False def crop_key_face(key_frame_path, bbox, output_path): """Crop key_face from key_frame using bbox.""" x, y, w, h = bbox["x"], bbox["y"], bbox["width"], bbox["height"] if w <= 0 or h <= 0: return False try: result = subprocess.run( ["ffmpeg", "-y", "-i", key_frame_path, "-vf", f"crop={w}:{h}:{x}:{y},scale=256:256", "-q:v", "2", output_path], capture_output=True, timeout=10 ) return result.returncode == 0 except Exception as e: print(f" ❌ Error cropping face: {e}", file=sys.stderr) return False def build_trace_profiles(file_uuid=None, dry_run=False): """Build trace profiles from Qdrant _faces data.""" # Get all unique file_uuids with trace_id >= 0 if file_uuid: file_uuids = [file_uuid] else: print("Scanning Qdrant for all file_uuids with trace_id >= 0...") points = scroll_all( {"must": [{"key": "trace_id", "range": {"gte": 0}}]}, with_payload={"include": ["file_uuid"]} ) file_uuids = sorted(set(p["payload"]["file_uuid"] for p in points)) print(f"Found {len(file_uuids)} files with trace data") total_profiles = 0 for fid in file_uuids: print(f"\n--- {fid} ---") # Scroll all points for this file with trace_id >= 0 points = scroll_all( { "must": [ {"key": "file_uuid", "match": {"value": fid}}, {"key": "trace_id", "range": {"gte": 0}}, # ✅ Changed from > to >= ] }, with_payload={"include": ["frame", "trace_id", "x", "y", "width", "height", "confidence", "capture_quality"]} ) if not points: print(" No points with trace_id >= 0") continue # Group by trace_id traces = defaultdict(list) for p in points: pl = p["payload"] tid = pl.get("trace_id", -1) # ✅ Include trace_id = 0 if tid >= 0: traces[tid].append(pl) print(f" Found {len(traces)} traces") if dry_run: print(f" (dry-run) Would process {len(traces)} traces") total_profiles += len(traces) continue # Get video path video_path = get_video_path(fid) if not video_path: print(f" ⚠️ Video path not found, skipping") continue # Process each trace for trace_id, faces in traces.items(): if not faces: continue # Compute statistics frames = [f["frame"] for f in faces] confidences = [f.get("confidence", 0) for f in faces] frame_count = len(faces) start_frame = min(frames) end_frame = max(frames) avg_confidence = sum(confidences) / len(confidences) # Find best face (highest confidence) best_face = max(faces, key=lambda f: f.get("confidence", 0)) best_frame = best_face["frame"] best_bbox = { "x": best_face.get("x", 0), "y": best_face.get("y", 0), "width": best_face.get("width", 0), "height": best_face.get("height", 0) } # Create trace directory trace_dir = Path(f"{OUTPUT_DIR}/{fid}/trace_{trace_id}") trace_dir.mkdir(parents=True, exist_ok=True) # Extract key_frame key_frame_path = trace_dir / "key_frame.jpg" if extract_key_frame(video_path, best_frame, str(key_frame_path)): # Crop key_face key_face_path = trace_dir / "key_face.jpg" crop_key_face(str(key_frame_path), best_bbox, str(key_face_path)) # Write trace_profile.json profile = { "trace_id": trace_id, "frame_count": frame_count, "start_frame": start_frame, "end_frame": end_frame, "avg_confidence": avg_confidence, "best_frame": best_frame, "key_face_bbox": best_bbox, "key_frame": "key_frame.jpg" } profile_path = trace_dir / "trace_profile.json" with open(profile_path, "w") as f: json.dump(profile, f, indent=2) total_profiles += 1 print(f" ✅ Created {len(traces)} trace profiles") print(f"\n=== Done ===") print(f"Total trace profiles: {total_profiles}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Backfill trace profiles from Qdrant (V2)") parser.add_argument("--file-uuid", help="Process specific file") parser.add_argument("--dry-run", action="store_true", help="Show what would be done") args = parser.parse_args() build_trace_profiles(args.file_uuid, args.dry_run)