feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
This commit is contained in:
@@ -12,20 +12,28 @@ MODEL = None
|
||||
TOKENIZER = None
|
||||
DEVICE = None
|
||||
|
||||
def load_model(model_path: str = "google/embeddinggemma-300m"):
|
||||
def load_model(model_path: str = ""):
|
||||
global MODEL, TOKENIZER, DEVICE
|
||||
if MODEL is not None:
|
||||
return
|
||||
import os
|
||||
# 一律使用本地模型目錄,絕不上網
|
||||
local = os.path.expanduser("~/momentry/models/embeddinggemma-300m")
|
||||
if not (os.path.isdir(local) and os.path.isfile(os.path.join(local, "config.json"))):
|
||||
raise RuntimeError(
|
||||
f"[EmbeddingGemma] Local model not found at {local}. "
|
||||
"Please copy the model files (config.json, model.safetensors, tokenizer*) to this directory."
|
||||
)
|
||||
DEVICE = "mps" if torch.backends.mps.is_available() else "cpu"
|
||||
dtype = torch.float32
|
||||
print(f"[EmbeddingGemma] Loading model on {DEVICE} (dtype={dtype})...")
|
||||
print(f"[EmbeddingGemma] Loading model from local: {local} on {DEVICE} (dtype={dtype})...")
|
||||
t0 = time.time()
|
||||
MODEL = AutoModel.from_pretrained(
|
||||
model_path,
|
||||
local,
|
||||
torch_dtype=dtype,
|
||||
trust_remote_code=True,
|
||||
).eval().to(DEVICE)
|
||||
TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
||||
TOKENIZER = AutoTokenizer.from_pretrained(local, trust_remote_code=True)
|
||||
print(f"[EmbeddingGemma] Loaded in {time.time()-t0:.1f}s on {DEVICE}")
|
||||
|
||||
def embed(texts: list[str]) -> list[list[float]]:
|
||||
@@ -79,7 +87,6 @@ def health():
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--port", type=int, default=11436)
|
||||
parser.add_argument("--model", type=str, default="google/embeddinggemma-300m")
|
||||
args = parser.parse_args()
|
||||
load_model(args.model)
|
||||
load_model() # 一律使用 ~/momentry/models/embeddinggemma-300m,絕不上網
|
||||
app.run(host="0.0.0.0", port=args.port, threaded=True)
|
||||
|
||||
@@ -171,7 +171,29 @@ def cluster_by_trace(
|
||||
return trace_embeddings, traces
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
def build_cooccurrence_constraints(frames_data: list) -> set:
|
||||
"""
|
||||
Build must-not-link constraints: traces appearing in same frame must be different persons.
|
||||
Returns set of (trace_id_a, trace_id_b) pairs.
|
||||
"""
|
||||
constraints = set()
|
||||
for frame in frames_data:
|
||||
trace_ids = set()
|
||||
for face in frame.get('faces', []):
|
||||
tid = face.get('trace_id')
|
||||
if tid is not None and tid >= 0:
|
||||
trace_ids.add(tid)
|
||||
# All traces in same frame must be different persons
|
||||
trace_list = list(trace_ids)
|
||||
for i in range(len(trace_list)):
|
||||
for j in range(i+1, len(trace_list)):
|
||||
constraints.add((min(trace_list[i], trace_list[j]),
|
||||
max(trace_list[i], trace_list[j])))
|
||||
return constraints
|
||||
|
||||
|
||||
def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15,
|
||||
cooccurrence_constraints: set = None, frames_data: list = None) -> tuple:
|
||||
"""
|
||||
Single-stage AgglomerativeClustering on trace means.
|
||||
No Stage 2 merge (the problematic logic has been removed).
|
||||
@@ -210,13 +232,67 @@ def single_stage_clustering(trace_embeddings: dict, threshold: float = 0.15) ->
|
||||
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
|
||||
trace_similarities[trace_id] = 1.0
|
||||
|
||||
# Post-process: split clusters that violate co-occurrence constraints
|
||||
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
|
||||
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
|
||||
next_person_id = max(trace_to_person.values()) + 1
|
||||
|
||||
for tid_a, tid_b in cooccurrence_constraints:
|
||||
if trace_to_person.get(tid_a) == trace_to_person.get(tid_b):
|
||||
# Same cluster but shouldn't be - split the one with fewer faces
|
||||
count_a = trace_embeddings.get(tid_a, {}).get('face_count', 0)
|
||||
count_b = trace_embeddings.get(tid_b, {}).get('face_count', 0)
|
||||
if count_a <= count_b:
|
||||
trace_to_person[tid_a] = next_person_id
|
||||
print(f" Split trace {tid_a} from {tid_b} (faces: {count_a} vs {count_b})")
|
||||
else:
|
||||
trace_to_person[tid_b] = next_person_id
|
||||
print(f" Split trace {tid_b} from {tid_a} (faces: {count_a} vs {count_b})")
|
||||
next_person_id += 1
|
||||
|
||||
# Merge clusters that are actually the same person (high embedding similarity)
|
||||
print(f"[CLUSTER] Merging similar persons (threshold={threshold*0.3:.2f})...")
|
||||
merge_threshold = threshold * 0.3 # More conservative for merging
|
||||
person_embeddings = {}
|
||||
for tid, pid in trace_to_person.items():
|
||||
if tid in trace_embeddings:
|
||||
if pid not in person_embeddings:
|
||||
person_embeddings[pid] = []
|
||||
person_embeddings[pid].append(trace_embeddings[tid]['embedding'])
|
||||
|
||||
# Compute person mean embeddings
|
||||
person_means = {}
|
||||
for pid, embs in person_embeddings.items():
|
||||
person_means[pid] = np.mean(embs, axis=0)
|
||||
|
||||
# Find and merge similar persons
|
||||
pids = list(person_means.keys())
|
||||
for i in range(len(pids)):
|
||||
for j in range(i+1, len(pids)):
|
||||
pid_i, pid_j = pids[i], pids[j]
|
||||
emb_i = person_means[pid_i]
|
||||
emb_j = person_means[pid_j]
|
||||
sim = np.dot(emb_i, emb_j) / (np.linalg.norm(emb_i) * np.linalg.norm(emb_j))
|
||||
dist = 1 - sim
|
||||
if dist < merge_threshold:
|
||||
# Merge pid_j into pid_i
|
||||
for tid in trace_to_person:
|
||||
if trace_to_person[tid] == pid_j:
|
||||
trace_to_person[tid] = pid_i
|
||||
print(f" Merged Person_{pid_j} into Person_{pid_i} (dist={dist:.3f})")
|
||||
|
||||
# Reindex person IDs
|
||||
unique_pids = sorted(set(trace_to_person.values()))
|
||||
pid_map = {old: new for new, old in enumerate(unique_pids)}
|
||||
trace_to_person = {tid: pid_map[pid] for tid, pid in trace_to_person.items()}
|
||||
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tuple:
|
||||
def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15,
|
||||
cooccurrence_constraints: set = None) -> tuple:
|
||||
"""
|
||||
Seed-leader clustering with incremental mean centroids.
|
||||
Algorithm:
|
||||
@@ -302,6 +378,39 @@ def seed_leader_cluster(trace_embeddings: dict, threshold: float = 0.15) -> tupl
|
||||
trace_to_person[tid] = person_label
|
||||
|
||||
print(f"[CLUSTER] Seed-leader detected {len(persons)} unique persons")
|
||||
|
||||
# Apply co-occurrence constraints: split traces that appear in same frame
|
||||
if cooccurrence_constraints and len(cooccurrence_constraints) > 0:
|
||||
print(f"[CLUSTER] Applying {len(cooccurrence_constraints)} co-occurrence constraints...")
|
||||
|
||||
# Build trace_id -> person mapping for fast lookup
|
||||
for tid_a, tid_b in cooccurrence_constraints:
|
||||
person_a = trace_to_person.get(tid_a)
|
||||
person_b = trace_to_person.get(tid_b)
|
||||
if person_a is not None and person_b is not None and person_a == person_b:
|
||||
# Same person but shouldn't be - split tid_b to new person
|
||||
new_person_label = len(persons)
|
||||
trace_to_person[tid_b] = new_person_label
|
||||
# Move trace from old person to new person
|
||||
old_person = persons[person_a]
|
||||
if tid_b in old_person["member_trace_ids"]:
|
||||
old_person["member_trace_ids"].remove(tid_b)
|
||||
# Create new person with just this trace
|
||||
if tid_b in trace_embeddings:
|
||||
persons.append({
|
||||
"centroid": trace_embeddings[tid_b]['embedding'].copy(),
|
||||
"member_trace_ids": [tid_b]
|
||||
})
|
||||
print(f" Split trace {tid_b} from Person_{person_a} (co-occurs with trace {tid_a})")
|
||||
|
||||
# Rebuild trace_to_person after splits
|
||||
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] After constraints: {len(persons)} unique persons")
|
||||
|
||||
return trace_to_person, trace_similarities
|
||||
|
||||
|
||||
@@ -466,13 +575,40 @@ def main():
|
||||
# Select clustering method
|
||||
threshold = args.threshold
|
||||
method = args.method
|
||||
|
||||
# Load face_traced.json to build co-occurrence constraints AND for later use
|
||||
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
|
||||
cooccurrence_constraints = set()
|
||||
traced_frames_dict = {} # Will be used later for person_id assignment
|
||||
if os.path.exists(traced_path):
|
||||
try:
|
||||
with open(traced_path) as f:
|
||||
traced_data = json.load(f)
|
||||
frames_raw = traced_data.get('frames', [])
|
||||
|
||||
# Build co-occurrence constraints
|
||||
cooccurrence_constraints = build_cooccurrence_constraints(frames_raw)
|
||||
print(f"[CONSTRAINT] Built {len(cooccurrence_constraints)} co-occurrence constraints from face_traced.json")
|
||||
|
||||
# Also build traced_frames_dict for later use
|
||||
if isinstance(frames_raw, list):
|
||||
for frame_obj in frames_raw:
|
||||
frame_num = frame_obj.get("frame")
|
||||
if frame_num is not None:
|
||||
traced_frames_dict[str(frame_num)] = frame_obj
|
||||
elif isinstance(frames_raw, dict):
|
||||
traced_frames_dict = frames_raw
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
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
|
||||
trace_embeddings, threshold=threshold,
|
||||
cooccurrence_constraints=cooccurrence_constraints
|
||||
)
|
||||
if not trace_to_person:
|
||||
print("Clustering produced no results.")
|
||||
@@ -484,35 +620,12 @@ 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")
|
||||
|
||||
# Load face_traced.json to get trace_id for each face
|
||||
traced_path = os.path.join(output_dir, f"{uuid}.face_traced.json")
|
||||
traced_frames = {}
|
||||
if os.path.exists(traced_path):
|
||||
try:
|
||||
with open(traced_path) as f:
|
||||
traced_data = json.load(f)
|
||||
frames_raw = traced_data.get("frames", {})
|
||||
# Handle both dict and list formats
|
||||
if isinstance(frames_raw, list):
|
||||
# Convert list to dict for backward compatibility
|
||||
for frame_obj in frames_raw:
|
||||
frame_num = frame_obj.get("frame")
|
||||
if frame_num is not None:
|
||||
traced_frames[str(frame_num)] = frame_obj
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (converted from list)")
|
||||
elif isinstance(frames_raw, dict):
|
||||
traced_frames = frames_raw
|
||||
print(f" Loaded face_traced.json: {len(traced_frames)} frames (dict)")
|
||||
else:
|
||||
print(f" Warning: Unexpected frames format: {type(frames_raw)}")
|
||||
except Exception as e:
|
||||
print(f" Warning: Failed to load face_traced.json: {e}")
|
||||
|
||||
# Use traced_frames_dict loaded earlier for person_id assignment
|
||||
matched_count = 0
|
||||
for frame_idx, frame_obj in enumerate(frames_list):
|
||||
frame_num = frame_obj.get("frame", frame_idx)
|
||||
# Get traced faces for this frame
|
||||
traced_frame = traced_frames.get(str(frame_num), {})
|
||||
traced_frame = traced_frames_dict.get(str(frame_num), {})
|
||||
traced_faces = traced_frame.get("faces", [])
|
||||
|
||||
for face_idx, face in enumerate(frame_obj.get("faces", [])):
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
#!/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())
|
||||
Reference in New Issue
Block a user