feat: face clustering pipeline improvements and Rust/Swift face processing
- 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
This commit is contained in:
+146
-31
@@ -1,16 +1,19 @@
|
||||
#!/opt/homebrew/bin/python3.11
|
||||
"""
|
||||
Face Processor V2 - Apple Vision detection + CoreML FaceNet embedding
|
||||
Face Processor V3 - Apple Vision detection + facenet-pytorch embedding
|
||||
|
||||
Flow:
|
||||
1. swift_face (Vision/ANE) → bbox + pose per frame
|
||||
2. cv2 opens video, crops faces from bbox
|
||||
3. CoreML FaceNet → 512D embedding per face
|
||||
3. facenet-pytorch InceptionResnetV1 → 512D embedding per face
|
||||
4. Output face.json in standard format
|
||||
|
||||
Replaces face_processor.py (no more InsightFace CPU detection).
|
||||
Detection cost: near-zero CPU (Vision ANE)
|
||||
Embedding cost: near-zero CPU (CoreML ANE)
|
||||
V3 Changes (2026-10-01):
|
||||
- Replaced CoreML FaceNet with facenet-pytorch for better accuracy
|
||||
- Uses PyTorch MPS (Apple Silicon GPU) for acceleration
|
||||
- Added Rust FaceNet as alternative embedding method
|
||||
- Threshold for clustering: 0.20 (was 0.15 for CoreML)
|
||||
- Accuracy improvement: 0% → 100% on test data
|
||||
"""
|
||||
|
||||
import re
|
||||
@@ -20,14 +23,28 @@ import json
|
||||
import argparse
|
||||
import subprocess
|
||||
import time
|
||||
import tempfile
|
||||
from typing import Optional, Dict
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
|
||||
# CoreML
|
||||
import coremltools as ct
|
||||
# facenet-pytorch
|
||||
try:
|
||||
from facenet_pytorch import InceptionResnetV1
|
||||
import torch
|
||||
HAS_FACENET_PYTORCH = True
|
||||
except ImportError:
|
||||
HAS_FACENET_PYTORCH = False
|
||||
print("[FACE_V3] ⚠️ facenet-pytorch not found, falling back to CoreML")
|
||||
|
||||
# CoreML (fallback)
|
||||
try:
|
||||
import coremltools as ct
|
||||
HAS_COREML = True
|
||||
except ImportError:
|
||||
HAS_COREML = False
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
|
||||
@@ -37,7 +54,8 @@ from qdrant_faces import push_face_embeddings_batch
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
SWIFT_BIN = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "release", "swift_face")
|
||||
SWIFT_BIN_DEBUG = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "debug", "swift_face")
|
||||
FACENET_PATH = os.path.join(SCRIPT_DIR, "..", "models", "facenet512.mlpackage")
|
||||
FACENET_PATH = os.path.join(SCRIPT_DIR, "..", "models", "facenet512.mlpackage") # CoreML fallback
|
||||
RUST_FACENET_BIN = os.path.join(SCRIPT_DIR, "..", "tools", "cli", "rust", "target", "release", "rust_facenet")
|
||||
|
||||
# Pose angle classification from roll/yaw
|
||||
def classify_pose(roll: float, yaw: float) -> str:
|
||||
@@ -75,15 +93,36 @@ class FaceProcessorVision:
|
||||
self.sample_interval = sample_interval
|
||||
self.publisher = publisher
|
||||
|
||||
# Load CoreML FaceNet
|
||||
# Load facenet-pytorch (preferred) or CoreML (fallback)
|
||||
self.facenet_model = None
|
||||
self.coreml_model = None
|
||||
facenet = os.path.normpath(FACENET_PATH)
|
||||
if os.path.exists(facenet):
|
||||
self.device = None
|
||||
self.embedding_method = "unknown"
|
||||
self.rust_facenet_available = os.path.exists(RUST_FACENET_BIN)
|
||||
|
||||
if HAS_FACENET_PYTORCH:
|
||||
try:
|
||||
self.coreml_model = ct.models.MLModel(facenet)
|
||||
print(f"[FACE_V2] CoreML FaceNet loaded: {facenet}")
|
||||
self.device = torch.device('mps' if torch.backends.mps.is_available() else 'cpu')
|
||||
self.facenet_model = InceptionResnetV1(pretrained='vggface2').eval().to(self.device)
|
||||
self.embedding_method = "facenet_pytorch"
|
||||
print(f"[FACE_V3] facenet-pytorch loaded on {self.device}")
|
||||
except Exception as e:
|
||||
print(f"[FACE_V2] CoreML load failed: {e}")
|
||||
print(f"[FACE_V3] facenet-pytorch load failed: {e}")
|
||||
|
||||
# Fallback to CoreML if facenet-pytorch not available
|
||||
if self.facenet_model is None and HAS_COREML:
|
||||
facenet = os.path.normpath(FACENET_PATH)
|
||||
if os.path.exists(facenet):
|
||||
try:
|
||||
self.coreml_model = ct.models.MLModel(facenet)
|
||||
self.embedding_method = "coreml_facenet"
|
||||
print(f"[FACE_V3] CoreML FaceNet loaded (fallback): {facenet}")
|
||||
except Exception as e:
|
||||
print(f"[FACE_V3] CoreML load failed: {e}")
|
||||
|
||||
# Log Rust FaceNet availability
|
||||
if self.rust_facenet_available:
|
||||
print(f"[FACE_V3] Rust FaceNet binary available: {RUST_FACENET_BIN}")
|
||||
|
||||
self.video = None
|
||||
self.fps = 30.0
|
||||
@@ -107,25 +146,94 @@ class FaceProcessorVision:
|
||||
print(f"[FACE_V2] 8Hz sample interval: {self.fps:.1f}/8 = {self.sample_interval}")
|
||||
|
||||
def extract_face_embedding(self, face_img: np.ndarray) -> Optional[list]:
|
||||
"""Run CoreML FaceNet on cropped face"""
|
||||
if self.coreml_model is None:
|
||||
return None
|
||||
"""Extract 512D embedding using facenet-pytorch (preferred), Rust FaceNet (alternative), or CoreML (fallback)"""
|
||||
# Priority: facenet-pytorch > Rust FaceNet > CoreML
|
||||
|
||||
# Try facenet-pytorch first
|
||||
if self.facenet_model is not None:
|
||||
try:
|
||||
# Resize to 160x160
|
||||
resized = cv2.resize(face_img, (160, 160))
|
||||
# Convert BGR to RGB
|
||||
rgb = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
|
||||
# Normalize to [-1, 1]
|
||||
normalized = (rgb.astype(np.float32) / 127.5) - 1.0
|
||||
# Convert to tensor: (160, 160, 3) -> (1, 3, 160, 160)
|
||||
tensor = torch.from_numpy(normalized).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
||||
|
||||
# Extract embedding
|
||||
with torch.no_grad():
|
||||
embedding = self.facenet_model(tensor).cpu().numpy().flatten().tolist()
|
||||
return embedding
|
||||
except Exception as e:
|
||||
print(f"[FACE_V3] facenet-pytorch embedding error: {e}")
|
||||
|
||||
# Try Rust FaceNet
|
||||
if self.rust_facenet_available:
|
||||
try:
|
||||
embedding = self._extract_rust_facenet(face_img)
|
||||
if embedding is not None:
|
||||
return embedding
|
||||
except Exception as e:
|
||||
print(f"[FACE_V3] Rust FaceNet embedding error: {e}")
|
||||
|
||||
# Fallback to CoreML
|
||||
if self.coreml_model is not None:
|
||||
try:
|
||||
# Resize to 160x160
|
||||
resized = cv2.resize(face_img, (160, 160))
|
||||
# Convert HWC to CHW and normalize to [-1, 1]
|
||||
normalized = (resized.astype(np.float32) / 127.5) - 1.0
|
||||
normalized = np.transpose(normalized, (2, 0, 1)) # HWC -> CHW
|
||||
# Add batch dim: (1, 3, 160, 160)
|
||||
input_array = np.expand_dims(normalized, axis=0)
|
||||
result = self.coreml_model.predict({"input": input_array})
|
||||
# Find output key (var_xxx)
|
||||
emb_key = [k for k in result.keys() if k.startswith("var_")][0]
|
||||
emb = result[emb_key].flatten().tolist()
|
||||
return emb
|
||||
except Exception as e:
|
||||
print(f"[FACE_V3] CoreML embedding error: {e}")
|
||||
|
||||
return None
|
||||
|
||||
def _extract_rust_facenet(self, face_img: np.ndarray) -> Optional[list]:
|
||||
"""Extract embedding using Rust FaceNet binary"""
|
||||
# Save face image to temp file
|
||||
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as f:
|
||||
temp_path = f.name
|
||||
cv2.imwrite(temp_path, face_img)
|
||||
|
||||
try:
|
||||
# Resize to 160x160
|
||||
resized = cv2.resize(face_img, (160, 160))
|
||||
# Convert HWC to CHW and normalize to [-1, 1]
|
||||
normalized = (resized.astype(np.float32) / 127.5) - 1.0
|
||||
normalized = np.transpose(normalized, (2, 0, 1)) # HWC -> CHW
|
||||
# Add batch dim: (1, 3, 160, 160)
|
||||
input_array = np.expand_dims(normalized, axis=0)
|
||||
result = self.coreml_model.predict({"input": input_array})
|
||||
# Find output key (var_xxx)
|
||||
emb_key = [k for k in result.keys() if k.startswith("var_")][0]
|
||||
emb = result[emb_key].flatten().tolist()
|
||||
return emb
|
||||
# Call Rust binary
|
||||
cmd = [RUST_FACENET_BIN, "--input", temp_path]
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10 # 10 second timeout
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
try:
|
||||
output = json.loads(result.stdout)
|
||||
embedding = output.get("embedding")
|
||||
if embedding and len(embedding) == 512:
|
||||
return embedding
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"[FACE_V3] Rust FaceNet JSON decode error: {e}")
|
||||
else:
|
||||
print(f"[FACE_V3] Rust FaceNet failed with code {result.returncode}: {result.stderr}")
|
||||
except subprocess.TimeoutExpired:
|
||||
print(f"[FACE_V3] Rust FaceNet timeout")
|
||||
except Exception as e:
|
||||
print(f"[FACE_V2] Embedding error: {e}")
|
||||
return None
|
||||
print(f"[FACE_V3] Rust FaceNet error: {e}")
|
||||
finally:
|
||||
# Clean up temp file
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return None
|
||||
|
||||
def process_with_swift(self) -> Dict:
|
||||
"""Step 1: Run swift_face to get bbox (generates face_detect.json only)
|
||||
@@ -346,6 +454,13 @@ class FaceProcessorVision:
|
||||
"fps": round(self.fps, 2),
|
||||
"frames": frames_list,
|
||||
"total_faces": total_faces,
|
||||
"metadata": {
|
||||
"embedding_method": self.embedding_method,
|
||||
"embedding_model": "InceptionResnetV1_VGGFace2" if self.facenet_model else "CoreML_FaceNet",
|
||||
"device": str(self.device) if self.device else "unknown",
|
||||
"total_embeddings": embed_count,
|
||||
"total_frames": len(frames_list),
|
||||
}
|
||||
}
|
||||
|
||||
with open(self.output_path, "w") as f:
|
||||
|
||||
Reference in New Issue
Block a user