github-actions[bot] commited on
Commit
4b1e064
·
1 Parent(s): 4598c11

Automated Deploy: 576e5fa0b5a38e119a36684f345434445973a81e

Browse files
backend/Dockerfile CHANGED
@@ -11,7 +11,8 @@ RUN pip install /opt/ai-coach-agent
11
  COPY backend/pyproject.toml backend/alembic.ini ./
12
  COPY backend/app ./app
13
  COPY backend/migrations ./migrations
14
- RUN pip install .
 
15
 
16
  RUN useradd --uid 1000 --create-home app
17
  USER app
@@ -21,4 +22,4 @@ EXPOSE 8000
21
  # Behind a proxy, set FORWARDED_ALLOW_IPS to the proxy's address only (never "*"), or clients can spoof their IP
22
  # and get around the per-IP login limits.
23
  ENV FORWARDED_ALLOW_IPS=127.0.0.1
24
- CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"]
 
11
  COPY backend/pyproject.toml backend/alembic.ini ./
12
  COPY backend/app ./app
13
  COPY backend/migrations ./migrations
14
+ RUN pip install . "google-auth[requests]>=2.30"
15
+ COPY backend/start-backend.sh /srv/start-backend.sh
16
 
17
  RUN useradd --uid 1000 --create-home app
18
  USER app
 
22
  # Behind a proxy, set FORWARDED_ALLOW_IPS to the proxy's address only (never "*"), or clients can spoof their IP
23
  # and get around the per-IP login limits.
24
  ENV FORWARDED_ALLOW_IPS=127.0.0.1
