File size: 14,693 Bytes
1558b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
 
1558b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
 
1558b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1558b6d
 
 
 
e21e264
 
 
 
 
 
 
 
 
 
1558b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
1558b6d
 
e21e264
 
 
 
1558b6d
 
 
 
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
"""Four experimental timing fields, without substituting body pose for impact.

This module is also embedded verbatim in the standalone Colab test notebook.
It uses only the standard library, reads an existing 2D result, and never alters
the API's current nine-metric payload. Reviewed frames are optional test inputs.
"""
from copy import deepcopy
import math

LOAD_TIMING_VERSION = "load-timing-test-v1"
LOAD_TIMING_KEYS = ("load_to_swing_ms", "foot_down_to_swing_ms",
                    "swing_duration_ms", "early_late_shift_ms")
REVIEW_FIELDS = {"source", "load_start_frame", "swing_start_frame",
                 "foot_contact_frame", "contact_frame", "closest_approach_frame",
                 "stepped", "outcome"}


def _timing_metric(key, note, status="unclear", **extra):
    return {"key": key, "value": None, "unit": "ms", "status": status,
            "confidence": "est", "note": note, **extra}


def _frame_event(frame, method, note):
    return {"frame": frame, "method": method, "estimated": True, "note": note}


def _timing_interval(track, rep, a, b, *, signed=False):
    """Use capture timestamps and expose ±1-frame sensitivity, not error bars."""
    diagnostic = {"start_frame": a, "end_frame": b,
                  "sensitivity_scope": "each event shifted ±1 frame; detection error may be larger"}
    if a is None or b is None:
        return None, "Required event is missing.", diagnostic
    start, end = rep["start_frame"], rep["end_frame"]
    if not start <= a <= end or not start <= b <= end:
        return None, "An event is outside this swing range.", diagnostic
    if not signed and b <= a:
        return None, "Event order does not give a positive duration.", diagnostic
    times = track["frames"]["t_s"]
    clock = times[start:end+1]
    if (len(clock) < 2 or any(t is None or not math.isfinite(t) for t in clock)
            or any(y <= x for x, y in zip(clock, clock[1:]))):
        return None, "Actual recording time is unknown or invalid; playback time is not used.", diagnostic
    steps = [y-x for x, y in zip(clock, clock[1:])]
    diagnostic["capture_interval_ms"] = [round(min(steps)*1000, 3), round(max(steps)*1000, 3)]
    if max(steps) > 1.01/30 + 1e-6:
        return None, "Capture cadence is below nominal 30 FPS or has large frame gaps.", diagnostic
    a_window = [max(start, a-1), min(end, a+1)]
    b_window = [max(start, b-1), min(end, b+1)]
    low = (times[b_window[0]]-times[a_window[1]])*1000
    high = (times[b_window[1]]-times[a_window[0]])*1000
    value = (times[b]-times[a])*1000
    diagnostic.update(event_shift_frames=[a_window, b_window],
                      frame_sensitivity_range_ms=[round(low, 3), round(high, 3)])
    if signed:
        diagnostic["order_resolved_under_frame_shift"] = low > 0 or high < 0
        note = ("Event order can change within ±1 frame; this estimate cannot establish which happened first."
                if low <= 0 <= high else "Signed difference from capture timestamps.")
        return round(value, 3), note, diagnostic
    width = (high-low)/value
    diagnostic["relative_sensitivity_width"] = width
    diagnostic["relative_sensitivity_width_limit"] = .5
    if low <= 0 or width > .5+1e-9:
        return None, "Duration is unresolved under ±1-frame event shifts; inspect the event frames and sensitivity range.", diagnostic
    return round(value, 3), "Duration from capture timestamps; event detection remains unvalidated.", diagnostic


