Files
momentry_core/scripts/store_traced_faces.py
T
Accusys 30b9a400ae fix: generate traces field when face.json already has trace_id
問題:
- face.json 已包含 trace_id (來自 Rust face_tracker)
- store_traced_faces.py 直接複製,跳過 traces 字段生成
- Worker 檢查 traces 字段判斷 trace_done
- 因缺少 traces 字段,trace_done=false,阻塞 TKG 構建

修復:
- ✅ 即使 face.json 有 trace_id,仍生成 traces 字段
- ✅ 從 faces 提取 trace_id,構建 traces dict
- ✅ 包含 start_frame, end_frame, duration 等信息
- ✅ Worker 可正確判斷 trace_done

影響:
- 修復 020.mp4 卡在 40% 的問題
- 確保 TKG 和後續流程可以繼續
2026-09-27 21:56:22 +08:00

422 lines
16 KiB
Python

#!/opt/homebrew/bin/python3.11
"""
Store Traced Faces - Pipeline integration for face trace + position data
Flow:
1. Reads face.json output from face_processor.py
2. Runs face_tracker.py to assign trace_id per face (IoU + embedding)
3. Inserts traced faces into face_detections table with trace_id and position (x,y,w,h)
Usage:
python store_traced_faces.py --file-uuid <uuid> [--face-json <path>]
TKG Export:
trace_id + position (x,y,w,h) per frame enables spatial-temporal graph construction.
Each trace is a temporal entity; position tracks movement across frames.
"""
import sys
import os
import json
import argparse
from collections import defaultdict
import numpy as np
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
from qdrant_faces import update_trace_ids
# Config
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev")
SCHEMA = os.environ.get("DATABASE_SCHEMA", "public")
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
def merge_traces_within_cuts(face_data: dict, cut_scenes: list) -> dict:
"""Merge traces within the same cut - DISABLED (no embeddings)."""
# TODO: Reimplement with Qdrant _faces collection
return face_data
def filter_traces(
face_data: dict, min_trace_len: int = 0, min_confidence: float = 0.0
) -> dict:
"""Optionally drop low-quality traces before writing face_traced.json.
A trace is dropped when:
- its path length (total_appearances) < min_trace_len, OR
- its avg_confidence < min_confidence (only when min_confidence > 0).
For every dropped trace, the corresponding faces in `frames` have their
`trace_id` set to None (NOT deleted) so frames/traces stay consistent and
downstream readers (`trace_id is None` → skip) are unaffected. Trace ids of
surviving traces are NOT renumbered.
Both thresholds default to "no filtering" so existing behaviour is unchanged
unless the caller opts in (env vars / CLI flags).
"""
traces = face_data.get("traces", {})
if not traces or (min_trace_len <= 0 and min_confidence <= 0.0):
return face_data
drop_ids = set()
for tid_str, trace in traces.items():
appearances = trace.get("total_appearances", len(trace.get("path", [])))
avg_conf = trace.get("avg_confidence", 1.0)
if appearances < min_trace_len:
drop_ids.add(tid_str)
elif min_confidence > 0.0 and avg_conf < min_confidence:
drop_ids.add(tid_str)
if not drop_ids:
return face_data
# Remove dropped traces from the traces dict
for tid_str in drop_ids:
traces.pop(tid_str, None)
# Clear trace_id on frames for dropped traces (keep the face detection itself)
drop_ints = {int(t) for t in drop_ids}
for frame_data in face_data.get("frames", {}).values():
for face in frame_data.get("faces", []):
if face.get("trace_id") in drop_ints:
face["trace_id"] = None
print(
f"[TRACE] Quality filter: dropped {len(drop_ids)} traces "
f"(min_trace_len={min_trace_len}, min_confidence={min_confidence}), "
f"kept {len(traces)}"
)
return face_data
def run_face_tracker(
face_json_path: str, traced_json_path: str, filter_eyes: bool = False
) -> str:
"""Run face_tracker.py on face.json, returns path to face_traced.json"""
from face_tracker import track_faces
with open(face_json_path) as f:
face_data = json.load(f)
# Check if faces already have trace_id (from Rust face_tracker)
frames_to_check = face_data.get("frames", {})
if isinstance(frames_to_check, list):
# List format (FaceResult)
has_trace = any(
face.get("trace_id") is not None
for frame in frames_to_check
for face in frame.get("faces", [])
)
else:
# Dict format (legacy)
has_trace = any(
face.get("trace_id") is not None
for frame_data in frames_to_check.values()
for face in frame_data.get("faces", [])
)
if has_trace:
print(f"[TRACE] face.json already contains trace_id, skipping tracking")
# Build traces dict from existing trace_ids before copying
traces = defaultdict(list)
if isinstance(frames_to_check, list):
for frame in frames_to_check:
for face in frame.get("faces", []):
trace_id = face.get("trace_id")
if trace_id is not None and trace_id > 0:
traces[trace_id].append(face)
else:
for frame_data in frames_to_check.values():
for face in frame_data.get("faces", []):
trace_id = face.get("trace_id")
if trace_id is not None and trace_id > 0:
traces[trace_id].append(face)
# Add traces field to face_data
face_data["traces"] = {}
fps = face_data.get("fps", 30.0)
for trace_id, trace_faces in traces.items():
if len(trace_faces) == 0:
continue
frames_list = [f.get("frame", f.get("frame_number", 0)) for f in trace_faces]
frame_indices = sorted([f if isinstance(f, int) else int(f) for f in frames_list])
duration_frames = len(frame_indices)
duration_seconds = duration_frames / fps if fps > 0 else 0
face_data["traces"][str(trace_id)] = {
"trace_id": int(trace_id),
"start_frame": frame_indices[0] if frame_indices else 0,
"end_frame": frame_indices[-1] if frame_indices else 0,
"duration_frames": duration_frames,
"duration_seconds": round(duration_seconds, 2),
}
print(f"[TRACE] Built {len(traces)} traces from existing trace_ids")
# Write to traced_json_path
import shutil
with open(traced_json_path, "w") as f:
json.dump(strip_embeddings_and_round(face_data), f, indent=2, ensure_ascii=False)
return traced_json_path
# V2.0 uses list format (FaceResult), convert to dict for face_tracker
if isinstance(face_data.get("frames"), list):
frames_dict = {}
for frame in face_data["frames"]:
fnum = str(frame["frame"])
faces = []
for f in frame.get("faces", []):
bbox = f.get("bbox", f)
face = {
"x": bbox.get("x", f.get("x", 0)),
"y": bbox.get("y", f.get("y", 0)),
"width": bbox.get("width", f.get("width", 0)),
"height": bbox.get("height", f.get("height", 0)),
"confidence": f.get("confidence", 0.0),
"captureQuality": f.get("captureQuality", 0.0),
}
if "landmarks" in f:
face["landmarks"] = f["landmarks"]
if "embedding" in f:
face["embedding"] = f["embedding"]
faces.append(face)
frames_dict[fnum] = {
"frame_number": frame["frame"],
"time_seconds": frame.get("timestamp", 0),
"faces": faces,
}
face_data["frames"] = frames_dict
# Preserve metadata (fps needed by face_tracker)
if "metadata" not in face_data:
face_data["metadata"] = {
"fps": face_data.get("fps", 30.0),
"total_frames": face_data.get("frame_count", 0),
}
# Eye filter: remove faces without at least one eye landmark
if filter_eyes:
removed = 0
for fnum_str, frm_data in face_data.get("frames", {}).items():
faces = frm_data.get("faces", [])
kept = []
for face in faces:
lm = face.get("landmarks", {})
if len(lm.get("left_eye", [])) > 0 or len(lm.get("right_eye", [])) > 0:
kept.append(face)
else:
removed += 1
frm_data["faces"] = kept
print(f"[TRACE] Eye filter: {removed} faces without eyes removed")
print(f"[TRACE] Processing {len(face_data.get('frames', {}))} frames")
# Load embeddings from Qdrant _faces collection
file_uuid = (
face_json_path.split("/")[-1]
.replace(".face.json", "")
.replace("_traced.json", "")
)
print(f"[TRACE] Loading embeddings from Qdrant for {file_uuid}...")
try:
from qdrant_faces import get_file_faces
qdrant_points = get_file_faces(file_uuid, with_vector=True)
# Build lookup: (frame, x, y) -> embedding
emb_lookup = {}
for p in qdrant_points:
pl = p.get("payload", {})
frame = pl.get("frame")
bbox = pl.get("bbox", {})
x, y = bbox.get("x"), bbox.get("y")
vec = p.get("vector")
if frame is not None and vec:
emb_lookup[(frame, x, y)] = vec
print(f"[TRACE] Loaded {len(emb_lookup)} embeddings from Qdrant")
# Attach embeddings to face data
attached = 0
for fnum_str, frm_data in face_data.get("frames", {}).items():
fnum = int(fnum_str)
for face in frm_data.get("faces", []):
key = (fnum, face.get("x"), face.get("y"))
if key in emb_lookup:
face["embedding"] = emb_lookup[key]
attached += 1
print(f"[TRACE] Attached {attached} embeddings to face data")
except Exception as e:
print(f"[TRACE] Warning: Failed to load embeddings from Qdrant: {e}")
# Load cut boundaries from cut.json (same directory as face.json)
cut_boundaries = None
cut_scenes = None
cuts_path = face_json_path.replace("_traced.json", ".cut.json").replace(
".face.json", ".cut.json"
)
if os.path.exists(cuts_path):
with open(cuts_path) as f:
cuts = json.load(f)
cut_scenes = cuts.get("scenes", [])
cut_boundaries = {s["start_frame"] for s in cut_scenes if s["start_frame"] > 0}
print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries")
face_data = track_faces(
face_data, use_embedding=True, cut_boundaries=cut_boundaries
)
# Merge traces within same cut (same person re-appearing after occlusion/pose change)
if cut_scenes and len(cut_scenes) > 0:
face_data = merge_traces_within_cuts(face_data, cut_scenes)
# Optional quality filter (opt-in via env; both default to 0 = disabled).
min_trace_len = int(os.environ.get("MOMENTRY_FACE_MIN_TRACE_LEN", "0"))
min_confidence = float(os.environ.get("MOMENTRY_FACE_MIN_CONFIDENCE", "0.0"))
if min_trace_len > 0 or min_confidence > 0.0:
face_data = filter_traces(face_data, min_trace_len, min_confidence)
metadata = face_data.get("metadata", {})
metadata["tracking_method"] = "iou_only"
metadata["tracked_at"] = datetime.now().isoformat()
face_data["metadata"] = metadata
with open(traced_json_path, "w") as f:
json.dump(
strip_embeddings_and_round(face_data), f, indent=2, ensure_ascii=False
)
trace_count = len(face_data.get("traces", {}))
print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}")
return traced_json_path
def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHEMA):
"""Update Qdrant _faces collection with trace_id after face tracking.
face_detections table is deprecated — trace_id is stored only in Qdrant _faces payload.
"""
with open(traced_json_path) as f:
data = json.load(f)
frames = data.get("frames", {})
# Build trace_mapping for Qdrant update: {frame: {bbox_key: trace_id}}
trace_mapping = {}
# Handle both list and dict formats
if isinstance(frames, list):
# New format: frames is a list of frame objects
for frame_data in frames:
frame_num = frame_data.get("frame")
if frame_num is None:
continue
trace_mapping[frame_num] = {}
for face in frame_data.get("faces", []):
trace_id = face.get("trace_id")
if trace_id is None:
continue
bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}"
trace_mapping[frame_num][bbox_key] = trace_id
else:
# Old format: frames is a dict with frame numbers as keys
for frame_num_str, frame_data in sorted(frames.items(), key=lambda x: int(x[0])):
frame_num = int(frame_num_str)
trace_mapping[frame_num] = {}
for face in frame_data.get("faces", []):
trace_id = face.get("trace_id")
if trace_id is None:
continue
bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}"
trace_mapping[frame_num][bbox_key] = trace_id
# Update Qdrant _faces collection with trace_id.
# return_trace_ids=True makes update_trace_ids also return the trace_id set seen
# during its scroll, so we avoid a redundant third full-collection scan below.
trace_ids = set()
try:
qdrant_updated, trace_ids = update_trace_ids(
file_uuid, trace_mapping, return_trace_ids=True
)
except Exception as e:
print(f"[TRACE] Warning: Qdrant trace_id update failed: {e}")
qdrant_updated = 0
# Unique trace count from the update scroll (no extra full scan needed).
qdrant_trace_count = len(trace_ids)
# Count total faces with trace_id
if isinstance(frames, list):
total_faces = sum(
1
for frame_data in frames
for f in frame_data.get("faces", [])
if f.get("trace_id") is not None
)
else:
total_faces = sum(
1
for fd in frames.values()
for f in fd.get("faces", [])
if f.get("trace_id") is not None
)
print(
f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces"
)
return total_faces, qdrant_trace_count
def main():
parser = argparse.ArgumentParser(description="Store traced faces in DB")
parser.add_argument("--file-uuid", required=True, help="Video file UUID")
parser.add_argument("--face-json", help="Path to face.json (default: auto-detect)")
parser.add_argument("--uuid", help="UUID for Redis tracking (accepted by executor)")
parser.add_argument(
"--filter-eyes",
action="store_true",
help="Remove faces without eye landmarks before tracking",
)
args = parser.parse_args()
face_json = args.face_json or os.path.join(
OUTPUT_DIR, f"{args.file_uuid}.face.json"
)
traced_json = os.path.join(OUTPUT_DIR, f"{args.file_uuid}.face_traced.json")
if not os.path.exists(face_json):
print(f"[TRACE] face.json not found: {face_json}", file=sys.stderr)
sys.exit(1)
# Step 1: Run face tracker
run_face_tracker(face_json, traced_json, filter_eyes=args.filter_eyes)
# Step 2: Store in Qdrant with trace_id
total, traces = store_traced_faces(args.file_uuid, traced_json)
print(f"[TRACE] Done: {total} detections, {traces} traces")
if __name__ == "__main__":
main()