File size: 13,101 Bytes
14c58d8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | """Self-test with no GPU, no models and no real videos:
python code/tests/test_pipeline.py
1. event detectors recover all known timeline events on synthetic keypoints
2. the full pipeline runs on a synthetic nets video in a temporary copy of the project
3. reviewer edits (event correction and removal, labels, coach note, calibration,
gold status) flow into SFT, Tier-1 tables and the release; bad edits are rejected
"""
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
import numpy as np
import yaml
CODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(CODE))
from events import (find_batter_trigger, find_bfc, find_bounce, find_contact, find_ffc, # noqa: E402
find_followthrough_end, find_releases, find_runup_start, find_shot_end, link_ball)
from tests import synthetic as syn # noqa: E402
cfg = yaml.safe_load(open(CODE / "config.yaml"))
FR = 1 / syn.FPS
def test_events():
t = np.arange(0, syn.DUR, FR)
k = np.stack([syn.skeleton(x) for x in t])
rel = find_releases(t, k, 1.0, cfg["release"])
assert [round(r["t"], 2) for r in rel] == syn.RELEASES, rel
for r in rel:
f = find_ffc(t, k, r["i"], r["side"], 1.0, cfg["ffc"])
b = find_bfc(t, k, f["i"], r["side"], 1.0, cfg["ffc"])
ru = find_runup_start(t, k, b["i"], 1.0, cfg["ffc"])
ft = find_followthrough_end(t, k, r["i"], r["side"], 1.0, cfg["ffc"])
assert abs(r["t"] - f["t"] - syn.FFC_LEAD) <= 2 * FR, f
assert abs(r["t"] - b["t"] - syn.BFC_LEAD) <= 3 * FR, b
assert abs(r["t"] - ru["t"] - syn.RUNUP_LEAD) <= 3 * FR, ru
assert ft and 0.1 < ft["t"] - r["t"] < 1.0, ft
seq = [(x, [syn.ball(x) + (0.6,)] if syn.ball(x) else []) for x in np.arange(8, 9.2, FR)]
tr = link_ball(seq, syn.skeleton(8.0)[10, :2], syn.TORSO, 1.0)
bo = find_bounce(tr)
assert abs(bo["t"] - 8 - syn.BOUNCE_AFTER) <= 2 * FR, bo
ct = find_contact(tr, bo["i"], lambda _: syn.BATTER_BOX)
assert ct and abs(ct["t"] - 8 - syn.CONTACT_AFTER) <= 2 * FR, ct
rot = k.copy(); rot[..., 0] = k[..., 1]; rot[..., 1] = 640 - k[..., 0] # sideways phone video
assert [round(r["t"], 2) for r in find_releases(t, rot, 1.0, cfg["release"])] == syn.RELEASES
assert [round(r["t"] / 4, 2) for r in find_releases(t * 4, k, 4.0, cfg["release"])] == syn.RELEASES
tb = np.arange(6, 9.5, FR)
kb = np.stack([syn.batter_skeleton(x) for x in tb])
trg = find_batter_trigger(tb, kb, 8.0, 1.0, cfg["batter"])
se = find_shot_end(tb, kb, 8.0 + syn.CONTACT_AFTER, 1.0, cfg["batter"])
assert trg and abs(trg["t"] - 8 - syn.TRIGGER_AFTER) <= 2 * FR, trg
assert se and abs(se["t"] - 8 - (syn.SHOT_END_AFTER - 0.05)) <= 2 * FR, se
print("ok events: run-up, back foot, front foot, release, bounce, batter trigger, bat contact, "
"shot end, follow-through; rotated video; slow motion")
def test_audio_and_camera_motion():
import cv2
from audio import SR, contact_from_sound
from camera_motion import match_homography
rng = np.random.default_rng(0)
a = rng.normal(0, 0.01, SR * 3).astype(np.float32)
i = int(1.734 * SR); a[i:i + 200] += (rng.normal(0, 0.6, 200) * np.exp(-np.arange(200) / 40)).astype(np.float32)
snd = contact_from_sound(a, 1.0, 2.5)
assert snd and abs(snd["t"] - 1.734) < 0.015, snd
img = cv2.GaussianBlur(rng.integers(0, 255, (360, 640, 3)).astype(np.uint8), (5, 5), 0)
for _ in range(60):
cv2.circle(img, (int(rng.integers(0, 640)), int(rng.integers(0, 360))), int(rng.integers(3, 20)),
[int(c) for c in rng.integers(0, 255, 3)], -1)
tmp = Path(tempfile.mkdtemp())
cv2.imwrite(str(tmp / "a.jpg"), img)
cv2.imwrite(str(tmp / "b.jpg"), cv2.warpAffine(img, np.float32([[1, 0, 25], [0, 1, -12]]), (640, 360)))
cv2.imwrite(str(tmp / "c.jpg"), rng.integers(0, 255, (360, 640, 3)).astype(np.uint8))
H, _ = match_homography(tmp / "a.jpg", tmp / "b.jpg")
assert H is not None and abs(H[0, 2] - 25) < 1 and abs(H[1, 2] + 12) < 1
assert match_homography(tmp / "a.jpg", tmp / "c.jpg")[0] is None
shutil.rmtree(tmp)
print("ok bat-sound onset within 15 ms; camera movement recovered; unrelated frame rejected")
def run(tmp, *args):
out = subprocess.run([sys.executable, str(tmp / "code" / "run_all.py"), *args], capture_output=True, text=True)
assert out.returncode == 0, out.stderr[-2000:]
return out.stdout
def test_end_to_end_and_review():
tmp = Path(tempfile.mkdtemp())
shutil.copytree(CODE, tmp / "code", ignore=shutil.ignore_patterns("__pycache__"))
c = (tmp / "code" / "config.yaml").read_text().replace("device: auto ", "device: cpu ")
(tmp / "code" / "config.yaml").write_text(c)
vids = tmp / "datasets" / "1_Full-Net-Sessions-Uncut"
vids.mkdir(parents=True)
syn.make_video(vids / "synthetic_nets.mp4")
run(tmp, "--backend", "fake")
R = tmp / "results"
summ = json.load(open(R / "qa" / "run_summary.json"))
assert summ["deliveries"] == 3 and summ["qc"]["pass"] == 3, summ
d = [json.loads(l) for l in open(R / "jsonl" / "deliveries.jsonl")][0]
assert len(d["events"]) == 9, sorted(d["events"])
assert d["events"]["bat_ball_contact"].get("audio_t_clip"), "bat contact should be confirmed by sound"
assert all(e["provenance"]["source_type"] == "model" for e in d["events"].values())
did = d["delivery_id"]
sys.path.insert(0, str(tmp / "code"))
from common import load_ontology
from review import load_people, stamp, validate
onto = load_ontology()
people = load_people()
assert validate({"kind": "status", "delivery_id": did, "field": "annotation_status", "value": "expert_gold",
"annotator_id": "reviewer_01"}, onto, people), "reviewers must not set expert_gold"
assert validate({"kind": "label", "delivery_id": did, "field": "shot_type", "value": "drive",
"annotator_id": "stranger"}, onto, people), "unknown reviewer IDs must be rejected"
bad = [{"kind": "label", "delivery_id": did, "field": "shot_type", "value": "slog", "annotator_id": "rev"},
{"kind": "label", "delivery_id": did, "field": "bowler_id", "value": "Rahul", "annotator_id": "rev"},
{"kind": "event", "delivery_id": did, "field": "ball_release", "value": {"t_clip": 1}}]
assert all(validate(r, onto) for r in bad), "invalid edits must be rejected"
good = [{"kind": "event", "delivery_id": did, "field": "front_foot_contact", "value": {"t_clip": 2.38}},
{"kind": "event", "delivery_id": did, "field": "followthrough_end", "value": None},
{"kind": "label", "delivery_id": did, "field": "shot_type", "value": "drive"},
{"kind": "label", "delivery_id": did, "field": "batter_handedness", "value": "right"},
{"kind": "coach", "delivery_id": did, "field": "note",
"value": {"observation": "Braced front leg.", "correction": "Pull the front arm down.",
"confidence": "high", "cf_question": "What if the knee collapsed?", "cf_answer": "Less pace."}},
{"kind": "calibration", "source_id": d["source_id"],
"value": {"points_px": [[250, 330], [390, 330], [300, 120], [340, 120]], "camera_end": "bowler",
"ref_delivery_id": did}},
{"kind": "status", "delivery_id": did, "field": "annotation_status", "value": "expert_gold"},
{"kind": "label", "delivery_id": did, "field": "contact_quality", "value": "clean", "annotator_id": "reviewer_01"},
{"kind": "label", "delivery_id": did, "field": "contact_quality", "value": "edge", "annotator_id": "reviewer_02"}]
(R / "annotations").mkdir(exist_ok=True)
with open(R / "annotations" / "review.jsonl", "w") as f:
for r in good:
r.setdefault("annotator_id", "coach_01")
assert validate(r, onto) is None, validate(r, onto)
f.write(json.dumps(stamp(r, onto)) + "\n")
run(tmp, "--stages", "sft,tables,release,web")
d = [json.loads(l) for l in open(R / "jsonl" / "deliveries.jsonl") if did in l][0]
ffc = d["events"]["front_foot_contact"]
assert ffc["t_clip"] == 2.38 and ffc["auto_t_clip"] == 2.4 and ffc["provenance"]["review_state"] == "corrected"
assert "followthrough_end" not in d["events"] and d["annotation_status"] == "expert_gold"
assert d["measurements"]["pitch"]["actual_length"]
assert d["labels"]["actual_line"]["provenance"]["source_type"] == "deterministic_rule"
recs = [json.loads(l) for l in open(R / "jsonl" / "sft_records.jsonl") if did in l]
types = {r["task"]: r["answer_type"] for r in recs}
assert types["coach_observation"] == "expert_interpretation" and types["counterfactual"] == "counterfactual"
assert types["shot_type"] == "human_label" and "pitch_location" in types and "event_timeline" in types
assert d["labels"]["contact_quality"]["provenance"]["review_state"] == "disputed"
ev = json.load(open(R / "qa" / "evaluation.json"))
assert ev["timing"]["front_foot_contact"]["scored"] == 1 and ev["agreement"]["labels"]["contact_quality"]["pairs"] == 1
others = [json.loads(l) for l in open(R / "jsonl" / "deliveries.jsonl") if did not in l]
assert all(o["calibration"]["status"] == "same" for o in others), [o.get("calibration") for o in others]
rep = json.load(open(R / "qa" / "schema_report.json"))
assert rep["passed"], rep["errors"][:5]
assert any(Path(f).suffix in (".parquet", ".csv") for f in rep["files"].values())
rel = json.load(open(R / "releases" / "latest.json"))
assert rel["release_kind"] == "dev_only" and not rel["leaks"] and did in rel["gold"]
assert (R / "web" / "index.html").exists() and (R / "web" / "data.js").exists()
# review points (expected vs performed)
rp = d["review_points"]
assert {r["aspect"] for r in rp["bowler"]} >= {"Line", "Length", "Delivery", "Pace"}
assert {r["aspect"] for r in rp["batter"]} >= {"Shot", "Contact", "Timing"}
more = [{"kind": "label", "delivery_id": did, "field": "target_length", "value": "good_length"},
{"kind": "label", "delivery_id": did, "field": "actual_length", "value": "short"},
{"kind": "label", "delivery_id": did, "field": "actual_line", "value": "outside_off"}]
with open(R / "annotations" / "review.jsonl", "a") as f:
for r in more:
r["annotator_id"] = "coach_01"
assert validate(r, onto, people) is None, validate(r, onto, people)
f.write(json.dumps(stamp(r, onto)) + "\n")
run(tmp, "--stages", "sft,tables,evaluate,release,web")
d = [json.loads(l) for l in open(R / "jsonl" / "deliveries.jsonl") if did in l][0]
length = {r["aspect"]: r for r in d["review_points"]["bowler"]}["Length"]
shot = {r["aspect"]: r for r in d["review_points"]["batter"]}["Shot"]
assert length["status"] == "mismatch" and shot["expected"] == "cut or leave", (length, shot)
tasks = {json.loads(l)["task"] for l in open(R / "jsonl" / "sft_records.jsonl") if did in l}
assert {"bowler_review", "batter_review", "coach_observation", "bat_movement", "front_foot_position"} <= tasks, tasks
assert d["bat"]["source"] == "estimated_from_hands" and d["bat"].get("backlift_top"), d.get("bat")
g = d["measurements"]["ground"]
assert "bowler_front_foot" in g and g.get("batter_movement") in ("front_foot", "back_foot", "stayed"), g
assert any(r["aspect"] == "Movement" for r in d["review_points"]["batter"])
assert validate({"kind": "bat_label", "field": "f1", "delivery_id": did, "value": {"handle": [1, 2]},
"annotator_id": "coach_01"}, onto, people), "bat labels need handle and toe"
# intent sheet, ball-label export, backup
sheet = tmp / "datasets" / "intent.csv"
sheet.write_text("ball_no,bowler_id,target_line,target_length\n1,P0023,outside_off,good_length\n2,P0023,off_stump,full\n3,P0023,middle,short\n")
out = subprocess.run([sys.executable, str(tmp / "code" / "import_intent.py"), "--source", d["source_id"], "--csv", str(sheet)],
capture_output=True, text=True)
assert out.returncode == 0 and "wrote 9 intent labels" in out.stdout, out.stdout + out.stderr
man = json.load(open(R / "labeling" / "manifest.json"))
assert man and all((tmp / m["image"]).exists() for m in man)
bk = subprocess.run([sys.executable, str(tmp / "code" / "backup.py"), "--to", str(tmp / "bk")], capture_output=True, text=True)
assert bk.returncode == 0 and "0 mismatches" in bk.stdout, bk.stdout + bk.stderr
print(f"ok end-to-end + review loop: 9 events, review points (bowler + batter), coach notes, roles, disputes, calibration reuse, intent import, label frames, backup; edits merged, {len(recs)} pairs for the edited delivery, "
f"schema valid, release {rel['release_id']} with no leaks")
shutil.rmtree(tmp)
if __name__ == "__main__":
test_events()
test_audio_and_camera_motion()
test_end_to_end_and_review()
print("all tests passed")
|