github-actions[bot] commited on
Commit
6b95c6c
·
1 Parent(s): ebede04

Automated Deploy: e8f9b601dd5464c98dfeaaab4cccd6af68ee2d82

Browse files
.dockerignore CHANGED
@@ -24,6 +24,7 @@
24
  !tools/
25
  !tools/setup_api_models.py
26
  !tools/setup_tracking_models.py
 
27
  !tools/setup_full_worker.py
28
  !tools/setup_sam_api_worker.py
29
  !tools/register_sam_api_worker.py
 
24
  !tools/
25
  !tools/setup_api_models.py
26
  !tools/setup_tracking_models.py
27
+ !tools/setup_camera_up.py
28
  !tools/setup_full_worker.py
29
  !tools/setup_sam_api_worker.py
30
  !tools/register_sam_api_worker.py
Dockerfile CHANGED
@@ -26,6 +26,14 @@ RUN python -m venv /opt/sam-runtime \
26
  && git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
27
 
28
 
 
 
 
 
 
 
 
 
29
  FROM python:3.11-slim-bookworm
30
 
31
  ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
@@ -33,7 +41,7 @@ ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
33
  NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility \
34
  BASEBALL_SAM_WORKER_RECORD=/data/sam-api-worker.json BASEBALL_SAM_SOURCE=/opt/sam-source \
35
  BASEBALL_GVHMR_WORKER_RECORD=/data/gvhmr-api-worker.json BASEBALL_GVHMR_SOURCE=/data/gvhmr-source \
36
- HF_HUB_DOWNLOAD_TIMEOUT=60
37
  WORKDIR /app
38
  RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini git libgl1 libegl1 libglib2.0-0 \
