#!/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.35 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.35) -> 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.35) -> 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()