Files
momentry_core/scripts/face_pipeline_check.py

361 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3.11
"""
face_pipeline_check.py — Face Pipeline 逐步檢查工具
檢查 face → face_traced → face_cluster → face_groups (DB/API)
用法:
python3.11 face_pipeline_check.py <uuid> [--api-key KEY] [--api-url URL]
python3.11 face_pipeline_check.py <uuid> -q # 快速模式
"""
import json
import sys
import os
import argparse
import urllib.request
import urllib.error
OUTPUT_DIR = '/Users/accusys/momentry/output'
API_KEY_ENV = 'MOMENTRY_API_KEY'
def check_file(uuid):
"""Step 0: 檢查檔案存在"""
files = {
'face': f'{uuid}.face.json',
'traced': f'{uuid}.face_traced.json',
'cluster': f'{uuid}.face_cluster.json',
}
status = {}
missing = []
for name, fname in files.items():
path = os.path.join(OUTPUT_DIR, fname)
exists = os.path.exists(path)
status[name] = exists
if exists:
status[f'{name}_size'] = os.path.getsize(path)
else:
missing.append(fname)
return {'pass': len(missing) == 0, 'missing': missing, **status}
def check_face_json(uuid):
"""Step 1: face.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face.json 不存在']}
d = json.load(open(path))
issues = []
total = d.get('total_faces', 0)
fc = d.get('frame_count', 0)
fps = d.get('fps', 0)
frames = d.get('frames') or []
if fc == 0:
issues.append('frame_count = 0(影片沒有被取幀)')
if fps > 0 and fps < 1:
issues.append(f'fps = {fps} (< 1,異常)')
if len(frames) != fc:
issues.append(f'frames 列表數量 {len(frames)} != frame_count {fc}')
# embedding 檢查
emb_total = 0
emb_missing = 0
emb_bad = 0
for fr in frames:
for fa in fr.get('faces') or []:
emb_total += 1
emb = fa.get('embedding')
if emb is None:
emb_missing += 1
elif not isinstance(emb, list) or len(emb) != 512:
emb_bad += 1
elif not all(isinstance(v, (int, float)) for v in emb):
emb_bad += 1
if emb_missing:
issues.append(f'embedding: {emb_missing}/{emb_total} faces 缺少')
if emb_bad:
issues.append(f'embedding: {emb_bad}/{emb_total} faces 非 512D 或格式異常')
return {
'pass': len(issues) == 0,
'total_faces': total,
'frame_count': fc,
'embedding_total': emb_total,
'embedding_missing': emb_missing,
'embedding_bad': emb_bad,
'issues': issues,
}
def check_face_traced(uuid, face_result):
"""Step 2: face_traced.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_traced.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_traced.json 不存在']}
d = json.load(open(path))
issues = []
traces_raw = d.get('traces') or []
# Normalize: dict (string keys) → list
if isinstance(traces_raw, dict):
traces = list(traces_raw.values())
elif isinstance(traces_raw, list):
traces = traces_raw
else:
traces = []
if not traces:
issues.append('traces 為空(沒有產生任何 trace)')
return {'pass': False, 'trace_count': 0, 'issues': issues}
# trace_id 唯一
tids = [t['trace_id'] for t in traces]
if len(tids) != len(set(tids)):
issues.append(f'trace_id 重複: {len(tids)} rows, {len(set(tids))} unique')
# confidence 範圍 & frame_count 合理性
total_frames_traced = 0
for t in traces:
fc = t.get('frame_count', 0)
if fc < 1:
issues.append(f'trace {t["trace_id"]}: frame_count = {fc} (< 1)')
total_frames_traced += fc
bc = t.get('best_confidence', -1)
ac = t.get('avg_confidence', -1)
if not (0 <= bc <= 1):
issues.append(f'trace {t["trace_id"]}: best_confidence = {bc}')
if not (0 <= ac <= 1):
issues.append(f'trace {t["trace_id"]}: avg_confidence = {ac}')
# face_instances 指向有效性(抽樣檢查)
all_face_ids = set()
face_json_frames = []
if os.path.exists(os.path.join(OUTPUT_DIR, f'{uuid}.face.json')):
fd = json.load(open(os.path.join(OUTPUT_DIR, f'{uuid}.face.json')))
for fr in fd.get('frames') or []:
for fa in fr.get('faces') or []:
fid = fa.get('face_id')
if fid:
all_face_ids.add(fid)
orphan_instances = 0
if all_face_ids:
for t in traces[:5]: # 抽樣前 5 筆
for fi in t.get('face_instances', []):
if fi.get('face_id') and fi['face_id'] not in all_face_ids:
orphan_instances += 1
if orphan_instances:
issues.append(f'face_instances: 抽樣發現 {orphan_instances} 個無效 face_id')
return {
'pass': len(issues) == 0,
'trace_count': len(traces),
'total_frames_traced': total_frames_traced,
'issues': issues,
}
def check_face_cluster(uuid, traced_result):
"""Step 3: face_cluster.json 驗證"""
path = os.path.join(OUTPUT_DIR, f'{uuid}.face_cluster.json')
if not os.path.exists(path):
return {'pass': False, 'issues': ['face_cluster.json 不存在']}
d = json.load(open(path))
issues = []
clusters = d.get('clusters') or []
frames = d.get('frames') or []
if not clusters:
issues.append('clusters 為空(可能 threshold 太高或人臉太少)')
# cluster_id 唯一
if clusters:
cids = [c['cluster_id'] for c in clusters]
if len(cids) != len(set(cids)):
issues.append('cluster_id 有重複')
# similarity 結構檢查
for c in clusters[:10]: # 抽樣
sim = c.get('similarity') or {}
for key in ['min', 'avg', 'threshold']:
if key not in sim:
issues.append(f'cluster "{c["cluster_id"]}" 缺少 similarity.{key}')
elif not isinstance(sim[key], (int, float)):
issues.append(f'cluster "{c["cluster_id"]}" similarity.{key} 非數值')
# frame faces 完整性
frame_faces = []
for f in frames:
for fa in f.get('faces') or []:
frame_faces.append(fa)
if not frame_faces and clusters:
issues.append('clusters 有資料但 frames 中沒有 faces')
# cluster_id 一致性
if clusters:
valid_cids = set(c['cluster_id'] for c in clusters)
bad = sum(1 for fa in frame_faces if fa.get('cluster_id') not in valid_cids)
if bad:
issues.append(f'{bad} frame faces 的 cluster_id 不在 clusters 列表中')
# trace_id 存在
no_trace = sum(1 for fa in frame_faces if fa.get('trace_id') is None)
if no_trace:
issues.append(f'{no_trace} frame faces 缺少 trace_id')
return {
'pass': len(issues) == 0,
'cluster_count': len(clusters),
'frame_face_count': len(frame_faces),
'issues': issues,
}
def check_api(uuid, api_key, api_url):
"""Step 4: API 回應驗證"""
issues = []
headers = {'X-API-Key': api_key}
url = f'{api_url}/api/v1/cluster-results?file_hash={uuid}'
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as resp:
if resp.status != 200:
issues.append(f'cluster-results HTTP {resp.status}')
return {'pass': False, 'issues': issues}
d = json.loads(resp.read())
except urllib.error.HTTPError as e:
issues.append(f'cluster-results HTTP {e.code}: {e.read().decode()[:200]}')
return {'pass': False, 'issues': issues}
except Exception as e:
issues.append(f'cluster-results 請求失敗: {e}')
return {'pass': False, 'issues': issues}
groups = d.get('face_groups', [])
frames = d.get('frames', [])
if not groups:
issues.append('face_groups 為空')
else:
# 檢查是否有群組 trace_ids 全空
empty_groups = [g for g in groups if not g.get('trace_ids')]
if empty_groups:
issues.append(
f'{len(empty_groups)} 個群組 trace_ids 為空: '
f'[{", ".join(g["name"] for g in empty_groups[:5])}]'
)
# frames faces 完整性
f_faces = []
for f in frames:
for fa in f.get('faces') or []:
f_faces.append(fa)
no_trace = sum(1 for fa in f_faces if fa.get('trace_id') is None)
if no_trace:
issues.append(f'{no_trace} API frame faces 缺少 trace_id')
# cluster_id → group_id 映射
if groups and f_faces:
group_ids = {g['group_id'] for g in groups}
bad_cids = set()
for fa in f_faces:
cid = fa.get('cluster_id')
if cid and cid not in group_ids:
bad_cids.add(cid)
if bad_cids:
issues.append(f'{len(bad_cids)} frame faces 的 cluster_id 無法映射到 group_id')
return {
'pass': len(issues) == 0,
'group_count': len(groups),
'frame_count': len(frames),
'total_traces': sum(len(g.get('trace_ids', [])) for g in groups),
'issues': issues,
}
def main():
parser = argparse.ArgumentParser(description='Face Pipeline 逐步檢查工具')
parser.add_argument('uuid', help='file_uuid 要檢查')
parser.add_argument('--api-key', default=os.environ.get(API_KEY_ENV, ''),
help=f'API key(預設取自 {API_KEY_ENV})')
parser.add_argument('--api-url', default='http://localhost:3002', help='API base URL')
parser.add_argument('--quiet', '-q', action='store_true', help='快速模式(只輸出 PASS/FAIL)')
args = parser.parse_args()
if not args.api_key:
print(f'⚠️ 未提供 API key,設定 {API_KEY_ENV} 或使用 --api-key')
results = {'uuid': args.uuid, 'steps': {}}
overall_pass = True
# Step 0: 檔案存在
r0 = check_file(args.uuid)
results['steps']['0_files'] = r0
if not r0['pass']:
overall_pass = False
# Step 1: face.json
r1 = check_face_json(args.uuid)
results['steps']['1_face_json'] = r1
if not r1['pass']:
overall_pass = False
# Step 2: face_traced.json
r2 = check_face_traced(args.uuid, r1)
results['steps']['2_face_traced'] = r2
if not r2['pass']:
overall_pass = False
# Step 3: face_cluster.json
r3 = check_face_cluster(args.uuid, r2)
results['steps']['3_face_cluster'] = r3
if not r3['pass']:
overall_pass = False
# Step 4: API/DB
r4 = check_api(args.uuid, args.api_key, args.api_url)
results['steps']['4_api'] = r4
if not r4['pass']:
overall_pass = False
# Print results
if args.quiet:
print('✅ PASS' if overall_pass else '❌ FAIL')
for name, r in results['steps'].items():
if r.get('issues'):
for i in r['issues']:
print(f' {name}: {i}')
else:
print(f'\n{"=" * 60}')
print(f'Face Pipeline Check: {args.uuid}')
print(f'{"=" * 60}\n')
for name, r in results['steps'].items():
icon = '✅' if r.get('pass', True) else '❌'
print(f'{icon} {name}')
if r.get('issues'):
for i in r['issues']:
print(f' ⚠️ {i}')
for key in ['total_faces', 'frame_count', 'embedding_total', 'embedding_missing',
'trace_count', 'cluster_count', 'frame_face_count', 'group_count',
'frame_count', 'total_traces']:
if key in r:
print(f' {key}: {r[key]}')
print()
print(f'Overall: {"✅ PASS" if overall_pass else "❌ FAIL"}\n')
return 0 if overall_pass else 1
if __name__ == '__main__':
sys.exit(main())