39
  && rm -rf /var/lib/apt/lists/*
@@ -51,7 +59,8 @@ COPY tools/setup_api_models.py tools/setup_full_worker.py tools/setup_sam_api_wo
51
  COPY tools/__init__.py ./tools/__init__.py
52
  COPY tools/prepare_sam_assets.py tools/start_api.py ./tools/
53
  COPY tools/prepare_gvhmr_assets.py tools/register_gvhmr_api_worker.py tools/check_gvhmr_runtime.py tools/setup_gvhmr_api_worker.py ./tools/
54
- COPY --from=sam-runtime /opt/sam-runtime /opt/sam-runtime
 
55
  COPY --chown=1000:1000 --from=sam-runtime /opt/sam-source /opt/sam-source
56
  COPY docs/api-result.schema.json ./docs/api-result.schema.json
57
  COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
 
26
  && git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
27
 
28
 
29
+ FROM sam-runtime AS camera-runtime
30
+ RUN /opt/sam-runtime/bin/python -m pip install --no-cache-dir --no-deps \
31
+ kornia==0.8.2 kornia-rs==0.1.10 \
32
+ git+https://github.com/cvg/GeoCalib.git@1dedb29f94fc11b896c5f572005978aeebccd67f
33
+ COPY baseball_batting/__init__.py baseball_batting/camera_up_provider.py ./baseball_batting/
34
+ COPY tools/__init__.py tools/setup_camera_up.py ./tools/
35
+ RUN /opt/sam-runtime/bin/python -m tools.setup_camera_up --output /opt/models/camera_up
36
+
37
  FROM python:3.11-slim-bookworm
38
 
39
  ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
 
41
  NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility \
42
  BASEBALL_SAM_WORKER_RECORD=/data/sam-api-worker.json BASEBALL_SAM_SOURCE=/opt/sam-source \
43
  BASEBALL_GVHMR_WORKER_RECORD=/data/gvhmr-api-worker.json BASEBALL_GVHMR_SOURCE=/data/gvhmr-source \
44
+ HF_HUB_DOWNLOAD_TIMEOUT=60 BASEBALL_CAMERA_UP_RECORD=/opt/models/camera_up/provider.json
45
  WORKDIR /app
46
  RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini git libgl1 libegl1 libglib2.0-0 \
47
  && rm -rf /var/lib/apt/lists/*
 
59
  COPY tools/__init__.py ./tools/__init__.py
60
  COPY tools/prepare_sam_assets.py tools/start_api.py ./tools/
61
  COPY tools/prepare_gvhmr_assets.py tools/register_gvhmr_api_worker.py tools/check_gvhmr_runtime.py tools/setup_gvhmr_api_worker.py ./tools/
62
+ COPY --from=camera-runtime /opt/sam-runtime /opt/sam-runtime
63
+ COPY --from=camera-runtime /opt/models/camera_up /opt/models/camera_up
64
  COPY --chown=1000:1000 --from=sam-runtime /opt/sam-source /opt/sam-source
65
  COPY docs/api-result.schema.json ./docs/api-result.schema.json
66
  COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
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.12.2", 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.13.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/camera_up.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Conservative camera-up consensus and isolated image-provider invocation."""
2
+ import math
3
+ import os
4
+ from pathlib import Path
5
+ import subprocess
6
+ import numpy as np
7
+ from .camera_up_provider import REVISION, WEIGHTS_SHA256, METHOD, CAMERA_FRAME
8
+ from .storage import atomic_json, read_json, sha256_file, digest
9
+
10
+
11
+ def implementation_hash():
12
+ return digest({n:sha256_file(Path(__file__).with_name(n)) for n in
13
+ ('camera_up.py','camera_up_worker.py','camera_up_provider.py')})
14
+
15
+
16
+ def configured_record(models=None):
17
+ path=Path(os.environ.get('BASEBALL_CAMERA_UP_RECORD',str(Path(models or '/opt/models')/'camera_up/provider.json')))
18
+ try:
19
+ data=read_json(path)
20
+ if (data['source_revision']==REVISION and data['weights_sha256']==WEIGHTS_SHA256
21
+ and Path(data['worker_python']).is_file() and Path(data['weights']).is_file()):return data
22
+ except (OSError,ValueError,KeyError,TypeError):pass
23
+ return None
24
+
25
+
26
+ def public_status(models=None):
27
+ return {'configured':configured_record(models) is not None,'method':METHOD,
28
+ 'automatic_when_missing':True,'coordinate_frame':CAMERA_FRAME,'accuracy_validated':False}
29
+
30
+
31
+ def reference(options,reason='not_estimated'):
32
+ supplied=options.up_vector is not None
33
+ return {'status':'provided' if supplied else 'unknown','up_vector':list(options.up_vector) if supplied else None,
34
+ 'up_source':options.up_source if supplied else None,'coordinate_frame':CAMERA_FRAME,
35
+ 'method':'caller_supplied' if supplied else METHOD,'applied':supplied,
36
+ 'reliable':None if supplied else False,'confidence':None,'accuracy_validated':False,
37
+ 'reason_code':'caller_input_not_independently_verified' if supplied else reason,
38
+ 'reliability_kind':'engineering_image_and_temporal_checks; not calibrated accuracy or probability'}
39
+
40
+
41
+ def sample_indices(capture,count):
42
+ times=np.array([f['playback_s'] for f in capture['frames']],float)
43
+ if not len(times) or not np.isfinite(times).all() or np.any(np.diff(times)<=0):return []
44
+ targets=np.linspace(times[0],times[-1],min(count,len(times)))
45
+ return sorted({int(np.argmin(np.abs(times-t))) for t in targets})
46
+
47
+
48
+ def frame_reasons(row,settings):
49
+ if row.get('reason_code'):return [row['reason_code']]
50
+ reasons=[]
51
+ v=np.asarray(row.get('up_vector',[]),float)
52
+ if v.shape!=(3,) or not np.isfinite(v).all() or np.linalg.norm(v)<1e-8:reasons.append('invalid_camera_up_vector')
53
+ checks=(('gravity_uncertainty_deg',settings.maximum_gravity_uncertainty_deg,'high_gravity_uncertainty'),
54
+ ('up_residual_deg',settings.maximum_up_residual_deg,'up_field_disagreement'),
55
+ ('latitude_residual_deg',settings.maximum_latitude_residual_deg,'latitude_field_disagreement'))
56
+ for name,limit,reason in checks:
57
+ value=row.get(name)
58
+ if value is None or not math.isfinite(value) or value<0 or value>limit:reasons.append(reason)
59
+ if row.get('covariance_valid') is not True:reasons.append('invalid_gravity_covariance')
60
+ if not row.get('gravity_uncertainty_deg',0)>0:reasons.append('zero_gravity_uncertainty')
61
+ minimums=(('background_fraction',settings.minimum_background_fraction),
62
+ ('up_effective_pixels',settings.minimum_effective_pixels),
63
+ ('latitude_effective_pixels',settings.minimum_effective_pixels),
64
+ ('up_spatial_cells',settings.minimum_spatial_cells),
65
+ ('latitude_spatial_cells',settings.minimum_spatial_cells),
66
+ ('texture_fraction',settings.minimum_texture_fraction))
67
+ for name,limit in minimums:
68
+ value=row.get(name)
69
+ if value is None or not math.isfinite(value) or value<limit:reasons.append('insufficient_'+name)
70
+ return reasons
71
+
72
+
73
+ def consensus(rows,capture,options):
74
+ settings=options.up_estimation;out=reference(options,'insufficient_reliable_frames')
75
+ out.update(settings=settings.model_dump(),sampled_frame_count=len(rows),accepted_frame_count=0,
76
+ sampled_frame_ids=[r['source_frame_index'] for r in rows],frames=rows)
77
+ credible=[];seen=set()
78
+ for row in rows:
79
+ row['reasons']=frame_reasons(row,settings)
80
+ image_hash=row.get('image_sha256')
81
+ if not image_hash or image_hash in seen:row['reasons'].append('duplicate_or_missing_image_evidence')
82
+ seen.add(image_hash)
83
+ if not row['reasons']:credible.append(row)
84
+ if len(credible)<settings.minimum_frames:return out
85
+ vectors=np.array([r['up_vector'] for r in credible],float)
86
+ vectors/=np.linalg.norm(vectors,axis=1,keepdims=True)
87
+ angles=np.degrees(np.arccos(np.clip(vectors@vectors.T,-1,1)))
88
+ members=angles<=settings.maximum_frame_deviation_deg
89
+ # A spherical medoid preserves sign; opposite directions never cancel into
90
+ # a plausible average. Do not flip predictions to force agreement.
91
+ best=int(np.argmax(members.sum(1)));take=members[best]
92
+ if take.sum()<max(settings.minimum_frames,math.ceil(settings.minimum_consensus_fraction*len(credible))):
93
+ out['reason_code']='inconsistent_camera_up_across_frames';return out
94
+ vector=np.mean(vectors[take],axis=0);vector/=np.linalg.norm(vector)
95
+ deviation=np.degrees(np.arccos(np.clip(vectors@vector,-1,1)))
96
+ if np.max(deviation[take])>settings.maximum_frame_deviation_deg:
97
+ out['reason_code']='inconsistent_camera_up_across_frames';return out
98
+ accepted=[r for r,good in zip(credible,take) if good]
99
+ times=[r['playback_s'] for r in capture['frames']];duration=times[-1]-times[0]
100
+ coverage=(max(r['video_time_s'] for r in accepted)-min(r['video_time_s'] for r in accepted))/duration if duration>0 else 0
101
+ out.update(temporal_coverage_fraction=float(coverage),maximum_deviation_deg=float(np.max(deviation[take])),
102
+ accepted_frame_count=len(accepted),accepted_frame_ids=[r['source_frame_index'] for r in accepted],
103
+ maximum_model_uncertainty_deg=max(r['gravity_uncertainty_deg'] for r in accepted))
104
+ if coverage<settings.minimum_temporal_coverage:
105
+ out['reason_code']='insufficient_camera_up_temporal_coverage';return out
106
+ source='GeoCalib pinhole image calibration; multi-frame camera-up consensus (estimated)'
107
+ out.update(status='estimated',up_vector=vector.tolist(),up_source=source,applied=True,reliable=True,reason_code=None)
108
+ return out
109
+
110
+
111
+ def estimate(job,video,capture,models,options,track,progress):
112
+ if options.up_vector is not None:return reference(options)
113
+ if not options.up_estimation.enabled:return reference(options,'automatic_up_estimation_disabled')
114
+ provider=configured_record(models)
115
+ if provider is None:return reference(options,'camera_up_provider_unavailable')
116
+ job=Path(job);indices=sample_indices(capture,options.up_estimation.sample_count)
117
+ if len(indices)<options.up_estimation.minimum_frames:return reference(options,'insufficient_source_frames_for_camera_up')
118
+ request={'video':str(Path(video).resolve()),'rotation':capture['rotation_degrees'],
119
+ 'frames':[{'source_frame_index':i,'video_time_s':capture['frames'][i]['playback_s']-capture['frames'][0]['playback_s'],
120
+ 'box':track.get('boxes',[None]*capture['frame_count'])[i],
121
+ 'tracking_reason':track['reasons'][i]} for i in indices],
122
+ 'camera':options.camera.model_dump() if options.camera else None,
123
+ 'weights':provider['weights'],'output':str((job/'camera-up-predictions-private.json').resolve())}
124
+ path=job/'camera-up-request-private.json';atomic_json(path,request)
125
+ env=dict(os.environ,MPLBACKEND='Agg',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
126
+ for key in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(key,None)
127
+ progress('camera_up_estimation',0,len(indices))
128
+ try:
129
+ with (job/'camera-up-worker-private.log').open('wb') as log:
130
+ subprocess.run([provider['worker_python'],'-m','baseball_batting.camera_up_worker','--request',str(path.resolve())],
131
+ env=env,stdout=log,stderr=subprocess.STDOUT,check=True,timeout=180)
132
+ rows=read_json(request['output'])['frames']
133
+ # Provider provenance is verified locally, never taken from video metadata.
134
+ out=consensus(rows,capture,options)
135
+ out.update(provider_revision=REVISION,weights_sha256=provider['weights_sha256'],
136
+ implementation_sha256=implementation_hash(),inference_seed=0,
137
+ camera_intrinsics_policy='calibration nuisance only; body-model intrinsics unchanged')
138
+ except (OSError,ValueError,KeyError,subprocess.SubprocessError) as error:
139
+ out=reference(options,'camera_up_estimation_failed');out['error_type']=type(error).__name__
140
+ atomic_json(job/'camera-up-private.json',out)
141
+ progress('camera_up_estimation',len(indices),len(indices))
142
+ return out
baseball_batting/camera_up_provider.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Pinned official GeoCalib inference provider; no credentials or body-model assets."""
2
+ REVISION = '1dedb29f94fc11b896c5f572005978aeebccd67f'
3
+ WEIGHTS_URL = 'https://github.com/cvg/GeoCalib/releases/download/v1.0/geocalib-pinhole.tar'
4
+ WEIGHTS_SHA256 = '86d6aeacd8bbd974c59ce39f61854e00d36911c732ad89be471476fd708722ac'
5
+ METHOD = 'geocalib_multiframe_camera_up_v1'
6
+ CAMERA_FRAME = 'upright_camera_x_right_y_down_z_away'
baseball_batting/camera_up_worker.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline GeoCalib image inference in the existing isolated Torch runtime."""
2
+ import argparse
3
+ import hashlib
4
+ import numpy as np
5
+ from .camera_up_provider import WEIGHTS_SHA256
6
+ from .ingest import iter_frames
7
+ from .storage import atomic_json, read_json, sha256_file
8
+
9
+
10
+ def prepare_image(image,box,camera,max_side=960):
11
+ """Rectify known intrinsics without rotating the optical/camera basis."""
12
+ import cv2
13
+ h,w=image.shape[:2];mask=np.ones((h,w),np.uint8)
14
+ x1,y1,x2,y2=box;pad=.1*max(x2-x1,y2-y1)
15
+ cv2.rectangle(mask,(max(0,int(x1-pad)),max(0,int(y1-pad))),
16
+ (min(w-1,int(x2+pad)),min(h-1,int(y2+pad))),0,-1)
17
+ valid=np.ones((h,w),np.uint8);focal=None
18
+ if camera:
19
+ k=np.array([[camera['fx'],0,camera['cx']],[0,camera['fy'],camera['cy']],[0,0,1]],float)
20
+ focal=float(np.sqrt(camera['fx']*camera['fy']))
21
+ virtual=np.array([[focal,0,w/2],[0,focal,h/2],[0,0,1]],float)
22
+ distortion=np.array(camera.get('distortion') or [0]*5,float)
23
+ mx,my=cv2.initUndistortRectifyMap(k,distortion,np.eye(3),virtual,(w,h),cv2.CV_32FC1)
24
+ valid=((mx>=0)&(mx<w-1)&(my>=0)&(my<h-1)).astype(np.uint8)
25
+ image=cv2.remap(image,mx,my,cv2.INTER_LINEAR)
26
+ mask=cv2.remap(mask,mx,my,cv2.INTER_NEAREST)*valid
27
+ scale=min(1.,max_side/max(h,w));size=(round(w*scale),round(h*scale))
28
+ image=cv2.resize(image,size,interpolation=cv2.INTER_AREA)
29
+ mask=cv2.resize(mask,size,interpolation=cv2.INTER_NEAREST).astype(bool)
30
+ valid=cv2.resize(valid,size,interpolation=cv2.INTER_NEAREST).astype(bool)
31
+ return image,mask,valid,None if focal is None else focal*scale
32
+
33
+
34
+ def weighted_diagnostics(error,weights,mask):
35
+ weights=np.where(mask&np.isfinite(error)&np.isfinite(weights),np.maximum(weights,0),0).astype(float)
36
+ total=weights.sum()
37
+ if not total>0:return None,0.,0
38
+ effective=float(total*total/np.sum(weights*weights))
39
+ # Learned confidence magnitudes differ between heads. Treat them as relative
40
+ # weights, not probability thresholds or calibrated visibility labels.
41
+ cells=0;h,w=mask.shape
42
+ for row in range(3):
43
+ for col in range(3):
44
+ mass=weights[row*h//3:(row+1)*h//3,col*w//3:(col+1)*w//3].sum()
45
+ cells+=int(mass>=.05*total)
46
+ return float(np.sum(error[weights>0]*weights[weights>0])/total),effective,cells
47
+
48
+
49
+ def diagnostics(result,image,mask,valid):
50
+ import cv2
51
+ def array(value):return value.detach().cpu().numpy()
52
+ vector=array(result['gravity'].vec3d)[0].astype(float)
53
+ # GeoCalib Gravity.from_rp(0,0) == [0,-1,0]: it is already
54
+ # camera-up in our x-right/y-down/z-away basis. No negation/axis swap.
55
+ vector/=np.linalg.norm(vector)
56
+ covariance=array(result['covariance'])[0,:2,:2].astype(float)
57
+ covariance_valid=bool(np.isfinite(covariance).all() and np.allclose(covariance,covariance.T,rtol=1e-3,atol=1e-7)
58
+ and np.linalg.eigvalsh((covariance+covariance.T)/2).min()>0)
59
+ uncertainty=float(np.degrees(array(result['gravity_uncertainty']).reshape(-1)[0]))
60
+ k=array(result['camera'].K)[0]
61
+ h,w=image.shape[:2];ratio=min(1.,320/max(h,w));size=(round(w*ratio),round(h*ratio))
62
+ mask=cv2.resize(mask.astype(np.uint8),size,interpolation=cv2.INTER_NEAREST).astype(bool)
63
+ valid=cv2.resize(valid.astype(np.uint8),size,interpolation=cv2.INTER_NEAREST).astype(bool)
64
+ rgb=cv2.resize(image,size,interpolation=cv2.INTER_AREA)
65
+ gray=cv2.cvtColor(rgb,cv2.COLOR_BGR2GRAY).astype(float)/255
66
+ gx=cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=3);gy=cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=3)
67
+ texture=float(np.mean(np.hypot(gx,gy)[mask]>.04)) if mask.any() else 0.
68
+ yy,xx=np.mgrid[:size[1],:size[0]]
69
+ rays2=np.stack([(xx/ratio-k[0,2])/k[0,0],(yy/ratio-k[1,2])/k[1,1]],-1)
70
+ predicted=vector[:2]-vector[2]*rays2
71
+ predicted/=np.maximum(np.linalg.norm(predicted,axis=-1,keepdims=True),1e-10)
72
+ observed=cv2.resize(array(result['up_field'])[0].transpose(1,2,0),size,interpolation=cv2.INTER_AREA)
73
+ observed/=np.maximum(np.linalg.norm(observed,axis=-1,keepdims=True),1e-10)
74
+ up_error=np.degrees(np.arccos(np.clip(np.sum(observed*predicted,axis=-1),-1,1)))
75
+ rays=np.concatenate([rays2,np.ones((*rays2.shape[:2],1))],-1);rays/=np.linalg.norm(rays,axis=-1,keepdims=True)
76
+ expected_latitude=np.arcsin(np.clip(rays@vector,-1+1e-6,1-1e-6))
77
+ latitude=cv2.resize(array(result['latitude_field'])[0,0],size,interpolation=cv2.INTER_AREA)
78
+ lat_error=np.degrees(np.abs(latitude-expected_latitude))
79
+ up_weight=cv2.resize(array(result['up_confidence'])[0],size,interpolation=cv2.INTER_AREA)
80
+ lat_weight=cv2.resize(array(result['latitude_confidence'])[0],size,interpolation=cv2.INTER_AREA)
81
+ up_residual,up_effective,up_cells=weighted_diagnostics(up_error,up_weight,mask)
82
+ lat_residual,lat_effective,lat_cells=weighted_diagnostics(lat_error,lat_weight,mask)
83
+ return {'up_vector':vector.tolist(),'gravity_uncertainty_deg':uncertainty,'covariance_valid':covariance_valid,
84
+ 'background_fraction':float(mask.mean()),'valid_rectification_fraction':float(valid.mean()),
85
+ 'texture_fraction':texture,'up_residual_deg':up_residual,'latitude_residual_deg':lat_residual,
86
+ 'up_effective_pixels':up_effective,'latitude_effective_pixels':lat_effective,
87
+ 'up_spatial_cells':up_cells,'latitude_spatial_cells':lat_cells}
88
+
89
+
90
+ def run(request,device='cuda'):
91
+ import torch
92
+ from geocalib import GeoCalib
93
+ if device=='cuda' and not torch.cuda.is_available():raise RuntimeError('Camera-up inference requires CUDA')
94
+ if sha256_file(request['weights'])!=WEIGHTS_SHA256:raise ValueError('Camera-up weights checksum differs')
95
+ torch.set_num_threads(2)
96
+ torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
97
+ model=GeoCalib(weights=request['weights']).eval().to(device)
98
+ frames={r['source_frame_index']:r for r in request['frames']};rows=[]
99
+ for i,_,_,image in iter_frames(request['video'],request['rotation']):
100
+ if i not in frames:continue
101
+ row=frames[i];base={'source_frame_index':i,'video_time_s':row['video_time_s'],
102
+ 'image_sha256':hashlib.sha256(image.tobytes()).hexdigest()}
103
+ if row['box'] is None or row['tracking_reason'] is not None:
104
+ rows.append({**base,'reason_code':'athlete_background_mask_unavailable'});continue
105
+ try:
106
+ prepared,mask,valid,focal=prepare_image(image,row['box'],request['camera'])
107
+ tensor=torch.from_numpy(prepared[:,:,::-1].copy()).permute(2,0,1).float().to(device)/255
108
+ priors={'focal':tensor.new_tensor(focal)} if focal is not None else None
109
+ # Fix the NMF decoder's random bases per frame for reproducibility.
110
+ torch.manual_seed(0)
111
+ result=model.calibrate(tensor,camera_model='pinhole',priors=priors)
112
+ item=diagnostics(result,prepared,mask,valid)
113
+ if item['valid_rectification_fraction']<.9:item['reason_code']='insufficient_valid_rectified_image'
114
+ rows.append({**base,**item})
115
+ del result,tensor
116
+ except (RuntimeError,ValueError,KeyError,np.linalg.LinAlgError) as error:
117
+ rows.append({**base,'reason_code':'frame_calibration_failed','error_type':type(error).__name__})
118
+ if i==max(frames):break
119
+ atomic_json(request['output'],{'frames':rows})
120
+
121
+
122
+ def main():
123
+ p=argparse.ArgumentParser();p.add_argument('--request',required=True);args=p.parse_args()
124
+ try:run(read_json(args.request));return 0
125
+ except Exception as error:print('Camera-up inference failed: '+type(error).__name__,flush=True);return 1
126
+
127
+
128
+ if __name__=='__main__':raise SystemExit(main())
baseball_batting/motion_api.py CHANGED
@@ -85,6 +85,7 @@ def register(app,service,authenticated):
85
 
86
  @app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
87
  def capabilities():
 
88
  models=[{**{k:descriptor(key)[k] for k in ('id','name','adapter_version','definition_version','source_schema')},
89
  **(public_status() if key=='sam3d' else gvhmr_runtime.public_status())} for key in ('sam3d','gvhmr')]
90
  return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
@@ -96,6 +97,7 @@ def register(app,service,authenticated):
96
  'whole_body_refinement':True,'refinement_default_enabled':True,
97
  'refinement_observations':'RTMW image landmarks and forward/backward optical flow; soft constraints',
98
  'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
 
99
  'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
100
  'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
101
  'output_schema_url':PREFIX+'/output-schema'}
 
85
 
86
  @app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
87
  def capabilities():
88
+ from .camera_up import public_status as camera_up_status
89
  models=[{**{k:descriptor(key)[k] for k in ('id','name','adapter_version','definition_version','source_schema')},
90
  **(public_status() if key=='sam3d' else gvhmr_runtime.public_status())} for key in ('sam3d','gvhmr')]
91
  return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
 
97
  'whole_body_refinement':True,'refinement_default_enabled':True,
98
  'refinement_observations':'RTMW image landmarks and forward/backward optical flow; soft constraints',
99
  'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
100
+ 'automatic_camera_up':camera_up_status(settings.model_root),
101
  'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
102
  'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
103
  'output_schema_url':PREFIX+'/output-schema'}
baseball_batting/motion_contract.py CHANGED
@@ -15,6 +15,28 @@ class MotionCamera(CameraInput):
15
  distortion: tuple[float, float, float, float, float] | None = None
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  class RefinementSettings(Strict):
19
  enabled: bool = True
20
  native_batch_frames: int = Field(default=8, ge=1, le=16, strict=True)
@@ -67,6 +89,7 @@ class GVHMRSettings(Strict):
67
 
68
 
69
  class MotionInput(SamBattingInput):
 
70
  model: Literal['sam3d', 'gvhmr'] = 'sam3d'
71
  gvhmr: GVHMRSettings = Field(default_factory=GVHMRSettings)
72
  coaching: Literal[False] = False
@@ -79,6 +102,7 @@ class MotionInput(SamBattingInput):
79
  camera: MotionCamera | None = None
80
  refinement: RefinementSettings = Field(default_factory=RefinementSettings)
81
  tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
 
82
 
83
  @model_validator(mode='after')
84
  def scale_evidence(self):
@@ -89,6 +113,9 @@ class MotionInput(SamBattingInput):
89
  def sam_options(self):
90
  data={k:v for k,v in self.model_dump().items() if k in SamBattingInput.model_fields}
91
  if data.get('camera'):data['camera'].pop('distortion',None)
 
 
 
92
  return SamBattingInput.model_validate(data)
93
 
94
 
 
15
  distortion: tuple[float, float, float, float, float] | None = None
16
 
17
 
18
+ class UpEstimationSettings(Strict):
19
+ enabled: bool = True
20
+ sample_count: int = Field(default=7, ge=3, le=15, strict=True)
21
+ minimum_frames: int = Field(default=3, ge=3, le=15, strict=True)
22
+ maximum_gravity_uncertainty_deg: float = Field(default=5., gt=0, le=15)
23
+ maximum_frame_deviation_deg: float = Field(default=3., gt=0, le=10)
24
+ minimum_consensus_fraction: float = Field(default=.8, ge=.6, le=1)
25
+ minimum_temporal_coverage: float = Field(default=.75, ge=.5, le=1)
26
+ minimum_background_fraction: float = Field(default=.2, ge=.1, le=.8)
27
+ minimum_effective_pixels: int = Field(default=32, ge=16, le=1000, strict=True)
28
+ minimum_spatial_cells: int = Field(default=3, ge=2, le=9, strict=True)
29
+ maximum_up_residual_deg: float = Field(default=10., gt=0, le=20)
30
+ maximum_latitude_residual_deg: float = Field(default=5., gt=0, le=15)
31
+ minimum_texture_fraction: float = Field(default=.005, gt=0, le=.1)
32
+
33
+ @model_validator(mode='after')
34
+ def enough_samples(self):
35
+ if self.minimum_frames > self.sample_count:
36
+ raise ValueError('Up estimation minimum_frames exceeds sample_count')
37
+ return self
38
+
39
+
40
  class RefinementSettings(Strict):
41
  enabled: bool = True
42
  native_batch_frames: int = Field(default=8, ge=1, le=16, strict=True)
 
89
 
90
 
91
  class MotionInput(SamBattingInput):
92
+ requires_vertical_for_pitcher = False
93
  model: Literal['sam3d', 'gvhmr'] = 'sam3d'
94
  gvhmr: GVHMRSettings = Field(default_factory=GVHMRSettings)
95
  coaching: Literal[False] = False
 
102
  camera: MotionCamera | None = None
103
  refinement: RefinementSettings = Field(default_factory=RefinementSettings)
104
  tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
105
+ up_estimation: UpEstimationSettings = Field(default_factory=UpEstimationSettings)
106
 
107
  @model_validator(mode='after')
108
  def scale_evidence(self):
 
113
  def sam_options(self):
114
  data={k:v for k,v in self.model_dump().items() if k in SamBattingInput.model_fields}
115
  if data.get('camera'):data['camera'].pop('distortion',None)
116
+ # These axes are measurement inputs, unused by native reconstruction.
117
+ # Keep the original direction in MotionInput until camera-up is resolved.
118
+ if data['up_vector'] is None:data.update(pitcher_vector=None,pitcher_source=None)
119
  return SamBattingInput.model_validate(data)
120
 
121
 
baseball_batting/motion_export.py CHANGED
@@ -104,7 +104,7 @@ def reproduce_measurements(manifest, motion_path):
104
  return _calculate({'points_relative':points,'boundary':boundary}, times, options, known)[0]
105
 
106
 
107
- def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=86400,progress=lambda *a:None,track=None,refinement=None):
108
  """Write all artifacts before atomically publishing the completed manifest."""
109
  import time
110
  job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
@@ -140,9 +140,14 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
140
  corrected['metadata']['whole_body_refinement']=refinement or {'enabled':False,'reason_code':'not_executed_in_this_export'}
141
  corrected['metadata']['native_rig_fitted_frame_count']=int(refined_mask.sum())
142
  corrected['metadata']['fitted_points_post_smoothing']='disabled; preserve accepted native rig geometry'
 
 
143
  calculation_options=options
 
 
 
144
  if refinement and refinement.get('image_evidence',{}).get('declared_static_camera_conflict'):
145
- calculation_options=options.model_copy(update={'camera_stability':'moving'})
146
  if options.model=='gvhmr':
147
  corrected['interpolated']|=resampled[:,None]&corrected['valid']
148
  corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
@@ -225,13 +230,17 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
225
  manual=bool(options.windows); source='manual' if manual else 'pose_estimated'
226
  rows={m.key:m for swings in groups.values() for swing in swings if swing.rep==rep for m in swing.measurements}
227
  interpolation=bool(corrected['interpolated'][a:b+1,indices].any())
228
- measurement_matrix,_=orientation(corrected['points_relative'],options,base)
229
  metadata={'analysis_revision':revision,'rep':rep,'definition_version':definition_version,
230
  'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
231
  'temporal_model_sample_spacing_ms':1000/30 if options.model=='gvhmr' and known else None,
232
  'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
 
233
  for key,metric in rows.items():
234
  details=metric.model_dump(mode='json');details.pop('coaching',None)
 
 
 
235
  summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
236
  'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
237
  'source_samples':[stamp(i) for i in metric.source_frame_ids]})
@@ -300,14 +309,15 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
300
  'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
301
  atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
302
  'definition_version':definition_version,'summaries':summaries,'series':series,
303
- 'calculation_inputs':calculation_options.model_dump(mode='json')})
304
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
305
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
306
  'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
307
  'reidentification':'bounded_short_loss_only; ambiguous_overlap_not_recovered','box_overlap_gate':.05,
308
  'tracking_reasons':track['reasons']},
309
  'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
310
- 'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting'})
 
311
  clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress,distortion=distortion) if options.annotated_videos else {}
312
  source=job/('source'+Path(video).suffix.lower())
313
  if source!=Path(video):
@@ -360,11 +370,14 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
360
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
361
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
362
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
 
 
 
363
  'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
364
  'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
365
  'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
366
- 'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
367
- {'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
368
  {'x':'camera_right','y':'camera_down','z':'camera_away'}),
369
  'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
370
  'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
 
104
  return _calculate({'points_relative':points,'boundary':boundary}, times, options, known)[0]
105
 
106
 
107
+ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=86400,progress=lambda *a:None,track=None,refinement=None,up_reference=None):
108
  """Write all artifacts before atomically publishing the completed manifest."""
109
  import time
110
  job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
 
140
  corrected['metadata']['whole_body_refinement']=refinement or {'enabled':False,'reason_code':'not_executed_in_this_export'}
141
  corrected['metadata']['native_rig_fitted_frame_count']=int(refined_mask.sum())
142
  corrected['metadata']['fitted_points_post_smoothing']='disabled; preserve accepted native rig geometry'
143
+ from .camera_up import reference as up_reference_default
144
+ up_reference=up_reference_default(options) if options.up_vector is not None else (up_reference or up_reference_default(options))
145
  calculation_options=options
146
+ if options.up_vector is None and up_reference.get('status')=='estimated' and up_reference.get('reliable') is True:
147
+ calculation_options=options.model_copy(update={'up_vector':tuple(up_reference['up_vector']),
148
+ 'up_source':up_reference['up_source']})
149
  if refinement and refinement.get('image_evidence',{}).get('declared_static_camera_conflict'):
150
+ calculation_options=calculation_options.model_copy(update={'camera_stability':'moving'})
151
  if options.model=='gvhmr':
152
  corrected['interpolated']|=resampled[:,None]&corrected['valid']
153
  corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
 
230
  manual=bool(options.windows); source='manual' if manual else 'pose_estimated'
231
  rows={m.key:m for swings in groups.values() for swing in swings if swing.rep==rep for m in swing.measurements}
232
  interpolation=bool(corrected['interpolated'][a:b+1,indices].any())
233
+ measurement_matrix,_=orientation(corrected['points_relative'],calculation_options,base)
234
  metadata={'analysis_revision':revision,'rep':rep,'definition_version':definition_version,
235
  'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
236
  'temporal_model_sample_spacing_ms':1000/30 if options.model=='gvhmr' and known else None,
237
  'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
238
+ metadata['up_reference_status']=up_reference['status']
239
  for key,metric in rows.items():
240
  details=metric.model_dump(mode='json');details.pop('coaching',None)
241
+ if (up_reference['status']=='estimated' and details['value'] is not None and key not in
242
+ ('head_excursion_relative_cm','hand_speed_relative_m_s','hands_peak_time_ms','stride_duration_ms')):
243
+ details['quality_flags'].append('vertical_reference_estimated_from_images')
244
  summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
245
  'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
246
  'source_samples':[stamp(i) for i in metric.source_frame_ids]})
 
309
  'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
310
  atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
311
  'definition_version':definition_version,'summaries':summaries,'series':series,
312
+ 'calculation_inputs':calculation_options.model_dump(mode='json'),'up_reference':up_reference})
313
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
314
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
315
  'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
316
  'reidentification':'bounded_short_loss_only; ambiguous_overlap_not_recovered','box_overlap_gate':.05,
317
  'tracking_reasons':track['reasons']},
318
  'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
319
+ 'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting',
320
+ 'up_reference':up_reference})
321
  clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress,distortion=distortion) if options.annotated_videos else {}
322
  source=job/('source'+Path(video).suffix.lower())
323
  if source!=Path(video):
 
370
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
371
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
372
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
373
+ 'up_vector':list(calculation_options.up_vector) if calculation_options.up_vector is not None else None,
374
+ 'up_source':calculation_options.up_source if calculation_options.up_vector is not None else None,
375
+ 'up_vector_frame':up_reference['coordinate_frame'],'up_estimation':up_reference,
376
  'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
377
  'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
378
  'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
379
+ 'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='declared_field_axes' else (
380
+ {'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='fixed_starting_hip_axis' else
381
  {'x':'camera_right','y':'camera_down','z':'camera_away'}),
382
  'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
383
  'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
baseball_batting/motion_worker.py CHANGED
@@ -38,7 +38,10 @@ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120,retention
38
  track=read_json(job/'person-track-private.json')
39
  from .motion_refine import refine
40
  raw,refinement=refine(job,video,capture,raw,models,options,progress)
41
- return export_motion(job,video,capture,raw,options,model,lineage,retention_s=retention_s,progress=progress,track=track,refinement=refinement)
 
 
 
42
 
43
 
44
  def main():
 
38
  track=read_json(job/'person-track-private.json')
39
  from .motion_refine import refine
40
  raw,refinement=refine(job,video,capture,raw,models,options,progress)
41
+ from .camera_up import estimate
42
+ up_reference=estimate(job,video,capture,models,options,track,progress)
43
+ return export_motion(job,video,capture,raw,options,model,lineage,retention_s=retention_s,
44
+ progress=progress,track=track,refinement=refinement,up_reference=up_reference)
45
 
46
 
47
  def main():
baseball_batting/sam_batting_contract.py CHANGED
@@ -1,5 +1,5 @@
1
  """Separate SAM measurements contract; public results never contain pose trajectories."""
2
- from typing import Literal
3
  from pydantic import BaseModel, ConfigDict, Field, model_validator
4
  import math
5
  from .api_contract import TimingInput, CameraInput
@@ -69,6 +69,9 @@ class SwingWindow(Strict):
69
 
70
 
71
  class SamBattingInput(Strict):
 
 
 
72
  timing: TimingInput = Field(default_factory=TimingInput)
73
  rotation_degrees: Literal[0, 90, 180, 270] | None = None
74
  camera_stability: Literal['unknown', 'fixed_verified', 'moving'] = 'unknown'
@@ -97,7 +100,7 @@ class SamBattingInput(Strict):
97
  raise ValueError('Reference vectors must be finite and nonzero')
98
  if not getattr(self, name + '_source'):
99
  raise ValueError('Reference vectors need a source description')
100
- if self.pitcher_vector and not self.up_vector:
101
  raise ValueError('Pitcher direction needs the vertical reference')
102
  if self.scale_factor != 1 and not self.scale_source:
103
  raise ValueError('Scale changes need a source description')
 
1
  """Separate SAM measurements contract; public results never contain pose trajectories."""
2
+ from typing import ClassVar, Literal
3
  from pydantic import BaseModel, ConfigDict, Field, model_validator
4
  import math
5
  from .api_contract import TimingInput, CameraInput
 
69
 
70
 
71
  class SamBattingInput(Strict):
72
+ # The separate motion API can resolve a missing vertical from image evidence.
73
+ # This legacy API still requires the caller to provide both reference axes.
74
+ requires_vertical_for_pitcher: ClassVar[bool] = True
75
  timing: TimingInput = Field(default_factory=TimingInput)
76
  rotation_degrees: Literal[0, 90, 180, 270] | None = None
77
  camera_stability: Literal['unknown', 'fixed_verified', 'moving'] = 'unknown'
 
100
  raise ValueError('Reference vectors must be finite and nonzero')
101
  if not getattr(self, name + '_source'):
102
  raise ValueError('Reference vectors need a source description')
103
+ if self.requires_vertical_for_pitcher and self.pitcher_vector and not self.up_vector:
104
  raise ValueError('Pitcher direction needs the vertical reference')
105
  if self.scale_factor != 1 and not self.scale_source:
106
  raise ValueError('Scale changes need a source description')
docs/APP_API_INTEGRATION.md CHANGED
@@ -1,591 +1,731 @@
1
- # App integration: swing analysis, coaching and swing clips
2
 
3
- For the coding agent updating the app's previous engine → separate coach flow.
 
4
 
5
  **Engine base URL:** `https://modventures-baseball-engine.hf.space`
6
 
7
- Use one upload and one combined result. The engine now runs the coach internally.
8
- The result includes measurements, the coach's existing response, experimental
9
- video feedback for the three features, and a playable clip for each detected swing.
10
-
11
  ```text
12
- App → app backend → upload video to engine → poll job
13
- ↓
14
- combined product + individual swing clips
15
- ↓
16
- app shows swing cards and feedback
17
  ```
18
 
19
- ## 1. Change the old integration
 
 
 
 
 
 
20
 
21
- | Previous integration | Current integration |
22
  | --- | --- |
23
- | Upload to `POST /v1/analyses` | Upload to `POST /v1/swing-coach/analyses` |
24
- | Fetch `/coach-payload`, then call the standalone coach | Fetch `/product`; coaching is already included |
25
- | Read only the coach response | Read `product.coaching` **and** `product.visual_review` |
26
- | Use frame ranges or still images as swing previews | Read `product.swings`; each available clip has an MP4 endpoint |
27
- | App receives coach response version `2.0` | That same response remains inside `product.coaching` |
28
-
29
- For this new flow, remove the extra standalone coach request. Do not pass the
30
- whole product into the old coach input: it already contains that coach's output.
31
-
32
- **Do not hide the entire result when `coaching.score.value` is null or
33
- `coaching.focus` is empty.** The experimental video observations and swing clips
34
- can still be available. Fetching `/coaching` alone also misses the new video
35
- feedback and clips; fetch `/product` for the app screen.
36
-
37
- Old engine upload/result routes and standalone coach routes remain available.
38
- Legacy measurements stay at schema `2.0`; timing defaults to `3.0`, with `3.1`
39
- when evidence is requested. The combined product is now **`schema_version: "1.1"`**.
40
- Its new `swings` and `swings_url` fields are additive to product `1.0`. Accept
41
- both product versions and treat a missing `swings` field as an older result.
 
 
42
 
43
  ## 2. Authentication and app backend
44
 
45
- Every engine `/v1/...` request uses:
46
 
47
  ```http
48
  Authorization: Bearer <ENGINE_SERVER_KEY>
49
  ```
50
 
51
- Store this key in your **app backend's environment**, for example
52
- `BASEBALL_ENGINE_API_KEY`. Use the same key for uploads, status, JSON results,
53
- images and MP4 clips. The old standalone coach's `X-API-Key` header is not used
54
- for this combined flow.
55
 
56
- The Gemini key stays in the engine's `GOOGLE_API_KEY` secret. The app does not
57
- send it. Browser uploads should go through your app backend: the engine does
58
- not enable cross-origin browser requests.
 
59
 
60
- Authenticate your app user and store which user owns each returned `job_id`.
61
- Check that ownership before proxying status, results, clips, frames, retry or
62
- delete. The engine's shared key does not provide per-user access control.
63
 
64
- ## 3. Upload one video
 
 
 
65
 
66
- **`POST /v1/swing-coach/analyses`**
 
 
67
 
68
- Body: **multipart form data**, with these two fields:
69
 
70
- | Field | Form-data type | Value |
71
- | --- | --- | --- |
72
- | `video` | File | The original video file |
73
- | `options` | Text | A JSON string containing the recording facts |
74
 
75
- Example options for a known right-handed batter, with the ball coming from the
76
- right side of the image and a fixed camera facing the batter's chest:
77
 
78
  ```json
79
  {
80
- "measurement_backend": "2d",
81
- "coaching_mode": "poc_video",
82
- "view": "face_on",
83
- "handedness": "right",
84
- "pitcher_direction": "image_right",
85
- "practice_type": "front_toss",
86
- "camera_stability": "fixed_verified",
87
- "timing": {
88
- "kind": "unretimed",
89
- "source": "Uploader confirms original recording; no speed changes"
90
- },
91
- "single_swing": false
 
 
 
92
  }
93
  ```
94
 
95
- These are example facts, not defaults to apply to every player. Ask the player
96
- for the facts the app does not know.
 
 
 
 
97
 
98
- | Option | Meaning and accepted values |
99
- | --- | --- |
100
- | `measurement_backend` | Use `"2d"` for this POC. It runs pose and bat/ball models on GPU without SAM. |
101
- | `coaching_mode` | `"poc_video"` includes the coach and sampled-image Gemini review; this is the new route's default. `"measurements_only"` includes the existing coach without Gemini images. `"disabled"` produces measurements and clips without a product. |
102
- | `view` | `"face_on"` when the camera faces the batter's chest; otherwise `"unknown"`. Do not infer this only because a person is visible. |
103
- | `handedness` | `"left"`, `"right"`, or `null`: the side the player bats from. |
104
- | `pitcher_direction` | `"image_left"`, `"image_right"`, or `null`: direction toward the pitcher/tee in the image, not the player's handedness. |
105
- | `practice_type` | `"tee"`, `"soft_toss"`, `"front_toss"`, `"live"`, `"machine"`, or `"unknown"`. |
106
- | `camera_stability` | `"fixed_verified"` if the camera stays still, `"moving"` if it moves, otherwise `"unknown"`. |
107
- | `timing` | `{"kind":"unknown"}` if speed changes are uncertain. Use documented `"unretimed"` only when the recording has no speed changes. |
108
- | `single_swing` | **`false` for a video containing multiple swings.** `true` treats the entire recording as one supplied swing range; it does not split it. |
109
-
110
- Unknown recording facts are accepted by the combined route. They can make
111
- measurements unavailable, so show upload `warnings` instead of silently changing
112
- the facts. The strict `/v1/load-timing/analyses` route can reject missing timing
113
- settings; it is not the recommended upload route for the combined app screen.
114
-
115
- If the recording is documented constant slow motion, the supported timing shape is:
116
 
117
- ```json
118
- {
119
- "kind": "constant_slowdown",
120
- "source": "Documented camera recording setting",
121
- "factor": 4,
122
- "all_captured_frames_retained": true
123
- }
124
- ```
125
 
126
- Do not set that flag if frames were removed or the slowdown is uncertain.
127
 
128
- If your app already knows the cuts, it may supply `reps` as sorted,
129
- non-overlapping, **zero-based inclusive** frame ranges:
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  ```json
132
  {
133
- "single_swing": false,
134
- "reps": [
135
- {"start_frame": 0, "end_frame": 119},
136
- {"start_frame": 120, "end_frame": 239}
137
- ]
 
138
  }
139
  ```
140
 
141
- Omit `reps` to let the engine detect swings. Do not send `single_swing: true`
142
- together with `reps`. Only send ranges that fit the actual source video.
143
-
144
- Successful upload returns **HTTP 202**, including:
145
 
146
  ```json
147
  {
148
- "job_id": "0123456789abcdef0123456789abcdef",
149
- "status": "queued",
150
- "status_url": "/v1/analyses/0123456789abcdef0123456789abcdef",
151
- "product_url": "/v1/analyses/0123456789abcdef0123456789abcdef/product",
152
- "swings_url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings",
153
- "coaching_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coaching",
154
- "result_url": "/v1/analyses/0123456789abcdef0123456789abcdef/result",
155
- "coach_payload_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coach-payload",
156
- "load_timing_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing",
157
- "load_timing_evidence_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing?include_evidence=true",
158
- "warnings": []
159
  }
160
  ```
161
 
162
- The job ID here is illustrative. Save the real ID returned by your upload.
163
- All returned URLs are relative to the engine base URL.
164
-
165
- ## 4. Poll the job, then fetch the product
166
-
167
- **`GET /v1/analyses/{job_id}`**
168
-
169
- Poll about every two seconds; back off during a long wait. An upload response
170
- does not mean analysis has finished. GPU work can take several minutes.
171
-
172
- | Job status | App behavior |
173
  | --- | --- |
174
- | `queued` | Show “Waiting to analyze”. |
175
- | `running` | Show “Analyzing”, optionally with the current `progress.stage`. |
176
- | `completed` | Fetch `product_url`, then render the result. |
177
- | `failed` | Show the returned `error`; allow a new upload. |
178
- | `cancel_requested` | Show “Cancelling” and continue polling. |
179
- | `cancelled` | Stop polling; the result files are removed. |
180
-
181
- `progress` can be null. Stages include decoding, pose, measurements, tracking,
182
- `swing_clips`, coaching and complete. `completed_frames`, `total_frames` and
183
- `stage_progress` describe the current stage, not the whole job. Do not present
184
- a stage's percentage as an overall completion percentage.
185
-
186
- Preserve the job ID if the user leaves the screen or a polling request fails;
187
- resume polling rather than uploading the same video again automatically.
188
-
189
- Once complete:
190
-
191
- **`GET /v1/analyses/{job_id}/product`**
192
-
193
- | Product field | What the app uses it for |
194
- | --- | --- |
195
- | `schema_version` | Product version `"1.1"`; also accept older `"1.0"`. |
196
- | `session_id` | Same ID as the analysis job. |
197
- | `discipline` | `"hitting"`. |
198
- | `coaching_mode` | The requested mode. |
199
- | `swings` | Every detected/supplied rep, with its boundaries and clip metadata. |
200
- | `swings_url` | Separate swing-list endpoint, if needed. |
201
- | `measurements` | Existing `2.0` per-rep nine-measurement payload. |
202
- | `timing` | `3.1` per-rep timing, event intervals, context and reason codes. |
203
- | `coaching` | Existing coach response, `response_version: "2.0"`. |
204
- | `visual_review` | Experimental observations, separate visual rubric score and optional priority/drill for the three features. |
205
- | `evidence` | Retained sampled frame images and review coverage. |
206
-
207
- There is no second upload or separate endpoint for each of the three feedback
208
- features. They are returned together in `visual_review.features`.
209
-
210
- ## 5. Show an individual video for each swing
211
-
212
- `product.swings` contains entries shaped like this. Numbers and checksum below
213
- are illustrative, not a real downloadable recording:
214
 
215
  ```json
216
  {
217
- "rep": 1,
218
- "start_frame": 0,
219
- "end_frame": 119,
220
- "boundary_method": "automatic_2d_hand_motion_candidate",
221
- "boundary_accuracy_validated": false,
222
- "source_start_playback_s": 0.0,
223
- "source_end_playback_s": 3.966667,
224
- "clip": {
225
- "status": "available",
226
- "reason_code": null,
227
- "url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings/1/clip",
228
- "content_type": "video/mp4",
229
- "duration_s": 4.0,
230
- "frame_count": 120,
231
- "width": 1280,
232
- "height": 720,
233
- "has_audio": false,
234
- "overlay": true,
235
- "size_bytes": 524288,
236
- "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
237
  }
238
  }
239
  ```
240
 
241
- Build the swing list from `swings`, ordered as returned. Labels are “Swing 1”,
242
- “Swing 2”, etc. Rep IDs are **one-based**; source frame IDs are **zero-based**.
243
-
244
- - `start_frame` and `end_frame` include both endpoint frames.
245
- - `boundary_method` is `automatic_2d_hand_motion_candidate`, `caller_supplied`,
246
- or `caller_declared_single_swing` for the current engine.
247
- - Automatic cuts are candidates. Detection may miss/merge movements; clips do
248
- not establish that every actual swing was found.
249
- - New clips use the same overlay renderer as the Colab `previews` folder:
250
- green body points/skeleton, orange toe/heel points, source frame numbers and
251
- estimated event labels. `clip.overlay: true` identifies annotated previews.
252
- A body-based contact event is labelled **estimated contact proxy**; it is not
253
- confirmed bat-ball impact. Missing joints/events are not drawn or invented.
254
- If a selected 3D backend produced projections, the clip also shows purple
255
- projected joints and red disagreement connectors at those sampled frames.
256
- The default 2D backend requires no SAM to draw the body skeleton.
257
- - The clips are upright H.264 MP4s, resized to at most 1280 pixels on the longest side,
258
- with at most one pixel of padding for odd dimensions. They have **no audio**.
259
- - Every source frame in the range is retained. Each clip starts at playback
260
- time zero and preserves the source's variable frame spacing and playback
261
- speed. An uploaded slow-motion video stays slow motion in the clip.
262
- - Capture-time measurements and clip playback time are separate clocks.
263
- `source_end_playback_s` is the last frame's timestamp; `duration_s` also
264
- includes that last frame's display duration.
265
-
266
- The clip endpoint is:
267
-
268
- **`GET /v1/analyses/{job_id}/swings/{rep}/clip`**
269
-
270
- It requires the same Bearer key and returns `video/mp4`. It supports normal GET
271
- (`200`), single byte ranges (`206`), suffix/open-ended ranges, and HEAD. Invalid
272
- or unsatisfiable byte ranges return `416` with `Content-Range: bytes */<size>`.
273
- Multiple ranges are unsupported. `Accept-Ranges`, `Content-Length`, `ETag` and
274
- `Content-Range` on partial responses support player seeking.
275
-
276
- **Use an app-backend media proxy for playback.** Browser `<video src>` cannot
277
- attach the engine's Bearer header. The proxy should authenticate the app user,
278
- check job ownership, add the engine key, forward `Range`/`If-Range`, and stream
279
- the response without buffering the whole video. Pass through the response
280
- status and media/range headers. Never put the engine key in the video URL.
281
-
282
- For a small internal browser test, fetching the authenticated clip into a Blob
283
- and setting `video.src = URL.createObjectURL(blob)` also works. Revoke the Blob
284
- URL when the result is replaced. This downloads the entire clip first; the
285
- backend proxy is the preferred app integration.
286
-
287
- For a separate swing-list request:
288
-
289
- **`GET /v1/analyses/{job_id}/swings`** returns:
290
 
291
- ```text
292
- schema_version: "1.0" # This is the swing-list version, not the product version.
293
- session_id: job ID
294
- swings: same array as product.swings
295
- notice: boundary/timing/format explanation
296
- ```
297
 
298
- New jobs on the legacy upload routes also create this manifest and clips.
299
- Older completed jobs cannot create clips after their original upload was
300
- removed. Their swing endpoint returns `409`; upload again to create clips.
301
- Clips from before the overlay update stay plain (`overlay: false` or missing).
302
- Upload again to generate annotated previews. Existing `clip.url` playback paths
303
- and authentication are unchanged; the mobile app does not need to draw joints.
304
- Gemini still receives unannotated original images, not these display overlays.
305
-
306
- If a particular clip cannot be exported, its rep remains in `swings` with
307
- `clip.status: "unavailable"`, a `reason_code`, and `url: null`. Hide that rep's
308
- player and show “Clip unavailable”; retain its measurements and feedback.
309
- Reasons include missing/invalid source timestamps, source mismatch,
310
- unavailable last-frame duration, and `clip_export_failed`. An empty `swings`
311
- array means no rep was detected; do not invent a swing card.
312
-
313
- ## 6. Match each swing to its measurements and feedback
314
-
315
- Join by **`rep`**, not by array position:
316
-
317
- ```javascript
318
- const cards = (product.swings ?? []).map(swing => ({
319
- ...swing,
320
- measurements: product.measurements.reps.find(r => r.rep === swing.rep) ?? null,
321
- timing: product.timing.reps.find(r => r.rep === swing.rep) ?? null,
322
- observations: product.visual_review.features.filter(f => f.rep === swing.rep)
323
- }));
324
  ```
325
 
326
- The current Gemini review returns **three feature observations for the session**,
327
- each referring to one rep. It does not promise all three observations for every
328
- swing. The configured default reviews sampled images from at most six reps;
329
- **clips are exported for all detected reps**, including unreviewed ones.
330
- Use `evidence.reviewed_reps` and `evidence.total_reps` to show that coverage.
331
- Label a swing without a visual observation “Not individually reviewed” rather
332
- than copying another swing's advice onto it.
333
 
334
- ### Three feedback cards
335
 
336
- When `visual_review.status` is `"completed"`, render its features:
 
337
 
338
- | `feature.key` | App label | Text |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  | --- | --- | --- |
340
- | `load_timing` | Load and timing | `feature.observation` |
341
- | `hip_shoulder_separation` | Hips and shoulders | `feature.observation` |
342
- | `bat_path_contact` | Bat path and contact | `feature.observation` |
343
-
344
- New reviews include `visual_review.text_style_version: "concise-observations-v1"`.
345
- The prompt asks for one or two complete sentences, at most thirty-five words per
346
- observation. Text describes the visible body part, movement direction and order,
347
- with a brief specific limitation when necessary. Render `observation` as returned;
348
- do not cut it mid-sentence. The numerical measurements and score rules are unchanged.
349
-
350
- Each feature also contains `status` (`"observed"` or `"unclear"`), `rep`,
351
- `evidence_frame_ids`, and `ball_interaction_visible`. Show unclear observations
352
- as uncertainty, not as a diagnosed problem. Label this section “Experimental
353
- video feedback”; `accuracy_validated` and `judgment_eligible` remain false.
354
-
355
- `ball_interaction_visible` is the visual review's interpretation. It does not
356
- change `timing.reps[].outcome` into a measured hit or turn an unavailable timing
357
- number into a measured value. Hips/shoulders feedback describes visible turning
358
- order, not a measured 3D separation angle. No validated score against exact pitch
359
- location is supplied by this one-camera visual review.
360
-
361
- When `visual_review.status` is `"unavailable"`, show its safe `message` or
362
- `reason_code`. Keep showing clips, supported measurements and `coaching`.
363
-
364
- ### Experimental video score
365
-
366
- Show **`product.visual_review.score`** separately from the original Mechanics
367
- score in `coaching.score`. When its `status` is `"available"` and `value` is
368
- non-null, display its `name` ("Experimental video score"), `value / max_value`,
369
- `explanation` and per-swing `rep_scores` matched by `rep`. Zero is a valid score;
370
- use `value !== null`, not a truthiness check. If unavailable, hide the number
371
- or show its explanation. Keep the rest of the result visible.
372
-
373
- The model chooses fixed Clear/Mixed/Needs practice grades; the server calculates
374
- points. A swing needs two rateable features from that same swing. Unclear
375
- features are excluded, not graded zero. Only `scored_reps` contribute to the
376
- root score; it does not rate every swing or the player's overall ability.
377
- Both `accuracy_validated` and `judgment_eligible` remain false. See
378
- [the scoring guide and full fields](EXPERIMENTAL_VIDEO_SCORE.md).
379
-
380
- ### Practice suggestion
381
-
382
- If both `visual_review.priority` and `visual_review.drill` exist, show:
383
-
384
- ```text
385
- Why: visual_review.priority.reason
386
- Drill: visual_review.drill.name
387
- How: visual_review.drill.instructions
388
- Cue: visual_review.drill.cue
389
- ```
390
-
391
- This is one experimental session suggestion, not one drill for every swing.
392
- If no visual suggestion exists, your previous `coaching.drill` display can be
393
- used when non-null (`name`, `how`, `cue`). Otherwise hide the drill area.
394
 
395
- ### Timing and older coach fields
 
 
396
 
397
- For a plain-language timing summary, keep using `coaching.timing.summary`,
398
- `observations[].text`, `unavailable[].text` and `data_quality` when present.
399
- For each swing's actual four values, read `timing.reps[].metrics` by key:
400
 
401
- | Key | Label |
402
  | --- | --- |
403
- | `load_to_swing_ms` | Preparation to forward swing |
404
- | `foot_down_to_swing_ms` | Front foot down to forward swing |
405
- | `swing_duration_ms` | Forward swing to contact/closest approach |
406
- | `early_late_shift_ms` | Estimated timing shift needed to meet the ball |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
- Render a number only when `value` is non-null, with its `status`/`confidence`.
409
- Use “Unavailable” with the `note`/`reason_code` for unclear metrics, and “Not
410
- applicable” when stated. Null is not zero. Keep signed foot-down differences;
411
- negative means the swing began before the foot landed.
 
 
412
 
413
- The original `coaching.summary`, `score`, `focus`, `strengths`, `drill`, and
414
- `data_quality` remain available in the same coach response shape. A null score
415
- must stay unavailable. Use the separate `visual_review.score` for the experimental
416
- visual rating; do not put it into `coaching.score` or fill missing measurements.
 
417
 
418
- ### Evidence frames and seeking inside a clip
419
 
420
- `evidence.frames[]` includes `frame`, `reps`, `url`, `playback_t_s`,
421
- `capture_t_s`, `athlete_box` and `sha256`. Images use
422
- `GET /v1/analyses/{job_id}/frames/{frame}` and require Bearer authentication.
423
- Match `evidence_frame_ids` to this list, not to array indices.
424
 
425
- For a frame belonging to a swing, the clip's local frame index is:
426
 
427
- ```text
428
- local_frame = source_frame - swing.start_frame
429
- clip_seek_seconds = evidence_frame.playback_t_s - swing.source_start_playback_s
 
 
 
 
 
