Spaces:
Running on T4
Running on T4
File size: 10,366 Bytes
6963661 66d2e51 6963661 66d2e51 6963661 66d2e51 6963661 66d2e51 6963661 66d2e51 6963661 66d2e51 6963661 6f4b727 6963661 7bf5a7e 6963661 7bf5a7e 6963661 66d2e51 6963661 66d2e51 6963661 66d2e51 6963661 | 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | """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")
@pytest.mark.parametrize(
"patch",
[
{"single_pitch": False},
{"single_swing": True},
{"contact_frame": 5},
{"swing_id": "wrong"},
{"release_frame": 3},
{"release_frame": 8},
{"release_frame": True},
{"release_frame": 2.5},
{"athlete": {"athlete_id": "test", "throwing_hand": "left"}},
{"lead_foot": "right"},
{"context": {"practice_type": "tee"}},
{"context": {"practice_type": "dry_delivery"}},
{"context": {"ball_type": "none"}},
{
"windows": [
{
"start_frame": 0,
"end_frame": 7,
"leg_lift_frame": 6,
"foot_strike_frame": 3,
}
]
},
],
)
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
)
|