Spaces:
Running on T4
Running on T4
File size: 7,588 Bytes
326d3cc f771d3b 326d3cc f771d3b 326d3cc 16459e8 326d3cc 16459e8 326d3cc 16459e8 326d3cc 16459e8 326d3cc | 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 | """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
|