#!/opt/homebrew/bin/python3.11 """ Face Clustering Threshold Sweep Experiment Runs seed-leader and agglomerative clustering across a range of cosine distance thresholds for a given file_uuid. Reports person count per threshold and (optionally) evaluation metrics against ground truth. Usage: python3 face_cluster_threshold_sweep.py --uuid python3 face_cluster_threshold_sweep.py --uuid --method leader --thresholds 0.25,0.30,0.35,0.40 python3 face_cluster_threshold_sweep.py --uuid --gt-file gt.json """ import argparse import json import os import sys import numpy as np 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 QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333") QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200") DEFAULT_THRESHOLDS = [0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60] def load_qdrant_trace_centroids(file_uuid: str) -> dict: """Load all face points from Qdrant, group by trace_id, compute weighted avg centroids.""" import requests headers = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {} all_points = [] offset = None while True: body = { "limit": 10000, "with_payload": True, "with_vector": True, "filter": { "must": [{"key": "file_uuid", "match": {"value": file_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 print(f"Loaded {len(all_points)} face points from Qdrant") # Group by trace_id traces = defaultdict(list) for point in all_points: payload = point.get("payload", {}) trace_id = payload.get("trace_id") confidence = payload.get("confidence", 0) if trace_id is not None and trace_id >= 0 and confidence >= 0.5: traces[trace_id].append(point) print(f"Found {len(traces)} unique traces (confidence >= 0.5)") # Compute weighted avg embedding per trace trace_embeddings = {} for trace_id, trace_points in traces.items(): 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), } return trace_embeddings def seed_leader_cluster(trace_embeddings: dict, threshold: float) -> dict: """Seed-leader clustering with incremental mean centroids.""" if not trace_embeddings: return {} trace_ids = sorted(trace_embeddings.keys()) sim_threshold = 1.0 - threshold persons = [] for trace_id in trace_ids: centroid = trace_embeddings[trace_id]["embedding"] if not persons: persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]}) continue best_sim = -1.0 best_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_idx = idx if best_sim >= sim_threshold: persons[best_idx]["member_trace_ids"].append(trace_id) member_embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in persons[best_idx]["member_trace_ids"]]) persons[best_idx]["centroid"] = np.mean(member_embeddings, axis=0) else: persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]}) trace_to_person = {} for label, person in enumerate(persons): for tid in person["member_trace_ids"]: trace_to_person[tid] = label return trace_to_person def agglomerative_cluster(trace_embeddings: dict, threshold: float) -> dict: """Agglomerative clustering (same as current production).""" if not trace_embeddings: return {} trace_ids = sorted(trace_embeddings.keys()) embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids]) clustering = AgglomerativeClustering( n_clusters=None, distance_threshold=threshold, metric="cosine", linkage="average" ) labels = clustering.fit_predict(embeddings) trace_to_person = {} for i, trace_id in enumerate(trace_ids): trace_to_person[trace_id] = labels[i] return trace_to_person def evaluate_pairwise(trace_to_person: dict, gt_trace_to_person: dict) -> dict: """Compute pairwise precision/recall/F1 against ground truth.""" if not trace_to_person or not gt_trace_to_person: return {"precision": 0, "recall": 0, "f1": 0} # Get all pairs that should be in same cluster (GT) and predicted same cluster all_trace_ids = sorted(set(trace_to_person.keys()) | set(gt_trace_to_person.keys())) n = len(all_trace_ids) tp = 0 # true positive: same in GT, same in predicted fp = 0 # false positive: different in GT, same in predicted fn = 0 # false negative: same in GT, different in predicted tn = 0 # true negative: different in GT, different in predicted for i in range(n): for j in range(i + 1, n): tid_i, tid_j = all_trace_ids[i], all_trace_ids[j] gt_same = gt_trace_to_person.get(tid_i) == gt_trace_to_person.get(tid_j) pred_same = trace_to_person.get(tid_i) == trace_to_person.get(tid_j) if gt_same and pred_same: tp += 1 elif gt_same and not pred_same: fn += 1 elif not gt_same and pred_same: fp += 1 else: tn += 1 precision = tp / (tp + fp) if (tp + fp) > 0 else 0 recall = tp / (tp + fn) if (tp + fn) > 0 else 0 f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 return { "precision": round(precision, 4), "recall": round(recall, 4), "f1": round(f1, 4), "tp": tp, "fp": fp, "fn": fn, "tn": tn } def main(): parser = argparse.ArgumentParser(description="Face Clustering Threshold Sweep") parser.add_argument("--uuid", required=True, help="File UUID to cluster") parser.add_argument("--method", choices=["leader", "agglomerative", "both"], default="both", help="Which method(s) to sweep") parser.add_argument("--thresholds", type=str, default=None, help="Comma-separated thresholds (default: 0.20..0.60 step 0.05)") parser.add_argument("--gt-file", type=str, default=None, help="JSON file with ground truth: {trace_id: person_label, ...}") args = parser.parse_args() file_uuid = args.uuid thresholds = [float(t) for t in args.thresholds.split(",")] if args.thresholds else DEFAULT_THRESHOLDS methods = ["leader", "agglomerative"] if args.method == "both" else [args.method] # Load GT if provided gt_trace_to_person = {} if args.gt_file and os.path.exists(args.gt_file): with open(args.gt_file) as f: gt_data = json.load(f) gt_trace_to_person = {int(k): v for k, v in gt_data.items()} print(f"Loaded ground truth for {len(gt_trace_to_person)} traces") # Load trace centroids from Qdrant print(f"Loading trace centroids for {file_uuid}...") trace_embeddings = load_qdrant_trace_centroids(file_uuid) n_traces = len(trace_embeddings) if n_traces == 0: print("No traces found. Exiting.") return print(f"\nSweeping {len(methods)} method(s) × {len(thresholds)} threshold(s) = {len(methods)*len(thresholds)} runs\n") print("=" * 80) results = {} for method in methods: print(f"\n--- Method: {method} ---") print(f"{'Threshold':>10} | {'Persons':>7} | {'Clustered Traces':>16} | {'Singletons':>10} | {'Precision':>9} | {'Recall':>7} | {'F1':>5}") print("-" * 80) method_results = {} cluster_func = seed_leader_cluster if method == "leader" else agglomerative_cluster for threshold in thresholds: trace_to_person = cluster_func(trace_embeddings, threshold=threshold) n_persons = len(set(trace_to_person.values())) n_clustered = len(trace_to_person) # Count singletons (clusters with only 1 trace) person_counts = defaultdict(int) for pid in trace_to_person.values(): person_counts[pid] += 1 n_singletons = sum(1 for c in person_counts.values() if c == 1) # Evaluate against GT if available eval_str = "" eval_data = {} if gt_trace_to_person: eval_data = evaluate_pairwise(trace_to_person, gt_trace_to_person) eval_str = f" | {eval_data['precision']:>9} | {eval_data['recall']:>7} | {eval_data['f1']:>5}" print(f"{threshold:>10.2f} | {n_persons:>7} | {n_clustered:>16} | {n_singletons:>10}{eval_str}") method_results[threshold] = { "n_persons": n_persons, "n_clustered": n_clustered, "n_singletons": n_singletons, "trace_to_person": {str(k): v for k, v in trace_to_person.items()}, "evaluation": eval_data if eval_data else None, } results[method] = method_results # Save results output_file = f"/Users/accusys/momentry/output/{file_uuid}.cluster_sweep.json" with open(output_file, "w") as f: # Don't save full trace_to_person in output (too large) summary = {} for method, method_results in results.items(): summary[method] = {} for t, r in method_results.items(): summary[method][str(t)] = {k: v for k, v in r.items() if k != "trace_to_person"} json.dump({ "file_uuid": file_uuid, "n_traces": n_traces, "summary": summary, }, f, indent=2) print(f"\n{'=' * 80}") print(f"Results saved to {output_file}") # Pick best threshold if GT available if gt_trace_to_person: for method in methods: best_t = max(results[method].items(), key=lambda x: x[1].get("evaluation", {}).get("f1", 0)) print(f"\nBest for {method}: threshold={best_t[0]}, F1={best_t[1]['evaluation']['f1']}, persons={best_t[1]['n_persons']}") if __name__ == "__main__": main()