fix: migrate TKG Builder to V4.0 architecture (Qdrant)

Problem: TKG Builder used deprecated face_detections table
Solution: Migrated to Qdrant _faces collection

Changes:
- Added qdrant_faces module import
- Replaced SQL queries with Qdrant API calls
- Updated build_face_track_nodes to use get_file_faces()
- Updated build_co_occurrence_edges to fetch from Qdrant
- Updated build_speaker_face_edges to calculate trace spans from Qdrant
- Updated build_face_face_edges to find co-occurrences in Python
- Updated build_face_body_edges to fetch face data from Qdrant
- Changed default schema from 'dev' to 'public'
- Changed default output_dir to /Users/accusys/momentry/output

Test results:
- ✅ Successfully created 7 face_track nodes
- ✅ Successfully created 6 face-face co-occurrence edges
- TKG Builder now works with V4.0 architecture

Related: #V4.0-migration
This commit is contained in:
Accusys
2026-09-27 10:59:23 +08:00
parent 461bb291a0
commit 82c400ed6c
+217 -87
View File
@@ -1,9 +1,9 @@
#!/opt/homebrew/bin/python3.11 #!/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: 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) - Body tracks (pose.json + Level 1 appearance features)
- Detected objects (yolo.json) - Detected objects (yolo.json)
- Speaker segments (asrx.json) - Speaker segments (asrx.json)
@@ -46,9 +46,15 @@ except ImportError:
calculate_proportions = None calculate_proportions = None
get_head_region = 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") DB_URL = os.environ.get("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry")
SCHEMA = os.environ.get("DATABASE_SCHEMA", "dev") SCHEMA = os.environ.get("DATABASE_SCHEMA", "public")
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev") OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
def get_conn(): 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): 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...") print("[TKG] Building face_track nodes...")
cur.execute(
f""" if get_file_faces is None:
SELECT trace_id, COUNT(*) as frame_count, print("[TKG] Error: qdrant_faces module not available")
MIN(frame_number) as start_f, MAX(frame_number) as end_f, return 0
AVG(x::float) as avg_x,
AVG(y::float) as avg_y, try:
AVG(width::float) as avg_w, # Get all faces from Qdrant
AVG(height::float) as avg_h faces = get_file_faces(file_uuid, with_vector=False)
FROM {schema}.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL # Filter and group by trace_id
GROUP BY trace_id traces = {}
ORDER BY trace_id for face in faces:
""", payload = face.get('payload', {})
(file_uuid,), trace_id = payload.get('trace_id')
) frame = payload.get('frame')
count = 0 bbox = payload.get('bbox', {})
for row in cur.fetchall():
tid, fc, sf, ef, ax, ay, aw, ah = row if trace_id is None or frame is None:
label = f"Face Track {tid}" continue
props = {
"frame_count": fc, if trace_id not in traces:
"start_frame": sf, traces[trace_id] = {
"end_frame": ef, 'frames': [],
"avg_bbox": {"x": round(ax or 0, 1), "y": round(ay or 0, 1), 'bboxes': []
"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) traces[trace_id]['frames'].append(frame)
count += 1 traces[trace_id]['bboxes'].append(bbox)
print(f"[TKG] {count} face_track nodes created")
return count # 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): def load_json_safe(path):
@@ -206,17 +252,37 @@ def build_co_occurrence_edges(cur, schema, file_uuid):
yolo_frames = yolo.get("frames", {}) yolo_frames = yolo.get("frames", {})
# Query face detections with trace_id # Get face detections from Qdrant
cur.execute( if get_file_faces is None:
f""" print("[TKG] Error: qdrant_faces module not available")
SELECT trace_id, frame_number, x, y, width, height return 0
FROM {schema}.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL try:
ORDER BY frame_number faces = get_file_faces(file_uuid, with_vector=False)
""", except Exception as e:
(file_uuid,), print(f"[TKG] Error fetching faces from Qdrant: {e}")
) return 0
face_rows = cur.fetchall()
# 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...") print(f"[TKG] Checking {len(face_rows)} face detections against YOLO frames...")
# Get or create frame nodes cache # 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") print("[TKG] No speaker segments found")
return 0 return 0
# Get face trace nodes with their time spans # Get face trace nodes with their time spans from Qdrant
cur.execute( if get_file_faces is None:
f""" print("[TKG] Error: qdrant_faces module not available")
SELECT trace_id, MIN(frame_number) as start_f, MAX(frame_number) as end_f return 0
FROM {schema}.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL try:
GROUP BY trace_id faces = get_file_faces(file_uuid, with_vector=False)
""", except Exception as e:
(file_uuid,), print(f"[TKG] Error fetching faces from Qdrant: {e}")
) return 0
traces = cur.fetchall()
# 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 fps = segments[-1]["end_frame"] / segments[-1]["end_time"] if segments else 30.0
@@ -387,25 +471,52 @@ def build_face_face_edges(cur, schema, file_uuid):
"""Build CO_OCCURS_WITH edges: face_track ↔ face_track in same frame""" """Build CO_OCCURS_WITH edges: face_track ↔ face_track in same frame"""
print("[TKG] Building face-face co-occurrence edges...") print("[TKG] Building face-face co-occurrence edges...")
cur.execute( if get_file_faces is None:
f""" print("[TKG] Error: qdrant_faces module not available")
SELECT a.trace_id AS tid_a, b.trace_id AS tid_b, return 0
a.frame_number, a.timestamp_secs,
a.x AS ax, a.y AS ay, a.width AS aw, a.height AS ah, try:
b.x AS bx, b.y AS by, b.width AS bw, b.height AS bh faces = get_file_faces(file_uuid, with_vector=False)
FROM {schema}.face_detections a except Exception as e:
JOIN {schema}.face_detections b print(f"[TKG] Error fetching faces from Qdrant: {e}")
ON a.file_uuid = b.file_uuid return 0
AND a.frame_number = b.frame_number
AND a.trace_id < b.trace_id # Group faces by frame
WHERE a.file_uuid = %s frame_faces = {}
AND a.trace_id IS NOT NULL for face in faces:
AND b.trace_id IS NOT NULL payload = face.get('payload', {})
ORDER BY a.frame_number trace_id = payload.get('trace_id')
""", frame = payload.get('frame')
(file_uuid,), bbox = payload.get('bbox', {})
)
rows = cur.fetchall() 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: if not rows:
print("[TKG] No face-face co-occurrences found") print("[TKG] No face-face co-occurrences found")
return 0 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) # Deduplicate by pair (group all frames where same two traces co-occur)
pair_first = {} pair_first = {}
pair_frames = {} 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)) key = (min(tid_a, tid_b), max(tid_a, tid_b))
if key not in pair_first: if key not in pair_first:
pair_first[key] = frame 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""" """Build HAS_BODY edges: face_track ↔ body_track via spatial proximity"""
print("[TKG] Building face-body edges...") print("[TKG] Building face-body edges...")
cur.execute( if get_file_faces is None:
f""" print("[TKG] Error: qdrant_faces module not available")
SELECT ft.trace_id, ft.frame_number, ft.x, ft.y, ft.width, ft.height return 0
FROM {schema}.face_detections ft
WHERE ft.file_uuid = %s AND ft.trace_id IS NOT NULL try:
ORDER BY ft.frame_number faces = get_file_faces(file_uuid, with_vector=False)
""", except Exception as e:
(file_uuid,), print(f"[TKG] Error fetching faces from Qdrant: {e}")
) return 0
face_rows = cur.fetchall()
# 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") pose_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json")
if not os.path.exists(pose_json_path): if not os.path.exists(pose_json_path):