CRICKET / code /tests /test_multiview.py
d9993r's picture
Add files using upload-large-folder tool
14c58d8 verified
Raw History Blame Contribute Delete
5.15 kB
"""Multi-view self-test (about a minute, no GPU): python code/tests/test_multiview.py
A synthetic 3D nets scene is filmed by four cameras that start recording at different
times (C1 bowler side, C2 behind the bowler, C3 batter side, C4 front of the batter).
Checks that the pipeline:
- syncs the cameras (audio + release) to the true offsets,
- turns 12 per-view deliveries into 3 multi-view deliveries,
- calibrates every camera in 3D from clicked pitch points only,
- triangulates release point, bounce, speed and the bowling elbow to ground truth,
- keeps all views of a delivery in the same release split and tags SFT rows with one sample id."""
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
CODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(CODE))
def main():
from tests import synthetic_multiview as S
tmp = Path(tempfile.mkdtemp())
shutil.copytree(CODE, tmp / "code", ignore=shutil.ignore_patterns("__pycache__"))
cfgp = tmp / "code" / "config.yaml"
c = cfgp.read_text().replace("device: auto ", "device: cpu ").replace(''' sessions: []
# - id: MV_NETS_20261020''', ''' sessions:
- id: MV_TEST
reference: C2
views:
C1: 4_Phone-Sessions/session_C1.mp4
C2: 4_Phone-Sessions/session_C2.mp4
C3: 4_Phone-Sessions/session_C3.mp4
C4: 4_Phone-Sessions/session_C4.mp4
# - id: MV_NETS_20261020''')
cfgp.write_text(c)
S.make_videos(tmp / "datasets" / "4_Phone-Sessions")
run = lambda *a: subprocess.run([sys.executable, str(tmp / "code" / "run_all.py"), "--backend", "fake_mv", *a],
capture_output=True, text=True, check=True)
run()
R = tmp / "results"
sync = json.load(open(R / "multiview" / "MV_TEST" / "session.json"))["sync"]
for cid, (_, _, _, off) in S.CAMS.items():
assert abs(sync[cid]["shift_s"] - off) < 0.02, (cid, sync[cid], off)
mv = [json.loads(l) for l in open(R / "jsonl" / "multiview_deliveries.jsonl")]
assert len(mv) == 3 and all(m["n_views"] == 4 for m in mv), [m["n_views"] for m in mv]
# a reviewer clicks the visible pitch points in each camera
sys.path.insert(0, str(tmp / "code"))
from common import load_ontology
from review import stamp, validate, load_people
onto, people = load_ontology(), load_people()
src = {s["path"].split("_")[-1][:2]: s for s in json.load(open(R / "registry" / "sources.json"))}
(R / "annotations").mkdir(exist_ok=True)
with open(R / "annotations" / "review.jsonl", "a") as f:
for cid in S.CAMS:
s = src[cid]
ref = sorted(p for p in os.listdir(R / "deliveries") if p.startswith(s["session_id"]))[0]
rec = {"kind": "calibration", "source_id": s["source_id"], "annotator_id": "reviewer_01",
"value": {"named_px": S.clicks(cid), "camera_end": "bowler", "ref_delivery_id": ref}}
assert validate(rec, onto, people) is None, validate(rec, onto, people)
f.write(json.dumps(stamp(rec, onto)) + "\n")
run("--stages", "sft,tables,evaluate,release,web")
cams = json.load(open(R / "multiview" / "MV_TEST" / "session.json"))["cameras"]
for cid, (pos, _, focal, _) in S.CAMS.items():
cc = cams[cid]
assert cc["reprojection_px"] < 0.5 and abs(cc["focal_px"] - focal) / focal < 0.02, (cid, cc)
assert sum((a - b) ** 2 for a, b in zip(cc["position_m"], pos)) ** 0.5 < 0.15, (cid, cc["position_m"], pos)
mv = [json.loads(l) for l in open(R / "jsonl" / "multiview_deliveries.jsonl")]
for m, r in zip(mv, S.RELEASES):
b, p = m["ball_3d"], m["bowler_3d_release"]
truth_rel = S.bowler3d(r)[10]
bt, _ = S.bounce_truth(r)
assert sum((a - b_) ** 2 for a, b_ in zip(b["release_xyz"], truth_rel)) ** 0.5 < 0.1, (b["release_xyz"], truth_rel)
assert abs(b["bounce_xyz"][1] - bt[1]) < 0.15, (b["bounce_xyz"], bt)
assert abs(b["speed_kmh"] - 108.4) < 2.5, b["speed_kmh"]
assert abs(p["elbow_angle_deg"] - 180) < 3, p["elbow_angle_deg"]
rel = json.load(open(R / "releases" / "latest.json"))
assert not rel["leaks"]
splits = {}
for sp in ("train", "val", "test"):
for l in open(R / "releases" / rel["release_id"] / f"manifest_{sp}.jsonl"):
splits[json.loads(l)["delivery_id"]] = sp
for m in mv:
assert len({splits.get(v["delivery_id"]) for v in m["views"]}) == 1, "views of one delivery split apart"
sft = [json.loads(l) for l in open(R / "jsonl" / "sft_records.jsonl")]
mv_ids = {m["mv_delivery_id"] for m in mv}
assert any(r["task"] == "mv_speed" and len(r["media"]["videos"]) == 4 for r in sft)
assert all(r["sample_id"] in mv_ids for r in sft if r.get("view"))
print(f"ok multi-view: 4 cameras synced and calibrated, 12 views -> {len(mv)} deliveries, "
f"speed {mv[0]['ball_3d']['speed_kmh']} km/h, release {mv[0]['ball_3d']['release_xyz']}, "
f"elbow {mv[0]['bowler_3d_release']['elbow_angle_deg']}°, splits keep views together")
shutil.rmtree(tmp)
if __name__ == "__main__":
main()