baseball-engine / tests /test_gvhmr_motion.py
github-actions[bot]
Automated Deploy: acb55f69ee3929c586c3ebc183e5ee1e69ca2acb
9756876
Raw History Blame Contribute Delete
15 kB
"""Known-sequence adapter/clock/export checks. These do not claim model accuracy."""
import json
from pathlib import Path
import numpy as np
import pytest
from fastapi.testclient import TestClient
from baseball_batting.motion_contract import MotionInput
from baseball_batting.motion_adapters import SMPLX_MAP,MHR,smplx_to_calculation,skeleton,GVHMR_REVISION
from baseball_batting.gvhmr_adapter import native_prediction,uniform_grid,resample_rotations,sequence_windows,COCO
from baseball_batting.motion_export import export_motion,reproduce_measurements
from baseball_batting.storage import atomic_json,sha256_file
from baseball_batting.ingest import ingest
from baseball_batting.geometry import project
from baseball_batting.api import create_app
from baseball_batting.api_jobs import JobService
from test_motion_player import raw_for,inputs
from test_api import settings,fake_service,wait_until,AUTH
def native_fixture(capture):
original=raw_for(capture);n=capture['frame_count']
names=['unused']*76
native=np.full((n,76,3),np.nan)
for name,index in SMPLX_MAP.items():names[index]=name;native[:,index]=original['points_body'][:,MHR[name]]
observed=np.zeros((n,17,3));observed[:,:,2]=1
for name,index in COCO.items():observed[:,index,:2]=original['projection'][:,MHR[name]]
boxes=np.tile([0,0,*original['image_size']],(n,1))
raw=native_prediction(native,names,original['camera_translation'],original['intrinsics'],
original['image_size'],observed,boxes,MotionInput().gvhmr.model_dump())
return raw,native,names,observed,boxes
def test_native_mapping_is_checked_and_translation_is_not_added_twice(video):
capture=ingest(video,inputs().metadata());raw,native,names,observed,boxes=native_fixture(capture)
np.testing.assert_allclose(raw['points_body'][:,MHR['left_hip']],native[:,1])
np.testing.assert_allclose(raw['projection'][:,MHR['right_wrist']],
np.array([project(j[21]+c,k) for j,c,k in zip(native,raw['camera_translation'],raw['intrinsics'])]))
assert skeleton('gvhmr')['joints'][0]['derived'] is True
shoulder=next(j for j in skeleton('gvhmr')['joints'] if j['name']=='left_shoulder')
assert shoulder['source_index']==16 and shoulder['source_schema']=='SMPL-X' and shoulder['derived'] is False
names[16]='left_acromion'
with pytest.raises(ValueError,match='anatomical mapping'):smplx_to_calculation(native,names)
def test_occluded_wrist_and_camera_inconsistency_disable_only_dependent_points(video):
capture=ingest(video,inputs().metadata());raw,native,names,observed,boxes=native_fixture(capture)
observed[3,COCO['right_wrist'],2]=.01
observed[4,COCO['left_wrist'],0]+=1000
out=native_prediction(native,names,raw['camera_translation'],raw['intrinsics'],raw['image_size'],
observed,boxes,MotionInput().gvhmr.model_dump())
assert not out['joint_usable'][3,MHR['right_wrist']]
assert not out['joint_usable'][4,MHR['left_wrist']]
assert out['joint_usable'][:,[MHR['left_ankle'],MHR['right_ankle']]].all()
assert out['projection_valid'].all()
def test_uniform_model_clock_rotations_and_chunks_do_not_bridge_gaps():
with pytest.raises(ValueError,match='nonempty core'):
MotionInput(model='gvhmr',gvhmr={'max_sequence_frames':90,'context_frames':60})
t=np.array([0,.016,.033,.051,.066,.083,1.,1.016,1.033,1.05])
grid=uniform_grid(t[:6]);np.testing.assert_allclose(np.diff(grid),1/30)
# +170 -> -170 degrees takes the short route through 180, never through zero.
rotations=np.deg2rad([[0,0,170],[0,0,-170]])
result=resample_rotations(rotations,np.array([0.,1.]),np.array([.5]))
assert abs(np.linalg.norm(result[0])-np.pi)<1e-8
windows=list(sequence_windows(np.ones(len(t),bool),t,.1,90,10))
assert len(windows)==2
assert windows[0][0].tolist()==list(range(6)) and windows[1][0].tolist()==list(range(6,10))
dense=np.arange(800)/60
chunks=list(sequence_windows(np.ones(len(dense),bool),dense,.1,90,10))
owners=np.zeros(len(dense),int)
for run,g,a,b,start,end in chunks:
source=dense[run]
take=run[(source>=g[start])&((source<g[end]) if end<len(g) else (source<=g[-1]))]
owners[take]+=1
assert b-a<=90
assert (owners==1).all()
def test_gvhmr_public_motion_reproduces_measurements_and_annotated_timeline(tmp_path,video):
opts=inputs(model='gvhmr',timing={'kind':'unretimed','source':'Known fixture clock'})
capture=ingest(video,opts.metadata());raw,*_=native_fixture(capture)
raw['sequence_ids']=np.zeros(capture['frame_count'],int)
raw['temporal_resampled']=np.array([False,True,False,True,False,True,False,False])
manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic SMPL-X adapter fixture'},
{'analysis_id':'fixture','analysis_revision':1})
assert manifest.pipeline['selected_model']=='gvhmr'
assert manifest.pipeline['measurement_definition_version']=='batting-corrected-points-smplx-v1'
assert manifest.coordinates['left_right'].endswith('SMPL-X')
assert manifest.skeleton['version']=='smplx-batting-20-v1'
rows=[json.loads(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
assert len(rows)==capture['frame_count'] and all(len(f['joints'])==20 for f in rows)
assert rows[1]['joints']['left_shoulder']['status']=='interpolated'
assert 'smplx_surface_landmark_derivation' in rows[0]['joints']['left_ear']['reasons']
groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
summaries=json.loads((tmp_path/'measurements.json').read_text())['summaries']
for metric in summaries:assert values[metric['rep'],metric['metric_id']]==metric['value']
assert all(m['uses_interpolated_input'] for m in summaries)
assert all(m['sample_spacing_ms']>=33.333 for m in summaries if m['unit'] in ('ms','m/s','deg/s'))
assert all(manifest.artifacts['annotated_'+key].status=='available' for key in ('rotation','timing','posture','stance'))
from baseball_batting.ingest import iter_frames
assert [float(pts*base) for _,pts,base,_ in iter_frames(tmp_path/'group-videos/rotation.mp4')]==pytest.approx([f['video_time_s'] for f in rows],abs=2e-6)
def test_model_window_jump_does_not_become_velocity_evidence(tmp_path,video):
opts=inputs(model='gvhmr',annotated_videos=False,timing={'kind':'unretimed','source':'Known fixture clock'})
capture=ingest(video,opts.metadata());raw,*_=native_fixture(capture)
raw['points_body'][4:,MHR['left_wrist'],0]+=.4
raw['projection']=np.stack([project(p+c,k) for p,c,k in zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
raw['sequence_ids']=np.array([0]*4+[1]*4)
manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic chunk-boundary fixture'},
{'analysis_id':'fixture','analysis_revision':1})
rows=[json.loads(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
assert rows[3]['segment_id']!=rows[4]['segment_id']
series=json.loads((tmp_path/'measurements.json').read_text())['series']
assert all(s['value'] is None for curve in series if curve['unit'] in ('m/s','deg/s') for s in curve['samples'])
original=json.loads((tmp_path/'measurements.json').read_text())['summaries']
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}
assert all(values[m['rep'],m['metric_id']]==m['value'] for m in original)
def test_real_swing_candidate_survives_a_larger_model_boundary_jump():
from test_sam_batting import pose
from baseball_batting.sam_measurements import calculate_measurements
t=np.arange(150)/60;points=pose(len(t))
points[:,[41,62],0]+=(.4*np.tanh((t-1.8)/.08))[:,None]
# A model boundary jump is larger/faster than the actual swing.
points[36:,[41,62],0]+=1.
boundary=np.zeros(points.shape[:2],bool);boundary[34:39]=True
boundary[:2]=True;boundary[-2:]=True
_,contexts=calculate_measurements({'points_relative':points,'boundary':boundary},t,inputs().sam_options())
window=contexts[0]['window']
assert t[window['forward_start_frame']]>1.
assert t[window['forward_start_frame']]<1.8<t[window['forward_end_frame']]
def test_model_selector_readiness_is_independent_and_unknown_model_is_rejected(tmp_path,video,monkeypatch):
import baseball_batting.motion_api as module
service=fake_service(settings(tmp_path),delay=30)
monkeypatch.setattr(module,'configured_record',lambda:None)
monkeypatch.setattr(module.gvhmr_runtime,'configured_record',lambda:{'configured':True})
files={'video':('clip.mp4',video.read_bytes(),'video/mp4')}
with TestClient(create_app(service.settings,service)) as client:
wait_until(lambda:service.ready)
capability=client.get('/v1/motion-analyses/capabilities',headers=AUTH).json()
assert capability['default_model']=='sam3d' and {m['id'] for m in capability['models']}=={'sam3d','gvhmr'}
assert client.post('/v1/motion-analyses',headers=AUTH,files=files,data={'options':'{"model":"other"}'}).status_code==422
assert client.post('/v1/motion-analyses',headers=AUTH,files=files).status_code==503
r=client.post('/v1/motion-analyses',headers=AUTH,files=files,data={'options':'{"model":"gvhmr"}'})
assert r.status_code==202,r.text
job=service.job_directory(r.json()['job_id'])
assert json.loads((job/'request.json').read_text())['model']=='gvhmr'
client.delete(r.json()['status_url'],headers=AUTH)
def test_model_switch_runs_fresh_inference_and_preserves_parent(tmp_path,video,monkeypatch):
import baseball_batting.motion_worker as worker
import baseball_batting.motion_api as api
service=JobService(settings(tmp_path));service.ready=True;calls=[]
monkeypatch.setattr(api,'configured_record',lambda:{'configured':True})
monkeypatch.setattr(api.gvhmr_runtime,'configured_record',lambda:{'configured':True})
def infer(model,job,source,capture):
calls.append(model);raw=raw_for(capture) if model=='sam3d' else native_fixture(capture)[0]
stem='sam' if model=='sam3d' else 'gvhmr'
np.savez_compressed(job/(stem+'-raw-private.npz'),**raw)
atomic_json(job/(stem+'-raw-private.json'),{'model':{'name':model+' fixture'}})
atomic_json(job/'person-track-private.json',{'reasons':[None]*capture['frame_count']})
return raw,{'name':model+' fixture'}
monkeypatch.setattr(worker,'reconstruct_sam',lambda job,source,capture,*a,**k:infer('sam3d',job,source,capture))
monkeypatch.setattr(worker,'reconstruct_gvhmr',lambda job,source,capture,*a,**k:infer('gvhmr',job,source,capture))
lineage=service.store.create_motion(20);parent=service.job_directory(lineage['job_id']);parent.mkdir()
(parent/'input.mp4').write_bytes(video.read_bytes())
atomic_json(parent/'lineage.json',lineage)
atomic_json(parent/'request.json',inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'}).model_dump(mode='json'))
worker.run(parent,tmp_path/'models');before=(parent/'result.json').read_bytes()
service.store.update(parent.name,'completed',result_hash=sha256_file(parent/'result.json'))
client=TestClient(create_app(service.settings,service))
child=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':{'model':'gvhmr'}})
assert child.status_code==202,child.text
directory=service.job_directory(child.json()['job_id'])
assert not (directory/'reused-inference.json').exists()
result=worker.run(directory,tmp_path/'models')
assert calls==['sam3d','gvhmr'] and result.analysis_revision==2
assert (parent/'result.json').read_bytes()==before
service.store.update(directory.name,'completed',result_hash=sha256_file(directory/'result.json'))
reviewed=client.post('/v1/motion-analyses/'+directory.name+'/revisions',headers=AUTH,json={'options':{'correction':{'min_cutoff_hz':8}}})
assert reviewed.status_code==202,reviewed.text
reviewed_dir=service.job_directory(reviewed.json()['job_id'])
assert (reviewed_dir/'reused-inference.json').exists()
worker.run(reviewed_dir,tmp_path/'models');assert calls==['sam3d','gvhmr']
different_clock=client.post('/v1/motion-analyses/'+directory.name+'/revisions',headers=AUTH,json={'options':{'timing':{'kind':'unknown'}}})
assert different_clock.status_code==202
assert not (service.job_directory(different_clock.json()['job_id'])/'reused-inference.json').exists()
def test_missing_licensed_body_model_stops_setup_before_any_download(tmp_path,monkeypatch):
from tools import prepare_gvhmr_assets
monkeypatch.setenv('BASEBALL_DATA_ROOT',str(tmp_path))
monkeypatch.setenv('BASEBALL_GVHMR_SOURCE',str(tmp_path))
monkeypatch.setenv('BASEBALL_GVHMR_WORKER_RECORD',str(tmp_path/'gvhmr-api-worker.json'))
(tmp_path/'gvhmr-api-worker.json').write_text('{"stale":true}')
monkeypatch.delenv('BASEBALL_SMPLX_MODEL_PATH',raising=False);monkeypatch.delenv('BASEBALL_SMPLX_REPO',raising=False)
monkeypatch.setattr(prepare_gvhmr_assets.subprocess,'check_output',lambda *a,**k:GVHMR_REVISION)
assert prepare_gvhmr_assets.main()==1
assert json.loads((tmp_path/'gvhmr-setup-status.json').read_text())['reason_code']=='gvhmr_smplx_license_asset_required'
assert not (tmp_path/'gvhmr-cache').exists()
assert not (tmp_path/'gvhmr-api-worker.json').exists()
def test_optional_bootstrap_does_not_block_api_or_install_without_license(tmp_path,monkeypatch):
from tools import setup_gvhmr_api_worker as setup
monkeypatch.setattr('baseball_batting.gvhmr_runtime.configured_record',lambda:None)
monkeypatch.setenv('BASEBALL_DATA_ROOT',str(tmp_path))
monkeypatch.delenv('BASEBALL_GVHMR_SKIP_SETUP',raising=False)
monkeypatch.delenv('BASEBALL_SMPLX_MODEL_PATH',raising=False);monkeypatch.delenv('BASEBALL_SMPLX_REPO',raising=False)
calls=[];monkeypatch.setattr(setup.subprocess,'Popen',lambda *a,**k:calls.append((a,k)))
assert setup.launch_optional_setup() is False and not calls
assert json.loads((tmp_path/'gvhmr-setup-status.json').read_text())['reason_code']=='gvhmr_smplx_license_asset_required'
monkeypatch.setenv('BASEBALL_SMPLX_REPO','operator/private-licensed-copy')
monkeypatch.setenv('BASEBALL_API_KEY','fixture-service-secret');monkeypatch.setenv('GOOGLE_API_KEY','fixture-google-secret')
monkeypatch.setenv('HF_TOKEN','fixture-approved-hub-token')
assert setup.launch_optional_setup() is True and len(calls)==1
env=calls[0][1]['env']
assert 'BASEBALL_API_KEY' not in env and 'GOOGLE_API_KEY' not in env
assert env['HF_TOKEN']=='fixture-approved-hub-token'
assert 'HF_TOKEN' not in setup.installation_environment()