Spaces:
Running on T4
Running on T4
Download tests/test_motion_coach.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 22 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_motion_coach.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tests/test_motion_coach.py
-
curl -L -o test_motion_coach.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_motion_coach.py
22 kB
| """Contract compatibility, exact event sampling and immutable delivery; no model accuracy claim.""" | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pytest | |
| from fastapi.testclient import TestClient | |
| from ai_coach.swing_report.validation import validate_payload | |
| from baseball_batting.api import create_app | |
| from baseball_batting.motion_contract import MotionInput | |
| from baseball_batting.motion_coach import build_coach_payload | |
| from baseball_batting.motion_export import export_motion | |
| from baseball_batting.sam_motion import MHR | |
| from baseball_batting.storage import atomic_json, sha256_file | |
| from test_api import settings, fake_service, AUTH | |
| from test_motion_player import inputs, raw_for | |
| from baseball_batting.ingest import ingest | |
| from baseball_batting.geometry import project | |
| from test_sam_batting import pose | |
| PLAYER = {'athlete_id': 'player-test', 'age_years': 16, 'height_cm': 175.0} | |
| WINDOW = {'start_frame': 0, 'end_frame': 7, 'baseline_frame': 0, | |
| 'stride_start_frame': 1, 'landing_frame': 4, | |
| 'forward_start_frame': 3, 'forward_end_frame': 7} | |
| LINEAGE = {'analysis_id': 'analysis-test', 'analysis_revision': 1} | |
| def options(**patch): | |
| base = inputs(annotated_videos=False, athlete=PLAYER, context={'practice_type': 'tee'}, | |
| windows=[WINDOW], contact_frame=6) | |
| return MotionInput.model_validate({**base.model_dump(mode='json'), **patch}) | |
| def motion(): | |
| p = pose(8) | |
| # Event values are distinct from the maximum; picking the summary would be wrong. | |
| for i, angle in enumerate([0, 5, 70, 45, 30, 20, 10, 0]): | |
| q = np.deg2rad(angle) | |
| p[i, 5] = [-.25*np.cos(q), -.5, -.25*np.sin(q)] | |
| p[i, 6] = [.25*np.cos(q), -.5, .25*np.sin(q)] | |
| p[4:, MHR['left_ankle'], 0] -= .2 | |
| p[4:, MHR['left_ankle'], 2] += .1 | |
| return {'points_relative': p, 'valid': np.isfinite(p).all(axis=-1), | |
| 'boundary': np.zeros((8, 70), bool), 'interpolated': np.zeros((8, 70), bool)} | |
| def payload(opts=None, corrected=None, physical=True): | |
| video = np.array([0, .03, .07, .10, .15, .19, .22, .27]) | |
| capture = video/4 if physical else np.full(8, np.nan) | |
| result = build_coach_payload(opts or options(), LINEAGE, corrected or motion(), video, capture, []) | |
| data = result.model_dump(mode='json') | |
| parsed, problems = validate_payload(data) | |
| assert not problems, problems | |
| assert parsed is not None | |
| return data | |
| def values(data): | |
| return {m['metric_id']: m for m in data['measurements']} | |
| def test_exact_selected_frames_relative_stride_and_receiver_contract(): | |
| data = payload() | |
| rows = values(data) | |
| assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30 | |
| assert rows['hip_shoulder_separation_at_contact']['value'] == 10 | |
| assert rows['stride_relative_length']['value'] == pytest.approx(22.361) | |
| assert rows['stride_relative_length']['reasons'] == ['event_timing_uncertain', 'scale_is_model_estimated', 'model_accuracy_unvalidated'] | |
| assert all(m['status'] == 'limited' and m['confidence'] is None and m['benchmark'] is None | |
| for m in data['measurements'] if m['value'] is not None) | |
| assert data['events']['contact'] == {'video_time_s': .22, 'capture_time_s': .055, | |
| 'source': 'manual_review', 'status': 'limited', 'source_frame_index': 6, 'reasons': ['event_timing_uncertain']} | |
| assert data['athlete'] == {**PLAYER, 'batting_hand': 'right', 'lead_foot': 'left'} | |
| assert data['swing_id'] == LINEAGE['analysis_id'] + ':swing_1' | |
| # Point-only and interval-only scope fields must be absent, including nulls. | |
| assert 'start_event_id' not in rows['hip_shoulder_separation_at_contact'] | |
| assert 'event_id' not in rows['stride_relative_length'] | |
| def test_player_fields_merge_with_existing_inputs_and_all_old_fields_are_preserved(): | |
| example = json.loads((Path(__file__).parents[1]/'docs/motion-options.example.json').read_text()) | |
| example.update(single_swing=True, athlete={**PLAYER, 'batting_hand': 'left'}, contact_frame=6, | |
| windows=[WINDOW], pitcher_floor_points={'source_frame_index': 0, | |
| 'near_batter': [10, 100], 'toward_pitcher': [70, 90]}) | |
| parsed = MotionInput.model_validate(example) | |
| assert parsed.handedness == 'left' | |
| dumped = parsed.model_dump(mode='json') | |
| assert dumped['windows'][0]['baseline_frame'] == 0 | |
| assert dumped['windows'][0]['forward_start_frame'] == 3 | |
| for key in ('gvhmr', 'refinement', 'tracking', 'correction', 'measurement', 'up_estimation', 'pitcher_floor_points'): | |
| assert all(dumped[key][field] == value for field, value in example[key].items()) | |
| assert MotionInput().athlete is None and MotionInput().contact_frame is None | |
| def test_invalid_or_ambiguous_new_inputs_are_rejected(patch): | |
| with pytest.raises(ValueError): | |
| options(**patch) | |
| def test_unavailable_dependencies_do_not_invent_or_remove_other_metrics(mode): | |
| opts = options(); corrected = motion() | |
| if mode == 'no_contact': opts = options(contact_frame=None) | |
| if mode == 'dry_swing': opts = options(contact_frame=None, context={'practice_type': 'dry_swing'}) | |
| if mode == 'no_stride': opts = options(windows=[]) | |
| if mode == 'unknown_scale': opts = options(scale_status='unknown') | |
| if mode == 'unknown_up': opts = options(up_vector=None, up_source=None) | |
| if mode == 'moving_camera': opts = options(camera_stability='moving') | |
| if mode in ('missing_ankle', 'missing_shoulder'): | |
| name = 'left_ankle' if mode == 'missing_ankle' else 'left_shoulder' | |
| corrected['points_relative'][4, MHR[name]] = np.nan | |
| corrected['valid'][4, MHR[name]] = False | |
| data = payload(opts, corrected, physical=mode != 'unknown_clock') | |
| rows = values(data) | |
| assert len(rows) == 9 | |
| if mode in ('no_contact', 'dry_swing'): | |
| reason = 'contact_not_applicable' if mode == 'dry_swing' else 'contact_not_verified' | |
| assert data['events']['contact']['reasons'] == [reason] | |
| assert rows['hip_shoulder_separation_at_contact']['value'] is None | |
| assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30 | |
| if mode in ('no_stride', 'unknown_scale', 'missing_ankle'): | |
| assert rows['stride_relative_length']['value'] is None | |
| assert rows['hip_shoulder_separation_at_contact']['value'] == 10 | |
| if mode == 'unknown_clock': | |
| assert all(e['capture_time_s'] is None for e in data['events'].values()) | |
| assert all(m['value'] is not None for k, m in rows.items() if k != 'shoulder_rotation_after_contact') | |
| assert rows['shoulder_rotation_after_contact']['reasons'] == ['required_event_unavailable', 'capture_time_unknown'] | |
| if mode in ('unknown_up', 'moving_camera'): | |
| assert all(m['value'] is None for k, m in rows.items() if k != 'lead_knee_extension_to_contact') | |
| assert rows['lead_knee_extension_to_contact']['value'] is not None | |
| if mode == 'missing_shoulder': | |
| assert rows['hip_shoulder_separation_at_foot_down']['value'] is None | |
| assert rows['stride_relative_length']['value'] is not None | |
| def test_scaling_handedness_and_interpolation_are_metric_specific(): | |
| data = payload(options(scale_factor=2, scale_source='Known fixture scale', scale_status='calibrated')) | |
| rows = values(data) | |
| assert rows['stride_relative_length']['value'] == pytest.approx(44.721) | |
| assert 'scale_is_model_estimated' not in rows['stride_relative_length']['reasons'] | |
| assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30 | |
| left = payload(options(handedness='left')) | |
| assert left['athlete']['lead_foot'] == 'right' | |
| assert values(left)['hip_shoulder_separation_at_foot_down']['value'] == 30 | |
| corrected = motion() | |
| corrected['interpolated'][4, MHR['right_wrist']] = True | |
| assert not any(m['uses_interpolated_input'] for m in payload(corrected=corrected)['measurements']) | |
| corrected['interpolated'][6, MHR['left_shoulder']] = True | |
| rows = values(payload(corrected=corrected)) | |
| assert rows['hip_shoulder_separation_at_contact']['uses_interpolated_input'] | |
| assert not rows['hip_shoulder_separation_at_foot_down']['uses_interpolated_input'] | |
| def test_unknown_lead_foot_and_rounding_at_angle_wrap(): | |
| data = payload(options(handedness=None)) | |
| assert 'lead_foot_unknown' in values(data)['stride_relative_length']['reasons'] | |
| corrected = motion() | |
| q = np.deg2rad(179.9998) | |
| corrected['points_relative'][4, 5] = [-.25*np.cos(q), -.5, -.25*np.sin(q)] | |
| corrected['points_relative'][4, 6] = [.25*np.cos(q), -.5, .25*np.sin(q)] | |
| assert values(payload(corrected=corrected))['hip_shoulder_separation_at_foot_down']['value'] == -180 | |
| def stored(service, video, opts, lineage=None, up_reference=None): | |
| lineage = lineage or service.store.create_motion(20) | |
| job = service.job_directory(lineage['job_id']); job.mkdir(exist_ok=True) | |
| capture = ingest(video, opts.metadata()); raw = raw_for(capture) | |
| raw['points_body'] = motion()['points_relative'] | |
| raw['projection'] = np.stack([project(p+c, k) for p, c, k in zip( | |
| raw['points_body'], raw['camera_translation'], raw['intrinsics'])]) | |
| raw['refinement_accepted'] = np.ones(capture['frame_count'], bool) | |
| if opts.model == 'gvhmr': | |
| raw['temporal_resampled'] = np.array([False, True, False, True, False, True, True, False]) | |
| manifest = export_motion(job, video, capture, raw, opts, {'name': 'Synthetic fixture, no GPU inference'}, | |
| lineage, up_reference=up_reference) | |
| atomic_json(job/'request.json', opts.model_dump(mode='json')) | |
| atomic_json(job/'lineage.json', lineage) | |
| service.store.update(job.name, 'completed', result_hash=sha256_file(job/'result.json')) | |
| return job, manifest | |
| def test_export_download_revisions_and_integrity_match_motion(tmp_path, video, monkeypatch, model): | |
| import baseball_batting.motion_api as api | |
| monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True}) | |
| monkeypatch.setattr(api.gvhmr_runtime, 'configured_record', lambda: {'configured': True}) | |
| service = fake_service(settings(tmp_path)); service.ready = True | |
| opts = options(model=model, timing={'kind': 'constant_slowdown', 'source': 'Known fixture capture', | |
| 'factor': 4, 'all_captured_frames_retained': True}, swing_id='swing-test') | |
| parent, manifest = stored(service, video, opts) | |
| url = '/v1/motion-analyses/' + parent.name | |
| # No lifespan: exercise a durable completed result and a revision without GPU dispatch. | |
| client = TestClient(create_app(service.settings, service)) | |
| assert client.get(url+'/coach-payload').status_code == 401 | |
| response = client.get(url+'/coach-payload', headers=AUTH) | |
| assert response.status_code == 200, response.text | |
| assert response.headers['cache-control'] == 'no-store' | |
| data = response.json(); assert validate_payload(data)[1] == {} | |
| capabilities = client.get('/v1/motion-analyses/capabilities', headers=AUTH).json() | |
| assert capabilities['coach_payload']['schema_version'] == data['schema_version'] == '1.1' | |
| assert manifest.pipeline['coach_payload']['schema_version'] == data['schema_version'] | |
| rows = values(data) | |
| assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30 | |
| assert rows['hip_shoulder_separation_at_contact']['value'] == 10 | |
| frames = [json.loads(line) for line in (parent/'motion.jsonl').read_text().splitlines()] | |
| assert data['events']['contact']['capture_time_s'] == frames[6]['capture_time_s'] | |
| assert data['events']['contact']['video_time_s'] == frames[6]['video_time_s'] | |
| assert data['analysis_id'] == manifest.analysis_id and data['analysis_revision'] == 1 | |
| for index, key in ((4, 'hip_shoulder_separation_at_foot_down'), (6, 'hip_shoulder_separation_at_contact')): | |
| joints = frames[index]['joints'] | |
| hip = np.array(joints['right_hip']['position']) - joints['left_hip']['position'] | |
| shoulder = np.array(joints['right_shoulder']['position']) - joints['left_shoulder']['position'] | |
| signed = (np.rad2deg(np.arctan2(shoulder[1], shoulder[0]) - np.arctan2(hip[1], hip[0])) + 180) % 360 - 180 | |
| assert rows[key]['value'] == pytest.approx(signed, abs=.001) | |
| artifact = manifest.artifacts['coach_payload'] | |
| assert artifact.url == url+'/coach-payload' | |
| # Hash and size describe the exact HTTP body, including its original whitespace. | |
| assert response.content == (parent/'coach-payload.json').read_bytes() | |
| assert len(response.content) == artifact.size_bytes | |
| assert hashlib.sha256(response.content).hexdigest() == artifact.sha256 | |
| assert client.get(url+'/artifacts/coach_payload', headers=AUTH).json() == data | |
| if model == 'gvhmr': assert rows['hip_shoulder_separation_at_contact']['uses_interpolated_input'] | |
| events = json.loads((parent/'events.json').read_text())['events'] | |
| contact = next(e for e in events if e['type'] == 'ball_contact') | |
| assert contact['source'] == 'manual' and contact['start']['source_frame_index'] == 6 | |
| original = (parent/'coach-payload.json').read_bytes() | |
| for patch in ({'swing_id': 'different'}, {'athlete': {'athlete_id': 'different'}}, | |
| {'athlete': None}, {'contact_frame': 999}): | |
| assert client.post(url+'/revisions', headers=AUTH, json={'options': patch}).status_code == 422 | |
| revision = client.post(url+'/revisions', headers=AUTH, json={'options': {'contact_frame': 5}}) | |
| assert revision.status_code == 202, revision.text | |
| lineage = revision.json() | |
| assert lineage['coach_payload_url'].endswith('/coach-payload') | |
| assert client.get(lineage['coach_payload_url'], headers=AUTH).status_code == 409 | |
| child_options = MotionInput.model_validate(json.loads((service.job_directory(lineage['job_id'])/'request.json').read_text())) | |
| child, child_manifest = stored(service, video, child_options, lineage) | |
| changed = client.get(lineage['coach_payload_url'], headers=AUTH).json() | |
| assert validate_payload(changed)[1] == {} | |
| assert changed['analysis_id'] == data['analysis_id'] and changed['analysis_revision'] == 2 | |
| assert changed['swing_id'] == data['swing_id'] == 'swing-test' | |
| assert values(changed)['hip_shoulder_separation_at_contact']['value'] == 20 | |
| assert (parent/'coach-payload.json').read_bytes() == original | |
| assert child_manifest.analysis_revision == 2 | |
| (child/'coach-payload.json').write_text('{}') | |
| assert client.get(lineage['coach_payload_url'], headers=AUTH).status_code == 500 | |
| def test_upload_persists_metadata_and_preserves_existing_request(tmp_path, video, monkeypatch): | |
| import baseball_batting.motion_api as api | |
| monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True}) | |
| service = fake_service(settings(tmp_path)); service.ready = True | |
| client = TestClient(create_app(service.settings, service)) | |
| r = client.post('/v1/motion-analyses', headers=AUTH, | |
| files={'video': ('swing.mp4', video.read_bytes(), 'video/mp4')}, | |
| data={'options': json.dumps(options().model_dump(mode='json'))}) | |
| assert r.status_code == 202, r.text | |
| saved = json.loads((service.job_directory(r.json()['job_id'])/'request.json').read_text()) | |
| assert saved['athlete'] == options().athlete.model_dump(mode='json') | |
| assert saved['contact_frame'] == 6 and saved['windows'][0]['landing_frame'] == 4 | |
| assert saved['refinement']['enabled'] and saved['up_vector'] == [0, -1, 0] | |
| assert client.delete(r.json()['status_url'], headers=AUTH).status_code == 202 | |
| # Older callers do not need new fields and still get motion artifacts normally. | |
| job, manifest = stored(service, video, options(athlete=None, contact_frame=None)) | |
| assert 'coach_payload' not in manifest.artifacts | |
| assert client.get(f'/v1/motion-analyses/{job.name}/coach-payload', headers=AUTH).status_code == 409 | |
| def test_contact_frame_bounds_checked_before_gpu_inference(tmp_path, video, monkeypatch): | |
| import baseball_batting.motion_worker as worker | |
| opts = options(windows=[], contact_frame=999) | |
| job = tmp_path/'job'; job.mkdir() | |
| (job/'input.mp4').write_bytes(video.read_bytes()) | |
| atomic_json(job/'request.json', opts.model_dump(mode='json')) | |
| atomic_json(job/'lineage.json', LINEAGE) | |
| def unexpected(*args, **kwargs): | |
| pytest.fail('GPU inference must not run for an out-of-range contact frame') | |
| monkeypatch.setattr(worker, 'reconstruct_sam', unexpected) | |
| with pytest.raises(ValueError, match='contact_frame_out_of_range'): | |
| worker.run(job, tmp_path/'models') | |
| def test_published_schemas_and_example_agree_with_receiver(): | |
| import jsonschema | |
| from baseball_batting.motion_coach_contract import MotionCoachPayload | |
| docs = Path(__file__).parents[1]/'docs' | |
| schema = json.loads((docs/'motion-coach-payload.schema.json').read_text()) | |
| assert schema == MotionCoachPayload.model_json_schema() | |
| example = json.loads((docs/'motion-coach-payload.example.json').read_text()) | |
| jsonschema.Draft202012Validator.check_schema(schema) | |
| jsonschema.validate(example, schema) | |
| assert validate_payload(example)[1] == {} | |
| assert json.loads((docs/'motion-input.schema.json').read_text()) == MotionInput.model_json_schema() | |
| def test_estimated_up_is_used_only_when_accepted_for_measurements(tmp_path, video, reliable): | |
| from baseball_batting.camera_up import reference | |
| opts = options(up_vector=None, up_source=None) | |
| up = {**reference(opts), 'status': 'estimated', 'reliable': reliable, | |
| 'up_vector': [0, -1, 0], 'up_source': 'GeoCalib consensus fixture'} | |
| job, manifest = stored(fake_service(settings(tmp_path)), video, opts, up_reference=up) | |
| data = json.loads((job/'coach-payload.json').read_text()) | |
| assert validate_payload(data)[1] == {} | |
| assert all((m['value'] is not None) == reliable for m in data['measurements'] | |
| if m['metric_id'] not in ('shoulder_rotation_after_contact', 'lead_knee_extension_to_contact')) | |
| assert next(m for m in data['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact')['value'] is not None | |
| assert manifest.pipeline['inputs']['up_vector'] is None | |
| assert manifest.pipeline['calculation_inputs']['up_vector'] == ([0, -1, 0] if reliable else None) | |
| def test_contact_revision_reuses_native_inference_and_keeps_default_swing_identity(tmp_path, video, monkeypatch, model): | |
| import baseball_batting.motion_api as api | |
| import baseball_batting.motion_worker as worker | |
| from test_gvhmr_motion import native_fixture | |
| from baseball_batting.api_jobs import JobService | |
| monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True}) | |
| monkeypatch.setattr(api.gvhmr_runtime, 'configured_record', lambda: {'configured': True}) | |
| calls = [] | |
| def infer(job, source, capture, *args, **kwargs): | |
| 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' if model == 'sam3d' else 'reconstruct_gvhmr', infer) | |
| service = JobService(settings(tmp_path)); service.ready = 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 = options(model=model, refinement={'enabled': False}) | |
| atomic_json(parent/'request.json', opts.model_dump(mode='json')) | |
| atomic_json(parent/'lineage.json', lineage) | |
| worker.run(parent, tmp_path/'models') | |
| service.store.update(parent.name, 'completed', result_hash=sha256_file(parent/'result.json')) | |
| original = json.loads((parent/'coach-payload.json').read_text()) | |
| client = TestClient(create_app(service.settings, service)) | |
| response = client.post('/v1/motion-analyses/'+parent.name+'/revisions', headers=AUTH, | |
| json={'options': {'contact_frame': 5, 'athlete': {'age_years': 17}}}) | |
| assert response.status_code == 202, response.text | |
| child = service.job_directory(response.json()['job_id']) | |
| assert (child/'reused-inference.json').is_file() | |
| worker.run(child, tmp_path/'models') | |
| updated = json.loads((child/'coach-payload.json').read_text()) | |
| assert validate_payload(updated)[1] == {} | |
| assert calls == [model] | |
| assert updated['swing_id'] == original['swing_id'] == lineage['analysis_id']+':swing_1' | |
| assert updated['analysis_revision'] == 2 and original['analysis_revision'] == 1 | |
| assert updated['athlete']['age_years'] == 17 | |
| assert original['athlete']['age_years'] == 16 | |