e0d04e242f
- Add Rust face processor module (detection, embedding, tracking, qdrant) - Add Facenet CoreML/ONNX conversion scripts and tests - Refactor swift_face into Sources/swift_face with ArgumentParser support - Update store_traced_faces to handle face.json correctly - Fix ASRX parsing and TKG bbox reading from Qdrant - Improve admin_config and trace_agent APIs - Add M4 workspace docs for face clustering, dedup, and Facenet validation - Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
139 lines
4.3 KiB
Python
139 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Test different clustering thresholds
|
|
"""
|
|
import os
|
|
import sys
|
|
import json
|
|
import cv2
|
|
import numpy as np
|
|
from collections import defaultdict
|
|
|
|
try:
|
|
from facenet_pytorch import InceptionResnetV1
|
|
import torch
|
|
except ImportError:
|
|
print("❌ facenet-pytorch or torch not found")
|
|
sys.exit(1)
|
|
|
|
def test_thresholds(video_path: str, face_json_path: str):
|
|
"""Test different thresholds"""
|
|
print(f"[TEST] Testing different thresholds")
|
|
|
|
# Load model
|
|
device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
|
|
model = InceptionResnetV1(pretrained='vggface2').eval().to(device)
|
|
|
|
# Load face.json
|
|
with open(face_json_path) as f:
|
|
face_data = json.load(f)
|
|
|
|
# Open video
|
|
cap = cv2.VideoCapture(video_path)
|
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
|
|
# Extract embeddings for trace_id
|
|
trace_embeddings = defaultdict(list)
|
|
|
|
for frame_data in face_data['frames']:
|
|
frame_idx = frame_data['frame']
|
|
faces = frame_data.get('faces', [])
|
|
|
|
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
continue
|
|
|
|
for face in faces:
|
|
trace_id = face.get('trace_id')
|
|
if trace_id is None:
|
|
continue
|
|
|
|
x, y, w, h = face['x'], face['y'], face['width'], face['height']
|
|
margin = 5
|
|
crop = frame[
|
|
max(0, y - margin) : y + h + margin,
|
|
max(0, x - margin) : x + w + margin
|
|
]
|
|
|
|
if crop.size == 0:
|
|
continue
|
|
|
|
crop_resized = cv2.resize(crop, (160, 160))
|
|
crop_rgb = cv2.cvtColor(crop_resized, cv2.COLOR_BGR2RGB)
|
|
crop_norm = (crop_rgb.astype(np.float32) / 127.5) - 1.0
|
|
crop_tensor = torch.from_numpy(crop_norm).permute(2, 0, 1).unsqueeze(0).to(device)
|
|
|
|
with torch.no_grad():
|
|
embedding = model(crop_tensor).cpu().numpy().flatten()
|
|
|
|
trace_embeddings[trace_id].append(embedding)
|
|
|
|
cap.release()
|
|
|
|
# Average embeddings per trace
|
|
trace_avg_emb = {}
|
|
for tid, embs in trace_embeddings.items():
|
|
if len(embs) > 0:
|
|
avg_emb = np.mean(embs, axis=0)
|
|
trace_avg_emb[tid] = avg_emb
|
|
|
|
trace_ids = sorted(trace_avg_emb.keys())
|
|
embeddings = np.array([trace_avg_emb[tid] for tid in trace_ids])
|
|
|
|
# Expected groups
|
|
group1 = {0, 1, 3, 5, 7, 9, 12, 14}
|
|
group2 = {2, 4, 6, 8, 10, 13, 15}
|
|
|
|
# Test different thresholds
|
|
from sklearn.cluster import AgglomerativeClustering
|
|
|
|
thresholds = [0.15, 0.18, 0.20, 0.22, 0.25]
|
|
|
|
print(f"\n[RESULTS] Testing thresholds:")
|
|
|
|
for threshold in thresholds:
|
|
clustering = AgglomerativeClustering(
|
|
n_clusters=None,
|
|
distance_threshold=threshold,
|
|
metric='cosine',
|
|
linkage='average'
|
|
)
|
|
|
|
labels = clustering.fit_predict(embeddings)
|
|
|
|
clusters = defaultdict(list)
|
|
for tid, label in zip(trace_ids, labels):
|
|
clusters[label].append(tid)
|
|
|
|
print(f"\n Threshold = {threshold}:")
|
|
|
|
# Check accuracy
|
|
correct_groups = 0
|
|
total_members = 0
|
|
|
|
for label, members in clusters.items():
|
|
member_set = set(members)
|
|
total_members += len(members)
|
|
|
|
if member_set == group1:
|
|
print(f" ✅ Cluster {label} = Group 1 ({len(members)} traces)")
|
|
correct_groups += 1
|
|
elif member_set == group2:
|
|
print(f" ✅ Cluster {label} = Group 2 ({len(members)} traces)")
|
|
correct_groups += 1
|
|
elif len(members) == 1 and 11 in members:
|
|
print(f" ✅ Cluster {label} = Group 3 (FS#11)")
|
|
correct_groups += 1
|
|
else:
|
|
print(f" ❌ Cluster {label} = {sorted(members)} ({len(members)} traces)")
|
|
|
|
print(f" Accuracy: {correct_groups}/3 groups correct")
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 3:
|
|
print("Usage: python test_thresholds.py <video_path> <face_json_path>")
|
|
sys.exit(1)
|
|
|
|
test_thresholds(sys.argv[1], sys.argv[2])
|