"""Timing arithmetic, missing-evidence behavior and the actual notebook export.""" import ast from copy import deepcopy import hashlib import json import os import subprocess import sys from pathlib import Path from types import ModuleType, SimpleNamespace import nbformat import pytest from baseball_batting.load_timing import build_load_timing_report from tools.build_load_timing_notebook import build from tools.preview_load_timing import export_timing_review ROOT = Path(__file__).resolve().parents[1] def timing_result(fps=120): n = 150 return {"measurements": {"capture": {"ok": True, "reasons": []}}, "pose_track": {"video": {"width": 160, "height": 120, "frame_count": n, "rotation_degrees_applied": 0, "time_source": "original_pts"}, "frames": {"t_s": [i/fps for i in range(n)], "playback_t_s": [i/fps for i in range(n)], "kp": [[None]*17 for _ in range(n)]}, "reps": [{"rep": 1, "start_frame": 0, "end_frame": n-1, "boundary_method": "caller_declared_single_swing", "missing_events": {}, "events": { "load_start": {"frame": 20, "method": "backward_hand_excursion_v1"}, "stride": {"frame": 30, "method": "test"}, "foot_contact": {"frame": 50, "method": "test"}, "swing_start": {"frame": 60, "method": "primary_swing_forward_hand_motion_v2"}, "contact": {"frame": 90, "method": "primary_swing_lead_arm_extension_proxy_v2"}}}]}} def metrics(report): return {m["key"]: m for m in report["payload"]["reps"][0]["metrics"]} def test_automatic_load_and_landing_never_substitute_arm_extension_for_contact(): result = timing_result() original = deepcopy(result) report = build_load_timing_report(result) values = metrics(report) assert values["load_to_swing_ms"]["value"] == pytest.approx(333.333) assert values["foot_down_to_swing_ms"]["value"] == pytest.approx(83.333) assert values["swing_duration_ms"]["value"] is None assert values["early_late_shift_ms"]["value"] is None assert report["payload"]["reps"][0]["outcome"] == "unknown" assert "body_extension_proxy" in report["diagnostics"][0]["events"] assert "contact" not in report["diagnostics"][0]["events"] assert result == original @pytest.mark.parametrize("outcome,end_key,end_name", [("hit", "contact_frame", "contact"), ("miss", "closest_approach_frame", "closest_approach")]) def test_reviewed_endpoints_are_explicit_and_capture_based(outcome, end_key, end_name): result = timing_result() report = build_load_timing_report(result, {1: {"source": "Visible bat/ball endpoint reviewed in original video", "outcome": outcome, end_key: 100}}) values = metrics(report) assert values["swing_duration_ms"]["value"] == pytest.approx(333.333) assert values["swing_duration_ms"]["end_event"] == end_name assert values["early_late_shift_ms"]["value"] is None assert values["early_late_shift_ms"]["status"] == ("not_applicable" if outcome == "hit" else "unclear") @pytest.mark.parametrize("landing,expected", [(75, -125), (60, 0), (45, 125)]) def test_landing_difference_preserves_negative_and_zero_values(landing, expected): result = timing_result() result["pose_track"]["reps"][0]["events"]["foot_contact"]["frame"] = landing report = build_load_timing_report(result) assert metrics(report)["foot_down_to_swing_ms"]["value"] == expected if landing == 60: check = report["diagnostics"][0]["timing_checks"]["foot_down_to_swing_ms"] assert not check["order_resolved_under_frame_shift"] assert check["frame_sensitivity_range_ms"] == [-16.667, 16.667] def test_missing_step_evidence_is_unknown_not_no_step(): result = timing_result() result["pose_track"]["reps"][0]["events"].pop("stride") report = build_load_timing_report(result) assert report["payload"]["reps"][0]["stepped"] is None assert metrics(report)["foot_down_to_swing_ms"]["status"] == "unclear" report = build_load_timing_report(result, {1: {"source": "No step visible", "stepped": False}}) assert metrics(report)["foot_down_to_swing_ms"]["status"] == "not_applicable" def test_generic_hand_onset_never_becomes_forward_swing(): result = timing_result() result["pose_track"]["reps"][0]["events"]["swing_start"]["method"] = "primary_swing_hand_motion_onset_v3" report = build_load_timing_report(result) assert metrics(report)["load_to_swing_ms"]["value"] is None assert not report["diagnostics"][0]["forward_swing_established"] reviewed = build_load_timing_report(result, {1: {"source": "Forward swing onset inspected", "swing_start_frame": 60}}) assert metrics(reviewed)["load_to_swing_ms"]["value"] == pytest.approx(333.333) @pytest.mark.parametrize("failure", ["unknown_clock", "nonmonotonic", "low_cadence", "capture_failed"]) def test_unsupported_time_or_capture_never_uses_playback_clock(failure): result = timing_result() if failure == "unknown_clock": result["pose_track"]["frames"]["t_s"] = [None]*150 if failure == "nonmonotonic": result["pose_track"]["frames"]["t_s"][40] = 0 if failure == "low_cadence": result["pose_track"]["frames"]["t_s"] = [i/24 for i in range(150)] if failure == "capture_failed": result["measurements"]["capture"] = {"ok": False, "reasons": ["multiple_people"]} report = build_load_timing_report(result, {1: {"source": "Reviewed visible contact", "outcome": "hit", "contact_frame": 100}}) assert all(m["value"] is None for m in metrics(report).values()) def test_slow_playback_does_not_change_values_and_variable_capture_times_are_used(): result = timing_result() result["pose_track"]["frames"]["playback_t_s"] = [i/15 for i in range(150)] times = [0.] for i in range(149): times.append(times[-1]+(1/120 if i % 2 else 1/100)) result["pose_track"]["frames"]["t_s"] = times report = build_load_timing_report(result) assert metrics(report)["load_to_swing_ms"]["value"] == round((times[60]-times[20])*1000, 3) def test_short_positive_durations_are_withheld_and_sensitivity_is_reported(): result = timing_result(fps=30) result["pose_track"]["reps"][0]["events"]["load_start"]["frame"] = 57 report = build_load_timing_report(result) assert metrics(report)["load_to_swing_ms"]["value"] is None assert "±1-frame" in metrics(report)["load_to_swing_ms"]["note"] @pytest.mark.parametrize("reviewed", [ {2: {"source": "unknown rep"}}, {1: {}}, {1: {"source": "review", "contact_frame": 100}}, {1: {"source": "review", "outcome": "hit", "contact_frame": 150}}, {1: {"source": "review", "swing_start_frame": True}}, {1: {"source": "review", "stepped": False, "foot_contact_frame": 50}}, {1: {"source": "review", "early_late_shift_ms": -40}}, ]) def test_invalid_reviews_cannot_inject_unsupported_values(reviewed): with pytest.raises(ValueError): build_load_timing_report(timing_result(), reviewed) def test_generated_notebook_valid_self_contained_and_2d_only(): notebook = nbformat.read(ROOT/"notebooks/load_and_swing_test.ipynb", as_version=4) nbformat.validate(notebook) assert json.loads(nbformat.writes(notebook)) == build() source = "\n".join(c.source for c in notebook.cells if c.cell_type == "code") for cell in notebook.cells: if cell.cell_type == "code": ast.parse(cell.source) assert not cell.outputs and cell.execution_count is None assert '"measurement_backend": "2d"' in source assert "setup_sam_api_worker" not in source assert "from baseball_batting.load_timing import" not in source assert "def build_load_timing_report" in source assert "load-timing-payload.json" in source def test_real_notebook_summary_and_download_exclude_stale_previews_and_secrets(tmp_path, monkeypatch): job = tmp_path/"session-test" job.mkdir() (job/"result.json").write_text(json.dumps(timing_result())) (job/"run-context.json").write_text('{}') (job/"input.mp4").write_text('private original') (job/".env").write_text('private credential') scope = {"json": json, "hashlib": hashlib, "JOB_ROOT": job, "WORKSPACE_ROOT": tmp_path, "SOURCE_CHECKOUT": {"commit_sha": "test"}} # IPython is supplied by Colab; local tests mock only its display surface. ipython = ModuleType("IPython") ipython.__path__ = [] display_module = ModuleType("IPython.display") display_module.HTML = lambda value: value display_module.Image = display_module.Video = lambda *args, **kwargs: None display_module.display = lambda *args: None monkeypatch.setitem(sys.modules, "IPython", ipython) monkeypatch.setitem(sys.modules, "IPython.display", display_module) notebook = build() exec("".join(notebook["cells"][12]["source"]), scope) exported = json.loads((job/"load-timing-payload.json").read_text()) assert len(exported["reps"][0]["metrics"]) == 4 previews = job/"timing-previews" previews.mkdir() for name in ("current.mp4", "event.png", "stale.png"): (previews/name).write_text('fixture') (previews/"previews.json").write_text(json.dumps({"previews": [{"status": "complete", "file": "current.mp4"}], "event_snapshots": [{"file": "event.png"}]})) downloads = [] scope["files"] = SimpleNamespace(download=downloads.append) exec("".join(notebook["cells"][-1]["source"]), scope) import zipfile with zipfile.ZipFile(downloads[0]) as archive: names = set(archive.namelist()) assert {"load-timing-payload.json", "timing-previews/current.mp4", "timing-previews/event.png"} <= names assert not {"input.mp4", ".env", "timing-previews/stale.png", "coach-payload.json"} & names def test_actual_preview_encoding_and_event_snapshots_preserve_pts(video, tmp_path): from baseball_batting.ingest import ingest, iter_frames result = timing_result() capture = ingest(video, {}) times = [f["playback_s"] for f in capture["frames"]] track = result["pose_track"] track["video"].update(frame_count=8, playback_fps=None, capture_fps=None) track["frames"].update(t_s=[None]*8, playback_t_s=times, kp=[[None]*17 for _ in range(8)]) track["reps"][0].update(start_frame=1, end_frame=6, events={ "load_start": {"frame": 2, "method": "backward_hand_excursion_v1"}, "swing_start": {"frame": 4, "method": "primary_swing_forward_hand_motion_v2"}, "contact": {"frame": 5, "method": "primary_swing_lead_arm_extension_proxy_v2"}}) original = deepcopy(result) report = build_load_timing_report(result) manifest = export_timing_review(video, result, report, tmp_path/"previews") assert result == original assert manifest["previews"][0]["status"] == "complete" decoded = list(iter_frames(tmp_path/"previews"/manifest["previews"][0]["file"])) assert len(decoded) == 6 for i, (_, pts, base, _) in enumerate(decoded): assert float(pts*base) == pytest.approx(times[1+i]-times[1], abs=float(base)) assert {s["event"] for s in manifest["event_snapshots"]} == {"load_start", "swing_start", "body_extension_proxy"} import cv2 for snapshot in manifest["event_snapshots"]: image = cv2.imread(str(tmp_path/"previews"/snapshot["file"])) assert image.shape[1] == 280*len(snapshot["neighbor_frames"]) assert snapshot["sha256"] == hashlib.sha256((tmp_path/"previews"/snapshot["file"]).read_bytes()).hexdigest() # The notebook launches its embedded helper outside the cloned repo. Check # that the real launch finds the engine and uses the same recorded frames. script = tmp_path/"embedded-timing-preview.py" script.write_text((ROOT/"tools/preview_load_timing.py").read_text()) result_path, report_path = tmp_path/"result.json", tmp_path/"report.json" result_path.write_text(json.dumps(result)) report_path.write_text(json.dumps(report)) completed = subprocess.run([sys.executable, "-c", "import runpy,sys; runpy.run_path(sys.argv.pop(1), run_name='__main__')", str(script), "--video", str(video), "--result", str(result_path), "--report", str(report_path), "--output", str(tmp_path/"embedded-preview")], cwd=ROOT, env={**os.environ, "MPLBACKEND": "Agg"}, capture_output=True, text=True) assert completed.returncode == 0, completed.stderr exported = json.loads((tmp_path/"embedded-preview/previews.json").read_text()) assert exported["previews"][0]["status"] == "complete" assert len(exported["event_snapshots"]) == 3 def test_zero_swings_does_not_fabricate_reps(): result = timing_result() result["pose_track"]["reps"] = [] assert build_load_timing_report(result)["payload"]["reps"] == []