github-actions[bot] commited on
Commit
4bf9ad1
·
1 Parent(s): b3f7d8d

Automated Deploy: 759e1f2c3b1e3cd4217894adb0dd9808d7b67b8a

Browse files
Dockerfile CHANGED
@@ -1,3 +1,4 @@
 
1
  FROM python:3.11-slim-bookworm AS tracking-export
2
  ENV PYTHONUNBUFFERED=1 MPLBACKEND=Agg YOLO_CONFIG_DIR=/tmp
3
  WORKDIR /export
@@ -25,7 +26,9 @@ RUN python -m venv /opt/sam-runtime \
25
  && git -C /opt/sam-source fetch --depth=1 origin b5c765a0d89d789985e186d396315e7590887b94 \
26
  && git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
27
 
28
- FROM python:3.11-slim-bookworm AS gvhmr-runtime
 
 
29
  ENV UV_PYTHON_INSTALL_DIR=/opt/gvhmr-python UV_LINK_MODE=copy
30
  RUN apt-get update && apt-get install -y --no-install-recommends git libgl1 libglib2.0-0 \
31
  && rm -rf /var/lib/apt/lists/*
@@ -40,6 +43,9 @@ RUN python -m pip install --no-cache-dir uv==0.9.10 \
40
  && git -C /opt/gvhmr-source fetch --depth=1 origin ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
41
  && git -C /opt/gvhmr-source checkout --detach ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
42
  && PYTHONPATH=/opt/gvhmr-source /opt/gvhmr-runtime/bin/python /tmp/check_gvhmr_runtime.py
 
 
 
43
 
44
  FROM python:3.11-slim-bookworm
45
 
 
1
+ ARG GVHMR_RUNTIME_BASE=sam-runtime
2
  FROM python:3.11-slim-bookworm AS tracking-export
3
  ENV PYTHONUNBUFFERED=1 MPLBACKEND=Agg YOLO_CONFIG_DIR=/tmp
4
  WORKDIR /export
 
26
  && git -C /opt/sam-source fetch --depth=1 origin b5c765a0d89d789985e186d396315e7590887b94 \
27
  && git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
28
 
29
+ # Inherit the completed build stage to serialize the two large CUDA installs.
30
+ # The final image still copies separate interpreters, never shared site-packages.
31
+ FROM ${GVHMR_RUNTIME_BASE} AS gvhmr-runtime
32
  ENV UV_PYTHON_INSTALL_DIR=/opt/gvhmr-python UV_LINK_MODE=copy
33
  RUN apt-get update && apt-get install -y --no-install-recommends git libgl1 libglib2.0-0 \
34
  && rm -rf /var/lib/apt/lists/*
 
43
  && git -C /opt/gvhmr-source fetch --depth=1 origin ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
44
  && git -C /opt/gvhmr-source checkout --detach ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
45
  && PYTHONPATH=/opt/gvhmr-source /opt/gvhmr-runtime/bin/python /tmp/check_gvhmr_runtime.py
46
+ COPY baseball_batting /opt/gvhmr-api-check/baseball_batting
47
+ RUN PYTHONPATH=/opt/gvhmr-api-check:/opt/gvhmr-source /opt/gvhmr-runtime/bin/python -c \
48
+ "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)"
49
 
50
  FROM python:3.11-slim-bookworm
51
 
baseball_batting/gvhmr_pose_worker.py CHANGED
@@ -126,6 +126,7 @@ def run(request):
126
  params={key:np.full((n,size),np.nan,np.float32) for key,size in
127
  [('body_pose',63),('global_orient',3),('transl',3),('betas',10)]}
128
  sequence_ids=np.full(n,-1,int);resampled=np.zeros(n,bool);windows=[]
 
129
  serial=0
130
  for run,grid,left,right,core_start,core_end in sequence_windows(valid,times,request['max_gap_s'],
131
  settings['max_sequence_frames'],settings['context_frames']):
@@ -140,12 +141,19 @@ def run(request):
140
  'f_imgseq':torch.tensor(resample_vectors(features[run],t,grid_part),dtype=torch.float32),
141
  'K_fullimg':torch.tensor(resample_vectors(ks[run],t,grid_part),dtype=torch.float32),
142
  'cam_angvel':compute_cam_angvel(torch.tensor(rg,dtype=torch.float32))}
143
- prediction=model.predict(data,static_cam=request['static_camera'])['smpl_params_incam']
 
144
  # Every source frame is owned by exactly one core, with context
145
  # on both sides. Chunk boundaries are exported and filter-marked.
146
  take=run[(t>=grid[core_start]) & ((t<grid[core_end]) if core_end<len(grid) else (t<=grid[-1]))]
147
  if not len(take):continue
148
  serial+=1;sequence_ids[take]=serial
 
 
 
 
 
 
149
  for key in params:
150
  values=prediction[key].detach().cpu().numpy()
151
  operation=resample_rotations if key in ('body_pose','global_orient') else resample_vectors
@@ -155,6 +163,7 @@ def run(request):
155
  'sequence_id':serial,'model_sample_count':len(grid_part),'model_rate_hz':MODEL_FPS,
156
  'model_time_start_s':float(grid_part[0]),'model_time_end_s':float(grid_part[-1])})
157
  progress('gvhmr_temporal_inference',int((sequence_ids>=0).sum()))
 
158
  del model;gc.collect();torch.cuda.empty_cache()
159
  predicted=np.flatnonzero(sequence_ids>=0)
160
  if not len(predicted):raise ValueError('no_usable_motion')
 
126
  params={key:np.full((n,size),np.nan,np.float32) for key,size in
127
  [('body_pose',63),('global_orient',3),('transl',3),('betas',10)]}
128
  sequence_ids=np.full(n,-1,int);resampled=np.zeros(n,bool);windows=[]
129
+ native_folder=destination.with_name('gvhmr-native-predictions-private');native_folder.mkdir(exist_ok=True)
130
  serial=0
131
  for run,grid,left,right,core_start,core_end in sequence_windows(valid,times,request['max_gap_s'],
132
  settings['max_sequence_frames'],settings['context_frames']):
 
141
  'f_imgseq':torch.tensor(resample_vectors(features[run],t,grid_part),dtype=torch.float32),
142
  'K_fullimg':torch.tensor(resample_vectors(ks[run],t,grid_part),dtype=torch.float32),
143
  'cam_angvel':compute_cam_angvel(torch.tensor(rg,dtype=torch.float32))}
144
+ native_prediction_result=model.predict(data,static_cam=request['static_camera'])
145
+ prediction=native_prediction_result['smpl_params_incam']
146
  # Every source frame is owned by exactly one core, with context
147
  # on both sides. Chunk boundaries are exported and filter-marked.
148
  take=run[(t>=grid[core_start]) & ((t<grid[core_end]) if core_end<len(grid) else (t<=grid[-1]))]
149
  if not len(take):continue
150
  serial+=1;sequence_ids[take]=serial
151
+ # Keep original checkpoint predictions before source-time
152
+ # interpolation, stable-shape aggregation or temporal correction.
153
+ np.savez_compressed(native_folder/(str(serial)+'.npz'),model_times=grid_part,
154
+ **{space+'_'+key:value.detach().cpu().numpy() for space,field in
155
+ [('camera','smpl_params_incam'),('global','smpl_params_global')]
156
+ for key,value in native_prediction_result[field].items()})
157
  for key in params:
158
  values=prediction[key].detach().cpu().numpy()
159
  operation=resample_rotations if key in ('body_pose','global_orient') else resample_vectors
 
163
  'sequence_id':serial,'model_sample_count':len(grid_part),'model_rate_hz':MODEL_FPS,
164
  'model_time_start_s':float(grid_part[0]),'model_time_end_s':float(grid_part[-1])})
165
  progress('gvhmr_temporal_inference',int((sequence_ids>=0).sum()))
166
+ del native_prediction_result,prediction,data
167
  del model;gc.collect();torch.cuda.empty_cache()
168
  predicted=np.flatnonzero(sequence_ids>=0)
169
  if not len(predicted):raise ValueError('no_usable_motion')
baseball_batting/motion_contract.py CHANGED
@@ -12,10 +12,16 @@ DEFINITION_VERSION = 'batting-corrected-points-v1'
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)
15
- context_frames: int = Field(default=30, ge=10, le=60, strict=True)
16
  minimum_keypoint_score: float = Field(default=.3, ge=0, le=1)
17
  maximum_reprojection_box_fraction: float = Field(default=.15, gt=0, le=1)
18
 
 
 
 
 
 
 
19
 
20
  class MotionInput(SamBattingInput):
21
  model: Literal['sam3d', 'gvhmr'] = 'sam3d'
 
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)
15
+ context_frames: int = Field(default=60, ge=10, le=60, strict=True)
16
  minimum_keypoint_score: float = Field(default=.3, ge=0, le=1)
17
  maximum_reprojection_box_fraction: float = Field(default=.15, gt=0, le=1)
18
 
19
+ @model_validator(mode='after')
20
+ def context_fits_sequence(self):
21
+ if self.max_sequence_frames<=2*self.context_frames:
22
+ raise ValueError('GVHMR sequence must contain a nonempty core in addition to both context margins')
23
+ return self
24
+
25
 
26
  class MotionInput(SamBattingInput):
27
  model: Literal['sam3d', 'gvhmr'] = 'sam3d'
baseball_batting/motion_export.py CHANGED
@@ -56,6 +56,8 @@ def _calculate(corrected, times, options, known):
56
  for metric in swing.measurements:
57
  metric.quality_flags=[f.replace('sam_joint_confidence_unknown','gvhmr_joint_confidence_unknown') for f in metric.quality_flags]
58
  metric.quality_flags.append('smplx_anatomical_definition; cross_model_values_not_interchangeable')
 
 
59
  if options.scale_status == 'unknown':
60
  for swings in groups.values():
61
  for swing in swings:
@@ -195,6 +197,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
195
  measurement_matrix,_=orientation(corrected['points_relative'],options,base)
196
  metadata={'analysis_revision':revision,'rep':rep,'definition_version':definition_version,
197
  'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
 
198
  'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
199
  for key,metric in rows.items():
200
  details=metric.model_dump(mode='json');details.pop('coaching',None)
@@ -287,6 +290,8 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
287
  pipeline={'model':model,'selected_model':options.model,'adapter_version':adapter['adapter_version'],'adapter_sha256':adapter_hash(options.model),
288
  'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
289
  'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
 
 
290
  'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
291
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
292
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
 
56
  for metric in swing.measurements:
57
  metric.quality_flags=[f.replace('sam_joint_confidence_unknown','gvhmr_joint_confidence_unknown') for f in metric.quality_flags]
58
  metric.quality_flags.append('smplx_anatomical_definition; cross_model_values_not_interchangeable')
59
+ if known and metric.unit in ('ms','m/s','deg/s'):
60
+ metric.sample_spacing_ms=round(max(metric.sample_spacing_ms or 0,1000/30),3)
61
  if options.scale_status == 'unknown':
62
  for swings in groups.values():
63
  for swing in swings:
 
197
  measurement_matrix,_=orientation(corrected['points_relative'],options,base)
198
  metadata={'analysis_revision':revision,'rep':rep,'definition_version':definition_version,
199
  'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
200
+ 'temporal_model_sample_spacing_ms':1000/30 if options.model=='gvhmr' and known else None,
201
  'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
202
  for key,metric in rows.items():
203
  details=metric.model_dump(mode='json');details.pop('coaching',None)
 
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),
296
  'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
297
  coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
baseball_batting/sam_measurements.py CHANGED
@@ -146,7 +146,7 @@ def peak(values,times,start,end,competition_ratio=.9,separation_s=.08):
146
  return start+k,None
147
 
148
 
149
- def automatic_windows(points,times,max_gap=.1,settings=None,margin=3,*,single_swing=False):
150
  """Conservative motion-window candidates, never labelled reviewed swing events."""
151
  n = len(points)
152
  if n<4: return []
@@ -154,7 +154,8 @@ def automatic_windows(points,times,max_gap=.1,settings=None,margin=3,*,single_sw
154
  from .sam_batting_contract import MeasurementSettings
155
  settings=MeasurementSettings()
156
  hands = (points[:,62]+points[:,41])/2-(points[:,9]+points[:,10])/2
157
- speed = np.linalg.norm(derivative(hands,times,max_gap=max_gap),axis=-1)
 
158
  finite = speed[np.isfinite(speed)]
159
  ids = []
160
  if len(finite)>4:
@@ -189,7 +190,7 @@ def calculate_measurements(corrected, times, options, *, clock_known=True):
189
  if not np.isfinite(times).all() or np.any(np.diff(times)<=0):
190
  raise ValueError('Measurement timestamps must increase strictly')
191
  windows = options.windows or automatic_windows(points,times,options.correction.max_gap_s,options.measurement,
192
- options.correction.boundary_samples+1,single_swing=options.single_swing)
193
  groups = {key:[] for key in GROUP_KEYS}; private=[]
194
  for rep,window in enumerate(windows,1):
195
  a,b=window.start_frame,window.end_frame
 
146
  return start+k,None
147
 
148
 
149
+ def automatic_windows(points,times,max_gap=.1,settings=None,margin=3,*,single_swing=False,boundary=None):
150
  """Conservative motion-window candidates, never labelled reviewed swing events."""
151
  n = len(points)
152
  if n<4: return []
 
154
  from .sam_batting_contract import MeasurementSettings
155
  settings=MeasurementSettings()
156
  hands = (points[:,62]+points[:,41])/2-(points[:,9]+points[:,10])/2
157
+ hand_boundary=boundary[:,[9,10,62,41]].any(axis=1) if boundary is not None else None
158
+ speed = np.linalg.norm(derivative(hands,times,max_gap=max_gap,boundary=hand_boundary),axis=-1)
159
  finite = speed[np.isfinite(speed)]
160
  ids = []
161
  if len(finite)>4:
 
190
  if not np.isfinite(times).all() or np.any(np.diff(times)<=0):
191
  raise ValueError('Measurement timestamps must increase strictly')
192
  windows = options.windows or automatic_windows(points,times,options.correction.max_gap_s,options.measurement,
193
+ options.correction.boundary_samples+1,single_swing=options.single_swing,boundary=corrected['boundary'])
194
  groups = {key:[] for key in GROUP_KEYS}; private=[]
195
  for rep,window in enumerate(windows,1):
196
  a,b=window.start_frame,window.end_frame
docs/MOTION_PLAYER_API.md CHANGED
@@ -144,6 +144,8 @@ affected joints carry `interpolated` status and explicit provenance, and depende
144
  metrics record interpolated input. This does not fill missing athlete tracks or
145
  source clock gaps. Long sequences use bounded windows with context; window
146
  boundaries start new segments and are excluded from derivative evidence.
 
 
147
  The `gvhmr` options expose batch size, window/context sizes and input-2D quality
148
  thresholds. These scores gate model inputs; they are not calibrated 3D confidence.
149
  Background camera-rotation failures remain unusable frames. Camera rotation and
 
144
  metrics record interpolated input. This does not fill missing athlete tracks or
145
  source clock gaps. Long sequences use bounded windows with context; window
146
  boundaries start new segments and are excluded from derivative evidence.
147
+ The effective GVHMR timing sample spacing is at least 33.333 ms even when the
148
+ source has more frames; resampling does not invent high-speed timing evidence.
149
  The `gvhmr` options expose batch size, window/context sizes and input-2D quality
150
  thresholds. These scores gate model inputs; they are not calibrated 3D confidence.
151
  Background camera-rotation failures remain unusable frames. Camera rotation and
docs/motion-input.schema.json CHANGED
@@ -115,7 +115,7 @@
115
  "type": "integer"
116
  },
117
  "context_frames": {
118
- "default": 30,
119
  "maximum": 60,
120
  "minimum": 10,
121
  "title": "Context Frames",
 
115
  "type": "integer"
116
  },
117
  "context_frames": {
118
+ "default": 60,
119
  "maximum": 60,
120
  "minimum": 10,
121
  "title": "Context Frames",
tests/test_gvhmr_motion.py CHANGED
@@ -55,6 +55,8 @@ def test_occluded_wrist_and_camera_inconsistency_disable_only_dependent_points(v
55
 
56
 
57
  def test_uniform_model_clock_rotations_and_chunks_do_not_bridge_gaps():
 
 
58
  t=np.array([0,.016,.033,.051,.066,.083,1.,1.016,1.033,1.05])
59
  grid=uniform_grid(t[:6]);np.testing.assert_allclose(np.diff(grid),1/30)
60
  # +170 -> -170 degrees takes the short route through 180, never through zero.
@@ -95,11 +97,45 @@ def test_gvhmr_public_motion_reproduces_measurements_and_annotated_timeline(tmp_
95
  summaries=json.loads((tmp_path/'measurements.json').read_text())['summaries']
96
  for metric in summaries:assert values[metric['rep'],metric['metric_id']]==metric['value']
97
  assert all(m['uses_interpolated_input'] for m in summaries)
 
98
  assert all(manifest.artifacts['annotated_'+key].status=='available' for key in ('rotation','timing','posture','stance'))
99
  from baseball_batting.ingest import iter_frames
100
  assert [float(pts*base) for _,pts,base,_ in iter_frames(tmp_path/'group-videos/rotation.mp4')]==pytest.approx([f['video_time_s'] for f in rows],abs=2e-6)
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def test_model_selector_readiness_is_independent_and_unknown_model_is_rejected(tmp_path,video,monkeypatch):
104
  import baseball_batting.motion_api as module
105
  service=fake_service(settings(tmp_path),delay=30)
@@ -163,8 +199,11 @@ def test_missing_licensed_body_model_stops_setup_before_any_download(tmp_path,mo
163
  from tools import prepare_gvhmr_assets
164
  monkeypatch.setenv('BASEBALL_DATA_ROOT',str(tmp_path))
165
  monkeypatch.setenv('BASEBALL_GVHMR_SOURCE',str(tmp_path))
 
 
166
  monkeypatch.delenv('BASEBALL_SMPLX_MODEL_PATH',raising=False);monkeypatch.delenv('BASEBALL_SMPLX_REPO',raising=False)
167
  monkeypatch.setattr(prepare_gvhmr_assets.subprocess,'check_output',lambda *a,**k:GVHMR_REVISION)
168
  assert prepare_gvhmr_assets.main()==1
169
  assert json.loads((tmp_path/'gvhmr-setup-status.json').read_text())['reason_code']=='gvhmr_smplx_license_asset_required'
170
  assert not (tmp_path/'gvhmr-cache').exists()
 
 
55
 
56
 
57
  def test_uniform_model_clock_rotations_and_chunks_do_not_bridge_gaps():
58
+ with pytest.raises(ValueError,match='nonempty core'):
59
+ MotionInput(model='gvhmr',gvhmr={'max_sequence_frames':90,'context_frames':60})
60
  t=np.array([0,.016,.033,.051,.066,.083,1.,1.016,1.033,1.05])
61
  grid=uniform_grid(t[:6]);np.testing.assert_allclose(np.diff(grid),1/30)
62
  # +170 -> -170 degrees takes the short route through 180, never through zero.
 
97
  summaries=json.loads((tmp_path/'measurements.json').read_text())['summaries']
98
  for metric in summaries:assert values[metric['rep'],metric['metric_id']]==metric['value']
99
  assert all(m['uses_interpolated_input'] for m in summaries)
100
+ assert all(m['sample_spacing_ms']>=33.333 for m in summaries if m['unit'] in ('ms','m/s','deg/s'))
101
  assert all(manifest.artifacts['annotated_'+key].status=='available' for key in ('rotation','timing','posture','stance'))
102
  from baseball_batting.ingest import iter_frames
103
  assert [float(pts*base) for _,pts,base,_ in iter_frames(tmp_path/'group-videos/rotation.mp4')]==pytest.approx([f['video_time_s'] for f in rows],abs=2e-6)
104
 
105
 
106
+ def test_model_window_jump_does_not_become_velocity_evidence(tmp_path,video):
107
+ opts=inputs(model='gvhmr',annotated_videos=False,timing={'kind':'unretimed','source':'Known fixture clock'})
108
+ capture=ingest(video,opts.metadata());raw,*_=native_fixture(capture)
109
+ raw['points_body'][4:,MHR['left_wrist'],0]+=.4
110
+ raw['projection']=np.stack([project(p+c,k) for p,c,k in zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
111
+ raw['sequence_ids']=np.array([0]*4+[1]*4)
112
+ manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic chunk-boundary fixture'},
113
+ {'analysis_id':'fixture','analysis_revision':1})
114
+ rows=[json.loads(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
115
+ assert rows[3]['segment_id']!=rows[4]['segment_id']
116
+ series=json.loads((tmp_path/'measurements.json').read_text())['series']
117
+ assert all(s['value'] is None for curve in series if curve['unit'] in ('m/s','deg/s') for s in curve['samples'])
118
+ original=json.loads((tmp_path/'measurements.json').read_text())['summaries']
119
+ recomputed=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
120
+ values={(s.rep,m.key):m.value for swings in recomputed.values() for s in swings for m in s.measurements}
121
+ assert all(values[m['rep'],m['metric_id']]==m['value'] for m in original)
122
+
123
+
124
+ def test_real_swing_candidate_survives_a_larger_model_boundary_jump():
125
+ from test_sam_batting import pose
126
+ from baseball_batting.sam_measurements import calculate_measurements
127
+ t=np.arange(150)/60;points=pose(len(t))
128
+ points[:,[41,62],0]+=(.4*np.tanh((t-1.8)/.08))[:,None]
129
+ # A model boundary jump is larger/faster than the actual swing.
130
+ points[36:,[41,62],0]+=1.
131
+ boundary=np.zeros(points.shape[:2],bool);boundary[34:39]=True
132
+ boundary[:2]=True;boundary[-2:]=True
133
+ _,contexts=calculate_measurements({'points_relative':points,'boundary':boundary},t,inputs().sam_options())
134
+ window=contexts[0]['window']
135
+ assert t[window['forward_start_frame']]>1.
136
+ assert t[window['forward_start_frame']]<1.8<t[window['forward_end_frame']]
137
+
138
+
139
  def test_model_selector_readiness_is_independent_and_unknown_model_is_rejected(tmp_path,video,monkeypatch):
140
  import baseball_batting.motion_api as module
141
  service=fake_service(settings(tmp_path),delay=30)
 
199
  from tools import prepare_gvhmr_assets
200
  monkeypatch.setenv('BASEBALL_DATA_ROOT',str(tmp_path))
201
  monkeypatch.setenv('BASEBALL_GVHMR_SOURCE',str(tmp_path))
202
+ monkeypatch.setenv('BASEBALL_GVHMR_WORKER_RECORD',str(tmp_path/'gvhmr-api-worker.json'))
203
+ (tmp_path/'gvhmr-api-worker.json').write_text('{"stale":true}')
204
  monkeypatch.delenv('BASEBALL_SMPLX_MODEL_PATH',raising=False);monkeypatch.delenv('BASEBALL_SMPLX_REPO',raising=False)
205
  monkeypatch.setattr(prepare_gvhmr_assets.subprocess,'check_output',lambda *a,**k:GVHMR_REVISION)
206
  assert prepare_gvhmr_assets.main()==1
207
  assert json.loads((tmp_path/'gvhmr-setup-status.json').read_text())['reason_code']=='gvhmr_smplx_license_asset_required'
208
  assert not (tmp_path/'gvhmr-cache').exists()
209
+ assert not (tmp_path/'gvhmr-api-worker.json').exists()
tools/prepare_gvhmr_assets.py CHANGED
@@ -28,7 +28,10 @@ def link(source,destination):
28
  def main():
29
  root=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'));root.mkdir(parents=True,exist_ok=True)
30
  status=root/'gvhmr-setup-status.json'
31
- def state(reason=None):atomic_json(status,{'status':'configured' if reason is None else 'unavailable','reason_code':reason})
 
 
 
32
  try:
33
  source=Path(os.environ.get('BASEBALL_GVHMR_SOURCE','/opt/gvhmr-source'))
34
  if not source.is_dir():state('gvhmr_runtime_not_installed');return 1
@@ -60,7 +63,7 @@ def main():
60
  'artifact_hashes':{key:sha256_file(path) for key,path in assets.items()},
61
  'weights_repository':weights_repo,'weights_revision':weights_revision,'body_model_revision':body_revision,
62
  'status':'installed_requires_inference','license_notice':'Operator supplies licensed SMPL-X; GVHMR research/non-commercial license applies'}
63
- atomic_json(Path(os.environ.get('BASEBALL_GVHMR_WORKER_RECORD',str(root/'gvhmr-api-worker.json'))),record)
64
  state();return 0
65
  except Exception as error:
66
  code=getattr(getattr(error,'response',None),'status_code',None)
 
28
  def main():
29
  root=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'));root.mkdir(parents=True,exist_ok=True)
30
  status=root/'gvhmr-setup-status.json'
31
+ destination=Path(os.environ.get('BASEBALL_GVHMR_WORKER_RECORD',str(root/'gvhmr-api-worker.json')))
32
+ def state(reason=None):
33
+ if reason:destination.unlink(missing_ok=True)
34
+ atomic_json(status,{'status':'configured' if reason is None else 'unavailable','reason_code':reason})
35
  try:
36
  source=Path(os.environ.get('BASEBALL_GVHMR_SOURCE','/opt/gvhmr-source'))
37
  if not source.is_dir():state('gvhmr_runtime_not_installed');return 1
 
63
  'artifact_hashes':{key:sha256_file(path) for key,path in assets.items()},
64
  'weights_repository':weights_repo,'weights_revision':weights_revision,'body_model_revision':body_revision,
65
  'status':'installed_requires_inference','license_notice':'Operator supplies licensed SMPL-X; GVHMR research/non-commercial license applies'}
66
+ atomic_json(destination,record)
67
  state();return 0
68
  except Exception as error:
69
  code=getattr(getattr(error,'response',None),'status_code',None)