Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
80174e1
1
Parent(s): ef4010d
Automated Deploy: c6e51d4e94af713875e99f157a4540f6ecc2004b
Browse files- baseball_batting/api.py +2 -4
- baseball_batting/api_jobs.py +9 -49
- baseball_batting/contact_api.py +0 -143
- baseball_batting/contact_audio.py +0 -48
- baseball_batting/contact_contract.py +0 -78
- baseball_batting/contact_detection.py +0 -130
- baseball_batting/contact_fast.py +0 -311
- baseball_batting/contact_fast_worker.py +0 -157
- baseball_batting/contact_render_worker.py +0 -73
- baseball_batting/contact_runtime.py +0 -202
- baseball_batting/contact_videos.py +0 -66
- baseball_batting/contact_vision.py +0 -92
- baseball_batting/contact_worker.py +0 -115
- baseball_batting/detection.py +2 -2
- baseball_batting/tracking_vision.py +3 -3
- deploy/huggingface/removed-files.txt +20 -0
- docs/CONTACT_API.md +0 -244
- docs/CONTACT_VALIDATION.md +0 -163
- docs/contact-input.schema.json +0 -129
- docs/contact-result.schema.json +0 -362
- tests/test_api.py +49 -0
- tests/test_contact_api.py +0 -147
- tests/test_contact_detection.py +0 -97
- tests/test_contact_fast.py +0 -349
- tests/test_deployment_sync.py +25 -0
- tools/benchmark_contact_api.py +0 -100
baseball_batting/api.py
CHANGED
|
@@ -58,7 +58,7 @@ class UploadGuard:
|
|
| 58 |
if received > limit:
|
| 59 |
raise HTTPException(413, "Request exceeds upload limit")
|
| 60 |
return message
|
| 61 |
-
is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses','/v1/sam-batting/analyses','/v1/motion-analyses'
|
| 62 |
if is_upload:
|
| 63 |
if not self.service.ready:
|
| 64 |
return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
|
|
@@ -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)
|
|
@@ -470,6 +470,4 @@ def create_app(settings=None, service=None):
|
|
| 470 |
register(app,service,authenticated)
|
| 471 |
from .motion_api import register as register_motion
|
| 472 |
register_motion(app,service,authenticated)
|
| 473 |
-
from .contact_api import register as register_contact
|
| 474 |
-
register_contact(app,service,authenticated)
|
| 475 |
return app
|
|
|
|
| 58 |
if received > limit:
|
| 59 |
raise HTTPException(413, "Request exceeds upload limit")
|
| 60 |
return message
|
| 61 |
+
is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses','/v1/sam-batting/analyses','/v1/motion-analyses'}
|
| 62 |
if is_upload:
|
| 63 |
if not self.service.ready:
|
| 64 |
return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
|
|
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
+
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.17.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)
|
|
|
|
| 470 |
register(app,service,authenticated)
|
| 471 |
from .motion_api import register as register_motion
|
| 472 |
register_motion(app,service,authenticated)
|
|
|
|
|
|
|
| 473 |
return app
|
baseball_batting/api_jobs.py
CHANGED
|
@@ -86,8 +86,6 @@ 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 |
-
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,28 +152,22 @@ class JobStore:
|
|
| 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
|
| 174 |
(status, time.time(), identifier))
|
| 175 |
return status
|
| 176 |
|
| 177 |
def recover(self):
|
| 178 |
with self.connect() as db:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
uploads = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='uploading'")]
|
| 180 |
cancellations = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='cancel_requested'")]
|
| 181 |
db.execute("DELETE FROM jobs WHERE status='uploading'")
|
|
@@ -225,12 +217,6 @@ class JobService:
|
|
| 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):
|
|
@@ -240,12 +226,13 @@ class JobService:
|
|
| 240 |
def job_command(self, directory):
|
| 241 |
s = self.settings
|
| 242 |
kind=(self.store.get(directory.name) or {}).get('kind')
|
| 243 |
-
|
| 244 |
-
|
|
|
|
| 245 |
command=[sys.executable, "-m", module, "--models", str(s.model_root),
|
| 246 |
"--job", str(directory), "--max-frames", str(s.max_frames),
|
| 247 |
"--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
|
| 248 |
-
if kind
|
| 249 |
return command
|
| 250 |
|
| 251 |
def start(self):
|
|
@@ -257,24 +244,16 @@ class JobService:
|
|
| 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,8 +275,6 @@ class JobService:
|
|
| 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,8 +282,6 @@ class JobService:
|
|
| 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,13 +311,9 @@ class JobService:
|
|
| 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,8 +323,6 @@ class JobService:
|
|
| 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,15 +330,6 @@ class JobService:
|
|
| 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:
|
|
|
|
| 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 |
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 |
|
| 165 |
def recover(self):
|
| 166 |
with self.connect() as db:
|
| 167 |
+
# Retired contact jobs must never fall back to the batting worker.
|
| 168 |
+
# Keep their records and artifacts until normal retention expires.
|
| 169 |
+
db.execute("UPDATE jobs SET status='failed', error='api_removed', updated=? "
|
| 170 |
+
"WHERE kind='contact' AND status IN (?,?,?,?)", (time.time(), *ACTIVE))
|
| 171 |
uploads = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='uploading'")]
|
| 172 |
cancellations = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='cancel_requested'")]
|
| 173 |
db.execute("DELETE FROM jobs WHERE status='uploading'")
|
|
|
|
| 217 |
self.lock = None
|
| 218 |
# Serializes completion/cancellation and deletion against result downloads.
|
| 219 |
self.mutation_lock = threading.RLock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
def job_directory(self, identifier):
|
| 222 |
if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier):
|
|
|
|
| 226 |
def job_command(self, directory):
|
| 227 |
s = self.settings
|
| 228 |
kind=(self.store.get(directory.name) or {}).get('kind')
|
| 229 |
+
if kind not in {'legacy', 'sam_batting', 'motion_player'}:
|
| 230 |
+
raise ValueError('Unsupported analysis job kind')
|
| 231 |
+
module={'sam_batting':'baseball_batting.sam_measurement_worker','motion_player':'baseball_batting.motion_worker'}.get(kind,'baseball_batting.api_worker')
|
| 232 |
command=[sys.executable, "-m", module, "--models", str(s.model_root),
|
| 233 |
"--job", str(directory), "--max-frames", str(s.max_frames),
|
| 234 |
"--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
|
| 235 |
+
if kind=='motion_player':command+=['--retention-s',str(s.retention_s)]
|
| 236 |
return command
|
| 237 |
|
| 238 |
def start(self):
|
|
|
|
| 244 |
raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker")
|
| 245 |
for identifier in self.store.recover():
|
| 246 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
|
|
|
|
|
|
|
|
|
| 247 |
self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True)
|
| 248 |
self.thread.start()
|
| 249 |
|
| 250 |
def stop(self):
|
| 251 |
self.ready = False
|
| 252 |
self.stopping.set(); self.wakeup.set()
|
|
|
|
| 253 |
if self.thread:
|
| 254 |
self.thread.join(timeout=15)
|
| 255 |
if self.thread.is_alive():
|
| 256 |
raise RuntimeError("GPU worker did not stop")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
if self.lock:
|
| 258 |
self.lock.close()
|
| 259 |
|
|
|
|
| 275 |
with self.mutation_lock:
|
| 276 |
status = self.store.cancel(identifier)
|
| 277 |
if status == "cancelled":
|
|
|
|
|
|
|
| 278 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 279 |
self.wakeup.set()
|
| 280 |
return status
|
|
|
|
| 282 |
def cleanup(self):
|
| 283 |
with self.mutation_lock:
|
| 284 |
for identifier in self.store.expired(time.time() - self.settings.retention_s):
|
|
|
|
|
|
|
| 285 |
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 286 |
self.store.forget(identifier)
|
| 287 |
|
|
|
|
| 311 |
record = read_json(readiness_path)
|
| 312 |
self.tracking_ready = record.get('ready') is True and record.get('bat_ball_tracking') is True
|
| 313 |
self.visual_model_status = record.get('visual_model_status', {'status': 'not_checked'})
|
|
|
|
|
|
|
| 314 |
self.ready = True; self.readiness_reason = "ready"
|
| 315 |
while not self.stopping.is_set():
|
| 316 |
self.cleanup()
|
|
|
|
|
|
|
| 317 |
identifier = self.store.claim()
|
| 318 |
if identifier:
|
| 319 |
self.execute(identifier)
|
|
|
|
| 323 |
self.readiness_reason = "queue_worker_failed"
|
| 324 |
LOG.exception("GPU job queue stopped")
|
| 325 |
finally:
|
|
|
|
|
|
|
| 326 |
self.ready = False
|
| 327 |
self.tracking_ready = False
|
| 328 |
|
|
|
|
| 330 |
directory = self.job_directory(identifier)
|
| 331 |
process = None
|
| 332 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 334 |
started = time.monotonic()
|
| 335 |
while process.poll() is None:
|
baseball_batting/contact_api.py
DELETED
|
@@ -1,143 +0,0 @@
|
|
| 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
|
| 7 |
-
from fastapi.responses import JSONResponse
|
| 8 |
-
from pydantic import ValidationError
|
| 9 |
-
from .contact_contract import ContactInput,ContactResult
|
| 10 |
-
from .api_jobs import QueueFull
|
| 11 |
-
from .storage import atomic_json,read_json,sha256_file
|
| 12 |
-
from .media import open_verified_media,media_response
|
| 13 |
-
|
| 14 |
-
PREFIX='/v1/contact-analyses'
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def register(app,service,authenticated):
|
| 18 |
-
settings=service.settings
|
| 19 |
-
def record(identifier):
|
| 20 |
-
try:directory=service.job_directory(identifier)
|
| 21 |
-
except ValueError:raise HTTPException(404,'Contact analysis not found') from None
|
| 22 |
-
row=service.store.get(identifier)
|
| 23 |
-
if row is None or row['kind']!='contact':raise HTTPException(404,'Contact analysis not found')
|
| 24 |
-
return directory,row
|
| 25 |
-
|
| 26 |
-
def completed(identifier):
|
| 27 |
-
directory,row=record(identifier)
|
| 28 |
-
if row['status']!='completed':raise HTTPException(409,'Contact analysis has not completed')
|
| 29 |
-
path=directory/'result.json'
|
| 30 |
-
if not path.is_file() or sha256_file(path)!=row['result_sha256']:
|
| 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 |
-
|
| 60 |
-
@app.get(PREFIX+'/input-schema',dependencies=[Depends(authenticated)])
|
| 61 |
-
def input_schema():return ContactInput.model_json_schema()
|
| 62 |
-
|
| 63 |
-
@app.get(PREFIX+'/output-schema',dependencies=[Depends(authenticated)])
|
| 64 |
-
def output_schema():return ContactResult.model_json_schema()
|
| 65 |
-
|
| 66 |
-
@app.post(PREFIX,status_code=202,dependencies=[Depends(authenticated)])
|
| 67 |
-
async def upload(video:Annotated[UploadFile,File(description='One swing video; any frame rate')],
|
| 68 |
-
options:Annotated[str,Form(description='Optional JSON; omit for video-only analysis')]='{}'):
|
| 69 |
-
identifier=None;directory=None
|
| 70 |
-
try:
|
| 71 |
-
if not service.ready or not service.tracking_ready:
|
| 72 |
-
raise HTTPException(503,{'code':'tracking_models_unavailable','message':'Bat and ball models must pass GPU preflight.'})
|
| 73 |
-
if len(options.encode())>512*1024:raise HTTPException(413,'Options exceed size limit')
|
| 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}
|
| 98 |
-
except BaseException:
|
| 99 |
-
if identifier:service.store.forget(identifier);shutil.rmtree(directory,ignore_errors=True)
|
| 100 |
-
raise
|
| 101 |
-
finally:await video.close()
|
| 102 |
-
|
| 103 |
-
@app.get(PREFIX+'/{identifier}',dependencies=[Depends(authenticated)])
|
| 104 |
-
def status(identifier:str):
|
| 105 |
-
with service.mutation_lock:
|
| 106 |
-
directory,row=record(identifier);progress=None;failure=None
|
| 107 |
-
try:progress=read_json(directory/'progress.json')
|
| 108 |
-
except (OSError,ValueError):pass
|
| 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)])
|
| 121 |
-
def result(identifier:str):
|
| 122 |
-
with service.mutation_lock:_,payload=completed(identifier)
|
| 123 |
-
return JSONResponse(payload.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
|
| 124 |
-
|
| 125 |
-
@app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
|
| 126 |
-
@app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
|
| 127 |
-
def artifact(identifier:str,name:str,request:Request):
|
| 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')
|
| 137 |
-
handle,size=open_verified_media(path,asset.sha256,asset.size_bytes)
|
| 138 |
-
return media_response(request,handle,size,asset.sha256,media_type=asset.media_type)
|
| 139 |
-
|
| 140 |
-
@app.delete(PREFIX+'/{identifier}',status_code=202,dependencies=[Depends(authenticated)])
|
| 141 |
-
def delete(identifier:str):
|
| 142 |
-
record(identifier)
|
| 143 |
-
return {'job_id':identifier,'status':service.delete(identifier)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_audio.py
DELETED
|
@@ -1,48 +0,0 @@
|
|
| 1 |
-
"""Optional embedded audio transients: corroboration only, never impact proof."""
|
| 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
|
| 9 |
-
from scipy.signal import find_peaks
|
| 10 |
-
try:
|
| 11 |
-
with av.open(str(video),options={'protocol_whitelist':'file,pipe'}) as container:
|
| 12 |
-
if not container.streams.audio:
|
| 13 |
-
return {'status':'no_audio','used_for_contact_timestamp':False}
|
| 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
|
| 21 |
-
start=float(sample.pts*sample.time_base)-origin_s
|
| 22 |
-
if start>duration_s+.5:
|
| 23 |
-
break
|
| 24 |
-
data=sample.to_ndarray().reshape(-1)
|
| 25 |
-
for a in range(0,len(data)-80+1,80):
|
| 26 |
-
time=start+a/16000
|
| 27 |
-
if 0<=time<=duration_s:
|
| 28 |
-
energy.append(float(np.mean(data[a:a+80]**2)));times.append(time)
|
| 29 |
-
if frame.pts is not None and float(frame.pts*frame.time_base)-origin_s>duration_s+.5:
|
| 30 |
-
break
|
| 31 |
-
if len(energy)<10:
|
| 32 |
-
return {'status':'insufficient_audio','used_for_contact_timestamp':False}
|
| 33 |
-
q=np.log(np.asarray(energy)+1e-10)
|
| 34 |
-
novelty=np.maximum(0,q-np.r_[q[0],q[:-1]])
|
| 35 |
-
floor=float(np.median(novelty)+6*np.median(np.abs(novelty-np.median(novelty))))
|
| 36 |
-
peaks,_=find_peaks(novelty,height=max(.5,floor),distance=10)
|
| 37 |
-
peaks=sorted(peaks,key=lambda i:novelty[i],reverse=True)[:32]
|
| 38 |
-
candidates=sorted(float(times[i]) for i in peaks)
|
| 39 |
-
near=[]
|
| 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):
|
| 48 |
-
return {'status':'audio_unreadable','used_for_contact_timestamp':False}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_contract.py
DELETED
|
@@ -1,78 +0,0 @@
|
|
| 1 |
-
"""Standalone single-video contact estimates; no pose or capture-FPS requirement."""
|
| 2 |
-
from typing import Any, Literal
|
| 3 |
-
from pydantic import Field, model_validator
|
| 4 |
-
from .sam_batting_contract import Strict
|
| 5 |
-
from .api_contract import TimingInput
|
| 6 |
-
from .motion_contract import Artifact
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
class ContactInput(Strict):
|
| 10 |
-
# All fields are optional. Unknown capture time never blocks video time.
|
| 11 |
-
timing: TimingInput = Field(default_factory=TimingInput)
|
| 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.)
|
| 17 |
-
|
| 18 |
-
def metadata(self):
|
| 19 |
-
result = {'timing': self.timing.model_dump(exclude_none=True), 'intended_use': 'research'}
|
| 20 |
-
if self.rotation_degrees is not None:
|
| 21 |
-
result['rotation_degrees'] = self.rotation_degrees
|
| 22 |
-
return result
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class ContactEstimate(Strict):
|
| 26 |
-
status: Literal['estimated', 'unavailable']
|
| 27 |
-
source_frame_index: int | None = Field(default=None, ge=0)
|
| 28 |
-
frame_interval: tuple[int, int] | None = None
|
| 29 |
-
video_time_s: float | None = Field(default=None, ge=0)
|
| 30 |
-
video_time_interval_s: tuple[float, float] | None = None
|
| 31 |
-
capture_time_s: float | None = Field(default=None, ge=0)
|
| 32 |
-
capture_time_interval_s: tuple[float, float] | None = None
|
| 33 |
-
local_frame_spacing_ms: float | None = Field(default=None, gt=0)
|
| 34 |
-
method: str | None = None
|
| 35 |
-
reasons: list[str] = Field(default_factory=list)
|
| 36 |
-
confidence: None = None
|
| 37 |
-
verified: Literal[False] = False
|
| 38 |
-
accuracy_validated: Literal[False] = False
|
| 39 |
-
evidence: dict[str, Any] = Field(default_factory=dict)
|
| 40 |
-
|
| 41 |
-
@model_validator(mode='after')
|
| 42 |
-
def consistent(self):
|
| 43 |
-
fields = ('source_frame_index', 'frame_interval', 'video_time_s',
|
| 44 |
-
'video_time_interval_s', 'local_frame_spacing_ms', 'method')
|
| 45 |
-
if self.status == 'estimated':
|
| 46 |
-
if any(getattr(self, key) is None for key in fields):
|
| 47 |
-
raise ValueError('An estimated contact requires source samples, a time interval and method')
|
| 48 |
-
for bounds, value in [(self.frame_interval, self.source_frame_index),
|
| 49 |
-
(self.video_time_interval_s, self.video_time_s),
|
| 50 |
-
(self.capture_time_interval_s, self.capture_time_s)]:
|
| 51 |
-
if bounds is not None and (bounds[1] < bounds[0] or value is None or not bounds[0] <= value <= bounds[1]):
|
| 52 |
-
raise ValueError('Contact estimate must lie in its interval')
|
| 53 |
-
if (self.capture_time_s is None) != (self.capture_time_interval_s is None):
|
| 54 |
-
raise ValueError('Capture time and interval must be available together')
|
| 55 |
-
elif any(getattr(self, key) is not None for key in (*fields, 'capture_time_s', 'capture_time_interval_s')) or not self.reasons:
|
| 56 |
-
raise ValueError('Unavailable contact has null locations and a reason')
|
| 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
|
| 70 |
-
source_video: dict[str, Any]
|
| 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_detection.py
DELETED
|
@@ -1,130 +0,0 @@
|
|
| 1 |
-
"""Observed bat sweep and ball deflection, at source timestamps of any cadence.
|
| 2 |
-
|
| 3 |
-
No pose, supplied swing onset, known capture clock, fixed FPS, or gap filling.
|
| 4 |
-
The result is a visual transition interval, never a verified impact or miss.
|
| 5 |
-
"""
|
| 6 |
-
import numpy as np
|
| 7 |
-
from .bat_ball_timing import _line_track, shaft_distance
|
| 8 |
-
from .contact_contract import ContactEstimate
|
| 9 |
-
|
| 10 |
-
VERSION = 'single-video-contact-v1'
|
| 11 |
-
MIN_CONTACT_CONTEXT = 7 # Three observed samples before, the interaction, three after.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def _unknown(reason, counts):
|
| 15 |
-
return ContactEstimate(status='unavailable', reasons=[reason], evidence=counts)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _branch(rows,times,index,side,length,stationary=False):
|
| 19 |
-
# At high FPS three frames may cover less than a ball radius. Extend observed
|
| 20 |
-
# support rather than declaring such footage unsupported or filling gaps.
|
| 21 |
-
for width in (3,5,7):
|
| 22 |
-
ids=list(range(index-width,index)) if side=='before' else list(range(index+1,index+width+1))
|
| 23 |
-
if ids[0]<0 or ids[-1]>=len(rows):continue
|
| 24 |
-
segment=rows[index].get('segment_id',0)
|
| 25 |
-
if any(r.get('segment_id',0)!=segment or r.get('camera_motion_status')=='unresolved' for r in rows[min(ids[0],index):max(ids[-1],index)+1]):continue
|
| 26 |
-
dt=np.diff(times[min(ids[0],index):max(ids[-1],index)+1])
|
| 27 |
-
if dt.max()>3*np.median(dt):continue
|
| 28 |
-
fit=_line_track([rows[k] for k in ids],times[ids],times[index],length,stationary=stationary)
|
| 29 |
-
if fit is not None:return fit,ids
|
| 30 |
-
return None,None
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def estimate(observations, capture):
|
| 34 |
-
rows = observations['frames']
|
| 35 |
-
times = np.asarray([f['playback_s'] for f in capture['frames']], float)
|
| 36 |
-
if len(times) != len(rows) or len(times) < 7:
|
| 37 |
-
return _unknown('insufficient_contact_context', {})
|
| 38 |
-
times -= times[0]
|
| 39 |
-
if not np.isfinite(times).all() or np.any(np.diff(times) <= 0):
|
| 40 |
-
raise ValueError('invalid_source_timestamps')
|
| 41 |
-
counts = {'frames_with_observed_bat_endpoints': sum(any(b.get('points') is not None for b in r['bat']) for r in rows),
|
| 42 |
-
'frames_with_observed_ball': sum(bool(r['ball']) for r in rows),
|
| 43 |
-
'supported_ball_transitions': 0, 'camera_motion_policy': 'background_affine_stabilized_segments',
|
| 44 |
-
'timing_interval_kind': 'observed_transition_frames; not a calibrated accuracy interval'}
|
| 45 |
-
candidates = []
|
| 46 |
-
for i in range(3, len(rows)-3):
|
| 47 |
-
context = rows[i-3:i+4]
|
| 48 |
-
if len({r.get('segment_id', 0) for r in context}) != 1:
|
| 49 |
-
continue
|
| 50 |
-
if any(r.get('camera_motion_status') == 'unresolved' for r in context):
|
| 51 |
-
continue
|
| 52 |
-
# Use local cadence: a true timestamp hole is not explained by a high/low FPS label.
|
| 53 |
-
dt = np.diff(times[i-3:i+4])
|
| 54 |
-
if dt.max() > 3*np.median(dt):
|
| 55 |
-
continue
|
| 56 |
-
bats = [[b for b in rows[k]['bat'] if b.get('points') is not None] for k in (i-1, i, i+1)]
|
| 57 |
-
if any(len(b) != 1 for b in bats):
|
| 58 |
-
continue
|
| 59 |
-
previous, ends, following = (np.asarray(b[0]['points'], float) for b in bats)
|
| 60 |
-
length = float(np.linalg.norm(ends[1]-ends[0]))
|
| 61 |
-
if not np.isfinite(length) or length < 12:
|
| 62 |
-
continue
|
| 63 |
-
after,after_ids = _branch(rows,times,i,'after',length)
|
| 64 |
-
if after is None:
|
| 65 |
-
continue
|
| 66 |
-
# Infer stationary tee versus moving incoming ball from observed motion, not a required form field.
|
| 67 |
-
for stationary in (False, True):
|
| 68 |
-
before,before_ids = _branch(rows,times,i,'before',length,stationary)
|
| 69 |
-
if before is None:
|
| 70 |
-
continue
|
| 71 |
-
ein, incoming, rin, incoming_xy = before
|
| 72 |
-
eout, outgoing, rout, outgoing_xy = after
|
| 73 |
-
if stationary and np.ptp(incoming_xy, axis=0).dot(np.ptp(incoming_xy, axis=0)) > max(2, rin)**2:
|
| 74 |
-
continue
|
| 75 |
-
v, u = incoming[0], outgoing[0]
|
| 76 |
-
change = np.linalg.norm(u-v)*(times[after_ids[-1]]-times[before_ids[0]])
|
| 77 |
-
cosine = np.dot(v, u)/max(np.linalg.norm(v)*np.linalg.norm(u), 1e-9)
|
| 78 |
-
if (not stationary and cosine > .8) or change < 4*max(rin, rout, ein, eout, 1):
|
| 79 |
-
continue
|
| 80 |
-
counts['supported_ball_transitions'] += 1
|
| 81 |
-
delta = u-v
|
| 82 |
-
offset = outgoing[1]-incoming[1]
|
| 83 |
-
relative = -np.dot(offset, delta)/max(np.dot(delta, delta), 1e-9)
|
| 84 |
-
t = float(times[i]+relative)
|
| 85 |
-
if not times[i-1] <= t <= times[i+1]:
|
| 86 |
-
continue
|
| 87 |
-
p, q = incoming[1]+v*relative, outgoing[1]+u*relative
|
| 88 |
-
if np.linalg.norm(p-q) > max(rin, rout)+ein+eout:
|
| 89 |
-
continue
|
| 90 |
-
# A motionless bat beside a ball bounce is insufficient evidence.
|
| 91 |
-
motion = following.mean(axis=0)-previous.mean(axis=0)
|
| 92 |
-
if np.linalg.norm(motion) <= max(2., .02*length) or np.dot(u-v, motion) <= 0:
|
| 93 |
-
continue
|
| 94 |
-
if float(shaft_distance((p+q)/2, ends)) > max(rin, rout)+ein+eout+max(2., .025*length):
|
| 95 |
-
continue
|
| 96 |
-
candidates.append({'index': i, 'time': t, 'interval': [i-1, i+1],
|
| 97 |
-
'support': before_ids+[i]+after_ids, 'residual': float(ein+eout),
|
| 98 |
-
'method': 'observed_stationary_ball_departure_and_bat' if stationary else 'observed_bat_and_ball_deflection',
|
| 99 |
-
'incoming_ball_pixels': incoming_xy.tolist(), 'outgoing_ball_pixels': outgoing_xy.tolist()})
|
| 100 |
-
if not candidates:
|
| 101 |
-
reason = ('bat_endpoints_unobserved_or_ambiguous' if not counts['frames_with_observed_bat_endpoints'] else
|
| 102 |
-
'ball_unobserved' if not counts['frames_with_observed_ball'] else
|
| 103 |
-
'contact_evidence_insufficient')
|
| 104 |
-
return _unknown(reason, counts)
|
| 105 |
-
groups = []
|
| 106 |
-
for c in sorted(candidates, key=lambda x: x['interval'][0]):
|
| 107 |
-
if groups and c['interval'][0] <= max(x['interval'][1] for x in groups[-1]):
|
| 108 |
-
groups[-1].append(c)
|
| 109 |
-
else:
|
| 110 |
-
groups.append([c])
|
| 111 |
-
if len(groups) != 1:
|
| 112 |
-
return _unknown('multiple_contact_candidates', {**counts, 'candidate_group_count': len(groups)})
|
| 113 |
-
group = groups[0]
|
| 114 |
-
best = min(group, key=lambda c: c['residual'])
|
| 115 |
-
a, b = min(c['interval'][0] for c in group), max(c['interval'][1] for c in group)
|
| 116 |
-
idx = min(range(a, b+1), key=lambda k: abs(times[k]-best['time']))
|
| 117 |
-
physical = np.asarray([f['physical_s'] if f['physical_s'] is not None else np.nan for f in capture['frames']], float)
|
| 118 |
-
known = np.isfinite(physical).all() and (np.diff(physical) > 0).all()
|
| 119 |
-
physical -= physical[0]
|
| 120 |
-
capture_value = float(np.interp(best['time'], times, physical)) if known else None
|
| 121 |
-
return ContactEstimate(status='estimated', source_frame_index=idx, frame_interval=(a, b),
|
| 122 |
-
video_time_s=best['time'], video_time_interval_s=(float(times[a]), float(times[b])),
|
| 123 |
-
capture_time_s=capture_value,
|
| 124 |
-
capture_time_interval_s=(float(physical[a]), float(physical[b])) if known else None,
|
| 125 |
-
local_frame_spacing_ms=float(np.diff(times[a:b+1]).max()*1000), method=best['method'],
|
| 126 |
-
reasons=['single_view_visual_estimate', 'accuracy_unvalidated']+([] if known else ['capture_time_unknown']),
|
| 127 |
-
evidence={**counts, 'source_frame_indices': sorted({k for c in group for k in c['support']}),
|
| 128 |
-
'candidate_count': len(group), 'fit_residual_px': best['residual'],
|
| 129 |
-
'fit_coordinate_space': 'stabilized_image_pixels',
|
| 130 |
-
'subframe_time_is_fitted_not_directly_observed': True})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_fast.py
DELETED
|
@@ -1,311 +0,0 @@
|
|
| 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 |
-
visual_started = budget.clock()
|
| 221 |
-
budget_limited = False
|
| 222 |
-
with av.open(str(video), options={'protocol_whitelist': 'file,pipe'}) as container:
|
| 223 |
-
stream = container.streams.video[0]
|
| 224 |
-
stream.thread_count = 2
|
| 225 |
-
for segment, window in enumerate(windows):
|
| 226 |
-
budget.check()
|
| 227 |
-
a, b = window['start_frame'], window['end_frame']
|
| 228 |
-
processed = sum(r['searched'] for r in original)
|
| 229 |
-
if processed:
|
| 230 |
-
# Use this request's observed processing cost, not an assumed
|
| 231 |
-
# FPS or GPU speed. Do not start a second incomplete context
|
| 232 |
-
# when the remaining budget is insufficient for its support.
|
| 233 |
-
expected = (budget.clock()-visual_started)/processed*(b-a+1)
|
| 234 |
-
if budget.ends-budget.clock() < expected+.08:
|
| 235 |
-
budget_limited = True
|
| 236 |
-
break
|
| 237 |
-
source = Fraction(frames[a]['pts'])*Fraction(frames[a]['time_base'])
|
| 238 |
-
container.seek(int(source/stream.time_base), stream=stream, backward=True)
|
| 239 |
-
previous = None; old_boxes = []; transform = np.eye(3); box = None; last = None
|
| 240 |
-
active_segment = segment*100000
|
| 241 |
-
for frame in container.decode(stream):
|
| 242 |
-
budget.check()
|
| 243 |
-
key = frame.pts*(frame.time_base or stream.time_base) if frame.pts is not None else None
|
| 244 |
-
i = by_pts.get(key)
|
| 245 |
-
if i is None:
|
| 246 |
-
raise ValueError('Source timestamps changed during contact search')
|
| 247 |
-
if i < a:
|
| 248 |
-
continue
|
| 249 |
-
if i > b:
|
| 250 |
-
break
|
| 251 |
-
image = frame.to_ndarray(format='bgr24')
|
| 252 |
-
if capture['rotation_degrees']:
|
| 253 |
-
image = np.ascontiguousarray(np.rot90(image, -(capture['rotation_degrees']//90)))
|
| 254 |
-
if last is None:
|
| 255 |
-
people = models.person(image)
|
| 256 |
-
budget.check()
|
| 257 |
-
if people:
|
| 258 |
-
box = max(people, key=lambda p: np.prod(np.asarray(p['box'][2:])-p['box'][:2]))['box']
|
| 259 |
-
roi, offset = _crop(image, box, .35*max(box[2]-box[0], box[3]-box[1])) if box else (image, np.zeros(2, int))
|
| 260 |
-
bats = models.bat(roi, offset)
|
| 261 |
-
budget.check()
|
| 262 |
-
visible = [p for p in bats if p.get('points') is not None]
|
| 263 |
-
target = max(visible or bats, key=lambda x: x['score']) if bats else None
|
| 264 |
-
# A single high-detail crop replaces the old overlapping whole-image tile search.
|
| 265 |
-
if target:
|
| 266 |
-
length = np.linalg.norm(np.asarray(target['box'][2:])-target['box'][:2])
|
| 267 |
-
ball_roi, ball_offset = _crop(image, target['box'], max(64., .65*length))
|
| 268 |
-
else:
|
| 269 |
-
ball_roi, ball_offset = roi, offset
|
| 270 |
-
balls = models.ball(ball_roi, ball_offset)
|
| 271 |
-
budget.check()
|
| 272 |
-
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 273 |
-
boxes = [box] if box is not None else []
|
| 274 |
-
matrix = (background_transform(previous, gray, old_boxes+boxes)
|
| 275 |
-
if previous is not None and previous.shape == gray.shape else None)
|
| 276 |
-
if last is None:
|
| 277 |
-
matrix = np.eye(3)
|
| 278 |
-
elif matrix is None or i != last+1:
|
| 279 |
-
active_segment += 1; transform = np.eye(3)
|
| 280 |
-
if matrix is not None:
|
| 281 |
-
transform = transform @ np.linalg.inv(matrix)
|
| 282 |
-
row = {**original[i], 'bat': bats, 'ball': balls, 'searched': True,
|
| 283 |
-
'segment_id': active_segment,
|
| 284 |
-
'camera_motion_status': 'background_affine_estimated' if matrix is not None else 'unresolved'}
|
| 285 |
-
original[i] = row
|
| 286 |
-
rows[i] = stabilized(row, transform)
|
| 287 |
-
previous = gray; old_boxes = boxes; last = i
|
| 288 |
-
progress('candidate_visual_check', sum(r['searched'] for r in original), len(frames))
|
| 289 |
-
if last != b:
|
| 290 |
-
raise ValueError('Candidate decode incomplete')
|
| 291 |
-
complete.append(window)
|
| 292 |
-
# A supported event is an estimate in the searched window. Do not
|
| 293 |
-
# spend the remaining budget rendering or searching a silent reset.
|
| 294 |
-
result = estimate({'frames': rows}, capture)
|
| 295 |
-
if result.status == 'estimated':
|
| 296 |
-
result.reasons.append('candidate_window_search_only')
|
| 297 |
-
result.evidence.update(search_complete=False, searched_frame_count=sum(r['searched'] for r in original),
|
| 298 |
-
source_frame_count=len(frames), windows_checked=complete)
|
| 299 |
-
return result, original, complete
|
| 300 |
-
result = estimate({'frames': rows}, capture)
|
| 301 |
-
if budget_limited:
|
| 302 |
-
result.reasons.append('search_budget_limited')
|
| 303 |
-
result.evidence.update(search_complete=all(r['searched'] for r in original),
|
| 304 |
-
searched_frame_count=sum(r['searched'] for r in original), source_frame_count=len(frames), windows_checked=complete,
|
| 305 |
-
budget_limited=budget_limited)
|
| 306 |
-
return result, original, complete
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
def unavailable(reason):
|
| 310 |
-
return ContactEstimate(status='unavailable', reasons=[reason], evidence={
|
| 311 |
-
'search_complete': False, 'does_not_establish_a_miss': True})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_fast_worker.py
DELETED
|
@@ -1,157 +0,0 @@
|
|
| 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 .contact_detection import MIN_CONTACT_CONTEXT
|
| 14 |
-
from .storage import atomic_json, read_json, sha256_file
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def source_asset(job, source, checksum, expiry):
|
| 18 |
-
return {'status': 'available', 'url': '/v1/contact-analyses/'+job.name+'/artifacts/source',
|
| 19 |
-
'filename': source.name, 'format': 'original_video', 'media_type': {'.mov': 'video/quicktime',
|
| 20 |
-
'.mkv': 'video/x-matroska', '.webm': 'video/webm', '.avi': 'video/x-msvideo'}.get(source.suffix, 'video/mp4'),
|
| 21 |
-
'size_bytes': source.stat().st_size, 'sha256': checksum, 'expires_at': expiry}
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def initial_result(job, options, *, retention_s=86400, started=None):
|
| 25 |
-
job = Path(job)
|
| 26 |
-
video = next(job.glob('input.*'))
|
| 27 |
-
source = job/('source'+video.suffix)
|
| 28 |
-
if not source.exists():
|
| 29 |
-
os.link(video, source)
|
| 30 |
-
# Hash computed as bytes arrived, outside GPU processing. CLI/test calls
|
| 31 |
-
# without an upload receipt calculate it here and report that elapsed time.
|
| 32 |
-
receipt = read_json(job/'upload.json') if (job/'upload.json').is_file() else {}
|
| 33 |
-
checksum = receipt.get('sha256') or sha256_file(source)
|
| 34 |
-
if receipt and receipt['size_bytes'] != source.stat().st_size:
|
| 35 |
-
raise ValueError('Upload receipt length mismatch')
|
| 36 |
-
expiry = datetime.fromtimestamp(time.time()+retention_s, timezone.utc).isoformat()
|
| 37 |
-
prefix = '/v1/contact-analyses/'+job.name+'/artifacts/'
|
| 38 |
-
artifacts = {'source': source_asset(job, source, checksum, expiry)}
|
| 39 |
-
for key, fmt, media in [('observations', 'jsonl', 'application/x-ndjson'), ('annotated', 'mp4', 'video/mp4'), ('evidence', 'mp4', 'video/mp4')]:
|
| 40 |
-
pending = options.annotated_video and key != 'observations'
|
| 41 |
-
artifacts[key] = {'status': 'pending' if pending else 'unavailable', 'url': prefix+key if pending else None,
|
| 42 |
-
'format': fmt, 'media_type': media, 'expires_at': expiry,
|
| 43 |
-
'reason_code': 'render_pending' if pending else 'not_searched' if key == 'observations' else 'not_requested'}
|
| 44 |
-
return ContactResult(job_id=job.name, contact=unavailable('processing_budget_exceeded'),
|
| 45 |
-
source_video={'sha256': checksum, 'frame_count': None, 'scan_complete': False},
|
| 46 |
-
timing={'video_time': 'source_PTS_minus_first_source_PTS', 'capture_time_available': False,
|
| 47 |
-
'mapping': options.timing.model_dump(mode='json'), 'minimum_fps_required': None,
|
| 48 |
-
'notice': 'Only selected consecutive original frames are inspected. Omitted frames are not interpolated.'},
|
| 49 |
-
pipeline={'version': VERSION, 'mode': 'fast', 'options': options.model_dump(mode='json'),
|
| 50 |
-
'processing_budget_s': options.processing_budget_s, 'deadline_scope': 'processing_after_queue_claim; upload, queue and video rendering excluded',
|
| 51 |
-
'decision_elapsed_s': None, 'requires_pose': False, 'requires_3d': False,
|
| 52 |
-
'object_gap_filling': False, 'contact_verification': 'visual_estimate_only; accuracy_unvalidated',
|
| 53 |
-
'clips': {}, 'models_warm': True},
|
| 54 |
-
audio={'status': 'not_checked', 'used_for_contact_timestamp': False}, artifacts=artifacts,
|
| 55 |
-
rendering={'status': 'pending' if options.annotated_video else 'not_requested'}, expires_at=expiry)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def decide(job, models, *, started=None, retention_s=86400, max_frames=7200, max_pixels=8294400, max_duration=120):
|
| 59 |
-
job = Path(job)
|
| 60 |
-
options = ContactInput.model_validate(read_json(job/'request.json'))
|
| 61 |
-
started = time.monotonic() if started is None else started
|
| 62 |
-
# Leave time for writing the decision and for the parent to publish it.
|
| 63 |
-
budget = Budget(max(.1, options.processing_budget_s-.2), started=started)
|
| 64 |
-
result = initial_result(job, options, retention_s=retention_s, started=started)
|
| 65 |
-
result.pipeline.update(models=models.record, device=models.device)
|
| 66 |
-
video = next(job.glob('input.*'))
|
| 67 |
-
capture = None
|
| 68 |
-
def progress(stage, done=0, total=None):
|
| 69 |
-
atomic_json(job/'progress.json', {'stage': stage, 'completed_frames': done,
|
| 70 |
-
'total_frames': total, 'elapsed_s': round(time.monotonic()-started, 3)})
|
| 71 |
-
try:
|
| 72 |
-
progress('candidate_scan')
|
| 73 |
-
capture, times, motion, ranked = scan(video, options, budget,
|
| 74 |
-
max_frames=max_frames, max_pixels=max_pixels, max_duration=max_duration)
|
| 75 |
-
capture['input_sha256'] = result.source_video['sha256']
|
| 76 |
-
atomic_json(job/'capture-private.json', capture)
|
| 77 |
-
progress('audio_candidate_search')
|
| 78 |
-
result.audio = inspect(video, capture['frames'][0]['playback_s'], float(times[-1]),
|
| 79 |
-
unavailable('not_checked'), options.use_audio, check=budget.check)
|
| 80 |
-
# Start with the minimum actual before/after support the detector needs,
|
| 81 |
-
# centered on each proposal. A large window processed from its beginning
|
| 82 |
-
# can consume the budget before reaching the possible interaction.
|
| 83 |
-
windows = candidate_windows(times, motion, ranked, result.audio, max_window_frames=MIN_CONTACT_CONTEXT)
|
| 84 |
-
result.pipeline['candidate_windows'] = windows
|
| 85 |
-
budget.check()
|
| 86 |
-
if windows:
|
| 87 |
-
result.contact, original, checked = collect_windows(video, capture, windows, models, budget, progress)
|
| 88 |
-
else:
|
| 89 |
-
result.contact = unavailable('no_contact_search_candidate')
|
| 90 |
-
original = []; checked = []
|
| 91 |
-
if original:
|
| 92 |
-
output = job/'observations.jsonl'
|
| 93 |
-
with output.open('w') as out:
|
| 94 |
-
for frame, row in zip(capture['frames'], original):
|
| 95 |
-
out.write(json.dumps({**row, 'source_pts': frame['pts'], 'source_time_base': frame['time_base'],
|
| 96 |
-
'confidence_meaning': 'object detector scores; not contact correctness'}, allow_nan=False)+'\n')
|
| 97 |
-
result.artifacts['observations'] = ContactArtifact.model_validate({'status': 'available',
|
| 98 |
-
'url': '/v1/contact-analyses/'+job.name+'/artifacts/observations', 'filename': output.name,
|
| 99 |
-
'format': 'jsonl', 'media_type': 'application/x-ndjson', 'size_bytes': output.stat().st_size,
|
| 100 |
-
'sha256': sha256_file(output), 'expires_at': result.expires_at})
|
| 101 |
-
result.pipeline.update(windows_checked=checked, models=models.record, device=models.device,
|
| 102 |
-
searched_frame_count=sum(r.get('searched', False) for r in original))
|
| 103 |
-
if result.contact.video_time_interval_s:
|
| 104 |
-
a, b = result.contact.video_time_interval_s
|
| 105 |
-
result.audio['near_visual_contact_times_s'] = [t for t in result.audio.get('transient_video_times_s', []) if a-.03 <= t <= b+.25]
|
| 106 |
-
except BudgetExpired:
|
| 107 |
-
# A deadline is not a miss. Never choose a sound peak as a fallback hit.
|
| 108 |
-
result.contact = unavailable('processing_budget_exceeded')
|
| 109 |
-
result.pipeline['budget_exhausted'] = True
|
| 110 |
-
if capture is not None:
|
| 111 |
-
frames = capture['frames']
|
| 112 |
-
intervals = np.diff([f['playback_s'] for f in frames])*1000
|
| 113 |
-
result.source_video.update(frame_count=len(frames), scan_complete=True,
|
| 114 |
-
display_width=frames[0]['width'], display_height=frames[0]['height'],
|
| 115 |
-
rotation_degrees_applied=capture['rotation_degrees'], last_frame_video_time_s=frames[-1]['playback_s']-frames[0]['playback_s'],
|
| 116 |
-
timeline_origin_pts=frames[0]['pts'], timeline_origin_time_base=frames[0]['time_base'])
|
| 117 |
-
result.timing.update(capture_time_available=capture['physical_clock_known'],
|
| 118 |
-
minimum_frame_spacing_ms=float(intervals.min()), maximum_frame_spacing_ms=float(intervals.max()))
|
| 119 |
-
result.pipeline['decision_elapsed_s'] = round(time.monotonic()-started, 4)
|
| 120 |
-
result.pipeline['budget_exhausted'] = 'processing_budget_exceeded' in result.contact.reasons
|
| 121 |
-
atomic_json(job/'fast-result.json', result.model_dump(mode='json'))
|
| 122 |
-
return result
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def main():
|
| 126 |
-
parser = argparse.ArgumentParser()
|
| 127 |
-
parser.add_argument('--models', required=True)
|
| 128 |
-
parser.add_argument('--root', required=True)
|
| 129 |
-
args = parser.parse_args()
|
| 130 |
-
root = Path(args.root).resolve()
|
| 131 |
-
cv_threads = __import__('cv2'); cv_threads.setNumThreads(2)
|
| 132 |
-
# First-request imports are warmed outside the per-video budget, too.
|
| 133 |
-
import av
|
| 134 |
-
from scipy.signal import find_peaks
|
| 135 |
-
try:
|
| 136 |
-
models = ContactModels(args.models)
|
| 137 |
-
atomic_json(root/'contact-ready.json', {'ready': True, 'models': models.record, 'pid': os.getpid()})
|
| 138 |
-
except Exception as error:
|
| 139 |
-
atomic_json(root/'contact-ready.json', {'ready': False, 'reason': type(error).__name__})
|
| 140 |
-
raise
|
| 141 |
-
for line in sys.stdin:
|
| 142 |
-
command = json.loads(line)
|
| 143 |
-
identifier = command['job_id']
|
| 144 |
-
if len(identifier) != 32 or any(c not in '0123456789abcdef' for c in identifier):
|
| 145 |
-
raise ValueError('Invalid worker job ID')
|
| 146 |
-
job = root/'jobs'/identifier
|
| 147 |
-
try:
|
| 148 |
-
decide(job, models, **command['limits'])
|
| 149 |
-
atomic_json(job/'fast-done.json', {'ok': True})
|
| 150 |
-
except Exception as error:
|
| 151 |
-
atomic_json(job/'fast-done.json', {'ok': False, 'error_type': type(error).__name__,
|
| 152 |
-
'code': 'invalid_video_or_capture' if isinstance(error, ValueError) else 'inference_failed'})
|
| 153 |
-
print('Contact decision failed: '+type(error).__name__, file=sys.stderr, flush=True)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
if __name__ == '__main__':
|
| 157 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_render_worker.py
DELETED
|
@@ -1,73 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,202 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,66 +0,0 @@
|
|
| 1 |
-
"""Source-timed bat/ball overlays and a contact-evidence clip."""
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import cv2
|
| 4 |
-
import numpy as np
|
| 5 |
-
from .ingest import iter_frames
|
| 6 |
-
from .swing_clips import _Writer, _source_time, _ticks, TIME_BASE, ClipError
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def draw(image, row, contact, index):
|
| 10 |
-
image=image.copy()
|
| 11 |
-
thickness=max(1,round(image.shape[1]/640))
|
| 12 |
-
for bat in row['bat']:
|
| 13 |
-
if bat.get('points') is not None:
|
| 14 |
-
a,b=np.rint(bat['points']).astype(int)
|
| 15 |
-
cv2.line(image,tuple(a),tuple(b),(90,225,130),thickness+1,cv2.LINE_AA)
|
| 16 |
-
for ball in row['ball']:
|
| 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
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def export(video,capture,rows,contact,job,progress=lambda *a:None):
|
| 30 |
-
job=Path(job);frames=capture['frames'];n=len(frames)
|
| 31 |
-
source=[_source_time(f) for f in frames]
|
| 32 |
-
if any(b<=a for a,b in zip(source,source[1:])):
|
| 33 |
-
raise ClipError('source_timestamps_invalid')
|
| 34 |
-
origin=source[0];timeline=[_ticks(t-origin) for t in source]
|
| 35 |
-
a=b=None
|
| 36 |
-
if contact.video_time_interval_s:
|
| 37 |
-
lo,hi=contact.video_time_interval_s
|
| 38 |
-
times=[float(t-origin) for t in source]
|
| 39 |
-
a=max(0,int(np.searchsorted(times,max(0,lo-.35)))-1)
|
| 40 |
-
b=min(n-1,int(np.searchsorted(times,hi+.35)))
|
| 41 |
-
writers={};metadata={}
|
| 42 |
-
temporary={k:job/('.'+k+'.tmp.mp4') for k in ('annotated','evidence')}
|
| 43 |
-
try:
|
| 44 |
-
for i,pts,base,image,duration in iter_frames(video,capture['rotation_degrees'],include_duration=True):
|
| 45 |
-
if i>=n or pts*base!=source[i]:raise ClipError('source_video_mismatch')
|
| 46 |
-
ticks=timeline[i+1]-timeline[i] if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
|
| 47 |
-
if ticks<=0:raise ClipError('last_frame_duration_unavailable')
|
| 48 |
-
image=draw(image,rows[i],contact,i)
|
| 49 |
-
keys=['annotated']+(['evidence'] if a is not None and a<=i<=b else [])
|
| 50 |
-
for key in keys:
|
| 51 |
-
if key not in writers:writers[key]=_Writer(temporary[key],image.shape)
|
| 52 |
-
writers[key].write(image,timeline[i]-(timeline[a] if key=='evidence' else 0),ticks)
|
| 53 |
-
if i%32==0 or i==n-1:progress('annotated_video',i+1,n)
|
| 54 |
-
for key,writer in writers.items():
|
| 55 |
-
writer.finish()
|
| 56 |
-
expected=n if key=='annotated' else b-a+1
|
| 57 |
-
if writer.count!=expected:raise ClipError('clip_frame_count_mismatch')
|
| 58 |
-
temporary[key].replace(job/(key+'.mp4'))
|
| 59 |
-
metadata[key]={'frame_count':writer.count,'duration_s':writer.end*float(TIME_BASE),
|
| 60 |
-
'source_start_frame':a if key=='evidence' else 0,
|
| 61 |
-
'source_end_frame':b if key=='evidence' else n-1,
|
| 62 |
-
'source_video_start_s':float(source[a]-origin) if key=='evidence' else 0.,'has_audio':False}
|
| 63 |
-
return metadata
|
| 64 |
-
finally:
|
| 65 |
-
for key,writer in writers.items():
|
| 66 |
-
if temporary[key].exists():writer.abort();temporary[key].unlink(missing_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_vision.py
DELETED
|
@@ -1,92 +0,0 @@
|
|
| 1 |
-
"""Video-only object observations with automatic crop search and camera checks."""
|
| 2 |
-
import numpy as np
|
| 3 |
-
import cv2
|
| 4 |
-
from .tracking_vision import TrackingModel, frame_detections, deduplicate
|
| 5 |
-
from .detection import YOLOXDetector
|
| 6 |
-
from .ingest import iter_frames
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
def background_transform(previous, current, boxes):
|
| 10 |
-
scale = min(1., 640/max(current.shape))
|
| 11 |
-
size = (round(current.shape[1]*scale), round(current.shape[0]*scale))
|
| 12 |
-
a, b = cv2.resize(previous, size), cv2.resize(current, size)
|
| 13 |
-
mask = np.full(a.shape, 255, np.uint8)
|
| 14 |
-
for box in boxes:
|
| 15 |
-
if box is None:
|
| 16 |
-
continue
|
| 17 |
-
x1,y1,x2,y2 = np.rint(np.asarray(box)*scale).astype(int)
|
| 18 |
-
cv2.rectangle(mask, (max(0,x1-8),max(0,y1-8)), (min(size[0],x2+8),min(size[1],y2+8)), 0, -1)
|
| 19 |
-
points = cv2.goodFeaturesToTrack(a, 250, .02, 8, mask=mask)
|
| 20 |
-
if points is None or len(points) < 12:
|
| 21 |
-
return None
|
| 22 |
-
moved, status, _ = cv2.calcOpticalFlowPyrLK(a,b,points,None)
|
| 23 |
-
if moved is None:
|
| 24 |
-
return None
|
| 25 |
-
back, reverse, _ = cv2.calcOpticalFlowPyrLK(b,a,moved,None)
|
| 26 |
-
if back is None:
|
| 27 |
-
return None
|
| 28 |
-
good = (status[:,0]>0)&(reverse[:,0]>0)&(np.linalg.norm(back[:,0]-points[:,0],axis=-1)<1.5)
|
| 29 |
-
if good.sum() < 12:
|
| 30 |
-
return None
|
| 31 |
-
transform, inliers = cv2.estimateAffinePartial2D(points[good,0],moved[good,0],method=cv2.RANSAC,ransacReprojThreshold=2.)
|
| 32 |
-
if transform is None or inliers is None or inliers.sum() < 12 or inliers.mean() < .6:
|
| 33 |
-
return None
|
| 34 |
-
# Features must cover more than a tiny foreground patch.
|
| 35 |
-
selected = points[good,0][inliers[:,0]>0]
|
| 36 |
-
if np.prod(np.ptp(selected,axis=0))/np.prod(size) < .08:
|
| 37 |
-
return None
|
| 38 |
-
transform[:,2] /= scale
|
| 39 |
-
matrix = np.vstack([transform,[0,0,1]])
|
| 40 |
-
if not np.isfinite(matrix).all() or not .8 < np.linalg.det(matrix[:2,:2]) < 1.2:
|
| 41 |
-
return None
|
| 42 |
-
return matrix
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def stabilized(row, matrix):
|
| 46 |
-
def point(p):
|
| 47 |
-
q = matrix @ np.r_[p, 1.]
|
| 48 |
-
return q[:2].tolist()
|
| 49 |
-
scale = float(np.sqrt(abs(np.linalg.det(matrix[:2,:2]))))
|
| 50 |
-
return {**row, 'bat':[{**b,'points':[point(p) for p in b['points']] if b.get('points') is not None else None} for b in row['bat']],
|
| 51 |
-
'ball':[{**b,'point':point(b['point']),'radius_px':b['radius_px']*scale} for b in row['ball']]}
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def collect(video, capture, models, progress=lambda *a:None, device='cuda'):
|
| 55 |
-
from .api_worker import model_files
|
| 56 |
-
paths,_ = model_files(models)
|
| 57 |
-
person = YOLOXDetector(paths['person_detector'], device, classes=[0])
|
| 58 |
-
bat, ball = TrackingModel(models,'bat',device), TrackingModel(models,'ball',device)
|
| 59 |
-
original, observations = [], []
|
| 60 |
-
previous = None; old_boxes = []; segment = 0; transform = np.eye(3)
|
| 61 |
-
for i,pts,base,image in iter_frames(video,capture['rotation_degrees']):
|
| 62 |
-
record = capture['frames'][i]
|
| 63 |
-
if pts != record['pts'] or str(base) != record['time_base']:
|
| 64 |
-
raise ValueError('Source timestamps changed during tracking')
|
| 65 |
-
people = person(image)
|
| 66 |
-
boxes = [p['box'] for p in sorted(people,key=lambda p:np.prod(np.asarray(p['box'][2:])-p['box'][:2]),reverse=True)[:2]]
|
| 67 |
-
row = frame_detections(image,bat,ball,boxes[0] if boxes else None)
|
| 68 |
-
# Additional person-scale crop improves small/blurred bat visibility without supplied ROI.
|
| 69 |
-
if boxes:
|
| 70 |
-
x1,y1,x2,y2 = boxes[0]; pad=.3*max(x2-x1,y2-y1)
|
| 71 |
-
a=np.maximum(0,np.array([x1-pad,y1-pad])).astype(int)
|
| 72 |
-
b=np.minimum(image.shape[1::-1],np.array([x2+pad,y2+pad])).astype(int)
|
| 73 |
-
if min(b-a)>16:
|
| 74 |
-
roi=image[a[1]:b[1],a[0]:b[0]]
|
| 75 |
-
row['bat']=deduplicate(row['bat']+bat(roi,a))
|
| 76 |
-
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
|
| 77 |
-
matrix=(background_transform(previous,gray,old_boxes+boxes) if previous.shape==gray.shape else None) if previous is not None else np.eye(3)
|
| 78 |
-
if matrix is None:
|
| 79 |
-
segment+=1;transform=np.eye(3)
|
| 80 |
-
else:
|
| 81 |
-
transform=transform@np.linalg.inv(matrix)
|
| 82 |
-
row.update(source_frame_index=i,segment_id=segment,
|
| 83 |
-
image_width=image.shape[1],image_height=image.shape[0],
|
| 84 |
-
video_time_s=float(record['playback_s']-capture['frames'][0]['playback_s']),
|
| 85 |
-
camera_motion_status='unresolved' if matrix is None else 'background_affine_estimated')
|
| 86 |
-
original.append(row)
|
| 87 |
-
observations.append(stabilized(row,transform))
|
| 88 |
-
previous=gray;old_boxes=boxes
|
| 89 |
-
progress('bat_ball_tracking',i+1,capture['frame_count'])
|
| 90 |
-
if len(original)!=capture['frame_count']:
|
| 91 |
-
raise ValueError('Tracking decode differs from source')
|
| 92 |
-
return {'frames':observations}, original, {'bat':bat.record,'ball':ball.record}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
baseball_batting/contact_worker.py
DELETED
|
@@ -1,115 +0,0 @@
|
|
| 1 |
-
"""Isolated GPU contact job. Video is the only required client input."""
|
| 2 |
-
import argparse
|
| 3 |
-
from datetime import datetime,timezone
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import json
|
| 6 |
-
import os
|
| 7 |
-
import time
|
| 8 |
-
import numpy as np
|
| 9 |
-
from .contact_contract import ContactInput,ContactResult
|
| 10 |
-
from .contact_detection import estimate,VERSION
|
| 11 |
-
from .ingest import ingest
|
| 12 |
-
from .storage import atomic_json,read_json,sha256_file
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retention_s=86400,device='cuda'):
|
| 16 |
-
from .contact_vision import collect
|
| 17 |
-
from .contact_audio import inspect
|
| 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)})
|
| 35 |
-
video=next(job.glob('input.*'));progress('decoding')
|
| 36 |
-
capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
|
| 37 |
-
playback=np.asarray([f['playback_s'] for f in capture['frames']],float)
|
| 38 |
-
if not np.isfinite(playback).all() or len(playback)<2 or np.any(np.diff(playback)<=0):
|
| 39 |
-
raise ValueError('invalid_source_timestamps')
|
| 40 |
-
atomic_json(job/'capture-private.json',capture)
|
| 41 |
-
observed,original,model=collect(video,capture,models,progress,device)
|
| 42 |
-
progress('contact_estimation',len(original),len(original));contact=estimate(observed,capture)
|
| 43 |
-
# Public observations are original upright pixels, never the stabilized fit coordinate system.
|
| 44 |
-
with (job/'observations.jsonl').open('w') as out:
|
| 45 |
-
for frame,row in zip(capture['frames'],original):
|
| 46 |
-
out.write(json.dumps({**row,'source_pts':frame['pts'],'source_time_base':frame['time_base'],
|
| 47 |
-
'confidence_meaning':'object detector scores; not contact correctness'},allow_nan=False)+'\n')
|
| 48 |
-
duration=float(playback[-1]-playback[0])
|
| 49 |
-
audio=inspect(video,float(playback[0]),duration,contact,options.use_audio)
|
| 50 |
-
clips={};video_export_reason=None
|
| 51 |
-
if options.annotated_video:
|
| 52 |
-
try:clips=export(video,capture,original,contact,job,progress)
|
| 53 |
-
except ClipError as error:
|
| 54 |
-
# Some valid containers omit final sample duration. Do not invent
|
| 55 |
-
# FPS/durations or discard an otherwise usable contact result.
|
| 56 |
-
video_export_reason=str(error)
|
| 57 |
-
source=job/('source'+video.suffix)
|
| 58 |
-
if source.exists():
|
| 59 |
-
if sha256_file(source)!=capture['input_sha256']:raise ValueError('Source differs from retained input')
|
| 60 |
-
else:os.link(video,source)
|
| 61 |
-
expiry=datetime.fromtimestamp(time.time()+retention_s,timezone.utc).isoformat()
|
| 62 |
-
prefix='/v1/contact-analyses/'+job.name+'/artifacts/'
|
| 63 |
-
def asset(name,path,fmt,media):
|
| 64 |
-
return {'status':'available','url':prefix+name,'filename':path.name,'format':fmt,
|
| 65 |
-
'media_type':media,'size_bytes':path.stat().st_size,'sha256':sha256_file(path),'expires_at':expiry}
|
| 66 |
-
artifacts={'observations':asset('observations',job/'observations.jsonl','jsonl','application/x-ndjson'),
|
| 67 |
-
'source':asset('source',source,'original_video',{'.mov':'video/quicktime','.webm':'video/webm',
|
| 68 |
-
'.mkv':'video/x-matroska','.avi':'video/x-msvideo'}.get(video.suffix,'video/mp4'))}
|
| 69 |
-
for key in ('annotated','evidence'):
|
| 70 |
-
artifacts[key]=asset(key,job/(key+'.mp4'),'mp4','video/mp4') if key in clips else {
|
| 71 |
-
'status':'unavailable','format':'mp4','media_type':'video/mp4','expires_at':expiry,
|
| 72 |
-
'reason_code':('not_requested' if not options.annotated_video else
|
| 73 |
-
video_export_reason or 'contact_not_located')}
|
| 74 |
-
result=ContactResult(job_id=job.name,contact=contact,audio=audio,expires_at=expiry,
|
| 75 |
-
source_video={'sha256':capture['input_sha256'],'frame_count':len(original),
|
| 76 |
-
'display_width':capture['frames'][0]['width'],'display_height':capture['frames'][0]['height'],
|
| 77 |
-
'rotation_degrees_applied':capture['rotation_degrees'],'last_frame_video_time_s':duration,
|
| 78 |
-
'timeline_origin_pts':capture['frames'][0]['pts'],'timeline_origin_time_base':capture['frames'][0]['time_base']},
|
| 79 |
-
timing={'video_time':'source_PTS_minus_first_source_PTS','capture_time_available':capture['physical_clock_known'],
|
| 80 |
-
'mapping':options.timing.model_dump(mode='json'),'minimum_fps_required':None,'frames_skipped':0,
|
| 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')},
|
| 89 |
-
'requires_pose':False,'requires_3d':False,'requires_manual_events':False,
|
| 90 |
-
'object_gap_filling':False,'contact_verification':'visual_estimate_only; independent_accuracy_validation_pending',
|
| 91 |
-
'clips':clips,'video_export_reason':video_export_reason},artifacts=artifacts)
|
| 92 |
-
atomic_json(job/'result.json',result.model_dump(mode='json'));progress('complete',len(original),len(original))
|
| 93 |
-
return result
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def main():
|
| 97 |
-
parser=argparse.ArgumentParser()
|
| 98 |
-
for key in ('job','models'):parser.add_argument('--'+key,required=True)
|
| 99 |
-
parser.add_argument('--max-frames',type=int,default=7200)
|
| 100 |
-
parser.add_argument('--max-pixels',type=int,default=8294400)
|
| 101 |
-
parser.add_argument('--max-duration',type=float,default=120)
|
| 102 |
-
parser.add_argument('--retention-s',type=float,default=86400)
|
| 103 |
-
args=parser.parse_args()
|
| 104 |
-
try:
|
| 105 |
-
run(args.job,args.models,max_frames=args.max_frames,max_pixels=args.max_pixels,max_duration=args.max_duration,retention_s=args.retention_s)
|
| 106 |
-
return 0
|
| 107 |
-
except Exception as error:
|
| 108 |
-
atomic_json(Path(args.job)/'error.json',{'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
|
| 109 |
-
'reason_code':'invalid_source_timestamps' if str(error)=='invalid_source_timestamps' else 'contact_processing_failed',
|
| 110 |
-
'error_type':type(error).__name__})
|
| 111 |
-
print(type(error).__name__+': '+str(error),flush=True)
|
| 112 |
-
return 1
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
if __name__=='__main__':raise SystemExit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
| 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") == "CUDAExecutionProvider" 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 =
|
| 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'):
|
| 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 |
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
|
deploy/huggingface/removed-files.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Retired standalone contact API files from previous Space deployments.
|
| 2 |
+
baseball_batting/contact_api.py
|
| 3 |
+
baseball_batting/contact_contract.py
|
| 4 |
+
baseball_batting/contact_worker.py
|
| 5 |
+
baseball_batting/contact_detection.py
|
| 6 |
+
baseball_batting/contact_vision.py
|
| 7 |
+
baseball_batting/contact_audio.py
|
| 8 |
+
baseball_batting/contact_videos.py
|
| 9 |
+
baseball_batting/contact_fast.py
|
| 10 |
+
baseball_batting/contact_fast_worker.py
|
| 11 |
+
baseball_batting/contact_runtime.py
|
| 12 |
+
baseball_batting/contact_render_worker.py
|
| 13 |
+
tests/test_contact_api.py
|
| 14 |
+
tests/test_contact_detection.py
|
| 15 |
+
tests/test_contact_fast.py
|
| 16 |
+
docs/CONTACT_API.md
|
| 17 |
+
docs/CONTACT_VALIDATION.md
|
| 18 |
+
docs/contact-input.schema.json
|
| 19 |
+
docs/contact-result.schema.json
|
| 20 |
+
tools/benchmark_contact_api.py
|
docs/CONTACT_API.md
DELETED
|
@@ -1,244 +0,0 @@
|
|
| 1 |
-
# Single-video bat–ball contact API
|
| 2 |
-
|
| 3 |
-
The separate contact API accepts **one video as its only required input**. It
|
| 4 |
-
estimates a visible bat/ball interaction and exports the supporting observations
|
| 5 |
-
and annotated video. SAM, GVHMR, body pose, player height, camera calibration,
|
| 6 |
-
manual event frames, a Gemini key, and a fixed recording FPS are not required.
|
| 7 |
-
|
| 8 |
-
This is a visual estimate, **not validated contact verification**. Do not turn
|
| 9 |
-
`contact.status: estimated` into a verified impact or apply validated laboratory
|
| 10 |
-
contact benchmarks automatically. No observed contact does not establish a miss
|
| 11 |
-
or a dry swing. The existing motion, coaching, and load-timing APIs are unchanged;
|
| 12 |
-
this endpoint does not modify their results or send a coaching payload.
|
| 13 |
-
|
| 14 |
-
## Requests and endpoints
|
| 15 |
-
|
| 16 |
-
Base URL: `https://modventures-baseball-engine.hf.space`
|
| 17 |
-
|
| 18 |
-
All `/v1/` routes need the existing server Bearer key. Keep that key on your app
|
| 19 |
-
backend. Upload the recording through your backend/proxy and enforce job ownership.
|
| 20 |
-
|
| 21 |
-
| Method and path | Purpose |
|
| 22 |
-
| --- | --- |
|
| 23 |
-
| `POST /v1/contact-analyses` | Multipart upload; returns 202 with job/status/result URLs. |
|
| 24 |
-
| `GET /v1/contact-analyses/{job_id}` | Poll queued/processing/completed/failed/cancelled status. |
|
| 25 |
-
| `GET /v1/contact-analyses/{job_id}/result` | Completed contact result; 409 before completion. |
|
| 26 |
-
| `GET` / `HEAD /v1/contact-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; video byte ranges supported. |
|
| 27 |
-
| `DELETE /v1/contact-analyses/{job_id}` | Cancel/delete retained job data. |
|
| 28 |
-
| `GET /v1/contact-analyses/capabilities` | GPU/model readiness, limits and retention. |
|
| 29 |
-
| `GET /v1/contact-analyses/input-schema` | Current optional-options JSON schema. |
|
| 30 |
-
| `GET /v1/contact-analyses/output-schema` | Current result JSON schema. |
|
| 31 |
-
|
| 32 |
-
In Postman, choose **Body → form-data** and add `video` as a **File**. Select the
|
| 33 |
-
video and send. Do not manually set multipart Content-Type; Postman supplies its
|
| 34 |
-
boundary. No `options` field is necessary. Swagger at `/docs` also supports upload.
|
| 35 |
-
|
| 36 |
-
Optional `options` is a **Text** field containing JSON:
|
| 37 |
-
|
| 38 |
-
```json
|
| 39 |
-
{
|
| 40 |
-
"mode": "fast",
|
| 41 |
-
"processing_budget_s": 5,
|
| 42 |
-
"annotated_video": true,
|
| 43 |
-
"use_audio": true,
|
| 44 |
-
"timing": {"kind": "unknown"}
|
| 45 |
-
}
|
| 46 |
-
```
|
| 47 |
-
|
| 48 |
-
Those are the defaults. `rotation_degrees` optionally overrides source orientation
|
| 49 |
-
with 0, 90, 180 or 270 clockwise. Unknown fields, including `fps`, are rejected.
|
| 50 |
-
Do not supply capture speed just to obtain non-null physical timing.
|
| 51 |
-
|
| 52 |
-
If original speed is documented, the existing timing structure is supported:
|
| 53 |
-
|
| 54 |
-
```json
|
| 55 |
-
{"timing": {"kind": "unretimed", "source": "Original recording; no speed changes"}}
|
| 56 |
-
```
|
| 57 |
-
|
| 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.2)
|
| 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 |
-
Each initial visual check uses the detector's minimum seven consecutive source
|
| 67 |
-
frames (three before, one candidate, three after), centered on its proposal, so
|
| 68 |
-
the budget reaches both sides of the possible interaction. Only those frames receive bat/ball inference,
|
| 69 |
-
with one bat crop and one ball crop per frame. Audio locates candidates; the
|
| 70 |
-
same visual bat-sweep/ball-deflection rule still decides the result. Audio alone
|
| 71 |
-
never supplies a contact time. A supported estimate can stop the remaining
|
| 72 |
-
candidate search; `candidate_window_search_only` explicitly limits its scope.
|
| 73 |
-
After a window, the worker uses the measured processing cost to avoid starting
|
| 74 |
-
another context it cannot finish in the remaining time; `search_budget_limited`
|
| 75 |
-
records that restricted search. Full mode can examine longer observed paths.
|
| 76 |
-
|
| 77 |
-
The default processing budget is **5 seconds**. Set `processing_budget_s` to any
|
| 78 |
-
finite value of at least 1 second; there is no upper cap. Both the worker and its
|
| 79 |
-
supervisor honor that requested budget. The cooperative deadline reserves time to publish JSON;
|
| 80 |
-
the parent process also supervises and kills a stuck GPU/decoder request. On
|
| 81 |
-
expiry a successful job returns unavailable contact with
|
| 82 |
-
`reasons: ["processing_budget_exceeded"]`, **not a fabricated hit or a miss**.
|
| 83 |
-
It may leave source-video frame count/clock details unknown if the scan did not
|
| 84 |
-
finish. This is a bounded attempt, not a guarantee of finding contact in five
|
| 85 |
-
seconds. The reported `pipeline.decision_elapsed_s`, `deadline_met` and
|
| 86 |
-
`budget_exhausted` expose the observed behavior; OS/storage stalls can overrun.
|
| 87 |
-
|
| 88 |
-
The budget starts when a warm worker claims the job. It **excludes upload,
|
| 89 |
-
queue wait, model warmup and annotation rendering**. The shared GPU queue is
|
| 90 |
-
unchanged. Warmup has its own readiness state; a fast upload during rewarm returns
|
| 91 |
-
503 `fast_worker_warming` and `Retry-After: 2`. Heavy SAM/GVHMR jobs release the
|
| 92 |
-
contact models' GPU memory; the worker warms again before the next fast request.
|
| 93 |
-
There is no five-second end-to-end guarantee for arbitrary uploads or concurrent
|
| 94 |
-
traffic. Inspect `GET /v1/contact-analyses/capabilities` before offering that SLA.
|
| 95 |
-
|
| 96 |
-
The initial completed result can have:
|
| 97 |
-
|
| 98 |
-
```json
|
| 99 |
-
{
|
| 100 |
-
"schema_version": "1.1",
|
| 101 |
-
"rendering": {"status": "pending"},
|
| 102 |
-
"artifacts_revision": 0,
|
| 103 |
-
"artifacts": {
|
| 104 |
-
"annotated": {"status": "pending", "reason_code": "render_pending"}
|
| 105 |
-
}
|
| 106 |
-
}
|
| 107 |
-
```
|
| 108 |
-
|
| 109 |
-
This is a partial response excerpt, not a complete result. Display the contact
|
| 110 |
-
JSON immediately. Poll the **same result URL** until `rendering.status` is
|
| 111 |
-
`completed` or `failed`. A pending artifact URL returns 202 with `Retry-After: 1`;
|
| 112 |
-
only play/download it after its status is `available`. A CPU-only background
|
| 113 |
-
process renders the videos without holding the GPU queue. Publication increments
|
| 114 |
-
`artifacts_revision`, saves an immutable rendered snapshot, then atomically
|
| 115 |
-
switches its SQLite checksum pointer under the download lock. The original
|
| 116 |
-
decision file never changes; a restart between saving and publication still
|
| 117 |
-
serves a consistent previous result. Contact/timing fields are checked against
|
| 118 |
-
the base decision on reads and never change during rendering.
|
| 119 |
-
Restart resumes pending renders; cancellation/deletion stops their process.
|
| 120 |
-
`annotated_video: false` skips rendering entirely.
|
| 121 |
-
|
| 122 |
-
Use `"mode": "full"` to retain the previous exhaustive scan and synchronous
|
| 123 |
-
annotation behavior. The requested processing budget applies only to `fast`.
|
| 124 |
-
Existing version-1.0 stored results remain readable. Motion/product/coaching
|
| 125 |
-
endpoints and their schemas are unchanged.
|
| 126 |
-
|
| 127 |
-
CUDA is the default backend in the current Docker image. The resident tracking
|
| 128 |
-
adapter can use TensorRT FP16 when a compatible TensorRT Python/runtime package
|
| 129 |
-
is installed (`BASEBALL_CONTACT_TENSORRT=auto`, or `0` to disable). Compilation
|
| 130 |
-
and cache initialization happen during warmup, not per request. The cache path
|
| 131 |
-
is `BASEBALL_CONTACT_ENGINE_CACHE`, default `/data/contact-engines`. Models report
|
| 132 |
-
their actual ONNX providers and executed GPU operators are checked. The base
|
| 133 |
-
image does not install TensorRT; this release must not be described as a measured
|
| 134 |
-
TensorRT speedup.
|
| 135 |
-
|
| 136 |
-
The queue shares the existing GPU service and cancellation/retention machinery.
|
| 137 |
-
The bat and ball models must pass CUDA preflight. Defaults are 512 MiB upload,
|
| 138 |
-
120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
|
| 139 |
-
server settings. A high-frame-rate clip can reach the frame cap sooner; there is
|
| 140 |
-
no minimum-FPS rule. Full mode examines every frame; fast mode inspects selected
|
| 141 |
-
consecutive windows without resampling their timestamps or filling omitted data.
|
| 142 |
-
Retention depends on the server's storage: an ephemeral Space rebuild can remove
|
| 143 |
-
jobs earlier. Your app should retain completed report assets in its own storage.
|
| 144 |
-
|
| 145 |
-
## Response and timing
|
| 146 |
-
|
| 147 |
-
The upload response contains `job_id`, `status_url`, `result_url`, and
|
| 148 |
-
`retention_hours`. Follow those URLs rather than constructing another API's path.
|
| 149 |
-
|
| 150 |
-
On completion, inspect `contact.status`:
|
| 151 |
-
|
| 152 |
-
- `estimated`: a single supported visual interaction interval was found.
|
| 153 |
-
- `unavailable`: insufficient/ambiguous evidence; all contact locations are null.
|
| 154 |
-
|
| 155 |
-
For an estimate, `contact` includes:
|
| 156 |
-
|
| 157 |
-
| Field | Meaning |
|
| 158 |
-
| --- | --- |
|
| 159 |
-
| `source_frame_index` | Nearest decoded source frame to the fitted estimate. Zero-based. |
|
| 160 |
-
| `frame_interval` | Inclusive source-frame interval supporting the transition. |
|
| 161 |
-
| `video_time_s` | Fitted estimate on the source playback timeline, elapsed from first video PTS. |
|
| 162 |
-
| `video_time_interval_s` | Source-frame bounds of the observed transition. Not a calibrated accuracy interval. |
|
| 163 |
-
| `capture_time_s`, `capture_time_interval_s` | Corresponding physical times only when a documented mapping was supplied; otherwise null. |
|
| 164 |
-
| `local_frame_spacing_ms` | Largest source sample spacing inside that transition. Not an accuracy guarantee. |
|
| 165 |
-
| `method` | Observed moving-ball deflection or stationary-ball departure with a bat sweep. |
|
| 166 |
-
| `confidence` | Null: no calibrated contact-confidence method exists. |
|
| 167 |
-
| `verified`, `accuracy_validated` | False. A fitted time is not independent verification. |
|
| 168 |
-
| `reasons` | Estimate limitations, or reasons contact could not be located. |
|
| 169 |
-
| `evidence` | Supporting source indices, observation counts, fit residual and coordinate-system description. |
|
| 170 |
-
|
| 171 |
-
At 25 FPS, frames are about 40 ms apart; at 30 FPS, about 33 ms. Such footage is
|
| 172 |
-
accepted. Contact can fall between frames or be blurred/hidden. Subframe fitting
|
| 173 |
-
does not create subframe observations or prove millisecond accuracy. A changed
|
| 174 |
-
playback FPS cannot reveal whether the original recording was retimed.
|
| 175 |
-
|
| 176 |
-
There is no user-supplied tee/live setting: the detector tests a moving incoming
|
| 177 |
-
ball and an observed stationary ball followed by departure. A ball simply
|
| 178 |
-
disappearing, a bat/ball projected overlap, or an arm-extension pose is insufficient.
|
| 179 |
-
|
| 180 |
-
## Artifacts and evidence playback
|
| 181 |
-
|
| 182 |
-
Follow `result.artifacts[name].url` for playback only when its status is `available`;
|
| 183 |
-
`pending` means the background render has not published it yet:
|
| 184 |
-
|
| 185 |
-
| Name | Content |
|
| 186 |
-
| --- | --- |
|
| 187 |
-
| `source` | Original uploaded video, unchanged bytes and original audio. |
|
| 188 |
-
| `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. |
|
| 189 |
-
| `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. |
|
| 190 |
-
| `evidence` | Short annotated clip surrounding a located contact interval; unavailable when no contact is located. |
|
| 191 |
-
|
| 192 |
-
Every available artifact has length, SHA-256, format, media type and expiry.
|
| 193 |
-
Both videos preserve source presentation timing and every included frame; the
|
| 194 |
-
longest dimension is at most 1,280 pixels. Their pixels may be resized; observation
|
| 195 |
-
JSONL remains in original upright source pixels. Use `pipeline.clips` for clip
|
| 196 |
-
source start/end frames and `source_video_start_s`. Add that offset to evidence
|
| 197 |
-
clip playback time to locate the corresponding source video position.
|
| 198 |
-
|
| 199 |
-
The result also includes source orientation, frame count and hash; timestamp
|
| 200 |
-
spacing; actual model/checkpoint hashes and implementation hashes; and optional
|
| 201 |
-
embedded-audio diagnostics. Audio transients can corroborate a visual estimate.
|
| 202 |
-
In fast mode they also propose search windows. They never establish contact, change its timestamp, or convert an unknown result
|
| 203 |
-
into a hit. Sounds may be unrelated, delayed, or offset by editing.
|
| 204 |
-
|
| 205 |
-
## Detection and validation limits
|
| 206 |
-
|
| 207 |
-
Production inference uses the existing pinned BaseballCV bat-shaft keypoint and
|
| 208 |
-
baseball detector ONNX weights on CUDA. Automatic person boxes guide crop search;
|
| 209 |
-
no body-joint reconstruction is run. Background affine tracking stabilizes short
|
| 210 |
-
continuous observation segments. Unresolved camera motion or cuts split support;
|
| 211 |
-
fits cannot cross them. This does not establish a 3D world or independently solve
|
| 212 |
-
parallax and occlusion.
|
| 213 |
-
|
| 214 |
-
The geometry requires independently observed ball paths before and after the
|
| 215 |
-
interaction, compatible bat movement, and one unambiguous transition. High-FPS
|
| 216 |
-
support can use a longer observed path when adjacent ball displacement is tiny.
|
| 217 |
-
Frame gaps, missing observations and multiple candidates remain explicit.
|
| 218 |
-
|
| 219 |
-
Common unavailable reasons:
|
| 220 |
-
|
| 221 |
-
- `insufficient_contact_context`
|
| 222 |
-
- `bat_endpoints_unobserved_or_ambiguous`
|
| 223 |
-
- `ball_unobserved`
|
| 224 |
-
- `contact_evidence_insufficient`
|
| 225 |
-
- `multiple_contact_candidates`
|
| 226 |
-
- `no_contact_search_candidate`
|
| 227 |
-
- `processing_budget_exceeded`
|
| 228 |
-
- `search_budget_limited` (additional limitation when other candidates were not checked)
|
| 229 |
-
- `fast_worker_unavailable` / `fast_worker_exited`
|
| 230 |
-
|
| 231 |
-
A job completes successfully with unavailable contact when detection is uncertain.
|
| 232 |
-
If source timing cannot support a faithful annotation export (for example, a
|
| 233 |
-
missing final-sample duration), the contact JSON and source/observations remain
|
| 234 |
-
available; video artifacts carry the export reason. Playback FPS is not invented.
|
| 235 |
-
Invalid media/timestamps or a worker/model failure instead fail the job. Model
|
| 236 |
-
availability is checked before upload allocation. Limits and readiness are not
|
| 237 |
-
claims that the pretrained models detect every phone recording reliably.
|
| 238 |
-
|
| 239 |
-
Tests cover clock mappings, varied/variable cadence, actual decoded artifact
|
| 240 |
-
timing, camera stabilization, ambiguity, missing evidence, optional audio,
|
| 241 |
-
queue completion, authentication, byte ranges, integrity and cancellation.
|
| 242 |
-
Constructed observations verify calculation behavior, not detector accuracy.
|
| 243 |
-
Record actual real-video test results separately; do not present synthetic success
|
| 244 |
-
as validation on real players.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/CONTACT_VALIDATION.md
DELETED
|
@@ -1,163 +0,0 @@
|
|
| 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.
|
| 74 |
-
|
| 75 |
-
## Fast candidate search (API 1.16.1, 22 October 2026)
|
| 76 |
-
|
| 77 |
-
Code revision `cc303c1` adds a resident GPU worker, audio/motion candidate
|
| 78 |
-
windows, a supervised five-second processing budget, and CPU-only asynchronous
|
| 79 |
-
annotation. Revision `a8710fc` makes the orientation test independent of system
|
| 80 |
-
FFmpeg and adds partial-observation deadline coverage. The original exhaustive
|
| 81 |
-
scan is still selectable with `mode: full`.
|
| 82 |
-
|
| 83 |
-
The 78 targeted contact/existing API checks passed locally. Checks cover actual
|
| 84 |
-
source decoding and orientation metadata, consecutive source-frame IDs, silent
|
| 85 |
-
motion candidates, sound candidates, explicit capture clocks, warm-process reuse,
|
| 86 |
-
hard timeout supervision, cooperative partial-data retention, cancellation,
|
| 87 |
-
pending video responses, source-timed asynchronous rendering, immutable contact
|
| 88 |
-
decisions, snapshot integrity, and restart-safe publication. Positive object
|
| 89 |
-
observations remain constructed fixtures, not pretrained-detector validation.
|
| 90 |
-
The separate coach suite passed 495 checks (12 live checks deselected).
|
| 91 |
-
|
| 92 |
-
Both GitHub engine/coach validation and the isolated GVHMR runtime check passed
|
| 93 |
-
for `a8710fc`. The initial `cc303c1` CI attempt correctly stopped deployment
|
| 94 |
-
because its orientation fixture required a missing system `ffmpeg`; the test now
|
| 95 |
-
writes a real ISO BMFF display matrix directly and exercises PyAV orientation.
|
| 96 |
-
|
| 97 |
-
A local CoreML/CPU test of the existing pretrained weights stopped both real
|
| 98 |
-
recording attempts at approximately 4.81 seconds, with unavailable contact and
|
| 99 |
-
`processing_budget_exceeded`. This verifies local bounded-attempt behavior only;
|
| 100 |
-
it is **not** a CUDA benchmark or evidence that detection accuracy improved.
|
| 101 |
-
The current implementation also retains fully processed observations when a
|
| 102 |
-
cooperative deadline expires. A parent-enforced hard timeout can instead return
|
| 103 |
-
the retained source with no published observations.
|
| 104 |
-
|
| 105 |
-
The processing budget excludes upload, shared-queue waiting, cold warmup, and
|
| 106 |
-
annotation. JSON may be ready while `rendering.status` is `pending`; the video
|
| 107 |
-
manifest is published later without changing contact/timing fields. TensorRT is
|
| 108 |
-
optional and is not installed in the default image. No TensorRT speedup has been
|
| 109 |
-
measured or claimed.
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
The first deployed fast build (`a8710fc`, API 1.16.0) completed real T4 attempts
|
| 113 |
-
in 4.8932 s (tee) and 4.8117 s (swing1), both within its server decision budget.
|
| 114 |
-
Client polling after upload observed 5.392 s and 5.312 s respectively; these
|
| 115 |
-
include queue/network/poll latency and are not a five-second end-to-end promise.
|
| 116 |
-
Both contacts remained unavailable with `processing_budget_exceeded`. Videos,
|
| 117 |
-
source bytes and observation manifests passed checksums; all 117/158 video frames
|
| 118 |
-
retained source PTS. Rendering did not change contact fields.
|
| 119 |
-
|
| 120 |
-
The tee attempt had examined only ten frames of its first 17-frame candidate
|
| 121 |
-
window before the budget expired. Revisions `896db3a` / `ae294ce` (API 1.16.1)
|
| 122 |
-
therefore center the initial check on the detector's minimum seven-frame context,
|
| 123 |
-
and use measured per-frame cost to avoid starting another context that cannot
|
| 124 |
-
finish in the remaining budget. This is an algorithm support requirement
|
| 125 |
-
(three samples before + one candidate + three after), not a video-specific FPS
|
| 126 |
-
or timestamp override. Additional regression coverage checks centered contexts
|
| 127 |
-
and finishing a supported window before spending time on another.
|
| 128 |
-
|
| 129 |
-
### Final T4 verification
|
| 130 |
-
|
| 131 |
-
Final code `ae294ce` (context scheduling `896db3a`) passed both engine/coach CI
|
| 132 |
-
and deployment, including the isolated GVHMR runtime check. The live Space is
|
| 133 |
-
serving API 1.16.1. The following real uploads sent **only the video field**:
|
| 134 |
-
|
| 135 |
-
| Recording | Server decision | Upload | Client wait after upload (queue/network/poll included) | Fully checked contexts | Searched frames | Contact |
|
| 136 |
-
| --- | ---: | ---: | ---: | ---: | ---: | --- |
|
| 137 |
-
| tee | 3.6705 s | 2.356 s | 3.851 s | 1 | 7 of 117 | unavailable |
|
| 138 |
-
| swing1 | 3.9982 s | 1.848 s | 4.502 s | 2 | 14 of 158 | unavailable |
|
| 139 |
-
|
| 140 |
-
Both final attempts met their five-second server budget and completed actual
|
| 141 |
-
before/after contexts rather than timing out in the first context. Both returned
|
| 142 |
-
`bat_endpoints_unobserved_or_ambiguous` plus `search_budget_limited`: sufficient
|
| 143 |
-
bat-shaft endpoints were not observed in the checked intervals, and additional
|
| 144 |
-
candidates were not examined within the remaining budget. Neither test located
|
| 145 |
-
contact. The optimization meets the tested latency target; **contact-detection
|
| 146 |
-
accuracy on these recordings remains unresolved**.
|
| 147 |
-
|
| 148 |
-
The first JSON reported video rendering pending. Both background renders then
|
| 149 |
-
completed, incrementing `artifacts_revision` to 1 without changing contact fields.
|
| 150 |
-
Source, observations, and annotated video passed size/SHA checks. All 117/158
|
| 151 |
-
original frame timestamps were preserved in the annotated video. Source bytes
|
| 152 |
-
matched the user's original recording, actual CUDA execution was reported, models
|
| 153 |
-
were warm, and deployed implementation hashes matched the checked source files.
|
| 154 |
-
No Gemini calls were made. Evidence clips remained unavailable because no contact
|
| 155 |
-
interval was located.
|
| 156 |
-
|
| 157 |
-
Total client upload-plus-result time was approximately **6.21 s / 6.35 s** in these
|
| 158 |
-
checks. This is not a guaranteed five-second end-to-end service and does not
|
| 159 |
-
establish worst-case latency under concurrency or OS/storage stalls. Full mode
|
| 160 |
-
still performs the broader original scan; the fast-mode timings are for a
|
| 161 |
-
limited candidate search, not a measured speedup of the same exhaustive analysis.
|
| 162 |
-
Detailed final artifacts remain ignored in
|
| 163 |
-
`artifacts/contact-validation/fast-live-final/`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/contact-input.schema.json
DELETED
|
@@ -1,129 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"$defs": {
|
| 3 |
-
"TimingInput": {
|
| 4 |
-
"additionalProperties": false,
|
| 5 |
-
"properties": {
|
| 6 |
-
"kind": {
|
| 7 |
-
"default": "unknown",
|
| 8 |
-
"enum": [
|
| 9 |
-
"unknown",
|
| 10 |
-
"unretimed",
|
| 11 |
-
"constant_slowdown",
|
| 12 |
-
"explicit"
|
| 13 |
-
],
|
| 14 |
-
"title": "Kind",
|
| 15 |
-
"type": "string"
|
| 16 |
-
},
|
| 17 |
-
"source": {
|
| 18 |
-
"anyOf": [
|
| 19 |
-
{
|
| 20 |
-
"maxLength": 512,
|
| 21 |
-
"minLength": 1,
|
| 22 |
-
"type": "string"
|
| 23 |
-
},
|
| 24 |
-
{
|
| 25 |
-
"type": "null"
|
| 26 |
-
}
|
| 27 |
-
],
|
| 28 |
-
"default": null,
|
| 29 |
-
"title": "Source"
|
| 30 |
-
},
|
| 31 |
-
"factor": {
|
| 32 |
-
"anyOf": [
|
| 33 |
-
{
|
| 34 |
-
"exclusiveMinimum": 0,
|
| 35 |
-
"type": "number"
|
| 36 |
-
},
|
| 37 |
-
{
|
| 38 |
-
"type": "null"
|
| 39 |
-
}
|
| 40 |
-
],
|
| 41 |
-
"default": null,
|
| 42 |
-
"title": "Factor"
|
| 43 |
-
},
|
| 44 |
-
"all_captured_frames_retained": {
|
| 45 |
-
"anyOf": [
|
| 46 |
-
{
|
| 47 |
-
"type": "boolean"
|
| 48 |
-
},
|
| 49 |
-
{
|
| 50 |
-
"type": "null"
|
| 51 |
-
}
|
| 52 |
-
],
|
| 53 |
-
"default": null,
|
| 54 |
-
"title": "All Captured Frames Retained"
|
| 55 |
-
},
|
| 56 |
-
"physical_times_s": {
|
| 57 |
-
"anyOf": [
|
| 58 |
-
{
|
| 59 |
-
"items": {
|
| 60 |
-
"type": "number"
|
| 61 |
-
},
|
| 62 |
-
"maxItems": 20000,
|
| 63 |
-
"minItems": 1,
|
| 64 |
-
"type": "array"
|
| 65 |
-
},
|
| 66 |
-
{
|
| 67 |
-
"type": "null"
|
| 68 |
-
}
|
| 69 |
-
],
|
| 70 |
-
"default": null,
|
| 71 |
-
"title": "Physical Times S"
|
| 72 |
-
}
|
| 73 |
-
},
|
| 74 |
-
"title": "TimingInput",
|
| 75 |
-
"type": "object"
|
| 76 |
-
}
|
| 77 |
-
},
|
| 78 |
-
"additionalProperties": false,
|
| 79 |
-
"properties": {
|
| 80 |
-
"timing": {
|
| 81 |
-
"$ref": "#/$defs/TimingInput"
|
| 82 |
-
},
|
| 83 |
-
"rotation_degrees": {
|
| 84 |
-
"anyOf": [
|
| 85 |
-
{
|
| 86 |
-
"enum": [
|
| 87 |
-
0,
|
| 88 |
-
90,
|
| 89 |
-
180,
|
| 90 |
-
270
|
| 91 |
-
],
|
| 92 |
-
"type": "integer"
|
| 93 |
-
},
|
| 94 |
-
{
|
| 95 |
-
"type": "null"
|
| 96 |
-
}
|
| 97 |
-
],
|
| 98 |
-
"default": null,
|
| 99 |
-
"title": "Rotation Degrees"
|
| 100 |
-
},
|
| 101 |
-
"annotated_video": {
|
| 102 |
-
"default": true,
|
| 103 |
-
"title": "Annotated Video",
|
| 104 |
-
"type": "boolean"
|
| 105 |
-
},
|
| 106 |
-
"use_audio": {
|
| 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 |
-
"minimum": 1.0,
|
| 123 |
-
"title": "Processing Budget S",
|
| 124 |
-
"type": "number"
|
| 125 |
-
}
|
| 126 |
-
},
|
| 127 |
-
"title": "ContactInput",
|
| 128 |
-
"type": "object"
|
| 129 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
docs/contact-result.schema.json
DELETED
|
@@ -1,362 +0,0 @@
|
|
| 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"
|
| 14 |
-
},
|
| 15 |
-
"url": {
|
| 16 |
-
"anyOf": [
|
| 17 |
-
{
|
| 18 |
-
"type": "string"
|
| 19 |
-
},
|
| 20 |
-
{
|
| 21 |
-
"type": "null"
|
| 22 |
-
}
|
| 23 |
-
],
|
| 24 |
-
"default": null,
|
| 25 |
-
"title": "Url"
|
| 26 |
-
},
|
| 27 |
-
"filename": {
|
| 28 |
-
"anyOf": [
|
| 29 |
-
{
|
| 30 |
-
"type": "string"
|
| 31 |
-
},
|
| 32 |
-
{
|
| 33 |
-
"type": "null"
|
| 34 |
-
}
|
| 35 |
-
],
|
| 36 |
-
"default": null,
|
| 37 |
-
"title": "Filename"
|
| 38 |
-
},
|
| 39 |
-
"format": {
|
| 40 |
-
"title": "Format",
|
| 41 |
-
"type": "string"
|
| 42 |
-
},
|
| 43 |
-
"media_type": {
|
| 44 |
-
"title": "Media Type",
|
| 45 |
-
"type": "string"
|
| 46 |
-
},
|
| 47 |
-
"size_bytes": {
|
| 48 |
-
"anyOf": [
|
| 49 |
-
{
|
| 50 |
-
"minimum": 1,
|
| 51 |
-
"type": "integer"
|
| 52 |
-
},
|
| 53 |
-
{
|
| 54 |
-
"type": "null"
|
| 55 |
-
}
|
| 56 |
-
],
|
| 57 |
-
"default": null,
|
| 58 |
-
"title": "Size Bytes"
|
| 59 |
-
},
|
| 60 |
-
"sha256": {
|
| 61 |
-
"anyOf": [
|
| 62 |
-
{
|
| 63 |
-
"pattern": "^[a-f0-9]{64}$",
|
| 64 |
-
"type": "string"
|
| 65 |
-
},
|
| 66 |
-
{
|
| 67 |
-
"type": "null"
|
| 68 |
-
}
|
| 69 |
-
],
|
| 70 |
-
"default": null,
|
| 71 |
-
"title": "Sha256"
|
| 72 |
-
},
|
| 73 |
-
"expires_at": {
|
| 74 |
-
"title": "Expires At",
|
| 75 |
-
"type": "string"
|
| 76 |
-
},
|
| 77 |
-
"reason_code": {
|
| 78 |
-
"anyOf": [
|
| 79 |
-
{
|
| 80 |
-
"type": "string"
|
| 81 |
-
},
|
| 82 |
-
{
|
| 83 |
-
"type": "null"
|
| 84 |
-
}
|
| 85 |
-
],
|
| 86 |
-
"default": null,
|
| 87 |
-
"title": "Reason Code"
|
| 88 |
-
}
|
| 89 |
-
},
|
| 90 |
-
"required": [
|
| 91 |
-
"status",
|
| 92 |
-
"format",
|
| 93 |
-
"media_type",
|
| 94 |
-
"expires_at"
|
| 95 |
-
],
|
| 96 |
-
"title": "ContactArtifact",
|
| 97 |
-
"type": "object"
|
| 98 |
-
},
|
| 99 |
-
"ContactEstimate": {
|
| 100 |
-
"additionalProperties": false,
|
| 101 |
-
"properties": {
|
| 102 |
-
"status": {
|
| 103 |
-
"enum": [
|
| 104 |
-
"estimated",
|
| 105 |
-
"unavailable"
|
| 106 |
-
],
|
| 107 |
-
"title": "Status",
|
| 108 |
-
"type": "string"
|
| 109 |
-
},
|
| 110 |
-
"source_frame_index": {
|
| 111 |
-
"anyOf": [
|
| 112 |
-
{
|
| 113 |
-
"minimum": 0,
|
| 114 |
-
"type": "integer"
|
| 115 |
-
},
|
| 116 |
-
{
|
| 117 |
-
"type": "null"
|
| 118 |
-
}
|
| 119 |
-
],
|
| 120 |
-
"default": null,
|
| 121 |
-
"title": "Source Frame Index"
|
| 122 |
-
},
|
| 123 |
-
"frame_interval": {
|
| 124 |
-
"anyOf": [
|
| 125 |
-
{
|
| 126 |
-
"maxItems": 2,
|
| 127 |
-
"minItems": 2,
|
| 128 |
-
"prefixItems": [
|
| 129 |
-
{
|
| 130 |
-
"type": "integer"
|
| 131 |
-
},
|
| 132 |
-
{
|
| 133 |
-
"type": "integer"
|
| 134 |
-
}
|
| 135 |
-
],
|
| 136 |
-
"type": "array"
|
| 137 |
-
},
|
| 138 |
-
{
|
| 139 |
-
"type": "null"
|
| 140 |
-
}
|
| 141 |
-
],
|
| 142 |
-
"default": null,
|
| 143 |
-
"title": "Frame Interval"
|
| 144 |
-
},
|
| 145 |
-
"video_time_s": {
|
| 146 |
-
"anyOf": [
|
| 147 |
-
{
|
| 148 |
-
"minimum": 0,
|
| 149 |
-
"type": "number"
|
| 150 |
-
},
|
| 151 |
-
{
|
| 152 |
-
"type": "null"
|
| 153 |
-
}
|
| 154 |
-
],
|
| 155 |
-
"default": null,
|
| 156 |
-
"title": "Video Time S"
|
| 157 |
-
},
|
| 158 |
-
"video_time_interval_s": {
|
| 159 |
-
"anyOf": [
|
| 160 |
-
{
|
| 161 |
-
"maxItems": 2,
|
| 162 |
-
"minItems": 2,
|
| 163 |
-
"prefixItems": [
|
| 164 |
-
{
|
| 165 |
-
"type": "number"
|
| 166 |
-
},
|
| 167 |
-
{
|
| 168 |
-
"type": "number"
|
| 169 |
-
}
|
| 170 |
-
],
|
| 171 |
-
"type": "array"
|
| 172 |
-
},
|
| 173 |
-
{
|
| 174 |
-
"type": "null"
|
| 175 |
-
}
|
| 176 |
-
],
|
| 177 |
-
"default": null,
|
| 178 |
-
"title": "Video Time Interval S"
|
| 179 |
-
},
|
| 180 |
-
"capture_time_s": {
|
| 181 |
-
"anyOf": [
|
| 182 |
-
{
|
| 183 |
-
"minimum": 0,
|
| 184 |
-
"type": "number"
|
| 185 |
-
},
|
| 186 |
-
{
|
| 187 |
-
"type": "null"
|
| 188 |
-
}
|
| 189 |
-
],
|
| 190 |
-
"default": null,
|
| 191 |
-
"title": "Capture Time S"
|
| 192 |
-
},
|
| 193 |
-
"capture_time_interval_s": {
|
| 194 |
-
"anyOf": [
|
| 195 |
-
{
|
| 196 |
-
"maxItems": 2,
|
| 197 |
-
"minItems": 2,
|
| 198 |
-
"prefixItems": [
|
| 199 |
-
{
|
| 200 |
-
"type": "number"
|
| 201 |
-
},
|
| 202 |
-
{
|
| 203 |
-
"type": "number"
|
| 204 |
-
}
|
| 205 |
-
],
|
| 206 |
-
"type": "array"
|
| 207 |
-
},
|
| 208 |
-
{
|
| 209 |
-
"type": "null"
|
| 210 |
-
}
|
| 211 |
-
],
|
| 212 |
-
"default": null,
|
| 213 |
-
"title": "Capture Time Interval S"
|
| 214 |
-
},
|
| 215 |
-
"local_frame_spacing_ms": {
|
| 216 |
-
"anyOf": [
|
| 217 |
-
{
|
| 218 |
-
"exclusiveMinimum": 0,
|
| 219 |
-
"type": "number"
|
| 220 |
-
},
|
| 221 |
-
{
|
| 222 |
-
"type": "null"
|
| 223 |
-
}
|
| 224 |
-
],
|
| 225 |
-
"default": null,
|
| 226 |
-
"title": "Local Frame Spacing Ms"
|
| 227 |
-
},
|
| 228 |
-
"method": {
|
| 229 |
-
"anyOf": [
|
| 230 |
-
{
|
| 231 |
-
"type": "string"
|
| 232 |
-
},
|
| 233 |
-
{
|
| 234 |
-
"type": "null"
|
| 235 |
-
}
|
| 236 |
-
],
|
| 237 |
-
"default": null,
|
| 238 |
-
"title": "Method"
|
| 239 |
-
},
|
| 240 |
-
"reasons": {
|
| 241 |
-
"items": {
|
| 242 |
-
"type": "string"
|
| 243 |
-
},
|
| 244 |
-
"title": "Reasons",
|
| 245 |
-
"type": "array"
|
| 246 |
-
},
|
| 247 |
-
"confidence": {
|
| 248 |
-
"default": null,
|
| 249 |
-
"title": "Confidence",
|
| 250 |
-
"type": "null"
|
| 251 |
-
},
|
| 252 |
-
"verified": {
|
| 253 |
-
"const": false,
|
| 254 |
-
"default": false,
|
| 255 |
-
"title": "Verified",
|
| 256 |
-
"type": "boolean"
|
| 257 |
-
},
|
| 258 |
-
"accuracy_validated": {
|
| 259 |
-
"const": false,
|
| 260 |
-
"default": false,
|
| 261 |
-
"title": "Accuracy Validated",
|
| 262 |
-
"type": "boolean"
|
| 263 |
-
},
|
| 264 |
-
"evidence": {
|
| 265 |
-
"additionalProperties": true,
|
| 266 |
-
"title": "Evidence",
|
| 267 |
-
"type": "object"
|
| 268 |
-
}
|
| 269 |
-
},
|
| 270 |
-
"required": [
|
| 271 |
-
"status"
|
| 272 |
-
],
|
| 273 |
-
"title": "ContactEstimate",
|
| 274 |
-
"type": "object"
|
| 275 |
-
}
|
| 276 |
-
},
|
| 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 |
-
},
|
| 288 |
-
"job_id": {
|
| 289 |
-
"title": "Job Id",
|
| 290 |
-
"type": "string"
|
| 291 |
-
},
|
| 292 |
-
"status": {
|
| 293 |
-
"const": "completed",
|
| 294 |
-
"default": "completed",
|
| 295 |
-
"title": "Status",
|
| 296 |
-
"type": "string"
|
| 297 |
-
},
|
| 298 |
-
"contact": {
|
| 299 |
-
"$ref": "#/$defs/ContactEstimate"
|
| 300 |
-
},
|
| 301 |
-
"source_video": {
|
| 302 |
-
"additionalProperties": true,
|
| 303 |
-
"title": "Source Video",
|
| 304 |
-
"type": "object"
|
| 305 |
-
},
|
| 306 |
-
"timing": {
|
| 307 |
-
"additionalProperties": true,
|
| 308 |
-
"title": "Timing",
|
| 309 |
-
"type": "object"
|
| 310 |
-
},
|
| 311 |
-
"pipeline": {
|
| 312 |
-
"additionalProperties": true,
|
| 313 |
-
"title": "Pipeline",
|
| 314 |
-
"type": "object"
|
| 315 |
-
},
|
| 316 |
-
"audio": {
|
| 317 |
-
"additionalProperties": true,
|
| 318 |
-
"title": "Audio",
|
| 319 |
-
"type": "object"
|
| 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"
|
| 342 |
-
},
|
| 343 |
-
"accuracy_validated": {
|
| 344 |
-
"const": false,
|
| 345 |
-
"default": false,
|
| 346 |
-
"title": "Accuracy Validated",
|
| 347 |
-
"type": "boolean"
|
| 348 |
-
}
|
| 349 |
-
},
|
| 350 |
-
"required": [
|
| 351 |
-
"job_id",
|
| 352 |
-
"contact",
|
| 353 |
-
"source_video",
|
| 354 |
-
"timing",
|
| 355 |
-
"pipeline",
|
| 356 |
-
"audio",
|
| 357 |
-
"artifacts",
|
| 358 |
-
"expires_at"
|
| 359 |
-
],
|
| 360 |
-
"title": "ContactResult",
|
| 361 |
-
"type": "object"
|
| 362 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_api.py
CHANGED
|
@@ -51,6 +51,55 @@ def upload(client, video, **kwargs):
|
|
| 51 |
files={"video": ("swing.mp4", video.read_bytes(), "video/mp4")}, **kwargs)
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def test_upload_poll_fetch_delete_and_auth(video, tmp_path):
|
| 55 |
s = settings(tmp_path)
|
| 56 |
service = fake_service(s, delay=.2)
|
|
|
|
| 51 |
files={"video": ("swing.mp4", video.read_bytes(), "video/mp4")}, **kwargs)
|
| 52 |
|
| 53 |
|
| 54 |
+
def test_retired_contact_endpoints_are_not_exposed(tmp_path):
|
| 55 |
+
s = settings(tmp_path)
|
| 56 |
+
service = fake_service(s)
|
| 57 |
+
app = create_app(s, service)
|
| 58 |
+
paths = app.openapi()['paths']
|
| 59 |
+
assert not any(path.startswith('/v1/contact-analyses') for path in paths)
|
| 60 |
+
for path in ('/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses',
|
| 61 |
+
'/v1/sam-batting/analyses', '/v1/motion-analyses'):
|
| 62 |
+
assert 'post' in paths[path]
|
| 63 |
+
with TestClient(app) as client:
|
| 64 |
+
wait_until(lambda: service.ready)
|
| 65 |
+
assert client.post('/v1/contact-analyses', headers=AUTH).status_code == 404
|
| 66 |
+
assert client.get('/v1/contact-analyses/input-schema', headers=AUTH).status_code == 404
|
| 67 |
+
assert client.get('/v1/contact-analyses/' + 'a' * 32, headers=AUTH).status_code == 404
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_recovery_retires_contact_jobs_and_preserves_existing_data(tmp_path):
|
| 71 |
+
service = fake_service(settings(tmp_path))
|
| 72 |
+
# Reuse a database from a deployment which still had the contact API.
|
| 73 |
+
with service.store.connect() as db:
|
| 74 |
+
db.execute('ALTER TABLE jobs ADD COLUMN contact_artifacts_sha256 TEXT')
|
| 75 |
+
store = JobStore(tmp_path)
|
| 76 |
+
contact_jobs = []
|
| 77 |
+
for status in ('uploading', 'queued', 'running', 'cancel_requested', 'completed'):
|
| 78 |
+
identifier = store.create(16, kind='contact')
|
| 79 |
+
store.update(identifier, status)
|
| 80 |
+
directory = service.job_directory(identifier)
|
| 81 |
+
directory.mkdir()
|
| 82 |
+
(directory/'result.json').write_text('{"retained": true}')
|
| 83 |
+
contact_jobs.append((identifier, status))
|
| 84 |
+
legacy = store.create(16)
|
| 85 |
+
store.update(legacy, 'running')
|
| 86 |
+
motion = store.create(16, kind='motion_player')
|
| 87 |
+
store.update(motion, 'queued')
|
| 88 |
+
|
| 89 |
+
assert store.recover() == []
|
| 90 |
+
for identifier, status in contact_jobs:
|
| 91 |
+
record = store.get(identifier)
|
| 92 |
+
assert record['status'] == ('completed' if status == 'completed' else 'failed')
|
| 93 |
+
assert record['error'] == (None if status == 'completed' else 'api_removed')
|
| 94 |
+
assert (service.job_directory(identifier)/'result.json').read_text() == '{"retained": true}'
|
| 95 |
+
with pytest.raises(ValueError, match='Unsupported analysis job kind'):
|
| 96 |
+
service.job_command(service.job_directory(identifier))
|
| 97 |
+
assert store.get(legacy)['status'] == 'queued'
|
| 98 |
+
assert store.get(motion)['status'] == 'queued'
|
| 99 |
+
assert {store.claim(), store.claim()} == {legacy, motion}
|
| 100 |
+
assert store.claim() is None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
def test_upload_poll_fetch_delete_and_auth(video, tmp_path):
|
| 104 |
s = settings(tmp_path)
|
| 105 |
service = fake_service(s, delay=.2)
|
tests/test_contact_api.py
DELETED
|
@@ -1,147 +0,0 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import sys
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
import numpy as np
|
| 5 |
-
import pytest
|
| 6 |
-
from fastapi.testclient import TestClient
|
| 7 |
-
from baseball_batting.api import create_app
|
| 8 |
-
from baseball_batting.api_jobs import JobService
|
| 9 |
-
from baseball_batting.contact_worker import run
|
| 10 |
-
from baseball_batting.contact_contract import ContactInput,ContactResult
|
| 11 |
-
from baseball_batting.ingest import ingest,iter_frames
|
| 12 |
-
from baseball_batting.storage import atomic_json,sha256_file
|
| 13 |
-
from test_api import settings,fake_service,wait_until,AUTH
|
| 14 |
-
from test_contact_detection import observed
|
| 15 |
-
|
| 16 |
-
PREFIX='/v1/contact-analyses'
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def inject_observations(monkeypatch, *, positive=True):
|
| 20 |
-
def collect(video,capture,models,progress,device):
|
| 21 |
-
times=[f['playback_s'] for f in capture['frames']]
|
| 22 |
-
obs,_=observed(times,index=4)
|
| 23 |
-
original=[]
|
| 24 |
-
for i,row in enumerate(obs['frames']):
|
| 25 |
-
if not positive:row['ball']=[]
|
| 26 |
-
original.append({**row,'source_frame_index':i,'video_time_s':times[i]-times[0]})
|
| 27 |
-
return obs,original,{'bat':{'test_fixture':True},'ball':{'test_fixture':True}}
|
| 28 |
-
monkeypatch.setattr('baseball_batting.contact_vision.collect',collect)
|
| 29 |
-
|
| 30 |
-
|
| 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
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def test_upload_only_video_accepts_defaults_and_dispatches_isolated_worker(video,tmp_path):
|
| 41 |
-
service=fake_service(settings(tmp_path),delay=30)
|
| 42 |
-
with TestClient(create_app(service.settings,service)) as client:
|
| 43 |
-
wait_until(lambda:service.ready);service.tracking_ready=True
|
| 44 |
-
files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
|
| 45 |
-
assert client.post(PREFIX,files=files).status_code==401
|
| 46 |
-
assert client.post(PREFIX,files=files,headers=AUTH,data={'options':'{"fps":30}'}).status_code==422
|
| 47 |
-
response=client.post(PREFIX,files=files,headers=AUTH)
|
| 48 |
-
assert response.status_code==202,response.text
|
| 49 |
-
data=response.json();job=service.job_directory(data['job_id'])
|
| 50 |
-
assert service.store.get(job.name)['kind']=='contact'
|
| 51 |
-
assert json.loads((job/'request.json').read_text())==ContactInput().model_dump(mode='json')
|
| 52 |
-
command=service.job_command(job)
|
| 53 |
-
assert 'baseball_batting.contact_worker' in command and '--retention-s' in command
|
| 54 |
-
assert client.get(data['result_url'],headers=AUTH).status_code==409
|
| 55 |
-
assert client.get(data['status_url'],headers=AUTH).status_code==200
|
| 56 |
-
assert client.get('/v1/motion-analyses/'+job.name,headers=AUTH).status_code==404
|
| 57 |
-
assert client.delete(data['status_url'],headers=AUTH).status_code==202
|
| 58 |
-
wait_until(lambda:client.get(data['status_url'],headers=AUTH).json()['status']=='cancelled')
|
| 59 |
-
service.tracking_ready=False
|
| 60 |
-
assert client.post(PREFIX,files=files,headers=AUTH).status_code==503
|
| 61 |
-
assert client.get(PREFIX+'/output-schema',headers=AUTH).status_code==200
|
| 62 |
-
assert client.get(PREFIX+'/capabilities',headers=AUTH).json()['minimum_fps_required'] is None
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
@pytest.mark.parametrize('positive',[False,True])
|
| 66 |
-
def test_real_decode_worker_result_and_source_timed_artifacts(video,tmp_path,monkeypatch,positive):
|
| 67 |
-
service=fake_service(settings(tmp_path));job,result=stored(service,video,monkeypatch,positive=positive)
|
| 68 |
-
result=ContactResult.model_validate_json((job/'result.json').read_text())
|
| 69 |
-
assert result.contact.status==('estimated' if positive else 'unavailable')
|
| 70 |
-
assert result.contact.capture_time_s is None and result.contact.verified is False
|
| 71 |
-
assert result.audio['status']=='no_audio'
|
| 72 |
-
capture=ingest(video,{})
|
| 73 |
-
actual=list(iter_frames(job/'annotated.mp4'))
|
| 74 |
-
expected=[f['playback_s']-capture['frames'][0]['playback_s'] for f in capture['frames']]
|
| 75 |
-
np.testing.assert_allclose([float(pts*base) for _,pts,base,_ in actual],expected,atol=2e-6)
|
| 76 |
-
assert result.source_video['frame_count']==len(actual)==8
|
| 77 |
-
assert (job/'source.mp4').read_bytes()==video.read_bytes()
|
| 78 |
-
assert result.artifacts['evidence'].status==('available' if positive else 'unavailable')
|
| 79 |
-
if positive:
|
| 80 |
-
meta=result.pipeline['clips']['evidence'];clip=list(iter_frames(job/'evidence.mp4'))
|
| 81 |
-
a,b=meta['source_start_frame'],meta['source_end_frame']
|
| 82 |
-
np.testing.assert_allclose([float(pts*base)+meta['source_video_start_s'] for _,pts,base,_ in clip],expected[a:b+1],atol=2e-6)
|
| 83 |
-
with TestClient(create_app(service.settings,service)) as client:
|
| 84 |
-
wait_until(lambda:service.ready)
|
| 85 |
-
root=PREFIX+'/'+job.name
|
| 86 |
-
assert client.get(root+'/result',headers=AUTH).json()['job_id']==job.name
|
| 87 |
-
for name in ['source','observations','annotated']:
|
| 88 |
-
url=root+'/artifacts/'+name
|
| 89 |
-
assert client.get(url).status_code==401
|
| 90 |
-
assert client.head(url,headers=AUTH).status_code==200
|
| 91 |
-
assert client.get(url,headers=AUTH).content==(job/result.artifacts[name].filename).read_bytes()
|
| 92 |
-
assert client.get(root+'/artifacts/source',headers={**AUTH,'Range':'bytes=0-9'}).status_code==206
|
| 93 |
-
assert client.get(root+'/artifacts/capture-private',headers=AUTH).status_code==404
|
| 94 |
-
(job/'observations.jsonl').write_text('tampered')
|
| 95 |
-
assert client.get(root+'/artifacts/observations',headers=AUTH).status_code==500
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def test_end_to_end_queue_completes_with_contact_worker_output(video,tmp_path,monkeypatch):
|
| 99 |
-
# Real subprocess/queue/persistence; its object observations are explicitly constructed.
|
| 100 |
-
script=("import sys; from pathlib import Path; from unittest.mock import patch; "
|
| 101 |
-
"sys.path.insert(0,'tests'); from test_contact_api import inject_observations; "
|
| 102 |
-
"from baseball_batting.contact_worker import run; "
|
| 103 |
-
"from pytest import MonkeyPatch; inject_observations(MonkeyPatch()); "
|
| 104 |
-
"run(sys.argv[1],sys.argv[2],device='cpu')")
|
| 105 |
-
s=settings(tmp_path)
|
| 106 |
-
service=JobService(s,command_factory=lambda d:[sys.executable,'-c',script,str(d),str(s.model_root)],
|
| 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'
|
| 114 |
-
assert not (service.job_directory(data['job_id'])/'input.mp4').exists()
|
| 115 |
-
assert client.get(result.json()['artifacts']['source']['url'],headers=AUTH).status_code==200
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def test_optional_audio_never_creates_contact_or_changes_video_time(tmp_path):
|
| 119 |
-
import av
|
| 120 |
-
from fractions import Fraction
|
| 121 |
-
from baseball_batting.contact_audio import inspect
|
| 122 |
-
from baseball_batting.contact_contract import ContactEstimate
|
| 123 |
-
path=tmp_path/'transients.wav'
|
| 124 |
-
with av.open(str(path),'w') as out:
|
| 125 |
-
stream=out.add_stream('pcm_s16le',rate=16000);stream.layout='mono'
|
| 126 |
-
data=np.zeros((1,16000),np.int16);data[0,3200:3240]=20000
|
| 127 |
-
frame=av.AudioFrame.from_ndarray(data,format='s16',layout='mono')
|
| 128 |
-
frame.sample_rate=16000;frame.pts=0;frame.time_base=Fraction(1,16000)
|
| 129 |
-
for packet in stream.encode(frame):out.mux(packet)
|
| 130 |
-
for packet in stream.encode():out.mux(packet)
|
| 131 |
-
unknown=ContactEstimate(status='unavailable',reasons=['no_ball'])
|
| 132 |
-
audio=inspect(path,0,1,unknown)
|
| 133 |
-
assert audio['status']=='analyzed' and audio['transient_video_times_s']
|
| 134 |
-
assert audio['used_for_contact_timestamp'] is False and unknown.status=='unavailable'
|
| 135 |
-
assert inspect(path,0,1,unknown,False)['status']=='not_requested'
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def test_unavailable_annotation_timing_preserves_contact_json(video,tmp_path,monkeypatch):
|
| 139 |
-
from baseball_batting.swing_clips import ClipError
|
| 140 |
-
def failed_export(*a,**k):raise ClipError('last_frame_duration_unavailable')
|
| 141 |
-
monkeypatch.setattr('baseball_batting.contact_videos.export',failed_export)
|
| 142 |
-
service=fake_service(settings(tmp_path));job,result=stored(service,video,monkeypatch)
|
| 143 |
-
assert result.contact.status=='estimated'
|
| 144 |
-
assert result.artifacts['source'].status=='available'
|
| 145 |
-
assert result.artifacts['observations'].status=='available'
|
| 146 |
-
assert result.artifacts['annotated'].status=='unavailable'
|
| 147 |
-
assert result.artifacts['annotated'].reason_code=='last_frame_duration_unavailable'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_contact_detection.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
| 1 |
-
"""Timing/geometry behavior, not a claim of neural-network accuracy."""
|
| 2 |
-
from copy import deepcopy
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pytest
|
| 5 |
-
from baseball_batting.contact_detection import estimate
|
| 6 |
-
from baseball_batting.contact_contract import ContactInput,ContactEstimate
|
| 7 |
-
from baseball_batting.contact_vision import background_transform,stabilized
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def observed(times, *, tee=False, index=None, physical=False):
|
| 11 |
-
times=np.asarray(times,float);index=len(times)//2 if index is None else index
|
| 12 |
-
rows=[]
|
| 13 |
-
for t in times-times[index]:
|
| 14 |
-
xy=[100+(0 if tee else 300*t),80] if t<=0 else [100-400*t,80-300*t]
|
| 15 |
-
rows.append({'bat':[{'points':[[100-800*t,20],[100-800*t,130]]}],
|
| 16 |
-
'ball':[{'point':xy,'radius_px':2.}],'segment_id':0})
|
| 17 |
-
capture={'frames':[{'playback_s':float(t),'physical_s':float(t) if physical else None} for t in times]}
|
| 18 |
-
return {'frames':rows},capture
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
@pytest.mark.parametrize('fps',[12,15,23.976,25,29.97,30,60,120,240])
|
| 22 |
-
@pytest.mark.parametrize('tee',[False,True])
|
| 23 |
-
def test_video_only_has_no_fps_or_pose_or_capture_clock_gate(fps,tee):
|
| 24 |
-
obs,cap=observed(np.arange(81)/fps,tee=tee)
|
| 25 |
-
result=estimate(obs,cap)
|
| 26 |
-
assert result.status=='estimated'
|
| 27 |
-
assert result.video_time_interval_s[0]<=40/fps<=result.video_time_interval_s[1]
|
| 28 |
-
assert result.video_time_s==pytest.approx(40/fps)
|
| 29 |
-
assert result.capture_time_s is None and result.verified is False
|
| 30 |
-
assert result.local_frame_spacing_ms==pytest.approx(1000/fps)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def test_variable_cadence_nonzero_pts_origin_and_physical_slowdown():
|
| 34 |
-
times=5+np.r_[0,np.cumsum(np.tile([.018,.024,.031,.020],20))]
|
| 35 |
-
obs,cap=observed(times)
|
| 36 |
-
for row,time in zip(cap['frames'],times):row['physical_s']=10+(time-5)/4
|
| 37 |
-
result=estimate(obs,cap)
|
| 38 |
-
assert result.status=='estimated'
|
| 39 |
-
assert result.video_time_s==pytest.approx(times[40]-times[0])
|
| 40 |
-
assert result.capture_time_s==pytest.approx((times[40]-times[0])/4)
|
| 41 |
-
assert result.capture_time_interval_s[1]-result.capture_time_interval_s[0]==pytest.approx((result.video_time_interval_s[1]-result.video_time_interval_s[0])/4)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
@pytest.mark.parametrize('failure',['no_bat','no_ball','no_deflection','stationary_bat','ball_gap','camera_cut','camera_unresolved','ambiguous_ball','ambiguous_bat'])
|
| 45 |
-
def test_uncertain_observations_never_create_contact_or_a_miss(failure):
|
| 46 |
-
obs,cap=observed(np.arange(81)/60)
|
| 47 |
-
for i,row in enumerate(obs['frames']):
|
| 48 |
-
if failure=='no_bat':row['bat']=[]
|
| 49 |
-
if failure=='no_ball':row['ball']=[]
|
| 50 |
-
if failure=='stationary_bat':row['bat']=[{'points':[[100,20],[100,130]]}]
|
| 51 |
-
if failure=='no_deflection':row['ball'][0]['point']=[100+(i-40)*5,80]
|
| 52 |
-
if failure=='ball_gap' and 36<=i<=44:row['ball']=[]
|
| 53 |
-
if failure=='camera_cut':row['segment_id']=int(i>=40)
|
| 54 |
-
if failure=='camera_unresolved':row['camera_motion_status']='unresolved'
|
| 55 |
-
if failure=='ambiguous_ball':row['ball'].append({'point':np.asarray(row['ball'][0]['point'])+.7,'radius_px':2.})
|
| 56 |
-
if failure=='ambiguous_bat':row['bat']*=2
|
| 57 |
-
result=estimate(obs,cap)
|
| 58 |
-
assert result.status=='unavailable' and result.video_time_s is None and result.reasons
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def test_multiple_hits_are_not_silently_selected_for_single_swing_endpoint():
|
| 62 |
-
first,_=observed(np.arange(81)/60)
|
| 63 |
-
second=deepcopy(first)
|
| 64 |
-
cap={'frames':[{'playback_s':i/60,'physical_s':None} for i in range(162)]}
|
| 65 |
-
out=estimate({'frames':first['frames']+second['frames']},cap)
|
| 66 |
-
assert out.status=='unavailable' and out.reasons==['multiple_contact_candidates']
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def test_actual_timestamp_hole_cannot_be_bridged_by_ball_fits():
|
| 70 |
-
obs,cap=observed(np.arange(81)/60)
|
| 71 |
-
for row in cap['frames'][40:]:row['playback_s']+=1
|
| 72 |
-
assert estimate(obs,cap).status=='unavailable'
|
| 73 |
-
cap['frames'][40]['playback_s']=cap['frames'][39]['playback_s']
|
| 74 |
-
with pytest.raises(ValueError,match='invalid_source_timestamps'):estimate(obs,cap)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def test_only_supported_optional_inputs_and_coherent_result_are_accepted():
|
| 78 |
-
assert ContactInput().timing.kind=='unknown'
|
| 79 |
-
for patch in [{'fps':30},{'model':'sam3d'},{'timing':{'kind':'unretimed'}},{'worker_python':'x'}]:
|
| 80 |
-
with pytest.raises(ValueError):ContactInput.model_validate(patch)
|
| 81 |
-
with pytest.raises(ValueError):ContactEstimate(status='estimated')
|
| 82 |
-
with pytest.raises(ValueError):ContactEstimate(status='unavailable',video_time_s=1,reasons=['x'])
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def test_camera_translation_is_estimated_from_distributed_background():
|
| 86 |
-
import cv2
|
| 87 |
-
rng=np.random.default_rng(51)
|
| 88 |
-
image=rng.integers(0,256,(240,320),np.uint8)
|
| 89 |
-
moved=cv2.warpAffine(image,np.float32([[1,0,4],[0,1,3]]),(320,240))
|
| 90 |
-
matrix=background_transform(image,moved,[])
|
| 91 |
-
assert matrix is not None
|
| 92 |
-
np.testing.assert_allclose(matrix[:2,2],[4,3],atol=.2)
|
| 93 |
-
row={'bat':[{'points':[[50,50],[70,70]]}],'ball':[{'point':[20,20],'radius_px':2}]}
|
| 94 |
-
actual=stabilized(row,np.linalg.inv(matrix))
|
| 95 |
-
np.testing.assert_allclose(actual['ball'][0]['point'],[16,17],atol=.2)
|
| 96 |
-
assert row['ball'][0]['point']==[20,20]
|
| 97 |
-
assert background_transform(np.zeros_like(image),np.zeros_like(image),[]) is None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_contact_fast.py
DELETED
|
@@ -1,349 +0,0 @@
|
|
| 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 [5.1, 30, 120, 3600]:
|
| 56 |
-
assert ContactInput(processing_budget_s=value).processing_budget_s == value
|
| 57 |
-
for value in [0, .9, float('inf')]:
|
| 58 |
-
with pytest.raises(ValueError):
|
| 59 |
-
ContactInput(processing_budget_s=value)
|
| 60 |
-
clock = [10.]
|
| 61 |
-
budget = Budget(1, clock=lambda: clock[0])
|
| 62 |
-
budget.check(); clock[0] = 11.
|
| 63 |
-
with pytest.raises(BudgetExpired): budget.check()
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def test_fast_scan_preserves_source_frame_time_and_explicit_clock(video):
|
| 67 |
-
expected = ingest(video, {})
|
| 68 |
-
capture, times, scores, peaks = scan(video, ContactInput(), Budget(5))
|
| 69 |
-
assert capture['frame_count'] == expected['frame_count']
|
| 70 |
-
assert [f['pts'] for f in capture['frames']] == [f['pts'] for f in expected['frames']]
|
| 71 |
-
np.testing.assert_allclose(times, [f['playback_s']-expected['frames'][0]['playback_s'] for f in expected['frames']])
|
| 72 |
-
assert capture['physical_clock_known'] is False
|
| 73 |
-
opts = ContactInput(timing={'kind': 'explicit', 'source': 'test clock', 'physical_times_s': list(4+times/4)})
|
| 74 |
-
cap, *_ = scan(video, opts, Budget(5))
|
| 75 |
-
assert cap['physical_clock_known'] is True
|
| 76 |
-
np.testing.assert_allclose([f['physical_s'] for f in cap['frames']], 4+times/4)
|
| 77 |
-
with pytest.raises(ValueError, match='match decoded'):
|
| 78 |
-
scan(video, ContactInput(timing={'kind': 'explicit', 'source': 'test', 'physical_times_s': list(range(20))}), Budget(5))
|
| 79 |
-
with pytest.raises(ValueError, match='limit'): scan(video, ContactInput(), Budget(5), max_frames=2)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def test_windows_use_audio_and_silent_motion_but_never_interpolate_frames():
|
| 83 |
-
times = np.arange(120)/30
|
| 84 |
-
motion = np.zeros(120); motion[60] = 100; motion[20] = 30
|
| 85 |
-
silent = candidate_windows(times, motion, [60, 20], {'status': 'no_audio'})
|
| 86 |
-
assert silent and silent[0]['start_frame'] <= 60 <= silent[0]['end_frame']
|
| 87 |
-
audio = {'transient_video_times_s': [2.05, 99], 'transient_strengths': {'2.05': 1}}
|
| 88 |
-
windows = candidate_windows(times, motion, [60, 20], audio)
|
| 89 |
-
assert windows[0]['method'] == 'audio_and_motion'
|
| 90 |
-
assert all(w['end_frame']-w['start_frame']+1 <= 32 for w in windows)
|
| 91 |
-
high = candidate_windows(np.arange(1000)/240, np.ones(1000), [500], {})
|
| 92 |
-
assert high[0]['end_frame']-high[0]['start_frame']+1 == 32
|
| 93 |
-
assert candidate_windows(times, np.zeros(120), [], {}) == []
|
| 94 |
-
from baseball_batting.contact_detection import MIN_CONTACT_CONTEXT
|
| 95 |
-
core = candidate_windows(times, motion, [60, 20], {}, max_window_frames=MIN_CONTACT_CONTEXT)
|
| 96 |
-
assert core[0]['start_frame'] == 57 and core[0]['end_frame'] == 63
|
| 97 |
-
low = candidate_windows(np.arange(20)/8, np.arange(20), [10], {}, max_window_frames=MIN_CONTACT_CONTEXT)
|
| 98 |
-
assert low[0]['start_frame'] == 7 and low[0]['end_frame'] == 13
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def test_rotation_metadata_matches_existing_upright_coordinate_system(video, tmp_path):
|
| 102 |
-
rotated = tmp_path/'rotated.mp4'
|
| 103 |
-
# Set the ISO BMFF track-header display matrix in this single-track fixture.
|
| 104 |
-
# This needs neither a system ffmpeg/ffprobe nor version-specific CLI flags.
|
| 105 |
-
data = bytearray(video.read_bytes())
|
| 106 |
-
header = data.index(b'tkhd')
|
| 107 |
-
version = data[header+4]
|
| 108 |
-
assert version in (0, 1)
|
| 109 |
-
offset = header+(56 if version else 44)
|
| 110 |
-
struct.pack_into('>9i', data, offset, 0, -65536, 0, 65536, 0, 0, 0, 0, 1 << 30)
|
| 111 |
-
rotated.write_bytes(data)
|
| 112 |
-
expected = ingest(rotated, {'rotation_degrees': 270})
|
| 113 |
-
capture, *_ = scan(rotated, ContactInput(), Budget(5))
|
| 114 |
-
assert capture['rotation_degrees'] == expected['rotation_degrees'] == 270
|
| 115 |
-
assert capture['frames'][0]['width'] == expected['frames'][0]['width']
|
| 116 |
-
overridden, *_ = scan(rotated, ContactInput(rotation_degrees=0), Budget(5))
|
| 117 |
-
assert overridden['rotation_degrees'] == 0
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def test_candidate_decoder_retains_consecutive_original_frame_ids(video, monkeypatch):
|
| 121 |
-
from baseball_batting.contact_fast import collect_windows
|
| 122 |
-
cap, *_ = scan(video, ContactInput(), Budget(5))
|
| 123 |
-
monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
|
| 124 |
-
calls = []
|
| 125 |
-
def person(image): calls.append('person'); return []
|
| 126 |
-
def bat(image, origin): calls.append('bat'); return []
|
| 127 |
-
def ball(image, origin): calls.append('ball'); return []
|
| 128 |
-
mock_models = SimpleNamespace(person=person, bat=bat, ball=ball)
|
| 129 |
-
result, rows, checked = collect_windows(video, cap, [{'start_frame': 1, 'end_frame': 7}], mock_models, Budget(5))
|
| 130 |
-
assert calls.count('person') == 1 and calls.count('bat') == calls.count('ball') == 7
|
| 131 |
-
assert [r['source_frame_index'] for r in rows if r['searched']] == list(range(1, 8))
|
| 132 |
-
assert rows[0]['camera_motion_status'] == 'not_searched'
|
| 133 |
-
assert rows[0]['bat'] == rows[0]['ball'] == []
|
| 134 |
-
assert result.status == 'unavailable' and result.evidence['searched_frame_count'] == 7
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def test_cooperative_deadline_retains_only_completed_observations(video, monkeypatch):
|
| 138 |
-
from baseball_batting.contact_fast import collect_windows
|
| 139 |
-
cap, *_ = scan(video, ContactInput(), Budget(5))
|
| 140 |
-
clock = [0.]
|
| 141 |
-
monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
|
| 142 |
-
def bat(image, origin): clock[0] += 1.; return []
|
| 143 |
-
def ball(image, origin): clock[0] += 1.; return []
|
| 144 |
-
bundle = SimpleNamespace(person=lambda image: [], bat=bat, ball=ball)
|
| 145 |
-
result, rows, checked = collect_windows(video, cap, [{'start_frame': 0, 'end_frame': 7}],
|
| 146 |
-
bundle, Budget(5, clock=lambda: clock[0]))
|
| 147 |
-
assert result.reasons == ['processing_budget_exceeded']
|
| 148 |
-
assert result.evidence['searched_frame_count'] == 2
|
| 149 |
-
assert [r['source_frame_index'] for r in rows if r['searched']] == [0, 1]
|
| 150 |
-
assert checked == [] and result.video_time_s is None
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def test_search_finishes_one_context_before_spending_budget_on_another(tmp_path, monkeypatch):
|
| 154 |
-
import av
|
| 155 |
-
from fractions import Fraction
|
| 156 |
-
from baseball_batting.contact_fast import collect_windows
|
| 157 |
-
video = tmp_path/'contexts.mp4'
|
| 158 |
-
with av.open(str(video), 'w') as out:
|
| 159 |
-
stream = out.add_stream('libx264', rate=30)
|
| 160 |
-
stream.width, stream.height, stream.pix_fmt = 160, 120, 'yuv420p'
|
| 161 |
-
for i in range(16):
|
| 162 |
-
frame = av.VideoFrame.from_ndarray(np.full((120, 160, 3), i*10, np.uint8), format='bgr24')
|
| 163 |
-
frame.pts, frame.time_base = i, Fraction(1, 30)
|
| 164 |
-
for packet in stream.encode(frame): out.mux(packet)
|
| 165 |
-
for packet in stream.encode(): out.mux(packet)
|
| 166 |
-
cap, *_ = scan(video, ContactInput(), Budget(5))
|
| 167 |
-
clock = [0.]
|
| 168 |
-
monkeypatch.setattr('baseball_batting.contact_fast.background_transform', lambda *args: np.eye(3))
|
| 169 |
-
def bat(image, origin): clock[0] += .2; return []
|
| 170 |
-
def ball(image, origin): clock[0] += .2; return []
|
| 171 |
-
windows = [{'start_frame': 0, 'end_frame': 6}, {'start_frame': 9, 'end_frame': 15}]
|
| 172 |
-
result, rows, checked = collect_windows(video, cap, windows,
|
| 173 |
-
SimpleNamespace(person=lambda image: [], bat=bat, ball=ball), Budget(5, clock=lambda: clock[0]))
|
| 174 |
-
assert checked == windows[:1]
|
| 175 |
-
assert [r['source_frame_index'] for r in rows if r['searched']] == list(range(7))
|
| 176 |
-
assert result.status == 'unavailable' and 'search_budget_limited' in result.reasons
|
| 177 |
-
assert 'processing_budget_exceeded' not in result.reasons
|
| 178 |
-
assert clock[0] < 5
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def test_fast_decision_returns_before_renderer_and_artifacts_preserve_pts(video, tmp_path, monkeypatch):
|
| 182 |
-
service = fake_service(settings(tmp_path))
|
| 183 |
-
path = job(service, video)
|
| 184 |
-
synthetic_check(monkeypatch)
|
| 185 |
-
result = decide(path, models())
|
| 186 |
-
assert result.contact.status == 'estimated' and result.contact.verified is False
|
| 187 |
-
assert result.pipeline['decision_elapsed_s'] < 5
|
| 188 |
-
assert result.artifacts['annotated'].status == 'pending'
|
| 189 |
-
assert not (path/'annotated.mp4').exists()
|
| 190 |
-
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 191 |
-
base_checksum = sha256_file(path/'result.json')
|
| 192 |
-
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 193 |
-
with TestClient(create_app(service.settings, service)) as client:
|
| 194 |
-
wait_until(lambda: service.ready)
|
| 195 |
-
# Render independently. The first response is still usable while pending.
|
| 196 |
-
url = '/v1/contact-analyses/'+path.name+'/result'
|
| 197 |
-
first = client.get(url, headers=AUTH).json()
|
| 198 |
-
assert first['contact'] == result.contact.model_dump(mode='json')
|
| 199 |
-
wait_until(lambda: client.get(url, headers=AUTH).json()['rendering']['status'] != 'pending', timeout=10)
|
| 200 |
-
final = client.get(url, headers=AUTH).json()
|
| 201 |
-
assert final['contact'] == first['contact']
|
| 202 |
-
assert final['artifacts_revision'] == 1 and final['rendering']['status'] == 'completed'
|
| 203 |
-
assert final['artifacts']['annotated']['status'] == 'available'
|
| 204 |
-
assert client.get(final['artifacts']['annotated']['url'], headers=AUTH).status_code == 200
|
| 205 |
-
row = service.store.get(path.name)
|
| 206 |
-
assert row['result_sha256'] == base_checksum == sha256_file(path/'result.json')
|
| 207 |
-
assert row['contact_artifacts_sha256'] == sha256_file(path/'rendered-result.json')
|
| 208 |
-
snapshot = (path/'rendered-result.json').read_bytes()
|
| 209 |
-
(path/'rendered-result.json').write_text('tampered')
|
| 210 |
-
assert client.get(url, headers=AUTH).status_code == 500
|
| 211 |
-
(path/'rendered-result.json').write_bytes(snapshot)
|
| 212 |
-
frames = list(iter_frames(path/'annotated.mp4'))
|
| 213 |
-
np.testing.assert_allclose([float(pts*base) for _, pts, base, _ in frames],
|
| 214 |
-
[f['playback_s'] for f in ingest(video, {})['frames']], atol=2e-6)
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
def test_budget_never_uses_audio_to_force_contact(video, tmp_path, monkeypatch):
|
| 218 |
-
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 219 |
-
def expired(*args, **kwargs): raise BudgetExpired()
|
| 220 |
-
monkeypatch.setattr('baseball_batting.contact_fast_worker.scan', expired)
|
| 221 |
-
result = decide(path, models())
|
| 222 |
-
assert result.contact.status == 'unavailable'
|
| 223 |
-
assert result.contact.reasons == ['processing_budget_exceeded']
|
| 224 |
-
assert result.contact.source_frame_index is None
|
| 225 |
-
assert result.artifacts['source'].status == 'available'
|
| 226 |
-
assert result.source_video['scan_complete'] is False
|
| 227 |
-
assert result.artifacts['annotated'].status == 'pending'
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
def test_warm_worker_reuses_process_and_supervisor_stops_stuck_request(video, tmp_path):
|
| 231 |
-
service = fake_service(settings(tmp_path))
|
| 232 |
-
runtime = ResidentContact(service)
|
| 233 |
-
# Real persistent subprocess, constructed decision. No model inference claim.
|
| 234 |
-
script = """
|
| 235 |
-
import json,sys
|
| 236 |
-
from pathlib import Path
|
| 237 |
-
from baseball_batting.contact_contract import ContactInput
|
| 238 |
-
from baseball_batting.contact_fast_worker import initial_result
|
| 239 |
-
from baseball_batting.storage import atomic_json,read_json
|
| 240 |
-
root=Path(sys.argv[1])
|
| 241 |
-
for line in sys.stdin:
|
| 242 |
-
c=json.loads(line);p=root/'jobs'/c['job_id']
|
| 243 |
-
options=ContactInput.model_validate(read_json(p/'request.json'))
|
| 244 |
-
if options.use_audio is False:
|
| 245 |
-
import time;time.sleep(30)
|
| 246 |
-
r=initial_result(p,options);r.contact.reasons=['fixture_no_contact']
|
| 247 |
-
atomic_json(p/'fast-result.json',r.model_dump(mode='json'))
|
| 248 |
-
atomic_json(p/'fast-done.json',{'ok':True})
|
| 249 |
-
"""
|
| 250 |
-
runtime.process = subprocess.Popen([sys.executable, '-c', script, str(tmp_path)],
|
| 251 |
-
stdin=subprocess.PIPE, text=True, start_new_session=True)
|
| 252 |
-
runtime.record = {'ready': True, 'models': {'fixture': True}}
|
| 253 |
-
pid = runtime.process.pid
|
| 254 |
-
try:
|
| 255 |
-
for _ in range(2):
|
| 256 |
-
path = job(service, video, {'annotated_video': False})
|
| 257 |
-
service.store.update(path.name, 'running')
|
| 258 |
-
runtime.execute(path.name)
|
| 259 |
-
assert service.store.get(path.name)['status'] == 'completed'
|
| 260 |
-
assert read_json(path/'result.json')['contact']['reasons'] == ['fixture_no_contact']
|
| 261 |
-
assert runtime.ready and runtime.process.pid == pid
|
| 262 |
-
path = job(service, video, {'annotated_video': False, 'use_audio': False, 'processing_budget_s': 1})
|
| 263 |
-
service.store.update(path.name, 'running')
|
| 264 |
-
started = time.monotonic(); runtime.execute(path.name)
|
| 265 |
-
assert time.monotonic()-started < 1.4
|
| 266 |
-
result = read_json(path/'result.json')
|
| 267 |
-
assert result['contact']['reasons'] == ['processing_budget_exceeded']
|
| 268 |
-
assert result['contact']['video_time_s'] is None
|
| 269 |
-
assert service.store.get(path.name)['status'] == 'completed'
|
| 270 |
-
assert not runtime.ready
|
| 271 |
-
finally:
|
| 272 |
-
runtime.stop(immediate=True)
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
def test_pending_video_is_distinct_from_unavailable_and_old_outputs_still_parse(video, tmp_path):
|
| 276 |
-
service = fake_service(settings(tmp_path))
|
| 277 |
-
path = job(service, video)
|
| 278 |
-
result = initial_result(path, ContactInput())
|
| 279 |
-
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 280 |
-
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 281 |
-
# Do not run the background thread, keeping a real pending artifact.
|
| 282 |
-
app = create_app(service.settings, service)
|
| 283 |
-
client = TestClient(app)
|
| 284 |
-
response = client.get(result.artifacts['annotated'].url, headers=AUTH)
|
| 285 |
-
assert response.status_code == 202 and response.headers['retry-after'] == '1'
|
| 286 |
-
assert client.get(result.artifacts['annotated'].url).status_code == 401
|
| 287 |
-
old = result.model_dump(mode='json'); old['schema_version'] = '1.0'
|
| 288 |
-
old.pop('rendering'); old.pop('artifacts_revision')
|
| 289 |
-
old['artifacts'] = {'source': old['artifacts']['source']}
|
| 290 |
-
assert ContactResult.model_validate(old).schema_version == '1.0'
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
def test_cancel_fast_request_kills_resident_and_removes_work(video, tmp_path):
|
| 294 |
-
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 295 |
-
service.store.update(path.name, 'running')
|
| 296 |
-
runtime = ResidentContact(service)
|
| 297 |
-
runtime.process = subprocess.Popen([sys.executable, '-c', 'import sys,time;sys.stdin.readline();time.sleep(30)'],
|
| 298 |
-
stdin=subprocess.PIPE, text=True, start_new_session=True)
|
| 299 |
-
process = runtime.process
|
| 300 |
-
runtime.record = {'ready': True}
|
| 301 |
-
thread = threading.Thread(target=runtime.execute, args=(path.name,))
|
| 302 |
-
try:
|
| 303 |
-
thread.start()
|
| 304 |
-
wait_until(lambda: (path/'source.mp4').exists())
|
| 305 |
-
service.store.cancel(path.name)
|
| 306 |
-
thread.join(timeout=2)
|
| 307 |
-
assert not thread.is_alive() and process.poll() is not None
|
| 308 |
-
assert service.store.get(path.name)['status'] == 'cancelled'
|
| 309 |
-
assert not path.exists()
|
| 310 |
-
finally:
|
| 311 |
-
runtime.stop(immediate=True)
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
def test_fast_warmup_guard_does_not_block_full_mode(video, tmp_path):
|
| 315 |
-
service = fake_service(settings(tmp_path)); service.ready = service.tracking_ready = True
|
| 316 |
-
service.contact_runtime = SimpleNamespace(ready=False, reason='warming')
|
| 317 |
-
client = TestClient(create_app(service.settings, service))
|
| 318 |
-
files = {'video': ('swing.mp4', video.read_bytes(), 'video/mp4')}
|
| 319 |
-
response = client.post('/v1/contact-analyses', files=files, headers=AUTH)
|
| 320 |
-
assert response.status_code == 503 and response.json()['detail']['code'] == 'fast_worker_warming'
|
| 321 |
-
assert list(service.jobs_root.iterdir()) == []
|
| 322 |
-
response = client.post('/v1/contact-analyses', files=files, headers=AUTH, data={'options': '{"mode":"full"}'})
|
| 323 |
-
assert response.status_code == 202
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
def test_unpublished_render_snapshot_does_not_replace_base_decision(video, tmp_path):
|
| 327 |
-
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 328 |
-
result = initial_result(path, ContactInput())
|
| 329 |
-
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 330 |
-
# Simulate a restart after writing a render snapshot but before its DB commit.
|
| 331 |
-
(path/'rendered-result.json').write_text('unpublished')
|
| 332 |
-
service.store.update(path.name, 'completed', result_hash=sha256_file(path/'result.json'))
|
| 333 |
-
client = TestClient(create_app(service.settings, service))
|
| 334 |
-
response = client.get('/v1/contact-analyses/'+path.name+'/result', headers=AUTH)
|
| 335 |
-
assert response.status_code == 200 and response.json()['rendering']['status'] == 'pending'
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
def test_render_failure_keeps_original_decision(video, tmp_path, monkeypatch):
|
| 339 |
-
from baseball_batting.contact_render_worker import render
|
| 340 |
-
from baseball_batting.swing_clips import ClipError
|
| 341 |
-
service = fake_service(settings(tmp_path)); path = job(service, video)
|
| 342 |
-
synthetic_check(monkeypatch); result = decide(path, models())
|
| 343 |
-
atomic_json(path/'result.json', result.model_dump(mode='json'))
|
| 344 |
-
def fail(*args, **kwargs): raise ClipError('last_frame_duration_unavailable')
|
| 345 |
-
monkeypatch.setattr('baseball_batting.contact_videos.export', fail)
|
| 346 |
-
value = render(path)
|
| 347 |
-
assert value['rendering']['status'] == 'failed'
|
| 348 |
-
assert value['artifacts']['annotated']['reason_code'] == 'last_frame_duration_unavailable'
|
| 349 |
-
assert read_json(path/'result.json')['contact'] == result.contact.model_dump(mode='json')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_deployment_sync.py
CHANGED
|
@@ -29,3 +29,28 @@ def test_deployment_copies_same_size_changes_with_identical_timestamps(tmp_path)
|
|
| 29 |
subprocess.run([rsync, *arguments[1:-2], str(source)+'/', str(space)+'/'], check=True)
|
| 30 |
assert old.read_bytes() == new.read_bytes()
|
| 31 |
assert retained.read_text() == 'keep'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
subprocess.run([rsync, *arguments[1:-2], str(source)+'/', str(space)+'/'], check=True)
|
| 30 |
assert old.read_bytes() == new.read_bytes()
|
| 31 |
assert retained.read_text() == 'keep'
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_deployment_removes_retired_contact_files_only(tmp_path):
|
| 35 |
+
root = Path(__file__).parents[1]
|
| 36 |
+
manifest = root/'deploy/huggingface/removed-files.txt'
|
| 37 |
+
retired = [line for line in manifest.read_text().splitlines()
|
| 38 |
+
if line and not line.startswith('#')]
|
| 39 |
+
for name in retired:
|
| 40 |
+
assert not (root/name).exists()
|
| 41 |
+
path = tmp_path/name
|
| 42 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 43 |
+
path.write_text('old deployment source')
|
| 44 |
+
retained = tmp_path/'baseball_batting/space-only.txt'
|
| 45 |
+
retained.write_text('keep')
|
| 46 |
+
shared = tmp_path/'baseball_batting/tracking_vision.py'
|
| 47 |
+
shared.write_text('shared bat/ball inference')
|
| 48 |
+
workflow = (root/'.github/workflows/deploy-huggingface.yml').read_text()
|
| 49 |
+
start = workflow.index(' while IFS= read -r path')
|
| 50 |
+
end = workflow.index('done < deploy/huggingface/removed-files.txt', start)
|
| 51 |
+
command = workflow[start:end] + 'done < deploy/huggingface/removed-files.txt'
|
| 52 |
+
subprocess.run(['bash', '-c', command], cwd=root,
|
| 53 |
+
env={**os.environ, 'workspace': str(tmp_path)}, check=True)
|
| 54 |
+
assert all(not (tmp_path/name).exists() for name in retired)
|
| 55 |
+
assert retained.read_text() == 'keep'
|
| 56 |
+
assert shared.read_text() == 'shared bat/ball inference'
|
tools/benchmark_contact_api.py
DELETED
|
@@ -1,100 +0,0 @@
|
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|