Spaces:
Running on T4
Running on T4
File size: 13,075 Bytes
f771d3b fb52124 f771d3b 999db75 f771d3b fb52124 f771d3b fb52124 e21e264 fb52124 | 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 | """Regressions for the supplied walkthrough run; these are not accuracy tests."""
from copy import deepcopy
import json
from pathlib import Path
import numpy as np
import pytest
from baseball_batting.api_contract import AnalysisInput
from baseball_batting.batting_measurements import analyze_batting, capture_checks, point_array
from baseball_batting.body2d import filter_implausible_feet
from baseball_batting.detection import relevant_people
from test_batting_measurements import swing_track, options, metric_map
@pytest.fixture
def walkthrough():
# Only numeric model observations are included; no player images or truth
# measurements. Assertions catch the reviewed failure modes, not accuracy.
record = json.loads((Path(__file__).parent / "fixtures/walkthrough_pose.json").read_text())
return record["track"]
@pytest.fixture
def outdoor():
record = json.loads((Path(__file__).parent / "fixtures/outdoor_swing_pose.json").read_text())
return record["track"]
def test_detached_toes_are_rejected_without_fabricating_replacements():
points = np.zeros((133, 2), float)
points[13:17] = [[200, 400], [300, 400], [200, 600], [300, 600]]
points[17:23] = [[220, 630], [225, 625], [190, 615],
[310, 100], [310, 230], [290, 615]]
scores = np.full(133, .9)
original = points.copy()
filtered, confidence = filter_implausible_feet(points, scores)
assert np.isnan(filtered[20:22]).all() and (confidence[20:22] == 0).all()
np.testing.assert_array_equal(filtered[17:20], points[17:20])
np.testing.assert_array_equal(filtered[22], points[22])
np.testing.assert_array_equal(filtered[:17], points[:17])
np.testing.assert_array_equal(points, original)
def test_small_background_hit_does_not_count_as_another_athlete():
athlete = {"class_id": 0, "box": [700, 190, 1400, 1030], "score": .94}
background = {"class_id": 0, "box": [1580, 400, 1675, 495], "score": .58}
other_person = {"class_id": 0, "box": [50, 200, 300, 1000], "score": .9}
assert relevant_people([athlete, background], athlete, 1080) == 1
assert relevant_people([athlete, background, other_person], athlete, 1080) == 2
small = {"class_id": 0, "box": [50, 30, 100, 100], "score": .9}
assert relevant_people([small], small, 1080) == 1 # reject small capture separately
def test_loose_border_box_is_not_a_cropped_body():
track = swing_track()
track["frames"]["box"] = [[0, 0, 1280, 720]]*180
capture, _ = capture_checks(track, options(), 400, range(180))
assert capture == {"ok": True, "reasons": []}
for frame in track["frames"]["kp"]:
frame[15] = [370, 715]
capture, _ = capture_checks(track, options(), 400, range(180))
assert "partly_out_of_frame" in capture["reasons"]
def test_walkthrough_keeps_preparation_and_follow_through(walkthrough):
original = deepcopy(walkthrough)
pose, reps, capture, _, method = analyze_batting(walkthrough, AnalysisInput(handedness="right"))
assert walkthrough == original
assert len(pose) == len(reps) == 1
assert pose[0]["start_frame"] < 40 # preparation was lost at frame 65 before
assert pose[0]["end_frame"] == 116
assert capture == {"ok": False, "reasons": ["view_uncertain"]}
assert method["pitcher_direction"] is None # inconsistent ankle/drive directions
assert 69 <= pose[0]["events"]["swing_start"]["frame"] <= 74
assert "finish" not in pose[0]["events"] # the recording ends before settling
assert reps[0]["events_ms"] == {} # physical capture clock remains unknown
assert all(m["value"] is None for m in reps[0]["metrics"])
body = point_array(walkthrough["frames"]["kp"], 17)
feet = point_array(walkthrough["frames"]["kp_extra"], 6)
for ankle, ids in ((15, slice(0, 3)), (16, slice(3, 6))):
distance = np.linalg.norm(feet[:, ids]-body[:, ankle, None], axis=2)
assert np.nanmax(distance) < 160 # old toes were roughly 780 px from ankles
def test_walkthrough_30fps_keeps_resolved_load_but_withholds_launch_ratio(walkthrough):
from baseball_batting.measurement_quality import apply_measurement_quality
from baseball_batting.event_body3d import reconstruct_events
# A declared test clock, not independent evidence about the source camera.
walkthrough["video"]["capture_fps"] = 30
walkthrough["frames"]["t_s"] = [i/30 for i in range(walkthrough["video"]["frame_count"])]
opt = AnalysisInput(view="face_on", handedness="left", pitcher_direction="image_left",
camera_stability="fixed_verified", single_swing=True)
pose, reps, capture, warnings, method = analyze_batting(walkthrough, opt)
result = {"pose_track": deepcopy(walkthrough), "measurement_method": method,
"capabilities": {"body_3d": False}, "warnings": warnings,
"measurements": {"schema_version": "2.0", "discipline": "hitting", "view": "face_on",
"fps": 30, "reps": reps, "capture": capture}}
result["pose_track"]["reps"] = pose
report = reconstruct_events(Path("unused.mp4"), result, opt, Path("."), Path("."))
full = apply_measurement_quality(result, opt, report)
metrics = metric_map(full["coach_payload"]["reps"][0])
assert metrics["load_tempo_s"]["value"] == pytest.approx(16/30, abs=.001)
assert metrics["load_launch_ratio"]["value"] is None
assert "±1-frame" in metrics["load_launch_ratio"]["note"]
assert metrics["foot_plant_to_contact_ms"]["value"] is None
def test_known_view_on_moving_camera_keeps_only_supported_numbers(walkthrough):
opt = AnalysisInput(view="face_on", handedness="left", pitcher_direction="image_left",
camera_stability="moving")
pose, reps, capture, _, _ = analyze_batting(walkthrough, opt)
assert capture == {"ok": True, "reasons": []}
assert 73 <= pose[0]["events"]["contact"]["frame"] <= 75 # visually reviewed swing window, not accuracy labels
assert "foot_plant" not in pose[0]["events"] and "finish" not in pose[0]["events"]
metrics = metric_map(reps[0])
assert metrics["com_drift_pct_height"]["value"] is not None
assert metrics["lead_knee_angle_contact_deg"]["value"] is not None
for key in ("stride_pct_height", "head_movement_pct_height", "foot_plant_to_contact_ms",
"load_tempo_s", "load_launch_ratio", "lateral_trunk_tilt_contact_deg",
"hip_shoulder_separation_foot_plant_deg"):
assert metrics[key]["value"] is None and metrics[key]["note"]
assert all(m["confidence"] == "est" for m in metrics.values())
def test_conflicting_metadata_never_labels_the_back_leg_as_front(walkthrough):
opt = AnalysisInput(view="face_on", handedness="right", pitcher_direction="image_left",
camera_stability="moving")
_, reps, _, _, _ = analyze_batting(walkthrough, opt)
for key in ("com_drift_pct_height", "lead_knee_angle_contact_deg"):
metric = metric_map(reps[0])[key]
assert metric["value"] is None
assert "conflicts" in metric["note"]
def test_translation_does_not_change_within_frame_body_measurements():
track = swing_track()
translated = deepcopy(track)
for i in range(180):
shift = np.array([i*1.2, i*.1])
for name in ("kp", "kp_extra"):
translated["frames"][name][i] = (np.asarray(track["frames"][name][i])+shift).tolist()
translated["frames"]["box"][i] = (np.asarray(track["frames"]["box"][i])+np.tile(shift, 2)).tolist()
opt = options(single_swing=True)
opt.camera_stability = "moving"
baseline = metric_map(analyze_batting(track, opt)[1][0])
shifted = metric_map(analyze_batting(translated, opt)[1][0])
for key in ("com_drift_pct_height", "lead_knee_angle_contact_deg", "load_tempo_s", "load_launch_ratio"):
assert shifted[key]["value"] == pytest.approx(baseline[key]["value"], abs=.01)
assert shifted["head_movement_pct_height"]["value"] is None
@pytest.mark.parametrize("fps", [30, 60, 120])
def test_loading_and_hand_return_do_not_become_extra_swings(fps):
pose, _, _, _, _ = analyze_batting(swing_track(fps=fps, repeats=2), options())
assert len(pose) == 2
assert pose[0]["end_frame"] < pose[1]["start_frame"]
assert pose[0]["start_frame"] < 25 and pose[1]["start_frame"] < 205
@pytest.mark.parametrize("declared", [False, True])
def test_outdoor_reset_never_replaces_the_actual_swing(outdoor, declared):
original = deepcopy(outdoor)
opt = AnalysisInput(view="face_on", handedness="right", pitcher_direction="image_left",
camera_stability="moving", single_swing=declared)
pose, reps, capture, _, method = analyze_batting(outdoor, opt)
assert outdoor == original
assert capture == {"ok": True, "reasons": []}
assert len(pose) == len(reps) == 1
events = pose[0]["events"]
# The reviewed video swings during 75-82, then lowers the bat around 105-110.
# These broad frame windows catch that failure; they aren't impact truth.
assert 74 <= events["swing_start"]["frame"] <= 77
assert 77 <= events["contact"]["frame"] <= 81
assert "load_start" not in events or events["load_start"]["frame"] < 75
assert events["contact"]["estimated"] is True
assert "primary" in events["contact"]["method"]
assert "finish" not in events # no finish fabricated from the end of the clip
assert method["version"] == "batting-2d-v6"
assert reps[0]["events_ms"] == {}
assert all("t_s" not in event for event in events.values())
# The feet overlap in projection at the real swing, unlike the later reset.
# Correct event selection must not resurrect the invalid at-contact numbers.
for key in ("com_drift_pct_height", "lead_knee_angle_contact_deg"):
metric = metric_map(reps[0])[key]
assert metric["value"] is None and "ambiguous" in metric["note"]
def test_outdoor_unknown_view_still_identifies_the_primary_motion(outdoor):
pose, reps, capture, _, _ = analyze_batting(outdoor, AnalysisInput())
assert len(pose) == 1
assert 74 <= pose[0]["events"]["swing_start"]["frame"] <= 77
assert "contact" not in pose[0]["events"]
assert capture == {"ok": False, "reasons": ["view_uncertain"]}
assert all(m["value"] is None for m in reps[0]["metrics"])
def test_outdoor_mirror_and_camera_translation_keep_event_frames(outdoor):
opt = AnalysisInput(view="face_on", handedness="right", pitcher_direction="image_left",
camera_stability="moving")
expected = analyze_batting(outdoor, opt)[0][0]["events"]
transformed = deepcopy(outdoor)
width = outdoor["video"]["width"]
for i in range(outdoor["video"]["frame_count"]):
for name in ("kp", "kp_extra"):
points = np.asarray(outdoor["frames"][name][i])
points[:, 0] = width-points[:, 0]+i*.1
points[:, 1] += i*.05
transformed["frames"][name][i] = points.tolist()
x1, y1, x2, y2 = outdoor["frames"]["box"][i]
transformed["frames"]["box"][i] = [width-x2+i*.1, y1+i*.05,
width-x1+i*.1, y2+i*.05]
opt.pitcher_direction = "image_right"
actual = analyze_batting(transformed, opt)[0][0]["events"]
assert {key: value["frame"] for key, value in actual.items()} == {
key: value["frame"] for key, value in expected.items()}
def test_opposite_projected_direction_never_selects_a_later_hand_return():
opt = options(single_swing=True, pitcher_direction="image_left")
pose, reps, _, _, _ = analyze_batting(swing_track(), opt)
events = pose[0]["events"]
assert 59 <= events["swing_start"]["frame"] <= 63
assert "contact" not in events # declared front side has no extension in the main drive
assert metric_map(reps[0])["com_drift_pct_height"]["value"] is None
def test_missing_extension_in_main_swing_cannot_borrow_extension_from_reset():
track = swing_track()
for i, body in enumerate(track["frames"]["kp"]):
shoulder, wrist = np.asarray(body[5]), np.asarray(body[9])
# Bent during the actual drive; straight during the later hand return.
body[7] = ((shoulder+wrist)/2 + ([0, 180] if i <= 100 else [0, 0])).tolist()
pose, reps, _, _, _ = analyze_batting(track, options(single_swing=True))
assert "swing_start" in pose[0]["events"]
assert "contact" not in pose[0]["events"]
for key in ("com_drift_pct_height", "lead_knee_angle_contact_deg", "foot_plant_to_contact_ms"):
assert metric_map(reps[0])[key]["value"] is None
def test_primary_swing_events_need_raw_joint_support_even_with_short_gap_fill(outdoor):
opt = AnalysisInput(view="face_on", handedness="right", pitcher_direction="image_left",
camera_stability="moving")
for i in (78, 79, 80):
outdoor["frames"]["kp"][i][9] = None
outdoor["frames"]["conf"][i][9] = 0
pose, _, _, _, _ = analyze_batting(outdoor, opt)
for event in pose[0]["events"].values():
assert event["frame"] not in (78, 79, 80)
|