remove: Portal project (Core Team 不再維護前端)

- 移除 portal/ 目錄 (Vue 3 + Tauri 前端)
- 更新 AGENTS.md 移除 Portal 相關說明
- 更新代碼註釋移除 Portal 引用
- 前端開發統一由 Studio Team 負責

參考: docs_v1.0/OPERATIONS/GUI_ARCHITECTURE_REVIEW.md
This commit is contained in:
Accusys
2026-09-30 18:59:40 +08:00
parent 144ec0768a
commit 4b694a1c2d
198 changed files with 3675 additions and 29374 deletions
+28 -2
View File
@@ -142,6 +142,17 @@ def build_trace_profiles(file_uuid=None, dry_run=False):
for fid in file_uuids:
print(f"\n--- {fid} ---")
# Load face.json for bbox lookup (fallback when Qdrant bbox is null)
face_json_path = os.path.join(OUTPUT_DIR, f"{fid}.face.json")
face_json_data = {}
if os.path.exists(face_json_path):
try:
with open(face_json_path) as f:
face_json_data = json.load(f)
print(f" Loaded face.json for bbox lookup")
except Exception as e:
print(f" Warning: Failed to load face.json: {e}")
# Scroll all points for this file with trace_id >= 0
points = scroll_all(
{
@@ -162,9 +173,24 @@ def build_trace_profiles(file_uuid=None, dry_run=False):
for p in points:
pl = p["payload"]
tid = pl.get("trace_id", 0)
frame_num = pl["frame"]
# Try to get bbox from Qdrant first, then fallback to face.json
bbox = pl.get("bbox", {})
if not bbox or (bbox.get("width", 0) == 0 and bbox.get("height", 0) == 0):
# Fallback: find matching face in face.json by frame number
if face_json_data:
for frame_data in face_json_data.get("frames", []):
if frame_data.get("frame") == frame_num:
for face in frame_data.get("faces", []):
if face.get("trace_id") == tid:
bbox = face.get("bbox", {})
break
break
traces[tid].append({
"frame": pl["frame"],
"bbox": pl.get("bbox", {}),
"frame": frame_num,
"bbox": bbox,
"confidence": pl.get("confidence", 0.0),
"capture_quality": pl.get("capture_quality", 0),
})
+295
View File
@@ -0,0 +1,295 @@
#!/usr/bin/env python3
"""
Backfill trace profiles from Qdrant _faces collection.
For each (file_uuid, trace_id) group in Qdrant:
1. Compute frame_count, start_frame, end_frame, avg_confidence
2. Pick representative frame (highest confidence)
3. Extract key_frame.jpg from video via ffmpeg
4. Crop key_face.jpg from key_frame using representative bbox
5. Write output/{file_uuid}/trace_{N}/trace_profile.json
Usage:
python3 backfill_trace_profiles.py [--file-uuid UUID] [--dry-run]
"""
import argparse
import json
import os
import subprocess
import sys
import urllib.request
import urllib.error
from collections import defaultdict
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
BATCH_SIZE = 1000
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
def qdrant_scroll(filter_dict, limit=BATCH_SIZE, offset=None, with_payload=None):
"""Scroll Qdrant collection with filter."""
body = {"limit": limit, "filter": filter_dict, "with_vector": False}
if offset:
body["offset"] = offset
if with_payload:
body["with_payload"] = with_payload
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points/scroll"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="POST")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
def scroll_all(filter_dict, with_payload=None):
"""Scroll all matching points."""
all_points = []
offset = None
while True:
result = qdrant_scroll(filter_dict, offset=offset, with_payload=with_payload)
points = result.get("result", {}).get("points", [])
if not points:
break
all_points.extend(points)
offset = result.get("result", {}).get("next_page_offset")
if not offset or len(points) < BATCH_SIZE:
break
return all_points
def get_video_path(file_uuid):
"""Get video file path from database."""
psql = "/opt/homebrew/Cellar/libpq/18.4/bin/psql"
result = subprocess.run(
[psql, "-U", "accusys", "-d", "momentry", "-t", "-A", "-c",
f"SELECT file_path FROM videos WHERE file_uuid = '{file_uuid}'"],
capture_output=True, text=True
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
return None
def extract_key_frame(video_path, frame_num, fps, output_path):
"""Extract a specific frame from video using ffmpeg select filter (precise frame)."""
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", video_path,
"-vf", f"select=eq(n\\,{frame_num}),scale=640:-1",
"-vframes", "1", "-q:v", "5",
output_path],
capture_output=True, timeout=30
)
return result.returncode == 0 and os.path.exists(output_path)
except Exception as e:
print(f" key_frame extraction failed: {e}", file=sys.stderr)
return False
def crop_key_face(key_frame_path, bbox, output_path, video_width=1920):
"""Crop key_face from key_frame using bbox (scaled to key_frame resolution)."""
x, y, w, h = bbox["x"], bbox["y"], bbox["width"], bbox["height"]
if w <= 0 or h <= 0:
return False
# Scale bbox to key_frame resolution (640px wide)
scale = 640.0 / video_width
x, y, w, h = int(x * scale), int(y * scale), int(w * scale), int(h * scale)
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", key_frame_path,
"-vf", f"crop={w}:{h}:{x}:{y}",
"-q:v", "2", output_path],
capture_output=True, timeout=10
)
return result.returncode == 0 and os.path.exists(output_path)
except Exception as e:
print(f" key_face crop failed: {e}", file=sys.stderr)
return False
def build_trace_profiles(file_uuid=None, dry_run=False):
"""Build trace profiles from Qdrant _faces data."""
# Get all unique file_uuids with trace_id >= 0
if file_uuid:
file_uuids = [file_uuid]
else:
print("Scanning Qdrant for all file_uuids with trace_id >= 0...")
points = scroll_all(
{"must": [{"key": "trace_id", "range": {"gte": 0}}]},
with_payload={"include": ["file_uuid"]}
)
file_uuids = sorted(set(p["payload"]["file_uuid"] for p in points))
print(f"Found {len(file_uuids)} files with trace data")
total_profiles = 0
for fid in file_uuids:
print(f"\n--- {fid} ---")
# Scroll all points for this file with trace_id >= 0
points = scroll_all(
{
"must": [
{"key": "file_uuid", "match": {"value": fid}},
{"key": "trace_id", "range": {"gte": 0}},
]
},
with_payload={"include": ["frame", "trace_id", "bbox", "confidence", "capture_quality"]}
)
if not points:
print(" No points with trace_id >= 0")
continue
# Group by trace_id
traces = defaultdict(list)
for p in points:
pl = p["payload"]
tid = pl.get("trace_id", 0)
traces[tid].append({
"frame": pl["frame"],
"bbox": pl.get("bbox", {}),
"confidence": pl.get("confidence", 0.0),
"capture_quality": pl.get("capture_quality", 0),
})
print(f" {len(points)} points, {len(traces)} traces")
# Get video path
video_path = get_video_path(fid)
if not video_path or not os.path.exists(video_path):
print(f" Video not found, skipping key_frame extraction")
video_path = None
# Get FPS and width from DB
fps = 30.0
video_width = 1920
if video_path:
psql = "/opt/homebrew/Cellar/libpq/18.4/bin/psql"
result = subprocess.run(
[psql, "-U", "accusys", "-d", "momentry", "-t", "-A", "-c",
f"SELECT COALESCE(fps, 30.0), COALESCE(width, 1920) FROM videos WHERE file_uuid = '{fid}'"],
capture_output=True, text=True
)
if result.returncode == 0 and result.stdout.strip():
parts = result.stdout.strip().split('|')
try:
fps = float(parts[0])
video_width = int(parts[1])
except (ValueError, IndexError):
pass
for tid, faces in sorted(traces.items()):
if tid < 0:
continue
frames = [f["frame"] for f in faces]
confidences = [f["confidence"] for f in faces]
capture_qualities = [f.get("capture_quality", 0) for f in faces]
bboxes = [f.get("bbox", {}) for f in faces if f.get("bbox")]
frame_count = len(faces)
start_frame = min(frames)
end_frame = max(frames)
avg_confidence = sum(confidences) / frame_count if frame_count > 0 else 0.0
# Representative frame: highest capture_quality
best = max(faces, key=lambda f: f.get("capture_quality", 0))
best_frame = best["frame"]
best_bbox = best["bbox"]
best_confidence = best["confidence"]
cq_best_quality = best.get("capture_quality", 0)
# Average bbox (approximate centroid)
avg_bbox = {}
if bboxes:
avg_bbox = {
"x": int(sum(b.get("x", 0) for b in bboxes) / len(bboxes)),
"y": int(sum(b.get("y", 0) for b in bboxes) / len(bboxes)),
"width": int(sum(b.get("width", 0) for b in bboxes) / len(bboxes)),
"height": int(sum(b.get("height", 0) for b in bboxes) / len(bboxes)),
}
avg_capture_quality = sum(capture_qualities) / frame_count if frame_count > 0 else 0.0
trace_dir = os.path.join(OUTPUT_DIR, fid, f"trace_{tid}")
profile_path = os.path.join(trace_dir, "trace_profile.json")
kf_path = os.path.join(trace_dir, "key_frame.jpg")
face_path = os.path.join(trace_dir, "key_face.jpg")
profile = {
"version": "1.0",
"file_uuid": fid,
"trace_id": tid,
"label": "",
"frame_count": frame_count,
"start_frame": start_frame,
"end_frame": end_frame,
"best_frame": best_frame,
"avg_confidence": round(avg_confidence, 6),
"best_confidence": round(best_confidence, 6),
"avg_capture_quality": round(avg_capture_quality, 6),
"best_capture_quality": round(cq_best_quality, 6),
"avg_bbox": avg_bbox,
"best_bbox": best_bbox,
"key_frame": "key_frame.jpg" if os.path.exists(kf_path) else None,
"key_face": "key_face.jpg" if os.path.exists(face_path) else None,
"status": "pending",
}
if dry_run:
print(f" trace_{tid}: {frame_count} frames [{start_frame}-{end_frame}] "
f"conf={avg_confidence:.3f} best_frame={best_frame}")
continue
os.makedirs(trace_dir, exist_ok=True)
# Extract key_frame.jpg if not exists
if not os.path.exists(kf_path) and video_path:
extract_key_frame(video_path, best_frame, fps, kf_path)
if os.path.exists(kf_path):
profile["key_frame"] = "key_frame.jpg"
# Crop key_face.jpg from key_frame if not exists
if not os.path.exists(face_path) and os.path.exists(kf_path) and best_bbox:
crop_key_face(kf_path, best_bbox, face_path, video_width)
if os.path.exists(face_path):
profile["key_face"] = "key_face.jpg"
# Write trace_profile.json
with open(profile_path, "w") as f:
json.dump(round_json_numbers(profile), f, indent=2, ensure_ascii=False)
total_profiles += 1
if not dry_run:
print(f" Created {len([t for t in traces if t >= 0])} trace profiles")
print(f"\nDone: {total_profiles} trace profiles created")
def main():
parser = argparse.ArgumentParser(description="Backfill trace profiles from Qdrant")
parser.add_argument("--file-uuid", help="Process only this file UUID")
parser.add_argument("--dry-run", action="store_true", help="Show what would be created")
args = parser.parse_args()
build_trace_profiles(file_uuid=args.file_uuid, dry_run=args.dry_run)
if __name__ == "__main__":
main()
+280
View File
@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""
Backfill trace profiles from Qdrant _faces collection (V2 - handles trace_id = 0).
For each (file_uuid, trace_id) group in Qdrant:
1. Compute frame_count, start_frame, end_frame, avg_confidence
2. Pick representative frame (highest confidence)
3. Extract key_frame.jpg from video via ffmpeg
4. Crop key_face.jpg from key_frame using representative bbox
5. Write output/{file_uuid}/trace_{N}/trace_profile.json
Changes from V1:
- Handles trace_id = 0 (not just trace_id > 0)
- Fixed trace_id filtering logic
- Better error handling
Usage:
python3 backfill_trace_profiles_v2.py [--file-uuid UUID] [--dry-run]
"""
import argparse
import json
import os
import subprocess
import sys
import urllib.request
import urllib.error
from collections import defaultdict
from pathlib import Path
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
BATCH_SIZE = 1000
def scroll_all(filter_body, with_payload=None):
"""Scroll all points from Qdrant."""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_vector": False
}
if with_payload:
body["with_payload"] = with_payload
else:
body["with_payload"] = True
if offset:
body["offset"] = offset
if filter_body:
body["filter"] = filter_body
req = urllib.request.Request(
f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points/scroll",
data=json.dumps(body).encode(),
method="POST"
)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
points = result.get("result", {}).get("points", [])
if not points:
break
all_points.extend(points)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
except Exception as e:
print(f"Error scrolling Qdrant: {e}", file=sys.stderr)
break
return all_points
def get_video_path(file_uuid):
"""Get video file path from PostgreSQL."""
import psycopg2
try:
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
cur.execute("""
SELECT file_path FROM videos WHERE file_uuid = %s
""", (file_uuid,))
row = cur.fetchone()
conn.close()
return row[0] if row else None
except Exception as e:
print(f"Error getting video path: {e}", file=sys.stderr)
return None
def extract_key_frame(video_path, frame_num, output_path):
"""Extract a specific frame from video."""
if not os.path.exists(video_path):
print(f" ⚠️ Video file not found: {video_path}")
return False
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", video_path,
"-vf", f"select=eq(n\\,{frame_num})",
"-vframes", "1", "-q:v", "5",
output_path],
capture_output=True,
timeout=30
)
return result.returncode == 0 and os.path.exists(output_path)
except Exception as e:
print(f" ❌ Error extracting frame: {e}", file=sys.stderr)
return False
def crop_key_face(key_frame_path, bbox, output_path):
"""Crop key_face from key_frame using bbox."""
x, y, w, h = bbox["x"], bbox["y"], bbox["width"], bbox["height"]
if w <= 0 or h <= 0:
return False
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", key_frame_path,
"-vf", f"crop={w}:{h}:{x}:{y},scale=256:256",
"-q:v", "2", output_path],
capture_output=True,
timeout=10
)
return result.returncode == 0
except Exception as e:
print(f" ❌ Error cropping face: {e}", file=sys.stderr)
return False
def build_trace_profiles(file_uuid=None, dry_run=False):
"""Build trace profiles from Qdrant _faces data."""
# Get all unique file_uuids with trace_id >= 0
if file_uuid:
file_uuids = [file_uuid]
else:
print("Scanning Qdrant for all file_uuids with trace_id >= 0...")
points = scroll_all(
{"must": [{"key": "trace_id", "range": {"gte": 0}}]},
with_payload={"include": ["file_uuid"]}
)
file_uuids = sorted(set(p["payload"]["file_uuid"] for p in points))
print(f"Found {len(file_uuids)} files with trace data")
total_profiles = 0
for fid in file_uuids:
print(f"\n--- {fid} ---")
# Scroll all points for this file with trace_id >= 0
points = scroll_all(
{
"must": [
{"key": "file_uuid", "match": {"value": fid}},
{"key": "trace_id", "range": {"gte": 0}}, # ✅ Changed from > to >=
]
},
with_payload={"include": ["frame", "trace_id", "x", "y", "width", "height", "confidence", "capture_quality"]}
)
if not points:
print(" No points with trace_id >= 0")
continue
# Group by trace_id
traces = defaultdict(list)
for p in points:
pl = p["payload"]
tid = pl.get("trace_id", -1)
# ✅ Include trace_id = 0
if tid >= 0:
traces[tid].append(pl)
print(f" Found {len(traces)} traces")
if dry_run:
print(f" (dry-run) Would process {len(traces)} traces")
total_profiles += len(traces)
continue
# Get video path
video_path = get_video_path(fid)
if not video_path:
print(f" ⚠️ Video path not found, skipping")
continue
# Process each trace
for trace_id, faces in traces.items():
if not faces:
continue
# Compute statistics
frames = [f["frame"] for f in faces]
confidences = [f.get("confidence", 0) for f in faces]
frame_count = len(faces)
start_frame = min(frames)
end_frame = max(frames)
avg_confidence = sum(confidences) / len(confidences)
# Find best face (highest confidence)
best_face = max(faces, key=lambda f: f.get("confidence", 0))
best_frame = best_face["frame"]
best_bbox = {
"x": best_face.get("x", 0),
"y": best_face.get("y", 0),
"width": best_face.get("width", 0),
"height": best_face.get("height", 0)
}
# Create trace directory
trace_dir = Path(f"{OUTPUT_DIR}/{fid}/trace_{trace_id}")
trace_dir.mkdir(parents=True, exist_ok=True)
# Extract key_frame
key_frame_path = trace_dir / "key_frame.jpg"
if extract_key_frame(video_path, best_frame, str(key_frame_path)):
# Crop key_face
key_face_path = trace_dir / "key_face.jpg"
crop_key_face(str(key_frame_path), best_bbox, str(key_face_path))
# Write trace_profile.json
profile = {
"trace_id": trace_id,
"frame_count": frame_count,
"start_frame": start_frame,
"end_frame": end_frame,
"avg_confidence": avg_confidence,
"best_frame": best_frame,
"key_face_bbox": best_bbox,
"key_frame": "key_frame.jpg"
}
profile_path = trace_dir / "trace_profile.json"
with open(profile_path, "w") as f:
json.dump(profile, f, indent=2)
total_profiles += 1
print(f" ✅ Created {len(traces)} trace profiles")
print(f"\n=== Done ===")
print(f"Total trace profiles: {total_profiles}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Backfill trace profiles from Qdrant (V2)")
parser.add_argument("--file-uuid", help="Process specific file")
parser.add_argument("--dry-run", action="store_true", help="Show what would be done")
args = parser.parse_args()
build_trace_profiles(args.file_uuid, args.dry_run)
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""
Batch restore faces from face.json to Qdrant
Usage: python3 batch_restore_faces.py [--dry-run]
"""
import os
import sys
import json
import requests
from pathlib import Path
QDRANT_URL = os.environ.get("QDRANT_URL", "http://127.0.0.1:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
def count_faces_in_qdrant(file_uuid):
"""Count faces in Qdrant for a file"""
response = requests.post(
f"{QDRANT_URL}/collections/_faces/points/count",
headers={"api-key": QDRANT_API_KEY},
json={
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
}
}
)
if response.status_code == 200:
return response.json()['result']['count']
return 0
def restore_faces_from_json(file_uuid, dry_run=False):
"""Restore faces from face.json to Qdrant"""
face_json_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.face.json")
if not os.path.exists(face_json_path):
print(f" [SKIP] face.json not found")
return False
# Check if already has faces in Qdrant
current_count = count_faces_in_qdrant(file_uuid)
if current_count > 0:
print(f" [SKIP] Already has {current_count} faces in Qdrant")
return True
# Load face.json
with open(face_json_path, 'r') as f:
face_data = json.load(f)
# Check if valid
if face_data.get('status') == 'no_faces':
print(f" [SKIP] No faces in file")
return True
frames = face_data.get('frames', [])
if not frames:
print(f" [SKIP] No frames in face.json")
return False
# Count valid faces
valid_count = 0
invalid_count = 0
for frame in frames:
faces = frame.get('faces', [])
for face in faces:
w = face.get('width', 0)
h = face.get('height', 0)
if w > 0 and h > 0 and face.get('embedding'):
valid_count += 1
else:
invalid_count += 1
print(f" [INFO] Faces: {valid_count} valid, {invalid_count} invalid")
if valid_count == 0:
print(f" [SKIP] No valid faces")
return False
if dry_run:
print(f" [DRY-RUN] Would restore {valid_count} faces")
return True
# TODO: Implement actual Qdrant storage
print(f" [TODO] Implement Qdrant storage")
return False
def main():
dry_run = '--dry-run' in sys.argv
if dry_run:
print("[INFO] DRY-RUN mode - no changes will be made")
# Find all face.json files
output_dir = Path(OUTPUT_DIR)
face_files = list(output_dir.glob("*.face.json"))
print(f"\n[INFO] Found {len(face_files)} face.json files")
print("\n[INFO] Processing files (first 20):")
restored = 0
skipped = 0
failed = 0
for i, face_file in enumerate(face_files[:20]):
# Extract file_uuid (remove .face.json)
filename = face_file.name
file_uuid = filename.replace('.face.json', '')
print(f"\n{i+1}. {file_uuid[:20]}...:")
result = restore_faces_from_json(file_uuid, dry_run)
if result:
restored += 1
else:
failed += 1
print(f"\n[INFO] Summary (first 20):")
print(f" Restored: {restored}")
print(f" Failed: {failed}")
if dry_run:
print("\n[INFO] Run without --dry-run to actually restore")
if __name__ == "__main__":
main()
@@ -129,6 +129,21 @@ def main():
sys.exit(1)
print(f"[STORE] ✅ Done: {len(points)} embeddings stored in Qdrant")
# Remove embeddings from JSON to save disk space (they're now in Qdrant only)
print(f"[STORE] Removing embeddings from JSON to save space...")
for frame in frames:
for face in frame.get("faces", []):
if "embedding" in face:
del face["embedding"]
# Write cleaned JSON back
with open(face_json_path, "w") as f:
json.dump(data, f, indent=2)
import os
new_size = os.path.getsize(face_json_path)
print(f"[STORE] ✅ JSON cleaned, size: {new_size / 1024:.1f} KB")
if __name__ == "__main__":
main()
+37 -2
View File
@@ -170,8 +170,43 @@ struct ASRXSwift: ParsableCommand {
}
func resolveLanguage() -> String {
if !language.isEmpty { return language }
let candidates = ["zh-TW", "zh-Hans", "en-US", "ja-JP", "ko-KR"]
// 1. If --language is specified, use it
if !language.isEmpty {
print("[ASRX_Swift] Using specified language: \(language)")
return language
}
// 2. Try to read language from ASR JSON
let outputDir = URL(fileURLWithPath: outputPath).deletingLastPathComponent()
let fileUUID = URL(fileURLWithPath: outputPath).deletingPathExtension().lastPathComponent
let asrJsonPath = outputDir.appendingPathComponent("\(fileUUID).asr.json").path
if FileManager.default.fileExists(atPath: asrJsonPath) {
do {
let asrData = try Data(contentsOf: URL(fileURLWithPath: asrJsonPath))
if let asrJson = try JSONSerialization.jsonObject(with: asrData) as? [String: Any],
let asrLang = asrJson["language"] as? String {
// Map ASR language codes to Apple locale identifiers
let langMap: [String: String] = [
"en": "en-US",
"zh": "zh-TW",
"ja": "ja-JP",
"ko": "ko-KR",
"es": "es-ES",
"fr": "fr-FR",
"de": "de-DE",
]
let appleLang = langMap[asrLang] ?? asrLang
print("[ASRX_Swift] Using language from ASR JSON: \(asrLang) -> \(appleLang)")
return appleLang
}
} catch {
print("[ASRX_Swift] Warning: Failed to read ASR JSON: \(error)")
}
}
// 3. Fallback to auto-detection (prioritize en-US)
let candidates = ["en-US", "zh-TW", "zh-Hans", "ja-JP", "ko-KR"]
for localeId in candidates {
if let reco = SFSpeechRecognizer(locale: Locale(identifier: localeId)), reco.isAvailable {
print("[ASRX_Swift] Auto-detected language: \(localeId)")
@@ -66,8 +66,8 @@ struct FaceNetEmbedding: ParsableCommand {
for j in 0..<faces.count {
var face = faces[j]
// Skip if already has embedding
if face["embedding"] != nil {
// Skip if already has valid embedding (not null and not empty)
if let existingEmbedding = face["embedding"] as? [Float], !existingEmbedding.isEmpty {
embeddingCount += 1
continue
}
+1 -39
View File
@@ -177,51 +177,13 @@ struct SwiftFace: ParsableCommand {
}
}
// Match face observation by bbox to extract faceprint (embedding)
var embedding: [Float]? = nil
if #available(macOS 14, *) {
var matchCount = 0
for faceObs in faceObservations {
let fBB = faceObs.boundingBox
let ix = max(bb.minX, fBB.origin.x)
let iy = max(bb.minY, fBB.origin.y)
let iw = min(bb.maxX, fBB.origin.x + fBB.width) - ix
let ih = min(bb.maxY, fBB.origin.y + fBB.height) - iy
if iw <= 0 || ih <= 0 { continue }
let intersection = iw * ih
let union = bb.width * bb.height + fBB.width * fBB.height - intersection
if intersection / union > 0.5 {
matchCount += 1
// Try to extract faceprint
if let fp = faceObs.value(forKey: "faceprint") as? NSObject {
if let desc = fp.value(forKey: "descriptor") as? NSObject {
if let elems = desc.value(forKey: "elements") as? [NSNumber] {
embedding = elems.map { Float($0.doubleValue) }
} else {
print("[DEBUG] No elements in descriptor")
}
} else {
print("[DEBUG] No descriptor in faceprint")
}
} else {
print("[DEBUG] No faceprint in faceObs (frame \(frameNumber), match \(matchCount))")
}
break
}
}
}
var faceData: [String: Any] = [
"bbox": ["x": max(0, faceX), "y": max(0, faceY),
"width": faceW, "height": faceH],
"confidence": Double(lmObs.confidence),
"captureQuality": captureQ,
]
// Add embedding if available
if let emb = embedding {
faceData["embedding"] = emb
}
// NOTE: embedding is NOT stored in JSON, only in Qdrant via Rust worker
// Pose from landmark observation
if let yaw = lmObs.yaw?.doubleValue,
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""
Backfill Qdrant _faces from PostgreSQL face_detections.
For files that have face_detections data but missing in Qdrant:
1. Read embeddings from face_detections
2. Store to Qdrant _faces collection
3. Update trace_profiles.best_bbox
Usage:
python3 backfill_qdrant_from_pg.py [--file-uuid UUID]
"""
import argparse
import json
import os
import sys
import urllib.request
import psycopg2
from pathlib import Path
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
def get_files_needing_qdrant():
"""Get files with face_detections but missing in Qdrant."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
cur.execute("""
SELECT DISTINCT file_uuid
FROM face_detections
WHERE embedding IS NOT NULL
AND file_uuid NOT IN (
SELECT DISTINCT file_uuid
FROM trace_profiles
WHERE best_bbox IS NOT NULL
)
""")
files = [row[0] for row in cur.fetchall()]
conn.close()
return files
def get_face_detections(file_uuid):
"""Get all face detections for a file."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
cur.execute("""
SELECT
frame_number,
x, y, width, height,
confidence,
trace_id,
embedding
FROM face_detections
WHERE file_uuid = %s
ORDER BY frame_number
""", (file_uuid,))
faces = []
for row in cur.fetchall():
frame, x, y, w, h, conf, trace_id, embedding = row
if embedding:
faces.append({
"frame": frame,
"x": x,
"y": y,
"width": w,
"height": h,
"confidence": conf,
"trace_id": trace_id,
"embedding": embedding
})
conn.close()
return faces
def store_to_qdrant(file_uuid, faces):
"""Store faces to Qdrant _faces collection."""
if not faces:
return 0
points = []
for face in faces:
# Generate point ID
point_id = hash(f"{file_uuid}_{face['frame']}_{face['trace_id']}") % (2**63)
points.append({
"id": point_id,
"vector": face["embedding"],
"payload": {
"file_uuid": file_uuid,
"frame": face["frame"],
"trace_id": face["trace_id"],
"x": face["x"],
"y": face["y"],
"width": face["width"],
"height": face["height"],
"confidence": face["confidence"],
"identity_id": 0,
"identity_uuid": "",
"stranger_id": 0
}
})
# Upload to Qdrant
body = {"points": points}
req = urllib.request.Request(
f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points?wait=true",
data=json.dumps(body).encode(),
method="PUT"
)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
return len(points)
except Exception as e:
print(f" ❌ Failed to store to Qdrant: {e}", file=sys.stderr)
return 0
def main():
parser = argparse.ArgumentParser(description="Backfill Qdrant from PostgreSQL")
parser.add_argument("--file-uuid", help="Process specific file")
args = parser.parse_args()
print("=== Backfill Qdrant from PostgreSQL ===\n")
if args.file_uuid:
files = [args.file_uuid]
else:
files = get_files_needing_qdrant()
print(f"找到 {len(files)} 個需要處理的文件\n")
total_stored = 0
for i, file_uuid in enumerate(files, 1):
print(f"[{i}/{len(files)}] {file_uuid[:16]}...")
# Get face detections
faces = get_face_detections(file_uuid)
print(f" 找到 {len(faces)} 個 face detections")
if faces:
# Store to Qdrant
stored = store_to_qdrant(file_uuid, faces)
print(f" ✅ 已存入 Qdrant: {stored} 點")
total_stored += stored
else:
print(f" ⚠️ 沒有有效的 face detections")
print()
print(f"=== 完成 ===")
print(f"總計存入: {total_stored} 點")
if __name__ == "__main__":
main()
+282
View File
@@ -0,0 +1,282 @@
#!/usr/bin/env python3
"""
Batch fix all traces with missing or invalid bbox.
Steps:
1. Query all traces with missing/invalid bbox from PostgreSQL
2. Get best_bbox from Qdrant _faces
3. Update PostgreSQL trace_profiles
4. Generate key_face.jpg
5. Draw bbox on key_frame.jpg
Usage:
python3 batch_fix_traces.py [--file-uuid UUID] [--dry-run]
"""
import argparse
import json
import os
import subprocess
import sys
import urllib.request
import psycopg2
import cv2
from pathlib import Path
from collections import defaultdict
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
def get_traces_needing_fix(file_uuid=None):
"""Get traces with missing or invalid bbox."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
if file_uuid:
cur.execute("""
SELECT file_uuid, trace_id
FROM trace_profiles
WHERE file_uuid = %s
AND (best_bbox IS NULL
OR best_bbox->>'x' = '0'
OR best_bbox->>'x' IS NULL)
ORDER BY trace_id
""", (file_uuid,))
else:
cur.execute("""
SELECT file_uuid, trace_id
FROM trace_profiles
WHERE best_bbox IS NULL
OR best_bbox->>'x' = '0'
OR best_bbox->>'x' IS NULL
ORDER BY file_uuid, trace_id
""")
traces = cur.fetchall()
conn.close()
return traces
def get_best_bbox_from_qdrant(file_uuid, trace_id):
"""Get best bbox for a trace from Qdrant."""
body = {
"limit": 100,
"with_payload": True,
"with_vector": False,
"filter": {
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}}
]
}
}
req = urllib.request.Request(
f"{QDRANT_URL}/collections/_faces/points/scroll",
data=json.dumps(body).encode(),
method="POST"
)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
result = json.loads(resp.read())
points = result.get("result", {}).get("points", [])
if not points:
return None
# Find best bbox
best_point = max(points, key=lambda p: p["payload"].get("confidence", 0))
payload = best_point["payload"]
x = payload.get("x", 0)
y = payload.get("y", 0)
w = payload.get("width", 0)
h = payload.get("height", 0)
if x <= 0 or y <= 0 or w <= 0 or h <= 0:
return None
return {
"x": x,
"y": y,
"width": w,
"height": h,
"confidence": payload.get("confidence", 0),
"frame": payload.get("frame", 0)
}
except Exception as e:
print(f" ❌ Qdrant query failed: {e}", file=sys.stderr)
return None
def update_trace_bbox(file_uuid, trace_id, best_bbox):
"""Update trace_profiles with best_bbox."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
bbox_json = {
"x": best_bbox["x"],
"y": best_bbox["y"],
"width": best_bbox["width"],
"height": best_bbox["height"]
}
cur.execute("""
UPDATE trace_profiles
SET best_bbox = %s, best_confidence = %s
WHERE file_uuid = %s AND trace_id = %s
""", (json.dumps(bbox_json), best_bbox["confidence"], file_uuid, trace_id))
conn.commit()
conn.close()
def generate_key_face(trace_dir, best_bbox):
"""Generate key_face.jpg from key_frame.jpg."""
key_frame_path = trace_dir / "key_frame.jpg"
key_face_path = trace_dir / "key_face.jpg"
if not key_frame_path.exists():
return False
x = best_bbox["x"]
y = best_bbox["y"]
w = best_bbox["width"]
h = best_bbox["height"]
cmd = [
"ffmpeg", "-y",
"-i", str(key_frame_path),
"-vf", f"crop={w}:{h}:{x}:{y},scale=256:256",
"-q:v", "2",
str(key_face_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
return result.returncode == 0
def draw_bbox_on_keyframe(trace_dir, best_bbox):
"""Draw bbox on key_frame.jpg."""
key_frame_path = trace_dir / "key_frame.jpg"
if not key_frame_path.exists():
return False
img = cv2.imread(str(key_frame_path))
if img is None:
return False
x = best_bbox["x"]
y = best_bbox["y"]
w = best_bbox["width"]
h = best_bbox["height"]
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)
cv2.imwrite(str(key_frame_path), img)
return True
def fix_trace(file_uuid, trace_id, dry_run=False):
"""Fix a single trace."""
trace_dir = Path(f"{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}")
print(f" Trace {trace_id}:")
# Step 1: Get best_bbox from Qdrant
print(f" 1. 查詢 Qdrant...")
best_bbox = get_best_bbox_from_qdrant(file_uuid, trace_id)
if not best_bbox:
print(f" ❌ 沒有找到 bbox")
return False
print(f" ✅ bbox=[{best_bbox['x']}, {best_bbox['y']}, {best_bbox['width']}, {best_bbox['height']}]")
if dry_run:
print(f" (dry-run) 跳過更新")
return True
# Step 2: Update PostgreSQL
print(f" 2. 更新 PostgreSQL...")
update_trace_bbox(file_uuid, trace_id, best_bbox)
# Step 3: Generate key_face.jpg
print(f" 3. 生成 key_face.jpg...")
if generate_key_face(trace_dir, best_bbox):
print(f" ✅ key_face.jpg 已生成")
else:
print(f" ⚠️ key_face.jpg 生成失敗")
# Step 4: Draw bbox
print(f" 4. 繪製 bbox...")
if draw_bbox_on_keyframe(trace_dir, best_bbox):
print(f" ✅ bbox 已繪製")
else:
print(f" ⚠️ bbox 繪製失敗")
return True
def main():
parser = argparse.ArgumentParser(description="Batch fix traces with missing bbox")
parser.add_argument("--file-uuid", help="Fix specific file")
parser.add_argument("--dry-run", action="store_true", help="Show what would be done")
args = parser.parse_args()
print("=== 批量修復 Traces ===\n")
# Get traces needing fix
traces = get_traces_needing_fix(args.file_uuid)
print(f"找到 {len(traces)} 個需要修復的 traces\n")
if not traces:
print("✅ 沒有需要修復的 traces")
return
# Group by file_uuid
traces_by_file = defaultdict(list)
for file_uuid, trace_id in traces:
traces_by_file[file_uuid].append(trace_id)
print(f"涉及 {len(traces_by_file)} 個文件\n")
# Fix each file
total_fixed = 0
total_failed = 0
for i, (file_uuid, trace_ids) in enumerate(traces_by_file.items(), 1):
print(f"\n--- 文件 {i}/{len(traces_by_file)}: {file_uuid[:16]}... ---")
print(f"需要修復 {len(trace_ids)} 個 traces\n")
for trace_id in trace_ids:
if fix_trace(file_uuid, trace_id, args.dry_run):
total_fixed += 1
else:
total_failed += 1
print(f"\n=== 完成 ===")
print(f"成功: {total_fixed}/{len(traces)}")
print(f"失敗: {total_failed}/{len(traces)}")
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""
Draw bbox on key_frame.jpg for all traces.
Reads best_bbox from PostgreSQL trace_profiles table,
then draws green rectangle on key_frame.jpg using OpenCV.
Usage:
python3 draw_bbox_on_keyframes.py --file-uuid UUID
python3 draw_bbox_on_keyframes.py --all
"""
import argparse
import cv2
import os
import psycopg2
from pathlib import Path
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
def draw_bbox_on_keyframe(file_uuid, trace_id, best_bbox):
"""Draw bbox on key_frame.jpg using OpenCV."""
trace_dir = Path(f"{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}")
key_frame_path = trace_dir / "key_frame.jpg"
if not key_frame_path.exists():
print(f" ⚠️ Trace {trace_id}: key_frame.jpg not found")
return False
# Read image
img = cv2.imread(str(key_frame_path))
if img is None:
print(f" ❌ Trace {trace_id}: cannot read image")
return False
x = best_bbox["x"]
y = best_bbox["y"]
w = best_bbox["width"]
h = best_bbox["height"]
# Draw green rectangle (line width: 4 pixels)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)
# Save
cv2.imwrite(str(key_frame_path), img)
return True
def process_file(file_uuid):
"""Process all traces for a file."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
cur.execute("""
SELECT trace_id, best_bbox
FROM trace_profiles
WHERE file_uuid = %s
ORDER BY trace_id
""", (file_uuid,))
rows = cur.fetchall()
conn.close()
print(f"Found {len(rows)} traces for {file_uuid}\n")
success_count = 0
for trace_id, best_bbox in rows:
if not best_bbox or best_bbox.get("x", 0) == 0:
print(f" ⚠️ Trace {trace_id}: no valid bbox")
continue
if draw_bbox_on_keyframe(file_uuid, trace_id, best_bbox):
print(f" ✅ Trace {trace_id}: bbox=[{best_bbox['x']}, {best_bbox['y']}, {best_bbox['width']}, {best_bbox['height']}]")
success_count += 1
print(f"\n✅ Successfully processed {success_count}/{len(rows)} traces")
def process_all():
"""Process all files."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
cur.execute("""
SELECT DISTINCT file_uuid
FROM trace_profiles
WHERE best_bbox IS NOT NULL
""")
files = [row[0] for row in cur.fetchall()]
conn.close()
print(f"Found {len(files)} files with traces\n")
for file_uuid in files:
print(f"Processing {file_uuid}...")
process_file(file_uuid)
print()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Draw bbox on key_frame.jpg")
parser.add_argument("--file-uuid", help="Process specific file")
parser.add_argument("--all", action="store_true", help="Process all files")
args = parser.parse_args()
if args.all:
process_all()
elif args.file_uuid:
process_file(args.file_uuid)
else:
parser.print_help()
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env python3
"""
Monitor trace data integrity between PostgreSQL and Qdrant.
Checks:
1. Files with traces in PostgreSQL but missing in Qdrant
2. Traces with missing or invalid bbox
3. Files with missing key_face.jpg or key_frame.jpg
4. Orphan records (traces without corresponding videos)
Usage:
python3 monitor_trace_integrity.py [--output REPORT.md]
"""
import argparse
import json
import os
import sys
import urllib.request
from collections import Counter, defaultdict
from datetime import datetime
import psycopg2
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
def get_qdrant_stats():
"""Get statistics from Qdrant."""
# Get all points
all_points = []
offset = None
while True:
body = {
"limit": 1000,
"with_payload": {"include": ["file_uuid", "trace_id"]},
"with_vector": False
}
if offset:
body["offset"] = offset
req = urllib.request.Request(
f"{QDRANT_URL}/collections/{FACES_COLLECTION}/points/scroll",
data=json.dumps(body).encode(),
method="POST"
)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
result = json.loads(resp.read())
points = result.get("result", {}).get("points", [])
if not points:
break
all_points.extend(points)
offset = result.get("result", {}).get("next_page_offset")
if not offset or len(all_points) >= 20000:
break
except Exception as e:
print(f"Error querying Qdrant: {e}", file=sys.stderr)
break
# Group by file_uuid
file_stats = defaultdict(lambda: {"points": 0, "traces": set()})
for p in all_points:
file_uuid = p["payload"]["file_uuid"]
trace_id = p["payload"].get("trace_id", -1)
file_stats[file_uuid]["points"] += 1
if trace_id >= 0:
file_stats[file_uuid]["traces"].add(trace_id)
return file_stats
def get_postgres_stats():
"""Get statistics from PostgreSQL."""
conn = psycopg2.connect(
host="localhost",
database="momentry",
user="accusys"
)
cur = conn.cursor()
# Get trace stats
cur.execute("""
SELECT
file_uuid,
COUNT(*) as trace_count,
COUNT(best_bbox) as has_bbox,
COUNT(CASE WHEN best_bbox->>'x' != '0' THEN 1 END) as valid_bbox
FROM trace_profiles
GROUP BY file_uuid
""")
trace_stats = {}
for row in cur.fetchall():
trace_stats[row[0]] = {
"traces": row[1],
"has_bbox": row[2],
"valid_bbox": row[3]
}
# Get video stats
cur.execute("""
SELECT file_uuid, file_name, file_path, status
FROM videos
""")
video_stats = {}
for row in cur.fetchall():
video_stats[row[0]] = {
"name": row[1],
"path": row[2],
"status": row[3]
}
conn.close()
return trace_stats, video_stats
def check_file_integrity(file_uuid, trace_count):
"""Check if trace files exist."""
issues = []
for trace_id in range(trace_count):
trace_dir = f"{OUTPUT_DIR}/{file_uuid}/trace_{trace_id}"
if not os.path.exists(trace_dir):
issues.append(f" Trace {trace_id}: directory missing")
continue
key_face = f"{trace_dir}/key_face.jpg"
key_frame = f"{trace_dir}/key_frame.jpg"
if not os.path.exists(key_frame):
issues.append(f" Trace {trace_id}: key_frame.jpg missing")
if not os.path.exists(key_face):
issues.append(f" Trace {trace_id}: key_face.jpg missing")
elif os.path.getsize(key_face) < 4000:
issues.append(f" Trace {trace_id}: key_face.jpg too small ({os.path.getsize(key_face)} bytes)")
return issues
def generate_report(output_file=None):
"""Generate integrity report."""
print("Gathering statistics...\n")
# Get stats
qdrant_stats = get_qdrant_stats()
pg_trace_stats, pg_video_stats = get_postgres_stats()
# Build report
report = []
report.append("# Trace Data Integrity Report")
report.append(f"\n**Generated**: {datetime.now().isoformat()}\n")
# Summary
report.append("## Summary\n")
report.append(f"- Qdrant files: {len(qdrant_stats)}")
report.append(f"- Qdrant points: {sum(s['points'] for s in qdrant_stats.values())}")
report.append(f"- PostgreSQL files with traces: {len(pg_trace_stats)}")
report.append(f"- PostgreSQL total traces: {sum(s['traces'] for s in pg_trace_stats.values())}")
report.append(f"- PostgreSQL valid bbox: {sum(s['valid_bbox'] for s in pg_trace_stats.values())}")
report.append("")
# Issues
report.append("## Issues\n")
# 1. Files in PostgreSQL but not in Qdrant
missing_qdrant = set(pg_trace_stats.keys()) - set(qdrant_stats.keys())
if missing_qdrant:
report.append("### Files missing in Qdrant\n")
for file_uuid in sorted(missing_qdrant):
stats = pg_trace_stats[file_uuid]
name = pg_video_stats.get(file_uuid, {}).get("name", "Unknown")
report.append(f"- {name} ({file_uuid[:16]}...): {stats['traces']} traces")
report.append("")
# 2. Traces with invalid bbox
invalid_bbox_files = []
for file_uuid, stats in pg_trace_stats.items():
if stats['valid_bbox'] < stats['traces']:
invalid_bbox_files.append((file_uuid, stats))
if invalid_bbox_files:
report.append("### Traces with invalid bbox\n")
for file_uuid, stats in sorted(invalid_bbox_files, key=lambda x: -x[1]['traces']):
name = pg_video_stats.get(file_uuid, {}).get("name", "Unknown")
missing = stats['traces'] - stats['valid_bbox']
report.append(f"- {name}: {missing}/{stats['traces']} traces missing valid bbox")
report.append("")
# 3. Orphan records
orphan_files = set(pg_trace_stats.keys()) - set(pg_video_stats.keys())
if orphan_files:
report.append("### Orphan records (no corresponding video)\n")
for file_uuid in sorted(orphan_files):
stats = pg_trace_stats[file_uuid]
report.append(f"- {file_uuid[:16]}...: {stats['traces']} traces")
report.append("")
# Detailed file list
report.append("## Detailed File Statistics\n")
report.append("| File | Traces | Valid Bbox | Qdrant Points | Status |")
report.append("|------|--------|------------|---------------|--------|")
for file_uuid in sorted(set(pg_trace_stats.keys()) | set(qdrant_stats.keys())):
name = pg_video_stats.get(file_uuid, {}).get("name", file_uuid[:16])
trace_stats = pg_trace_stats.get(file_uuid, {"traces": 0, "valid_bbox": 0})
qdrant_stats_file = qdrant_stats.get(file_uuid, {"points": 0})
traces = trace_stats["traces"]
valid_bbox = trace_stats["valid_bbox"]
qdrant_pts = qdrant_stats_file["points"]
# Determine status
if qdrant_pts == 0:
status = "❌ Missing Qdrant"
elif valid_bbox == traces:
status = "✅ Complete"
elif valid_bbox > 0:
status = "⚠️ Partial"
else:
status = "❌ No bbox"
report.append(f"| {name[:30]} | {traces} | {valid_bbox}/{traces} | {qdrant_pts} | {status} |")
# Output
report_text = "\n".join(report)
if output_file:
with open(output_file, "w") as f:
f.write(report_text)
print(f"Report written to: {output_file}")
else:
print(report_text)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Monitor trace data integrity")
parser.add_argument("--output", help="Output report file")
args = parser.parse_args()
generate_report(args.output)
+3 -3
View File
@@ -129,9 +129,9 @@ def push_face_embeddings_batch(file_uuid: str, faces: list, publisher=None) -> i
"bbox": face["bbox"],
"confidence": face.get("confidence", 0.5),
"capture_quality": face.get("capture_quality", 0.0),
"identity_id": None,
"identity_uuid": None,
"stranger_id": None,
"identity_id": 0,
"identity_uuid": "",
"stranger_id": 0,
},
}
)
+722
View File
@@ -0,0 +1,722 @@
#!/opt/homebrew/bin/python3.11
"""
Qdrant _faces and _seeds Collection Operations
Functions for _faces:
- ensure_faces_collection(): Create _faces collection if not exists
- generate_point_id(): Generate consistent point ID
- push_face_embeddings_batch(): Batch push embeddings to Qdrant
- update_trace_ids(): Update trace_id after face tracking
- get_file_faces(): Get all face points for a file
- get_trace_representatives(): Get representative embeddings per trace
Functions for _seeds:
- ensure_seeds_collection(): Create _seeds collection if not exists
- push_seed_embedding(): Push identity seed embedding
- get_seeds(): Get all seed points
- search_seeds(): Cosine search against seeds
- delete_seed(): Delete a seed point
Collection Schema:
- _faces: 512D, Cosine, payload: {file_uuid, frame, trace_id, bbox, confidence, identity_id, identity_uuid, stranger_id}
- _seeds: 512D, Cosine, payload: {identity_id, identity_uuid, name, source, file_uuid, trace_id, tmdb_id, created_at}
"""
import os
import json
import hashlib
import urllib.request
import urllib.error
from typing import Optional
from datetime import datetime
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", "Test3200Test3200Test3200")
FACES_COLLECTION = "_faces"
SEEDS_COLLECTION = "_seeds"
VECTOR_DIM = 512
# Default 1000 (was 100): larger pages cut the number of scroll/set_payload HTTP
# round-trips ~10x on large files (B2). Still overridable via QDRANT_BATCH_SIZE.
BATCH_SIZE = int(os.environ.get("QDRANT_BATCH_SIZE", "1000"))
def qdrant_request(method: str, path: str, body: dict = None) -> dict:
"""Make HTTP request to Qdrant"""
url = f"{QDRANT_URL}{path}"
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read())
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(f"Qdrant HTTP {e.code}: {error_body}")
def ensure_faces_collection() -> bool:
"""Create _faces collection if not exists"""
url = f"{QDRANT_URL}/collections/{FACES_COLLECTION}"
req = urllib.request.Request(url, method="GET")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
return True # Collection exists
except urllib.error.HTTPError as e:
if e.code != 404:
raise RuntimeError(f"Qdrant check failed: {e.read().decode()}")
# Create collection
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")
req.add_header("Content-Type", "application/json")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
print(f"[QDRANT] Created collection: {FACES_COLLECTION}")
return True
except urllib.error.HTTPError as e:
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
def generate_point_id(file_uuid: str, frame: int, trace_id: int = 0) -> int:
"""Generate consistent point ID from file_uuid + frame + trace_id"""
key = f"{file_uuid}_{frame}_{trace_id}"
return int(hashlib.md5(key.encode()).hexdigest()[:16], 16)
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]
points = []
for face in batch:
point_id = generate_point_id(
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),
"capture_quality": face.get("capture_quality", 0.0),
"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}"
)
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, return_trace_ids: bool = False
):
"""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}"
return_trace_ids: If True, also return the set of trace_ids seen during the
scroll. This lets the caller avoid a redundant full collection scan just
to count unique traces (B1 optimization for large files).
Returns:
Number of updated points, or (updated_count, trace_id_set) if return_trace_ids.
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"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
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
# Group point IDs by trace_id
trace_groups = {}
for point in all_points:
point_id = point["id"]
payload = point.get("payload", {})
frame = payload.get("frame")
# Support two bbox formats:
# 1. Nested bbox field
# 2. Direct x, y, width, height fields
bbox = payload.get("bbox", {})
if bbox:
# Format 1: has bbox field
x = bbox.get('x')
y = bbox.get('y')
width = bbox.get('width')
height = bbox.get('height')
else:
# Format 2: direct fields
x = payload.get('x')
y = payload.get('y')
width = payload.get('width')
height = payload.get('height')
if x is None or y is None or width is None or height is None:
continue
bbox_key = f"{x}_{y}_{width}_{height}"
trace_id = trace_mapping.get(frame, {}).get(bbox_key)
if trace_id is None:
continue
if trace_id not in trace_groups:
trace_groups[trace_id] = []
trace_groups[trace_id].append(point_id)
if not trace_groups:
return (0, set()) if return_trace_ids else 0
# 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}")
if return_trace_ids:
return total, set(trace_groups.keys())
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
)
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, 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 if requested)
"""
all_points = []
offset = None
while True:
body = {
"limit": BATCH_SIZE,
"with_payload": True,
"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
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
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
)
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, 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),
}
)
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:
start = points[0]
end = points[-1]
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}"
req = urllib.request.Request(url, method="GET")
req.add_header("Api-Key", QDRANT_API_KEY)
try:
urllib.request.urlopen(req)
return True # Collection exists
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"}}
create_url = f"{QDRANT_URL}/collections/{SEEDS_COLLECTION}"
data = json.dumps(body).encode()
req = urllib.request.Request(create_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] Created collection: {SEEDS_COLLECTION}")
return True
except urllib.error.HTTPError as e:
raise RuntimeError(f"Qdrant create collection failed: {e.read().decode()}")
def push_seed_embedding(
identity_id: int,
identity_uuid: str,
name: str,
embedding: list,
source: str = "tmdb",
file_uuid: str = None,
trace_id: int = None,
tmdb_id: int = None,
) -> bool:
"""Push identity seed embedding to _seeds collection
Args:
identity_id: PG identity.id
identity_uuid: Identity UUID
name: Identity name
embedding: 512D embedding
source: 'tmdb' | 'manual' | 'propagation'
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,
"name": name,
"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,
}
]
}
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})")
return True
except urllib.error.HTTPError as e:
error_body = e.read().decode()
raise RuntimeError(f"Qdrant seed push failed: HTTP {e.code} - {error_body}")
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
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
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:
"""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
)
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,
}
)
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
)
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
)
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:
"""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": 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
)
batch = result.get("result", {}).get("points", [])
if not batch:
break
all_points.extend(batch)
offset = result.get("result", {}).get("next_page_offset")
if not offset:
break
if not all_points:
return 0
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)