File size: 14,395 Bytes
2426de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
"""Check arithmetic, provenance and abstention independently of any AI wording."""
from copy import deepcopy
import json
import math
from pathlib import Path

import pytest

pytest.importorskip('pydantic')
from baseball_batting.objective_feedback import build_objective_feedback, ObjectiveFeedback


def inputs():
    times = [i/60 for i in range(16)]
    pose = {'rep':1,'start_frame':0,'end_frame':15,'events':{
        'foot_contact':{'frame':1,'method':'lead_sole_return_v2'},
        'foot_plant':{'frame':3,'method':'settled_lead_foot_return_v2'},
        'swing_start':{'frame':4,'method':'primary_swing_forward_hand_motion_v2'},
        'contact':{'frame':10,'method':'primary_swing_lead_arm_extension_proxy_v2'}}}
    measurements = {'capture':{'ok':True},'reps':[{'rep':1,'metrics':[
        {'key':'hip_shoulder_separation_foot_plant_deg','value':None,'unit':'deg'}]}]}
    def metric(key,value=None,reason='measurement_unavailable'):
        return {'key':key,'value':value,'status':'estimated' if value is not None else 'unclear',
            'reason_code':None if value is not None else reason,'uncertainty':{'interval_ms':None,'kind':'unknown'}}
    timing = {'capture':{'ok':True},'context':{'practice_type':'unknown'},'reps':[{
        'rep':1,'outcome':'unknown','stepped':True,
        'metrics':[metric('load_to_swing_ms',reason='load_start_missing'),
                   metric('foot_down_to_swing_ms',50),
                   metric('swing_duration_ms',reason='ball_trajectory_unobserved_or_ambiguous'),
                   metric('early_late_shift_ms',reason='depth_unresolved')],
        'events':[{'event':key,'method':pose['events'][key]['method'],'frame_interval':[i-1,i+1],
                   'capture_interval_s':[times[i-1],times[i+1]],'uncertainty_kind':'frame_sensitivity'}
                  for key,i in [('foot_contact',1),('swing_start',4)]]}]}
    timing['reps'][0]['metrics'][1]['uncertainty']={'interval_ms':[16.667,83.333],'kind':'frame_sensitivity'}
    result={'pose_track':{'reps':[pose],'frames':{'t_s':times,'playback_t_s':times}},'measurement_diagnostics':[]}
    return measurements,timing,result


def report(data=None,observed=None,fixed=True):
    m,t,r=data or inputs()
    return build_objective_feedback(m,t,result=r,observed=observed,
        camera_stability='fixed_verified' if fixed else 'unknown')


def lookup(r,key):
    return next(m for f in r['reps'][0]['features'] for m in f['measurements'] if m['key']==key)


def shafts(angles=None):
    rows=[]
    for i,angle in enumerate(angles or [10,20,30,40,50,60,70],4):
        a=math.radians(angle)
        rows.append({'frame':i,'bat':[{'state':'model_observed',
            'points':[[100,100],[100+60*math.cos(a),100-60*math.sin(a)]]}]})
    return {'frames':rows}


def test_report_is_numeric_and_unknowns_are_not_a_player_grade():
    data=inputs();old=deepcopy(data)
    r=report(data)
    assert data==old and report(data)==r
    assert r['coverage']['available_count']==1 and r['coverage']['applicable_count']==7
    assert r['coverage']['value']==14
    m=lookup(r,'foot_down_to_swing_ms')
    assert m['value']==50 and m['interval']==[16.667,83.333]
    assert '50 ms after' in m['explanation'] and '17–83 ms' in m['explanation']
    assert m['evidence_frame_ids']==[0,2,3,5]
    assert m['accuracy_validated'] is False and m['judgment_eligible'] is False
    assert r['median_capture_frame_interval_ms']==16.667
    assert r['reps'][0]['moments'][-1]['is_contact_proxy'] is True
    assert lookup(r,'contact_capture_time_s')['value'] is None
    assert 'grade' not in r['coverage'] and r['coverage']['basis']=='available_requested_measurements'


def test_zero_is_available_and_zero_coverage_is_not_null():
    m,t,r=inputs();t['reps'][0]['metrics'][1]['value']=0
    t['reps'][0]['metrics'][1]['uncertainty']['interval_ms']=[-33.333,33.333]
    out=report((m,t,r));row=lookup(out,'foot_down_to_swing_ms')
    assert row['value']==0 and 'order is unresolved' in row['explanation']
    assert out['coverage']['available_count']==1
    t['reps'][0]['metrics'][1].update(value=None,status='unclear')
    out=report((m,t,r));assert out['coverage']['value']==0
    t['reps']=[]
    assert report((m,t,r))['coverage']['value'] is None


