File size: 11,044 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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