github-actions[bot] commited on
Commit
0a35b6f
·
1 Parent(s): 9756876

Automated Deploy: 20fc409889f58f6cb0bba327ee7d2bd7e33c226f

Browse files
Dockerfile.gvhmr CHANGED
@@ -17,7 +17,7 @@ RUN python -m pip install --no-cache-dir uv==0.9.10 \
17
  && PYTHONPATH=/opt/gvhmr-source /opt/gvhmr-runtime/bin/python /tmp/check_gvhmr_runtime.py
18
  COPY baseball_batting /opt/gvhmr-api-check/baseball_batting
19
  RUN PYTHONPATH=/opt/gvhmr-api-check:/opt/gvhmr-source /opt/gvhmr-runtime/bin/python -c \
20
- "import numpy as np; from baseball_batting.gvhmr_pose_worker import run; from baseball_batting.motion_adapters import smplx_to_calculation; from smplx.joint_names import JOINT_NAMES; assert smplx_to_calculation(np.zeros((2,len(JOINT_NAMES),3)),JOINT_NAMES).shape == (2,70,3)"
21
 
22
 
23
  FROM ${BASE_IMAGE}
 
17
  && PYTHONPATH=/opt/gvhmr-source /opt/gvhmr-runtime/bin/python /tmp/check_gvhmr_runtime.py
18
  COPY baseball_batting /opt/gvhmr-api-check/baseball_batting
19
  RUN PYTHONPATH=/opt/gvhmr-api-check:/opt/gvhmr-source /opt/gvhmr-runtime/bin/python -c \
20
+ "import numpy as np; from baseball_batting.gvhmr_pose_worker import run; from baseball_batting.motion_refine_worker import load_adapter; from baseball_batting.motion_refinement import fit_window; from baseball_batting.motion_adapters import smplx_to_calculation; from smplx.joint_names import JOINT_NAMES; assert smplx_to_calculation(np.zeros((2,len(JOINT_NAMES),3)),JOINT_NAMES).shape == (2,70,3)"
21
 
22
 
23
  FROM ${BASE_IMAGE}
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.11.0", lifespan=lifespan,
82
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
83
  app.state.service = service
84
  app.add_middleware(UploadGuard, settings=settings, service=service)
 
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.12.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/geometry.py CHANGED
@@ -24,9 +24,18 @@ def rotation(value):
24
  return r
25
 
26
 
27
- def project(points, k):
28
  points = np.asarray(points, float)
29
- homogeneous = points @ intrinsics(k).T
 
 
 
 
 
 
 
 
 
30
  result = np.full(points.shape[:-1] + (2,), np.nan)
31
  valid = np.isfinite(points).all(axis=-1) & (points[..., 2] > 1e-8)
32
  result[valid] = homogeneous[valid, :2] / homogeneous[valid, 2:3]
 
24
  return r
25
 
26
 
27
+ def project(points, k, distortion=None):
28
  points = np.asarray(points, float)
29
+ intrinsic=intrinsics(k)
30
+ if distortion is not None:
31
+ import cv2
32
+ d=matrix(distortion,(5,),'Brown-Conrady distortion')
33
+ result=np.full(points.shape[:-1]+(2,),np.nan)
34
+ valid=np.isfinite(points).all(axis=-1)&(points[...,2]>1e-8)
35
+ if valid.any():
36
+ result[valid]=cv2.projectPoints(points[valid].reshape(-1,1,3),np.zeros(3),np.zeros(3),intrinsic,d)[0].reshape(-1,2)
37
+ return result
38
+ homogeneous = points @ intrinsic.T
39
  result = np.full(points.shape[:-1] + (2,), np.nan)
40
  valid = np.isfinite(points).all(axis=-1) & (points[..., 2] > 1e-8)
41
  result[valid] = homogeneous[valid, :2] / homogeneous[valid, 2:3]
baseball_batting/gvhmr_worker.py CHANGED
@@ -16,7 +16,7 @@ def reconstruct_gvhmr(job,video,capture,models,options,progress):
16
  raise ValueError('Changing image dimensions require separate recording segments')
17
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
18
  raise ValueError('Camera principal point is outside upright video')
19
- boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=True)
20
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
21
  c=options.camera
22
  physical=[f['physical_s'] for f in capture['frames']]
 
16
  raise ValueError('Changing image dimensions require separate recording segments')
17
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
18
  raise ValueError('Camera principal point is outside upright video')
19
+ boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=True,recovery=options.tracking)
20
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
21
  c=options.camera
22
  physical=[f['physical_s'] for f in capture['frames']]
baseball_batting/motion_api.py CHANGED
@@ -15,6 +15,7 @@ from . import gvhmr_runtime
15
  from .motion_adapters import descriptor, adapter_hash
16
  from .storage import atomic_json, read_json, sha256_file
17
  from .media import open_verified_media, media_response
 
18
 
19
  PREFIX='/v1/motion-analyses'
20
 
@@ -88,10 +89,13 @@ def register(app,service,authenticated):
88
  **(public_status() if key=='sam3d' else gvhmr_runtime.public_status())} for key in ('sam3d','gvhmr')]
89
  return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
90
  'default_model':'sam3d','models':models,'model_selector':'options.model',
91
- 'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
92
  'sam':public_status(),'gpu_queue_ready':service.ready,'mesh_available':False,
93
  'joint_count':len(MHR),'per_frame_motion':True,'projections':True,'measurement_series':True,
94
  'immutable_revisions':True,'source_video_retained':True,'interpolation':'disabled; gaps explicit',
 
 
 
95
  'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
96
  'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
97
  'output_schema_url':PREFIX+'/output-schema'}
@@ -186,11 +190,11 @@ def register(app,service,authenticated):
186
  raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
187
  directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
188
  # Reviewed events/calibration axes/correction changes reuse native inference.
189
- geometry=('camera','athlete_box','rotation_degrees','source_mirrored','model','gvhmr')
190
  parent_options=MotionInput.model_validate(inputs).model_dump()
191
  reusable=(all(parent_options.get(k)==parsed.model_dump().get(k) for k in geometry)
192
  and manifest.pipeline['adapter_sha256']==adapter_hash(parsed.model)
193
- and manifest.pipeline.get('tracking_implementation_sha256')==sha256_file(Path(__file__).with_name('sam_measurement_worker.py')))
194
  if parsed.model=='gvhmr':
195
  # These facts change the temporal conditioning, not merely the export.
