github-actions[bot] commited on
Commit
f08f3e0
·
1 Parent(s): c3e239e

Automated Deploy: ae294ce0ed7f92ea349a40c81cd96e301ae30d8f

Browse files
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.16.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.16.1", 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/contact_detection.py CHANGED
@@ -8,6 +8,7 @@ from .bat_ball_timing import _line_track, shaft_distance
8
  from .contact_contract import ContactEstimate
9
 
10
  VERSION = 'single-video-contact-v1'
 
11
 
12
 
13
  def _unknown(reason, counts):
 
8
  from .contact_contract import ContactEstimate
9
 
10
  VERSION = 'single-video-contact-v1'
11
+ MIN_CONTACT_CONTEXT = 7 # Three observed samples before, the interaction, three after.
12
 
13
 
14
  def _unknown(reason, counts):
baseball_batting/contact_fast.py CHANGED
@@ -217,12 +217,23 @@ def _collect_windows(video, capture, windows, models, budget, progress, state):
217
  by_pts = {Fraction(f['pts'])*Fraction(f['time_base']): i for i, f in enumerate(frames)}
218
  complete = []
219
  state.update(original=original, complete=complete)
 
 
220
  with av.open(str(video), options={'protocol_whitelist': 'file,pipe'}) as container:
221
  stream = container.streams.video[0]
222
  stream.thread_count = 2
223
  for segment, window in enumerate(windows):
224
  budget.check()
225
  a, b = window['start_frame'], window['end_frame']
 
 
 
 
 
 
 
 
 
226
  source = Fraction(frames[a]['pts'])*Fraction(frames[a]['time_base'])
227
  container.seek(int(source/stream.time_base), stream=stream, backward=True)
228
  previous = None; old_boxes = []; transform = np.eye(3); box = None; last = None
@@ -287,8 +298,11 @@ def _collect_windows(video, capture, windows, models, budget, progress, state):
287
  source_frame_count=len(frames), windows_checked=complete)
288
  return result, original, complete
289
  result = estimate({'frames': rows}, capture)
 
 
290
  result.evidence.update(search_complete=all(r['searched'] for r in original),
291
- searched_frame_count=sum(r['searched'] for r in original), source_frame_count=len(frames), windows_checked=complete)
 
292
  return result, original, complete
293
 
294
 
 
217
  by_pts = {Fraction(f['pts'])*Fraction(f['time_base']): i for i, f in enumerate(frames)}
218
  complete = []
219
  state.update(original=original, complete=complete)
220
+ visual_started = budget.clock()
221
+ budget_limited = False
222
  with av.open(str(video), options={'protocol_whitelist': 'file,pipe'}) as container:
223
  stream = container.streams.video[0]
224
  stream.thread_count = 2
225
  for segment, window in enumerate(windows):
226
  budget.check()
227
  a, b = window['start_frame'], window['end_frame']
228
+ processed = sum(r['searched'] for r in original)
229
+ if processed:
230
+ # Use this request's observed processing cost, not an assumed
231
+ # FPS or GPU speed. Do not start a second incomplete context
232
+ # when the remaining budget is insufficient for its support.
233
+ expected = (budget.clock()-visual_started)/processed*(b-a+1)
234
+ if budget.ends-budget.clock() < expected+.08:
235
+ budget_limited = True
236
+ break
237
  source = Fraction(frames[a]['pts'])*Fraction(frames[a]['time_base'])
238
  container.seek(int(source/stream.time_base), stream=stream, backward=True)
239
  previous = None; old_boxes = []; transform = np.eye(3); box = None; last = None
 
298
  source_frame_count=len(frames), windows_checked=complete)
299
  return result, original, complete
300
  result = estimate({'frames': rows}, capture)
301
+ if budget_limited:
302
+ result.reasons.append('search_budget_limited')
303
  result.evidence.update(search_complete=all(r['searched'] for r in original),
304
+ searched_frame_count=sum(r['searched'] for r in original), source_frame_count=len(frames), windows_checked=complete,
305
+ budget_limited=budget_limited)
306
  return result, original, complete
307
 
308
 
baseball_batting/contact_fast_worker.py CHANGED
@@ -10,6 +10,7 @@ import numpy as np
10
  from .contact_contract import ContactInput, ContactResult, ContactArtifact