430
  ```
431
 
432
- Use the playback timestamps for seeking; do not divide capture milliseconds
433
- by 1000 and assume they are clip times. Check the frame belongs to the swing
434
- and both timestamps are available. Capture-time intervals remain in
435
- `timing.reps[].events`; they describe uncertainty, not exact measured contact.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
 
437
- ## 7. Request examples in application code
 
438
 
439
- The frontend below calls **your app's authenticated backend proxy**, which maps
440
- `/api/baseball/v1/...` onto engine `/v1/...`. Adapt the prefix to your app. The
441
- browser never receives the engine key.
442
 
443
- ```javascript
444
- async function uploadSwingVideo(file, recordingFacts, signal) {
445
- const form = new FormData();
446
- form.append("video", file);
447
- form.append("options", JSON.stringify({
448
- ...recordingFacts,
449
- measurement_backend: "2d",
450
- coaching_mode: "poc_video"
451
- }));
452
- const response = await fetch("/api/baseball/v1/swing-coach/analyses", {
453
- method: "POST", body: form, signal
454
- });
455
- // Let fetch set the multipart boundary; do not set Content-Type manually.
456
- if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
457
- return response.json();
458
  }
 
459
 
460
- async function readAnalysis(jobId, signal) {
461
- const response = await fetch(`/api/baseball/v1/analyses/${jobId}`, { signal });
462
- if (!response.ok) throw new Error(`Status failed: ${response.status}`);
463
- return response.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  }
465
 
466
- async function readProduct(jobId, signal) {
467
- const response = await fetch(`/api/baseball/v1/analyses/${jobId}/product`, { signal });
468
- if (!response.ok) throw new Error(`Result failed: ${response.status}`);
469
- return response.json();
 
 
 
 
 
 
 
 
 
 
 
470
  }
471
 
472
- // After a completed status, each available clip can use your same-origin proxy:
473
- function appClipUrl(jobId, swing) {
474
- return `/api/baseball/v1/analyses/${jobId}/swings/${swing.rep}/clip`;
 
 
475
  }
476
- ```
477
-
478
- Backend-only example for an engine request, using Node's built-in fetch:
479
 
480
- ```javascript
481
- const ENGINE_ORIGIN = "https://modventures-baseball-engine.hf.space";
482
-
483
- async function engineRequest(relativePath, init = {}) {
484
- const url = new URL(relativePath, ENGINE_ORIGIN);
485
- if (url.origin !== ENGINE_ORIGIN || !url.pathname.startsWith("/v1/")) {
486
- throw new Error("Unexpected engine path");
 
 
 
 
 
 
487
  }
488
- const key = process.env.BASEBALL_ENGINE_API_KEY;
489
- if (!key) throw new Error("Engine key not configured");
490
- const headers = new Headers(init.headers);
491
- headers.set("Authorization", `Bearer ${key}`);
492
- return fetch(url, { ...init, headers, redirect: "error" });
493
  }
494
 
495
- // Inside your authenticated/ownership-checked media route:
496
- // 1. Validate jobId as 32 lowercase hex characters and rep as a positive integer.
497
- // 2. Confirm the logged-in user owns that job.
498
- // 3. Construct the path yourself; do not accept an arbitrary upstream URL.
499
- // 4. Forward only supported request headers such as Range and If-Range.
500
- // 5. Stream upstream.body using your framework's Web-to-Node stream adapter.
501
- async function fetchClipForProxy(jobId, rep, requestHeaders) {
502
- const headers = new Headers();
503
- for (const name of ["Range", "If-Range"]) {
504
- const value = requestHeaders.get(name);
505
- if (value) headers.set(name, value);
506
- }
507
- return engineRequest(`/v1/analyses/${jobId}/swings/${rep}/clip`, { headers });
508
  }
