"""Load and timing section: validated engine measurements -> plain words. Descriptive only; never a verdict.""" import copy import re import pytest from ai_coach.guardrails import BANNED from ai_coach.input_builder import InputError from ai_coach.timing import build_timing_section, parse_timing VERDICTS = re.compile(r"rushed|too early|too late|you were (early|late)|slow|fast|bad|wrong", re.IGNORECASE) def tmetric(key, value, status="estimated", **extra): return {"key": key, "value": value, "unit": "ms", "status": status, "confidence": "est", **extra} def swing(rep=1, load=300, foot=50, duration=None, shift=None, outcome="unknown", practice="unknown", **extra): metrics = [ tmetric("load_to_swing_ms", load), tmetric("foot_down_to_swing_ms", foot, **extra.pop("foot_extra", {})), tmetric("swing_duration_ms", duration, **extra.pop("duration_extra", {})), tmetric("early_late_shift_ms", shift, **extra.pop("shift_extra", {})), ] for m in metrics: if m["value"] is None and m["status"] == "estimated": m["status"] = "unclear" return {"rep": rep, "outcome": outcome, "stepped": True, "context": {"practice_type": practice}, "metrics": metrics, **extra} def payload(reps=None, fps=240.0, time_source="original_pts", version="3.1", **extra): return { "schema_version": version, "discipline": "hitting", "capture": {"capture_fps": fps, "time_source": time_source}, "reps": reps if reps is not None else [swing()], **extra, } def section(**kw): return build_timing_section(parse_timing(payload(**kw))) def by_key(items): return {i.metric_key: i for i in items} def all_text(s): return " ".join( [s.summary, *s.data_quality, *(o.text for o in s.observations), *(u.text for u in s.unavailable)] + (s.consistency.notes if s.consistency else []) ) def test_the_documents_own_example_is_described_without_a_verdict(): s = section() obs, miss = by_key(s.observations), by_key(s.unavailable) assert obs["load_to_swing_ms"].value_ms == 300 and "300 ms" in obs["load_to_swing_ms"].text assert obs["foot_down_to_swing_ms"].value_ms == 50 assert "cannot show which came first" in obs["foot_down_to_swing_ms"].text # order_resolved was not sent assert set(miss) == {"swing_duration_ms", "early_late_shift_ms"} assert "actual_end_unavailable" in miss["swing_duration_ms"].reason_codes assert "Actual contact" in miss["swing_duration_ms"].text assert s.summary.startswith("Timing: Preparation to swing and Front foot down to swing were estimated.") assert not VERDICTS.search(all_text(s)) and not BANNED.search(all_text(s)) def test_unknown_recording_time_withholds_every_number(): s = section(time_source="unknown", fps=None) assert s.observations == [] and len(s.unavailable) == 4 assert all(u.reason_codes == ["capture_time_unknown"] for u in s.unavailable) assert s.data_quality == ["The real recording speed of this video is unknown, so no timing numbers are shown."] def test_signed_foot_timing_is_only_stated_when_the_order_is_resolved(): resolved = section(reps=[swing(foot=-40, foot_extra={"order_resolved": True})]) assert "40 ms before your front foot first touched down" in by_key(resolved.observations)["foot_down_to_swing_ms"].text after = section(reps=[swing(foot=80, foot_extra={"order_resolved": True})]) assert "80 ms after" in by_key(after.observations)["foot_down_to_swing_ms"].text same = section(reps=[swing(foot=3, foot_extra={"order_resolved": True})]) assert "same time" in by_key(same.observations)["foot_down_to_swing_ms"].text def test_swing_duration_needs_an_actual_endpoint_never_the_arm_extension_proxy(): proxy = section(reps=[swing(duration=150, duration_extra={"end_event": "body_extension_proxy"})]) assert "swing_duration_ms" in by_key(proxy.unavailable) real = section( reps=[swing(duration=150, duration_extra={"end_event": "contact", "end_event_source": "reviewed_video_frame"})] ) text = by_key(real.observations)["swing_duration_ms"].text assert "150 ms to reach ball contact" in text and "not bat speed" in text closest = section( reps=[swing(duration=150, duration_extra={"end_event": "closest_approach", "end_event_source": "reviewed_video_frame"})] ) assert "closest the bat came" in by_key(closest.observations)["swing_duration_ms"].text def miss(practice="live", eligible=True, shift=-40): return swing(outcome="miss", practice=practice, shift=shift, shift_extra={"judgment_eligible": eligible}) def test_early_late_advice_needs_a_validated_miss_against_a_moving_ball(): ok = by_key(section(reps=[miss()]).observations)["early_late_shift_ms"].text assert "40 ms earlier" in ok later = by_key(section(reps=[miss(shift=60)]).observations)["early_late_shift_ms"].text assert "60 ms later" in later for reps, code in [ ([miss(practice="tee")], "practice_not_applicable"), ([miss(practice="unknown")], "practice_unknown"), ([miss(eligible=False)], "not_validated"), ([swing(outcome="hit", practice="live")], "not_a_miss"), ]: unavailable = by_key(section(reps=reps).unavailable)["early_late_shift_ms"] assert code in unavailable.reason_codes, code def test_engine_reason_codes_become_fixed_sentences_and_unknown_codes_are_dropped(): rep = swing(shift_extra={"reason_codes": ["no_feasible_time_shift", "totally_made_up"]}, outcome="miss", practice="live") u = by_key(section(reps=[rep]).unavailable)["early_late_shift_ms"] assert u.reason_codes == ["not_validated"] or "no_feasible_time_shift" in u.reason_codes or u.reason_codes assert "totally_made_up" not in u.reason_codes and "totally_made_up" not in u.text stepless = swing(foot=None, foot_extra={"status": "not_applicable", "reason_codes": ["no_step"]}) stepless["stepped"] = False assert "no_step" in by_key(section(reps=[stepless]).unavailable)["foot_down_to_swing_ms"].reason_codes def test_no_step_is_explained_even_without_a_reason_code(): rep = swing(foot=None, foot_extra={"status": "not_applicable"}) rep["stepped"] = False u = by_key(section(reps=[rep]).unavailable)["foot_down_to_swing_ms"] assert u.reason_codes == ["no_step"] and "did not step" in u.text def five(practice="tee", loads=(300, 310, 290, 305, 295), **kw): return [swing(rep=i + 1, load=v, practice=practice, **kw) for i, v in enumerate(loads)] def test_consistency_needs_five_swings_of_the_same_known_practice_type(): s = section(reps=five(loads=(300, 340, 290, 380, 295))) assert s.consistency and s.consistency.practice_type == "tee" and s.consistency.swings == 5 assert "varied by about 90 ms" in s.consistency.notes[0] assert section(reps=five()[:4]).consistency is None # four swings assert section(reps=five(practice="unknown")).consistency is None mixed = five()[:3] + five(practice="live")[:2] assert section(reps=mixed).consistency is None # no single practice type reaches five def test_a_difference_smaller_than_one_frame_is_not_called_a_difference(): s = section(reps=five(loads=(300, 302, 301, 303, 300)), fps=120.0) assert "less than one video frame" in s.consistency.notes[0] def test_low_frame_rates_say_how_coarse_the_video_is(): s = section(fps=30.0) assert any("30 frames per second" in line and "30 ms" in line for line in s.data_quality) assert not any("frames per second" in line for line in section(fps=240.0).data_quality) def test_the_swings_own_timestamps_set_the_frame_interval(): reps = five(loads=(300, 306, 298, 304, 300)) for r in reps: r["frame_interval_ms"] = {"min": 33.0, "median": 33.3, "max": 34.0} s = section(reps=reps, fps=None, time_source="explicit_capture_times") assert "less than one video frame" in s.consistency.notes[0] def test_nothing_is_called_a_timing_fault_while_the_numbers_are_unvalidated(): s = section(reps=[*five(practice="live"), miss()]) assert "cannot show a timing fault" in " ".join(s.data_quality) assert not VERDICTS.search(all_text(s)) def test_the_unvalidated_warning_goes_only_when_every_shown_number_is_validated(): rep = swing(practice="live", outcome="miss", shift=-30) for m in rep["metrics"]: m["judgment_eligible"] = True assert "cannot show a timing fault" not in " ".join(section(reps=[rep]).data_quality) rep["metrics"][0]["judgment_eligible"] = False # one still-unvalidated number brings the warning back assert "cannot show a timing fault" in " ".join(section(reps=[rep]).data_quality) def test_missing_outcome_and_practice_type_are_stated_not_guessed(): dq = " ".join(section().data_quality) assert "Whether the bat met the ball was not established" in dq and "type of practice" in dq known = " ".join(section(reps=[swing(outcome="hit", practice="tee")]).data_quality) assert "met the ball" not in known and "type of practice" not in known def test_implausible_values_are_not_shown(): s = section(reps=[swing(load=90_000)]) assert "load_to_swing_ms" in by_key(s.unavailable) assert by_key(s.unavailable)["load_to_swing_ms"].reason_codes == ["value_out_of_range"] def test_displayed_numbers_are_rounded_so_decimals_do_not_imply_accuracy(): s = section(reps=[swing(load=303.7)]) obs = by_key(s.observations)["load_to_swing_ms"] assert obs.value_ms == 300 and "300 ms" in obs.text def test_several_swings_report_the_median_and_the_range(): s = section(reps=five(loads=(280, 300, 320, 340, 360))) obs = by_key(s.observations)["load_to_swing_ms"] assert obs.value_ms == 320 and obs.range_ms == (280, 360) and obs.swings == 5 @pytest.mark.parametrize( "raw,message", [ ("nope", "timing must be an object"), ({"schema_version": "2.0", "reps": []}, "schema_version"), ({"schema_version": "3.1", "reps": "x"}, "reps"), (payload(reps=[{"outcome": "maybe", "metrics": []}]), "outcome"), (payload(reps=[{"metrics": [{"key": "load_to_swing_ms", "status": "great"}]}]), "status"), (payload(time_source="guess"), "time_source"), (payload(reps=[{"context": {"practice_type": "golf"}, "metrics": []}]), "practice_type"), ], ) def test_malformed_timing_is_an_input_error(raw, message): with pytest.raises(InputError, match=message): parse_timing(raw) def test_unknown_fields_and_metrics_from_a_newer_engine_are_ignored(): raw = copy.deepcopy(payload()) raw["future_field"] = 1 raw["reps"][0]["metrics"].append(tmetric("brand_new_metric", 5)) raw["reps"][0]["metrics"][0]["uncertainty_interval_ms"] = [250, 350] assert build_timing_section(parse_timing(raw)).observations def test_a_zero_timing_is_a_real_measurement_not_a_missing_one(): s = section(reps=[swing(foot=0, foot_extra={"order_resolved": True})]) assert by_key(s.observations)["foot_down_to_swing_ms"].value_ms == 0