11
  from .contact_fast import Budget, BudgetExpired, ContactModels, scan, candidate_windows, collect_windows, unavailable, VERSION
12
  from .contact_audio import inspect
 
13
  from .storage import atomic_json, read_json, sha256_file
14
 
15
 
@@ -76,7 +77,10 @@ def decide(job, models, *, started=None, retention_s=86400, max_frames=7200, max
76
  progress('audio_candidate_search')
77
  result.audio = inspect(video, capture['frames'][0]['playback_s'], float(times[-1]),
78
  unavailable('not_checked'), options.use_audio, check=budget.check)
79
- windows = candidate_windows(times, motion, ranked, result.audio)
 
 
 
80
  result.pipeline['candidate_windows'] = windows
81
  budget.check()
82
  if windows:
 
10
  from .contact_contract import ContactInput, ContactResult, ContactArtifact
11
  from .contact_fast import Budget, BudgetExpired, ContactModels, scan, candidate_windows, collect_windows, unavailable, VERSION
12
  from .contact_audio import inspect
13
+ from .contact_detection import MIN_CONTACT_CONTEXT
14
  from .storage import atomic_json, read_json, sha256_file
15
 
16
 
 
77
  progress('audio_candidate_search')
78
  result.audio = inspect(video, capture['frames'][0]['playback_s'], float(times[-1]),
79
  unavailable('not_checked'), options.use_audio, check=budget.check)
80
+ # Start with the minimum actual before/after support the detector needs,
81
+ # centered on each proposal. A large window processed from its beginning
82
+ # can consume the budget before reaching the possible interaction.
83
+ windows = candidate_windows(times, motion, ranked, result.audio, max_window_frames=MIN_CONTACT_CONTEXT)
84
  result.pipeline['candidate_windows'] = windows
85
  budget.check()
86
  if windows:
docs/CONTACT_API.md CHANGED
@@ -63,11 +63,16 @@ supported. Video-only uploads remain usable with unknown physical time.
63
  `fast` is now the default. The GPU worker keeps its three models loaded and
64
  executes a warmup inference before reporting `fast_ready: true`. A low-resolution
65
  motion scan and optional audio transients propose up to three short windows.
66
- Only consecutive original frames in those windows receive bat/ball inference,
 
 
67
  with one bat crop and one ball crop per frame. Audio locates candidates; the
68
  same visual bat-sweep/ball-deflection rule still decides the result. Audio alone
69
  never supplies a contact time. A supported estimate can stop the remaining
70
  candidate search; `candidate_window_search_only` explicitly limits its scope.
 
 
 
71
 
72
  The default processing budget is **5 seconds**, adjustable from 1 to 5 through
73
  `processing_budget_s`. The cooperative deadline reserves time to publish JSON;
@@ -219,6 +224,7 @@ Common unavailable reasons:
219
  - `multiple_contact_candidates`
220
  - `no_contact_search_candidate`
221
  - `processing_budget_exceeded`
 
222
  - `fast_worker_unavailable` / `fast_worker_exited`
223
 
224
  A job completes successfully with unavailable contact when detection is uncertain.
 
63
  `fast` is now the default. The GPU worker keeps its three models loaded and
64
  executes a warmup inference before reporting `fast_ready: true`. A low-resolution
65
  motion scan and optional audio transients propose up to three short windows.
66
+ Each initial visual check uses the detector's minimum seven consecutive source
67
+ frames (three before, one candidate, three after), centered on its proposal, so
68
+ the budget reaches both sides of the possible interaction. Only those frames receive bat/ball inference,
69
  with one bat crop and one ball crop per frame. Audio locates candidates; the
70
  same visual bat-sweep/ball-deflection rule still decides the result. Audio alone
71
  never supplies a contact time. A supported estimate can stop the remaining
72
  candidate search; `candidate_window_search_only` explicitly limits its scope.
73
+ After a window, the worker uses the measured processing cost to avoid starting
74
+ another context it cannot finish in the remaining time; `search_budget_limited`
75
+ records that restricted search. Full mode can examine longer observed paths.
76
 
77
  The default processing budget is **5 seconds**, adjustable from 1 to 5 through
78
  `processing_budget_s`. The cooperative deadline reserves time to publish JSON;
 
224
  - `multiple_contact_candidates`
225
  - `no_contact_search_candidate`
226
  - `processing_budget_exceeded`
227
+ - `search_budget_limited` (additional limitation when other candidates were not checked)
228
  - `fast_worker_unavailable` / `fast_worker_exited`
229
 
230
  A job completes successfully with unavailable contact when detection is uncertain.
tests/test_contact_fast.py CHANGED
@@ -89,6 +89,11 @@ def test_windows_use_audio_and_silent_motion_but_never_interpolate_frames():
89
  high = candidate_windows(np.arange(1000)/240, np.ones(1000), [500], {})
90
  assert high[0]['end_frame']-high[0]['start_frame']+1 == 32
91
  assert candidate_windows(times, np.zeros(120), [], {}) == []
 
 
 
 
 
92
 
93
 
94
  def test_rotation_metadata_matches_existing_upright_coordinate_system(video, tmp_path):
@@ -143,6 +148,34 @@ def test_cooperative_deadline_retains_only_completed_observations(video, monkeyp
143
  assert checked == [] and result.video_time_s is None
144
 
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  def test_fast_decision_returns_before_renderer_and_artifacts_preserve_pts(video, tmp_path, monkeypatch):
147
  service = fake_service(settings(tmp_path))
148
  path = job(service, video)
 
89
  high = candidate_windows(np.arange(1000)/240, np.ones(1000), [500], {})
90
  assert high[0]['end_frame']-high[0]['start_frame']+1 == 32
91
  assert candidate_windows(times, np.zeros(120), [], {}) == []
92
+ from baseball_batting.contact_detection import MIN_CONTACT_CONTEXT
93
+ core = candidate_windows(times, motion, [60, 20], {}, max_window_frames=MIN_CONTACT_CONTEXT)
94
+ assert core[0]['start_frame'] == 57 and core[0]['end_frame'] == 63
95
+ low = candidate_windows(np.arange(20)/8, np.arange(20), [10], {}, max_window_frames=MIN_CONTACT_CONTEXT)
96
+ assert low[0]['start_frame'] == 7 and low[0]['end_frame'] == 13
97
 
98
 
99
  def test_rotation_metadata_matches_existing_upright_coordinate_system(video, tmp_path):
 
148
  assert checked == [] and result.video_time_s is None
149
 
150
 
151
+ def test_search_finishes_one_context_before_spending_budget_on_another(tmp_path, monkeypatch):
152
+ import av
153
+ from fractions import Fraction
154
+ from baseball_batting.contact_fast import collect_windows
155
+ video = tmp_path/'contexts.mp4'
156
+ with av.open(str(video), 'w') as out:
157
+ stream = out.add_stream('libx264', rate=30)
158
+ stream.width, stream.height, stream.pix_fmt = 160, 120, 'yuv420p'
159
+ for i in range(16):
160
+ frame = av.VideoFrame.from_ndarray(np.full((120, 160, 3), i*10, np.uint8), format='bgr24')
161
+ frame.pts, frame.time_base = i, Fraction(1, 30)
162
+ for packet in stream.encode(frame): out.mux(packet)
163
+ for packet in stream.encode(): out.mux(packet)
164
+ cap, *_ = scan(video, ContactInput(), Budget(5))
165
+ clock = [0.]
166
+ monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
167
+ def bat(image, origin): clock[0] += .2; return []
168
+ def ball(image, origin): clock[0] += .2; return []
169
+ windows = [{'start_frame': 0, 'end_frame': 6}, {'start_frame': 9, 'end_frame': 15}]
170
+ result, rows, checked = collect_windows(video, cap, windows,
171
+ SimpleNamespace(person=lambda image: [], bat=bat, ball=ball), Budget(5, clock=lambda: clock[0]))
172
+ assert checked == windows[:1]
173
+ assert [r['source_frame_index'] for r in rows if r['searched']] == list(range(7))
174
+ assert result.status == 'unavailable' and 'search_budget_limited' in result.reasons
175
+ assert 'processing_budget_exceeded' not in result.reasons
176
+ assert clock[0] < 5
177
+
178
+
179
  def test_fast_decision_returns_before_renderer_and_artifacts_preserve_pts(video, tmp_path, monkeypatch):
180
  service = fake_service(settings(tmp_path))
181
  path = job(service, video)