509
- ```
510
 
511
- The media proxy must pass through `200`, `206` and `416`, plus `Content-Type`,
512
- `Content-Length`, `Content-Range`, `Accept-Ranges`, `ETag` and `Cache-Control`.
513
- Do not convert every upstream response to HTTP 200. Support HEAD if the app's
514
- player uses it. Forward authenticated JSON error responses for failed requests.
515
-
516
- ## 8. Retry, cancel and retain results
517
-
518
- **Retry optional video feedback:**
519
- `POST /v1/analyses/{job_id}/video-review`, no request body.
520
 
521
- This returns the updated whole product. It reuses retained images and keeps
522
- the measurements and swing clips. It does not repeat pose inference. A completed
523
- review with the current visual-scoring rubric and wording style is returned unchanged, without
524
- another Gemini call. An older completed review with retained frames can be
525
- explicitly upgraded once using this route. An unavailable review
526
- can be retried; a genuine retry consumes Gemini quota. Allow a longer request
527
- timeout for this synchronous route and show “Retrying video feedback”. Do not
528
- retry it continuously on every poll. No retained images returns `409`.
 
529
 
530
- **Cancel/delete:** `DELETE /v1/analyses/{job_id}`, returning HTTP 202.
531
- Running jobs first return `cancel_requested`; completed jobs become cancelled
532
- and their JSON, images and clips are removed.
 
 
533
 
534
- **Storage:** default engine retention is 24 hours; check `/v1/capabilities` for
535
- the actual value. Hugging Face ephemeral storage can disappear during rebuilds
536
- or restarts. Clip URLs are authenticated engine resources, not permanent media
537
- hosting URLs. After completion, copy the product and each available clip into
538
- your app's persistent storage if the user should revisit sessions later. Keep
539
- rep IDs with those copies. An engine rebuild can erase jobs before 24 hours.
540
 
541
- ## 9. Errors and limits
542
 
543
- | HTTP status | Meaning |
544
  | --- | --- |
545
- | `401` | Invalid/missing engine Bearer key. |
546
- | `404` | Job, rep or evidence frame not found. |
547
- | `409` | Result not complete, older artifact missing, or requested clip unavailable. Check `detail`. |
548
- | `413` | Upload/options/request too large. |
549
- | `415` | Unsupported video extension. |
550
- | `416` | Invalid/unsupported/unsatisfiable byte range. |
551
- | `422` | Bad options, missing upload field, empty file, or invalid explicit ranges. |
552
- | `429` | Queue, upload slots or review already busy. Respect `Retry-After` when provided. |
553
- | `500` | Stored artifact failed integrity/structure checks, or review could not be saved. |
554
- | `503` | GPU not ready or requested server component unavailable. |
555
- | `507` | Insufficient engine storage. |
556
-
557
- Errors use `{"detail": ...}`; `detail` can be a string, object or validation
558
- list. Parse safely. A job can later fail with `error` codes such as
559
- `invalid_video_or_capture`, `inference_failed`, `job_timeout`, or `worker_error`.
560
- Optional Gemini failure is instead reported within `visual_review`; it does
561
- not automatically make the analysis job fail.
562
-
563
- Default limits: 512 MiB upload, 120 seconds of playback, 7200 decoded frames,
564
- 8,294,400 pixels per source frame. Supported extensions: `.mp4`, `.mov`, `.mkv`,
565
- `.avi`, `.webm`. Limits can be configured; read `/v1/capabilities` rather than
566
- assuming these values forever.
567
-
568
- Public `/healthz` checks liveness; `/readyz` checks GPU readiness and reports
569
- visual model configuration/provider status. `/docs` serves interactive engine
570
- API documentation. Authenticated `/v1/input-schema` and `/v1/swings-schema`
571
- return the current input and swing-list schemas.
572
-
573
- ## 10. Integration acceptance checks
574
-
575
- - Upload a multi-swing video with `single_swing: false`; store the returned job
576
- ID and poll it to completion without sending a second coach request.
577
- - Show all returned swing entries, each with its own rep ID and playable clip
578
- when available. Test seeking, and check HTTP 206 through the media proxy.
579
- - Match each swing's timing/measurements by `rep`; attach only visual features
580
- that cite that rep. Show review coverage for unreviewed swings.
581
- - Show the three experimental feedback cards even when the older coach's score
582
- and focus are unavailable.
583
- - Handle unclear/null metrics, unavailable video review, unavailable individual
584
- clips, an empty swing list, and an older product with no `swings` field.
585
- - Retry feedback without re-uploading or losing existing clips/measurements.
586
- - Keep the engine key in the backend; test user ownership on results and media.
587
- - Copy retained sessions to app storage; handle expired/rebuilt engine jobs.
588
-
589
- Do not fill unavailable measurements with visual guesses. This integration
590
- provides the working POC's visible observations, supported estimates and clips;
591
- it does not establish validated one-camera measurement accuracy.
 
1
+ # Frontend integration guide: SAM and GVHMR motion analysis
2
 
3
+ Updated **19 October 2026**. Motion API contract **1.0**. For the coding agent
4
+ updating the mobile/web app's previous engine integration.
5
 
6
  **Engine base URL:** `https://modventures-baseball-engine.hf.space`
7
 
 
 
 
 
8
  ```text
9
+ App → app backend → upload recording with selected model → poll job
10
+ ↓
11
+ result manifest with authenticated artifact URLs
12
+ ↓
13
+ corrected motion + measurements + events + four annotated videos
14
  ```
15
 
16
+ SAM (`sam3d`) and GVHMR (`gvhmr`) use the **same routes and output structure**.
17
+ SAM is the default. Both completed live GPU integration tests on 16 October
18
+ 2026. Check capabilities at runtime: installation/readiness can change after a
19
+ Space restart. Those tests verified execution and output consistency; independent
20
+ 3D accuracy validation remains pending.
21
+
22
+ ## 1. Migrate the correct flow
23
 
24
+ | App currently uses | Change for the motion player |
25
  | --- | --- |
26
+ | `/v1/analyses` or `/v1/swing-coach/analyses` and `/product` | Upload to `/v1/motion-analyses`; fetch the returned `result_url`. |
27
+ | `/v1/sam-batting/analyses` and `groups[]` | The motion result is a manifest. Fetch its `measurements` artifact for summaries/series and its video artifacts for playback. |
28
+ | `measurement_backend` | Use `model: "sam3d"` or `model: "gvhmr"`. This motion API has no `2d` model option. |
29
+ | `reps` | Use `windows` for reviewed frame ranges, or omit windows for automatic motion candidates. |
30
+ | `view`, `pitcher_direction`, `camera_up` | These old field names are not accepted here. Known camera-space references use `up_vector`/`up_source` and `pitcher_vector`/`pitcher_source`. An image-left/right direction is not a 3D vector. |
31
+ | `coaching_mode`, `level`, other legacy options | Remove them from motion requests. Unknown fields return 422. Use the published input schema. |
32
+
33
+ Existing APIs continue working. Their result formats are separate:
34
+
35
+ - This **motion API** returns corrected points, measurements, graphs, events and
36
+ annotated videos. It does **not** return `/product`, coaching paragraphs,
37
+ drills, group scores, a swing-quality score, or bat/ball contact tracking.
38
+ `coaching` is fixed to `false`; omit it or send `false`.
39
+ - The existing [SAM batting API](SAM_BATTING_API.md) still supplies its four
40
+ groups' coaching/reviews/scores. It is SAM-only and has its own processing path.
41
+ - The previous [swing-coach integration](LEGACY_SWING_COACH_INTEGRATION.md) still
42
+ documents `/product`, video feedback, and separately encoded per-swing clips.
43
+
44
+ Keep these result screens/contracts distinct. A matching rep number from separate
45
+ jobs does not establish matching swing boundaries or measurements. Do not present
46
+ an old SAM review as a review of a new GVHMR result.
47
 
48
  ## 2. Authentication and app backend
49
 
50
+ Every engine `/v1/...` request, including JSON and videos, requires:
51
 
52
  ```http
53
  Authorization: Bearer <ENGINE_SERVER_KEY>
54
  ```
55
 
56
+ Keep this shared key in the **app backend**, never in shipped mobile code,
57
+ browser JavaScript, video URLs, or query strings. The frontend does not need
58
+ `HF_TOKEN`, the SMPL-X file, or a Gemini key.
 
59
 
60
+ The app backend proxies engine routes, authenticates your app user, records job
61
+ ownership, and checks ownership on every job/result/artifact request. The engine's
62
+ shared key does not identify individual app users. Restrict the proxy to expected
63
+ engine paths and the requesting user's jobs; do not accept arbitrary upstream URLs.
64
 
65
+ The JavaScript example below assumes your backend exposes engine routes under
66
+ `/api/baseball`, for example:
 
67
 
68
+ ```text
69
+ App: /api/baseball/v1/motion-analyses
70
+ Engine: https://modventures-baseball-engine.hf.space/v1/motion-analyses
71
+ ```
72
 
73
+ That app prefix is an **integration example you implement**, not an existing
74
+ engine endpoint. The proxy adds the engine Bearer header server-side. Browser
75
+ requests use your normal app session. The engine does not enable browser CORS.
76
 
77
+ ## 3. Check models before upload
78
 
79
+ **`GET /v1/motion-analyses/capabilities`**
 
 
 
80
 
81
+ Relevant fields, shown as an excerpt:
 
82
 
83
  ```json
84
  {
85
+ "schema_version": "1.0",
86
+ "default_model": "sam3d",
87
+ "model_selector": "options.model",
88
+ "gpu_queue_ready": true,
89
+ "joint_count": 20,
90
+ "models": [
91
+ {"id": "sam3d", "name": "SAM 3D Body", "configured": true},
92
+ {"id": "gvhmr", "name": "GVHMR", "configured": true}
93
+ ],
94
+ "whole_body_refinement": true,
95
+ "refinement_default_enabled": true,
96
+ "mesh_available": false,
97
+ "retention_hours": 24,
98
+ "max_frames": 7200,
99
+ "max_duration_s": 120
100
  }
101
  ```
102
 
103
+ Build the model selector from `models[].id` and `name`. Enable a selection when
104
+ its `configured` value and `gpu_queue_ready` are true. Inspect `reason_code` when
105
+ not ready; show a setup/warming state instead of submitting repeatedly. Never
106
+ silently switch models. `inference_verified: false` in capabilities is a
107
+ configuration-status field, not proof that a completed analysis failed; judge a
108
+ specific execution using its job status and result.
109
 
110
+ Read live limits instead of hardcoding the example defaults. The default upload
111
+ limit is 512 MiB. Filename extensions: `.mp4`, `.mov`, `.mkv`, `.avi`, `.webm`;
112
+ decoding is also checked. Schemas:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ - `GET /v1/motion-analyses/input-schema`
115
+ - `GET /v1/motion-analyses/output-schema`
116
+
117
+ ## 4. Upload a recording
 
 
 
 
118
 
119
+ **`POST /v1/motion-analyses`**, body **multipart form data**:
120
 
121
+ | Field | Type | Value |
122
+ | --- | --- | --- |
123
+ | `video` | File | Original recording. |
124
+ | `options` | Text | JSON string of recording facts and selected model. |
125
+
126
+ Do not manually set the multipart `Content-Type`; the HTTP client supplies its
127
+ boundary. All examples are illustrative, not downloadable jobs or values to reuse.
128
+
129
+ The short examples below show common fields, not the entire options contract.
130
+ See [all fields with defaults and GVHMR selected](motion-options.example.json) and the
131
+ [complete input schema](motion-input.schema.json). Omitted fields use backend
132
+ defaults. Null/unknown defaults are not calibration evidence and must not be
133
+ copied as known recording facts.
134
+
135
+ Safe request when recording facts are unknown:
136
 
137
  ```json
138
  {
139
+ "model": "gvhmr",
140
+ "annotated_videos": true,
141
+ "handedness": null,
142
+ "camera_stability": "unknown",
143
+ "timing": {"kind": "unknown"},
144
+ "single_swing": false
145
  }
146
  ```
147
 
148
+ Example **only when the uploader confirms these recording facts**:
 
 
 
149
 
150
  ```json
151
  {
152
+ "model": "sam3d",
153
+ "annotated_videos": true,
154
+ "handedness": "right",
155
+ "handedness_source": "Uploader supplied",
156
+ "camera_stability": "fixed_verified",
157
+ "timing": {
158
+ "kind": "unretimed",
159
+ "source": "Uploader confirms original recording speed; no speed changes"
160
+ },
161
+ "single_swing": true
 
162
  }
163
  ```
164
 
165
+ | Option | App behavior |
 
 
 
 
 
 
 
 
 
 
166
  | --- | --- |
167
+ | `model` | `sam3d` or `gvhmr`. Omission defaults to SAM. |
168
+ | `annotated_videos` | Keep `true` for four group videos. `false` leaves those artifacts unavailable with `not_requested`. |
169
+ | `handedness` | `left`, `right`, or `null`; batting side, not image direction. |
170
+ | `camera_stability` | `fixed_verified`, `moving`, or `unknown`. Never auto-fill verified merely to unlock values. |
171
+ | `timing` | Unknown recording speed: `{"kind":"unknown"}`. Confirmed original speed: `unretimed` plus `source`. File FPS does not establish original speed. |
172
+ | `single_swing` | `true` only for exactly one swing. Use `false` for multiple swings. |
173
+ | `athlete_box` | Optional `[x1,y1,x2,y2]` rectangle in upright original-image pixels; needed for ambiguous athlete selection. |
174
+ | `source_mirrored` | `true`, `false`, or `null`. Records mirror status; does not flip the image. |
175
+ | `windows` | Optional reviewed swing/event ranges; see section 8. |
176
+ | `refinement` | Leave defaults for normal app use. Motion checking/refinement is already enabled; frontend smoothing is not needed for calculations. |
177
+ | `up_estimation` | Enabled by default. When `up_vector` is omitted/null, estimate camera-up from sampled scene frames. Normal users do not need to supply an angle. |
178
+
179
+ Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
180
+ `pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
181
+ Keep manual calibration overrides in a reviewed flow, not frontend guesses.
182
+ Camera-up is now estimated automatically when omitted; explicit `up_vector`
183
+ and `up_source` always take priority. Many body angles still require verified
184
+ camera stability. Camera-up estimation does not declare the camera fixed.
185
+ `up_vector: [0,-1,0]` is only an explicit camera-up approximation when an upright,
186
+ level recording supports it; it is not recovered gravity. A pitcher vector is
187
+ used once a supplied or accepted estimated vertical is available. Missing calibration can leave individual measurements
188
+ unavailable while motion and videos remain usable.
189
+
190
+ Documented constant slow motion uses:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  ```json
193
  {
194
+ "timing": {
195
+ "kind": "constant_slowdown",
196
+ "source": "Documented camera slowdown setting",
197
+ "factor": 4,
198
+ "all_captured_frames_retained": true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  }
200
  }
