Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
c3e239e
1
Parent(s): 64a7cee
Automated Deploy: a8710fc83fdc8b3d85b85e22f06540faed661adc
Browse files- baseball_batting/api.py +1 -1
- baseball_batting/api_jobs.py +46 -1
- baseball_batting/contact_api.py +30 -3
- baseball_batting/contact_audio.py +4 -2
- baseball_batting/contact_contract.py +11 -2
- baseball_batting/contact_fast.py +297 -0
- baseball_batting/contact_fast_worker.py +153 -0
- baseball_batting/contact_render_worker.py +73 -0
- baseball_batting/contact_runtime.py +202 -0
- baseball_batting/contact_videos.py +4 -0
- baseball_batting/contact_worker.py +13 -1
- baseball_batting/detection.py +2 -2
- baseball_batting/tracking_vision.py +3 -3
- docs/CONTACT_API.md +80 -4
- docs/CONTACT_VALIDATION.md +73 -0
- docs/contact-input.schema.json +16 -0
- docs/contact-result.schema.json +21 -6
- tests/test_contact_api.py +2 -2
- tests/test_contact_fast.py +314 -0
- tools/benchmark_contact_api.py +100 -0
baseball_batting/api.py
CHANGED
|
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
-
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
|
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
+
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.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)
|
baseball_batting/api_jobs.py
CHANGED
|
@@ -86,6 +86,8 @@ class JobStore:
|
|
| 86 |
db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT')
|
| 87 |
if 'kind' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
|
| 88 |
db.execute("ALTER TABLE jobs ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'")
|
|
|
|
|
|
|
| 89 |
db.execute('CREATE TABLE IF NOT EXISTS motion_revisions (analysis_id TEXT NOT NULL, revision INTEGER NOT NULL, job_id TEXT UNIQUE NOT NULL, parent_job_id TEXT, PRIMARY KEY (analysis_id, revision))')
|
| 90 |
|
| 91 |
@contextmanager
|
|
@@ -152,13 +154,23 @@ class JobStore:
|
|
| 152 |
db.execute("UPDATE jobs SET updated=?, product_sha256=? WHERE id=? AND status='completed'",
|
| 153 |
(time.time(), product_hash, identifier))
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
def cancel(self, identifier):
|
| 156 |
with self.connect() as db:
|
| 157 |
db.execute("BEGIN IMMEDIATE")
|
| 158 |
row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 159 |
if not row: return None
|
| 160 |
status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
|
| 161 |
-
db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL, product_sha256=NULL, swings_sha256=NULL WHERE id=?",
|
| 162 |
(status, time.time(), identifier))
|
| 163 |
return status
|
| 164 |
|
|
@@ -213,6 +225,12 @@ class JobService:
|
|
| 213 |
self.lock = None
|
| 214 |
# Serializes completion/cancellation and deletion against result downloads.
|
| 215 |
self.mutation_lock = threading.RLock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
def job_directory(self, identifier):
|
| 218 |
if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier):
|
|
@@ -239,16 +257,24 @@ class JobService:
|
|
| 239 |
raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker")
|
| 240 |
for identifier in self.store.recover():
|
| 241 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
|
|
|
|
|
|
|
|
|
| 242 |
self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True)
|
| 243 |
self.thread.start()
|
| 244 |
|
| 245 |
def stop(self):
|
| 246 |
self.ready = False
|
| 247 |
self.stopping.set(); self.wakeup.set()
|
|
|
|
| 248 |
if self.thread:
|
| 249 |
self.thread.join(timeout=15)
|
| 250 |
if self.thread.is_alive():
|
| 251 |
raise RuntimeError("GPU worker did not stop")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
if self.lock:
|
| 253 |
self.lock.close()
|
| 254 |
|
|
@@ -270,6 +296,8 @@ class JobService:
|
|
| 270 |
with self.mutation_lock:
|
| 271 |
status = self.store.cancel(identifier)
|
| 272 |
if status == "cancelled":
|
|
|
|
|
|
|
| 273 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 274 |
self.wakeup.set()
|
| 275 |
return status
|
|
@@ -277,6 +305,8 @@ class JobService:
|
|
| 277 |
def cleanup(self):
|
| 278 |
with self.mutation_lock:
|
| 279 |
for identifier in self.store.expired(time.time() - self.settings.retention_s):
|
|
|
|
|
|
|
| 280 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 281 |
self.store.forget(identifier)
|
| 282 |
|
|
@@ -306,9 +336,13 @@ class JobService:
|
|
| 306 |
record = read_json(readiness_path)
|
| 307 |
self.tracking_ready = record.get('ready') is True and record.get('bat_ball_tracking') is True
|
| 308 |
self.visual_model_status = record.get('visual_model_status', {'status': 'not_checked'})
|
|
|
|
|
|
|
| 309 |
self.ready = True; self.readiness_reason = "ready"
|
| 310 |
while not self.stopping.is_set():
|
| 311 |
self.cleanup()
|
|
|
|
|
|
|
| 312 |
identifier = self.store.claim()
|
| 313 |
if identifier:
|
| 314 |
self.execute(identifier)
|
|
@@ -318,6 +352,8 @@ class JobService:
|
|
| 318 |
self.readiness_reason = "queue_worker_failed"
|
| 319 |
LOG.exception("GPU job queue stopped")
|
| 320 |
finally:
|
|
|
|
|
|
|
| 321 |
self.ready = False
|
| 322 |
self.tracking_ready = False
|
| 323 |
|
|
@@ -325,6 +361,15 @@ class JobService:
|
|
| 325 |
directory = self.job_directory(identifier)
|
| 326 |
process = None
|
| 327 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 329 |
started = time.monotonic()
|
| 330 |
while process.poll() is None:
|
|
|
|
| 86 |
db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT')
|
| 87 |
if 'kind' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
|
| 88 |
db.execute("ALTER TABLE jobs ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'")
|
| 89 |
+
if 'contact_artifacts_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
|
| 90 |
+
db.execute('ALTER TABLE jobs ADD COLUMN contact_artifacts_sha256 TEXT')
|
| 91 |
db.execute('CREATE TABLE IF NOT EXISTS motion_revisions (analysis_id TEXT NOT NULL, revision INTEGER NOT NULL, job_id TEXT UNIQUE NOT NULL, parent_job_id TEXT, PRIMARY KEY (analysis_id, revision))')
|
| 92 |
|
| 93 |
@contextmanager
|
|
|
|
| 154 |
db.execute("UPDATE jobs SET updated=?, product_sha256=? WHERE id=? AND status='completed'",
|
| 155 |
(time.time(), product_hash, identifier))
|
| 156 |
|
| 157 |
+
def update_contact_artifacts(self, identifier, result_hash):
|
| 158 |
+
"""Point at a durable rendered snapshot; keep the base decision immutable."""
|
| 159 |
+
with self.connect() as db:
|
| 160 |
+
db.execute("UPDATE jobs SET contact_artifacts_sha256=? WHERE id=? AND status='completed'",
|
| 161 |
+
(result_hash, identifier))
|
| 162 |
+
|
| 163 |
+
def completed_contacts(self):
|
| 164 |
+
with self.connect() as db:
|
| 165 |
+
return [row[0] for row in db.execute("SELECT id FROM jobs WHERE kind='contact' AND status='completed'")]
|
| 166 |
+
|
| 167 |
def cancel(self, identifier):
|
| 168 |
with self.connect() as db:
|
| 169 |
db.execute("BEGIN IMMEDIATE")
|
| 170 |
row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 171 |
if not row: return None
|
| 172 |
status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
|
| 173 |
+
db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL, product_sha256=NULL, swings_sha256=NULL, contact_artifacts_sha256=NULL WHERE id=?",
|
| 174 |
(status, time.time(), identifier))
|
| 175 |
return status
|
| 176 |
|
|
|
|
| 225 |
self.lock = None
|
| 226 |
# Serializes completion/cancellation and deletion against result downloads.
|
| 227 |
self.mutation_lock = threading.RLock()
|
| 228 |
+
from .contact_runtime import ResidentContact
|
| 229 |
+
self.contact_runtime = ResidentContact(self) if command_factory is None else None
|
| 230 |
+
self.render_thread = None
|
| 231 |
+
self.render_process = None
|
| 232 |
+
self.render_identifier = None
|
| 233 |
+
self.render_wakeup = threading.Event()
|
| 234 |
|
| 235 |
def job_directory(self, identifier):
|
| 236 |
if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier):
|
|
|
|
| 257 |
raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker")
|
| 258 |
for identifier in self.store.recover():
|
| 259 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 260 |
+
from .contact_runtime import render_loop
|
| 261 |
+
self.render_thread = threading.Thread(target=render_loop, args=(self,), name='contact-video-queue', daemon=True)
|
| 262 |
+
self.render_thread.start()
|
| 263 |
self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True)
|
| 264 |
self.thread.start()
|
| 265 |
|
| 266 |
def stop(self):
|
| 267 |
self.ready = False
|
| 268 |
self.stopping.set(); self.wakeup.set()
|
| 269 |
+
self.render_wakeup.set()
|
| 270 |
if self.thread:
|
| 271 |
self.thread.join(timeout=15)
|
| 272 |
if self.thread.is_alive():
|
| 273 |
raise RuntimeError("GPU worker did not stop")
|
| 274 |
+
if self.render_thread:
|
| 275 |
+
self.render_thread.join(timeout=10)
|
| 276 |
+
if self.render_thread.is_alive():
|
| 277 |
+
raise RuntimeError('Contact render worker did not stop')
|
| 278 |
if self.lock:
|
| 279 |
self.lock.close()
|
| 280 |
|
|
|
|
| 296 |
with self.mutation_lock:
|
| 297 |
status = self.store.cancel(identifier)
|
| 298 |
if status == "cancelled":
|
| 299 |
+
if self.render_identifier == identifier and self.render_process is not None:
|
| 300 |
+
stop_process(self.render_process)
|
| 301 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 302 |
self.wakeup.set()
|
| 303 |
return status
|
|
|
|
| 305 |
def cleanup(self):
|
| 306 |
with self.mutation_lock:
|
| 307 |
for identifier in self.store.expired(time.time() - self.settings.retention_s):
|
| 308 |
+
if self.render_identifier == identifier and self.render_process is not None:
|
| 309 |
+
stop_process(self.render_process)
|
| 310 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 311 |
self.store.forget(identifier)
|
| 312 |
|
|
|
|
| 336 |
record = read_json(readiness_path)
|
| 337 |
self.tracking_ready = record.get('ready') is True and record.get('bat_ball_tracking') is True
|
| 338 |
self.visual_model_status = record.get('visual_model_status', {'status': 'not_checked'})
|
| 339 |
+
if self.tracking_ready and self.contact_runtime:
|
| 340 |
+
self.contact_runtime.start()
|
| 341 |
self.ready = True; self.readiness_reason = "ready"
|
| 342 |
while not self.stopping.is_set():
|
| 343 |
self.cleanup()
|
| 344 |
+
if self.tracking_ready and self.contact_runtime and not self.contact_runtime.ready:
|
| 345 |
+
self.contact_runtime.start()
|
| 346 |
identifier = self.store.claim()
|
| 347 |
if identifier:
|
| 348 |
self.execute(identifier)
|
|
|
|
| 352 |
self.readiness_reason = "queue_worker_failed"
|
| 353 |
LOG.exception("GPU job queue stopped")
|
| 354 |
finally:
|
| 355 |
+
if self.contact_runtime:
|
| 356 |
+
self.contact_runtime.stop()
|
| 357 |
self.ready = False
|
| 358 |
self.tracking_ready = False
|
| 359 |
|
|
|
|
| 361 |
directory = self.job_directory(identifier)
|
| 362 |
process = None
|
| 363 |
try:
|
| 364 |
+
kind = (self.store.get(identifier) or {}).get('kind')
|
| 365 |
+
if self.contact_runtime:
|
| 366 |
+
fast = kind == 'contact' and read_json(directory/'request.json').get('mode', 'fast') == 'fast'
|
| 367 |
+
if fast:
|
| 368 |
+
self.contact_runtime.execute(identifier)
|
| 369 |
+
return
|
| 370 |
+
# Give SAM/GVHMR their original GPU memory headroom. Requests
|
| 371 |
+
# arriving during rewarm report that state instead of a false SLA.
|
| 372 |
+
self.contact_runtime.stop()
|
| 373 |
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 374 |
started = time.monotonic()
|
| 375 |
while process.poll() is None:
|
baseball_batting/contact_api.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Authenticated video-only contact estimates sharing the existing GPU queue."""
|
| 2 |
from pathlib import Path
|
|
|
|
| 3 |
import shutil
|
| 4 |
from typing import Annotated
|
| 5 |
from fastapi import Depends,File,Form,HTTPException,Request,UploadFile
|
|
@@ -30,14 +31,29 @@ def register(app,service,authenticated):
|
|
| 30 |
raise HTTPException(500,'Stored contact result failed its integrity check')
|
| 31 |
try:result=ContactResult.model_validate(read_json(path))
|
| 32 |
except (ValueError,ValidationError):raise HTTPException(500,'Stored contact result is invalid') from None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
return directory,result
|
| 34 |
|
| 35 |
@app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
|
| 36 |
def capabilities():
|
| 37 |
-
|
|
|
|
| 38 |
'required_fields':['video'],'minimum_fps_required':None,'variable_frame_rate':True,
|
| 39 |
'capture_clock_required':False,'sam_required':False,'manual_events_required':False,
|
| 40 |
-
'audio':'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
'max_frames':settings.max_frames,'max_duration_s':settings.max_duration_s,
|
| 42 |
'retention_hours':settings.retention_s/3600}
|
| 43 |
|
|
@@ -58,20 +74,24 @@ def register(app,service,authenticated):
|
|
| 58 |
try:parsed=ContactInput.model_validate_json(options)
|
| 59 |
except ValidationError as error:
|
| 60 |
raise HTTPException(422,[{k:e[k] for k in ('loc','type','msg')} for e in error.errors(include_input=False,include_url=False)]) from None
|
|
|
|
|
|
|
| 61 |
suffix=Path(video.filename or '').suffix.lower()
|
| 62 |
if suffix not in {'.mp4','.mov','.mkv','.avi','.webm'}:raise HTTPException(415,'Unsupported video extension')
|
| 63 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:raise HTTPException(507,'Insufficient storage')
|
| 64 |
try:identifier=service.store.create(settings.max_active_jobs,kind='contact')
|
| 65 |
except QueueFull:raise HTTPException(429,'GPU queue is full',headers={'Retry-After':'30'}) from None
|
| 66 |
-
directory=service.job_directory(identifier);directory.mkdir();size=0
|
| 67 |
with (directory/('input'+suffix)).open('wb') as out:
|
| 68 |
while block:=await video.read(1024*1024):
|
| 69 |
size+=len(block)
|
| 70 |
if size>settings.max_upload_bytes:raise HTTPException(413,'Video exceeds upload limit')
|
| 71 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes+len(block):raise HTTPException(507,'Insufficient storage')
|
| 72 |
out.write(block)
|
|
|
|
| 73 |
if not size:raise HTTPException(422,'Video is empty')
|
| 74 |
atomic_json(directory/'request.json',parsed.model_dump(mode='json'))
|
|
|
|
| 75 |
service.store.update(identifier,'queued');service.wakeup.set()
|
| 76 |
return {'job_id':identifier,'status':'queued','status_url':PREFIX+'/'+identifier,
|
| 77 |
'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600}
|
|
@@ -89,8 +109,12 @@ def register(app,service,authenticated):
|
|
| 89 |
if row['status']=='failed':
|
| 90 |
try:failure=read_json(directory/'error.json')
|
| 91 |
except (OSError,ValueError):pass
|
|
|
|
|
|
|
|
|
|
| 92 |
return JSONResponse({'job_id':identifier,'status':'processing' if row['status']=='running' else row['status'],
|
| 93 |
'progress':progress,'error':row['error'],'failure':failure,
|
|
|
|
| 94 |
'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None},headers={'Cache-Control':'no-store'})
|
| 95 |
|
| 96 |
@app.get(PREFIX+'/{identifier}/result',response_model=ContactResult,dependencies=[Depends(authenticated)])
|
|
@@ -104,6 +128,9 @@ def register(app,service,authenticated):
|
|
| 104 |
with service.mutation_lock:
|
| 105 |
directory,payload=completed(identifier);asset=payload.artifacts.get(name)
|
| 106 |
if asset is None:raise HTTPException(404,'Unknown contact artifact')
|
|
|
|
|
|
|
|
|
|
| 107 |
if asset.status!='available':raise HTTPException(409,{'code':asset.reason_code})
|
| 108 |
path=(directory/asset.filename).resolve()
|
| 109 |
if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
|
|
|
|
| 1 |
"""Authenticated video-only contact estimates sharing the existing GPU queue."""
|
| 2 |
from pathlib import Path
|
| 3 |
+
import hashlib
|
| 4 |
import shutil
|
| 5 |
from typing import Annotated
|
| 6 |
from fastapi import Depends,File,Form,HTTPException,Request,UploadFile
|
|
|
|
| 31 |
raise HTTPException(500,'Stored contact result failed its integrity check')
|
| 32 |
try:result=ContactResult.model_validate(read_json(path))
|
| 33 |
except (ValueError,ValidationError):raise HTTPException(500,'Stored contact result is invalid') from None
|
| 34 |
+
if row.get('contact_artifacts_sha256'):
|
| 35 |
+
snapshot=directory/'rendered-result.json'
|
| 36 |
+
if not snapshot.is_file() or sha256_file(snapshot)!=row['contact_artifacts_sha256']:
|
| 37 |
+
raise HTTPException(500,'Stored contact video manifest failed its integrity check')
|
| 38 |
+
try:rendered=ContactResult.model_validate(read_json(snapshot))
|
| 39 |
+
except (ValueError,ValidationError):raise HTTPException(500,'Stored contact video manifest is invalid') from None
|
| 40 |
+
if rendered.contact!=result.contact or rendered.source_video!=result.source_video or rendered.timing!=result.timing:
|
| 41 |
+
raise HTTPException(500,'Rendering changed the stored contact decision')
|
| 42 |
+
result=rendered
|
| 43 |
return directory,result
|
| 44 |
|
| 45 |
@app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
|
| 46 |
def capabilities():
|
| 47 |
+
runtime=service.contact_runtime
|
| 48 |
+
return {'schema_version':'1.1','ready':service.ready and service.tracking_ready,'device':'cuda',
|
| 49 |
'required_fields':['video'],'minimum_fps_required':None,'variable_frame_rate':True,
|
| 50 |
'capture_clock_required':False,'sam_required':False,'manual_events_required':False,
|
| 51 |
+
'audio':'optional_candidate_search; visual_evidence_required','accuracy_validated':False,
|
| 52 |
+
'default_mode':'fast','modes':['fast','full'],'processing_budget_s':5.,
|
| 53 |
+
'fast_ready':runtime.ready if runtime else False,
|
| 54 |
+
'fast_readiness_reason':runtime.reason if runtime else 'custom_worker',
|
| 55 |
+
'deadline_scope':'processing_after_queue_claim; excludes upload, queue, warmup and annotation',
|
| 56 |
+
'annotation_delivery':'asynchronous_in_fast_mode',
|
| 57 |
'max_frames':settings.max_frames,'max_duration_s':settings.max_duration_s,
|
| 58 |
'retention_hours':settings.retention_s/3600}
|
| 59 |
|
|
|
|
| 74 |
try:parsed=ContactInput.model_validate_json(options)
|
| 75 |
except ValidationError as error:
|
| 76 |
raise HTTPException(422,[{k:e[k] for k in ('loc','type','msg')} for e in error.errors(include_input=False,include_url=False)]) from None
|
| 77 |
+
if parsed.mode=='fast' and service.contact_runtime is not None and not service.contact_runtime.ready:
|
| 78 |
+
raise HTTPException(503,{'code':'fast_worker_warming','message':'Fast GPU models are warming; retry shortly.'},headers={'Retry-After':'2'})
|
| 79 |
suffix=Path(video.filename or '').suffix.lower()
|
| 80 |
if suffix not in {'.mp4','.mov','.mkv','.avi','.webm'}:raise HTTPException(415,'Unsupported video extension')
|
| 81 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:raise HTTPException(507,'Insufficient storage')
|
| 82 |
try:identifier=service.store.create(settings.max_active_jobs,kind='contact')
|
| 83 |
except QueueFull:raise HTTPException(429,'GPU queue is full',headers={'Retry-After':'30'}) from None
|
| 84 |
+
directory=service.job_directory(identifier);directory.mkdir();size=0;digest=hashlib.sha256()
|
| 85 |
with (directory/('input'+suffix)).open('wb') as out:
|
| 86 |
while block:=await video.read(1024*1024):
|
| 87 |
size+=len(block)
|
| 88 |
if size>settings.max_upload_bytes:raise HTTPException(413,'Video exceeds upload limit')
|
| 89 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes+len(block):raise HTTPException(507,'Insufficient storage')
|
| 90 |
out.write(block)
|
| 91 |
+
digest.update(block)
|
| 92 |
if not size:raise HTTPException(422,'Video is empty')
|
| 93 |
atomic_json(directory/'request.json',parsed.model_dump(mode='json'))
|
| 94 |
+
atomic_json(directory/'upload.json',{'sha256':digest.hexdigest(),'size_bytes':size})
|
| 95 |
service.store.update(identifier,'queued');service.wakeup.set()
|
| 96 |
return {'job_id':identifier,'status':'queued','status_url':PREFIX+'/'+identifier,
|
| 97 |
'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600}
|
|
|
|
| 109 |
if row['status']=='failed':
|
| 110 |
try:failure=read_json(directory/'error.json')
|
| 111 |
except (OSError,ValueError):pass
|
| 112 |
+
rendering=None
|
| 113 |
+
if row['status']=='completed':
|
| 114 |
+
_,payload=completed(identifier);rendering=payload.rendering
|
| 115 |
return JSONResponse({'job_id':identifier,'status':'processing' if row['status']=='running' else row['status'],
|
| 116 |
'progress':progress,'error':row['error'],'failure':failure,
|
| 117 |
+
'rendering':rendering,
|
| 118 |
'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None},headers={'Cache-Control':'no-store'})
|
| 119 |
|
| 120 |
@app.get(PREFIX+'/{identifier}/result',response_model=ContactResult,dependencies=[Depends(authenticated)])
|
|
|
|
| 128 |
with service.mutation_lock:
|
| 129 |
directory,payload=completed(identifier);asset=payload.artifacts.get(name)
|
| 130 |
if asset is None:raise HTTPException(404,'Unknown contact artifact')
|
| 131 |
+
if asset.status=='pending':
|
| 132 |
+
return JSONResponse({'status':'pending','reason_code':'render_pending'},status_code=202,
|
| 133 |
+
headers={'Retry-After':'1','Cache-Control':'no-store'})
|
| 134 |
if asset.status!='available':raise HTTPException(409,{'code':asset.reason_code})
|
| 135 |
path=(directory/asset.filename).resolve()
|
| 136 |
if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
|
baseball_batting/contact_audio.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
import numpy as np
|
| 3 |
|
| 4 |
|
| 5 |
-
def inspect(video, origin_s, duration_s, contact, enabled=True):
|
| 6 |
if not enabled:
|
| 7 |
return {'status':'not_requested','used_for_contact_timestamp':False}
|
| 8 |
import av
|
|
@@ -14,6 +14,7 @@ def inspect(video, origin_s, duration_s, contact, enabled=True):
|
|
| 14 |
resampler=av.AudioResampler(format='fltp',layout='mono',rate=16000)
|
| 15 |
energy=[];times=[]
|
| 16 |
for frame in container.decode(container.streams.audio[0]):
|
|
|
|
| 17 |
for sample in resampler.resample(frame):
|
| 18 |
if sample.pts is None or sample.time_base is None:
|
| 19 |
continue
|
|
@@ -39,7 +40,8 @@ def inspect(video, origin_s, duration_s, contact, enabled=True):
|
|
| 39 |
if contact.video_time_interval_s:
|
| 40 |
a,b=contact.video_time_interval_s
|
| 41 |
near=[t for t in candidates if a-.03<=t<=b+.25]
|
| 42 |
-
|
|
|
|
| 43 |
'used_for_contact_timestamp':False,'impact_sound_verified':False,
|
| 44 |
'note':'Transient sounds may be unrelated or delayed; audio never creates or verifies contact.'}
|
| 45 |
except (av.FFmpegError,ValueError,OverflowError):
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
|
| 4 |
|
| 5 |
+
def inspect(video, origin_s, duration_s, contact, enabled=True, *, check=lambda: None):
|
| 6 |
if not enabled:
|
| 7 |
return {'status':'not_requested','used_for_contact_timestamp':False}
|
| 8 |
import av
|
|
|
|
| 14 |
resampler=av.AudioResampler(format='fltp',layout='mono',rate=16000)
|
| 15 |
energy=[];times=[]
|
| 16 |
for frame in container.decode(container.streams.audio[0]):
|
| 17 |
+
check()
|
| 18 |
for sample in resampler.resample(frame):
|
| 19 |
if sample.pts is None or sample.time_base is None:
|
| 20 |
continue
|
|
|
|
| 40 |
if contact.video_time_interval_s:
|
| 41 |
a,b=contact.video_time_interval_s
|
| 42 |
near=[t for t in candidates if a-.03<=t<=b+.25]
|
| 43 |
+
strengths={str(float(times[i])):float(min(1.,novelty[i]/max(float(novelty[peaks].max()),1e-9))) for i in peaks}
|
| 44 |
+
return {'status':'analyzed','transient_video_times_s':candidates,'transient_strengths':strengths,'near_visual_contact_times_s':near,
|
| 45 |
'used_for_contact_timestamp':False,'impact_sound_verified':False,
|
| 46 |
'note':'Transient sounds may be unrelated or delayed; audio never creates or verifies contact.'}
|
| 47 |
except (av.FFmpegError,ValueError,OverflowError):
|
baseball_batting/contact_contract.py
CHANGED
|
@@ -12,6 +12,8 @@ class ContactInput(Strict):
|
|
| 12 |
rotation_degrees: Literal[0, 90, 180, 270] | None = None
|
| 13 |
annotated_video: bool = True
|
| 14 |
use_audio: bool = True
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def metadata(self):
|
| 17 |
result = {'timing': self.timing.model_dump(exclude_none=True), 'intended_use': 'research'}
|
|
@@ -55,8 +57,13 @@ class ContactEstimate(Strict):
|
|
| 55 |
return self
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
class ContactResult(Strict):
|
| 59 |
-
schema_version: Literal['1.0'] = '1.
|
| 60 |
job_id: str
|
| 61 |
status: Literal['completed'] = 'completed'
|
| 62 |
contact: ContactEstimate
|
|
@@ -64,6 +71,8 @@ class ContactResult(Strict):
|
|
| 64 |
timing: dict[str, Any]
|
| 65 |
pipeline: dict[str, Any]
|
| 66 |
audio: dict[str, Any]
|
| 67 |
-
artifacts: dict[str,
|
|
|
|
|
|
|
| 68 |
expires_at: str
|
| 69 |
accuracy_validated: Literal[False] = False
|
|
|
|
| 12 |
rotation_degrees: Literal[0, 90, 180, 270] | None = None
|
| 13 |
annotated_video: bool = True
|
| 14 |
use_audio: bool = True
|
| 15 |
+
mode: Literal['fast', 'full'] = 'fast'
|
| 16 |
+
processing_budget_s: float = Field(default=5., ge=1., le=5.)
|
| 17 |
|
| 18 |
def metadata(self):
|
| 19 |
result = {'timing': self.timing.model_dump(exclude_none=True), 'intended_use': 'research'}
|
|
|
|
| 57 |
return self
|
| 58 |
|
| 59 |
|
| 60 |
+
class ContactArtifact(Artifact):
|
| 61 |
+
# Contact videos are rendered after the decision; motion artifacts are unchanged.
|
| 62 |
+
status: Literal['available', 'unavailable', 'pending']
|
| 63 |
+
|
| 64 |
+
|
| 65 |
class ContactResult(Strict):
|
| 66 |
+
schema_version: Literal['1.0', '1.1'] = '1.1'
|
| 67 |
job_id: str
|
| 68 |
status: Literal['completed'] = 'completed'
|
| 69 |
contact: ContactEstimate
|
|
|
|
| 71 |
timing: dict[str, Any]
|
| 72 |
pipeline: dict[str, Any]
|
| 73 |
audio: dict[str, Any]
|
| 74 |
+
artifacts: dict[str, ContactArtifact]
|
| 75 |
+
artifacts_revision: int = Field(default=0, ge=0)
|
| 76 |
+
rendering: dict[str, Any] = Field(default_factory=lambda: {'status': 'not_requested'})
|
| 77 |
expires_at: str
|
| 78 |
accuracy_validated: Literal[False] = False
|
baseball_batting/contact_fast.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Budgeted candidate search. Audio proposes windows; only visual evidence decides.
|
| 2 |
+
|
| 3 |
+
Models live in the resident worker. A cheap, source-timed video pass proposes
|
| 4 |
+
motion windows, then consecutive original frames in those windows are examined.
|
| 5 |
+
This does not use a pose/contact proxy, resample time, or invent object positions.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import importlib.util
|
| 11 |
+
import numpy as np
|
| 12 |
+
import cv2
|
| 13 |
+
from .contact_contract import ContactEstimate
|
| 14 |
+
from .contact_detection import estimate
|
| 15 |
+
from .contact_vision import background_transform, stabilized
|
| 16 |
+
from .ingest import physical_time
|
| 17 |
+
|
| 18 |
+
VERSION = 'candidate-window-contact-v1'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class BudgetExpired(Exception):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Budget:
|
| 26 |
+
def __init__(self, seconds, *, started=None, clock=time.monotonic):
|
| 27 |
+
self.clock = clock
|
| 28 |
+
self.started = clock() if started is None else started
|
| 29 |
+
self.ends = self.started + seconds
|
| 30 |
+
|
| 31 |
+
def check(self):
|
| 32 |
+
if self.clock() >= self.ends:
|
| 33 |
+
raise BudgetExpired()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def optimized_session(path, device):
|
| 37 |
+
"""Use TensorRT only when installed; expose the actual selected providers.
|
| 38 |
+
|
| 39 |
+
Engine compilation is a startup operation, never charged to a request or
|
| 40 |
+
silently substituted for a warm request. The default image also supports
|
| 41 |
+
ordinary CUDA, so installing TensorRT is not required for existing APIs.
|
| 42 |
+
"""
|
| 43 |
+
from .detection import ort_session
|
| 44 |
+
if device != 'cuda' or os.environ.get('BASEBALL_CONTACT_TENSORRT', 'auto') == '0':
|
| 45 |
+
return ort_session(path, device)
|
| 46 |
+
import onnxruntime as ort
|
| 47 |
+
if 'TensorrtExecutionProvider' not in ort.get_available_providers() or importlib.util.find_spec('tensorrt') is None:
|
| 48 |
+
return ort_session(path, device)
|
| 49 |
+
import tempfile
|
| 50 |
+
import uuid
|
| 51 |
+
if hasattr(ort, 'preload_dlls'):
|
| 52 |
+
ort.preload_dlls()
|
| 53 |
+
options = ort.SessionOptions()
|
| 54 |
+
options.intra_op_num_threads = 2
|
| 55 |
+
options.enable_profiling = True
|
| 56 |
+
options.profile_file_prefix = str(Path(tempfile.gettempdir()) / ('contact-ort-' + uuid.uuid4().hex))
|
| 57 |
+
cache = Path(os.environ.get('BASEBALL_CONTACT_ENGINE_CACHE', '/data/contact-engines'))
|
| 58 |
+
cache.mkdir(parents=True, exist_ok=True)
|
| 59 |
+
return ort.InferenceSession(str(path), sess_options=options, providers=[
|
| 60 |
+
('TensorrtExecutionProvider', {'trt_fp16_enable': True, 'trt_engine_cache_enable': True,
|
| 61 |
+
'trt_engine_cache_path': str(cache), 'trt_max_workspace_size': 1 << 29}),
|
| 62 |
+
('CUDAExecutionProvider', {'use_tf32': 0}), 'CPUExecutionProvider'])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ContactModels:
|
| 66 |
+
def __init__(self, root, device='cuda'):
|
| 67 |
+
from .api_worker import model_files
|
| 68 |
+
from .detection import YOLOXDetector
|
| 69 |
+
from .tracking_vision import TrackingModel
|
| 70 |
+
files, _ = model_files(root)
|
| 71 |
+
self.person = YOLOXDetector(files['person_detector'], device, classes=[0])
|
| 72 |
+
self.bat = TrackingModel(root, 'bat', device, session_factory=optimized_session)
|
| 73 |
+
self.ball = TrackingModel(root, 'ball', device, session_factory=optimized_session)
|
| 74 |
+
self.device = device
|
| 75 |
+
blank = np.zeros((640, 640, 3), np.uint8)
|
| 76 |
+
# Run and verify real GPU operators before admitting fast requests.
|
| 77 |
+
self.person(blank); self.bat(blank); self.ball(blank)
|
| 78 |
+
self.record = {'bat': self.bat.record, 'ball': self.ball.record,
|
| 79 |
+
'providers': {name: getattr(self, name).session.get_providers() for name in ('person', 'bat', 'ball')}}
|
| 80 |
+
from .storage import sha256_file
|
| 81 |
+
self.record['implementation_sha256'] = {name: sha256_file(Path(__file__).with_name(name)) for name in
|
| 82 |
+
('contact_fast.py', 'contact_fast_worker.py', 'contact_detection.py', 'contact_audio.py',
|
| 83 |
+
'tracking_vision.py', 'detection.py', 'contact_vision.py')}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def scan(video, options, budget, *, max_frames=7200, max_pixels=8294400, max_duration=120):
|
| 87 |
+
"""Decode once to tiny grayscale images, retaining original PTS and frame IDs."""
|
| 88 |
+
import av
|
| 89 |
+
from scipy.signal import find_peaks
|
| 90 |
+
frames, motion = [], []
|
| 91 |
+
previous = None
|
| 92 |
+
origin = None
|
| 93 |
+
rotation = options.rotation_degrees
|
| 94 |
+
with av.open(str(video), options={'protocol_whitelist': 'file,pipe'}) as container:
|
| 95 |
+
if not container.streams.video:
|
| 96 |
+
raise ValueError('No video stream')
|
| 97 |
+
stream = container.streams.video[0]
|
| 98 |
+
if stream.width * stream.height > max_pixels:
|
| 99 |
+
raise ValueError('Video exceeds pixel limit')
|
| 100 |
+
stream.thread_count = 2
|
| 101 |
+
for index, frame in enumerate(container.decode(stream)):
|
| 102 |
+
budget.check()
|
| 103 |
+
if index >= max_frames or frame.width * frame.height > max_pixels:
|
| 104 |
+
raise ValueError('Video exceeds frame or pixel limit')
|
| 105 |
+
base = frame.time_base or stream.time_base
|
| 106 |
+
if frame.pts is None or not base:
|
| 107 |
+
raise ValueError('invalid_source_timestamps')
|
| 108 |
+
playback = float(frame.pts * base)
|
| 109 |
+
if origin is None:
|
| 110 |
+
origin = playback
|
| 111 |
+
# PyAV exposes display-matrix rotation counterclockwise; API overrides are clockwise.
|
| 112 |
+
rotation = (-int(getattr(frame, 'rotation', 0))) % 360 if rotation is None else rotation
|
| 113 |
+
if rotation not in (0, 90, 180, 270):
|
| 114 |
+
raise ValueError('Unsupported source orientation')
|
| 115 |
+
if frames and playback <= frames[-1]['playback_s']:
|
| 116 |
+
raise ValueError('invalid_source_timestamps')
|
| 117 |
+
if playback - origin > max_duration:
|
| 118 |
+
raise ValueError('Video exceeds duration limit')
|
| 119 |
+
width, height = (frame.width, frame.height) if rotation % 180 == 0 else (frame.height, frame.width)
|
| 120 |
+
frames.append({'frame_id': index, 'pts': frame.pts, 'time_base': str(base),
|
| 121 |
+
'playback_s': playback, 'physical_s': physical_time(playback, index, options.timing.model_dump()),
|
| 122 |
+
'width': width, 'height': height, 'flags': []})
|
| 123 |
+
ratio = min(1., 256/max(frame.width, frame.height))
|
| 124 |
+
tiny = frame.reformat(width=max(1, round(frame.width*ratio)), height=max(1, round(frame.height*ratio))).to_ndarray(format='gray')
|
| 125 |
+
# A frame difference only proposes a search window; it never establishes contact.
|
| 126 |
+
score = 0. if previous is None or tiny.shape != previous.shape else float(np.mean(
|
| 127 |
+
np.partition(cv2.absdiff(tiny, previous).reshape(-1), -max(1, tiny.size//20))[-max(1, tiny.size//20):]))
|
| 128 |
+
motion.append(score)
|
| 129 |
+
previous = tiny
|
| 130 |
+
if len(frames) < 2:
|
| 131 |
+
raise ValueError('insufficient_source_frames')
|
| 132 |
+
if options.timing.kind == 'explicit' and len(options.timing.physical_times_s) != len(frames):
|
| 133 |
+
raise ValueError('Physical-time map must match decoded frame count')
|
| 134 |
+
budget.check()
|
| 135 |
+
times = np.array([f['playback_s']-origin for f in frames])
|
| 136 |
+
# Local maxima are time-separated below, not by a fixed recording FPS.
|
| 137 |
+
peaks, _ = find_peaks(np.asarray(motion), plateau_size=1)
|
| 138 |
+
ranked = sorted(peaks, key=lambda i: motion[i], reverse=True)
|
| 139 |
+
if not ranked and max(motion) > 0:
|
| 140 |
+
ranked = [int(np.argmax(motion))]
|
| 141 |
+
return {'frames': frames, 'frame_count': len(frames), 'rotation_degrees': rotation,
|
| 142 |
+
'physical_clock_known': all(f['physical_s'] is not None for f in frames)}, times, motion, ranked
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def candidate_windows(times, motion, ranked_motion, audio, *, maximum=3, max_window_frames=32):
|
| 146 |
+
"""Merge audio and motion proposals; retain consecutive frames around each.
|
| 147 |
+
|
| 148 |
+
The cap is a compute limit, never a change in the source clock. Omitted
|
| 149 |
+
frames stay unobserved and are reported as such.
|
| 150 |
+
"""
|
| 151 |
+
motion = np.asarray(motion, float)
|
| 152 |
+
scale = max(float(motion.max()), 1.)
|
| 153 |
+
proposals = [(float(times[i]), float(motion[i]/scale), 'motion') for i in ranked_motion]
|
| 154 |
+
strengths = audio.get('transient_strengths', {})
|
| 155 |
+
for t in audio.get('transient_video_times_s', []):
|
| 156 |
+
if times[0] <= t <= times[-1]:
|
| 157 |
+
near = np.abs(times-t) <= .25
|
| 158 |
+
activity = float(motion[near].max()/scale) if near.any() else 0.
|
| 159 |
+
# Favor sound near swing motion, while keeping silent motion candidates.
|
| 160 |
+
proposals.append((float(t), .5+activity+.1*float(strengths.get(str(t), 0)), 'audio_and_motion'))
|
| 161 |
+
windows = []
|
| 162 |
+
for center, score, method in sorted(proposals, key=lambda x: x[1], reverse=True):
|
| 163 |
+
# Sound may follow the visible impact; inspect earlier frames as well.
|
| 164 |
+
ids = np.flatnonzero((times >= center-.32) & (times <= center+.25))
|
| 165 |
+
if not len(ids):
|
| 166 |
+
continue
|
| 167 |
+
if len(ids) < 7 and len(times) >= 7:
|
| 168 |
+
mid = int(np.argmin(np.abs(times-center)))
|
| 169 |
+
start = max(0, min(mid-3, len(times)-7))
|
| 170 |
+
ids = np.arange(start, start+7)
|
| 171 |
+
if len(ids) > max_window_frames:
|
| 172 |
+
mid = int(np.argmin(np.abs(times-center)))
|
| 173 |
+
start = max(int(ids[0]), min(mid-max_window_frames//2, int(ids[-1])-max_window_frames+1))
|
| 174 |
+
ids = np.arange(start, start+max_window_frames)
|
| 175 |
+
a, b = int(ids[0]), int(ids[-1])
|
| 176 |
+
if any(not (b < w['start_frame'] or a > w['end_frame']) for w in windows):
|
| 177 |
+
continue
|
| 178 |
+
if b-a < 6:
|
| 179 |
+
continue
|
| 180 |
+
windows.append({'start_frame': a, 'end_frame': b, 'candidate_video_time_s': center,
|
| 181 |
+
'method': method, 'proposal_score': score})
|
| 182 |
+
if len(windows) >= maximum:
|
| 183 |
+
break
|
| 184 |
+
return windows
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _crop(image, box, padding):
|
| 188 |
+
h, w = image.shape[:2]
|
| 189 |
+
lo = np.maximum([0, 0], np.floor(np.asarray(box[:2])-padding)).astype(int)
|
| 190 |
+
hi = np.minimum([w, h], np.ceil(np.asarray(box[2:])+padding)).astype(int)
|
| 191 |
+
if min(hi-lo) < 16:
|
| 192 |
+
return image, np.zeros(2, int)
|
| 193 |
+
return image[lo[1]:hi[1], lo[0]:hi[0]], lo
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def collect_windows(video, capture, windows, models, budget, progress=lambda *a: None):
|
| 197 |
+
state = {}
|
| 198 |
+
try:
|
| 199 |
+
return _collect_windows(video, capture, windows, models, budget, progress, state)
|
| 200 |
+
except BudgetExpired:
|
| 201 |
+
original = state.get('original', [])
|
| 202 |
+
result = unavailable('processing_budget_exceeded')
|
| 203 |
+
result.evidence.update(searched_frame_count=sum(r.get('searched', False) for r in original),
|
| 204 |
+
source_frame_count=len(capture['frames']), windows_checked=state.get('complete', []))
|
| 205 |
+
return result, original, state.get('complete', [])
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _collect_windows(video, capture, windows, models, budget, progress, state):
|
| 209 |
+
import av
|
| 210 |
+
from fractions import Fraction
|
| 211 |
+
frames = capture['frames']
|
| 212 |
+
origin = frames[0]['playback_s']
|
| 213 |
+
original = [{'bat': [], 'ball': [], 'source_frame_index': i,
|
| 214 |
+
'video_time_s': f['playback_s']-origin, 'image_width': f['width'], 'image_height': f['height'],
|
| 215 |
+
'segment_id': -1, 'camera_motion_status': 'not_searched', 'searched': False} for i, f in enumerate(frames)]
|
| 216 |
+
rows = [dict(r) for r in original]
|
| 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
|
| 229 |
+
active_segment = segment*100000
|
| 230 |
+
for frame in container.decode(stream):
|
| 231 |
+
budget.check()
|
| 232 |
+
key = frame.pts*(frame.time_base or stream.time_base) if frame.pts is not None else None
|
| 233 |
+
i = by_pts.get(key)
|
| 234 |
+
if i is None:
|
| 235 |
+
raise ValueError('Source timestamps changed during contact search')
|
| 236 |
+
if i < a:
|
| 237 |
+
continue
|
| 238 |
+
if i > b:
|
| 239 |
+
break
|
| 240 |
+
image = frame.to_ndarray(format='bgr24')
|
| 241 |
+
if capture['rotation_degrees']:
|
| 242 |
+
image = np.ascontiguousarray(np.rot90(image, -(capture['rotation_degrees']//90)))
|
| 243 |
+
if last is None:
|
| 244 |
+
people = models.person(image)
|
| 245 |
+
budget.check()
|
| 246 |
+
if people:
|
| 247 |
+
box = max(people, key=lambda p: np.prod(np.asarray(p['box'][2:])-p['box'][:2]))['box']
|
| 248 |
+
roi, offset = _crop(image, box, .35*max(box[2]-box[0], box[3]-box[1])) if box else (image, np.zeros(2, int))
|
| 249 |
+
bats = models.bat(roi, offset)
|
| 250 |
+
budget.check()
|
| 251 |
+
visible = [p for p in bats if p.get('points') is not None]
|
| 252 |
+
target = max(visible or bats, key=lambda x: x['score']) if bats else None
|
| 253 |
+
# A single high-detail crop replaces the old overlapping whole-image tile search.
|
| 254 |
+
if target:
|
| 255 |
+
length = np.linalg.norm(np.asarray(target['box'][2:])-target['box'][:2])
|
| 256 |
+
ball_roi, ball_offset = _crop(image, target['box'], max(64., .65*length))
|
| 257 |
+
else:
|
| 258 |
+
ball_roi, ball_offset = roi, offset
|
| 259 |
+
balls = models.ball(ball_roi, ball_offset)
|
| 260 |
+
budget.check()
|
| 261 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 262 |
+
boxes = [box] if box is not None else []
|
| 263 |
+
matrix = (background_transform(previous, gray, old_boxes+boxes)
|
| 264 |
+
if previous is not None and previous.shape == gray.shape else None)
|
| 265 |
+
if last is None:
|
| 266 |
+
matrix = np.eye(3)
|
| 267 |
+
elif matrix is None or i != last+1:
|
| 268 |
+
active_segment += 1; transform = np.eye(3)
|
| 269 |
+
if matrix is not None:
|
| 270 |
+
transform = transform @ np.linalg.inv(matrix)
|
| 271 |
+
row = {**original[i], 'bat': bats, 'ball': balls, 'searched': True,
|
| 272 |
+
'segment_id': active_segment,
|
| 273 |
+
'camera_motion_status': 'background_affine_estimated' if matrix is not None else 'unresolved'}
|
| 274 |
+
original[i] = row
|
| 275 |
+
rows[i] = stabilized(row, transform)
|
| 276 |
+
previous = gray; old_boxes = boxes; last = i
|
| 277 |
+
progress('candidate_visual_check', sum(r['searched'] for r in original), len(frames))
|
| 278 |
+
if last != b:
|
| 279 |
+
raise ValueError('Candidate decode incomplete')
|
| 280 |
+
complete.append(window)
|
| 281 |
+
# A supported event is an estimate in the searched window. Do not
|
| 282 |
+
# spend the remaining budget rendering or searching a silent reset.
|
| 283 |
+
result = estimate({'frames': rows}, capture)
|
| 284 |
+
if result.status == 'estimated':
|
| 285 |
+
result.reasons.append('candidate_window_search_only')
|
| 286 |
+
result.evidence.update(search_complete=False, searched_frame_count=sum(r['searched'] for r in original),
|
| 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 |
+
|
| 295 |
+
def unavailable(reason):
|
| 296 |
+
return ContactEstimate(status='unavailable', reasons=[reason], evidence={
|
| 297 |
+
'search_complete': False, 'does_not_establish_a_miss': True})
|
baseball_batting/contact_fast_worker.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resident, single-request-at-a-time GPU worker with a bounded fast decision."""
|
| 2 |
+
import argparse
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
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 |
+
|
| 16 |
+
def source_asset(job, source, checksum, expiry):
|
| 17 |
+
return {'status': 'available', 'url': '/v1/contact-analyses/'+job.name+'/artifacts/source',
|
| 18 |
+
'filename': source.name, 'format': 'original_video', 'media_type': {'.mov': 'video/quicktime',
|
| 19 |
+
'.mkv': 'video/x-matroska', '.webm': 'video/webm', '.avi': 'video/x-msvideo'}.get(source.suffix, 'video/mp4'),
|
| 20 |
+
'size_bytes': source.stat().st_size, 'sha256': checksum, 'expires_at': expiry}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def initial_result(job, options, *, retention_s=86400, started=None):
|
| 24 |
+
job = Path(job)
|
| 25 |
+
video = next(job.glob('input.*'))
|
| 26 |
+
source = job/('source'+video.suffix)
|
| 27 |
+
if not source.exists():
|
| 28 |
+
os.link(video, source)
|
| 29 |
+
# Hash computed as bytes arrived, outside GPU processing. CLI/test calls
|
| 30 |
+
# without an upload receipt calculate it here and report that elapsed time.
|
| 31 |
+
receipt = read_json(job/'upload.json') if (job/'upload.json').is_file() else {}
|
| 32 |
+
checksum = receipt.get('sha256') or sha256_file(source)
|
| 33 |
+
if receipt and receipt['size_bytes'] != source.stat().st_size:
|
| 34 |
+
raise ValueError('Upload receipt length mismatch')
|
| 35 |
+
expiry = datetime.fromtimestamp(time.time()+retention_s, timezone.utc).isoformat()
|
| 36 |
+
prefix = '/v1/contact-analyses/'+job.name+'/artifacts/'
|
| 37 |
+
artifacts = {'source': source_asset(job, source, checksum, expiry)}
|
| 38 |
+
for key, fmt, media in [('observations', 'jsonl', 'application/x-ndjson'), ('annotated', 'mp4', 'video/mp4'), ('evidence', 'mp4', 'video/mp4')]:
|
| 39 |
+
pending = options.annotated_video and key != 'observations'
|
| 40 |
+
artifacts[key] = {'status': 'pending' if pending else 'unavailable', 'url': prefix+key if pending else None,
|
| 41 |
+
'format': fmt, 'media_type': media, 'expires_at': expiry,
|
| 42 |
+
'reason_code': 'render_pending' if pending else 'not_searched' if key == 'observations' else 'not_requested'}
|
| 43 |
+
return ContactResult(job_id=job.name, contact=unavailable('processing_budget_exceeded'),
|
| 44 |
+
source_video={'sha256': checksum, 'frame_count': None, 'scan_complete': False},
|
| 45 |
+
timing={'video_time': 'source_PTS_minus_first_source_PTS', 'capture_time_available': False,
|
| 46 |
+
'mapping': options.timing.model_dump(mode='json'), 'minimum_fps_required': None,
|
| 47 |
+
'notice': 'Only selected consecutive original frames are inspected. Omitted frames are not interpolated.'},
|
| 48 |
+
pipeline={'version': VERSION, 'mode': 'fast', 'options': options.model_dump(mode='json'),
|
| 49 |
+
'processing_budget_s': options.processing_budget_s, 'deadline_scope': 'processing_after_queue_claim; upload, queue and video rendering excluded',
|
| 50 |
+
'decision_elapsed_s': None, 'requires_pose': False, 'requires_3d': False,
|
| 51 |
+
'object_gap_filling': False, 'contact_verification': 'visual_estimate_only; accuracy_unvalidated',
|
| 52 |
+
'clips': {}, 'models_warm': True},
|
| 53 |
+
audio={'status': 'not_checked', 'used_for_contact_timestamp': False}, artifacts=artifacts,
|
| 54 |
+
rendering={'status': 'pending' if options.annotated_video else 'not_requested'}, expires_at=expiry)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def decide(job, models, *, started=None, retention_s=86400, max_frames=7200, max_pixels=8294400, max_duration=120):
|
| 58 |
+
job = Path(job)
|
| 59 |
+
options = ContactInput.model_validate(read_json(job/'request.json'))
|
| 60 |
+
started = time.monotonic() if started is None else started
|
| 61 |
+
# Leave time for writing the decision and for the parent to publish it.
|
| 62 |
+
budget = Budget(max(.1, options.processing_budget_s-.2), started=started)
|
| 63 |
+
result = initial_result(job, options, retention_s=retention_s, started=started)
|
| 64 |
+
result.pipeline.update(models=models.record, device=models.device)
|
| 65 |
+
video = next(job.glob('input.*'))
|
| 66 |
+
capture = None
|
| 67 |
+
def progress(stage, done=0, total=None):
|
| 68 |
+
atomic_json(job/'progress.json', {'stage': stage, 'completed_frames': done,
|
| 69 |
+
'total_frames': total, 'elapsed_s': round(time.monotonic()-started, 3)})
|
| 70 |
+
try:
|
| 71 |
+
progress('candidate_scan')
|
| 72 |
+
capture, times, motion, ranked = scan(video, options, budget,
|
| 73 |
+
max_frames=max_frames, max_pixels=max_pixels, max_duration=max_duration)
|
| 74 |
+
capture['input_sha256'] = result.source_video['sha256']
|
| 75 |
+
atomic_json(job/'capture-private.json', capture)
|
| 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:
|
| 83 |
+
result.contact, original, checked = collect_windows(video, capture, windows, models, budget, progress)
|
| 84 |
+
else:
|
| 85 |
+
result.contact = unavailable('no_contact_search_candidate')
|
| 86 |
+
original = []; checked = []
|
| 87 |
+
if original:
|
| 88 |
+
output = job/'observations.jsonl'
|
| 89 |
+
with output.open('w') as out:
|
| 90 |
+
for frame, row in zip(capture['frames'], original):
|
| 91 |
+
out.write(json.dumps({**row, 'source_pts': frame['pts'], 'source_time_base': frame['time_base'],
|
| 92 |
+
'confidence_meaning': 'object detector scores; not contact correctness'}, allow_nan=False)+'\n')
|
| 93 |
+
result.artifacts['observations'] = ContactArtifact.model_validate({'status': 'available',
|
| 94 |
+
'url': '/v1/contact-analyses/'+job.name+'/artifacts/observations', 'filename': output.name,
|
| 95 |
+
'format': 'jsonl', 'media_type': 'application/x-ndjson', 'size_bytes': output.stat().st_size,
|
| 96 |
+
'sha256': sha256_file(output), 'expires_at': result.expires_at})
|
| 97 |
+
result.pipeline.update(windows_checked=checked, models=models.record, device=models.device,
|
| 98 |
+
searched_frame_count=sum(r.get('searched', False) for r in original))
|
| 99 |
+
if result.contact.video_time_interval_s:
|
| 100 |
+
a, b = result.contact.video_time_interval_s
|
| 101 |
+
result.audio['near_visual_contact_times_s'] = [t for t in result.audio.get('transient_video_times_s', []) if a-.03 <= t <= b+.25]
|
| 102 |
+
except BudgetExpired:
|
| 103 |
+
# A deadline is not a miss. Never choose a sound peak as a fallback hit.
|
| 104 |
+
result.contact = unavailable('processing_budget_exceeded')
|
| 105 |
+
result.pipeline['budget_exhausted'] = True
|
| 106 |
+
if capture is not None:
|
| 107 |
+
frames = capture['frames']
|
| 108 |
+
intervals = np.diff([f['playback_s'] for f in frames])*1000
|
| 109 |
+
result.source_video.update(frame_count=len(frames), scan_complete=True,
|
| 110 |
+
display_width=frames[0]['width'], display_height=frames[0]['height'],
|
| 111 |
+
rotation_degrees_applied=capture['rotation_degrees'], last_frame_video_time_s=frames[-1]['playback_s']-frames[0]['playback_s'],
|
| 112 |
+
timeline_origin_pts=frames[0]['pts'], timeline_origin_time_base=frames[0]['time_base'])
|
| 113 |
+
result.timing.update(capture_time_available=capture['physical_clock_known'],
|
| 114 |
+
minimum_frame_spacing_ms=float(intervals.min()), maximum_frame_spacing_ms=float(intervals.max()))
|
| 115 |
+
result.pipeline['decision_elapsed_s'] = round(time.monotonic()-started, 4)
|
| 116 |
+
result.pipeline['budget_exhausted'] = 'processing_budget_exceeded' in result.contact.reasons
|
| 117 |
+
atomic_json(job/'fast-result.json', result.model_dump(mode='json'))
|
| 118 |
+
return result
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def main():
|
| 122 |
+
parser = argparse.ArgumentParser()
|
| 123 |
+
parser.add_argument('--models', required=True)
|
| 124 |
+
parser.add_argument('--root', required=True)
|
| 125 |
+
args = parser.parse_args()
|
| 126 |
+
root = Path(args.root).resolve()
|
| 127 |
+
cv_threads = __import__('cv2'); cv_threads.setNumThreads(2)
|
| 128 |
+
# First-request imports are warmed outside the per-video budget, too.
|
| 129 |
+
import av
|
| 130 |
+
from scipy.signal import find_peaks
|
| 131 |
+
try:
|
| 132 |
+
models = ContactModels(args.models)
|
| 133 |
+
atomic_json(root/'contact-ready.json', {'ready': True, 'models': models.record, 'pid': os.getpid()})
|
| 134 |
+
except Exception as error:
|
| 135 |
+
atomic_json(root/'contact-ready.json', {'ready': False, 'reason': type(error).__name__})
|
| 136 |
+
raise
|
| 137 |
+
for line in sys.stdin:
|
| 138 |
+
command = json.loads(line)
|
| 139 |
+
identifier = command['job_id']
|
| 140 |
+
if len(identifier) != 32 or any(c not in '0123456789abcdef' for c in identifier):
|
| 141 |
+
raise ValueError('Invalid worker job ID')
|
| 142 |
+
job = root/'jobs'/identifier
|
| 143 |
+
try:
|
| 144 |
+
decide(job, models, **command['limits'])
|
| 145 |
+
atomic_json(job/'fast-done.json', {'ok': True})
|
| 146 |
+
except Exception as error:
|
| 147 |
+
atomic_json(job/'fast-done.json', {'ok': False, 'error_type': type(error).__name__,
|
| 148 |
+
'code': 'invalid_video_or_capture' if isinstance(error, ValueError) else 'inference_failed'})
|
| 149 |
+
print('Contact decision failed: '+type(error).__name__, file=sys.stderr, flush=True)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == '__main__':
|
| 153 |
+
main()
|
baseball_batting/contact_render_worker.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only delayed annotation of the immutable fast contact decision."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from .contact_contract import ContactResult, ContactInput
|
| 7 |
+
from .ingest import ingest
|
| 8 |
+
from .storage import atomic_json, read_json, sha256_file
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def render(job, *, max_frames=7200, max_pixels=8294400, max_duration=120):
|
| 12 |
+
import cv2
|
| 13 |
+
cv2.setNumThreads(1)
|
| 14 |
+
from .contact_videos import export
|
| 15 |
+
job = Path(job)
|
| 16 |
+
result = ContactResult.model_validate(read_json(job/'result.json'))
|
| 17 |
+
options = ContactInput.model_validate(read_json(job/'request.json'))
|
| 18 |
+
started = time.monotonic()
|
| 19 |
+
source = job/result.artifacts['source'].filename
|
| 20 |
+
if sha256_file(source) != result.artifacts['source'].sha256:
|
| 21 |
+
raise ValueError('Source failed integrity check')
|
| 22 |
+
capture_path = job/'capture-private.json'
|
| 23 |
+
capture = read_json(capture_path) if capture_path.exists() else ingest(source, options.metadata(),
|
| 24 |
+
max_frames=max_frames, max_pixels=max_pixels, max_duration_s=max_duration)
|
| 25 |
+
observations = result.artifacts['observations']
|
| 26 |
+
if observations.status == 'available':
|
| 27 |
+
path = job/observations.filename
|
| 28 |
+
if sha256_file(path) != observations.sha256:
|
| 29 |
+
raise ValueError('Observations failed integrity check')
|
| 30 |
+
rows = [json.loads(line) for line in path.read_text().splitlines()]
|
| 31 |
+
if len(rows) != len(capture['frames']):
|
| 32 |
+
raise ValueError('Source and observation lengths differ')
|
| 33 |
+
else:
|
| 34 |
+
rows = [{'bat': [], 'ball': [], 'searched': False} for _ in capture['frames']]
|
| 35 |
+
artifacts = {}
|
| 36 |
+
try:
|
| 37 |
+
clips = export(source, capture, rows, result.contact, job)
|
| 38 |
+
for name in ('annotated', 'evidence'):
|
| 39 |
+
if name in clips:
|
| 40 |
+
path = job/(name+'.mp4')
|
| 41 |
+
artifacts[name] = {'status': 'available', 'url': '/v1/contact-analyses/'+job.name+'/artifacts/'+name,
|
| 42 |
+
'filename': path.name, 'format': 'mp4', 'media_type': 'video/mp4', 'size_bytes': path.stat().st_size,
|
| 43 |
+
'sha256': sha256_file(path), 'expires_at': result.expires_at}
|
| 44 |
+
else:
|
| 45 |
+
artifacts[name] = {'status': 'unavailable', 'format': 'mp4', 'media_type': 'video/mp4',
|
| 46 |
+
'reason_code': 'contact_not_located', 'expires_at': result.expires_at}
|
| 47 |
+
rendering = {'status': 'completed', 'elapsed_s': round(time.monotonic()-started, 3),
|
| 48 |
+
'observation_scope': 'selected candidate windows; unsearched frames have no invented annotations'}
|
| 49 |
+
except Exception as error:
|
| 50 |
+
from .swing_clips import ClipError
|
| 51 |
+
reason = str(error) if isinstance(error, ClipError) else 'video_render_failed'
|
| 52 |
+
clips = {}
|
| 53 |
+
rendering = {'status': 'failed', 'reason_code': reason}
|
| 54 |
+
for name in ('annotated', 'evidence'):
|
| 55 |
+
artifacts[name] = {'status': 'unavailable', 'format': 'mp4', 'media_type': 'video/mp4',
|
| 56 |
+
'reason_code': reason, 'expires_at': result.expires_at}
|
| 57 |
+
value = {'artifacts': artifacts, 'clips': clips, 'rendering': rendering}
|
| 58 |
+
atomic_json(job/'render-outcome.json', value)
|
| 59 |
+
return value
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
parser = argparse.ArgumentParser()
|
| 64 |
+
parser.add_argument('--job', required=True)
|
| 65 |
+
parser.add_argument('--max-frames', type=int, default=7200)
|
| 66 |
+
parser.add_argument('--max-pixels', type=int, default=8294400)
|
| 67 |
+
parser.add_argument('--max-duration', type=float, default=120)
|
| 68 |
+
args = parser.parse_args()
|
| 69 |
+
render(args.job, max_frames=args.max_frames, max_pixels=args.max_pixels, max_duration=args.max_duration)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == '__main__':
|
| 73 |
+
main()
|
baseball_batting/contact_runtime.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parent-side supervision of a warm, isolated contact process.
|
| 2 |
+
|
| 3 |
+
The existing GPU queue remains the single owner of inference. It can kill a
|
| 4 |
+
stuck decision at its budget, rewarm later, and publish an honest unknown.
|
| 5 |
+
"""
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import signal
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from .contact_contract import ContactInput, ContactResult
|
| 14 |
+
from .storage import atomic_json, read_json, sha256_file
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ResidentContact:
|
| 18 |
+
def __init__(self, service):
|
| 19 |
+
self.service = service
|
| 20 |
+
self.process = None
|
| 21 |
+
self.record = {}
|
| 22 |
+
self.reason = 'warming'
|
| 23 |
+
self.retry_after = 0.
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def ready(self):
|
| 27 |
+
return self.process is not None and self.process.poll() is None and self.record.get('ready') is True
|
| 28 |
+
|
| 29 |
+
def start(self):
|
| 30 |
+
if self.ready or time.monotonic() < self.retry_after:
|
| 31 |
+
return
|
| 32 |
+
self.stop()
|
| 33 |
+
s = self.service
|
| 34 |
+
path = s.settings.data_root/'contact-ready.json'
|
| 35 |
+
path.unlink(missing_ok=True)
|
| 36 |
+
self.reason = 'warming'
|
| 37 |
+
with (s.settings.data_root/'contact-resident.log').open('ab') as log:
|
| 38 |
+
self.process = subprocess.Popen([sys.executable, '-m', 'baseball_batting.contact_fast_worker',
|
| 39 |
+
'--models', str(s.settings.model_root), '--root', str(s.settings.data_root)],
|
| 40 |
+
stdin=subprocess.PIPE, stdout=log, stderr=log, text=True, bufsize=1,
|
| 41 |
+
env=s.environment(), start_new_session=True)
|
| 42 |
+
started = time.monotonic()
|
| 43 |
+
while self.process.poll() is None:
|
| 44 |
+
if s.stopping.wait(.05) or time.monotonic()-started > 180:
|
| 45 |
+
self.stop(); self.reason = 'warmup_interrupted'
|
| 46 |
+
self.retry_after = time.monotonic()+30
|
| 47 |
+
return
|
| 48 |
+
if path.is_file():
|
| 49 |
+
self.record = read_json(path)
|
| 50 |
+
if self.record.get('ready'):
|
| 51 |
+
self.reason = 'ready'
|
| 52 |
+
return
|
| 53 |
+
break
|
| 54 |
+
self.stop(); self.reason = 'warmup_failed'
|
| 55 |
+
self.retry_after = time.monotonic()+30
|
| 56 |
+
|
| 57 |
+
def stop(self, *, immediate=False):
|
| 58 |
+
from .api_jobs import stop_process
|
| 59 |
+
if self.process is not None:
|
| 60 |
+
if immediate and self.process.poll() is None:
|
| 61 |
+
try:
|
| 62 |
+
os.killpg(self.process.pid, signal.SIGKILL)
|
| 63 |
+
self.process.wait(timeout=1)
|
| 64 |
+
except ProcessLookupError:
|
| 65 |
+
pass
|
| 66 |
+
else:
|
| 67 |
+
stop_process(self.process)
|
| 68 |
+
if self.process.stdin:
|
| 69 |
+
self.process.stdin.close()
|
| 70 |
+
self.process = None
|
| 71 |
+
self.record = {}
|
| 72 |
+
self.reason = 'not_loaded'
|
| 73 |
+
|
| 74 |
+
def execute(self, identifier):
|
| 75 |
+
started = time.monotonic()
|
| 76 |
+
from .contact_fast_worker import initial_result
|
| 77 |
+
s = self.service
|
| 78 |
+
directory = s.job_directory(identifier)
|
| 79 |
+
options = ContactInput.model_validate(read_json(directory/'request.json'))
|
| 80 |
+
fallback = initial_result(directory, options, retention_s=s.settings.retention_s)
|
| 81 |
+
fallback.pipeline.update(models=self.record.get('models', {}), device='cuda')
|
| 82 |
+
for name in ('fast-done.json', 'fast-result.json'):
|
| 83 |
+
(directory/name).unlink(missing_ok=True)
|
| 84 |
+
limits = {'started': started, 'retention_s': s.settings.retention_s,
|
| 85 |
+
'max_frames': s.settings.max_frames, 'max_pixels': s.settings.max_pixels,
|
| 86 |
+
'max_duration': s.settings.max_duration_s}
|
| 87 |
+
done = directory/'fast-done.json'
|
| 88 |
+
outcome = None
|
| 89 |
+
if not self.ready:
|
| 90 |
+
fallback.contact.reasons = ['fast_worker_unavailable']
|
| 91 |
+
fallback.pipeline['models_warm'] = False
|
| 92 |
+
else:
|
| 93 |
+
try:
|
| 94 |
+
self.process.stdin.write(json.dumps({'job_id': identifier, 'limits': limits})+'\n')
|
| 95 |
+
self.process.stdin.flush()
|
| 96 |
+
while time.monotonic()-started < options.processing_budget_s-.05:
|
| 97 |
+
row = s.store.get(identifier)
|
| 98 |
+
if row['status'] == 'cancel_requested':
|
| 99 |
+
self.stop(immediate=True)
|
| 100 |
+
with s.mutation_lock:
|
| 101 |
+
s.store.update(identifier, 'cancelled')
|
| 102 |
+
__import__('shutil').rmtree(directory, ignore_errors=True)
|
| 103 |
+
return
|
| 104 |
+
if s.stopping.is_set():
|
| 105 |
+
self.stop(immediate=True)
|
| 106 |
+
with s.mutation_lock:
|
| 107 |
+
s.store.update(identifier, 'queued')
|
| 108 |
+
return
|
| 109 |
+
if done.is_file():
|
| 110 |
+
outcome = read_json(done)
|
| 111 |
+
break
|
| 112 |
+
if self.process.poll() is not None:
|
| 113 |
+
fallback.contact.reasons = ['fast_worker_exited']
|
| 114 |
+
self.stop()
|
| 115 |
+
break
|
| 116 |
+
time.sleep(.005)
|
| 117 |
+
if outcome is None and self.process is not None and self.process.poll() is None:
|
| 118 |
+
self.stop(immediate=True)
|
| 119 |
+
self.reason = 'rewarming_after_deadline'
|
| 120 |
+
except (OSError, BrokenPipeError):
|
| 121 |
+
self.stop(immediate=True)
|
| 122 |
+
fallback.contact.reasons = ['fast_worker_exited']
|
| 123 |
+
if outcome and not outcome['ok']:
|
| 124 |
+
atomic_json(directory/'error.json', {'code': outcome['code'], 'error_type': outcome.get('error_type')})
|
| 125 |
+
s.finish_failed(identifier, directory, outcome['code'])
|
| 126 |
+
return
|
| 127 |
+
result = ContactResult.model_validate(read_json(directory/'fast-result.json')) if outcome else fallback
|
| 128 |
+
elapsed = time.monotonic()-started
|
| 129 |
+
result.pipeline.update(decision_elapsed_s=round(elapsed, 4),
|
| 130 |
+
budget_exhausted='processing_budget_exceeded' in result.contact.reasons,
|
| 131 |
+
deadline_met=elapsed <= options.processing_budget_s)
|
| 132 |
+
with s.mutation_lock:
|
| 133 |
+
if s.store.get(identifier)['status'] == 'cancel_requested':
|
| 134 |
+
s.store.update(identifier, 'cancelled')
|
| 135 |
+
__import__('shutil').rmtree(directory, ignore_errors=True)
|
| 136 |
+
return
|
| 137 |
+
atomic_json(directory/'result.json', result.model_dump(mode='json'))
|
| 138 |
+
s.store.update(identifier, 'completed', result_hash=sha256_file(directory/'result.json'))
|
| 139 |
+
atomic_json(directory/'progress.json', {'stage': 'decision_complete',
|
| 140 |
+
'elapsed_s': round(time.monotonic()-started, 4), 'video_rendering': result.rendering['status']})
|
| 141 |
+
s.render_wakeup.set()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def render_loop(service):
|
| 145 |
+
"""CPU-only render queue; publishing never changes the contact decision."""
|
| 146 |
+
from .api_jobs import stop_process
|
| 147 |
+
while not service.stopping.is_set():
|
| 148 |
+
for identifier in service.store.completed_contacts():
|
| 149 |
+
if service.stopping.is_set():
|
| 150 |
+
return
|
| 151 |
+
directory = service.job_directory(identifier)
|
| 152 |
+
with service.mutation_lock:
|
| 153 |
+
row = service.store.get(identifier)
|
| 154 |
+
path = directory/'result.json'
|
| 155 |
+
if not row or row['status'] != 'completed' or row.get('contact_artifacts_sha256') or not path.is_file():
|
| 156 |
+
continue
|
| 157 |
+
if sha256_file(path) != row['result_sha256']:
|
| 158 |
+
continue
|
| 159 |
+
result = read_json(path)
|
| 160 |
+
if result.get('rendering', {}).get('status') != 'pending':
|
| 161 |
+
continue
|
| 162 |
+
command = [sys.executable, '-m', 'baseball_batting.contact_render_worker', '--job', str(directory),
|
| 163 |
+
'--max-frames', str(service.settings.max_frames), '--max-pixels', str(service.settings.max_pixels),
|
| 164 |
+
'--max-duration', str(service.settings.max_duration_s)]
|
| 165 |
+
process = service.launch(command, directory/'render.log')
|
| 166 |
+
service.render_process, service.render_identifier = process, identifier
|
| 167 |
+
started = time.monotonic()
|
| 168 |
+
timeout = min(180., service.settings.job_timeout_s)
|
| 169 |
+
while process.poll() is None:
|
| 170 |
+
current = service.store.get(identifier)
|
| 171 |
+
if service.stopping.wait(.05) or not current or current['status'] != 'completed' or time.monotonic()-started > timeout:
|
| 172 |
+
stop_process(process)
|
| 173 |
+
break
|
| 174 |
+
with service.mutation_lock:
|
| 175 |
+
service.render_process = service.render_identifier = None
|
| 176 |
+
current = service.store.get(identifier)
|
| 177 |
+
if not current or current['status'] != 'completed' or service.stopping.is_set():
|
| 178 |
+
continue
|
| 179 |
+
# Verify the decision again; never overwrite a tampered result.
|
| 180 |
+
if not path.is_file() or sha256_file(path) != current['result_sha256']:
|
| 181 |
+
continue
|
| 182 |
+
outcome_path = directory/'render-outcome.json'
|
| 183 |
+
outcome = read_json(outcome_path) if outcome_path.is_file() and process.returncode == 0 else None
|
| 184 |
+
if outcome:
|
| 185 |
+
result['artifacts'].update(outcome['artifacts'])
|
| 186 |
+
result['pipeline']['clips'] = outcome['clips']
|
| 187 |
+
result['rendering'] = outcome['rendering']
|
| 188 |
+
else:
|
| 189 |
+
result['rendering'] = {'status': 'failed', 'reason_code': 'video_render_failed'}
|
| 190 |
+
for name in ('annotated', 'evidence'):
|
| 191 |
+
if result['artifacts'][name]['status'] == 'pending':
|
| 192 |
+
result['artifacts'][name].update(status='unavailable', reason_code='video_render_failed')
|
| 193 |
+
result['artifacts_revision'] = result.get('artifacts_revision', 0)+1
|
| 194 |
+
validated = ContactResult.model_validate(result)
|
| 195 |
+
# The base decision never changes. Persist first, then atomically
|
| 196 |
+
# switch the SQLite pointer: a restart cannot expose a new file
|
| 197 |
+
# with an old checksum between these two operations.
|
| 198 |
+
snapshot = directory/'rendered-result.json'
|
| 199 |
+
atomic_json(snapshot, validated.model_dump(mode='json'))
|
| 200 |
+
service.store.update_contact_artifacts(identifier, sha256_file(snapshot))
|
| 201 |
+
service.render_wakeup.wait(.2)
|
| 202 |
+
service.render_wakeup.clear()
|
baseball_batting/contact_videos.py
CHANGED
|
@@ -17,6 +17,10 @@ def draw(image, row, contact, index):
|
|
| 17 |
cv2.circle(image,tuple(np.rint(ball['point']).astype(int)),max(3,round(ball['radius_px'])),(20,220,255),thickness,cv2.LINE_AA)
|
| 18 |
active=contact.frame_interval is not None and contact.frame_interval[0]<=index<=contact.frame_interval[1]
|
| 19 |
text='CONTACT ESTIMATE' if active else 'Bat/ball observations' if contact.status=='estimated' else 'Contact not located'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
cv2.putText(image,text,(12,32*thickness),cv2.FONT_HERSHEY_SIMPLEX,.7*thickness,
|
| 21 |
(30,220,255) if active else (230,230,230),thickness,cv2.LINE_AA)
|
| 22 |
return image
|
|
|
|
| 17 |
cv2.circle(image,tuple(np.rint(ball['point']).astype(int)),max(3,round(ball['radius_px'])),(20,220,255),thickness,cv2.LINE_AA)
|
| 18 |
active=contact.frame_interval is not None and contact.frame_interval[0]<=index<=contact.frame_interval[1]
|
| 19 |
text='CONTACT ESTIMATE' if active else 'Bat/ball observations' if contact.status=='estimated' else 'Contact not located'
|
| 20 |
+
if row.get('searched') is False:
|
| 21 |
+
text='Outside searched contact windows'
|
| 22 |
+
cv2.putText(image,text,(12,32*thickness),cv2.FONT_HERSHEY_SIMPLEX,.7*thickness,
|
| 23 |
+
(15,15,15),thickness+3,cv2.LINE_AA)
|
| 24 |
cv2.putText(image,text,(12,32*thickness),cv2.FONT_HERSHEY_SIMPLEX,.7*thickness,
|
| 25 |
(30,220,255) if active else (230,230,230),thickness,cv2.LINE_AA)
|
| 26 |
return image
|
baseball_batting/contact_worker.py
CHANGED
|
@@ -18,6 +18,17 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 18 |
from .contact_videos import export
|
| 19 |
from .swing_clips import ClipError
|
| 20 |
job=Path(job);options=ContactInput.model_validate(read_json(job/'request.json'));started=time.monotonic()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
def progress(stage,done=0,total=None):
|
| 22 |
atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
|
| 23 |
'elapsed_s':round(time.monotonic()-started,2)})
|
|
@@ -70,7 +81,8 @@ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retenti
|
|
| 70 |
'minimum_frame_spacing_ms':float(np.diff(playback).min()*1000),
|
| 71 |
'maximum_frame_spacing_ms':float(np.diff(playback).max()*1000),
|
| 72 |
'notice':'Fitted subframe time is an estimate. Frame spacing and transition interval limit timing resolution.'},
|
| 73 |
-
|
|
|
|
| 74 |
'implementation_sha256':{name:sha256_file(Path(__file__).with_name(name)) for name in
|
| 75 |
('contact_worker.py','contact_contract.py','contact_detection.py','contact_vision.py',
|
| 76 |
'contact_audio.py','contact_videos.py','bat_ball_timing.py','tracking_vision.py','detection.py','ingest.py')},
|
|
|
|
| 18 |
from .contact_videos import export
|
| 19 |
from .swing_clips import ClipError
|
| 20 |
job=Path(job);options=ContactInput.model_validate(read_json(job/'request.json'));started=time.monotonic()
|
| 21 |
+
if options.mode=='fast':
|
| 22 |
+
# Standalone CLI use; the server instead reuses ContactModels in its
|
| 23 |
+
# resident process. Make cold startup explicit in offline provenance.
|
| 24 |
+
from .contact_fast import ContactModels
|
| 25 |
+
from .contact_fast_worker import decide
|
| 26 |
+
warmed=ContactModels(models,device)
|
| 27 |
+
result=decide(job,warmed,retention_s=retention_s,max_frames=max_frames,
|
| 28 |
+
max_pixels=max_pixels,max_duration=max_duration)
|
| 29 |
+
result.pipeline.update(cold_start_s=round(time.monotonic()-started-result.pipeline['decision_elapsed_s'],4))
|
| 30 |
+
atomic_json(job/'result.json',result.model_dump(mode='json'))
|
| 31 |
+
return result
|
| 32 |
def progress(stage,done=0,total=None):
|
| 33 |
atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
|
| 34 |
'elapsed_s':round(time.monotonic()-started,2)})
|
|
|
|
| 81 |
'minimum_frame_spacing_ms':float(np.diff(playback).min()*1000),
|
| 82 |
'maximum_frame_spacing_ms':float(np.diff(playback).max()*1000),
|
| 83 |
'notice':'Fitted subframe time is an estimate. Frame spacing and transition interval limit timing resolution.'},
|
| 84 |
+
rendering={'status':'completed' if options.annotated_video and clips else 'failed' if video_export_reason else 'not_requested'},
|
| 85 |
+
pipeline={'version':VERSION,'mode':'full','device':device,'models':model,'options':options.model_dump(mode='json'),
|
| 86 |
'implementation_sha256':{name:sha256_file(Path(__file__).with_name(name)) for name in
|
| 87 |
('contact_worker.py','contact_contract.py','contact_detection.py','contact_vision.py',
|
| 88 |
'contact_audio.py','contact_videos.py','bat_ball_timing.py','tracking_vision.py','detection.py','ingest.py')},
|
baseball_batting/detection.py
CHANGED
|
@@ -75,12 +75,12 @@ def ort_session(path, device):
|
|
| 75 |
"Check GPU runtime and CUDA/cuDNN libraries; rerun vision preflight.")
|
| 76 |
return session
|
| 77 |
|
| 78 |
-
def verify_cuda_nodes(session):
|
| 79 |
"""Provider registration alone is not proof that CUDA actually executed an operator."""
|
| 80 |
path = Path(session.end_profiling())
|
| 81 |
try:
|
| 82 |
events = json.loads(path.read_text())
|
| 83 |
-
if not any(e.get("args", {}).get("provider")
|
| 84 |
raise RuntimeError("No CUDA operator execution was observed in ONNX profiling")
|
| 85 |
finally:
|
| 86 |
path.unlink(missing_ok=True)
|
|
|
|
| 75 |
"Check GPU runtime and CUDA/cuDNN libraries; rerun vision preflight.")
|
| 76 |
return session
|
| 77 |
|
| 78 |
+
def verify_cuda_nodes(session, *, providers=('CUDAExecutionProvider',)):
|
| 79 |
"""Provider registration alone is not proof that CUDA actually executed an operator."""
|
| 80 |
path = Path(session.end_profiling())
|
| 81 |
try:
|
| 82 |
events = json.loads(path.read_text())
|
| 83 |
+
if not any(e.get("args", {}).get("provider") in providers for e in events):
|
| 84 |
raise RuntimeError("No CUDA operator execution was observed in ONNX profiling")
|
| 85 |
finally:
|
| 86 |
path.unlink(missing_ok=True)
|
baseball_batting/tracking_vision.py
CHANGED
|
@@ -11,13 +11,13 @@ from .storage import sha256_file
|
|
| 11 |
|
| 12 |
|
| 13 |
class TrackingModel:
|
| 14 |
-
def __init__(self, root, name, device='cuda'):
|
| 15 |
folder = Path(root)/('tracking_'+name)
|
| 16 |
self.record = json.loads((folder/'model.json').read_text())
|
| 17 |
path = folder/'model.onnx'
|
| 18 |
if sha256_file(path) != self.record['onnx_sha256']:
|
| 19 |
raise ValueError(f'{name} ONNX checksum mismatch')
|
| 20 |
-
self.session = ort_session(path, device)
|
| 21 |
self.size = self.record['input_size']
|
| 22 |
self.name, self.device, self.verified = name, device, False
|
| 23 |
if self.session.get_inputs()[0].shape != [1, 3, self.size, self.size]:
|
|
@@ -39,7 +39,7 @@ class TrackingModel:
|
|
| 39 |
tensor = np.ascontiguousarray(canvas[..., ::-1].transpose(2, 0, 1)[None], dtype=np.float32)/255
|
| 40 |
output = self.session.run(None, {self.session.get_inputs()[0].name: tensor})[0]
|
| 41 |
if self.device == 'cuda' and not self.verified:
|
| 42 |
-
verify_cuda_nodes(self.session)
|
| 43 |
self.verified = True
|
| 44 |
p = np.asarray(output)[0].T
|
| 45 |
count = self.record['keypoint_shape'][0] if self.name == 'bat' else 0
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
class TrackingModel:
|
| 14 |
+
def __init__(self, root, name, device='cuda', *, session_factory=None):
|
| 15 |
folder = Path(root)/('tracking_'+name)
|
| 16 |
self.record = json.loads((folder/'model.json').read_text())
|
| 17 |
path = folder/'model.onnx'
|
| 18 |
if sha256_file(path) != self.record['onnx_sha256']:
|
| 19 |
raise ValueError(f'{name} ONNX checksum mismatch')
|
| 20 |
+
self.session = (session_factory or ort_session)(path, device)
|
| 21 |
self.size = self.record['input_size']
|
| 22 |
self.name, self.device, self.verified = name, device, False
|
| 23 |
if self.session.get_inputs()[0].shape != [1, 3, self.size, self.size]:
|
|
|
|
| 39 |
tensor = np.ascontiguousarray(canvas[..., ::-1].transpose(2, 0, 1)[None], dtype=np.float32)/255
|
| 40 |
output = self.session.run(None, {self.session.get_inputs()[0].name: tensor})[0]
|
| 41 |
if self.device == 'cuda' and not self.verified:
|
| 42 |
+
verify_cuda_nodes(self.session, providers=('CUDAExecutionProvider', 'TensorrtExecutionProvider'))
|
| 43 |
self.verified = True
|
| 44 |
p = np.asarray(output)[0].T
|
| 45 |
count = self.record['keypoint_shape'][0] if self.name == 'bat' else 0
|
docs/CONTACT_API.md
CHANGED
|
@@ -37,6 +37,8 @@ Optional `options` is a **Text** field containing JSON:
|
|
| 37 |
|
| 38 |
```json
|
| 39 |
{
|
|
|
|
|
|
|
| 40 |
"annotated_video": true,
|
| 41 |
"use_audio": true,
|
| 42 |
"timing": {"kind": "unknown"}
|
|
@@ -56,11 +58,81 @@ If original speed is documented, the existing timing structure is supported:
|
|
| 56 |
Documented constant slowdown and explicit per-frame physical-time maps are also
|
| 57 |
supported. Video-only uploads remain usable with unknown physical time.
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
The queue shares the existing GPU service and cancellation/retention machinery.
|
| 60 |
The bat and ball models must pass CUDA preflight. Defaults are 512 MiB upload,
|
| 61 |
120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
|
| 62 |
server settings. A high-frame-rate clip can reach the frame cap sooner; there is
|
| 63 |
-
no minimum-FPS rule
|
|
|
|
| 64 |
Retention depends on the server's storage: an ephemeral Space rebuild can remove
|
| 65 |
jobs earlier. Your app should retain completed report assets in its own storage.
|
| 66 |
|
|
@@ -101,12 +173,13 @@ disappearing, a bat/ball projected overlap, or an arm-extension pose is insuffic
|
|
| 101 |
|
| 102 |
## Artifacts and evidence playback
|
| 103 |
|
| 104 |
-
Follow `result.artifacts[name].url` only when its status is `available`
|
|
|
|
| 105 |
|
| 106 |
| Name | Content |
|
| 107 |
| --- | --- |
|
| 108 |
| `source` | Original uploaded video, unchanged bytes and original audio. |
|
| 109 |
-
| `observations` | JSONL of actual bat/ball detections in upright original-image pixels, source indices/PTS and camera continuity status. No filled object tracks. |
|
| 110 |
| `annotated` | Full silent H.264 video with bat lines, ball circles and an estimated-contact interval highlight. Available even if contact is unknown when requested. |
|
| 111 |
| `evidence` | Short annotated clip surrounding a located contact interval; unavailable when no contact is located. |
|
| 112 |
|
|
@@ -120,7 +193,7 @@ clip playback time to locate the corresponding source video position.
|
|
| 120 |
The result also includes source orientation, frame count and hash; timestamp
|
| 121 |
spacing; actual model/checkpoint hashes and implementation hashes; and optional
|
| 122 |
embedded-audio diagnostics. Audio transients can corroborate a visual estimate.
|
| 123 |
-
They never establish contact, change its timestamp, or convert an unknown result
|
| 124 |
into a hit. Sounds may be unrelated, delayed, or offset by editing.
|
| 125 |
|
| 126 |
## Detection and validation limits
|
|
@@ -144,6 +217,9 @@ Common unavailable reasons:
|
|
| 144 |
- `ball_unobserved`
|
| 145 |
- `contact_evidence_insufficient`
|
| 146 |
- `multiple_contact_candidates`
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
A job completes successfully with unavailable contact when detection is uncertain.
|
| 149 |
If source timing cannot support a faithful annotation export (for example, a
|
|
|
|
| 37 |
|
| 38 |
```json
|
| 39 |
{
|
| 40 |
+
"mode": "fast",
|
| 41 |
+
"processing_budget_s": 5,
|
| 42 |
"annotated_video": true,
|
| 43 |
"use_audio": true,
|
| 44 |
"timing": {"kind": "unknown"}
|
|
|
|
| 58 |
Documented constant slowdown and explicit per-frame physical-time maps are also
|
| 59 |
supported. Video-only uploads remain usable with unknown physical time.
|
| 60 |
|
| 61 |
+
### Fast processing and video delivery (API 1.16.0)
|
| 62 |
+
|
| 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;
|
| 74 |
+
the parent process also supervises and kills a stuck GPU/decoder request. On
|
| 75 |
+
expiry a successful job returns unavailable contact with
|
| 76 |
+
`reasons: ["processing_budget_exceeded"]`, **not a fabricated hit or a miss**.
|
| 77 |
+
It may leave source-video frame count/clock details unknown if the scan did not
|
| 78 |
+
finish. This is a bounded attempt, not a guarantee of finding contact in five
|
| 79 |
+
seconds. The reported `pipeline.decision_elapsed_s`, `deadline_met` and
|
| 80 |
+
`budget_exhausted` expose the observed behavior; OS/storage stalls can overrun.
|
| 81 |
+
|
| 82 |
+
The budget starts when a warm worker claims the job. It **excludes upload,
|
| 83 |
+
queue wait, model warmup and annotation rendering**. The shared GPU queue is
|
| 84 |
+
unchanged. Warmup has its own readiness state; a fast upload during rewarm returns
|
| 85 |
+
503 `fast_worker_warming` and `Retry-After: 2`. Heavy SAM/GVHMR jobs release the
|
| 86 |
+
contact models' GPU memory; the worker warms again before the next fast request.
|
| 87 |
+
There is no five-second end-to-end guarantee for arbitrary uploads or concurrent
|
| 88 |
+
traffic. Inspect `GET /v1/contact-analyses/capabilities` before offering that SLA.
|
| 89 |
+
|
| 90 |
+
The initial completed result can have:
|
| 91 |
+
|
| 92 |
+
```json
|
| 93 |
+
{
|
| 94 |
+
"schema_version": "1.1",
|
| 95 |
+
"rendering": {"status": "pending"},
|
| 96 |
+
"artifacts_revision": 0,
|
| 97 |
+
"artifacts": {
|
| 98 |
+
"annotated": {"status": "pending", "reason_code": "render_pending"}
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
This is a partial response excerpt, not a complete result. Display the contact
|
| 104 |
+
JSON immediately. Poll the **same result URL** until `rendering.status` is
|
| 105 |
+
`completed` or `failed`. A pending artifact URL returns 202 with `Retry-After: 1`;
|
| 106 |
+
only play/download it after its status is `available`. A CPU-only background
|
| 107 |
+
process renders the videos without holding the GPU queue. Publication increments
|
| 108 |
+
`artifacts_revision`, saves an immutable rendered snapshot, then atomically
|
| 109 |
+
switches its SQLite checksum pointer under the download lock. The original
|
| 110 |
+
decision file never changes; a restart between saving and publication still
|
| 111 |
+
serves a consistent previous result. Contact/timing fields are checked against
|
| 112 |
+
the base decision on reads and never change during rendering.
|
| 113 |
+
Restart resumes pending renders; cancellation/deletion stops their process.
|
| 114 |
+
`annotated_video: false` skips rendering entirely.
|
| 115 |
+
|
| 116 |
+
Use `"mode": "full"` to retain the previous exhaustive scan and synchronous
|
| 117 |
+
annotation behavior. The five-second processing budget applies only to `fast`.
|
| 118 |
+
Existing version-1.0 stored results remain readable. Motion/product/coaching
|
| 119 |
+
endpoints and their schemas are unchanged.
|
| 120 |
+
|
| 121 |
+
CUDA is the default backend in the current Docker image. The resident tracking
|
| 122 |
+
adapter can use TensorRT FP16 when a compatible TensorRT Python/runtime package
|
| 123 |
+
is installed (`BASEBALL_CONTACT_TENSORRT=auto`, or `0` to disable). Compilation
|
| 124 |
+
and cache initialization happen during warmup, not per request. The cache path
|
| 125 |
+
is `BASEBALL_CONTACT_ENGINE_CACHE`, default `/data/contact-engines`. Models report
|
| 126 |
+
their actual ONNX providers and executed GPU operators are checked. The base
|
| 127 |
+
image does not install TensorRT; this release must not be described as a measured
|
| 128 |
+
TensorRT speedup.
|
| 129 |
+
|
| 130 |
The queue shares the existing GPU service and cancellation/retention machinery.
|
| 131 |
The bat and ball models must pass CUDA preflight. Defaults are 512 MiB upload,
|
| 132 |
120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
|
| 133 |
server settings. A high-frame-rate clip can reach the frame cap sooner; there is
|
| 134 |
+
no minimum-FPS rule. Full mode examines every frame; fast mode inspects selected
|
| 135 |
+
consecutive windows without resampling their timestamps or filling omitted data.
|
| 136 |
Retention depends on the server's storage: an ephemeral Space rebuild can remove
|
| 137 |
jobs earlier. Your app should retain completed report assets in its own storage.
|
| 138 |
|
|
|
|
| 173 |
|
| 174 |
## Artifacts and evidence playback
|
| 175 |
|
| 176 |
+
Follow `result.artifacts[name].url` for playback only when its status is `available`;
|
| 177 |
+
`pending` means the background render has not published it yet:
|
| 178 |
|
| 179 |
| Name | Content |
|
| 180 |
| --- | --- |
|
| 181 |
| `source` | Original uploaded video, unchanged bytes and original audio. |
|
| 182 |
+
| `observations` | JSONL of actual bat/ball detections in upright original-image pixels, source indices/PTS and camera continuity status. Fast mode marks omitted frames `searched: false`; empty detections there do not establish absence. No filled object tracks. |
|
| 183 |
| `annotated` | Full silent H.264 video with bat lines, ball circles and an estimated-contact interval highlight. Available even if contact is unknown when requested. |
|
| 184 |
| `evidence` | Short annotated clip surrounding a located contact interval; unavailable when no contact is located. |
|
| 185 |
|
|
|
|
| 193 |
The result also includes source orientation, frame count and hash; timestamp
|
| 194 |
spacing; actual model/checkpoint hashes and implementation hashes; and optional
|
| 195 |
embedded-audio diagnostics. Audio transients can corroborate a visual estimate.
|
| 196 |
+
In fast mode they also propose search windows. They never establish contact, change its timestamp, or convert an unknown result
|
| 197 |
into a hit. Sounds may be unrelated, delayed, or offset by editing.
|
| 198 |
|
| 199 |
## Detection and validation limits
|
|
|
|
| 217 |
- `ball_unobserved`
|
| 218 |
- `contact_evidence_insufficient`
|
| 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.
|
| 225 |
If source timing cannot support a faithful annotation export (for example, a
|
docs/CONTACT_VALIDATION.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contact API verification — 21 October 2026
|
| 2 |
+
|
| 3 |
+
The endpoint is implemented and deployed. Its pretrained detectors **did not
|
| 4 |
+
locate a supported contact interval in either supplied real test recording**.
|
| 5 |
+
This release must not be described as validated contact timing or as having
|
| 6 |
+
solved contact detection on the user's phone footage.
|
| 7 |
+
|
| 8 |
+
## Implementation checks
|
| 9 |
+
|
| 10 |
+
- 38 focused contact checks passed, including constructed moving-ball and tee
|
| 11 |
+
interactions at 12, 15, 23.976, 25, 29.97, 30, 60, 120 and 240 FPS, variable
|
| 12 |
+
cadence, unknown capture time, physical-time mappings, missing/ambiguous
|
| 13 |
+
observations, camera continuity, optional audio and incomplete annotation timing.
|
| 14 |
+
- 63 targeted contact/existing API regression checks passed after the final fix.
|
| 15 |
+
- The complete engine/coach GitHub CI and deployment passed for code revision
|
| 16 |
+
`4cf3b4d`. The separate local coach suite passed 495 tests, with 12 live tests
|
| 17 |
+
deselected.
|
| 18 |
+
- Positive endpoint tests use constructed object observations with actual media
|
| 19 |
+
decoding, queue execution, authentication, JSON persistence and video export.
|
| 20 |
+
Those tests establish implementation behavior, not pretrained-detector accuracy.
|
| 21 |
+
|
| 22 |
+
## Real NVIDIA T4 endpoint checks
|
| 23 |
+
|
| 24 |
+
Both uploads sent **only the multipart `video` field** to the new API. No FPS,
|
| 25 |
+
capture-clock declaration, manual event frame, practice label, height, pose or
|
| 26 |
+
camera calibration was supplied.
|
| 27 |
+
|
| 28 |
+
| Recording | Source frames | Frames with bat endpoints | Frames with ball candidates | Worker time | Contact result |
|
| 29 |
+
| --- | ---: | ---: | ---: | ---: | --- |
|
| 30 |
+
| `tee-_walk_through (1080p).mp4` | 117 | 59 | 23 | 210.47 s | unavailable: `contact_evidence_insufficient` |
|
| 31 |
+
| `swing1 (1).mp4` | 158 | 63 | 59 | 180.25 s | unavailable: `contact_evidence_insufficient` |
|
| 32 |
+
|
| 33 |
+
These candidate counts are model outputs, **not true-positive counts**. Neither
|
| 34 |
+
recording supplied consistent observed ball branches through the interaction.
|
| 35 |
+
The tee check also showed missing bat endpoints around the swing. The engine did
|
| 36 |
+
not insert positions, lower a per-video threshold, use the old arm-extension
|
| 37 |
+
proxy, or choose an audio impulse to force a contact result.
|
| 38 |
+
|
| 39 |
+
For both completed GPU jobs:
|
| 40 |
+
|
| 41 |
+
- The result reports CUDA execution; the model adapter checks actual CUDA nodes.
|
| 42 |
+
- Source and observation files and the annotated MP4 passed manifest size/SHA checks.
|
| 43 |
+
- The annotated video retained every source frame and its playback timestamps.
|
| 44 |
+
- Downloaded source bytes matched the uploaded original.
|
| 45 |
+
- Physical contact time stayed null; original capture speed was not assumed.
|
| 46 |
+
- Embedded audio was analyzed as optional transient evidence. It did not create
|
| 47 |
+
contact or change a timestamp.
|
| 48 |
+
|
| 49 |
+
The tee job completed during the initial rollout, before the final export-timing
|
| 50 |
+
fix; the second job completed on the final deployed image. A Space rebuild removed
|
| 51 |
+
one intermediate second-video job; that upload was retried after readiness. This
|
| 52 |
+
is an example of the documented ephemeral-storage limit, not a detected miss.
|
| 53 |
+
|
| 54 |
+
An additional local run used profile-verified CoreML/CPU execution of the same
|
| 55 |
+
ONNX weights. Both recordings again returned unavailable contact; original bytes,
|
| 56 |
+
artifact hashes and source video timestamps were checked. That local run does
|
| 57 |
+
not substitute for CUDA verification and its timings are not GPU benchmarks.
|
| 58 |
+
|
| 59 |
+
Detailed recordings, JSON results, observations, videos and verification records
|
| 60 |
+
remain in ignored `artifacts/contact-validation/`; user recordings are not committed.
|
| 61 |
+
|
| 62 |
+
## Remaining accuracy gap
|
| 63 |
+
|
| 64 |
+
The API transport, queue, source timing and exports are verified. The pretrained
|
| 65 |
+
bat/ball models still need improvement and evaluation on representative phone
|
| 66 |
+
recordings, including blurred bats and stationary tee balls. A supported visual
|
| 67 |
+
estimate is possible only when the required observations exist. We do not yet
|
| 68 |
+
have a real-video detection-rate estimate, calibrated contact error bound or
|
| 69 |
+
validated contact-confidence score. All returned estimates retain
|
| 70 |
+
`accuracy_validated: false` and `verified: false`.
|
| 71 |
+
|
| 72 |
+
See [request/response integration](CONTACT_API.md). This separate endpoint does
|
| 73 |
+
not populate the motion API's contact event or change the coach payload.
|
docs/contact-input.schema.json
CHANGED
|
@@ -107,6 +107,22 @@
|
|
| 107 |
"default": true,
|
| 108 |
"title": "Use Audio",
|
| 109 |
"type": "boolean"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
}
|
| 111 |
},
|
| 112 |
"title": "ContactInput",
|
|
|
|
| 107 |
"default": true,
|
| 108 |
"title": "Use Audio",
|
| 109 |
"type": "boolean"
|
| 110 |
+
},
|
| 111 |
+
"mode": {
|
| 112 |
+
"default": "fast",
|
| 113 |
+
"enum": [
|
| 114 |
+
"fast",
|
| 115 |
+
"full"
|
| 116 |
+
],
|
| 117 |
+
"title": "Mode",
|
| 118 |
+
"type": "string"
|
| 119 |
+
},
|
| 120 |
+
"processing_budget_s": {
|
| 121 |
+
"default": 5.0,
|
| 122 |
+
"maximum": 5.0,
|
| 123 |
+
"minimum": 1.0,
|
| 124 |
+
"title": "Processing Budget S",
|
| 125 |
+
"type": "number"
|
| 126 |
}
|
| 127 |
},
|
| 128 |
"title": "ContactInput",
|
docs/contact-result.schema.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
{
|
| 2 |
"$defs": {
|
| 3 |
-
"
|
| 4 |
"additionalProperties": false,
|
| 5 |
"properties": {
|
| 6 |
"status": {
|
| 7 |
"enum": [
|
| 8 |
"available",
|
| 9 |
-
"unavailable"
|
|
|
|
| 10 |
],
|
| 11 |
"title": "Status",
|
| 12 |
"type": "string"
|
|
@@ -92,7 +93,7 @@
|
|
| 92 |
"media_type",
|
| 93 |
"expires_at"
|
| 94 |
],
|
| 95 |
-
"title": "
|
| 96 |
"type": "object"
|
| 97 |
},
|
| 98 |
"ContactEstimate": {
|
|
@@ -276,8 +277,11 @@
|
|
| 276 |
"additionalProperties": false,
|
| 277 |
"properties": {
|
| 278 |
"schema_version": {
|
| 279 |
-
"
|
| 280 |
-
"
|
|
|
|
|
|
|
|
|
|
| 281 |
"title": "Schema Version",
|
| 282 |
"type": "string"
|
| 283 |
},
|
|
@@ -316,11 +320,22 @@
|
|
| 316 |
},
|
| 317 |
"artifacts": {
|
| 318 |
"additionalProperties": {
|
| 319 |
-
"$ref": "#/$defs/
|
| 320 |
},
|
| 321 |
"title": "Artifacts",
|
| 322 |
"type": "object"
|
| 323 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
"expires_at": {
|
| 325 |
"title": "Expires At",
|
| 326 |
"type": "string"
|
|
|
|
| 1 |
{
|
| 2 |
"$defs": {
|
| 3 |
+
"ContactArtifact": {
|
| 4 |
"additionalProperties": false,
|
| 5 |
"properties": {
|
| 6 |
"status": {
|
| 7 |
"enum": [
|
| 8 |
"available",
|
| 9 |
+
"unavailable",
|
| 10 |
+
"pending"
|
| 11 |
],
|
| 12 |
"title": "Status",
|
| 13 |
"type": "string"
|
|
|
|
| 93 |
"media_type",
|
| 94 |
"expires_at"
|
| 95 |
],
|
| 96 |
+
"title": "ContactArtifact",
|
| 97 |
"type": "object"
|
| 98 |
},
|
| 99 |
"ContactEstimate": {
|
|
|
|
| 277 |
"additionalProperties": false,
|
| 278 |
"properties": {
|
| 279 |
"schema_version": {
|
| 280 |
+
"default": "1.1",
|
| 281 |
+
"enum": [
|
| 282 |
+
"1.0",
|
| 283 |
+
"1.1"
|
| 284 |
+
],
|
| 285 |
"title": "Schema Version",
|
| 286 |
"type": "string"
|
| 287 |
},
|
|
|
|
| 320 |
},
|
| 321 |
"artifacts": {
|
| 322 |
"additionalProperties": {
|
| 323 |
+
"$ref": "#/$defs/ContactArtifact"
|
| 324 |
},
|
| 325 |
"title": "Artifacts",
|
| 326 |
"type": "object"
|
| 327 |
},
|
| 328 |
+
"artifacts_revision": {
|
| 329 |
+
"default": 0,
|
| 330 |
+
"minimum": 0,
|
| 331 |
+
"title": "Artifacts Revision",
|
| 332 |
+
"type": "integer"
|
| 333 |
+
},
|
| 334 |
+
"rendering": {
|
| 335 |
+
"additionalProperties": true,
|
| 336 |
+
"title": "Rendering",
|
| 337 |
+
"type": "object"
|
| 338 |
+
},
|
| 339 |
"expires_at": {
|
| 340 |
"title": "Expires At",
|
| 341 |
"type": "string"
|
tests/test_contact_api.py
CHANGED
|
@@ -31,7 +31,7 @@ def inject_observations(monkeypatch, *, positive=True):
|
|
| 31 |
def stored(service,video,monkeypatch, *, positive=True):
|
| 32 |
inject_observations(monkeypatch,positive=positive)
|
| 33 |
identifier=service.store.create(20,kind='contact');job=service.job_directory(identifier);job.mkdir()
|
| 34 |
-
(job/'input.mp4').write_bytes(video.read_bytes());atomic_json(job/'request.json',{})
|
| 35 |
result=run(job,service.settings.model_root,device='cpu')
|
| 36 |
service.store.update(identifier,'completed',result_hash=sha256_file(job/'result.json'))
|
| 37 |
return job,result
|
|
@@ -107,7 +107,7 @@ def test_end_to_end_queue_completes_with_contact_worker_output(video,tmp_path,mo
|
|
| 107 |
preflight_command=[sys.executable,'-c','raise SystemExit(0)'])
|
| 108 |
with TestClient(create_app(s,service)) as client:
|
| 109 |
wait_until(lambda:service.ready);service.tracking_ready=True
|
| 110 |
-
response=client.post(PREFIX,headers=AUTH,files={'video':('swing.mp4',video.read_bytes(),'video/mp4')})
|
| 111 |
data=response.json();wait_until(lambda:service.store.get(data['job_id'])['status']=='completed',timeout=20)
|
| 112 |
result=client.get(data['result_url'],headers=AUTH)
|
| 113 |
assert result.status_code==200 and result.json()['contact']['status']=='estimated'
|
|
|
|
| 31 |
def stored(service,video,monkeypatch, *, positive=True):
|
| 32 |
inject_observations(monkeypatch,positive=positive)
|
| 33 |
identifier=service.store.create(20,kind='contact');job=service.job_directory(identifier);job.mkdir()
|
| 34 |
+
(job/'input.mp4').write_bytes(video.read_bytes());atomic_json(job/'request.json',{'mode':'full'})
|
| 35 |
result=run(job,service.settings.model_root,device='cpu')
|
| 36 |
service.store.update(identifier,'completed',result_hash=sha256_file(job/'result.json'))
|
| 37 |
return job,result
|
|
|
|
| 107 |
preflight_command=[sys.executable,'-c','raise SystemExit(0)'])
|
| 108 |
with TestClient(create_app(s,service)) as client:
|
| 109 |
wait_until(lambda:service.ready);service.tracking_ready=True
|
| 110 |
+
response=client.post(PREFIX,headers=AUTH,files={'video':('swing.mp4',video.read_bytes(),'video/mp4')},data={'options':'{"mode":"full"}'})
|
| 111 |
data=response.json();wait_until(lambda:service.store.get(data['job_id'])['status']=='completed',timeout=20)
|
| 112 |
result=client.get(data['result_url'],headers=AUTH)
|
| 113 |
assert result.status_code==200 and result.json()['contact']['status']=='estimated'
|
tests/test_contact_fast.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fast-path timing/queue/artifact behavior; constructed evidence is not accuracy validation."""
|
| 2 |
+
from types import SimpleNamespace
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import subprocess
|
| 6 |
+
import struct
|
| 7 |
+
import sys
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
from fastapi.testclient import TestClient
|
| 13 |
+
from baseball_batting.api import create_app
|
| 14 |
+
from baseball_batting.contact_contract import ContactInput, ContactResult
|
| 15 |
+
from baseball_batting.contact_fast import Budget, BudgetExpired, scan, candidate_windows, unavailable
|
| 16 |
+
from baseball_batting.contact_fast_worker import decide, initial_result
|
| 17 |
+
from baseball_batting.contact_runtime import ResidentContact
|
| 18 |
+
from baseball_batting.ingest import ingest, iter_frames
|
| 19 |
+
from baseball_batting.storage import atomic_json, read_json, sha256_file
|
| 20 |
+
from test_api import settings, fake_service, wait_until, AUTH
|
| 21 |
+
from test_contact_detection import observed
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def job(service, video, options=None):
|
| 25 |
+
identifier = service.store.create(20, kind='contact')
|
| 26 |
+
path = service.job_directory(identifier); path.mkdir()
|
| 27 |
+
(path/'input.mp4').write_bytes(video.read_bytes())
|
| 28 |
+
atomic_json(path/'request.json', options or {})
|
| 29 |
+
atomic_json(path/'upload.json', {'sha256': sha256_file(video), 'size_bytes': video.stat().st_size})
|
| 30 |
+
return path
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def models():
|
| 34 |
+
return SimpleNamespace(record={'fixture': True}, device='cpu')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def synthetic_check(monkeypatch):
|
| 38 |
+
def windows(times, *args, **kwargs):
|
| 39 |
+
return [{'start_frame': 0, 'end_frame': len(times)-1}]
|
| 40 |
+
def collect(video, capture, windows, models, budget, progress):
|
| 41 |
+
times = [f['playback_s'] for f in capture['frames']]
|
| 42 |
+
obs, _ = observed(times, index=4)
|
| 43 |
+
from baseball_batting.contact_detection import estimate
|
| 44 |
+
rows = [{**r, 'source_frame_index': i, 'video_time_s': times[i]-times[0], 'searched': True}
|
| 45 |
+
for i, r in enumerate(obs['frames'])]
|
| 46 |
+
return estimate(obs, capture), rows, windows
|
| 47 |
+
monkeypatch.setattr('baseball_batting.contact_fast_worker.candidate_windows', windows)
|
| 48 |
+
monkeypatch.setattr('baseball_batting.contact_fast_worker.collect_windows', collect)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_fast_is_default_but_full_and_legacy_optional_settings_remain():
|
| 52 |
+
assert ContactInput().mode == 'fast'
|
| 53 |
+
assert ContactInput(mode='full').mode == 'full'
|
| 54 |
+
assert ContactInput().processing_budget_s == 5
|
| 55 |
+
for value in [0, .9, 5.1, float('inf')]:
|
| 56 |
+
with pytest.raises(ValueError):
|
| 57 |
+
ContactInput(processing_budget_s=value)
|
| 58 |
+
clock = [10.]
|
| 59 |
+
budget = Budget(1, clock=lambda: clock[0])
|
| 60 |
+
budget.check(); clock[0] = 11.
|
| 61 |
+
with pytest.raises(BudgetExpired): budget.check()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_fast_scan_preserves_source_frame_time_and_explicit_clock(video):
|
| 65 |
+
expected = ingest(video, {})
|
| 66 |
+
capture, times, scores, peaks = scan(video, ContactInput(), Budget(5))
|
| 67 |
+
assert capture['frame_count'] == expected['frame_count']
|
| 68 |
+
assert [f['pts'] for f in capture['frames']] == [f['pts'] for f in expected['frames']]
|
| 69 |
+
np.testing.assert_allclose(times, [f['playback_s']-expected['frames'][0]['playback_s'] for f in expected['frames']])
|
| 70 |
+
assert capture['physical_clock_known'] is False
|
| 71 |
+
opts = ContactInput(timing={'kind': 'explicit', 'source': 'test clock', 'physical_times_s': list(4+times/4)})
|
| 72 |
+
cap, *_ = scan(video, opts, Budget(5))
|
| 73 |
+
assert cap['physical_clock_known'] is True
|
| 74 |
+
np.testing.assert_allclose([f['physical_s'] for f in cap['frames']], 4+times/4)
|
| 75 |
+
with pytest.raises(ValueError, match='match decoded'):
|
| 76 |
+
scan(video, ContactInput(timing={'kind': 'explicit', 'source': 'test', 'physical_times_s': list(range(20))}), Budget(5))
|
| 77 |
+
with pytest.raises(ValueError, match='limit'): scan(video, ContactInput(), Budget(5), max_frames=2)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_windows_use_audio_and_silent_motion_but_never_interpolate_frames():
|
| 81 |
+
times = np.arange(120)/30
|
| 82 |
+
motion = np.zeros(120); motion[60] = 100; motion[20] = 30
|
| 83 |
+
silent = candidate_windows(times, motion, [60, 20], {'status': 'no_audio'})
|
| 84 |
+
assert silent and silent[0]['start_frame'] <= 60 <= silent[0]['end_frame']
|
| 85 |
+
audio = {'transient_video_times_s': [2.05, 99], 'transient_strengths': {'2.05': 1}}
|
| 86 |
+
windows = candidate_windows(times, motion, [60, 20], audio)
|
| 87 |
+
assert windows[0]['method'] == 'audio_and_motion'
|
| 88 |
+
assert all(w['end_frame']-w['start_frame']+1 <= 32 for w in windows)
|
| 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):
|
| 95 |
+
rotated = tmp_path/'rotated.mp4'
|
| 96 |
+
# Set the ISO BMFF track-header display matrix in this single-track fixture.
|
| 97 |
+
# This needs neither a system ffmpeg/ffprobe nor version-specific CLI flags.
|
| 98 |
+
data = bytearray(video.read_bytes())
|
| 99 |
+
header = data.index(b'tkhd')
|
| 100 |
+
version = data[header+4]
|
| 101 |
+
assert version in (0, 1)
|
| 102 |
+
offset = header+(56 if version else 44)
|
| 103 |
+
struct.pack_into('>9i', data, offset, 0, -65536, 0, 65536, 0, 0, 0, 0, 1 << 30)
|
| 104 |
+
rotated.write_bytes(data)
|
| 105 |
+
expected = ingest(rotated, {'rotation_degrees': 270})
|
| 106 |
+
capture, *_ = scan(rotated, ContactInput(), Budget(5))
|
| 107 |
+
assert capture['rotation_degrees'] == expected['rotation_degrees'] == 270
|
| 108 |
+
assert capture['frames'][0]['width'] == expected['frames'][0]['width']
|
| 109 |
+
overridden, *_ = scan(rotated, ContactInput(rotation_degrees=0), Budget(5))
|
| 110 |
+
assert overridden['rotation_degrees'] == 0
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_candidate_decoder_retains_consecutive_original_frame_ids(video, monkeypatch):
|
| 114 |
+
from baseball_batting.contact_fast import collect_windows
|
| 115 |
+
cap, *_ = scan(video, ContactInput(), Budget(5))
|
| 116 |
+
monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
|
| 117 |
+
calls = []
|
| 118 |
+
def person(image): calls.append('person'); return []
|
| 119 |
+
def bat(image, origin): calls.append('bat'); return []
|
| 120 |
+
def ball(image, origin): calls.append('ball'); return []
|
| 121 |
+
mock_models = SimpleNamespace(person=person, bat=bat, ball=ball)
|
| 122 |
+
result, rows, checked = collect_windows(video, cap, [{'start_frame': 1, 'end_frame': 7}], mock_models, Budget(5))
|
| 123 |
+
assert calls.count('person') == 1 and calls.count('bat') == calls.count('ball') == 7
|
| 124 |
+
assert [r['source_frame_index'] for r in rows if r['searched']] == list(range(1, 8))
|
| 125 |
+
assert rows[0]['camera_motion_status'] == 'not_searched'
|
| 126 |
+
assert rows[0]['bat'] == rows[0]['ball'] == []
|
| 127 |
+
assert result.status == 'unavailable' and result.evidence['searched_frame_count'] == 7
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_cooperative_deadline_retains_only_completed_observations(video, monkeypatch):
|
| 131 |
+
from baseball_batting.contact_fast import collect_windows
|
| 132 |
+
cap, *_ = scan(video, ContactInput(), Budget(5))
|
| 133 |
+
clock = [0.]
|
| 134 |
+
monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
|
| 135 |
+
def bat(image, origin): clock[0] += 1.; return []
|
| 136 |
+
def ball(image, origin): clock[0] += 1.; return []
|
| 137 |
+
bundle = SimpleNamespace(person=lambda image: [], bat=bat, ball=ball)
|
| 138 |
+
result, rows, checked = collect_windows(video, cap, [{'start_frame': 0, 'end_frame': 7}],
|
| 139 |
+
bundle, Budget(5, clock=lambda: clock[0]))
|
| 140 |
+
assert result.reasons == ['processing_budget_exceeded']
|
| 141 |
+
assert result.evidence['searched_frame_count'] == 2
|
| 142 |
+
assert [r['source_frame_index'] for r in rows if r['searched']] == [0, 1]
|
| 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)
|
| 149 |
+
synthetic_check(monkeypatch)
|
| 150 |
+
result = decide(path, models())
|
| 151 |
+
assert result.contact.status == 'estimated' and result.contact.verified is False
|
| 152 |
+
assert result.pipeline['decision_elapsed_s'] < 5
|
| 153 |
+
assert result.artifacts['annotated'].status == 'pending'
|
| 154 |
+
assert not (path/'annotated.mp4').exists()
|
| 155 |
+
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 156 |
+
base_checksum = sha256_file(path/'result.json')
|
| 157 |
+
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 158 |
+
with TestClient(create_app(service.settings, service)) as client:
|
| 159 |
+
wait_until(lambda: service.ready)
|
| 160 |
+
# Render independently. The first response is still usable while pending.
|
| 161 |
+
url = '/v1/contact-analyses/'+path.name+'/result'
|
| 162 |
+
first = client.get(url, headers=AUTH).json()
|
| 163 |
+
assert first['contact'] == result.contact.model_dump(mode='json')
|
| 164 |
+
wait_until(lambda: client.get(url, headers=AUTH).json()['rendering']['status'] != 'pending', timeout=10)
|
| 165 |
+
final = client.get(url, headers=AUTH).json()
|
| 166 |
+
assert final['contact'] == first['contact']
|
| 167 |
+
assert final['artifacts_revision'] == 1 and final['rendering']['status'] == 'completed'
|
| 168 |
+
assert final['artifacts']['annotated']['status'] == 'available'
|
| 169 |
+
assert client.get(final['artifacts']['annotated']['url'], headers=AUTH).status_code == 200
|
| 170 |
+
row = service.store.get(path.name)
|
| 171 |
+
assert row['result_sha256'] == base_checksum == sha256_file(path/'result.json')
|
| 172 |
+
assert row['contact_artifacts_sha256'] == sha256_file(path/'rendered-result.json')
|
| 173 |
+
snapshot = (path/'rendered-result.json').read_bytes()
|
| 174 |
+
(path/'rendered-result.json').write_text('tampered')
|
| 175 |
+
assert client.get(url, headers=AUTH).status_code == 500
|
| 176 |
+
(path/'rendered-result.json').write_bytes(snapshot)
|
| 177 |
+
frames = list(iter_frames(path/'annotated.mp4'))
|
| 178 |
+
np.testing.assert_allclose([float(pts*base) for _, pts, base, _ in frames],
|
| 179 |
+
[f['playback_s'] for f in ingest(video, {})['frames']], atol=2e-6)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def test_budget_never_uses_audio_to_force_contact(video, tmp_path, monkeypatch):
|
| 183 |
+
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 184 |
+
def expired(*args, **kwargs): raise BudgetExpired()
|
| 185 |
+
monkeypatch.setattr('baseball_batting.contact_fast_worker.scan', expired)
|
| 186 |
+
result = decide(path, models())
|
| 187 |
+
assert result.contact.status == 'unavailable'
|
| 188 |
+
assert result.contact.reasons == ['processing_budget_exceeded']
|
| 189 |
+
assert result.contact.source_frame_index is None
|
| 190 |
+
assert result.artifacts['source'].status == 'available'
|
| 191 |
+
assert result.source_video['scan_complete'] is False
|
| 192 |
+
assert result.artifacts['annotated'].status == 'pending'
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def test_warm_worker_reuses_process_and_supervisor_stops_stuck_request(video, tmp_path):
|
| 196 |
+
service = fake_service(settings(tmp_path))
|
| 197 |
+
runtime = ResidentContact(service)
|
| 198 |
+
# Real persistent subprocess, constructed decision. No model inference claim.
|
| 199 |
+
script = """
|
| 200 |
+
import json,sys
|
| 201 |
+
from pathlib import Path
|
| 202 |
+
from baseball_batting.contact_contract import ContactInput
|
| 203 |
+
from baseball_batting.contact_fast_worker import initial_result
|
| 204 |
+
from baseball_batting.storage import atomic_json,read_json
|
| 205 |
+
root=Path(sys.argv[1])
|
| 206 |
+
for line in sys.stdin:
|
| 207 |
+
c=json.loads(line);p=root/'jobs'/c['job_id']
|
| 208 |
+
options=ContactInput.model_validate(read_json(p/'request.json'))
|
| 209 |
+
if options.use_audio is False:
|
| 210 |
+
import time;time.sleep(30)
|
| 211 |
+
r=initial_result(p,options);r.contact.reasons=['fixture_no_contact']
|
| 212 |
+
atomic_json(p/'fast-result.json',r.model_dump(mode='json'))
|
| 213 |
+
atomic_json(p/'fast-done.json',{'ok':True})
|
| 214 |
+
"""
|
| 215 |
+
runtime.process = subprocess.Popen([sys.executable, '-c', script, str(tmp_path)],
|
| 216 |
+
stdin=subprocess.PIPE, text=True, start_new_session=True)
|
| 217 |
+
runtime.record = {'ready': True, 'models': {'fixture': True}}
|
| 218 |
+
pid = runtime.process.pid
|
| 219 |
+
try:
|
| 220 |
+
for _ in range(2):
|
| 221 |
+
path = job(service, video, {'annotated_video': False})
|
| 222 |
+
service.store.update(path.name, 'running')
|
| 223 |
+
runtime.execute(path.name)
|
| 224 |
+
assert service.store.get(path.name)['status'] == 'completed'
|
| 225 |
+
assert read_json(path/'result.json')['contact']['reasons'] == ['fixture_no_contact']
|
| 226 |
+
assert runtime.ready and runtime.process.pid == pid
|
| 227 |
+
path = job(service, video, {'annotated_video': False, 'use_audio': False, 'processing_budget_s': 1})
|
| 228 |
+
service.store.update(path.name, 'running')
|
| 229 |
+
started = time.monotonic(); runtime.execute(path.name)
|
| 230 |
+
assert time.monotonic()-started < 1.4
|
| 231 |
+
result = read_json(path/'result.json')
|
| 232 |
+
assert result['contact']['reasons'] == ['processing_budget_exceeded']
|
| 233 |
+
assert result['contact']['video_time_s'] is None
|
| 234 |
+
assert service.store.get(path.name)['status'] == 'completed'
|
| 235 |
+
assert not runtime.ready
|
| 236 |
+
finally:
|
| 237 |
+
runtime.stop(immediate=True)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def test_pending_video_is_distinct_from_unavailable_and_old_outputs_still_parse(video, tmp_path):
|
| 241 |
+
service = fake_service(settings(tmp_path))
|
| 242 |
+
path = job(service, video)
|
| 243 |
+
result = initial_result(path, ContactInput())
|
| 244 |
+
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 245 |
+
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 246 |
+
# Do not run the background thread, keeping a real pending artifact.
|
| 247 |
+
app = create_app(service.settings, service)
|
| 248 |
+
client = TestClient(app)
|
| 249 |
+
response = client.get(result.artifacts['annotated'].url, headers=AUTH)
|
| 250 |
+
assert response.status_code == 202 and response.headers['retry-after'] == '1'
|
| 251 |
+
assert client.get(result.artifacts['annotated'].url).status_code == 401
|
| 252 |
+
old = result.model_dump(mode='json'); old['schema_version'] = '1.0'
|
| 253 |
+
old.pop('rendering'); old.pop('artifacts_revision')
|
| 254 |
+
old['artifacts'] = {'source': old['artifacts']['source']}
|
| 255 |
+
assert ContactResult.model_validate(old).schema_version == '1.0'
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_cancel_fast_request_kills_resident_and_removes_work(video, tmp_path):
|
| 259 |
+
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 260 |
+
service.store.update(path.name, 'running')
|
| 261 |
+
runtime = ResidentContact(service)
|
| 262 |
+
runtime.process = subprocess.Popen([sys.executable, '-c', 'import sys,time;sys.stdin.readline();time.sleep(30)'],
|
| 263 |
+
stdin=subprocess.PIPE, text=True, start_new_session=True)
|
| 264 |
+
process = runtime.process
|
| 265 |
+
runtime.record = {'ready': True}
|
| 266 |
+
thread = threading.Thread(target=runtime.execute, args=(path.name,))
|
| 267 |
+
try:
|
| 268 |
+
thread.start()
|
| 269 |
+
wait_until(lambda: (path/'source.mp4').exists())
|
| 270 |
+
service.store.cancel(path.name)
|
| 271 |
+
thread.join(timeout=2)
|
| 272 |
+
assert not thread.is_alive() and process.poll() is not None
|
| 273 |
+
assert service.store.get(path.name)['status'] == 'cancelled'
|
| 274 |
+
assert not path.exists()
|
| 275 |
+
finally:
|
| 276 |
+
runtime.stop(immediate=True)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def test_fast_warmup_guard_does_not_block_full_mode(video, tmp_path):
|
| 280 |
+
service = fake_service(settings(tmp_path)); service.ready = service.tracking_ready = True
|
| 281 |
+
service.contact_runtime = SimpleNamespace(ready=False, reason='warming')
|
| 282 |
+
client = TestClient(create_app(service.settings, service))
|
| 283 |
+
files = {'video': ('swing.mp4', video.read_bytes(), 'video/mp4')}
|
| 284 |
+
response = client.post('/v1/contact-analyses', files=files, headers=AUTH)
|
| 285 |
+
assert response.status_code == 503 and response.json()['detail']['code'] == 'fast_worker_warming'
|
| 286 |
+
assert list(service.jobs_root.iterdir()) == []
|
| 287 |
+
response = client.post('/v1/contact-analyses', files=files, headers=AUTH, data={'options': '{"mode":"full"}'})
|
| 288 |
+
assert response.status_code == 202
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def test_unpublished_render_snapshot_does_not_replace_base_decision(video, tmp_path):
|
| 292 |
+
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 293 |
+
result = initial_result(path, ContactInput())
|
| 294 |
+
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 295 |
+
# Simulate a restart after writing a render snapshot but before its DB commit.
|
| 296 |
+
(path/'rendered-result.json').write_text('unpublished')
|
| 297 |
+
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 298 |
+
client = TestClient(create_app(service.settings, service))
|
| 299 |
+
response = client.get('/v1/contact-analyses/'+path.name+'/result', headers=AUTH)
|
| 300 |
+
assert response.status_code == 200 and response.json()['rendering']['status'] == 'pending'
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def test_render_failure_keeps_original_decision(video, tmp_path, monkeypatch):
|
| 304 |
+
from baseball_batting.contact_render_worker import render
|
| 305 |
+
from baseball_batting.swing_clips import ClipError
|
| 306 |
+
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 307 |
+
synthetic_check(monkeypatch); result = decide(path, models())
|
| 308 |
+
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 309 |
+
def fail(*args, **kwargs): raise ClipError('last_frame_duration_unavailable')
|
| 310 |
+
monkeypatch.setattr('baseball_batting.contact_videos.export', fail)
|
| 311 |
+
value = render(path)
|
| 312 |
+
assert value['rendering']['status'] == 'failed'
|
| 313 |
+
assert value['artifacts']['annotated']['reason_code'] == 'last_frame_duration_unavailable'
|
| 314 |
+
assert read_json(path/'result.json')['contact'] == result.contact.model_dump(mode='json')
|
tools/benchmark_contact_api.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measure warm contact decisions separately from upload/queue/video rendering.
|
| 2 |
+
|
| 3 |
+
Reads the server key only from BASEBALL_API_KEY; never writes it to artifacts.
|
| 4 |
+
The default target is the existing baseball-engine Space. No Gemini calls.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import time
|
| 12 |
+
import urllib.error
|
| 13 |
+
import urllib.request
|
| 14 |
+
import uuid
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def main():
|
| 18 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 19 |
+
parser.add_argument('--base', default='https://modventures-baseball-engine.hf.space')
|
| 20 |
+
parser.add_argument('--video', type=Path, action='append', required=True)
|
| 21 |
+
parser.add_argument('--output', type=Path, default=Path('artifacts/contact-validation/fast-live'))
|
| 22 |
+
parser.add_argument('--wait-videos', action='store_true')
|
| 23 |
+
args = parser.parse_args()
|
| 24 |
+
key = os.environ.get('BASEBALL_API_KEY')
|
| 25 |
+
if not key:
|
| 26 |
+
parser.error('Set BASEBALL_API_KEY in the environment; do not pass secrets on the command line')
|
| 27 |
+
base = args.base.rstrip('/')
|
| 28 |
+
def request(path, data=None, headers=None):
|
| 29 |
+
if not path.startswith('/v1/contact-analyses'):
|
| 30 |
+
raise ValueError('Unexpected contact endpoint')
|
| 31 |
+
req = urllib.request.Request(base+path, data=data, headers={
|
| 32 |
+
**(headers or {}), 'Authorization': 'Bearer '+key})
|
| 33 |
+
with urllib.request.urlopen(req, timeout=30) as response:
|
| 34 |
+
return response.read()
|
| 35 |
+
def get(path):
|
| 36 |
+
return json.loads(request(path))
|
| 37 |
+
def save(path, value):
|
| 38 |
+
path.write_text(json.dumps(value, indent=2)+'\n')
|
| 39 |
+
capability = get('/v1/contact-analyses/capabilities')
|
| 40 |
+
print('Fast worker:', capability.get('fast_ready'), capability.get('fast_readiness_reason'), flush=True)
|
| 41 |
+
if not capability.get('fast_ready'):
|
| 42 |
+
raise SystemExit('Wait for fast_ready before measuring a warm request')
|
| 43 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
for index, video in enumerate(args.video):
|
| 45 |
+
folder = args.output/(str(index+1)+'-'+video.stem)
|
| 46 |
+
folder.mkdir(exist_ok=True)
|
| 47 |
+
boundary = uuid.uuid4().hex
|
| 48 |
+
body = (('--'+boundary+'\r\nContent-Disposition: form-data; name="video"; filename="swing'+video.suffix+'"\r\n'
|
| 49 |
+
'Content-Type: video/mp4\r\n\r\n').encode()+video.read_bytes()+('\r\n--'+boundary+'--\r\n').encode())
|
| 50 |
+
started = time.monotonic()
|
| 51 |
+
response = json.loads(request('/v1/contact-analyses', body,
|
| 52 |
+
{'Content-Type': 'multipart/form-data; boundary='+boundary}))
|
| 53 |
+
upload_s = time.monotonic()-started
|
| 54 |
+
save(folder/'job.json', response)
|
| 55 |
+
while True:
|
| 56 |
+
status = get(response['status_url'])
|
| 57 |
+
if status['status'] in ('completed', 'failed', 'cancelled'):
|
| 58 |
+
break
|
| 59 |
+
if time.monotonic()-started > 300:
|
| 60 |
+
raise TimeoutError('Waiting for contact result exceeded five minutes')
|
| 61 |
+
time.sleep(.15)
|
| 62 |
+
result_wait_s = time.monotonic()-started-upload_s
|
| 63 |
+
save(folder/'status.json', status)
|
| 64 |
+
if status['status'] != 'completed':
|
| 65 |
+
raise RuntimeError('Contact job failed: '+str(status.get('failure') or status.get('error')))
|
| 66 |
+
result = get(response['result_url'])
|
| 67 |
+
save(folder/'initial-result.json', result)
|
| 68 |
+
original_contact = result['contact']
|
| 69 |
+
print(video.name, json.dumps({'server_decision_s': result['pipeline'].get('decision_elapsed_s'),
|
| 70 |
+
'deadline_met': result['pipeline'].get('deadline_met'), 'upload_s': round(upload_s, 3),
|
| 71 |
+
'client_wait_including_queue_and_poll_s': round(result_wait_s, 3), 'contact': original_contact['status'],
|
| 72 |
+
'reasons': original_contact['reasons'], 'rendering_at_result': result['rendering']['status']}), flush=True)
|
| 73 |
+
if args.wait_videos:
|
| 74 |
+
render_started = time.monotonic()
|
| 75 |
+
while result['rendering']['status'] == 'pending':
|
| 76 |
+
if time.monotonic()-render_started > 240:
|
| 77 |
+
raise TimeoutError('Video render did not finish')
|
| 78 |
+
time.sleep(.5)
|
| 79 |
+
result = get(response['result_url'])
|
| 80 |
+
if result['contact'] != original_contact:
|
| 81 |
+
raise AssertionError('Rendering changed the contact decision')
|
| 82 |
+
save(folder/'result.json', result)
|
| 83 |
+
verified = {}
|
| 84 |
+
for name, asset in result['artifacts'].items():
|
| 85 |
+
if asset['status'] != 'available':
|
| 86 |
+
continue
|
| 87 |
+
data = request(asset['url'])
|
| 88 |
+
if len(data) != asset['size_bytes'] or hashlib.sha256(data).hexdigest() != asset['sha256']:
|
| 89 |
+
raise AssertionError('Artifact failed checksum: '+name)
|
| 90 |
+
(folder/Path(asset['filename']).name).write_bytes(data)
|
| 91 |
+
verified[name] = 'sha256_and_length_verified'
|
| 92 |
+
save(folder/'verification.json', {'server_decision_s': result['pipeline'].get('decision_elapsed_s'),
|
| 93 |
+
'deadline_met': result['pipeline'].get('deadline_met'), 'contact': original_contact,
|
| 94 |
+
'upload_s': upload_s, 'client_wait_including_queue_and_poll_s': result_wait_s,
|
| 95 |
+
'contact_unchanged_after_rendering': True, 'artifacts': verified})
|
| 96 |
+
print('Verified:', json.dumps(verified), flush=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == '__main__':
|
| 100 |
+
main()
|