baseball-engine / tests /test_colab_2d.py
github-actions[bot]
Automated Deploy: 0f6712d462fa0d8a00c5bbc6cfffe99ab79b85d6
16459e8
Raw History Blame Contribute Delete
7.59 kB
"""Colab entry-point and actual clip encoding checks; no accuracy claims."""
import ast
from copy import deepcopy
import json
from pathlib import Path
import nbformat
import pytest
from baseball_batting.ingest import ingest, iter_frames
from tools.build_2d_notebook import build
from tools.preview_swing_ranges import export_previews
ROOT = Path(__file__).resolve().parents[1]
def preview_result(video, rotation=0):
capture = ingest(video, {"rotation_degrees": rotation})
shape = capture["frames"][0]
return {"pose_track": {"video": {"width": shape["width"], "height": shape["height"],
"frame_count": capture["frame_count"], "rotation_degrees_applied": rotation,
"playback_fps": None, "capture_fps": None},
"frames": {"kp": [[None]*17 for _ in capture["frames"]],
"playback_t_s": [f["playback_s"] for f in capture["frames"]]},
"reps": [{"rep": 1, "start_frame": 2, "end_frame": 4, "events": {}},
{"rep": 2, "start_frame": 6, "end_frame": 7, "events": {}}]}}
def test_generated_2d_notebook_is_valid_and_uses_api_worker():
notebook = nbformat.read(ROOT / "notebooks/batting_2d_test.ipynb", as_version=4)
nbformat.validate(notebook)
assert json.loads(nbformat.writes(notebook)) == build()
code_cells = [cell.source for cell in notebook.cells if cell.cell_type == "code"]
for cell in code_cells: ast.parse(cell)
source = "\n".join(code_cells)
assert "baseball_batting.api_worker" in source
assert "tools.setup_api_models" in source
assert "tools.preview_swing_ranges" in source
assert "setup_full_worker" not in source
assert 'SINGLE_SWING = False' in source
assert 'TIMING = {"kind": "unknown"}' in source
assert not any(cell.outputs for cell in notebook.cells if cell.cell_type == "code")
def test_swing_previews_preserve_inclusive_frames_and_variable_playback_timing(video, tmp_path):
result = preview_result(video)
original = deepcopy(result)
manifest = export_previews(video, result, tmp_path / "clips", overlay=False)
assert result == original
assert len(manifest["previews"]) == 2
source = list(iter_frames(video))
for record in manifest["previews"]:
assert record["status"] == "complete", record
frames = list(iter_frames(tmp_path / "clips" / record["file"]))
start, end = record["start_frame"], record["end_frame"]
assert len(frames) == end-start+1
for local, (_, pts, base, image) in enumerate(frames):
expected = result["pose_track"]["frames"]["playback_t_s"][start+local]
origin = result["pose_track"]["frames"]["playback_t_s"][start]
assert float(pts*base) == pytest.approx(expected-origin, abs=float(base))
# Actual pixel content verifies that encoder selected the right frames.
assert float(image[70:90,90:110].mean()) == pytest.approx(
float(source[start+local][3][70:90,90:110].mean()), abs=4)
def test_preview_rotation_limit_and_raw_point_overlay(video, tmp_path):
result = preview_result(video, 90)
result["pose_track"]["frames"]["kp"][2][0] = [50, 70]
result["pose_track"]["frames"]["kp"][2][15] = [50, 70]
result["pose_track"]["frames"]["kp_extra"] = [[None]*6 for _ in range(8)]
result["pose_track"]["frames"]["kp_extra"][2][0] = [58, 80]
manifest = export_previews(video, result, tmp_path / "clips", max_clips=1)
assert manifest["swing_candidates_total"] == 2
assert len(manifest["previews"]) == 1
record = manifest["previews"][0]
assert record["status"] == "complete", record
assert (record["width"], record["height"]) == (120,160)
frames = list(iter_frames(tmp_path / "clips" / record["file"]))
assert frames[0][3].shape[:2] == (160,120)
assert frames[0][3][70,50,1] > 150 # Visible raw nose point.
foot = frames[0][3][80,58]
assert foot[2] > int(foot[1])+20 and foot[1] > 120 # Orange toe point.
def test_preview_exports_model_comparison_without_changing_measurements(video, tmp_path):
result = preview_result(video)
result['pose_track']['frames']['kp'][2][0] = [50,70]
result['pose_track']['reps'][0]['events'] = {'contact':{'frame':2}}
projection = [None]*17; projection[0] = [70,70]
result['experimental_body3d'] = {'frames':[{'frame':2,'projection':projection}]}
result['measurement_method'] = {'body_height_px':100}
original = deepcopy(result)
manifest = export_previews(video,result,tmp_path/'clips',max_clips=1)
assert result == original
assert manifest['previews'][0]['status']=='complete'
comparison = manifest['model_comparisons'][0]
assert comparison['frame']==2 and comparison['events']==['contact']
import cv2
image = cv2.imread(str(tmp_path/'clips'/comparison['file']))
assert image[70,60,2] > 200 # Red discrepancy connector between the models.
assert image[70,50,1] > 150 # Raw model point is preserved.
assert image[70,75,0] > 200 # Purple projected 3D ring.
@pytest.mark.parametrize("bad_clock", [None, 0.0])
def test_bad_playback_timing_is_withheld_without_fabricating_preview(video, tmp_path, bad_clock):
result = preview_result(video)
result["pose_track"]["frames"]["playback_t_s"][3] = bad_clock
manifest = export_previews(video, result, tmp_path / "clips", max_clips=1)
assert manifest["previews"][0]["status"] == "unavailable"
assert not list((tmp_path / "clips").glob("*.mp4"))
def test_zero_candidates_and_wrong_ranges_never_invent_clips(video, tmp_path):
result = preview_result(video)
result["pose_track"]["reps"] = []
assert export_previews(video, result, tmp_path / "none")["previews"] == []
result = preview_result(video)
result["pose_track"]["reps"][1]["start_frame"] = 4
with pytest.raises(ValueError, match="disjoint"):
export_previews(video, result, tmp_path / "overlap")
def test_notebook_download_contains_results_and_current_previews_only(tmp_path):
import zipfile
from types import SimpleNamespace
job = tmp_path / "results/session-example"
previews = job / "previews"
previews.mkdir(parents=True)
for name in ("result.json", "coach-payload.json", "request.json", "source_checkout.json",
"input.mp4", ".env", "worker.log"):
(job / name).write_text("fixture")
(previews / "swing-001.mp4").write_text("current preview")
(previews / "swing-001-comparison.png").write_text("current comparison")
(previews / "stale-comparison.png").write_text("stale comparison")
(previews / "swing-002.mp4").write_text("stale previous preview")
(previews / "previews.json").write_text(json.dumps({"previews": [
{"status": "complete", "file": "swing-001.mp4"}, {"status": "unavailable", "rep": 2}],
"model_comparisons": [{"file": "swing-001-comparison.png"}]}))
downloads = []
scope = {"WORKSPACE_ROOT": tmp_path, "JOB_ROOT": job, "json": json,
"files": SimpleNamespace(download=downloads.append)}
download_cell = "".join(build()["cells"][-1]["source"])
exec(compile(download_cell, "colab_download", "exec"), scope)
assert downloads == [str(scope["ARCHIVE_PATH"])]
with zipfile.ZipFile(downloads[0]) as archive:
names = set(archive.namelist())
assert {"result.json", "coach-payload.json", "previews/previews.json", "previews/swing-001.mp4"} <= names
assert "previews/swing-001-comparison.png" in names
assert "previews/stale-comparison.png" not in names
assert not {"input.mp4", ".env", "previews/swing-002.mp4"} & names