201
  ```
202
 
203
+ Do not declare that all captured frames were retained unless that is known.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
+ Successful upload returns **202**:
 
 
 
 
 
206
 
207
+ ```json
208
+ {
209
+ "analysis_id": "11111111111111111111111111111111",
210
+ "job_id": "11111111111111111111111111111111",
211
+ "analysis_revision": 1,
212
+ "parent_job_id": null,
213
+ "status": "queued",
214
+ "status_url": "/v1/motion-analyses/11111111111111111111111111111111",
215
+ "result_url": "/v1/motion-analyses/11111111111111111111111111111111/result",
216
+ "retention_hours": 24
217
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  ```
219
 
220
+ Save the real returned IDs and URLs with the app user's session. Use returned
221
+ URLs rather than constructing paths from artifact filenames.
 
 
 
 
 
222
 
223
+ ## 5. Poll, then fetch the manifest
224
 
225
+ **`GET {status_url}`**. Start around every 2 seconds, backing off to 5 seconds.
226
+ GPU processing can take minutes. A network timeout is not an analysis failure.
227
 
228
+ | `status` | Screen behavior |
229
+ | --- | --- |
230
+ | `uploading` | Upload is being saved. |
231
+ | `queued` | Waiting for GPU processing. |
232
+ | `processing` | Analysis running; show its current stage if present. |
233
+ | `completed` | Fetch `result_url`, then the needed artifacts. |
234
+ | `failed` | Show a useful error from `failure.reason_code`/`error`; allow retry. |
235
+ | `cancel_requested` | Cancelling; continue polling. |
236
+ | `cancelled` | Stop polling; files are removed. |
237
+
238
+ This route uses **`processing`**; the older product flow used `running`.
239
+ `progress` can be null. Its `stage`, `completed_frames`, `total_frames`, and
240
+ `elapsed_s` refer to the current stage. A stage fraction is not overall
241
+ completion. Unknown stage names should use a generic “Analyzing” label. Stages
242
+ include tracking, SAM/GVHMR reconstruction, image evidence, native refinement,
243
+ motion artifacts, and annotated videos.
244
+
245
+ **`GET {result_url}`** returns a **manifest**, not a measurement array:
246
+
247
+ | Manifest field | Frontend use |
248
+ | --- | --- |
249
+ | `schema_version` | Motion contract `1.0`; tolerate additive fields. |
250
+ | `analysis_id`, `job_id`, `analysis_revision`, `parent_job_id` | Session lineage and immutable cache identity. |
251
+ | `person_id` | Athlete track identity within this analysis; not the app account ID. |
252
+ | `pipeline.selected_model` | Actual `sam3d`/`gvhmr` selection. |
253
+ | `pipeline.measurement_definition_version` | Keep with measurements/comparisons. |
254
+ | `pipeline.refinement` | Acceptance/fallback diagnostics; acceptance does not establish anatomical accuracy. |
255
+ | `coordinates` | Axes, units, scale and separate root translation. |
256
+ | `coordinates.up_vector`, `coordinates.up_source` | Effective camera-up and provenance, in `up_vector_frame` camera axes rather than exported player axes. |
257
+ | `coordinates.up_estimation` | `provided`, `estimated`, or `unknown`; acceptance, method, source-frame diagnostics and reason codes. |
258
+ | `timing.physical_time_available` | Whether physical speeds/durations can be interpreted. |
259
+ | `skeleton.joint_order`, `skeleton.bones` | Ordered joint names and bone connections. |
260
+ | `source_video` | Source dimensions, orientation, asset ID and duration. |
261
+ | `sampling` | Source frame count and sampling policy. |
262
+ | `quality` | Usable frame count, segments and accuracy limitations. |
263
+ | `artifacts` | JSON, JSONL, source and MP4 locations/availability. |
264
+ | `expires_at` | Retention deadline. |
265
+
266
+ Never mix artifacts from different job/revision pairs. Revisions can retain the
267
+ same `analysis_id` while changing the job and its measurement results.
268
+
269
+ ## 6. Fetch artifacts and build the four groups
270
+
271
+ Artifact metadata includes `status`, `format`, `media_type`, `url`, `filename`,
272
+ `size_bytes`, `sha256`, `expires_at`, and optionally `reason_code`. An unavailable
273
+ artifact has no usable URL. Use **`url`**, not `filename`, for requests.
274
+
275
+ | Artifact key | Content / use |
276
+ | --- | --- |
277
+ | `measurements` | JSON object: `summaries[]`, `series[]`, definition version and calculation inputs. |
278
+ | `events` | JSON object: `events[]` with per-rep windows, times and reasons. |
279
+ | `motion` | JSONL/NDJSON: corrected 3D joints for each source frame. |
280
+ | `projections` | JSONL/NDJSON: corrected 2D image projections of that same motion; may be unavailable. |
281
+ | `quality` | JSON object: tracking, segments and correction diagnostics. |
282
+ | `source` | Exact uploaded bytes with original container/orientation. |
283
+ | `annotated_rotation` | Hips and shoulders video. |
284
+ | `annotated_timing` | Movement timing video. |
285
+ | `annotated_posture` | Posture and head movement video. |
286
+ | `annotated_stance` | Stance and stride video. |
287
+ | `mesh` | Unavailable: `animated_mesh_second_phase`. Render joints/bones instead. |
288
+
289
+ Group mapping:
290
+
291
+ | `series[].group` | Screen title | Video artifact |
292
  | --- | --- | --- |
293
+ | `rotation` | Hips and shoulders | `annotated_rotation` |
294
+ | `timing` | Movement timing | `annotated_timing` |
295
+ | `posture` | Posture and head movement | `annotated_posture` |
296
+ | `stance` | Stance and stride | `annotated_stance` |
297
+
298
+ The measurement response has **no `groups[]` wrapper**. Build groups from
299
+ `series[].group` and match summaries using **`rep` + `metric_id`** within the
300
+ same job/revision. Summaries include both `key` and `metric_id`; use `metric_id`
301
+ as the stable UI measurement key. See the catalogue in section 11.
302
+
303
+ Each summary supplies `label`, `value`, `unit`, `status`, `statistic`,
304
+ `reference_frame`, `baseline_frame`, `window`, `source_samples`, `quality_flags`,
305
+ `reason_code`, `uses_interpolated_input`, and `stability`, among other provenance.
306
+ Keep the statistic/reference with the number: a peak, baseline, and end-of-window
307
+ value describe different things.
308
+
309
+ Each series includes `rep`, `metric_id`, `group`, `unit`, `reference_frame`,
310
+ and `samples[]`. Samples contain `source_frame_index`, `video_time_s`,
311
+ `capture_time_s`, `value`, `status`, `reasons`, and interpolation provenance.
312
+ Use these backend values for graphs. Some event-only metrics have null curves
313
+ with `event_summary_only`; show the summary/event marker instead of inventing
314
+ a flat line from the summary.
315
+
316
+ ### Display rules
317
+
318
+ | Value/status | Display |
319
+ | --- | --- |
320
+ | Finite value, `estimated` | Number/unit with “Estimated”. |
321
+ | Finite value, `partial` | Number/unit with “Partial data”; retain its explanation. |
322
+ | Null or `unavailable` | `—` with a short reason, or omit the numeric card and retain the explanation in group details. |
323
+ | Zero | Display zero; never treat it as missing. |
324
+ | Joint `confidence: null` | Confidence was not supplied; do not convert it to 0% or 100%. |
325
+ | Missing/rejected joint or invalid projection | Skip the point/affected bone; never substitute zero coordinates. |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
+ Keep usable cards/videos visible when another value is missing. Break graphs at
328
+ null samples and invalid-data/segment gaps. An unavailable metric/artifact is not
329
+ automatically a failed job.
330
 
331
+ Suggested short reason labels:
 
 
332
 
333
+ | Reason code | User-facing wording |
334
  | --- | --- |
335
+ | `capture_time_unknown` | Recording speed was not confirmed. |
336
+ | `missing_vertical_reference` | Camera vertical reference is missing. |
337
+ | `camera_stability_unverified` | Camera stability is not verified. |
338
+ | `missing_3d_pitcher_direction` | Direction toward the pitcher is not calibrated. |
339
+ | `missing_reviewed_stride_events` | Step-start and landing frames need review. |
340
+ | `missing_ground_reference` | Ground movement is not calibrated. |
341
+ | `missing_mass_model` | Body mass distribution is not available. |
342
+ | `incomplete_peak_window` | Tracking is incomplete around the speed peak. |
343
+ | `peak_at_window_boundary` | The speed peak reaches the selected window edge. |
344
+ | `scale_unknown` | Physical distance scale is unknown. |
345
+
346
+ Use a generic fallback for other codes and preserve the exact code for support.
347
+ `stability.minimum`/`maximum` describe sensitivity to alternative smoothing
348
+ strengths **only when `stability.status === "evaluated"`**. They are not accuracy
349
+ bounds, confidence intervals, or a player score. Measurements retain
350
+ `accuracy_validated: false` in this release.
351
+
352
+ ### Automatic camera-up in the frontend
353
+
354
+ Leave `up_vector`/`up_source` omitted or null for automatic estimation. The backend
355
+ uses GeoCalib on timestamp-spaced frames, checks background scene support,
356
+ model uncertainty and agreement across frames, and only uses accepted estimates.
357
+ Both SAM and GVHMR use the same estimator and camera-coordinate convention.
358
+
359
+ Read `manifest.coordinates.up_estimation.status`:
360
+
361
+ - `estimated`: show **Estimated camera-up** and the returned source/vector.
362
+ `reliable: true` means the engineering checks passed, not a calibrated accuracy
363
+ probability. `confidence` remains null. The vector is normalized.
364
+ - `provided`: show **User-supplied camera-up**. Original inputs are preserved;
365
+ their accuracy has not been independently verified (`reliable: null`).
366
+ - `unknown`: keep camera-up unknown, show a short reason if useful, and do not
367
+ substitute a default vector. Measurements requiring vertical remain unavailable.
368
+
369
+ The vector frame is `upright_camera_x_right_y_down_z_away`. It is not in the
370
+ exported skeleton's rotated coordinate axes. Diagnostics include sample and
371
+ accepted-frame counts, temporal coverage, frame disagreement and provider
372
+ uncertainty in degrees. Per-frame candidates are diagnostic only; use the
373
+ effective `coordinates.up_vector` for display, never a rejected candidate.
374
+
375
+ Submitted inputs remain in `pipeline.inputs`; effective inputs used for numbers
376
+ are in `pipeline.calculation_inputs`. The same reference is also recorded in
377
+ the measurements/quality artifacts. A gravity estimate does not supply pitcher
378
+ direction, physical scale, a recording clock, or proof of a fixed camera.
379
+
380
+ Additional reason codes: `camera_up_provider_unavailable`,
381
+ `insufficient_reliable_frames`, `inconsistent_camera_up_across_frames`,
382
+ `insufficient_camera_up_temporal_coverage`, `camera_up_estimation_failed`, and
383
+ `automatic_up_estimation_disabled`. See [estimator details](CAMERA_UP_ESTIMATION.md).
384
+
385
+ ## 7. Play the annotated videos
386
+
387
+ Only enable a player when its artifact has `status: "available"` and a URL.
388
+ Each group video contains its skeleton/measurement overlay, with **no bottom
389
+ information panel**. `source` is the original upload, not an annotated preview.
390
+ Prefer the group artifact when the UI promises annotations.
391
+
392
+ A plain `<video src="https://...hf.space/...">` cannot attach the engine Bearer
393
+ header. Use your **authenticated app media proxy**. Native app players should
394
+ also use app authentication, not a bundled engine key.
395
+
396
+ The proxy forwards `Range` and `If-Range` and preserves the upstream status and
397
+ `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, and `ETag`.
398
+ Support `HEAD`, 206 partial responses, and 416 range errors. Stream media instead
399
+ of buffering every MP4 into app-server memory. Check ownership on every range
400
+ request.
401
+
402
+ After implementing the proxy from section 2:
403
+
404
+ ```html
405
+ <video id="rotation-video" controls playsinline preload="metadata"></video>
406
+ ```
407
 
408
+ ```js
409
+ const artifact = manifest.artifacts.annotated_rotation;
410
+ if (artifact?.status === "available" && artifact.url) {
411
+ document.querySelector("#rotation-video").src = engineProxyPath(artifact.url);
412
+ }
413
+ ```
414
 
415
+ Annotations are silent H.264 MP4s at up to 1280 pixels on the longest side.
416
+ They preserve source playback timing, including variable spacing and slow
417
+ playback. Their dimensions can differ from the source; preserve aspect ratio.
418
+ The original `source` can use a codec/container unsupported by the browser;
419
+ prefer the annotated MP4 for browser playback.
420
 
421
+ ## 8. Multiple swings, events and per-swing playback
422
 
423
+ With `single_swing: false`, automatic hand-motion analysis proposes windows.
424
+ These are **motion candidates**, not a guaranteed complete swing count. Reviewed
425
+ `windows` supply explicit boundaries. Frame indices are **zero-based, inclusive**;
426
+ rep IDs are **one-based**, local to the job.
427
 
428
+ Reviewed range example; replace every frame number with actual reviewed values:
429
 
430
+ ```json
431
+ {
432
+ "single_swing": false,
433
+ "windows": [
434
+ {"start_frame": 0, "end_frame": 119, "source": "Reviewed recording"},
435
+ {"start_frame": 150, "end_frame": 269, "source": "Reviewed recording"}
436
+ ]
437
+ }
438
  ```
439
 
440
+ Build the rep list from `events.events` entries with `type: "swing_window"` and
441
+ present `start`/`end`. Each event includes `rep`, `status`, `source`,
442
+ `source_detail`, and timestamped `start`/`end`. Other types include `baseline`,
443
+ `forward_swing_window`, `stride_start`, `foot_plant`, `hip_speed_peak`,
444
+ `shoulder_speed_peak`, `hands_speed_peak`, and `ball_contact`. Only draw events
445
+ with an actual start sample. Distinguish reviewed from estimated events.
446
+ Body landmarks do not establish bat-ball impact: `ball_contact` is currently
447
+ unavailable on this route.
448
+
449
+ **The four motion API videos cover the complete recording. This route does not
450
+ currently return a separately encoded annotated MP4 for every swing.** For a
451
+ selected rep, reuse each group video, seek to the swing window's start
452
+ `video_time_s`, and stop/loop at its end. The final included frame starts at the
453
+ event end timestamp; the exclusive stop is the next source frame's
454
+ `video_time_s`, or `source_video.duration_s` at the end of the recording.
455
+ Use the motion/projection timestamp list, not nominal FPS, to find that stop.
456
+ This is range playback in the same media, not a downloadable swing cut.
457
+
458
+ For individual downloadable annotated swing files from this motion, your app
459
+ backend must cut returned videos using the reviewed ranges, or this must be added
460
+ as a separate engine feature. Do not invent motion `/swings/{rep}/clip` URLs.
461
+ The older swing-coach API has its own clip endpoints with its own detection and
462
+ annotations.
463
+
464
+ ## 9. Interactive skeleton and synchronized graphs
465
+
466
+ Parse `motion` and `projections` as **JSONL/NDJSON**: each nonempty line is a JSON
467
+ object, not one JSON array. For larger recordings, stream/index data or parse it
468
+ in a worker rather than blocking the main UI thread.
469
+
470
+ `motion` records every decoded source frame, with every declared joint name:
471
+
472
+ - `analysis_revision`, `source_frame_index`, `source_pts`, `source_time_base`;
473
+ - elapsed `video_time_s` and `capture_time_s` or null;
474
+ - `segment_id`, `joints`, separate `root_translation`, and `frame_quality`.
475
+
476
+ Each joint has `position: [x,y,z] | null`, `status` (`estimated`, `interpolated`,
477
+ `rejected`, `missing`), `confidence`, and `reasons`. Use `skeleton.joint_order`
478
+ and `skeleton.bones`, not native model indices. Left/right are the athlete's
479
+ anatomical sides, not screen sides. Draw a bone only when both endpoints are
480
+ usable. Model-resampled `interpolated` points are explicitly labelled; they do
481
+ not supply extra independent high-speed observations.
482
+
483
+ For a 3D player, positions are hip-relative in the declared fixed frame. Read
484
+ `coordinates.axes` and `coordinates.unit`; do not assume Z-up or calibrated
485
+ metres. Any visualization rotation for Three.js/Unity must apply uniformly to
486
+ all joints. `root_translation` is separate model-estimated camera placement,
487
+ not measured ground travel. A centered skeleton viewer can leave it out;
488
+ camera-scene reconstruction adds it exactly once.
489
+
490
+ For 2D overlays, use `projections.joints[name].pixel` when both `valid` and
491
+ `in_frame` are true. These project the same corrected 3D motion; they are not
492
+ an unrelated detector's skeleton. Scale upright image pixels to the displayed
493
+ video content rectangle and account for letterboxing. Read projection
494
+ `image_width`/`image_height`; do not apply a second source rotation/mirror.
495
+ Respect `source_video` orientation metadata when displaying raw source bytes.
496
+
497
+ Synchronize video, skeleton, events and graphs using **`video_time_s`**. During
498
+ playback choose the sample at/before `video.currentTime`, using actual timestamps.
499
+ Never use `frame_index / nominal_fps` or seek media with `capture_time_s`.
500
+ Capture time is for physical rates. Hide/break motion over unusable gaps and
501
+ never interpolate across missing/rejected data or segment boundaries.
502
+ Optional interpolation between valid neighboring samples is display-only;
503
+ never recalculate submitted measurements from it.
504
+
505
+ GVHMR uses 30-Hz temporal conditioning and maps poses to source timestamps.
506
+ A 60/120-FPS upload therefore does not provide independent 60/120-Hz GVHMR
507
+ observations. Preserve `sample_spacing_ms`, `temporal_model_sample_spacing_ms`,
508
+ and interpolation labels in measurement details.
509
+
510
+ ## 10. Revisions, model comparison and retention
511
+
512
+ To compare the same video using the other model, upload no file and send:
513
+
514
+ | Form-data field | Value |
515
+ | --- | --- |
516
+ | `source_asset_id` | Completed manifest's `source_video.asset_id`. |
517
+ | `options` | `{"model":"gvhmr","annotated_videos":true}` plus recording facts from the original request. |
518
 
519
+ Exactly one of `video` and `source_asset_id` is required. A **new analysis does
520
+ not inherit original options**. To retain facts automatically, create a revision:
521
 
522
+ **`POST /v1/motion-analyses/{parent_job_id}/revisions`**, JSON body:
 
 
523
 
524
+ ```json
525
+ {
526
+ "options": {
527
+ "model": "gvhmr",
528
+ "annotated_videos": true
529
+ }
 
 
 
 
 
 
 
 
 
530
  }
531
+ ```
532
 
533
+ Unspecified inputs are inherited. The response retains `analysis_id`, creates a
534
+ new `job_id`/`analysis_revision`, and reruns inference for a model switch. The
535
+ parent stays unchanged. Poll the new returned URLs. Reviewed windows/recording
536
+ corrections also use revisions. Changing `athlete_box` requires a new analysis
537
+ using the source asset. Calibration/model changes can require full inference;
538
+ revisions are not guaranteed instant.
539
+
540
+ Cache by job/revision. Retain model, anatomical definition, reference frame,
541
+ scale, timing and recording conditions in session comparisons. SAM/MHR and
542
+ GVHMR/SMPL-X define landmarks differently; switching models is not player
543
+ improvement. Do not average their points or combine their numbers in an
544
+ unlabeled trend.
545
+
546
+ Artifacts expire according to `expires_at` and may disappear earlier on an
547
+ ephemeral Space restart. Retention defaults to 24 hours. A cached job ID/URL is
548
+ not permanent app storage: the app backend should retain required results/media
549
+ under its own retention policy. Source reuse/revisions require the original
550
+ job to still exist and be completed.
551
+
552
+ **`DELETE /v1/motion-analyses/{job_id}`** returns 202 with `cancel_requested` or
553
+ `cancelled`. Running work is stopped and files are removed. Continue polling
554
+ until cancellation settles. A browser AbortController only stops that request
555
+ or polling; it does not cancel the GPU job. Check app-user ownership before
556
+ deletion. Later cleanup can make expired/deleted jobs return 404.
557
+
558
+ ## 11. Measurement catalogue
559
+
560
+ Read each returned `label`, `unit`, `statistic`, `reference_frame`, and status.
561
+ This catalogue identifies group membership, not guaranteed availability.
562
+
563
+ | Group | `metric_id` | Unit |
564
+ | --- | --- | --- |
565
+ | rotation | `hip_heading_deg` | deg |
566
+ | rotation | `shoulder_heading_deg` | deg |
567
+ | rotation | `hip_shoulder_separation_deg` | deg |
568
+ | rotation | `hip_rotation_from_start_deg` | deg |
569
+ | rotation | `shoulder_rotation_from_start_deg` | deg |
570
+ | rotation | `hip_angular_velocity_deg_s` | deg/s |
571
+ | rotation | `shoulder_angular_velocity_deg_s` | deg/s |
572
+ | timing | `hand_speed_relative_m_s` | m/s |
573
+ | timing | `hip_peak_time_ms` | ms |
574
+ | timing | `shoulder_peak_time_ms` | ms |
575
+ | timing | `hands_peak_time_ms` | ms |
576
+ | timing | `hip_to_shoulder_ms` | ms |
577
+ | timing | `shoulder_to_hands_ms` | ms |
578
+ | posture | `forward_lean_deg` | deg |
579
+ | posture | `side_lean_deg` | deg |
580
+ | posture | `head_excursion_relative_cm` | cm |
581
+ | posture | `head_horizontal_relative_cm` | cm |
582
+ | posture | `head_vertical_relative_cm` | cm |
583
+ | posture | `head_excursion_ground_cm` | cm |
584
+ | posture | `pelvis_ground_displacement_cm` | cm |
585
+ | posture | `center_of_mass_displacement_cm` | cm |
586
+ | stance | `stance_span_cm` | cm |
587
+ | stance | `stance_width_baseline_cm` | cm |
588
+ | stance | `left_foot_heading_deg` | deg |
589
+ | stance | `right_foot_heading_deg` | deg |
590
+ | stance | `stride_relative_forward_cm` | cm |
591
+ | stance | `stride_relative_lateral_cm` | cm |
592
+ | stance | `stride_relative_length_cm` | cm |
593
+ | stance | `stride_duration_ms` | ms |
594
+ | stance | `stride_ground_length_cm` | cm |
595
+
596
+ Hand speed is wrist-midpoint speed relative to hips, not bat speed. Separation
597
+ is a signed body-line angle, not a quality score. Ground movement/centre of mass
598
+ require evidence this API does not currently reconstruct. Displayed decimals do
599
+ not establish real-world accuracy.
600
+
601
+ ## 12. Minimal browser JavaScript client
602
+
603
+ This example uses the **app backend proxy** from section 2 and your existing app
604
+ session, with no engine credential. Retain its returned job so a screen can resume
605
+ polling after a network interruption.
606
+
607
+ ```js
608
+ const APP_PROXY = "/api/baseball";
609
+ const MOTION = "/v1/motion-analyses";
610
+
611
+ function engineProxyPath(enginePath) {
612
+ if (enginePath !== MOTION && !enginePath.startsWith(MOTION + "/")) {
613
+ throw new Error("Unexpected engine route");
614
+ }
615
+ return APP_PROXY + enginePath;
616
  }
617
 
618
+ async function engineJSON(enginePath, init = {}) {
619
+ const response = await fetch(engineProxyPath(enginePath), {
620
+ ...init,
621
+ credentials: "include"
622
+ });
623
+ const body = await response.json().catch(() => null);
624
+ if (!response.ok) {
625
+ const detail = body?.detail ?? body?.error ?? `HTTP ${response.status}`;
626
+ const error = new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
627
+ error.httpStatus = response.status;
628
+ error.detail = detail;
629
+ error.retryAfter = response.headers.get("Retry-After");
630
+ throw error;
631
+ }
632
+ return body;
633
  }
634
 
635
+ async function uploadMotion(file, options, signal) {
636
+ const form = new FormData();
637
+ form.append("video", file);
638
+ form.append("options", JSON.stringify(options));
639
+ return engineJSON(MOTION, {method: "POST", body: form, signal});
640
  }
 
 
 
641
 
642
+ async function waitForMotion(job, onProgress, signal) {
643
+ let delayMs = 2000;
644
+ while (true) {
645
+ const status = await engineJSON(job.status_url, {signal});
646
+ onProgress?.(status);
647
+ if (status.status === "completed") {
648
+ return engineJSON(status.result_url ?? job.result_url, {signal});
649
+ }
650
+ if (["failed", "cancelled"].includes(status.status)) {
651
+ throw new Error(status.failure?.reason_code ?? status.error ?? status.status);
652
+ }
653
+ await new Promise(resolve => setTimeout(resolve, delayMs));
654
+ delayMs = Math.min(5000, Math.round(delayMs * 1.2));
655
  }
 
 
 
 
 
656
  }
657
 
658
+ async function fetchJSONArtifact(manifest, name, signal) {
659
+ const artifact = manifest.artifacts[name];
660
+ if (artifact?.status !== "available" || !artifact.url) return null;
661
+ if (artifact.format !== "json") throw new Error("Use a line parser for JSONL artifacts");
662
+ return engineJSON(artifact.url, {signal});
 
 
 
 
 
 
 
 
663
  }
 
664
 
665
+ function formatMetric(metric) {
666
+ if (metric.value == null || !Number.isFinite(metric.value) || metric.status === "unavailable") {
667
+ return "—";
668
+ }
669
+ return `${metric.value} ${metric.unit}`;
670
+ }
 
 
 
671
 
672
+ // On the app's upload action, using this user's recording facts:
673
+ // const job = await uploadMotion(file, options, abortController.signal);
674
+ // await saveJobForCurrentAppUser(job); // implement in your app
675
+ // const manifest = await waitForMotion(job, showProgress, abortController.signal);
676
+ // const measurements = await fetchJSONArtifact(manifest, "measurements");
677
+ // const events = await fetchJSONArtifact(manifest, "events");
678
+ // const rotationVideo = manifest.artifacts.annotated_rotation;
679
+ // video.src = engineProxyPath(rotationVideo.url); // only when available
680
+ ```
681
 
682
+ For transient network/502/503 polling failures, keep the job and resume with
683
+ backoff; this compact helper surfaces them for the app to handle. Do not
684
+ blindly repeat a POST after a timeout: it may already have created a job.
685
+ There is no upload idempotency key or job-list lookup in this contract. Your
686
+ backend should retain received job IDs before replying to its frontend.
687
 
688
+ The frontend path check is convenience, not authorization. The backend still
689
+ validates route/ownership and adds the engine key. Apply app CSRF protection
690
+ to cookie-authenticated upload, revision and delete operations.
 
 
 
691
 
692
+ ## 13. Errors and frontend acceptance checks
693
 
694
+ | HTTP status | Meaning / action |
695
  | --- | --- |
696
+ | 401 | Engine credential missing/incorrect; do not ask the player for it. |
697
+ | 404 | Unknown/wrong-flow/expired/deleted job or unknown artifact. Show an unavailable-session state. |
698
+ | 409 | Result not completed, or requested artifact unavailable. Inspect job/artifact status. |
699
+ | 413 | Upload/options exceed limits. |
700
+ | 415 | Unsupported video extension. |
701
+ | 422 | Invalid options/ranges. `detail` may be a string, object or validation-error array. |
702
+ | 429 | Queue full; respect `Retry-After`. Avoid duplicate uploads. |
703
+ | 503 | GPU/model setup not ready; refresh capabilities and back off. |
704
+ | 507 | Engine storage insufficient; surface a service issue. |
705
+ | 500 | Server/integrity failure; retain the job ID for support. |
706
+
707
+ The Space proxy can return non-JSON 502/503 during wake-up/restart. Handle HTTP
708
+ status even when JSON parsing fails. Preserve `failure.code`,
709
+ `failure.reason_code`, `failure.error_type`, and `error` for support without
710
+ showing raw internal logs to players.
711
+
712
+ Before shipping the frontend, verify:
713
+
714
+ - SAM/GVHMR selection uses the same upload flow and the actual returned model
715
+ labels the result.
716
+ - One-swing and multiple-window results render per rep, with correct range
717
+ seeking inside each full group video.
718
+ - All four annotated videos play and seek through the app media proxy.
719
+ - Cards display zero, label estimated/partial numbers, and keep available data
720
+ visible when another metric is null.
721
+ - Skeleton, graphs and events follow source timestamps; invalid points/gaps
722
+ are not replaced with invented coordinates or connected curves.
723
+ - Model switches/revisions do not display stale cached artifacts as new results.
724
+ - Polling survives leaving/resuming the screen and temporary network errors.
725
+ - Cancellation, expiry and unavailable models have clear app states.
726
+ - One app user cannot request another user's job, source, JSON or videos.
727
+
728
+ Backend details and coordinate formulas: [Motion-player API](MOTION_PLAYER_API.md).
729
+ Model setup: [GVHMR setup](GVHMR_SETUP.md). Legacy coaching:
730
+ [SAM batting API](SAM_BATTING_API.md) and
731
+ [swing-coach integration](LEGACY_SWING_COACH_INTEGRATION.md).
 
 
 
 
 
 
 
 
 
 
 
docs/CAMERA_UP_ESTIMATION.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Automatic camera-up estimation
2
+
3
+ Motion API 1.13.0 · 19 October 2026
4
+
5
+ `POST /v1/motion-analyses` estimates camera-up when `up_vector` is omitted/null.
6
+ The implementation is shared by SAM 3D Body and GVHMR. Supplied vectors and sources
7
+ always take priority, even if the estimator is unavailable. Existing SAM/coaching
8
+ API contracts retain their processing paths.
9
+
10
+ ## Provider and coordinates
11
+
12
+ Provider: [GeoCalib, cvg/ETH Zurich](https://github.com/cvg/GeoCalib), revision
13
+ `1dedb29f94fc11b896c5f572005978aeebccd67f`. Official v1.0 pinhole weights:
14
+ `86d6aeacd8bbd974c59ce39f61854e00d36911c732ad89be471476fd708722ac` (SHA-256).
15
+ Code: Apache-2.0. Weights: CC-BY-4.0, Copyright 2024 ETH Zurich. No model weights
16
+ were modified. See the provider's `LICENSE` and `LICENSE-WEIGHTS`.
17
+
18
+ GeoCalib's `Gravity.vec3d` is already camera-up in x-right/y-down/z-away axes:
19
+ `Gravity.from_rp(0,0)` is `[0,-1,0]`. Do not negate it. Frames use the same
20
+ orientation correction as body inference. A supplied intrinsic/distortion model
21
+ rectifies only estimator input pixels to a centred equal-focal pinhole image,
22
+ without rotating its optical/camera basis. The source video, supplied calibration,
23
+ body intrinsics and output projections are not rewritten by this stage.
24
+
25
+ The standard Docker image installs GeoCalib in the existing isolated Torch
26
+ runtime and bakes the checksummed checkpoint. No provider credentials or remote
27
+ video/image upload is involved. Inference is offline, CUDA, FP32 with TF32
28
+ disabled; NMF initialization uses seed 0 per frame. Setup verifies offline model
29
+ construction. Missing setup or inference failure safely leaves camera-up unknown.
30
+ Capabilities expose `automatic_camera_up.configured` and the method/frame.
31
+
32
+ ## Acceptance
33
+
34
+ Defaults sample seven distinct frames spread over original video timestamps.
35
+ At least three reliable distinct images must span 75% of playback duration.
36
+ The selected athlete's expanded box is excluded from support diagnostics.
37
+ Sparse learned up/latitude confidences are relative image weights, not detection
38
+ probabilities. Checks require textured background, distributed effective support,
39
+ agreement between fitted geometry and predicted fields, positive finite gravity
40
+ covariance, and model-reported gravity uncertainty no greater than five degrees.
41
+ At least 80% of credible frame vectors must agree within three degrees; no sign
42
+ flipping forces consensus. A final mean is normalized and rechecked.
43
+
44
+ All gates appear in `options.up_estimation` and returned settings. They are
45
+ configurable engineering gates, not independently validated error limits. A
46
+ consistent learned prediction can still be wrong. No confidence percentage or
47
+ calibrated accuracy interval is invented. Unmodelled lens distortion, ambiguous
48
+ scenes, unstable camera orientation, inadequate coverage, textureless background,
49
+ or numerical uncertainty can leave the result unknown.
50
+
51
+ ## Response and calculation provenance
52
+
53
+ Read `coordinates.up_vector`, `up_source`, `up_vector_frame`, and
54
+ `up_estimation`. The latter contains status (`provided`, `estimated`, `unknown`),
55
+ `method`, `applied`, `reliable`, reason codes and diagnostics. `applied` means
56
+ selected as a calculation input, not that all measurements became eligible.
57
+ User-provided inputs have `reliable: null`; they are not independently checked.
58
+ Rejected per-frame candidates are diagnostic only, never effective up vectors.
59
+
60
+ `pipeline.inputs` preserves the exact validated submission. Reliable estimates
61
+ are added to separate `pipeline.calculation_inputs`. Measurements, orientation,
62
+ series and public-artifact reproduction use those effective inputs. Metrics
63
+ depending on estimated vertical carry `vertical_reference_estimated_from_images`.
64
+ Quality and measurement artifacts also include the reference; raw per-frame
65
+ worker files are private and are not artifact download endpoints.
66
+
67
+ Camera stability, physical timing, scale, reviewed events and field/pitcher
68
+ direction keep their existing eligibility checks. Camera-up estimation does not
69
+ establish any of them. Scene motion can still contradict a fixed-camera claim
70
+ and withhold dependent metrics. Revisions re-estimate when the source input still
71
+ has no explicit vector; they never overwrite an immutable parent result.
72
+
73
+ Disable explicitly with `{"up_estimation":{"enabled":false}}`. All numerical
74
+ defaults and validation bounds are published in the motion input schema.
docs/LEGACY_SWING_COACH_INTEGRATION.md ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # App integration: swing analysis, coaching and swing clips
2
+
3
+ > This guide covers the existing swing-coach `/product` flow. For the current SAM/GVHMR motion player, use [the frontend integration guide](APP_API_INTEGRATION.md). These APIs have separate contracts.
4
+
5
+ For the coding agent updating the app's previous engine → separate coach flow.
6
+
7
+ **Engine base URL:** `https://modventures-baseball-engine.hf.space`
8
+
9
+ Use one upload and one combined result. The engine now runs the coach internally.
10
+ The result includes measurements, the coach's existing response, experimental
11
+ video feedback for the three features, and a playable clip for each detected swing.
12
+
13
+ ```text
14
+ App → app backend → upload video to engine → poll job
15
+ ↓
16
+ combined product + individual swing clips
17
+ ↓
18
+ app shows swing cards and feedback
19
+ ```
20
+
21
+ ## 1. Change the old integration
22
+
23
+ | Previous integration | Current integration |
24
+ | --- | --- |
25
+ | Upload to `POST /v1/analyses` | Upload to `POST /v1/swing-coach/analyses` |
26
+ | Fetch `/coach-payload`, then call the standalone coach | Fetch `/product`; coaching is already included |
27
+ | Read only the coach response | Read `product.coaching` **and** `product.visual_review` |
28
+ | Use frame ranges or still images as swing previews | Read `product.swings`; each available clip has an MP4 endpoint |
29
+ | App receives coach response version `2.0` | That same response remains inside `product.coaching` |
30
+
31
+ For this new flow, remove the extra standalone coach request. Do not pass the
32
+ whole product into the old coach input: it already contains that coach's output.
33
+
34
+ **Do not hide the entire result when `coaching.score.value` is null or
35
+ `coaching.focus` is empty.** The experimental video observations and swing clips
36
+ can still be available. Fetching `/coaching` alone also misses the new video
37
+ feedback and clips; fetch `/product` for the app screen.
38
+
39
+ Old engine upload/result routes and standalone coach routes remain available.
40
+ Legacy measurements stay at schema `2.0`; timing defaults to `3.0`, with `3.1`
41
+ when evidence is requested. The combined product is now **`schema_version: "1.1"`**.
42
+ Its new `swings` and `swings_url` fields are additive to product `1.0`. Accept
43
+ both product versions and treat a missing `swings` field as an older result.
44
+
45
+ ## 2. Authentication and app backend
46
+
47
+ Every engine `/v1/...` request uses:
48
+
49
+ ```http
50
+ Authorization: Bearer <ENGINE_SERVER_KEY>
51
+ ```
52
+
53
+ Store this key in your **app backend's environment**, for example
54
+ `BASEBALL_ENGINE_API_KEY`. Use the same key for uploads, status, JSON results,
55
+ images and MP4 clips. The old standalone coach's `X-API-Key` header is not used
56
+ for this combined flow.
57
+
58
+ The Gemini key stays in the engine's `GOOGLE_API_KEY` secret. The app does not
59
+ send it. Browser uploads should go through your app backend: the engine does
60
+ not enable cross-origin browser requests.
61
+
62
+ Authenticate your app user and store which user owns each returned `job_id`.
63
+ Check that ownership before proxying status, results, clips, frames, retry or
64
+ delete. The engine's shared key does not provide per-user access control.
65
+
66
+ ## 3. Upload one video
67
+
68
+ **`POST /v1/swing-coach/analyses`**
69
+
70
+ Body: **multipart form data**, with these two fields:
71
+
72
+ | Field | Form-data type | Value |
73
+ | --- | --- | --- |
74
+ | `video` | File | The original video file |
75
+ | `options` | Text | A JSON string containing the recording facts |
76
+
77
+ Example options for a known right-handed batter, with the ball coming from the
78
+ right side of the image and a fixed camera facing the batter's chest:
79
+
80
+ ```json
81
+ {
82
+ "measurement_backend": "2d",
83
+ "coaching_mode": "poc_video",
84
+ "view": "face_on",
85
+ "handedness": "right",
86
+ "pitcher_direction": "image_right",
87
+ "practice_type": "front_toss",
88
+ "camera_stability": "fixed_verified",
89
+ "timing": {
90
+ "kind": "unretimed",
91
+ "source": "Uploader confirms original recording; no speed changes"
92
+ },
93
+ "single_swing": false
94
+ }
95
+ ```
96
+
97
+ These are example facts, not defaults to apply to every player. Ask the player
98
+ for the facts the app does not know.
99
+
100
+ | Option | Meaning and accepted values |
101
+ | --- | --- |
102
+ | `measurement_backend` | Use `"2d"` for this POC. It runs pose and bat/ball models on GPU without SAM. |
103
+ | `coaching_mode` | `"poc_video"` includes the coach and sampled-image Gemini review; this is the new route's default. `"measurements_only"` includes the existing coach without Gemini images. `"disabled"` produces measurements and clips without a product. |
104
+ | `view` | `"face_on"` when the camera faces the batter's chest; otherwise `"unknown"`. Do not infer this only because a person is visible. |
105
+ | `handedness` | `"left"`, `"right"`, or `null`: the side the player bats from. |
106
+ | `pitcher_direction` | `"image_left"`, `"image_right"`, or `null`: direction toward the pitcher/tee in the image, not the player's handedness. |
107
+ | `practice_type` | `"tee"`, `"soft_toss"`, `"front_toss"`, `"live"`, `"machine"`, or `"unknown"`. |
108
+ | `camera_stability` | `"fixed_verified"` if the camera stays still, `"moving"` if it moves, otherwise `"unknown"`. |
109
+ | `timing` | `{"kind":"unknown"}` if speed changes are uncertain. Use documented `"unretimed"` only when the recording has no speed changes. |
110
+ | `single_swing` | **`false` for a video containing multiple swings.** `true` treats the entire recording as one supplied swing range; it does not split it. |
111
+
112
+ Unknown recording facts are accepted by the combined route. They can make
113
+ measurements unavailable, so show upload `warnings` instead of silently changing
114
+ the facts. The strict `/v1/load-timing/analyses` route can reject missing timing
115
+ settings; it is not the recommended upload route for the combined app screen.
116
+
117
+ If the recording is documented constant slow motion, the supported timing shape is:
118
+
119
+ ```json
120
+ {
121
+ "kind": "constant_slowdown",
122
+ "source": "Documented camera recording setting",
123
+ "factor": 4,
124
+ "all_captured_frames_retained": true
125
+ }
126
+ ```
127
+
128
+ Do not set that flag if frames were removed or the slowdown is uncertain.
129
+
130
+ If your app already knows the cuts, it may supply `reps` as sorted,
131
+ non-overlapping, **zero-based inclusive** frame ranges:
132
+
133
+ ```json
134
+ {
135
+ "single_swing": false,
136
+ "reps": [
137
+ {"start_frame": 0, "end_frame": 119},
138
+ {"start_frame": 120, "end_frame": 239}
139
+ ]
140
+ }
141
+ ```
142
+
143
+ Omit `reps` to let the engine detect swings. Do not send `single_swing: true`
144
+ together with `reps`. Only send ranges that fit the actual source video.
145
+
146
+ Successful upload returns **HTTP 202**, including:
147
+
148
+ ```json
149
+ {
150
+ "job_id": "0123456789abcdef0123456789abcdef",
151
+ "status": "queued",
152
+ "status_url": "/v1/analyses/0123456789abcdef0123456789abcdef",
153
+ "product_url": "/v1/analyses/0123456789abcdef0123456789abcdef/product",
154
+ "swings_url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings",
155
+ "coaching_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coaching",
156
+ "result_url": "/v1/analyses/0123456789abcdef0123456789abcdef/result",
157
+ "coach_payload_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coach-payload",
158
+ "load_timing_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing",
159
+ "load_timing_evidence_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing?include_evidence=true",
160
+ "warnings": []
161
+ }
162
+ ```
163
+
164
+ The job ID here is illustrative. Save the real ID returned by your upload.
165
+ All returned URLs are relative to the engine base URL.
166
+
167
+ ## 4. Poll the job, then fetch the product
168
+
169
+ **`GET /v1/analyses/{job_id}`**
170
+
171
+ Poll about every two seconds; back off during a long wait. An upload response
172
+ does not mean analysis has finished. GPU work can take several minutes.
173
+
174
+ | Job status | App behavior |
175
+ | --- | --- |
176
+ | `queued` | Show “Waiting to analyze”. |
177
+ | `running` | Show “Analyzing”, optionally with the current `progress.stage`. |
178
+ | `completed` | Fetch `product_url`, then render the result. |
179
+ | `failed` | Show the returned `error`; allow a new upload. |
180
+ | `cancel_requested` | Show “Cancelling” and continue polling. |
181
+ | `cancelled` | Stop polling; the result files are removed. |
182
+
183
+ `progress` can be null. Stages include decoding, pose, measurements, tracking,
184
+ `swing_clips`, coaching and complete. `completed_frames`, `total_frames` and
185
+ `stage_progress` describe the current stage, not the whole job. Do not present
186
+ a stage's percentage as an overall completion percentage.
187
+
188
+ Preserve the job ID if the user leaves the screen or a polling request fails;
189
+ resume polling rather than uploading the same video again automatically.
190
+
191
+ Once complete:
192
+
193
+ **`GET /v1/analyses/{job_id}/product`**
194
+
195
+ | Product field | What the app uses it for |
196
+ | --- | --- |
197
+ | `schema_version` | Product version `"1.1"`; also accept older `"1.0"`. |
198
+ | `session_id` | Same ID as the analysis job. |
199
+ | `discipline` | `"hitting"`. |
200
+ | `coaching_mode` | The requested mode. |
201
+ | `swings` | Every detected/supplied rep, with its boundaries and clip metadata. |
202
+ | `swings_url` | Separate swing-list endpoint, if needed. |
203
+ | `measurements` | Existing `2.0` per-rep nine-measurement payload. |
204
+ | `timing` | `3.1` per-rep timing, event intervals, context and reason codes. |
205
+ | `coaching` | Existing coach response, `response_version: "2.0"`. |
206
+ | `visual_review` | Experimental observations, separate visual rubric score and optional priority/drill for the three features. |
207
+ | `evidence` | Retained sampled frame images and review coverage. |
208
+
209
+ There is no second upload or separate endpoint for each of the three feedback
210
+ features. They are returned together in `visual_review.features`.
211
+
212
+ ## 5. Show an individual video for each swing
213
+
214
+ `product.swings` contains entries shaped like this. Numbers and checksum below
215
+ are illustrative, not a real downloadable recording:
216
+
217
+ ```json
218
+ {
219
+ "rep": 1,
220
+ "start_frame": 0,
221
+ "end_frame": 119,
222
+ "boundary_method": "automatic_2d_hand_motion_candidate",
223
+ "boundary_accuracy_validated": false,
224
+ "source_start_playback_s": 0.0,
225
+ "source_end_playback_s": 3.966667,
226
+ "clip": {
227
+ "status": "available",
228
+ "reason_code": null,
229
+ "url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings/1/clip",
230
+ "content_type": "video/mp4",
231
+ "duration_s": 4.0,
232
+ "frame_count": 120,
233
+ "width": 1280,
234
+ "height": 720,
235
+ "has_audio": false,
236
+ "overlay": true,
237
+ "size_bytes": 524288,
238
+ "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
239
+ }
240
+ }
241
+ ```
242
+
243
+ Build the swing list from `swings`, ordered as returned. Labels are “Swing 1”,
244
+ “Swing 2”, etc. Rep IDs are **one-based**; source frame IDs are **zero-based**.
245
+
246
+ - `start_frame` and `end_frame` include both endpoint frames.
247
+ - `boundary_method` is `automatic_2d_hand_motion_candidate`, `caller_supplied`,
248
+ or `caller_declared_single_swing` for the current engine.
249
+ - Automatic cuts are candidates. Detection may miss/merge movements; clips do
250
+ not establish that every actual swing was found.
251
+ - New clips use the same overlay renderer as the Colab `previews` folder:
252
+ green body points/skeleton, orange toe/heel points, source frame numbers and
253
+ estimated event labels. `clip.overlay: true` identifies annotated previews.
254
+ A body-based contact event is labelled **estimated contact proxy**; it is not
255
+ confirmed bat-ball impact. Missing joints/events are not drawn or invented.
256
+ If a selected 3D backend produced projections, the clip also shows purple
257
+ projected joints and red disagreement connectors at those sampled frames.
258
+ The default 2D backend requires no SAM to draw the body skeleton.
259
+ - The clips are upright H.264 MP4s, resized to at most 1280 pixels on the longest side,
260
+ with at most one pixel of padding for odd dimensions. They have **no audio**.
261
+ - Every source frame in the range is retained. Each clip starts at playback
262
+ time zero and preserves the source's variable frame spacing and playback
263
+ speed. An uploaded slow-motion video stays slow motion in the clip.
264
+ - Capture-time measurements and clip playback time are separate clocks.
265
+ `source_end_playback_s` is the last frame's timestamp; `duration_s` also
266
+ includes that last frame's display duration.
267
+
268
+ The clip endpoint is:
269
+
270
+ **`GET /v1/analyses/{job_id}/swings/{rep}/clip`**
271
+
272
+ It requires the same Bearer key and returns `video/mp4`. It supports normal GET
273
+ (`200`), single byte ranges (`206`), suffix/open-ended ranges, and HEAD. Invalid
274
+ or unsatisfiable byte ranges return `416` with `Content-Range: bytes */<size>`.
275
+ Multiple ranges are unsupported. `Accept-Ranges`, `Content-Length`, `ETag` and
276
+ `Content-Range` on partial responses support player seeking.
277
+
278
+ **Use an app-backend media proxy for playback.** Browser `<video src>` cannot
279
+ attach the engine's Bearer header. The proxy should authenticate the app user,
280
+ check job ownership, add the engine key, forward `Range`/`If-Range`, and stream
281
+ the response without buffering the whole video. Pass through the response
282
+ status and media/range headers. Never put the engine key in the video URL.
283
+
284
+ For a small internal browser test, fetching the authenticated clip into a Blob
285
+ and setting `video.src = URL.createObjectURL(blob)` also works. Revoke the Blob
286
+ URL when the result is replaced. This downloads the entire clip first; the
287
+ backend proxy is the preferred app integration.
288
+
289
+ For a separate swing-list request:
290
+
291
+ **`GET /v1/analyses/{job_id}/swings`** returns:
292
+
293
+ ```text
294
+ schema_version: "1.0" # This is the swing-list version, not the product version.
295
+ session_id: job ID
296
+ swings: same array as product.swings
297
+ notice: boundary/timing/format explanation
298
+ ```
299
+
300
+ New jobs on the legacy upload routes also create this manifest and clips.
301
+ Older completed jobs cannot create clips after their original upload was
302
+ removed. Their swing endpoint returns `409`; upload again to create clips.
303
+ Clips from before the overlay update stay plain (`overlay: false` or missing).
304
+ Upload again to generate annotated previews. Existing `clip.url` playback paths
305
+ and authentication are unchanged; the mobile app does not need to draw joints.
306
+ Gemini still receives unannotated original images, not these display overlays.
307
+
308
+ If a particular clip cannot be exported, its rep remains in `swings` with
309
+ `clip.status: "unavailable"`, a `reason_code`, and `url: null`. Hide that rep's
310
+ player and show “Clip unavailable”; retain its measurements and feedback.
311
+ Reasons include missing/invalid source timestamps, source mismatch,
312
+ unavailable last-frame duration, and `clip_export_failed`. An empty `swings`
313
+ array means no rep was detected; do not invent a swing card.
314
+
315
+ ## 6. Match each swing to its measurements and feedback
316
+
317
+ Join by **`rep`**, not by array position:
318
+
319
+ ```javascript
320
+ const cards = (product.swings ?? []).map(swing => ({
321
+ ...swing,
322
+ measurements: product.measurements.reps.find(r => r.rep === swing.rep) ?? null,
323
+ timing: product.timing.reps.find(r => r.rep === swing.rep) ?? null,
324
+ observations: product.visual_review.features.filter(f => f.rep === swing.rep)
325
+ }));
326
+ ```
327
+
328
+ The current Gemini review returns **three feature observations for the session**,
329
+ each referring to one rep. It does not promise all three observations for every
330
+ swing. The configured default reviews sampled images from at most six reps;
331
+ **clips are exported for all detected reps**, including unreviewed ones.
332
+ Use `evidence.reviewed_reps` and `evidence.total_reps` to show that coverage.
333
+ Label a swing without a visual observation “Not individually reviewed” rather
334
+ than copying another swing's advice onto it.
335
+
336
+ ### Three feedback cards
337
+
338
+ When `visual_review.status` is `"completed"`, render its features:
339
+
340
+ | `feature.key` | App label | Text |
341
+ | --- | --- | --- |
342
+ | `load_timing` | Load and timing | `feature.observation` |
343
+ | `hip_shoulder_separation` | Hips and shoulders | `feature.observation` |
344
+ | `bat_path_contact` | Bat path and contact | `feature.observation` |
345
+
346
+ New reviews include `visual_review.text_style_version: "concise-observations-v1"`.
347
+ The prompt asks for one or two complete sentences, at most thirty-five words per
348
+ observation. Text describes the visible body part, movement direction and order,
349
+ with a brief specific limitation when necessary. Render `observation` as returned;
350
+ do not cut it mid-sentence. The numerical measurements and score rules are unchanged.
351
+
352
+ Each feature also contains `status` (`"observed"` or `"unclear"`), `rep`,
353
+ `evidence_frame_ids`, and `ball_interaction_visible`. Show unclear observations
354
+ as uncertainty, not as a diagnosed problem. Label this section “Experimental
355
+ video feedback”; `accuracy_validated` and `judgment_eligible` remain false.
356
+
357
+ `ball_interaction_visible` is the visual review's interpretation. It does not
358
+ change `timing.reps[].outcome` into a measured hit or turn an unavailable timing
359
+ number into a measured value. Hips/shoulders feedback describes visible turning
360
+ order, not a measured 3D separation angle. No validated score against exact pitch
361
+ location is supplied by this one-camera visual review.
362
+
363
+ When `visual_review.status` is `"unavailable"`, show its safe `message` or
364
+ `reason_code`. Keep showing clips, supported measurements and `coaching`.
365
+
366
+ ### Experimental video score
367
+
368
+ Show **`product.visual_review.score`** separately from the original Mechanics
369
+ score in `coaching.score`. When its `status` is `"available"` and `value` is
370
+ non-null, display its `name` ("Experimental video score"), `value / max_value`,
371
+ `explanation` and per-swing `rep_scores` matched by `rep`. Zero is a valid score;
372
+ use `value !== null`, not a truthiness check. If unavailable, hide the number
373
+ or show its explanation. Keep the rest of the result visible.
374
+
375
+ The model chooses fixed Clear/Mixed/Needs practice grades; the server calculates
376
+ points. A swing needs two rateable features from that same swing. Unclear
377
+ features are excluded, not graded zero. Only `scored_reps` contribute to the
378
+ root score; it does not rate every swing or the player's overall ability.
379
+ Both `accuracy_validated` and `judgment_eligible` remain false. See
380
+ [the scoring guide and full fields](EXPERIMENTAL_VIDEO_SCORE.md).
381
+
382
+ ### Practice suggestion
383
+
384
+ If both `visual_review.priority` and `visual_review.drill` exist, show:
385
+
386
+ ```text
387
+ Why: visual_review.priority.reason
388
+ Drill: visual_review.drill.name
389
+ How: visual_review.drill.instructions
390
+ Cue: visual_review.drill.cue
391
+ ```
392
+
393
+ This is one experimental session suggestion, not one drill for every swing.
394
+ If no visual suggestion exists, your previous `coaching.drill` display can be
395
+ used when non-null (`name`, `how`, `cue`). Otherwise hide the drill area.
396
+
397
+ ### Timing and older coach fields
398
+
399
+ For a plain-language timing summary, keep using `coaching.timing.summary`,
400
+ `observations[].text`, `unavailable[].text` and `data_quality` when present.
401
+ For each swing's actual four values, read `timing.reps[].metrics` by key:
402
+
403
+ | Key | Label |
404
+ | --- | --- |
405
+ | `load_to_swing_ms` | Preparation to forward swing |
406
+ | `foot_down_to_swing_ms` | Front foot down to forward swing |
407
+ | `swing_duration_ms` | Forward swing to contact/closest approach |
408
+ | `early_late_shift_ms` | Estimated timing shift needed to meet the ball |
409
+
410
+ Render a number only when `value` is non-null, with its `status`/`confidence`.
411
+ Use “Unavailable” with the `note`/`reason_code` for unclear metrics, and “Not
412
+ applicable” when stated. Null is not zero. Keep signed foot-down differences;
413
+ negative means the swing began before the foot landed.
414
+
415
+ The original `coaching.summary`, `score`, `focus`, `strengths`, `drill`, and
416
+ `data_quality` remain available in the same coach response shape. A null score
417
+ must stay unavailable. Use the separate `visual_review.score` for the experimental
418
+ visual rating; do not put it into `coaching.score` or fill missing measurements.
419
+
420
+ ### Evidence frames and seeking inside a clip
421
+
422
+ `evidence.frames[]` includes `frame`, `reps`, `url`, `playback_t_s`,
423
+ `capture_t_s`, `athlete_box` and `sha256`. Images use
424
+ `GET /v1/analyses/{job_id}/frames/{frame}` and require Bearer authentication.
425
+ Match `evidence_frame_ids` to this list, not to array indices.
426
+
427
+ For a frame belonging to a swing, the clip's local frame index is:
428
+
429
+ ```text
430
+ local_frame = source_frame - swing.start_frame
431
+ clip_seek_seconds = evidence_frame.playback_t_s - swing.source_start_playback_s
432
+ ```
433
+
434
+ Use the playback timestamps for seeking; do not divide capture milliseconds
435
+ by 1000 and assume they are clip times. Check the frame belongs to the swing
436
+ and both timestamps are available. Capture-time intervals remain in
437
+ `timing.reps[].events`; they describe uncertainty, not exact measured contact.
438
+
439
+ ## 7. Request examples in application code
440
+
441
+ The frontend below calls **your app's authenticated backend proxy**, which maps
442
+ `/api/baseball/v1/...` onto engine `/v1/...`. Adapt the prefix to your app. The
443
+ browser never receives the engine key.
444
+
445
+ ```javascript
446
+ async function uploadSwingVideo(file, recordingFacts, signal) {
447
+ const form = new FormData();
448
+ form.append("video", file);
449
+ form.append("options", JSON.stringify({
450
+ ...recordingFacts,
451
+ measurement_backend: "2d",
452
+ coaching_mode: "poc_video"
453
+ }));
454
+ const response = await fetch("/api/baseball/v1/swing-coach/analyses", {
455
+ method: "POST", body: form, signal
456
+ });
457
+ // Let fetch set the multipart boundary; do not set Content-Type manually.
458
+ if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
459
+ return response.json();
460
+ }
461
+
462
+ async function readAnalysis(jobId, signal) {
463
+ const response = await fetch(`/api/baseball/v1/analyses/${jobId}`, { signal });
464
+ if (!response.ok) throw new Error(`Status failed: ${response.status}`);
465
+ return response.json();
466
+ }
467
+
468
+ async function readProduct(jobId, signal) {
469
+ const response = await fetch(`/api/baseball/v1/analyses/${jobId}/product`, { signal });
470
+ if (!response.ok) throw new Error(`Result failed: ${response.status}`);
471
+ return response.json();
472
+ }
473
+
474
+ // After a completed status, each available clip can use your same-origin proxy:
475
+ function appClipUrl(jobId, swing) {
476
+ return `/api/baseball/v1/analyses/${jobId}/swings/${swing.rep}/clip`;
477
+ }
478
+ ```
479
+
480
+ Backend-only example for an engine request, using Node's built-in fetch:
481
+
482
+ ```javascript
483
+ const ENGINE_ORIGIN = "https://modventures-baseball-engine.hf.space";
484
+
485
+ async function engineRequest(relativePath, init = {}) {
486
+ const url = new URL(relativePath, ENGINE_ORIGIN);
487
+ if (url.origin !== ENGINE_ORIGIN || !url.pathname.startsWith("/v1/")) {
488
+ throw new Error("Unexpected engine path");
489
+ }
490
+ const key = process.env.BASEBALL_ENGINE_API_KEY;
491
+ if (!key) throw new Error("Engine key not configured");
492
+ const headers = new Headers(init.headers);
493
+ headers.set("Authorization", `Bearer ${key}`);
494
+ return fetch(url, { ...init, headers, redirect: "error" });
495
+ }
496
+
497
+ // Inside your authenticated/ownership-checked media route:
498
+ // 1. Validate jobId as 32 lowercase hex characters and rep as a positive integer.
499
+ // 2. Confirm the logged-in user owns that job.
500
+ // 3. Construct the path yourself; do not accept an arbitrary upstream URL.
501
+ // 4. Forward only supported request headers such as Range and If-Range.
502
+ // 5. Stream upstream.body using your framework's Web-to-Node stream adapter.
503
+ async function fetchClipForProxy(jobId, rep, requestHeaders) {
504
+ const headers = new Headers();
505
+ for (const name of ["Range", "If-Range"]) {
506
+ const value = requestHeaders.get(name);
507
+ if (value) headers.set(name, value);
508
+ }
509
+ return engineRequest(`/v1/analyses/${jobId}/swings/${rep}/clip`, { headers });
510
+ }
511
+ ```
512
+
513
+ The media proxy must pass through `200`, `206` and `416`, plus `Content-Type`,
514
+ `Content-Length`, `Content-Range`, `Accept-Ranges`, `ETag` and `Cache-Control`.
515
+ Do not convert every upstream response to HTTP 200. Support HEAD if the app's
516
+ player uses it. Forward authenticated JSON error responses for failed requests.
517
+
518
+ ## 8. Retry, cancel and retain results
519
+
520
+ **Retry optional video feedback:**
521
+ `POST /v1/analyses/{job_id}/video-review`, no request body.
522
+
523
+ This returns the updated whole product. It reuses retained images and keeps
524
+ the measurements and swing clips. It does not repeat pose inference. A completed
525
+ review with the current visual-scoring rubric and wording style is returned unchanged, without
526
+ another Gemini call. An older completed review with retained frames can be
527
+ explicitly upgraded once using this route. An unavailable review
528
+ can be retried; a genuine retry consumes Gemini quota. Allow a longer request
529
+ timeout for this synchronous route and show “Retrying video feedback”. Do not
530
+ retry it continuously on every poll. No retained images returns `409`.
531
+
532
+ **Cancel/delete:** `DELETE /v1/analyses/{job_id}`, returning HTTP 202.
533
+ Running jobs first return `cancel_requested`; completed jobs become cancelled
534
+ and their JSON, images and clips are removed.
535
+
536
+ **Storage:** default engine retention is 24 hours; check `/v1/capabilities` for
537
+ the actual value. Hugging Face ephemeral storage can disappear during rebuilds
538
+ or restarts. Clip URLs are authenticated engine resources, not permanent media
539
+ hosting URLs. After completion, copy the product and each available clip into
540
+ your app's persistent storage if the user should revisit sessions later. Keep
541
+ rep IDs with those copies. An engine rebuild can erase jobs before 24 hours.
542
+
543
+ ## 9. Errors and limits
544
+
545
+ | HTTP status | Meaning |
546
+ | --- | --- |
547
+ | `401` | Invalid/missing engine Bearer key. |
548
+ | `404` | Job, rep or evidence frame not found. |
549
+ | `409` | Result not complete, older artifact missing, or requested clip unavailable. Check `detail`. |
550
+ | `413` | Upload/options/request too large. |
551
+ | `415` | Unsupported video extension. |
552
+ | `416` | Invalid/unsupported/unsatisfiable byte range. |
553
+ | `422` | Bad options, missing upload field, empty file, or invalid explicit ranges. |
554
+ | `429` | Queue, upload slots or review already busy. Respect `Retry-After` when provided. |
555
+ | `500` | Stored artifact failed integrity/structure checks, or review could not be saved. |
556
+ | `503` | GPU not ready or requested server component unavailable. |
557
+ | `507` | Insufficient engine storage. |
558
+
559
+ Errors use `{"detail": ...}`; `detail` can be a string, object or validation
560
+ list. Parse safely. A job can later fail with `error` codes such as
561
+ `invalid_video_or_capture`, `inference_failed`, `job_timeout`, or `worker_error`.
562
+ Optional Gemini failure is instead reported within `visual_review`; it does
563
+ not automatically make the analysis job fail.
564
+
565
+ Default limits: 512 MiB upload, 120 seconds of playback, 7200 decoded frames,
566
+ 8,294,400 pixels per source frame. Supported extensions: `.mp4`, `.mov`, `.mkv`,
567
+ `.avi`, `.webm`. Limits can be configured; read `/v1/capabilities` rather than
568
+ assuming these values forever.
569
+
570
+ Public `/healthz` checks liveness; `/readyz` checks GPU readiness and reports
571
+ visual model configuration/provider status. `/docs` serves interactive engine
572
+ API documentation. Authenticated `/v1/input-schema` and `/v1/swings-schema`
573
+ return the current input and swing-list schemas.
574
+
575
+ ## 10. Integration acceptance checks
576
+
577
+ - Upload a multi-swing video with `single_swing: false`; store the returned job
578
+ ID and poll it to completion without sending a second coach request.
579
+ - Show all returned swing entries, each with its own rep ID and playable clip
580
+ when available. Test seeking, and check HTTP 206 through the media proxy.
581
+ - Match each swing's timing/measurements by `rep`; attach only visual features
582
+ that cite that rep. Show review coverage for unreviewed swings.
583
+ - Show the three experimental feedback cards even when the older coach's score
584
+ and focus are unavailable.
585
+ - Handle unclear/null metrics, unavailable video review, unavailable individual
586
+ clips, an empty swing list, and an older product with no `swings` field.
587
+ - Retry feedback without re-uploading or losing existing clips/measurements.
588
+ - Keep the engine key in the backend; test user ownership on results and media.
589
+ - Copy retained sessions to app storage; handle expired/rebuilt engine jobs.
590
+
591
+ Do not fill unavailable measurements with visual guesses. This integration
592
+ provides the working POC's visible observations, supported estimates and clips;
593
+ it does not establish validated one-camera measurement accuracy.
docs/MOTION_PLAYER_API.md CHANGED
@@ -1,6 +1,10 @@
1
  # Motion-player backend API
2
 
3
- Contract 1.0 · SAM and GVHMR adapters · native-body refinement · 16 October 2026
 
 
 
 
4
 
5
  Base URL: `https://modventures-baseball-engine.hf.space`. Use the existing server
6
  Bearer key for every `/v1/` request. Keep that shared credential in your app's
@@ -93,6 +97,15 @@ warped. With no coefficients the pinhole assumption remains explicit. Calibrated
93
  ground translation is not supplied. Missing calibration does not prevent motion export.
94
  Coaching/LLM calls are disabled on this path.
95
 
 
 
 
 
 
 
 
 
 
96
  ## Native-body refinement
97
 
98
  New motion jobs enable `refinement.enabled` by default. Existing engine and SAM
 
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,
7
+ multi-swing range playback, measurement cards and skeleton/graph synchronization.
8
 
9
  Base URL: `https://modventures-baseball-engine.hf.space`. Use the existing server
10
  Bearer key for every `/v1/` request. Keep that shared credential in your app's
 
97
  ground translation is not supplied. Missing calibration does not prevent motion export.
98
  Coaching/LLM calls are disabled on this path.
99
 
100
+ When `up_vector` is omitted/null, the shared pipeline estimates it from sampled
101
+ video frames using GeoCalib. Reliable estimates populate effective calculation
102
+ inputs, with `up_source` and diagnostics in `coordinates.up_estimation`; submitted
103
+ inputs stay unchanged. Explicit vectors take priority. Unreliable estimates stay
104
+ unknown, and camera stability, scale and timing checks still apply. A declared
105
+ pitcher direction may be supplied before vertical is resolved. See
106
+ [automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates,
107
+ acceptance checks, FE labels and the `up_estimation.enabled` opt-out.
108
+
109
  ## Native-body refinement
110
 
111
  New motion jobs enable `refinement.enabled` by default. Existing engine and SAM
docs/MOTION_REQUIREMENTS_AUDIT.md CHANGED
@@ -18,10 +18,10 @@ Against `Motion_Player_Backend_Requirements.md` v1.0, 15 October 2026.
18
  | Projections and annotation | Same corrected sequence and intrinsics produce JSON projections and all four videos. Source playback timeline preserved; no bottom panel. |
19
  | Ready/failed semantics | No usable motion fails. Missing selected model returns actionable 503 before job allocation; other model and old APIs remain available. Publish after referenced artifacts are ready. |
20
  | Auth, retention, cancellation | Existing queue/auth, safe artifact allowlist, checksums/ranges/expiry, cancellation and staging cleanup retained. Durable replay requires persistent storage. |
21
- | Optional ground/distortion inputs | Declared up/field axes and intrinsics; optional five-coefficient Brown–Conrady projection shared by fitting, motion projection and annotation. Background motion can contradict a static-camera declaration. No calibrated ground trajectory is inferred. Missing/estimated calibration remains explicit. |
22
  | Optional animated mesh | Deferred second phase, as the document allows. Artifact explicitly unavailable; skeleton remains measurement source. |
23
  | Reference accuracy acceptance criterion 9 | **Pending independent reference data.** Fixture/round-trip tests establish arithmetic and alignment, not hidden-depth or arbitrary real-video accuracy. |
24
- | Real GVHMR GPU validation | **Requires the operator's licensed SMPL-X neutral file.** Dependency/configuration and synthetic adapter tests do not count as completed real inference. |
25
 
26
  Existing `/v1/analyses`, `/product`, and `/v1/sam-batting/analyses` contracts remain
27
  separate. The selector is added only to `/v1/motion-analyses`.
 
18
  | Projections and annotation | Same corrected sequence and intrinsics produce JSON projections and all four videos. Source playback timeline preserved; no bottom panel. |
19
  | Ready/failed semantics | No usable motion fails. Missing selected model returns actionable 503 before job allocation; other model and old APIs remain available. Publish after referenced artifacts are ready. |
20
  | Auth, retention, cancellation | Existing queue/auth, safe artifact allowlist, checksums/ranges/expiry, cancellation and staging cleanup retained. Durable replay requires persistent storage. |
21
+ | Optional ground/distortion inputs | Declared axes/intrinsics preserved. Missing camera-up is estimated with pinned offline GeoCalib and conservative multi-frame image/uncertainty checks, or left unknown. Both adapters use the same camera axes and effective calculation provenance. Optional five-coefficient Brown–Conrady projection shared by fitting, motion projection and annotation. Background motion can contradict a static-camera declaration. No calibrated ground trajectory is inferred. Missing/estimated calibration remains explicit. |
22
  | Optional animated mesh | Deferred second phase, as the document allows. Artifact explicitly unavailable; skeleton remains measurement source. |
23
  | Reference accuracy acceptance criterion 9 | **Pending independent reference data.** Fixture/round-trip tests establish arithmetic and alignment, not hidden-depth or arbitrary real-video accuracy. |
24
+ | Real GVHMR GPU validation | Completed on T4 with the operator's licensed SMPL-X neutral file: 70 source frames, accepted fitted motion, four annotated videos and public-artifact measurement reproduction. This verifies execution and consistency, not independent depth accuracy. |
25
 
26
  Existing `/v1/analyses`, `/product`, and `/v1/sam-batting/analyses` contracts remain
27
  separate. The selector is added only to `/v1/motion-analyses`.
docs/motion-input.schema.json CHANGED
@@ -624,6 +624,102 @@
624
  },
625
  "title": "TimingInput",
626
  "type": "object"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  }
628
  },