def build_load_timing_report(result, reviewed=None, ball_evidence=None):
    """Extract timing estimates from body events and separate bat/ball evidence.

    reviewed maps rep numbers to visible event frames and their source. It is
    empty by default. Manual labels never manufacture a clock or an early/late
    correction. Every supplied frame must be inside its existing rep range.
    """
    if reviewed is None:
        reviewed = {}
    if not isinstance(reviewed, dict):
        raise ValueError("Reviewed events must be a dictionary keyed by swing number.")
    track = result["pose_track"]
    reps = track["reps"]
    normalized = {}
    for key, label in reviewed.items():
        if isinstance(key, bool) or not str(key).isdigit():
            raise ValueError("Reviewed swing numbers must be positive integers.")
        number = int(key)
        if number in normalized or number not in {r["rep"] for r in reps}:
            raise ValueError("Reviewed events name a duplicate or nonexistent swing.")
        if not isinstance(label, dict) or set(label)-REVIEW_FIELDS:
            raise ValueError("Unknown reviewed-event fields.")
        if not isinstance(label.get("source"), str) or not label["source"].strip():
            raise ValueError("Reviewed events require a source describing what was checked.")
        normalized[number] = label
    capture = deepcopy(result["measurements"]["capture"])
    payload = {"schema_version": "3.0", "discipline": "hitting", "time_basis": "capture",
               "capture": capture, "reps": []}
    diagnostics = []
    for rep in reps:
        label = normalized.get(rep["rep"], {})
        events = deepcopy(rep["events"])
        for name in ("load_start", "swing_start", "foot_contact", "contact", "closest_approach"):
            key = name+"_frame"
            if key in label:
                frame = label[key]
                if (type(frame) is not int or not rep["start_frame"] <= frame <= rep["end_frame"]):
                    raise ValueError(f"{key} must be an integer frame inside swing {rep['rep']}.")
                events[name] = _frame_event(frame, "reviewed_video_frame", label["source"].strip())
        evidence = (ball_evidence or {}).get(rep['rep'], {})
        outcome = label.get("outcome", evidence.get('outcome', 'unknown'))
        if not isinstance(outcome, str) or outcome not in {"hit", "miss", "unknown"}:
            raise ValueError("Outcome must be hit, miss or unknown.")
        if "contact_frame" in label and (outcome != "hit" or "closest_approach_frame" in label):
            raise ValueError("A reviewed contact frame requires hit and no closest-approach frame.")
        if "closest_approach_frame" in label and outcome != "miss":
            raise ValueError("A reviewed closest-approach frame requires miss.")
        stepped = label.get("stepped", True if "stride" in events and "foot_contact" in events else None)
        if stepped is not None and type(stepped) is not bool:
            raise ValueError("Stepped must be true, false or unknown (None).")
        if stepped is False and "foot_contact_frame" in label:
            raise ValueError("A no-step swing cannot have a reviewed step landing.")
        onset = events.get("swing_start", {})
        forward = (onset.get("method", "").startswith("primary_swing_forward_hand_motion_")
                   or onset.get("method") == "reviewed_video_frame")
        block = ("Capture check failed: " + ", ".join(capture.get("reasons", []))
                 if not capture.get("ok") else None)
        if not forward:
            block = block or "Only generic hand movement was detected; forward swing start is not established."
        by_key, intervals = {}, {}
        def interval(key, first, last, description, signed=False, **extra):
            a, b = events.get(first, {}).get("frame"), events.get(last, {}).get("frame")
            value, reason, evidence = _timing_interval(track, rep, a, b, signed=signed)
            intervals[key] = evidence
            if block:
                value, reason = None, block
            elif a is None or b is None:
                absent = [n for n in (first, last) if n not in events]
                reason = "Missing " + ", ".join(absent) + ". " + " ".join(
                    rep.get("missing_events", {}).get(n, "") for n in absent)
            metric = _timing_metric(key, reason, **extra)
            if value is not None:
                metric.update(value=value, status="estimated", note=description+" "+reason)
            by_key[key] = metric
        interval("load_to_swing_ms", "load_start", "swing_start",
                 "Preparation (backward hand load) to estimated forward swing start.")
        if stepped is False:
            by_key["foot_down_to_swing_ms"] = _timing_metric("foot_down_to_swing_ms", "Player did not step.", "not_applicable")
        elif stepped is None:
            by_key["foot_down_to_swing_ms"] = _timing_metric("foot_down_to_swing_ms", "Whether the player stepped is unknown; missing foot events do not prove no step.")
        else:
            interval("foot_down_to_swing_ms", "foot_contact", "swing_start",
                     "First front-foot ground contact to estimated forward swing start; negative means swing began before landing.", signed=True)
        end_name = "contact" if outcome == "hit" else "closest_approach" if outcome == "miss" else None
        # The 2D detector's contact field is an arm-extension proxy. It is
        # deliberately rejected here even when its score or timing looks good.
        actual_end = end_name and events.get(end_name, {}).get("method") == "reviewed_video_frame"
        if actual_end:
            interval("swing_duration_ms", "swing_start", end_name,
                     "Swing start to " + ("reviewed ball contact." if outcome == "hit" else "reviewed closest bat-ball approach for a miss; this is a visual estimate."),
                     end_event=end_name)
        else:
            by_key["swing_duration_ms"] = _timing_metric("swing_duration_ms",
                "Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.", end_event=None)
        if not actual_end and evidence.get('end_event') in {'contact', 'closest_approach'}:
            frame = events.get('swing_start', {}).get('frame')
            times = track['frames']['t_s']
            value, reason = None, block
            bounds = evidence.get('time_interval_s')
            interval_evidence = {'end_method': evidence['method'], 'end_interval_s': bounds,
                                 'sensitivity_scope': 'endpoint interval plus ±1-frame start sensitivity; onset error unvalidated'}
            if not block and frame is not None and times[frame] is not None and bounds:
                a, b = max(rep['start_frame'], frame-1), min(rep['end_frame'], frame+1)
                if times[a] is not None and times[b] is not None:
                    value = (evidence['time_s']-times[frame])*1000
                    low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000
                    interval_evidence['frame_sensitivity_range_ms'] = [round(low, 3), round(high, 3)]
                    if value <= 0 or low <= 0 or (high-low)/value > .5:
                        value, reason = None, 'Endpoint/start interval does not resolve swing duration.'
            note = reason or ('Forward hand onset to '+evidence['end_event']+' from bat/ball observations. Event accuracy remains unvalidated.')
            by_key['swing_duration_ms'] = _timing_metric('swing_duration_ms', note,
                status='estimated' if value is not None else 'unclear', end_event=evidence['end_event'] if value is not None else None)
            if value is not None:
                by_key['swing_duration_ms']['value'] = round(value, 3)
            intervals['swing_duration_ms'] = interval_evidence
        by_key["early_late_shift_ms"] = _timing_metric("early_late_shift_ms",
            "Only applies to misses." if outcome == "hit" else
            "Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.",
            "not_applicable" if outcome == "hit" else "unclear")
        if outcome == 'miss':
            shift = evidence.get('shift', {})
            value = shift.get('value') if not block else None
            reason = block or shift.get('reason_code') or evidence.get('reason_code') or 'depth_unresolved'
            by_key['early_late_shift_ms'] = _timing_metric('early_late_shift_ms',
                'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.' if value is not None else reason,
                'estimated' if value is not None else 'unclear')
            if value is not None:
                by_key['early_late_shift_ms']['value'] = value
            intervals['early_late_shift_ms'] = deepcopy(shift)
        payload["reps"].append({"rep": rep["rep"], "outcome": outcome, "stepped": stepped,
                                "metrics": [by_key[key] for key in LOAD_TIMING_KEYS]})
        moments = {}
        for name in ("load_start", "foot_contact", "swing_start"):
            if name in events:
                moments[name] = deepcopy(events[name])
        proxy = rep["events"].get("contact")
        if proxy:
            moments["body_extension_proxy"] = deepcopy(proxy)
        if actual_end:
            moments["reviewed_"+end_name] = deepcopy(events[end_name])
        for event in moments.values():
            i = event["frame"]
            event["capture_time_s"] = track["frames"]["t_s"][i]
            event["playback_time_s"] = track["frames"]["playback_t_s"][i]
        diagnostics.append({"rep": rep["rep"], "start_frame": rep["start_frame"],
            "end_frame": rep["end_frame"], "boundary_method": rep["boundary_method"],
            "forward_swing_established": forward, "events": moments,
            "missing_events": deepcopy(rep.get("missing_events", {})), "timing_checks": intervals,
            "review_source": label.get("source"), "reviewed_fields": sorted(label)})
        diagnostics[-1]['bat_ball_evidence'] = deepcopy(evidence)
    return {"version": LOAD_TIMING_VERSION, "validation": "reference_validation_pending",
        "contract_status": "proposed_v3_not_current_coach_api_contract", "payload": payload,
        "capabilities": {"automatic_body_events": True,
                         "automatic_ball_contact": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),
                         "automatic_bat_ball_tracking": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),
                         "early_late_estimate": any('shift' in e for e in (ball_evidence or {}).values())},
        "diagnostics": diagnostics,
        "notes": ["All numbers are estimates; a successful run does not establish accuracy.",
                  "Sensitivity ranges are frame-shift checks, not validated error bounds.",
                  "No ready, pause, rushed, fault, priority or drill decisions are produced."]}