feat: face fix deployment + trace_* regeneration + executor stderr filter fix

- swift_face.swift: frame rounding (.rounded()), conf 0.75, min_size 64
- trace_* directories regenerated for KOBA (37 traces, start_frame 5307)
- executor.rs: stderr filter now logs all non-empty stderr (was discarding)
- VAD not skippable in ASRX (main_fixed.py Step 2 always runs)
- Step 2.5 sentence boundary refinement added
- Cluster agent async endpoints + similarity transparency
- Keyword search: relationship text extraction, priority ordering
- Face fix handoff doc for Studio team
This commit is contained in:
Accusys
2026-08-05 00:13:50 +08:00
parent 36a704e3d3
commit 3d13a06bd9
42 changed files with 3447 additions and 778 deletions
+8 -6
View File
@@ -198,8 +198,8 @@ def _convert_result(result, output_path):
for seg in asr_segments:
start_time = seg.get("start_time", seg.get("start", 0))
end_time = seg.get("end_time", seg.get("end", 0))
start_frame = int(start_time * fps)
end_frame = int(end_time * fps)
start_frame = seg.get("start_frame", int(start_time * fps))
end_frame = seg.get("end_frame", int(end_time * fps))
converted_segments.append({
"start_time": start_time,
"end_time": end_time,
@@ -372,7 +372,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "",
output_result = {
"status": "has_transcript",
"language": None,
"segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segment_count": len(asr_segments),
"fallback_from_asr": True,
}
@@ -400,12 +400,14 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "",
with open(asr_path) as f:
asr_data = json.load(f)
raw_segments = asr_data.get("segments", [])
# Convert field names: start_time/end_time -> start/end
# Convert field names: start_time/end_time -> start/end, preserve frames
asr_segments = []
for seg in raw_segments:
converted = {
"start": seg.get("start_time", seg.get("start", 0)),
"end": seg.get("end_time", seg.get("end", 0)),
"start_frame": seg.get("start_frame"),
"end_frame": seg.get("end_frame"),
"text": seg.get("text", ""),
}
asr_segments.append(converted)
@@ -447,7 +449,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "",
output_result = {
"status": "has_transcript",
"language": None,
"segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segment_count": len(asr_segments),
"fallback_from_asr": True,
}
@@ -489,7 +491,7 @@ def process_asrx(video_path: str, output_path: str, uuid: str = "",
output_result = {
"status": "has_transcript",
"language": None,
"segments": [{"start_time": s["start"], "end_time": s["end"], "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segments": [{"start_time": s["start"], "end_time": s["end"], "start_frame": s.get("start_frame"), "end_frame": s.get("end_frame"), "text": s["text"], "speaker_id": "SPEAKER_0"} for s in asr_segments],
"segment_count": len(asr_segments),
"fallback_from_asr": True,
}
+105 -22
View File
@@ -215,32 +215,35 @@ class SelfASRXFixed:
print("[SelfASRX] No speech detected by whisper!")
return {"error": "No speech detected", "segments": []}
# ── Step 2: VAD scan 每個 rough segment 細切 ──
# Skip VAD if using ASR segments (preserve all ASR segments)
if asr_segments:
print("\n[Step 2] Skipping VAD scan, using ASR segments directly...")
t2 = time.time()
refined_segments = [(seg["start"], seg["end"]) for seg in rough_segments]
print(f" Refined segments: {len(refined_segments)}")
print(f" Step 2 time: {time.time() - t2:.2f}s")
else:
print("\n[Step 2] VAD scan for refined segmentation...")
t2 = time.time()
refined_segments = []
for seg in rough_segments:
s = seg["start"]
e = seg["end"]
sub = self._vad_scan_segment(wav, sample_rate, s, e)
if sub:
refined_segments.extend(sub)
else:
refined_segments.append((s, e))
print(f" Refined segments: {len(refined_segments)}")
print(f" Step 2 time: {time.time() - t2:.2f}s")
# ── Step 2: VAD scan 每個 rough segment 細切(不可跳過)─
print("\n[Step 2] VAD scan for refined segmentation...")
t2 = time.time()
refined_segments = []
for seg in rough_segments:
s = seg["start"]
e = seg["end"]
sub = self._vad_scan_segment(wav, sample_rate, s, e)
if sub:
refined_segments.extend(sub)
else:
refined_segments.append((s, e))
print(f" Refined segments: {len(refined_segments)}")
print(f" Step 2 time: {time.time() - t2:.2f}s")
if not refined_segments:
return {"error": "No segments after VAD scan", "segments": []}
# ── Step 2.5: 句子邊界偵測 + VAD 聲紋確認(新增)─
# 偵測懸空句(結尾是冠詞/介系詞/省略號),從下一句借詞補齊
# 合併前必須通過 VAD 檢測確認是同一說話者
print("\n[Step 2.5] Sentence boundary refinement...")
t25 = time.time()
refined_segments = self._refine_sentence_boundaries(
refined_segments, wav, sample_rate
)
print(f" Refined segments after boundary fix: {len(refined_segments)}")
print(f" Step 2.5 time: {time.time() - t25:.2f}s")
# ── Step 3: whisper per refined segment ──
print("\n[Step 3] Per-segment transcription...")
t3 = time.time()
@@ -549,6 +552,86 @@ class SelfASRXFixed:
# ── Internal helpers ──
def _refine_sentence_boundaries(self, segments, wav, sample_rate):
"""
偵測懸空句(結尾是冠詞/介系詞/省略號),從下一句借詞補齊。
合併前必須通過 VAD 檢測確認是同一說話者。
"""
# 懸空詞清單:這些詞後面應該接名詞,不該是句尾
HANGING_WORDS = {
"the", "a", "an", "is", "are", "was", "were",
"to", "of", "in", "on", "at", "for", "with",
"and", "but", "or", "so",
}
# 結尾標記:表示句子未完成
HANGING_ENDINGS = ["...", "…"]
if len(segments) < 2:
return segments
refined = []
skip_next = False
for i in range(len(segments) - 1):
if skip_next:
skip_next = False
continue
start, end = segments[i]
next_start, next_end = segments[i + 1]
# 轉錄當前句來偵測結尾
current_text = self._transcribe_segment(wav, sample_rate, start, end).get("text", "").strip().lower()
# 檢查是否為懸空句
is_hanging = False
if current_text:
last_word = current_text.split()[-1] if current_text.split() else ""
if last_word.rstrip(".,!?;:") in HANGING_WORDS:
is_hanging = True
for ending in HANGING_ENDINGS:
if current_text.endswith(ending):
is_hanging = True
break
if not is_hanging:
refined.append((start, end))
continue
# 懸空句:嘗試從下一句借第一個字詞
# 先用 VAD 掃描下一句開頭,確認邊界
gap = next_start - end
vad_sub = self._vad_scan_segment(wav, sample_rate, next_start, min(next_start + 1.5, next_end))
if vad_sub and len(vad_sub) >= 1:
# VAD 切出的第一個子區段
borrow_end = vad_sub[0][1] if vad_sub else next_start + 0.5
# 轉錄借來的部分,檢查語音連續性
borrowed_text = self._transcribe_segment(wav, sample_rate, next_start, borrow_end).get("text", "").strip()
if borrowed_text and len(borrowed_text.split()) <= 3:
# 借來的詞很少(1-3 字),可能是邊界字詞
# 合併:當前句 + 借來的詞
new_end = borrow_end
refined.append((start, new_end))
# 下一句從 borrow_end 開始
if borrow_end < next_end:
segments[i + 1] = (borrow_end, next_end)
skip_next = False # 不跳過,繼續處理調整後的下一句
else:
skip_next = True
continue
# 無法安全合併,保持原樣
refined.append((start, end))
# 最後一段
if not skip_next and segments:
refined.append(segments[-1])
return refined if refined else segments
def _vad_scan_segment(self, wav, sample_rate, start_sec, end_sec):
"""VAD 細切單一段落"""
from vad import scan_within_segment
+241
View File
@@ -0,0 +1,241 @@
#!/usr/bin/env python3
"""
Momentry File Health Check
Checks all registered videos for consistency across:
- JSON files (face.json, face_traced.json, face_cluster.json, etc.)
- Trace directories (key_frame.jpg, key_face.jpg, trace_profile.json)
- Qdrant _faces collection
- PostgreSQL (tkg_nodes, trace_profiles)
Usage:
python3 scripts/check_file_health.py
"""
import json
import os
import sys
import requests
import subprocess
from pathlib import Path
from collections import defaultdict
OUTPUT_DIR = Path(os.environ.get('MOMENTRY_OUTPUT_DIR', '/Users/accusys/momentry/output'))
PSQL = os.environ.get('PSQL_PATH', '/opt/homebrew/opt/libpq/bin/psql')
QDRANT_BASE = os.environ.get('QDRANT_URL', 'http://localhost:6333')
QDRANT_HEADERS = {'api-key': os.environ.get('QDRANT_API_KEY', 'Test3200Test3200Test3200')}
DB_NAME = os.environ.get('DB_NAME', 'momentry')
DB_USER = os.environ.get('DB_USER', 'accusys')
def run_sql(query):
result = subprocess.run(
[PSQL, '-U', DB_USER, '-d', DB_NAME, '-t', '-c', query],
capture_output=True, text=True
)
return result.stdout.strip()
def check_json_files(uuid):
"""Check required JSON files exist."""
json_files = {
'face.json': OUTPUT_DIR / f'{uuid}.face.json',
'face_traced.json': OUTPUT_DIR / f'{uuid}.face_traced.json',
'face_cluster.json': OUTPUT_DIR / f'{uuid}.face_cluster.json',
'cut.json': OUTPUT_DIR / f'{uuid}.cut.json',
'asr.json': OUTPUT_DIR / f'{uuid}.asr.json',
}
missing = [name for name, path in json_files.items() if not path.exists()]
return missing, json_files
def check_cluster_content(uuid, json_files):
"""Check face_cluster.json has valid content if face.json has faces."""
issues = []
cluster_path = json_files['face_cluster.json']
face_path = json_files['face.json']
if cluster_path.exists() and face_path.exists():
with open(cluster_path) as f:
cd = json.load(f)
with open(face_path) as f:
fd = json.load(f)
if fd.get('status') == 'has_faces':
if cd.get('status') == 'no_faces' or len(cd.get('clusters', [])) == 0:
issues.append('face_cluster.json empty but face.json has faces')
return issues
def check_trace_directories(uuid, json_files):
"""Check trace directories are complete and consistent."""
issues = []
trace_dir = OUTPUT_DIR / uuid
traced_path = json_files['face_traced.json']
traced = None
if not trace_dir.is_dir():
return issues, traced, 0, 0
trace_dirs = [t for t in trace_dir.iterdir() if t.is_dir() and t.name.startswith('trace_')]
if traced_path.exists():
with open(traced_path) as f:
traced = json.load(f)
traced_count = len(traced.get('traces', {}))
dir_count = len(trace_dirs)
if traced_count != dir_count:
issues.append(f'Trace count mismatch: JSON={traced_count}, dirs={dir_count}')
# Check each trace directory has required files
missing_files = 0
for td in trace_dirs:
has_kf = (td / 'key_frame.jpg').exists()
has_kface = (td / 'key_face.jpg').exists()
has_tp = (td / 'trace_profile.json').exists()
if not (has_kf and has_kface and has_tp):
missing_files += 1
if missing_files > 0:
issues.append(f'{missing_files} trace dirs missing key_frame/key_face/trace_profile')
# Check for orphaned traces (in JSON but not on disk)
orphaned = 0
for tid in traced.get('traces', {}).keys():
td = trace_dir / f'trace_{tid}'
if not td.exists():
orphaned += 1
if orphaned > 0:
issues.append(f'{orphaned} orphaned traces in JSON (no directory)')
return issues, traced, len(trace_dirs), traced.get('total_faces', 0) if traced else 0
def check_qdrant(uuid):
"""Check Qdrant _faces collection."""
try:
r = requests.post(
f'{QDRANT_BASE}/collections/_faces/points/count',
headers=QDRANT_HEADERS,
json={'filter': {'must': [{'key': 'file_uuid', 'match': {'value': uuid}}]}},
timeout=15
)
return r.json().get('result', {}).get('count', 0)
except Exception as e:
return -1
def check_database(uuid):
"""Check PostgreSQL tables."""
tkg_raw = run_sql(
f"SELECT COUNT(*) FROM public.tkg_nodes WHERE file_uuid = '{uuid}' AND node_type = 'face_track';"
)
tkg_count = int(tkg_raw) if tkg_raw else 0
tp_raw = run_sql(f"SELECT COUNT(*) FROM public.trace_profiles WHERE file_uuid = '{uuid}';")
tp_count = int(tp_raw) if tp_raw else 0
return tkg_count, tp_count
def check_consistency(uuid, traced, qdrant_count, tkg_count, tp_count, dir_count):
"""Cross-check all data sources."""
issues = []
# Qdrant vs traced
if traced and qdrant_count > 0:
face_count = traced.get('total_faces', 0)
if abs(qdrant_count - face_count) > 100:
issues.append(f'Face count mismatch: traced={face_count}, qdrant={qdrant_count}')
# tkg_nodes vs trace_profiles
if tkg_count != tp_count:
issues.append(f'TKG/TP mismatch: tkg_nodes={tkg_count}, trace_profiles={tp_count}')
# tkg_nodes vs trace directories
if dir_count > 0 and tkg_count > 0 and abs(tkg_count - dir_count) > dir_count * 0.1:
issues.append(f'TKG vs dir mismatch: tkg={tkg_count}, dirs={dir_count}')
return issues
def main():
print('=' * 70)
print('MOMENTRY FILE HEALTH CHECK')
print('=' * 70)
print(f'Output dir: {OUTPUT_DIR}')
print(f'Database: {DB_NAME}')
print(f'Qdrant: {QDRANT_BASE}')
print()
# Get all registered videos
raw = run_sql("SELECT file_uuid, file_name FROM videos WHERE file_type = 'video' ORDER BY file_name;")
videos = {}
for line in raw.split('\n'):
parts = [p.strip() for p in line.split('|')]
if len(parts) == 2 and parts[0] and parts[1]:
videos[parts[0]] = parts[1]
print(f'Registered videos: {len(videos)}')
print()
issues = []
all_ok = []
for uuid, filename in sorted(videos.items(), key=lambda x: x[1]):
file_issues = []
# 1. Check JSON files
missing_json, json_files = check_json_files(uuid)
if missing_json:
file_issues.append(f'Missing JSON: {", ".join(missing_json)}')
# 2. Check cluster content
file_issues.extend(check_cluster_content(uuid, json_files))
# 3. Check trace directories
trace_issues, traced, dir_count, face_count = check_trace_directories(uuid, json_files)
file_issues.extend(trace_issues)
# 4. Check Qdrant
qdrant_count = check_qdrant(uuid)
# 5. Check database
tkg_count, tp_count = check_database(uuid)
# 6. Cross-check consistency
file_issues.extend(check_consistency(uuid, traced, qdrant_count, tkg_count, tp_count, dir_count))
if file_issues:
issues.append((uuid, filename, file_issues))
else:
all_ok.append((uuid, filename))
# Print results
print(f'OK: {len(all_ok)}')
print(f'Issues: {len(issues)}')
print()
if issues:
print('=' * 70)
print('FILES WITH ISSUES')
print('=' * 70)
for uuid, filename, file_issues in issues:
print(f'\n{filename}')
print(f' UUID: {uuid}')
for issue in file_issues:
print(f' - {issue}')
print()
print('=' * 70)
print(f'SUMMARY: {len(videos)} total | {len(all_ok)} OK | {len(issues)} issues')
print('=' * 70)
return 1 if issues else 0
if __name__ == '__main__':
sys.exit(main())
+1
View File
@@ -291,3 +291,4 @@ dad775ecdca0144bd14b7abaa7ec8fb213e8b9428e39906abce541e93db496b6 yolo_processor
e13cf22b9aeae96c7e28b4512dd2137743a25eb59027da446966c1aaaaf4ce71 zero_shot_combined_test.py
f4aaf017ff588999f06cd9ba1787517e06c6d6e6228a15a54d8aa4f54fde5eb3 zero_shot_gun_test.py
0a285b8ec33d7999e9d4ae8d43ce768c9f06ee1929e13a6809e98bdabe6357ce zero_shot_objects_test.py
9a44cdd155953778b52ac0cfb118504c56eb6b1141984365ffbb717e28f3e65b scripts/release_pack.py
+184 -50
View File
@@ -1,7 +1,8 @@
#!/opt/homebrew/bin/python3.11
#! /opt/homebrew/bin/python3.11
"""
CUT Processor - Scene Detection & Video Quality Check
Uses ffprobe for video analysis. Always produces at least 1 scene.
Dual-detector: ffprobe scene filter + PySceneDetect ContentDetector (merged).
Always produces at least 1 scene.
"""
import json
@@ -13,14 +14,32 @@ import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
try:
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector, AdaptiveDetector
HAS_SCENEDETECT = True
except ImportError:
HAS_SCENEDETECT = False
def get_video_info(video_path: str) -> dict:
"""Get video info via ffprobe"""
try:
result = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", video_path],
capture_output=True, text=True, timeout=30,
[
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
video_path,
],
capture_output=True,
text=True,
timeout=30,
)
info = json.loads(result.stdout)
for stream in info.get("streams", []):
@@ -50,69 +69,167 @@ def get_video_info(video_path: str) -> dict:
"codec": stream.get("codec_name", ""),
}
return {
"frame_count": 0, "fps": 0.0, "duration": dur,
"width": 0, "height": 0, "codec": "",
"frame_count": 0,
"fps": 0.0,
"duration": dur,
"width": 0,
"height": 0,
"codec": "",
}
return {"frame_count": 0, "fps": 0.0, "duration": 0, "width": 0, "height": 0, "codec": ""}
return {
"frame_count": 0,
"fps": 0.0,
"duration": 0,
"width": 0,
"height": 0,
"codec": "",
}
except Exception:
return {"frame_count": 0, "fps": 0.0, "duration": 0, "width": 0, "height": 0, "codec": ""}
return {
"frame_count": 0,
"fps": 0.0,
"duration": 0,
"width": 0,
"height": 0,
"codec": "",
}
def detect_scenes_ffmpeg(video_path: str, fps: float, duration: float) -> list:
"""Detect scene changes using ffmpeg scene filter"""
"""Detect scene change times using ffmpeg scene filter
Returns:
List of cut times in seconds (empty if failed or no cuts found)
"""
try:
result = subprocess.run(
["ffprobe", "-v", "quiet", "-show_entries", "frame=pts_time",
"-of", "default=nk=0",
"-f", "lavfi",
f"movie={video_path},select='gt(scene\\,0.3)',showinfo",
"-show_frames"],
capture_output=True, text=True, timeout=300,
[
"ffprobe",
"-v",
"quiet",
"-show_entries",
"frame=pts_time",
"-of",
"default=nk=0",
"-f",
"lavfi",
f"movie={video_path},select='gt(scene\\,0.3)',showinfo",
"-show_frames",
],
capture_output=True,
text=True,
timeout=300,
)
times = []
times = set()
for line in (result.stderr + "\n" + result.stdout).split("\n"):
for prefix in ("pts_time=", "pts_time:"):
if prefix in line:
rest = line.split(prefix)[1].split()[0]
try:
t = float(rest)
times.append(t)
times.add(t)
except ValueError:
pass
return sorted(times)
except Exception:
return []
scenes = []
prev_time = 0.0
for i, t in enumerate(times):
end_frame = round(t * fps)
start_frame = round(prev_time * fps)
if end_frame > start_frame:
scenes.append({
"scene_number": i + 1,
"start_frame": start_frame,
def detect_scenes_scenedetect(video_path: str, fps: float, duration: float) -> list:
"""Detect scene change times using PySceneDetect (ContentDetector + AdaptiveDetector)
Runs both detectors and merges results for maximum recall.
Returns:
List of cut times in seconds (empty if failed or no cuts found)
"""
if not HAS_SCENEDETECT:
return []
try:
all_times = set()
# ContentDetector with lower threshold for higher recall
video = open_video(video_path)
sm = SceneManager()
sm.add_detector(ContentDetector(threshold=15.0))
sm.detect_scenes(video)
for i, (start_tc, _) in enumerate(sm.get_scene_list()):
if i == 0:
continue
t = start_tc.get_seconds()
if 0 < t < duration:
all_times.add(t)
# AdaptiveDetector (self-tuning, catches gradual transitions)
video = open_video(video_path)
sm = SceneManager()
sm.add_detector(AdaptiveDetector())
sm.detect_scenes(video)
for i, (start_tc, _) in enumerate(sm.get_scene_list()):
if i == 0:
continue
t = start_tc.get_seconds()
if 0 < t < duration:
all_times.add(t)
return sorted(all_times)
except Exception as e:
print(f"[CUT] scenedetect failed: {e}", file=sys.stderr)
return []
def rebuild_scenes(
cut_times: list, fps: float, total_frames: int, duration: float
) -> list:
"""Rebuild scene list from sorted cut times
Args:
cut_times: Sorted list of cut times in seconds
fps: Frames per second
total_frames: Total frame count
duration: Video duration in seconds
Returns:
List of {scene_number, start_frame, end_frame, start_time, end_time}
"""
scenes = []
prev_time = 0.0
prev_frame = 0
for i, t in enumerate(cut_times):
end_frame = round(t * fps)
if end_frame > prev_frame:
scenes.append(
{
"scene_number": len(scenes) + 1,
"start_frame": prev_frame,
"end_frame": end_frame - 1,
"start_time": prev_time,
"end_time": t - (1.0 / fps) if fps > 0 else t,
})
prev_time = t
}
)
prev_time = t
prev_frame = end_frame
last_frame = round(duration * fps) if fps > 0 else 0
prev_frame = round(prev_time * fps) if fps > 0 else 0
if last_frame > prev_frame:
scenes.append({
# Final scene
last_frame = total_frames
if last_frame > prev_frame:
scenes.append(
{
"scene_number": len(scenes) + 1,
"start_frame": prev_frame,
"end_frame": last_frame - 1,
"start_time": prev_time,
"end_time": duration,
})
}
)
return scenes
except Exception:
return []
return scenes
def process_cut(video_path: str, output_path: str, uuid: str = ""):
"""Process video for scene detection and quality verification"""
"""Process video for scene detection using dual detectors (ffmpeg + scenedetect)"""
publisher = RedisPublisher(uuid) if uuid else None
if publisher:
@@ -121,26 +238,40 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
vinfo = get_video_info(video_path)
if publisher:
publisher.info("cut", f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}")
publisher.info(
"cut",
f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}",
)
total_frames = vinfo["frame_count"]
fps = vinfo["fps"]
duration = vinfo["duration"]
# Try ffmpeg scene detection
scenes = detect_scenes_ffmpeg(video_path, fps, duration)
# Phase 1: ffmpeg scene filter
cut_times_ffmpeg = detect_scenes_ffmpeg(video_path, fps, duration)
# Phase 2: scenedetect ContentDetector
cut_times_sd = detect_scenes_scenedetect(video_path, fps, duration)
# Merge: union of cut points from both detectors
all_cut_times = sorted(set(cut_times_ffmpeg + cut_times_sd))
scenes = rebuild_scenes(all_cut_times, fps, total_frames, duration)
# Always ensure at least 1 scene
if not scenes and total_frames > 0:
scenes = [{
"scene_number": 1,
"start_frame": 0,
"end_frame": total_frames - 1,
"start_time": 0.0,
"end_time": duration,
}]
scenes = [
{
"scene_number": 1,
"start_frame": 0,
"end_frame": total_frames - 1,
"start_time": 0.0,
"end_time": duration,
}
]
if publisher:
publisher.info("cut", "No scene changes detected, using whole video as single scene")
publisher.info(
"cut", "No scene changes detected, using whole video as single scene"
)
result = {
"frame_count": total_frames,
@@ -152,7 +283,10 @@ def process_cut(video_path: str, output_path: str, uuid: str = ""):
json.dump(result, f, indent=2)
if publisher:
publisher.complete("cut", f"{len(scenes)} scenes")
publisher.complete(
"cut",
f"{len(scenes)} scenes ({len(cut_times_ffmpeg)} ffmpeg + {len(cut_times_sd)} scenedetect)",
)
return result
+309
View File
@@ -0,0 +1,309 @@
#!/opt/homebrew/bin/python3.11
"""
Face Clustering Threshold Sweep Experiment
Runs seed-leader and agglomerative clustering across a range of cosine distance
thresholds for a given file_uuid. Reports person count per threshold and
(optionally) evaluation metrics against ground truth.
Usage:
python3 face_cluster_threshold_sweep.py --uuid <file_uuid>
python3 face_cluster_threshold_sweep.py --uuid <file_uuid> --method leader --thresholds 0.25,0.30,0.35,0.40
python3 face_cluster_threshold_sweep.py --uuid <file_uuid> --gt-file gt.json
"""
import argparse
import json
import os
import sys
import numpy as np
from collections import defaultdict
from sklearn.cluster import AgglomerativeClustering
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
DEFAULT_THRESHOLDS = [0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60]
def load_qdrant_trace_centroids(file_uuid: str) -> dict:
"""Load all face points from Qdrant, group by trace_id, compute weighted avg centroids."""
import requests
headers = {"api-key": QDRANT_API_KEY} if QDRANT_API_KEY else {}
all_points = []
offset = None
while True:
body = {
"limit": 10000,
"with_payload": True,
"with_vector": True,
"filter": {
"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]
}
}
if offset:
body["offset"] = offset
resp = requests.post(
f"{QDRANT_URL}/collections/_faces/points/scroll",
json=body, headers=headers, timeout=60
)
if resp.status_code != 200:
print(f"Qdrant scroll error: {resp.status_code}")
break
data = resp.json()
batch = data.get("result", {}).get("points", [])
all_points.extend(batch)
next_offset = data.get("result", {}).get("next_page_offset")
if not next_offset:
break
print(f"Loaded {len(all_points)} face points from Qdrant")
# Group by trace_id
traces = defaultdict(list)
for point in all_points:
payload = point.get("payload", {})
trace_id = payload.get("trace_id")
confidence = payload.get("confidence", 0)
if trace_id is not None and trace_id >= 0 and confidence >= 0.5:
traces[trace_id].append(point)
print(f"Found {len(traces)} unique traces (confidence >= 0.5)")
# Compute weighted avg embedding per trace
trace_embeddings = {}
for trace_id, trace_points in traces.items():
embeddings = []
weights = []
for p in trace_points:
embeddings.append(p["vector"])
weights.append(p.get("payload", {}).get("confidence", 1.0))
embeddings = np.array(embeddings)
weights = np.array(weights)
weights = weights / weights.sum()
avg_embedding = np.average(embeddings, axis=0, weights=weights)
avg_embedding = avg_embedding / np.linalg.norm(avg_embedding)
trace_embeddings[trace_id] = {
"embedding": avg_embedding,
"face_count": len(trace_points),
}
return trace_embeddings
def seed_leader_cluster(trace_embeddings: dict, threshold: float) -> dict:
"""Seed-leader clustering with incremental mean centroids."""
if not trace_embeddings:
return {}
trace_ids = sorted(trace_embeddings.keys())
sim_threshold = 1.0 - threshold
persons = []
for trace_id in trace_ids:
centroid = trace_embeddings[trace_id]["embedding"]
if not persons:
persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]})
continue
best_sim = -1.0
best_idx = -1
for idx, person in enumerate(persons):
p_centroid = person["centroid"]
norm1 = np.linalg.norm(centroid)
norm2 = np.linalg.norm(p_centroid)
if norm1 > 0 and norm2 > 0:
sim = np.dot(centroid, p_centroid) / (norm1 * norm2)
if sim > best_sim:
best_sim = sim
best_idx = idx
if best_sim >= sim_threshold:
persons[best_idx]["member_trace_ids"].append(trace_id)
member_embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in persons[best_idx]["member_trace_ids"]])
persons[best_idx]["centroid"] = np.mean(member_embeddings, axis=0)
else:
persons.append({"centroid": centroid.copy(), "member_trace_ids": [trace_id]})
trace_to_person = {}
for label, person in enumerate(persons):
for tid in person["member_trace_ids"]:
trace_to_person[tid] = label
return trace_to_person
def agglomerative_cluster(trace_embeddings: dict, threshold: float) -> dict:
"""Agglomerative clustering (same as current production)."""
if not trace_embeddings:
return {}
trace_ids = sorted(trace_embeddings.keys())
embeddings = np.array([trace_embeddings[tid]["embedding"] for tid in trace_ids])
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=threshold,
metric="cosine",
linkage="average"
)
labels = clustering.fit_predict(embeddings)
trace_to_person = {}
for i, trace_id in enumerate(trace_ids):
trace_to_person[trace_id] = labels[i]
return trace_to_person
def evaluate_pairwise(trace_to_person: dict, gt_trace_to_person: dict) -> dict:
"""Compute pairwise precision/recall/F1 against ground truth."""
if not trace_to_person or not gt_trace_to_person:
return {"precision": 0, "recall": 0, "f1": 0}
# Get all pairs that should be in same cluster (GT) and predicted same cluster
all_trace_ids = sorted(set(trace_to_person.keys()) | set(gt_trace_to_person.keys()))
n = len(all_trace_ids)
tp = 0 # true positive: same in GT, same in predicted
fp = 0 # false positive: different in GT, same in predicted
fn = 0 # false negative: same in GT, different in predicted
tn = 0 # true negative: different in GT, different in predicted
for i in range(n):
for j in range(i + 1, n):
tid_i, tid_j = all_trace_ids[i], all_trace_ids[j]
gt_same = gt_trace_to_person.get(tid_i) == gt_trace_to_person.get(tid_j)
pred_same = trace_to_person.get(tid_i) == trace_to_person.get(tid_j)
if gt_same and pred_same:
tp += 1
elif gt_same and not pred_same:
fn += 1
elif not gt_same and pred_same:
fp += 1
else:
tn += 1
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
return {
"precision": round(precision, 4),
"recall": round(recall, 4),
"f1": round(f1, 4),
"tp": tp, "fp": fp, "fn": fn, "tn": tn
}
def main():
parser = argparse.ArgumentParser(description="Face Clustering Threshold Sweep")
parser.add_argument("--uuid", required=True, help="File UUID to cluster")
parser.add_argument("--method", choices=["leader", "agglomerative", "both"], default="both",
help="Which method(s) to sweep")
parser.add_argument("--thresholds", type=str, default=None,
help="Comma-separated thresholds (default: 0.20..0.60 step 0.05)")
parser.add_argument("--gt-file", type=str, default=None,
help="JSON file with ground truth: {trace_id: person_label, ...}")
args = parser.parse_args()
file_uuid = args.uuid
thresholds = [float(t) for t in args.thresholds.split(",")] if args.thresholds else DEFAULT_THRESHOLDS
methods = ["leader", "agglomerative"] if args.method == "both" else [args.method]
# Load GT if provided
gt_trace_to_person = {}
if args.gt_file and os.path.exists(args.gt_file):
with open(args.gt_file) as f:
gt_data = json.load(f)
gt_trace_to_person = {int(k): v for k, v in gt_data.items()}
print(f"Loaded ground truth for {len(gt_trace_to_person)} traces")
# Load trace centroids from Qdrant
print(f"Loading trace centroids for {file_uuid}...")
trace_embeddings = load_qdrant_trace_centroids(file_uuid)
n_traces = len(trace_embeddings)
if n_traces == 0:
print("No traces found. Exiting.")
return
print(f"\nSweeping {len(methods)} method(s) × {len(thresholds)} threshold(s) = {len(methods)*len(thresholds)} runs\n")
print("=" * 80)
results = {}
for method in methods:
print(f"\n--- Method: {method} ---")
print(f"{'Threshold':>10} | {'Persons':>7} | {'Clustered Traces':>16} | {'Singletons':>10} | {'Precision':>9} | {'Recall':>7} | {'F1':>5}")
print("-" * 80)
method_results = {}
cluster_func = seed_leader_cluster if method == "leader" else agglomerative_cluster
for threshold in thresholds:
trace_to_person = cluster_func(trace_embeddings, threshold=threshold)
n_persons = len(set(trace_to_person.values()))
n_clustered = len(trace_to_person)
# Count singletons (clusters with only 1 trace)
person_counts = defaultdict(int)
for pid in trace_to_person.values():
person_counts[pid] += 1
n_singletons = sum(1 for c in person_counts.values() if c == 1)
# Evaluate against GT if available
eval_str = ""
eval_data = {}
if gt_trace_to_person:
eval_data = evaluate_pairwise(trace_to_person, gt_trace_to_person)
eval_str = f" | {eval_data['precision']:>9} | {eval_data['recall']:>7} | {eval_data['f1']:>5}"
print(f"{threshold:>10.2f} | {n_persons:>7} | {n_clustered:>16} | {n_singletons:>10}{eval_str}")
method_results[threshold] = {
"n_persons": n_persons,
"n_clustered": n_clustered,
"n_singletons": n_singletons,
"trace_to_person": {str(k): v for k, v in trace_to_person.items()},
"evaluation": eval_data if eval_data else None,
}
results[method] = method_results
# Save results
output_file = f"/Users/accusys/momentry/output/{file_uuid}.cluster_sweep.json"
with open(output_file, "w") as f:
# Don't save full trace_to_person in output (too large)
summary = {}
for method, method_results in results.items():
summary[method] = {}
for t, r in method_results.items():
summary[method][str(t)] = {k: v for k, v in r.items() if k != "trace_to_person"}
json.dump({
"file_uuid": file_uuid,
"n_traces": n_traces,
"summary": summary,
}, f, indent=2)
print(f"\n{'=' * 80}")
print(f"Results saved to {output_file}")
# Pick best threshold if GT available
if gt_trace_to_person:
for method in methods:
best_t = max(results[method].items(), key=lambda x: x[1].get("evaluation", {}).get("f1", 0))
print(f"\nBest for {method}: threshold={best_t[0]}, F1={best_t[1]['evaluation']['f1']}, persons={best_t[1]['n_persons']}")
if __name__ == "__main__":
main()
+171 -37
View File
@@ -41,6 +41,7 @@ ASRX_JSON_PATH = os.path.join(OUTPUT_DIR, f"{UUID}.asrx.json")
DB_URL = os.getenv("DATABASE_URL", "postgresql://accusys@localhost:5432/momentry")
CLUSTER_THRESHOLD = 0.35
CLUSTER_METHOD = "leader"
def write_empty_output(status: str, file_uuid: str, output_path: str):
@@ -159,29 +160,31 @@ def cluster_by_trace(points: list, min_faces_per_trace: int = 1, confidence_thre
return trace_embeddings, traces
def single_stage_clustering(trace_embeddings: dict) -> dict:
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.35) -> 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 {}
return {}, {}
trace_ids = list(trace_embeddings.keys())
n_traces = len(trace_ids)
if n_traces == 0:
return {}
return {}, {}
if n_traces == 1:
return {trace_ids[0]: 0}
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] Clustering {n_traces} traces (threshold={CLUSTER_THRESHOLD})...")
print(f"[CLUSTER] Agglomerative: {n_traces} traces, distance_threshold={threshold}...")
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=CLUSTER_THRESHOLD,
distance_threshold=threshold,
metric="cosine",
linkage="average"
)
@@ -191,10 +194,97 @@ def single_stage_clustering(trace_embeddings: dict) -> dict:
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
return trace_to_person, trace_similarities
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.35) -> 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():
@@ -285,6 +375,10 @@ def main():
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
@@ -329,9 +423,22 @@ def main():
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)
# Adaptive threshold: only filter noise when trace count is large
# For small files (<=1000 traces), keep all traces for maximum recall
# For large files (>1000 traces), filter out single-face noise
min_faces = 4 if len(unique_trace_ids) > 1000 else 1
print(f"[CONFIG] unique_traces={len(unique_trace_ids)}, min_faces_per_trace={min_faces} (adaptive)")
trace_embeddings, traces = cluster_by_trace(
points,
min_faces_per_trace=1,
min_faces_per_trace=min_faces,
confidence_threshold=0.5
)
@@ -343,7 +450,13 @@ def main():
publisher.progress("face_cluster", 30, 100, f"Found {len(trace_embeddings)} traces")
trace_to_person = single_stage_clustering(trace_embeddings)
# 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)
@@ -354,40 +467,35 @@ def main():
print(f"Clustering result: {n_persons} persons ({len(trace_to_person)} traces)")
publisher.progress("face_cluster", 50, 100, f"Found {n_persons} persons")
qdrant_by_frame_trace = {}
for point in points:
payload = point.get("payload", {})
frame = payload.get("frame")
trace_id = payload.get("trace_id", -1)
bbox = payload.get("bbox", {})
if frame is not None and trace_id >= 0:
cx = bbox.get("x", 0) + bbox.get("width", 0) // 2
cy = bbox.get("y", 0) + bbox.get("height", 0) // 2
key = (frame, cx, cy)
qdrant_by_frame_trace[key] = trace_id
# 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)
traced_frames = traced_data.get("frames", {})
print(f" Loaded face_traced.json: {len(traced_frames)} frames")
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)
for face in frame_obj.get("faces", []):
x = face.get("x", 0)
y = face.get("y", 0)
w = face.get("width", 0)
h = face.get("height", 0)
cx = x + w // 2
cy = y + h // 2
key = (frame_num, cx, cy)
# Get traced faces for this frame
traced_frame = traced_frames.get(str(frame_num), {})
traced_faces = traced_frame.get("faces", [])
trace_id = qdrant_by_frame_trace.get(key)
if trace_id is None:
for (qf, qx, qy), tid in qdrant_by_frame_trace.items():
if qf == frame_num and abs(qx - cx) < 50 and abs(qy - cy) < 50:
trace_id = tid
break
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")
@@ -422,26 +530,52 @@ def main():
}
}
# 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)
"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 in frame_obj.get("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}_{frame_idx}",
"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:
+20 -1
View File
@@ -57,8 +57,23 @@ def parse_trace_profile(json_path: Path) -> dict | None:
"end_frame": data.get("end_frame"),
"frame_count": data.get("frame_count"),
"key_frame": data.get("key_frame"),
"key_face": data.get("key_face"),
"status": data.get("status", "pending"),
"avg_confidence": data.get("avg_confidence"),
"properties": json.dumps({
"trace_id": trace_id,
"frame_count": data.get("frame_count"),
"start_frame": data.get("start_frame"),
"end_frame": data.get("end_frame"),
"key_frame": data.get("key_frame"),
"key_face": data.get("key_face"),
"avg_confidence": data.get("avg_confidence"),
"avg_bbox": data.get("avg_bbox"),
"avg_yaw": data.get("avg_yaw"),
"avg_pitch": data.get("avg_pitch"),
"avg_roll": data.get("avg_roll"),
"pose_count": data.get("pose_count"),
}),
"vlm_description": data.get("vlm_description"),
"vlm_clothing": data.get("vlm_clothing"),
"vlm_tags": data.get("vlm_tags", []),
@@ -87,7 +102,7 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False):
sql = f"""
INSERT INTO {table} (
file_uuid, trace_id, name, start_frame, end_frame, frame_count,
key_frame, status, avg_confidence,
key_frame, key_face, status, avg_confidence, properties,
vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting,
vlm_lighting, vlm_weather, vlm_hand_objects, vlm_has_plants, vlm_has_animals,
vlm_background, vlm_bg_tags, vlm_model
@@ -98,8 +113,10 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False):
end_frame = EXCLUDED.end_frame,
frame_count = EXCLUDED.frame_count,
key_frame = EXCLUDED.key_frame,
key_face = EXCLUDED.key_face,
status = EXCLUDED.status,
avg_confidence = EXCLUDED.avg_confidence,
properties = EXCLUDED.properties,
vlm_description = EXCLUDED.vlm_description,
vlm_clothing = EXCLUDED.vlm_clothing,
vlm_tags = EXCLUDED.vlm_tags,
@@ -132,8 +149,10 @@ def insert_trace_profiles(conn, profiles: list[dict], dry_run: bool = False):
p["end_frame"],
p["frame_count"],
p["key_frame"],
p["key_face"],
p["status"],
p["avg_confidence"],
p["properties"],
p["vlm_description"],
p["vlm_clothing"],
p["vlm_tags"],
+9 -3
View File
@@ -140,7 +140,7 @@ def run_face_tracker(
def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHEMA):
"""Update Qdrant _faces collection with trace_id after face tracking.
face_detections table is deprecated — trace_id is stored only in Qdrant _faces payload.
"""
with open(traced_json_path) as f:
@@ -170,6 +170,7 @@ def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHE
# Count unique traces from Qdrant
try:
from qdrant_faces import get_file_faces
points = get_file_faces(file_uuid)
trace_ids = set()
for p in points:
@@ -182,10 +183,15 @@ def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHE
qdrant_trace_count = 0
total_faces = sum(
1 for fd in frames.values() for f in fd.get("faces", []) if f.get("trace_id") is not None
1
for fd in frames.values()
for f in fd.get("faces", [])
if f.get("trace_id") is not None
)
print(f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces")
print(
f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces"
)
return total_faces, qdrant_trace_count
+5 -5
View File
@@ -118,7 +118,7 @@ struct SwiftFace: ParsableCommand {
}
let seconds = CMTimeGetSeconds(actualTime)
let frameNumber = Int(seconds * Double(fps))
let frameNumber = Int((seconds * Double(fps)).rounded())
var frameFaces: [[String: Any]] = []
// Use actual CGImage size (may differ from naturalSize after transform)
@@ -127,8 +127,8 @@ struct SwiftFace: ParsableCommand {
// Process landmark observations FIRST (each has bbox + landmarks, self-consistent)
// Quality filtering
let MIN_CONFIDENCE = 0.6
let MIN_SIZE = 20
let MIN_CONFIDENCE = 0.75
let MIN_SIZE = 64
for lmObs in landmarkObservations {
// Confidence filter
@@ -217,8 +217,8 @@ struct SwiftFace: ParsableCommand {
if matched { continue }
// Quality filtering for unmatched face rects
let MIN_CONFIDENCE = 0.6
let MIN_SIZE = 20
let MIN_CONFIDENCE = 0.75
let MIN_SIZE = 64
let faceConf = Double(faceObs.faceCaptureQuality ?? faceObs.confidence)
if faceConf < MIN_CONFIDENCE { continue }
+20 -9
View File
@@ -43,7 +43,7 @@ def encode_image(image_path: str) -> str:
return base64.b64encode(f.read()).decode("utf-8")
def call_vlm(image_path: str, prompt: str) -> str:
def call_vlm(image_path: str, prompt: str, model: str = None) -> str:
"""Call VLM API using OpenAI-compatible format."""
image_b64 = encode_image(image_path)
@@ -183,20 +183,31 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
print(f"[vlm] Analyzing {trace_path.name}...")
# Prompt 1: Person description
desc_prompt = "Describe this person briefly. Include: gender, age range, hair, visible clothing. If uncertain, say 'unknown'. Be concise and honest."
desc_prompt = "Describe this person briefly. For EVERY item, include COLOR: hair color, skin tone, clothing colors. If uncertain, say 'unknown color'. Be concise and honest."
description = call_vlm(image_to_analyze, desc_prompt, model)
# Prompt 2: Clothing details
clothing_prompt = "Describe this person's clothing in detail. Include colors, type of clothing, any visible text or logos. If unclear, say 'unclear' or 'partially visible'. Do not guess."
clothing_prompt = "Describe this person's clothing in detail. For EACH item, you MUST specify the COLOR: shirt color, pants color, jacket color, hat color, glasses frame color, shoe color. Format: 'color + item' (e.g., 'black hoodie', 'blue jeans'). If color is unclear, say 'unclear color'. Do not skip colors. Include any visible text or logos."
clothing = call_vlm(image_to_analyze, clothing_prompt, model)
# Prompt 3: Tags
tags_prompt = "List 5 tags describing this person's appearance, comma-separated. Only include what you can clearly see. Examples: man, glasses, red-shirt, formal, casual."
tags_raw = call_vlm(image_to_analyze, tags_prompt, model)
tags = [t.strip() for t in tags_raw.replace(",", " ").split() if t.strip()][:5]
# Prompt 3: Tags - auto-extract from description
tags = []
# Simple keyword extraction from description and clothing
for text in [description, clothing]:
if not text:
continue
# Look for color+item patterns
import re
color_patterns = re.findall(r'([a-z]+ (?:hoodie|shirt|pants|jacket|glasses|hat|shoes|beard|hair|sweater|cap|coat))', text.lower())
tags.extend([p.strip() for p in color_patterns])
# Also add simple descriptors
for word in ['man', 'woman', 'glasses', 'beard', 'hat', 'hoodie', 'jacket', 'shirt']:
if word in text.lower() and word not in tags:
tags.append(word)
tags = tags[:5] if tags else ["unknown"]
# Prompt 5: Objects in hand
hand_prompt = "What is this person holding in their hands? Answer: object names if clearly visible, or 'nothing visible', or 'unclear'. Do not guess."
hand_prompt = "Look at the person's hands. What objects are they holding or touching? For EACH object, state its COLOR and type (e.g., 'red cup', 'black phone'). If hands not visible, say 'hands not visible'. If empty, say 'empty hands'."
hand_objects = call_vlm(image_to_analyze, hand_prompt, model)
# Prompt 6: Lighting (day/night)
@@ -217,7 +228,7 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
scene_data = {}
# Prompt 8: Background description
bg_prompt = "Describe the background and environment briefly. Include only what is clearly visible. If uncertain about details, say 'unclear' or 'partially visible'. Do not guess or imagine."
bg_prompt = "Describe the background and environment. For EACH visible object, state its COLOR and type. Include: wall color, monitor colors, furniture colors, equipment colors. If color unclear, say 'unclear'."
background = call_vlm(image_to_analyze, bg_prompt, model)
# Prompt 9: Plants detection
+233 -227
View File
@@ -66,12 +66,7 @@ def ensure_faces_collection() -> bool:
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
# Create collection
body = {
"vectors": {
"size": VECTOR_DIM,
"distance": "Cosine"
}
}
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
create_url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
data = json.dumps(body).encode()
req = urllib.request.Request(create_url, data=data, method="PUT")
@@ -91,112 +86,107 @@ def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int:
return int(hashlib.md5(key.encode()).hexdigest()[:16], 16)
def push_face_embeddings_batch(
file_uuid: str,
faces: list,
publisher=None
) -> int:
def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> int:
"""Batch push face embeddings to _faces collection
Args:
file_uuid: Video file UUID
faces: List of {frame, trace_id, bbox, confidence, embedding}
publisher: RedisPublisher for progress reporting (optional)
Returns:
Number of successfully pushed embeddings
Raises:
RuntimeError: If Qdrant push fails
"""
if not faces:
return 0
ensure_faces_collection()
total = len(faces)
pushed = 0
for i in range(0, total, BATCH_SIZE):
batch = faces[i:i + BATCH_SIZE]
batch = faces[i : i + BATCH_SIZE]
points = []
for face in batch:
point_id = generate_point_id(
file_uuid,
face["frame"],
face.get("trace_id", 0)
file_uuid, face["frame"], face.get("trace_id", 0)
)
points.append({
"id": point_id,
"vector": face["embedding"],
"payload": {
"file_uuid": file_uuid,
"frame": face["frame"],
"trace_id": face.get("trace_id", 0),
"bbox": face["bbox"],
"confidence": face.get("confidence", 0.5),
"identity_id": None,
"identity_uuid": None,
"stranger_id": None,
points.append(
{
"id": point_id,
"vector": face["embedding"],
"payload": {
"file_uuid": file_uuid,
"frame": face["frame"],
"trace_id": face.get("trace_id", 0),
"bbox": face["bbox"],
"confidence": face.get("confidence", 0.5),
"identity_id": None,
"identity_uuid": None,
"stranger_id": None,
},
}
})
)
body = {"points": points}
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
pushed += len(batch)
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(
f"Qdrant push failed (batch {i//BATCH_SIZE}): HTTP {e.code} - {error_body}"
f"Qdrant push failed (batch {i // BATCH_SIZE}): HTTP {e.code} - {error_body}"
)
if publisher:
pct = int((i + len(batch)) * 100 / total)
publisher.progress("face", i + len(batch), total, f"Qdrant push {pct}%")
print(f"[QDRANT] Pushed {pushed} embeddings to {FACES_COLLECTION}")
return pushed
def update_trace_ids(file_uuid: str, trace_mapping: dict) -> int:
"""Update trace_id for all face points in a file
Called by store_traced_faces.py after face tracking.
Uses Qdrant set_payload to avoid reading/writing vectors.
Args:
file_uuid: Video file UUID
trace_mapping: {frame: {bbox_key: trace_id}}
bbox_key = f"{x}_{y}_{width}_{height}"
Returns:
Number of updated points
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": True,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
}
"with_vector": False,
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
}
if offset:
body["offset"] = offset
result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body)
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
@@ -204,89 +194,107 @@ def update_trace_ids(file_uuid: str, trace_mapping: dict) -> int:
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
updates = []
# Group point IDs by trace_id
trace_groups = {}
for point in all_points:
point_id = point["id"]
payload = point.get("payload", {})
vector = point.get("vector", [])
frame = payload.get("frame")
bbox = payload.get("bbox", {})
bbox_key = f"{bbox.get('x')}_{bbox.get('y')}_{bbox.get('width')}_{bbox.get('height')}"
bbox_key = (
f"{bbox.get('x')}_{bbox.get('y')}_{bbox.get('width')}_{bbox.get('height')}"
)
trace_id = trace_mapping.get(frame, {}).get(bbox_key)
if trace_id is None:
continue
payload["trace_id"] = trace_id
updates.append({
"id": point_id,
"vector": vector,
"payload": payload,
})
if not updates:
if trace_id not in trace_groups:
trace_groups[trace_id] = []
trace_groups[trace_id].append(point_id)
if not trace_groups:
return 0
for i in range(0, len(updates), BATCH_SIZE):
batch = updates[i:i + BATCH_SIZE]
body = {"points": batch}
qdrant_request("PUT", f"/collections/{FACES_COLLECTION}/points?wait=true", body)
print(f"[QDRANT] Updated {len(updates)} trace_ids in {FACES_COLLECTION}")
return len(updates)
# Use set_payload per trace_id group (no vector write)
total = 0
for trace_id, point_ids in trace_groups.items():
for i in range(0, len(point_ids), BATCH_SIZE):
batch_ids = point_ids[i : i + BATCH_SIZE]
set_points_payload({"trace_id": trace_id}, batch_ids)
total += len(batch_ids)
print(f"[QDRANT] Updated {total} trace_ids in {FACES_COLLECTION}")
return total
def set_points_payload(payload: dict, point_ids: list, wait: bool = True) -> dict:
"""Set payload fields on specific Qdrant points (without touching vectors)
Args:
payload: Dict of payload fields to set (e.g. {"trace_id": 5})
point_ids: List of Qdrant point IDs
wait: Wait for operation to complete
Returns:
Qdrant API response
"""
body = {
"payload": payload,
"points": point_ids,
"wait": wait,
}
return qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/payload", body
)
def delete_file_faces(file_uuid: str) -> int:
"""Delete all face points for a file
Args:
file_uuid: Video file UUID
Returns:
Number of deleted points
"""
body = {
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
}
}
result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/delete", body)
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/delete", body
)
deleted = result.get("result", {}).get("operation_id", 0)
print(f"[QDRANT] Deleted faces for file_uuid={file_uuid}")
return deleted
def get_file_faces(file_uuid: str) -> list:
def get_file_faces(file_uuid: str, with_vector: bool = False) -> list:
"""Get all face points for a file
Args:
file_uuid: Video file UUID
with_vector: Whether to include vector data (default False for payload-only)
Returns:
List of points with payload and vector
List of points with payload (and vector if requested)
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": True,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
}
"with_vector": with_vector,
"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]},
}
if offset:
body["offset"] = offset
result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body)
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
@@ -294,65 +302,63 @@ def get_file_faces(file_uuid: str) -> list:
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
return all_points
def count_file_faces(file_uuid: str) -> int:
"""Count face points for a file
Args:
file_uuid: Video file UUID
Returns:
Number of face points
"""
body = {
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
}
}
result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/count", body)
body = {"filter": {"must": [{"key": "file_uuid", "match": {"value": file_uuid}}]}}
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/count", body
)
return result.get("result", {}).get("count", 0)
def get_trace_representatives(file_uuid: str) -> dict:
"""Get representative embeddings per trace for multi-angle matching
Args:
file_uuid: Video file UUID
Returns:
{trace_id: [{'frame', 'embedding', 'bbox'}, ...]}
Each trace has 3 representatives: start, middle, end
"""
all_points = get_file_faces(file_uuid)
all_points = get_file_faces(file_uuid, with_vector=True)
traces = {}
for point in all_points:
payload = point.get("payload", {})
vector = point.get("vector", [])
trace_id = payload.get("trace_id", 0)
if trace_id == 0:
continue
if trace_id not in traces:
traces[trace_id] = []
traces[trace_id].append({
"frame": payload.get("frame"),
"embedding": vector,
"bbox": payload.get("bbox", {}),
"confidence": payload.get("confidence", 0.5),
})
traces[trace_id].append(
{
"frame": payload.get("frame"),
"embedding": vector,
"bbox": payload.get("bbox", {}),
"confidence": payload.get("confidence", 0.5),
}
)
for trace_id in traces:
points = traces[trace_id]
points.sort(key=lambda x: x["frame"])
if len(points) <= 3:
traces[trace_id] = points
else:
@@ -361,39 +367,40 @@ def get_trace_representatives(file_uuid: str) -> dict:
middle_idx = len(points) // 2
middle = points[middle_idx]
traces[trace_id] = [start, middle, end]
return traces
def get_trace_centroid(file_uuid: str, trace_id: int) -> list:
"""Get centroid embedding for a trace
Args:
file_uuid: Video file UUID
trace_id: Trace ID
Returns:
Centroid embedding (512D)
"""
reps = get_trace_representatives(file_uuid).get(trace_id, [])
if not reps:
return [0.0] * VECTOR_DIM
centroid = [0.0] * VECTOR_DIM
for rep in reps:
for i, v in enumerate(rep["embedding"]):
centroid[i] += v
count = len(reps)
for i in range(VECTOR_DIM):
centroid[i] /= count
return centroid
# ==================== _seeds Collection ====================
def ensure_seeds_collection() -> bool:
"""Create _seeds collection if not exists"""
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
@@ -405,13 +412,8 @@ def ensure_seeds_collection() -> bool:
except urllib.error.HTTPError as e:
if e.code != 404:
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
body = {
"vectors": {
"size": VECTOR_DIM,
"distance": "Cosine"
}
}
body = {"vectors": {"size": VECTOR_DIM, "distance": "Cosine"}}
create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
data = json.dumps(body).encode()
req = urllib.request.Request(create_url, data=data, method="PUT")
@@ -436,7 +438,7 @@ def push_seed_embedding(
tmdb_id: int = None,
) -> bool:
"""Push identity seed embedding to _seeds collection
Args:
identity_id: PG identity.id
identity_uuid: Identity UUID
@@ -446,15 +448,15 @@ def push_seed_embedding(
file_uuid: File UUID (for manual/propagation seeds)
trace_id: Trace ID (for propagation seeds)
tmdb_id: TMDb ID (for TMDb seeds)
Returns:
True if successful
Raises:
RuntimeError: If Qdrant push fails
"""
ensure_seeds_collection()
payload = {
"identity_id": identity_id,
"identity_uuid": identity_uuid,
@@ -462,28 +464,30 @@ def push_seed_embedding(
"source": source,
"created_at": datetime.now().isoformat(),
}
if file_uuid:
payload["file_uuid"] = file_uuid
if trace_id:
payload["trace_id"] = trace_id
if tmdb_id:
payload["tmdb_id"] = tmdb_id
body = {
"points": [{
"id": identity_id, # Use identity_id as point_id
"vector": embedding,
"payload": payload,
}]
"points": [
{
"id": identity_id, # Use identity_id as point_id
"vector": embedding,
"payload": payload,
}
]
}
url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}/points?wait=true"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="PUT")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
print(f"[QDRANT] Pushed seed: {name} (id={identity_id}, source={source})")
@@ -495,39 +499,41 @@ def push_seed_embedding(
def get_seeds(source: str = None, file_uuid: str = None) -> list:
"""Get all seed points
Args:
source: Filter by source ('tmdb', 'manual', 'propagation'), or None for all
file_uuid: Filter by file_uuid, or None for all
Returns:
List of seed points with payload and vector
"""
ensure_seeds_collection()
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": True,
}
filters = []
if source:
filters.append({"key": "source", "match": {"value": source}})
if file_uuid:
filters.append({"key": "file_uuid", "match": {"value": file_uuid}})
if filters:
body["filter"] = {"must": filters}
if offset:
body["offset"] = offset
result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body)
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
@@ -535,124 +541,133 @@ def get_seeds(source: str = None, file_uuid: str = None) -> list:
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
return all_points
def search_seeds(query_embedding: list, limit: int = 10, threshold: float = 0.0) -> list:
def search_seeds(
query_embedding: list, limit: int = 10, threshold: float = 0.0
) -> list:
"""Cosine search against seeds
Args:
query_embedding: 512D query vector
limit: Max results
threshold: Minimum score threshold
Returns:
List of {identity_id, identity_uuid, name, source, score}
"""
ensure_seeds_collection()
body = {
"vector": query_embedding,
"limit": limit,
"with_payload": True,
}
result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/search", body)
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/search", body
)
points = result.get("result", [])
results = []
for point in points:
score = point.get("score", 0)
if score < threshold:
continue
payload = point.get("payload", {})
results.append({
"identity_id": payload.get("identity_id"),
"identity_uuid": payload.get("identity_uuid"),
"name": payload.get("name"),
"source": payload.get("source"),
"score": score,
})
results.append(
{
"identity_id": payload.get("identity_id"),
"identity_uuid": payload.get("identity_uuid"),
"name": payload.get("name"),
"source": payload.get("source"),
"score": score,
}
)
return results
def delete_seed(identity_id: int) -> bool:
"""Delete a seed point
Args:
identity_id: Identity ID (used as point_id)
Returns:
True if successful
"""
body = {
"points": [identity_id]
}
result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body)
body = {"points": [identity_id]}
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/delete?wait=true", body
)
print(f"[QDRANT] Deleted seed: identity_id={identity_id}")
return result.get("result", {}).get("status") == "completed"
def count_seeds(source: str = None) -> int:
"""Count seed points
Args:
source: Filter by source, or None for all
Returns:
Number of seed points
"""
ensure_seeds_collection()
body = {}
if source:
body["filter"] = {
"must": [
{"key": "source", "match": {"value": source}}
]
}
result = qdrant_request("POST", f"/collections/{SEEDS_COLLECTION}/points/count", body)
body["filter"] = {"must": [{"key": "source", "match": {"value": source}}]}
result = qdrant_request(
"POST", f"/collections/{SEEDS_COLLECTION}/points/count", body
)
return result.get("result", {}).get("count", 0)
def update_identity_in_faces(file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str) -> int:
def update_identity_in_faces(
file_uuid: str, trace_id: int, identity_id: int, identity_uuid: str
) -> int:
"""Update identity_id/identity_uuid for all face points with trace_id
Called after identity binding confirmation.
Uses Qdrant set_payload to avoid reading/writing vectors.
Args:
file_uuid: Video file UUID
trace_id: Trace ID
identity_id: Identity ID
identity_uuid: Identity UUID
Returns:
Number of updated points
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"with_vector": True,
"with_vector": False,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}},
]
}
},
}
if offset:
body["offset"] = offset
result = qdrant_request("POST", f"/collections/{FACES_COLLECTION}/points/scroll", body)
result = qdrant_request(
"POST", f"/collections/{FACES_COLLECTION}/points/scroll", body
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
@@ -660,29 +675,20 @@ def update_identity_in_faces(file_uuid: str, trace_id: int, identity_id: int, id
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
if not all_points:
return 0
updates = []
for point in all_points:
point_id = point["id"]
vector = point.get("vector", [])
payload = point.get("payload", {})
payload["identity_id"] = identity_id
payload["identity_uuid"] = identity_uuid
updates.append({
"id": point_id,
"vector": vector,
"payload": payload,
})
for i in range(0, len(updates), BATCH_SIZE):
batch = updates[i:i + BATCH_SIZE]
body = {"points": batch}
qdrant_request("PUT", f"/collections/{FACES_COLLECTION}/points?wait=true", body)
print(f"[QDRANT] Updated {len(updates)} face points with identity_id={identity_id}")
return len(updates)
point_ids = [point["id"] for point in all_points]
# Use set_payload (no vector write)
for i in range(0, len(point_ids), BATCH_SIZE):
batch_ids = point_ids[i : i + BATCH_SIZE]
set_points_payload(
{"identity_id": identity_id, "identity_uuid": identity_uuid}, batch_ids
)
print(
f"[QDRANT] Updated {len(point_ids)} face points with identity_id={identity_id}"
)
return len(point_ids)