196
  reusable &= (parent_options['timing']==parsed.timing.model_dump() and
@@ -203,8 +207,12 @@ def register(app,service,authenticated):
203
  if reusable and integrity.is_file():
204
  hashes=read_json(integrity)
205
  files=descriptor(parsed.model)['raw_files']
206
- if all((parent/name).is_file() and sha256_file(parent/name)==hashes.get(name) for name in files):
 
 
207
  for name in files:os.link(parent/name,directory/name)
 
 
208
  atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
209
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
210
  return response(lineage)
 
15
  from .motion_adapters import descriptor, adapter_hash
16
  from .storage import atomic_json, read_json, sha256_file
17
  from .media import open_verified_media, media_response
18
+ from .sam_measurement_worker import tracking_hash
19
 
20
  PREFIX='/v1/motion-analyses'
21
 
 
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',
91
  'default_model':'sam3d','models':models,'model_selector':'options.model',
92
+ 'tracking_implementation_sha256':tracking_hash(),
93
  'sam':public_status(),'gpu_queue_ready':service.ready,'mesh_available':False,
94
  'joint_count':len(MHR),'per_frame_motion':True,'projections':True,'measurement_series':True,
95
  'immutable_revisions':True,'source_video_retained':True,'interpolation':'disabled; gaps explicit',
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'}
 
190
  raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
191
  directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
192
  # Reviewed events/calibration axes/correction changes reuse native inference.
193
+ geometry=('camera','athlete_box','rotation_degrees','source_mirrored','model','gvhmr','tracking')
194
  parent_options=MotionInput.model_validate(inputs).model_dump()
195
  reusable=(all(parent_options.get(k)==parsed.model_dump().get(k) for k in geometry)
196
  and manifest.pipeline['adapter_sha256']==adapter_hash(parsed.model)
197
+ and manifest.pipeline.get('tracking_implementation_sha256')==tracking_hash())
198
  if parsed.model=='gvhmr':
199
  # These facts change the temporal conditioning, not merely the export.
200
  reusable &= (parent_options['timing']==parsed.timing.model_dump() and
 
207
  if reusable and integrity.is_file():
208
  hashes=read_json(integrity)
209
  files=descriptor(parsed.model)['raw_files']
210
+ extras=('sam-parameters-private.npz','sam-mhr-adapter-private.npz') if parsed.model=='sam3d' else ('gvhmr-parameters-private.npz',)
211
+ parameters_verified=all(name not in hashes or ((parent/name).is_file() and hashes[name]==sha256_file(parent/name)) for name in extras)
212
+ if parameters_verified and all((parent/name).is_file() and sha256_file(parent/name)==hashes.get(name) for name in files):
213
  for name in files:os.link(parent/name,directory/name)
214
+ for name in extras:
215
+ if (parent/name).is_file() and hashes.get(name)==sha256_file(parent/name):os.link(parent/name,directory/name)
216
  atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
217
  service.store.update(lineage['job_id'],'queued');service.wakeup.set()
218
  return response(lineage)
baseball_batting/motion_contract.py CHANGED
@@ -3,12 +3,53 @@ from typing import Any, Literal
3
  from pydantic import Field, model_validator
4
  from .sam_batting_contract import Strict, SamBattingInput
5
  from .sam_motion import MHR
 
6
 
7
  SCHEMA_VERSION = '1.0'
8
  ADAPTER_VERSION = 'sam-mhr70-motion-v1'
9
  DEFINITION_VERSION = 'batting-corrected-points-v1'
10
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  class GVHMRSettings(Strict):
13
  batch_size: int = Field(default=4, ge=1, le=16, strict=True)
14
  max_sequence_frames: int = Field(default=300, ge=90, le=900, strict=True)
@@ -33,6 +74,9 @@ class MotionInput(SamBattingInput):
33
  lead_foot_source: str | None = Field(default=None, min_length=1, max_length=300)
34
  scale_status: Literal['model_estimated', 'calibrated', 'unknown'] = 'model_estimated'
35
  minimum_usable_joints: int = Field(default=3, ge=3, le=len(MHR), strict=True)
 
 
 
36
 
37
  @model_validator(mode='after')
38
  def scale_evidence(self):
@@ -41,8 +85,9 @@ class MotionInput(SamBattingInput):
41
  return self
42
 
43
  def sam_options(self):
44
- return SamBattingInput.model_validate({k: v for k, v in self.model_dump().items()
45
- if k in SamBattingInput.model_fields})
 
46
 
47
 
48
  class RevisionRequest(Strict):
@@ -134,4 +179,5 @@ class ProjectionFrame(Strict):
134
  image_width: int = Field(ge=1)
135
  image_height: int = Field(ge=1)
136
  camera_intrinsics: list[list[float]] | None
 
137
  joints: dict[str, dict[str, Any]]
 
3
  from pydantic import Field, model_validator
4
  from .sam_batting_contract import Strict, SamBattingInput
5
  from .sam_motion import MHR
6
+ from .api_contract import CameraInput
7
 
8
  SCHEMA_VERSION = '1.0'
9
  ADAPTER_VERSION = 'sam-mhr70-motion-v1'
10
  DEFINITION_VERSION = 'batting-corrected-points-v1'
11
 
12
 
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 RefinementSettings(Strict):
19
+ enabled: bool = True
20
+ window_frames: int = Field(default=48, ge=12, le=120, strict=True)
21
+ context_frames: int = Field(default=8, ge=2, le=24, strict=True)
22
+ iterations: int = Field(default=25, ge=5, le=100, strict=True)
23
+ learning_rate: float = Field(default=.005, gt=0, le=.05)
24
+ minimum_observation_score: float = Field(default=.45, ge=.1, le=.95)
25
+ minimum_observed_joints: int = Field(default=6, ge=4, le=20, strict=True)
26
+ observation_scale_box_fraction: float = Field(default=.025, gt=0, le=.15)
27
+ maximum_observation_error_box_fraction: float = Field(default=.08, gt=0, le=.3)
28
+ maximum_body_change_fraction: float = Field(default=.12, gt=0, le=.3)
29
+ maximum_bone_change_fraction: float = Field(default=.06, gt=0, le=.2)
30
+ temporal_weight: float = Field(default=.02, ge=0, le=1)
31
+ initializer_weight: float = Field(default=.1, gt=0, le=10)
32
+ maximum_peak_time_shift_s: float = Field(default=.025, gt=0, le=.1)
33
+ maximum_peak_speed_change_fraction: float = Field(default=.2, gt=0, le=.5)
34
+ maximum_static_background_motion_fraction: float = Field(default=.003, gt=0, le=.05)
35
+ sensitivity_factors: tuple[float, float] = (.5, 2.)
36
+
37
+ @model_validator(mode='after')
38
+ def bounded_windows(self):
39
+ if self.window_frames <= 2*self.context_frames:
40
+ raise ValueError('Refinement requires a nonempty core between context margins')
41
+ if not all(0 < f <= 4 for f in self.sensitivity_factors):
42
+ raise ValueError('Sensitivity factors must be positive and at most four')
43
+ return self
44
+
45
+
46
+ class MotionTrackingSettings(Strict):
47
+ recover_short_losses: bool = True
48
+ maximum_recovery_gap_s: float = Field(default=.2, gt=0, le=.5)
49
+ minimum_appearance_similarity: float = Field(default=.85, ge=.7, le=.99)
50
+ minimum_candidate_margin: float = Field(default=.1, ge=.05, le=.5)
51
+
52
+
53
  class GVHMRSettings(Strict):
54
  batch_size: int = Field(default=4, ge=1, le=16, strict=True)
55
  max_sequence_frames: int = Field(default=300, ge=90, le=900, strict=True)
 
74
  lead_foot_source: str | None = Field(default=None, min_length=1, max_length=300)
75
  scale_status: Literal['model_estimated', 'calibrated', 'unknown'] = 'model_estimated'
76
  minimum_usable_joints: int = Field(default=3, ge=3, le=len(MHR), strict=True)
77
+ camera: MotionCamera | None = None
78
+ refinement: RefinementSettings = Field(default_factory=RefinementSettings)
79
+ tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
80
 
81
  @model_validator(mode='after')
82
  def scale_evidence(self):
 
85
  return self
86
 
87
  def sam_options(self):
88
+ data={k:v for k,v in self.model_dump().items() if k in SamBattingInput.model_fields}
89
+ if data.get('camera'):data['camera'].pop('distortion',None)
90
+ return SamBattingInput.model_validate(data)
91
 
92
 
93
  class RevisionRequest(Strict):
 
179
  image_width: int = Field(ge=1)
180
  image_height: int = Field(ge=1)
181
  camera_intrinsics: list[list[float]] | None
182
+ camera_distortion: tuple[float,float,float,float,float] | None = None
183
  joints: dict[str, dict[str, Any]]
baseball_batting/motion_evidence.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private image observations for fitting, never substituted for exported 3D joints."""
2
+ import numpy as np
3
+ from .motion_refinement import NAMES
4
+ from .contracts import RTMW_CORE
5
+ from .ingest import iter_frames
6
+ from .storage import sha256_file,atomic_json,read_json
7
+
8
+ OBSERVATIONS={**RTMW_CORE,'left_ear':3,'right_ear':4}
9
+
10
+
11
+ def background_motion(previous,current,old_box,box):
12
+ """Robust image displacement outside the athlete, not calibrated camera pose."""
13
+ import cv2
14
+ scale=min(1.,640/current.shape[1]);size=(round(current.shape[1]*scale),round(current.shape[0]*scale))
15
+ a=cv2.resize(previous,size);b=cv2.resize(current,size);mask=np.full(a.shape,255,np.uint8)
16
+ for region in (old_box,box):
17
+ if region is not None:
18
+ x1,y1,x2,y2=np.rint(np.asarray(region)*scale).astype(int)
19
+ cv2.rectangle(mask,(max(0,x1-12),max(0,y1-12)),(min(size[0],x2+12),min(size[1],y2+12)),0,-1)
20
+ points=cv2.goodFeaturesToTrack(a,200,.02,10,mask=mask)
21
+ if points is None or len(points)<12:return np.nan
22
+ moved,status,_=cv2.calcOpticalFlowPyrLK(a,b,points,None)
23
+ if moved is None:return np.nan
24
+ back,reverse,_=cv2.calcOpticalFlowPyrLK(b,a,moved,None)
25
+ if back is None:return np.nan
26
+ valid=(status[:,0]>0)&(reverse[:,0]>0)&(np.linalg.norm(back[:,0]-points[:,0],axis=-1)<1.5)
27
+ if valid.sum()<12:return np.nan
28
+ transform,inliers=cv2.estimateAffinePartial2D(points[valid,0],moved[valid,0],method=cv2.RANSAC,ransacReprojThreshold=2.)
29
+ if transform is None or inliers.sum()<12:return np.nan
30
+ displacement=np.linalg.norm(moved[valid,0]-points[valid,0],axis=-1)[inliers[:,0]>0]
31
+ return float(np.median(displacement)/max(size))
32
+
33
+
34
+ def flow_support(previous,current,old_points,new_points,old_scores,new_scores,minimum):
35
+ """Forward/backward LK corroborates detections; it never fabricates a landmark."""
36
+ import cv2
37
+ supported=np.zeros(len(old_points),bool);testable=np.zeros(len(old_points),bool)
38
+ ids=np.flatnonzero(np.isfinite(old_points).all(-1)&np.isfinite(new_points).all(-1)&
39
+ (old_scores>=minimum)&(new_scores>=minimum))
40
+ if not len(ids):return supported,testable
41
+ scale=min(1.,1280/current.shape[1]);size=(round(current.shape[1]*scale),round(current.shape[0]*scale))
42
+ a=cv2.resize(previous,size);b=cv2.resize(current,size)
43
+ p=(old_points[ids]*scale).astype(np.float32).reshape(-1,1,2)
44
+ q,status,_=cv2.calcOpticalFlowPyrLK(a,b,p,None,winSize=(31,31),maxLevel=4)
45
+ if q is None:return supported,testable
46
+ back,reverse,_=cv2.calcOpticalFlowPyrLK(b,a,q,None,winSize=(31,31),maxLevel=4)
47
+ if back is None:return supported,testable
48
+ testable[ids]=(status[:,0]>0)&(reverse[:,0]>0)
49
+ fb=np.linalg.norm(back[:,0]-p[:,0],axis=-1)
50
+ agreement=np.linalg.norm(q[:,0]-new_points[ids]*scale,axis=-1)
51
+ # Pixel tolerance scales with displayed image, not a particular test clip.
52
+ tolerance=max(2.,.006*size[1])
53
+ supported[ids]=testable[ids]&(fb<=2.)&(agreement<=tolerance)
54
+ return supported,testable
55
+
56
+
57
+ def collect(job,video,capture,models,options,progress,device='cuda'):
58
+ import cv2
59
+ from .api_worker import model_files
60
+ from .body2d import RTMWPose
61
+ job=__import__('pathlib').Path(job);paths,hashes=model_files(models)
62
+ tracker=read_json(job/'person-track-private.json');boxes=tracker['boxes']
63
+ pose=RTMWPose(paths['body_pose'],device)
64
+ n=capture['frame_count'];j=len(NAMES)
65
+ pixels=np.full((n,j,2),np.nan);weights=np.zeros((n,j));scores=np.zeros((n,j))
66
+ usable=np.zeros(n,bool);heights=np.ones(n);flow=np.zeros((n,j),bool);flow_testable=np.zeros((n,j),bool)
67
+ previous=None;prior=None;prior_scores=None;prior_time=None;old_box=None
68
+ camera_displacement=np.full(n,np.nan)
69
+ times=np.array([r['physical_s'] if r['physical_s'] is not None else r['playback_s'] for r in capture['frames']])
70
+ sequence=np.zeros(n,int);serial=0
71
+ for i,_,_,image in iter_frames(video,capture['rotation_degrees']):
72
+ if i>=n:raise ValueError('Evidence source changed after ingest')
73
+ box=boxes[i];gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
74
+ if box is None or tracker['reasons'][i] is not None:
75
+ previous=None;prior=None;prior_scores=None;prior_time=None;old_box=None;serial+=1;sequence[i]=serial;continue
76
+ points,score=pose(image,box);heights[i]=max(box[3]-box[1],1)
77
+ for k,name in enumerate(NAMES):
78
+ index=OBSERVATIONS[name];pixels[i,k]=points[index];scores[i,k]=score[index]
79
+ finite=np.isfinite(pixels[i]).all(-1)&np.isfinite(scores[i])
80
+ inside=finite&(pixels[i,:,0]>=0)&(pixels[i,:,0]<image.shape[1])&(pixels[i,:,1]>=0)&(pixels[i,:,1]<image.shape[0])
81
+ # Detector scores are observation weights, never calibrated 3D confidence.
82
+ weights[i]=np.where(inside&(scores[i]>=options.refinement.minimum_observation_score),np.clip(scores[i],0,1),0)
83
+ if previous is not None and 0<times[i]-prior_time<=options.correction.max_gap_s:
84
+ camera_displacement[i]=background_motion(previous,gray,old_box,box)
85
+ flow[i],flow_testable[i]=flow_support(previous,gray,prior,pixels[i],prior_scores,scores[i],options.refinement.minimum_observation_score)
86
+ # Failed LK is common in a fast swing: downweight, do not delete it.
87
+ weights[i,flow_testable[i]&~flow[i]]*=.25
88
+ elif previous is not None:serial+=1
89
+ usable[i]=np.count_nonzero(weights[i]>0)>=options.refinement.minimum_observed_joints
90
+ sequence[i]=serial;previous=gray;prior=pixels[i].copy();prior_scores=scores[i].copy();prior_time=times[i];old_box=box
91
+ if i%16==0 or i==n-1:progress('image_motion_evidence',i+1,n)
92
+ evidence={'pixels':pixels,'weights':weights,'scores':scores,'box_heights':heights,
93
+ 'frame_usable':usable,'flow_supported':flow,'flow_testable':flow_testable,'sequence_ids':sequence,
94
+ 'background_displacement_image_fraction':camera_displacement}
95
+ if options.camera and options.camera.distortion is not None:evidence['distortion']=np.array(options.camera.distortion)
96
+ np.savez_compressed(job/'motion-evidence-private.npz',**evidence)
97
+ metadata={'version':'rtmw-image-evidence-v1','model_sha256':sha256_file(paths['body_pose']),
98
+ 'observation_names':list(NAMES),'minimum_score':options.refinement.minimum_observation_score,
99
+ 'frames_with_minimum_support':int(usable.sum()),'optical_flow':'forward_backward_LK_corroboration_only',
100
+ 'anatomy':'RTMW homologous image landmarks are soft constraints; not asserted identical to native rig joint centers',
101
+ 'visibility':'detector confidence and image continuity; not verified occlusion labels or depth accuracy',
102
+ 'confidence':'image evidence weights only; no calibrated 3D confidence',
103
+ 'camera_motion':'background affine RANSAC displacement; diagnostic only, not ground/world calibration',
104
+ 'camera_motion_evaluable_pairs':int(np.isfinite(camera_displacement).sum()),
105
+ 'maximum_background_displacement_image_fraction':float(np.nanmax(camera_displacement)) if np.isfinite(camera_displacement).any() else None,
106
+ 'implementation_sha256':sha256_file(__import__('pathlib').Path(__file__))}
107
+ atomic_json(job/'motion-evidence-private.json',metadata)
108
+ return evidence,metadata
baseball_batting/motion_export.py CHANGED
@@ -11,6 +11,7 @@ from .motion_adapters import descriptor, adapter_hash, skeleton, SURFACE_LANDMAR
11
  from .sam_measurements import DEFINITIONS, GROUP_KEYS, calculate_measurements, orientation
12
  from .sam_videos import export_group_videos, corrected_projection
13
  from .storage import atomic_json, sha256_file, digest
 
14
 
15
  JOINTS = tuple(MHR)
16
  INDEX_NAMES = {v: k for k, v in MHR.items()}
@@ -87,11 +88,11 @@ def reproduce_measurements(manifest, motion_path):
87
  boundary[i,index]='filter_boundary' in joint.reasons
88
  known=m['timing']['physical_time_available']
89
  times=np.array([f.capture_time_s if known else f.video_time_s for f in rows])
90
- options=MotionInput.model_validate(m['pipeline']['inputs'])
91
  return _calculate({'points_relative':points,'boundary':boundary}, times, options, known)[0]
92
 
93
 
94
- def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=86400,progress=lambda *a:None,track=None):
95
  """Write all artifacts before atomically publishing the completed manifest."""
96
  import time
97
  job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
@@ -116,8 +117,20 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
116
  # Preserve native arrays for debugging; uncertain identity must never become replay evidence.
117
  mask=np.array([reason is None for reason in track['reasons']],bool)
118
  correction_raw={**raw,'projection_valid':np.asarray(raw['projection_valid'],bool)&mask}
 
 
 
 
 
119
  progress('temporal_correction',0,n)
120
  corrected=correct_motion(correction_raw,times,options.correction)
 
 
 
 
 
 
 
121
  if options.model=='gvhmr':
122
  corrected['interpolated']|=resampled[:,None]&corrected['valid']
123
  corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
@@ -125,7 +138,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
125
  indices=list(MHR.values()); count=corrected['valid'][:,indices].sum(axis=1)
126
  usable=count>=options.minimum_usable_joints
127
  if not usable.any(): raise ValueError('no_usable_motion')
128
- groups,contexts=_calculate(corrected,times,options,known)
129
  baseline=next((c['baseline'] for c in contexts if corrected['valid'][c['baseline'],[9,10]].all()),int(np.flatnonzero(usable)[0]))
130
  rotation,reference=orientation(corrected['points_relative'],options,baseline)
131
  if rotation is None: rotation=np.eye(3); reference='camera_oriented_hip_relative'
@@ -147,11 +160,12 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
147
  return {'source_frame_index':i,'video_time_s':float(video_times[i]),
148
  'capture_time_s':float(capture_times[i]) if known else None}
149
  projection_count=0
 
150
  motion_rows=[]; projection_rows=[]
151
  for i in range(n):
152
  frame=records[i]; joints={}; projected={}; k=raw['intrinsics'][i]
153
  # Both artifacts and videos use the same corrected camera-space projection.
154
- xy,projection_valid=corrected_projection(corrected,raw['intrinsics'],i)
155
  for name,index in MHR.items():
156
  reasons=[label for bit,label in REASONS.items() if corrected['reasons'][i,index]&bit]
157
  model_reason=model_frame_reasons[i]
@@ -161,6 +175,9 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
161
  if name in SURFACE_LANDMARKS:reasons.append('smplx_surface_landmark_derivation')
162
  if resampled[i]:reasons.append('uniform_grid_pose_resampled_to_source_timestamp')
163
  if track['reasons'][i]:reasons.append(track['reasons'][i])
 
 
 
164
  good=bool(corrected['valid'][i,index] and np.isfinite(positions[i,index]).all())
165
  status=('interpolated' if corrected['interpolated'][i,index] else 'estimated') if good else (
166
  'missing' if not np.isfinite(raw['points_body'][i,index]).all() else 'rejected')
@@ -181,10 +198,11 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
181
  common={'analysis_revision':revision,**stamp(i),'segment_id':segment_ids[i]}
182
  row=MotionFrame(**common,source_pts=frame['pts'],source_time_base=frame['time_base'],joints=joints,
183
  root_translation=_finite(root[i]),frame_quality={'pose_available':bool(usable[i]),'reasons':flags,
184
- 'usable_joint_count':int(count[i]),'joint_confidence_available':False})
 
185
  motion_rows.append(row.model_dump(mode='json'))
186
  projection_rows.append(ProjectionFrame(**common,image_width=frame['width'],image_height=frame['height'],
187
- camera_intrinsics=_finite(k),joints=projected).model_dump(mode='json'))
188
  _jsonl(job/'motion.jsonl',motion_rows)
189
  if projection_count:_jsonl(job/'projections.jsonl',projection_rows)
190
  progress('motion_artifacts',n,n)
@@ -237,17 +255,40 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
237
  metric=rows[name+'_peak_time_ms']
238
  event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
239
  event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
241
  'definition_version':definition_version,'summaries':summaries,'series':series,
242
  'calculation_inputs':options.model_dump(mode='json')})
243
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
244
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
245
- 'identity':{'person_id':person_id,'method':'conservative_single_athlete_box_continuity',
246
- 'reidentification':'disabled_after_tracking_loss_or_ambiguous_overlap','box_overlap_gate':.05,
247
  'tracking_reasons':track['reasons']},
248
  'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
249
  'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting'})
250
- clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress) if options.annotated_videos else {}
251
  source=job/('source'+Path(video).suffix.lower())
252
  if source!=Path(video):
253
  if source.exists():
@@ -285,11 +326,15 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
285
  'source_mirrored':options.source_mirrored,'mirroring_transform_applied':False,
286
  'timeline_origin_pts':records[0]['pts'],'timeline_origin_time_base':records[0]['time_base'],
287
  'projection_space':'upright_original_image_pixels_x_right_y_down',
288
- 'camera_model':'pinhole','distortion_correction':'not_applied; source_lens_distortion_unverified',
 
 
289
  'camera_intrinsics_source':options.camera.source if options.camera else adapter['name']+' estimated focal length and centered principal point'},
290
  pipeline={'model':model,'selected_model':options.model,'adapter_version':adapter['adapter_version'],'adapter_sha256':adapter_hash(options.model),
291
- 'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
292
  'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
 
 
293
  'correction_implementation_sha256':sha256_file(Path(__file__).with_name('sam_motion.py')),
294
  'measurement_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurements.py')),
295
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
@@ -301,7 +346,8 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
301
  'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
302
  {'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
303
  {'x':'camera_right','y':'camera_down','z':'camera_away'}),
304
- 'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable','camera_motion':options.camera_stability,
 
305
  'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
306
  'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
307
  'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
 
11
  from .sam_measurements import DEFINITIONS, GROUP_KEYS, calculate_measurements, orientation
12
  from .sam_videos import export_group_videos, corrected_projection
13
  from .storage import atomic_json, sha256_file, digest
14
+ from .sam_measurement_worker import tracking_hash
15
 
16
  JOINTS = tuple(MHR)
17
  INDEX_NAMES = {v: k for k, v in MHR.items()}
 
88
  boundary[i,index]='filter_boundary' in joint.reasons
89
  known=m['timing']['physical_time_available']
90
  times=np.array([f.capture_time_s if known else f.video_time_s for f in rows])
91
+ options=MotionInput.model_validate(m['pipeline'].get('calculation_inputs',m['pipeline']['inputs']))
92
  return _calculate({'points_relative':points,'boundary':boundary}, times, options, known)[0]
93
 
94
 
95
+ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=86400,progress=lambda *a:None,track=None,refinement=None):
96
  """Write all artifacts before atomically publishing the completed manifest."""
97
  import time
98
  job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
 
117
  # Preserve native arrays for debugging; uncertain identity must never become replay evidence.
118
  mask=np.array([reason is None for reason in track['reasons']],bool)
119
  correction_raw={**raw,'projection_valid':np.asarray(raw['projection_valid'],bool)&mask}
120
+ distortion=options.camera.distortion if options.camera else None
121
+ if distortion is not None:
122
+ from .geometry import project
123
+ correction_raw['projection']=np.stack([project(p+c,k,distortion) for p,c,k in
124
+ zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
125
  progress('temporal_correction',0,n)
126
  corrected=correct_motion(correction_raw,times,options.correction)
127
+ refined_mask=np.asarray(raw.get('refinement_accepted',np.zeros(n,bool)))
128
+ corrected['metadata']['whole_body_refinement']=refinement or {'enabled':False,'reason_code':'not_executed_in_this_export'}
129
+ corrected['metadata']['native_rig_fitted_frame_count']=int(refined_mask.sum())
130
+ corrected['metadata']['fitted_points_post_smoothing']='disabled; preserve accepted native rig geometry'
131
+ calculation_options=options
132
+ if refinement and refinement.get('image_evidence',{}).get('declared_static_camera_conflict'):
133
+ calculation_options=options.model_copy(update={'camera_stability':'moving'})
134
  if options.model=='gvhmr':
135
  corrected['interpolated']|=resampled[:,None]&corrected['valid']
136
  corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
 
138
  indices=list(MHR.values()); count=corrected['valid'][:,indices].sum(axis=1)
139
  usable=count>=options.minimum_usable_joints
140
  if not usable.any(): raise ValueError('no_usable_motion')
141
+ groups,contexts=_calculate(corrected,times,calculation_options,known)
142
  baseline=next((c['baseline'] for c in contexts if corrected['valid'][c['baseline'],[9,10]].all()),int(np.flatnonzero(usable)[0]))
143
  rotation,reference=orientation(corrected['points_relative'],options,baseline)
144
  if rotation is None: rotation=np.eye(3); reference='camera_oriented_hip_relative'
 
160
  return {'source_frame_index':i,'video_time_s':float(video_times[i]),
161
  'capture_time_s':float(capture_times[i]) if known else None}
162
  projection_count=0
163
+ image_conflicts=np.asarray(raw.get('refinement_image_conflict',np.zeros((n,70),bool)),bool)
164
  motion_rows=[]; projection_rows=[]
165
  for i in range(n):
166
  frame=records[i]; joints={}; projected={}; k=raw['intrinsics'][i]
167
  # Both artifacts and videos use the same corrected camera-space projection.
168
+ xy,projection_valid=corrected_projection(corrected,raw['intrinsics'],i,distortion)
169
  for name,index in MHR.items():
170
  reasons=[label for bit,label in REASONS.items() if corrected['reasons'][i,index]&bit]
171
  model_reason=model_frame_reasons[i]
 
175
  if name in SURFACE_LANDMARKS:reasons.append('smplx_surface_landmark_derivation')
176
  if resampled[i]:reasons.append('uniform_grid_pose_resampled_to_source_timestamp')
177
  if track['reasons'][i]:reasons.append(track['reasons'][i])
178
+ if refinement and refinement.get('enabled'):
179
+ reasons.append('native_rig_refinement_accepted' if refined_mask[i] else 'native_prediction_retained_refinement_not_accepted')
180
+ if image_conflicts[i,index]:reasons.append('strong_image_evidence_disagrees')
181
  good=bool(corrected['valid'][i,index] and np.isfinite(positions[i,index]).all())
182
  status=('interpolated' if corrected['interpolated'][i,index] else 'estimated') if good else (
183
  'missing' if not np.isfinite(raw['points_body'][i,index]).all() else 'rejected')
 
198
  common={'analysis_revision':revision,**stamp(i),'segment_id':segment_ids[i]}
199
  row=MotionFrame(**common,source_pts=frame['pts'],source_time_base=frame['time_base'],joints=joints,
200
  root_translation=_finite(root[i]),frame_quality={'pose_available':bool(usable[i]),'reasons':flags,
201
+ 'usable_joint_count':int(count[i]),'joint_confidence_available':False,
202
+ 'whole_body_refinement_accepted':bool(refined_mask[i])})
203
  motion_rows.append(row.model_dump(mode='json'))
204
  projection_rows.append(ProjectionFrame(**common,image_width=frame['width'],image_height=frame['height'],
205
+ camera_intrinsics=_finite(k),camera_distortion=distortion,joints=projected).model_dump(mode='json'))
206
  _jsonl(job/'motion.jsonl',motion_rows)
207
  if projection_count:_jsonl(job/'projections.jsonl',projection_rows)
208
  progress('motion_artifacts',n,n)
 
255
  metric=rows[name+'_peak_time_ms']
256
  event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
257
  event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
258
+ # Recompute each summary from alternate accepted rig fits, rather than
259
+ # interpreting a positional residual as an angular/timing error bar.
260
+ alternative_values=[]
261
+ for scenario,accepted_scenario in zip(raw.get('refinement_scenario_points_body',[]),raw.get('refinement_scenario_valid',[])):
262
+ hip=(scenario[:,9]+scenario[:,10])/2
263
+ alternate={'points_relative':np.where(corrected['valid'][...,None],scenario-hip[:,None],np.nan),
264
+ 'boundary':corrected['boundary']}
265
+ alternate_groups,_=_calculate(alternate,times,calculation_options,known)
266
+ alternative_values.append(({(s.rep,m.key):m.value for swings in alternate_groups.values() for s in swings for m in s.measurements},accepted_scenario))
267
+ for summary in summaries:
268
+ context=next((c for c in contexts if c['rep']==summary['rep']),None)
269
+ window=context['window'] if context else None
270
+ values=[]
271
+ for alternatives,accepted_scenario in alternative_values:
272
+ if window and np.asarray(accepted_scenario)[window['start_frame']:window['end_frame']+1].all():
273
+ value=alternatives.get((summary['rep'],summary['metric_id']))
274
+ if value is not None:values.append(value)
275
+ complete=bool(alternative_values and len(values)==len(alternative_values) and summary['value'] is not None)
276
+ summary['stability']={'kind':'temporal_regularization_sensitivity; not an accuracy interval',
277
+ 'status':'evaluated' if complete else 'not_evaluated',
278
+ 'reason_code':None if complete else 'accepted_alternative_fits_required_for_complete_swing',
279
+ 'minimum':min([summary['value'],*values]) if complete else None,
280
+ 'maximum':max([summary['value'],*values]) if complete else None,'unit':summary['unit']}
281
  atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
282
  'definition_version':definition_version,'summaries':summaries,'series':series,
283
  'calculation_inputs':options.model_dump(mode='json')})
284
  atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
285
  atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
286
+ 'identity':{'person_id':person_id,'method':'box_motion_and_torso_appearance_with_ambiguity_gates',
287
+ 'reidentification':'bounded_short_loss_only; ambiguous_overlap_not_recovered','box_overlap_gate':.05,
288
  'tracking_reasons':track['reasons']},
289
  'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
290
  'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting'})
291
+ clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress,distortion=distortion) if options.annotated_videos else {}
292
  source=job/('source'+Path(video).suffix.lower())
293
  if source!=Path(video):
294
  if source.exists():
 
326
  'source_mirrored':options.source_mirrored,'mirroring_transform_applied':False,
327
  'timeline_origin_pts':records[0]['pts'],'timeline_origin_time_base':records[0]['time_base'],
328
  'projection_space':'upright_original_image_pixels_x_right_y_down',
329
+ 'camera_model':'pinhole_Brown_Conrady' if distortion is not None else 'pinhole',
330
+ 'camera_distortion':list(distortion) if distortion is not None else None,
331
+ 'distortion_correction':'fitting_and_projection_use_original_distorted_pixels; source_not_warped' if distortion is not None else 'not_applied; source_lens_distortion_unverified',
332
  'camera_intrinsics_source':options.camera.source if options.camera else adapter['name']+' estimated focal length and centered principal point'},
333
  pipeline={'model':model,'selected_model':options.model,'adapter_version':adapter['adapter_version'],'adapter_sha256':adapter_hash(options.model),
334
+ 'tracking_implementation_sha256':tracking_hash(),
335
  'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
336
+ 'refinement':refinement or {'enabled':False,'reason_code':'not_executed_in_this_export'},
337
+ 'calculation_inputs':calculation_options.model_dump(mode='json'),
338
  'correction_implementation_sha256':sha256_file(Path(__file__).with_name('sam_motion.py')),
339
  'measurement_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurements.py')),
340
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
 
346
  'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
347
  {'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
348
  {'x':'camera_right','y':'camera_down','z':'camera_away'}),
349
+ 'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
350
+ 'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
351
  'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
352
  'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
353
  'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
baseball_batting/motion_refine.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Queue-side evidence collection and isolated native-body refinement launch."""
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import numpy as np
6
+ from .storage import read_json,atomic_json,sha256_file,digest
7
+ from .motion_refinement import VERSION
8
+
9
+
10
+ def implementation_hash():
11
+ return digest({name:sha256_file(Path(__file__).with_name(name)) for name in
12
+ ('motion_refine.py','motion_refine_worker.py','motion_refinement.py','motion_evidence.py','temporal3d.py','geometry.py')})
13
+
14
+
15
+ def refine(job,video,capture,raw,models,options,progress):
16
+ job=Path(job)
17
+ metadata={'version':VERSION,'enabled':options.refinement.enabled,'accepted_frame_count':0,
18
+ 'native_fallback_frame_count':capture['frame_count'],'implementation_sha256':implementation_hash(),
19
+ 'accuracy_validated':False}
20
+ if not options.refinement.enabled:
21
+ metadata['reason_code']='disabled_by_caller';return raw,metadata
22
+ names=('sam-parameters-private.npz','sam-mhr-adapter-private.npz') if options.model=='sam3d' else ('gvhmr-parameters-private.npz',)
23
+ if not all((job/name).is_file() for name in names):
24
+ metadata['reason_code']='native_parameters_unavailable';return raw,metadata
25
+ from .motion_evidence import collect
26
+ arrays,evidence=collect(job,video,capture,models,options,progress)
27
+ displacement=arrays['background_displacement_image_fraction']
28
+ moving=np.isfinite(displacement)&(displacement>options.refinement.maximum_static_background_motion_fraction)
29
+ # A caller's static declaration is contradicted only by multiple robust
30
+ # background observations. This never establishes a calibrated world frame.
31
+ conflict=bool(options.camera_stability=='fixed_verified' and np.count_nonzero(moving)>=3)
32
+ evidence['declared_static_camera_conflict']=conflict
33
+ if evidence['frames_with_minimum_support']<4:
34
+ metadata.update(reason_code='insufficient_image_evidence',image_evidence=evidence);return raw,metadata
35
+ from .sam_runtime import configured_record
36
+ from . import gvhmr_runtime
37
+ record=configured_record() if options.model=='sam3d' else gvhmr_runtime.configured_record()
38
+ if record is None:raise RuntimeError('Native refinement worker is not configured')
39
+ stem='sam' if options.model=='sam3d' else 'gvhmr'
40
+ times=[r['physical_s'] for r in capture['frames']]
41
+ known=all(t is not None for t in times)
42
+ if not known:times=[r['playback_s'] for r in capture['frames']]
43
+ request={'job':str(job.resolve()),'worker_record':os.environ['BASEBALL_SAM_WORKER_RECORD' if options.model=='sam3d' else 'BASEBALL_GVHMR_WORKER_RECORD'],
44
+ 'raw_path':str((job/(stem+'-raw-private.npz')).resolve()),'model':options.model,
45
+ 'times':times,'max_gap_s':options.correction.max_gap_s,'settings':options.refinement.model_dump()}
46
+ path=job/'motion-refine-request-private.json';atomic_json(path,request)
47
+ env=dict(os.environ,MPLBACKEND='Agg',MOMENTUM_ENABLED='0',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
48
+ for secret in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(secret,None)
49
+ progress('loading_native_refinement',0,capture['frame_count'])
50
+ subprocess.run([record['worker_python'],'-m','baseball_batting.motion_refine_worker','--request',str(path)],env=env,check=True)
51
+ with np.load(job/'motion-refined-private.npz',allow_pickle=False) as a:refined=dict(a)
52
+ metadata={**read_json(job/'motion-refinement-private.json'),'implementation_sha256':implementation_hash(),
53
+ 'time_basis':'capture' if known else 'video_only; no physical speed claims','image_evidence':evidence}
54
+ atomic_json(job/'motion-refinement-private.json',metadata)
55
+ return refined,metadata
baseball_batting/motion_refine_worker.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Refit one native rig in its isolated CUDA interpreter; no model fusion."""
2
+ import argparse
3
+ import os
4
+ from pathlib import Path
5
+ import sys
6
+ import numpy as np
7
+ from .storage import read_json,atomic_json
8
+ from .motion_refinement import INDICES,refine_sequence
9
+
10
+
11
+ def load_adapter(job,record,model,raw,device='cuda'):
12
+ import torch
13
+ def tensor(q):return torch.as_tensor(q,dtype=torch.float32,device=device)
14
+ if model=='sam3d':
15
+ from .temporal3d import MHRForward
16
+ with np.load(job/'sam-parameters-private.npz',allow_pickle=False) as a:data=dict(a)
17
+ native=MHRForward(record['mhr_path'],job/'sam-mhr-adapter-private.npz',device)
18
+ motion=data['mhr_model_params']
19
+ if motion.shape[1]!=204:raise ValueError('Unexpected MHR parameter topology')
20
+ parameters={'pose':motion[:,:136],'camera':raw['camera_translation']}
21
+ def factory(segment):
22
+ shape=tensor(np.nanmedian(data['shape_params'][segment],axis=0))
23
+ scales=tensor(np.nanmedian(motion[segment,136:],axis=0))
24
+ # Check native forward conventions before changing shape or pose.
25
+ first=segment[0]
26
+ with torch.no_grad():
27
+ original=native(tensor(data['shape_params'][first]),tensor(motion[first:first+1,:136]),
28
+ tensor(motion[first,136:]),tensor(raw['camera_translation'][first:first+1]))[0,list(INDICES)].cpu().numpy()
29
+ expected=raw['points_body'][first,list(INDICES)]+raw['camera_translation'][first]
30
+ if np.max(np.linalg.norm(original-expected,axis=-1))>.001:
31
+ raise ValueError('Native MHR forward does not reproduce initializer within arithmetic tolerance')
32
+ def forward(pose,camera):
33
+ # Fix native translation; camera is the single translation gauge.
34
+ pose=torch.cat([pose[:,:3].detach(),pose[:,3:]],1)
35
+ return native(shape,pose,scales,camera)[:,list(INDICES)]
36
+ return forward
37
+ else:
38
+ repo=Path(record['gvhmr_repo']).resolve();os.chdir(repo);sys.path.insert(0,str(repo))
39
+ from hmr4d.utils.smplx_utils import make_smplx
40
+ from smplx.joint_names import JOINT_NAMES
41
+ from .motion_adapters import SMPLX_MAP
42
+ with np.load(job/'gvhmr-parameters-private.npz',allow_pickle=False) as a:data=dict(a)
43
+ native=make_smplx('supermotion').eval().to(device)
44
+ for parameter in native.parameters():parameter.requires_grad_(False)
45
+ indices=[]
46
+ for name,index in SMPLX_MAP.items():
47
+ if JOINT_NAMES[index]!=name:raise ValueError('SMPL-X anatomical map changed')
48
+ indices.append(index)
49
+ parameters={'pose':np.concatenate([data['global_orient'],data['body_pose']],-1),'camera':data['transl']}
50
+ def factory(segment):
51
+ shape=tensor(np.nanmedian(data['betas'][segment],axis=0))
52
+ def forward(pose,camera):
53
+ # No transl argument: add the separately fitted camera exactly once.
54
+ return native(betas=shape[None].expand(len(pose),-1),global_orient=pose[:,:3],body_pose=pose[:,3:]).joints[:,indices]+camera[:,None]
55
+ first=segment[0]
56
+ with torch.no_grad():original=forward(tensor(parameters['pose'][first:first+1]),tensor(parameters['camera'][first:first+1]))[0].cpu().numpy()
57
+ expected=raw['points_body'][first,list(INDICES)]+raw['camera_translation'][first]
58
+ if np.max(np.linalg.norm(original-expected,axis=-1))>.001:raise ValueError('SMPL-X native reconstruction mismatch')
59
+ return forward
60
+ return parameters,factory
61
+
62
+
63
+ def run(request):
64
+ import torch
65
+ if not torch.cuda.is_available():raise RuntimeError('Native motion refinement requires CUDA')
66
+ torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
67
+ job=Path(request['job']).resolve();record=read_json(request['worker_record'])
68
+ with np.load(request['raw_path'],allow_pickle=False) as a:raw=dict(a)
69
+ with np.load(job/'motion-evidence-private.npz',allow_pickle=False) as a:evidence=dict(a)
70
+ parameters,factory=load_adapter(job,record,request['model'],raw)
71
+ # Split invalid parameter frames, without inventing poses through the hole.
72
+ evidence['frame_usable']&=np.isfinite(parameters['pose']).all(-1)&np.isfinite(parameters['camera']).all(-1)
73
+ raw['sequence_ids']=np.asarray(raw.get('sequence_ids',np.zeros(len(parameters['pose']),int)))*(len(parameters['pose'])+1)+evidence['sequence_ids']
74
+ def progress(stage,done,total):atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total})
75
+ refined,metadata=refine_sequence(factory,parameters,raw,evidence,np.array(request['times']),request['settings'],request['max_gap_s'],progress=progress)
76
+ if 'distortion' in evidence:refined['distortion']=evidence['distortion']
77
+ # Private parameter/candidate arrays never enter the artifact allowlist.
78
+ np.savez_compressed(job/'motion-refined-private.npz',**refined)
79
+ atomic_json(job/'motion-refinement-private.json',metadata)
80
+
81
+
82
+ def main():
83
+ parser=argparse.ArgumentParser();parser.add_argument('--request',required=True);args=parser.parse_args()
84
+ request=read_json(args.request)
85
+ try:run(request);return 0
86
+ except Exception as error:
87
+ atomic_json(Path(request['job'])/'motion-refinement-error-private.json',
88
+ {'reason_code':'native_refinement_failed','error_type':type(error).__name__})
89
+ print(type(error).__name__+': '+str(error),flush=True);return 1
90
+
91
+
92
+ if __name__=='__main__':raise SystemExit(main())
baseball_batting/motion_refinement.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Whole-body fitting and acceptance checks; no GPU/provider imports at module import.
2
+
3
+ Image evidence is a noisy constraint, not 3D truth. Only native model parameters
4
+ are fitted. Shared shape is supplied by the adapter; joints are never stretched
5
+ individually. Every rejected window rolls back to its native prediction.
6
+ """
7
+ import numpy as np
8
+ from .sam_motion import MHR, BONES, segments
9
+
10
+ VERSION = 'native-body-refinement-v1'
11
+ NAMES = tuple(MHR)
12
+ INDICES = tuple(MHR.values())
13
+ LOCAL = {name:i for i,name in enumerate(NAMES)}
14
+ EDGES = [(INDICES.index(a),INDICES.index(b)) for a,b in BONES]
15
+
16
+
17
+ def continuous_windows(valid,times,sequence,maximum,context,max_gap):
18
+ """One owner per source frame; missing frames/clocks/model boundaries split fits."""
19
+ for run in segments(valid,times,max_gap):
20
+ for ids in np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1):
21
+ if len(ids)<4:continue
22
+ core=maximum-2*context
23
+ if len(ids)<=maximum:
24
+ yield ids,ids
25
+ else:
26
+ for start in range(0,len(ids),core):
27
+ end=min(start+core,len(ids))
28
+ yield ids[max(0,start-context):min(len(ids),end+context)],ids[start:end]
29
+
30
+
31
+ def project_torch(points,k,distortion=None):
32
+ """Same Brown–Conrady projection as public replay, differentiable in the rig."""
33
+ z=points[...,2:].clamp(min=1e-5);xy=points[...,:2]/z
34
+ if distortion is not None:
35
+ x,y=xy.unbind(-1);k1,k2,p1,p2,k3=distortion
36
+ r2=x*x+y*y;radial=1+k1*r2+k2*r2*r2+k3*r2*r2*r2
37
+ import torch
38
+ xy=torch.stack([x*radial+2*p1*x*y+p2*(r2+2*x*x),
39
+ y*radial+p1*(r2+2*y*y)+2*p2*x*y],-1)
40
+ import torch
41
+ homogeneous=torch.cat([xy,torch.ones_like(z)],-1)
42
+ return torch.einsum('nji,nki->njk',homogeneous,k)[...,:2]
43
+
44
+
45
+ def body_size(points):
46
+ # Trunk + hip/ankle distance is less affected by raised hands than a bbox.
47
+ sizes=[]
48
+ for side in ('left','right'):
49
+ a,b,c=[LOCAL[side+'_'+part] for part in ('shoulder','hip','ankle')]
50
+ sizes.append(np.linalg.norm(points[:,a]-points[:,b],axis=-1)+
51
+ np.linalg.norm(points[:,b]-points[:,c],axis=-1))
52
+ q=np.concatenate(sizes);q=q[np.isfinite(q)&(q>1e-5)]
53
+ return float(np.median(q)) if len(q) else None
54
+
55
+
56
+ def fit_window(forward,pose,camera,target,pixels,weights,times,intrinsics,box_heights,
57
+ settings,distortion=None,temporal_factor=1.,device='cuda'):
58
+ """Adapt the existing MHR fitter's image/prior/temporal objective for either rig.
59
+
60
+ No gap is filled. Robust penalties and image-score weights avoid treating
61
+ detector guesses as exact anatomical positions. Camera translation has one
62
+ owner, in the adapter, and is never interpreted as ground movement.
63
+ """
64
+ import torch
65
+ def tensor(v):return torch.as_tensor(v,dtype=torch.float32,device=device)
66
+ initial_pose=tensor(pose);initial_camera=tensor(camera);target=tensor(target)
67
+ p=torch.nn.Parameter(initial_pose.clone());c=torch.nn.Parameter(initial_camera.clone())
68
+ w=tensor(weights);observed=tensor(np.nan_to_num(pixels));k=tensor(intrinsics)
69
+ heights=tensor(box_heights).clamp(min=1)
70
+ size=body_size(target.detach().cpu().numpy())
71
+ if size is None:raise ValueError('refinement_body_scale_unresolved')
72
+ t=tensor(times);dt=t[1:]-t[:-1]
73
+ if (dt<=0).any():raise ValueError('refinement_clock_not_increasing')
74
+ distortion=tensor(distortion) if distortion is not None else None
75
+ sigma=heights[:,None]*settings['observation_scale_box_fraction']
76
+ hip=[LOCAL['left_hip'],LOCAL['right_hip']]
77
+ initial_relative=target-target[:,hip].mean(1)[:,None]
78
+ speed=(initial_relative[1:]-initial_relative[:-1]).norm(dim=-1)/dt[:,None]
79
+ # Fast motion receives a larger allowable curvature. No speed rejection.
80
+ tolerance=(.005*size+.03*torch.maximum(speed[:-1],speed[1:])*
81
+ ((dt[:-1]+dt[1:])/2)[:,None]).detach()
82
+ def evaluate():
83
+ xyz=forward(p,c)
84
+ projected=project_torch(xyz,k,distortion)
85
+ e=(projected-observed)/sigma[...,None]
86
+ image=((torch.sqrt(1+e.square().sum(-1))-1)*w).sum()/w.sum().clamp(min=1)
87
+ prior=((xyz-target)/size).square().mean()
88
+ relative=xyz-xyz[:,hip].mean(1)[:,None]
89
+ fraction=(dt[:-1]/(dt[:-1]+dt[1:]))[:,None,None]
90
+ middle=relative[:-2]+fraction*(relative[2:]-relative[:-2])
91
+ q=(relative[1:-1]-middle)/tolerance[...,None]
92
+ temporal=(torch.sqrt(1+q.square().sum(-1))-1).mean()
93
+ cheirality=torch.relu(.02-xyz[...,2]).square().mean()
94
+ # Native coordinate units differ. A weak parameter anchor complements
95
+ # the unitless 3D anchor; no invented anatomical angle limits are used.
96
+ parameter=((p-initial_pose).square().mean()+((c-initial_camera)/size).square().mean())
97
+ loss=image+settings['initializer_weight']*prior+settings['temporal_weight']*temporal_factor*temporal+1e-4*parameter+100*cheirality
98
+ return loss,xyz,projected
99
+ optimizer=torch.optim.Adam([p,c],lr=settings['learning_rate'])
100
+ best=float('inf');best_pose=p.detach().clone();best_camera=c.detach().clone()
101
+ for _ in range(settings['iterations']):
102
+ optimizer.zero_grad();loss,_,_=evaluate()
103
+ if not torch.isfinite(loss):raise ValueError('refinement_nonfinite_objective')
104
+ value=float(loss.detach())
105
+ if value<best:best=value;best_pose=p.detach().clone();best_camera=c.detach().clone()
106
+ loss.backward();torch.nn.utils.clip_grad_norm_([p,c],5.);optimizer.step()
107
+ with torch.no_grad():
108
+ loss,_,_=evaluate()
109
+ if torch.isfinite(loss) and float(loss)<best:best_pose=p.detach().clone();best_camera=c.detach().clone()
110
+ xyz=forward(best_pose,best_camera);xy=project_torch(xyz,k,distortion)
111
+ return {'points_camera':xyz.detach().cpu().numpy(),'projection':xy.detach().cpu().numpy(),
112
+ 'pose':best_pose.cpu().numpy(),'camera':best_camera.cpu().numpy()}
113
+
114
+
115
+ def acceptance(original,candidate,original_xy,candidate_xy,pixels,weights,times,box_heights,settings):
116
+ """Independent diagnostics, beyond the optimizer's scalar objective.
117
+
118
+ Thresholds are configurable engineering gates, not validated accuracy limits.
119
+ Accept/reject a complete window to avoid framewise replacement artifacts.
120
+ """
121
+ size=body_size(original);reasons=[]
122
+ if size is None or not np.isfinite(candidate).all() or (candidate[...,2]<=0).any():
123
+ return False,{'reasons':['nonfinite_or_invalid_body_geometry']}
124
+ observed=(weights>0)&np.isfinite(pixels).all(-1)
125
+ if (observed.sum(1)>=settings['minimum_observed_joints']).mean()<.75:
126
+ reasons.append('insufficient_image_support')
127
+ def errors(xy):
128
+ e=np.linalg.norm(xy-pixels,axis=-1)/np.maximum(box_heights[:,None],1)
129
+ return float(np.sum(np.where(observed,e,0)*weights)/max(weights.sum(),1e-9))
130
+ before,after=errors(original_xy),errors(candidate_xy)
131
+ if not np.isfinite(after) or after>settings['maximum_observation_error_box_fraction']:
132
+ reasons.append('image_alignment_outside_gate')
133
+ if after>before+1e-5:reasons.append('image_alignment_worsened')
134
+ hip=[LOCAL['left_hip'],LOCAL['right_hip']]
135
+ old=original-original[:,hip].mean(1)[:,None];new=candidate-candidate[:,hip].mean(1)[:,None]
136
+ change=float(np.max(np.linalg.norm(new-old,axis=-1))/size)
137
+ if change>settings['maximum_body_change_fraction']:reasons.append('excessive_body_adjustment')
138
+ bone_change=0.
139
+ for a,b in EDGES:
140
+ lengths=np.linalg.norm(new[:,a]-new[:,b],axis=-1)
141
+ baseline=np.median(np.linalg.norm(old[:,a]-old[:,b],axis=-1))
142
+ if baseline>size*.01:
143
+ bone_change=max(bone_change,float(np.max(np.abs(lengths-baseline))/baseline))
144
+ if bone_change>settings['maximum_bone_change_fraction']:reasons.append('body_proportions_changed')
145
+ # A fast, image-supported hand peak cannot be erased or moved by smoothing.
146
+ peak_checks=[]
147
+ for side in ('left','right'):
148
+ j=LOCAL[side+'_wrist'];dt=np.diff(times)
149
+ a=np.linalg.norm(np.diff(old[:,j],axis=0),axis=-1)/dt
150
+ b=np.linalg.norm(np.diff(new[:,j],axis=0),axis=-1)/dt
151
+ supported=observed[:-1,j]&observed[1:,j]
152
+ if not supported.any():continue
153
+ reference=np.where(supported,a,-np.inf);peak=int(np.argmax(reference))
154
+ # Only protect a peak if its two endpoints agree with the image.
155
+ residual=np.linalg.norm(original_xy[:,j]-pixels[:,j],axis=-1)/box_heights
156
+ if a[peak]<size or np.max(residual[peak:peak+2])>settings['observation_scale_box_fraction']:continue
157
+ image_speed=np.linalg.norm(np.diff(pixels[:,j],axis=0),axis=-1)/dt
158
+ projected_speed=np.linalg.norm(np.diff(original_xy[:,j],axis=0),axis=-1)/dt
159
+ image_peak=int(np.argmax(np.where(supported,image_speed,-np.inf)))
160
+ if (abs(times[image_peak]-times[peak])>np.median(dt) or
161
+ abs(projected_speed[peak]-image_speed[peak])/max(image_speed[peak],1e-9)>
162
+ settings['maximum_peak_speed_change_fraction']):continue
163
+ peak_new=int(np.argmax(np.where(supported,b,-np.inf)))
164
+ shift=abs((times[peak_new]+times[peak_new+1]-times[peak]-times[peak+1])/2)
165
+ ratio=abs(b[peak_new]-a[peak])/max(a[peak],1e-9)
166
+ peak_checks.append({'joint':NAMES[j],'shift_s':float(shift),'speed_change_fraction':float(ratio)})
167
+ if shift>max(settings['maximum_peak_time_shift_s'],float(np.median(dt))):reasons.append('fast_hand_peak_shifted')
168
+ if ratio>settings['maximum_peak_speed_change_fraction']:reasons.append('fast_hand_peak_distorted')
169
+ return not reasons,{'reasons':sorted(set(reasons)),'image_error_before_box_fraction':before,
170
+ 'image_error_after_box_fraction':after,'maximum_body_adjustment_fraction':change,
171
+ 'maximum_bone_change_fraction':bone_change,'fast_hand_peak_checks':peak_checks}
172
+
173
+
174
+ def refine_sequence(forward_factory,parameters,raw,evidence,times,settings,max_gap,device='cuda',progress=None):
175
+ """Fit each continuous segment; keep raw input, ownership and sensitivity explicit."""
176
+ n=len(times);indices=list(INDICES);result={k:np.array(v,copy=True) for k,v in raw.items()}
177
+ points=raw['points_body'][:,indices]+raw['camera_translation'][:,None]
178
+ valid=np.isfinite(points).all((1,2))&raw['projection_valid']&evidence['frame_usable']
179
+ sequence=np.asarray(raw.get('sequence_ids',np.zeros(n,int)))
180
+ accepted=np.zeros(n,bool);sensitivity=np.full((n,70),np.nan);boundaries=np.zeros(n,bool)
181
+ scenarios=np.repeat(raw['points_body'][None],len(settings['sensitivity_factors']),axis=0)
182
+ scenario_valid=np.zeros((len(scenarios),n),bool)
183
+ windows=[];fitted_pose=np.array(parameters['pose'],copy=True);fitted_camera=np.array(parameters['camera'],copy=True)
184
+ distortion=evidence.get('distortion');serial=np.array(sequence,copy=True)
185
+ # Shape aggregation is limited to a continuous identity/model segment.
186
+ for contiguous in segments(valid,times,max_gap):
187
+ for segment in np.split(contiguous,np.flatnonzero(np.diff(sequence[contiguous])!=0)+1):
188
+ if len(segment)<4:continue
189
+ forward=forward_factory(segment)
190
+ local_valid=np.zeros(n,bool);local_valid[segment]=True
191
+ for ids,owned in continuous_windows(local_valid,times,sequence,settings['window_frames'],settings['context_frames'],max_gap):
192
+ take=np.searchsorted(ids,owned)
193
+ pixels=evidence['pixels'][ids];weights=evidence['weights'][ids]
194
+ arguments=(forward,parameters['pose'][ids],parameters['camera'][ids],points[ids],pixels,weights,
195
+ times[ids],raw['intrinsics'][ids],evidence['box_heights'][ids],settings)
196
+ try:
197
+ fit=fit_window(*arguments,distortion=distortion,device=device)
198
+ from .geometry import project
199
+ original_xy=np.stack([project(p,k,distortion) for p,k in zip(points[ids],raw['intrinsics'][ids])])
200
+ ok,checks=acceptance(points[ids],fit['points_camera'],original_xy,fit['projection'],pixels,weights,
201
+ times[ids],evidence['box_heights'][ids],settings)
202
+ maximum=np.zeros((len(ids),len(indices)))
203
+ sensitivity_complete=True
204
+ if ok:
205
+ for scenario_index,factor in enumerate(settings['sensitivity_factors']):
206
+ alternative=fit_window(*arguments,distortion=distortion,device=device,temporal_factor=factor)
207
+ good,_=acceptance(points[ids],alternative['points_camera'],original_xy,alternative['projection'],pixels,weights,
208
+ times[ids],evidence['box_heights'][ids],settings)
209
+ if not good:sensitivity_complete=False
210
+ hip=[LOCAL['left_hip'],LOCAL['right_hip']]
211
+ alt_relative=alternative['points_camera']-alternative['points_camera'][:,hip].mean(1)[:,None]
212
+ fit_relative=fit['points_camera']-fit['points_camera'][:,hip].mean(1)[:,None]
213
+ delta=np.linalg.norm(alt_relative-fit_relative,axis=-1)
214
+ maximum=np.maximum(maximum,delta)
215
+ scenarios[scenario_index][np.ix_(owned,indices)]=alternative['points_camera'][take]-alternative['camera'][take,None]
216
+ scenario_valid[scenario_index,owned]=good
217
+ if ok:
218
+ accepted[owned]=True
219
+ fitted_pose[owned]=fit['pose'][take];fitted_camera[owned]=fit['camera'][take]
220
+ result['camera_translation'][owned]=fit['camera'][take]
221
+ result['points_body'][np.ix_(owned,indices)]=fit['points_camera'][take]-fit['camera'][take,None]
222
+ result['projection'][np.ix_(owned,indices)]=fit['projection'][take]
223
+ if sensitivity_complete:sensitivity[np.ix_(owned,indices)]=maximum[take]
224
+ checks['sensitivity_complete']=sensitivity_complete if ok else False
225
+ except (ValueError,FloatingPointError) as error:
226
+ ok=False;checks={'reasons':['refinement_numerical_failure'],'error_type':type(error).__name__}
227
+ windows.append({'start_frame':int(owned[0]),'end_frame':int(owned[-1]),
228
+ 'context_start_frame':int(ids[0]),'context_end_frame':int(ids[-1]),'accepted':bool(ok),**checks})
229
+ if len(segment)>settings['window_frames']:
230
+ boundaries[owned[0]]=True;boundaries[owned[-1]]=True
231
+ if progress:progress('whole_body_refinement',int(owned[-1])+1,n)
232
+ # No derivative spans a switch between raw/refined motion, or fit-window seam.
233
+ boundaries[1:]|=accepted[1:]!=accepted[:-1];boundaries[:-1]|=accepted[1:]!=accepted[:-1]
234
+ extra=np.cumsum(np.r_[0,(boundaries[1:]|boundaries[:-1])])
235
+ result['sequence_ids']=serial*(n+1)+extra
236
+ result['refinement_accepted']=accepted;result['refinement_boundary']=boundaries
237
+ result['refinement_sensitivity_m']=sensitivity
238
+ result['refinement_pose']=fitted_pose;result['refinement_camera']=fitted_camera
239
+ result['refinement_scenario_points_body']=scenarios;result['refinement_scenario_valid']=scenario_valid
240
+ # Retaining the native prediction is explicit rollback, not an assertion that
241
+ # it agrees with the image. Strong contradictory evidence disables that joint.
242
+ from .geometry import project
243
+ final_xy=np.stack([project(p[list(INDICES)]+c,k,distortion) for p,c,k in
244
+ zip(result['points_body'],result['camera_translation'],result['intrinsics'])])
245
+ error=np.linalg.norm(final_xy-evidence['pixels'],axis=-1)/evidence['box_heights'][:,None]
246
+ strong=evidence['weights']>=max(settings['minimum_observation_score'],.7)
247
+ conflict=strong&(error>settings['maximum_observation_error_box_fraction'])
248
+ joint_usable=np.asarray(result.get('joint_usable',np.ones((n,70),bool))).copy()
249
+ joint_usable[:,list(INDICES)]&=~conflict
250
+ result['joint_usable']=joint_usable
251
+ conflict_full=np.zeros((n,70),bool);conflict_full[:,list(INDICES)]=conflict
252
+ result['refinement_image_conflict']=conflict_full
253
+ metadata={'version':VERSION,'enabled':True,'method':'native_rig_image_constrained_sequence_fit',
254
+ 'settings':settings,'accepted_frame_count':int(accepted.sum()),'native_fallback_frame_count':int((~accepted).sum()),
255
+ 'windows':windows,'shape_scope':'shared_per_contiguous_identity_and_model_segment',
256
+ 'gap_interpolation':'disabled; no image evidence invented','parameter_limits':'native_rig_and_initializer_prior; no invented anatomical bounds',
257
+ 'sensitivity_kind':'temporal_regularization_sensitivity; not a calibrated error interval',
258
+ 'sensitivity_factors':settings['sensitivity_factors'],'accuracy_validated':False}
259
+ metadata['image_conflicting_joint_count']=int(conflict.sum())
260
+ return result,metadata
baseball_batting/motion_tracking.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Conservative recovery of a short detection loss, limited to the motion API."""
2
+ import numpy as np
3
+ from .detection import iou,select_person,relevant_people
4
+
5
+
6
+ def appearance(image,box):
7
+ import cv2
8
+ h,w=image.shape[:2];x1,y1,x2,y2=np.asarray(box,float)
9
+ # Clothing/torso rather than a changing background or the moving bat.
10
+ x1,x2=x1+.2*(x2-x1),x2-.2*(x2-x1);y2=y1+.65*(y2-y1)
11
+ x1,y1,x2,y2=np.rint([x1,y1,x2,y2]).astype(int)
12
+ crop=image[max(0,y1):min(h,y2),max(0,x1):min(w,x2)]
13
+ if crop.size<48:return None
14
+ hsv=cv2.cvtColor(crop,cv2.COLOR_BGR2HSV)
15
+ hist=cv2.calcHist([hsv],[0,1],None,[16,8],[0,180,0,256]).ravel()
16
+ return hist/max(np.linalg.norm(hist),1e-8)
17
+
18
+
19
+ class AthleteRecovery:
20
+ def __init__(self,settings):
21
+ self.settings=settings;self.box=None;self.template=None;self.last_time=None
22
+ self.velocity=np.zeros(4);self.lost=False;self.ambiguous=False
23
+
24
+ def update(self,image,detections,t,roi=None):
25
+ candidates=[d for d in detections if d['class_id']==0]
26
+ if self.box is None:
27
+ selected=select_person(candidates,roi)
28
+ if selected is None:return None,'person_not_tracked'
29
+ if roi is None and relevant_people(candidates,selected,image.shape[0])>1:
30
+ raise ValueError('multiple_people_select_athlete_box')
31
+ else:
32
+ gap=t-self.last_time
33
+ if gap<=0:raise ValueError('Tracking clock must increase')
34
+ predicted=np.asarray(self.box)+self.velocity*gap
35
+ overlaps=iou(predicted,[d['box'] for d in candidates])
36
+ eligible=np.flatnonzero(overlaps>=.05)
37
+ if len(eligible)>1:
38
+ self.lost=True;self.ambiguous=True
39
+ return None,'identity_ambiguous_multiple_overlapping_athletes'
40
+ selected=candidates[eligible[0]] if len(eligible)==1 else None
41
+ if self.lost or selected is None:
42
+ if (not self.settings.recover_short_losses or gap>self.settings.maximum_recovery_gap_s or
43
+ self.template is None or self.ambiguous):
44
+ self.lost=True;return None,'identity_uncertain_after_tracking_loss'
45
+ choices=[]
46
+ for d in candidates:
47
+ b=np.asarray(d['box']);size=b[2:]-b[:2];old=np.asarray(self.box[2:])-self.box[:2]
48
+ if (size<=0).any() or (size/old<.6).any() or (size/old>1.6).any():continue
49
+ if iou(predicted,[b])[0]<.15:continue
50
+ feature=appearance(image,b)
51
+ if feature is not None:choices.append((float(self.template@feature),d))
52
+ choices.sort(key=lambda p:p[0],reverse=True)
53
+ if not choices or choices[0][0]<self.settings.minimum_appearance_similarity or (
54
+ len(choices)>1 and choices[0][0]-choices[1][0]<self.settings.minimum_candidate_margin):
55
+ self.lost=True;return None,'identity_uncertain_after_tracking_loss'
56
+ selected=choices[0][1]
57
+ box=np.asarray(selected['box'],float);h,w=image.shape[:2]
58
+ box=np.maximum([0,0,0,0],np.minimum([w,h,w,h],box))
59
+ feature=appearance(image,box)
60
+ if self.box is not None:
61
+ velocity=(box-self.box)/(t-self.last_time)
62
+ self.velocity=.5*self.velocity+.5*velocity
63
+ self.box=box;self.last_time=t;self.lost=False
64
+ if feature is not None:
65
+ if self.template is None:self.template=feature
66
+ else:
67
+ self.template=.95*self.template+.05*feature
68
+ self.template/=max(np.linalg.norm(self.template),1e-8)
69
+ return box.tolist(),None
baseball_batting/motion_worker.py CHANGED
@@ -29,11 +29,16 @@ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120,retention
29
  with np.load(job/files[0],allow_pickle=False) as data:raw=dict(data)
30
  model=read_json(job/files[1])['model']
31
  model={**model,'inference_reused_from_job':reused['job_id']}
32
- elif options.model=='sam3d':raw,model=reconstruct_sam(job,video,capture,models,options.sam_options(),progress,strict_identity=True)
33
  else:raw,model=reconstruct_gvhmr(job,video,capture,models,options,progress)
34
- atomic_json(job/'inference-integrity-private.json',{name:sha256_file(job/name) for name in files})
 
 
 
35
  track=read_json(job/'person-track-private.json')
36
- return export_motion(job,video,capture,raw,options,model,lineage,retention_s=retention_s,progress=progress,track=track)
 
 
37
 
38
 
39
  def main():
@@ -48,7 +53,7 @@ def main():
48
  'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames'} else 'motion_processing_failed'
49
  failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
50
  'reason_code':reason,'error_type':type(error).__name__}
51
- for filename in ('sam-raw-private.error.json','gvhmr-raw-private.error.json'):
52
  native_error=Path(args.job)/filename
53
  if native_error.is_file():failure.update(read_json(native_error))
54
  atomic_json(Path(args.job)/'error.json',failure)
 
29
  with np.load(job/files[0],allow_pickle=False) as data:raw=dict(data)
30
  model=read_json(job/files[1])['model']
31
  model={**model,'inference_reused_from_job':reused['job_id']}
32
+ elif options.model=='sam3d':raw,model=reconstruct_sam(job,video,capture,models,options.sam_options(),progress,strict_identity=True,recovery=options.tracking)
33
  else:raw,model=reconstruct_gvhmr(job,video,capture,models,options,progress)
34
+ # Native outputs remain immutable; optional parameters are covered by the
35
+ # same integrity record before an event/correction revision can reuse them.
36
+ extra=('sam-parameters-private.npz','sam-mhr-adapter-private.npz') if options.model=='sam3d' else ('gvhmr-parameters-private.npz',)
37
+ atomic_json(job/'inference-integrity-private.json',{name:sha256_file(job/name) for name in (*files,*extra) if (job/name).is_file()})
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():
 
53
  'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames'} else 'motion_processing_failed'
54
  failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
55
  'reason_code':reason,'error_type':type(error).__name__}
56
+ for filename in ('sam-raw-private.error.json','gvhmr-raw-private.error.json','motion-refinement-error-private.json'):
57
  native_error=Path(args.job)/filename
58
  if native_error.is_file():failure.update(read_json(native_error))
59
  atomic_json(Path(args.job)/'error.json',failure)
baseball_batting/sam_measurement_worker.py CHANGED
@@ -10,18 +10,32 @@ from .sam_batting_contract import SamBattingInput,SamBattingResult,MeasurementGr
10
  from .storage import read_json,atomic_json
11
 
12
 
13
- def athlete_boxes(video,capture,models,options,device,progress,*,strict_identity=False):
 
 
 
 
 
 
14
  from .api_worker import model_files
15
  from .detection import YOLOXDetector,select_person,relevant_people,iou
16
  from .ingest import iter_frames
17
  paths,_=model_files(models)
18
  detector=YOLOXDetector(paths['person_detector'],device,classes=[0])
19
  previous=None;boxes=[];reasons=[];identity_lost=False
 
 
 
20
  width,height=capture['frames'][0]['width'],capture['frames'][0]['height']
21
  roi=options.athlete_box
22
  if roi is not None and (roi[2]>width or roi[3]>height):raise ValueError('Athlete box is outside the upright video')
23
  for i,_,_,image in iter_frames(video,capture['rotation_degrees']):
24
  detections=detector(image)
 
 
 
 
 
25
  selected=select_person(detections,previous or roi)
26
  reason=None
27
  if strict_identity and previous is not None and selected is not None:
@@ -108,7 +122,7 @@ def process_predictions(job,video,capture,raw,options,model,*,progress=lambda *a
108
  return public
109
 
110
 
111
- def reconstruct_sam(job,video,capture,models,options,progress,*,strict_identity=False):
112
  """Shared native reconstruction; exporters must not run a second pose model."""
113
  from .sam_runtime import configured_record
114
  record=configured_record()
@@ -118,14 +132,15 @@ def reconstruct_sam(job,video,capture,models,options,progress,*,strict_identity=
118
  raise ValueError('Changing image dimensions require separate recording segments')
119
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
120
  raise ValueError('Camera principal point is outside upright video')
121
- boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=strict_identity)
122
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
123
  c=options.camera
124
  k=[[c.fx,0,c.cx],[0,c.fy,c.cy],[0,0,1]] if c else None
125
  request={'video':str(video.resolve()),'rotation':capture['rotation_degrees'],
126
  'worker_record':os.environ['BASEBALL_SAM_WORKER_RECORD'],'boxes':boxes,
127
  'frame_count':capture['frame_count'],'image_size':[first['width'],first['height']],
128
- 'intrinsics':k,'progress_path':str(job/'progress.json'),'output':str(job/'sam-raw-private.npz')}
 
129
  atomic_json(job/'sam-request-private.json',request)
130
  env=dict(os.environ,MPLBACKEND='Agg',MOMENTUM_ENABLED='0',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
131
  for secret in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(secret,None)
 
10
  from .storage import read_json,atomic_json
11
 
12
 
13
+ def tracking_hash():
14
+ from .storage import digest,sha256_file
15
+ return digest({name:sha256_file(Path(__file__).with_name(name)) for name in
16
+ ('sam_measurement_worker.py','motion_tracking.py','detection.py')})
17
+
18
+
19
+ def athlete_boxes(video,capture,models,options,device,progress,*,strict_identity=False,recovery=None):
20
  from .api_worker import model_files
21
  from .detection import YOLOXDetector,select_person,relevant_people,iou
22
  from .ingest import iter_frames
23
  paths,_=model_files(models)
24
  detector=YOLOXDetector(paths['person_detector'],device,classes=[0])
25
  previous=None;boxes=[];reasons=[];identity_lost=False
26
+ if recovery is not None:
27
+ from .motion_tracking import AthleteRecovery
28
+ recover=AthleteRecovery(recovery)
29
  width,height=capture['frames'][0]['width'],capture['frames'][0]['height']
30
  roi=options.athlete_box
31
  if roi is not None and (roi[2]>width or roi[3]>height):raise ValueError('Athlete box is outside the upright video')
32
  for i,_,_,image in iter_frames(video,capture['rotation_degrees']):
33
  detections=detector(image)
34
+ if recovery is not None:
35
+ box,reason=recover.update(image,detections,capture['frames'][i]['playback_s'],roi)
36
+ boxes.append(box);reasons.append(reason)
37
+ if i%32==0:progress('person_tracking',i+1,capture['frame_count'])
38
+ continue
39
  selected=select_person(detections,previous or roi)
40
  reason=None
41
  if strict_identity and previous is not None and selected is not None:
 
122
  return public
123
 
124
 
125
+ def reconstruct_sam(job,video,capture,models,options,progress,*,strict_identity=False,recovery=None):
126
  """Shared native reconstruction; exporters must not run a second pose model."""
127
  from .sam_runtime import configured_record
128
  record=configured_record()
 
132
  raise ValueError('Changing image dimensions require separate recording segments')
133
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
134
  raise ValueError('Camera principal point is outside upright video')
135
+ boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=strict_identity,recovery=recovery)
136
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
137
  c=options.camera
138
  k=[[c.fx,0,c.cx],[0,c.fy,c.cy],[0,0,1]] if c else None
139
  request={'video':str(video.resolve()),'rotation':capture['rotation_degrees'],
140
  'worker_record':os.environ['BASEBALL_SAM_WORKER_RECORD'],'boxes':boxes,
141
  'frame_count':capture['frame_count'],'image_size':[first['width'],first['height']],
142
+ 'intrinsics':k,'progress_path':str(job/'progress.json'),'output':str(job/'sam-raw-private.npz'),
143
+ 'retain_native_parameters':strict_identity}
144
  atomic_json(job/'sam-request-private.json',request)
145
  env=dict(os.environ,MPLBACKEND='Agg',MOMENTUM_ENABLED='0',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
146
  for secret in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(secret,None)
baseball_batting/sam_motion.py CHANGED
@@ -100,6 +100,8 @@ def correct_motion(raw, times, settings):
100
  valid &= observed; reasons[~observed] |= OBSERVATION
101
  sequence=np.asarray(raw.get('sequence_ids',np.zeros(len(p),int)))
102
  if sequence.shape!=(len(p),):raise ValueError('Sequence IDs differ from timestamps')
 
 
103
  def runs(mask):
104
  for run in segments(mask,t,settings.max_gap_s):
105
  yield from np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1)
@@ -152,15 +154,21 @@ def correct_motion(raw, times, settings):
152
  for j in range(70):
153
  for ids in runs(valid[:,j]):
154
  q = rel[ids,j]
155
- corrected[ids,j] = _adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
 
 
 
 
 
156
  b = settings.boundary_samples
157
  boundary[ids[:b],j] = True; boundary[ids[-b:],j] = True
158
  reasons[boundary] |= BOUNDARY
159
  # Retain SAM's predicted translation for projection, never call it ground motion.
160
  camera_root = hip + np.asarray(raw['camera_translation'],float)
161
  for ids in runs(hip_ok & np.isfinite(camera_root).all(axis=-1)):
162
- q=camera_root[ids]
163
- camera_root[ids]=_adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
 
164
  corrected_camera = corrected+camera_root[:,None,:]
165
  changes = np.linalg.norm(corrected-rel,axis=-1)
166
  essential=sorted(set(j for edge in BONES for j in edge))
 
100
  valid &= observed; reasons[~observed] |= OBSERVATION
101
  sequence=np.asarray(raw.get('sequence_ids',np.zeros(len(p),int)))
102
  if sequence.shape!=(len(p),):raise ValueError('Sequence IDs differ from timestamps')
103
+ fitted=np.asarray(raw.get('refinement_accepted',np.zeros(len(p),bool)),bool)
104
+ if fitted.shape!=(len(p),):raise ValueError('Refinement mask differs from timestamps')
105
  def runs(mask):
106
  for run in segments(mask,t,settings.max_gap_s):
107
  yield from np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1)
 
154
  for j in range(70):
155
  for ids in runs(valid[:,j]):
156
  q = rel[ids,j]
157
+ # Whole-body fit has its own temporal objective and acceptance tests.
158
+ # Independent joint smoothing here would break its anatomical rig.
159
+ corrected[ids,j]=q
160
+ for unfitted in np.split(ids,np.flatnonzero(np.diff(fitted[ids]))+1):
161
+ if len(unfitted) and not fitted[unfitted[0]]:
162
+ corrected[unfitted,j]=_adaptive_smooth(rel[unfitted,j],t[unfitted],settings.min_cutoff_hz,settings.speed_coefficient)
163
  b = settings.boundary_samples
164
  boundary[ids[:b],j] = True; boundary[ids[-b:],j] = True
165
  reasons[boundary] |= BOUNDARY
166
  # Retain SAM's predicted translation for projection, never call it ground motion.
167
  camera_root = hip + np.asarray(raw['camera_translation'],float)
168
  for ids in runs(hip_ok & np.isfinite(camera_root).all(axis=-1)):
169
+ for unfitted in np.split(ids,np.flatnonzero(np.diff(fitted[ids]))+1):
170
+ if len(unfitted) and not fitted[unfitted[0]]:
171
+ camera_root[unfitted]=_adaptive_smooth(camera_root[unfitted],t[unfitted],settings.min_cutoff_hz,settings.speed_coefficient)
172
  corrected_camera = corrected+camera_root[:,None,:]
173
  changes = np.linalg.norm(corrected-rel,axis=-1)
174
  essential=sorted(set(j for edge in BONES for j in edge))
baseball_batting/sam_pose_worker.py CHANGED
@@ -44,7 +44,7 @@ def run(request):
44
  cam=np.full((n,3),np.nan); ks=np.full((n,3,3),np.nan); valid=np.zeros(n,bool)
45
  camera=request.get('intrinsics')
46
  camera_tensor=torch.tensor(camera,dtype=torch.float32)[None] if camera is not None else None
47
- boxes=request['boxes']; started=time.monotonic()
48
  for i,_,_,image in iter_frames(request['video'],request['rotation']):
49
  if i>=n: raise ValueError('Source changed after ingest')
50
  if boxes[i] is not None:
@@ -54,6 +54,17 @@ def run(request):
54
  predictions=estimator.process_one_image(image[...,::-1].copy(),**kwargs)
55
  if len(predictions)==1:
56
  rows[i],xy[i],cam[i],ks[i],valid[i]=native_prediction(predictions[0],image.shape,camera)
 
 
 
 
 
 
 
 
 
 
 
57
  atomic_json(request['progress_path'],{'stage':'sam_full_video','completed_frames':i+1,
58
  'total_frames':n,'stage_progress':(i+1)/n,'elapsed_s':round(time.monotonic()-started,2)})
59
  destination=Path(request['output'])
@@ -61,6 +72,8 @@ def run(request):
61
  np.savez_compressed(tmp,points_body=rows,projection=xy,camera_translation=cam,
62
  intrinsics=ks,projection_valid=valid,image_size=np.array(request['image_size']))
63
  tmp.replace(destination)
 
 
64
  atomic_json(destination.with_suffix('.json'),{'model':model,'frames_predicted':int(np.isfinite(rows).any(axis=(1,2)).sum()),
65
  'frames_projection_verified':int(valid.sum()),'inference_type':'full_body_and_hands',
66
  'inference_elapsed_s':round(time.monotonic()-started,3),
 
44
  cam=np.full((n,3),np.nan); ks=np.full((n,3,3),np.nan); valid=np.zeros(n,bool)
45
  camera=request.get('intrinsics')
46
  camera_tensor=torch.tensor(camera,dtype=torch.float32)[None] if camera is not None else None
47
+ boxes=request['boxes']; started=time.monotonic();parameters={};adapter_exported=False
48
  for i,_,_,image in iter_frames(request['video'],request['rotation']):
49
  if i>=n: raise ValueError('Source changed after ingest')
50
  if boxes[i] is not None:
 
54
  predictions=estimator.process_one_image(image[...,::-1].copy(),**kwargs)
55
  if len(predictions)==1:
56
  rows[i],xy[i],cam[i],ks[i],valid[i]=native_prediction(predictions[0],image.shape,camera)
57
+ if request.get('retain_native_parameters'):
58
+ prediction=predictions[0]
59
+ if not adapter_exported:
60
+ from .temporal3d import export_mhr_adapter
61
+ record=read_json(request['worker_record'])
62
+ export_mhr_adapter(estimator.model,Path(request['output']).with_name('sam-mhr-adapter-private.npz'),prediction,record['mhr_path'])
63
+ adapter_exported=True
64
+ for key in ('mhr_model_params','shape_params','scale_params'):
65
+ value=np.asarray(prediction[key]).reshape(-1)
66
+ if key not in parameters:parameters[key]=np.full((n,len(value)),np.nan)
67
+ parameters[key][i]=value
68
  atomic_json(request['progress_path'],{'stage':'sam_full_video','completed_frames':i+1,
69
  'total_frames':n,'stage_progress':(i+1)/n,'elapsed_s':round(time.monotonic()-started,2)})
70
  destination=Path(request['output'])
 
72
  np.savez_compressed(tmp,points_body=rows,projection=xy,camera_translation=cam,
73
  intrinsics=ks,projection_valid=valid,image_size=np.array(request['image_size']))
74
  tmp.replace(destination)
75
+ if request.get('retain_native_parameters'):
76
+ np.savez_compressed(destination.with_name('sam-parameters-private.npz'),**parameters,camera_translation=cam)
77
  atomic_json(destination.with_suffix('.json'),{'model':model,'frames_predicted':int(np.isfinite(rows).any(axis=(1,2)).sum()),
78
  'frames_projection_verified':int(valid.sum()),'inference_type':'full_body_and_hands',
79
  'inference_elapsed_s':round(time.monotonic()-started,3),
baseball_batting/sam_videos.py CHANGED
@@ -13,9 +13,9 @@ FOCUS={'rotation':{5,6,9,10},'timing':{5,6,7,8,9,10,41,62},
13
  'posture':{3,4,5,6,9,10},'stance':{9,10,11,12,13,14,15,16,17,18,19,20}}
14
 
15
 
16
- def corrected_projection(corrected,intrinsics,index):
17
  points=corrected['points_camera'][index];k=intrinsics[index]
18
- xy=project(points,k) if np.isfinite(k).all() else np.full((70,2),np.nan)
19
  valid=corrected['valid'][index]&np.isfinite(xy).all(axis=-1)&(points[:,2]>1e-8)
20
  return xy,valid
21
 
@@ -38,7 +38,7 @@ def draw_group(image,xy,valid,group):
38
  return image
39
 
40
 
41
- def export_group_videos(video,capture,corrected,intrinsics,job,progress=None):
42
  job=Path(job);folder=job/'group-videos';folder.mkdir(exist_ok=True)
43
  keys=list(GROUPS);clips={k:Clip(status='unavailable',reason_code='annotation_export_failed') for k in keys}
44
  writers={};frames=capture['frames'];n=len(frames)
@@ -51,7 +51,7 @@ def export_group_videos(video,capture,corrected,intrinsics,job,progress=None):
51
  if i>=n or pts is None or not base or pts*base!=source[i]:raise ClipError('source_video_mismatch')
52
  ticks=(timeline[i+1]-timeline[i]) if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
53
  if ticks<=0:raise ClipError('last_frame_duration_unavailable')
54
- xy,valid=corrected_projection(corrected,intrinsics,i)
55
  for key in keys:
56
  annotated=draw_group(image,xy,valid,key)
57
  if key not in writers:writers[key]=_Writer(temporary[key],annotated.shape)
 
13
  'posture':{3,4,5,6,9,10},'stance':{9,10,11,12,13,14,15,16,17,18,19,20}}
14
 
15
 
16
+ def corrected_projection(corrected,intrinsics,index,distortion=None):
17
  points=corrected['points_camera'][index];k=intrinsics[index]
18
+ xy=project(points,k,distortion) if np.isfinite(k).all() else np.full((70,2),np.nan)
19
  valid=corrected['valid'][index]&np.isfinite(xy).all(axis=-1)&(points[:,2]>1e-8)
20
  return xy,valid
21
 
 
38
  return image
39
 
40
 
41
+ def export_group_videos(video,capture,corrected,intrinsics,job,progress=None,distortion=None):
42
  job=Path(job);folder=job/'group-videos';folder.mkdir(exist_ok=True)
43
  keys=list(GROUPS);clips={k:Clip(status='unavailable',reason_code='annotation_export_failed') for k in keys}
44
  writers={};frames=capture['frames'];n=len(frames)
 
51
  if i>=n or pts is None or not base or pts*base!=source[i]:raise ClipError('source_video_mismatch')
52
  ticks=(timeline[i+1]-timeline[i]) if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
53
  if ticks<=0:raise ClipError('last_frame_duration_unavailable')
54
+ xy,valid=corrected_projection(corrected,intrinsics,i,distortion)
55
  for key in keys:
56
  annotated=draw_group(image,xy,valid,key)
57
  if key not in writers:writers[key]=_Writer(temporary[key],annotated.shape)
docs/MOTION_PLAYER_API.md CHANGED
@@ -1,6 +1,6 @@
1
  # Motion-player backend API
2
 
3
- Contract 1.0 · SAM and GVHMR adapters · 15 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
@@ -86,10 +86,79 @@ source-frame indices. `scale_status` defaults to `model_estimated`; `calibrated`
86
  requires a calibration source; `unknown` exports model units and disables absolute
87
  distances/linear speeds. Height alone is not camera calibration. `source_mirrored`
88
  records the source information; the adapter does not silently flip/relabel it.
89
- This version uses a pinhole model; distortion correction and calibrated ground
90
- translation are not supplied. Missing calibration does not prevent motion export.
 
 
 
91
  Coaching/LLM calls are disabled on this path.
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  The 202 response includes `analysis_id`, `job_id`, `analysis_revision`,
94
  `parent_job_id`, `status_url`, `result_url` and `retention_hours`. The first
95
  analysis ID equals its job ID. Poll the supplied status URL until `completed` or
 
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
 
86
  requires a calibration source; `unknown` exports model units and disables absolute
87
  distances/linear speeds. Height alone is not camera calibration. `source_mirrored`
88
  records the source information; the adapter does not silently flip/relabel it.
89
+ `camera.distortion` optionally supplies five Brown–Conrady coefficients in
90
+ `[k1,k2,p1,p2,k3]` order, calibrated in the upright displayed image convention.
91
+ Fitting and projections use the same distortion model; the source video is not
92
+ 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
99
+ coaching APIs retain their processing paths. To compare against the previous
100
+ correction, create a revision with `{"refinement":{"enabled":false}}`; the native
101
+ model outputs are reused when their integrity and recording facts still match.
102
+
103
+ Processing is: native reconstruction → independent RTMW image observations and
104
+ forward/backward optical-flow checks → native-rig fitting → acceptance checks →
105
+ one corrected sequence for motion, measurements, projections, and annotation.
106
+ SAM now retains its native shape/motion parameters and exact MHR landmark
107
+ regressor. GVHMR fits SMPL-X parameters in its own isolated interpreter. Their
108
+ anatomical definitions remain separate; model outputs are never averaged.
109
+
110
+ Each continuous identity/model segment uses a shared robust body-shape estimate.
111
+ The optimizer changes native pose and camera translation, using soft image
112
+ constraints, initializer priors and timestamp-aware temporal penalties. RTMW
113
+ landmarks are homologous observations, not asserted identical anatomical joint
114
+ centres or calibrated visibility/depth scores. LK can reduce an inconsistent
115
+ observation's weight; it never creates a missing landmark. Shape/scale priors do
116
+ not establish physical calibration. Native rig constraints and initializer priors
117
+ apply; no unsupported anatomical angle limits are invented.
118
+
119
+ Fitting uses bounded overlapping windows with one owner per original frame.
120
+ Missing observations, identity/model boundaries and clock gaps split fits.
121
+ Window boundaries and raw/refined switches are derivative boundaries. No pose
122
+ is generated through a missing interval. Rapid movement receives weaker temporal
123
+ regularization. Image-supported fast hand peaks are checked for timing and speed
124
+ distortion. Accepted fitted points bypass the old independent-joint filter so
125
+ their rig geometry is preserved. Rejected windows retain native predictions;
126
+ strong image disagreement additionally disables the conflicting joints.
127
+
128
+ `pipeline.refinement` (also in `quality.correction.whole_body_refinement`) records
129
+ accepted/fallback frame counts, per-window reasons, settings, implementation
130
+ hash, image evidence and diagnostics. Each frame reports
131
+ `whole_body_refinement_accepted`; joint reasons distinguish an accepted fit from
132
+ native fallback. Fallback is not presented as verified motion. Native parameters,
133
+ fitting candidates, evidence and raw debug arrays remain private.
134
+
135
+ Robust background image displacement checks a declared static camera. Multiple
136
+ contradictory observations set `declared_static_camera_conflict`; calculation
137
+ inputs then use moving/uncertain camera semantics and dependent measurements are
138
+ withheld. Original submitted inputs and effective `calculation_inputs` are both
139
+ recorded, so measurements remain reproducible. Background displacement is not a
140
+ calibrated camera trajectory or ground frame. No unsupported foot locking or
141
+ field direction is inferred.
142
+
143
+ Each accepted window is fitted again with temporal-weight factors 0.5 and 2.0.
144
+ Summary `stability` gives the resulting minimum/maximum in the metric's own units
145
+ only when both alternative fits and the complete swing are supported. Otherwise
146
+ it supplies `not_evaluated` with a reason. This is sensitivity to regularization,
147
+ **not a confidence interval or independent accuracy validation**. No numerical
148
+ uncertainty is fabricated for unsupported sections. Acceptance defaults are
149
+ configurable engineering gates, not established biomechanical error limits.
150
+
151
+ Defaults are 48 frames/window, eight context frames/side and 25 optimizer steps
152
+ per fit. Three fits are performed for each accepted window. This adds GPU work;
153
+ the actual inference/refinement runtime must be evaluated on the deployed GPU.
154
+ Options and bounds are published in `/input-schema`. Progress includes
155
+ `image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`.
156
+
157
+ Short person-detection losses can be recovered through consistent predicted box
158
+ motion, size and torso appearance. Maximum recovery gap defaults to 0.2 s of
159
+ video time. Ambiguous overlapping people are never recovered on clothing alone.
160
+ Lost frames remain gaps. `tracking` settings are versioned native-inference inputs.
161
+
162
  The 202 response includes `analysis_id`, `job_id`, `analysis_revision`,
163
  `parent_job_id`, `status_url`, `result_url` and `retention_hours`. The first
164
  analysis ID equals its job ID. Poll the supplied status URL until `completed` or
docs/MOTION_REQUIREMENTS_AUDIT.md CHANGED
@@ -8,8 +8,8 @@ Against `Motion_Player_Backend_Requirements.md` v1.0, 15 October 2026.
8
  | Source upload or backend asset | Authenticated multipart upload or `source_asset_id`; no arbitrary URL/path input. Source bytes retained and checksummed. |
9
  | Manifest, lineage and versions | Immutable analysis/job/revision/person IDs; model/source/asset hashes, adapter, correction inputs and definition revision. |
10
  | Original PTS, VFR, retiming | Every source frame retained. Video and capture clocks exported separately. GVHMR explicitly maps a 30-Hz model grid back to original times; rotation interpolation uses SO(3). |
11
- | Athlete selection and identity | Required box when ambiguous; conservative continuity. Lost/ambiguous identity stays unusable, never automatically reassigned. |
12
- | Correct and check motion | Shared adaptive temporal filter, bone-proportion/spike checks, no gap filling, explicit filter and model-window boundaries. GVHMR adds 2D observation/reprojection gates and background camera-rotation checks. These are consistency checks, not accuracy validation. |
13
  | Anatomy and canonical names | Both export all 20 names. Native joint definitions/indices verified. SMPL-X surface-derived landmarks explicitly marked; no claim that its hips/shoulders equal MHR70 landmarks. |
14
  | Coordinates, scale and root | Fixed camera/declared reference axes; hip-relative positions, root separate, added once for projection. Model scale documented; unknown scale disables absolute measurements. Native global predictions are not promoted to calibrated ground motion. |
15
  | Motion and quality artifacts | Finite positions or null, status/confidence/reasons for every joint/frame, explicit gaps/segments, stable skeleton/bones. No invented cross-model confidence. |
@@ -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 | This release supports declared up/field axes and pinhole intrinsics; it does not implement a calibrated ground trajectory or lens-distortion correction. Dependent results remain unavailable, with explicit metadata/reasons. No unsupported calibration claim. |
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. |
 
8
  | Source upload or backend asset | Authenticated multipart upload or `source_asset_id`; no arbitrary URL/path input. Source bytes retained and checksummed. |
9
  | Manifest, lineage and versions | Immutable analysis/job/revision/person IDs; model/source/asset hashes, adapter, correction inputs and definition revision. |
10
  | Original PTS, VFR, retiming | Every source frame retained. Video and capture clocks exported separately. GVHMR explicitly maps a 30-Hz model grid back to original times; rotation interpolation uses SO(3). |
11
+ | Athlete selection and identity | Required box when ambiguous; bounded short-loss recovery requires spatial/motion/size/appearance agreement. Lost frames remain gaps; ambiguous crossings cannot be recovered on clothing alone. |
12
+ | Correct and check motion | Native MHR/SMPL-X rig fitting against separate RTMW image evidence and LK corroboration; shared segment shape, initializer/temporal priors, window acceptance/rollback, image contradiction gates, hand-peak preservation and sensitivity fits. Accepted rig points bypass independent smoothing. No gap filling; explicit fit/model/filter boundaries. Engineering diagnostics do not establish depth accuracy. |
13
  | Anatomy and canonical names | Both export all 20 names. Native joint definitions/indices verified. SMPL-X surface-derived landmarks explicitly marked; no claim that its hips/shoulders equal MHR70 landmarks. |
14
  | Coordinates, scale and root | Fixed camera/declared reference axes; hip-relative positions, root separate, added once for projection. Model scale documented; unknown scale disables absolute measurements. Native global predictions are not promoted to calibrated ground motion. |
15
  | Motion and quality artifacts | Finite positions or null, status/confidence/reasons for every joint/frame, explicit gaps/segments, stable skeleton/bones. No invented cross-model confidence. |
 
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. |
docs/motion-input.schema.json CHANGED
@@ -1,46 +1,5 @@
1
  {
2
  "$defs": {
3
- "CameraInput": {
4
- "additionalProperties": false,
5
- "description": "Intrinsics refer to the upright decoded image, after rotation.",
6
- "properties": {
7
- "fx": {
8
- "exclusiveMinimum": 0,
9
- "title": "Fx",
10
- "type": "number"
11
- },
12
- "fy": {
13
- "exclusiveMinimum": 0,
14
- "title": "Fy",
15
- "type": "number"
16
- },
17
- "cx": {
18
- "minimum": 0,
19
- "title": "Cx",
20
- "type": "number"
21
- },
22
- "cy": {
23
- "minimum": 0,
24
- "title": "Cy",
25
- "type": "number"
26
- },
27
- "source": {
28
- "maxLength": 512,
29
- "minLength": 1,
30
- "title": "Source",
31
- "type": "string"
32
- }
33
- },
34
- "required": [
35
- "fx",
36
- "fy",
37
- "cx",
38
- "cy",
39
- "source"
40
- ],
41
- "title": "CameraInput",
42
- "type": "object"
43
- },
44
  "CorrectionSettings": {
45
  "additionalProperties": false,
46
  "properties": {
@@ -230,6 +189,245 @@
230
  "title": "MeasurementSettings",
231
  "type": "object"
232
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  "SwingWindow": {
234
  "additionalProperties": false,
235
  "properties": {
@@ -482,7 +680,7 @@
482
  "camera": {
483
  "anyOf": [
484
  {
485
- "$ref": "#/$defs/CameraInput"
486
  },
487
  {
488
  "type": "null"
@@ -712,6 +910,12 @@
712
  "minimum": 3,
713
  "title": "Minimum Usable Joints",
714
  "type": "integer"
 
 
 
 
 
 
715
  }
716
  },
717
  "title": "MotionInput",
 
1
  {
2
  "$defs": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  "CorrectionSettings": {
4
  "additionalProperties": false,
5
  "properties": {
 
189
  "title": "MeasurementSettings",
190
  "type": "object"
191
  },
192
+ "MotionCamera": {
193
+ "additionalProperties": false,
194
+ "properties": {
195
+ "fx": {
196
+ "exclusiveMinimum": 0,
197
+ "title": "Fx",
198
+ "type": "number"
199
+ },
200
+ "fy": {
201
+ "exclusiveMinimum": 0,
202
+ "title": "Fy",
203
+ "type": "number"
204
+ },
205
+ "cx": {
206
+ "minimum": 0,
207
+ "title": "Cx",
208
+ "type": "number"
209
+ },
210
+ "cy": {
211
+ "minimum": 0,
212
+ "title": "Cy",
213
+ "type": "number"
214
+ },
215
+ "source": {
216
+ "maxLength": 512,
217
+ "minLength": 1,
218
+ "title": "Source",
219
+ "type": "string"
220
+ },
221
+ "distortion": {
222
+ "anyOf": [
223
+ {
224
+ "maxItems": 5,
225
+ "minItems": 5,
226
+ "prefixItems": [
227
+ {
228
+ "type": "number"
229
+ },
230
+ {
231
+ "type": "number"
232
+ },
233
+ {
234
+ "type": "number"
235
+ },
236
+ {
237
+ "type": "number"
238
+ },
239
+ {
240
+ "type": "number"
241
+ }
242
+ ],
243
+ "type": "array"
244
+ },
245
+ {
246
+ "type": "null"
247
+ }
248
+ ],
249
+ "default": null,
250
+ "title": "Distortion"
251
+ }
252
+ },
253
+ "required": [
254
+ "fx",
255
+ "fy",
256
+ "cx",
257
+ "cy",
258
+ "source"
259
+ ],
260
+ "title": "MotionCamera",
261
+ "type": "object"
262
+ },
263
+ "MotionTrackingSettings": {
264
+ "additionalProperties": false,
265
+ "properties": {
266
+ "recover_short_losses": {
267
+ "default": true,
268
+ "title": "Recover Short Losses",
269
+ "type": "boolean"
270
+ },
271
+ "maximum_recovery_gap_s": {
272
+ "default": 0.2,
273
+ "exclusiveMinimum": 0,
274
+ "maximum": 0.5,
275
+ "title": "Maximum Recovery Gap S",
276
+ "type": "number"
277
+ },
278
+ "minimum_appearance_similarity": {
279
+ "default": 0.85,
280
+ "maximum": 0.99,
281
+ "minimum": 0.7,
282
+ "title": "Minimum Appearance Similarity",
283
+ "type": "number"
284
+ },
285
+ "minimum_candidate_margin": {
286
+ "default": 0.1,
287
+ "maximum": 0.5,
288
+ "minimum": 0.05,
289
+ "title": "Minimum Candidate Margin",
290
+ "type": "number"
291
+ }
292
+ },
293
+ "title": "MotionTrackingSettings",
294
+ "type": "object"
295
+ },
296
+ "RefinementSettings": {
297
+ "additionalProperties": false,
298
+ "properties": {
299
+ "enabled": {
300
+ "default": true,
301
+ "title": "Enabled",
302
+ "type": "boolean"
303
+ },
304
+ "window_frames": {
305
+ "default": 48,
306
+ "maximum": 120,
307
+ "minimum": 12,
308
+ "title": "Window Frames",
309
+ "type": "integer"
310
+ },
311
+ "context_frames": {
312
+ "default": 8,
313
+ "maximum": 24,
314
+ "minimum": 2,
315
+ "title": "Context Frames",
316
+ "type": "integer"
317
+ },
318
+ "iterations": {
319
+ "default": 25,
320
+ "maximum": 100,
321
+ "minimum": 5,
322
+ "title": "Iterations",
323
+ "type": "integer"
324
+ },
325
+ "learning_rate": {
326
+ "default": 0.005,
327
+ "exclusiveMinimum": 0,
328
+ "maximum": 0.05,
329
+ "title": "Learning Rate",
330
+ "type": "number"
331
+ },
332
+ "minimum_observation_score": {
333
+ "default": 0.45,
334
+ "maximum": 0.95,
335
+ "minimum": 0.1,
336
+ "title": "Minimum Observation Score",
337
+ "type": "number"
338
+ },
339
+ "minimum_observed_joints": {
340
+ "default": 6,
341
+ "maximum": 20,
342
+ "minimum": 4,
343
+ "title": "Minimum Observed Joints",
344
+ "type": "integer"
345
+ },
346
+ "observation_scale_box_fraction": {
347
+ "default": 0.025,
348
+ "exclusiveMinimum": 0,
349
+ "maximum": 0.15,
350
+ "title": "Observation Scale Box Fraction",
351
+ "type": "number"
352
+ },
353
+ "maximum_observation_error_box_fraction": {
354
+ "default": 0.08,
355
+ "exclusiveMinimum": 0,
356
+ "maximum": 0.3,
357
+ "title": "Maximum Observation Error Box Fraction",
358
+ "type": "number"
359
+ },
360
+ "maximum_body_change_fraction": {
361
+ "default": 0.12,
362
+ "exclusiveMinimum": 0,
363
+ "maximum": 0.3,
364
+ "title": "Maximum Body Change Fraction",
365
+ "type": "number"
366
+ },
367
+ "maximum_bone_change_fraction": {
368
+ "default": 0.06,
369
+ "exclusiveMinimum": 0,
370
+ "maximum": 0.2,
371
+ "title": "Maximum Bone Change Fraction",
372
+ "type": "number"
373
+ },
374
+ "temporal_weight": {
375
+ "default": 0.02,
376
+ "maximum": 1,
377
+ "minimum": 0,
378
+ "title": "Temporal Weight",
379
+ "type": "number"
380
+ },
381
+ "initializer_weight": {
382
+ "default": 0.1,
383
+ "exclusiveMinimum": 0,
384
+ "maximum": 10,
385
+ "title": "Initializer Weight",
386
+ "type": "number"
387
+ },
388
+ "maximum_peak_time_shift_s": {
389
+ "default": 0.025,
390
+ "exclusiveMinimum": 0,
391
+ "maximum": 0.1,
392
+ "title": "Maximum Peak Time Shift S",
393
+ "type": "number"
394
+ },
395
+ "maximum_peak_speed_change_fraction": {
396
+ "default": 0.2,
397
+ "exclusiveMinimum": 0,
398
+ "maximum": 0.5,
399
+ "title": "Maximum Peak Speed Change Fraction",
400
+ "type": "number"
401
+ },
402
+ "maximum_static_background_motion_fraction": {
403
+ "default": 0.003,
404
+ "exclusiveMinimum": 0,
405
+ "maximum": 0.05,
406
+ "title": "Maximum Static Background Motion Fraction",
407
+ "type": "number"
408
+ },
409
+ "sensitivity_factors": {
410
+ "default": [
411
+ 0.5,
412
+ 2.0
413
+ ],
414
+ "maxItems": 2,
415
+ "minItems": 2,
416
+ "prefixItems": [
417
+ {
418
+ "type": "number"
419
+ },
420
+ {
421
+ "type": "number"
422
+ }
423
+ ],
424
+ "title": "Sensitivity Factors",
425
+ "type": "array"
426
+ }
427
+ },
428
+ "title": "RefinementSettings",
429
+ "type": "object"
430
+ },
431
  "SwingWindow": {
432
  "additionalProperties": false,
433
  "properties": {
 
680
  "camera": {
681
  "anyOf": [
682
  {
683
+ "$ref": "#/$defs/MotionCamera"
684
  },
685
  {
686
  "type": "null"
 
910
  "minimum": 3,
911
  "title": "Minimum Usable Joints",
912
  "type": "integer"
913
+ },
914
+ "refinement": {
915
+ "$ref": "#/$defs/RefinementSettings"
916
+ },
917
+ "tracking": {
918
+ "$ref": "#/$defs/MotionTrackingSettings"
919
  }
920
  },
921
  "title": "MotionInput",
docs/motion-projection-frame.schema.json CHANGED
@@ -58,6 +58,37 @@
58
  ],
59
  "title": "Camera Intrinsics"
60
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  "joints": {
62
  "additionalProperties": {
63
  "additionalProperties": true,
 
58
  ],
59
  "title": "Camera Intrinsics"
60
  },
61
+ "camera_distortion": {
62
+ "anyOf": [
63
+ {
64
+ "maxItems": 5,
65
+ "minItems": 5,
66
+ "prefixItems": [
67
+ {
68
+ "type": "number"
69
+ },
70
+ {
71
+ "type": "number"
72
+ },
73
+ {
74
+ "type": "number"
75
+ },
76
+ {
77
+ "type": "number"
78
+ },
79
+ {
80
+ "type": "number"
81
+ }
82
+ ],
83
+ "type": "array"
84
+ },
85
+ {
86
+ "type": "null"
87
+ }
88
+ ],
89
+ "default": null,
90
+ "title": "Camera Distortion"
91
+ },
92
  "joints": {
93
  "additionalProperties": {
94
  "additionalProperties": true,
tests/test_motion_refinement.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Known articulated motion, rejection/rollback, clocks, projection and API agreement."""
2
+ import json
3
+ import numpy as np
4
+ import pytest
5
+ from baseball_batting.motion_contract import MotionInput,RefinementSettings,MotionTrackingSettings
6
+ from baseball_batting.motion_refinement import (fit_window,acceptance,continuous_windows,project_torch,
7
+ NAMES,LOCAL,INDICES,refine_sequence)
8
+ from baseball_batting.geometry import project
9
+ from baseball_batting.motion_tracking import AthleteRecovery
10
+ from baseball_batting.sam_motion import correct_motion
11
+ from test_motion_player import raw_for,inputs
12
+ from baseball_batting.ingest import ingest
13
+
14
+
15
+ def articulated_fixture(n=25):
16
+ torch=pytest.importorskip('torch')
17
+ # A constrained articulated rig with one shared shape. Positions are derived
18
+ # from its rotations, never independently optimized joint coordinates.
19
+ rest=np.zeros((20,3))
20
+ for side,sign in [('left',-1),('right',1)]:
21
+ for part,y in [('ear',-.75),('shoulder',-.5),('hip',0),('knee',.4),('ankle',.8),('heel',.83),('big_toe',.83),('small_toe',.83)]:
22
+ rest[LOCAL[side+'_'+part]]=[sign*(.12 if part=='ear' else .2),y,0]
23
+ rest[LOCAL[side+'_heel'],2]=-.08
24
+ rest[LOCAL[side+'_big_toe'],2]=.15;rest[LOCAL[side+'_small_toe'],2]=.12
25
+ base=torch.tensor(rest,dtype=torch.float32)
26
+ def forward(pose,camera):
27
+ p=base[None].expand(len(pose),-1,-1).clone()
28
+ for side,sign in [('left',-1),('right',1)]:
29
+ shoulder=LOCAL[side+'_shoulder'];elbow=LOCAL[side+'_elbow'];wrist=LOCAL[side+'_wrist']
30
+ a=pose[:,1]+sign*.1
31
+ direction=torch.stack([sign*.30*torch.cos(a),.30*torch.sin(a),torch.zeros_like(a)],-1)
32
+ p[:,elbow]=p[:,shoulder]+direction
33
+ p[:,wrist]=p[:,elbow]+direction
34
+ yaw=pose[:,0];co,si=torch.cos(yaw),torch.sin(yaw)
35
+ x=co[:,None]*p[...,0]+si[:,None]*p[...,2]
36
+ z=-si[:,None]*p[...,0]+co[:,None]*p[...,2]
37
+ return torch.stack([x,p[...,1],z],-1)+camera[:,None]
38
+ times=np.cumsum(np.linspace(.014,.020,n));times-=times[0]
39
+ truth_pose=np.column_stack([.2+times*.3,.5+1.2/(1+np.exp(-25*(times-.2)))])
40
+ camera=np.tile([0,0,4.],(n,1))
41
+ rng=np.random.default_rng(83)
42
+ initial=truth_pose+rng.normal(0,.035,truth_pose.shape)
43
+ with torch.no_grad():
44
+ truth=forward(torch.tensor(truth_pose,dtype=torch.float32),torch.tensor(camera,dtype=torch.float32)).numpy()
45
+ raw=forward(torch.tensor(initial,dtype=torch.float32),torch.tensor(camera,dtype=torch.float32)).numpy()
46
+ k=np.tile([[650,0,320],[0,650,240],[0,0,1.]],(n,1,1))
47
+ pixels=np.stack([project(p,K) for p,K in zip(truth,k)])
48
+ return forward,initial,camera,raw,truth,pixels,times,k
49
+
50
+
51
+ def test_constrained_fit_improves_known_motion_without_stretching_limbs():
52
+ forward,pose,camera,raw,truth,pixels,times,k=articulated_fixture()
53
+ settings=RefinementSettings(iterations=45,learning_rate=.01).model_dump()
54
+ result=fit_window(forward,pose,camera,raw,pixels,np.ones(pixels.shape[:2]),times,k,np.full(len(times),300),settings,device='cpu')
55
+ before=np.mean(np.linalg.norm(raw-truth,axis=-1));after=np.mean(np.linalg.norm(result['points_camera']-truth,axis=-1))
56
+ assert after<before*.6
57
+ original_xy=np.stack([project(p,K) for p,K in zip(raw,k)])
58
+ ok,checks=acceptance(raw,result['points_camera'],original_xy,result['projection'],pixels,
59
+ np.ones(pixels.shape[:2]),times,np.full(len(times),300),settings)
60
+ assert ok,checks
61
+ for side in ('left','right'):
62
+ a,b=[LOCAL[side+'_'+p] for p in ('shoulder','elbow')]
63
+ np.testing.assert_allclose(np.linalg.norm(result['points_camera'][:,a]-result['points_camera'][:,b],axis=-1),.3,atol=2e-6)
64
+
65
+
66
+ def test_acceptance_rejects_worse_image_alignment_and_deformation():
67
+ _,_,_,_,truth,pixels,times,k=articulated_fixture(12)
68
+ candidate=truth.copy();candidate[:,LOCAL['left_wrist'],0]+=.4
69
+ candidate_xy=np.stack([project(p,K) for p,K in zip(candidate,k)])
70
+ ok,checks=acceptance(truth,candidate,pixels,candidate_xy,pixels,np.ones(pixels.shape[:2]),times,np.full(len(times),300),RefinementSettings().model_dump())
71
+ assert not ok and 'body_proportions_changed' in checks['reasons']
72
+ assert 'image_alignment_worsened' in checks['reasons']
73
+
74
+
75
+ def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_frames():
76
+ t=np.arange(100)/60;t[60:]+=.3;valid=np.ones(100,bool);valid[30:33]=False
77
+ sequence=np.zeros(100,int);sequence[80:]=1
78
+ windows=list(continuous_windows(valid,t,sequence,24,5,.1));owners=np.zeros(100,int)
79
+ for context,core in windows:
80
+ owners[core]+=1
81
+ assert np.diff(context).max()==1 and np.diff(t[context]).max()<.1
82
+ assert len(np.unique(sequence[context]))==1
83
+ assert (owners[valid]==1).all() and (owners[~valid]==0).all()
84
+
85
+
86
+ def test_torch_and_public_distortion_projection_agree_and_have_gradients():
87
+ torch=pytest.importorskip('torch')
88
+ points=torch.tensor([[[.4,.3,2.],[-.3,.2,3.]]],requires_grad=True)
89
+ k=torch.tensor([[[700.,0,320],[0,690,240],[0,0,1]]]);d=[-.2,.03,.001,-.002,.01]
90
+ actual=project_torch(points,k,torch.tensor(d));expected=project(points.detach().numpy()[0],k.numpy()[0],d)
91
+ np.testing.assert_allclose(actual.detach().numpy()[0],expected,atol=5e-5)
92
+ actual.sum().backward();assert torch.isfinite(points.grad).all()
93
+
94
+
95
+ def test_accepted_rig_points_are_not_independently_smoothed(video):
96
+ opts=inputs();capture=ingest(video,opts.metadata());raw=raw_for(capture)
97
+ raw['refinement_accepted']=np.ones(capture['frame_count'],bool)
98
+ t=np.array([f['playback_s'] for f in capture['frames']])
99
+ corrected=correct_motion(raw,t,opts.correction)
100
+ expected=raw['points_body']-(raw['points_body'][:,9]+raw['points_body'][:,10])[:,None]/2
101
+ valid=corrected['valid']
102
+ np.testing.assert_allclose(corrected['points_relative'][valid],expected[valid],atol=1e-12)
103
+
104
+
105
+ def test_short_loss_recovery_needs_spatial_and_appearance_agreement():
106
+ tracker=AthleteRecovery(MotionTrackingSettings());image=np.zeros((200,300,3),np.uint8)
107
+ image[20:180,30:120]=[0,0,255]
108
+ def box(x=30):return {'class_id':0,'score':.9,'box':[x,20,x+90,180]}
109
+ assert tracker.update(image,[box()],0)[0] is not None
110
+ assert tracker.update(image,[],.05)[0] is None
111
+ assert tracker.update(image,[box()],.1)[0] is not None
112
+ tracker.update(image,[],.15)
113
+ assert tracker.update(image,[box(190)],.2)[0] is None
114
+ assert tracker.update(image,[box()],.5)[0] is None
115
+
116
+
117
+ def test_ambiguous_crossing_does_not_reidentify_by_clothing_alone():
118
+ tracker=AthleteRecovery(MotionTrackingSettings());image=np.full((200,300,3),100,np.uint8)
119
+ box=lambda x:{'class_id':0,'score':.9,'box':[x,20,x+90,180]}
120
+ tracker.update(image,[box(30)],0)
121
+ assert tracker.update(image,[box(30),box(40)],.02)[1]=='identity_ambiguous_multiple_overlapping_athletes'
122
+ assert tracker.update(image,[box(30)],.04)[0] is None
123
+
124
+
125
+ def test_camera_input_preserves_legacy_sam_contract_and_rejects_bad_distortion():
126
+ camera={'fx':700,'fy':690,'cx':320,'cy':240,'source':'calibration fixture','distortion':[-.2,.03,.001,-.002,.01]}
127
+ options=MotionInput(camera=camera)
128
+ assert options.sam_options().camera.fx==700
129
+ assert options.camera.distortion[0]==-.2
130
+ with pytest.raises(ValueError):MotionInput(camera={**camera,'distortion':[1,2]})
131
+
132
+
133
+ def test_export_uses_distortion_for_same_motion_video_and_reports_refinement(tmp_path,video):
134
+ from baseball_batting.motion_export import export_motion,reproduce_measurements
135
+ opts=inputs(annotated_videos=False,camera={'fx':60,'fy':60,'cx':160,'cy':120,'source':'fixture',
136
+ 'distortion':[-.05,.01,0,0,0]},timing={'kind':'unretimed','source':'fixture'})
137
+ capture=ingest(video,opts.metadata());raw=raw_for(capture)
138
+ raw['refinement_accepted']=np.ones(len(capture['frames']),bool)
139
+ manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
140
+ {'analysis_id':'fixture','analysis_revision':1},refinement={'enabled':True,'accepted_frame_count':len(capture['frames'])})
141
+ motion=[json.loads(q) for q in (tmp_path/'motion.jsonl').read_text().splitlines()]
142
+ projections=[json.loads(q) for q in (tmp_path/'projections.jsonl').read_text().splitlines()]
143
+ r=np.asarray(manifest.coordinates['camera_to_export_rotation'])
144
+ for frame,p in zip(motion,projections):
145
+ for name,joint in frame['joints'].items():
146
+ if joint['position'] is not None:
147
+ xyz=(np.array(joint['position'])+frame['root_translation'])@r
148
+ np.testing.assert_allclose(project(xyz,p['camera_intrinsics'],p['camera_distortion']),p['joints'][name]['pixel'],atol=1e-9)
149
+ assert manifest.pipeline['refinement']['accepted_frame_count']==len(motion)
150
+ groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
151
+ values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
152
+ for summary in json.loads((tmp_path/'measurements.json').read_text())['summaries']:
153
+ assert summary['value']==values[summary['rep'],summary['metric_id']]
154
+ assert summary['stability']['status']=='not_evaluated'
155
+
156
+
157
+ def test_numerically_bad_fit_rolls_back_without_filling_gap(monkeypatch):
158
+ import baseball_batting.motion_refinement as module
159
+ _,pose,camera,points,truth,pixels,times,k=articulated_fixture(12)
160
+ n=len(times);body=np.full((n,70,3),np.nan);body[:,list(INDICES)]=points-camera[:,None]
161
+ raw={'points_body':body,'camera_translation':camera,'intrinsics':k,'projection_valid':np.ones(n,bool),
162
+ 'projection':np.full((n,70,2),np.nan),'image_size':np.array([640,480])}
163
+ evidence={'pixels':pixels,'weights':np.ones((n,20)),'box_heights':np.full(n,300),'frame_usable':np.ones(n,bool)}
164
+ evidence['frame_usable'][6]=False
165
+ def bad(*args,**kwargs):raise FloatingPointError('controlled optimizer failure')
166
+ monkeypatch.setattr(module,'fit_window',bad)
167
+ result,metadata=refine_sequence(lambda ids:None,{'pose':pose,'camera':camera},raw,evidence,times,
168
+ RefinementSettings().model_dump(),.1,device='cpu')
169
+ np.testing.assert_equal(result['points_body'],raw['points_body'])
170
+ assert not result['refinement_accepted'].any() and metadata['accepted_frame_count']==0
171
+ assert len(metadata['windows'])==2
172
+
173
+
174
+ def test_supported_fast_peak_cannot_be_delayed_by_fitting():
175
+ _,_,_,_,truth,pixels,times,k=articulated_fixture(25)
176
+ candidate=np.concatenate([truth[:1].repeat(3,axis=0),truth[:-3]])
177
+ candidate_xy=np.stack([project(p,K) for p,K in zip(candidate,k)])
178
+ ok,checks=acceptance(truth,candidate,pixels,candidate_xy,pixels,np.ones(pixels.shape[:2]),times,
179
+ np.full(len(times),300),RefinementSettings().model_dump())
180
+ assert not ok
181
+ assert 'fast_hand_peak_shifted' in checks['reasons']
182
+
183
+
184
+ def test_stability_reports_measurement_units_and_camera_conflict_is_reproducible(tmp_path,video):
185
+ from baseball_batting.motion_export import export_motion,reproduce_measurements
186
+ opts=inputs(annotated_videos=False,timing={'kind':'unretimed','source':'fixture'})
187
+ capture=ingest(video,opts.metadata());raw=raw_for(capture);n=capture['frame_count']
188
+ raw['refinement_accepted']=np.ones(n,bool)
189
+ raw['refinement_scenario_points_body']=np.repeat(raw['points_body'][None],2,axis=0)
190
+ raw['refinement_scenario_valid']=np.ones((2,n),bool)
191
+ metadata={'enabled':True,'accepted_frame_count':n,'image_evidence':{'declared_static_camera_conflict':True}}
192
+ manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
193
+ {'analysis_id':'fixture','analysis_revision':1},refinement=metadata)
194
+ assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified'
195
+ assert manifest.pipeline['calculation_inputs']['camera_stability']=='moving'
196
+ report=json.loads((tmp_path/'measurements.json').read_text())['summaries']
197
+ groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
198
+ values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
199
+ for summary in report:
200
+ assert summary['value']==values[summary['rep'],summary['metric_id']]
201
+ if summary['value'] is not None:
202
+ assert summary['stability']['status']=='evaluated'
203
+ assert summary['stability']['minimum']==summary['stability']['maximum']==summary['value']
tools/setup_gvhmr_api_worker.py CHANGED
@@ -77,7 +77,7 @@ def main():
77
  run('git','-C',source,'checkout','--detach',GVHMR_REVISION)
