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
110 lines
3.5 KiB
Python
110 lines
3.5 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Extract facenet-pytorch embeddings from existing face.json
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import cv2
|
|
import numpy as np
|
|
from pathlib import Path
|
|
from collections import defaultdict
|
|
from datetime import datetime
|
|
|
|
try:
|
|
from facenet_pytorch import InceptionResnetV1
|
|
import torch
|
|
except ImportError:
|
|
print("❌ facenet-pytorch or torch not found")
|
|
sys.exit(1)
|
|
|
|
def extract_embeddings(video_path: str, face_json_path: str, output_path: str):
|
|
"""Extract embeddings using facenet-pytorch"""
|
|
print(f"[EXTRACT] Loading InceptionResnetV1...")
|
|
device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
|
|
print(f"[EXTRACT] Device: {device}")
|
|
|
|
model = InceptionResnetV1(pretrained='vggface2').eval().to(device)
|
|
print(f"[EXTRACT] Model loaded")
|
|
|
|
# Load face.json
|
|
with open(face_json_path) as f:
|
|
face_data = json.load(f)
|
|
|
|
print(f"[EXTRACT] Loaded {len(face_data['frames'])} frames")
|
|
|
|
# Open video
|
|
cap = cv2.VideoCapture(video_path)
|
|
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
print(f"[EXTRACT] Video: {total_frames} frames, {fps} fps")
|
|
|
|
# Extract embeddings
|
|
start_time = datetime.now()
|
|
embed_count = 0
|
|
|
|
for frame_data in face_data['frames']:
|
|
frame_idx = frame_data['frame']
|
|
faces = frame_data.get('faces', [])
|
|
|
|
# Read frame
|
|
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
|
|
|
|
# Extract embedding
|
|
try:
|
|
resized = cv2.resize(crop, (160, 160))
|
|
rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
|
|
normalized = (rgb.astype(np.float32) / 127.5) - 1.0
|
|
tensor = torch.from_numpy(normalized).permute(2, 0, 1).unsqueeze(0).to(device)
|
|
|
|
with torch.no_grad():
|
|
embedding = model(tensor).cpu().numpy().flatten().tolist()
|
|
|
|
face['embedding'] = embedding
|
|
embed_count += 1
|
|
except Exception as e:
|
|
print(f"[EXTRACT] Error at frame {frame_idx}, trace {trace_id}: {e}")
|
|
|
|
cap.release()
|
|
|
|
elapsed = (datetime.now() - start_time).total_seconds()
|
|
print(f"[EXTRACT] {embed_count} embeddings extracted in {elapsed:.1f}s")
|
|
|
|
# Update metadata
|
|
face_data['metadata']['embedding_method'] = 'facenet_pytorch'
|
|
face_data['metadata']['embedding_model'] = 'InceptionResnetV1_VGGFace2'
|
|
face_data['metadata']['device'] = str(device)
|
|
face_data['metadata']['total_embeddings'] = embed_count
|
|
|
|
# Save
|
|
with open(output_path, 'w') as f:
|
|
json.dump(face_data, f, indent=2)
|
|
|
|
print(f"[EXTRACT] ✅ Saved: {output_path}")
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 4:
|
|
print("Usage: python extract_facenet_embeddings.py <video_path> <face_json_path> <output_path>")
|
|
sys.exit(1)
|
|
|
|
extract_embeddings(sys.argv[1], sys.argv[2], sys.argv[3])
|