File size: 15,346 Bytes
d835db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445f7bc
 
 
d835db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445f7bc
 
 
 
d835db0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de94a96
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Replay/recalculation agreement, clocks, conditional validity and immutable artifacts."""
import json
from pathlib import Path
import numpy as np
import pytest
from baseball_batting.motion_contract import MotionInput,MotionManifest,MotionFrame
from baseball_batting.motion_export import export_motion,reproduce_measurements,JOINTS
from baseball_batting.ingest import ingest,iter_frames
from baseball_batting.geometry import project
from baseball_batting.sam_motion import MHR
from baseball_batting.storage import sha256_file,atomic_json
from test_sam_batting import pose,raw_pose


def inputs(**kwargs):
    return MotionInput(camera_stability='fixed_verified',up_vector=[0,-1,0],up_source='Known fixture vertical',
        handedness='right',single_swing=True,**kwargs)


def raw_for(capture):
    f=capture['frames'][0];raw=raw_pose(pose(capture['frame_count']),f['width'],f['height'])
    # A known camera making all requested fixture joints visible, not a SAM accuracy claim.
    raw['intrinsics'][:,0,0]=raw['intrinsics'][:,1,1]=60
    raw['projection']=np.stack([project(p+c,k) for p,c,k in zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
    return raw


def build(tmp_path,video,opts=None,mutate=None):
    opts=opts or inputs(timing={'kind':'unretimed','source':'Known synthetic clock'})
    capture=ingest(video,opts.metadata());raw=raw_for(capture)
    if mutate:mutate(raw)
    manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic fixture, not SAM'},
        {'analysis_id':'fixture-analysis','analysis_revision':1},retention_s=100)
    return manifest,capture,raw


def test_artifacts_reconstruct_all_joints_and_reproduce_measurements(tmp_path,video):
    manifest,capture,_=build(tmp_path,video)
    MotionManifest.model_validate_json((tmp_path/'result.json').read_text())
    frames=[MotionFrame.model_validate_json(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
    assert len(frames)==capture['frame_count']
    expected={side+'_'+part for side in ('left','right') for part in
              ('ear','shoulder','elbow','wrist','hip','knee','ankle','heel','big_toe','small_toe')}
    assert set(manifest.skeleton['joint_order'])==expected and len(expected)==20
    assert all(set(f.joints)==set(JOINTS) for f in frames)
    assert all(f.joints['left_wrist'].confidence is None for f in frames)
    assert manifest.coordinates['root_translation_included'] is False
    assert manifest.source_video['sha256']==sha256_file(video)
    assert manifest.source_video['duration_s']>frames[-1].video_time_s
    for asset in manifest.artifacts.values():
        if asset.status=='available':assert sha256_file(tmp_path/asset.filename)==asset.sha256
    assert (tmp_path/'source.mp4').read_bytes()==video.read_bytes()
    series=json.loads((tmp_path/'measurements.json').read_text())
    recomputed=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
    values={(s.rep,m.key):m.value for swings in recomputed.values() for s in swings for m in s.measurements}
    for metric in series['summaries']:
        value=values[metric['rep'],metric['metric_id']]
        assert value==pytest.approx(metric['value']) if value is not None else metric['value'] is None
    assert {g for g in ('rotation','timing','posture','stance')}=={s['group'] for s in series['series']}
    # Variable-cadence source timestamps survive both exported motion and all four videos.
    expected=[r['playback_s']-capture['frames'][0]['playback_s'] for r in capture['frames']]
    np.testing.assert_allclose([f.video_time_s for f in frames],expected)
    for group in ('rotation','timing','posture','stance'):
        actual=list(iter_frames(tmp_path/'group-videos'/(group+'.mp4')))
        np.testing.assert_allclose([float(pts*base) for _,pts,base,_ in actual],expected,atol=2e-6)
        assert actual[0][3].shape[:2]==(capture['frames'][0]['height'],capture['frames'][0]['width'])


def test_public_projection_uses_same_motion_and_root_exactly_once(tmp_path,video):
    opts=inputs(scale_factor=2,scale_source='Fixture known scale',timing={'kind':'unretimed','source':'Fixture clock'})
    manifest,_,_=build(tmp_path,video,opts)
    motion=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
    projections=[json.loads(l) for l in (tmp_path/'projections.jsonl').read_text().splitlines()]
    rotation=np.array(manifest.coordinates['camera_to_export_rotation'])
    assert np.linalg.det(rotation)==pytest.approx(1)
    for frame,projection in zip(motion,projections):
        assert frame['source_frame_index']==projection['source_frame_index']
        for name,joint in frame['joints'].items():
            if joint['position'] is None:continue
            camera=(np.array(joint['position'])+frame['root_translation'])@rotation
            xy=project(camera,projection['camera_intrinsics'])
            np.testing.assert_allclose(xy,projection['joints'][name]['pixel'],atol=1e-9)
    # Corrected joints stay in a fixed, right-handed frame, with anatomical mapping.
    assert manifest.skeleton['joint_order'].index('left_wrist')!=MHR['left_wrist']
    assert next(j for j in manifest.skeleton['joints'] if j['name']=='left_wrist')['source_index']==62
    recomputed=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
    stance=next(m for s in recomputed['stance'] for m in s.measurements if m.key=='stance_span_cm')
    assert stance.value==120


@pytest.mark.parametrize('kind',['unknown_clock','unknown_scale','unknown_camera','missing_wrist','spike'])
def test_specific_quality_and_missing_dependencies_do_not_remove_other_groups(tmp_path,video,kind):
    if kind=='spike':
        # Robust spike statistics need a longer clean baseline than the eight-frame cadence fixture.
        import av
        video=tmp_path/'spike.mp4'
        with av.open(str(video),'w') as out:
            stream=out.add_stream('libx264',rate=30);stream.width=160;stream.height=120;stream.pix_fmt='yuv420p'
            for i in range(31):
                for packet in stream.encode(av.VideoFrame.from_ndarray(np.full((120,160,3),i,np.uint8),format='bgr24')):out.mux(packet)
            for packet in stream.encode():out.mux(packet)
    kwargs={'annotated_videos':False,'timing':{'kind':'unretimed','source':'Fixture clock'}}
    if kind=='unknown_clock':kwargs['timing']={'kind':'unknown'}
    if kind=='unknown_scale':kwargs['scale_status']='unknown'
    opts=inputs(**kwargs)
    if kind=='unknown_camera':opts.camera_stability='moving'
    def mutate(raw):
        if kind=='missing_wrist':raw['points_body'][4,MHR['right_wrist']]=np.nan
        if kind=='spike':raw['points_body'][4,MHR['left_wrist'],0]+=1
    manifest,_,_=build(tmp_path,video,opts,mutate)
    rows=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
    values=json.loads((tmp_path/'measurements.json').read_text())
    if kind=='unknown_clock':
        assert all(f['capture_time_s'] is None for f in rows)
        assert all(m['value'] is None for m in values['summaries'] if m['unit'] in ('m/s','deg/s','ms'))
    if kind=='unknown_scale':
        assert manifest.coordinates['unit']=='model_units'
        assert all(m['value'] is None and m['reason_code']=='scale_unknown' for m in values['summaries'] if m['unit'] in ('cm','m/s'))
    if kind=='unknown_camera':
        assert manifest.coordinates['frame']=='camera_oriented_hip_relative'
        assert manifest.coordinates['axes']['y']=='camera_down'
        assert all(m['value'] is None for m in values['summaries'] if m['unit']=='deg')
    if kind in ('missing_wrist','spike'):
        name='right_wrist' if kind=='missing_wrist' else 'left_wrist'
        joint=rows[4]['joints'][name]
        assert joint['position'] is None
        assert joint['status']==('missing' if kind=='missing_wrist' else 'rejected')
        assert next(m['value'] for m in values['summaries'] if m['metric_id']=='stance_span_cm')==60
    assert not any(f['joints'][name]['status']=='interpolated' for f in rows for name in JOINTS)
    assert manifest.artifacts['mesh'].status=='unavailable'
    assert all(a.status=='unavailable' for key,a in manifest.artifacts.items() if key.startswith('annotated_'))
    for path in tmp_path.glob('*.json*'):
        for line in path.read_text().splitlines() if path.suffix=='.jsonl' else [path.read_text()]:
            json.loads(line,parse_constant=lambda v:(_ for _ in ()).throw(ValueError(v)))


def test_retiming_events_and_immutable_export_are_aligned(tmp_path,video):
    opts=inputs(timing={'kind':'constant_slowdown','source':'Fixture capture','factor':4,'all_captured_frames_retained':True},
        annotated_videos=False,windows=[{'start_frame':0,'end_frame':7,'baseline_frame':0,
            'stride_start_frame':1,'landing_frame':5,'forward_start_frame':1,'forward_end_frame':6,'forward_rotation_sign':1}])
    manifest,capture,_=build(tmp_path,video,opts)
    frames=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
    np.testing.assert_allclose([f['capture_time_s'] for f in frames],[f['video_time_s']/4 for f in frames])
    events=json.loads((tmp_path/'events.json').read_text())['events']
    plant=next(e for e in events if e['type']=='foot_plant')
    assert plant['source']=='manual' and plant['status']=='reviewed'
    assert plant['start']['source_frame_index']==5
    assert plant['start']['capture_time_s']==pytest.approx(capture['frames'][5]['physical_s'])
    assert next(e for e in events if e['type']=='ball_contact')['status']=='unavailable'
    # A resumed export is safe if the source link was already written before restart.
    original=manifest.artifacts['source'].sha256
    export_motion(tmp_path,video,capture,raw_for(capture),opts,{'name':'fixture'},
        {'analysis_id':'fixture-analysis','analysis_revision':1})
    assert sha256_file(tmp_path/'source.mp4')==original


def test_no_usable_pose_is_failure_instead_of_empty_success(tmp_path,video):
    def missing(raw):raw['points_body'][:]=np.nan
    with pytest.raises(ValueError,match='no_usable_motion'):build(tmp_path,video,mutate=missing)
    assert not (tmp_path/'result.json').exists()


def test_pose_quality_limit_cannot_exceed_the_declared_joint_count():
    with pytest.raises(ValueError):MotionInput(minimum_usable_joints=21)


def test_clock_gaps_and_identity_uncertainty_remain_explicit(tmp_path,video):
    opts=inputs(annotated_videos=False,timing={'kind':'explicit','source':'Known fixture times',
        'physical_times_s':[0,.01,.02,.03,1.,1.01,1.02,1.03]})
    capture=ingest(video,opts.metadata());raw=raw_for(capture)
    track={'reasons':[None]*6+['identity_uncertain_after_tracking_loss']*2}
    manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
        {'analysis_id':'fixture','analysis_revision':1},track=track)
    rows=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
    assert rows[3]['segment_id']!=rows[4]['segment_id']
    assert 'timestamp_gap' in rows[4]['frame_quality']['reasons']
    assert not rows[6]['frame_quality']['pose_available']
    assert all(j['position'] is None for j in rows[6]['joints'].values())
    assert all('identity_uncertain_after_tracking_loss' in j['reasons'] for j in rows[6]['joints'].values())
    assert np.isfinite(raw['points_body']).all()  # Debug predictions have not been overwritten.
    series=json.loads((tmp_path/'measurements.json').read_text())['series']
    assert all(s['value'] is None for metric in series if metric['unit'] in ('deg/s','m/s') for s in metric['samples'])


def test_worker_reuses_native_inference_for_reviewed_event_revision(tmp_path,video,monkeypatch):
    from baseball_batting import motion_worker
    from baseball_batting.api import create_app
    from baseball_batting.api_jobs import JobService
    from fastapi.testclient import TestClient
    from test_api import settings,AUTH
    service=JobService(settings(tmp_path));calls=[]
    def infer(job,source,capture,models,options,progress,**kwargs):
        calls.append(kwargs);raw=raw_for(capture)
        np.savez_compressed(job/'sam-raw-private.npz',**raw)
        model={'name':'fixture only'}
        atomic_json(job/'sam-raw-private.json',{'model':model})
        atomic_json(job/'person-track-private.json',{'reasons':[None]*capture['frame_count']})
        return raw,model
    monkeypatch.setattr(motion_worker,'reconstruct_sam',infer)
    monkeypatch.setattr('baseball_batting.motion_api.configured_record',lambda:{'configured':True})
    lineage=service.store.create_motion(20);parent=service.job_directory(lineage['job_id']);parent.mkdir()
    (parent/'input.mp4').write_bytes(video.read_bytes())
    opts=inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'})
    atomic_json(parent/'request.json',opts.model_dump(mode='json'));atomic_json(parent/'lineage.json',lineage)
    motion_worker.run(parent,tmp_path/'models')
    service.store.update(parent.name,'completed',result_hash=sha256_file(parent/'result.json'))
    before=(parent/'result.json').read_bytes();service.ready=True
    client=TestClient(create_app(service.settings,service))
    r=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,
        json={'options':{'correction':{'min_cutoff_hz':8},'windows':[{'start_frame':0,'end_frame':7,'stride_start_frame':1,'landing_frame':5}]}})
    assert r.status_code==202
    child=service.job_directory(r.json()['job_id']);assert (child/'reused-inference.json').is_file()
    result=motion_worker.run(child,tmp_path/'models')
    assert len(calls)==1 and calls[0]['strict_identity'] is True
    assert result.analysis_revision==2 and result.analysis_id==lineage['analysis_id']
    assert result.pipeline['model']['inference_reused_from_job']==parent.name
    assert (parent/'result.json').read_bytes()==before
    # Queue finalization removes only the upload link, retaining the authenticated source artifact.
    import sys
    service.command_factory=lambda directory:[sys.executable,'-c','pass']
    service.store.claim();service.execute(child.name)
    assert service.store.get(child.name)['status']=='completed'
    assert not (child/'input.mp4').exists() and (child/'source.mp4').exists()
    reject=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,
        json={'options':{'athlete_box':[0,0,100,100]}})
    assert reject.status_code==422


def test_overlapping_athletes_do_not_silently_switch_identity(video,monkeypatch,tmp_path):
    from baseball_batting.sam_measurement_worker import athlete_boxes
    opts=inputs();capture=ingest(video,opts.metadata())
    a={'class_id':0,'box':[20,5,100,115],'score':.9}
    b={'class_id':0,'box':[35,5,115,115],'score':.95}
    detections=iter([[a],[a,b]]+[[a]]*6)
    monkeypatch.setattr('baseball_batting.api_worker.model_files',lambda _:({'person_detector':'fixture'},None))
    monkeypatch.setattr('baseball_batting.detection.YOLOXDetector',lambda *args,**kwargs:lambda image:next(detections))
    boxes,reasons=athlete_boxes(video,capture,tmp_path,opts,'fixture',lambda *a:None,strict_identity=True)
    assert boxes[0]==a['box'] and all(box is None for box in boxes[1:])
    assert reasons[1]=='identity_ambiguous_multiple_overlapping_athletes'
    assert all(r=='identity_uncertain_after_tracking_loss' for r in reasons[2:])