diff --git a/scripts/tkg_builder.py b/scripts/tkg_builder.py index d4785e7f..7bd5d5bd 100644 --- a/scripts/tkg_builder.py +++ b/scripts/tkg_builder.py @@ -1,9 +1,9 @@ #!/opt/homebrew/bin/python3.11 """ -TKG Builder - Unified Temporal Knowledge Graph Builder +TKG Builder - Unified Temporal Knowledge Graph Builder (V4.0 - Qdrant) Builds graph nodes and edges from all pipeline outputs: -- Face tracks (face_detections with trace_id) +- Face tracks (from Qdrant _faces collection with trace_id) - Body tracks (pose.json + Level 1 appearance features) - Detected objects (yolo.json) - Speaker segments (asrx.json) @@ -46,9 +46,15 @@ except ImportError: calculate_proportions = None get_head_region = None +try: + from qdrant_faces import get_file_faces +except ImportError: + print("[TKG] Warning: Qdrant faces module unavailable") + get_file_faces = None + DB_URL = os.environ.get("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry") -SCHEMA = os.environ.get("DATABASE_SCHEMA", "dev") -OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev") +SCHEMA = os.environ.get("DATABASE_SCHEMA", "public") +OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output") def get_conn(): @@ -86,38 +92,78 @@ def ensure_edge(cur, schema, file_uuid, edge_type, source_id, target_id, propert def build_face_track_nodes(cur, schema, file_uuid): - """Create graph nodes for each face track""" + """Create graph nodes for each face track (Qdrant version)""" print("[TKG] Building face_track nodes...") - cur.execute( - f""" - SELECT trace_id, COUNT(*) as frame_count, - MIN(frame_number) as start_f, MAX(frame_number) as end_f, - AVG(x::float) as avg_x, - AVG(y::float) as avg_y, - AVG(width::float) as avg_w, - AVG(height::float) as avg_h - FROM {schema}.face_detections - WHERE file_uuid = %s AND trace_id IS NOT NULL - GROUP BY trace_id - ORDER BY trace_id - """, - (file_uuid,), - ) - count = 0 - for row in cur.fetchall(): - tid, fc, sf, ef, ax, ay, aw, ah = row - label = f"Face Track {tid}" - props = { - "frame_count": fc, - "start_frame": sf, - "end_frame": ef, - "avg_bbox": {"x": round(ax or 0, 1), "y": round(ay or 0, 1), - "width": round(aw or 0, 1), "height": round(ah or 0, 1)}, - } - ensure_node(cur, schema, file_uuid, "face_track", f"face_track_{tid}", label, props) - count += 1 - print(f"[TKG] {count} face_track nodes created") - return count + + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + # Get all faces from Qdrant + faces = get_file_faces(file_uuid, with_vector=False) + + # Filter and group by trace_id + traces = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + if trace_id not in traces: + traces[trace_id] = { + 'frames': [], + 'bboxes': [] + } + + traces[trace_id]['frames'].append(frame) + traces[trace_id]['bboxes'].append(bbox) + + # Create nodes + count = 0 + for trace_id, data in sorted(traces.items()): + frames = data['frames'] + bboxes = data['bboxes'] + + frame_count = len(frames) + start_f = min(frames) + end_f = max(frames) + + # Calculate average bbox + if bboxes: + avg_x = sum(b.get('x', 0) for b in bboxes) / len(bboxes) + avg_y = sum(b.get('y', 0) for b in bboxes) / len(bboxes) + avg_w = sum(b.get('width', 0) for b in bboxes) / len(bboxes) + avg_h = sum(b.get('height', 0) for b in bboxes) / len(bboxes) + else: + avg_x = avg_y = avg_w = avg_h = 0 + + label = f"Face Track {trace_id}" + props = { + "frame_count": frame_count, + "start_frame": start_f, + "end_frame": end_f, + "avg_bbox": { + "x": round(avg_x, 1), + "y": round(avg_y, 1), + "width": round(avg_w, 1), + "height": round(avg_h, 1) + }, + } + ensure_node(cur, schema, file_uuid, "face_track", f"face_track_{trace_id}", label, props) + count += 1 + + print(f"[TKG] {count} face_track nodes created") + return count + except Exception as e: + print(f"[TKG] Error building face_track nodes: {e}") + import traceback + traceback.print_exc() + return 0 def load_json_safe(path): @@ -206,17 +252,37 @@ def build_co_occurrence_edges(cur, schema, file_uuid): yolo_frames = yolo.get("frames", {}) - # Query face detections with trace_id - cur.execute( - f""" - SELECT trace_id, frame_number, x, y, width, height - FROM {schema}.face_detections - WHERE file_uuid = %s AND trace_id IS NOT NULL - ORDER BY frame_number - """, - (file_uuid,), - ) - face_rows = cur.fetchall() + # Get face detections from Qdrant + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Filter faces with trace_id + face_rows = [] + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + face_rows.append(( + trace_id, + frame, + bbox.get('x', 0), + bbox.get('y', 0), + bbox.get('width', 0), + bbox.get('height', 0) + )) + print(f"[TKG] Checking {len(face_rows)} face detections against YOLO frames...") # Get or create frame nodes cache @@ -309,17 +375,35 @@ def build_speaker_face_edges(cur, schema, file_uuid): print("[TKG] No speaker segments found") return 0 - # Get face trace nodes with their time spans - cur.execute( - f""" - SELECT trace_id, MIN(frame_number) as start_f, MAX(frame_number) as end_f - FROM {schema}.face_detections - WHERE file_uuid = %s AND trace_id IS NOT NULL - GROUP BY trace_id - """, - (file_uuid,), - ) - traces = cur.fetchall() + # Get face trace nodes with their time spans from Qdrant + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Group by trace_id + trace_frames = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + + if trace_id is None or frame is None: + continue + + if trace_id not in trace_frames: + trace_frames[trace_id] = [] + trace_frames[trace_id].append(frame) + + # Calculate time spans + traces = [] + for trace_id, frames in sorted(trace_frames.items()): + traces.append((trace_id, min(frames), max(frames))) fps = segments[-1]["end_frame"] / segments[-1]["end_time"] if segments else 30.0 @@ -386,26 +470,53 @@ def build_speaker_face_edges(cur, schema, file_uuid): def build_face_face_edges(cur, schema, file_uuid): """Build CO_OCCURS_WITH edges: face_track ↔ face_track in same frame""" print("[TKG] Building face-face co-occurrence edges...") - - cur.execute( - f""" - SELECT a.trace_id AS tid_a, b.trace_id AS tid_b, - a.frame_number, a.timestamp_secs, - a.x AS ax, a.y AS ay, a.width AS aw, a.height AS ah, - b.x AS bx, b.y AS by, b.width AS bw, b.height AS bh - FROM {schema}.face_detections a - JOIN {schema}.face_detections b - ON a.file_uuid = b.file_uuid - AND a.frame_number = b.frame_number - AND a.trace_id < b.trace_id - WHERE a.file_uuid = %s - AND a.trace_id IS NOT NULL - AND b.trace_id IS NOT NULL - ORDER BY a.frame_number - """, - (file_uuid,), - ) - rows = cur.fetchall() + + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Group faces by frame + frame_faces = {} + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + if frame not in frame_faces: + frame_faces[frame] = [] + + frame_faces[frame].append({ + 'trace_id': trace_id, + 'x': bbox.get('x', 0), + 'y': bbox.get('y', 0), + 'width': bbox.get('width', 0), + 'height': bbox.get('height', 0) + }) + + # Find co-occurrences (same frame, different traces) + rows = [] + for frame, face_list in frame_faces.items(): + for i, face_a in enumerate(face_list): + for face_b in face_list[i+1:]: + if face_a['trace_id'] != face_b['trace_id']: + rows.append(( + face_a['trace_id'], + face_b['trace_id'], + frame, + face_a['x'], face_a['y'], face_a['width'], face_a['height'], + face_b['x'], face_b['y'], face_b['width'], face_b['height'] + )) + if not rows: print("[TKG] No face-face co-occurrences found") return 0 @@ -413,7 +524,7 @@ def build_face_face_edges(cur, schema, file_uuid): # Deduplicate by pair (group all frames where same two traces co-occur) pair_first = {} pair_frames = {} - for tid_a, tid_b, frame, ts, ax, ay, aw, ah, bx, by, bw, bh in rows: + for tid_a, tid_b, frame, ax, ay, aw, ah, bx, by, bw, bh in rows: key = (min(tid_a, tid_b), max(tid_a, tid_b)) if key not in pair_first: pair_first[key] = frame @@ -735,16 +846,35 @@ def build_face_body_edges(cur, schema, file_uuid): """Build HAS_BODY edges: face_track ↔ body_track via spatial proximity""" print("[TKG] Building face-body edges...") - cur.execute( - f""" - SELECT ft.trace_id, ft.frame_number, ft.x, ft.y, ft.width, ft.height - FROM {schema}.face_detections ft - WHERE ft.file_uuid = %s AND ft.trace_id IS NOT NULL - ORDER BY ft.frame_number - """, - (file_uuid,), - ) - face_rows = cur.fetchall() + if get_file_faces is None: + print("[TKG] Error: qdrant_faces module not available") + return 0 + + try: + faces = get_file_faces(file_uuid, with_vector=False) + except Exception as e: + print(f"[TKG] Error fetching faces from Qdrant: {e}") + return 0 + + # Extract face data + face_rows = [] + for face in faces: + payload = face.get('payload', {}) + trace_id = payload.get('trace_id') + frame = payload.get('frame') + bbox = payload.get('bbox', {}) + + if trace_id is None or frame is None: + continue + + face_rows.append(( + trace_id, + frame, + bbox.get('x', 0), + bbox.get('y', 0), + bbox.get('width', 0), + bbox.get('height', 0) + )) pose_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json") if not os.path.exists(pose_json_path):