629
  "additionalProperties": false,
@@ -930,6 +1026,9 @@
930
  },
931
  "tracking": {
932
  "$ref": "#/$defs/MotionTrackingSettings"
 
 
 
933
  }
934
  },
935
  "title": "MotionInput",
 
624
  },
625
  "title": "TimingInput",
626
  "type": "object"
627
+ },
628
+ "UpEstimationSettings": {
629
+ "additionalProperties": false,
630
+ "properties": {
631
+ "enabled": {
632
+ "default": true,
633
+ "title": "Enabled",
634
+ "type": "boolean"
635
+ },
636
+ "sample_count": {
637
+ "default": 7,
638
+ "maximum": 15,
639
+ "minimum": 3,
640
+ "title": "Sample Count",
641
+ "type": "integer"
642
+ },
643
+ "minimum_frames": {
644
+ "default": 3,
645
+ "maximum": 15,
646
+ "minimum": 3,
647
+ "title": "Minimum Frames",
648
+ "type": "integer"
649
+ },
650
+ "maximum_gravity_uncertainty_deg": {
651
+ "default": 5.0,
652
+ "exclusiveMinimum": 0,
653
+ "maximum": 15,
654
+ "title": "Maximum Gravity Uncertainty Deg",
655
+ "type": "number"
656
+ },
657
+ "maximum_frame_deviation_deg": {
658
+ "default": 3.0,
659
+ "exclusiveMinimum": 0,
660
+ "maximum": 10,
661
+ "title": "Maximum Frame Deviation Deg",
662
+ "type": "number"
663
+ },
664
+ "minimum_consensus_fraction": {
665
+ "default": 0.8,
666
+ "maximum": 1,
667
+ "minimum": 0.6,
668
+ "title": "Minimum Consensus Fraction",
669
+ "type": "number"
670
+ },
671
+ "minimum_temporal_coverage": {
672
+ "default": 0.75,
673
+ "maximum": 1,
674
+ "minimum": 0.5,
675
+ "title": "Minimum Temporal Coverage",
676
+ "type": "number"
677
+ },
678
+ "minimum_background_fraction": {
679
+ "default": 0.2,
680
+ "maximum": 0.8,
681
+ "minimum": 0.1,
682
+ "title": "Minimum Background Fraction",
683
+ "type": "number"
684
+ },
685
+ "minimum_effective_pixels": {
686
+ "default": 32,
687
+ "maximum": 1000,
688
+ "minimum": 16,
689
+ "title": "Minimum Effective Pixels",
690
+ "type": "integer"
691
+ },
692
+ "minimum_spatial_cells": {
693
+ "default": 3,
694
+ "maximum": 9,
695
+ "minimum": 2,
696
+ "title": "Minimum Spatial Cells",
697
+ "type": "integer"
698
+ },
699
+ "maximum_up_residual_deg": {
700
+ "default": 10.0,
701
+ "exclusiveMinimum": 0,
702
+ "maximum": 20,
703
+ "title": "Maximum Up Residual Deg",
704
+ "type": "number"
705
+ },
706
+ "maximum_latitude_residual_deg": {
707
+ "default": 5.0,
708
+ "exclusiveMinimum": 0,
709
+ "maximum": 15,
710
+ "title": "Maximum Latitude Residual Deg",
711
+ "type": "number"
712
+ },
713
+ "minimum_texture_fraction": {
714
+ "default": 0.005,
715
+ "exclusiveMinimum": 0,
716
+ "maximum": 0.1,
717
+ "title": "Minimum Texture Fraction",
718
+ "type": "number"
719
+ }
720
+ },
721
+ "title": "UpEstimationSettings",
722
+ "type": "object"
723
  }