25
+ CMD ["sh", "/srv/start-backend.sh"]
backend/Dockerfile.dockerignore CHANGED
@@ -6,6 +6,7 @@
6
  !AI-coach-agent/src/**
7
  !backend/pyproject.toml
8
  !backend/alembic.ini
 
9
  !backend/app/
10
  !backend/app/**
11
  !backend/migrations/
 
6
  !AI-coach-agent/src/**
7
  !backend/pyproject.toml
8
  !backend/alembic.ini
9
+ !backend/start-backend.sh
10
  !backend/app/
11
  !backend/app/**
12
  !backend/migrations/
backend/README.md CHANGED
@@ -59,3 +59,12 @@ docker build -f backend/Dockerfile -t cognivision-backend . # from the repos
59
  docker run --env-file backend/.env cognivision-backend alembic upgrade head
60
  docker run --env-file backend/.env -p 8000:8000 cognivision-backend
61
  ```
 
 
 
 
 
 
 
 
 
 
59
  docker run --env-file backend/.env cognivision-backend alembic upgrade head
60
  docker run --env-file backend/.env -p 8000:8000 cognivision-backend
61
  ```
62
+
63
+ For Firebase on a Hugging Face Docker Space running this backend, set `FCM_PROJECT_ID` to your Firebase project ID
64
+ and `FCM_SERVICE_ACCOUNT_FILE` to `/tmp/firebase-service-account.json` in the Space's variables. Add the entire
65
+ service account JSON as a secret named `FCM_SERVICE_ACCOUNT_JSON`. At startup, the container writes that secret
66
+ to the configured path with owner-only permissions before starting the API. Keep the JSON out of Git and Docker
67
+ build arguments. Without the JSON secret, startup still supports an existing credentials file or disabled push.
68
+
69
+ The repository's root Dockerfile and existing Hugging Face deployment run the separate GPU analysis API;
70
+ this setup requires deploying `backend/Dockerfile` with Space `app_port: 8000`.
backend/start-backend.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+
4
+ if [ -n "${FCM_SERVICE_ACCOUNT_JSON:-}" ]; then
5
+ : "${FCM_PROJECT_ID:?Missing Firebase project ID}"
6
+ : "${FCM_SERVICE_ACCOUNT_FILE:?Missing Firebase credentials path}"
7
+
8
+ umask 077
9
+ printf '%s' "$FCM_SERVICE_ACCOUNT_JSON" > "$FCM_SERVICE_ACCOUNT_FILE"
10
+ chmod 600 "$FCM_SERVICE_ACCOUNT_FILE"
11
+ unset FCM_SERVICE_ACCOUNT_JSON
12
+ fi
13
+
14
+ exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --proxy-headers
baseball_batting/api.py CHANGED
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
- app = FastAPI(title="Baseball Swing Engine and Coach", version="1.17.0", lifespan=lifespan,
82
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
83
  app.state.service = service
84
  app.add_middleware(UploadGuard, settings=settings, service=service)
 
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.18.0", lifespan=lifespan,
82
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
83
  app.state.service = service
84
  app.add_middleware(UploadGuard, settings=settings, service=service)
baseball_batting/motion_api.py CHANGED
@@ -16,6 +16,8 @@ from .motion_adapters import descriptor, adapter_hash
16
  from .storage import atomic_json, read_json, sha256_file
17
  from .media import open_verified_media, media_response
18
  from .sam_measurement_worker import tracking_hash
 
 
19
 
20
  PREFIX='/v1/motion-analyses'
21
 
@@ -58,10 +60,11 @@ def register(app,service,authenticated):
58
  except ValidationError as error:
59
  raise HTTPException(422,[{'loc':list(e['loc']),'msg':e['msg'],'type':e['type']} for e in error.errors(include_input=False,include_url=False)]) from None
60
 
61
- def response(lineage):
62
  identifier=lineage['job_id']
63
  return {**lineage,'status':'queued','status_url':PREFIX+'/'+identifier,
64
- 'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600}
 
65
 
66
  def reserve(options,parent=None):
67
  try:lineage=service.store.create_motion(settings.max_active_jobs,parent)
@@ -101,6 +104,9 @@ def register(app,service,authenticated):
101
  'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
102
  'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
103
  'camera_frame':'upright_camera_x_right_y_down_z_away'},
 
 
 
104
  'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
105
  'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
106
  'output_schema_url':PREFIX+'/output-schema'}
@@ -111,7 +117,7 @@ def register(app,service,authenticated):
111
  @app.get(PREFIX+'/output-schema',dependencies=[Depends(authenticated)])
112
  def output_schema():
113
  return {'manifest':MotionManifest.model_json_schema(),'motion_frame':MotionFrame.model_json_schema(),
114
- 'projection_frame':ProjectionFrame.model_json_schema()}
115
 
116
  @app.post(PREFIX,status_code=202,dependencies=[Depends(authenticated)])
117
  async def upload(video:Annotated[UploadFile|None,File()]=None,
@@ -140,7 +146,7 @@ def register(app,service,authenticated):
140
  out.write(block)
141
  if not size:raise HTTPException(422,'Video is empty')
142
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
143
- return response(lineage)
144
  except BaseException:
145
  if lineage:
146
  service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
@@ -162,7 +168,8 @@ def register(app,service,authenticated):
162
  return JSONResponse({**service.store.motion_lineage(identifier),
163
  'status':'processing' if row['status']=='running' else row['status'],'progress':progress,
164
  'failure':failure,'error':row['error'],
165
- 'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None},
 
166
  headers={'Cache-Control':'no-store'})
167
 
168
  @app.get(PREFIX+'/{identifier}/result',response_model=MotionManifest,dependencies=[Depends(authenticated)])
@@ -170,6 +177,23 @@ def register(app,service,authenticated):
170
  with service.mutation_lock:_,manifest=completed(identifier)
171
  return JSONResponse(manifest.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  @app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
174
  @app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
175
  def artifact(identifier:str,name:str,request:Request):
@@ -191,8 +215,18 @@ def register(app,service,authenticated):
191
  return {**before,**{k:merge(before[k],v) if isinstance(v,dict) and isinstance(before.get(k),dict) else v for k,v in patch.items()}}
192
  parsed=validated(merge(inputs,payload.options))
193
  require_ready(parsed.model)
194
- if parsed.athlete_box!=MotionInput.model_validate(inputs).athlete_box:
 
195
  raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
 
 
 
 
 
 
 
 
 
196
  directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
197
  # Reviewed events/calibration axes/correction changes reuse native inference.
198
  geometry=('camera','athlete_box','rotation_degrees','source_mirrored','model','gvhmr','tracking')
@@ -220,7 +254,7 @@ def register(app,service,authenticated):
220
  if (parent/name).is_file() and hashes.get(name)==sha256_file(parent/name):os.link(parent/name,directory/name)
221
  atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
222
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
223
- return response(lineage)
224
  except BaseException:
225
  if lineage:service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
226
  raise
 
16
  from .storage import atomic_json, read_json, sha256_file
17
  from .media import open_verified_media, media_response
18
  from .sam_measurement_worker import tracking_hash
19
+ from .motion_coach_contract import MotionCoachPayload
20
+ from .motion_coach import swing_identity
21
 
22
  PREFIX='/v1/motion-analyses'
23
 
 
60
  except ValidationError as error:
61
  raise HTTPException(422,[{'loc':list(e['loc']),'msg':e['msg'],'type':e['type']} for e in error.errors(include_input=False,include_url=False)]) from None
62
 
63
+ def response(lineage,options):
64
  identifier=lineage['job_id']
65
  return {**lineage,'status':'queued','status_url':PREFIX+'/'+identifier,
66
+ 'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600,
67
+ 'coach_payload_url':PREFIX+'/'+identifier+'/coach-payload' if options.athlete is not None else None}
68
 
69
  def reserve(options,parent=None):
70
  try:lineage=service.store.create_motion(settings.max_active_jobs,parent)
 
104
  'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
105
  'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
106
  'camera_frame':'upright_camera_x_right_y_down_z_away'},
107
+ 'coach_payload':{'schema_version':'1.0','measurement_definitions_version':'1.0',
108
+ 'one_swing_per_video':True,'requires':['single_swing=true','athlete.athlete_id'],
109
+ 'manual_contact_frame':True},
110
  'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
111
  'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
112
  'output_schema_url':PREFIX+'/output-schema'}
 
117
  @app.get(PREFIX+'/output-schema',dependencies=[Depends(authenticated)])
118
  def output_schema():
119
  return {'manifest':MotionManifest.model_json_schema(),'motion_frame':MotionFrame.model_json_schema(),
120
+ 'projection_frame':ProjectionFrame.model_json_schema(),'coach_payload':MotionCoachPayload.model_json_schema()}
121
 
122
  @app.post(PREFIX,status_code=202,dependencies=[Depends(authenticated)])
123
  async def upload(video:Annotated[UploadFile|None,File()]=None,
 
146
  out.write(block)
147
  if not size:raise HTTPException(422,'Video is empty')
148
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
149
+ return response(lineage,parsed)
150
  except BaseException:
151
  if lineage:
152
  service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
 
168
  return JSONResponse({**service.store.motion_lineage(identifier),
169
  'status':'processing' if row['status']=='running' else row['status'],'progress':progress,
170
  'failure':failure,'error':row['error'],
171
+ 'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None,
172
+ 'coach_payload_url':PREFIX+'/'+identifier+'/coach-payload' if row['status']=='completed' and (directory/'coach-payload.json').is_file() else None},
173
  headers={'Cache-Control':'no-store'})
174
 
175
  @app.get(PREFIX+'/{identifier}/result',response_model=MotionManifest,dependencies=[Depends(authenticated)])
 
177
  with service.mutation_lock:_,manifest=completed(identifier)
178
  return JSONResponse(manifest.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
179
 
180
+ @app.get(PREFIX+'/{identifier}/coach-payload',response_model=MotionCoachPayload,dependencies=[Depends(authenticated)])
181
+ def coach_payload(identifier:str):
182
+ with service.mutation_lock:
183
+ directory,manifest=completed(identifier)
184
+ asset=manifest.artifacts.get('coach_payload')
185
+ if asset is None or asset.status!='available':
186
+ raise HTTPException(409,{'code':'coach_payload_not_requested',
187
+ 'detail':'Submit athlete information and single_swing=true, or create a revision with those options'})
188
+ handle,_=open_verified_media(artifact_path(directory,asset),asset.sha256,asset.size_bytes)
189
+ try:
190
+ with handle:payload=MotionCoachPayload.model_validate(json.load(handle))
191
+ except (ValueError,ValidationError):
192
+ raise HTTPException(500,'Stored coach payload is invalid') from None
193
+ if payload.analysis_id!=manifest.analysis_id or payload.analysis_revision!=manifest.analysis_revision:
194
+ raise HTTPException(500,'Coach payload differs from the analysis revision')
195
+ return JSONResponse(payload.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
196
+
197
  @app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
198
  @app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
199
  def artifact(identifier:str,name:str,request:Request):
 
215
  return {**before,**{k:merge(before[k],v) if isinstance(v,dict) and isinstance(before.get(k),dict) else v for k,v in patch.items()}}
216
  parsed=validated(merge(inputs,payload.options))
217
  require_ready(parsed.model)
218
+ previous=MotionInput.model_validate(inputs)
219
+ if parsed.athlete_box!=previous.athlete_box:
220
  raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
221
+ if previous.athlete is not None:
222
+ if parsed.athlete is None:
223
+ raise HTTPException(422,'Athlete information must be retained across coach revisions')
224
+ if parsed.athlete.athlete_id!=previous.athlete.athlete_id:
225
+ raise HTTPException(422,'Changing athlete_id requires a new analysis using source_asset_id')
226
+ if swing_identity(parsed,manifest.analysis_id)!=swing_identity(previous,manifest.analysis_id):
227
+ raise HTTPException(422,'swing_id must stay stable across revisions')
228
+ try:parsed.validate_frame_count(manifest.sampling['frame_count'])
229
+ except ValueError as error:raise HTTPException(422,{'code':str(error)}) from None
230
  directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
231
  # Reviewed events/calibration axes/correction changes reuse native inference.
232
  geometry=('camera','athlete_box','rotation_degrees','source_mirrored','model','gvhmr','tracking')
 
254
  if (parent/name).is_file() and hashes.get(name)==sha256_file(parent/name):os.link(parent/name,directory/name)
255
  atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
256
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
257
+ return response(lineage,parsed)
258
  except BaseException:
259
  if lineage:service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
260
  raise
baseball_batting/motion_coach.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export the coach's three metrics from the same corrected motion as replay.
2
+
3
+ The selected source frames are manual review, not automatic event detections.
4
+ They identify sampled video moments, not measured ground force or subframe contact.
5
+ """
6
+ import numpy as np
7
+ from .motion_coach_contract import (CoachEvents, CoachEvent, MotionCoachPayload,
8
+ SeparationAtFootDown, RelativeStride, SeparationAtContact)
9
+ from .sam_measurements import frame_curves, wrap180
10
+ from .sam_motion import MHR
11
+
12
+
13
+ def swing_identity(options, analysis_id):
14
+ return options.swing_id or analysis_id + ':swing_1'
15
+
16
+
17
+ def build_coach_payload(options, lineage, corrected, video_times, capture_times, contexts):
18
+ if options.athlete is None:
19
+ return None
20
+ if not options.single_swing or len(contexts) > 1:
21
+ raise ValueError('Coach contract 1.0 requires one swing per video')
22
+ n = len(video_times)
23
+ options.validate_frame_count(n)
24
+ window = options.windows[0] if options.windows else None
25
+ stride_start = window.stride_start_frame if window else None
26
+ landing = window.landing_frame if window else None
27
+ contact = options.contact_frame
28
+ lead = options.lead_foot or {'right': 'left', 'left': 'right'}.get(options.handedness)
29
+ athlete = options.athlete.model_copy(update={'batting_hand': options.handedness, 'lead_foot': lead})
30
+
31
+ def event(index, missing_reason):
32
+ if index is None:
33
+ return CoachEvent(status='unavailable', video_time_s=None, capture_time_s=None,
34
+ source=None, reasons=[missing_reason])
35
+ return CoachEvent(status='limited', video_time_s=float(video_times[index]),
36
+ capture_time_s=float(capture_times[index]) if np.isfinite(capture_times[index]) else None,
37
+ source='manual_review', reasons=['event_timing_uncertain'])
38
+
39
+ events = CoachEvents(stride_start=event(stride_start, 'event_not_detected'),
40
+ front_foot_down=event(landing, 'event_not_detected'),
41
+ contact=event(contact, 'contact_not_applicable' if options.context.practice_type == 'dry_swing'
42
+ else 'contact_not_verified'))
43
+ if contexts:
44
+ context = contexts[0]
45
+ curves = context['curves']
46
+ # Reuse exactly the fixed orientation/baseline of the existing calculator.
47
+ _, reference, oriented = frame_curves(corrected['points_relative'], video_times,
48
+ corrected['boundary'], options.sam_options(), context['baseline'])
49
+ else:
50
+ hips = corrected['valid'][:, [MHR['left_hip'], MHR['right_hip']]].all(axis=1)
51
+ baseline = int(np.flatnonzero(hips)[0]) if hips.any() else 0
52
+ curves, reference, oriented = frame_curves(corrected['points_relative'], video_times,
53
+ corrected['boundary'], options.sam_options(), baseline)
54
+
55
+ def quality(indices, names):
56
+ ids = [i for i in indices if i is not None]
57
+ joints = [MHR[name] for name in names]
58
+ selected = np.ix_(ids, joints)
59
+ interpolated = bool(ids and corrected['interpolated'][selected].any())
60
+ reasons = []
61
+ if ids and not corrected['valid'][selected].all():
62
+ reasons.append('required_landmarks_unusable')
63
+ if options.up_vector is None:
64
+ reasons.append('ground_plane_unknown')
65
+ if options.camera_stability != 'fixed_verified':
66
+ reasons.append('temporal_inconsistency')
67
+ if reference == 'degenerate_analysis_axis':
68
+ reasons.append('required_landmarks_unusable')
69
+ warnings = []
70
+ if ids and (corrected['boundary'][selected].any() or interpolated):
71
+ warnings.append('temporal_inconsistency')
72
+ return interpolated, list(dict.fromkeys(reasons)), warnings
73
+
74
+ def result(model, value, missing, timing, interpolated, warnings):
75
+ missing = list(dict.fromkeys(missing))
76
+ if missing:
77
+ return model(value=None, status='unavailable', confidence=None,
78
+ uses_interpolated_input=interpolated, reasons=missing)
79
+ reasons = list(dict.fromkeys([*timing, *warnings]))
80
+ return model(value=value, status='limited' if reasons else 'available', confidence=None,
81
+ uses_interpolated_input=interpolated, reasons=reasons)
82
+
83
+ def separation(model, index, selected_event):
84
+ interpolated, missing, warnings = quality([index],
85
+ ['left_hip', 'right_hip', 'left_shoulder', 'right_shoulder'])
86
+ if selected_event.status == 'unavailable':
87
+ missing = ['required_event_unavailable', *selected_event.reasons, *missing]
88
+ value = None
89
+ if not missing:
90
+ q = curves['hip_shoulder_separation_deg'][index]
91
+ if np.isfinite(q):
92
+ # Round before wrapping so 179.9998 cannot serialize as +180.
93
+ value = float(wrap180(round(float(q), 3)))
94
+ else:
95
+ missing.append('required_landmarks_unusable')
96
+ return result(model, value, missing, selected_event.reasons, interpolated, warnings)
97
+
98
+ foot_angle = separation(SeparationAtFootDown, landing, events.front_foot_down)
99
+ contact_angle = separation(SeparationAtContact, contact, events.contact)
100
+ interpolated, missing, warnings = quality([stride_start, landing],
101
+ ['left_hip', 'right_hip', 'left_ankle', 'right_ankle'])
102
+ timing = []
103
+ for selected_event in (events.stride_start, events.front_foot_down):
104
+ if selected_event.status == 'unavailable':
105
+ missing += ['required_event_unavailable', *selected_event.reasons]
106
+ else:
107
+ timing += selected_event.reasons
108
+ if lead is None:
109
+ missing.append('lead_foot_unknown')
110
+ if options.scale_status == 'unknown':
111
+ missing.append('scale_unknown')
112
+ elif options.scale_status == 'model_estimated':
113
+ warnings.append('scale_is_model_estimated')
114
+ stride = None
115
+ if not missing:
116
+ if oriented is None:
117
+ missing.append('required_landmarks_unusable')
118
+ else:
119
+ li, ri = (MHR['left_ankle'], MHR['right_ankle']) if lead == 'left' else (
120
+ MHR['right_ankle'], MHR['left_ankle'])
121
+ start = oriented[stride_start, li] - oriented[stride_start, ri]
122
+ end = oriented[landing, li] - oriented[landing, ri]
123
+ q = 100 * np.linalg.norm((end - start)[:2])
124
+ if np.isfinite(q):
125
+ stride = round(float(q), 3)
126
+ else:
127
+ missing.append('required_landmarks_unusable')
128
+ stride_metric = result(RelativeStride, stride, missing, timing, interpolated, warnings)
129
+ return MotionCoachPayload(analysis_id=lineage['analysis_id'], analysis_revision=lineage['analysis_revision'],
130
+ swing_id=swing_identity(options, lineage['analysis_id']), athlete=athlete, context=options.context,
131
+ events=events, measurements=[foot_angle, stride_metric, contact_angle])
baseball_batting/motion_coach_contract.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Coach contract 1.0: exactly three measurements for one recorded swing."""
2
+ from typing import Literal
3
+ from pydantic import Field, model_validator
4
+ from .sam_batting_contract import Strict
5
+
6
+
7
+ class CoachAthlete(Strict):
8
+ athlete_id: str = Field(min_length=1, max_length=180, pattern=r'\S')
9
+ batting_hand: Literal['left', 'right'] | None = None
10
+ lead_foot: Literal['left', 'right'] | None = None
11
+ age_years: int | None = Field(default=None, ge=0, strict=True)
12
+ height_cm: float | None = Field(default=None, gt=0, strict=True)
13
+
14
+
15
+ class CoachContext(Strict):
16
+ sport: Literal['baseball'] = 'baseball'
17
+ practice_type: Literal['tee', 'front_toss', 'side_toss', 'pitching_machine',
18
+ 'live_pitching', 'game', 'dry_swing', 'unknown'] = 'unknown'
19
+
20
+
21
+ Reason = Literal['contact_not_verified', 'contact_not_applicable', 'event_not_detected',
22
+ 'event_timing_uncertain', 'required_event_unavailable', 'required_event_limited',
23
+ 'lead_foot_unknown', 'required_landmarks_unusable', 'ground_plane_unknown',
24
+ 'scale_is_model_estimated', 'scale_unknown', 'excessive_interpolation',
25
+ 'occlusion_unresolved', 'temporal_inconsistency']
26
+
27
+
28
+ class CoachEvent(Strict):
29
+ video_time_s: float | None = Field(ge=0)
30
+ capture_time_s: float | None = Field(ge=0)
31
+ status: Literal['available', 'limited', 'unavailable']
32
+ source: Literal['manual_review', 'pose_estimated', 'bat_ball_detector'] | None
33
+ reasons: list[Reason]
34
+
35
+ @model_validator(mode='after')
36
+ def consistent(self):
37
+ if self.status == 'unavailable':
38
+ if any(v is not None for v in (self.video_time_s, self.capture_time_s, self.source)):
39
+ raise ValueError('Unavailable events must have null times and source')
40
+ elif self.video_time_s is None or self.source is None:
41
+ raise ValueError('Usable events need video time and source')
42
+ if (self.status == 'available') != (not self.reasons):
43
+ raise ValueError('Only available events have an empty reasons list')
44
+ return self
45
+
46
+
47
+ class CoachEvents(Strict):
48
+ stride_start: CoachEvent
49
+ front_foot_down: CoachEvent
50
+ contact: CoachEvent
51
+
52
+
53
+ class CoachMeasurement(Strict):
54
+ value: float | None
55
+ status: Literal['available', 'limited', 'unavailable']
56
+ confidence: float | None = Field(ge=0, le=1)
57
+ uses_interpolated_input: bool
58
+ reasons: list[Reason]
59
+ benchmark: None = None
60
+
61
+ @model_validator(mode='after')
62
+ def consistent(self):
63
+ if (self.status == 'unavailable') != (self.value is None):
64
+ raise ValueError('Only unavailable measurements have a null value')
65
+ if self.status == 'unavailable' and self.confidence is not None:
66
+ raise ValueError('Unavailable measurements have null confidence')
67
+ if (self.status == 'available') != (not self.reasons):
68
+ raise ValueError('Only available measurements have an empty reasons list')
69
+ return self
70
+
71
+
72
+ class SeparationAtFootDown(CoachMeasurement):
73
+ metric_id: Literal['hip_shoulder_separation_at_foot_down'] = 'hip_shoulder_separation_at_foot_down'
74
+ group: Literal['stride'] = 'stride'
75
+ unit: Literal['deg'] = 'deg'
76
+ reference: Literal['signed_horizontal_shoulder_minus_hip_heading'] = 'signed_horizontal_shoulder_minus_hip_heading'
77
+ event_id: Literal['front_foot_down'] = 'front_foot_down'
78
+ value: float | None = Field(ge=-180, lt=180)
79
+
80
+
81
+ class RelativeStride(CoachMeasurement):
82
+ metric_id: Literal['stride_relative_length'] = 'stride_relative_length'
83
+ group: Literal['stride'] = 'stride'
84
+ unit: Literal['cm'] = 'cm'
85
+ reference: Literal['lead_ankle_displacement_relative_to_rear_ankle'] = 'lead_ankle_displacement_relative_to_rear_ankle'
86
+ start_event_id: Literal['stride_start'] = 'stride_start'
87
+ end_event_id: Literal['front_foot_down'] = 'front_foot_down'
88
+ value: float | None = Field(ge=0)
89
+
90
+
91
+ class SeparationAtContact(CoachMeasurement):
92
+ metric_id: Literal['hip_shoulder_separation_at_contact'] = 'hip_shoulder_separation_at_contact'
93
+ group: Literal['contact_follow_through'] = 'contact_follow_through'
94
+ unit: Literal['deg'] = 'deg'
95
+ reference: Literal['signed_horizontal_shoulder_minus_hip_heading'] = 'signed_horizontal_shoulder_minus_hip_heading'
96
+ event_id: Literal['contact'] = 'contact'
97
+ value: float | None = Field(ge=-180, lt=180)
98
+
99
+
100
+ class MotionCoachPayload(Strict):
101
+ schema_version: Literal['1.0'] = '1.0'
102
+ measurement_definitions_version: Literal['1.0'] = '1.0'
103
+ analysis_id: str = Field(min_length=1)
104
+ analysis_revision: int = Field(ge=1)
105
+ swing_id: str = Field(min_length=1)
106
+ status: Literal['completed'] = 'completed'
107
+ athlete: CoachAthlete
108
+ context: CoachContext
109
+ events: CoachEvents
110
+ measurements: list[SeparationAtFootDown | RelativeStride | SeparationAtContact] = Field(min_length=3, max_length=3)
111
+
112
+ @model_validator(mode='after')
113
+ def metric_set(self):
114
+ if len({m.metric_id for m in self.measurements}) != 3:
115
+ raise ValueError('Each registered metric must appear exactly once')
116
+ return self
baseball_batting/motion_contract.py CHANGED
@@ -4,6 +4,7 @@ from pydantic import Field, model_validator
4
  from .sam_batting_contract import Strict, SamBattingInput
5
  from .sam_motion import MHR
6
  from .api_contract import CameraInput
 
7
 
8
  SCHEMA_VERSION = '1.0'
9
  ADAPTER_VERSION = 'sam-mhr70-motion-v1'
@@ -113,6 +114,39 @@ class MotionInput(SamBattingInput):
113
  tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
114
  up_estimation: UpEstimationSettings = Field(default_factory=UpEstimationSettings)
115
  pitcher_floor_points: PitcherFloorPoints | None = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  @model_validator(mode='after')
118
  def scale_evidence(self):
 
4
  from .sam_batting_contract import Strict, SamBattingInput
5
  from .sam_motion import MHR
6
  from .api_contract import CameraInput
7
+ from .motion_coach_contract import CoachAthlete, CoachContext
8
 
9
  SCHEMA_VERSION = '1.0'
10
  ADAPTER_VERSION = 'sam-mhr70-motion-v1'
 
114
  tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
115
  up_estimation: UpEstimationSettings = Field(default_factory=UpEstimationSettings)
116
  pitcher_floor_points: PitcherFloorPoints | None = None
117
+ athlete: CoachAthlete | None = None
118
+ context: CoachContext = Field(default_factory=CoachContext)
119
+ contact_frame: int | None = Field(default=None, ge=0, strict=True)
120
+ swing_id: str | None = Field(default=None, min_length=1, max_length=180, pattern=r'\S')
121
+
122
+ @model_validator(mode='after')
123
+ def coach_inputs(self):
124
+ if self.athlete is not None:
125
+ for outer, inner in (('handedness', 'batting_hand'), ('lead_foot', 'lead_foot')):
126
+ old, new = getattr(self, outer), getattr(self.athlete, inner)
127
+ if old is not None and new is not None and old != new:
128
+ raise ValueError(f'athlete.{inner} conflicts with {outer}')
129
+ if old is None and new is not None:
130
+ # Assignment validation would recursively invoke this validator.
131
+ object.__setattr__(self, outer, new)
132
+ if (self.athlete is not None or self.contact_frame is not None) and not self.single_swing:
133
+ raise ValueError('Player coaching inputs require single_swing=true')
134
+ if self.contact_frame is not None:
135
+ if self.context.practice_type == 'dry_swing':
136
+ raise ValueError('A dry swing cannot have bat-ball contact')
137
+ if self.windows:
138
+ window = self.windows[0]
139
+ if not window.start_frame <= self.contact_frame <= window.end_frame:
140
+ raise ValueError('Contact frame must lie inside the swing window')
141
+ if window.landing_frame is not None and self.contact_frame < window.landing_frame:
142
+ raise ValueError('Contact frame must not precede landing_frame')
143
+ return self
144
+
145
+ def validate_frame_count(self, count):
146
+ if any(w.end_frame >= count for w in self.windows):
147
+ raise ValueError('reviewed_frame_out_of_range')
148
+ if self.contact_frame is not None and self.contact_frame >= count:
149
+ raise ValueError('contact_frame_out_of_range')
150
 
151
  @model_validator(mode='after')
152
  def scale_evidence(self):
baseball_batting/motion_export.py CHANGED
@@ -111,6 +111,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
111
  adapter=descriptor(options.model); definition_version=adapter['definition_version']
112
  records=capture['frames']; n=len(records)
113
  if n<4:raise ValueError('insufficient_source_frames')
 
114
  playback=np.array([r['playback_s'] for r in records],float)
115
  if not np.isfinite(playback).all() or np.any(np.diff(playback)<=0):
116
  raise ValueError('invalid_source_timestamps')
@@ -287,7 +288,11 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
287
  for name,index in context['peaks'].items():
288
  metric=rows[name+'_peak_time_ms']
289
  event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
290
- event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
 
 
 
 
291
  # Recompute each summary from alternate accepted rig fits, rather than
292
  # interpreting a positional residual as an angular/timing error bar.
293
  alternative_values=[]
@@ -323,6 +328,10 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
323
  'calculation_inputs':calculation_options.model_dump(mode='json'),'up_reference':up_reference,
324
  'pitcher_reference':pitcher_reference})
325
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
 
 
 
 
326
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
327
  'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
328
  'reidentification':'bounded_short_loss_only; ambiguous_overlap_not_recovered','box_overlap_gate':.05,
@@ -346,6 +355,9 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
346
  ('motion','motion.jsonl','application/x-ndjson','jsonl'),('measurements','measurements.json','application/json','json'),
347
  ('events','events.json','application/json','json'),('quality','quality.json','application/json','json')]}
348
  artifacts['source']=asset(source,media[source.suffix],'original_video')
 
 
 
349
  artifacts['projections']=asset(job/'projections.jsonl','application/x-ndjson','jsonl') if projection_count else {
350
  'status':'unavailable','reason_code':'camera_projection_unavailable','format':'jsonl','media_type':'application/x-ndjson','expires_at':expiry}
351
  artifacts['mesh']={'status':'unavailable','reason_code':'animated_mesh_second_phase','format':'none','media_type':'application/octet-stream','expires_at':expiry}
@@ -380,6 +392,12 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
380
  'correction_implementation_sha256':sha256_file(Path(__file__).with_name('sam_motion.py')),
381
  'measurement_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurements.py')),
382
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
 
 
 
 
 
 
383
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
384
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
385
  'up_vector':list(calculation_options.up_vector) if calculation_options.up_vector is not None else None,
 
111
  adapter=descriptor(options.model); definition_version=adapter['definition_version']
112
  records=capture['frames']; n=len(records)
113
  if n<4:raise ValueError('insufficient_source_frames')
114
+ options.validate_frame_count(n)
115
  playback=np.array([r['playback_s'] for r in records],float)
116
  if not np.isfinite(playback).all() or np.any(np.diff(playback)<=0):
117
  raise ValueError('invalid_source_timestamps')
 
288
  for name,index in context['peaks'].items():
289
  metric=rows[name+'_peak_time_ms']
290
  event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
291
+ if options.contact_frame is not None:
292
+ event('ball_contact',options.contact_frame,detector='manual')
293
+ events[-1]['source_detail']='caller_reviewed_contact_frame'
294
+ else:
295
+ event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
296
  # Recompute each summary from alternate accepted rig fits, rather than
297
  # interpreting a positional residual as an angular/timing error bar.
298
  alternative_values=[]
 
328
  'calculation_inputs':calculation_options.model_dump(mode='json'),'up_reference':up_reference,
329
  'pitcher_reference':pitcher_reference})
330
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
331
+ from .motion_coach import build_coach_payload
332
+ coach_payload=build_coach_payload(calculation_options,lineage,corrected,video_times,capture_times,contexts)
333
+ if coach_payload is not None:
334
+ atomic_json(job/'coach-payload.json',coach_payload.model_dump(mode='json'))
335
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
336
  'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
337
  'reidentification':'bounded_short_loss_only; ambiguous_overlap_not_recovered','box_overlap_gate':.05,
 
355
  ('motion','motion.jsonl','application/x-ndjson','jsonl'),('measurements','measurements.json','application/json','json'),
356
  ('events','events.json','application/json','json'),('quality','quality.json','application/json','json')]}
357
  artifacts['source']=asset(source,media[source.suffix],'original_video')
358
+ if coach_payload is not None:
359
+ artifacts['coach_payload']=asset(job/'coach-payload.json','application/json','json')
360
+ artifacts['coach_payload']['url']=f'/v1/motion-analyses/{job.name}/coach-payload'
361
  artifacts['projections']=asset(job/'projections.jsonl','application/x-ndjson','jsonl') if projection_count else {
362
  'status':'unavailable','reason_code':'camera_projection_unavailable','format':'jsonl','media_type':'application/x-ndjson','expires_at':expiry}
363
  artifacts['mesh']={'status':'unavailable','reason_code':'animated_mesh_second_phase','format':'none','media_type':'application/octet-stream','expires_at':expiry}
 
392
  'correction_implementation_sha256':sha256_file(Path(__file__).with_name('sam_motion.py')),
393
  'measurement_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurements.py')),
394
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
395
+ 'coach_payload':{'schema_version':'1.0','requested':options.athlete is not None,
396
+ 'implementation_sha256':sha256_file(Path(__file__).with_name('motion_coach.py')),
397
+ 'swing_id':coach_payload.swing_id if coach_payload is not None else None,
398
+ 'event_frame_basis':'zero_based_decoded_source_frame_index',
399
+ 'foot_down_definition':'caller_selected_first_visible_touch_at_end_of_final_stride; not measured ground force',
400
+ 'event_accuracy_validated':False,'confidence_calibrated':False},
401
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
402
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
403
  'up_vector':list(calculation_options.up_vector) if calculation_options.up_vector is not None else None,
baseball_batting/motion_worker.py CHANGED
@@ -21,7 +21,7 @@ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120,retention
21
  progress('decoding');video=next(job.glob('input.*'))
22
  capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
23
  atomic_json(job/'capture-private.json',capture)
24
- if any(w.end_frame>=capture['frame_count'] for w in options.windows):raise ValueError('Reviewed window exceeds video')
25
  files=descriptor(options.model)['raw_files']
26
  if (job/'reused-inference.json').is_file():
27
  reused=read_json(job/'reused-inference.json')
@@ -53,7 +53,8 @@ def main():
53
  try:run(args.job,args.models,args.max_frames,args.max_pixels,args.max_duration,args.retention_s);return 0
54
  except Exception as error:
55
  reason=str(error) if isinstance(error,ValueError) and str(error) in {
56
- 'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames'} else 'motion_processing_failed'
 
57
  failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
58
  'reason_code':reason,'error_type':type(error).__name__}
59
  for filename in ('sam-raw-private.error.json','gvhmr-raw-private.error.json','motion-refinement-error-private.json'):
 
21
  progress('decoding');video=next(job.glob('input.*'))
22
  capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
23
  atomic_json(job/'capture-private.json',capture)
24
+ options.validate_frame_count(capture['frame_count'])
25
  files=descriptor(options.model)['raw_files']
26
  if (job/'reused-inference.json').is_file():
27
  reused=read_json(job/'reused-inference.json')
 
53
  try:run(args.job,args.models,args.max_frames,args.max_pixels,args.max_duration,args.retention_s);return 0
54
  except Exception as error:
55
  reason=str(error) if isinstance(error,ValueError) and str(error) in {
56
+ 'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames',
57
+ 'reviewed_frame_out_of_range','contact_frame_out_of_range'} else 'motion_processing_failed'
58
  failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
59
  'reason_code':reason,'error_type':type(error).__name__}
60
  for filename in ('sam-raw-private.error.json','gvhmr-raw-private.error.json','motion-refinement-error-private.json'):
docs/APP_API_INTEGRATION.md CHANGED
@@ -116,6 +116,13 @@ decoding is also checked. Schemas:
116
 
117
  ## 4. Upload a recording
118
 
 
 
 
 
 
 
 
119
  **`POST /v1/motion-analyses`**, body **multipart form data**:
120
 
121
  | Field | Type | Value |
@@ -459,8 +466,9 @@ present `start`/`end`. Each event includes `rep`, `status`, `source`,
459
  `forward_swing_window`, `stride_start`, `foot_plant`, `hip_speed_peak`,
460
  `shoulder_speed_peak`, `hands_speed_peak`, and `ball_contact`. Only draw events
461
  with an actual start sample. Distinguish reviewed from estimated events.
462
- Body landmarks do not establish bat-ball impact: `ball_contact` is currently
463
- unavailable on this route.
 
464
 
465
  **The four motion API videos cover the complete recording. This route does not
466
  currently return a separately encoded annotated MP4 for every swing.** For a
 
116
 
117
  ## 4. Upload a recording
118
 
119
+ To also obtain the AI coach's single-swing contract, use the same upload with
120
+ `single_swing: true`, `athlete` information and optional `contact_frame`. Keep all
121
+ existing recording options and reviewed window fields. Follow
122
+ [MOTION_COACH_PAYLOAD.md](MOTION_COACH_PAYLOAD.md) for the request and the new
123
+ `GET /v1/motion-analyses/{job_id}/coach-payload` response, then forward that JSON
124
+ unchanged to `POST /v1/sessions/{id}/swing-report` on the coach backend.
125
+
126
  **`POST /v1/motion-analyses`**, body **multipart form data**:
127
 
128
  | Field | Type | Value |
 
466
  `forward_swing_window`, `stride_start`, `foot_plant`, `hip_speed_peak`,
467
  `shoulder_speed_peak`, `hands_speed_peak`, and `ball_contact`. Only draw events
468
  with an actual start sample. Distinguish reviewed from estimated events.
469
+ Body landmarks do not establish bat-ball impact. With `single_swing: true`, an
470
+ optional `contact_frame` creates a manually reviewed `ball_contact` event;
471
+ otherwise it remains unavailable.
472
 
473
  **The four motion API videos cover the complete recording. This route does not
474
  currently return a separately encoded annotated MP4 for every swing.** For a
docs/MOTION_COACH_PAYLOAD.md ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Motion analysis → AI coach: contract 1.0
2
+
3
+ The existing motion API can export the three measurements from `ml_contract_v1.md`.
4
+ It still supports every previous request field, both SAM 3D and GVHMR, skeleton
5
+ playback, measurements, projections, annotated videos and immutable revisions.
6
+ The coaching export is opt-in through `options.athlete`, and supports **one swing
7
+ per video**. Existing uploads without athlete information keep their previous flow.
8
+
9
+ ## Request
10
+
11
+ Send multipart form data to **`POST /v1/motion-analyses`**:
12
+
13
+ | Field | Type | Meaning |
14
+ |---|---|---|
15
+ | `video` | File | Original recording. |
16
+ | `options` | Text containing JSON | Existing motion options plus the fields below. |
17
+ | `source_asset_id` | Text, optional | Existing source reuse; supply this **instead of** `video`. |
18
+
19
+ Example `options` (frame numbers are illustrative and must match your recording):
20
+
21
+ ```json
22
+ {
23
+ "model": "gvhmr",
24
+ "single_swing": true,
25
+ "annotated_videos": true,
26
+ "handedness": "right",
27
+ "lead_foot": "left",
28
+ "camera_stability": "fixed_verified",
29
+ "timing": { "kind": "unknown" },
30
+ "athlete": {
31
+ "athlete_id": "player-001",
32
+ "batting_hand": "right",
33
+ "lead_foot": "left",
34
+ "age_years": 16,
35
+ "height_cm": 175
36
+ },
37
+ "context": { "sport": "baseball", "practice_type": "tee" },
38
+ "swing_id": "swing-001",
39
+ "contact_frame": 90,
40
+ "windows": [{
41
+ "start_frame": 0,
42
+ "end_frame": 140,
43
+ "baseline_frame": 10,
44
+ "forward_start_frame": 75,
45
+ "forward_end_frame": 120,
46
+ "stride_start_frame": 45,
47
+ "landing_frame": 70,
48
+ "source": "Reviewed original recording"
49
+ }]
50
+ }
51
+ ```
52
+
53
+ Use `model: "sam3d"` to run SAM. Set `fixed_verified` only when known. Use
54
+ `timing: {"kind":"unretimed","source":"Original recording; no speed changes"}`
55
+ only when confirmed. Existing camera calibration, up/pitcher references and floor
56
+ point selections, scale, rotation, athlete box, correction, refinement, tracking,
57
+ GVHMR settings and window fields remain accepted. No new tuning is required.
58
+
59
+ | New option | Required / default | Meaning |
60
+ |---|---|---|
61
+ | `athlete` | Optional; default `null` | Enables the coach payload. Requires `single_swing: true`. |
62
+ | `athlete.athlete_id` | Required when athlete is supplied | Nonempty player ID. |
63
+ | `athlete.batting_hand` | Optional, default `null` | `left` / `right`. May use existing top-level `handedness` instead. Conflicting non-null values are rejected. |
64
+ | `athlete.lead_foot` | Optional, default `null` | `left` / `right`. May use existing top-level `lead_foot` instead. Conflicting non-null values are rejected. When omitted, inferred from known batting hand. |
65
+ | `athlete.age_years` | Optional, default `null` | Nonnegative integer. |
66
+ | `athlete.height_cm` | Optional, default `null` | Positive number. Player metadata; **does not calibrate 3D scale**. |
67
+ | `context` | Default baseball / unknown | `sport: "baseball"`; `practice_type`: `tee`, `front_toss`, `side_toss`, `pitching_machine`, `live_pitching`, `game`, `dry_swing`, `unknown`. |
68
+ | `contact_frame` | Optional, default `null` | Reviewed bat-ball contact source-frame index. Requires `single_swing: true`. |
69
+ | `swing_id` | Optional | Stable ID for this recorded swing. Defaults to `<analysis_id>:swing_1`. |
70
+
71
+ All frame indices are **zero-based decoded source-frame indices**, matching
72
+ `motion.jsonl.source_frame_index`. They refer to the uploaded video, before any
73
+ cropping of the timeline or playback-speed changes. Image rotation does not
74
+ renumber frames. Do not send a timestamp or a screenshot number in these fields.
75
+ No bat/ball pixel coordinates are required for these three body measurements.
76
+
77
+ ## Which frames should the app request?
78
+
79
+ - `windows[0].stride_start_frame`: the reviewed beginning of the final stride.
80
+ - `windows[0].landing_frame`: the **first visible ground touch at the end of that
81
+ stride**, excluding earlier toe taps. This supplies the coach's `front_foot_down`.
82
+ - `contact_frame`: the reviewed frame showing bat-ball contact.
83
+
84
+ Keep the existing `start_frame`, `end_frame`, baseline and forward-window fields.
85
+ Stride start and landing must be supplied together, with stride start before
86
+ landing. Contact must be inside the selected swing window and cannot precede
87
+ landing. If frame count is only known after decoding, an out-of-range frame fails
88
+ the job **before model inference** with `contact_frame_out_of_range` or
89
+ `reviewed_frame_out_of_range`. Revision requests reject known invalid ranges with
90
+ HTTP 422 before queuing. Negative, fractional and boolean frame indices are invalid.
91
+
92
+ These are reviewed video events, not validated automatic detections. The coach's
93
+ laboratory benchmark uses a ground-force threshold; visible touch is an
94
+ approximation and does not prove 10% bodyweight loading or full plant. Selected
95
+ events use `source: "manual_review"`, `status: "limited"` and
96
+ `reasons: ["event_timing_uncertain"]`. Dependent measurements retain this limitation.
97
+ The API does not guess a landing from the maximum separation or a contact from
98
+ body pose. Missing stride frames leave both foot-down metrics unavailable.
99
+ Missing contact leaves only the contact metric unavailable. For `dry_swing`,
100
+ contact is `contact_not_applicable`; supplying a contact frame is rejected.
101
+
102
+ ## Fetch and forward the payload
103
+
104
+ 1. Upload as before; save `job_id`, `analysis_id`, `analysis_revision`, `status_url`
105
+ and the new `coach_payload_url`.
106
+ 2. Poll `status_url` until completed. Fetch the normal `result_url` for motion
107
+ playback and existing artifacts.
108
+ 3. Fetch **`GET /v1/motion-analyses/{job_id}/coach-payload`** using the same bearer
109
+ authentication. It returns the contract JSON itself, without an envelope.
110
+ 4. The app forwards that JSON unchanged to the coach's
111
+ **`POST /v1/sessions/{id}/swing-report`**. The motion API does not call the coach,
112
+ invent benchmarks or produce additional scores.
113
+
114
+ The manifest also exposes `artifacts.coach_payload` with its URL, filename,
115
+ checksum, size and expiry. `GET /v1/motion-analyses/{job_id}/artifacts/coach_payload`
116
+ downloads the same immutable bytes. The convenience endpoint checks the artifact
117
+ checksum and analysis ID/revision before returning it, and sends `Cache-Control:
118
+ no-store`. A pending job or a completed analysis without player information returns
119
+ 409; unauthorized access returns 401; failed integrity checks return 500.
120
+
121
+ See [output schema](motion-coach-payload.schema.json) and
122
+ [example response](motion-coach-payload.example.json). Live schemas remain at
123
+ `GET /v1/motion-analyses/input-schema` and `output-schema`; the latter includes
124
+ `coach_payload`. The original motion manifest schema version remains `1.0`.
125
+
126
+ ## Measurements, units and reliability
127
+
128
+ Every completed coach payload includes exactly these three entries, even when
129
+ some values are unavailable. Contract and measurement-definition versions are
130
+ both `"1.0"`; IDs, units, groups, references and point/interval scopes match the
131
+ receiver contract exactly.
132
+
133
+ | Metric | Calculation |
134
+ |---|---|
135
+ | `hip_shoulder_separation_at_foot_down` | `wrap180(shoulder_heading - hip_heading)` at `landing_frame`, using the corrected horizontal hip and shoulder lines. **Not the maximum over the swing.** |
136
+ | `stride_relative_length` | `100 * norm(horizontal((lead_ankle - rear_ankle)[landing] - (lead_ankle - rear_ankle)[stride_start]))`, in cm. Includes forward and sideways displacement; is not absolute lead-foot ground travel or a percentage of height. |
137
+ | `hip_shoulder_separation_at_contact` | The same signed angle at `contact_frame`. |
138
+
139
+ Angles are in `[-180, 180)`: positive is counter-clockwise shoulder minus hip
140
+ heading viewed from above. The same sign convention is kept for both batting
141
+ sides. The coach owns side-specific comparisons. SAM and GVHMR use different
142
+ native anatomical joint definitions; formula compatibility does not establish
143
+ lab accuracy or interchangeability between models.
144
+
145
+ The exporter uses the **same corrected points** and resolved up direction as
146
+ `motion.jsonl`, existing measurements and annotations. Relative measurements do
147
+ not require a ground origin; their horizontal plane requires a usable up
148
+ direction. The existing camera-stability and landmark checks still apply.
149
+
150
+ - Unknown up direction → `ground_plane_unknown`; unusable body points →
151
+ `required_landmarks_unusable`; unverified/moving camera → `temporal_inconsistency`.
152
+ - Model-estimated centimeters → `limited` with `scale_is_model_estimated`.
153
+ Unknown scale → stride `unavailable`, `value: null`, `scale_unknown`.
154
+ - Missing required events propagate `required_event_unavailable`; missing verified
155
+ contact includes `contact_not_verified`. Unknown lead foot includes `lead_foot_unknown`.
156
+ - `uses_interpolated_input` checks the required joints at the actual event frames,
157
+ not unrelated joints elsewhere in the recording. GVHMR's source-time resampling
158
+ is retained as interpolated provenance. Such inputs and filter boundaries add
159
+ `temporal_inconsistency`; small interpolation is not called excessive.
160
+ - `confidence: null` and `benchmark: null` for every measurement. Accuracy has
161
+ not been independently validated. Numerical availability is not a quality grade.
162
+ - `video_time_s` comes from source presentation timestamps relative to the first
163
+ frame. `capture_time_s` is supplied only with a documented clock mapping; it is
164
+ otherwise null. No physical timing is guessed from playback FPS.
165
+
166
+ ## Revisions
167
+
168
+ Use existing **`POST /v1/motion-analyses/{job_id}/revisions`** with an `options`
169
+ patch to change player metadata, contact/stride selections or calculation inputs.
170
+ An older analysis can acquire a coach export through a revision adding `athlete`
171
+ and `single_swing: true`. Review its `landing_frame` again if it previously marked
172
+ a settled/full plant: this contract uses first visible touch. For example:
173
+
174
+ ```json
175
+ {
176
+ "options": {
177
+ "contact_frame": 91,
178
+ "athlete": { "height_cm": 176 }
179
+ }
180
+ }
181
+ ```
182
+
183
+ The new payload keeps the root `analysis_id` and `swing_id` and increments
184
+ `analysis_revision`, matching the new visual artifacts. Parent files remain
185
+ unchanged. Changing an established `athlete_id` or `swing_id` requires a new
186
+ analysis. The app/coach must ignore duplicate or older revisions as specified by
187
+ the receiver contract. Once enabled, retain `athlete` across revisions; individual
188
+ optional player fields can still be cleared to null. Event/player metadata edits reuse eligible native inference
189
+ through the existing integrity-checked reuse path.
190
+
191
+ The payload registers no Balance and Load or Power Move metrics. Other motion
192
+ measurements remain in the existing artifacts, but cannot be appended to this
193
+ strict three-metric contract without a coordinated contract update.
docs/MOTION_PLAYER_API.md CHANGED
@@ -1,6 +1,6 @@
1
  # Motion-player backend API
2
 
3
- Contract 1.0 · SAM and GVHMR adapters · native-body refinement · 19 October 2026
4
 
5
  For app implementation, start with the [frontend integration guide](APP_API_INTEGRATION.md),
6
  updated 19 October 2026. It covers migration, authenticated video playback,
@@ -13,6 +13,11 @@ It exports actual corrected motion for an interactive skeleton player, using
13
  SAM 3D Body or GVHMR through the same routes. A client frontend and animated
14
  body mesh are outside this version. Existing callers continue to default to SAM.
15
 
 
 
 
 
 
16
  ## Choose the model
17
 
18
  Set `model` inside the existing form-data `options` JSON:
@@ -56,12 +61,13 @@ player improvement. Each manifest records the actual native indices/definitions.
56
  | `POST /v1/motion-analyses` | Multipart video or existing source asset; returns 202. |
57
  | `GET /v1/motion-analyses/{job_id}` | Status, progress, immutable revision and failure reason. |
58
  | `GET /v1/motion-analyses/{job_id}/result` | Completed manifest and artifact URLs. |
 
59
  | `GET` / `HEAD /v1/motion-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; byte ranges supported. |
60
  | `POST /v1/motion-analyses/{job_id}/revisions` | Recording-fact/correction/event patch into a new immutable revision. |
61
  | `DELETE /v1/motion-analyses/{job_id}` | Cancel/delete this execution and its retained files. |
62
  | `GET /v1/motion-analyses/capabilities` | Model/configuration, limits and retention. |
63
  | `GET /v1/motion-analyses/input-schema` | Recording options schema. |
64
- | `GET /v1/motion-analyses/output-schema` | Manifest, motion-frame and projection-frame schemas. |
65
 
66
  ## Upload and polling
67
 
@@ -316,6 +322,12 @@ reasons. Sources distinguish manual review, pose-estimated windows and sampled
316
  speed peaks. Automatic windows remain candidates. An unavailable foot-plant
317
  event does not prove that no step occurred.
318
 
 
 
 
 
 
 
319
  ## Immutable reviewed revisions
320
 
321
  Send a JSON patch to the parent's `/revisions` endpoint. Unchanged options are
 
1
  # Motion-player backend API
2
 
3
+ Contract 1.0 · SAM and GVHMR adapters · native-body refinement · 23 October 2026
4
 
5
  For app implementation, start with the [frontend integration guide](APP_API_INTEGRATION.md),
6
  updated 19 October 2026. It covers migration, authenticated video playback,
 
13
  SAM 3D Body or GVHMR through the same routes. A client frontend and animated
14
  body mesh are outside this version. Existing callers continue to default to SAM.
15
 
16
+ For the AI coach's strict three-measurement payload, see
17
+ [single-swing coach export](MOTION_COACH_PAYLOAD.md). Add player information and
18
+ an optional reviewed `contact_frame` to the existing request; previous options
19
+ and motion artifacts are preserved.
20
+
21
  ## Choose the model
22
 
23
  Set `model` inside the existing form-data `options` JSON:
 
61
  | `POST /v1/motion-analyses` | Multipart video or existing source asset; returns 202. |
62
  | `GET /v1/motion-analyses/{job_id}` | Status, progress, immutable revision and failure reason. |
63
  | `GET /v1/motion-analyses/{job_id}/result` | Completed manifest and artifact URLs. |
64
+ | `GET /v1/motion-analyses/{job_id}/coach-payload` | Opt-in single-swing measurement payload matching the coach's contract 1.0. |
65
  | `GET` / `HEAD /v1/motion-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; byte ranges supported. |
66
  | `POST /v1/motion-analyses/{job_id}/revisions` | Recording-fact/correction/event patch into a new immutable revision. |
67
  | `DELETE /v1/motion-analyses/{job_id}` | Cancel/delete this execution and its retained files. |
68
  | `GET /v1/motion-analyses/capabilities` | Model/configuration, limits and retention. |
69
  | `GET /v1/motion-analyses/input-schema` | Recording options schema. |
70
+ | `GET /v1/motion-analyses/output-schema` | Manifest, motion-frame, projection-frame and coach-payload schemas. |
71
 
72
  ## Upload and polling
73
 
 
322
  speed peaks. Automatic windows remain candidates. An unavailable foot-plant
323
  event does not prove that no step occurred.
324
 
325
+ For one swing, a supplied `contact_frame` creates a reviewed `ball_contact` event;
326
+ without it contact remains unavailable. Player information under `athlete` enables
327
+ the separate coach payload, sampled at the reviewed stride/landing/contact frames.
328
+ It does not change the existing maximum-separation summary. See the
329
+ [request, event definitions and reliability mapping](MOTION_COACH_PAYLOAD.md).
330
+
331
  ## Immutable reviewed revisions
332
 
333
  Send a JSON patch to the parent's `/revisions` endpoint. Unchanged options are
docs/motion-coach-payload.example.json ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "1.0",
3
+ "measurement_definitions_version": "1.0",
4
+ "analysis_id": "analysis-test",
5
+ "analysis_revision": 1,
6
+ "swing_id": "analysis-test:swing_1",
7
+ "status": "completed",
8
+ "athlete": {
9
+ "athlete_id": "player-test",
10
+ "batting_hand": "right",
11
+ "lead_foot": "left",
12
+ "age_years": 16,
13
+ "height_cm": 175.0
14
+ },
15
+ "context": {
16
+ "sport": "baseball",
17
+ "practice_type": "tee"
18
+ },
19
+ "events": {
20
+ "stride_start": {
21
+ "video_time_s": 0.03,
22
+ "capture_time_s": 0.0075,
23
+ "status": "limited",
24
+ "source": "manual_review",
25
+ "reasons": [
26
+ "event_timing_uncertain"
27
+ ]
28
+ },
29
+ "front_foot_down": {
30
+ "video_time_s": 0.15,
31
+ "capture_time_s": 0.0375,
32
+ "status": "limited",
33
+ "source": "manual_review",
34
+ "reasons": [
35
+ "event_timing_uncertain"
36
+ ]
37
+ },
38
+ "contact": {
39
+ "video_time_s": 0.22,
40
+ "capture_time_s": 0.055,
41
+ "status": "limited",
42
+ "source": "manual_review",
43
+ "reasons": [
44
+ "event_timing_uncertain"
45
+ ]
46
+ }
47
+ },
48
+ "measurements": [
49
+ {
50
+ "value": 30.0,
51
+ "status": "limited",
52
+ "confidence": null,
53
+ "uses_interpolated_input": false,
54
+ "reasons": [
55
+ "event_timing_uncertain"
56
+ ],
57
+ "benchmark": null,
58
+ "metric_id": "hip_shoulder_separation_at_foot_down",
59
+ "group": "stride",
60
+ "unit": "deg",
61
+ "reference": "signed_horizontal_shoulder_minus_hip_heading",
62
+ "event_id": "front_foot_down"
63
+ },
64
+ {
65
+ "value": 22.361,
66
+ "status": "limited",
67
+ "confidence": null,
68
+ "uses_interpolated_input": false,
69
+ "reasons": [
70
+ "event_timing_uncertain",
71
+ "scale_is_model_estimated"
72
+ ],
73
+ "benchmark": null,
74
+ "metric_id": "stride_relative_length",
75
+ "group": "stride",
76
+ "unit": "cm",
77
+ "reference": "lead_ankle_displacement_relative_to_rear_ankle",
78
+ "start_event_id": "stride_start",
79
+ "end_event_id": "front_foot_down"
80
+ },
81
+ {
82
+ "value": 10.0,
83
+ "status": "limited",
84
+ "confidence": null,
85
+ "uses_interpolated_input": false,
86
+ "reasons": [
87
+ "event_timing_uncertain"
88
+ ],
89
+ "benchmark": null,
90
+ "metric_id": "hip_shoulder_separation_at_contact",
91
+ "group": "contact_follow_through",
92
+ "unit": "deg",
93
+ "reference": "signed_horizontal_shoulder_minus_hip_heading",
94
+ "event_id": "contact"
95
+ }
96
+ ]
97
+ }
docs/motion-coach-payload.schema.json ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "CoachAthlete": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "athlete_id": {
7
+ "maxLength": 180,
8
+ "minLength": 1,
9
+ "pattern": "\\S",
10
+ "title": "Athlete Id",
11
+ "type": "string"
12
+ },
13
+ "batting_hand": {
14
+ "anyOf": [
15
+ {
16
+ "enum": [
17
+ "left",
18
+ "right"
19
+ ],
20
+ "type": "string"
21
+ },
22
+ {
23
+ "type": "null"
24
+ }
25
+ ],
26
+ "default": null,
27
+ "title": "Batting Hand"
28
+ },
29
+ "lead_foot": {
30
+ "anyOf": [
31
+ {
32
+ "enum": [
33
+ "left",
34
+ "right"
35
+ ],
36
+ "type": "string"
37
+ },
38
+ {
39
+ "type": "null"
40
+ }
41
+ ],
42
+ "default": null,
43
+ "title": "Lead Foot"
44
+ },
45
+ "age_years": {
46
+ "anyOf": [
47
+ {
48
+ "minimum": 0,
49
+ "type": "integer"
50
+ },
51
+ {
52
+ "type": "null"
53
+ }
54
+ ],
55
+ "default": null,
56
+ "title": "Age Years"
57
+ },
58
+ "height_cm": {
59
+ "anyOf": [
60
+ {
61
+ "exclusiveMinimum": 0,
62
+ "type": "number"
63
+ },
64
+ {
65
+ "type": "null"
66
+ }
67
+ ],
68
+ "default": null,
69
+ "title": "Height Cm"
70
+ }
71
+ },
72
+ "required": [
73
+ "athlete_id"
74
+ ],
75
+ "title": "CoachAthlete",
76
+ "type": "object"
77
+ },
78
+ "CoachContext": {
79
+ "additionalProperties": false,
80
+ "properties": {
81
+ "sport": {
82
+ "const": "baseball",
83
+ "default": "baseball",
84
+ "title": "Sport",
85
+ "type": "string"
86
+ },
87
+ "practice_type": {
88
+ "default": "unknown",
89
+ "enum": [
90
+ "tee",
91
+ "front_toss",
92
+ "side_toss",
93
+ "pitching_machine",
94
+ "live_pitching",
95
+ "game",
96
+ "dry_swing",
97
+ "unknown"
98
+ ],
99
+ "title": "Practice Type",
100
+ "type": "string"
101
+ }
102
+ },
103
+ "title": "CoachContext",
104
+ "type": "object"
105
+ },
106
+ "CoachEvent": {
107
+ "additionalProperties": false,
108
+ "properties": {
109
+ "video_time_s": {
110
+ "anyOf": [
111
+ {
112
+ "minimum": 0,
113
+ "type": "number"
114
+ },
115
+ {
116
+ "type": "null"
117
+ }
118
+ ],
119
+ "title": "Video Time S"
120
+ },
121
+ "capture_time_s": {
122
+ "anyOf": [
123
+ {
124
+ "minimum": 0,
125
+ "type": "number"
126
+ },
127
+ {
128
+ "type": "null"
129
+ }
130
+ ],
131
+ "title": "Capture Time S"
132
+ },
133
+ "status": {
134
+ "enum": [
135
+ "available",
136
+ "limited",
137
+ "unavailable"
138
+ ],
139
+ "title": "Status",
140
+ "type": "string"
141
+ },
142
+ "source": {
143
+ "anyOf": [
144
+ {
145
+ "enum": [
146
+ "manual_review",
147
+ "pose_estimated",
148
+ "bat_ball_detector"
149
+ ],
150
+ "type": "string"
151
+ },
152
+ {
153
+ "type": "null"
154
+ }
155
+ ],
156
+ "title": "Source"
157
+ },
158
+ "reasons": {
159
+ "items": {
160
+ "enum": [
161
+ "contact_not_verified",
162
+ "contact_not_applicable",
163
+ "event_not_detected",
164
+ "event_timing_uncertain",
165
+ "required_event_unavailable",
166
+ "required_event_limited",
167
+ "lead_foot_unknown",
168
+ "required_landmarks_unusable",
169
+ "ground_plane_unknown",
170
+ "scale_is_model_estimated",
171
+ "scale_unknown",
172
+ "excessive_interpolation",
173
+ "occlusion_unresolved",
174
+ "temporal_inconsistency"
175
+ ],
176
+ "type": "string"
177
+ },
178
+ "title": "Reasons",
179
+ "type": "array"
180
+ }
181
+ },
182
+ "required": [
183
+ "video_time_s",
184
+ "capture_time_s",
185
+ "status",
186
+ "source",
187
+ "reasons"
188
+ ],
189
+ "title": "CoachEvent",
190
+ "type": "object"
191
+ },
192
+ "CoachEvents": {
193
+ "additionalProperties": false,
194
+ "properties": {
195
+ "stride_start": {
196
+ "$ref": "#/$defs/CoachEvent"
197
+ },
198
+ "front_foot_down": {
199
+ "$ref": "#/$defs/CoachEvent"
200
+ },
201
+ "contact": {
202
+ "$ref": "#/$defs/CoachEvent"
203
+ }
204
+ },
205
+ "required": [
206
+ "stride_start",
207
+ "front_foot_down",
208
+ "contact"
209
+ ],
210
+ "title": "CoachEvents",
211
+ "type": "object"
212
+ },
213
+ "RelativeStride": {
214
+ "additionalProperties": false,
215
+ "properties": {
216
+ "value": {
217
+ "anyOf": [
218
+ {
219
+ "minimum": 0,
220
+ "type": "number"
221
+ },
222
+ {
223
+ "type": "null"
224
+ }
225
+ ],
226
+ "title": "Value"
227
+ },
228
+ "status": {
229
+ "enum": [
230
+ "available",
231
+ "limited",
232
+ "unavailable"
233
+ ],
234
+ "title": "Status",
235
+ "type": "string"
236
+ },
237
+ "confidence": {
238
+ "anyOf": [
239
+ {
240
+ "maximum": 1,
241
+ "minimum": 0,
242
+ "type": "number"
243
+ },
244
+ {
245
+ "type": "null"
246
+ }
247
+ ],
248
+ "title": "Confidence"
249
+ },
250
+ "uses_interpolated_input": {
251
+ "title": "Uses Interpolated Input",
252
+ "type": "boolean"
253
+ },
254
+ "reasons": {
255
+ "items": {
256
+ "enum": [
257
+ "contact_not_verified",
258
+ "contact_not_applicable",
259
+ "event_not_detected",
260
+ "event_timing_uncertain",
261
+ "required_event_unavailable",
262
+ "required_event_limited",
263
+ "lead_foot_unknown",
264
+ "required_landmarks_unusable",
265
+ "ground_plane_unknown",
266
+ "scale_is_model_estimated",
267
+ "scale_unknown",
268
+ "excessive_interpolation",
269
+ "occlusion_unresolved",
270
+ "temporal_inconsistency"
271
+ ],
272
+ "type": "string"
273
+ },
274
+ "title": "Reasons",
275
+ "type": "array"
276
+ },
277
+ "benchmark": {
278
+ "default": null,
279
+ "title": "Benchmark",
280
+ "type": "null"
281
+ },
282
+ "metric_id": {
283
+ "const": "stride_relative_length",
284
+ "default": "stride_relative_length",
285
+ "title": "Metric Id",
286
+ "type": "string"
287
+ },
288
+ "group": {
289
+ "const": "stride",
290
+ "default": "stride",
291
+ "title": "Group",
292
+ "type": "string"
293
+ },
294
+ "unit": {
295
+ "const": "cm",
296
+ "default": "cm",
297
+ "title": "Unit",
298
+ "type": "string"
299
+ },
300
+ "reference": {
301
+ "const": "lead_ankle_displacement_relative_to_rear_ankle",
302
+ "default": "lead_ankle_displacement_relative_to_rear_ankle",
303
+ "title": "Reference",
304
+ "type": "string"
305
+ },
306
+ "start_event_id": {
307
+ "const": "stride_start",
308
+ "default": "stride_start",
309
+ "title": "Start Event Id",
310
+ "type": "string"
311
+ },
312
+ "end_event_id": {
313
+ "const": "front_foot_down",
314
+ "default": "front_foot_down",
315
+ "title": "End Event Id",
316
+ "type": "string"
317
+ }
318
+ },
319
+ "required": [
320
+ "value",
321
+ "status",
322
+ "confidence",
323
+ "uses_interpolated_input",
324
+ "reasons"
325
+ ],
326
+ "title": "RelativeStride",
327
+ "type": "object"
328
+ },
329
+ "SeparationAtContact": {
330
+ "additionalProperties": false,
331
+ "properties": {
332
+ "value": {
333
+ "anyOf": [
334
+ {
335
+ "exclusiveMaximum": 180,
336
+ "minimum": -180,
337
+ "type": "number"
338
+ },
339
+ {
340
+ "type": "null"
341
+ }
342
+ ],
343
+ "title": "Value"
344
+ },
345
+ "status": {
346
+ "enum": [
347
+ "available",
348
+ "limited",
349
+ "unavailable"
350
+ ],
351
+ "title": "Status",
352
+ "type": "string"
353
+ },
354
+ "confidence": {
355
+ "anyOf": [
356
+ {
357
+ "maximum": 1,
358
+ "minimum": 0,
359
+ "type": "number"
360
+ },
361
+ {
362
+ "type": "null"
363
+ }
364
+ ],
365
+ "title": "Confidence"
366
+ },
367
+ "uses_interpolated_input": {
368
+ "title": "Uses Interpolated Input",
369
+ "type": "boolean"
370
+ },
371
+ "reasons": {
372
+ "items": {
373
+ "enum": [
374
+ "contact_not_verified",
375
+ "contact_not_applicable",
376
+ "event_not_detected",
377
+ "event_timing_uncertain",
378
+ "required_event_unavailable",
379
+ "required_event_limited",
380
+ "lead_foot_unknown",
381
+ "required_landmarks_unusable",
382
+ "ground_plane_unknown",
383
+ "scale_is_model_estimated",
384
+ "scale_unknown",
385
+ "excessive_interpolation",
386
+ "occlusion_unresolved",
387
+ "temporal_inconsistency"
388
+ ],
389
+ "type": "string"
390
+ },
391
+ "title": "Reasons",
392
+ "type": "array"
393
+ },
394
+ "benchmark": {
395
+ "default": null,
396
+ "title": "Benchmark",
397
+ "type": "null"
398
+ },
399
+ "metric_id": {
400
+ "const": "hip_shoulder_separation_at_contact",
401
+ "default": "hip_shoulder_separation_at_contact",
402
+ "title": "Metric Id",
403
+ "type": "string"
404
+ },
405
+ "group": {
406
+ "const": "contact_follow_through",
407
+ "default": "contact_follow_through",
408
+ "title": "Group",
409
+ "type": "string"
410
+ },
411
+ "unit": {
412
+ "const": "deg",
413
+ "default": "deg",
414
+ "title": "Unit",
415
+ "type": "string"
416
+ },
417
+ "reference": {
418
+ "const": "signed_horizontal_shoulder_minus_hip_heading",
419
+ "default": "signed_horizontal_shoulder_minus_hip_heading",
420
+ "title": "Reference",
421
+ "type": "string"
422
+ },
423
+ "event_id": {
424
+ "const": "contact",
425
+ "default": "contact",
426
+ "title": "Event Id",
427
+ "type": "string"
428
+ }
429
+ },
430
+ "required": [
431
+ "value",
432
+ "status",
433
+ "confidence",
434
+ "uses_interpolated_input",
435
+ "reasons"
436
+ ],
437
+ "title": "SeparationAtContact",
438
+ "type": "object"
439
+ },
440
+ "SeparationAtFootDown": {
441
+ "additionalProperties": false,
442
+ "properties": {
443
+ "value": {
444
+ "anyOf": [
445
+ {
446
+ "exclusiveMaximum": 180,
447
+ "minimum": -180,
448
+ "type": "number"
449
+ },
450
+ {
451
+ "type": "null"
452
+ }
453
+ ],
454
+ "title": "Value"
455
+ },
456
+ "status": {
457
+ "enum": [
458
+ "available",
459
+ "limited",
460
+ "unavailable"
461
+ ],
462
+ "title": "Status",
463
+ "type": "string"
464
+ },
465
+ "confidence": {
466
+ "anyOf": [
467
+ {
468
+ "maximum": 1,
469
+ "minimum": 0,
470
+ "type": "number"
471
+ },
472
+ {
473
+ "type": "null"
474
+ }
475
+ ],
476
+ "title": "Confidence"
477
+ },
478
+ "uses_interpolated_input": {
479
+ "title": "Uses Interpolated Input",
480
+ "type": "boolean"
481
+ },
482
+ "reasons": {
483
+ "items": {
484
+ "enum": [
485
+ "contact_not_verified",
486
+ "contact_not_applicable",
487
+ "event_not_detected",
488
+ "event_timing_uncertain",
489
+ "required_event_unavailable",
490
+ "required_event_limited",
491
+ "lead_foot_unknown",
492
+ "required_landmarks_unusable",
493
+ "ground_plane_unknown",
494
+ "scale_is_model_estimated",
495
+ "scale_unknown",
496
+ "excessive_interpolation",
497
+ "occlusion_unresolved",
498
+ "temporal_inconsistency"
499
+ ],
500
+ "type": "string"
501
+ },
502
+ "title": "Reasons",
503
+ "type": "array"
504
+ },
505
+ "benchmark": {
506
+ "default": null,
507
+ "title": "Benchmark",
508
+ "type": "null"
509
+ },
510
+ "metric_id": {
511
+ "const": "hip_shoulder_separation_at_foot_down",
512
+ "default": "hip_shoulder_separation_at_foot_down",
513
+ "title": "Metric Id",
514
+ "type": "string"
515
+ },
516
+ "group": {
517
+ "const": "stride",
518
+ "default": "stride",
519
+ "title": "Group",
520
+ "type": "string"
521
+ },
522
+ "unit": {
523
+ "const": "deg",
524
+ "default": "deg",
525
+ "title": "Unit",
526
+ "type": "string"
527
+ },
528
+ "reference": {
529
+ "const": "signed_horizontal_shoulder_minus_hip_heading",
530
+ "default": "signed_horizontal_shoulder_minus_hip_heading",
531
+ "title": "Reference",
532
+ "type": "string"
533
+ },
534
+ "event_id": {
535
+ "const": "front_foot_down",
536
+ "default": "front_foot_down",
537
+ "title": "Event Id",
538
+ "type": "string"
539
+ }
540
+ },
541
+ "required": [
542
+ "value",
543
+ "status",
544
+ "confidence",
545
+ "uses_interpolated_input",
546
+ "reasons"
547
+ ],
548
+ "title": "SeparationAtFootDown",
549
+ "type": "object"
550
+ }
551
+ },
552
+ "additionalProperties": false,
553
+ "properties": {
554
+ "schema_version": {
555
+ "const": "1.0",
556
+ "default": "1.0",
557
+ "title": "Schema Version",
558
+ "type": "string"
559
+ },
560
+ "measurement_definitions_version": {
561
+ "const": "1.0",
562
+ "default": "1.0",
563
+ "title": "Measurement Definitions Version",
564
+ "type": "string"
565
+ },
566
+ "analysis_id": {
567
+ "minLength": 1,
568
+ "title": "Analysis Id",
569
+ "type": "string"
570
+ },
571
+ "analysis_revision": {
572
+ "minimum": 1,
573
+ "title": "Analysis Revision",
574
+ "type": "integer"
575
+ },
576
+ "swing_id": {
577
+ "minLength": 1,
578
+ "title": "Swing Id",
579
+ "type": "string"
580
+ },
581
+ "status": {
582
+ "const": "completed",
583
+ "default": "completed",
584
+ "title": "Status",
585
+ "type": "string"
586
+ },
587
+ "athlete": {
588
+ "$ref": "#/$defs/CoachAthlete"
589
+ },
590
+ "context": {
591
+ "$ref": "#/$defs/CoachContext"
592
+ },
593
+ "events": {
594
+ "$ref": "#/$defs/CoachEvents"
595
+ },
596
+ "measurements": {
597
+ "items": {
598
+ "anyOf": [
599
+ {
600
+ "$ref": "#/$defs/SeparationAtFootDown"
601
+ },
602
+ {
603
+ "$ref": "#/$defs/RelativeStride"
604
+ },
605
+ {
606
+ "$ref": "#/$defs/SeparationAtContact"
607
+ }
608
+ ]
609
+ },
610
+ "maxItems": 3,
611
+ "minItems": 3,
612
+ "title": "Measurements",
613
+ "type": "array"
614
+ }
615
+ },
616
+ "required": [
617
+ "analysis_id",
618
+ "analysis_revision",
619
+ "swing_id",
620
+ "athlete",
621
+ "context",
622
+ "events",
623
+ "measurements"
624
+ ],
625
+ "title": "MotionCoachPayload",
626
+ "type": "object"
627
+ }
docs/motion-input.schema.json CHANGED
@@ -1,5 +1,108 @@
1
  {
2
  "$defs": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  "CorrectionSettings": {
4
  "additionalProperties": false,
5
  "properties": {
@@ -1109,6 +1212,48 @@
1109
  }
1110
  ],
1111
  "default": null
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1112
  }
1113
  },
1114
  "title": "MotionInput",
 
1
  {
2
  "$defs": {
3
+ "CoachAthlete": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "athlete_id": {
7
+ "maxLength": 180,
8
+ "minLength": 1,
9
+ "pattern": "\\S",
10
+ "title": "Athlete Id",
11
+ "type": "string"
12
+ },
13
+ "batting_hand": {
14
+ "anyOf": [
15
+ {
16
+ "enum": [
17
+ "left",
18
+ "right"
19
+ ],
20
+ "type": "string"
21
+ },
22
+ {
23
+ "type": "null"
24
+ }
25
+ ],
26
+ "default": null,
27
+ "title": "Batting Hand"
28
+ },
29
+ "lead_foot": {
30
+ "anyOf": [
31
+ {
32
+ "enum": [
33
+ "left",
34
+ "right"
35
+ ],
36
+ "type": "string"
37
+ },
38
+ {
39
+ "type": "null"
40
+ }
41
+ ],
42
+ "default": null,
43
+ "title": "Lead Foot"
44
+ },
45
+ "age_years": {
46
+ "anyOf": [
47
+ {
48
+ "minimum": 0,
49
+ "type": "integer"
50
+ },
51
+ {
52
+ "type": "null"
53
+ }
54
+ ],
55
+ "default": null,
56
+ "title": "Age Years"
57
+ },
58
+ "height_cm": {
59
+ "anyOf": [
60
+ {
61
+ "exclusiveMinimum": 0,
62
+ "type": "number"
63
+ },
64
+ {
65
+ "type": "null"
66
+ }
67
+ ],
68
+ "default": null,
69
+ "title": "Height Cm"
70
+ }
71
+ },
72
+ "required": [
73
+ "athlete_id"
74
+ ],
75
+ "title": "CoachAthlete",
76
+ "type": "object"
77
+ },
78
+ "CoachContext": {
79
+ "additionalProperties": false,
80
+ "properties": {
81
+ "sport": {
82
+ "const": "baseball",
83
+ "default": "baseball",
84
+ "title": "Sport",
85
+ "type": "string"
86
+ },
87
+ "practice_type": {
88
+ "default": "unknown",
89
+ "enum": [
90
+ "tee",
91
+ "front_toss",
92
+ "side_toss",
93
+ "pitching_machine",
94
+ "live_pitching",
95
+ "game",
96
+ "dry_swing",
97
+ "unknown"
98
+ ],
99
+ "title": "Practice Type",
100
+ "type": "string"
101
+ }
102
+ },
103
+ "title": "CoachContext",
104
+ "type": "object"
105
+ },
106
  "CorrectionSettings": {
107
  "additionalProperties": false,
108
  "properties": {
 
1212
  }
1213
  ],
1214
  "default": null
1215
+ },
1216
+ "athlete": {
1217
+ "anyOf": [
1218
+ {
1219
+ "$ref": "#/$defs/CoachAthlete"
1220
+ },
1221
+ {
1222
+ "type": "null"
1223
+ }
1224
+ ],
1225
+ "default": null
1226
+ },
1227
+ "context": {
1228
+ "$ref": "#/$defs/CoachContext"
1229
+ },
1230
+ "contact_frame": {
1231
+ "anyOf": [
1232
+ {
1233
+ "minimum": 0,
1234
+ "type": "integer"
1235
+ },
1236
+ {
1237
+ "type": "null"
1238
+ }
1239
+ ],
1240
+ "default": null,
1241
+ "title": "Contact Frame"
1242
+ },
1243
+ "swing_id": {
1244
+ "anyOf": [
1245
+ {
1246
+ "maxLength": 180,
1247
+ "minLength": 1,
1248
+ "pattern": "\\S",
1249
+ "type": "string"
1250
+ },
1251
+ {
1252
+ "type": "null"
1253
+ }
1254
+ ],
1255
+ "default": null,
1256
+ "title": "Swing Id"
1257
  }
1258
  },
1259
  "title": "MotionInput",
docs/motion-options.example.json CHANGED
@@ -103,5 +103,12 @@
103
  "maximum_latitude_residual_deg": 5.0,
104
  "minimum_texture_fraction": 0.005
105
  },
106
- "pitcher_floor_points": null
 
 
 
 
 
 
 
107
  }
 
103
  "maximum_latitude_residual_deg": 5.0,
104
  "minimum_texture_fraction": 0.005
105
  },
106
+ "pitcher_floor_points": null,
107
+ "athlete": null,
108
+ "context": {
109
+ "sport": "baseball",
110
+ "practice_type": "unknown"
111
+ },
112
+ "contact_frame": null,
113
+ "swing_id": null
114
  }
tests/test_motion_coach.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract compatibility, exact event sampling and immutable delivery; no model accuracy claim."""
2
+ import json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pytest
6
+ from fastapi.testclient import TestClient
7
+ from ai_coach.swing_report.validation import validate_payload
8
+ from baseball_batting.api import create_app
9
+ from baseball_batting.motion_contract import MotionInput
10
+ from baseball_batting.motion_coach import build_coach_payload
11
+ from baseball_batting.motion_export import export_motion
12
+ from baseball_batting.sam_motion import MHR
13
+ from baseball_batting.storage import atomic_json, sha256_file
14
+ from test_api import settings, fake_service, AUTH
15
+ from test_motion_player import inputs, raw_for
16
+ from baseball_batting.ingest import ingest
17
+ from baseball_batting.geometry import project
18
+ from test_sam_batting import pose
19
+
20
+
21
+ PLAYER = {'athlete_id': 'player-test', 'age_years': 16, 'height_cm': 175.0}
22
+ WINDOW = {'start_frame': 0, 'end_frame': 7, 'baseline_frame': 0,
23
+ 'stride_start_frame': 1, 'landing_frame': 4,
24
+ 'forward_start_frame': 3, 'forward_end_frame': 7}
25
+ LINEAGE = {'analysis_id': 'analysis-test', 'analysis_revision': 1}
26
+
27
+
28
+ def options(**patch):
29
+ base = inputs(annotated_videos=False, athlete=PLAYER, context={'practice_type': 'tee'},
30
+ windows=[WINDOW], contact_frame=6)
31
+ return MotionInput.model_validate({**base.model_dump(mode='json'), **patch})
32
+
33
+
34
+ def motion():
35
+ p = pose(8)
36
+ # Event values are distinct from the maximum; picking the summary would be wrong.
37
+ for i, angle in enumerate([0, 5, 70, 45, 30, 20, 10, 0]):
38
+ q = np.deg2rad(angle)
39
+ p[i, 5] = [-.25*np.cos(q), -.5, -.25*np.sin(q)]
40
+ p[i, 6] = [.25*np.cos(q), -.5, .25*np.sin(q)]
41
+ p[4:, MHR['left_ankle'], 0] -= .2
42
+ p[4:, MHR['left_ankle'], 2] += .1
43
+ return {'points_relative': p, 'valid': np.isfinite(p).all(axis=-1),
44
+ 'boundary': np.zeros((8, 70), bool), 'interpolated': np.zeros((8, 70), bool)}
45
+
46
+
47
+ def payload(opts=None, corrected=None, physical=True):
48
+ video = np.array([0, .03, .07, .10, .15, .19, .22, .27])
49
+ capture = video/4 if physical else np.full(8, np.nan)
50
+ result = build_coach_payload(opts or options(), LINEAGE, corrected or motion(), video, capture, [])
51
+ data = result.model_dump(mode='json')
52
+ parsed, problems = validate_payload(data)
53
+ assert not problems, problems
54
+ assert parsed is not None
55
+ return data
56
+
57
+
58
+ def values(data):
59
+ return {m['metric_id']: m for m in data['measurements']}
60
+
61
+
62
+ def test_exact_selected_frames_relative_stride_and_receiver_contract():
63
+ data = payload()
64
+ rows = values(data)
65
+ assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30
66
+ assert rows['hip_shoulder_separation_at_contact']['value'] == 10
67
+ assert rows['stride_relative_length']['value'] == pytest.approx(22.361)
68
+ assert rows['stride_relative_length']['reasons'] == ['event_timing_uncertain', 'scale_is_model_estimated']
69
+ assert all(m['status'] == 'limited' and m['confidence'] is None and m['benchmark'] is None
70
+ for m in data['measurements'])
71
+ assert data['events']['contact'] == {'video_time_s': .22, 'capture_time_s': .055,
72
+ 'source': 'manual_review', 'status': 'limited', 'reasons': ['event_timing_uncertain']}
73
+ assert data['athlete'] == {**PLAYER, 'batting_hand': 'right', 'lead_foot': 'left'}
74
+ assert data['swing_id'] == LINEAGE['analysis_id'] + ':swing_1'
75
+ # Point-only and interval-only scope fields must be absent, including nulls.
76
+ assert 'start_event_id' not in rows['hip_shoulder_separation_at_contact']
77
+ assert 'event_id' not in rows['stride_relative_length']
78
+
79
+
80
+ def test_player_fields_merge_with_existing_inputs_and_all_old_fields_are_preserved():
81
+ example = json.loads((Path(__file__).parents[1]/'docs/motion-options.example.json').read_text())
82
+ example.update(single_swing=True, athlete={**PLAYER, 'batting_hand': 'left'}, contact_frame=6,
83
+ windows=[WINDOW], pitcher_floor_points={'source_frame_index': 0,
84
+ 'near_batter': [10, 100], 'toward_pitcher': [70, 90]})
85
+ parsed = MotionInput.model_validate(example)
86
+ assert parsed.handedness == 'left'
87
+ dumped = parsed.model_dump(mode='json')
88
+ assert dumped['windows'][0]['baseline_frame'] == 0
89
+ assert dumped['windows'][0]['forward_start_frame'] == 3
90
+ for key in ('gvhmr', 'refinement', 'tracking', 'correction', 'measurement', 'up_estimation', 'pitcher_floor_points'):
91
+ assert all(dumped[key][field] == value for field, value in example[key].items())
92
+ assert MotionInput().athlete is None and MotionInput().contact_frame is None
93
+
94
+
95
+ @pytest.mark.parametrize('patch', [
96
+ {'single_swing': False}, {'contact_frame': -1}, {'contact_frame': True}, {'contact_frame': 1.5},
97
+ {'contact_frame': 3}, {'contact_frame': 8}, {'context': {'practice_type': 'dry_swing'}},
98
+ {'athlete': {**PLAYER, 'age_years': 16.5}}, {'athlete': {**PLAYER, 'age_years': True}},
99
+ {'athlete': {**PLAYER, 'height_cm': -1}}, {'athlete': {**PLAYER, 'height_cm': float('nan')}},
100
+ {'athlete': {'athlete_id': ' '}}, {'athlete': {**PLAYER, 'batting_hand': 'left'}},
101
+ {'lead_foot': 'left', 'athlete': {**PLAYER, 'lead_foot': 'right'}},
102
+ {'windows': [WINDOW, {**WINDOW, 'start_frame': 8, 'end_frame': 15,
103
+ 'baseline_frame': 8, 'stride_start_frame': 9, 'landing_frame': 11,
104
+ 'forward_start_frame': 12, 'forward_end_frame': 15}]},
105
+ ])
106
+ def test_invalid_or_ambiguous_new_inputs_are_rejected(patch):
107
+ with pytest.raises(ValueError):
108
+ options(**patch)
109
+
110
+
111
+ @pytest.mark.parametrize('mode', ['no_contact', 'dry_swing', 'no_stride', 'unknown_clock',
112
+ 'unknown_scale', 'unknown_up', 'moving_camera', 'missing_ankle', 'missing_shoulder'])
113
+ def test_unavailable_dependencies_do_not_invent_or_remove_other_metrics(mode):
114
+ opts = options(); corrected = motion()
115
+ if mode == 'no_contact': opts = options(contact_frame=None)
116
+ if mode == 'dry_swing': opts = options(contact_frame=None, context={'practice_type': 'dry_swing'})
117
+ if mode == 'no_stride': opts = options(windows=[])
118
+ if mode == 'unknown_scale': opts = options(scale_status='unknown')
119
+ if mode == 'unknown_up': opts = options(up_vector=None, up_source=None)
120
+ if mode == 'moving_camera': opts = options(camera_stability='moving')
121
+ if mode in ('missing_ankle', 'missing_shoulder'):
122
+ name = 'left_ankle' if mode == 'missing_ankle' else 'left_shoulder'
123
+ corrected['points_relative'][4, MHR[name]] = np.nan
124
+ corrected['valid'][4, MHR[name]] = False
125
+ data = payload(opts, corrected, physical=mode != 'unknown_clock')
126
+ rows = values(data)
127
+ assert len(rows) == 3
128
+ if mode in ('no_contact', 'dry_swing'):
129
+ reason = 'contact_not_applicable' if mode == 'dry_swing' else 'contact_not_verified'
130
+ assert data['events']['contact']['reasons'] == [reason]
131
+ assert rows['hip_shoulder_separation_at_contact']['value'] is None
132
+ assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30
133
+ if mode in ('no_stride', 'unknown_scale', 'missing_ankle'):
134
+ assert rows['stride_relative_length']['value'] is None
135
+ assert rows['hip_shoulder_separation_at_contact']['value'] == 10
136
+ if mode == 'unknown_clock':
137
+ assert all(e['capture_time_s'] is None for e in data['events'].values())
138
+ assert all(m['value'] is not None for m in rows.values())
139
+ if mode in ('unknown_up', 'moving_camera'):
140
+ assert all(m['value'] is None for m in rows.values())
141
+ if mode == 'missing_shoulder':
142
+ assert rows['hip_shoulder_separation_at_foot_down']['value'] is None
143
+ assert rows['stride_relative_length']['value'] is not None
144
+
145
+
146
+ def test_scaling_handedness_and_interpolation_are_metric_specific():
147
+ data = payload(options(scale_factor=2, scale_source='Known fixture scale', scale_status='calibrated'))
148
+ rows = values(data)
149
+ assert rows['stride_relative_length']['value'] == pytest.approx(44.721)
150
+ assert 'scale_is_model_estimated' not in rows['stride_relative_length']['reasons']
151
+ assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30
152
+ left = payload(options(handedness='left'))
153
+ assert left['athlete']['lead_foot'] == 'right'
154
+ assert values(left)['hip_shoulder_separation_at_foot_down']['value'] == 30
155
+ corrected = motion()
156
+ corrected['interpolated'][4, MHR['right_wrist']] = True
157
+ assert not any(m['uses_interpolated_input'] for m in payload(corrected=corrected)['measurements'])
158
+ corrected['interpolated'][6, MHR['left_shoulder']] = True
159
+ rows = values(payload(corrected=corrected))
160
+ assert rows['hip_shoulder_separation_at_contact']['uses_interpolated_input']
161
+ assert not rows['hip_shoulder_separation_at_foot_down']['uses_interpolated_input']
162
+
163
+
164
+ def test_unknown_lead_foot_and_rounding_at_angle_wrap():
165
+ data = payload(options(handedness=None))
166
+ assert 'lead_foot_unknown' in values(data)['stride_relative_length']['reasons']
167
+ corrected = motion()
168
+ q = np.deg2rad(179.9998)
169
+ corrected['points_relative'][4, 5] = [-.25*np.cos(q), -.5, -.25*np.sin(q)]
170
+ corrected['points_relative'][4, 6] = [.25*np.cos(q), -.5, .25*np.sin(q)]
171
+ assert values(payload(corrected=corrected))['hip_shoulder_separation_at_foot_down']['value'] == -180
172
+
173
+
174
+ def stored(service, video, opts, lineage=None, up_reference=None):
175
+ lineage = lineage or service.store.create_motion(20)
176
+ job = service.job_directory(lineage['job_id']); job.mkdir(exist_ok=True)
177
+ capture = ingest(video, opts.metadata()); raw = raw_for(capture)
178
+ raw['points_body'] = motion()['points_relative']
179
+ raw['projection'] = np.stack([project(p+c, k) for p, c, k in zip(
180
+ raw['points_body'], raw['camera_translation'], raw['intrinsics'])])
181
+ raw['refinement_accepted'] = np.ones(capture['frame_count'], bool)
182
+ if opts.model == 'gvhmr':
183
+ raw['temporal_resampled'] = np.array([False, True, False, True, False, True, True, False])
184
+ manifest = export_motion(job, video, capture, raw, opts, {'name': 'Synthetic fixture, no GPU inference'},
185
+ lineage, up_reference=up_reference)
186
+ atomic_json(job/'request.json', opts.model_dump(mode='json'))
187
+ atomic_json(job/'lineage.json', lineage)
188
+ service.store.update(job.name, 'completed', result_hash=sha256_file(job/'result.json'))
189
+ return job, manifest
190
+
191
+
192
+ @pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
193
+ def test_export_download_revisions_and_integrity_match_motion(tmp_path, video, monkeypatch, model):
194
+ import baseball_batting.motion_api as api
195
+ monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True})
196
+ monkeypatch.setattr(api.gvhmr_runtime, 'configured_record', lambda: {'configured': True})
197
+ service = fake_service(settings(tmp_path)); service.ready = True
198
+ opts = options(model=model, timing={'kind': 'constant_slowdown', 'source': 'Known fixture capture',
199
+ 'factor': 4, 'all_captured_frames_retained': True}, swing_id='swing-test')
200
+ parent, manifest = stored(service, video, opts)
201
+ url = '/v1/motion-analyses/' + parent.name
202
+ # No lifespan: exercise a durable completed result and a revision without GPU dispatch.
203
+ client = TestClient(create_app(service.settings, service))
204
+ assert client.get(url+'/coach-payload').status_code == 401
205
+ response = client.get(url+'/coach-payload', headers=AUTH)
206
+ assert response.status_code == 200, response.text
207
+ assert response.headers['cache-control'] == 'no-store'
208
+ data = response.json(); assert validate_payload(data)[1] == {}
209
+ rows = values(data)
210
+ assert rows['hip_shoulder_separation_at_foot_down']['value'] == 30
211
+ assert rows['hip_shoulder_separation_at_contact']['value'] == 10
212
+ frames = [json.loads(line) for line in (parent/'motion.jsonl').read_text().splitlines()]
213
+ assert data['events']['contact']['capture_time_s'] == frames[6]['capture_time_s']
214
+ assert data['events']['contact']['video_time_s'] == frames[6]['video_time_s']
215
+ assert data['analysis_id'] == manifest.analysis_id and data['analysis_revision'] == 1
216
+ for index, key in ((4, 'hip_shoulder_separation_at_foot_down'), (6, 'hip_shoulder_separation_at_contact')):
217
+ joints = frames[index]['joints']
218
+ hip = np.array(joints['right_hip']['position']) - joints['left_hip']['position']
219
+ shoulder = np.array(joints['right_shoulder']['position']) - joints['left_shoulder']['position']
220
+ signed = (np.rad2deg(np.arctan2(shoulder[1], shoulder[0]) - np.arctan2(hip[1], hip[0])) + 180) % 360 - 180
221
+ assert rows[key]['value'] == pytest.approx(signed, abs=.001)
222
+ artifact = manifest.artifacts['coach_payload']
223
+ assert artifact.url == url+'/coach-payload'
224
+ assert client.get(url+'/artifacts/coach_payload', headers=AUTH).json() == data
225
+ if model == 'gvhmr': assert rows['hip_shoulder_separation_at_contact']['uses_interpolated_input']
226
+ events = json.loads((parent/'events.json').read_text())['events']
227
+ contact = next(e for e in events if e['type'] == 'ball_contact')
228
+ assert contact['source'] == 'manual' and contact['start']['source_frame_index'] == 6
229
+ original = (parent/'coach-payload.json').read_bytes()
230
+ for patch in ({'swing_id': 'different'}, {'athlete': {'athlete_id': 'different'}},
231
+ {'athlete': None}, {'contact_frame': 999}):
232
+ assert client.post(url+'/revisions', headers=AUTH, json={'options': patch}).status_code == 422
233
+ revision = client.post(url+'/revisions', headers=AUTH, json={'options': {'contact_frame': 5}})
234
+ assert revision.status_code == 202, revision.text
235
+ lineage = revision.json()
236
+ assert lineage['coach_payload_url'].endswith('/coach-payload')
237
+ assert client.get(lineage['coach_payload_url'], headers=AUTH).status_code == 409
238
+ child_options = MotionInput.model_validate(json.loads((service.job_directory(lineage['job_id'])/'request.json').read_text()))
239
+ child, child_manifest = stored(service, video, child_options, lineage)
240
+ changed = client.get(lineage['coach_payload_url'], headers=AUTH).json()
241
+ assert validate_payload(changed)[1] == {}
242
+ assert changed['analysis_id'] == data['analysis_id'] and changed['analysis_revision'] == 2
243
+ assert changed['swing_id'] == data['swing_id'] == 'swing-test'
244
+ assert values(changed)['hip_shoulder_separation_at_contact']['value'] == 20
245
+ assert (parent/'coach-payload.json').read_bytes() == original
246
+ assert child_manifest.analysis_revision == 2
247
+ (child/'coach-payload.json').write_text('{}')
248
+ assert client.get(lineage['coach_payload_url'], headers=AUTH).status_code == 500
249
+
250
+
251
+ def test_upload_persists_metadata_and_preserves_existing_request(tmp_path, video, monkeypatch):
252
+ import baseball_batting.motion_api as api
253
+ monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True})
254
+ service = fake_service(settings(tmp_path)); service.ready = True
255
+ client = TestClient(create_app(service.settings, service))
256
+ r = client.post('/v1/motion-analyses', headers=AUTH,
257
+ files={'video': ('swing.mp4', video.read_bytes(), 'video/mp4')},
258
+ data={'options': json.dumps(options().model_dump(mode='json'))})
259
+ assert r.status_code == 202, r.text
260
+ saved = json.loads((service.job_directory(r.json()['job_id'])/'request.json').read_text())
261
+ assert saved['athlete'] == options().athlete.model_dump(mode='json')
262
+ assert saved['contact_frame'] == 6 and saved['windows'][0]['landing_frame'] == 4
263
+ assert saved['refinement']['enabled'] and saved['up_vector'] == [0, -1, 0]
264
+ assert client.delete(r.json()['status_url'], headers=AUTH).status_code == 202
265
+ # Older callers do not need new fields and still get motion artifacts normally.
266
+ job, manifest = stored(service, video, options(athlete=None, contact_frame=None))
267
+ assert 'coach_payload' not in manifest.artifacts
268
+ assert client.get(f'/v1/motion-analyses/{job.name}/coach-payload', headers=AUTH).status_code == 409
269
+
270
+
271
+ def test_contact_frame_bounds_checked_before_gpu_inference(tmp_path, video, monkeypatch):
272
+ import baseball_batting.motion_worker as worker
273
+ opts = options(windows=[], contact_frame=999)
274
+ job = tmp_path/'job'; job.mkdir()
275
+ (job/'input.mp4').write_bytes(video.read_bytes())
276
+ atomic_json(job/'request.json', opts.model_dump(mode='json'))
277
+ atomic_json(job/'lineage.json', LINEAGE)
278
+ def unexpected(*args, **kwargs):
279
+ pytest.fail('GPU inference must not run for an out-of-range contact frame')
280
+ monkeypatch.setattr(worker, 'reconstruct_sam', unexpected)
281
+ with pytest.raises(ValueError, match='contact_frame_out_of_range'):
282
+ worker.run(job, tmp_path/'models')
283
+
284
+
285
+ def test_published_schemas_and_example_agree_with_receiver():
286
+ import jsonschema
287
+ from baseball_batting.motion_coach_contract import MotionCoachPayload
288
+ docs = Path(__file__).parents[1]/'docs'
289
+ schema = json.loads((docs/'motion-coach-payload.schema.json').read_text())
290
+ assert schema == MotionCoachPayload.model_json_schema()
291
+ example = json.loads((docs/'motion-coach-payload.example.json').read_text())
292
+ jsonschema.Draft202012Validator.check_schema(schema)
293
+ jsonschema.validate(example, schema)
294
+ assert validate_payload(example)[1] == {}
295
+ assert json.loads((docs/'motion-input.schema.json').read_text()) == MotionInput.model_json_schema()
296
+
297
+
298
+ @pytest.mark.parametrize('reliable', [True, False])
299
+ def test_estimated_up_is_used_only_when_accepted_for_measurements(tmp_path, video, reliable):
300
+ from baseball_batting.camera_up import reference
301
+ opts = options(up_vector=None, up_source=None)
302
+ up = {**reference(opts), 'status': 'estimated', 'reliable': reliable,
303
+ 'up_vector': [0, -1, 0], 'up_source': 'GeoCalib consensus fixture'}
304
+ job, manifest = stored(fake_service(settings(tmp_path)), video, opts, up_reference=up)
305
+ data = json.loads((job/'coach-payload.json').read_text())
306
+ assert validate_payload(data)[1] == {}
307
+ assert all((m['value'] is not None) == reliable for m in data['measurements'])
308
+ assert manifest.pipeline['inputs']['up_vector'] is None
309
+ assert manifest.pipeline['calculation_inputs']['up_vector'] == ([0, -1, 0] if reliable else None)
310
+
311
+
312
+ @pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
313
+ def test_contact_revision_reuses_native_inference_and_keeps_default_swing_identity(tmp_path, video, monkeypatch, model):
314
+ import baseball_batting.motion_api as api
315
+ import baseball_batting.motion_worker as worker
316
+ from test_gvhmr_motion import native_fixture
317
+ from baseball_batting.api_jobs import JobService
318
+ monkeypatch.setattr(api, 'configured_record', lambda: {'configured': True})
319
+ monkeypatch.setattr(api.gvhmr_runtime, 'configured_record', lambda: {'configured': True})
320
+ calls = []
321
+ def infer(job, source, capture, *args, **kwargs):
322
+ calls.append(model)
323
+ raw = raw_for(capture) if model == 'sam3d' else native_fixture(capture)[0]
324
+ stem = 'sam' if model == 'sam3d' else 'gvhmr'
325
+ np.savez_compressed(job/(stem+'-raw-private.npz'), **raw)
326
+ atomic_json(job/(stem+'-raw-private.json'), {'model': {'name': model+' fixture'}})
327
+ atomic_json(job/'person-track-private.json', {'reasons': [None]*capture['frame_count']})
328
+ return raw, {'name': model+' fixture'}
329
+ monkeypatch.setattr(worker, 'reconstruct_sam' if model == 'sam3d' else 'reconstruct_gvhmr', infer)
330
+ service = JobService(settings(tmp_path)); service.ready = True
331
+ lineage = service.store.create_motion(20)
332
+ parent = service.job_directory(lineage['job_id']); parent.mkdir()
333
+ (parent/'input.mp4').write_bytes(video.read_bytes())
334
+ opts = options(model=model, refinement={'enabled': False})
335
+ atomic_json(parent/'request.json', opts.model_dump(mode='json'))
336
+ atomic_json(parent/'lineage.json', lineage)
337
+ worker.run(parent, tmp_path/'models')
338
+ service.store.update(parent.name, 'completed', result_hash=sha256_file(parent/'result.json'))
339
+ original = json.loads((parent/'coach-payload.json').read_text())
340
+ client = TestClient(create_app(service.settings, service))
341
+ response = client.post('/v1/motion-analyses/'+parent.name+'/revisions', headers=AUTH,
342
+ json={'options': {'contact_frame': 5, 'athlete': {'age_years': 17}}})
343
+ assert response.status_code == 202, response.text
344
+ child = service.job_directory(response.json()['job_id'])
345
+ assert (child/'reused-inference.json').is_file()
346
+ worker.run(child, tmp_path/'models')
347
+ updated = json.loads((child/'coach-payload.json').read_text())
348
+ assert validate_payload(updated)[1] == {}
349
+ assert calls == [model]
350
+ assert updated['swing_id'] == original['swing_id'] == lineage['analysis_id']+':swing_1'
351
+ assert updated['analysis_revision'] == 2 and original['analysis_revision'] == 1
352
+ assert updated['athlete']['age_years'] == 17
353
+ assert original['athlete']['age_years'] == 16