feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx
Consolidated snapshot (previously WIP in working tree). - core/pipeline_config: new module loading config/pipeline_flows.json as the source of truth for stage execution mode (parallel/blocking) and dependencies - worker/job_worker: dispatch Scene VLM to a background task when the stage is declared parallel, unblocking the worker poll loop; resolve processor dependencies from pipeline_flows.json (fallback to built-in) - config/pipeline_flows.json: asrx depends on [cut, asr] - scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold to 6h, skip jobs with recent processor activity - rust_asrx: Rust speaker diarization CLI + processor wiring - processor metadata helper; fast_face_clustering script; file_progress pipeline API; scan API; VAD updates
This commit is contained in:
Executable
+590
@@ -0,0 +1,590 @@
|
||||
#!/opt/homebrew/bin/python3.11
|
||||
"""
|
||||
Face Tracker - Track faces across frames using embedding similarity and bbox proximity
|
||||
|
||||
Purpose:
|
||||
1. Assign unique trace_id to each face across frames
|
||||
2. Track face movement across adjacent frames
|
||||
3. Output trace statistics (duration, path, confidence)
|
||||
|
||||
Algorithm:
|
||||
1. For first frame: assign new trace_id to each face
|
||||
2. For subsequent frames:
|
||||
- Calculate bbox overlap with previous frame faces
|
||||
- Calculate embedding cosine similarity
|
||||
- Match faces if both conditions met
|
||||
- Assign same trace_id if matched, new trace_id if not
|
||||
|
||||
Matching Conditions:
|
||||
- bbox overlap > 0.3 (IoU)
|
||||
- embedding similarity > 0.7
|
||||
- OR single condition > threshold (fallback)
|
||||
|
||||
Output:
|
||||
- face.json with trace_id added to each face
|
||||
- trace statistics report
|
||||
"""
|
||||
|
||||
import json
|
||||
import argparse
|
||||
import numpy as np
|
||||
|
||||
|
||||
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
|
||||
from typing import Dict, List, Set
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def calculate_bbox_iou(bbox1: Dict, bbox2: Dict) -> float:
|
||||
"""
|
||||
Calculate Intersection over Union (IoU) between two bboxes
|
||||
|
||||
Args:
|
||||
bbox1: {"x": int, "y": int, "width": int, "height": int}
|
||||
bbox2: same structure
|
||||
|
||||
Returns:
|
||||
IoU score (0.0 - 1.0)
|
||||
"""
|
||||
x1, y1, w1, h1 = bbox1["x"], bbox1["y"], bbox1["width"], bbox1["height"]
|
||||
x2, y2, w2, h2 = bbox2["x"], bbox2["y"], bbox2["width"], bbox2["height"]
|
||||
|
||||
x1_min, x1_max = x1, x1 + w1
|
||||
y1_min, y1_max = y1, y1 + h1
|
||||
x2_min, x2_max = x2, x2 + w2
|
||||
y2_min, y2_max = y2, y2 + h2
|
||||
|
||||
inter_x_min = max(x1_min, x2_min)
|
||||
inter_x_max = min(x1_max, x2_max)
|
||||
inter_y_min = max(y1_min, y2_min)
|
||||
inter_y_max = min(y1_max, y2_max)
|
||||
|
||||
if inter_x_max <= inter_x_min or inter_y_max <= inter_y_min:
|
||||
return 0.0
|
||||
|
||||
inter_area = (inter_x_max - inter_x_min) * (inter_y_max - inter_y_min)
|
||||
area1 = w1 * h1
|
||||
area2 = w2 * h2
|
||||
union_area = area1 + area2 - inter_area
|
||||
|
||||
return inter_area / union_area if union_area > 0 else 0.0
|
||||
|
||||
|
||||
def calculate_bbox_distance(bbox1: Dict, bbox2: Dict) -> float:
|
||||
"""
|
||||
Calculate center distance between two bboxes
|
||||
|
||||
Returns:
|
||||
Euclidean distance between centers
|
||||
"""
|
||||
cx1 = bbox1["x"] + bbox1["width"] / 2
|
||||
cy1 = bbox1["y"] + bbox1["height"] / 2
|
||||
cx2 = bbox2["x"] + bbox2["width"] / 2
|
||||
cy2 = bbox2["y"] + bbox2["height"] / 2
|
||||
|
||||
return np.sqrt((cx1 - cx2) ** 2 + (cy1 - cy2) ** 2)
|
||||
|
||||
|
||||
def calculate_embedding_similarity(emb1: List[float], emb2: List[float]) -> float:
|
||||
"""
|
||||
Calculate cosine similarity between two embeddings
|
||||
|
||||
Returns:
|
||||
Cosine similarity (-1.0 - 1.0)
|
||||
"""
|
||||
if emb1 is None or emb2 is None:
|
||||
return 0.0
|
||||
|
||||
v1 = np.array(emb1)
|
||||
v2 = np.array(emb2)
|
||||
|
||||
norm1 = np.linalg.norm(v1)
|
||||
norm2 = np.linalg.norm(v2)
|
||||
|
||||
if norm1 == 0 or norm2 == 0:
|
||||
return 0.0
|
||||
|
||||
return np.dot(v1, v2) / (norm1 * norm2)
|
||||
|
||||
|
||||
def match_faces(
|
||||
current_faces: List[Dict],
|
||||
previous_faces: List[Dict],
|
||||
iou_threshold: float = 0.3,
|
||||
similarity_threshold: float = 0.7,
|
||||
distance_threshold: float = 100.0,
|
||||
use_embedding: bool = True,
|
||||
frame_gap: int = 1,
|
||||
cut_boundaries: Set[int] = None,
|
||||
prev_frame: int = None,
|
||||
curr_frame: int = None,
|
||||
) -> Dict[int, int]:
|
||||
"""
|
||||
Match current frame faces to previous frame faces
|
||||
|
||||
Args:
|
||||
current_faces: Faces in current frame
|
||||
previous_faces: Faces in previous frame
|
||||
iou_threshold: Minimum IoU for matching
|
||||
similarity_threshold: Minimum embedding similarity for matching
|
||||
distance_threshold: Maximum bbox center distance for matching
|
||||
use_embedding: Whether to use embedding similarity
|
||||
frame_gap: Number of frames between current and previous (1=adjacent)
|
||||
cut_boundaries: Set of frame numbers where scene cuts occur
|
||||
prev_frame: Previous frame number (for cut detection)
|
||||
curr_frame: Current frame number (for cut detection)
|
||||
|
||||
Returns:
|
||||
Dict mapping current_face_index -> previous_face_index (or -1 if new)
|
||||
"""
|
||||
if not previous_faces:
|
||||
return {i: -1 for i in range(len(current_faces))}
|
||||
|
||||
# If frame gap is too large, force new traces (likely crossed multiple scenes)
|
||||
if frame_gap is not None and frame_gap > 30:
|
||||
return {i: -1 for i in range(len(current_faces))}
|
||||
|
||||
# If a scene cut exists between prev and current frame, only continue
|
||||
# traces for faces matching the previous frame with high IoU (same person
|
||||
# in the same position across the cut); unmatched faces get new traces.
|
||||
if cut_boundaries and prev_frame is not None and curr_frame is not None:
|
||||
for cf in cut_boundaries:
|
||||
if prev_frame < cf <= curr_frame:
|
||||
matches = {}
|
||||
used_prev = set()
|
||||
for curr_idx, curr_face in enumerate(current_faces):
|
||||
best_prev_idx = -1
|
||||
best_iou = 0.0
|
||||
curr_bbox = {
|
||||
"x": curr_face["x"],
|
||||
"y": curr_face["y"],
|
||||
"width": curr_face["width"],
|
||||
"height": curr_face["height"],
|
||||
}
|
||||
for prev_idx, prev_face in enumerate(previous_faces):
|
||||
if prev_idx in used_prev:
|
||||
continue
|
||||
prev_bbox = {
|
||||
"x": prev_face["x"],
|
||||
"y": prev_face["y"],
|
||||
"width": prev_face["width"],
|
||||
"height": prev_face["height"],
|
||||
}
|
||||
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
|
||||
if iou > best_iou:
|
||||
best_iou = iou
|
||||
best_prev_idx = prev_idx
|
||||
if best_prev_idx >= 0 and best_iou > 0.5:
|
||||
matches[curr_idx] = best_prev_idx
|
||||
used_prev.add(best_prev_idx)
|
||||
else:
|
||||
matches[curr_idx] = -1
|
||||
return matches
|
||||
|
||||
matches = {}
|
||||
used_prev = set()
|
||||
|
||||
for curr_idx, curr_face in enumerate(current_faces):
|
||||
best_prev_idx = -1
|
||||
best_score = 0.0
|
||||
|
||||
curr_bbox = {
|
||||
"x": curr_face["x"],
|
||||
"y": curr_face["y"],
|
||||
"width": curr_face["width"],
|
||||
"height": curr_face["height"],
|
||||
}
|
||||
curr_emb = curr_face.get("embedding")
|
||||
|
||||
for prev_idx, prev_face in enumerate(previous_faces):
|
||||
if prev_idx in used_prev:
|
||||
continue
|
||||
|
||||
prev_bbox = {
|
||||
"x": prev_face["x"],
|
||||
"y": prev_face["y"],
|
||||
"width": prev_face["width"],
|
||||
"height": prev_face["height"],
|
||||
}
|
||||
prev_emb = prev_face.get("embedding")
|
||||
|
||||
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
|
||||
distance = calculate_bbox_distance(curr_bbox, prev_bbox)
|
||||
|
||||
similarity = 0.0
|
||||
if use_embedding and curr_emb and prev_emb:
|
||||
similarity = calculate_embedding_similarity(curr_emb, prev_emb)
|
||||
|
||||
# Bbox size consistency check: sudden size change = different person
|
||||
prev_area = prev_bbox["width"] * prev_bbox["height"]
|
||||
curr_area = curr_bbox["width"] * curr_bbox["height"]
|
||||
area_ratio = max(curr_area, prev_area) / max(1, min(curr_area, prev_area))
|
||||
|
||||
score = 0.0
|
||||
|
||||
# Reject only if BOTH embedding AND IoU disagree (different person + different position)
|
||||
if use_embedding and curr_emb and prev_emb and similarity < 0.5 and iou < 0.3:
|
||||
continue
|
||||
|
||||
# Reject if bbox size changes by more than 5x (e.g., far shot → close-up)
|
||||
if area_ratio > 5.0 and similarity < 0.8:
|
||||
continue
|
||||
|
||||
# Edge exit: if previous face was near frame edge and current face is not,
|
||||
# the old face likely exited and a new face appeared
|
||||
prev_at_edge = (prev_bbox["x"] < 50 or
|
||||
prev_bbox["x"] + prev_bbox["width"] > 1870 or
|
||||
prev_bbox["y"] < 50 or
|
||||
prev_bbox["y"] + prev_bbox["height"] > 1030)
|
||||
curr_at_edge = (curr_bbox["x"] < 50 or
|
||||
curr_bbox["x"] + curr_bbox["width"] > 1870 or
|
||||
curr_bbox["y"] < 50 or
|
||||
curr_bbox["y"] + curr_bbox["height"] > 1030)
|
||||
if prev_at_edge and not curr_at_edge and similarity < 0.8:
|
||||
continue
|
||||
|
||||
if iou > iou_threshold and similarity > similarity_threshold:
|
||||
score = iou + similarity
|
||||
elif iou > 0.5 and similarity > 0.65:
|
||||
score = iou * 1.5 + similarity * 0.5
|
||||
elif iou > 0.35 and distance < distance_threshold:
|
||||
score = iou * 2 - distance / 500
|
||||
elif similarity > 0.85:
|
||||
score = similarity * 2
|
||||
elif similarity > 0.75 and distance < distance_threshold:
|
||||
score = similarity - distance / 1000
|
||||
# For frame gaps (tracking lost and recovered), require higher confidence
|
||||
elif frame_gap > 1 and similarity > 0.8 and iou > 0.2:
|
||||
score = similarity + iou
|
||||
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_prev_idx = prev_idx
|
||||
|
||||
if best_prev_idx >= 0 and best_score > 0:
|
||||
matches[curr_idx] = best_prev_idx
|
||||
used_prev.add(best_prev_idx)
|
||||
else:
|
||||
matches[curr_idx] = -1
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
def track_faces(
|
||||
face_data: Dict,
|
||||
iou_threshold: float = 0.3,
|
||||
similarity_threshold: float = 0.7,
|
||||
distance_threshold: float = 100.0,
|
||||
use_embedding: bool = True,
|
||||
cut_boundaries: Set[int] = None,
|
||||
) -> Dict:
|
||||
"""
|
||||
Track faces across all frames
|
||||
|
||||
Args:
|
||||
face_data: face.json data
|
||||
iou_threshold: IoU threshold for matching
|
||||
similarity_threshold: Embedding similarity threshold
|
||||
distance_threshold: Distance threshold for matching
|
||||
use_embedding: Whether to use embedding
|
||||
|
||||
Returns:
|
||||
Updated face_data with trace_id added to each face
|
||||
"""
|
||||
frames = face_data.get("frames", {})
|
||||
|
||||
if not frames:
|
||||
print("No frames found in face.json")
|
||||
return face_data
|
||||
|
||||
# Support both list and dict formats
|
||||
if isinstance(frames, list):
|
||||
# List format: [{frame: 0, faces: [...]}, ...]
|
||||
sorted_frames = sorted(frames, key=lambda x: x.get("frame", 0))
|
||||
# Convert to dict format for consistency
|
||||
frames_dict = {}
|
||||
for frame_data in sorted_frames:
|
||||
frame_num = frame_data.get("frame")
|
||||
if frame_num is not None:
|
||||
frames_dict[str(frame_num)] = {"faces": frame_data.get("faces", [])}
|
||||
frames = frames_dict
|
||||
face_data["frames"] = frames
|
||||
|
||||
sorted_frames = sorted(frames.items(), key=lambda x: int(x[0]))
|
||||
|
||||
next_trace_id = 0
|
||||
traces = defaultdict(list)
|
||||
|
||||
prev_faces = []
|
||||
prev_trace_ids = []
|
||||
prev_frame_num = None
|
||||
prev_face_frame = None # last frame number that had actual faces
|
||||
|
||||
print(f"\nTracking faces across {len(sorted_frames)} frames...")
|
||||
print(f"Parameters: iou={iou_threshold}, similarity={similarity_threshold}, distance={distance_threshold}")
|
||||
print()
|
||||
|
||||
for frame_num_str, frame_data in sorted_frames:
|
||||
frame_num = int(frame_num_str)
|
||||
frame_gap = frame_num - prev_frame_num if prev_frame_num is not None else 1
|
||||
prev_frame_num = frame_num
|
||||
|
||||
faces = frame_data.get("faces", [])
|
||||
|
||||
if not faces:
|
||||
prev_faces = []
|
||||
prev_trace_ids = []
|
||||
continue
|
||||
|
||||
matches = match_faces(
|
||||
faces,
|
||||
prev_faces,
|
||||
iou_threshold,
|
||||
similarity_threshold,
|
||||
distance_threshold,
|
||||
use_embedding,
|
||||
frame_gap,
|
||||
cut_boundaries,
|
||||
prev_face_frame,
|
||||
frame_num,
|
||||
)
|
||||
|
||||
trace_ids = []
|
||||
for curr_idx, prev_idx in matches.items():
|
||||
if prev_idx >= 0:
|
||||
trace_id = prev_trace_ids[prev_idx]
|
||||
else:
|
||||
trace_id = next_trace_id
|
||||
next_trace_id += 1
|
||||
|
||||
faces[curr_idx]["trace_id"] = trace_id
|
||||
trace_ids.append(trace_id)
|
||||
traces[trace_id].append({
|
||||
"frame": frame_num,
|
||||
"face_index": curr_idx,
|
||||
"bbox": {
|
||||
"x": faces[curr_idx]["x"],
|
||||
"y": faces[curr_idx]["y"],
|
||||
"width": faces[curr_idx]["width"],
|
||||
"height": faces[curr_idx]["height"],
|
||||
},
|
||||
"confidence": faces[curr_idx].get("confidence", 0.0),
|
||||
"pose_angle": faces[curr_idx].get("pose_angle", {}).get("angle", "unknown"),
|
||||
"pose_full": faces[curr_idx].get("pose_angle", {}), # 完整 pose 信息
|
||||
})
|
||||
|
||||
prev_faces = faces
|
||||
prev_trace_ids = trace_ids
|
||||
prev_face_frame = frame_num
|
||||
|
||||
if frame_num % 100 == 0:
|
||||
print(f" Frame {frame_num}: {len(faces)} faces, {len(set(trace_ids))} active traces")
|
||||
|
||||
face_data["traces"] = {}
|
||||
for trace_id, path in traces.items():
|
||||
if len(path) >= 1:
|
||||
duration_frames = path[-1]["frame"] - path[0]["frame"] + 1
|
||||
avg_confidence = sum(p["confidence"] for p in path) / len(path)
|
||||
pose_angles = [p["pose_angle"] for p in path]
|
||||
|
||||
# Pose Trace: 完整 pose 信息
|
||||
pose_trace = []
|
||||
for p in path:
|
||||
pose_info = p.get("pose_full", {})
|
||||
pose_trace.append({
|
||||
"frame": p["frame"],
|
||||
"angle": pose_info.get("angle", "unknown"),
|
||||
"confidence": pose_info.get("confidence", 0.0),
|
||||
"pitch": pose_info.get("pitch", "neutral"),
|
||||
"features": pose_info.get("features", {}),
|
||||
})
|
||||
|
||||
# Pose Statistics
|
||||
pose_counts = defaultdict(int)
|
||||
pose_confidence_by_angle = defaultdict(list)
|
||||
for pose in pose_trace:
|
||||
pose_counts[pose["angle"]] += 1
|
||||
pose_confidence_by_angle[pose["angle"]].append(pose["confidence"])
|
||||
|
||||
pose_statistics = {
|
||||
"distribution": dict(pose_counts),
|
||||
"avg_confidence_by_angle": {
|
||||
angle: round(sum(conf_list) / len(conf_list), 3)
|
||||
for angle, conf_list in pose_confidence_by_angle.items()
|
||||
},
|
||||
"dominant_angle": max(pose_counts.items(), key=lambda x: x[1])[0] if pose_counts else "unknown",
|
||||
"pose_count": len(pose_counts),
|
||||
}
|
||||
|
||||
# Pose Transitions: pose 变化事件
|
||||
pose_transitions = []
|
||||
prev_pose = None
|
||||
for i, pose in enumerate(pose_trace):
|
||||
if prev_pose is not None and pose["angle"] != prev_pose["angle"]:
|
||||
pose_transitions.append({
|
||||
"frame": pose["frame"],
|
||||
"from_angle": prev_pose["angle"],
|
||||
"to_angle": pose["angle"],
|
||||
"transition_index": len(pose_transitions) + 1,
|
||||
})
|
||||
prev_pose = pose
|
||||
|
||||
face_data["traces"][str(trace_id)] = {
|
||||
"trace_id": trace_id,
|
||||
"start_frame": path[0]["frame"],
|
||||
"end_frame": path[-1]["frame"],
|
||||
"duration_frames": duration_frames,
|
||||
"duration_seconds": duration_frames / (face_data.get("metadata") or {}).get("fps", face_data.get("fps", 30.0)),
|
||||
"total_appearances": len(path),
|
||||
"avg_confidence": avg_confidence,
|
||||
"pose_angles": pose_angles,
|
||||
"pose_trace": pose_trace,
|
||||
"pose_statistics": pose_statistics,
|
||||
"pose_transitions": pose_transitions,
|
||||
"path": path,
|
||||
}
|
||||
|
||||
# Ensure metadata exists
|
||||
if not face_data.get("metadata"):
|
||||
face_data["metadata"] = {}
|
||||
|
||||
face_data["metadata"]["trace_stats"] = {
|
||||
"total_traces": next_trace_id,
|
||||
"active_traces": len(traces),
|
||||
"long_traces": len([t for t in traces.values() if len(t) >= 2]),
|
||||
}
|
||||
|
||||
return face_data
|
||||
|
||||
|
||||
def analyze_traces(face_data: Dict) -> None:
|
||||
"""
|
||||
Analyze and print trace statistics
|
||||
"""
|
||||
traces = face_data.get("traces", {})
|
||||
metadata = face_data.get("metadata", {})
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Face Trace Analysis")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"\nTotal traces: {metadata.get('trace_stats', {}).get('total_traces', 0)}")
|
||||
print(f"Long traces (>= 2 frames): {len(traces)}")
|
||||
|
||||
if not traces:
|
||||
return
|
||||
|
||||
sorted_traces = sorted(traces.values(), key=lambda x: x["duration_frames"], reverse=True)
|
||||
|
||||
print("\n=== Top 10 Longest Traces ===")
|
||||
for i, trace in enumerate(sorted_traces[:10]):
|
||||
print(f"\nTrace {trace['trace_id']}:")
|
||||
print(f" Frames: {trace['start_frame']} - {trace['end_frame']} ({trace['duration_frames']} frames)")
|
||||
print(f" Duration: {trace['duration_seconds']:.2f} seconds")
|
||||
print(f" Appearances: {trace['total_appearances']}")
|
||||
print(f" Avg Confidence: {trace['avg_confidence']:.3f}")
|
||||
|
||||
# Pose Statistics
|
||||
pose_stats = trace.get("pose_statistics", {})
|
||||
print(f" Pose Distribution: {pose_stats.get('distribution', {})}")
|
||||
print(f" Dominant Angle: {pose_stats.get('dominant_angle', 'unknown')}")
|
||||
|
||||
# Pose Transitions
|
||||
transitions = trace.get("pose_transitions", [])
|
||||
if transitions:
|
||||
print(f" Pose Transitions: {len(transitions)} events")
|
||||
for t in transitions[:3]: # 只显示前 3 个
|
||||
print(f" - Frame {t['frame']}: {t['from_angle']} → {t['to_angle']}")
|
||||
|
||||
pose_stats = defaultdict(int)
|
||||
for trace in traces.values():
|
||||
for pose in trace["pose_angles"]:
|
||||
pose_stats[pose] += 1
|
||||
|
||||
print("\n=== Pose Distribution in Traces ===")
|
||||
for pose, count in sorted(pose_stats.items(), key=lambda x: x[1], reverse=True):
|
||||
print(f" {pose}: {count}")
|
||||
|
||||
duration_distribution = defaultdict(int)
|
||||
for trace in traces.values():
|
||||
d = trace["duration_frames"]
|
||||
if d <= 30:
|
||||
duration_distribution["short (<= 30 frames)"] += 1
|
||||
elif d <= 90:
|
||||
duration_distribution["medium (31-90 frames)"] += 1
|
||||
else:
|
||||
duration_distribution["long (> 90 frames)"] += 1
|
||||
|
||||
print("\n=== Trace Duration Distribution ===")
|
||||
for duration, count in sorted(duration_distribution.items()):
|
||||
print(f" {duration}: {count}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Track faces across frames")
|
||||
parser.add_argument("--face-json", required=True, help="Path to face.json")
|
||||
parser.add_argument("--output", help="Output path (default: face_traced.json)")
|
||||
parser.add_argument("--iou-threshold", type=float, default=0.3, help="IoU threshold")
|
||||
parser.add_argument("--similarity-threshold", type=float, default=0.7, help="Embedding similarity threshold")
|
||||
parser.add_argument("--distance-threshold", type=float, default=100.0, help="Distance threshold")
|
||||
parser.add_argument("--no-embedding", action="store_true", help="Disable embedding matching")
|
||||
parser.add_argument("--cuts-json", help="Path to cut.json for scene-cut-aware tracking")
|
||||
parser.add_argument("--analyze-only", action="store_true", help="Only analyze, don't output")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Load cut boundaries if provided
|
||||
cut_boundaries = None
|
||||
if args.cuts_json:
|
||||
with open(args.cuts_json) as f:
|
||||
cuts = json.load(f)
|
||||
cut_boundaries = {s["start_frame"] for s in cuts.get("scenes", []) if s["start_frame"] > 0}
|
||||
print(f" Cut boundaries loaded: {len(cut_boundaries)} cuts")
|
||||
|
||||
print("=" * 60)
|
||||
print("Face Tracker")
|
||||
print("=" * 60)
|
||||
|
||||
with open(args.face_json) as f:
|
||||
face_data = json.load(f)
|
||||
|
||||
print(f"\nInput: {args.face_json}")
|
||||
print(f"Frames: {len(face_data.get('frames', {}))}")
|
||||
|
||||
face_data = track_faces(
|
||||
face_data,
|
||||
iou_threshold=args.iou_threshold,
|
||||
similarity_threshold=args.similarity_threshold,
|
||||
distance_threshold=args.distance_threshold,
|
||||
use_embedding=not args.no_embedding,
|
||||
cut_boundaries=cut_boundaries,
|
||||
)
|
||||
|
||||
analyze_traces(face_data)
|
||||
|
||||
if not args.analyze_only:
|
||||
output_path = args.output or args.face_json.replace(".json", "_traced.json")
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(strip_embeddings_and_round(face_data), f, indent=2)
|
||||
print(f"\n✅ Output saved to: {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,722 @@
|
||||
#!/opt/homebrew/bin/python3.11
|
||||
"""
|
||||
Qdrant _faces and _seeds Collection Operations
|
||||
|
||||
Functions for _faces:
|
||||
- ensure_faces_collection(): Create _faces collection if not exists
|
||||
- generate_point_id(): Generate consistent point ID
|
||||
- push_face_embeddings_batch(): Batch push embeddings to Qdrant
|
||||
- update_trace_ids(): Update trace_id after face tracking
|
||||
- get_file_faces(): Get all face points for a file
|
||||
- get_trace_representatives(): Get representative embeddings per trace
|
||||
|
||||
Functions for _seeds:
|
||||
- ensure_seeds_collection(): Create _seeds collection if not exists
|
||||
- push_seed_embedding(): Push identity seed embedding
|
||||
- get_seeds(): Get all seed points
|
||||
- search_seeds(): Cosine search against seeds
|
||||
- delete_seed(): Delete a seed point
|
||||
|
||||
Collection Schema:
|
||||
- _faces: 512D, Cosine, payload: {file_uuid, frame, trace_id, bbox, confidence, identity_id, identity_uuid, stranger_id}
|
||||
- _seeds: 512D, Cosine, payload: {identity_id, identity_uuid, name, source, file_uuid, trace_id, tmdb_id, created_at}
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import hashlib
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
|
||||
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
|
||||
FACES_COLLECTION = "_faces"
|
||||
SEEDS_COLLECTION = "_seeds"
|
||||
VECTOR_DIM = 512
|
||||
# Default 1000 (was 100): larger pages cut the number of scroll/set_payload HTTP
|
||||
# round-trips ~10x on large files (B2). Still overridable via QDRANT_BATCH_SIZE.
|
||||
BATCH_SIZE = int(os.environ.get("QDRANT_BATCH_SIZE", "1000"))
|
||||
|
||||
|
||||
def qdrant_request(method: str, path: str, body: dict = None) -> dict:
|
||||
"""Make HTTP request to Qdrant"""
|
||||
url = f"{QDRANT_URL}{path}"
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
return json.loads(resp.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
error_body = e.read().decode()
|
||||
raise RuntimeError(f"Qdrant HTTP {e.code}: {error_body}")
|
||||
|
||||
|
||||
def ensure_faces_collection() -> bool:
|
||||
"""Create _faces collection if not exists"""
|
||||
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
return True # Collection exists
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 404:
|
||||
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
|
||||
|
||||
# Create collection
|
||||
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
|
||||
create_url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
|
||||
data = json.dumps(body).encode()
|
||||
req = urllib.request.Request(create_url, data=data, method="PUT")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"[QDRANT] Created collection: {FACES_COLLECTION}")
|
||||
return True
|
||||
except urllib.error.HTTPError as e:
|
||||
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
|
||||
|
||||
|
||||
def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int:
|
||||
"""Generate consistent point ID from file_uuid + frame + trace_id"""
|
||||
key = f"{file_uuid}_{frame}_{trace_id}"
|
||||
return int(hashlib.md5(key.encode()).hexdigest()[:16], 16)
|
||||
|
||||
|
||||
def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> int:
|
||||
"""Batch push face embeddings to _faces collection
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
faces: List of {frame, trace_id, bbox, confidence, embedding}
|
||||
publisher: RedisPublisher for progress reporting (optional)
|
||||
|
||||
Returns:
|
||||
Number of successfully pushed embeddings
|
||||
|
||||
Raises:
|
||||
RuntimeError: If Qdrant push fails
|
||||
"""
|
||||
if not faces:
|
||||
return 0
|
||||
|
||||
ensure_faces_collection()
|
||||
|
||||
total = len(faces)
|
||||
pushed = 0
|
||||
|
||||
for i in range(0, total, BATCH_SIZE):
|
||||
batch = faces[i : i + BATCH_SIZE]
|
||||
|
||||
points = []
|
||||
for face in batch:
|
||||
point_id = generate_point_id(
|
||||
file_uuid, face["frame"], face.get("trace_id", 0)
|
||||
)
|
||||
points.append(
|
||||
{
|
||||
"id": point_id,
|
||||
"vector": face["embedding"],
|
||||
"payload": {
|
||||
"file_uuid": file_uuid,
|
||||
"frame": face["frame"],
|
||||
"trace_id": face.get("trace_id", 0),
|
||||
"bbox": face["bbox"],
|
||||
"confidence": face.get("confidence", 0.5),
|
||||
"capture_quality": face.get("capture_quality", 0.0),
|
||||
"identity_id": 0,
|
||||
"identity_uuid": "",
|
||||
"stranger_id": 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
body = {"points": points}
|
||||
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true"
|
||||
data = json.dumps(body).encode()
|
||||
req = urllib.request.Request(url, data=data, method="PUT")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
pushed += len(batch)
|
||||
except urllib.error.HTTPError as e:
|
||||
error_body = e.read().decode()
|
||||
raise RuntimeError(
|
||||
f"Qdrant push failed (batch {i // BATCH_SIZE}): HTTP {e.code} - {error_body}"
|
||||
)
|
||||
|
||||
if publisher:
|
||||
pct = int((i + len(batch)) * 100 / total)
|
||||
publisher.progress("face", i + len(batch), total, f"Qdrant push {pct}%")
|
||||
|
||||
print(f"[QDRANT] Pushed {pushed} embeddings to {FACES_COLLECTION}")
|
||||
return pushed
|
||||
|
||||
|
||||
def update_trace_ids(
|
||||
file_uuid: str, trace_mapping: dict, return_trace_ids: bool = False
|
||||
):
|
||||
"""Update trace_id for all face points in a file
|
||||
|
||||
Called by store_traced_faces.py after face tracking.
|
||||
Uses Qdrant set_payload to avoid reading/writing vectors.
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
trace_mapping: {frame: {bbox_key: trace_id}}
|
||||
bbox_key = f"{x}_{y}_{width}_{height}"
|
||||
return_trace_ids: If True, also return the set of trace_ids seen during the
|
||||
scroll. This lets the caller avoid a redundant full collection scan just
|
||||
to count unique traces (B1 optimization for large files).
|
||||
|
||||
Returns:
|
||||
Number of updated points, or (updated_count, trace_id_set) if return_trace_ids.
|
||||
"""
|
||||
all_points = []
|
||||
offset = None
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"limit": BATCH_SIZE,
|
||||
"with_payload": True,
|
||||
"with_vector": False,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
|
||||
}
|
||||
if offset:
|
||||
body["offset"] = offset
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
|
||||
)
|
||||
batch = result.get("result", {}).get("points", [])
|
||||
if not batch:
|
||||
break
|
||||
all_points.extend(batch)
|
||||
offset = result.get("result", {}).get("next_page_offset")
|
||||
if not offset:
|
||||
break
|
||||
|
||||
# Group point IDs by trace_id
|
||||
trace_groups = {}
|
||||
for point in all_points:
|
||||
point_id = point["id"]
|
||||
payload = point.get("payload", {})
|
||||
|
||||
frame = payload.get("frame")
|
||||
|
||||
# Support two bbox formats:
|
||||
# 1. Nested bbox field
|
||||
# 2. Direct x, y, width, height fields
|
||||
bbox = payload.get("bbox", {})
|
||||
if bbox:
|
||||
# Format 1: has bbox field
|
||||
x = bbox.get('x')
|
||||
y = bbox.get('y')
|
||||
width = bbox.get('width')
|
||||
height = bbox.get('height')
|
||||
else:
|
||||
# Format 2: direct fields
|
||||
x = payload.get('x')
|
||||
y = payload.get('y')
|
||||
width = payload.get('width')
|
||||
height = payload.get('height')
|
||||
|
||||
if x is None or y is None or width is None or height is None:
|
||||
continue
|
||||
|
||||
bbox_key = f"{x}_{y}_{width}_{height}"
|
||||
|
||||
trace_id = trace_mapping.get(frame, {}).get(bbox_key)
|
||||
if trace_id is None:
|
||||
continue
|
||||
|
||||
if trace_id not in trace_groups:
|
||||
trace_groups[trace_id] = []
|
||||
trace_groups[trace_id].append(point_id)
|
||||
|
||||
if not trace_groups:
|
||||
return (0, set()) if return_trace_ids else 0
|
||||
|
||||
# Use set_payload per trace_id group (no vector write)
|
||||
total = 0
|
||||
for trace_id, point_ids in trace_groups.items():
|
||||
for i in range(0, len(point_ids), BATCH_SIZE):
|
||||
batch_ids = point_ids[i : i + BATCH_SIZE]
|
||||
set_points_payload({"trace_id": trace_id}, batch_ids)
|
||||
total += len(batch_ids)
|
||||
|
||||
print(f"[QDRANT] Updated {total} trace_ids in {FACES_COLLECTION}")
|
||||
if return_trace_ids:
|
||||
return total, set(trace_groups.keys())
|
||||
return total
|
||||
|
||||
|
||||
def set_points_payload(payload: dict, point_ids: list, wait: bool = True) -> dict:
|
||||
"""Set payload fields on specific Qdrant points (without touching vectors)
|
||||
|
||||
Args:
|
||||
payload: Dict of payload fields to set (e.g. {"trace_id": 5})
|
||||
point_ids: List of Qdrant point IDs
|
||||
wait: Wait for operation to complete
|
||||
|
||||
Returns:
|
||||
Qdrant API response
|
||||
"""
|
||||
body = {
|
||||
"payload": payload,
|
||||
"points": point_ids,
|
||||
"wait": wait,
|
||||
}
|
||||
return qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/payload", body
|
||||
)
|
||||
|
||||
|
||||
def delete_file_faces(file_uuid: str) -> int:
|
||||
"""Delete all face points for a file
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
|
||||
Returns:
|
||||
Number of deleted points
|
||||
"""
|
||||
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/delete", body
|
||||
)
|
||||
deleted = result.get("result", {}).get("operation_id", 0)
|
||||
print(f"[QDRANT] Deleted faces for file_uuid={file_uuid}")
|
||||
return deleted
|
||||
|
||||
|
||||
def get_file_faces(file_uuid: str, with_vector: bool = False) -> list:
|
||||
"""Get all face points for a file
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
with_vector: Whether to include vector data (default False for payload-only)
|
||||
|
||||
Returns:
|
||||
List of points with payload (and vector if requested)
|
||||
"""
|
||||
all_points = []
|
||||
offset = None
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"limit": BATCH_SIZE,
|
||||
"with_payload": True,
|
||||
"with_vector": with_vector,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
|
||||
}
|
||||
if offset:
|
||||
body["offset"] = offset
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
|
||||
)
|
||||
batch = result.get("result", {}).get("points", [])
|
||||
if not batch:
|
||||
break
|
||||
all_points.extend(batch)
|
||||
offset = result.get("result", {}).get("next_page_offset")
|
||||
if not offset:
|
||||
break
|
||||
|
||||
return all_points
|
||||
|
||||
|
||||
def count_file_faces(file_uuid: str) -> int:
|
||||
"""Count face points for a file
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
|
||||
Returns:
|
||||
Number of face points
|
||||
"""
|
||||
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/count", body
|
||||
)
|
||||
return result.get("result", {}).get("count", 0)
|
||||
|
||||
|
||||
def get_trace_representatives(file_uuid: str) -> dict:
|
||||
"""Get representative embeddings per trace for multi-angle matching
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
|
||||
Returns:
|
||||
{trace_id: [{'frame', 'embedding', 'bbox'}, ...]}
|
||||
Each trace has 3 representatives: start, middle, end
|
||||
"""
|
||||
all_points = get_file_faces(file_uuid, with_vector=True)
|
||||
|
||||
traces = {}
|
||||
for point in all_points:
|
||||
payload = point.get("payload", {})
|
||||
vector = point.get("vector", [])
|
||||
trace_id = payload.get("trace_id", 0)
|
||||
|
||||
if trace_id == 0:
|
||||
continue
|
||||
|
||||
if trace_id not in traces:
|
||||
traces[trace_id] = []
|
||||
|
||||
traces[trace_id].append(
|
||||
{
|
||||
"frame": payload.get("frame"),
|
||||
"embedding": vector,
|
||||
"bbox": payload.get("bbox", {}),
|
||||
"confidence": payload.get("confidence", 0.5),
|
||||
}
|
||||
)
|
||||
|
||||
for trace_id in traces:
|
||||
points = traces[trace_id]
|
||||
points.sort(key=lambda x: x["frame"])
|
||||
|
||||
if len(points) <= 3:
|
||||
traces[trace_id] = points
|
||||
else:
|
||||
start = points[0]
|
||||
end = points[-1]
|
||||
middle_idx = len(points) // 2
|
||||
middle = points[middle_idx]
|
||||
traces[trace_id] = [start, middle, end]
|
||||
|
||||
return traces
|
||||
|
||||
|
||||
def get_trace_centroid(file_uuid: str, trace_id: int) -> list:
|
||||
"""Get centroid embedding for a trace
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
trace_id: Trace ID
|
||||
|
||||
Returns:
|
||||
Centroid embedding (512D)
|
||||
"""
|
||||
reps = get_trace_representatives(file_uuid).get(trace_id, [])
|
||||
|
||||
if not reps:
|
||||
return [0.0] * VECTOR_DIM
|
||||
|
||||
centroid = [0.0] * VECTOR_DIM
|
||||
for rep in reps:
|
||||
for i, v in enumerate(rep["embedding"]):
|
||||
centroid[i] += v
|
||||
|
||||
count = len(reps)
|
||||
for i in range(VECTOR_DIM):
|
||||
centroid[i] /= count
|
||||
|
||||
return centroid
|
||||
|
||||
|
||||
# ==================== _seeds Collection ====================
|
||||
|
||||
|
||||
def ensure_seeds_collection() -> bool:
|
||||
"""Create _seeds collection if not exists"""
|
||||
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
|
||||
req = urllib.request.Request(url, method="GET")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
return True # Collection exists
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 404:
|
||||
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
|
||||
|
||||
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
|
||||
create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
|
||||
data = json.dumps(body).encode()
|
||||
req = urllib.request.Request(create_url, data=data, method="PUT")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"[QDRANT] Created collection: {SEEDS_COLLECTION}")
|
||||
return True
|
||||
except urllib.error.HTTPError as e:
|
||||
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
|
||||
|
||||
|
||||
def push_seed_embedding(
|
||||
identity_id: int,
|
||||
identity_uuid: str,
|
||||
name: str,
|
||||
embedding: list,
|
||||
source: str = "tmdb",
|
||||
file_uuid: str = None,
|
||||
trace_id: int = None,
|
||||
tmdb_id: int = None,
|
||||
) -> bool:
|
||||
"""Push identity seed embedding to _seeds collection
|
||||
|
||||
Args:
|
||||
identity_id: PG identity.id
|
||||
identity_uuid: Identity UUID
|
||||
name: Identity name
|
||||
embedding: 512D embedding
|
||||
source: 'tmdb' | 'manual' | 'propagation'
|
||||
file_uuid: File UUID (for manual/propagation seeds)
|
||||
trace_id: Trace ID (for propagation seeds)
|
||||
tmdb_id: TMDb ID (for TMDb seeds)
|
||||
|
||||
Returns:
|
||||
True if successful
|
||||
|
||||
Raises:
|
||||
RuntimeError: If Qdrant push fails
|
||||
"""
|
||||
ensure_seeds_collection()
|
||||
|
||||
payload = {
|
||||
"identity_id": identity_id,
|
||||
"identity_uuid": identity_uuid,
|
||||
"name": name,
|
||||
"source": source,
|
||||
"created_at": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
if file_uuid:
|
||||
payload["file_uuid"] = file_uuid
|
||||
if trace_id:
|
||||
payload["trace_id"] = trace_id
|
||||
if tmdb_id:
|
||||
payload["tmdb_id"] = tmdb_id
|
||||
|
||||
body = {
|
||||
"points": [
|
||||
{
|
||||
"id": identity_id, # Use identity_id as point_id
|
||||
"vector": embedding,
|
||||
"payload": payload,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}/points?wait=true"
|
||||
data = json.dumps(body).encode()
|
||||
req = urllib.request.Request(url, data=data, method="PUT")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Api-Key", QDRANT_API_KEY)
|
||||
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"[QDRANT] Pushed seed: {name} (id={identity_id}, source={source})")
|
||||
return True
|
||||
except urllib.error.HTTPError as e:
|
||||
error_body = e.read().decode()
|
||||
raise RuntimeError(f"Qdrant seed push failed: HTTP {e.code} - {error_body}")
|
||||
|
||||
|
||||
def get_seeds(source: str = None, file_uuid: str = None) -> list:
|
||||
"""Get all seed points
|
||||
|
||||
Args:
|
||||
source: Filter by source ('tmdb', 'manual', 'propagation'), or None for all
|
||||
file_uuid: Filter by file_uuid, or None for all
|
||||
|
||||
Returns:
|
||||
List of seed points with payload and vector
|
||||
"""
|
||||
ensure_seeds_collection()
|
||||
|
||||
all_points = []
|
||||
offset = None
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"limit": BATCH_SIZE,
|
||||
"with_payload": True,
|
||||
"with_vector": True,
|
||||
}
|
||||
|
||||
filters = []
|
||||
if source:
|
||||
filters.append({"key": "source", "match": {"value": source}})
|
||||
if file_uuid:
|
||||
filters.append({"key": "file_uuid", "match": {"value": file_uuid}})
|
||||
|
||||
if filters:
|
||||
body["filter"] = {"must": filters}
|
||||
|
||||
if offset:
|
||||
body["offset"] = offset
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body
|
||||
)
|
||||
batch = result.get("result", {}).get("points", [])
|
||||
if not batch:
|
||||
break
|
||||
all_points.extend(batch)
|
||||
offset = result.get("result", {}).get("next_page_offset")
|
||||
if not offset:
|
||||
break
|
||||
|
||||
return all_points
|
||||
|
||||
|
||||
def search_seeds(
|
||||
query_embedding: list, limit: int = 10, threshold: float = 0.0
|
||||
) -> list:
|
||||
"""Cosine search against seeds
|
||||
|
||||
Args:
|
||||
query_embedding: 512D query vector
|
||||
limit: Max results
|
||||
threshold: Minimum score threshold
|
||||
|
||||
Returns:
|
||||
List of {identity_id, identity_uuid, name, source, score}
|
||||
"""
|
||||
ensure_seeds_collection()
|
||||
|
||||
body = {
|
||||
"vector": query_embedding,
|
||||
"limit": limit,
|
||||
"with_payload": True,
|
||||
}
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{SEEDS_COLLECTION}/points/search", body
|
||||
)
|
||||
points = result.get("result", [])
|
||||
|
||||
results = []
|
||||
for point in points:
|
||||
score = point.get("score", 0)
|
||||
if score < threshold:
|
||||
continue
|
||||
|
||||
payload = point.get("payload", {})
|
||||
results.append(
|
||||
{
|
||||
"identity_id": payload.get("identity_id"),
|
||||
"identity_uuid": payload.get("identity_uuid"),
|
||||
"name": payload.get("name"),
|
||||
"source": payload.get("source"),
|
||||
"score": score,
|
||||
}
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def delete_seed(identity_id: int) -> bool:
|
||||
"""Delete a seed point
|
||||
|
||||
Args:
|
||||
identity_id: Identity ID (used as point_id)
|
||||
|
||||
Returns:
|
||||
True if successful
|
||||
"""
|
||||
body = {"points": [identity_id]}
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body
|
||||
)
|
||||
print(f"[QDRANT] Deleted seed: identity_id={identity_id}")
|
||||
return result.get("result", {}).get("status") == "completed"
|
||||
|
||||
|
||||
def count_seeds(source: str = None) -> int:
|
||||
"""Count seed points
|
||||
|
||||
Args:
|
||||
source: Filter by source, or None for all
|
||||
|
||||
Returns:
|
||||
Number of seed points
|
||||
"""
|
||||
ensure_seeds_collection()
|
||||
|
||||
body = {}
|
||||
if source:
|
||||
body["filter"] = {"must": [{"key": "source", "match": {"value": source}}]}
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{SEEDS_COLLECTION}/points/count", body
|
||||
)
|
||||
return result.get("result", {}).get("count", 0)
|
||||
|
||||
|
||||
def update_identity_in_faces(
|
||||
file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str
|
||||
) -> int:
|
||||
"""Update identity_id/identity_uuid for all face points with trace_id
|
||||
|
||||
Called after identity binding confirmation.
|
||||
Uses Qdrant set_payload to avoid reading/writing vectors.
|
||||
|
||||
Args:
|
||||
file_uuid: Video file UUID
|
||||
trace_id: Trace ID
|
||||
identity_id: Identity ID
|
||||
identity_uuid: Identity UUID
|
||||
|
||||
Returns:
|
||||
Number of updated points
|
||||
"""
|
||||
all_points = []
|
||||
offset = None
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"limit": BATCH_SIZE,
|
||||
"with_payload": True,
|
||||
"with_vector": False,
|
||||
"filter": {
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": trace_id}},
|
||||
]
|
||||
},
|
||||
}
|
||||
if offset:
|
||||
body["offset"] = offset
|
||||
|
||||
result = qdrant_request(
|
||||
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
|
||||
)
|
||||
batch = result.get("result", {}).get("points", [])
|
||||
if not batch:
|
||||
break
|
||||
all_points.extend(batch)
|
||||
offset = result.get("result", {}).get("next_page_offset")
|
||||
if not offset:
|
||||
break
|
||||
|
||||
if not all_points:
|
||||
return 0
|
||||
|
||||
point_ids = [point["id"] for point in all_points]
|
||||
|
||||
# Use set_payload (no vector write)
|
||||
for i in range(0, len(point_ids), BATCH_SIZE):
|
||||
batch_ids = point_ids[i : i + BATCH_SIZE]
|
||||
set_points_payload(
|
||||
{"identity_id": identity_id, "identity_uuid": identity_uuid}, batch_ids
|
||||
)
|
||||
|
||||
print(
|
||||
f"[QDRANT] Updated {len(point_ids)} face points with identity_id={identity_id}"
|
||||
)
|
||||
return len(point_ids)
|
||||
Reference in New Issue
Block a user