def test_not_applicable_is_excluded_and_reference_values_cannot_inflate_coverage():
    m,t,r=inputs();t['context']['practice_type']='tee'
    m['reps'][0]['metrics'].append({'key':'stride_pct_height','unit':'%','value':45.2,'note':'Projected skeleton scaling.'})
    r['measurement_diagnostics']=[{'rep':1,'metrics':[{'key':'stride_pct_height','status':'estimated','method':'2d_estimate_v6'}]}]
    out=report((m,t,r))
    assert out['coverage']['available_count']==1 and out['coverage']['applicable_count']==6
    assert out['coverage']['not_applicable_count']==1 and out['coverage']['value']==17
    assert next(d for d in out['reps'][0]['references'] if d['key']=='stride_pct_height')['value']==45.2
    t['reps'][0]['stepped']=False
    out=report((m,t,r));assert out['coverage']['applicable_count']==5 and out['coverage']['available_count']==0


def test_projection_and_contact_proxies_cannot_supply_physical_measurements():
    m,t,r=inputs();m['reps'][0]['metrics'][0]['value']=42
    r['measurement_diagnostics']=[{'rep':1,'metrics':[{'key':'hip_shoulder_separation_foot_plant_deg',
        'status':'estimated','method':'2d_estimate_v6'}]}]
    t['reps'][0]['events'].append({'event':'contact','method':'lead_arm_extension_proxy',
        'uncertainty_kind':'visual_contact_interval','capture_interval_s':[.15,.18],'frame_interval':[9,11]})
    t['reps'][0]['metrics'][2].update(value=100,status='estimated',end_event='contact')
    out=report((m,t,r))
    assert lookup(out,'hip_shoulder_separation_foot_plant_deg')['value'] is None
    assert lookup(out,'swing_duration_ms')['value'] is None
    assert lookup(out,'contact_capture_time_s')['value'] is None
    r['measurement_diagnostics'][0]['metrics'][0]['method']='3d_landmark_geometry_v2'
    assert lookup(report((m,t,r)),'hip_shoulder_separation_foot_plant_deg')['value']==42


def test_real_ball_interaction_interval_can_supply_contact_time_and_duration():
    m,t,r=inputs();rep=t['reps'][0]
    rep['events'].append({'event':'contact','method':'observed_bat_and_piecewise_ball_trajectory_v1',
        'uncertainty_kind':'visual_contact_interval','capture_interval_s':[.15,.183333],'frame_interval':[9,11]})
    rep['metrics'][2].update(value=100,status='estimated',end_event='contact')
    out=report((m,t,r))
    assert lookup(out,'swing_duration_ms')['value']==100
    contact=lookup(out,'contact_capture_time_s')
    assert contact['value']==pytest.approx(.1666665) and contact['interval']==[.15,.183333]
    assert contact['evidence_frame_ids']==[9,11]


@pytest.mark.parametrize('flip', [False, True])
def test_bat_direction_uses_detected_endpoints_and_handles_endpoint_order(flip):
    observed=shafts()
    if flip:
        for row in observed['frames'][::2]:row['bat'][0]['points'].reverse()
    out=report(observed=observed)
    row=lookup(out,'bat_image_axis_rotation_deg')
    assert row['value']==pytest.approx(60) and row['unit']=='deg_projected'
    assert row['evidence_frame_ids']==list(range(4,11))
    assert 'arm-extension proxy' in row['explanation'] and '3D attack angle' in row['explanation']
    assert out['coverage']['available_count']==2 and out['coverage']['value']==29
    assert lookup(out,'contact_capture_time_s')['value'] is None


def test_bat_axis_wrap_is_not_an_invented_half_turn():
    out=report(observed=shafts([80,85,89,-87,-84,-81,-78]))
    assert lookup(out,'bat_image_axis_rotation_deg')['value']==pytest.approx(22)


def test_generic_hand_motion_cannot_define_a_forward_swing_bat_window():
    m,t,r=inputs();r['pose_track']['reps'][0]['events']['swing_start']['method']='generic_hand_motion'
    assert lookup(report((m,t,r),observed=shafts()),'bat_image_axis_rotation_deg')['reason_code']=='forward_swing_unresolved'


@pytest.mark.parametrize('failure',['gap','multiple','moving','unretained','large_step'])
def test_bat_direction_abstains_on_missing_or_ambiguous_evidence(failure):
    observed=shafts()
    if failure=='gap':observed['frames'][2]['bat']=[]
    if failure=='multiple':observed['frames'][2]['bat']*=2
    if failure=='unretained':observed=None
    if failure=='large_step':observed=shafts([0,80,81,82,83,84,85])
    out=report(observed=observed,fixed=failure!='moving')
    assert lookup(out,'bat_image_axis_rotation_deg')['value'] is None
    assert out['coverage']['available_count']==1


def test_every_rep_has_its_own_values_and_coverage_includes_all_requested_pairs():
    m,t,r=inputs();second=deepcopy(t['reps'][0]);second['rep']=2
    second['metrics'][1].update(value=None,status='unclear',reason_code='foot_contact_missing')
    t['reps'].append(second)
    out=report((m,t,r))
    assert len(out['reps'])==2 and out['coverage']['requested_count']==14
    assert out['coverage']['available_count']==1 and out['coverage']['value']==7
    assert out['reps'][0]['coverage']['value']==14 and out['reps'][1]['coverage']['value']==0


