Spaces:
Running on T4
Running on T4
Download tests/test_pitching_api.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_pitching_api.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tests/test_pitching_api.py
-
curl -L -o test_pitching_api.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_pitching_api.py
10.4 kB
| """Pitching contract, invariance, export/API delivery and evidence gates.""" | |
| import copy | |
| import json | |
| import numpy as np | |
| import pytest | |
| from ai_coach.pitch_report.v1_1.contract import METRICS, PitchPayload | |
| from ai_coach.pitch_report.v1_1.schemas import PitchReport | |
| from ai_coach.pitch_report.v1_1.service import AthleteContext, build_report | |
| from fastapi.testclient import TestClient | |
| from pydantic import ValidationError | |
| from test_api import AUTH, fake_service, settings | |
| from test_motion_player import raw_for | |
| from test_sam_batting import pose | |
| from baseball_batting.api import create_app | |
| from baseball_batting.api_contract import TimingInput | |
| from baseball_batting.ingest import ingest | |
| from baseball_batting.motion_export import export_motion, reproduce_measurements | |
| from baseball_batting.pitching_coach import build_pitch_payload | |
| from baseball_batting.pitching_geometry import curves | |
| from baseball_batting.pitching_input import PitchingInput | |
| from baseball_batting.sam_motion import MHR | |
| from baseball_batting.storage import atomic_json, sha256_file | |
| def options(**patch): | |
| data = { | |
| "discipline": "pitching", | |
| "single_pitch": True, | |
| "annotated_videos": False, | |
| "handedness": "right", | |
| "camera_stability": "fixed_verified", | |
| "timing": {"kind": "unretimed", "source": "Synthetic fixture clock"}, | |
| "up_vector": [0, -1, 0], | |
| "up_source": "Known synthetic fixture vertical", | |
| "athlete": {"athlete_id": "fixture-athlete", "throwing_hand": "right"}, | |
| "context": {"practice_type": "flat_ground", "drill_type": "step_back"}, | |
| "release_frame": 5, | |
| "windows": [ | |
| { | |
| "start_frame": 0, | |
| "end_frame": 7, | |
| "leg_lift_frame": 1, | |
| "foot_strike_frame": 3, | |
| } | |
| ], | |
| } | |
| return PitchingInput.model_validate({**data, **patch}) | |
| def payload(opts=None, points=None, clock=True): | |
| opts = opts or options() | |
| if not clock: | |
| opts = opts.model_copy(update={"timing": TimingInput(kind="unknown")}) | |
| p = points if points is not None else pose(8) | |
| times = np.arange(8) * 0.04 | |
| corrected = { | |
| "points_relative": p, | |
| "valid": np.isfinite(p).all(axis=-1), | |
| "boundary": np.zeros((8, 70), bool), | |
| "interpolated": np.zeros((8, 70), bool), | |
| } | |
| return build_pitch_payload( | |
| opts, | |
| {"analysis_id": "pitch-test", "analysis_revision": 1}, | |
| corrected, | |
| times, | |
| times if clock else np.full(8, np.nan), | |
| ).model_dump(mode="json") | |
| def test_reject_incompatible_or_invalid_pitch_options(patch): | |
| with pytest.raises(ValidationError): | |
| options(**patch) | |
| def test_frame_count_is_count_not_last_index(): | |
| opts = options(windows=[{"start_frame": 0, "end_frame": 8}]) | |
| with pytest.raises(ValueError, match="reviewed_frame_out_of_range"): | |
| opts.validate_frame_count(8) | |
| options().validate_frame_count(8) | |
| def test_rocker_without_leg_lift_does_not_invent_a_phase_or_grade(): | |
| p = payload( | |
| options( | |
| context={"drill_type": "rocker"}, | |
| windows=[{"start_frame": 0, "end_frame": 7, "foot_strike_frame": 3}], | |
| ) | |
| ) | |
| assert p["events"]["leg_lift"]["status"] == "unavailable" | |
| assert p["events"]["leg_lift"]["reasons"] == ["event_not_applicable"] | |
| report = build_report(p, AthleteContext(level="college")) | |
| PitchReport.model_validate(report) | |
| # No leg lift: the gather phase is never graded; the rest of the rocker delivery is compared. | |
| gather = next(g for g in report["groups"] if g["group"] == "gather") | |
| assert gather["score"] is None | |
| assert len(report["measurements"]) == 10 | |
| assert any(m["value"] is not None for m in report["measurements"]) | |
| assert all(m["coach_tip"] is None for m in report["measurements"] if m["group"] == "gather") | |
| assert report["focus_area"]["drill"] is not None | |
| def test_unknown_camera_keeps_intrinsic_angles_unknown_clock_blocks_times(): | |
| p = payload( | |
| options(camera_stability="unknown", up_vector=None, up_source=None), clock=False | |
| ) | |
| rows = {m["metric_id"]: m for m in p["measurements"]} | |
| assert rows["lead_knee_flexion_at_foot_strike"]["value"] is not None | |
| assert rows["throwing_elbow_flexion_at_release"]["value"] is not None | |
| assert rows["torso_inclination_at_release"]["value"] is None | |
| assert rows["foot_strike_to_release_ms"]["value"] is None | |
| assert "capture_time_unknown" in rows["foot_strike_to_release_ms"]["reasons"] | |
| assert p["events"]["release"]["capture_time_s"] is None | |
| def test_missing_throwing_wrist_blocks_only_elbow_measurement(): | |
| p = pose(8) | |
| p[5, MHR["right_wrist"]] = np.nan | |
| rows = {m["metric_id"]: m for m in payload(points=p)["measurements"]} | |
| assert rows["throwing_elbow_flexion_at_release"]["value"] is None | |
| assert rows["lead_knee_flexion_at_foot_strike"]["value"] is not None | |
| def test_camera_rotation_translation_scale_and_anatomical_mirror(): | |
| p = pose(8) | |
| original = curves(p, "right", [0, -1, 0]) | |
| a = 0.74 | |
| r = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]]) | |
| transformed = curves(p @ r.T + [2, 3, 5], "right", np.array([0, -1, 0]) @ r.T) | |
| for key in ("knee", "elbow", "torso", "span", "separation"): | |
| np.testing.assert_allclose( | |
| original[key], transformed[key], atol=1e-6, equal_nan=True | |
| ) | |
| mirrored = p.copy() | |
| mirrored[:, :, 0] *= -1 | |
| for name, index in MHR.items(): | |
| opposite = ( | |
| ("right_" + name[5:]) if name.startswith("left_") else ("left_" + name[6:]) | |
| ) | |
| mirrored[:, index] = p[:, MHR[opposite]] * [-1, 1, 1] | |
| left = curves(mirrored, "left", [0, -1, 0]) | |
| for key in ("knee", "elbow", "torso", "span"): | |
| np.testing.assert_allclose(original[key], left[key], atol=1e-6, equal_nan=True) | |
| np.testing.assert_allclose(original["separation"], -left["separation"], atol=1e-6) | |
| scaled = curves(p * 2, "right", [0, -1, 0]) | |
| np.testing.assert_allclose(scaled["span"], original["span"] * 2) | |
| np.testing.assert_allclose(scaled["knee"], original["knee"]) | |
| def test_payload_rejects_wrong_definitions_duplicate_metrics_and_missing_events(): | |
| p = payload() | |
| for mutate in ( | |
| lambda d: d["measurements"].append(d["measurements"][0]), | |
| lambda d: d["measurements"][0].update(reference="invented"), | |
| lambda d: d["measurements"][0].update(confidence=0.9), | |
| lambda d: d["measurements"][0].update(reasons=["event_timing_uncertain"]), | |
| ): | |
| d = copy.deepcopy(p) | |
| mutate(d) | |
| with pytest.raises(ValidationError): | |
| PitchPayload.model_validate(d) | |
| def test_pitch_export_immutable_http_and_independent_replay(tmp_path, video, monkeypatch): | |
| def forbidden(*args, **kwargs): | |
| pytest.fail("Pitching export must not invoke a visual LLM") | |
| monkeypatch.setattr("baseball_batting.pitching_visual.review_pitch_video", forbidden) | |
| opts = options(timing={"kind": "unretimed", "source": "Synthetic fixture clock"}) | |
| capture = ingest(video, opts.metadata()) | |
| # Fixture videos may have more frames; keep reviewed events in the first eight. | |
| raw = raw_for(capture) | |
| s = settings(tmp_path) | |
| service = fake_service(s) | |
| lineage = service.store.create_motion(4) | |
| job = service.job_directory(lineage["job_id"]) | |
| job.mkdir() | |
| atomic_json(job / "lineage.json", lineage) | |
| atomic_json(job / "request.json", opts.model_dump(mode="json")) | |
| manifest = export_motion( | |
| job, | |
| video, | |
| capture, | |
| raw, | |
| opts, | |
| {"name": "synthetic, not a neural accuracy test"}, | |
| lineage, | |
| ) | |
| service.store.update( | |
| lineage["job_id"], "completed", result_hash=sha256_file(job / "result.json") | |
| ) | |
| data = json.loads((job / "coach-payload.json").read_text()) | |
| assert data.get("visual_evidence") is None | |
| assert manifest.pipeline["coach_payload"]["evidence_mode"] == "ml_measurements_only" | |
| assert manifest.pipeline["coach_payload"]["media_sent_to_coach"] is False | |
| assert "visual_implementation_sha256" not in manifest.pipeline["coach_payload"] | |
| assert {m["metric_id"] for m in data["measurements"]} == set(METRICS) | |
| replay = reproduce_measurements(manifest, job / "motion.jsonl").model_dump( | |
| mode="json" | |
| ) | |
| for a, b in zip(data["measurements"], replay["measurements"]): | |
| assert ( | |
| a["value"] == pytest.approx(b["value"]) | |
| if a["value"] is not None | |
| else b["value"] is None | |
| ) | |
| with TestClient(create_app(s, service)) as client: | |
| pitching = client.get("/v1/motion-analyses/capabilities", headers=AUTH).json()["pitching"] | |
| assert pitching["visual_evidence"] == "disabled" | |
| assert pitching["media_sent_to_coach"] is False | |
| response = client.get( | |
| "/v1/motion-analyses/" + job.name + "/coach-payload", headers=AUTH | |
| ) | |
| assert response.status_code == 200, response.text | |
| assert response.content == (job / "coach-payload.json").read_bytes() | |
| assert ( | |
| client.get( | |
| "/v1/motion-analyses/input-schema?discipline=pitching", headers=AUTH | |
| ).json() | |
| == PitchingInput.model_json_schema() | |
| ) | |
| assert ( | |
| client.post( | |
| "/v1/motion-analyses/" + job.name + "/revisions", | |
| headers=AUTH, | |
| json={"options": {"release_frame": capture["frame_count"] + 1}}, | |
| ).status_code | |
| == 422 | |
| ) | |