refactor: eliminate all CARGO_MANIFEST_DIR compile-time dependencies (A-4)

- Add src/core/path_utils.rs with runtime path resolution helpers
- Replace all env!("CARGO_MANIFEST_DIR") with runtime resolution
- Priority: env var -> current_exe sibling -> dev fallback

Changes:
- executor.rs: scripts_dir(), cli_dir() (4 locations)
- face.rs: swift_processor_path()
- tool_selector.rs: swift_binary_path()
- thumbnail/mod.rs: script_path()

Issue: CARGO_MANIFEST_DIR expands to build machine path at compile time,
       breaking on binary-only release hosts.

Solution: Resolve paths at runtime in this order:
1. Explicit environment variable (MOMENTRY_SCRIPTS_DIR, MOMENTRY_CLI_DIR)
2. Sibling of current_exe (same directory as running binary)
3. Relative path fallback (dev machine)

Verified: cargo check --lib passes
This commit is contained in:
Accusys
2026-10-04 13:44:40 +08:00
parent 3d363e6266
commit a3c3ed8dc1
850 changed files with 130339 additions and 91 deletions
+18 -5
View File
@@ -362,11 +362,24 @@ def get_fps_from_ffprobe(video_path):
"-show_entries", "stream=r_frame_rate",
"-of", "csv=p=0", video_path]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
fps_str = result.stdout.strip()
if "/" in fps_str:
num, den = fps_str.split("/")
return float(num) / float(den)
return float(fps_str)
# ffprobe 的 csv 輸出可能帶多餘欄位或重複行(如 "60000/1001," 或
# "60000/1001\n\n60000/1001"),需逐行取第一個可解析且 >0 的值。
for line in result.stdout.splitlines():
for token in line.split(","):
token = token.strip()
if not token:
continue
try:
if "/" in token:
num, den = token.split("/", 1)
fps = float(num) / float(den)
else:
fps = float(token)
except (ValueError, ZeroDivisionError):
continue
if fps > 0:
return fps
return None
except Exception:
return None
+677
View File
@@ -0,0 +1,677 @@
#!/opt/homebrew/bin/python3.11
"""
ASR Processor - faster-whisper small model (Production)
Version: 2.1
Model: small (int8 quantization, CPU)
Reason: small 模型在準確率和速度間取得最佳平衡
經實驗驗證,最少要使用 small 才可以較好的處理多語種及台灣腔國語
Configuration:
- Model: faster-whisper/small
- Device: CPU (MPS not supported by faster_whisper)
- Compute: int8
- Beam size: 5
- VAD filter: enabled (min_silence=500ms, speech_pad=200ms)
- Audio fallback: ffmpeg extraction for PyAV-incompatible streams (v2.1)
"""
import sys
import json
import os
import math
import time
import argparse
import signal
import subprocess
import tempfile
from faster_whisper import WhisperModel
PROCESSOR_VERSION = "2.2"
MODEL_SIZE = "large-v3" # Upgraded from small to large-v3 for better language detection
DEVICE = "cpu"
# Common languages to try when auto-detection fails
COMMON_LANGUAGES = ["en", "zh", "ja"] # English, Chinese (auto繁简), Japanese
def segment_confidence(segment) -> float:
"""Derive a 0-1 confidence from faster-whisper's avg_logprob.
faster-whisper segments do NOT expose a `confidence` attribute, so the old
getattr(segment, "confidence", 0.0) always returned 0. avg_logprob is the
average log-probability per token (negative); exp() maps it to (0, 1].
"""
logprob = getattr(segment, "avg_logprob", -0.1)
return min(1.0, math.exp(logprob))
def calculate_transcription_quality(segments, info) -> dict:
"""Calculate transcription quality metrics.
Returns:
dict with:
- avg_logprob: Average log probability (higher is better)
- avg_no_speech_prob: Average no_speech_prob (lower is better)
- segment_count: Number of segments
- quality_score: Combined quality score (higher is better)
"""
# Convert generator to list if needed
if not isinstance(segments, list):
segments = list(segments)
if not segments:
return {
"avg_logprob": -1.0,
"avg_no_speech_prob": 1.0,
"segment_count": 0,
"quality_score": 0.0,
}
total_logprob = sum(getattr(s, "avg_logprob", -0.5) for s in segments)
total_no_speech = sum(getattr(s, "no_speech_prob", 0.5) for s in segments)
avg_logprob = total_logprob / len(segments)
avg_no_speech_prob = total_no_speech / len(segments)
# Quality score: combination of metrics
# Higher logprob is better, lower no_speech_prob is better
quality_score = (
(1 + avg_logprob) * # Normalize logprob to positive
(1 - avg_no_speech_prob) * # Lower no_speech is better
min(len(segments) / 100, 1.0) # Prefer more segments (cap at 100)
)
return {
"avg_logprob": avg_logprob,
"avg_no_speech_prob": avg_no_speech_prob,
"segment_count": len(segments),
"quality_score": quality_score,
}
def transcribe_with_common_languages(model, video_path, publisher=None):
"""Transcribe video using common languages when auto-detection fails.
Strategy:
1. Try auto-detection first
2. If detected language is in COMMON_LANGUAGES, use it
3. If not, or quality is poor, try common languages
4. Return the best result
Args:
model: WhisperModel instance
video_path: Path to video or audio file
publisher: RedisPublisher for progress updates
Returns:
Tuple of (segments_list, info)
"""
# Step 1: Try auto-detection
msg = "[ASR] Trying auto language detection..."
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", "Trying auto language detection...")
segments_gen, info = transcribe_with_fallback(model, video_path, publisher, language=None)
segments = list(segments_gen) # Convert generator to list
detected_lang = info.language
quality = calculate_transcription_quality(segments, info)
msg = f"[ASR] Auto-detection: {detected_lang}, quality: {quality['quality_score']:.2f}"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Auto-detection: {detected_lang}, quality: {quality['quality_score']:.2f}")
# Step 2: Check if detected language is in common languages
if detected_lang in COMMON_LANGUAGES:
# Good detection, return it
msg = f"[ASR] Using auto-detected language: {detected_lang}"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Using auto-detected language: {detected_lang}")
return segments, info
# Step 3: If quality is good enough, accept auto-detection even if not common
if quality["quality_score"] > 0.5 and quality["segment_count"] > 10:
msg = f"[ASR] Auto-detected {detected_lang} has good quality, using it"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Auto-detected {detected_lang} has good quality, using it")
return segments, info
# Step 4: Try common languages
msg = "[ASR] Auto-detection poor, trying common languages..."
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", "Auto-detection poor, trying common languages...")
best_result = (segments, info)
best_quality = quality
for lang in COMMON_LANGUAGES:
if lang == detected_lang:
continue # Already tried
msg = f"[ASR] Trying language: {lang}"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Trying language: {lang}")
try:
seg_gen, inf = transcribe_with_fallback(model, video_path, publisher, language=lang)
seg = list(seg_gen) # Convert generator to list
q = calculate_transcription_quality(seg, inf)
msg = f"[ASR] Language {lang}: quality {q['quality_score']:.2f}"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Language {lang}: quality {q['quality_score']:.2f}")
# Compare quality
if q["quality_score"] > best_quality["quality_score"]:
best_quality = q
best_result = (seg, inf)
except Exception as e:
sys.stderr.write(f"ASR: Failed to transcribe with {lang}: {e}\n")
sys.stderr.flush()
continue
# Step 5: Return best result
final_lang = best_result[1].language
msg = f"[ASR] Best language: {final_lang}, quality: {best_quality['quality_score']:.2f}"
sys.stderr.write(msg + "\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Best language: {final_lang}, quality: {best_quality['quality_score']:.2f}")
return best_result
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
COMPUTE_TYPE = "int8"
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
def signal_handler(signum, frame):
print(f"ASR: Received signal {signum}, exiting...")
sys.exit(1)
def has_audio_stream(video_path):
"""Check if video file has audio stream using ffprobe."""
try:
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
return bool(result.stdout.strip())
except subprocess.CalledProcessError:
return False
except FileNotFoundError:
print("WARNING: ffprobe not found, assuming audio exists")
return True
def extract_audio_with_ffmpeg(video_path):
"""Extract audio from video to WAV using ffmpeg.
Returns path to temporary WAV file. Caller is responsible for cleanup.
"""
wav_path = tempfile.mktemp(suffix=".wav", prefix="asr_audio_")
cmd = [
"ffmpeg",
"-y",
"-i", video_path,
"-vn",
"-acodec", "pcm_s16le",
"-ar", "16000",
"-ac", "1",
wav_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
sys.stderr.write(f"ASR: ffmpeg extraction failed: {result.stderr}\n")
sys.stderr.flush()
return None
return wav_path
def transcribe_with_fallback(model, video_path, publisher=None, language=None):
"""Transcribe video with fallback to ffmpeg-extracted WAV.
First tries direct transcription (PyAV). If PyAV fails to decode,
falls back to ffmpeg audio extraction then transcription.
Args:
model: WhisperModel instance
video_path: Path to video or audio file
publisher: RedisPublisher for progress updates
language: Force language (e.g., "ja", "en", None for auto-detect)
"""
# Try direct transcription first
try:
if publisher:
publisher.info("asr", "Direct transcription attempt...")
# Build transcription kwargs
transcribe_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
transcribe_kwargs["language"] = language
if publisher:
publisher.info("asr", f"Forcing language: {language}")
return model.transcribe(video_path, **transcribe_kwargs)
except Exception as e:
error_str = str(e)
# Check if it's a PyAV/av decoding error
is_pyav_error = any(
keyword in error_str.lower()
for keyword in ["av.error", "avcodec", "decode", "packet"]
)
if not is_pyav_error:
raise # Re-raise non-PyAV errors
if publisher:
publisher.info("asr", "PyAV decode failed, falling back to ffmpeg extraction...")
sys.stderr.write("ASR: PyAV decode error detected, falling back to ffmpeg extraction\n")
sys.stderr.flush()
wav_path = extract_audio_with_ffmpeg(video_path)
if wav_path is None:
raise RuntimeError("Failed to extract audio with ffmpeg")
try:
if publisher:
publisher.info("asr", "Transcribing extracted WAV audio...")
# Build transcription kwargs for fallback
fallback_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
fallback_kwargs["language"] = language
segments, info = model.transcribe(wav_path, **fallback_kwargs)
return segments, info
finally:
# Clean up temporary WAV file
try:
os.remove(wav_path)
except OSError:
pass
def get_fps_from_cut(cut_path):
"""從 CUT 資料獲取 FPS"""
if os.path.exists(cut_path):
try:
with open(cut_path) as f:
cut_data = json.load(f)
fps = cut_data.get("fps")
if fps and fps > 0:
return fps
except Exception as e:
print(f"[ASR] Failed to load CUT FPS: {e}", file=sys.stderr)
return None
def get_fps_from_ffprobe(video_path):
"""從影片獲取 FPS (ffprobe)"""
try:
cmd = ["ffprobe", "-v", "error",
"-select_streams", "v:0",
"-show_entries", "stream=r_frame_rate",
"-of", "csv=p=0", video_path]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
fps_str = result.stdout.strip()
if "/" in fps_str:
num, den = fps_str.split("/")
return float(num) / float(den)
return float(fps_str)
except Exception:
return None
def run_asr(video_path, output_path, uuid: str = "", fps: float = None, language: str = None, separate_vocals: bool = False, try_common_languages: bool = False):
# Set up signal handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
# Vocal separation (optional preprocessing)
if separate_vocals:
sys.stderr.write("[ASR] Separating vocals using demucs...\n")
sys.stderr.flush()
from preprocess_audio import preprocess_audio_for_asr
processed_audio = preprocess_audio_for_asr(video_path, separate=True)
if processed_audio:
video_path = processed_audio # Use separated vocals
sys.stderr.write(f"[ASR] Using separated vocals: {processed_audio}\n")
else:
sys.stderr.write("[ASR] Vocal separation failed, using original audio\n")
sys.stderr.flush()
# If try_common_languages is enabled and no language specified, use smart detection
if try_common_languages and not language:
sys.stderr.write("[ASR] Smart language detection enabled (common languages)\n")
sys.stderr.flush()
# FPS detection chain: CLI → CUT → ffprobe → FAIL
if fps is not None:
print(f"[ASR] Using CLI-provided FPS: {fps}", file=sys.stderr)
else:
# Use uuid to construct CUT path (output_path may have .tmp suffix from executor)
output_dir = os.path.dirname(output_path)
if uuid and output_dir:
cut_path_check = os.path.join(output_dir, f"{uuid}.cut.json")
else:
cut_path_check = output_path.replace(".asr.json", ".cut.json")
fps = get_fps_from_cut(cut_path_check)
if fps:
print(f"[ASR] FPS from CUT: {fps}", file=sys.stderr)
if fps is None:
fps = get_fps_from_ffprobe(video_path)
if fps:
print(f"[ASR] FPS from ffprobe: {fps}", file=sys.stderr)
if fps is None:
print("[ASR] ERROR: Cannot determine FPS (no CUT data, ffprobe failed). Aborting.", file=sys.stderr)
sys.exit(1)
publisher = RedisPublisher(uuid) if uuid else None
if publisher:
publisher.info("asr", "ASR_START")
# Check for audio stream
if not has_audio_stream(video_path):
if publisher:
publisher.info("asr", "No audio stream detected, skipping transcription")
output = {
"status": "no_audio_track",
"language": "",
"language_probability": 0.0,
"segments": []
}
with open(output_path, "w") as f:
json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
if publisher:
publisher.complete("asr", "0 segments (no audio)")
sys.stderr.write("ASR: No audio stream, skipping transcription\n")
sys.stderr.flush()
sys.exit(0)
# 嘗試以 CUT 場景分段處理(降低長片記憶體使用)
cut_scenes = []
cut_path = output_path.replace(".asr.json", ".cut.json")
if os.path.exists(cut_path):
try:
with open(cut_path) as f:
cut_data = json.load(f)
scenes = cut_data.get("scenes", [])
if scenes:
cut_scenes = [(s["start_time"], s["end_time"]) for s in scenes]
print(f"[ASR] Loaded {len(cut_scenes)} cut scenes for segmented transcription", file=sys.stderr)
except Exception as e:
print(f"[ASR] Failed to load cut scenes: {e}", file=sys.stderr)
if publisher:
publisher.info("asr", "Loading Whisper model...")
sys.stderr.write(f"[ASR] Loading Whisper model {MODEL_SIZE}...\n")
sys.stderr.flush()
model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8")
sys.stderr.write(f"[ASR] Model loaded\n")
sys.stderr.flush()
if publisher:
publisher.info("asr", f"Transcribing: {video_path}")
results = []
total_segments = 0
if cut_scenes:
# 分段處理:對每個場景萃取音訊並轉錄
sys.stderr.write(f"[ASR] Starting segmented transcription for {len(cut_scenes)} scenes\n")
sys.stderr.flush()
import subprocess
import tempfile
temp_dir = tempfile.mkdtemp(prefix="asr_cut_")
sys.stderr.write(f"[ASR] Temp dir: {temp_dir}\n")
sys.stderr.flush()
transcript_language = None
# 建立 scene lookup: 給定時間點,找是哪個 scene
import bisect
scene_starts = [s[0] for s in cut_scenes]
def find_scene_idx(t):
i = bisect.bisect_right(scene_starts, t) - 1
return max(0, i)
# 逐段處理,每段結果即時寫入 .asr.tmp
tmp_path = output_path + ".tmp"
err_path = output_path + ".err"
all_segments = []
# Resume: 若 executor 將 .tmp rename 成 .err,先救回
if not os.path.exists(tmp_path) and os.path.exists(err_path) and os.path.getsize(err_path) > 10:
try:
os.rename(err_path, tmp_path)
sys.stderr.write(f"[ASR] Recovered .err → .tmp for resume ({os.path.getsize(tmp_path)} bytes)\n")
sys.stderr.flush()
except Exception as e:
sys.stderr.write(f"[ASR] Failed to recover .err: {e}\n")
sys.stderr.flush()
# Resume: 若已有 .asr.tmp,載入已完成的 segments 並跳過已處理的 scenes
resume_from_scene = 0
if os.path.exists(tmp_path) and os.path.getsize(tmp_path) > 10:
try:
with open(tmp_path) as f:
existing = json.load(f)
all_segments = existing.get("segments", [])
if all_segments:
# 找出最後一個 segment 的 end_time,決定 resume 起點
last_end = max(s.get("end", 0) for s in all_segments)
# 找出最後完成的 scene_idx(場景 end_time > last_end)
for i, (st, et) in enumerate(cut_scenes):
if et > last_end:
resume_from_scene = i
break
else:
resume_from_scene = len(cut_scenes) # 全部完成
# 繼承 language
if existing.get("language"):
transcript_language = existing["language"]
sys.stderr.write(f"[ASR] Resume from scene {resume_from_scene}/{len(cut_scenes)} "
f"(last segment end={last_end:.1f}s, {len(all_segments)} existing segments)\n")
sys.stderr.flush()
except Exception as e:
sys.stderr.write(f"[ASR] Failed to load tmp for resume: {e}, starting fresh\n")
sys.stderr.flush()
all_segments = []
for idx, (start_t, end_t) in enumerate(cut_scenes):
if idx < resume_from_scene:
continue # 跳過已處理的 scenes
seg_wav = os.path.join(temp_dir, f"seg_{idx:04d}.wav")
sys.stderr.write(f"[ASR] Scene {idx}: {start_t:.1f}-{end_t:.1f}s\n")
sys.stderr.flush()
# 用 ffmpeg 萃取出該段音訊
t0 = time.time()
cmd = ["ffmpeg", "-y", "-v", "quiet", "-i", video_path,
"-ss", str(start_t), "-to", str(end_t),
"-ar", "16000", "-ac", "1", seg_wav]
subprocess.run(cmd, check=False, capture_output=True)
sys.stderr.write(f"[ASR] Scene {idx}: ffmpeg took {time.time()-t0:.1f}s\n")
sys.stderr.flush()
if not os.path.exists(seg_wav) or os.path.getsize(seg_wav) < 100:
sys.stderr.write(f"[ASR] Scene {idx}: empty audio, skipping\n")
sys.stderr.flush()
continue
try:
t1 = time.time()
# Build transcription kwargs for segmented processing
seg_transcribe_kwargs = {
"beam_size": 5,
"vad_filter": True,
"vad_parameters": dict(min_silence_duration_ms=500, speech_pad_ms=200),
}
# Add language if specified
if language:
seg_transcribe_kwargs["language"] = language
seg_result, seg_info = model.transcribe(seg_wav, **seg_transcribe_kwargs)
sys.stderr.write(f"[ASR] Scene {idx}: transcribe took {time.time()-t1:.1f}s, language={seg_info.language}\n")
sys.stderr.flush()
scene_segments = []
seg_language = seg_info.language if seg_info else transcript_language
for segment in seg_result:
seg_start = start_t + segment.start
seg_end = start_t + segment.end
scene_idx = find_scene_idx((seg_start + seg_end) / 2)
scene_segments.append({
"start_time": round(seg_start, 2),
"end_time": round(seg_end, 2),
"start_frame": int(round(seg_start * fps)),
"end_frame": int(round(seg_end * fps)),
"text": segment.text.strip(),
"scene_number": scene_idx + 1,
"language": seg_language,
"confidence": round(segment_confidence(segment), 2),
})
total_segments += 1
# 當前 scene 結果寫入 .asr.tmp
all_segments.extend(scene_segments)
with open(tmp_path, "w") as f:
json.dump(round_json_numbers({"language": transcript_language or "", "segments": all_segments}), f, ensure_ascii=False)
if total_segments % 100 == 0:
if publisher:
publisher.progress("asr", total_segments, 0, f"Segment {total_segments}")
except Exception as e:
print(f"[ASR] Segment {idx} failed: {e}", file=sys.stderr)
# 清理暫存 WAV
try: os.remove(seg_wav)
except: pass
try: os.rmdir(temp_dir)
except: pass
# Determine status for cut_scenes branch
if total_segments > 0:
status = "has_transcript"
else:
status = "silent_audio"
info_language = transcript_language or "unknown"
print(f"[ASR] Segmented transcription complete: {total_segments} segments, status={status}", file=sys.stderr)
# Write final output with status
with open(tmp_path, "w") as f:
json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
else:
# 無 CUT 資料,直接轉錄(原有流程)
if try_common_languages and not language:
# Use smart language detection
segments, info = transcribe_with_common_languages(model, video_path, publisher)
else:
segments, info = transcribe_with_fallback(model, video_path, publisher, language=language)
info_language = info.language
tmp_path = output_path + ".tmp"
all_segments = []
for segment in segments:
all_segments.append({
"start_time": round(segment.start, 2),
"end_time": round(segment.end, 2),
"start_frame": int(round(segment.start * fps)),
"end_frame": int(round(segment.end * fps)),
"text": segment.text.strip(),
"confidence": round(segment_confidence(segment), 2),
})
total_segments += 1
if total_segments % 100 == 0:
if publisher:
publisher.progress("asr", total_segments, 0, f"Segment {total_segments}")
# Determine status for direct transcription branch
if total_segments > 0:
status = "has_transcript"
else:
status = "silent_audio"
with open(tmp_path, "w") as f:
json.dump(round_json_numbers({"status": status, "language": info_language, "segments": all_segments}), f, ensure_ascii=False)
if publisher:
publisher.info("asr", f"ASR_LANGUAGE:{info_language}")
# rename .tmp → .json
os.rename(tmp_path, output_path)
if publisher:
publisher.complete("asr", f"{total_segments} segments")
sys.stderr.write(
f"ASR: Transcription complete, {total_segments} segments written to {output_path}\n"
)
sys.stderr.flush()
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="ASR Transcription")
parser.add_argument("video_path", help="Path to video file")
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", help="UUID for Redis progress", default="")
parser.add_argument("--fps", type=float, help="Override FPS (default: auto-detect)")
parser.add_argument("--language", "-l", help="Force language (e.g., ja for Japanese, en for English)", default=None)
parser.add_argument("--separate-vocals", action="store_true", help="Separate vocals using demucs before transcription")
parser.add_argument("--try-common-languages", action="store_true", help="Try common languages (en, zh, ja) if auto-detection fails or produces garbled output")
args = parser.parse_args()
run_asr(args.video_path, args.output_path, args.uuid, fps=args.fps, language=args.language, separate_vocals=args.separate_vocals, try_common_languages=args.try_common_languages)
+655
View File
@@ -0,0 +1,655 @@
#!/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.15
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.15) -> 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.15) -> 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()
+655
View File
@@ -0,0 +1,655 @@
#!/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.15) -> 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.15) -> 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()
+655
View File
@@ -0,0 +1,655 @@
#!/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.15) -> 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.15) -> 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()
+655
View File
@@ -0,0 +1,655 @@
#!/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.15) -> 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.15) -> 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()
+655
View File
@@ -0,0 +1,655 @@
#!/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.15) -> 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.15) -> 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()
+655
View File
@@ -0,0 +1,655 @@
#!/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.15) -> 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.15) -> 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()
+421
View File
@@ -0,0 +1,421 @@
#!/opt/homebrew/bin/python3.11
"""
Face Processor V2 - Apple Vision detection + CoreML FaceNet 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
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)
"""
import re
import sys
import os
import json
import argparse
import subprocess
import time
from typing import Optional, Dict
import cv2
import numpy as np
from pathlib import Path
# CoreML
import coremltools as ct
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"))
from redis_publisher import RedisPublisher
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")
# Pose angle classification from roll/yaw
def classify_pose(roll: float, yaw: float) -> str:
"""Convert roll/yaw to pose angle label"""
abs_yaw = abs(yaw)
abs_roll = abs(roll)
if abs_yaw < 15 and abs_roll < 15:
return "frontal"
elif abs_yaw > 30:
return "profile_right" if yaw > 0 else "profile_left"
else:
return "three_quarter"
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only).
Intentionally leaves Qdrant push payloads untouched (they use raw values).
"""
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
class FaceProcessorVision:
def __init__(self, video_path: str, output_path: str, uuid: str = "",
sample_interval: int = 3, publisher: RedisPublisher = None):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid
self.sample_interval = sample_interval
self.publisher = publisher
# Load CoreML FaceNet
self.coreml_model = None
facenet = os.path.normpath(FACENET_PATH)
if os.path.exists(facenet):
try:
self.coreml_model = ct.models.MLModel(facenet)
print(f"[FACE_V2] CoreML FaceNet loaded: {facenet}")
except Exception as e:
print(f"[FACE_V2] CoreML load failed: {e}")
self.video = None
self.fps = 30.0
self.total_frames = 0
self.width = 0
self.height = 0
def open_video(self):
self.video = cv2.VideoCapture(self.video_path)
if not self.video.isOpened():
raise RuntimeError(f"Cannot open: {self.video_path}")
self.fps = self.video.get(cv2.CAP_PROP_FPS)
self.total_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))
self.width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Calculate 8Hz sample interval based on FPS
self.sample_interval = max(1, round(self.fps / 8))
print(f"[FACE_V2] Video: {self.width}x{self.height}, {self.fps:.1f}fps, {self.total_frames}f")
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
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_V2] Embedding error: {e}")
return None
def process_with_swift(self) -> Dict:
"""Step 1: Run swift_face to get bbox (generates face_detect.json only)
Note: swift_face only does face detection.
Pose and appearance expansion happen later via separate processors:
- swift_pose_expansion reads face_traced.json (with trace_id)
- swift_appearance_expansion reads pose.json
"""
print(f"[FACE_V2] Step 1: Vision detection (face only)...")
# Build swift_face if missing or stale (source newer than binary)
src = os.path.join(SCRIPT_DIR, "swift_processors", "swift_face.swift")
def _stale(bin_path):
return os.path.exists(bin_path) and os.path.exists(src) and \
os.path.getmtime(src) > os.path.getmtime(bin_path)
if _stale(SWIFT_BIN):
print(f"[FACE_V2] swift_face release binary stale (source newer), removing to force rebuild...")
os.remove(SWIFT_BIN)
if _stale(SWIFT_BIN_DEBUG):
os.remove(SWIFT_BIN_DEBUG)
if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG):
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
print(f"[FACE_V2] Building swift_face in {build_dir}...")
subprocess.run(
["swift", "build", "-c", "release", "--product", "swift_face"],
cwd=build_dir, check=True
)
# Determine which binary to use
swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG
swift_face_out = self.output_path.replace(".json", "_detect.json")
cmd = [
swift_bin,
self.video_path,
swift_face_out,
"--sample-interval", str(self.sample_interval),
]
if self.uuid:
cmd.extend(["--uuid", self.uuid])
print(f"[FACE_V2] Running: {' '.join(cmd)}")
# Log face detection settings being passed to swift_face.
# Defaults mirror src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT (0.5 / 1).
min_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)")
min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)")
print(f"[FACE_V2] Settings passed to swift_face: FACE_MIN_CONFIDENCE={min_conf}, FACE_MIN_SIZE={min_size}")
t0 = time.time()
log_path = swift_face_out + ".log"
log_f = open(log_path, "w")
# Pass environment variables to swift_face subprocess (FACE_MIN_CONFIDENCE, FACE_MIN_SIZE)
proc = subprocess.Popen(cmd, stdout=log_f, stderr=subprocess.STDOUT, text=True, env=os.environ)
last_pct = -1
while proc.poll() is None:
time.sleep(10)
# Read latest log lines
try:
with open(log_path) as lf:
for line in lf:
line = line.strip()
m = re.search(r'(\d+)% complete', line)
if m:
pct = int(m.group(1))
if pct > last_pct:
last_pct = pct
if self.publisher:
self.publisher.progress("face", pct, 100, f"swift detect {pct}%")
except Exception:
pass
log_f.close()
if proc.returncode != 0:
stderr_out = proc.stderr.read() if proc.stderr else ""
if stderr_out:
print(stderr_out.strip(), file=sys.stderr)
raise RuntimeError(f"swift_face exited with code {proc.returncode}")
elapsed = time.time() - t0
print(f"[FACE_V2] Detection done in {elapsed:.1f}s")
with open(swift_face_out) as f:
face_data = json.load(f)
return face_data
def embed_and_save(self, detection_data: Dict):
"""Step 2: Crop faces + CoreML embedding + save face.json"""
print(f"[FACE_V2] Step 2: CoreML embedding...")
frames = detection_data.get("frames", [])
self.open_video()
face_data = {
"metadata": {
"video_path": os.path.abspath(self.video_path),
"fps": self.fps, "width": self.width, "height": self.height,
"sample_interval": self.sample_interval,
"detection_method": "apple_vision",
"embedding_method": "coreml_facenet",
"status": "in_progress",
"total_frames": self.total_frames,
},
"frames": {}
}
t0 = time.time()
embed_count = 0
total_face_count = 0
last_pct = -1
all_embeddings = [] # Collect embeddings for Qdrant push
for frame_info in frames:
frame_num = frame_info["frame"]
faces = []
for face_idx, face in enumerate(frame_info.get("faces", [])):
bb = face["bbox"]
x, y, w, h = bb["x"], bb["y"], bb["width"], bb["height"]
if w <= 10 or h <= 10:
continue # skip tiny faces
# Seek to frame and read
self.video.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
ret, frame = self.video.read()
if not ret:
continue
# Crop face
x1, y1 = max(0, x), max(0, y)
x2, y2 = min(self.width, x + w), min(self.height, y + h)
if x2 <= x1 or y2 <= y1:
continue
face_img = frame[y1:y2, x1:x2]
if face_img.size == 0:
continue
# CoreML embedding - push to Qdrant _faces collection
emb = self.extract_face_embedding(face_img)
if emb is not None:
embed_count += 1
# Collect for batch Qdrant push
# Use face_idx to distinguish multiple faces in same frame
all_embeddings.append({
"frame": frame_num,
"trace_id": face_idx, # Use face_idx as unique identifier within frame
"bbox": {"x": x, "y": y, "width": w, "height": h},
"confidence": face.get("confidence", 0.5),
"capture_quality": face.get("captureQuality", 0),
"embedding": emb,
})
# Pose classification
pose_info = face.get("pose", {})
pose_angle = classify_pose(
pose_info.get("roll", 0),
pose_info.get("yaw", 0)
)
faces.append({
"x": x, "y": y, "width": w, "height": h,
"confidence": face.get("confidence", 0.5),
"captureQuality": face.get("captureQuality", 0),
"pose_angle": {
"angle": pose_angle,
"roll": pose_info.get("roll", 0),
"yaw": pose_info.get("yaw", 0),
"pitch": pose_info.get("pitch", 0),
},
"lips": face.get("lips"),
"landmarks": face.get("landmarks"),
"attributes": None,
})
if faces:
face_data["frames"][str(frame_num)] = {
"frame_number": frame_num,
"time_seconds": frame_info.get("timestamp", frame_num / self.fps),
"time_formatted": f"{frame_num / self.fps:.1f}s",
"faces": faces,
}
if len(face_data["frames"]) % 100 == 0:
elapsed = time.time() - t0
print(f"[FACE_V2] {len(face_data['frames'])} frames, {elapsed:.0f}s")
if self.publisher:
pct = int(len(face_data["frames"]) * 100 / max(len(frames), 1))
if pct > last_pct:
last_pct = pct
self.publisher.progress("face", len(face_data["frames"]), len(frames),
"", 0, "faces")
self.video.release()
face_data["metadata"]["status"] = "completed"
# Convert dict frames to list for Rust FaceResult format
frames_list = []
total_faces = 0
for fnum_str, fdata in sorted(face_data["frames"].items(), key=lambda x: int(x[0])):
faces = fdata["faces"]
total_faces += len(faces)
frames_list.append({
"frame": int(fnum_str),
"timestamp": fdata["time_seconds"],
"faces": faces,
})
# Determine status based on face count
if total_faces > 0:
status = "has_faces"
else:
status = "no_faces"
output = {
"status": status,
"frame_count": len(frames_list),
"fps": round(self.fps, 2),
"frames": frames_list,
"total_faces": total_faces,
}
with open(self.output_path, "w") as f:
json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
# Push embeddings to Qdrant _faces collection
if all_embeddings:
try:
pushed = push_face_embeddings_batch(self.uuid, all_embeddings, self.publisher)
if pushed != len(all_embeddings):
raise RuntimeError(
f"Qdrant push incomplete: {pushed}/{len(all_embeddings)} embeddings pushed"
)
except Exception as e:
print(f"[FACE_V2] ERROR: Qdrant push failed: {e}", file=sys.stderr)
raise RuntimeError(f"Qdrant push failed: {e}")
elapsed = time.time() - t0
print(f"[FACE_V2] Done: {len(frames_list)} frames, {embed_count} embeddings, {elapsed:.0f}s")
def main():
parser = argparse.ArgumentParser(description="Apple Vision Face Processor V2")
parser.add_argument("video_path", help="Video file path")
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", default="")
parser.add_argument("--sample-interval", type=int, default=3)
parser.add_argument("--force", action="store_true")
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("face", "FACE_START")
if args.force and os.path.exists(args.output_path):
os.remove(args.output_path)
processor = FaceProcessorVision(
args.video_path, args.output_path,
args.uuid, args.sample_interval, publisher
)
# Open video to get FPS and calculate sample_interval
processor.open_video()
# Step 1: Vision detection (bbox + pose via ANE)
try:
detection = processor.process_with_swift()
except Exception as e:
if publisher:
publisher.error("face", f"Detection failed: {e}")
raise
# Step 2: CoreML embedding + save
try:
processor.embed_and_save(detection)
except Exception as e:
if publisher:
publisher.error("face", f"Embedding failed: {e}")
raise
if publisher:
publisher.complete("face", f"{len(detection.get('frames',[]))} frames")
# Clean up temp detection file
swift_out = args.output_path.replace(".json", "_detect.json")
if os.path.exists(swift_out):
os.remove(swift_out)
if __name__ == "__main__":
main()
+479
View File
@@ -0,0 +1,479 @@
#!/opt/homebrew/bin/python3.11
"""
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. facenet-pytorch InceptionResnetV1 → 512D embedding per face
4. Output face.json in standard format
V3 Changes (2026-10-01):
- Replaced CoreML FaceNet with facenet-pytorch for better accuracy
- Uses PyTorch MPS (Apple Silicon GPU) for acceleration
- Threshold for clustering: 0.20 (was 0.15 for CoreML)
- Accuracy improvement: 0% → 100% on test data
"""
import re
import sys
import os
import json
import argparse
import subprocess
import time
from typing import Optional, Dict
import cv2
import numpy as np
from pathlib import Path
# 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"))
from redis_publisher import RedisPublisher
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") # CoreML fallback
# Pose angle classification from roll/yaw
def classify_pose(roll: float, yaw: float) -> str:
"""Convert roll/yaw to pose angle label"""
abs_yaw = abs(yaw)
abs_roll = abs(roll)
if abs_yaw < 15 and abs_roll < 15:
return "frontal"
elif abs_yaw > 30:
return "profile_right" if yaw > 0 else "profile_left"
else:
return "three_quarter"
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only).
Intentionally leaves Qdrant push payloads untouched (they use raw values).
"""
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
class FaceProcessorVision:
def __init__(self, video_path: str, output_path: str, uuid: str = "",
sample_interval: int = 3, publisher: RedisPublisher = None):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid
self.sample_interval = sample_interval
self.publisher = publisher
# Load facenet-pytorch (preferred) or CoreML (fallback)
self.facenet_model = None
self.coreml_model = None
self.device = None
self.embedding_method = "unknown"
if HAS_FACENET_PYTORCH:
try:
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_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}")
self.video = None
self.fps = 30.0
self.total_frames = 0
self.width = 0
self.height = 0
def open_video(self):
self.video = cv2.VideoCapture(self.video_path)
if not self.video.isOpened():
raise RuntimeError(f"Cannot open: {self.video_path}")
self.fps = self.video.get(cv2.CAP_PROP_FPS)
self.total_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))
self.width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Calculate 8Hz sample interval based on FPS
self.sample_interval = max(1, round(self.fps / 8))
print(f"[FACE_V2] Video: {self.width}x{self.height}, {self.fps:.1f}fps, {self.total_frames}f")
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]:
"""Extract 512D embedding using facenet-pytorch (preferred) or CoreML (fallback)"""
# 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}")
# 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 process_with_swift(self) -> Dict:
"""Step 1: Run swift_face to get bbox (generates face_detect.json only)
Note: swift_face only does face detection.
Pose and appearance expansion happen later via separate processors:
- swift_pose_expansion reads face_traced.json (with trace_id)
- swift_appearance_expansion reads pose.json
"""
print(f"[FACE_V2] Step 1: Vision detection (face only)...")
# Build swift_face if missing or stale (source newer than binary)
src = os.path.join(SCRIPT_DIR, "swift_processors", "swift_face.swift")
def _stale(bin_path):
return os.path.exists(bin_path) and os.path.exists(src) and \
os.path.getmtime(src) > os.path.getmtime(bin_path)
if _stale(SWIFT_BIN):
print(f"[FACE_V2] swift_face release binary stale (source newer), removing to force rebuild...")
os.remove(SWIFT_BIN)
if _stale(SWIFT_BIN_DEBUG):
os.remove(SWIFT_BIN_DEBUG)
if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG):
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
print(f"[FACE_V2] Building swift_face in {build_dir}...")
subprocess.run(
["swift", "build", "-c", "release", "--product", "swift_face"],
cwd=build_dir, check=True
)
# Determine which binary to use
swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG
swift_face_out = self.output_path.replace(".json", "_detect.json")
cmd = [
swift_bin,
self.video_path,
swift_face_out,
"--sample-interval", str(self.sample_interval),
]
if self.uuid:
cmd.extend(["--uuid", self.uuid])
print(f"[FACE_V2] Running: {' '.join(cmd)}")
# Log face detection settings being passed to swift_face.
# Defaults mirror src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT (0.5 / 1).
min_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)")
min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)")
print(f"[FACE_V2] Settings passed to swift_face: FACE_MIN_CONFIDENCE={min_conf}, FACE_MIN_SIZE={min_size}")
t0 = time.time()
log_path = swift_face_out + ".log"
log_f = open(log_path, "w")
# Pass environment variables to swift_face subprocess (FACE_MIN_CONFIDENCE, FACE_MIN_SIZE)
proc = subprocess.Popen(cmd, stdout=log_f, stderr=subprocess.STDOUT, text=True, env=os.environ)
last_pct = -1
while proc.poll() is None:
time.sleep(10)
# Read latest log lines
try:
with open(log_path) as lf:
for line in lf:
line = line.strip()
m = re.search(r'(\d+)% complete', line)
if m:
pct = int(m.group(1))
if pct > last_pct:
last_pct = pct
if self.publisher:
self.publisher.progress("face", pct, 100, f"swift detect {pct}%")
except Exception:
pass
log_f.close()
if proc.returncode != 0:
stderr_out = proc.stderr.read() if proc.stderr else ""
if stderr_out:
print(stderr_out.strip(), file=sys.stderr)
raise RuntimeError(f"swift_face exited with code {proc.returncode}")
elapsed = time.time() - t0
print(f"[FACE_V2] Detection done in {elapsed:.1f}s")
with open(swift_face_out) as f:
face_data = json.load(f)
return face_data
def embed_and_save(self, detection_data: Dict):
"""Step 2: Crop faces + CoreML embedding + save face.json"""
print(f"[FACE_V2] Step 2: CoreML embedding...")
frames = detection_data.get("frames", [])
self.open_video()
face_data = {
"metadata": {
"video_path": os.path.abspath(self.video_path),
"fps": self.fps, "width": self.width, "height": self.height,
"sample_interval": self.sample_interval,
"detection_method": "apple_vision",
"embedding_method": "coreml_facenet",
"status": "in_progress",
"total_frames": self.total_frames,
},
"frames": {}
}
t0 = time.time()
embed_count = 0
total_face_count = 0
last_pct = -1
all_embeddings = [] # Collect embeddings for Qdrant push
for frame_info in frames:
frame_num = frame_info["frame"]
faces = []
for face_idx, face in enumerate(frame_info.get("faces", [])):
bb = face["bbox"]
x, y, w, h = bb["x"], bb["y"], bb["width"], bb["height"]
if w <= 10 or h <= 10:
continue # skip tiny faces
# Seek to frame and read
self.video.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
ret, frame = self.video.read()
if not ret:
continue
# Crop face
x1, y1 = max(0, x), max(0, y)
x2, y2 = min(self.width, x + w), min(self.height, y + h)
if x2 <= x1 or y2 <= y1:
continue
face_img = frame[y1:y2, x1:x2]
if face_img.size == 0:
continue
# CoreML embedding - push to Qdrant _faces collection
emb = self.extract_face_embedding(face_img)
if emb is not None:
embed_count += 1
# Collect for batch Qdrant push
# Use face_idx to distinguish multiple faces in same frame
all_embeddings.append({
"frame": frame_num,
"trace_id": face_idx, # Use face_idx as unique identifier within frame
"bbox": {"x": x, "y": y, "width": w, "height": h},
"confidence": face.get("confidence", 0.5),
"capture_quality": face.get("captureQuality", 0),
"embedding": emb,
})
# Pose classification
pose_info = face.get("pose", {})
pose_angle = classify_pose(
pose_info.get("roll", 0),
pose_info.get("yaw", 0)
)
faces.append({
"x": x, "y": y, "width": w, "height": h,
"confidence": face.get("confidence", 0.5),
"captureQuality": face.get("captureQuality", 0),
"pose_angle": {
"angle": pose_angle,
"roll": pose_info.get("roll", 0),
"yaw": pose_info.get("yaw", 0),
"pitch": pose_info.get("pitch", 0),
},
"lips": face.get("lips"),
"landmarks": face.get("landmarks"),
"attributes": None,
})
if faces:
face_data["frames"][str(frame_num)] = {
"frame_number": frame_num,
"time_seconds": frame_info.get("timestamp", frame_num / self.fps),
"time_formatted": f"{frame_num / self.fps:.1f}s",
"faces": faces,
}
if len(face_data["frames"]) % 100 == 0:
elapsed = time.time() - t0
print(f"[FACE_V2] {len(face_data['frames'])} frames, {elapsed:.0f}s")
if self.publisher:
pct = int(len(face_data["frames"]) * 100 / max(len(frames), 1))
if pct > last_pct:
last_pct = pct
self.publisher.progress("face", len(face_data["frames"]), len(frames),
"", 0, "faces")
self.video.release()
face_data["metadata"]["status"] = "completed"
# Convert dict frames to list for Rust FaceResult format
frames_list = []
total_faces = 0
for fnum_str, fdata in sorted(face_data["frames"].items(), key=lambda x: int(x[0])):
faces = fdata["faces"]
total_faces += len(faces)
frames_list.append({
"frame": int(fnum_str),
"timestamp": fdata["time_seconds"],
"faces": faces,
})
# Determine status based on face count
if total_faces > 0:
status = "has_faces"
else:
status = "no_faces"
output = {
"status": status,
"frame_count": len(frames_list),
"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:
json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
# Push embeddings to Qdrant _faces collection
if all_embeddings:
try:
pushed = push_face_embeddings_batch(self.uuid, all_embeddings, self.publisher)
if pushed != len(all_embeddings):
raise RuntimeError(
f"Qdrant push incomplete: {pushed}/{len(all_embeddings)} embeddings pushed"
)
except Exception as e:
print(f"[FACE_V2] ERROR: Qdrant push failed: {e}", file=sys.stderr)
raise RuntimeError(f"Qdrant push failed: {e}")
elapsed = time.time() - t0
print(f"[FACE_V2] Done: {len(frames_list)} frames, {embed_count} embeddings, {elapsed:.0f}s")
def main():
parser = argparse.ArgumentParser(description="Apple Vision Face Processor V2")
parser.add_argument("video_path", help="Video file path")
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", default="")
parser.add_argument("--sample-interval", type=int, default=3)
parser.add_argument("--force", action="store_true")
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("face", "FACE_START")
if args.force and os.path.exists(args.output_path):
os.remove(args.output_path)
processor = FaceProcessorVision(
args.video_path, args.output_path,
args.uuid, args.sample_interval, publisher
)
# Open video to get FPS and calculate sample_interval
processor.open_video()
# Step 1: Vision detection (bbox + pose via ANE)
try:
detection = processor.process_with_swift()
except Exception as e:
if publisher:
publisher.error("face", f"Detection failed: {e}")
raise
# Step 2: CoreML embedding + save
try:
processor.embed_and_save(detection)
except Exception as e:
if publisher:
publisher.error("face", f"Embedding failed: {e}")
raise
if publisher:
publisher.complete("face", f"{len(detection.get('frames',[]))} frames")
# Clean up temp detection file
swift_out = args.output_path.replace(".json", "_detect.json")
if os.path.exists(swift_out):
os.remove(swift_out)
if __name__ == "__main__":
main()
+590
View File
@@ -0,0 +1,590 @@
#!/opt/homebrew/bin/python3.11
"""
Face Tracker - Track faces across frames using embedding similarity and bbox proximity
Purpose:
1. Assign unique trace_id to each face across frames
2. Track face movement across adjacent frames
3. Output trace statistics (duration, path, confidence)
Algorithm:
1. For first frame: assign new trace_id to each face
2. For subsequent frames:
- Calculate bbox overlap with previous frame faces
- Calculate embedding cosine similarity
- Match faces if both conditions met
- Assign same trace_id if matched, new trace_id if not
Matching Conditions:
- bbox overlap > 0.3 (IoU)
- embedding similarity > 0.7
- OR single condition > threshold (fallback)
Output:
- face.json with trace_id added to each face
- trace statistics report
"""
import json
import argparse
import numpy as np
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
from typing import Dict, List, Set
from collections import defaultdict
def calculate_bbox_iou(bbox1: Dict, bbox2: Dict) -> float:
"""
Calculate Intersection over Union (IoU) between two bboxes
Args:
bbox1: {"x": int, "y": int, "width": int, "height": int}
bbox2: same structure
Returns:
IoU score (0.0 - 1.0)
"""
x1, y1, w1, h1 = bbox1["x"], bbox1["y"], bbox1["width"], bbox1["height"]
x2, y2, w2, h2 = bbox2["x"], bbox2["y"], bbox2["width"], bbox2["height"]
x1_min, x1_max = x1, x1 + w1
y1_min, y1_max = y1, y1 + h1
x2_min, x2_max = x2, x2 + w2
y2_min, y2_max = y2, y2 + h2
inter_x_min = max(x1_min, x2_min)
inter_x_max = min(x1_max, x2_max)
inter_y_min = max(y1_min, y2_min)
inter_y_max = min(y1_max, y2_max)
if inter_x_max <= inter_x_min or inter_y_max <= inter_y_min:
return 0.0
inter_area = (inter_x_max - inter_x_min) * (inter_y_max - inter_y_min)
area1 = w1 * h1
area2 = w2 * h2
union_area = area1 + area2 - inter_area
return inter_area / union_area if union_area > 0 else 0.0
def calculate_bbox_distance(bbox1: Dict, bbox2: Dict) -> float:
"""
Calculate center distance between two bboxes
Returns:
Euclidean distance between centers
"""
cx1 = bbox1["x"] + bbox1["width"] / 2
cy1 = bbox1["y"] + bbox1["height"] / 2
cx2 = bbox2["x"] + bbox2["width"] / 2
cy2 = bbox2["y"] + bbox2["height"] / 2
return np.sqrt((cx1 - cx2) ** 2 + (cy1 - cy2) ** 2)
def calculate_embedding_similarity(emb1: List[float], emb2: List[float]) -> float:
"""
Calculate cosine similarity between two embeddings
Returns:
Cosine similarity (-1.0 - 1.0)
"""
if emb1 is None or emb2 is None:
return 0.0
v1 = np.array(emb1)
v2 = np.array(emb2)
norm1 = np.linalg.norm(v1)
norm2 = np.linalg.norm(v2)
if norm1 == 0 or norm2 == 0:
return 0.0
return np.dot(v1, v2) / (norm1 * norm2)
def match_faces(
current_faces: List[Dict],
previous_faces: List[Dict],
iou_threshold: float = 0.3,
similarity_threshold: float = 0.7,
distance_threshold: float = 100.0,
use_embedding: bool = True,
frame_gap: int = 1,
cut_boundaries: Set[int] = None,
prev_frame: int = None,
curr_frame: int = None,
) -> Dict[int, int]:
"""
Match current frame faces to previous frame faces
Args:
current_faces: Faces in current frame
previous_faces: Faces in previous frame
iou_threshold: Minimum IoU for matching
similarity_threshold: Minimum embedding similarity for matching
distance_threshold: Maximum bbox center distance for matching
use_embedding: Whether to use embedding similarity
frame_gap: Number of frames between current and previous (1=adjacent)
cut_boundaries: Set of frame numbers where scene cuts occur
prev_frame: Previous frame number (for cut detection)
curr_frame: Current frame number (for cut detection)
Returns:
Dict mapping current_face_index -> previous_face_index (or -1 if new)
"""
if not previous_faces:
return {i: -1 for i in range(len(current_faces))}
# If frame gap is too large, force new traces (likely crossed multiple scenes)
if frame_gap is not None and frame_gap > 30:
return {i: -1 for i in range(len(current_faces))}
# If a scene cut exists between prev and current frame, only continue
# traces for faces matching the previous frame with high IoU (same person
# in the same position across the cut); unmatched faces get new traces.
if cut_boundaries and prev_frame is not None and curr_frame is not None:
for cf in cut_boundaries:
if prev_frame < cf <= curr_frame:
matches = {}
used_prev = set()
for curr_idx, curr_face in enumerate(current_faces):
best_prev_idx = -1
best_iou = 0.0
curr_bbox = {
"x": curr_face["x"],
"y": curr_face["y"],
"width": curr_face["width"],
"height": curr_face["height"],
}
for prev_idx, prev_face in enumerate(previous_faces):
if prev_idx in used_prev:
continue
prev_bbox = {
"x": prev_face["x"],
"y": prev_face["y"],
"width": prev_face["width"],
"height": prev_face["height"],
}
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
if iou > best_iou:
best_iou = iou
best_prev_idx = prev_idx
if best_prev_idx >= 0 and best_iou > 0.5:
matches[curr_idx] = best_prev_idx
used_prev.add(best_prev_idx)
else:
matches[curr_idx] = -1
return matches
matches = {}
used_prev = set()
for curr_idx, curr_face in enumerate(current_faces):
best_prev_idx = -1
best_score = 0.0
curr_bbox = {
"x": curr_face["x"],
"y": curr_face["y"],
"width": curr_face["width"],
"height": curr_face["height"],
}
curr_emb = curr_face.get("embedding")
for prev_idx, prev_face in enumerate(previous_faces):
if prev_idx in used_prev:
continue
prev_bbox = {
"x": prev_face["x"],
"y": prev_face["y"],
"width": prev_face["width"],
"height": prev_face["height"],
}
prev_emb = prev_face.get("embedding")
iou = calculate_bbox_iou(curr_bbox, prev_bbox)
distance = calculate_bbox_distance(curr_bbox, prev_bbox)
similarity = 0.0
if use_embedding and curr_emb and prev_emb:
similarity = calculate_embedding_similarity(curr_emb, prev_emb)
# Bbox size consistency check: sudden size change = different person
prev_area = prev_bbox["width"] * prev_bbox["height"]
curr_area = curr_bbox["width"] * curr_bbox["height"]
area_ratio = max(curr_area, prev_area) / max(1, min(curr_area, prev_area))
score = 0.0
# Reject only if BOTH embedding AND IoU disagree (different person + different position)
if use_embedding and curr_emb and prev_emb and similarity < 0.5 and iou < 0.3:
continue
# Reject if bbox size changes by more than 5x (e.g., far shot → close-up)
if area_ratio > 5.0 and similarity < 0.8:
continue
# Edge exit: if previous face was near frame edge and current face is not,
# the old face likely exited and a new face appeared
prev_at_edge = (prev_bbox["x"] < 50 or
prev_bbox["x"] + prev_bbox["width"] > 1870 or
prev_bbox["y"] < 50 or
prev_bbox["y"] + prev_bbox["height"] > 1030)
curr_at_edge = (curr_bbox["x"] < 50 or
curr_bbox["x"] + curr_bbox["width"] > 1870 or
curr_bbox["y"] < 50 or
curr_bbox["y"] + curr_bbox["height"] > 1030)
if prev_at_edge and not curr_at_edge and similarity < 0.8:
continue
if iou > iou_threshold and similarity > similarity_threshold:
score = iou + similarity
elif iou > 0.5 and similarity > 0.65:
score = iou * 1.5 + similarity * 0.5
elif iou > 0.35 and distance < distance_threshold:
score = iou * 2 - distance / 500
elif similarity > 0.85:
score = similarity * 2
elif similarity > 0.75 and distance < distance_threshold:
score = similarity - distance / 1000
# For frame gaps (tracking lost and recovered), require higher confidence
elif frame_gap > 1 and similarity > 0.8 and iou > 0.2:
score = similarity + iou
if score > best_score:
best_score = score
best_prev_idx = prev_idx
if best_prev_idx >= 0 and best_score > 0:
matches[curr_idx] = best_prev_idx
used_prev.add(best_prev_idx)
else:
matches[curr_idx] = -1
return matches
def track_faces(
face_data: Dict,
iou_threshold: float = 0.3,
similarity_threshold: float = 0.7,
distance_threshold: float = 100.0,
use_embedding: bool = True,
cut_boundaries: Set[int] = None,
) -> Dict:
"""
Track faces across all frames
Args:
face_data: face.json data
iou_threshold: IoU threshold for matching
similarity_threshold: Embedding similarity threshold
distance_threshold: Distance threshold for matching
use_embedding: Whether to use embedding
Returns:
Updated face_data with trace_id added to each face
"""
frames = face_data.get("frames", {})
if not frames:
print("No frames found in face.json")
return face_data
# Support both list and dict formats
if isinstance(frames, list):
# List format: [{frame: 0, faces: [...]}, ...]
sorted_frames = sorted(frames, key=lambda x: x.get("frame", 0))
# Convert to dict format for consistency
frames_dict = {}
for frame_data in sorted_frames:
frame_num = frame_data.get("frame")
if frame_num is not None:
frames_dict[str(frame_num)] = {"faces": frame_data.get("faces", [])}
frames = frames_dict
face_data["frames"] = frames
sorted_frames = sorted(frames.items(), key=lambda x: int(x[0]))
next_trace_id = 0
traces = defaultdict(list)
prev_faces = []
prev_trace_ids = []
prev_frame_num = None
prev_face_frame = None # last frame number that had actual faces
print(f"\nTracking faces across {len(sorted_frames)} frames...")
print(f"Parameters: iou={iou_threshold}, similarity={similarity_threshold}, distance={distance_threshold}")
print()
for frame_num_str, frame_data in sorted_frames:
frame_num = int(frame_num_str)
frame_gap = frame_num - prev_frame_num if prev_frame_num is not None else 1
prev_frame_num = frame_num
faces = frame_data.get("faces", [])
if not faces:
prev_faces = []
prev_trace_ids = []
continue
matches = match_faces(
faces,
prev_faces,
iou_threshold,
similarity_threshold,
distance_threshold,
use_embedding,
frame_gap,
cut_boundaries,
prev_face_frame,
frame_num,
)
trace_ids = []
for curr_idx, prev_idx in matches.items():
if prev_idx >= 0:
trace_id = prev_trace_ids[prev_idx]
else:
trace_id = next_trace_id
next_trace_id += 1
faces[curr_idx]["trace_id"] = trace_id
trace_ids.append(trace_id)
traces[trace_id].append({
"frame": frame_num,
"face_index": curr_idx,
"bbox": {
"x": faces[curr_idx]["x"],
"y": faces[curr_idx]["y"],
"width": faces[curr_idx]["width"],
"height": faces[curr_idx]["height"],
},
"confidence": faces[curr_idx].get("confidence", 0.0),
"pose_angle": faces[curr_idx].get("pose_angle", {}).get("angle", "unknown"),
"pose_full": faces[curr_idx].get("pose_angle", {}), # 完整 pose 信息
})
prev_faces = faces
prev_trace_ids = trace_ids
prev_face_frame = frame_num
if frame_num % 100 == 0:
print(f" Frame {frame_num}: {len(faces)} faces, {len(set(trace_ids))} active traces")
face_data["traces"] = {}
for trace_id, path in traces.items():
if len(path) >= 1:
duration_frames = path[-1]["frame"] - path[0]["frame"] + 1
avg_confidence = sum(p["confidence"] for p in path) / len(path)
pose_angles = [p["pose_angle"] for p in path]
# Pose Trace: 完整 pose 信息
pose_trace = []
for p in path:
pose_info = p.get("pose_full", {})
pose_trace.append({
"frame": p["frame"],
"angle": pose_info.get("angle", "unknown"),
"confidence": pose_info.get("confidence", 0.0),
"pitch": pose_info.get("pitch", "neutral"),
"features": pose_info.get("features", {}),
})
# Pose Statistics
pose_counts = defaultdict(int)
pose_confidence_by_angle = defaultdict(list)
for pose in pose_trace:
pose_counts[pose["angle"]] += 1
pose_confidence_by_angle[pose["angle"]].append(pose["confidence"])
pose_statistics = {
"distribution": dict(pose_counts),
"avg_confidence_by_angle": {
angle: round(sum(conf_list) / len(conf_list), 3)
for angle, conf_list in pose_confidence_by_angle.items()
},
"dominant_angle": max(pose_counts.items(), key=lambda x: x[1])[0] if pose_counts else "unknown",
"pose_count": len(pose_counts),
}
# Pose Transitions: pose 变化事件
pose_transitions = []
prev_pose = None
for i, pose in enumerate(pose_trace):
if prev_pose is not None and pose["angle"] != prev_pose["angle"]:
pose_transitions.append({
"frame": pose["frame"],
"from_angle": prev_pose["angle"],
"to_angle": pose["angle"],
"transition_index": len(pose_transitions) + 1,
})
prev_pose = pose
face_data["traces"][str(trace_id)] = {
"trace_id": trace_id,
"start_frame": path[0]["frame"],
"end_frame": path[-1]["frame"],
"duration_frames": duration_frames,
"duration_seconds": duration_frames / face_data.get("metadata", {}).get("fps", face_data.get("fps", 30.0)),
"total_appearances": len(path),
"avg_confidence": avg_confidence,
"pose_angles": pose_angles,
"pose_trace": pose_trace,
"pose_statistics": pose_statistics,
"pose_transitions": pose_transitions,
"path": path,
}
# Ensure metadata exists
if "metadata" not in face_data:
face_data["metadata"] = {}
face_data["metadata"]["trace_stats"] = {
"total_traces": next_trace_id,
"active_traces": len(traces),
"long_traces": len([t for t in traces.values() if len(t) >= 2]),
}
return face_data
def analyze_traces(face_data: Dict) -> None:
"""
Analyze and print trace statistics
"""
traces = face_data.get("traces", {})
metadata = face_data.get("metadata", {})
print("\n" + "=" * 60)
print("Face Trace Analysis")
print("=" * 60)
print(f"\nTotal traces: {metadata.get('trace_stats', {}).get('total_traces', 0)}")
print(f"Long traces (>= 2 frames): {len(traces)}")
if not traces:
return
sorted_traces = sorted(traces.values(), key=lambda x: x["duration_frames"], reverse=True)
print("\n=== Top 10 Longest Traces ===")
for i, trace in enumerate(sorted_traces[:10]):
print(f"\nTrace {trace['trace_id']}:")
print(f" Frames: {trace['start_frame']} - {trace['end_frame']} ({trace['duration_frames']} frames)")
print(f" Duration: {trace['duration_seconds']:.2f} seconds")
print(f" Appearances: {trace['total_appearances']}")
print(f" Avg Confidence: {trace['avg_confidence']:.3f}")
# Pose Statistics
pose_stats = trace.get("pose_statistics", {})
print(f" Pose Distribution: {pose_stats.get('distribution', {})}")
print(f" Dominant Angle: {pose_stats.get('dominant_angle', 'unknown')}")
# Pose Transitions
transitions = trace.get("pose_transitions", [])
if transitions:
print(f" Pose Transitions: {len(transitions)} events")
for t in transitions[:3]: # 只显示前 3 个
print(f" - Frame {t['frame']}: {t['from_angle']} → {t['to_angle']}")
pose_stats = defaultdict(int)
for trace in traces.values():
for pose in trace["pose_angles"]:
pose_stats[pose] += 1
print("\n=== Pose Distribution in Traces ===")
for pose, count in sorted(pose_stats.items(), key=lambda x: x[1], reverse=True):
print(f" {pose}: {count}")
duration_distribution = defaultdict(int)
for trace in traces.values():
d = trace["duration_frames"]
if d <= 30:
duration_distribution["short (<= 30 frames)"] += 1
elif d <= 90:
duration_distribution["medium (31-90 frames)"] += 1
else:
duration_distribution["long (> 90 frames)"] += 1
print("\n=== Trace Duration Distribution ===")
for duration, count in sorted(duration_distribution.items()):
print(f" {duration}: {count}")
def main():
parser = argparse.ArgumentParser(description="Track faces across frames")
parser.add_argument("--face-json", required=True, help="Path to face.json")
parser.add_argument("--output", help="Output path (default: face_traced.json)")
parser.add_argument("--iou-threshold", type=float, default=0.3, help="IoU threshold")
parser.add_argument("--similarity-threshold", type=float, default=0.7, help="Embedding similarity threshold")
parser.add_argument("--distance-threshold", type=float, default=100.0, help="Distance threshold")
parser.add_argument("--no-embedding", action="store_true", help="Disable embedding matching")
parser.add_argument("--cuts-json", help="Path to cut.json for scene-cut-aware tracking")
parser.add_argument("--analyze-only", action="store_true", help="Only analyze, don't output")
args = parser.parse_args()
# Load cut boundaries if provided
cut_boundaries = None
if args.cuts_json:
with open(args.cuts_json) as f:
cuts = json.load(f)
cut_boundaries = {s["start_frame"] for s in cuts.get("scenes", []) if s["start_frame"] > 0}
print(f" Cut boundaries loaded: {len(cut_boundaries)} cuts")
print("=" * 60)
print("Face Tracker")
print("=" * 60)
with open(args.face_json) as f:
face_data = json.load(f)
print(f"\nInput: {args.face_json}")
print(f"Frames: {len(face_data.get('frames', {}))}")
face_data = track_faces(
face_data,
iou_threshold=args.iou_threshold,
similarity_threshold=args.similarity_threshold,
distance_threshold=args.distance_threshold,
use_embedding=not args.no_embedding,
cut_boundaries=cut_boundaries,
)
analyze_traces(face_data)
if not args.analyze_only:
output_path = args.output or args.face_json.replace(".json", "_traced.json")
with open(output_path, "w") as f:
json.dump(strip_embeddings_and_round(face_data), f, indent=2)
print(f"\n✅ Output saved to: {output_path}")
if __name__ == "__main__":
main()