Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
220c87b
1
Parent(s): 6b95c6c
Automated Deploy: 926823bd23ad2b08b74eb16ef7fd55c84022d1e8
Browse files- baseball_batting/api.py +1 -1
- baseball_batting/motion_api.py +3 -0
- baseball_batting/motion_contract.py +12 -1
- baseball_batting/motion_export.py +17 -2
- baseball_batting/pitcher_direction.py +165 -0
- docs/APP_API_INTEGRATION.md +16 -0
- docs/MOTION_PLAYER_API.md +7 -0
- docs/MOTION_REQUIREMENTS_AUDIT.md +1 -1
- docs/PITCHER_FLOOR_DIRECTION.md +224 -0
- docs/motion-input.schema.json +80 -0
- docs/motion-options.example.json +2 -1
- tests/test_motion_player_api.py +34 -1
- tests/test_pitcher_direction.py +182 -0
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.
|
| 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.14.0", lifespan=lifespan,
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
baseball_batting/motion_api.py
CHANGED
|
@@ -98,6 +98,9 @@ def register(app,service,authenticated):
|
|
| 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'}
|
|
|
|
| 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 |
+
'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
|
| 102 |
+
'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
|
| 103 |
+
'camera_frame':'upright_camera_x_right_y_down_z_away'},
|
| 104 |
'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
|
| 105 |
'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
|
| 106 |
'output_schema_url':PREFIX+'/output-schema'}
|
baseball_batting/motion_contract.py
CHANGED
|
@@ -13,6 +13,15 @@ DEFINITION_VERSION = 'batting-corrected-points-v1'
|
|
| 13 |
class MotionCamera(CameraInput):
|
| 14 |
# OpenCV Brown–Conrady order in the original upright image. No image warp.
|
| 15 |
distortion: tuple[float, float, float, float, float] | None = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
class UpEstimationSettings(Strict):
|
|
@@ -103,6 +112,7 @@ class MotionInput(SamBattingInput):
|
|
| 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):
|
|
@@ -112,7 +122,8 @@ class MotionInput(SamBattingInput):
|
|
| 112 |
|
| 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'):
|
|
|
|
| 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)
|
|
|
|
| 13 |
class MotionCamera(CameraInput):
|
| 14 |
# OpenCV Brown–Conrady order in the original upright image. No image warp.
|
| 15 |
distortion: tuple[float, float, float, float, float] | None = None
|
| 16 |
+
calibration_status: Literal['unknown', 'estimated', 'calibrated'] = 'unknown'
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PitcherFloorPoints(Strict):
|
| 20 |
+
source_frame_index: int = Field(ge=0, strict=True)
|
| 21 |
+
near_batter: tuple[float, float]
|
| 22 |
+
toward_pitcher: tuple[float, float]
|
| 23 |
+
selection_uncertainty_px: float = Field(default=2., gt=0, le=25)
|
| 24 |
+
up_sensitivity_deg: float = Field(default=1., gt=0, le=30)
|
| 25 |
|
| 26 |
|
| 27 |
class UpEstimationSettings(Strict):
|
|
|
|
| 112 |
refinement: RefinementSettings = Field(default_factory=RefinementSettings)
|
| 113 |
tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
|
| 114 |
up_estimation: UpEstimationSettings = Field(default_factory=UpEstimationSettings)
|
| 115 |
+
pitcher_floor_points: PitcherFloorPoints | None = None
|
| 116 |
|
| 117 |
@model_validator(mode='after')
|
| 118 |
def scale_evidence(self):
|
|
|
|
| 122 |
|
| 123 |
def sam_options(self):
|
| 124 |
data={k:v for k,v in self.model_dump().items() if k in SamBattingInput.model_fields}
|
| 125 |
+
if data.get('camera'):
|
| 126 |
+
for key in ('distortion','calibration_status'):data['camera'].pop(key,None)
|
| 127 |
# These axes are measurement inputs, unused by native reconstruction.
|
| 128 |
# Keep the original direction in MotionInput until camera-up is resolved.
|
| 129 |
if data['up_vector'] is None:data.update(pitcher_vector=None,pitcher_source=None)
|
baseball_batting/motion_export.py
CHANGED
|
@@ -148,6 +148,12 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 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'
|
|
@@ -236,11 +242,16 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 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,7 +320,8 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 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',
|
|
@@ -317,7 +329,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 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):
|
|
@@ -373,6 +385,9 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 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',
|
|
|
|
| 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 |
+
from .pitcher_direction import resolve as resolve_pitcher_direction
|
| 152 |
+
pitcher_reference=resolve_pitcher_direction(calculation_options,capture,up_reference)
|
| 153 |
+
if options.pitcher_vector is None and pitcher_reference['status']=='estimated' and pitcher_reference['reliable'] is True:
|
| 154 |
+
calculation_options=calculation_options.model_copy(update={
|
| 155 |
+
'pitcher_vector':tuple(pitcher_reference['pitcher_vector']),
|
| 156 |
+
'pitcher_source':pitcher_reference['pitcher_source']})
|
| 157 |
if options.model=='gvhmr':
|
| 158 |
corrected['interpolated']|=resampled[:,None]&corrected['valid']
|
| 159 |
corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
|
|
|
|
| 242 |
'temporal_model_sample_spacing_ms':1000/30 if options.model=='gvhmr' and known else None,
|
| 243 |
'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
|
| 244 |
metadata['up_reference_status']=up_reference['status']
|
| 245 |
+
metadata['pitcher_reference_status']=pitcher_reference['status']
|
| 246 |
for key,metric in rows.items():
|
| 247 |
details=metric.model_dump(mode='json');details.pop('coaching',None)
|
| 248 |
if (up_reference['status']=='estimated' and details['value'] is not None and key not in
|
| 249 |
('head_excursion_relative_cm','hand_speed_relative_m_s','hands_peak_time_ms','stride_duration_ms')):
|
| 250 |
details['quality_flags'].append('vertical_reference_estimated_from_images')
|
| 251 |
+
if (pitcher_reference['status']=='estimated' and details['value'] is not None and key in
|
| 252 |
+
('hip_heading_deg','shoulder_heading_deg','left_foot_heading_deg','right_foot_heading_deg',
|
| 253 |
+
'stride_relative_forward_cm','stride_relative_lateral_cm')):
|
| 254 |
+
details['quality_flags'].append('pitcher_reference_estimated_from_floor_points')
|
| 255 |
summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
|
| 256 |
'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
|
| 257 |
'source_samples':[stamp(i) for i in metric.source_frame_ids]})
|
|
|
|
| 320 |
'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
|
| 321 |
atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
|
| 322 |
'definition_version':definition_version,'summaries':summaries,'series':series,
|
| 323 |
+
'calculation_inputs':calculation_options.model_dump(mode='json'),'up_reference':up_reference,
|
| 324 |
+
'pitcher_reference':pitcher_reference})
|
| 325 |
atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
|
| 326 |
atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
|
| 327 |
'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
|
|
|
|
| 329 |
'tracking_reasons':track['reasons']},
|
| 330 |
'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
|
| 331 |
'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting',
|
| 332 |
+
'up_reference':up_reference,'pitcher_reference':pitcher_reference})
|
| 333 |
clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress,distortion=distortion) if options.annotated_videos else {}
|
| 334 |
source=job/('source'+Path(video).suffix.lower())
|
| 335 |
if source!=Path(video):
|
|
|
|
| 385 |
'up_vector':list(calculation_options.up_vector) if calculation_options.up_vector is not None else None,
|
| 386 |
'up_source':calculation_options.up_source if calculation_options.up_vector is not None else None,
|
| 387 |
'up_vector_frame':up_reference['coordinate_frame'],'up_estimation':up_reference,
|
| 388 |
+
'pitcher_vector':list(calculation_options.pitcher_vector) if calculation_options.pitcher_vector is not None else None,
|
| 389 |
+
'pitcher_source':calculation_options.pitcher_source if calculation_options.pitcher_vector is not None else None,
|
| 390 |
+
'pitcher_vector_frame':pitcher_reference['coordinate_frame'],'pitcher_estimation':pitcher_reference,
|
| 391 |
'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
|
| 392 |
'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
|
| 393 |
'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
|
baseball_batting/pitcher_direction.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conditional level-floor direction from two calibrated camera rays.
|
| 2 |
+
|
| 3 |
+
With up u and unknown positive camera height h, a floor hit is
|
| 4 |
+
X = -h*r/(u.r). Height cancels from normalize(X_toward - X_near).
|
| 5 |
+
No body-model focal guess, floor height, or ground trajectory is inferred.
|
| 6 |
+
"""
|
| 7 |
+
from itertools import product
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import math
|
| 10 |
+
import numpy as np
|
| 11 |
+
from .camera_up_provider import CAMERA_FRAME
|
| 12 |
+
from .storage import sha256_file
|
| 13 |
+
|
| 14 |
+
METHOD='two_floor_points_ray_plane_v1'
|
| 15 |
+
LIMITS={'minimum_point_separation_px':10.,'minimum_floor_incidence_deg':3.,
|
| 16 |
+
'maximum_direction_deviation_deg':10.,'maximum_undistortion_residual_px':.1,
|
| 17 |
+
'minimum_field_of_view_deg':5.,'maximum_field_of_view_deg':170.,
|
| 18 |
+
'maximum_distortion_jacobian_condition':100.}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Unreliable(ValueError):pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reference(options,reason='floor_points_not_supplied'):
|
| 25 |
+
supplied=options.pitcher_vector is not None
|
| 26 |
+
return {'status':'provided' if supplied else 'unknown',
|
| 27 |
+
'pitcher_vector':list(options.pitcher_vector) if supplied else None,
|
| 28 |
+
'pitcher_source':options.pitcher_source if supplied else None,
|
| 29 |
+
'coordinate_frame':CAMERA_FRAME,'method':'caller_supplied' if supplied else METHOD,
|
| 30 |
+
'applied':supplied,'reliable':None if supplied else False,'confidence':None,
|
| 31 |
+
'accuracy_validated':False,'reason_code':'caller_input_not_independently_verified' if supplied else reason,
|
| 32 |
+
'reliability_kind':'conditional_geometry_and_sensitivity_checks; not calibrated accuracy or probability'}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _unit(v):
|
| 36 |
+
v=np.asarray(v,float);length=np.linalg.norm(v,axis=-1,keepdims=True)
|
| 37 |
+
if not np.isfinite(v).all() or np.any(length<1e-10):raise Unreliable('invalid_direction_geometry')
|
| 38 |
+
return v/length
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _distort(xy,d):
|
| 42 |
+
x,y=np.moveaxis(xy,-1,0);k1,k2,p1,p2,k3=d;r2=x*x+y*y
|
| 43 |
+
radial=1+k1*r2+k2*r2*r2+k3*r2*r2*r2
|
| 44 |
+
xy_out=np.stack([x*radial+2*p1*x*y+p2*(r2+2*x*x),
|
| 45 |
+
y*radial+p1*(r2+2*y*y)+2*p2*x*y],-1)
|
| 46 |
+
slope=k1+2*k2*r2+3*k3*r2*r2
|
| 47 |
+
cross=2*x*y*slope+2*p1*x+2*p2*y
|
| 48 |
+
jac=np.stack([radial+2*x*x*slope+2*p1*y+6*p2*x,cross,
|
| 49 |
+
cross,radial+2*y*y*slope+6*p1*y+2*p2*x],-1).reshape(*x.shape,2,2)
|
| 50 |
+
return xy_out,jac
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _rays(pixels,camera):
|
| 54 |
+
import cv2
|
| 55 |
+
k=np.array([[camera.fx,0,camera.cx],[0,camera.fy,camera.cy],[0,0,1]],float)
|
| 56 |
+
pixels=np.asarray(pixels,float);flat=pixels.reshape(-1,2)
|
| 57 |
+
d=np.asarray(camera.distortion or (0.,)*5,float)
|
| 58 |
+
undistorted=cv2.undistortPointsIter(flat[:,None,:],k,d,None,None,
|
| 59 |
+
(cv2.TERM_CRITERIA_COUNT|cv2.TERM_CRITERIA_EPS,60,1e-12)).reshape(-1,2)
|
| 60 |
+
if not np.isfinite(undistorted).all():raise Unreliable('camera_undistortion_unreliable')
|
| 61 |
+
distorted,jac=_distort(undistorted,d)
|
| 62 |
+
projected=distorted*[camera.fx,camera.fy]+[camera.cx,camera.cy]
|
| 63 |
+
residual=float(np.linalg.norm(projected-flat,axis=-1).max())
|
| 64 |
+
singular=np.linalg.svd(jac,compute_uv=False)
|
| 65 |
+
if (not math.isfinite(residual) or residual>LIMITS['maximum_undistortion_residual_px']
|
| 66 |
+
or np.any(np.linalg.det(jac)<=0) or np.any(singular[:,-1]<=1e-8)
|
| 67 |
+
or np.any(singular[:,0]/singular[:,-1]>LIMITS['maximum_distortion_jacobian_condition'])):
|
| 68 |
+
raise Unreliable('camera_undistortion_unreliable')
|
| 69 |
+
# Radial monotonicity on the full radius interval, including polynomial extrema.
|
| 70 |
+
maximum=float(np.max(np.sum(undistorted*undistorted,axis=-1)))
|
| 71 |
+
k1,k2,_,_,k3=d
|
| 72 |
+
for polynomial in ([k3,k2,k1,1.],[7*k3,5*k2,3*k1,1.]):
|
| 73 |
+
candidates=[0.,maximum]
|
| 74 |
+
for root in np.roots(np.polyder(polynomial)):
|
| 75 |
+
if abs(root.imag)<1e-9 and 0<root.real<maximum:candidates.append(float(root.real))
|
| 76 |
+
if min(np.polyval(polynomial,candidates))<=1e-8:raise Unreliable('camera_distortion_not_monotonic')
|
| 77 |
+
rays=np.concatenate([undistorted,np.ones((len(flat),1))],-1)
|
| 78 |
+
return rays.reshape(*pixels.shape[:-1],3),residual
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _direction(rays,up):
|
| 82 |
+
rays=np.asarray(rays,float);up=np.asarray(up,float)
|
| 83 |
+
incidence=np.sum(_unit(rays)*up,axis=-1)
|
| 84 |
+
if np.any(incidence>=0):raise Unreliable('floor_points_not_below_horizon')
|
| 85 |
+
if np.any(-incidence<np.sin(np.radians(LIMITS['minimum_floor_incidence_deg']))):
|
| 86 |
+
raise Unreliable('floor_points_too_near_horizon')
|
| 87 |
+
hits=-rays/np.sum(rays*up,axis=-1,keepdims=True)
|
| 88 |
+
delta=hits[...,1,:]-hits[...,0,:]
|
| 89 |
+
return _unit(delta),np.degrees(np.arcsin(np.clip(-incidence,0,1)))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def resolve(options,capture,up_reference):
|
| 93 |
+
out=reference(options)
|
| 94 |
+
if options.pitcher_vector is not None or options.pitcher_floor_points is None:return out
|
| 95 |
+
chosen=options.pitcher_floor_points
|
| 96 |
+
out.update(selection=chosen.model_dump(mode='json'),limits=dict(LIMITS),
|
| 97 |
+
implementation_sha256=sha256_file(Path(__file__)),
|
| 98 |
+
assumptions=['both_selected_points_on_same_level_floor','camera_above_floor',
|
| 99 |
+
'first_point_near_batter_second_toward_pitcher','supplied_calibration_applies_to_upright_source_image'],
|
| 100 |
+
floor_points_verified_by_backend=False,calibration_accuracy_verified_by_backend=False,
|
| 101 |
+
up_reference_status=up_reference.get('status'))
|
| 102 |
+
try:
|
| 103 |
+
if chosen.source_frame_index>=len(capture['frames']):raise Unreliable('floor_source_frame_out_of_range')
|
| 104 |
+
frame=capture['frames'][chosen.source_frame_index];w,h=frame['width'],frame['height']
|
| 105 |
+
out['source_frame']={'source_frame_index':chosen.source_frame_index,'image_width':w,'image_height':h,
|
| 106 |
+
'source_pts':frame['pts'],'source_time_base':frame['time_base'],
|
| 107 |
+
'video_time_s':frame['playback_s']-capture['frames'][0]['playback_s']}
|
| 108 |
+
pixels=np.array([chosen.near_batter,chosen.toward_pitcher],float)
|
| 109 |
+
def inside(points):return bool(np.all((points>=[0,0])&(points<=[w-1,h-1])))
|
| 110 |
+
if not inside(pixels):raise Unreliable('floor_points_outside_source_image')
|
| 111 |
+
separation=float(np.linalg.norm(pixels[1]-pixels[0]));out['pixel_separation_px']=separation
|
| 112 |
+
if separation<LIMITS['minimum_point_separation_px']:raise Unreliable('floor_points_too_close')
|
| 113 |
+
if options.camera_stability!='fixed_verified':raise Unreliable('camera_not_fixed_for_pitcher_reference')
|
| 114 |
+
if any(f['width']!=w or f['height']!=h for f in capture['frames']):raise Unreliable('source_image_dimensions_changed')
|
| 115 |
+
camera=options.camera
|
| 116 |
+
if camera is None:raise Unreliable('pitcher_camera_calibration_missing')
|
| 117 |
+
out['camera_calibration']=camera.model_dump(mode='json')
|
| 118 |
+
if camera.calibration_status!='calibrated':raise Unreliable('pitcher_camera_calibration_unverified')
|
| 119 |
+
if not camera.source.strip():raise Unreliable('pitcher_camera_calibration_unverified')
|
| 120 |
+
fov=np.degrees(2*np.arctan(np.array([w,h])/(2*np.array([camera.fx,camera.fy]))))
|
| 121 |
+
if (not 0<=camera.cx<w or not 0<=camera.cy<h
|
| 122 |
+
or np.any(fov<LIMITS['minimum_field_of_view_deg']) or np.any(fov>LIMITS['maximum_field_of_view_deg'])):
|
| 123 |
+
raise Unreliable('pitcher_camera_calibration_implausible')
|
| 124 |
+
if options.up_vector is None:raise Unreliable('pitcher_up_reference_unknown')
|
| 125 |
+
if up_reference.get('status') not in ('provided','estimated'):raise Unreliable('pitcher_up_reference_unknown')
|
| 126 |
+
if up_reference.get('status')=='estimated' and up_reference.get('reliable') is not True:
|
| 127 |
+
raise Unreliable('pitcher_up_reference_unreliable')
|
| 128 |
+
up=_unit(options.up_vector);out['up_vector_used']=up.tolist()
|
| 129 |
+
up_spread=chosen.up_sensitivity_deg
|
| 130 |
+
if up_reference.get('status')=='estimated':
|
| 131 |
+
uncertainty=up_reference.get('maximum_model_uncertainty_deg');deviation=up_reference.get('maximum_deviation_deg')
|
| 132 |
+
if (uncertainty is None or deviation is None or not math.isfinite(uncertainty+deviation)
|
| 133 |
+
or uncertainty<=0 or deviation<0):raise Unreliable('pitcher_up_uncertainty_unknown')
|
| 134 |
+
up_spread=max(up_spread,uncertainty+deviation)
|
| 135 |
+
out['up_sensitivity_deg_used']=float(up_spread)
|
| 136 |
+
grid=np.stack(np.meshgrid(np.linspace(0,w-1,21),np.linspace(0,h-1,21)),-1).reshape(-1,2)
|
| 137 |
+
_,grid_error=_rays(grid,camera)
|
| 138 |
+
rays,residual=_rays(pixels,camera)
|
| 139 |
+
direction,incidence=_direction(rays,up)
|
| 140 |
+
out.update(ray_floor_incidence_deg=incidence.tolist(),maximum_undistortion_residual_px=max(grid_error,residual))
|
| 141 |
+
offsets=np.array(list(product([-chosen.selection_uncertainty_px,chosen.selection_uncertainty_px],repeat=4)))
|
| 142 |
+
scenarios=np.concatenate([pixels[None],pixels+offsets.reshape(-1,2,2)])
|
| 143 |
+
if not inside(scenarios):raise Unreliable('floor_point_uncertainty_outside_source_image')
|
| 144 |
+
sampled_rays,_=_rays(scenarios,camera)
|
| 145 |
+
e=np.eye(3)[int(np.argmin(np.abs(up)))];e=_unit(e-np.dot(e,up)*up);f=np.cross(up,e)
|
| 146 |
+
azimuth=np.arange(16)*2*np.pi/16;angle=np.radians(up_spread)
|
| 147 |
+
ups=np.concatenate([up[None],np.cos(angle)*up+np.sin(angle)*(np.cos(azimuth)[:,None]*e+np.sin(azimuth)[:,None]*f)])
|
| 148 |
+
try:vectors,_=_direction(sampled_rays[None],ups[:,None,None,:])
|
| 149 |
+
except Unreliable as error:raise Unreliable('floor_direction_uncertainty_unreliable') from error
|
| 150 |
+
spread=float(np.degrees(np.arccos(np.clip(vectors@direction,-1,1))).max())
|
| 151 |
+
out.update(maximum_direction_deviation_deg=spread,evaluated_scenarios=int(np.prod(vectors.shape[:-1])),
|
| 152 |
+
sensitivity_kind='sampled_pixel_and_up_perturbations; not an accuracy interval')
|
| 153 |
+
if spread>LIMITS['maximum_direction_deviation_deg']:raise Unreliable('floor_direction_uncertainty_too_high')
|
| 154 |
+
source=f'Two user-selected floor points at source frame {chosen.source_frame_index}; calibrated ray-plane intersection with level floor and camera above floor (estimated)'
|
| 155 |
+
out.update(status='estimated',pitcher_vector=direction.tolist(),pitcher_source=source,
|
| 156 |
+
applied=True,reliable=True,reason_code=None)
|
| 157 |
+
except Unreliable as error:out['reason_code']=str(error)
|
| 158 |
+
except (ValueError,ArithmeticError,np.linalg.LinAlgError) as error:
|
| 159 |
+
out.update(reason_code='floor_direction_geometry_failed',error_type=type(error).__name__)
|
| 160 |
+
# OpenCV errors are not ValueError; numerical calibration failure is still an unknown reference.
|
| 161 |
+
except Exception as error:
|
| 162 |
+
import cv2
|
| 163 |
+
if not isinstance(error,cv2.error):raise
|
| 164 |
+
out.update(reason_code='camera_undistortion_unreliable',error_type=type(error).__name__)
|
| 165 |
+
return out
|
docs/APP_API_INTEGRATION.md
CHANGED
|
@@ -175,6 +175,7 @@ Example **only when the uploader confirms these recording facts**:
|
|
| 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`.
|
|
@@ -382,6 +383,21 @@ Additional reason codes: `camera_up_provider_unavailable`,
|
|
| 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.
|
|
|
|
| 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 |
+
| `pitcher_floor_points` | Optional source-frame index and two upright source-image floor points, first near the batter and second toward the pitcher. Derived camera-space field direction requires applicable `camera` calibration marked `calibration_status: "calibrated"` and a supplied/accepted estimated up reference. |
|
| 179 |
|
| 180 |
Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
|
| 181 |
`pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
|
|
|
|
| 383 |
`insufficient_camera_up_temporal_coverage`, `camera_up_estimation_failed`, and
|
| 384 |
`automatic_up_estimation_disabled`. See [estimator details](CAMERA_UP_ESTIMATION.md).
|
| 385 |
|
| 386 |
+
### Pitcher direction from selected floor points
|
| 387 |
+
|
| 388 |
+
Motion API 1.14.0 supports `pitcher_floor_points` for both models. The frontend
|
| 389 |
+
sends `source_frame_index`, `near_batter: [x,y]`, and `toward_pitcher: [x,y]`
|
| 390 |
+
in upright original source pixels. The camera needs `calibration_status:
|
| 391 |
+
"calibrated"`; the default is `unknown`. Camera height is not required. Omitted
|
| 392 |
+
up uses the existing automatic estimator; a manual pitcher vector always wins.
|
| 393 |
+
|
| 394 |
+
Read `coordinates.pitcher_vector`, `pitcher_source`, `pitcher_vector_frame`, and
|
| 395 |
+
`pitcher_estimation`. Display estimated/provided/unknown according to its `status`;
|
| 396 |
+
unknown includes a reason and never substitutes a 2D arrow. Reliability checks
|
| 397 |
+
are conditional engineering checks, not an accuracy probability. The derived
|
| 398 |
+
vector/source enter `pipeline.calculation_inputs`; original inputs stay unchanged.
|
| 399 |
+
See [request, response, coordinate mapping and reason codes](PITCHER_FLOOR_DIRECTION.md).
|
| 400 |
+
|
| 401 |
## 7. Play the annotated videos
|
| 402 |
|
| 403 |
Only enable a player when its artifact has `status: "available"` and a URL.
|
docs/MOTION_PLAYER_API.md
CHANGED
|
@@ -106,6 +106,13 @@ 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
|
|
|
|
| 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 |
+
To derive field direction, send `pitcher_floor_points` with `source_frame_index`,
|
| 110 |
+
`near_batter` and `toward_pitcher` in upright source pixels. This uses supplied
|
| 111 |
+
camera calibration marked `camera.calibration_status: "calibrated"` and supplied
|
| 112 |
+
or accepted estimated up. Explicit pitcher vectors take priority. Returned
|
| 113 |
+
`coordinates.pitcher_estimation` records the source, assumptions and rejection
|
| 114 |
+
reasons. See [floor-point direction and FE integration](PITCHER_FLOOR_DIRECTION.md).
|
| 115 |
+
|
| 116 |
## Native-body refinement
|
| 117 |
|
| 118 |
New motion jobs enable `refinement.enabled` by default. Existing engine and SAM
|
docs/MOTION_REQUIREMENTS_AUDIT.md
CHANGED
|
@@ -18,7 +18,7 @@ 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 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. |
|
|
|
|
| 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. Two selected upright-image floor points can derive pitcher direction using declared calibrated intrinsics and the supplied/accepted estimated up reference; ray/horizon, distortion and perturbation checks reject unreliable geometry. Manual vectors take priority. 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. |
|
docs/PITCHER_FLOOR_DIRECTION.md
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pitcher direction from two floor points
|
| 2 |
+
|
| 3 |
+
Motion API 1.14.0 · SAM 3D Body and GVHMR · 19 October 2026
|
| 4 |
+
|
| 5 |
+
Use the existing `/v1/motion-analyses` upload and `/revisions` routes. Select a
|
| 6 |
+
decoded source frame and two points **on the same level floor**: first near the
|
| 7 |
+
batter, then farther along the floor toward the pitcher. They need not be at
|
| 8 |
+
the pitcher's feet. Their order defines the positive direction; reversing the
|
| 9 |
+
points reverses the vector. This is a field direction, not the ball trajectory.
|
| 10 |
+
|
| 11 |
+
## Request
|
| 12 |
+
|
| 13 |
+
Add `pitcher_floor_points` to the multipart form's `options` JSON. Example for
|
| 14 |
+
an **illustrative 1920 × 1080 source**, with illustrative calibration values;
|
| 15 |
+
use the actual camera's calibration rather than copying these numbers:
|
| 16 |
+
|
| 17 |
+
```json
|
| 18 |
+
{
|
| 19 |
+
"model": "gvhmr",
|
| 20 |
+
"annotated_videos": true,
|
| 21 |
+
"camera_stability": "fixed_verified",
|
| 22 |
+
"camera": {
|
| 23 |
+
"fx": 1100,
|
| 24 |
+
"fy": 1050,
|
| 25 |
+
"cx": 925,
|
| 26 |
+
"cy": 500,
|
| 27 |
+
"source": "Calibration procedure and recording configuration",
|
| 28 |
+
"calibration_status": "calibrated",
|
| 29 |
+
"distortion": [0, 0, 0, 0, 0]
|
| 30 |
+
},
|
| 31 |
+
"pitcher_floor_points": {
|
| 32 |
+
"source_frame_index": 40,
|
| 33 |
+
"near_batter": [650, 893.75],
|
| 34 |
+
"toward_pitcher": [1291.666666667, 762.5],
|
| 35 |
+
"selection_uncertainty_px": 2,
|
| 36 |
+
"up_sensitivity_deg": 1
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Use `"model":"sam3d"` for SAM; every other field and response stays the same.
|
| 42 |
+
Omit `up_vector`/`up_source` to use the existing automatic GeoCalib estimate.
|
| 43 |
+
Alternatively supply the known camera-space up vector and its source. An
|
| 44 |
+
unreliable or missing up reference leaves the floor direction unknown.
|
| 45 |
+
|
| 46 |
+
| Field | Contract |
|
| 47 |
+
| --- | --- |
|
| 48 |
+
| `pitcher_floor_points` | Optional object; omit/null when no selection is available. |
|
| 49 |
+
| `source_frame_index` | Required, zero-based decoded **source** frame index, integer ≥ 0. Both points belong to this frame. |
|
| 50 |
+
| `near_batter` | Required `[x,y]`, upright original source-image pixels, first point. |
|
| 51 |
+
| `toward_pitcher` | Required `[x,y]`, same frame/pixel convention, second point. |
|
| 52 |
+
| `selection_uncertainty_px` | Optional positive perturbation radius per pixel coordinate; default 2 source pixels, maximum 25. Increase for coarse selections. This is a sensitivity assumption, not measured click accuracy. |
|
| 53 |
+
| `up_sensitivity_deg` | Optional positive up-direction perturbation angle; default 1°, maximum 30°. For estimated up, the calculation uses at least the model uncertainty plus frame disagreement; this field cannot lower that test. |
|
| 54 |
+
| `camera.calibration_status` | New motion-only field: `unknown` (default), `estimated`, or `calibrated`. Floor direction requires `calibrated`; set this only for calibration that applies to this recording's upright image, crop, resolution, zoom and lens configuration. |
|
| 55 |
+
| `camera.fx/fy/cx/cy/source` | Existing camera calibration fields. Focal lengths and principal point are in upright source-image pixels. A source description is required. |
|
| 56 |
+
| `camera.distortion` | Existing optional Brown–Conrady `[k1,k2,p1,p2,k3]`. Omitted/null means a pinhole assumption; use it only when appropriate for the calibrated source. |
|
| 57 |
+
| `pitcher_vector/pitcher_source` | Existing manual override. When supplied, it wins over floor points, even if floor points/calibration would be unusable. Original values and magnitude stay unchanged. |
|
| 58 |
+
|
| 59 |
+
`calibration_status` does not change existing body reconstruction or up
|
| 60 |
+
estimation. Older motion requests continue to work, defaulting it to `unknown`;
|
| 61 |
+
they cannot silently promote a guessed focal length into floor calibration.
|
| 62 |
+
SAM/GVHMR body-model intrinsics and GeoCalib's internal focal estimate are not
|
| 63 |
+
substituted for the required declared calibration. This option belongs to the
|
| 64 |
+
motion API; legacy SAM/coaching request contracts remain separate.
|
| 65 |
+
|
| 66 |
+
## Frontend coordinate mapping
|
| 67 |
+
|
| 68 |
+
Use `source_video.display_width/display_height` and the upright source frame.
|
| 69 |
+
Coordinates are **not** CSS pixels, raw rotated-file pixels, the skeleton's
|
| 70 |
+
3D coordinates, or the smaller annotated-video dimensions. Account for preview
|
| 71 |
+
scaling, cropping, and letterboxing:
|
| 72 |
+
|
| 73 |
+
```text
|
| 74 |
+
x_source = (x_in_preview - content_left) * source_width / content_width
|
| 75 |
+
y_source = (y_in_preview - content_top) * source_height / content_height
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Undo any frontend-only mirror transform before sending coordinates. The backend
|
| 79 |
+
does not mirror selections. Select the source-frame index using the returned
|
| 80 |
+
frame records and actual source/video timestamps; do not calculate it from
|
| 81 |
+
`currentTime * FPS`, because the recording can have variable frame timing.
|
| 82 |
+
Both points must come from the same displayed frame and actually touch the floor,
|
| 83 |
+
not a knee, elevated tee, distant wall, or projected line above the ground.
|
| 84 |
+
|
| 85 |
+
To add or correct points after an analysis, submit:
|
| 86 |
+
|
| 87 |
+
```json
|
| 88 |
+
{
|
| 89 |
+
"options": {
|
| 90 |
+
"pitcher_floor_points": {
|
| 91 |
+
"source_frame_index": 40,
|
| 92 |
+
"near_batter": [650, 893.75],
|
| 93 |
+
"toward_pitcher": [1291.666666667, 762.5]
|
| 94 |
+
},
|
| 95 |
+
"pitcher_vector": null,
|
| 96 |
+
"pitcher_source": null
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Send this to `POST /v1/motion-analyses/{job_id}/revisions`. Clearing a previous
|
| 102 |
+
manual vector is necessary to enable floor estimation. Existing calibration and
|
| 103 |
+
other recording facts are inherited. The parent stays immutable. Point-only
|
| 104 |
+
changes can reuse verified native inference; calibration changes may require
|
| 105 |
+
new inference. To remove the selection, revise `pitcher_floor_points` to null.
|
| 106 |
+
|
| 107 |
+
## Response
|
| 108 |
+
|
| 109 |
+
Read the completed manifest's `coordinates`. The following is an illustrative
|
| 110 |
+
excerpt; actual vectors and diagnostics depend on the recording and selection:
|
| 111 |
+
|
| 112 |
+
```json
|
| 113 |
+
{
|
| 114 |
+
"pitcher_vector": [0.8320502943, 0, 0.5547001962],
|
| 115 |
+
"pitcher_source": "Two user-selected floor points at source frame 40; calibrated ray-plane intersection with level floor and camera above floor (estimated)",
|
| 116 |
+
"pitcher_vector_frame": "upright_camera_x_right_y_down_z_away",
|
| 117 |
+
"pitcher_estimation": {
|
| 118 |
+
"status": "estimated",
|
| 119 |
+
"method": "two_floor_points_ray_plane_v1",
|
| 120 |
+
"applied": true,
|
| 121 |
+
"reliable": true,
|
| 122 |
+
"confidence": null,
|
| 123 |
+
"accuracy_validated": false,
|
| 124 |
+
"reason_code": null
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
The full `pitcher_estimation` also repeats its vector/source and includes:
|
| 130 |
+
|
| 131 |
+
- `selection` and `source_frame`: original selection, actual source-frame index,
|
| 132 |
+
dimensions, PTS/time base and video timestamp.
|
| 133 |
+
- `camera_calibration`, `up_vector_used`, `up_reference_status`: inputs used by
|
| 134 |
+
the geometry. The up vector here is normalized for calculation.
|
| 135 |
+
- `ray_floor_incidence_deg`, `pixel_separation_px`,
|
| 136 |
+
`maximum_undistortion_residual_px`: geometric checks.
|
| 137 |
+
- `up_sensitivity_deg_used`, `maximum_direction_deviation_deg`,
|
| 138 |
+
`evaluated_scenarios`, `sensitivity_kind`, and `limits`: sensitivity diagnostics
|
| 139 |
+
and the acceptance thresholds.
|
| 140 |
+
- `assumptions`, `floor_points_verified_by_backend: false`,
|
| 141 |
+
`calibration_accuracy_verified_by_backend: false`, and the implementation hash.
|
| 142 |
+
|
| 143 |
+
Display **Estimated pitcher direction** for `status: estimated`. Derived vectors
|
| 144 |
+
are normalized and in camera axes **x right, y down, z away**. They are not in
|
| 145 |
+
the rotated skeleton/export axes. `reliable: true` means the conditional
|
| 146 |
+
engineering checks passed; it is not a probability or independent accuracy
|
| 147 |
+
validation. Keep `confidence: null` as unknown, not 0%.
|
| 148 |
+
|
| 149 |
+
For `provided`, display **User-supplied pitcher direction**. The vector/source
|
| 150 |
+
remain exact, `method` is `caller_supplied`, and `reliable` is null. For `unknown`,
|
| 151 |
+
both effective vector and source are null, `applied/reliable` are false, and
|
| 152 |
+
`reason_code` explains why. Do not turn the 2D arrow into a substitute vector.
|
| 153 |
+
|
| 154 |
+
Original validated facts remain in `pipeline.inputs`; the derived vector/source
|
| 155 |
+
are added only to `pipeline.calculation_inputs`. The same reference is included
|
| 156 |
+
as `pitcher_reference` in measurement and quality artifacts. Measurement summaries
|
| 157 |
+
and series contain `pitcher_reference_status`; available field-axis-dependent
|
| 158 |
+
summaries carry `pitcher_reference_estimated_from_floor_points`.
|
| 159 |
+
|
| 160 |
+
Accepted direction sets the measurement/export X axis toward the pitcher. The
|
| 161 |
+
existing frame identifier `declared_field_axes` remains for compatibility;
|
| 162 |
+
`pitcher_estimation.status` records whether that field axis was derived or
|
| 163 |
+
manually provided. Measurements and public-artifact reproduction use the same
|
| 164 |
+
effective reference. Physical clock, body-point quality, scale, reviewed events,
|
| 165 |
+
and other measurement guards still apply. This direction does not provide ground
|
| 166 |
+
positions, camera height, floor distances, or a calibrated ground trajectory.
|
| 167 |
+
|
| 168 |
+
## Calculation and rejection checks
|
| 169 |
+
|
| 170 |
+
Undistort the two pixels using the supplied calibration, then form optical rays
|
| 171 |
+
`r = [x_normalized, y_normalized, 1]`. With normalized camera-up `u` and a camera
|
| 172 |
+
at positive unknown height `h` above the level floor, the floor plane is
|
| 173 |
+
`u·X = -h`. Each hit is `X = -h*r/(u·r)`. Therefore:
|
| 174 |
+
|
| 175 |
+
```text
|
| 176 |
+
q_near = -r_near / dot(u, r_near)
|
| 177 |
+
q_toward = -r_toward / dot(u, r_toward)
|
| 178 |
+
pitcher_vector = normalize(q_toward - q_near)
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
Height cancels, while perspective and the first-to-second sign are retained.
|
| 182 |
+
Subtracting raw pixel positions or projecting a 2D arrow onto the floor is not
|
| 183 |
+
this calculation. Pixel/ray and distortion conventions follow the
|
| 184 |
+
[OpenCV camera model](https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html).
|
| 185 |
+
|
| 186 |
+
Acceptance requires fixed verified camera orientation, no observed static-camera
|
| 187 |
+
conflict, a valid source index, consistent source dimensions, in-image points
|
| 188 |
+
at least 10 pixels apart, declared calibrated intrinsics, plausible focal/principal
|
| 189 |
+
point values, finite monotonic distortion geometry, ≤ 0.1-pixel undistortion
|
| 190 |
+
round-trip error, and both floor rays at least 3° below the horizon.
|
| 191 |
+
|
| 192 |
+
The backend perturbs each click coordinate by its selection uncertainty and
|
| 193 |
+
samples an up-direction cone at 16 azimuths plus its center: 289 combined
|
| 194 |
+
scenarios. Every sampled ray must still hit a well-conditioned visible floor;
|
| 195 |
+
the maximum direction change must be ≤ 10°. These are engineering gates, not
|
| 196 |
+
guaranteed error bounds. A consistent wrong calibration, wrong up direction,
|
| 197 |
+
sloping/nonplanar floor, or a tap on an elevated object can still produce a wrong
|
| 198 |
+
direction. The backend cannot establish those facts from two clicks.
|
| 199 |
+
|
| 200 |
+
Common unknown reasons:
|
| 201 |
+
|
| 202 |
+
| `reason_code` | FE action |
|
| 203 |
+
| --- | --- |
|
| 204 |
+
| `floor_points_not_supplied` | Offer the two-point selection. |
|
| 205 |
+
| `floor_source_frame_out_of_range` | Re-select a source frame from this recording. |
|
| 206 |
+
| `floor_points_outside_source_image` | Correct preview-to-source coordinate mapping. |
|
| 207 |
+
| `floor_point_uncertainty_outside_source_image` | Select points farther from image borders. |
|
| 208 |
+
| `floor_points_too_close` | Select floor points farther apart. |
|
| 209 |
+
| `floor_points_not_below_horizon` | Select visible floor below the horizon; check up/calibration. |
|
| 210 |
+
| `floor_points_too_near_horizon` | Choose nearer, better-conditioned floor points. |
|
| 211 |
+
| `camera_not_fixed_for_pitcher_reference` | Verify a fixed recording or re-record with a fixed camera. |
|
| 212 |
+
| `source_image_dimensions_changed` | Supply a recording/calibration with consistent source dimensions. |
|
| 213 |
+
| `pitcher_camera_calibration_missing` | Provide applicable camera calibration. |
|
| 214 |
+
| `pitcher_camera_calibration_unverified` | Use verified calibration; do not relabel guessed intrinsics. |
|
| 215 |
+
| `pitcher_camera_calibration_implausible` | Check focal lengths, principal point, crop and resolution. |
|
| 216 |
+
| `camera_undistortion_unreliable`, `camera_distortion_not_monotonic` | Check the lens model/calibration. |
|
| 217 |
+
| `pitcher_up_reference_unknown`, `pitcher_up_reference_unreliable`, `pitcher_up_uncertainty_unknown` | Resolve the up reference before estimating direction. |
|
| 218 |
+
| `floor_direction_uncertainty_unreliable`, `floor_direction_uncertainty_too_high` | Use a better-separated selection away from the horizon; check up/calibration. |
|
| 219 |
+
| `floor_direction_geometry_failed`, `invalid_direction_geometry` | Recheck the selection and calibration. |
|
| 220 |
+
|
| 221 |
+
Geometrically unusable inputs leave this reference unknown without failing an
|
| 222 |
+
otherwise usable motion analysis. Malformed JSON/options still return 422;
|
| 223 |
+
ordinary upload, native-model, queue and artifact errors keep their existing
|
| 224 |
+
semantics. Capabilities expose `pitcher_direction_from_floor_points`.
|
docs/motion-input.schema.json
CHANGED
|
@@ -248,6 +248,16 @@
|
|
| 248 |
],
|
| 249 |
"default": null,
|
| 250 |
"title": "Distortion"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
}
|
| 252 |
},
|
| 253 |
"required": [
|
|
@@ -293,6 +303,65 @@
|
|
| 293 |
"title": "MotionTrackingSettings",
|
| 294 |
"type": "object"
|
| 295 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
"RefinementSettings": {
|
| 297 |
"additionalProperties": false,
|
| 298 |
"properties": {
|
|
@@ -1029,6 +1098,17 @@
|
|
| 1029 |
},
|
| 1030 |
"up_estimation": {
|
| 1031 |
"$ref": "#/$defs/UpEstimationSettings"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1032 |
}
|
| 1033 |
},
|
| 1034 |
"title": "MotionInput",
|
|
|
|
| 248 |
],
|
| 249 |
"default": null,
|
| 250 |
"title": "Distortion"
|
| 251 |
+
},
|
| 252 |
+
"calibration_status": {
|
| 253 |
+
"default": "unknown",
|
| 254 |
+
"enum": [
|
| 255 |
+
"unknown",
|
| 256 |
+
"estimated",
|
| 257 |
+
"calibrated"
|
| 258 |
+
],
|
| 259 |
+
"title": "Calibration Status",
|
| 260 |
+
"type": "string"
|
| 261 |
}
|
| 262 |
},
|
| 263 |
"required": [
|
|
|
|
| 303 |
"title": "MotionTrackingSettings",
|
| 304 |
"type": "object"
|
| 305 |
},
|
| 306 |
+
"PitcherFloorPoints": {
|
| 307 |
+
"additionalProperties": false,
|
| 308 |
+
"properties": {
|
| 309 |
+
"source_frame_index": {
|
| 310 |
+
"minimum": 0,
|
| 311 |
+
"title": "Source Frame Index",
|
| 312 |
+
"type": "integer"
|
| 313 |
+
},
|
| 314 |
+
"near_batter": {
|
| 315 |
+
"maxItems": 2,
|
| 316 |
+
"minItems": 2,
|
| 317 |
+
"prefixItems": [
|
| 318 |
+
{
|
| 319 |
+
"type": "number"
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"type": "number"
|
| 323 |
+
}
|
| 324 |
+
],
|
| 325 |
+
"title": "Near Batter",
|
| 326 |
+
"type": "array"
|
| 327 |
+
},
|
| 328 |
+
"toward_pitcher": {
|
| 329 |
+
"maxItems": 2,
|
| 330 |
+
"minItems": 2,
|
| 331 |
+
"prefixItems": [
|
| 332 |
+
{
|
| 333 |
+
"type": "number"
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"type": "number"
|
| 337 |
+
}
|
| 338 |
+
],
|
| 339 |
+
"title": "Toward Pitcher",
|
| 340 |
+
"type": "array"
|
| 341 |
+
},
|
| 342 |
+
"selection_uncertainty_px": {
|
| 343 |
+
"default": 2.0,
|
| 344 |
+
"exclusiveMinimum": 0,
|
| 345 |
+
"maximum": 25,
|
| 346 |
+
"title": "Selection Uncertainty Px",
|
| 347 |
+
"type": "number"
|
| 348 |
+
},
|
| 349 |
+
"up_sensitivity_deg": {
|
| 350 |
+
"default": 1.0,
|
| 351 |
+
"exclusiveMinimum": 0,
|
| 352 |
+
"maximum": 30,
|
| 353 |
+
"title": "Up Sensitivity Deg",
|
| 354 |
+
"type": "number"
|
| 355 |
+
}
|
| 356 |
+
},
|
| 357 |
+
"required": [
|
| 358 |
+
"source_frame_index",
|
| 359 |
+
"near_batter",
|
| 360 |
+
"toward_pitcher"
|
| 361 |
+
],
|
| 362 |
+
"title": "PitcherFloorPoints",
|
| 363 |
+
"type": "object"
|
| 364 |
+
},
|
| 365 |
"RefinementSettings": {
|
| 366 |
"additionalProperties": false,
|
| 367 |
"properties": {
|
|
|
|
| 1098 |
},
|
| 1099 |
"up_estimation": {
|
| 1100 |
"$ref": "#/$defs/UpEstimationSettings"
|
| 1101 |
+
},
|
| 1102 |
+
"pitcher_floor_points": {
|
| 1103 |
+
"anyOf": [
|
| 1104 |
+
{
|
| 1105 |
+
"$ref": "#/$defs/PitcherFloorPoints"
|
| 1106 |
+
},
|
| 1107 |
+
{
|
| 1108 |
+
"type": "null"
|
| 1109 |
+
}
|
| 1110 |
+
],
|
| 1111 |
+
"default": null
|
| 1112 |
}
|
| 1113 |
},
|
| 1114 |
"title": "MotionInput",
|
docs/motion-options.example.json
CHANGED
|
@@ -102,5 +102,6 @@
|
|
| 102 |
"maximum_up_residual_deg": 10.0,
|
| 103 |
"maximum_latitude_residual_deg": 5.0,
|
| 104 |
"minimum_texture_fraction": 0.005
|
| 105 |
-
}
|
|
|
|
| 106 |
}
|
|
|
|
| 102 |
"maximum_up_residual_deg": 10.0,
|
| 103 |
"maximum_latitude_residual_deg": 5.0,
|
| 104 |
"minimum_texture_fraction": 0.005
|
| 105 |
+
},
|
| 106 |
+
"pitcher_floor_points": null
|
| 107 |
}
|
tests/test_motion_player_api.py
CHANGED
|
@@ -39,7 +39,9 @@ def test_motion_upload_auth_readiness_validation_queue_and_cancel(tmp_path,video
|
|
| 39 |
assert client.get(data['result_url'],headers=AUTH).status_code==409
|
| 40 |
assert client.get(data['status_url'],headers=AUTH).json()['analysis_revision']==1
|
| 41 |
assert client.delete(data['status_url'],headers=AUTH).status_code==202
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
assert not job.exists()
|
| 44 |
assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
|
| 45 |
assert client.get('/v1/motion-analyses/input-schema').status_code==401
|
|
@@ -123,3 +125,34 @@ def test_failed_job_reservation_does_not_leak_queue_slots(tmp_path,video,monkeyp
|
|
| 123 |
assert db.execute('SELECT COUNT(*) FROM jobs').fetchone()[0]==0
|
| 124 |
assert db.execute('SELECT COUNT(*) FROM motion_revisions').fetchone()[0]==0
|
| 125 |
assert not list(service.jobs_root.iterdir())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
assert client.get(data['result_url'],headers=AUTH).status_code==409
|
| 40 |
assert client.get(data['status_url'],headers=AUTH).json()['analysis_revision']==1
|
| 41 |
assert client.delete(data['status_url'],headers=AUTH).status_code==202
|
| 42 |
+
# The public status route holds the mutation lock through cleanup; a raw
|
| 43 |
+
# SQLite read can see the intermediate state before rmtree finishes.
|
| 44 |
+
wait_until(lambda:client.get(data['status_url'],headers=AUTH).json()['status']=='cancelled')
|
| 45 |
assert not job.exists()
|
| 46 |
assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
|
| 47 |
assert client.get('/v1/motion-analyses/input-schema').status_code==401
|
|
|
|
| 125 |
assert db.execute('SELECT COUNT(*) FROM jobs').fetchone()[0]==0
|
| 126 |
assert db.execute('SELECT COUNT(*) FROM motion_revisions').fetchone()[0]==0
|
| 127 |
assert not list(service.jobs_root.iterdir())
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize('model',['sam3d','gvhmr'])
|
| 131 |
+
def test_floor_selection_round_trips_upload_and_revision_without_mutating_parent(tmp_path,video,monkeypatch,model):
|
| 132 |
+
import baseball_batting.motion_api as module
|
| 133 |
+
monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
|
| 134 |
+
monkeypatch.setattr(module.gvhmr_runtime,'configured_record',lambda:{'configured':True})
|
| 135 |
+
service=fake_service(settings(tmp_path),delay=30);parent,manifest=stored(service,video)
|
| 136 |
+
original=(parent/'result.json').read_bytes()
|
| 137 |
+
camera={'fx':100,'fy':110,'cx':80,'cy':40,'source':'Known fixture calibration','calibration_status':'calibrated'}
|
| 138 |
+
points={'source_frame_index':2,'near_batter':[40,100],'toward_pitcher':[120,90]}
|
| 139 |
+
options={'model':model,'camera':camera,'pitcher_floor_points':points}
|
| 140 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 141 |
+
wait_until(lambda:service.ready)
|
| 142 |
+
r=client.post('/v1/motion-analyses',headers=AUTH,
|
| 143 |
+
files={'video':('swing.mp4',video.read_bytes(),'video/mp4')},data={'options':json.dumps(options)})
|
| 144 |
+
assert r.status_code==202,r.text
|
| 145 |
+
job=service.job_directory(r.json()['job_id']);data=json.loads((job/'request.json').read_text())
|
| 146 |
+
assert data['model']==model and data['camera']['calibration_status']=='calibrated'
|
| 147 |
+
assert data['pitcher_floor_points']['source_frame_index']==2
|
| 148 |
+
assert data['pitcher_floor_points']['near_batter']==[40,100]
|
| 149 |
+
client.delete(r.json()['status_url'],headers=AUTH)
|
| 150 |
+
wait_until(lambda:service.store.get(job.name)['status']=='cancelled')
|
| 151 |
+
child=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':options})
|
| 152 |
+
assert child.status_code==202,child.text
|
| 153 |
+
path=service.job_directory(child.json()['job_id']);saved=json.loads((path/'request.json').read_text())
|
| 154 |
+
assert saved['pitcher_floor_points']==data['pitcher_floor_points']
|
| 155 |
+
assert saved['up_vector']==manifest.pipeline['inputs']['up_vector']
|
| 156 |
+
assert (parent/'result.json').read_bytes()==original
|
| 157 |
+
client.delete(child.json()['status_url'],headers=AUTH)
|
| 158 |
+
wait_until(lambda:service.store.get(path.name)['status']=='cancelled')
|
tests/test_pitcher_direction.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent projected floor truth, abstention, and shared adapter integration."""
|
| 2 |
+
import copy
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
from scipy.spatial.transform import Rotation
|
| 7 |
+
from baseball_batting.motion_contract import MotionInput
|
| 8 |
+
from baseball_batting.camera_up import reference
|
| 9 |
+
from baseball_batting.pitcher_direction import resolve
|
| 10 |
+
from baseball_batting.geometry import project
|
| 11 |
+
from baseball_batting.ingest import ingest
|
| 12 |
+
from baseball_batting.motion_export import export_motion,reproduce_measurements
|
| 13 |
+
from test_motion_player import raw_for
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def capture(w=1920,h=1080):
|
| 17 |
+
return {'frames':[{'width':w,'height':h,'pts':i*11,'time_base':'1/1000','playback_s':3+i*.011} for i in range(8)]}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def scene(angles=(0,0,0),height=1.5,distortion=None):
|
| 21 |
+
rotation=Rotation.from_euler('xyz',angles,degrees=True).as_matrix()
|
| 22 |
+
truth=np.array([[-1.,height,4.],[2.,height,6.]])@rotation.T
|
| 23 |
+
up=rotation@np.array([0.,-1.,0.]);direction=truth[1]-truth[0];direction/=np.linalg.norm(direction)
|
| 24 |
+
k=np.array([[900,0,925],[0,900,500],[0,0,1.]])
|
| 25 |
+
pixels=project(truth,k,distortion)
|
| 26 |
+
opts=MotionInput(camera_stability='fixed_verified',up_vector=up,up_source='Known synthetic gravity',
|
| 27 |
+
camera={'fx':900,'fy':900,'cx':925,'cy':500,'source':'Known synthetic camera',
|
| 28 |
+
'distortion':distortion,'calibration_status':'calibrated'},
|
| 29 |
+
pitcher_floor_points={'source_frame_index':3,'near_batter':pixels[0],'toward_pitcher':pixels[1]})
|
| 30 |
+
return opts,direction
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@pytest.mark.parametrize('angles',[(0,0,0),(12,-10,15),(-8,7,-22),(3,25,-10),(-12,-15,28)])
|
| 34 |
+
@pytest.mark.parametrize('distortion',[None,[-.12,.03,.001,-.002,.005]])
|
| 35 |
+
def test_projected_floor_points_recover_camera_direction_with_camera_tilt_and_distortion(angles,distortion):
|
| 36 |
+
opts,truth=scene(angles,distortion=distortion);out=resolve(opts,capture(),reference(opts))
|
| 37 |
+
assert out['status']=='estimated' and out['reliable'] is True,out
|
| 38 |
+
np.testing.assert_allclose(out['pitcher_vector'],truth,atol=1e-9)
|
| 39 |
+
assert np.linalg.norm(out['pitcher_vector'])==pytest.approx(1)
|
| 40 |
+
assert np.dot(out['pitcher_vector'],opts.up_vector)==pytest.approx(0,abs=1e-10)
|
| 41 |
+
assert out['source_frame']['source_frame_index']==3 and out['source_frame']['source_pts']==33
|
| 42 |
+
assert out['source_frame']['video_time_s']==pytest.approx(.033)
|
| 43 |
+
assert out['evaluated_scenarios']==289 and out['confidence'] is None and not out['accuracy_validated']
|
| 44 |
+
assert opts.pitcher_vector is None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_point_order_sets_direction_and_camera_height_is_not_required():
|
| 48 |
+
opts,truth=scene();first=resolve(opts,capture(),reference(opts))
|
| 49 |
+
data=opts.model_dump(mode='json');p=data['pitcher_floor_points'];p['near_batter'],p['toward_pitcher']=p['toward_pitcher'],p['near_batter']
|
| 50 |
+
reverse=resolve(MotionInput(**data),capture(),reference(opts))
|
| 51 |
+
np.testing.assert_allclose(reverse['pitcher_vector'],-truth,atol=1e-10)
|
| 52 |
+
# Scaling all physical camera-relative points preserves the source pixels.
|
| 53 |
+
xyz=np.array([[-1.,1.5,4.],[2.,1.5,6.]])
|
| 54 |
+
k=np.array([[1100,0,925],[0,1050,500],[0,0,1.]])
|
| 55 |
+
np.testing.assert_allclose(project(xyz,k),project(xyz*4.3,k))
|
| 56 |
+
assert first['assumptions'][1]=='camera_above_floor'
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize('patch,reason',[
|
| 60 |
+
({'pitcher_floor_points':{'source_frame_index':8}},'floor_source_frame_out_of_range'),
|
| 61 |
+
({'pitcher_floor_points':{'near_batter':[-1,900]}},'floor_points_outside_source_image'),
|
| 62 |
+
({'pitcher_floor_points':{'near_batter':[0,900]}},'floor_point_uncertainty_outside_source_image'),
|
| 63 |
+
({'pitcher_floor_points':{'near_batter':[700,800],'toward_pitcher':[700,800]}},'floor_points_too_close'),
|
| 64 |
+
({'pitcher_floor_points':{'near_batter':[700,800],'toward_pitcher':[704,801]}},'floor_points_too_close'),
|
| 65 |
+
({'pitcher_floor_points':{'near_batter':[700,500],'toward_pitcher':[1300,850]}},'floor_points_not_below_horizon'),
|
| 66 |
+
({'pitcher_floor_points':{'near_batter':[700,510],'toward_pitcher':[1300,850]}},'floor_points_too_near_horizon'),
|
| 67 |
+
({'pitcher_floor_points':{'near_batter':[700,560],'toward_pitcher':[1300,850]}},'floor_direction_uncertainty_unreliable'),
|
| 68 |
+
({'camera':None},'pitcher_camera_calibration_missing'),
|
| 69 |
+
({'camera':{'calibration_status':'unknown'}},'pitcher_camera_calibration_unverified'),
|
| 70 |
+
({'camera':{'calibration_status':'estimated'}},'pitcher_camera_calibration_unverified'),
|
| 71 |
+
({'camera':{'cx':3000}},'pitcher_camera_calibration_implausible'),
|
| 72 |
+
({'camera':{'fx':1e7}},'pitcher_camera_calibration_implausible'),
|
| 73 |
+
({'camera':{'distortion':[-5,0,0,0,0]}},'camera_undistortion_unreliable'),
|
| 74 |
+
({'up_vector':None,'up_source':None},'pitcher_up_reference_unknown'),
|
| 75 |
+
({'camera_stability':'moving'},'camera_not_fixed_for_pitcher_reference'),
|
| 76 |
+
({'camera_stability':'unknown'},'camera_not_fixed_for_pitcher_reference'),
|
| 77 |
+
])
|
| 78 |
+
def test_unreliable_inputs_are_unknown_with_actionable_reasons(patch,reason):
|
| 79 |
+
opts,_=scene();data=opts.model_dump(mode='json')
|
| 80 |
+
for key,value in patch.items():data[key]={**data[key],**value} if isinstance(value,dict) else value
|
| 81 |
+
opts=MotionInput(**data);out=resolve(opts,capture(),reference(opts))
|
| 82 |
+
assert out['status']=='unknown' and out['reason_code']==reason,out
|
| 83 |
+
assert out['pitcher_vector'] is None and out['pitcher_source'] is None
|
| 84 |
+
assert not out['applied'] and not out['reliable']
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_accepted_estimated_up_is_used_with_its_uncertainty_and_unreliable_up_is_rejected():
|
| 88 |
+
opts,_=scene();auto={**reference(opts),'status':'estimated','reliable':True,
|
| 89 |
+
'maximum_model_uncertainty_deg':2.,'maximum_deviation_deg':.5}
|
| 90 |
+
out=resolve(opts,capture(),auto)
|
| 91 |
+
assert out['status']=='estimated' and out['up_sensitivity_deg_used']==2.5,out
|
| 92 |
+
assert resolve(opts,capture(),{**auto,'reliable':False})['reason_code']=='pitcher_up_reference_unreliable'
|
| 93 |
+
assert resolve(opts,capture(),{**auto,'maximum_model_uncertainty_deg':None})['reason_code']=='pitcher_up_uncertainty_unknown'
|
| 94 |
+
out=resolve(opts,capture(),{**auto,'maximum_model_uncertainty_deg':8.})
|
| 95 |
+
assert out['status']=='unknown' and out['reason_code'].startswith('floor_direction_uncertainty'),out
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_changed_frame_dimensions_do_not_silently_reuse_calibration():
|
| 99 |
+
opts,_=scene();c=capture();c['frames'][6]['width']=1280
|
| 100 |
+
assert resolve(opts,c,reference(opts))['reason_code']=='source_image_dimensions_changed'
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_explicit_manual_vector_and_source_take_priority_without_normalization():
|
| 104 |
+
opts=MotionInput(pitcher_vector=[-2.,.1,3.],pitcher_source='Surveyed camera-space vector',
|
| 105 |
+
pitcher_floor_points={'source_frame_index':500,'near_batter':[1,1],'toward_pitcher':[1,1]})
|
| 106 |
+
out=resolve(opts,None,None)
|
| 107 |
+
assert out['status']=='provided' and out['method']=='caller_supplied' and out['reliable'] is None
|
| 108 |
+
assert out['pitcher_vector']==[-2.,.1,3.] and out['pitcher_source']==opts.pitcher_source
|
| 109 |
+
assert resolve(MotionInput(),None,None)['reason_code']=='floor_points_not_supplied'
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@pytest.mark.parametrize('model',['sam3d','gvhmr'])
|
| 113 |
+
@pytest.mark.parametrize('automatic_up',[False,True])
|
| 114 |
+
def test_shared_export_applies_floor_reference_preserves_inputs_and_reproduces_all_measurements(tmp_path,video,model,automatic_up):
|
| 115 |
+
from baseball_batting.motion_contract import MotionFrame,ProjectionFrame
|
| 116 |
+
opts=MotionInput(model=model,annotated_videos=False,single_swing=True,handedness='right',
|
| 117 |
+
camera_stability='fixed_verified',timing={'kind':'unretimed','source':'Known synthetic clock'},
|
| 118 |
+
up_vector=None if automatic_up else [0,-1,0],up_source=None if automatic_up else 'Known synthetic gravity',
|
| 119 |
+
camera={'fx':100,'fy':110,'cx':80,'cy':40,'source':'Known synthetic calibration','calibration_status':'calibrated'},
|
| 120 |
+
pitcher_floor_points={'source_frame_index':2,'near_batter':[63.333333333333,95],'toward_pitcher':[110,73],
|
| 121 |
+
'selection_uncertainty_px':.5},
|
| 122 |
+
windows=[{'start_frame':0,'end_frame':7,'baseline_frame':1,'stride_start_frame':2,'landing_frame':5}])
|
| 123 |
+
c=ingest(video,opts.metadata());raw=raw_for(c);original=copy.deepcopy(opts.model_dump(mode='json'))
|
| 124 |
+
k=np.array([[100,0,80],[0,110,40],[0,0,1.]])
|
| 125 |
+
raw['intrinsics'][:]=k
|
| 126 |
+
raw['projection']=np.stack([project(p+t,k) for p,t in zip(raw['points_body'],raw['camera_translation'])])
|
| 127 |
+
auto=None if not automatic_up else {**reference(opts),'status':'estimated','reliable':True,
|
| 128 |
+
'up_vector':[0,-1,0],'up_source':'Test image estimator','maximum_model_uncertainty_deg':1.,'maximum_deviation_deg':.2}
|
| 129 |
+
manifest=export_motion(tmp_path,video,c,raw,opts,{'name':'fixture'},
|
| 130 |
+
{'analysis_id':'floor-fixture','analysis_revision':1},up_reference=auto)
|
| 131 |
+
assert opts.model_dump(mode='json')==original==manifest.pipeline['inputs']
|
| 132 |
+
estimated=manifest.coordinates['pitcher_estimation'];assert estimated['status']=='estimated',estimated
|
| 133 |
+
np.testing.assert_allclose(manifest.coordinates['pitcher_vector'],[2**-.5,0,2**-.5],atol=1e-10)
|
| 134 |
+
assert manifest.coordinates['frame']=='declared_field_axes'
|
| 135 |
+
assert manifest.pipeline['calculation_inputs']['pitcher_vector']==estimated['pitcher_vector']
|
| 136 |
+
report=json.loads((tmp_path/'measurements.json').read_text())
|
| 137 |
+
assert report['pitcher_reference']==estimated
|
| 138 |
+
assert json.loads((tmp_path/'quality.json').read_text())['pitcher_reference']==estimated
|
| 139 |
+
stride=next(m for m in report['summaries'] if m['metric_id']=='stride_relative_forward_cm')
|
| 140 |
+
assert stride['value'] is not None and 'pitcher_reference_estimated_from_floor_points' in stride['quality_flags']
|
| 141 |
+
reproduced=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
|
| 142 |
+
values={(s.rep,m.key):m.value for swings in reproduced.values() for s in swings for m in s.measurements}
|
| 143 |
+
for row in report['summaries']:
|
| 144 |
+
expected=values[row['rep'],row['metric_id']]
|
| 145 |
+
assert row['value']==pytest.approx(expected) if expected is not None else row['value'] is None
|
| 146 |
+
rotation=np.array(manifest.coordinates['camera_to_export_rotation'])
|
| 147 |
+
for a,b in zip((tmp_path/'motion.jsonl').read_text().splitlines(),(tmp_path/'projections.jsonl').read_text().splitlines()):
|
| 148 |
+
frame=MotionFrame.model_validate_json(a);projection=ProjectionFrame.model_validate_json(b)
|
| 149 |
+
for name,joint in frame.joints.items():
|
| 150 |
+
if joint.position is not None and projection.joints[name]['valid']:
|
| 151 |
+
camera=(np.array(joint.position)+frame.root_translation)@rotation
|
| 152 |
+
np.testing.assert_allclose(project(camera,projection.camera_intrinsics),projection.joints[name]['pixel'],atol=1e-9)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_observed_camera_motion_blocks_floor_estimation_but_keeps_manual_inputs(tmp_path,video):
|
| 156 |
+
opts=MotionInput(camera_stability='fixed_verified',annotated_videos=False,
|
| 157 |
+
up_vector=[0,-1,0],up_source='test',pitcher_floor_points={'source_frame_index':0,'near_batter':[40,100],'toward_pitcher':[120,100]})
|
| 158 |
+
c=ingest(video,opts.metadata())
|
| 159 |
+
manifest=export_motion(tmp_path,video,c,raw_for(c),opts,{'name':'fixture'},
|
| 160 |
+
{'analysis_id':'test','analysis_revision':1},refinement={'image_evidence':{'declared_static_camera_conflict':True}})
|
| 161 |
+
assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified'
|
| 162 |
+
assert manifest.coordinates['pitcher_estimation']['reason_code']=='camera_not_fixed_for_pitcher_reference'
|
| 163 |
+
assert manifest.pipeline['calculation_inputs']['pitcher_vector'] is None
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_floor_selection_uses_upright_image_after_source_rotation(tmp_path,video):
|
| 167 |
+
opts=MotionInput(rotation_degrees=90,annotated_videos=False,single_swing=True,camera_stability='fixed_verified',
|
| 168 |
+
up_vector=[0,-1,0],up_source='Upright source gravity',
|
| 169 |
+
camera={'fx':100,'fy':100,'cx':60,'cy':60,'source':'Upright test calibration','calibration_status':'calibrated'},
|
| 170 |
+
pitcher_floor_points={'source_frame_index':1,'near_batter':[30,130],'toward_pitcher':[95,100]})
|
| 171 |
+
c=ingest(video,opts.metadata());out=resolve(opts,c,reference(opts))
|
| 172 |
+
assert out['status']=='estimated',out
|
| 173 |
+
assert (out['source_frame']['image_width'],out['source_frame']['image_height'])==(120,160)
|
| 174 |
+
bad=opts.model_copy(update={'pitcher_floor_points':opts.pitcher_floor_points.model_copy(update={'toward_pitcher':(140,100)})})
|
| 175 |
+
assert resolve(bad,c,reference(opts))['reason_code']=='floor_points_outside_source_image'
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize('value',[{'source_frame_index':True,'near_batter':[1,2],'toward_pitcher':[3,4]},
|
| 179 |
+
{'source_frame_index':0,'near_batter':[float('nan'),2],'toward_pitcher':[3,4]},
|
| 180 |
+
{'source_frame_index':0,'near_batter':[1,2,3],'toward_pitcher':[3,4]}])
|
| 181 |
+
def test_malformed_floor_options_rejected_at_request_validation(value):
|
| 182 |
+
with pytest.raises(ValueError):MotionInput(pitcher_floor_points=value)
|