def test_capture_failure_and_nonfinite_values_never_become_numbers():
    m,t,r=inputs();t['capture']['ok']=False
    assert report((m,t,r),observed=shafts())['coverage']['available_count']==0
    t['capture']['ok']=True;t['reps'][0]['metrics'][1]['value']=float('nan')
    out=report((m,t,r))
    assert lookup(out,'foot_down_to_swing_ms')['value'] is None
    assert 'NaN' not in json.dumps(out)


def test_early_late_requires_a_miss_and_actual_calibrated_feasible_geometry():
    m,t,r=inputs();metric=t['reps'][0]['metrics'][3]
    metric.update(value=0,status='estimated',feasible_shift_intervals_ms=[[-10,10]])
    assert lookup(report((m,t,r)),'early_late_shift_ms')['value'] is None
    t['reps'][0]['outcome']='miss'
    t['reps'][0]['events'].append({'event':'closest_approach','method':'calibrated_dual_view_paths',
        'uncertainty_kind':'supplied_geometry_bound'})
    assert lookup(report((m,t,r)),'early_late_shift_ms')['value']==0
    metric['value']=20
    assert lookup(report((m,t,r)),'early_late_shift_ms')['value'] is None


def test_slow_playback_seek_time_is_separate_from_capture_time_and_bad_clock_has_no_cadence():
    m,t,r=inputs();r['pose_track']['frames']['playback_t_s']=[i/15 for i in range(16)]
    out=report((m,t,r));onset=next(e for e in out['reps'][0]['moments'] if e['key']=='swing_start')
    assert onset['capture_time_s']==pytest.approx(4/60)
    assert onset['clip_playback_time_s']==pytest.approx(4/15,abs=1e-6)
    r['pose_track']['frames']['t_s'][5]=None
    assert report((m,t,r))['median_capture_frame_interval_ms'] is None


def test_objective_report_schema_is_published_and_api_is_authenticated(tmp_path):
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    from test_api import AUTH,fake_service,settings,wait_until
    service=fake_service(settings(tmp_path))
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        assert client.get('/v1/objective-feedback-schema').status_code==401
        assert client.get('/v1/objective-feedback-schema',headers=AUTH).json()==ObjectiveFeedback.model_json_schema()
    root=Path(__file__).parents[1]
    assert json.loads((root/'docs/objective-feedback.schema.json').read_text())==ObjectiveFeedback.model_json_schema()


def test_upgrade_cannot_read_tampered_measurement_artifacts(tmp_path):
    pytest.importorskip('ai_coach')
    from fastapi.testclient import TestClient
    from baseball_batting.api import create_app
    from test_api import AUTH,wait_until
    from test_product import retained_review_job
    service,identifier,job,product=retained_review_job(tmp_path)
    (job/'result.json').write_text('{"tampered":true}')
    with TestClient(create_app(service.settings,service)) as client:
        wait_until(lambda:service.ready)
        response=client.post(f'/v1/analyses/{identifier}/video-review',headers=AUTH)
        assert response.status_code==500 and 'integrity' in response.json()['detail']
        assert client.get(f'/v1/analyses/{identifier}/product',headers=AUTH).json()==product


def test_gemini_receives_only_sampled_rep_measurements_and_cannot_create_a_grade(tmp_path):
    pytest.importorskip('ai_coach')
    from ai_coach.video_review import review_video,OBJECTIVE_STYLE
    from ai_coach.schemas import Usage
    from test_product import coach_settings,frames
    from test_visual_scoring import graded_note
    context=report();other=deepcopy(context['reps'][0]);other['rep']=2;context['reps'].append(other)
    def generate(settings,images,facts):
        assert facts['feedback_style']==OBJECTIVE_STYLE
        assert [r['rep'] for r in facts['engine_measurements']['reps']]==[1]
        assert facts['engine_measurements']['reps'][0]['features'][0]['measurements'][1]['value']==50
        return json.dumps(graded_note(('clear','clear','clear'))),Usage()
    reviewed=review_video(frames(),{},coach_settings(tmp_path),generator=generate,objective_context=context)
    assert reviewed['status']=='completed' and reviewed['score']['value'] is None
    assert reviewed['score']['reason_code']=='replaced_by_measurement_coverage'
    assert all(f['rating'] is None for f in reviewed['features'])
    assert reviewed['priority'] is None and reviewed['drill'] is None
    assert reviewed['text_style_version']==OBJECTIVE_STYLE


def test_objective_visual_notes_remove_generic_performance_judgments(tmp_path):
    pytest.importorskip('ai_coach')
    from ai_coach.video_review import review_video
    from ai_coach.schemas import Usage
    from test_product import coach_settings,frames
    from test_visual_scoring import graded_note
    note=graded_note();note['features'][0]['observation']='Your preparation is smooth and your swing is powerful.'
    reviewed=review_video(frames(),{},coach_settings(tmp_path),objective_context=report(),
        generator=lambda *a:(json.dumps(note),Usage()))
    assert reviewed['status']=='completed' and reviewed['features'][0]['status']=='unclear'
    assert 'powerful' not in reviewed['features'][0]['observation']
    assert reviewed['features'][1]['status']=='observed'
    assert reviewed['guardrail_warnings']==[{'feature':'load_timing','reason_code':'subjective_visual_description_removed'}]