Files
momentry_core/scripts/verify_face_cluster.py
T
Accusys e25c279eeb feat: port face clustering to Rust (rust_face_cluster) with A/B gating
- rust_face_cluster: seed-leader + agglomerative clustering port of
  fast_face_clustering_processor.py (Qdrant _faces scroll, trace aggregation,
  auto speaker bind, strict 2dp rounding parity)
- A/B verified vs Python on same Qdrant snapshot: both methods match on
  cluster membership/trace_id/confidence (leader + agglomerative)
- face_clustering.rs: USE_RUST_PROCESSORS switch with Python fallback
- executor.rs: run_rust_with_output_idx_and_frames (+ QDRANT env passthrough)
- appearance/pose: re-use rust runner path (previous migration)
- verify_face_cluster.py / verify_pose.py / verify_appearance.py: A/B harness
2026-09-16 21:50:07 +08:00

225 lines
7.5 KiB
Python

#!/opt/homebrew/bin/python3.11
"""
A/B verify: Python fast_face_clustering_processor.py vs rust_face_cluster.
Runs both against the SAME Qdrant _faces data and SAME face.json/face_traced.json
inputs. Compares:
- cluster membership correspondence (trace_id -> person mapping)
- cluster_id set equivalence (members may be renumbered, but must match)
- representative_face face_id / frame / bbox equality
- output frame face_id / cluster / trace / confidence equality
Usage:
verify_face_cluster.py <video> <uuid> <outdir> [--method leader|agglomerative]
"""
import argparse
import json
import os
import subprocess
import sys
import tempfile
from collections import defaultdict
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PY_SCRIPT = os.path.join(SCRIPT_DIR, "fast_face_clustering_processor.py")
RUST_BIN = os.path.join(
SCRIPT_DIR, "rust_processors", "target", "release", "rust_face_cluster"
)
def norm_mapping(trace_to_person: dict) -> dict:
"""Renumber person labels per trace set so order doesn't matter."""
return trace_to_person
def load_cluster_json(path: str) -> dict:
with open(path) as f:
return json.load(f)
def mapping_from_output(output: dict) -> dict:
"""Rebuild {trace_id: cluster_id_renormalized} from frames section."""
trace_to_person = {}
for frame in output.get("frames", []):
for face in frame.get("faces", []):
tid = face.get("trace_id")
if tid is not None:
trace_to_person[tid] = face.get("cluster_id")
# Renormalize: sort trace_ids by cluster id assignment → integer labels.
# Group traces by raw cluster_id, then sort clusters by first-seen trace.
clusters = defaultdict(list)
for tid, cid in trace_to_person.items():
clusters[cid].append(tid)
# order by min trace_id within cluster (deterministic)
ordered = sorted(clusters.items(), key=lambda kv: min(kv[1]))
renum = {old: new for new, (old, _) in enumerate(ordered)}
return {tid: renum[cid] for tid, cid in trace_to_person.items()}
def compare(output_py, output_rust, method):
errors = []
status_py = output_py.get("status")
status_rust = output_rust.get("status")
if status_py != status_rust:
errors.append(f"status mismatch: {status_py} vs {status_rust}")
frames_py = output_py.get("frames", [])
frames_rust = output_rust.get("frames", [])
if len(frames_py) != len(frames_rust):
errors.append(f"frame count mismatch: {len(frames_py)} vs {len(frames_rust)}")
# Compare per-frame face assignments (face_id is the key).
map_py = {}
map_rust = {}
for frame in frames_py:
for face in frame.get("faces", []):
map_py[face["face_id"]] = face
for frame in frames_rust:
for face in frame.get("faces", []):
map_rust[face["face_id"]] = face
if set(map_py.keys()) != set(map_rust.keys()):
errors.append(
f"face_id set mismatch: {len(map_py)} vs {len(map_rust)}"
)
return errors
# Renumber both cluster_id sets so labels are comparable.
cluster_renum = {}
for fid, face in sorted(map_py.items(), key=lambda kv: kv[1].get("trace_id") or 0):
cid = face["cluster_id"]
if cid not in cluster_renum:
cluster_renum[cid] = len(cluster_renum)
map_py_renum = {fid: cluster_renum.get(f["cluster_id"]) for fid, f in map_py.items()}
cluster_renum_r = {}
for fid, face in sorted(map_rust.items(), key=lambda kv: kv[1].get("trace_id") or 0):
cid = face["cluster_id"]
if cid not in cluster_renum_r:
cluster_renum_r[cid] = len(cluster_renum_r)
map_rust_renum = {fid: cluster_renum_r.get(f["cluster_id"]) for fid, f in map_rust.items()}
metric = method
cluster_mismatch = 0
trace_mismatch = 0
conf_mismatch = 0
for fid in map_py.keys():
f_py = map_py[fid]
f_rust = map_rust[fid]
if map_py_renum[fid] != map_rust_renum[fid]:
cluster_mismatch += 1
if f_py.get("trace_id") != f_rust.get("trace_id"):
trace_mismatch += 1
if abs((f_py.get("confidence") or 0) - (f_rust.get("confidence") or 0)) > 1e-9:
conf_mismatch += 1
if cluster_mismatch == 0:
print(f" [{metric}] cluster_id assignments: MATCH ({len(map_py)} faces)")
else:
errors.append(
f" [{metric}] {cluster_mismatch}/{len(map_py)} faces have different cluster after renumber"
)
if trace_mismatch == 0:
print(f" [{metric}] trace_id: MATCH")
else:
errors.append(f" [{metric}] {trace_mismatch} trace_id mismatches")
if conf_mismatch == 0:
print(f" [{metric}] confidence: MATCH")
else:
errors.append(f" [{metric}] {conf_mismatch} confidence mismatches")
# Compare cluster-level stats (counts, representative face).
clusters_py = {c["cluster_id"]: c for c in output_py.get("clusters", [])}
clusters_rust = {c["cluster_id"]: c for c in output_rust.get("clusters", [])}
if set(clusters_py.keys()) != set(clusters_rust.keys()):
errors.append(
f"cluster_id key set mismatch: {sorted(clusters_py.keys())} vs {sorted(clusters_rust.keys())}"
)
# Map Python cluster -> Rust cluster by member traces (frame-level).
py_cluster_members = defaultdict(set)
rust_cluster_members = defaultdict(set)
for fid, label in map_py_renum.items():
py_cluster_members[label].add(fid)
for fid, label in map_rust_renum.items():
rust_cluster_members[label].add(fid)
for label_py, members_py in py_cluster_members.items():
match = None
for label_r, members_r in rust_cluster_members.items():
if members_py == members_r:
match = label_r
break
if match is None:
errors.append(
f"cluster {label_py} (py, {len(members_py)} members) has no equivalent in rust"
)
print(f" [{metric}] cluster correspondence: {'MATCH' if not errors else 'MISMATCH'}")
return errors
def main():
parser = argparse.ArgumentParser()
parser.add_argument("video")
parser.add_argument("uuid")
parser.add_argument("outdir", help="dir containing face.json/face_traced.json/asrx.json")
parser.add_argument("--method", default="leader", choices=["leader", "agglomerative"])
args = parser.parse_args()
py_out = os.path.join(args.outdir, "ab_python.json")
rust_out = os.path.join(args.outdir, "ab_rust.json")
env = dict(os.environ)
env["MOMENTRY_OUTPUT_DIR"] = args.outdir
print(f"Running Python ({args.method}) ...")
subprocess.run(
[
sys.executable,
PY_SCRIPT,
args.video,
py_out,
"--uuid",
args.uuid,
"--method",
args.method,
],
check=True,
env=env,
capture_output=True,
text=True,
)
print(f"Running Rust ({args.method}) ...")
subprocess.run(
[
RUST_BIN,
args.video,
rust_out,
"--uuid",
args.uuid,
"--method",
args.method,
],
check=True,
env=env,
capture_output=True,
text=True,
)
output_py = load_cluster_json(py_out)
output_rust = load_cluster_json(rust_out)
errors = compare(output_py, output_rust, args.method)
if errors:
print("\nFAIL")
for e in errors:
print(" -", e)
sys.exit(1)
print("\nPASS")
if __name__ == "__main__":
main()