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:
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/accusys/momentry_core/scripts/asr_processor_simplified.py
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/accusys/momentry_core/scripts/asrx_processor.py
|
||||
@@ -0,0 +1,655 @@
|
||||
#!/opt/homebrew/bin/python3.11
|
||||
"""
|
||||
Face Clustering Processor V3 - Single-stage trace clustering (Stage 2 merge removed)
|
||||
|
||||
Strategy:
|
||||
1. Load face embeddings from Qdrant _faces collection
|
||||
2. Group by trace_id, compute weighted average embedding per trace
|
||||
3. Single-stage AgglomerativeClustering (no Stage 2 merge)
|
||||
4. Assign person_id to all faces in each trace
|
||||
5. Output face_cluster.json with auto speaker binding
|
||||
|
||||
Output format:
|
||||
{"status", "file_uuid", "clusters": [{cluster_id, face_count, representative_face}], "frames": [{frame, timestamp, faces: [{face_id, cluster_id, confidence}]}]}
|
||||
|
||||
Changes from V2:
|
||||
- Added argparse for CLI arguments
|
||||
- Added Redis progress reporting
|
||||
- Added status + file_uuid to output
|
||||
- Added auto_bind_speakers() integration
|
||||
|
||||
Changes from previous (broken) version:
|
||||
- REMOVED Stage 2 merge logic (was incorrectly merging different people)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import numpy as np
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from sklearn.cluster import AgglomerativeClustering
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from redis_publisher import RedisPublisher
|
||||
|
||||
|
||||
def round_json_numbers(obj):
|
||||
"""Recursively round all float values to 2 decimal places (JSON output only)."""
|
||||
if isinstance(obj, float):
|
||||
return round(obj, 2)
|
||||
if isinstance(obj, dict):
|
||||
return {k: round_json_numbers(v) for k, v in obj.items()}
|
||||
if isinstance(obj, list):
|
||||
return [round_json_numbers(v) for v in obj]
|
||||
return obj
|
||||
|
||||
UUID = os.getenv("UUID", "quick_preview")
|
||||
OUTPUT_DIR = os.getenv("MOMENTRY_OUTPUT_DIR", "./output")
|
||||
OUTPUT_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.face_clustered.json")
|
||||
ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json")
|
||||
|
||||
CLUSTER_THRESHOLD = 0.20 # Updated for facenet-pytorch (was 0.15 for CoreML)
|
||||
CLUSTER_METHOD = "leader"
|
||||
|
||||
|
||||
def write_empty_output(status: str, file_uuid: str, output_path: str):
|
||||
output_data = {
|
||||
"status": status,
|
||||
"file_uuid": file_uuid,
|
||||
"clusters": [],
|
||||
"frames": [],
|
||||
}
|
||||
with open(output_path, "w", encoding="utf-8") as f:
|
||||
json.dump(output_data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Wrote empty output ({status}) to {output_path}")
|
||||
|
||||
|
||||
def load_qdrant_faces(uuid: str, publisher: RedisPublisher) -> list:
|
||||
"""Load all face points (payload + vector) from Qdrant _faces for a file."""
|
||||
publisher.progress("face_cluster", 0, 100, "Loading embeddings from Qdrant")
|
||||
try:
|
||||
import requests
|
||||
|
||||
qdrant_url = os.environ.get("QDRANT_URL", "http://localhost:6333")
|
||||
qdrant_api_key = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
|
||||
headers = {}
|
||||
if qdrant_api_key:
|
||||
headers["api-key"] = qdrant_api_key
|
||||
|
||||
all_points = []
|
||||
offset = None
|
||||
while True:
|
||||
body = {
|
||||
"limit": 10000,
|
||||
"with_payload": True,
|
||||
"with_vector": True,
|
||||
"filter": {"must": [{"key": "file_uuid", "match": {"value": uuid}}]},
|
||||
}
|
||||
if offset:
|
||||
body["offset"] = offset
|
||||
|
||||
resp = requests.post(
|
||||
f"{qdrant_url}/collections/_faces/points/scroll",
|
||||
json=body,
|
||||
headers=headers,
|
||||
timeout=60,
|
||||
)
|
||||
if resp.status_code != 200:
|
||||
print(f"Qdrant scroll error: {resp.status_code}")
|
||||
break
|
||||
|
||||
data = resp.json()
|
||||
batch = data.get("result", {}).get("points", [])
|
||||
all_points.extend(batch)
|
||||
next_offset = data.get("result", {}).get("next_page_offset")
|
||||
if not next_offset:
|
||||
break
|
||||
offset = next_offset
|
||||
|
||||
print(f"Loaded {len(all_points)} points from Qdrant _faces")
|
||||
return all_points
|
||||
except Exception as e:
|
||||
print(f"Failed to load embeddings from Qdrant: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def cluster_by_trace(
|
||||
points: list, min_faces_per_trace: int = 1, confidence_threshold: float = 0.5
|
||||
) -> tuple:
|
||||
"""
|
||||
Cluster faces by trace_id:
|
||||
1. Filter low-confidence faces
|
||||
2. Group by trace_id
|
||||
3. Compute weighted average embedding per trace
|
||||
"""
|
||||
high_conf_points = [
|
||||
p
|
||||
for p in points
|
||||
if p.get("payload", {}).get("confidence", 0) >= confidence_threshold
|
||||
]
|
||||
print(
|
||||
f"[FILTER] {len(high_conf_points)}/{len(points)} faces pass confidence >= {confidence_threshold}"
|
||||
)
|
||||
|
||||
traces = defaultdict(list)
|
||||
for point in high_conf_points:
|
||||
payload = point.get("payload", {})
|
||||
trace_id = payload.get("trace_id")
|
||||
if trace_id is not None and trace_id >= 0:
|
||||
traces[trace_id].append(point)
|
||||
|
||||
print(f"[TRACE] Found {len(traces)} unique traces")
|
||||
|
||||
trace_embeddings = {}
|
||||
for trace_id, trace_points in traces.items():
|
||||
if len(trace_points) < min_faces_per_trace:
|
||||
continue
|
||||
|
||||
embeddings = []
|
||||
weights = []
|
||||
for p in trace_points:
|
||||
embeddings.append(p["vector"])
|
||||
weights.append(p.get("payload", {}).get("confidence", 1.0))
|
||||
|
||||
embeddings = np.array(embeddings)
|
||||
weights = np.array(weights)
|
||||
weights = weights / weights.sum()
|
||||
|
||||
avg_embedding = np.average(embeddings, axis=0, weights=weights)
|
||||
avg_embedding = avg_embedding / np.linalg.norm(avg_embedding)
|
||||
|
||||
trace_embeddings[trace_id] = {
|
||||
"embedding": avg_embedding,
|
||||
"face_count": len(trace_points),
|
||||
"avg_confidence": float(np.mean(weights)),
|
||||
"frames": [p.get("payload", {}).get("frame") for p in trace_points],
|
||||
"points": trace_points,
|
||||
}
|
||||
|
||||
print(f"[TRACE] {len(trace_embeddings)} traces with >= {min_faces_per_trace} faces")
|
||||
return trace_embeddings, traces
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
"""
|
||||
Single-stage AgglomerativeClustering on trace means.
|
||||
No Stage 2 merge (the problematic logic has been removed).
|
||||
|
||||
Returns: (trace_to_person, trace_similarities)
|
||||
"""
|
||||
if not trace_embeddings:
|
||||
return {}, {}
|
||||
|
||||
trace_ids = list(trace_embeddings.keys())
|
||||
n_traces = len(trace_ids)
|
||||
|
||||
if n_traces == 0:
|
||||
return {}, {}
|
||||
|
||||
if n_traces == 1:
|
||||
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
|
||||
|
||||
embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids])
|
||||
|
||||
print(
|
||||
f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}..."
|
||||
)
|
||||
clustering = AgglomerativeClustering(
|
||||
n_clusters=None,
|
||||
distance_threshold=threshold,
|
||||
metric="cosine",
|
||||
linkage="average",
|
||||
)
|
||||
labels = clustering.fit_predict(embeddings)
|
||||
|
||||
unique_labels = set(labels)
|
||||
print(f"[CLUSTER] Detected {len(unique_labels)} unique persons")
|
||||
|
||||
trace_to_person = {}
|
||||
trace_similarities = {}
|
||||
for i, trace_id in enumerate(trace_ids):
|
||||
trace_to_person[trace_id] = labels[i]
|
||||
# For agglomerative, similarity = 1 - distance to cluster (approximate)
|
||||
trace_similarities[trace_id] = 1.0 # placeholder; exact requires pairwise
|
||||
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
"""
|
||||
Seed-leader clustering with incremental mean centroids.
|
||||
Algorithm:
|
||||
1. Iterate traces in stable order (by trace_id).
|
||||
2. For each trace, compare its centroid to each existing person's mean centroid.
|
||||
3. If max cosine similarity >= (1 - threshold) → assign to that person, update mean.
|
||||
4. Else → create new person seeded by this trace.
|
||||
|
||||
threshold: cosine distance threshold (default 0.35 = similarity >= 0.65)
|
||||
|
||||
Returns: (trace_to_person: dict, trace_similarities: dict)
|
||||
trace_to_person: {trace_id: person_label}
|
||||
trace_similarities: {trace_id: similarity_to_centroid}
|
||||
"""
|
||||
if not trace_embeddings:
|
||||
return {}, {}
|
||||
|
||||
# Sort by trace_id for deterministic order
|
||||
trace_ids = sorted(trace_embeddings.keys())
|
||||
n_traces = len(trace_ids)
|
||||
|
||||
if n_traces == 0:
|
||||
return {}, {}
|
||||
|
||||
if n_traces == 1:
|
||||
return {trace_ids[0]: 0}, {trace_ids[0]: 1.0}
|
||||
|
||||
sim_threshold = 1.0 - threshold # cosine similarity threshold
|
||||
persons = [] # list of {centroid: np.array, member_trace_ids: []}
|
||||
trace_similarities = {}
|
||||
|
||||
print(
|
||||
f"[CLUSTER] Seed-leader: {n_traces} traces, similarity_threshold={sim_threshold:.3f} (distance={threshold})..."
|
||||
)
|
||||
|
||||
for trace_id in trace_ids:
|
||||
centroid = trace_embeddings[trace_id]["embedding"]
|
||||
|
||||
if not persons:
|
||||
# First trace → seed first person
|
||||
persons.append(
|
||||
{"centroid": centroid.copy(), "member_trace_ids": [trace_id]}
|
||||
)
|
||||
trace_similarities[trace_id] = 1.0 # first trace is the centroid
|
||||
continue
|
||||
|
||||
# Find best matching person by cosine similarity to current mean centroid
|
||||
best_sim = -1.0
|
||||
best_person_idx = -1
|
||||
for idx, person in enumerate(persons):
|
||||
p_centroid = person["centroid"]
|
||||
norm1 = np.linalg.norm(centroid)
|
||||
norm2 = np.linalg.norm(p_centroid)
|
||||
if norm1 > 0 and norm2 > 0:
|
||||
sim = np.dot(centroid, p_centroid) / (norm1 * norm2)
|
||||
if sim > best_sim:
|
||||
best_sim = sim
|
||||
best_person_idx = idx
|
||||
|
||||
if best_sim >= sim_threshold:
|
||||
# Assign to this person, update mean centroid (incremental)
|
||||
persons[best_person_idx]["member_trace_ids"].append(trace_id)
|
||||
trace_similarities[trace_id] = best_sim
|
||||
# Recompute mean from all member trace centroids
|
||||
member_embeddings = np.array(
|
||||
[
|
||||
trace_embeddings[tid]["embedding"]
|
||||
for tid in persons[best_person_idx]["member_trace_ids"]
|
||||
]
|
||||
)
|
||||
persons[best_person_idx]["centroid"] = np.mean(member_embeddings, axis=0)
|
||||
else:
|
||||
# New person
|
||||
persons.append(
|
||||
{"centroid": centroid.copy(), "member_trace_ids": [trace_id]}
|
||||
)
|
||||
trace_similarities[trace_id] = 1.0 # seed trace is its own centroid
|
||||
|
||||
# Build trace_to_person mapping
|
||||
trace_to_person = {}
|
||||
for person_label, person in enumerate(persons):
|
||||
for tid in person["member_trace_ids"]:
|
||||
trace_to_person[tid] = person_label
|
||||
|
||||
print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons")
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def auto_bind_speakers(output_frames: list, asrx_path: str = ASRX_JSON_PATH) -> dict:
|
||||
"""
|
||||
Compute speaker -> Person_N mapping by vote.
|
||||
Each ASRX segment is matched against face timestamps; the most frequent
|
||||
person within the segment's time span gets one vote for that speaker.
|
||||
Returns {"SPEAKER_0": "Person_37", ...}. Pure computation, no DB writes.
|
||||
"""
|
||||
if not os.path.exists(asrx_path):
|
||||
print("Missing data for speaker binding.")
|
||||
return {}
|
||||
|
||||
try:
|
||||
with open(asrx_path) as f:
|
||||
asrx_data = json.load(f)
|
||||
except Exception as e:
|
||||
print(f" Failed to load ASRX: {e}")
|
||||
return {}
|
||||
|
||||
print("Auto-binding Speakers to Persons...")
|
||||
|
||||
face_spans = []
|
||||
for frame_obj in output_frames:
|
||||
ts = frame_obj.get("timestamp")
|
||||
for face in frame_obj.get("faces", []):
|
||||
person_id = face.get("cluster_id")
|
||||
if person_id and ts is not None:
|
||||
face_spans.append({"ts": ts, "person_id": person_id})
|
||||
|
||||
speaker_person_counts = {}
|
||||
|
||||
for seg in asrx_data.get("segments", []):
|
||||
start = seg.get("start_time", seg.get("start"))
|
||||
end = seg.get("end_time", seg.get("end"))
|
||||
speaker = seg.get("speaker_id")
|
||||
if not speaker or start is None or end is None:
|
||||
continue
|
||||
candidates = [
|
||||
f for f in face_spans if f.get("ts") is not None and start <= f["ts"] <= end
|
||||
]
|
||||
if candidates:
|
||||
person_counts = {}
|
||||
for c in candidates:
|
||||
pid = c["person_id"]
|
||||
person_counts[pid] = person_counts.get(pid, 0) + 1
|
||||
if speaker not in speaker_person_counts:
|
||||
speaker_person_counts[speaker] = {}
|
||||
best_person = max(person_counts, key=person_counts.get)
|
||||
speaker_person_counts[speaker][best_person] = (
|
||||
speaker_person_counts[speaker].get(best_person, 0) + 1
|
||||
)
|
||||
|
||||
mapping = {}
|
||||
for speaker, persons in speaker_person_counts.items():
|
||||
if not persons:
|
||||
continue
|
||||
best_person = max(persons, key=persons.get)
|
||||
mapping[speaker] = best_person
|
||||
print(f" {speaker} is likely {best_person} ({persons[best_person]} votes)")
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
def main():
|
||||
global OUTPUT_JSON_PATH, UUID
|
||||
|
||||
parser = argparse.ArgumentParser(description="Face Clustering Processor V3")
|
||||
parser.add_argument("video_path", help="Path to video file")
|
||||
parser.add_argument("output_path", help="Path to output JSON file")
|
||||
parser.add_argument("--uuid", help="Video UUID (optional, overrides env var)")
|
||||
parser.add_argument(
|
||||
"--force", action="store_true", help="Overwrite existing output"
|
||||
)
|
||||
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
|
||||
parser.add_argument(
|
||||
"--method",
|
||||
choices=["agglomerative", "leader"],
|
||||
default="leader",
|
||||
help="Clustering method: agglomerative (sklearn) or seed-leader (default: leader)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--threshold",
|
||||
type=float,
|
||||
default=CLUSTER_THRESHOLD,
|
||||
help=f"Cosine distance threshold for clustering (default: {CLUSTER_THRESHOLD})",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
OUTPUT_JSON_PATH = args.output_path
|
||||
output_dir = os.path.dirname(args.output_path)
|
||||
if args.uuid:
|
||||
uuid = args.uuid
|
||||
else:
|
||||
uuid = os.path.basename(args.video_path).rsplit(".", 1)[0]
|
||||
UUID = uuid
|
||||
|
||||
face_json_path = os.path.join(output_dir, f"{uuid}.face.json")
|
||||
if not os.path.exists(face_json_path):
|
||||
face_json_path = os.path.join(output_dir, uuid, f"{uuid}.face.json")
|
||||
|
||||
publisher = RedisPublisher(uuid)
|
||||
publisher.info("face_cluster", "Face clustering started")
|
||||
|
||||
if not os.path.exists(face_json_path):
|
||||
print("Face JSON not found.")
|
||||
write_empty_output("no_face_json", uuid, OUTPUT_JSON_PATH)
|
||||
publisher.complete("face_cluster", "No face.json found")
|
||||
return
|
||||
|
||||
with open(face_json_path) as f:
|
||||
face_data = json.load(f)
|
||||
|
||||
frames_list = face_data.get("frames", [])
|
||||
if not frames_list:
|
||||
print("No frames in JSON (no faces).")
|
||||
write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH)
|
||||
publisher.complete("face_cluster", "No faces to cluster")
|
||||
return
|
||||
|
||||
fps_value = face_data.get("fps", 23.98)
|
||||
|
||||
points = load_qdrant_faces(uuid, publisher)
|
||||
if not points:
|
||||
print("No embeddings found in Qdrant.")
|
||||
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
|
||||
publisher.complete("face_cluster", "No embeddings in Qdrant")
|
||||
return
|
||||
|
||||
publisher.progress("face_cluster", 10, 100, f"Loaded {len(points)} Qdrant points")
|
||||
|
||||
# Count unique traces before filtering
|
||||
unique_trace_ids = set()
|
||||
for p in points:
|
||||
tid = p.get("payload", {}).get("trace_id")
|
||||
if tid is not None and tid >= 0:
|
||||
unique_trace_ids.add(tid)
|
||||
|
||||
# Keep all traces for maximum recall. Noise is handled by the
|
||||
# confidence_threshold filter in cluster_by_trace (0.5), not by
|
||||
# dropping short traces — short appearances (walk-ons, passers-by)
|
||||
# are real people and must stay in the dedup pool, even for
|
||||
# large files with many faces.
|
||||
min_faces = 1
|
||||
print(
|
||||
f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces}"
|
||||
)
|
||||
|
||||
trace_embeddings, traces = cluster_by_trace(
|
||||
points, min_faces_per_trace=min_faces, confidence_threshold=0.5
|
||||
)
|
||||
|
||||
if not trace_embeddings:
|
||||
print("No valid traces found.")
|
||||
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
|
||||
publisher.complete("face_cluster", "No valid traces")
|
||||
return
|
||||
|
||||
publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces")
|
||||
|
||||
# Select clustering method
|
||||
threshold = args.threshold
|
||||
method = args.method
|
||||
if method == "leader":
|
||||
trace_to_person, trace_similarities = seed_leader_cluster(
|
||||
trace_embeddings, threshold=threshold
|
||||
)
|
||||
else:
|
||||
trace_to_person, trace_similarities = single_stage_clustering(
|
||||
trace_embeddings, threshold=threshold
|
||||
)
|
||||
if not trace_to_person:
|
||||
print("Clustering produced no results.")
|
||||
write_empty_output("no_embeddings", uuid, OUTPUT_JSON_PATH)
|
||||
publisher.complete("face_cluster", "Clustering empty")
|
||||
return
|
||||
|
||||
n_persons = len(set(trace_to_person.values()))
|
||||
print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)")
|
||||
publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons")
|
||||
|
||||
# Load face_traced.json to get trace_id for each face
|
||||
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
|
||||
traced_frames = {}
|
||||
if os.path.exists(traced_path):
|
||||
try:
|
||||
with open(traced_path) as f:
|
||||
traced_data = json.load(f)
|
||||
frames_raw = traced_data.get("frames", {})
|
||||
# Handle both dict and list formats
|
||||
if isinstance(frames_raw, list):
|
||||
# Convert list to dict for backward compatibility
|
||||
for frame_obj in frames_raw:
|
||||
frame_num = frame_obj.get("frame")
|
||||
if frame_num is not None:
|
||||
traced_frames[str(frame_num)] = frame_obj
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)")
|
||||
elif isinstance(frames_raw, dict):
|
||||
traced_frames = frames_raw
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)")
|
||||
else:
|
||||
print(f" Warning: Unexpected frames format: {type(frames_raw)}")
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
matched_count = 0
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
frame_num = frame_obj.get("frame", frame_idx)
|
||||
# Get traced faces for this frame
|
||||
traced_frame = traced_frames.get(str(frame_num), {})
|
||||
traced_faces = traced_frame.get("faces", [])
|
||||
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
# Get trace_id from face_traced.json
|
||||
trace_id = None
|
||||
if face_idx < len(traced_faces):
|
||||
trace_id = traced_faces[face_idx].get("trace_id")
|
||||
|
||||
if trace_id is not None and trace_id in trace_to_person:
|
||||
person_label = trace_to_person[trace_id]
|
||||
face["person_id"] = f"Person_{person_label}"
|
||||
face["trace_id"] = trace_id
|
||||
matched_count += 1
|
||||
|
||||
print(f" Assigned person_id to {matched_count} faces")
|
||||
|
||||
if matched_count == 0:
|
||||
print("No faces matched to any trace - check Qdrant data integrity")
|
||||
publisher.progress("face_cluster", 100, 100, "No trace matches")
|
||||
write_empty_output("no_faces", uuid, OUTPUT_JSON_PATH)
|
||||
return
|
||||
|
||||
publisher.progress("face_cluster", 70, 100, f"Matched {matched_count} faces")
|
||||
|
||||
person_face_count = defaultdict(int)
|
||||
person_best_face = {}
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
person_id = face.get("person_id")
|
||||
if not person_id:
|
||||
continue
|
||||
person_face_count[person_id] += 1
|
||||
confidence = face.get("confidence", 0.9)
|
||||
if (
|
||||
person_id not in person_best_face
|
||||
or confidence > person_best_face[person_id]["confidence"]
|
||||
):
|
||||
person_best_face[person_id] = {
|
||||
"face_id": f"face_{frame_idx}_{face_idx}",
|
||||
"confidence": confidence,
|
||||
"frame": frame_obj.get("frame", frame_idx),
|
||||
"bbox": {
|
||||
"x": face.get("x"),
|
||||
"y": face.get("y"),
|
||||
"width": face.get("width"),
|
||||
"height": face.get("height"),
|
||||
},
|
||||
}
|
||||
|
||||
# Build per-person similarity stats from trace_similarities
|
||||
person_sims = defaultdict(list)
|
||||
sim_threshold_value = 1.0 - threshold # similarity threshold
|
||||
for tid, person_label in trace_to_person.items():
|
||||
sim = trace_similarities.get(tid, 0.0)
|
||||
person_sims[person_label].append(sim)
|
||||
|
||||
person_labels_sorted = sorted(
|
||||
person_face_count.keys(), key=lambda p: -person_face_count[p]
|
||||
)
|
||||
clusters = []
|
||||
for person_id in person_labels_sorted:
|
||||
# Extract person number from "Person_N" to get the integer label
|
||||
person_label = None
|
||||
try:
|
||||
person_label = int(person_id.split("_")[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
sims = person_sims.get(person_label, []) if person_label is not None else []
|
||||
similarity_info = None
|
||||
if sims:
|
||||
similarity_info = {
|
||||
"min": round(float(min(sims)), 4),
|
||||
"avg": round(float(sum(sims) / len(sims)), 4),
|
||||
"threshold": round(sim_threshold_value, 4),
|
||||
}
|
||||
|
||||
cluster_entry = {
|
||||
"cluster_id": person_id,
|
||||
"face_count": person_face_count[person_id],
|
||||
"representative_face": person_best_face.get(person_id),
|
||||
}
|
||||
if similarity_info:
|
||||
cluster_entry["similarity"] = similarity_info
|
||||
clusters.append(cluster_entry)
|
||||
|
||||
output_frames = []
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
timestamp = frame_obj.get(
|
||||
"timestamp", frame_obj.get("frame", 0) / fps_value if fps_value > 0 else 0
|
||||
)
|
||||
output_faces = []
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
person_id = face.get("person_id")
|
||||
if person_id:
|
||||
output_faces.append(
|
||||
{
|
||||
"face_id": f"face_{frame_idx}_{face_idx}",
|
||||
"cluster_id": person_id,
|
||||
"trace_id": face.get("trace_id"),
|
||||
"confidence": face.get("confidence", 0.9),
|
||||
}
|
||||
)
|
||||
if output_faces:
|
||||
output_frames.append(
|
||||
{
|
||||
"frame": frame_obj.get("frame", frame_idx),
|
||||
"timestamp": timestamp,
|
||||
"faces": output_faces,
|
||||
}
|
||||
)
|
||||
|
||||
output_data = {
|
||||
"status": "has_faces",
|
||||
"file_uuid": UUID,
|
||||
"clusters": clusters,
|
||||
"frames": output_frames,
|
||||
}
|
||||
|
||||
speaker_mapping = auto_bind_speakers(
|
||||
output_frames, os.path.join(output_dir, f"{uuid}.asrx.json")
|
||||
)
|
||||
if speaker_mapping:
|
||||
output_data["speaker_person_mapping"] = speaker_mapping
|
||||
|
||||
with open(OUTPUT_JSON_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(round_json_numbers(output_data), f, indent=2, ensure_ascii=False)
|
||||
print(f"Saved clustered data to {OUTPUT_JSON_PATH}")
|
||||
publisher.progress("face_cluster", 90, 100, f"{len(clusters)} clusters")
|
||||
|
||||
publisher.complete("face_cluster", f"{len(clusters)} clusters")
|
||||
if speaker_mapping:
|
||||
publisher.info(
|
||||
"face_cluster",
|
||||
f"Speaker mapping: {len(speaker_mapping)} speakers",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/accusys/momentry_core/tools/script/ocr/ocr_processor.py
|
||||
+1
@@ -0,0 +1 @@
|
||||
/Users/accusys/momentry_core/tools/script/face/store_traced_faces.py
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/accusys/momentry_core/scripts/swift_processors
|
||||
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