78
  check_env={**env,'PYTHONPATH':str(source)+os.pathsep+str(ROOT)}
79
  run(worker,ROOT/'tools/check_gvhmr_runtime.py',env=check_env)
80
- run(worker,'-c','from baseball_batting.gvhmr_pose_worker import run',env=check_env)
81
  state('gvhmr_assets_installing')
82
  provider_env=dict(os.environ,BASEBALL_GVHMR_SOURCE=str(source),PYTHONPATH=str(ROOT))
83
  provider_env.pop('BASEBALL_API_KEY',None);provider_env.pop('GOOGLE_API_KEY',None)
 
77
  run('git','-C',source,'checkout','--detach',GVHMR_REVISION)
78
  check_env={**env,'PYTHONPATH':str(source)+os.pathsep+str(ROOT)}
79
  run(worker,ROOT/'tools/check_gvhmr_runtime.py',env=check_env)
80
+ run(worker,'-c','from baseball_batting.gvhmr_pose_worker import run; from baseball_batting.motion_refine_worker import load_adapter; from baseball_batting.motion_refinement import fit_window',env=check_env)
81
  state('gvhmr_assets_installing')
82
  provider_env=dict(os.environ,BASEBALL_GVHMR_SOURCE=str(source),PYTHONPATH=str(ROOT))
83
  provider_env.pop('BASEBALL_API_KEY',None);provider_env.pop('GOOGLE_API_KEY',None)