724
  },
725
  "additionalProperties": false,
 
1026
  },
1027
  "tracking": {
1028
  "$ref": "#/$defs/MotionTrackingSettings"
1029
+ },
1030
+ "up_estimation": {
1031
+ "$ref": "#/$defs/UpEstimationSettings"
1032
  }
1033
  },
1034
  "title": "MotionInput",
docs/motion-options.example.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "timing": {
3
+ "kind": "unknown",
4
+ "source": null,
5
+ "factor": null,
6
+ "all_captured_frames_retained": null,
7
+ "physical_times_s": null
8
+ },
9
+ "rotation_degrees": null,
10
+ "camera_stability": "unknown",
11
+ "handedness": null,
12
+ "lead_foot": null,
13
+ "camera": null,
14
+ "up_vector": null,
15
+ "up_source": null,
16
+ "pitcher_vector": null,
17
+ "pitcher_source": null,
18
+ "scale_factor": 1.0,
19
+ "scale_source": null,
20
+ "athlete_box": null,
21
+ "single_swing": false,
22
+ "windows": [],
23
+ "correction": {
24
+ "min_cutoff_hz": 6.0,
25
+ "speed_coefficient": 4.0,
26
+ "max_gap_s": 0.1,
27
+ "bone_relative_tolerance": 0.35,
28
+ "spike_mad_multiplier": 6.0,
29
+ "boundary_samples": 2,
30
+ "spike_minimum_m": 0.005
31
+ },
32
+ "measurement": {
33
+ "minimum_axis_length_m": 0.015,
34
+ "minimum_horizontal_fraction": 0.15,
35
+ "minimum_foot_vector_m": 0.01,
36
+ "minimum_upright_torso_m": 0.05,
37
+ "maximum_heading_step_deg": 150.0,
38
+ "peak_competition_ratio": 0.9,
39
+ "peak_separation_s": 0.08,
40
+ "direction_min_rotation_deg": 5.0,
41
+ "motion_prominence_m_s": 0.15,
42
+ "motion_separation_s": 0.7,
43
+ "window_before_peak_s": 0.2,
44
+ "window_after_peak_s": 0.25
45
+ },
46
+ "coaching": false,
47
+ "model": "gvhmr",
48
+ "gvhmr": {
49
+ "batch_size": 4,
50
+ "max_sequence_frames": 300,
51
+ "context_frames": 60,
52
+ "minimum_keypoint_score": 0.3,
53
+ "maximum_reprojection_box_fraction": 0.15
54
+ },
55
+ "annotated_videos": true,
56
+ "source_mirrored": null,
57
+ "handedness_source": null,
58
+ "lead_foot_source": null,
59
+ "scale_status": "model_estimated",
60
+ "minimum_usable_joints": 3,
61
+ "refinement": {
62
+ "enabled": true,
63
+ "native_batch_frames": 8,
64
+ "window_frames": 48,
65
+ "context_frames": 8,
66
+ "iterations": 25,
67
+ "learning_rate": 0.005,
68
+ "minimum_observation_score": 0.45,
69
+ "minimum_observed_joints": 6,
70
+ "observation_scale_box_fraction": 0.025,
71
+ "maximum_observation_error_box_fraction": 0.08,
72
+ "maximum_body_change_fraction": 0.12,
73
+ "maximum_bone_change_fraction": 0.06,
74
+ "temporal_weight": 0.02,
75
+ "initializer_weight": 0.1,
76
+ "initializer_scale_body_fraction": 0.03,
77
+ "maximum_peak_time_shift_s": 0.025,
78
+ "maximum_peak_speed_change_fraction": 0.2,
79
+ "maximum_static_background_motion_fraction": 0.003,
80
+ "sensitivity_factors": [
81
+ 0.5,
82
+ 2.0
83
+ ]
84
+ },
85
+ "tracking": {
86
+ "recover_short_losses": true,
87
+ "maximum_recovery_gap_s": 0.2,
88
+ "minimum_appearance_similarity": 0.85,
89
+ "minimum_candidate_margin": 0.1
90
+ },
91
+ "up_estimation": {
92
+ "enabled": true,
93
+ "sample_count": 7,
94
+ "minimum_frames": 3,
95
+ "maximum_gravity_uncertainty_deg": 5.0,
96
+ "maximum_frame_deviation_deg": 3.0,
97
+ "minimum_consensus_fraction": 0.8,
98
+ "minimum_temporal_coverage": 0.75,
99
+ "minimum_background_fraction": 0.2,
100
+ "minimum_effective_pixels": 32,
101
+ "minimum_spatial_cells": 3,
102
+ "maximum_up_residual_deg": 10.0,
103
+ "maximum_latitude_residual_deg": 5.0,
104
+ "minimum_texture_fraction": 0.005
105
+ }
106
+ }
tests/test_camera_up.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camera-axis truth, uncertainty abstention, and public measurement reproduction."""
2
+ import copy
3
+ import json
4
+ from pathlib import Path
5
+ import numpy as np
6
+ import pytest
7
+ from baseball_batting.camera_up import consensus,estimate,sample_indices,frame_reasons
8
+ from baseball_batting.camera_up_worker import diagnostics,prepare_image
9
+ from baseball_batting.motion_contract import MotionInput
10
+ from baseball_batting.ingest import ingest
11
+ from baseball_batting.motion_export import export_motion,reproduce_measurements
12
+ from baseball_batting.geometry import project
13
+ from test_motion_player import raw_for
14
+
15
+
16
+ def evidence(i,vector=(0,-1,0),**changes):
17
+ return {'source_frame_index':i,'video_time_s':i/6,'up_vector':list(vector),
18
+ 'image_sha256':str(i),'gravity_uncertainty_deg':1.,'covariance_valid':True,
19
+ 'background_fraction':.7,'texture_fraction':.1,'up_residual_deg':1.,'latitude_residual_deg':1.,
20
+ 'up_effective_pixels':200.,'latitude_effective_pixels':200.,'up_spatial_cells':6,'latitude_spatial_cells':6,**changes}
21
+
22
+
23
+ def capture():return {'frames':[{'playback_s':i/6} for i in range(7)]}
24
+
25
+
26
+ def test_consensus_uses_consistent_camera_up_without_flipping_sign():
27
+ r=consensus([evidence(i) for i in range(7)],capture(),MotionInput())
28
+ assert r['status']=='estimated' and r['reliable'] and r['confidence'] is None
29
+ np.testing.assert_allclose(r['up_vector'],[0,-1,0]);assert 'estimated' in r['up_source']
30
+ assert r['temporal_coverage_fraction']==1 and r['accepted_frame_count']==7
31
+ opposite=[evidence(i,(0,1 if i>3 else -1,0)) for i in range(7)]
32
+ r=consensus(opposite,capture(),MotionInput())
33
+ assert r['status']=='unknown' and r['up_vector'] is None
34
+ assert r['reason_code']=='inconsistent_camera_up_across_frames'
35
+
36
+
37
+ @pytest.mark.parametrize('changes',[{'gravity_uncertainty_deg':0.},{'gravity_uncertainty_deg':8.},
38
+ {'covariance_valid':False},{'background_fraction':.01},{'texture_fraction':0.},
39
+ {'up_effective_pixels':3.},{'latitude_spatial_cells':1},{'up_residual_deg':25.},
40
+ {'up_vector':[float('nan'),0,0]},{'image_sha256':'repeated'}])
41
+ def test_bad_image_evidence_cannot_become_reliable(changes):
42
+ result=consensus([evidence(i,**changes) for i in range(7)],capture(),MotionInput())
43
+ assert result['status']=='unknown' and result['up_vector'] is None and not result['applied']
44
+
45
+
46
+ def test_only_middle_frames_do_not_establish_a_reference_for_entire_video():
47
+ result=consensus([evidence(i,**({'covariance_valid':False} if i in (0,6) else {})) for i in range(7)],capture(),MotionInput())
48
+ assert result['reason_code']=='insufficient_camera_up_temporal_coverage'
49
+ assert result['up_vector'] is None
50
+
51
+
52
+ def test_explicit_input_bypasses_estimator_and_preserves_exact_values(monkeypatch):
53
+ options=MotionInput(up_vector=[.2,-2.,.1],up_source='Operator supplied calibration')
54
+ monkeypatch.setattr('baseball_batting.camera_up.configured_record',lambda *a:pytest.fail('Should not inspect estimator'))
55
+ result=estimate(None,None,None,None,options,None,None)
56
+ assert result['status']=='provided' and result['reliable'] is None
57
+ assert result['up_vector']==[.2,-2.,.1] and result['up_source']==options.up_source
58
+
59
+
60
+ def test_unconfigured_provider_and_disabled_estimation_are_safe(monkeypatch):
61
+ monkeypatch.setattr('baseball_batting.camera_up.configured_record',lambda *a:None)
62
+ for opts,reason in [(MotionInput(),'camera_up_provider_unavailable'),
63
+ (MotionInput(up_estimation={'enabled':False}),'automatic_up_estimation_disabled')]:
64
+ assert estimate(None,None,None,None,opts,None,None)['reason_code']==reason
65
+
66
+
67
+ def test_motion_accepts_declared_pitcher_direction_before_auto_up_without_changing_legacy_contract():
68
+ from pydantic import ValidationError
69
+ from baseball_batting.sam_batting_contract import SamBattingInput
70
+ values={'pitcher_vector':[1.,0.,0.],'pitcher_source':'Surveyed field direction'}
71
+ motion=MotionInput(**values)
72
+ assert motion.pitcher_vector==(1.,0.,0.) and motion.up_vector is None
73
+ assert motion.sam_options().pitcher_vector is None
74
+ assert motion.pitcher_source==values['pitcher_source']
75
+ with pytest.raises(ValidationError,match='vertical reference'):SamBattingInput(**values)
76
+ with pytest.raises(ValidationError,match='source description'):MotionInput(pitcher_vector=[1.,0.,0.])
77
+
78
+
79
+ def test_sampling_uses_actual_video_timestamps():
80
+ c={'frames':[{'playback_s':t} for t in [10,10.01,10.02,10.03,10.5,10.99,11]]}
81
+ assert sample_indices(c,3)==[0,4,6]
82
+ assert sample_indices({'frames':[{'playback_s':None}]},7)==[]
83
+
84
+
85
+ class Tensor:
86
+ def __init__(self,a):self.a=np.asarray(a)
87
+ def detach(self):return self
88
+ def cpu(self):return self
89
+ def numpy(self):return self.a
90
+
91
+
92
+ def prediction(vector=(0,-1,0),covariance=None):
93
+ from types import SimpleNamespace
94
+ h,w=120,160;f=150.;y,x=np.mgrid[:h,:w]
95
+ rays2=np.stack([(x-w/2)/f,(y-h/2)/f],-1);v=np.array(vector,float)
96
+ up=v[:2]-v[2]*rays2;up/=np.linalg.norm(up,axis=-1,keepdims=True)
97
+ rays=np.concatenate([rays2,np.ones((h,w,1))],-1);rays/=np.linalg.norm(rays,axis=-1,keepdims=True)
98
+ lat=np.arcsin(rays@v)
99
+ return {'gravity':SimpleNamespace(vec3d=Tensor([v])),
100
+ 'camera':SimpleNamespace(K=Tensor([[[f,0,w/2],[0,f,h/2],[0,0,1]]])),
101
+ 'covariance':Tensor([np.eye(3)*.001 if covariance is None else covariance]),
102
+ 'gravity_uncertainty':Tensor([.03]),'up_field':Tensor(up.transpose(2,0,1)[None]),
103
+ 'latitude_field':Tensor(lat[None,None]),'up_confidence':Tensor(np.ones((1,h,w))),
104
+ 'latitude_confidence':Tensor(np.ones((1,h,w)))}
105
+
106
+
107
+ def test_perspective_fields_match_tilted_camera_truth_and_reject_invalid_covariance():
108
+ r,p=np.radians([22,-14]);vector=[-np.sin(r)*np.cos(p),-np.cos(r)*np.cos(p),np.sin(p)]
109
+ image=np.random.default_rng(3).integers(0,256,(120,160,3),dtype=np.uint8)
110
+ mask=np.ones((120,160),bool)
111
+ result=diagnostics(prediction(vector),image,mask,mask)
112
+ np.testing.assert_allclose(result['up_vector'],vector,atol=1e-8)
113
+ assert result['up_residual_deg']<1e-4 and result['latitude_residual_deg']<1e-4
114
+ assert result['covariance_valid'] and result['up_spatial_cells']==9
115
+ bad=diagnostics(prediction(vector,np.zeros((3,3))),image,mask,mask)
116
+ assert not bad['covariance_valid']
117
+ # Sign inversion cannot pass geometric image agreement.
118
+ wrong=prediction(vector);wrong['gravity'].vec3d=Tensor([-np.array(vector)])
119
+ assert diagnostics(wrong,image,mask,mask)['up_residual_deg']>179
120
+
121
+
122
+ def test_known_camera_rectification_changes_image_grid_but_not_camera_axes():
123
+ image=np.zeros((120,160,3),np.uint8)
124
+ camera={'fx':160.,'fy':140.,'cx':78.,'cy':59.,'distortion':[0,0,0,0,0]}
125
+ prepared,mask,valid,focal=prepare_image(image,[60,30,100,100],camera)
126
+ assert focal==pytest.approx(np.sqrt(160*140)) and prepared.shape==image.shape
127
+ assert valid.mean()>.9 and mask.mean()<valid.mean()
128
+ assert not mask[60,80] # Foreground is excluded from scene support.
129
+
130
+
131
+ @pytest.mark.parametrize('model',['sam3d','gvhmr'])
132
+ @pytest.mark.parametrize('reliable',[True,False])
133
+ def test_auto_reference_applies_to_both_models_and_public_results_reproduce(tmp_path,video,model,reliable):
134
+ from scipy.spatial.transform import Rotation
135
+ options=MotionInput(model=model,camera_stability='fixed_verified',single_swing=True,
136
+ annotated_videos=False,timing={'kind':'unretimed','source':'Synthetic known time'})
137
+ c=ingest(video,options.metadata());raw=raw_for(c)
138
+ rot=Rotation.from_euler('zx',[20,12],degrees=True).as_matrix();up=rot@np.array([0,-1,0.])
139
+ raw['points_body']=raw['points_body']@rot.T;raw['camera_translation']=raw['camera_translation']@rot.T
140
+ raw['projection']=np.stack([project(p+t,k) for p,t,k in zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
141
+ result=consensus([evidence(i,up) for i in range(7)],capture(),options)
142
+ if not reliable:result.update(status='unknown',reliable=False,up_vector=None,up_source=None,applied=False)
143
+ m=export_motion(tmp_path,video,c,raw,options,{'name':'synthetic rig, not accuracy evidence'},
144
+ {'analysis_id':'test','analysis_revision':1},up_reference=result)
145
+ assert m.pipeline['inputs']['up_vector'] is None and options.up_vector is None
146
+ assert (m.coordinates['up_vector'] is not None)==reliable
147
+ if reliable:
148
+ np.testing.assert_allclose(m.pipeline['calculation_inputs']['up_vector'],up)
149
+ assert m.coordinates['up_estimation']['status']=='estimated'
150
+ else:assert m.pipeline['calculation_inputs']['up_vector'] is None
151
+ summaries=json.loads((tmp_path/'measurements.json').read_text())['summaries']
152
+ hips=next(x for x in summaries if x['metric_id']=='hip_heading_deg')
153
+ assert (hips['value'] is not None)==reliable
154
+ if reliable:assert 'vertical_reference_estimated_from_images' in hips['quality_flags']
155
+ reproduced=reproduce_measurements(m,tmp_path/'motion.jsonl')
156
+ values={(s.rep,v.key):v.value for swings in reproduced.values() for s in swings for v in s.measurements}
157
+ for row in summaries:
158
+ expected=values[row['rep'],row['metric_id']]
159
+ assert row['value']==pytest.approx(expected) if expected is not None else row['value'] is None
160
+
161
+
162
+ def test_static_camera_conflict_still_blocks_angles_with_estimated_up(tmp_path,video):
163
+ options=MotionInput(camera_stability='fixed_verified',single_swing=True,annotated_videos=False)
164
+ c=ingest(video,options.metadata());auto=consensus([evidence(i) for i in range(7)],capture(),options)
165
+ m=export_motion(tmp_path,video,c,raw_for(c),options,{'name':'fixture'},
166
+ {'analysis_id':'test','analysis_revision':1},up_reference=auto,
167
+ refinement={'image_evidence':{'declared_static_camera_conflict':True}})
168
+ assert m.pipeline['calculation_inputs']['camera_stability']=='moving'
169
+ assert m.pipeline['inputs']['camera_stability']=='fixed_verified'
170
+ assert m.coordinates['up_vector']==[0,-1,0] and m.coordinates['frame']=='camera_oriented_hip_relative'
171
+ rows=json.loads((tmp_path/'measurements.json').read_text())['summaries']
172
+ assert all(r['value'] is None for r in rows if r['unit']=='deg')
173
+ assert all(r['camera_to_measurement_rotation'] is None for r in rows)
174
+
175
+
176
+ def test_estimator_failure_is_unknown_instead_of_a_failed_motion_job(tmp_path,monkeypatch,video):
177
+ import subprocess
178
+ opts=MotionInput();c=ingest(video,opts.metadata())
179
+ monkeypatch.setattr('baseball_batting.camera_up.configured_record',lambda *a:{'worker_python':'fixture','weights':'fixture','weights_sha256':'fixture'})
180
+ monkeypatch.setattr('baseball_batting.camera_up.subprocess.run',lambda *a,**k:(_ for _ in ()).throw(subprocess.TimeoutExpired('fixture',180)))
181
+ r=estimate(tmp_path,video,c,None,opts,{'reasons':[None]*c['frame_count']},lambda *a:None)
182
+ assert r['status']=='unknown' and r['reason_code']=='camera_up_estimation_failed'
183
+ assert (tmp_path/'camera-up-private.json').is_file()
tools/setup_camera_up.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build-time official GeoCalib checkpoint acquisition and offline preflight."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+ import urllib.request
8
+ from baseball_batting.camera_up_provider import REVISION,WEIGHTS_URL,WEIGHTS_SHA256
9
+
10
+
11
+ def main():
12
+ p=argparse.ArgumentParser();p.add_argument('--output',required=True);args=p.parse_args()
13
+ root=Path(args.output);root.mkdir(parents=True,exist_ok=True);weights=root/'geocalib-pinhole.tar'
14
+ if not weights.is_file() or hashlib.sha256(weights.read_bytes()).hexdigest()!=WEIGHTS_SHA256:
15
+ temporary=weights.with_suffix('.part')
16
+ with urllib.request.urlopen(WEIGHTS_URL,timeout=90) as response,temporary.open('wb') as out:
17
+ while block:=response.read(1024*1024):out.write(block)
18
+ if hashlib.sha256(temporary.read_bytes()).hexdigest()!=WEIGHTS_SHA256:raise ValueError('GeoCalib checkpoint checksum mismatch')
19
+ temporary.replace(weights)
20
+ from geocalib import GeoCalib
21
+ GeoCalib(weights=str(weights)).eval() # Offline model construction, no video or provider credentials.
22
+ (root/'provider.json').write_text(json.dumps({'worker_python':sys.executable,'weights':str(weights.resolve()),
23
+ 'weights_sha256':WEIGHTS_SHA256,'source_revision':REVISION,'provider':'cvg/GeoCalib',
24
+ 'weights_license':'CC-BY-4.0; Copyright 2024 ETH Zurich','code_license':'Apache-2.0'},indent=2))
25
+ return 0
26
+
27
+
28
+ if __name__=='__main__':raise SystemExit(main())