#!/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())