Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
e21e264
1
Parent(s): 1558b6d
Automated Deploy: d224e5e7e286809d46aa129b6ddaf8b604039efe
Browse files- .dockerignore +3 -0
- BUILD_STATUS.md +12 -0
- Dockerfile +14 -0
- baseball_batting/api.py +72 -17
- baseball_batting/api_contract.py +59 -0
- baseball_batting/api_jobs.py +17 -5
- baseball_batting/api_worker.py +58 -2
- baseball_batting/bat_ball_timing.py +217 -0
- baseball_batting/load_timing.py +40 -5
- baseball_batting/timing_evidence.py +155 -0
- baseball_batting/tracking_geometry.py +134 -0
- baseball_batting/tracking_vision.py +173 -0
- docs/GPU_API_DEPLOYMENT.md +3 -3
- docs/LOAD_TIMING_API.md +81 -90
- docs/TRACKING_VALIDATION.md +50 -0
- docs/load-and-timing-for-coach-agent.md +1 -1
- docs/load-timing-evidence.example.json +161 -0
- docs/load-timing-evidence.schema.json +428 -0
- examples/api_client.py +12 -2
- notebooks/load_and_swing_test.ipynb +41 -6
- requirements-tracking-export.txt +5 -0
- tests/test_2d_regressions.py +1 -1
- tests/test_api.py +1 -0
- tests/test_bat_ball_timing.py +130 -0
- tests/test_load_timing_api.py +2 -1
- tests/test_measurement_backends.py +5 -0
- tests/test_timing_tracking_api.py +194 -0
- tests/test_tracking_export.py +43 -0
- tests/test_tracking_geometry.py +94 -0
- tests/test_tracking_vision.py +84 -0
- tools/setup_tracking_models.py +75 -0
.dockerignore
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
!requirements-core.txt
|
| 5 |
!requirements-api.txt
|
| 6 |
!requirements-api-gpu.txt
|
|
|
|
| 7 |
!requirements-sam.txt
|
| 8 |
!pyproject.toml
|
| 9 |
!baseball_batting/
|
|
@@ -12,6 +13,7 @@
|
|
| 12 |
!configs/*.yaml
|
| 13 |
!tools/
|
| 14 |
!tools/setup_api_models.py
|
|
|
|
| 15 |
!tools/setup_full_worker.py
|
| 16 |
!tools/setup_sam_api_worker.py
|
| 17 |
!tools/register_sam_api_worker.py
|
|
@@ -20,4 +22,5 @@
|
|
| 20 |
!docs/api-result.schema.json
|
| 21 |
!docs/coach-payload.schema.json
|
| 22 |
!docs/load-timing.schema.json
|
|
|
|
| 23 |
**/__pycache__
|
|
|
|
| 4 |
!requirements-core.txt
|
| 5 |
!requirements-api.txt
|
| 6 |
!requirements-api-gpu.txt
|
| 7 |
+
!requirements-tracking-export.txt
|
| 8 |
!requirements-sam.txt
|
| 9 |
!pyproject.toml
|
| 10 |
!baseball_batting/
|
|
|
|
| 13 |
!configs/*.yaml
|
| 14 |
!tools/
|
| 15 |
!tools/setup_api_models.py
|
| 16 |
+
!tools/setup_tracking_models.py
|
| 17 |
!tools/setup_full_worker.py
|
| 18 |
!tools/setup_sam_api_worker.py
|
| 19 |
!tools/register_sam_api_worker.py
|
|
|
|
| 22 |
!docs/api-result.schema.json
|
| 23 |
!docs/coach-payload.schema.json
|
| 24 |
!docs/load-timing.schema.json
|
| 25 |
+
!docs/load-timing-evidence.schema.json
|
| 26 |
**/__pycache__
|
BUILD_STATUS.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
| 1 |
# Build status
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## Four-field load and timing API — 2026-10-12
|
| 4 |
|
| 5 |
`GET /v1/analyses/{job_id}/load-timing` returns the discussed version 3.0 JSON with `load_to_swing_ms`, `foot_down_to_swing_ms`, `swing_duration_ms` and `early_late_shift_ms` per candidate. Upload/status responses now include `load_timing_url`; `GET /v1/load-timing-schema` exposes the separate contract. The existing nine-field coach endpoint remains version 2.0. Use `measurement_backend: "2d"` to run timing jobs without 3D. [LOAD_TIMING_API.md](docs/LOAD_TIMING_API.md) documents API testing, the shape and limitations.
|
|
|
|
| 1 |
# Build status
|
| 2 |
|
| 3 |
+
## Bat/ball load timing implementation — 2026-10-13
|
| 4 |
+
|
| 5 |
+
The dedicated `POST /v1/load-timing/analyses` route rejects missing recording settings and requires actual bat/ball CUDA preflight. It uses 2D body pose; SAM does not run. Separate pinned BaseballCV bat pose and baseball detector checkpoints are exported to ONNX in a Docker build stage. The bat adapter uses observed outer shaft landmarks rather than replacing an endpoint with a hand. Searches preserve full-image candidates and additional athlete/bat crops, with direct observations and missing frames retained in diagnostics.
|
| 6 |
+
|
| 7 |
+
Estimated visual hit intervals now feed `swing_duration_ms` when supported, including a separate stationary-tee departure branch. Projection overlap, disappearance, an unrelated ball bounce or the body-extension proxy do not establish contact. Optional synchronized calibrated second views support physical miss closest approach and a barrel timing-shift search on the same observed paths. The search propagates supplied position/synchronization bounds, preserves disconnected intervals and withholds ambiguous, unsupported or boundary-limited solutions. A finite scalar uses the closest-to-zero certified feasible shift under these assumptions. Tee misses do not receive moving-pitch timing corrections.
|
| 8 |
+
|
| 9 |
+
Existing 2.0 and default 3.0 payloads remain available. Opt-in `?include_evidence=true` returns 3.1 with event intervals, metric reason codes, sensitivity and supplied practice/pitch context. New artifacts receive checksums through an additive database migration. Terminal cleanup includes the second recording. A trusted replacement checkpoint can be exported without changing calculation code.
|
| 10 |
+
|
| 11 |
+
Executed checks: **294 passed, 2 skipped** in the complete regression suite, including replacement-checkpoint export and incoming-flight regressions. A final class-dominance adapter check also passed. A return from a net is withheld rather than treated as the incoming pitch. The existing Starlette/httpx deprecation warning remains. Constructed model observations passed actual decoding, worker storage, strict payload validation and HTTP retrieval for hit duration and a two-view miss with all four values. These tests do not establish neural-network measurement accuracy.
|
| 12 |
+
|
| 13 |
+
Real exported ONNX checks on selected frames of the supplied tee recording and `IMG_1610` exposed detector misses, including blurred bats around impact and a ball on the tee. No per-video coordinates, hidden labels or fabricated endpoints were added to force outputs. **Reliable contact measurement on these recordings remains unresolved.** Models need further evaluation and likely fine-tuning for this footage; all values remain estimates. The local Docker daemon is unavailable and no NVIDIA GPU is present, so the rebuilt Linux image/CUDA deployment still needs verification. See [tracking validation](docs/TRACKING_VALIDATION.md) and [API integration](docs/LOAD_TIMING_API.md).
|
| 14 |
+
|
| 15 |
## Four-field load and timing API — 2026-10-12
|
| 16 |
|
| 17 |
`GET /v1/analyses/{job_id}/load-timing` returns the discussed version 3.0 JSON with `load_to_swing_ms`, `foot_down_to_swing_ms`, `swing_duration_ms` and `early_late_shift_ms` per candidate. Upload/status responses now include `load_timing_url`; `GET /v1/load-timing-schema` exposes the separate contract. The existing nine-field coach endpoint remains version 2.0. Use `measurement_backend: "2d"` to run timing jobs without 3D. [LOAD_TIMING_API.md](docs/LOAD_TIMING_API.md) documents API testing, the shape and limitations.
|
Dockerfile
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
FROM python:3.11-slim-bookworm
|
| 2 |
|
| 3 |
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
|
|
@@ -17,6 +28,9 @@ COPY tools/__init__.py ./tools/__init__.py
|
|
| 17 |
COPY docs/api-result.schema.json ./docs/api-result.schema.json
|
| 18 |
COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
|
| 19 |
COPY docs/load-timing.schema.json ./docs/load-timing.schema.json
|
|
|
|
|
|
|
|
|
|
| 20 |
RUN python -m tools.setup_api_models --output /opt/models --with-3d \
|
| 21 |
&& python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \
|
| 22 |
&& groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \
|
|
|
|
| 1 |
+
FROM python:3.11-slim-bookworm AS tracking-export
|
| 2 |
+
ENV PYTHONUNBUFFERED=1 MPLBACKEND=Agg YOLO_CONFIG_DIR=/tmp
|
| 3 |
+
WORKDIR /export
|
| 4 |
+
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 \
|
| 5 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 6 |
+
COPY requirements-tracking-export.txt ./
|
| 7 |
+
RUN python -m pip install --index-url https://download.pytorch.org/whl/cpu torch==2.9.1 torchvision==0.24.1 \
|
| 8 |
+
&& python -m pip install -r requirements-tracking-export.txt
|
| 9 |
+
COPY tools/__init__.py tools/setup_tracking_models.py ./tools/
|
| 10 |
+
RUN python -m tools.setup_tracking_models --output /tracking-models --weights /tmp/weights
|
| 11 |
+
|
| 12 |
FROM python:3.11-slim-bookworm
|
| 13 |
|
| 14 |
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
|
|
|
|
| 28 |
COPY docs/api-result.schema.json ./docs/api-result.schema.json
|
| 29 |
COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
|
| 30 |
COPY docs/load-timing.schema.json ./docs/load-timing.schema.json
|
| 31 |
+
COPY docs/load-timing-evidence.schema.json ./docs/load-timing-evidence.schema.json
|
| 32 |
+
COPY --from=tracking-export /tracking-models/tracking_bat /opt/models/tracking_bat
|
| 33 |
+
COPY --from=tracking-export /tracking-models/tracking_ball /opt/models/tracking_ball
|
| 34 |
RUN python -m tools.setup_api_models --output /opt/models --with-3d \
|
| 35 |
&& python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \
|
| 36 |
&& groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \
|
baseball_batting/api.py
CHANGED
|
@@ -7,7 +7,7 @@ import os
|
|
| 7 |
from pathlib import Path
|
| 8 |
import shutil
|
| 9 |
from typing import Annotated
|
| 10 |
-
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
|
| 11 |
from fastapi.responses import JSONResponse, StreamingResponse
|
| 12 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 13 |
from pydantic import ValidationError
|
|
@@ -16,6 +16,7 @@ from starlette.concurrency import run_in_threadpool
|
|
| 16 |
from .api_contract import AnalysisInput
|
| 17 |
from .api_jobs import ApiSettings, JobService, QueueFull
|
| 18 |
from .load_timing_contract import LoadTimingPayload
|
|
|
|
| 19 |
from .storage import atomic_json, read_json, sha256_file
|
| 20 |
|
| 21 |
ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
|
|
@@ -52,7 +53,7 @@ class UploadGuard:
|
|
| 52 |
if received > limit:
|
| 53 |
raise HTTPException(413, "Request exceeds upload limit")
|
| 54 |
return message
|
| 55 |
-
is_upload = scope["method"] == "POST" and scope["path"]
|
| 56 |
if is_upload:
|
| 57 |
if not self.service.ready:
|
| 58 |
return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
|
|
@@ -71,8 +72,8 @@ def create_app(settings=None, service=None):
|
|
| 71 |
service.start()
|
| 72 |
try: yield
|
| 73 |
finally: service.stop()
|
| 74 |
-
app = FastAPI(title="Baseball GPU Measurement API", version="1.
|
| 75 |
-
description="GPU batting
|
| 76 |
app.state.service = service
|
| 77 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
| 78 |
|
|
@@ -95,10 +96,12 @@ def create_app(settings=None, service=None):
|
|
| 95 |
@app.get("/readyz")
|
| 96 |
def ready():
|
| 97 |
return JSONResponse({"ready": service.ready, "reason": service.readiness_reason,
|
|
|
|
| 98 |
"device": "cuda", "body_3d": False}, status_code=200 if service.ready else 503)
|
| 99 |
|
| 100 |
@app.get("/v1/capabilities", dependencies=[Depends(authenticated)])
|
| 101 |
def capabilities():
|
|
|
|
| 102 |
sam_record = os.environ.get("BASEBALL_SAM_WORKER_RECORD")
|
| 103 |
sam_configured = False
|
| 104 |
if sam_record and Path(sam_record).is_file():
|
|
@@ -115,9 +118,13 @@ def create_app(settings=None, service=None):
|
|
| 115 |
"body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
|
| 116 |
"automatic_events": True, "swing_metrics": True, "estimated_only": True,
|
| 117 |
"measurement_validation": "reference_validation_pending", "coaching": False,
|
| 118 |
-
"load_timing": {"schema_version": "3.0", "route": "/v1/analyses/{job_id}/load-timing",
|
| 119 |
-
|
| 120 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
"limits": {"upload_bytes": settings.max_upload_bytes, "duration_s": settings.max_duration_s,
|
| 122 |
"frames": settings.max_frames, "pixels": settings.max_pixels},
|
| 123 |
"retention_hours": settings.retention_s / 3600}
|
|
@@ -135,12 +142,18 @@ def create_app(settings=None, service=None):
|
|
| 135 |
return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json")
|
| 136 |
|
| 137 |
@app.get("/v1/load-timing-schema", dependencies=[Depends(authenticated)])
|
| 138 |
-
def timing_schema():
|
|
|
|
|
|
|
| 139 |
return read_json(Path(__file__).resolve().parents[1] / "docs/load-timing.schema.json")
|
| 140 |
|
| 141 |
@app.post("/v1/analyses", status_code=202, dependencies=[Depends(authenticated)])
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
identifier = None
|
| 145 |
try:
|
| 146 |
if not service.ready: raise HTTPException(503, "GPU worker is not ready; check /readyz")
|
|
@@ -151,6 +164,24 @@ def create_app(settings=None, service=None):
|
|
| 151 |
details = [{"loc": list(item["loc"]), "type": item["type"], "msg": item["msg"]}
|
| 152 |
for item in error.errors(include_url=False, include_input=False)]
|
| 153 |
raise HTTPException(422, details)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
suffix = Path(video.filename or "").suffix.lower()
|
| 155 |
if suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, "Unsupported video extension")
|
| 156 |
if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes:
|
|
@@ -168,12 +199,31 @@ def create_app(settings=None, service=None):
|
|
| 168 |
raise HTTPException(507, "Insufficient storage")
|
| 169 |
destination.write(block)
|
| 170 |
if size == 0: raise HTTPException(422, "Video is empty")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
atomic_json(directory / "request.json", parsed.model_dump(exclude_none=True))
|
| 172 |
service.store.update(identifier, "queued")
|
| 173 |
service.wakeup.set()
|
| 174 |
return {"job_id": identifier, "status": "queued",
|
| 175 |
"status_url": f"/v1/analyses/{identifier}", "result_url": f"/v1/analyses/{identifier}/result",
|
| 176 |
"load_timing_url": f"/v1/analyses/{identifier}/load-timing",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
"coach_payload_url": f"/v1/analyses/{identifier}/coach-payload"}
|
| 178 |
except BaseException:
|
| 179 |
if identifier:
|
|
@@ -182,6 +232,8 @@ def create_app(settings=None, service=None):
|
|
| 182 |
raise
|
| 183 |
finally:
|
| 184 |
await video.close()
|
|
|
|
|
|
|
| 185 |
|
| 186 |
@app.get("/v1/analyses/{job_id}", dependencies=[Depends(authenticated)])
|
| 187 |
def status(job_id: str):
|
|
@@ -192,6 +244,7 @@ def create_app(settings=None, service=None):
|
|
| 192 |
"updated_at": record["updated"], "progress": progress, "error": record["error"],
|
| 193 |
"result_url": f"/v1/analyses/{job_id}/result" if record["status"] == "completed" else None,
|
| 194 |
"load_timing_url": f"/v1/analyses/{job_id}/load-timing" if record["status"] == "completed" and record.get("load_timing_sha256") else None,
|
|
|
|
| 195 |
"coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None}
|
| 196 |
|
| 197 |
@app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)])
|
|
@@ -207,22 +260,24 @@ def create_app(settings=None, service=None):
|
|
| 207 |
payload = read_json(path)
|
| 208 |
return JSONResponse(payload, headers={"Cache-Control": "no-store"})
|
| 209 |
|
| 210 |
-
@app.get("/v1/analyses/{job_id}/load-timing", response_model=LoadTimingPayload,
|
| 211 |
dependencies=[Depends(authenticated)],
|
| 212 |
summary="Get four load and swing timing measurements",
|
| 213 |
-
description="Capture milliseconds per swing.
|
| 214 |
-
def get_load_timing(job_id: str):
|
| 215 |
with service.mutation_lock:
|
| 216 |
directory, record = job_record(job_id)
|
| 217 |
if record["status"] != "completed":
|
| 218 |
raise HTTPException(409, "Job has no completed result; check job status")
|
| 219 |
-
path = directory /
|
| 220 |
-
if
|
|
|
|
| 221 |
raise HTTPException(409, "This older job has no load/timing payload; submit the video again")
|
| 222 |
-
if not path.is_file() or sha256_file(path) != record[
|
| 223 |
raise HTTPException(500, "Stored load/timing payload failed its integrity check")
|
| 224 |
try:
|
| 225 |
-
|
|
|
|
| 226 |
except (ValidationError, ValueError):
|
| 227 |
raise HTTPException(500, "Stored load/timing payload has invalid structure") from None
|
| 228 |
return JSONResponse(payload.model_dump(mode="json"), headers={"Cache-Control": "no-store"})
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
import shutil
|
| 9 |
from typing import Annotated
|
| 10 |
+
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile, Request
|
| 11 |
from fastapi.responses import JSONResponse, StreamingResponse
|
| 12 |
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 13 |
from pydantic import ValidationError
|
|
|
|
| 16 |
from .api_contract import AnalysisInput
|
| 17 |
from .api_jobs import ApiSettings, JobService, QueueFull
|
| 18 |
from .load_timing_contract import LoadTimingPayload
|
| 19 |
+
from .timing_evidence import TimingEvidencePayload
|
| 20 |
from .storage import atomic_json, read_json, sha256_file
|
| 21 |
|
| 22 |
ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
|
|
|
|
| 53 |
if received > limit:
|
| 54 |
raise HTTPException(413, "Request exceeds upload limit")
|
| 55 |
return message
|
| 56 |
+
is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses'}
|
| 57 |
if is_upload:
|
| 58 |
if not self.service.ready:
|
| 59 |
return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
|
|
|
|
| 72 |
service.start()
|
| 73 |
try: yield
|
| 74 |
finally: service.stop()
|
| 75 |
+
app = FastAPI(title="Baseball GPU Measurement API", version="1.4.0", lifespan=lifespan,
|
| 76 |
+
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.")
|
| 77 |
app.state.service = service
|
| 78 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
| 79 |
|
|
|
|
| 96 |
@app.get("/readyz")
|
| 97 |
def ready():
|
| 98 |
return JSONResponse({"ready": service.ready, "reason": service.readiness_reason,
|
| 99 |
+
'bat_ball_tracking_ready': service.tracking_ready,
|
| 100 |
"device": "cuda", "body_3d": False}, status_code=200 if service.ready else 503)
|
| 101 |
|
| 102 |
@app.get("/v1/capabilities", dependencies=[Depends(authenticated)])
|
| 103 |
def capabilities():
|
| 104 |
+
tracking_configured = service.tracking_ready
|
| 105 |
sam_record = os.environ.get("BASEBALL_SAM_WORKER_RECORD")
|
| 106 |
sam_configured = False
|
| 107 |
if sam_record and Path(sam_record).is_file():
|
|
|
|
| 118 |
"body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
|
| 119 |
"automatic_events": True, "swing_metrics": True, "estimated_only": True,
|
| 120 |
"measurement_validation": "reference_validation_pending", "coaching": False,
|
| 121 |
+
"load_timing": {"schema_version": "3.0", 'evidence_schema_version': '3.1', "route": "/v1/analyses/{job_id}/load-timing",
|
| 122 |
+
'upload_route': '/v1/load-timing/analyses',
|
| 123 |
+
"automatic_load_and_foot_timing": True, "automatic_ball_contact": tracking_configured,
|
| 124 |
+
'contact_scope': 'visual bat/ball interaction estimate; not independently validated',
|
| 125 |
+
"automatic_bat_ball_tracking": tracking_configured, "early_late_estimate": tracking_configured,
|
| 126 |
+
'early_late_requirements': 'secondary_video, documented calibration/synchronization/position bounds and complete spatial paths',
|
| 127 |
+
'single_video_early_late': False},
|
| 128 |
"limits": {"upload_bytes": settings.max_upload_bytes, "duration_s": settings.max_duration_s,
|
| 129 |
"frames": settings.max_frames, "pixels": settings.max_pixels},
|
| 130 |
"retention_hours": settings.retention_s / 3600}
|
|
|
|
| 142 |
return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json")
|
| 143 |
|
| 144 |
@app.get("/v1/load-timing-schema", dependencies=[Depends(authenticated)])
|
| 145 |
+
def timing_schema(include_evidence: bool = False):
|
| 146 |
+
if include_evidence:
|
| 147 |
+
return TimingEvidencePayload.model_json_schema()
|
| 148 |
return read_json(Path(__file__).resolve().parents[1] / "docs/load-timing.schema.json")
|
| 149 |
|
| 150 |
@app.post("/v1/analyses", status_code=202, dependencies=[Depends(authenticated)])
|
| 151 |
+
@app.post('/v1/load-timing/analyses', status_code=202, dependencies=[Depends(authenticated)],
|
| 152 |
+
summary='Upload for load/timing; reject missing recording settings before inference')
|
| 153 |
+
async def create_analysis(request: Request,
|
| 154 |
+
video: Annotated[UploadFile, File(description="Original recording")],
|
| 155 |
+
options: Annotated[str, Form(description="One JSON text field. For timing: view=face_on, handedness, pitcher_direction and documented timing are required.")] = "{}",
|
| 156 |
+
secondary_video: Annotated[UploadFile | None, File(description='Optional synchronized second view; requires stereo_tracking calibration in options')] = None):
|
| 157 |
identifier = None
|
| 158 |
try:
|
| 159 |
if not service.ready: raise HTTPException(503, "GPU worker is not ready; check /readyz")
|
|
|
|
| 164 |
details = [{"loc": list(item["loc"]), "type": item["type"], "msg": item["msg"]}
|
| 165 |
for item in error.errors(include_url=False, include_input=False)]
|
| 166 |
raise HTTPException(422, details)
|
| 167 |
+
missing = []
|
| 168 |
+
if parsed.view != 'face_on': missing.append('view')
|
| 169 |
+
if parsed.handedness is None: missing.append('handedness')
|
| 170 |
+
if parsed.pitcher_direction is None: missing.append('pitcher_direction')
|
| 171 |
+
if parsed.timing.kind == 'unknown': missing.append('timing')
|
| 172 |
+
if request.url.path == '/v1/load-timing/analyses' and missing:
|
| 173 |
+
raise HTTPException(422, {'code': 'timing_settings_required', 'fields': missing,
|
| 174 |
+
'message': 'Supply these recording facts in the options JSON. The engine cannot infer original capture time or verify your camera view.'})
|
| 175 |
+
if request.url.path == '/v1/load-timing/analyses':
|
| 176 |
+
if parsed.measurement_backend != '2d':
|
| 177 |
+
raise HTTPException(422, {'code': 'timing_uses_2d_body',
|
| 178 |
+
'message': 'Use measurement_backend=2d for this route. Bat/ball geometry is independent of SAM body reconstruction.'})
|
| 179 |
+
if not service.tracking_ready:
|
| 180 |
+
raise HTTPException(503, {'code': 'tracking_models_unavailable',
|
| 181 |
+
'message': 'Bat and ball models must pass CUDA preflight. Rebuild the tracking-enabled GPU image.'})
|
| 182 |
+
if (secondary_video is not None) != (parsed.stereo_tracking is not None):
|
| 183 |
+
raise HTTPException(422, {'code': 'stereo_input_incomplete',
|
| 184 |
+
'message': 'Supply both secondary_video and stereo_tracking calibration, or neither.'})
|
| 185 |
suffix = Path(video.filename or "").suffix.lower()
|
| 186 |
if suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, "Unsupported video extension")
|
| 187 |
if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes:
|
|
|
|
| 199 |
raise HTTPException(507, "Insufficient storage")
|
| 200 |
destination.write(block)
|
| 201 |
if size == 0: raise HTTPException(422, "Video is empty")
|
| 202 |
+
if secondary_video is not None:
|
| 203 |
+
second_suffix = Path(secondary_video.filename or '').suffix.lower()
|
| 204 |
+
if second_suffix not in ALLOWED_VIDEO_SUFFIXES:
|
| 205 |
+
raise HTTPException(415, 'Unsupported secondary video extension')
|
| 206 |
+
second_size = 0
|
| 207 |
+
with (directory/('secondary'+second_suffix)).open('wb') as destination:
|
| 208 |
+
while block := await secondary_video.read(1024*1024):
|
| 209 |
+
size += len(block); second_size += len(block)
|
| 210 |
+
if size > settings.max_upload_bytes:
|
| 211 |
+
raise HTTPException(413, 'Combined videos exceed upload limit')
|
| 212 |
+
if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes+len(block):
|
| 213 |
+
raise HTTPException(507, 'Insufficient storage')
|
| 214 |
+
destination.write(block)
|
| 215 |
+
if second_size == 0:
|
| 216 |
+
raise HTTPException(422, 'Secondary video is empty')
|
| 217 |
atomic_json(directory / "request.json", parsed.model_dump(exclude_none=True))
|
| 218 |
service.store.update(identifier, "queued")
|
| 219 |
service.wakeup.set()
|
| 220 |
return {"job_id": identifier, "status": "queued",
|
| 221 |
"status_url": f"/v1/analyses/{identifier}", "result_url": f"/v1/analyses/{identifier}/result",
|
| 222 |
"load_timing_url": f"/v1/analyses/{identifier}/load-timing",
|
| 223 |
+
'load_timing_evidence_url': f'/v1/analyses/{identifier}/load-timing?include_evidence=true',
|
| 224 |
+
'warnings': ([{'code': 'timing_settings_missing', 'fields': missing,
|
| 225 |
+
'message': 'Timing measurements may be unavailable. Supply recording facts in options.'}] if missing else []) +
|
| 226 |
+
([{'code': 'camera_stability_unverified', 'message': 'Foot landing timing needs a verified fixed camera.'}] if parsed.camera_stability != 'fixed_verified' else []),
|
| 227 |
"coach_payload_url": f"/v1/analyses/{identifier}/coach-payload"}
|
| 228 |
except BaseException:
|
| 229 |
if identifier:
|
|
|
|
| 232 |
raise
|
| 233 |
finally:
|
| 234 |
await video.close()
|
| 235 |
+
if secondary_video is not None:
|
| 236 |
+
await secondary_video.close()
|
| 237 |
|
| 238 |
@app.get("/v1/analyses/{job_id}", dependencies=[Depends(authenticated)])
|
| 239 |
def status(job_id: str):
|
|
|
|
| 244 |
"updated_at": record["updated"], "progress": progress, "error": record["error"],
|
| 245 |
"result_url": f"/v1/analyses/{job_id}/result" if record["status"] == "completed" else None,
|
| 246 |
"load_timing_url": f"/v1/analyses/{job_id}/load-timing" if record["status"] == "completed" and record.get("load_timing_sha256") else None,
|
| 247 |
+
'load_timing_evidence_url': f'/v1/analyses/{job_id}/load-timing?include_evidence=true' if record['status'] == 'completed' and record.get('timing_evidence_sha256') else None,
|
| 248 |
"coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None}
|
| 249 |
|
| 250 |
@app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)])
|
|
|
|
| 260 |
payload = read_json(path)
|
| 261 |
return JSONResponse(payload, headers={"Cache-Control": "no-store"})
|
| 262 |
|
| 263 |
+
@app.get("/v1/analyses/{job_id}/load-timing", response_model=LoadTimingPayload | TimingEvidencePayload,
|
| 264 |
dependencies=[Depends(authenticated)],
|
| 265 |
summary="Get four load and swing timing measurements",
|
| 266 |
+
description="Capture milliseconds per swing. Default 3.0; include_evidence=true returns 3.1 with events, reason codes, context and sensitivity. Physical miss/shift requires supported two-view geometry.")
|
| 267 |
+
def get_load_timing(job_id: str, include_evidence: bool = False):
|
| 268 |
with service.mutation_lock:
|
| 269 |
directory, record = job_record(job_id)
|
| 270 |
if record["status"] != "completed":
|
| 271 |
raise HTTPException(409, "Job has no completed result; check job status")
|
| 272 |
+
path = directory / ('load-timing-evidence.json' if include_evidence else 'load-timing.json')
|
| 273 |
+
hash_key = 'timing_evidence_sha256' if include_evidence else 'load_timing_sha256'
|
| 274 |
+
if record.get(hash_key) is None:
|
| 275 |
raise HTTPException(409, "This older job has no load/timing payload; submit the video again")
|
| 276 |
+
if not path.is_file() or sha256_file(path) != record[hash_key]:
|
| 277 |
raise HTTPException(500, "Stored load/timing payload failed its integrity check")
|
| 278 |
try:
|
| 279 |
+
model = TimingEvidencePayload if include_evidence else LoadTimingPayload
|
| 280 |
+
payload = model.model_validate(read_json(path))
|
| 281 |
except (ValidationError, ValueError):
|
| 282 |
raise HTTPException(500, "Stored load/timing payload has invalid structure") from None
|
| 283 |
return JSONResponse(payload.model_dump(mode="json"), headers={"Cache-Control": "no-store"})
|
baseball_batting/api_contract.py
CHANGED
|
@@ -47,6 +47,54 @@ class CameraInput(BaseModel):
|
|
| 47 |
source: str = Field(min_length=1, max_length=512)
|
| 48 |
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
class AnalysisInput(BaseModel):
|
| 51 |
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 52 |
discipline: Literal["hitting"] = "hitting"
|
|
@@ -67,10 +115,21 @@ class AnalysisInput(BaseModel):
|
|
| 67 |
timing: TimingInput = Field(default_factory=TimingInput)
|
| 68 |
single_swing: bool = False
|
| 69 |
reps: list[RepRange] = Field(default_factory=list, max_length=100)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
@model_validator(mode="after")
|
| 72 |
def ranges(self):
|
| 73 |
import math
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
if self.root_depth_m is not None and not (self.root_depth_source and self.root_depth_source.strip()):
|
| 75 |
raise ValueError("A supplied pelvis depth needs a source description")
|
| 76 |
if sum(x*x for x in self.camera_up) < .5 or not all(math.isfinite(x) for x in self.camera_up):
|
|
|
|
| 47 |
source: str = Field(min_length=1, max_length=512)
|
| 48 |
|
| 49 |
|
| 50 |
+
class TrackingCamera(BaseModel):
|
| 51 |
+
"""Calibration in upright image pixels, world translation in metres."""
|
| 52 |
+
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 53 |
+
intrinsics: list[list[float]]
|
| 54 |
+
rotation: list[list[float]]
|
| 55 |
+
translation_m: tuple[float, float, float]
|
| 56 |
+
distortion: list[float] = Field(default_factory=lambda: [0., 0., 0., 0., 0.])
|
| 57 |
+
|
| 58 |
+
@model_validator(mode="after")
|
| 59 |
+
def valid_geometry(self):
|
| 60 |
+
from .geometry import intrinsics, rotation
|
| 61 |
+
intrinsics(self.intrinsics)
|
| 62 |
+
rotation(self.rotation)
|
| 63 |
+
if len(self.distortion) not in (4, 5, 8):
|
| 64 |
+
raise ValueError('Lens distortion must have 4, 5 or 8 coefficients')
|
| 65 |
+
return self
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class StereoTrackingInput(BaseModel):
|
| 69 |
+
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 70 |
+
cameras: list[TrackingCamera] = Field(min_length=2, max_length=2)
|
| 71 |
+
source: str = Field(min_length=1, max_length=512)
|
| 72 |
+
synchronization_source: str = Field(min_length=1, max_length=512)
|
| 73 |
+
secondary_offset_s: float
|
| 74 |
+
synchronization_bound_ms: float = Field(ge=0, le=10)
|
| 75 |
+
position_bound_m: float = Field(gt=0, le=.2)
|
| 76 |
+
position_bound_source: str = Field(min_length=1, max_length=512)
|
| 77 |
+
bat_length_m: float = Field(gt=.2, lt=1.5)
|
| 78 |
+
barrel_radius_m: float = Field(gt=.005, lt=.1)
|
| 79 |
+
barrel_start_fraction: float = Field(default=.5, ge=0, lt=1)
|
| 80 |
+
ball_radius_m: float = Field(default=.0366, gt=.005, lt=.1)
|
| 81 |
+
secondary_timing: TimingInput
|
| 82 |
+
secondary_rotation_degrees: Literal[0, 90, 180, 270] | None = None
|
| 83 |
+
max_shift_ms: float = Field(default=250, gt=0, le=1000)
|
| 84 |
+
|
| 85 |
+
@model_validator(mode="after")
|
| 86 |
+
def documented(self):
|
| 87 |
+
if any(not s.strip() for s in (self.source, self.synchronization_source, self.position_bound_source)):
|
| 88 |
+
raise ValueError('Calibration, synchronization and position bounds need documented sources')
|
| 89 |
+
if self.secondary_timing.kind == 'unknown':
|
| 90 |
+
raise ValueError('Secondary capture time must be documented')
|
| 91 |
+
import numpy as np
|
| 92 |
+
centres = [-np.asarray(c.rotation).T@np.asarray(c.translation_m) for c in self.cameras]
|
| 93 |
+
if np.linalg.norm(centres[1]-centres[0]) < .01:
|
| 94 |
+
raise ValueError('Two distinct calibrated camera positions are required')
|
| 95 |
+
return self
|
| 96 |
+
|
| 97 |
+
|
| 98 |
class AnalysisInput(BaseModel):
|
| 99 |
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 100 |
discipline: Literal["hitting"] = "hitting"
|
|
|
|
| 115 |
timing: TimingInput = Field(default_factory=TimingInput)
|
| 116 |
single_swing: bool = False
|
| 117 |
reps: list[RepRange] = Field(default_factory=list, max_length=100)
|
| 118 |
+
practice_type: Literal['tee', 'soft_toss', 'front_toss', 'live', 'machine', 'unknown'] = 'unknown'
|
| 119 |
+
pitch_speed_mps: float | None = Field(default=None, gt=0, le=100)
|
| 120 |
+
pitch_location: str | None = Field(default=None, min_length=1, max_length=256)
|
| 121 |
+
pitch_context_source: str | None = Field(default=None, min_length=1, max_length=512)
|
| 122 |
+
stereo_tracking: StereoTrackingInput | None = None
|
| 123 |
|
| 124 |
@model_validator(mode="after")
|
| 125 |
def ranges(self):
|
| 126 |
import math
|
| 127 |
+
if (self.pitch_speed_mps is not None or self.pitch_location is not None) and not (self.pitch_context_source and self.pitch_context_source.strip()):
|
| 128 |
+
raise ValueError('Pitch speed/location need a source; they are supplied context, not video measurements')
|
| 129 |
+
if self.stereo_tracking and self.timing.kind == 'unknown':
|
| 130 |
+
raise ValueError('Two-view analysis requires documented primary capture time')
|
| 131 |
+
if self.stereo_tracking and self.camera_stability != 'fixed_verified':
|
| 132 |
+
raise ValueError('Two-view calibration requires verified fixed cameras')
|
| 133 |
if self.root_depth_m is not None and not (self.root_depth_source and self.root_depth_source.strip()):
|
| 134 |
raise ValueError("A supplied pelvis depth needs a source description")
|
| 135 |
if sum(x*x for x in self.camera_up) < .5 or not all(math.isfinite(x) for x in self.camera_up):
|
baseball_batting/api_jobs.py
CHANGED
|
@@ -78,6 +78,8 @@ class JobStore:
|
|
| 78 |
db.execute("ALTER TABLE jobs ADD COLUMN coach_payload_sha256 TEXT")
|
| 79 |
if "load_timing_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}:
|
| 80 |
db.execute("ALTER TABLE jobs ADD COLUMN load_timing_sha256 TEXT")
|
|
|
|
|
|
|
| 81 |
|
| 82 |
@contextmanager
|
| 83 |
def connect(self):
|
|
@@ -103,10 +105,10 @@ class JobStore:
|
|
| 103 |
value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 104 |
return dict(value) if value else None
|
| 105 |
|
| 106 |
-
def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None):
|
| 107 |
with self.connect() as db:
|
| 108 |
-
db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=? WHERE id=?",
|
| 109 |
-
(status, time.time(), error, result_hash, coach_hash, timing_hash, identifier))
|
| 110 |
|
| 111 |
def claim(self):
|
| 112 |
with self.connect() as db:
|
|
@@ -122,7 +124,7 @@ class JobStore:
|
|
| 122 |
row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 123 |
if not row: return None
|
| 124 |
status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
|
| 125 |
-
db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL WHERE id=?",
|
| 126 |
(status, time.time(), identifier))
|
| 127 |
return status
|
| 128 |
|
|
@@ -167,6 +169,7 @@ class JobService:
|
|
| 167 |
self.preflight_command = preflight_command or [sys.executable, "-m", "baseball_batting.api_worker",
|
| 168 |
"--preflight", "--models", str(settings.model_root), "--output", str(settings.data_root / "gpu-ready.json")]
|
| 169 |
self.ready = False
|
|
|
|
| 170 |
self.readiness_reason = "gpu_preflight_pending"
|
| 171 |
self.stopping = threading.Event()
|
| 172 |
self.wakeup = threading.Event()
|
|
@@ -246,6 +249,8 @@ class JobService:
|
|
| 246 |
|
| 247 |
def loop(self):
|
| 248 |
try:
|
|
|
|
|
|
|
| 249 |
preflight = self.launch(self.preflight_command, self.settings.data_root / "gpu-preflight.log")
|
| 250 |
start = time.monotonic()
|
| 251 |
while preflight.poll() is None:
|
|
@@ -256,6 +261,9 @@ class JobService:
|
|
| 256 |
if preflight.returncode:
|
| 257 |
self.readiness_reason = "gpu_preflight_failed"
|
| 258 |
return
|
|
|
|
|
|
|
|
|
|
| 259 |
self.ready = True; self.readiness_reason = "ready"
|
| 260 |
while not self.stopping.is_set():
|
| 261 |
self.cleanup()
|
|
@@ -269,6 +277,7 @@ class JobService:
|
|
| 269 |
LOG.exception("GPU job queue stopped")
|
| 270 |
finally:
|
| 271 |
self.ready = False
|
|
|
|
| 272 |
|
| 273 |
def execute(self, identifier):
|
| 274 |
directory = self.job_directory(identifier)
|
|
@@ -306,7 +315,8 @@ class JobService:
|
|
| 306 |
timing_path = directory / "load-timing.json"
|
| 307 |
self.store.update(identifier, "completed", result_hash=sha256_file(directory / "result.json"),
|
| 308 |
coach_hash=sha256_file(coach_path) if coach_path.is_file() else None,
|
| 309 |
-
timing_hash=sha256_file(timing_path) if timing_path.is_file() else None
|
|
|
|
| 310 |
else:
|
| 311 |
error = read_json(directory / "error.json") if (directory / "error.json").exists() else {}
|
| 312 |
code = error.get("code")
|
|
@@ -321,3 +331,5 @@ class JobService:
|
|
| 321 |
if self.store.get(identifier)["status"] in TERMINAL:
|
| 322 |
for video in directory.glob("input.*"):
|
| 323 |
video.unlink(missing_ok=True)
|
|
|
|
|
|
|
|
|
| 78 |
db.execute("ALTER TABLE jobs ADD COLUMN coach_payload_sha256 TEXT")
|
| 79 |
if "load_timing_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}:
|
| 80 |
db.execute("ALTER TABLE jobs ADD COLUMN load_timing_sha256 TEXT")
|
| 81 |
+
if 'timing_evidence_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
|
| 82 |
+
db.execute('ALTER TABLE jobs ADD COLUMN timing_evidence_sha256 TEXT')
|
| 83 |
|
| 84 |
@contextmanager
|
| 85 |
def connect(self):
|
|
|
|
| 105 |
value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 106 |
return dict(value) if value else None
|
| 107 |
|
| 108 |
+
def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None):
|
| 109 |
with self.connect() as db:
|
| 110 |
+
db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=? WHERE id=?",
|
| 111 |
+
(status, time.time(), error, result_hash, coach_hash, timing_hash, evidence_hash, identifier))
|
| 112 |
|
| 113 |
def claim(self):
|
| 114 |
with self.connect() as db:
|
|
|
|
| 124 |
row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 125 |
if not row: return None
|
| 126 |
status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
|
| 127 |
+
db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL WHERE id=?",
|
| 128 |
(status, time.time(), identifier))
|
| 129 |
return status
|
| 130 |
|
|
|
|
| 169 |
self.preflight_command = preflight_command or [sys.executable, "-m", "baseball_batting.api_worker",
|
| 170 |
"--preflight", "--models", str(settings.model_root), "--output", str(settings.data_root / "gpu-ready.json")]
|
| 171 |
self.ready = False
|
| 172 |
+
self.tracking_ready = False
|
| 173 |
self.readiness_reason = "gpu_preflight_pending"
|
| 174 |
self.stopping = threading.Event()
|
| 175 |
self.wakeup = threading.Event()
|
|
|
|
| 249 |
|
| 250 |
def loop(self):
|
| 251 |
try:
|
| 252 |
+
readiness_path = self.settings.data_root/'gpu-ready.json'
|
| 253 |
+
readiness_path.unlink(missing_ok=True)
|
| 254 |
preflight = self.launch(self.preflight_command, self.settings.data_root / "gpu-preflight.log")
|
| 255 |
start = time.monotonic()
|
| 256 |
while preflight.poll() is None:
|
|
|
|
| 261 |
if preflight.returncode:
|
| 262 |
self.readiness_reason = "gpu_preflight_failed"
|
| 263 |
return
|
| 264 |
+
if readiness_path.is_file():
|
| 265 |
+
record = read_json(readiness_path)
|
| 266 |
+
self.tracking_ready = record.get('ready') is True and record.get('bat_ball_tracking') is True
|
| 267 |
self.ready = True; self.readiness_reason = "ready"
|
| 268 |
while not self.stopping.is_set():
|
| 269 |
self.cleanup()
|
|
|
|
| 277 |
LOG.exception("GPU job queue stopped")
|
| 278 |
finally:
|
| 279 |
self.ready = False
|
| 280 |
+
self.tracking_ready = False
|
| 281 |
|
| 282 |
def execute(self, identifier):
|
| 283 |
directory = self.job_directory(identifier)
|
|
|
|
| 315 |
timing_path = directory / "load-timing.json"
|
| 316 |
self.store.update(identifier, "completed", result_hash=sha256_file(directory / "result.json"),
|
| 317 |
coach_hash=sha256_file(coach_path) if coach_path.is_file() else None,
|
| 318 |
+
timing_hash=sha256_file(timing_path) if timing_path.is_file() else None,
|
| 319 |
+
evidence_hash=sha256_file(directory/'load-timing-evidence.json') if (directory/'load-timing-evidence.json').is_file() else None)
|
| 320 |
else:
|
| 321 |
error = read_json(directory / "error.json") if (directory / "error.json").exists() else {}
|
| 322 |
code = error.get("code")
|
|
|
|
| 331 |
if self.store.get(identifier)["status"] in TERMINAL:
|
| 332 |
for video in directory.glob("input.*"):
|
| 333 |
video.unlink(missing_ok=True)
|
| 334 |
+
for video in directory.glob('secondary.*'):
|
| 335 |
+
video.unlink(missing_ok=True)
|
baseball_batting/api_worker.py
CHANGED
|
@@ -29,8 +29,14 @@ def gpu_preflight(models):
|
|
| 29 |
detector(np.zeros((640, 640, 3), np.uint8))
|
| 30 |
pose = RTMWPose(paths["body_pose"], "cuda")
|
| 31 |
pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# Both adapters check that actual operators executed on CUDA.
|
| 33 |
-
return {"ready": True, "device": "cuda", "body_3d": False,
|
| 34 |
"scope": "required_2d_models; selected_3d_verified_during_job",
|
| 35 |
"pose_providers": pose.session.get_providers(), "detector_providers": detector.providers}
|
| 36 |
|
|
@@ -85,12 +91,62 @@ def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_durati
|
|
| 85 |
from .measurement_quality import apply_measurement_quality
|
| 86 |
report = reconstruct_events(video, result, options, models, job, device=device, progress=progress)
|
| 87 |
result = apply_measurement_quality(result, options, report)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
from .load_timing import build_load_timing_report
|
| 89 |
from .load_timing_contract import LoadTimingPayload
|
| 90 |
-
timing = build_load_timing_report(result)
|
| 91 |
timing_payload = LoadTimingPayload.model_validate(timing["payload"]).model_dump(mode="json")
|
| 92 |
atomic_json(job / "load-timing.json", timing_payload)
|
| 93 |
atomic_json(job / "load-timing-diagnostics.json", timing)
|
|
|
|
|
|
|
| 94 |
atomic_json(job / "coach-payload.json", result["coach_payload"])
|
| 95 |
atomic_json(job / "result.json", result)
|
| 96 |
progress("complete", n, n)
|
|
|
|
| 29 |
detector(np.zeros((640, 640, 3), np.uint8))
|
| 30 |
pose = RTMWPose(paths["body_pose"], "cuda")
|
| 31 |
pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480])
|
| 32 |
+
tracking_ready = False
|
| 33 |
+
if (Path(models)/'tracking_bat/model.json').is_file() and (Path(models)/'tracking_ball/model.json').is_file():
|
| 34 |
+
from .tracking_vision import TrackingModel
|
| 35 |
+
for name in ('bat', 'ball'):
|
| 36 |
+
TrackingModel(models, name, 'cuda')(np.zeros((640, 640, 3), np.uint8))
|
| 37 |
+
tracking_ready = True
|
| 38 |
# Both adapters check that actual operators executed on CUDA.
|
| 39 |
+
return {"ready": True, "device": "cuda", "body_3d": False, 'bat_ball_tracking': tracking_ready,
|
| 40 |
"scope": "required_2d_models; selected_3d_verified_during_job",
|
| 41 |
"pose_providers": pose.session.get_providers(), "detector_providers": detector.providers}
|
| 42 |
|
|
|
|
| 91 |
from .measurement_quality import apply_measurement_quality
|
| 92 |
report = reconstruct_events(video, result, options, models, job, device=device, progress=progress)
|
| 93 |
result = apply_measurement_quality(result, options, report)
|
| 94 |
+
evidence = {}
|
| 95 |
+
if (Path(models)/'tracking_bat/model.json').is_file() and (Path(models)/'tracking_ball/model.json').is_file():
|
| 96 |
+
from .tracking_vision import track_video
|
| 97 |
+
from .bat_ball_timing import visual_contact
|
| 98 |
+
observed = track_video(video, result, models, device=device, progress=progress)
|
| 99 |
+
atomic_json(job/'bat-ball-observations.json', observed)
|
| 100 |
+
secondary = None
|
| 101 |
+
if options.stereo_tracking:
|
| 102 |
+
secondary_video = next(job.glob('secondary.*'), None)
|
| 103 |
+
if secondary_video is None:
|
| 104 |
+
raise ValueError('Two-view calibration requires a secondary video')
|
| 105 |
+
stereo = options.stereo_tracking
|
| 106 |
+
metadata = {'timing': stereo.secondary_timing.model_dump(exclude_none=True),
|
| 107 |
+
'camera_stability': 'fixed_verified', 'intended_use': 'research'}
|
| 108 |
+
if stereo.secondary_rotation_degrees is not None:
|
| 109 |
+
metadata['rotation_degrees'] = stereo.secondary_rotation_degrees
|
| 110 |
+
second_capture = ingest(secondary_video, metadata, max_frames=max_frames,
|
| 111 |
+
max_pixels=max_pixels, max_duration_s=max_duration_s)
|
| 112 |
+
count = second_capture['frame_count']
|
| 113 |
+
second_result = {'pose_track': {'video': {
|
| 114 |
+
'rotation_degrees_applied': second_capture['rotation_degrees'], 'frame_count': count},
|
| 115 |
+
'frames': {'t_s': [f['physical_s'] for f in second_capture['frames']], 'box': [None]*count},
|
| 116 |
+
'reps': [{'start_frame': 0, 'end_frame': count-1}]}}
|
| 117 |
+
secondary = track_video(secondary_video, second_result, models, device=device, progress=progress)
|
| 118 |
+
atomic_json(job/'secondary-bat-ball-observations.json', secondary)
|
| 119 |
+
for rep in result['pose_track']['reps']:
|
| 120 |
+
visual = (visual_contact(observed, result['pose_track'], rep, practice_type=options.practice_type)
|
| 121 |
+
if options.camera_stability == 'fixed_verified' else
|
| 122 |
+
{'outcome': 'unknown', 'reason_code': 'camera_motion_unresolved'})
|
| 123 |
+
if secondary is not None:
|
| 124 |
+
from .tracking_geometry import reconstruct_rep
|
| 125 |
+
spatial = (reconstruct_rep(observed, secondary, result['pose_track'], rep, options.stereo_tracking)
|
| 126 |
+
if options.camera_stability == 'fixed_verified' else
|
| 127 |
+
{'outcome': 'unknown', 'reason_code': 'camera_motion_unresolved'})
|
| 128 |
+
if options.practice_type == 'tee' and spatial.get('outcome') == 'miss':
|
| 129 |
+
spatial['shift'] = {'value': None, 'reason_code': 'stationary_tee_ball_no_pitch_timing'}
|
| 130 |
+
if spatial.get('outcome') == 'miss' and visual.get('outcome') != 'hit':
|
| 131 |
+
visual = spatial
|
| 132 |
+
elif spatial.get('outcome') == 'miss' and visual.get('outcome') == 'hit':
|
| 133 |
+
visual = {'outcome': 'unknown', 'reason_code': 'visual_spatial_outcome_conflict'}
|
| 134 |
+
else:
|
| 135 |
+
visual['geometry_reason'] = spatial.get('reason_code')
|
| 136 |
+
else:
|
| 137 |
+
visual['geometry_reason'] = 'depth_unresolved'
|
| 138 |
+
evidence[rep['rep']] = visual
|
| 139 |
+
else:
|
| 140 |
+
evidence = {r['rep']: {'outcome': 'unknown', 'reason_code': 'tracking_models_unavailable',
|
| 141 |
+
'geometry_reason': 'depth_unresolved'} for r in result['pose_track']['reps']}
|
| 142 |
from .load_timing import build_load_timing_report
|
| 143 |
from .load_timing_contract import LoadTimingPayload
|
| 144 |
+
timing = build_load_timing_report(result, ball_evidence=evidence)
|
| 145 |
timing_payload = LoadTimingPayload.model_validate(timing["payload"]).model_dump(mode="json")
|
| 146 |
atomic_json(job / "load-timing.json", timing_payload)
|
| 147 |
atomic_json(job / "load-timing-diagnostics.json", timing)
|
| 148 |
+
from .timing_evidence import build_timing_evidence
|
| 149 |
+
atomic_json(job/'load-timing-evidence.json', build_timing_evidence(timing, result, options))
|
| 150 |
atomic_json(job / "coach-payload.json", result["coach_payload"])
|
| 151 |
atomic_json(job / "result.json", result)
|
| 152 |
progress("complete", n, n)
|
baseball_batting/bat_ball_timing.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bat/ball event evidence and physical timing-only correction.
|
| 2 |
+
|
| 3 |
+
Image observations can support a visual hit interval. A projected near miss
|
| 4 |
+
never supplies a physical closest-approach endpoint or timing correction.
|
| 5 |
+
"""
|
| 6 |
+
import itertools
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def shaft_distance(ball, ends, region_start=0.):
|
| 11 |
+
ends = np.asarray(ends, float)
|
| 12 |
+
a, b = ends[..., 0, :], ends[..., 1, :]
|
| 13 |
+
a = a+region_start*(b-a)
|
| 14 |
+
shaft = b-a
|
| 15 |
+
fraction = np.clip(np.sum((ball-a)*shaft, axis=-1)/np.maximum(np.sum(shaft*shaft, axis=-1), 1e-12), 0, 1)
|
| 16 |
+
return np.linalg.norm(ball-a-fraction[..., None]*shaft, axis=-1)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _line_track(rows, times, anchor, scale, *, stationary=False):
|
| 20 |
+
"""Fit directly detected positions; reject ambiguous tracks."""
|
| 21 |
+
if len(rows) < 3 or any(not r['ball'] or len(r['ball']) > 8 for r in rows):
|
| 22 |
+
return None
|
| 23 |
+
possibilities = []
|
| 24 |
+
for first, last in itertools.product(rows[0]['ball'][:8], rows[-1]['ball'][:8]):
|
| 25 |
+
p, q = np.array(first['point']), np.array(last['point'])
|
| 26 |
+
if times[-1] <= times[0]:
|
| 27 |
+
continue
|
| 28 |
+
velocity = (q-p)/(times[-1]-times[0])
|
| 29 |
+
if not stationary and np.linalg.norm(q-p) < max(3, .01*scale):
|
| 30 |
+
continue
|
| 31 |
+
chosen, ambiguous = [], False
|
| 32 |
+
for row, t in zip(rows, times):
|
| 33 |
+
predicted = p+velocity*(t-times[0])
|
| 34 |
+
candidates = sorted(row['ball'], key=lambda c: np.linalg.norm(np.array(c['point'])-predicted))
|
| 35 |
+
radius = max(2., candidates[0]['radius_px'])
|
| 36 |
+
distances = [np.linalg.norm(np.array(c['point'])-predicted) for c in candidates[:2]]
|
| 37 |
+
if distances[0] > 2*radius or (len(distances) > 1 and distances[1]-distances[0] < radius):
|
| 38 |
+
ambiguous = True
|
| 39 |
+
break
|
| 40 |
+
chosen.append(candidates[0])
|
| 41 |
+
if ambiguous:
|
| 42 |
+
continue
|
| 43 |
+
xy = np.array([c['point'] for c in chosen])
|
| 44 |
+
design = np.column_stack((times-anchor, np.ones(len(times))))
|
| 45 |
+
fit = np.linalg.lstsq(design, xy, rcond=None)[0]
|
| 46 |
+
error = np.linalg.norm(design@fit-xy, axis=1).max()
|
| 47 |
+
radius = float(np.median([c['radius_px'] for c in chosen]))
|
| 48 |
+
if error <= max(2., radius):
|
| 49 |
+
possibilities.append((error, fit, radius, xy))
|
| 50 |
+
unique = []
|
| 51 |
+
for candidate in sorted(possibilities, key=lambda p: p[0]):
|
| 52 |
+
if not any(np.allclose(candidate[3], old[3], atol=.5) for old in unique):
|
| 53 |
+
unique.append(candidate)
|
| 54 |
+
return unique[0] if len(unique) == 1 else None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def visual_contact(observations, track, rep, *, practice_type='unknown'):
|
| 58 |
+
frames = observations['frames']
|
| 59 |
+
times = np.array(track['frames']['t_s'], float)
|
| 60 |
+
if not np.isfinite(times[rep['start_frame']:rep['end_frame']+1]).all():
|
| 61 |
+
return {'outcome': 'unknown', 'reason_code': 'capture_time_unknown'}
|
| 62 |
+
onset = rep['events'].get('swing_start', {}).get('frame')
|
| 63 |
+
if onset is None:
|
| 64 |
+
return {'outcome': 'unknown', 'reason_code': 'swing_start_missing'}
|
| 65 |
+
hits = []
|
| 66 |
+
tested_bats, supported_paths = 0, 0
|
| 67 |
+
for i in range(max(onset+1, rep['start_frame']+3), rep['end_frame']-2):
|
| 68 |
+
bats = [b for b in frames[i]['bat'] if b.get('points') is not None]
|
| 69 |
+
if len(bats) != 1:
|
| 70 |
+
continue
|
| 71 |
+
tested_bats += 1
|
| 72 |
+
ends = np.array(bats[0]['points'])
|
| 73 |
+
length = np.linalg.norm(ends[1]-ends[0])
|
| 74 |
+
before_ids, after_ids = list(range(i-3, i)), list(range(i+1, i+4))
|
| 75 |
+
if np.max(np.diff(times[i-3:i+4])) > 1.01/30:
|
| 76 |
+
continue
|
| 77 |
+
before = _line_track([frames[k] for k in before_ids], times[before_ids], times[i], length,
|
| 78 |
+
stationary=practice_type == 'tee')
|
| 79 |
+
after = _line_track([frames[k] for k in after_ids], times[after_ids], times[i], length)
|
| 80 |
+
if before is None or after is None:
|
| 81 |
+
continue
|
| 82 |
+
supported_paths += 1
|
| 83 |
+
ein, incoming, rin, _ = before
|
| 84 |
+
eout, outgoing, rout, _ = after
|
| 85 |
+
v, u = incoming[0], outgoing[0]
|
| 86 |
+
# Tee contact needs the same stationary ball before impact and an
|
| 87 |
+
# independently observed outgoing path. Disappearance is insufficient.
|
| 88 |
+
change = np.linalg.norm(u-v)*(times[i+3]-times[i-3])
|
| 89 |
+
cosine = np.dot(v, u)/max(np.linalg.norm(v)*np.linalg.norm(u), 1e-9)
|
| 90 |
+
is_tee = practice_type == 'tee' and np.linalg.norm(v)*(times[i]-times[i-3]) <= max(2, rin)
|
| 91 |
+
if (not is_tee and cosine > .8) or change < 4*max(rin, rout, ein, eout, 1):
|
| 92 |
+
continue
|
| 93 |
+
# The two fitted branches must meet near the observed bat during the
|
| 94 |
+
# same bounded transition. A disappearance never creates a branch.
|
| 95 |
+
delta = u-v
|
| 96 |
+
offset = outgoing[1]-incoming[1]
|
| 97 |
+
relative_time = -np.dot(offset, delta)/max(np.dot(delta, delta), 1e-9)
|
| 98 |
+
t = times[i]+relative_time
|
| 99 |
+
if not times[i-1] <= t <= times[i+1]:
|
| 100 |
+
continue
|
| 101 |
+
p, q = incoming[1]+v*relative_time, outgoing[1]+u*relative_time
|
| 102 |
+
if np.linalg.norm(p-q) > max(rin, rout)+ein+eout:
|
| 103 |
+
continue
|
| 104 |
+
distance = float(shaft_distance((p+q)/2, ends))
|
| 105 |
+
if distance > max(rin, rout)+ein+eout+max(2, .025*length):
|
| 106 |
+
continue
|
| 107 |
+
# Endpoints must be independently observed on both sides, with no
|
| 108 |
+
# replaced bat identity. Points supplied by body pose are never used.
|
| 109 |
+
adjacent = [[b for b in frames[j]['bat'] if b.get('points') is not None] for j in (i-1, i+1)]
|
| 110 |
+
if any(len(b) != 1 for b in adjacent):
|
| 111 |
+
continue
|
| 112 |
+
# A ball bouncing elsewhere in the image must not become contact merely
|
| 113 |
+
# because its projected position happens to overlap a bat. Require an
|
| 114 |
+
# observed bat sweep and compatible ball deflection. This remains a
|
| 115 |
+
# single-view visual estimate, not an independent depth measurement.
|
| 116 |
+
previous, following = (np.array(b[0]['points']) for b in adjacent)
|
| 117 |
+
motion = following.mean(axis=0)-previous.mean(axis=0)
|
| 118 |
+
if np.linalg.norm(motion) <= max(2., .02*length) or np.dot(u-v, motion) <= 0:
|
| 119 |
+
continue
|
| 120 |
+
hit = {'outcome': 'hit', 'end_event': 'contact', 'frame_interval': [i-1, i+1],
|
| 121 |
+
'time_s': float(t), 'time_interval_s': [float(times[i-1]), float(times[i+1])],
|
| 122 |
+
'method': ('observed_tee_ball_departure_and_bat_v1' if is_tee else
|
| 123 |
+
'observed_bat_and_piecewise_ball_trajectory_v1'),
|
| 124 |
+
'reason_code': None, 'evidence_frames': before_ids+[i]+after_ids,
|
| 125 |
+
'fit_residual_px': [float(ein), float(eout)],
|
| 126 |
+
'validation': 'visual_estimate_accuracy_pending'}
|
| 127 |
+
hits.append(hit)
|
| 128 |
+
if not hits:
|
| 129 |
+
reason = ('bat_endpoints_unobserved_or_ambiguous' if not tested_bats else
|
| 130 |
+
'ball_trajectory_unobserved_or_ambiguous' if not supported_paths else
|
| 131 |
+
'contact_evidence_insufficient')
|
| 132 |
+
return {'outcome': 'unknown', 'reason_code': reason,
|
| 133 |
+
'frames_with_unique_bat': tested_bats, 'frames_with_supported_ball_branches': supported_paths}
|
| 134 |
+
groups = []
|
| 135 |
+
for hit in hits:
|
| 136 |
+
if groups and hit['frame_interval'][0] <= groups[-1][-1]['frame_interval'][1]:
|
| 137 |
+
groups[-1].append(hit)
|
| 138 |
+
else:
|
| 139 |
+
groups.append([hit])
|
| 140 |
+
if len(groups) != 1:
|
| 141 |
+
return {'outcome': 'unknown', 'reason_code': 'multiple_contact_candidates'}
|
| 142 |
+
group = groups[0]
|
| 143 |
+
best = min(group, key=lambda h: sum(h['fit_residual_px']))
|
| 144 |
+
best['time_interval_s'] = [min(h['time_interval_s'][0] for h in group),
|
| 145 |
+
max(h['time_interval_s'][1] for h in group)]
|
| 146 |
+
best['frame_interval'] = [min(h['frame_interval'][0] for h in group),
|
| 147 |
+
max(h['frame_interval'][1] for h in group)]
|
| 148 |
+
return best
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def physical_shift(times, bat, ball, *, bat_radius_m, ball_radius_m,
|
| 152 |
+
position_bound_m, region_start=.5, max_shift_s=.25,
|
| 153 |
+
resolution_s=.001, max_cells=30_000_000):
|
| 154 |
+
"""Search supported 3D paths; return disconnected conservative shift bands.
|
| 155 |
+
|
| 156 |
+
Operates on complete, piecewise linear supplied paths, without extrapolation.
|
| 157 |
+
A Lipschitz allowance covers grid spacing. Unresolved boundaries/coverage
|
| 158 |
+
never turn into an assertion that the path is unreachable.
|
| 159 |
+
"""
|
| 160 |
+
t, bat, ball = np.asarray(times, float), np.asarray(bat, float), np.asarray(ball, float)
|
| 161 |
+
if (len(t) < 4 or bat.shape != (len(t), 2, 3) or ball.shape != (len(t), 3)
|
| 162 |
+
or not np.isfinite(t).all() or not np.isfinite(bat).all() or not np.isfinite(ball).all()
|
| 163 |
+
or (np.diff(t) <= 0).any() or np.diff(t).max() > 1.01/30):
|
| 164 |
+
return {'value': None, 'reason_code': 'spatial_track_incomplete'}
|
| 165 |
+
if min(bat_radius_m, ball_radius_m, resolution_s, max_shift_s) <= 0 or position_bound_m < 0:
|
| 166 |
+
raise ValueError('Physical dimensions and resolution must be positive; error bound nonnegative')
|
| 167 |
+
radius = bat_radius_m+ball_radius_m
|
| 168 |
+
dt = np.diff(t)
|
| 169 |
+
vb = np.linalg.norm(np.diff(bat, axis=0), axis=2)/dt[:, None]
|
| 170 |
+
vp = np.linalg.norm(np.diff(ball, axis=0), axis=1)/dt
|
| 171 |
+
speed = float(vb.max()+vp.max())
|
| 172 |
+
spacing = min(resolution_s, radius/max(4*speed, 1e-9))
|
| 173 |
+
shifts = np.linspace(-max_shift_s, max_shift_s, int(np.ceil(2*max_shift_s/spacing))+1)
|
| 174 |
+
fine = np.linspace(t[0], t[-1], int(np.ceil((t[-1]-t[0])/spacing))+1)
|
| 175 |
+
if len(shifts)*len(fine) > max_cells:
|
| 176 |
+
return {'value': None, 'reason_code': 'search_resolution_insufficient'}
|
| 177 |
+
observed_ball = np.column_stack([np.interp(fine, t, ball[:, j]) for j in range(3)])
|
| 178 |
+
minima, endpoints = [], []
|
| 179 |
+
for shift in shifts:
|
| 180 |
+
query = fine-shift
|
| 181 |
+
valid = (query >= t[0]) & (query <= t[-1])
|
| 182 |
+
if not valid.any():
|
| 183 |
+
minima.append(np.inf); endpoints.append(None)
|
| 184 |
+
continue
|
| 185 |
+
ends = np.stack([np.column_stack([np.interp(query[valid], t, bat[:, k, j]) for j in range(3)]) for k in range(2)], axis=1)
|
| 186 |
+
distance = shaft_distance(observed_ball[valid], ends, region_start)
|
| 187 |
+
k = int(distance.argmin())
|
| 188 |
+
minima.append(float(distance[k])); endpoints.append(float(fine[valid][k]))
|
| 189 |
+
minima = np.array(minima)
|
| 190 |
+
# Nearest samples are at most half a time step and half a shift step
|
| 191 |
+
# away; speed*spacing conservatively covers both contributions.
|
| 192 |
+
grid_allowance = speed*spacing
|
| 193 |
+
possible = minima-grid_allowance-2*position_bound_m <= radius
|
| 194 |
+
certain = minima+grid_allowance+2*position_bound_m < radius
|
| 195 |
+
bands = []
|
| 196 |
+
edges = np.diff(np.r_[False, possible, False].astype(int))
|
| 197 |
+
for a, b in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)):
|
| 198 |
+
bands.append([float(shifts[max(0, a-1)]*1000), float(shifts[min(len(shifts)-1, b)]*1000)])
|
| 199 |
+
diagnostic = {'feasible_shift_intervals_ms': bands, 'search_range_ms': [-max_shift_s*1000, max_shift_s*1000],
|
| 200 |
+
'resolution_ms': float(spacing*1000), 'position_bound_m': position_bound_m,
|
| 201 |
+
'bound_kind': 'supplied_position_bound_and_grid_sensitivity',
|
| 202 |
+
'selection_policy': 'closest_to_zero_certified_feasible_shift'}
|
| 203 |
+
if not bands:
|
| 204 |
+
return {'value': None, 'reason_code': 'no_feasible_shift_in_observed_window', **diagnostic}
|
| 205 |
+
if len(bands) != 1 or bands[0][0] <= 0 <= bands[0][1]:
|
| 206 |
+
return {'value': None, 'reason_code': 'ambiguous_time_shift', **diagnostic}
|
| 207 |
+
if possible[0] or possible[-1]:
|
| 208 |
+
return {'value': None, 'reason_code': 'shift_search_boundary', **diagnostic}
|
| 209 |
+
candidates = np.flatnonzero(certain)
|
| 210 |
+
if not len(candidates):
|
| 211 |
+
return {'value': None, 'reason_code': 'shift_unresolved_under_position_error', **diagnostic}
|
| 212 |
+
k = min(candidates, key=lambda i: abs(shifts[i]))
|
| 213 |
+
# An intersection at a time-coverage boundary cannot support the result.
|
| 214 |
+
endpoint = endpoints[k]
|
| 215 |
+
if min(endpoint-t[0], t[-1]-endpoint, endpoint-shifts[k]-t[0], t[-1]-(endpoint-shifts[k])) <= spacing:
|
| 216 |
+
return {'value': None, 'reason_code': 'spatial_coverage_insufficient', **diagnostic}
|
| 217 |
+
return {'value': round(float(shifts[k]*1000), 3), 'reason_code': None, **diagnostic}
|
baseball_batting/load_timing.py
CHANGED
|
@@ -64,8 +64,8 @@ def _timing_interval(track, rep, a, b, *, signed=False):
|
|
| 64 |
return round(value, 3), "Duration from capture timestamps; event detection remains unvalidated.", diagnostic
|
| 65 |
|
| 66 |
|
| 67 |
-
def build_load_timing_report(result, reviewed=None):
|
| 68 |
-
"""Extract timing estimates
|
| 69 |
|
| 70 |
reviewed maps rep numbers to visible event frames and their source. It is
|
| 71 |
empty by default. Manual labels never manufacture a clock or an early/late
|
|
@@ -103,7 +103,8 @@ def build_load_timing_report(result, reviewed=None):
|
|
| 103 |
if (type(frame) is not int or not rep["start_frame"] <= frame <= rep["end_frame"]):
|
| 104 |
raise ValueError(f"{key} must be an integer frame inside swing {rep['rep']}.")
|
| 105 |
events[name] = _frame_event(frame, "reviewed_video_frame", label["source"].strip())
|
| 106 |
-
|
|
|
|
| 107 |
if not isinstance(outcome, str) or outcome not in {"hit", "miss", "unknown"}:
|
| 108 |
raise ValueError("Outcome must be hit, miss or unknown.")
|
| 109 |
if "contact_frame" in label and (outcome != "hit" or "closest_approach_frame" in label):
|
|
@@ -157,10 +158,41 @@ def build_load_timing_report(result, reviewed=None):
|
|
| 157 |
else:
|
| 158 |
by_key["swing_duration_ms"] = _timing_metric("swing_duration_ms",
|
| 159 |
"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.", end_event=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
by_key["early_late_shift_ms"] = _timing_metric("early_late_shift_ms",
|
| 161 |
"Only applies to misses." if outcome == "hit" else
|
| 162 |
"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.",
|
| 163 |
"not_applicable" if outcome == "hit" else "unclear")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
payload["reps"].append({"rep": rep["rep"], "outcome": outcome, "stepped": stepped,
|
| 165 |
"metrics": [by_key[key] for key in LOAD_TIMING_KEYS]})
|
| 166 |
moments = {}
|
|
@@ -181,10 +213,13 @@ def build_load_timing_report(result, reviewed=None):
|
|
| 181 |
"forward_swing_established": forward, "events": moments,
|
| 182 |
"missing_events": deepcopy(rep.get("missing_events", {})), "timing_checks": intervals,
|
| 183 |
"review_source": label.get("source"), "reviewed_fields": sorted(label)})
|
|
|
|
| 184 |
return {"version": LOAD_TIMING_VERSION, "validation": "reference_validation_pending",
|
| 185 |
"contract_status": "proposed_v3_not_current_coach_api_contract", "payload": payload,
|
| 186 |
-
"capabilities": {"automatic_body_events": True,
|
| 187 |
-
"
|
|
|
|
|
|
|
| 188 |
"diagnostics": diagnostics,
|
| 189 |
"notes": ["All numbers are estimates; a successful run does not establish accuracy.",
|
| 190 |
"Sensitivity ranges are frame-shift checks, not validated error bounds.",
|
|
|
|
| 64 |
return round(value, 3), "Duration from capture timestamps; event detection remains unvalidated.", diagnostic
|
| 65 |
|
| 66 |
|
| 67 |
+
def build_load_timing_report(result, reviewed=None, ball_evidence=None):
|
| 68 |
+
"""Extract timing estimates from body events and separate bat/ball evidence.
|
| 69 |
|
| 70 |
reviewed maps rep numbers to visible event frames and their source. It is
|
| 71 |
empty by default. Manual labels never manufacture a clock or an early/late
|
|
|
|
| 103 |
if (type(frame) is not int or not rep["start_frame"] <= frame <= rep["end_frame"]):
|
| 104 |
raise ValueError(f"{key} must be an integer frame inside swing {rep['rep']}.")
|
| 105 |
events[name] = _frame_event(frame, "reviewed_video_frame", label["source"].strip())
|
| 106 |
+
evidence = (ball_evidence or {}).get(rep['rep'], {})
|
| 107 |
+
outcome = label.get("outcome", evidence.get('outcome', 'unknown'))
|
| 108 |
if not isinstance(outcome, str) or outcome not in {"hit", "miss", "unknown"}:
|
| 109 |
raise ValueError("Outcome must be hit, miss or unknown.")
|
| 110 |
if "contact_frame" in label and (outcome != "hit" or "closest_approach_frame" in label):
|
|
|
|
| 158 |
else:
|
| 159 |
by_key["swing_duration_ms"] = _timing_metric("swing_duration_ms",
|
| 160 |
"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.", end_event=None)
|
| 161 |
+
if not actual_end and evidence.get('end_event') in {'contact', 'closest_approach'}:
|
| 162 |
+
frame = events.get('swing_start', {}).get('frame')
|
| 163 |
+
times = track['frames']['t_s']
|
| 164 |
+
value, reason = None, block
|
| 165 |
+
bounds = evidence.get('time_interval_s')
|
| 166 |
+
interval_evidence = {'end_method': evidence['method'], 'end_interval_s': bounds,
|
| 167 |
+
'sensitivity_scope': 'endpoint interval plus ±1-frame start sensitivity; onset error unvalidated'}
|
| 168 |
+
if not block and frame is not None and times[frame] is not None and bounds:
|
| 169 |
+
a, b = max(rep['start_frame'], frame-1), min(rep['end_frame'], frame+1)
|
| 170 |
+
if times[a] is not None and times[b] is not None:
|
| 171 |
+
value = (evidence['time_s']-times[frame])*1000
|
| 172 |
+
low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000
|
| 173 |
+
interval_evidence['frame_sensitivity_range_ms'] = [round(low, 3), round(high, 3)]
|
| 174 |
+
if value <= 0 or low <= 0 or (high-low)/value > .5:
|
| 175 |
+
value, reason = None, 'Endpoint/start interval does not resolve swing duration.'
|
| 176 |
+
note = reason or ('Forward hand onset to '+evidence['end_event']+' from bat/ball observations. Event accuracy remains unvalidated.')
|
| 177 |
+
by_key['swing_duration_ms'] = _timing_metric('swing_duration_ms', note,
|
| 178 |
+
status='estimated' if value is not None else 'unclear', end_event=evidence['end_event'] if value is not None else None)
|
| 179 |
+
if value is not None:
|
| 180 |
+
by_key['swing_duration_ms']['value'] = round(value, 3)
|
| 181 |
+
intervals['swing_duration_ms'] = interval_evidence
|
| 182 |
by_key["early_late_shift_ms"] = _timing_metric("early_late_shift_ms",
|
| 183 |
"Only applies to misses." if outcome == "hit" else
|
| 184 |
"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.",
|
| 185 |
"not_applicable" if outcome == "hit" else "unclear")
|
| 186 |
+
if outcome == 'miss':
|
| 187 |
+
shift = evidence.get('shift', {})
|
| 188 |
+
value = shift.get('value') if not block else None
|
| 189 |
+
reason = block or shift.get('reason_code') or evidence.get('reason_code') or 'depth_unresolved'
|
| 190 |
+
by_key['early_late_shift_ms'] = _timing_metric('early_late_shift_ms',
|
| 191 |
+
'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.' if value is not None else reason,
|
| 192 |
+
'estimated' if value is not None else 'unclear')
|
| 193 |
+
if value is not None:
|
| 194 |
+
by_key['early_late_shift_ms']['value'] = value
|
| 195 |
+
intervals['early_late_shift_ms'] = deepcopy(shift)
|
| 196 |
payload["reps"].append({"rep": rep["rep"], "outcome": outcome, "stepped": stepped,
|
| 197 |
"metrics": [by_key[key] for key in LOAD_TIMING_KEYS]})
|
| 198 |
moments = {}
|
|
|
|
| 213 |
"forward_swing_established": forward, "events": moments,
|
| 214 |
"missing_events": deepcopy(rep.get("missing_events", {})), "timing_checks": intervals,
|
| 215 |
"review_source": label.get("source"), "reviewed_fields": sorted(label)})
|
| 216 |
+
diagnostics[-1]['bat_ball_evidence'] = deepcopy(evidence)
|
| 217 |
return {"version": LOAD_TIMING_VERSION, "validation": "reference_validation_pending",
|
| 218 |
"contract_status": "proposed_v3_not_current_coach_api_contract", "payload": payload,
|
| 219 |
+
"capabilities": {"automatic_body_events": True,
|
| 220 |
+
"automatic_ball_contact": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),
|
| 221 |
+
"automatic_bat_ball_tracking": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),
|
| 222 |
+
"early_late_estimate": any('shift' in e for e in (ball_evidence or {}).values())},
|
| 223 |
"diagnostics": diagnostics,
|
| 224 |
"notes": ["All numbers are estimates; a successful run does not establish accuracy.",
|
| 225 |
"Sensitivity ranges are frame-shift checks, not validated error bounds.",
|
baseball_batting/timing_evidence.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Opt-in 3.1 timing response; unchanged 3.0 remains available to old clients."""
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 4 |
+
from .load_timing_contract import LoadTimingPayload, TimingCapture
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class EventEvidence(BaseModel):
|
| 8 |
+
model_config = ConfigDict(extra='forbid', strict=True, allow_inf_nan=False)
|
| 9 |
+
event: str
|
| 10 |
+
method: str
|
| 11 |
+
frame_interval: list[int] | None
|
| 12 |
+
capture_interval_s: list[float] | None
|
| 13 |
+
uncertainty_kind: Literal['frame_sensitivity', 'visual_contact_interval', 'supplied_geometry_bound']
|
| 14 |
+
accuracy_validated: Literal[False] = False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TimingUncertainty(BaseModel):
|
| 18 |
+
model_config = ConfigDict(extra='forbid', strict=True, allow_inf_nan=False)
|
| 19 |
+
interval_ms: list[float] | None
|
| 20 |
+
kind: Literal['frame_sensitivity', 'supplied_geometry_bound', 'unknown']
|
| 21 |
+
accuracy_validated: Literal[False] = False
|
| 22 |
+
note: str
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class EvidenceMetric(BaseModel):
|
| 26 |
+
model_config = ConfigDict(extra='forbid', strict=True, allow_inf_nan=False)
|
| 27 |
+
key: Literal['load_to_swing_ms', 'foot_down_to_swing_ms', 'swing_duration_ms', 'early_late_shift_ms']
|
| 28 |
+
value: float | None
|
| 29 |
+
unit: Literal['ms']
|
| 30 |
+
status: Literal['estimated', 'unclear', 'not_applicable']
|
| 31 |
+
confidence: Literal['est']
|
| 32 |
+
note: str
|
| 33 |
+
end_event: Literal['contact', 'closest_approach'] | None = None
|
| 34 |
+
reason_code: str | None
|
| 35 |
+
uncertainty: TimingUncertainty
|
| 36 |
+
feasible_shift_intervals_ms: list[list[float]] | None = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class EvidenceRep(BaseModel):
|
| 40 |
+
model_config = ConfigDict(extra='forbid', strict=True)
|
| 41 |
+
rep: int = Field(ge=1)
|
| 42 |
+
outcome: Literal['hit', 'miss', 'unknown']
|
| 43 |
+
stepped: bool | None
|
| 44 |
+
metrics: list[EvidenceMetric] = Field(min_length=4, max_length=4)
|
| 45 |
+
events: list[EventEvidence]
|
| 46 |
+
outcome_method: str
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PracticeContext(BaseModel):
|
| 50 |
+
model_config = ConfigDict(extra='forbid', strict=True, allow_inf_nan=False)
|
| 51 |
+
practice_type: Literal['tee', 'soft_toss', 'front_toss', 'live', 'machine', 'unknown']
|
| 52 |
+
pitch_speed_mps: float | None
|
| 53 |
+
pitch_location: str | None
|
| 54 |
+
source: str | None
|
| 55 |
+
provenance: Literal['supplied_by_uploader']
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class TimingEvidencePayload(BaseModel):
|
| 59 |
+
model_config = ConfigDict(extra='forbid', strict=True)
|
| 60 |
+
schema_version: Literal['3.1']
|
| 61 |
+
discipline: Literal['hitting']
|
| 62 |
+
time_basis: Literal['capture']
|
| 63 |
+
capture: TimingCapture
|
| 64 |
+
context: PracticeContext
|
| 65 |
+
reps: list[EvidenceRep] = Field(max_length=100)
|
| 66 |
+
|
| 67 |
+
@model_validator(mode='after')
|
| 68 |
+
def coherent(self):
|
| 69 |
+
LoadTimingPayload.model_validate(self.legacy())
|
| 70 |
+
for rep in self.reps:
|
| 71 |
+
for metric in rep.metrics:
|
| 72 |
+
if metric.value is None and not metric.reason_code:
|
| 73 |
+
raise ValueError('Unavailable or inapplicable measurements need a reason code')
|
| 74 |
+
for bounds in ([metric.uncertainty.interval_ms] if metric.uncertainty.interval_ms is not None else []) + (metric.feasible_shift_intervals_ms or []):
|
| 75 |
+
if len(bounds) != 2 or bounds[0] > bounds[1]:
|
| 76 |
+
raise ValueError('Timing bounds must be ordered pairs')
|
| 77 |
+
bounds = metric.uncertainty.interval_ms
|
| 78 |
+
if metric.value is not None and bounds is not None and not bounds[0] <= metric.value <= bounds[1]:
|
| 79 |
+
raise ValueError('Timing estimate must lie inside its supplied interval')
|
| 80 |
+
bands = metric.feasible_shift_intervals_ms
|
| 81 |
+
if bands and metric.value is not None and not any(a <= metric.value <= b for a, b in bands):
|
| 82 |
+
raise ValueError('Timing correction must belong to a feasible interval')
|
| 83 |
+
for event in rep.events:
|
| 84 |
+
for bounds in (event.frame_interval, event.capture_interval_s):
|
| 85 |
+
if bounds is not None and (len(bounds) != 2 or bounds[0] > bounds[1]):
|
| 86 |
+
raise ValueError('Event bounds must be ordered pairs')
|
| 87 |
+
return self
|
| 88 |
+
|
| 89 |
+
def legacy(self):
|
| 90 |
+
return {'schema_version': '3.0', 'discipline': self.discipline, 'time_basis': self.time_basis,
|
| 91 |
+
'capture': self.capture.model_dump(), 'reps': [
|
| 92 |
+
{'rep': r.rep, 'outcome': r.outcome, 'stepped': r.stepped, 'metrics': [
|
| 93 |
+
{**{k: getattr(m, k) for k in ('key', 'value', 'unit', 'status', 'confidence', 'note')},
|
| 94 |
+
**({'end_event': m.end_event} if m.key == 'swing_duration_ms' else {})}
|
| 95 |
+
for m in r.metrics]} for r in self.reps]}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def build_timing_evidence(report, result, options):
|
| 99 |
+
payload = report['payload']
|
| 100 |
+
rich = {**payload, 'schema_version': '3.1', 'context': {
|
| 101 |
+
'practice_type': options.practice_type, 'pitch_speed_mps': options.pitch_speed_mps,
|
| 102 |
+
'pitch_location': options.pitch_location, 'source': options.pitch_context_source,
|
| 103 |
+
'provenance': 'supplied_by_uploader'}, 'reps': []}
|
| 104 |
+
times = result['pose_track']['frames']['t_s']
|
| 105 |
+
for rep, diagnostic in zip(payload['reps'], report['diagnostics']):
|
| 106 |
+
source = diagnostic.get('bat_ball_evidence', {})
|
| 107 |
+
events = []
|
| 108 |
+
for name, event in diagnostic['events'].items():
|
| 109 |
+
if name == 'body_extension_proxy':
|
| 110 |
+
continue
|
| 111 |
+
frame = event['frame']
|
| 112 |
+
a, b = max(diagnostic['start_frame'], frame-1), min(diagnostic['end_frame'], frame+1)
|
| 113 |
+
events.append({'event': name, 'method': event['method'], 'frame_interval': [a, b],
|
| 114 |
+
'capture_interval_s': [times[a], times[b]] if times[a] is not None and times[b] is not None else None,
|
| 115 |
+
'uncertainty_kind': 'frame_sensitivity'})
|
| 116 |
+
if source.get('end_event'):
|
| 117 |
+
events.append({'event': source['end_event'], 'method': source['method'],
|
| 118 |
+
'frame_interval': source.get('frame_interval'), 'capture_interval_s': source.get('time_interval_s'),
|
| 119 |
+
'uncertainty_kind': 'visual_contact_interval' if source['end_event'] == 'contact' else 'supplied_geometry_bound'})
|
| 120 |
+
metrics = []
|
| 121 |
+
for metric in rep['metrics']:
|
| 122 |
+
key = metric['key']
|
| 123 |
+
check = diagnostic['timing_checks'].get(key, {})
|
| 124 |
+
reason = None
|
| 125 |
+
if metric['value'] is None:
|
| 126 |
+
if metric['status'] == 'not_applicable':
|
| 127 |
+
reason = 'no_step' if key == 'foot_down_to_swing_ms' else 'hit_no_correction_needed'
|
| 128 |
+
elif not payload['capture']['ok']:
|
| 129 |
+
reason = 'capture_failed'
|
| 130 |
+
elif key == 'early_late_shift_ms':
|
| 131 |
+
reason = source.get('shift', {}).get('reason_code') or source.get('geometry_reason') or 'depth_unresolved'
|
| 132 |
+
elif key == 'swing_duration_ms':
|
| 133 |
+
reason = source.get('reason_code') or 'duration_interval_unresolved'
|
| 134 |
+
elif not diagnostic['forward_swing_established']:
|
| 135 |
+
reason = 'forward_swing_unresolved'
|
| 136 |
+
elif key == 'foot_down_to_swing_ms' and rep['stepped'] is None:
|
| 137 |
+
reason = 'step_unresolved'
|
| 138 |
+
elif check.get('start_frame') is None:
|
| 139 |
+
reason = 'load_start_missing' if key == 'load_to_swing_ms' else 'foot_contact_missing'
|
| 140 |
+
elif not check.get('capture_interval_ms'):
|
| 141 |
+
reason = 'capture_time_unknown'
|
| 142 |
+
else:
|
| 143 |
+
reason = 'timing_interval_unresolved'
|
| 144 |
+
bands = check.get('feasible_shift_intervals_ms')
|
| 145 |
+
interval = check.get('frame_sensitivity_range_ms')
|
| 146 |
+
kind = 'frame_sensitivity' if interval is not None else 'unknown'
|
| 147 |
+
if key == 'early_late_shift_ms' and bands:
|
| 148 |
+
kind = 'supplied_geometry_bound'
|
| 149 |
+
interval = bands[0] if len(bands) == 1 else None
|
| 150 |
+
metrics.append({**metric, 'reason_code': reason, 'uncertainty': {
|
| 151 |
+
'interval_ms': interval, 'kind': kind, 'note': 'Sensitivity to recorded frames or supplied geometry bounds; not a validated accuracy interval.'},
|
| 152 |
+
'feasible_shift_intervals_ms': bands})
|
| 153 |
+
rich['reps'].append({**rep, 'metrics': metrics, 'events': events,
|
| 154 |
+
'outcome_method': source.get('method', 'outcome_unresolved')})
|
| 155 |
+
return TimingEvidencePayload.model_validate(rich).model_dump(mode='json', exclude_none=False)
|
baseball_batting/tracking_geometry.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calibrated two-view paths in metres, with explicit visibility and coverage."""
|
| 2 |
+
import itertools
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from .geometry import triangulate
|
| 6 |
+
from .bat_ball_timing import physical_shift, shaft_distance
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _sample(rows, times, t, field):
|
| 10 |
+
j = int(np.searchsorted(times, t))
|
| 11 |
+
if j < len(times) and abs(times[j]-t) < 1e-7:
|
| 12 |
+
return rows[j][field]
|
| 13 |
+
# No extrapolation and no interpolation across detection/clock gaps.
|
| 14 |
+
if not 0 < j < len(times) or times[j]-times[j-1] > 1.01/30:
|
| 15 |
+
return []
|
| 16 |
+
a, b = rows[j-1][field], rows[j][field]
|
| 17 |
+
if len(a) != 1 or len(b) != 1:
|
| 18 |
+
return []
|
| 19 |
+
key = 'points' if field == 'bat' else 'point'
|
| 20 |
+
if a[0].get(key) is None or b[0].get(key) is None:
|
| 21 |
+
return []
|
| 22 |
+
fraction = (t-times[j-1])/(times[j]-times[j-1])
|
| 23 |
+
return [{key: ((1-fraction)*np.array(a[0][key])+fraction*np.array(b[0][key])).tolist(),
|
| 24 |
+
'state': 'interpolated_between_observed_frames'}]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def reconstruct_rep(primary, secondary, track, rep, config):
|
| 28 |
+
rows = primary['frames']; other = secondary['frames']
|
| 29 |
+
times = np.array([r['capture_time_s'] for r in rows], float)
|
| 30 |
+
other_times = np.array([r['capture_time_s'] for r in other], float)+config.secondary_offset_s
|
| 31 |
+
if (not np.isfinite(times).all() or not np.isfinite(other_times).all()
|
| 32 |
+
or (np.diff(times) <= 0).any() or (np.diff(other_times) <= 0).any()):
|
| 33 |
+
return {'outcome': 'unknown', 'reason_code': 'synchronization_unresolved'}
|
| 34 |
+
cameras = [np.asarray(c.intrinsics)@np.column_stack((c.rotation, c.translation_m)) for c in config.cameras]
|
| 35 |
+
def recover(pixels):
|
| 36 |
+
corrected = [cv2.undistortPoints(np.array(p).reshape(1, 1, 2), np.array(c.intrinsics),
|
| 37 |
+
np.array(c.distortion), P=np.array(c.intrinsics)).reshape(2)
|
| 38 |
+
for p, c in zip(pixels, config.cameras)]
|
| 39 |
+
return triangulate(corrected, cameras)
|
| 40 |
+
onset = rep['events'].get('swing_start', {}).get('frame')
|
| 41 |
+
finish = rep['events'].get('finish', {}).get('frame')
|
| 42 |
+
if onset is None or finish is None or finish <= onset:
|
| 43 |
+
return {'outcome': 'unknown', 'reason_code': 'primary_swing_coverage_unresolved'}
|
| 44 |
+
bat_points, ball_points, errors, ids = [], [], [], []
|
| 45 |
+
order_votes = []
|
| 46 |
+
for i in range(onset, finish+1):
|
| 47 |
+
bats = [b for b in rows[i]['bat'] if b.get('points') is not None]
|
| 48 |
+
bats2 = [b for b in _sample(other, other_times, times[i], 'bat') if b.get('points') is not None]
|
| 49 |
+
balls, balls2 = rows[i]['ball'], _sample(other, other_times, times[i], 'ball')
|
| 50 |
+
if len(bats) != 1 or len(bats2) != 1 or not balls or not balls2:
|
| 51 |
+
return {'outcome': 'unknown', 'reason_code': 'spatial_track_incomplete', 'missing_frame': i}
|
| 52 |
+
p = np.array(bats[0]['points']); q = np.array(bats2[0]['points'])
|
| 53 |
+
pairings = []
|
| 54 |
+
for permutation in (q, q[::-1]):
|
| 55 |
+
try:
|
| 56 |
+
points, residual = zip(*(recover([a, b]) for a, b in zip(p, permutation)))
|
| 57 |
+
except ValueError:
|
| 58 |
+
continue
|
| 59 |
+
length = np.linalg.norm(points[1]-points[0])
|
| 60 |
+
if abs(length-config.bat_length_m) <= max(.02, 2*config.position_bound_m):
|
| 61 |
+
pairings.append((np.array(points), max(residual)))
|
| 62 |
+
if len(pairings) != 1:
|
| 63 |
+
return {'outcome': 'unknown', 'reason_code': 'bat_geometry_ambiguous', 'frame': i}
|
| 64 |
+
ball_candidates = []
|
| 65 |
+
for a, b in itertools.product(balls, balls2):
|
| 66 |
+
try:
|
| 67 |
+
point, residual = recover([a['point'], b['point']])
|
| 68 |
+
ball_candidates.append((point, residual))
|
| 69 |
+
except ValueError:
|
| 70 |
+
continue
|
| 71 |
+
if len(ball_candidates) != 1:
|
| 72 |
+
return {'outcome': 'unknown', 'reason_code': 'ball_identity_ambiguous', 'frame': i}
|
| 73 |
+
hands = track['frames']['kp'][i][9:11]
|
| 74 |
+
if all(h is not None for h in hands):
|
| 75 |
+
hand = np.mean(hands, axis=0)
|
| 76 |
+
distances = np.linalg.norm(p-hand, axis=1)
|
| 77 |
+
length_px = np.linalg.norm(p[1]-p[0])
|
| 78 |
+
if distances.min() < .25*length_px and abs(distances[0]-distances[1]) > .2*length_px:
|
| 79 |
+
order_votes.append(int(distances.argmin()))
|
| 80 |
+
bat_points.append(pairings[0][0]); ball_points.append(ball_candidates[0][0])
|
| 81 |
+
errors.append(max(pairings[0][1], ball_candidates[0][1])); ids.append(i)
|
| 82 |
+
if not order_votes or len(set(order_votes)) != 1:
|
| 83 |
+
return {'outcome': 'unknown', 'reason_code': 'barrel_identity_unresolved'}
|
| 84 |
+
bat = np.array(bat_points); ball = np.array(ball_points); clock = times[ids]
|
| 85 |
+
if order_votes[0] == 1:
|
| 86 |
+
bat = bat[:, ::-1]
|
| 87 |
+
dt = np.diff(clock)
|
| 88 |
+
if not len(dt) or dt.max() > 1.01/30:
|
| 89 |
+
return {'outcome': 'unknown', 'reason_code': 'capture_cadence_insufficient'}
|
| 90 |
+
velocities = np.diff(ball, axis=0)/dt[:, None]
|
| 91 |
+
excursions = ball-ball[0]
|
| 92 |
+
travel = excursions[np.linalg.norm(excursions, axis=1).argmax()]
|
| 93 |
+
if np.linalg.norm(travel) > 2*config.ball_radius_m:
|
| 94 |
+
direction = travel/np.linalg.norm(travel)
|
| 95 |
+
# A caught/rebounding ball is a different flight. Do not recommend
|
| 96 |
+
# shifting a swing to meet its return from a net or another object.
|
| 97 |
+
# With no supported incoming-only range, conservatively withhold.
|
| 98 |
+
if (velocities@direction < -2*config.position_bound_m/dt).any():
|
| 99 |
+
return {'outcome': 'unknown', 'reason_code': 'incoming_ball_motion_unresolved'}
|
| 100 |
+
speed = float(np.linalg.norm(np.diff(ball, axis=0), axis=1).max()/dt.min()+
|
| 101 |
+
np.linalg.norm(np.diff(bat, axis=0), axis=2).max()/dt.min())
|
| 102 |
+
bound = config.position_bound_m+speed*config.synchronization_bound_ms/1000
|
| 103 |
+
radius = config.ball_radius_m+config.barrel_radius_m
|
| 104 |
+
spacing = min(.001, radius/max(4*speed, 1e-9))
|
| 105 |
+
count = int(np.ceil((clock[-1]-clock[0])/spacing))+1
|
| 106 |
+
if count > 200_000:
|
| 107 |
+
return {'outcome': 'unknown', 'reason_code': 'search_resolution_insufficient'}
|
| 108 |
+
fine = np.linspace(clock[0], clock[-1], count)
|
| 109 |
+
bats = np.stack([np.column_stack([np.interp(fine, clock, bat[:, k, j]) for j in range(3)]) for k in range(2)], axis=1)
|
| 110 |
+
balls = np.column_stack([np.interp(fine, clock, ball[:, j]) for j in range(3)])
|
| 111 |
+
distance = shaft_distance(balls, bats, 0.)
|
| 112 |
+
k = int(distance.argmin())
|
| 113 |
+
allowance = speed*spacing+2*bound
|
| 114 |
+
evidence = {'version': 'calibrated_two_view_paths_v1', 'frames': ids, 'times_s': clock.tolist(),
|
| 115 |
+
'bat_m': bat.tolist(), 'ball_m': ball.tolist(), 'max_reprojection_px': max(errors),
|
| 116 |
+
'position_bound_m': bound, 'bound_source': config.position_bound_source,
|
| 117 |
+
'closest_distance_m': float(distance[k]), 'grid_allowance_m': allowance}
|
| 118 |
+
# A positive margin over the entire supported swing proves separation only
|
| 119 |
+
# under the supplied position/synchronization bounds; this is not calibration.
|
| 120 |
+
if distance[k]-allowance <= radius:
|
| 121 |
+
return {'outcome': 'unknown', 'reason_code': 'contact_or_miss_spatially_unresolved', 'spatial': evidence}
|
| 122 |
+
if k in (0, len(fine)-1):
|
| 123 |
+
return {'outcome': 'unknown', 'reason_code': 'closest_approach_at_coverage_boundary', 'spatial': evidence}
|
| 124 |
+
closest = float(fine[k])
|
| 125 |
+
# Closest-time uncertainty is the set of samples indistinguishable under
|
| 126 |
+
# the supplied spatial bounds, rather than a fabricated one-frame bound.
|
| 127 |
+
possible = np.flatnonzero(distance <= distance[k]+2*allowance)
|
| 128 |
+
end_interval = [float(fine[max(0, possible[0]-1)]), float(fine[min(len(fine)-1, possible[-1]+1)])]
|
| 129 |
+
shift = physical_shift(clock, bat, ball, bat_radius_m=config.barrel_radius_m,
|
| 130 |
+
ball_radius_m=config.ball_radius_m, position_bound_m=bound,
|
| 131 |
+
region_start=config.barrel_start_fraction, max_shift_s=config.max_shift_ms/1000)
|
| 132 |
+
return {'outcome': 'miss', 'end_event': 'closest_approach', 'time_s': closest,
|
| 133 |
+
'time_interval_s': end_interval, 'method': 'calibrated_two_view_physical_closest_approach_v1',
|
| 134 |
+
'reason_code': None, 'spatial': evidence, 'shift': shift}
|
baseball_batting/tracking_vision.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Actual bat keypoint/ball detections, in original pixels, with no gap filling.
|
| 2 |
+
|
| 3 |
+
The public worker uses CUDA. CPU is an explicit internal evaluation seam.
|
| 4 |
+
"""
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
from .detection import ort_session, verify_cuda_nodes, iou
|
| 10 |
+
from .storage import sha256_file
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TrackingModel:
|
| 14 |
+
def __init__(self, root, name, device='cuda'):
|
| 15 |
+
folder = Path(root)/('tracking_'+name)
|
| 16 |
+
self.record = json.loads((folder/'model.json').read_text())
|
| 17 |
+
path = folder/'model.onnx'
|
| 18 |
+
if sha256_file(path) != self.record['onnx_sha256']:
|
| 19 |
+
raise ValueError(f'{name} ONNX checksum mismatch')
|
| 20 |
+
self.session = ort_session(path, device)
|
| 21 |
+
self.size = self.record['input_size']
|
| 22 |
+
self.name, self.device, self.verified = name, device, False
|
| 23 |
+
if self.session.get_inputs()[0].shape != [1, 3, self.size, self.size]:
|
| 24 |
+
raise ValueError('Unsupported tracking input shape')
|
| 25 |
+
self.classes = len(self.record['classes'])
|
| 26 |
+
labels = {'bat'} if name == 'bat' else {'baseball', 'ball'}
|
| 27 |
+
matches = [int(k) for k, v in self.record['classes'].items() if v in labels]
|
| 28 |
+
if len(matches) != 1:
|
| 29 |
+
raise ValueError(f'Tracking model has no unambiguous {name} class')
|
| 30 |
+
self.target_class = matches[0]
|
| 31 |
+
|
| 32 |
+
def __call__(self, image, origin=(0, 0)):
|
| 33 |
+
h, w = image.shape[:2]
|
| 34 |
+
ratio = min(self.size/w, self.size/h)
|
| 35 |
+
rw, rh = round(w*ratio), round(h*ratio)
|
| 36 |
+
left, top = (self.size-rw)//2, (self.size-rh)//2
|
| 37 |
+
canvas = np.full((self.size, self.size, 3), 114, np.uint8)
|
| 38 |
+
canvas[top:top+rh, left:left+rw] = cv2.resize(image, (rw, rh))
|
| 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
|
| 46 |
+
expected = 4+self.classes+3*count
|
| 47 |
+
if p.ndim != 2 or p.shape[1] != expected:
|
| 48 |
+
raise ValueError(f'Unsupported {self.name} output shape: {output.shape}')
|
| 49 |
+
scores = p[:, 4+self.target_class]
|
| 50 |
+
classes = p[:, 4:4+self.classes]
|
| 51 |
+
other = np.delete(classes, self.target_class, axis=1)
|
| 52 |
+
unique_target = scores > other.max(axis=1) if other.shape[1] else np.ones(len(p), bool)
|
| 53 |
+
order = np.flatnonzero(np.isfinite(p).all(axis=1) & (scores >= .35) & unique_target)
|
| 54 |
+
order = order[np.argsort(scores[order])[::-1]]
|
| 55 |
+
centers, extent = p[:, :2], p[:, 2:4]
|
| 56 |
+
boxes = np.concatenate((centers-extent/2, centers+extent/2), axis=1)
|
| 57 |
+
boxes = (boxes-[left, top, left, top])/ratio+[*origin, *origin]
|
| 58 |
+
result = []
|
| 59 |
+
while len(order):
|
| 60 |
+
i = order[0]
|
| 61 |
+
box = boxes[i]
|
| 62 |
+
class_id = self.target_class
|
| 63 |
+
label = self.record['classes'].get(str(class_id), self.record['classes'].get(class_id))
|
| 64 |
+
if label in ('bat', 'baseball', 'ball') and box[2] > box[0] and box[3] > box[1]:
|
| 65 |
+
row = {'box': box.tolist(), 'score': float(scores[i]),
|
| 66 |
+
'state': 'model_observed', 'method': self.name+'_keypoints' if self.name == 'bat' else 'baseball_detector'}
|
| 67 |
+
if self.name == 'bat':
|
| 68 |
+
k = p[i, 4+self.classes:].reshape(count, 3).copy()
|
| 69 |
+
xy = (k[:, :2]-[left, top])/ratio+origin
|
| 70 |
+
inside = ((xy >= origin).all() and
|
| 71 |
+
(xy[:, 0] < origin[0]+w).all() and (xy[:, 1] < origin[1]+h).all())
|
| 72 |
+
distances = np.linalg.norm(xy[:, None]-xy[None, :], axis=2)
|
| 73 |
+
a, b = np.unravel_index(distances.argmax(), distances.shape)
|
| 74 |
+
length = distances[a, b]
|
| 75 |
+
ends = xy[[a, b]]
|
| 76 |
+
shaft = ends[1]-ends[0]
|
| 77 |
+
delta = xy-ends[0]
|
| 78 |
+
residual = np.abs(delta[:, 0]*shaft[1]-delta[:, 1]*shaft[0])/max(length, 1e-9)
|
| 79 |
+
if inside and (k[:, 2] >= .5).all() and length >= 12 and residual.max() <= max(2, .04*length):
|
| 80 |
+
row.update(points=ends.tolist(), point_scores=k[[a, b], 2].tolist(),
|
| 81 |
+
shaft_points=xy.tolist(), endpoint_indices=[int(a), int(b)])
|
| 82 |
+
else:
|
| 83 |
+
row.update(points=None, reason_code='bat_endpoint_unobserved')
|
| 84 |
+
else:
|
| 85 |
+
row.update(point=((box[:2]+box[2:])/2).tolist(),
|
| 86 |
+
radius_px=float(max(box[2:]-box[:2])/2))
|
| 87 |
+
result.append(row)
|
| 88 |
+
order = order[1:][iou(box, boxes[order[1:]]) <= .45]
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def deduplicate(rows):
|
| 93 |
+
kept = []
|
| 94 |
+
for row in sorted(rows, key=lambda x: x['score'], reverse=True):
|
| 95 |
+
if not kept or max(iou(row['box'], [r['box'] for r in kept])) < .45:
|
| 96 |
+
kept.append(row)
|
| 97 |
+
elif row.get('points') is not None:
|
| 98 |
+
# A higher box score does not override independently visible shaft
|
| 99 |
+
# landmarks from a crop of the same bat.
|
| 100 |
+
duplicate = next(r for r in kept if iou(row['box'], [r['box']])[0] >= .45)
|
| 101 |
+
if duplicate.get('points') is None:
|
| 102 |
+
duplicate.update({k: row[k] for k in ('points', 'point_scores', 'shaft_points', 'endpoint_indices')})
|
| 103 |
+
duplicate.pop('reason_code', None)
|
| 104 |
+
return kept
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def frame_detections(image, bat, ball, athlete_box=None):
|
| 108 |
+
"""Full-frame search plus overlapping tiles near the hitting area.
|
| 109 |
+
|
| 110 |
+
Tiles preserve small-ball detail. Incoming/outgoing candidates outside the
|
| 111 |
+
athlete crop are retained by the full-frame search. No hand becomes a bat point.
|
| 112 |
+
"""
|
| 113 |
+
bats = bat(image)
|
| 114 |
+
balls = ball(image)
|
| 115 |
+
h, w = image.shape[:2]
|
| 116 |
+
if athlete_box is not None:
|
| 117 |
+
box = np.asarray(athlete_box, float)
|
| 118 |
+
extent = box[2:]-box[:2]
|
| 119 |
+
a = np.maximum(0, box[:2]-.5*extent).astype(int)
|
| 120 |
+
z = np.minimum([w, h], box[2:]+.5*extent).astype(int)
|
| 121 |
+
if min(z-a) > 16:
|
| 122 |
+
bats.extend(bat(image[a[1]:z[1], a[0]:z[0]], a))
|
| 123 |
+
bats = deduplicate(bats)
|
| 124 |
+
for b in bats[:2]:
|
| 125 |
+
a = np.maximum(0, np.array(b['box'][:2])-32).astype(int)
|
| 126 |
+
z = np.minimum([w, h], np.array(b['box'][2:])+32).astype(int)
|
| 127 |
+
if min(z-a) > 16:
|
| 128 |
+
bats.extend(bat(image[a[1]:z[1], a[0]:z[0]], a))
|
| 129 |
+
bats = deduplicate(bats)
|
| 130 |
+
boxes = ([athlete_box] if athlete_box is not None else []) + [b['box'] for b in bats[:1]]
|
| 131 |
+
searched = set()
|
| 132 |
+
for box in boxes[:2]:
|
| 133 |
+
box = np.asarray(box, float)
|
| 134 |
+
pad = .75*max(np.linalg.norm(box[2:]-box[:2]), 64)
|
| 135 |
+
low = np.maximum(0, box[:2]-pad).astype(int)
|
| 136 |
+
high = np.minimum([w, h], box[2:]+pad).astype(int)
|
| 137 |
+
# Search the bat interaction area, retaining the full-frame search for
|
| 138 |
+
# incoming/outgoing candidates. No whole-video UHD tiling is performed.
|
| 139 |
+
for y in range(low[1], high[1], 512):
|
| 140 |
+
for x in range(low[0], high[0], 512):
|
| 141 |
+
if (x, y) in searched:
|
| 142 |
+
continue
|
| 143 |
+
searched.add((x, y))
|
| 144 |
+
roi = image[y:min(y+640, h), x:min(x+640, w)]
|
| 145 |
+
if min(roi.shape[:2]) < 16:
|
| 146 |
+
continue
|
| 147 |
+
balls.extend(ball(roi, (x, y)))
|
| 148 |
+
return {'bat': deduplicate(bats), 'ball': deduplicate(balls)}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def track_video(video, result, model_root, device='cuda', progress=None):
|
| 152 |
+
from .ingest import iter_frames
|
| 153 |
+
bat, ball = TrackingModel(model_root, 'bat', device), TrackingModel(model_root, 'ball', device)
|
| 154 |
+
track = result['pose_track']
|
| 155 |
+
selected = set()
|
| 156 |
+
for rep in track['reps']:
|
| 157 |
+
events = rep.get('events', {})
|
| 158 |
+
onset = events.get('swing_start', {}).get('frame', rep['start_frame'])
|
| 159 |
+
finish = events.get('finish', {}).get('frame', rep['end_frame'])
|
| 160 |
+
selected.update(range(max(rep['start_frame'], onset-3), min(rep['end_frame'], finish+3)+1))
|
| 161 |
+
rows = []
|
| 162 |
+
for i, _, _, image in iter_frames(video, track['video']['rotation_degrees_applied']):
|
| 163 |
+
if i >= track['video']['frame_count']:
|
| 164 |
+
raise ValueError('Tracking decode exceeds body frame count')
|
| 165 |
+
row = frame_detections(image, bat, ball, track['frames']['box'][i]) if i in selected else {'bat': [], 'ball': []}
|
| 166 |
+
rows.append({'frame': i, 'capture_time_s': track['frames']['t_s'][i], **row})
|
| 167 |
+
if progress and (i in selected or i % 30 == 0):
|
| 168 |
+
progress('bat_ball_tracking', i+1, track['video']['frame_count'])
|
| 169 |
+
if len(rows) != track['video']['frame_count']:
|
| 170 |
+
raise ValueError('Tracking decode differs from body frame count')
|
| 171 |
+
return {'version': 'bat-ball-observations-v1', 'frames': rows,
|
| 172 |
+
'models': {'bat': bat.record, 'ball': ball.record},
|
| 173 |
+
'validation': 'real_video_accuracy_pending', 'gap_filling': False}
|
docs/GPU_API_DEPLOYMENT.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
|
| 3 |
This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. Lightweight RTMW3D is optional per request. SAM can be added in a separate worker/image; temporal fitting, OpenSim, bat 3D and coaching do not run. The Colab notebook remains available separately.
|
| 4 |
|
| 5 |
-
The four-field **Load and timing** output is available at `GET /v1/analyses/{job_id}/load-timing`. Use the `2d` backend and
|
| 6 |
|
| 7 |
Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain `est` pending independent validation. Weak events and unsupported angles are withheld. See [API_FOR_COACH.md](API_FOR_COACH.md) for the handoff and [BATTING_2D_MEASUREMENTS.md](BATTING_2D_MEASUREMENTS.md) for definitions and limitations.
|
| 8 |
|
|
@@ -10,7 +10,7 @@ Automatic rep/event detection is a versioned 2D heuristic, and all computed meas
|
|
| 10 |
|
| 11 |
Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the three model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee.
|
| 12 |
|
| 13 |
-
Install Docker with Compose and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see [ONNX CUDA requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html). The image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras
|
| 14 |
|
| 15 |
Clone your repository, enter its directory, then create your private configuration:
|
| 16 |
|
|
@@ -33,7 +33,7 @@ docker compose up -d --build
|
|
| 33 |
curl --fail http://127.0.0.1:8000/readyz
|
| 34 |
```
|
| 35 |
|
| 36 |
-
The image build downloads the RTMW-x, HumanArt person and optional RTMW3D models and verifies their SHA-256 values. A build fails if a required download or checksum fails. Startup runs actual pose and
|
| 37 |
|
| 38 |
RTMLib is installed with `--no-deps` for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently `pip check` reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution.
|
| 39 |
|
|
|
|
| 2 |
|
| 3 |
This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. Lightweight RTMW3D is optional per request. SAM can be added in a separate worker/image; temporal fitting, OpenSim, bat 3D and coaching do not run. The Colab notebook remains available separately.
|
| 4 |
|
| 5 |
+
The four-field **Load and timing** output is available at `GET /v1/analyses/{job_id}/load-timing`. Use the `2d` backend and `POST /v1/load-timing/analyses` for settings validation before queuing. The image includes separate BaseballCV bat/ball ONNX models; no SAM reconstruction runs on this route. New jobs save checksummed default 3.0 and opt-in 3.1 evidence payloads; older jobs need resubmission. Physical misses and timing correction require calibrated synchronized views. See [LOAD_TIMING_API.md](LOAD_TIMING_API.md) and [current validation limits](TRACKING_VALIDATION.md).
|
| 6 |
|
| 7 |
Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain `est` pending independent validation. Weak events and unsupported angles are withheld. See [API_FOR_COACH.md](API_FOR_COACH.md) for the handoff and [BATTING_2D_MEASUREMENTS.md](BATTING_2D_MEASUREMENTS.md) for definitions and limitations.
|
| 8 |
|
|
|
|
| 10 |
|
| 11 |
Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the three model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee.
|
| 12 |
|
| 13 |
+
Install Docker with Compose and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see [ONNX CUDA requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html). The final image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras without PyTorch or SAM. A separate build stage installs CPU PyTorch/Ultralytics to export the pinned bat/ball checkpoints.
|
| 14 |
|
| 15 |
Clone your repository, enter its directory, then create your private configuration:
|
| 16 |
|
|
|
|
| 33 |
curl --fail http://127.0.0.1:8000/readyz
|
| 34 |
```
|
| 35 |
|
| 36 |
+
The image build downloads the RTMW-x, HumanArt person and optional RTMW3D models plus pinned BaseballCV bat/ball checkpoints and verifies their SHA-256 values. It records the hash of each exported ONNX model. A build fails if a required download or checksum fails. Startup runs actual pose, person, bat and ball inference on CUDA; `/readyz` returns 503 until it passes and reports `bat_ball_tracking_ready`. A missing GPU or broken CUDA setup prevents video jobs from being accepted. This confirms GPU execution, not measurement accuracy. Existing body-only installations may still accept the old upload route, but the dedicated timing route returns 503 until tracking passes preflight.
|
| 37 |
|
| 38 |
RTMLib is installed with `--no-deps` for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently `pip check` reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution.
|
| 39 |
|
docs/LOAD_TIMING_API.md
CHANGED
|
@@ -1,126 +1,117 @@
|
|
| 1 |
# Load and swing timing API
|
| 2 |
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
| 6 |
|
| 7 |
-
|
| 8 |
|
| 9 |
-
|
| 10 |
-
| --- | --- |
|
| 11 |
-
| `POST /v1/analyses` | Upload the video and recording options. Returns a job ID and `load_timing_url`. |
|
| 12 |
-
| `GET /v1/analyses/{job_id}` | Check progress. Wait for `status: "completed"`. |
|
| 13 |
-
| `GET /v1/analyses/{job_id}/load-timing` | Return the four-field JSON, one entry per swing candidate. |
|
| 14 |
-
| `GET /v1/load-timing-schema` | Return the exact timing payload JSON Schema. |
|
| 15 |
-
| `DELETE /v1/analyses/{job_id}` | Cancel the job and remove its artifacts. |
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
```json
|
| 31 |
{
|
| 32 |
-
"discipline": "hitting",
|
| 33 |
"measurement_backend": "2d",
|
| 34 |
"handedness": "right",
|
| 35 |
-
"pitcher_direction": "
|
| 36 |
"view": "face_on",
|
| 37 |
"camera_stability": "fixed_verified",
|
| 38 |
"timing": {
|
| 39 |
"kind": "unretimed",
|
| 40 |
"source": "Original camera recording; no speed changes"
|
| 41 |
},
|
| 42 |
-
"single_swing":
|
|
|
|
| 43 |
}
|
| 44 |
```
|
| 45 |
|
| 46 |
-
`
|
| 47 |
|
| 48 |
-
|
| 49 |
|
| 50 |
-
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
"unit": "ms",
|
| 93 |
-
"status": "unclear",
|
| 94 |
-
"confidence": "est",
|
| 95 |
-
"note": "Reliable bat/ball paths are unavailable; a timing correction cannot be estimated."
|
| 96 |
-
}
|
| 97 |
-
]
|
| 98 |
-
}
|
| 99 |
-
]
|
| 100 |
-
}
|
| 101 |
-
```
|
| 102 |
|
| 103 |
-
|
| 104 |
|
| 105 |
-
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
| `swing_duration_ms` | Ball contact − swing start; for misses, closest bat–ball approach − swing start | Unclear in the automatic worker: no actual bat/ball endpoint is detected. The body-extension guess is not substituted. |
|
| 112 |
-
| `early_late_shift_ms` | Estimate the shift needed for the same bat movement to meet the recorded ball | Unclear: reliable bat/ball tracking is not implemented in this worker. Negative would mean move the swing earlier; positive would mean move it later. |
|
| 113 |
|
| 114 |
-
|
| 115 |
|
| 116 |
-
|
| 117 |
|
| 118 |
-
|
| 119 |
|
| 120 |
-
|
| 121 |
|
| 122 |
-
|
| 123 |
|
| 124 |
-
|
| 125 |
|
| 126 |
-
|
|
|
|
| 1 |
# Load and swing timing API
|
| 2 |
|
| 3 |
+
This API measures swings for the separate coach agent. It does not choose faults, priorities or drills. Load/timing jobs use GPU person/2D pose inference plus separate GPU bat and baseball models. SAM is unnecessary for these jobs.
|
| 4 |
|
| 5 |
+
The four calculations now have implementation paths. That does **not** mean all four can be measured from every recording. Public detector accuracy on our phone footage is still unvalidated; a visible-looking preview does not validate the measurements.
|
| 6 |
|
| 7 |
+
## Requests and versions
|
| 8 |
|
| 9 |
+
Every `/v1/` request needs Bearer authorization with your engine API key.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
| Request | Purpose |
|
| 12 |
+
|---|---|
|
| 13 |
+
| `POST /v1/load-timing/analyses` | Upload for timing. Rejects missing recording settings before queuing. |
|
| 14 |
+
| `GET /v1/analyses/{job_id}` | Poll status and frame progress. |
|
| 15 |
+
| `GET /v1/analyses/{job_id}/load-timing` | Existing version `3.0`, four ordered metrics per swing. |
|
| 16 |
+
| `GET /v1/analyses/{job_id}/load-timing?include_evidence=true` | Opt-in version `3.1`, with event intervals, metric reasons, sensitivity and practice context. |
|
| 17 |
+
| `GET /v1/load-timing-schema?include_evidence=true` | Exact schema for the evidence response. Omit the query for `3.0`. |
|
| 18 |
+
| `DELETE /v1/analyses/{job_id}` | Cancel processing and delete artifacts. |
|
| 19 |
|
| 20 |
+
`POST /v1/analyses` remains compatible with previous clients, including optional body reconstruction. It now returns warnings when timing settings are missing. `/coach-payload` still returns version `2.0`. The engine never calls the friend's coach API automatically.
|
| 21 |
|
| 22 |
+
## Postman: one recording
|
| 23 |
|
| 24 |
+
Set **Authorization → Bearer Token** to the engine API key. In **Body → form-data**, add:
|
| 25 |
+
|
| 26 |
+
| Key | Type | Value |
|
| 27 |
+
|---|---|---|
|
| 28 |
+
| `video` | File | Original recording |
|
| 29 |
+
| `options` | Text | One JSON object, below |
|
| 30 |
+
|
| 31 |
+
Send to `https://YOUR_ENGINE_HOST/v1/load-timing/analyses`. This example assumes a right-handed hitter, pitcher/tee to image-left, a known face-on view and fixed camera. Change the declarations to match the actual recording.
|
| 32 |
|
| 33 |
```json
|
| 34 |
{
|
|
|
|
| 35 |
"measurement_backend": "2d",
|
| 36 |
"handedness": "right",
|
| 37 |
+
"pitcher_direction": "image_left",
|
| 38 |
"view": "face_on",
|
| 39 |
"camera_stability": "fixed_verified",
|
| 40 |
"timing": {
|
| 41 |
"kind": "unretimed",
|
| 42 |
"source": "Original camera recording; no speed changes"
|
| 43 |
},
|
| 44 |
+
"single_swing": false,
|
| 45 |
+
"practice_type": "tee"
|
| 46 |
}
|
| 47 |
```
|
| 48 |
|
| 49 |
+
`single_swing: false` separates multiple swing candidates automatically; `true` declares exactly one. `practice_type` accepts `tee`, `soft_toss`, `front_toss`, `live`, `machine` or `unknown`. Tee contact needs the stationary ball before impact and its outgoing movement after impact. A disappearing ball alone is insufficient.
|
| 50 |
|
| 51 |
+
Optional `pitch_speed_mps`, `pitch_location` and `pitch_context_source` carry supplied practice information. They are not measured automatically. Unknown pitch conditions remain unknown so the agent can avoid comparing unlike sessions. Timing uses original capture timestamps; a downloaded or slowed video must not be declared unretimed without evidence. See [capture clock options](API_FOR_COACH.md#upload-options).
|
| 52 |
|
| 53 |
+
Wait for `status: "completed"`, then request the returned `load_timing_url` or `load_timing_evidence_url`. The same flow is available in `/docs` using **Authorize → Try it out**.
|
| 54 |
|
| 55 |
+
## What the calculations mean
|
| 56 |
+
|
| 57 |
+
| Metric | Calculation and interpretation |
|
| 58 |
+
|---|---|
|
| 59 |
+
| `load_to_swing_ms` | Forward hand-based swing onset minus the start of backward hand preparation. The existing onset definition is unchanged. |
|
| 60 |
+
| `foot_down_to_swing_ms` | Forward onset minus first front-foot landing, when a step is supported. Negative means the swing starts before landing. Missing foot events mean unknown, not no-step. |
|
| 61 |
+
| `swing_duration_ms` | Supported contact time minus forward onset. For a physical miss, uses `closest_approach`, explicitly separate from contact. |
|
| 62 |
+
| `early_late_shift_ms` | For a supported miss, shift the same observed bat path in time against the unchanged ball path. Negative means repeat earlier; positive means repeat later. This does not predict the player's ability to execute the adjustment. |
|
| 63 |
+
|
| 64 |
+
A single phone can support an **estimated visual hit interval** when actual bat landmarks and independently observed ball movement establish the interaction. The arm-extension proxy is never used as contact. Screen-space overlap does not establish a physical miss or timing correction.
|
| 65 |
+
|
| 66 |
+
All values stay `confidence: "est"`. No independently validated accuracy class is available. Capture cadence, visibility, coverage and event-interval sensitivity can withhold individual values even when other metrics are available. The cadence floor is nominal 30 FPS (including 29.97), not a promise of useful contact detection at 30 FPS. Decimal milliseconds describe arithmetic, not millisecond accuracy.
|
| 67 |
+
|
| 68 |
+
## Two views: physical misses and timing correction
|
| 69 |
+
|
| 70 |
+
Add a second form-data **File** named `secondary_video` and an `options.stereo_tracking` object. Both must be supplied together. The primary upload still uses the known face-on body view. Cameras must cover the same swing, remain fixed, and have measured intrinsics, lens distortion, relative position/rotation and time alignment.
|
| 71 |
+
|
| 72 |
+
Required `stereo_tracking` fields:
|
| 73 |
+
|
| 74 |
+
| Field | Meaning |
|
| 75 |
+
|---|---|
|
| 76 |
+
| `cameras` | Exactly two camera objects in primary/secondary order. Each has `intrinsics` (3×3), `rotation` (3×3), `translation_m` (3), and optional `distortion` (4, 5 or 8 coefficients). |
|
| 77 |
+
| `source` | How calibration was obtained. Coordinates refer to the upright decoded images. Extrinsics map world to camera: `X_camera = rotation @ X_world + translation_m`. |
|
| 78 |
+
| `secondary_offset_s` | Add this value to secondary capture time to align with the primary clock. |
|
| 79 |
+
| `synchronization_source`, `synchronization_bound_ms` | How alignment was measured and its supplied error bound. Starting both phones together is insufficient. |
|
| 80 |
+
| `position_bound_m`, `position_bound_source` | Supplied spatial error bound, including detection, calibration, bat endpoint definition and interpolation error. A model score is not this bound. |
|
| 81 |
+
| `bat_length_m`, `barrel_radius_m` | Measured dimensions. |
|
| 82 |
+
| `barrel_start_fraction` | Start of the target barrel along knob-to-cap length; default `0.5`. |
|
| 83 |
+
| `ball_radius_m` | Default `0.0366`; replace if appropriate to the recorded ball. |
|
| 84 |
+
| `secondary_timing` | Documented capture clock, same structure as primary `timing`. |
|
| 85 |
+
| `secondary_rotation_degrees` | Optional explicit orientation, 0/90/180/270 clockwise. |
|
| 86 |
+
| `max_shift_ms` | Search limit in each direction, default 250, maximum 1000. |
|
| 87 |
+
|
| 88 |
+
The API checks ray geometry, positive depth, reprojection agreement, measured bat length, endpoint identity, clock cadence, visibility and complete primary-swing coverage. Missing observations do not become filled-in impact evidence. Adjacent second-view samples may be interpolated only between directly observed detections with usable cadence; they retain their interpolation state.
|
| 89 |
+
|
| 90 |
+
The physical model is a bat capsule and ball sphere on piecewise linear paths. Closest approach uses the whole observed bat; timing correction targets the declared barrel. Spatial and synchronization bounds are propagated conservatively under this model. They remain **supplied assumptions**, not validated accuracy. Position error larger than the collision margin can make a correction unavailable.
|
| 91 |
+
|
| 92 |
+
The correction searches supported footage without extrapolation and retains disconnected feasible shift intervals. It returns a scalar only for one sign-stable interval with a certified interior solution under the supplied bounds. The policy is **closest-to-zero certified feasible shift**, not the centre of an assumed probability distribution. Coverage/search boundaries, ambiguity and insufficient resolution yield nulls.
|
| 93 |
+
|
| 94 |
+
Tee misses do not receive a moving-pitch early/late correction. Two-view reconstruction uses the objects, not a SAM body mesh.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
## Evidence response
|
| 97 |
|
| 98 |
+
Version `3.1` preserves the four metric meanings and adds:
|
| 99 |
|
| 100 |
+
- `context`: supplied practice type/pitch facts and provenance.
|
| 101 |
+
- `reps[].events`: event method, frame/capture-time interval and uncertainty kind.
|
| 102 |
+
- `reps[].outcome_method`: how hit/miss evidence was established.
|
| 103 |
+
- Each metric: `reason_code`, `uncertainty`, and optional `feasible_shift_intervals_ms`.
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
`uncertainty.accuracy_validated` is always false. Frame sensitivity is not a calibrated accuracy interval. See the [synthetic example](load-timing-evidence.example.json) and [schema](load-timing-evidence.schema.json). Default `3.0` has exactly its previous structure, so old strict validators continue to work.
|
| 106 |
|
| 107 |
+
Common unavailable reasons include `capture_failed`, `capture_time_unknown`, `forward_swing_unresolved`, `step_unresolved`, `timing_interval_unresolved`, `bat_endpoints_unobserved_or_ambiguous`, `ball_trajectory_unobserved_or_ambiguous`, `contact_evidence_insufficient`, `depth_unresolved`, `spatial_track_incomplete`, `bat_geometry_ambiguous`, `barrel_identity_unresolved`, `ball_identity_ambiguous`, `incoming_ball_motion_unresolved`, `camera_motion_unresolved`, `synchronization_unresolved`, `ambiguous_time_shift`, `shift_search_boundary`, `spatial_coverage_insufficient`, `shift_unresolved_under_position_error`, and `search_resolution_insufficient`.
|
| 108 |
|
| 109 |
+
`no_feasible_shift_in_observed_window` is limited to the supported footage and search range; it is not a diagnosis of bad mechanics or a claim about unseen paths. `stationary_tee_ball_no_pitch_timing`, `hit_no_correction_needed` and `no_step` explain inapplicable calculations.
|
| 110 |
|
| 111 |
+
## Deployment and artifacts
|
| 112 |
|
| 113 |
+
Rebuild the GPU Docker image. Its build downloads checksummed BaseballCV bat/ball checkpoints and exports static ONNX in a separate build stage. PyTorch/Ultralytics are build dependencies; inference uses ONNX Runtime CUDA. Startup executes all required models on CUDA. The timing upload route requires `/readyz` to report `bat_ball_tracking_ready: true`; legacy body-only installations remain compatible with the old upload route.
|
| 114 |
|
| 115 |
+
New jobs save checksummed `load-timing.json` and `load-timing-evidence.json`. Server diagnostics retain direct observations, model identities and calculation evidence. Database migration adds hashes without losing existing jobs. Original uploads, including the second view, are deleted after terminal jobs. Previous completed jobs need resubmission for new artifacts. Results before completion return 409; integrity failures return 500.
|
| 116 |
|
| 117 |
+
See [deployment](GPU_API_DEPLOYMENT.md) and [validation results and remaining model limits](TRACKING_VALIDATION.md). The Python client supports `--load-timing`, optional `--include-evidence`, and optional `--secondary-video` with calibration in its options file.
|
docs/TRACKING_VALIDATION.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Bat/ball timing verification — 13 October 2026
|
| 2 |
+
|
| 3 |
+
The implementation is present and tested; its real-video measurement accuracy is **not established**. The public models are candidates, not proven winners for our capture conditions.
|
| 4 |
+
|
| 5 |
+
## Models and reproducibility
|
| 6 |
+
|
| 7 |
+
`tools/setup_tracking_models.py` downloads two pinned public BaseballCV checkpoints and verifies SHA-256 before loading/exporting. Model identities come from the actual checkpoint heads, not the registry's brief description:
|
| 8 |
+
|
| 9 |
+
| Branch | Checkpoint | Actual output |
|
| 10 |
+
|---|---|---|
|
| 11 |
+
| Bat | `bat_tracking_v2.pt` | YOLO11x pose, bat/hitter classes, four shaft landmarks. The outer observed pair estimates bat ends; independent hand proximity can establish knob/barrel identity without replacing either endpoint. |
|
| 12 |
+
| Ball | `ball_tracking_v4-YOLOv11.pt` | YOLO11x detection, glove/homeplate/baseball/rubber. Only the baseball class is used. |
|
| 13 |
+
|
| 14 |
+
Registry snapshot: BaseballCV commit `c3c26c979766b28e0c78c3fee2edc2aa3dad571e`. Source URLs, checkpoint hashes, actual classes, input size and exported ONNX hash are saved with each model. Export uses Ultralytics 8.4.175, static 640×640 float32, opset 17, raw output without built-in NMS. Runtime validates the ONNX hash and actual CUDA operator execution. No tracking weights are downloaded during an upload.
|
| 15 |
+
|
| 16 |
+
The adapter converts BGR to RGB, reverses letterbox/crop transforms, filters actual target classes, suppresses duplicate boxes and rejects missing/non-collinear shaft landmarks. Ball searches include the full image and overlapping crops near the athlete/bat. Tracking concentrates on the detected swing and adjacent endpoint context, preserving empty observations outside those windows.
|
| 17 |
+
|
| 18 |
+
## Verified behavior
|
| 19 |
+
|
| 20 |
+
Automated checks cover preprocessing/class selection, shaft validity, observation windows, no gap filling, visual incoming/outgoing contact evidence, stationary tee departure, projected overlap rejection, unknown capture time and insufficient cadence. Constructed camera paths test triangulation, miss closest approach, both correction signs, disconnected solutions, position-error instability, search boundaries and unsupported coverage.
|
| 21 |
+
|
| 22 |
+
The worker-to-HTTP checks use actual video decoding and persistence with constructed model observations. They exercise a hit duration and a two-view miss with all four non-null calculations. Authentication, missing-settings rejection, second-view pairing, terminal upload deletion, checksums, old 3.0/2.0 compatibility and opt-in 3.1 are tested. These tests establish calculation and API behavior, not neural-network accuracy on real players.
|
| 23 |
+
|
| 24 |
+
## Real recording check
|
| 25 |
+
|
| 26 |
+
The exported ONNX models were run on selected frames from the supplied `tee-_walk_through (1080p).mp4` on CPU. The bat is detected before the forward swing, but crop/full-image endpoint predictions can disagree. Around frames 75/80, the strongly blurred bat is not detected. The visible ball on the tee at frame 60 was missed in full-image and targeted crop checks; a separate background baseball candidate was detected instead.
|
| 27 |
+
|
| 28 |
+
This recording cannot support a trusted automatic contact duration with these observations. Its old arm-extension endpoint does not supply the missing ball contact. No threshold was lowered, missing endpoint invented, or per-video coordinate fix added to force a result. The local evaluation images and raw observations are in ignored `artifacts/load-timing-validation/`; the recordings and artifacts are not committed.
|
| 29 |
+
|
| 30 |
+
Only selected frames were checked. This is a demonstrated failure case, not a dataset-wide detection-rate estimate. Local CPU timings are not GPU performance measurements. The Linux Docker image and CUDA worker need deployment verification: the local Docker daemon was unavailable and this machine has no NVIDIA GPU.
|
| 31 |
+
|
| 32 |
+
## What still needs evidence
|
| 33 |
+
|
| 34 |
+
The public checkpoints need evaluation and likely fine-tuning for the intended phone footage, especially blurred bats, balls on tees, nets, backgrounds, small incoming balls and object identity near contact. A temporal baseball model can be evaluated as another candidate; a tennis/shuttlecock checkpoint is not treated as validated baseball tracking.
|
| 35 |
+
|
| 36 |
+
Reliable early/late measurements additionally need synchronized calibrated views, defensible spatial/interpolation error bounds, and complete physical trajectories. More decimal places or a SAM body mesh do not supply those observations. Forward hand-onset accuracy also remains unvalidated. Keep all confidences as estimates and retain nulls/reasons until independent checks establish reliable measurement errors.
|
| 37 |
+
|
| 38 |
+
The same ONNX adapter was also checked on frames 169, 185 and 200 of `IMG_1610.mp4`, using athlete boxes from its archived pose result after verifying the original video's SHA-256. No bat was detected in those samples; one ball candidate was present at frame 200. This is another limited sample check, not validation of that candidate or a full-video accuracy score.
|
| 39 |
+
|
| 40 |
+
## Exporting a replacement detector
|
| 41 |
+
|
| 42 |
+
The inference adapter is separate from contact/geometry calculations. An improved trusted YOLO checkpoint can be exported with `--bat-checkpoint` or `--ball-checkpoint` without changing measurement logic. The bat checkpoint must predict at least two visible landmarks representing its shaft ends; a box-only model is rejected. The ball checkpoint must have one unambiguous `baseball` or `ball` class. The local source checkpoint and exported ONNX hashes are recorded. This interface does not train or validate the replacement model.
|
| 43 |
+
|
| 44 |
+
In an export environment with CPU PyTorch/Torchvision and `requirements-tracking-export.txt` installed, run:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
python -m tools.setup_tracking_models --output downloads --bat-checkpoint /path/to/trusted-bat.pt --ball-checkpoint /path/to/trusted-ball.pt
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Install the resulting `tracking_bat` and `tracking_ball` directories in the server's model root and restart for CUDA preflight. Keep the required person/body models in that root. The default Docker build uses the pinned public candidates.
|
docs/load-and-timing-for-coach-agent.md
CHANGED
|
@@ -35,7 +35,7 @@ The calculations are:
|
|
| 35 |
- Swing duration: `1450 - 1300 = 150 ms`.
|
| 36 |
- Early/late adjustment: not applicable because this example is a hit.
|
| 37 |
|
| 38 |
-
The timing payload keeps the `reps[].metrics[]` structure. This illustrative hit example describes the
|
| 39 |
|
| 40 |
```json
|
| 41 |
{
|
|
|
|
| 35 |
- Swing duration: `1450 - 1300 = 150 ms`.
|
| 36 |
- Early/late adjustment: not applicable because this example is a hit.
|
| 37 |
|
| 38 |
+
The timing payload keeps the `reps[].metrics[]` structure. This illustrative hit example describes the contract, not independently validated measurements. The tracking-enabled API can now establish estimated visual hit intervals when actual bat/ball observations support them; it returns unknown when evidence is missing. Physical misses and timing corrections require calibrated synchronized two-view paths. Default version 3.0 remains compatible; opt-in 3.1 includes reason codes, event intervals and supplied practice context. See [API requests and evidence](LOAD_TIMING_API.md).
|
| 39 |
|
| 40 |
```json
|
| 41 |
{
|
docs/load-timing-evidence.example.json
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "3.1",
|
| 3 |
+
"discipline": "hitting",
|
| 4 |
+
"time_basis": "capture",
|
| 5 |
+
"capture": {
|
| 6 |
+
"ok": true,
|
| 7 |
+
"reasons": []
|
| 8 |
+
},
|
| 9 |
+
"context": {
|
| 10 |
+
"practice_type": "live",
|
| 11 |
+
"pitch_speed_mps": null,
|
| 12 |
+
"pitch_location": null,
|
| 13 |
+
"source": null,
|
| 14 |
+
"provenance": "supplied_by_uploader"
|
| 15 |
+
},
|
| 16 |
+
"reps": [
|
| 17 |
+
{
|
| 18 |
+
"rep": 1,
|
| 19 |
+
"outcome": "hit",
|
| 20 |
+
"stepped": true,
|
| 21 |
+
"metrics": [
|
| 22 |
+
{
|
| 23 |
+
"key": "load_to_swing_ms",
|
| 24 |
+
"value": 333.333,
|
| 25 |
+
"unit": "ms",
|
| 26 |
+
"status": "estimated",
|
| 27 |
+
"confidence": "est",
|
| 28 |
+
"note": "Preparation (backward hand load) to estimated forward swing start. Duration from capture timestamps; event detection remains unvalidated.",
|
| 29 |
+
"end_event": null,
|
| 30 |
+
"reason_code": null,
|
| 31 |
+
"uncertainty": {
|
| 32 |
+
"interval_ms": [
|
| 33 |
+
316.667,
|
| 34 |
+
350.0
|
| 35 |
+
],
|
| 36 |
+
"kind": "frame_sensitivity",
|
| 37 |
+
"accuracy_validated": false,
|
| 38 |
+
"note": "Sensitivity to recorded frames or supplied geometry bounds; not a validated accuracy interval."
|
| 39 |
+
},
|
| 40 |
+
"feasible_shift_intervals_ms": null
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"key": "foot_down_to_swing_ms",
|
| 44 |
+
"value": 83.333,
|
| 45 |
+
"unit": "ms",
|
| 46 |
+
"status": "estimated",
|
| 47 |
+
"confidence": "est",
|
| 48 |
+
"note": "First front-foot ground contact to estimated forward swing start; negative means swing began before landing. Signed difference from capture timestamps.",
|
| 49 |
+
"end_event": null,
|
| 50 |
+
"reason_code": null,
|
| 51 |
+
"uncertainty": {
|
| 52 |
+
"interval_ms": [
|
| 53 |
+
66.667,
|
| 54 |
+
100.0
|
| 55 |
+
],
|
| 56 |
+
"kind": "frame_sensitivity",
|
| 57 |
+
"accuracy_validated": false,
|
| 58 |
+
"note": "Sensitivity to recorded frames or supplied geometry bounds; not a validated accuracy interval."
|
| 59 |
+
},
|
| 60 |
+
"feasible_shift_intervals_ms": null
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"key": "swing_duration_ms",
|
| 64 |
+
"value": 333.333,
|
| 65 |
+
"unit": "ms",
|
| 66 |
+
"status": "estimated",
|
| 67 |
+
"confidence": "est",
|
| 68 |
+
"note": "Forward hand onset to contact from bat/ball observations. Event accuracy remains unvalidated.",
|
| 69 |
+
"end_event": "contact",
|
| 70 |
+
"reason_code": null,
|
| 71 |
+
"uncertainty": {
|
| 72 |
+
"interval_ms": [
|
| 73 |
+
308.333,
|
| 74 |
+
358.333
|
| 75 |
+
],
|
| 76 |
+
"kind": "frame_sensitivity",
|
| 77 |
+
"accuracy_validated": false,
|
| 78 |
+
"note": "Sensitivity to recorded frames or supplied geometry bounds; not a validated accuracy interval."
|
| 79 |
+
},
|
| 80 |
+
"feasible_shift_intervals_ms": null
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"key": "early_late_shift_ms",
|
| 84 |
+
"value": null,
|
| 85 |
+
"unit": "ms",
|
| 86 |
+
"status": "not_applicable",
|
| 87 |
+
"confidence": "est",
|
| 88 |
+
"note": "Only applies to misses.",
|
| 89 |
+
"end_event": null,
|
| 90 |
+
"reason_code": "hit_no_correction_needed",
|
| 91 |
+
"uncertainty": {
|
| 92 |
+
"interval_ms": null,
|
| 93 |
+
"kind": "unknown",
|
| 94 |
+
"accuracy_validated": false,
|
| 95 |
+
"note": "Sensitivity to recorded frames or supplied geometry bounds; not a validated accuracy interval."
|
| 96 |
+
},
|
| 97 |
+
"feasible_shift_intervals_ms": null
|
| 98 |
+
}
|
| 99 |
+
],
|
| 100 |
+
"events": [
|
| 101 |
+
{
|
| 102 |
+
"event": "load_start",
|
| 103 |
+
"method": "backward_hand_excursion_v1",
|
| 104 |
+
"frame_interval": [
|
| 105 |
+
19,
|
| 106 |
+
21
|
| 107 |
+
],
|
| 108 |
+
"capture_interval_s": [
|
| 109 |
+
0.15833333333333333,
|
| 110 |
+
0.175
|
| 111 |
+
],
|
| 112 |
+
"uncertainty_kind": "frame_sensitivity",
|
| 113 |
+
"accuracy_validated": false
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"event": "foot_contact",
|
| 117 |
+
"method": "test",
|
| 118 |
+
"frame_interval": [
|
| 119 |
+
49,
|
| 120 |
+
51
|
| 121 |
+
],
|
| 122 |
+
"capture_interval_s": [
|
| 123 |
+
0.4083333333333333,
|
| 124 |
+
0.425
|
| 125 |
+
],
|
| 126 |
+
"uncertainty_kind": "frame_sensitivity",
|
| 127 |
+
"accuracy_validated": false
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"event": "swing_start",
|
| 131 |
+
"method": "primary_swing_forward_hand_motion_v2",
|
| 132 |
+
"frame_interval": [
|
| 133 |
+
59,
|
| 134 |
+
61
|
| 135 |
+
],
|
| 136 |
+
"capture_interval_s": [
|
| 137 |
+
0.49166666666666664,
|
| 138 |
+
0.5083333333333333
|
| 139 |
+
],
|
| 140 |
+
"uncertainty_kind": "frame_sensitivity",
|
| 141 |
+
"accuracy_validated": false
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"event": "contact",
|
| 145 |
+
"method": "observed_bat_and_piecewise_ball_trajectory_v1",
|
| 146 |
+
"frame_interval": [
|
| 147 |
+
98,
|
| 148 |
+
102
|
| 149 |
+
],
|
| 150 |
+
"capture_interval_s": [
|
| 151 |
+
0.8166666666666667,
|
| 152 |
+
0.85
|
| 153 |
+
],
|
| 154 |
+
"uncertainty_kind": "visual_contact_interval",
|
| 155 |
+
"accuracy_validated": false
|
| 156 |
+
}
|
| 157 |
+
],
|
| 158 |
+
"outcome_method": "observed_bat_and_piecewise_ball_trajectory_v1"
|
| 159 |
+
}
|
| 160 |
+
]
|
| 161 |
+
}
|
docs/load-timing-evidence.schema.json
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$defs": {
|
| 3 |
+
"EventEvidence": {
|
| 4 |
+
"additionalProperties": false,
|
| 5 |
+
"properties": {
|
| 6 |
+
"event": {
|
| 7 |
+
"title": "Event",
|
| 8 |
+
"type": "string"
|
| 9 |
+
},
|
| 10 |
+
"method": {
|
| 11 |
+
"title": "Method",
|
| 12 |
+
"type": "string"
|
| 13 |
+
},
|
| 14 |
+
"frame_interval": {
|
| 15 |
+
"anyOf": [
|
| 16 |
+
{
|
| 17 |
+
"items": {
|
| 18 |
+
"type": "integer"
|
| 19 |
+
},
|
| 20 |
+
"type": "array"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"type": "null"
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
"title": "Frame Interval"
|
| 27 |
+
},
|
| 28 |
+
"capture_interval_s": {
|
| 29 |
+
"anyOf": [
|
| 30 |
+
{
|
| 31 |
+
"items": {
|
| 32 |
+
"type": "number"
|
| 33 |
+
},
|
| 34 |
+
"type": "array"
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"type": "null"
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
"title": "Capture Interval S"
|
| 41 |
+
},
|
| 42 |
+
"uncertainty_kind": {
|
| 43 |
+
"enum": [
|
| 44 |
+
"frame_sensitivity",
|
| 45 |
+
"visual_contact_interval",
|
| 46 |
+
"supplied_geometry_bound"
|
| 47 |
+
],
|
| 48 |
+
"title": "Uncertainty Kind",
|
| 49 |
+
"type": "string"
|
| 50 |
+
},
|
| 51 |
+
"accuracy_validated": {
|
| 52 |
+
"const": false,
|
| 53 |
+
"default": false,
|
| 54 |
+
"title": "Accuracy Validated",
|
| 55 |
+
"type": "boolean"
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"required": [
|
| 59 |
+
"event",
|
| 60 |
+
"method",
|
| 61 |
+
"frame_interval",
|
| 62 |
+
"capture_interval_s",
|
| 63 |
+
"uncertainty_kind"
|
| 64 |
+
],
|
| 65 |
+
"title": "EventEvidence",
|
| 66 |
+
"type": "object"
|
| 67 |
+
},
|
| 68 |
+
"EvidenceMetric": {
|
| 69 |
+
"additionalProperties": false,
|
| 70 |
+
"properties": {
|
| 71 |
+
"key": {
|
| 72 |
+
"enum": [
|
| 73 |
+
"load_to_swing_ms",
|
| 74 |
+
"foot_down_to_swing_ms",
|
| 75 |
+
"swing_duration_ms",
|
| 76 |
+
"early_late_shift_ms"
|
| 77 |
+
],
|
| 78 |
+
"title": "Key",
|
| 79 |
+
"type": "string"
|
| 80 |
+
},
|
| 81 |
+
"value": {
|
| 82 |
+
"anyOf": [
|
| 83 |
+
{
|
| 84 |
+
"type": "number"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"type": "null"
|
| 88 |
+
}
|
| 89 |
+
],
|
| 90 |
+
"title": "Value"
|
| 91 |
+
},
|
| 92 |
+
"unit": {
|
| 93 |
+
"const": "ms",
|
| 94 |
+
"title": "Unit",
|
| 95 |
+
"type": "string"
|
| 96 |
+
},
|
| 97 |
+
"status": {
|
| 98 |
+
"enum": [
|
| 99 |
+
"estimated",
|
| 100 |
+
"unclear",
|
| 101 |
+
"not_applicable"
|
| 102 |
+
],
|
| 103 |
+
"title": "Status",
|
| 104 |
+
"type": "string"
|
| 105 |
+
},
|
| 106 |
+
"confidence": {
|
| 107 |
+
"const": "est",
|
| 108 |
+
"title": "Confidence",
|
| 109 |
+
"type": "string"
|
| 110 |
+
},
|
| 111 |
+
"note": {
|
| 112 |
+
"title": "Note",
|
| 113 |
+
"type": "string"
|
| 114 |
+
},
|
| 115 |
+
"end_event": {
|
| 116 |
+
"anyOf": [
|
| 117 |
+
{
|
| 118 |
+
"enum": [
|
| 119 |
+
"contact",
|
| 120 |
+
"closest_approach"
|
| 121 |
+
],
|
| 122 |
+
"type": "string"
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"type": "null"
|
| 126 |
+
}
|
| 127 |
+
],
|
| 128 |
+
"default": null,
|
| 129 |
+
"title": "End Event"
|
| 130 |
+
},
|
| 131 |
+
"reason_code": {
|
| 132 |
+
"anyOf": [
|
| 133 |
+
{
|
| 134 |
+
"type": "string"
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"type": "null"
|
| 138 |
+
}
|
| 139 |
+
],
|
| 140 |
+
"title": "Reason Code"
|
| 141 |
+
},
|
| 142 |
+
"uncertainty": {
|
| 143 |
+
"$ref": "#/$defs/TimingUncertainty"
|
| 144 |
+
},
|
| 145 |
+
"feasible_shift_intervals_ms": {
|
| 146 |
+
"anyOf": [
|
| 147 |
+
{
|
| 148 |
+
"items": {
|
| 149 |
+
"items": {
|
| 150 |
+
"type": "number"
|
| 151 |
+
},
|
| 152 |
+
"type": "array"
|
| 153 |
+
},
|
| 154 |
+
"type": "array"
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"type": "null"
|
| 158 |
+
}
|
| 159 |
+
],
|
| 160 |
+
"default": null,
|
| 161 |
+
"title": "Feasible Shift Intervals Ms"
|
| 162 |
+
}
|
| 163 |
+
},
|
| 164 |
+
"required": [
|
| 165 |
+
"key",
|
| 166 |
+
"value",
|
| 167 |
+
"unit",
|
| 168 |
+
"status",
|
| 169 |
+
"confidence",
|
| 170 |
+
"note",
|
| 171 |
+
"reason_code",
|
| 172 |
+
"uncertainty"
|
| 173 |
+
],
|
| 174 |
+
"title": "EvidenceMetric",
|
| 175 |
+
"type": "object"
|
| 176 |
+
},
|
| 177 |
+
"EvidenceRep": {
|
| 178 |
+
"additionalProperties": false,
|
| 179 |
+
"properties": {
|
| 180 |
+
"rep": {
|
| 181 |
+
"minimum": 1,
|
| 182 |
+
"title": "Rep",
|
| 183 |
+
"type": "integer"
|
| 184 |
+
},
|
| 185 |
+
"outcome": {
|
| 186 |
+
"enum": [
|
| 187 |
+
"hit",
|
| 188 |
+
"miss",
|
| 189 |
+
"unknown"
|
| 190 |
+
],
|
| 191 |
+
"title": "Outcome",
|
| 192 |
+
"type": "string"
|
| 193 |
+
},
|
| 194 |
+
"stepped": {
|
| 195 |
+
"anyOf": [
|
| 196 |
+
{
|
| 197 |
+
"type": "boolean"
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"type": "null"
|
| 201 |
+
}
|
| 202 |
+
],
|
| 203 |
+
"title": "Stepped"
|
| 204 |
+
},
|
| 205 |
+
"metrics": {
|
| 206 |
+
"items": {
|
| 207 |
+
"$ref": "#/$defs/EvidenceMetric"
|
| 208 |
+
},
|
| 209 |
+
"maxItems": 4,
|
| 210 |
+
"minItems": 4,
|
| 211 |
+
"title": "Metrics",
|
| 212 |
+
"type": "array"
|
| 213 |
+
},
|
| 214 |
+
"events": {
|
| 215 |
+
"items": {
|
| 216 |
+
"$ref": "#/$defs/EventEvidence"
|
| 217 |
+
},
|
| 218 |
+
"title": "Events",
|
| 219 |
+
"type": "array"
|
| 220 |
+
},
|
| 221 |
+
"outcome_method": {
|
| 222 |
+
"title": "Outcome Method",
|
| 223 |
+
"type": "string"
|
| 224 |
+
}
|
| 225 |
+
},
|
| 226 |
+
"required": [
|
| 227 |
+
"rep",
|
| 228 |
+
"outcome",
|
| 229 |
+
"stepped",
|
| 230 |
+
"metrics",
|
| 231 |
+
"events",
|
| 232 |
+
"outcome_method"
|
| 233 |
+
],
|
| 234 |
+
"title": "EvidenceRep",
|
| 235 |
+
"type": "object"
|
| 236 |
+
},
|
| 237 |
+
"PracticeContext": {
|
| 238 |
+
"additionalProperties": false,
|
| 239 |
+
"properties": {
|
| 240 |
+
"practice_type": {
|
| 241 |
+
"enum": [
|
| 242 |
+
"tee",
|
| 243 |
+
"soft_toss",
|
| 244 |
+
"front_toss",
|
| 245 |
+
"live",
|
| 246 |
+
"machine",
|
| 247 |
+
"unknown"
|
| 248 |
+
],
|
| 249 |
+
"title": "Practice Type",
|
| 250 |
+
"type": "string"
|
| 251 |
+
},
|
| 252 |
+
"pitch_speed_mps": {
|
| 253 |
+
"anyOf": [
|
| 254 |
+
{
|
| 255 |
+
"type": "number"
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"type": "null"
|
| 259 |
+
}
|
| 260 |
+
],
|
| 261 |
+
"title": "Pitch Speed Mps"
|
| 262 |
+
},
|
| 263 |
+
"pitch_location": {
|
| 264 |
+
"anyOf": [
|
| 265 |
+
{
|
| 266 |
+
"type": "string"
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"type": "null"
|
| 270 |
+
}
|
| 271 |
+
],
|
| 272 |
+
"title": "Pitch Location"
|
| 273 |
+
},
|
| 274 |
+
"source": {
|
| 275 |
+
"anyOf": [
|
| 276 |
+
{
|
| 277 |
+
"type": "string"
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"type": "null"
|
| 281 |
+
}
|
| 282 |
+
],
|
| 283 |
+
"title": "Source"
|
| 284 |
+
},
|
| 285 |
+
"provenance": {
|
| 286 |
+
"const": "supplied_by_uploader",
|
| 287 |
+
"title": "Provenance",
|
| 288 |
+
"type": "string"
|
| 289 |
+
}
|
| 290 |
+
},
|
| 291 |
+
"required": [
|
| 292 |
+
"practice_type",
|
| 293 |
+
"pitch_speed_mps",
|
| 294 |
+
"pitch_location",
|
| 295 |
+
"source",
|
| 296 |
+
"provenance"
|
| 297 |
+
],
|
| 298 |
+
"title": "PracticeContext",
|
| 299 |
+
"type": "object"
|
| 300 |
+
},
|
| 301 |
+
"TimingCapture": {
|
| 302 |
+
"additionalProperties": false,
|
| 303 |
+
"properties": {
|
| 304 |
+
"ok": {
|
| 305 |
+
"title": "Ok",
|
| 306 |
+
"type": "boolean"
|
| 307 |
+
},
|
| 308 |
+
"reasons": {
|
| 309 |
+
"items": {
|
| 310 |
+
"enum": [
|
| 311 |
+
"a_bit_blurry",
|
| 312 |
+
"a_bit_dark",
|
| 313 |
+
"low_fps",
|
| 314 |
+
"low_pose_confidence",
|
| 315 |
+
"multiple_people",
|
| 316 |
+
"no_person",
|
| 317 |
+
"partly_out_of_frame",
|
| 318 |
+
"person_too_small",
|
| 319 |
+
"player_switched",
|
| 320 |
+
"pose_confidence_fair",
|
| 321 |
+
"too_blurry",
|
| 322 |
+
"too_dark",
|
| 323 |
+
"very_low_fps",
|
| 324 |
+
"view_uncertain",
|
| 325 |
+
"wrong_view"
|
| 326 |
+
],
|
| 327 |
+
"type": "string"
|
| 328 |
+
},
|
| 329 |
+
"title": "Reasons",
|
| 330 |
+
"type": "array"
|
| 331 |
+
}
|
| 332 |
+
},
|
| 333 |
+
"required": [
|
| 334 |
+
"ok",
|
| 335 |
+
"reasons"
|
| 336 |
+
],
|
| 337 |
+
"title": "TimingCapture",
|
| 338 |
+
"type": "object"
|
| 339 |
+
},
|
| 340 |
+
"TimingUncertainty": {
|
| 341 |
+
"additionalProperties": false,
|
| 342 |
+
"properties": {
|
| 343 |
+
"interval_ms": {
|
| 344 |
+
"anyOf": [
|
| 345 |
+
{
|
| 346 |
+
"items": {
|
| 347 |
+
"type": "number"
|
| 348 |
+
},
|
| 349 |
+
"type": "array"
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"type": "null"
|
| 353 |
+
}
|
| 354 |
+
],
|
| 355 |
+
"title": "Interval Ms"
|
| 356 |
+
},
|
| 357 |
+
"kind": {
|
| 358 |
+
"enum": [
|
| 359 |
+
"frame_sensitivity",
|
| 360 |
+
"supplied_geometry_bound",
|
| 361 |
+
"unknown"
|
| 362 |
+
],
|
| 363 |
+
"title": "Kind",
|
| 364 |
+
"type": "string"
|
| 365 |
+
},
|
| 366 |
+
"accuracy_validated": {
|
| 367 |
+
"const": false,
|
| 368 |
+
"default": false,
|
| 369 |
+
"title": "Accuracy Validated",
|
| 370 |
+
"type": "boolean"
|
| 371 |
+
},
|
| 372 |
+
"note": {
|
| 373 |
+
"title": "Note",
|
| 374 |
+
"type": "string"
|
| 375 |
+
}
|
| 376 |
+
},
|
| 377 |
+
"required": [
|
| 378 |
+
"interval_ms",
|
| 379 |
+
"kind",
|
| 380 |
+
"note"
|
| 381 |
+
],
|
| 382 |
+
"title": "TimingUncertainty",
|
| 383 |
+
"type": "object"
|
| 384 |
+
}
|
| 385 |
+
},
|
| 386 |
+
"additionalProperties": false,
|
| 387 |
+
"properties": {
|
| 388 |
+
"schema_version": {
|
| 389 |
+
"const": "3.1",
|
| 390 |
+
"title": "Schema Version",
|
| 391 |
+
"type": "string"
|
| 392 |
+
},
|
| 393 |
+
"discipline": {
|
| 394 |
+
"const": "hitting",
|
| 395 |
+
"title": "Discipline",
|
| 396 |
+
"type": "string"
|
| 397 |
+
},
|
| 398 |
+
"time_basis": {
|
| 399 |
+
"const": "capture",
|
| 400 |
+
"title": "Time Basis",
|
| 401 |
+
"type": "string"
|
| 402 |
+
},
|
| 403 |
+
"capture": {
|
| 404 |
+
"$ref": "#/$defs/TimingCapture"
|
| 405 |
+
},
|
| 406 |
+
"context": {
|
| 407 |
+
"$ref": "#/$defs/PracticeContext"
|
| 408 |
+
},
|
| 409 |
+
"reps": {
|
| 410 |
+
"items": {
|
| 411 |
+
"$ref": "#/$defs/EvidenceRep"
|
| 412 |
+
},
|
| 413 |
+
"maxItems": 100,
|
| 414 |
+
"title": "Reps",
|
| 415 |
+
"type": "array"
|
| 416 |
+
}
|
| 417 |
+
},
|
| 418 |
+
"required": [
|
| 419 |
+
"schema_version",
|
| 420 |
+
"discipline",
|
| 421 |
+
"time_basis",
|
| 422 |
+
"capture",
|
| 423 |
+
"context",
|
| 424 |
+
"reps"
|
| 425 |
+
],
|
| 426 |
+
"title": "TimingEvidencePayload",
|
| 427 |
+
"type": "object"
|
| 428 |
+
}
|
examples/api_client.py
CHANGED
|
@@ -4,6 +4,7 @@ import json
|
|
| 4 |
import os
|
| 5 |
from pathlib import Path
|
| 6 |
import time
|
|
|
|
| 7 |
import requests
|
| 8 |
|
| 9 |
|
|
@@ -16,8 +17,12 @@ def main():
|
|
| 16 |
outputs = parser.add_mutually_exclusive_group()
|
| 17 |
outputs.add_argument("--coach-payload", action="store_true", help="Download the existing nine-field coach payload")
|
| 18 |
outputs.add_argument("--load-timing", action="store_true", help="Download the four-field version 3.0 timing payload using 2D only")
|
|
|
|
|
|
|
| 19 |
parser.add_argument("--wait-seconds", type=float, default=1900)
|
| 20 |
args = parser.parse_args()
|
|
|
|
|
|
|
| 21 |
key = os.environ.get("BASEBALL_API_KEY")
|
| 22 |
if not key: parser.error("Set BASEBALL_API_KEY")
|
| 23 |
base = args.url.rstrip("/")
|
|
@@ -28,8 +33,11 @@ def main():
|
|
| 28 |
options["measurement_backend"] = "2d"
|
| 29 |
with requests.Session() as client:
|
| 30 |
client.headers["Authorization"] = "Bearer " + key
|
| 31 |
-
with
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
| 33 |
data={"options": json.dumps(options)}, timeout=(10, 300))
|
| 34 |
response.raise_for_status()
|
| 35 |
job = response.json()
|
|
@@ -43,6 +51,8 @@ def main():
|
|
| 43 |
if status["status"] == "completed":
|
| 44 |
target = (job["load_timing_url"] if args.load_timing else
|
| 45 |
job["coach_payload_url"] if args.coach_payload else job["result_url"])
|
|
|
|
|
|
|
| 46 |
with client.get(base + target, stream=True, timeout=60) as result:
|
| 47 |
result.raise_for_status()
|
| 48 |
with args.output.open("wb") as out:
|
|
|
|
| 4 |
import os
|
| 5 |
from pathlib import Path
|
| 6 |
import time
|
| 7 |
+
from contextlib import ExitStack
|
| 8 |
import requests
|
| 9 |
|
| 10 |
|
|
|
|
| 17 |
outputs = parser.add_mutually_exclusive_group()
|
| 18 |
outputs.add_argument("--coach-payload", action="store_true", help="Download the existing nine-field coach payload")
|
| 19 |
outputs.add_argument("--load-timing", action="store_true", help="Download the four-field version 3.0 timing payload using 2D only")
|
| 20 |
+
parser.add_argument('--include-evidence', action='store_true', help='With --load-timing, get 3.1 event intervals, context and reason codes')
|
| 21 |
+
parser.add_argument('--secondary-video', type=Path, help='Optional second view; options must include stereo_tracking calibration')
|
| 22 |
parser.add_argument("--wait-seconds", type=float, default=1900)
|
| 23 |
args = parser.parse_args()
|
| 24 |
+
if args.include_evidence and not args.load_timing:
|
| 25 |
+
parser.error('--include-evidence requires --load-timing')
|
| 26 |
key = os.environ.get("BASEBALL_API_KEY")
|
| 27 |
if not key: parser.error("Set BASEBALL_API_KEY")
|
| 28 |
base = args.url.rstrip("/")
|
|
|
|
| 33 |
options["measurement_backend"] = "2d"
|
| 34 |
with requests.Session() as client:
|
| 35 |
client.headers["Authorization"] = "Bearer " + key
|
| 36 |
+
with ExitStack() as files:
|
| 37 |
+
uploads = {'video': (args.video.name, files.enter_context(args.video.open('rb')))}
|
| 38 |
+
if args.secondary_video:
|
| 39 |
+
uploads['secondary_video'] = (args.secondary_video.name, files.enter_context(args.secondary_video.open('rb')))
|
| 40 |
+
response = client.post(base + ('/v1/load-timing/analyses' if args.load_timing else '/v1/analyses'), files=uploads,
|
| 41 |
data={"options": json.dumps(options)}, timeout=(10, 300))
|
| 42 |
response.raise_for_status()
|
| 43 |
job = response.json()
|
|
|
|
| 51 |
if status["status"] == "completed":
|
| 52 |
target = (job["load_timing_url"] if args.load_timing else
|
| 53 |
job["coach_payload_url"] if args.coach_payload else job["result_url"])
|
| 54 |
+
if args.include_evidence:
|
| 55 |
+
target = job['load_timing_evidence_url']
|
| 56 |
with client.get(base + target, stream=True, timeout=60) as result:
|
| 57 |
result.raise_for_status()
|
| 58 |
with args.output.open("wb") as out:
|
notebooks/load_and_swing_test.ipynb
CHANGED
|
@@ -462,8 +462,8 @@
|
|
| 462 |
" return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\n",
|
| 463 |
"\n",
|
| 464 |
"\n",
|
| 465 |
-
"def build_load_timing_report(result, reviewed=None):\n",
|
| 466 |
-
" \"\"\"Extract timing estimates
|
| 467 |
"\n",
|
| 468 |
" reviewed maps rep numbers to visible event frames and their source. It is\n",
|
| 469 |
" empty by default. Manual labels never manufacture a clock or an early/late\n",
|
|
@@ -501,7 +501,8 @@
|
|
| 501 |
" if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\n",
|
| 502 |
" raise ValueError(f\"{key} must be an integer frame inside swing {rep['rep']}.\")\n",
|
| 503 |
" events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\n",
|
| 504 |
-
"
|
|
|
|
| 505 |
" if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\n",
|
| 506 |
" raise ValueError(\"Outcome must be hit, miss or unknown.\")\n",
|
| 507 |
" if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\n",
|
|
@@ -555,10 +556,41 @@
|
|
| 555 |
" else:\n",
|
| 556 |
" by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\n",
|
| 557 |
" \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
" by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\n",
|
| 559 |
" \"Only applies to misses.\" if outcome == \"hit\" else\n",
|
| 560 |
" \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\n",
|
| 561 |
" \"not_applicable\" if outcome == \"hit\" else \"unclear\")\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
" payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\n",
|
| 563 |
" \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\n",
|
| 564 |
" moments = {}\n",
|
|
@@ -579,10 +611,13 @@
|
|
| 579 |
" \"forward_swing_established\": forward, \"events\": moments,\n",
|
| 580 |
" \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\n",
|
| 581 |
" \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\n",
|
|
|
|
| 582 |
" return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\n",
|
| 583 |
" \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\n",
|
| 584 |
-
" \"capabilities\": {\"automatic_body_events\": True,
|
| 585 |
-
" \"
|
|
|
|
|
|
|
| 586 |
" \"diagnostics\": diagnostics,\n",
|
| 587 |
" \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\n",
|
| 588 |
" \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\n",
|
|
@@ -596,7 +631,7 @@
|
|
| 596 |
"TIMING_REPORT = build_load_timing_report(result, REVIEWED_EVENTS)\n",
|
| 597 |
"TIMING_REPORT[\"source_checkout\"] = SOURCE_CHECKOUT\n",
|
| 598 |
"TIMING_REPORT[\"run_context\"] = json.loads((JOB_ROOT / \"run-context.json\").read_text())\n",
|
| 599 |
-
"TIMING_HELPER_SOURCE = '\"\"\"Four experimental timing fields, without substituting body pose for impact.\\n\\nThis module is also embedded verbatim in the standalone Colab test notebook.\\nIt uses only the standard library, reads an existing 2D result, and never alters\\nthe API\\'s current nine-metric payload. Reviewed frames are optional test inputs.\\n\"\"\"\\nfrom copy import deepcopy\\nimport math\\n\\nLOAD_TIMING_VERSION = \"load-timing-test-v1\"\\nLOAD_TIMING_KEYS = (\"load_to_swing_ms\", \"foot_down_to_swing_ms\",\\n \"swing_duration_ms\", \"early_late_shift_ms\")\\nREVIEW_FIELDS = {\"source\", \"load_start_frame\", \"swing_start_frame\",\\n \"foot_contact_frame\", \"contact_frame\", \"closest_approach_frame\",\\n \"stepped\", \"outcome\"}\\n\\n\\ndef _timing_metric(key, note, status=\"unclear\", **extra):\\n return {\"key\": key, \"value\": None, \"unit\": \"ms\", \"status\": status,\\n \"confidence\": \"est\", \"note\": note, **extra}\\n\\n\\ndef _frame_event(frame, method, note):\\n return {\"frame\": frame, \"method\": method, \"estimated\": True, \"note\": note}\\n\\n\\ndef _timing_interval(track, rep, a, b, *, signed=False):\\n \"\"\"Use capture timestamps and expose \u00b11-frame sensitivity, not error bars.\"\"\"\\n diagnostic = {\"start_frame\": a, \"end_frame\": b,\\n \"sensitivity_scope\": \"each event shifted \u00b11 frame; detection error may be larger\"}\\n if a is None or b is None:\\n return None, \"Required event is missing.\", diagnostic\\n start, end = rep[\"start_frame\"], rep[\"end_frame\"]\\n if not start <= a <= end or not start <= b <= end:\\n return None, \"An event is outside this swing range.\", diagnostic\\n if not signed and b <= a:\\n return None, \"Event order does not give a positive duration.\", diagnostic\\n times = track[\"frames\"][\"t_s\"]\\n clock = times[start:end+1]\\n if (len(clock) < 2 or any(t is None or not math.isfinite(t) for t in clock)\\n or any(y <= x for x, y in zip(clock, clock[1:]))):\\n return None, \"Actual recording time is unknown or invalid; playback time is not used.\", diagnostic\\n steps = [y-x for x, y in zip(clock, clock[1:])]\\n diagnostic[\"capture_interval_ms\"] = [round(min(steps)*1000, 3), round(max(steps)*1000, 3)]\\n if max(steps) > 1.01/30 + 1e-6:\\n return None, \"Capture cadence is below nominal 30 FPS or has large frame gaps.\", diagnostic\\n a_window = [max(start, a-1), min(end, a+1)]\\n b_window = [max(start, b-1), min(end, b+1)]\\n low = (times[b_window[0]]-times[a_window[1]])*1000\\n high = (times[b_window[1]]-times[a_window[0]])*1000\\n value = (times[b]-times[a])*1000\\n diagnostic.update(event_shift_frames=[a_window, b_window],\\n frame_sensitivity_range_ms=[round(low, 3), round(high, 3)])\\n if signed:\\n diagnostic[\"order_resolved_under_frame_shift\"] = low > 0 or high < 0\\n note = (\"Event order can change within \u00b11 frame; this estimate cannot establish which happened first.\"\\n if low <= 0 <= high else \"Signed difference from capture timestamps.\")\\n return round(value, 3), note, diagnostic\\n width = (high-low)/value\\n diagnostic[\"relative_sensitivity_width\"] = width\\n diagnostic[\"relative_sensitivity_width_limit\"] = .5\\n if low <= 0 or width > .5+1e-9:\\n return None, \"Duration is unresolved under \u00b11-frame event shifts; inspect the event frames and sensitivity range.\", diagnostic\\n return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\\n\\n\\ndef build_load_timing_report(result, reviewed=None):\\n \"\"\"Extract timing estimates. Actual contact/closest approach are never inferred.\\n\\n reviewed maps rep numbers to visible event frames and their source. It is\\n empty by default. Manual labels never manufacture a clock or an early/late\\n correction. Every supplied frame must be inside its existing rep range.\\n \"\"\"\\n if reviewed is None:\\n reviewed = {}\\n if not isinstance(reviewed, dict):\\n raise ValueError(\"Reviewed events must be a dictionary keyed by swing number.\")\\n track = result[\"pose_track\"]\\n reps = track[\"reps\"]\\n normalized = {}\\n for key, label in reviewed.items():\\n if isinstance(key, bool) or not str(key).isdigit():\\n raise ValueError(\"Reviewed swing numbers must be positive integers.\")\\n number = int(key)\\n if number in normalized or number not in {r[\"rep\"] for r in reps}:\\n raise ValueError(\"Reviewed events name a duplicate or nonexistent swing.\")\\n if not isinstance(label, dict) or set(label)-REVIEW_FIELDS:\\n raise ValueError(\"Unknown reviewed-event fields.\")\\n if not isinstance(label.get(\"source\"), str) or not label[\"source\"].strip():\\n raise ValueError(\"Reviewed events require a source describing what was checked.\")\\n normalized[number] = label\\n capture = deepcopy(result[\"measurements\"][\"capture\"])\\n payload = {\"schema_version\": \"3.0\", \"discipline\": \"hitting\", \"time_basis\": \"capture\",\\n \"capture\": capture, \"reps\": []}\\n diagnostics = []\\n for rep in reps:\\n label = normalized.get(rep[\"rep\"], {})\\n events = deepcopy(rep[\"events\"])\\n for name in (\"load_start\", \"swing_start\", \"foot_contact\", \"contact\", \"closest_approach\"):\\n key = name+\"_frame\"\\n if key in label:\\n frame = label[key]\\n if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\\n raise ValueError(f\"{key} must be an integer frame inside swing {rep[\\'rep\\']}.\")\\n events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\\n outcome = label.get(\"outcome\", \"unknown\")\\n if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\\n raise ValueError(\"Outcome must be hit, miss or unknown.\")\\n if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\\n raise ValueError(\"A reviewed contact frame requires hit and no closest-approach frame.\")\\n if \"closest_approach_frame\" in label and outcome != \"miss\":\\n raise ValueError(\"A reviewed closest-approach frame requires miss.\")\\n stepped = label.get(\"stepped\", True if \"stride\" in events and \"foot_contact\" in events else None)\\n if stepped is not None and type(stepped) is not bool:\\n raise ValueError(\"Stepped must be true, false or unknown (None).\")\\n if stepped is False and \"foot_contact_frame\" in label:\\n raise ValueError(\"A no-step swing cannot have a reviewed step landing.\")\\n onset = events.get(\"swing_start\", {})\\n forward = (onset.get(\"method\", \"\").startswith(\"primary_swing_forward_hand_motion_\")\\n or onset.get(\"method\") == \"reviewed_video_frame\")\\n block = (\"Capture check failed: \" + \", \".join(capture.get(\"reasons\", []))\\n if not capture.get(\"ok\") else None)\\n if not forward:\\n block = block or \"Only generic hand movement was detected; forward swing start is not established.\"\\n by_key, intervals = {}, {}\\n def interval(key, first, last, description, signed=False, **extra):\\n a, b = events.get(first, {}).get(\"frame\"), events.get(last, {}).get(\"frame\")\\n value, reason, evidence = _timing_interval(track, rep, a, b, signed=signed)\\n intervals[key] = evidence\\n if block:\\n value, reason = None, block\\n elif a is None or b is None:\\n absent = [n for n in (first, last) if n not in events]\\n reason = \"Missing \" + \", \".join(absent) + \". \" + \" \".join(\\n rep.get(\"missing_events\", {}).get(n, \"\") for n in absent)\\n metric = _timing_metric(key, reason, **extra)\\n if value is not None:\\n metric.update(value=value, status=\"estimated\", note=description+\" \"+reason)\\n by_key[key] = metric\\n interval(\"load_to_swing_ms\", \"load_start\", \"swing_start\",\\n \"Preparation (backward hand load) to estimated forward swing start.\")\\n if stepped is False:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Player did not step.\", \"not_applicable\")\\n elif stepped is None:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Whether the player stepped is unknown; missing foot events do not prove no step.\")\\n else:\\n interval(\"foot_down_to_swing_ms\", \"foot_contact\", \"swing_start\",\\n \"First front-foot ground contact to estimated forward swing start; negative means swing began before landing.\", signed=True)\\n end_name = \"contact\" if outcome == \"hit\" else \"closest_approach\" if outcome == \"miss\" else None\\n # The 2D detector\\'s contact field is an arm-extension proxy. It is\\n # deliberately rejected here even when its score or timing looks good.\\n actual_end = end_name and events.get(end_name, {}).get(\"method\") == \"reviewed_video_frame\"\\n if actual_end:\\n interval(\"swing_duration_ms\", \"swing_start\", end_name,\\n \"Swing start to \" + (\"reviewed ball contact.\" if outcome == \"hit\" else \"reviewed closest bat-ball approach for a miss; this is a visual estimate.\"),\\n end_event=end_name)\\n else:\\n by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\\n \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\\n by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\\n \"Only applies to misses.\" if outcome == \"hit\" else\\n \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\\n \"not_applicable\" if outcome == \"hit\" else \"unclear\")\\n payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\\n \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\\n moments = {}\\n for name in (\"load_start\", \"foot_contact\", \"swing_start\"):\\n if name in events:\\n moments[name] = deepcopy(events[name])\\n proxy = rep[\"events\"].get(\"contact\")\\n if proxy:\\n moments[\"body_extension_proxy\"] = deepcopy(proxy)\\n if actual_end:\\n moments[\"reviewed_\"+end_name] = deepcopy(events[end_name])\\n for event in moments.values():\\n i = event[\"frame\"]\\n event[\"capture_time_s\"] = track[\"frames\"][\"t_s\"][i]\\n event[\"playback_time_s\"] = track[\"frames\"][\"playback_t_s\"][i]\\n diagnostics.append({\"rep\": rep[\"rep\"], \"start_frame\": rep[\"start_frame\"],\\n \"end_frame\": rep[\"end_frame\"], \"boundary_method\": rep[\"boundary_method\"],\\n \"forward_swing_established\": forward, \"events\": moments,\\n \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\\n \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\\n return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\\n \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\\n \"capabilities\": {\"automatic_body_events\": True, \"automatic_ball_contact\": False,\\n \"automatic_bat_ball_tracking\": False, \"early_late_estimate\": False},\\n \"diagnostics\": diagnostics,\\n \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\\n \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\\n \"No ready, pause, rushed, fault, priority or drill decisions are produced.\"]}\\n'\n",
|
| 600 |
"PREVIEW_HELPER_SOURCE = '\"\"\"Timing-only previews and neighboring event frames, using the original PTS.\"\"\"\\nimport argparse\\nfrom copy import deepcopy\\nfrom pathlib import Path\\n\\nfrom baseball_batting.ingest import iter_frames\\nfrom baseball_batting.storage import atomic_json, read_json, sha256_file\\nfrom tools.preview_swing_ranges import export_previews\\n\\n\\ndef export_timing_review(video, result, report, destination, max_clips=10):\\n import cv2\\n import numpy as np\\n destination = Path(destination)\\n destination.mkdir(parents=True, exist_ok=True)\\n filtered = deepcopy(result)\\n track = filtered[\"pose_track\"]\\n diagnostics = {row[\"rep\"]: row for row in report[\"diagnostics\"]}\\n for rep in track[\"reps\"]:\\n row = diagnostics[rep[\"rep\"]]\\n rep[\"events\"] = deepcopy(row[\"events\"])\\n # 3D is neither needed nor rendered by this timing test.\\n filtered.pop(\"experimental_body3d\", None)\\n manifest = export_previews(video, filtered, destination, max_clips=max_clips)\\n selections, needed = [], set()\\n for rep in track[\"reps\"][:max_clips]:\\n for name, event in rep[\"events\"].items():\\n center = event[\"frame\"]\\n frames = list(range(max(rep[\"start_frame\"], center-2), min(rep[\"end_frame\"], center+2)+1))\\n selections.append((rep, name, center, frames))\\n needed.update(frames)\\n snapshots = {}\\n if needed:\\n info = track[\"video\"]\\n decoded = iter_frames(video, info[\"rotation_degrees_applied\"], max_pixels=8294400)\\n try:\\n for index, pts, base, image in decoded:\\n if index > max(needed):\\n break\\n if index not in needed:\\n continue\\n expected = track[\"frames\"][\"playback_t_s\"][index]\\n if (pts is None or expected is None or (image.shape[1], image.shape[0]) != (info[\"width\"], info[\"height\"])\\n or abs(float(pts*base)-expected) > float(base)+1e-6):\\n raise ValueError(\"Event frames do not match the original video timestamps and size.\")\\n scale = min(1., 256/image.shape[1], 320/image.shape[0])\\n snapshots[index] = cv2.resize(image, (max(1, round(image.shape[1]*scale)),\\n max(1, round(image.shape[0]*scale))))\\n finally:\\n decoded.close()\\n if needed-set(snapshots):\\n raise ValueError(\"Source video is missing expected event frames.\")\\n records = []\\n for rep, name, center, frames in selections:\\n tiles = []\\n for index in frames:\\n image = snapshots[index]\\n canvas = np.full((380, 280, 3), 20, np.uint8)\\n x, y = (280-image.shape[1])//2, 42\\n canvas[y:y+image.shape[0], x:x+image.shape[1]] = image\\n color = (0, 230, 255) if index == center else (255, 255, 255)\\n cv2.putText(canvas, f\"frame {index}\" + (\" (event)\" if index == center else \"\"),\\n (8, 24), cv2.FONT_HERSHEY_SIMPLEX, .5, color, 1, cv2.LINE_AA)\\n real = track[\"frames\"][\"t_s\"][index]\\n stamp = f\"capture {real:.4f}s\" if real is not None else \"capture time unknown\"\\n cv2.putText(canvas, stamp, (8, 366), cv2.FONT_HERSHEY_SIMPLEX, .43, color, 1, cv2.LINE_AA)\\n tiles.append(canvas)\\n image = np.concatenate(tiles, axis=1)\\n filename = f\"swing-{rep[\\'rep\\']:03d}-{name}-frames.png\"\\n if not cv2.imwrite(str(destination/filename), image):\\n raise OSError(\"Could not write event frame review.\")\\n records.append({\"rep\": rep[\"rep\"], \"event\": name, \"frame\": center, \"neighbor_frames\": frames,\\n \"file\": filename, \"sha256\": sha256_file(destination/filename)})\\n manifest[\"event_snapshots\"] = records\\n manifest[\"purpose\"] = \"Load/timing event inspection; body_extension_proxy is not ball contact.\"\\n atomic_json(destination/\"previews.json\", manifest)\\n return manifest\\n\\n\\ndef main():\\n parser = argparse.ArgumentParser(description=__doc__)\\n parser.add_argument(\"--video\", required=True)\\n parser.add_argument(\"--result\", required=True)\\n parser.add_argument(\"--report\", required=True)\\n parser.add_argument(\"--output\", required=True)\\n parser.add_argument(\"--max-clips\", type=int, default=10)\\n args = parser.parse_args()\\n manifest = export_timing_review(args.video, read_json(args.result), read_json(args.report),\\n args.output, args.max_clips)\\n print(f\"Saved {len(manifest[\\'previews\\'])} preview records and {len(manifest[\\'event_snapshots\\'])} event frame sequences.\")\\n\\n\\nif __name__ == \"__main__\":\\n main()\\n'\n",
|
| 601 |
"TIMING_REPORT[\"helper_sha256\"] = {\n",
|
| 602 |
" \"calculations\": hashlib.sha256(TIMING_HELPER_SOURCE.encode()).hexdigest(),\n",
|
|
|
|
| 462 |
" return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\n",
|
| 463 |
"\n",
|
| 464 |
"\n",
|
| 465 |
+
"def build_load_timing_report(result, reviewed=None, ball_evidence=None):\n",
|
| 466 |
+
" \"\"\"Extract timing estimates from body events and separate bat/ball evidence.\n",
|
| 467 |
"\n",
|
| 468 |
" reviewed maps rep numbers to visible event frames and their source. It is\n",
|
| 469 |
" empty by default. Manual labels never manufacture a clock or an early/late\n",
|
|
|
|
| 501 |
" if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\n",
|
| 502 |
" raise ValueError(f\"{key} must be an integer frame inside swing {rep['rep']}.\")\n",
|
| 503 |
" events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\n",
|
| 504 |
+
" evidence = (ball_evidence or {}).get(rep['rep'], {})\n",
|
| 505 |
+
" outcome = label.get(\"outcome\", evidence.get('outcome', 'unknown'))\n",
|
| 506 |
" if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\n",
|
| 507 |
" raise ValueError(\"Outcome must be hit, miss or unknown.\")\n",
|
| 508 |
" if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\n",
|
|
|
|
| 556 |
" else:\n",
|
| 557 |
" by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\n",
|
| 558 |
" \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\n",
|
| 559 |
+
" if not actual_end and evidence.get('end_event') in {'contact', 'closest_approach'}:\n",
|
| 560 |
+
" frame = events.get('swing_start', {}).get('frame')\n",
|
| 561 |
+
" times = track['frames']['t_s']\n",
|
| 562 |
+
" value, reason = None, block\n",
|
| 563 |
+
" bounds = evidence.get('time_interval_s')\n",
|
| 564 |
+
" interval_evidence = {'end_method': evidence['method'], 'end_interval_s': bounds,\n",
|
| 565 |
+
" 'sensitivity_scope': 'endpoint interval plus \u00b11-frame start sensitivity; onset error unvalidated'}\n",
|
| 566 |
+
" if not block and frame is not None and times[frame] is not None and bounds:\n",
|
| 567 |
+
" a, b = max(rep['start_frame'], frame-1), min(rep['end_frame'], frame+1)\n",
|
| 568 |
+
" if times[a] is not None and times[b] is not None:\n",
|
| 569 |
+
" value = (evidence['time_s']-times[frame])*1000\n",
|
| 570 |
+
" low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000\n",
|
| 571 |
+
" interval_evidence['frame_sensitivity_range_ms'] = [round(low, 3), round(high, 3)]\n",
|
| 572 |
+
" if value <= 0 or low <= 0 or (high-low)/value > .5:\n",
|
| 573 |
+
" value, reason = None, 'Endpoint/start interval does not resolve swing duration.'\n",
|
| 574 |
+
" note = reason or ('Forward hand onset to '+evidence['end_event']+' from bat/ball observations. Event accuracy remains unvalidated.')\n",
|
| 575 |
+
" by_key['swing_duration_ms'] = _timing_metric('swing_duration_ms', note,\n",
|
| 576 |
+
" status='estimated' if value is not None else 'unclear', end_event=evidence['end_event'] if value is not None else None)\n",
|
| 577 |
+
" if value is not None:\n",
|
| 578 |
+
" by_key['swing_duration_ms']['value'] = round(value, 3)\n",
|
| 579 |
+
" intervals['swing_duration_ms'] = interval_evidence\n",
|
| 580 |
" by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\n",
|
| 581 |
" \"Only applies to misses.\" if outcome == \"hit\" else\n",
|
| 582 |
" \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\n",
|
| 583 |
" \"not_applicable\" if outcome == \"hit\" else \"unclear\")\n",
|
| 584 |
+
" if outcome == 'miss':\n",
|
| 585 |
+
" shift = evidence.get('shift', {})\n",
|
| 586 |
+
" value = shift.get('value') if not block else None\n",
|
| 587 |
+
" reason = block or shift.get('reason_code') or evidence.get('reason_code') or 'depth_unresolved'\n",
|
| 588 |
+
" by_key['early_late_shift_ms'] = _timing_metric('early_late_shift_ms',\n",
|
| 589 |
+
" 'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.' if value is not None else reason,\n",
|
| 590 |
+
" 'estimated' if value is not None else 'unclear')\n",
|
| 591 |
+
" if value is not None:\n",
|
| 592 |
+
" by_key['early_late_shift_ms']['value'] = value\n",
|
| 593 |
+
" intervals['early_late_shift_ms'] = deepcopy(shift)\n",
|
| 594 |
" payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\n",
|
| 595 |
" \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\n",
|
| 596 |
" moments = {}\n",
|
|
|
|
| 611 |
" \"forward_swing_established\": forward, \"events\": moments,\n",
|
| 612 |
" \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\n",
|
| 613 |
" \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\n",
|
| 614 |
+
" diagnostics[-1]['bat_ball_evidence'] = deepcopy(evidence)\n",
|
| 615 |
" return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\n",
|
| 616 |
" \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\n",
|
| 617 |
+
" \"capabilities\": {\"automatic_body_events\": True,\n",
|
| 618 |
+
" \"automatic_ball_contact\": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),\n",
|
| 619 |
+
" \"automatic_bat_ball_tracking\": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),\n",
|
| 620 |
+
" \"early_late_estimate\": any('shift' in e for e in (ball_evidence or {}).values())},\n",
|
| 621 |
" \"diagnostics\": diagnostics,\n",
|
| 622 |
" \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\n",
|
| 623 |
" \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\n",
|
|
|
|
| 631 |
"TIMING_REPORT = build_load_timing_report(result, REVIEWED_EVENTS)\n",
|
| 632 |
"TIMING_REPORT[\"source_checkout\"] = SOURCE_CHECKOUT\n",
|
| 633 |
"TIMING_REPORT[\"run_context\"] = json.loads((JOB_ROOT / \"run-context.json\").read_text())\n",
|
| 634 |
+
"TIMING_HELPER_SOURCE = '\"\"\"Four experimental timing fields, without substituting body pose for impact.\\n\\nThis module is also embedded verbatim in the standalone Colab test notebook.\\nIt uses only the standard library, reads an existing 2D result, and never alters\\nthe API\\'s current nine-metric payload. Reviewed frames are optional test inputs.\\n\"\"\"\\nfrom copy import deepcopy\\nimport math\\n\\nLOAD_TIMING_VERSION = \"load-timing-test-v1\"\\nLOAD_TIMING_KEYS = (\"load_to_swing_ms\", \"foot_down_to_swing_ms\",\\n \"swing_duration_ms\", \"early_late_shift_ms\")\\nREVIEW_FIELDS = {\"source\", \"load_start_frame\", \"swing_start_frame\",\\n \"foot_contact_frame\", \"contact_frame\", \"closest_approach_frame\",\\n \"stepped\", \"outcome\"}\\n\\n\\ndef _timing_metric(key, note, status=\"unclear\", **extra):\\n return {\"key\": key, \"value\": None, \"unit\": \"ms\", \"status\": status,\\n \"confidence\": \"est\", \"note\": note, **extra}\\n\\n\\ndef _frame_event(frame, method, note):\\n return {\"frame\": frame, \"method\": method, \"estimated\": True, \"note\": note}\\n\\n\\ndef _timing_interval(track, rep, a, b, *, signed=False):\\n \"\"\"Use capture timestamps and expose \u00b11-frame sensitivity, not error bars.\"\"\"\\n diagnostic = {\"start_frame\": a, \"end_frame\": b,\\n \"sensitivity_scope\": \"each event shifted \u00b11 frame; detection error may be larger\"}\\n if a is None or b is None:\\n return None, \"Required event is missing.\", diagnostic\\n start, end = rep[\"start_frame\"], rep[\"end_frame\"]\\n if not start <= a <= end or not start <= b <= end:\\n return None, \"An event is outside this swing range.\", diagnostic\\n if not signed and b <= a:\\n return None, \"Event order does not give a positive duration.\", diagnostic\\n times = track[\"frames\"][\"t_s\"]\\n clock = times[start:end+1]\\n if (len(clock) < 2 or any(t is None or not math.isfinite(t) for t in clock)\\n or any(y <= x for x, y in zip(clock, clock[1:]))):\\n return None, \"Actual recording time is unknown or invalid; playback time is not used.\", diagnostic\\n steps = [y-x for x, y in zip(clock, clock[1:])]\\n diagnostic[\"capture_interval_ms\"] = [round(min(steps)*1000, 3), round(max(steps)*1000, 3)]\\n if max(steps) > 1.01/30 + 1e-6:\\n return None, \"Capture cadence is below nominal 30 FPS or has large frame gaps.\", diagnostic\\n a_window = [max(start, a-1), min(end, a+1)]\\n b_window = [max(start, b-1), min(end, b+1)]\\n low = (times[b_window[0]]-times[a_window[1]])*1000\\n high = (times[b_window[1]]-times[a_window[0]])*1000\\n value = (times[b]-times[a])*1000\\n diagnostic.update(event_shift_frames=[a_window, b_window],\\n frame_sensitivity_range_ms=[round(low, 3), round(high, 3)])\\n if signed:\\n diagnostic[\"order_resolved_under_frame_shift\"] = low > 0 or high < 0\\n note = (\"Event order can change within \u00b11 frame; this estimate cannot establish which happened first.\"\\n if low <= 0 <= high else \"Signed difference from capture timestamps.\")\\n return round(value, 3), note, diagnostic\\n width = (high-low)/value\\n diagnostic[\"relative_sensitivity_width\"] = width\\n diagnostic[\"relative_sensitivity_width_limit\"] = .5\\n if low <= 0 or width > .5+1e-9:\\n return None, \"Duration is unresolved under \u00b11-frame event shifts; inspect the event frames and sensitivity range.\", diagnostic\\n return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\\n\\n\\ndef build_load_timing_report(result, reviewed=None, ball_evidence=None):\\n \"\"\"Extract timing estimates from body events and separate bat/ball evidence.\\n\\n reviewed maps rep numbers to visible event frames and their source. It is\\n empty by default. Manual labels never manufacture a clock or an early/late\\n correction. Every supplied frame must be inside its existing rep range.\\n \"\"\"\\n if reviewed is None:\\n reviewed = {}\\n if not isinstance(reviewed, dict):\\n raise ValueError(\"Reviewed events must be a dictionary keyed by swing number.\")\\n track = result[\"pose_track\"]\\n reps = track[\"reps\"]\\n normalized = {}\\n for key, label in reviewed.items():\\n if isinstance(key, bool) or not str(key).isdigit():\\n raise ValueError(\"Reviewed swing numbers must be positive integers.\")\\n number = int(key)\\n if number in normalized or number not in {r[\"rep\"] for r in reps}:\\n raise ValueError(\"Reviewed events name a duplicate or nonexistent swing.\")\\n if not isinstance(label, dict) or set(label)-REVIEW_FIELDS:\\n raise ValueError(\"Unknown reviewed-event fields.\")\\n if not isinstance(label.get(\"source\"), str) or not label[\"source\"].strip():\\n raise ValueError(\"Reviewed events require a source describing what was checked.\")\\n normalized[number] = label\\n capture = deepcopy(result[\"measurements\"][\"capture\"])\\n payload = {\"schema_version\": \"3.0\", \"discipline\": \"hitting\", \"time_basis\": \"capture\",\\n \"capture\": capture, \"reps\": []}\\n diagnostics = []\\n for rep in reps:\\n label = normalized.get(rep[\"rep\"], {})\\n events = deepcopy(rep[\"events\"])\\n for name in (\"load_start\", \"swing_start\", \"foot_contact\", \"contact\", \"closest_approach\"):\\n key = name+\"_frame\"\\n if key in label:\\n frame = label[key]\\n if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\\n raise ValueError(f\"{key} must be an integer frame inside swing {rep[\\'rep\\']}.\")\\n events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\\n evidence = (ball_evidence or {}).get(rep[\\'rep\\'], {})\\n outcome = label.get(\"outcome\", evidence.get(\\'outcome\\', \\'unknown\\'))\\n if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\\n raise ValueError(\"Outcome must be hit, miss or unknown.\")\\n if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\\n raise ValueError(\"A reviewed contact frame requires hit and no closest-approach frame.\")\\n if \"closest_approach_frame\" in label and outcome != \"miss\":\\n raise ValueError(\"A reviewed closest-approach frame requires miss.\")\\n stepped = label.get(\"stepped\", True if \"stride\" in events and \"foot_contact\" in events else None)\\n if stepped is not None and type(stepped) is not bool:\\n raise ValueError(\"Stepped must be true, false or unknown (None).\")\\n if stepped is False and \"foot_contact_frame\" in label:\\n raise ValueError(\"A no-step swing cannot have a reviewed step landing.\")\\n onset = events.get(\"swing_start\", {})\\n forward = (onset.get(\"method\", \"\").startswith(\"primary_swing_forward_hand_motion_\")\\n or onset.get(\"method\") == \"reviewed_video_frame\")\\n block = (\"Capture check failed: \" + \", \".join(capture.get(\"reasons\", []))\\n if not capture.get(\"ok\") else None)\\n if not forward:\\n block = block or \"Only generic hand movement was detected; forward swing start is not established.\"\\n by_key, intervals = {}, {}\\n def interval(key, first, last, description, signed=False, **extra):\\n a, b = events.get(first, {}).get(\"frame\"), events.get(last, {}).get(\"frame\")\\n value, reason, evidence = _timing_interval(track, rep, a, b, signed=signed)\\n intervals[key] = evidence\\n if block:\\n value, reason = None, block\\n elif a is None or b is None:\\n absent = [n for n in (first, last) if n not in events]\\n reason = \"Missing \" + \", \".join(absent) + \". \" + \" \".join(\\n rep.get(\"missing_events\", {}).get(n, \"\") for n in absent)\\n metric = _timing_metric(key, reason, **extra)\\n if value is not None:\\n metric.update(value=value, status=\"estimated\", note=description+\" \"+reason)\\n by_key[key] = metric\\n interval(\"load_to_swing_ms\", \"load_start\", \"swing_start\",\\n \"Preparation (backward hand load) to estimated forward swing start.\")\\n if stepped is False:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Player did not step.\", \"not_applicable\")\\n elif stepped is None:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Whether the player stepped is unknown; missing foot events do not prove no step.\")\\n else:\\n interval(\"foot_down_to_swing_ms\", \"foot_contact\", \"swing_start\",\\n \"First front-foot ground contact to estimated forward swing start; negative means swing began before landing.\", signed=True)\\n end_name = \"contact\" if outcome == \"hit\" else \"closest_approach\" if outcome == \"miss\" else None\\n # The 2D detector\\'s contact field is an arm-extension proxy. It is\\n # deliberately rejected here even when its score or timing looks good.\\n actual_end = end_name and events.get(end_name, {}).get(\"method\") == \"reviewed_video_frame\"\\n if actual_end:\\n interval(\"swing_duration_ms\", \"swing_start\", end_name,\\n \"Swing start to \" + (\"reviewed ball contact.\" if outcome == \"hit\" else \"reviewed closest bat-ball approach for a miss; this is a visual estimate.\"),\\n end_event=end_name)\\n else:\\n by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\\n \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\\n if not actual_end and evidence.get(\\'end_event\\') in {\\'contact\\', \\'closest_approach\\'}:\\n frame = events.get(\\'swing_start\\', {}).get(\\'frame\\')\\n times = track[\\'frames\\'][\\'t_s\\']\\n value, reason = None, block\\n bounds = evidence.get(\\'time_interval_s\\')\\n interval_evidence = {\\'end_method\\': evidence[\\'method\\'], \\'end_interval_s\\': bounds,\\n \\'sensitivity_scope\\': \\'endpoint interval plus \u00b11-frame start sensitivity; onset error unvalidated\\'}\\n if not block and frame is not None and times[frame] is not None and bounds:\\n a, b = max(rep[\\'start_frame\\'], frame-1), min(rep[\\'end_frame\\'], frame+1)\\n if times[a] is not None and times[b] is not None:\\n value = (evidence[\\'time_s\\']-times[frame])*1000\\n low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000\\n interval_evidence[\\'frame_sensitivity_range_ms\\'] = [round(low, 3), round(high, 3)]\\n if value <= 0 or low <= 0 or (high-low)/value > .5:\\n value, reason = None, \\'Endpoint/start interval does not resolve swing duration.\\'\\n note = reason or (\\'Forward hand onset to \\'+evidence[\\'end_event\\']+\\' from bat/ball observations. Event accuracy remains unvalidated.\\')\\n by_key[\\'swing_duration_ms\\'] = _timing_metric(\\'swing_duration_ms\\', note,\\n status=\\'estimated\\' if value is not None else \\'unclear\\', end_event=evidence[\\'end_event\\'] if value is not None else None)\\n if value is not None:\\n by_key[\\'swing_duration_ms\\'][\\'value\\'] = round(value, 3)\\n intervals[\\'swing_duration_ms\\'] = interval_evidence\\n by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\\n \"Only applies to misses.\" if outcome == \"hit\" else\\n \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\\n \"not_applicable\" if outcome == \"hit\" else \"unclear\")\\n if outcome == \\'miss\\':\\n shift = evidence.get(\\'shift\\', {})\\n value = shift.get(\\'value\\') if not block else None\\n reason = block or shift.get(\\'reason_code\\') or evidence.get(\\'reason_code\\') or \\'depth_unresolved\\'\\n by_key[\\'early_late_shift_ms\\'] = _timing_metric(\\'early_late_shift_ms\\',\\n \\'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.\\' if value is not None else reason,\\n \\'estimated\\' if value is not None else \\'unclear\\')\\n if value is not None:\\n by_key[\\'early_late_shift_ms\\'][\\'value\\'] = value\\n intervals[\\'early_late_shift_ms\\'] = deepcopy(shift)\\n payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\\n \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\\n moments = {}\\n for name in (\"load_start\", \"foot_contact\", \"swing_start\"):\\n if name in events:\\n moments[name] = deepcopy(events[name])\\n proxy = rep[\"events\"].get(\"contact\")\\n if proxy:\\n moments[\"body_extension_proxy\"] = deepcopy(proxy)\\n if actual_end:\\n moments[\"reviewed_\"+end_name] = deepcopy(events[end_name])\\n for event in moments.values():\\n i = event[\"frame\"]\\n event[\"capture_time_s\"] = track[\"frames\"][\"t_s\"][i]\\n event[\"playback_time_s\"] = track[\"frames\"][\"playback_t_s\"][i]\\n diagnostics.append({\"rep\": rep[\"rep\"], \"start_frame\": rep[\"start_frame\"],\\n \"end_frame\": rep[\"end_frame\"], \"boundary_method\": rep[\"boundary_method\"],\\n \"forward_swing_established\": forward, \"events\": moments,\\n \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\\n \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\\n diagnostics[-1][\\'bat_ball_evidence\\'] = deepcopy(evidence)\\n return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\\n \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\\n \"capabilities\": {\"automatic_body_events\": True,\\n \"automatic_ball_contact\": any(e.get(\\'reason_code\\') != \\'tracking_models_unavailable\\' for e in (ball_evidence or {}).values()),\\n \"automatic_bat_ball_tracking\": any(e.get(\\'reason_code\\') != \\'tracking_models_unavailable\\' for e in (ball_evidence or {}).values()),\\n \"early_late_estimate\": any(\\'shift\\' in e for e in (ball_evidence or {}).values())},\\n \"diagnostics\": diagnostics,\\n \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\\n \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\\n \"No ready, pause, rushed, fault, priority or drill decisions are produced.\"]}\\n'\n",
|
| 635 |
"PREVIEW_HELPER_SOURCE = '\"\"\"Timing-only previews and neighboring event frames, using the original PTS.\"\"\"\\nimport argparse\\nfrom copy import deepcopy\\nfrom pathlib import Path\\n\\nfrom baseball_batting.ingest import iter_frames\\nfrom baseball_batting.storage import atomic_json, read_json, sha256_file\\nfrom tools.preview_swing_ranges import export_previews\\n\\n\\ndef export_timing_review(video, result, report, destination, max_clips=10):\\n import cv2\\n import numpy as np\\n destination = Path(destination)\\n destination.mkdir(parents=True, exist_ok=True)\\n filtered = deepcopy(result)\\n track = filtered[\"pose_track\"]\\n diagnostics = {row[\"rep\"]: row for row in report[\"diagnostics\"]}\\n for rep in track[\"reps\"]:\\n row = diagnostics[rep[\"rep\"]]\\n rep[\"events\"] = deepcopy(row[\"events\"])\\n # 3D is neither needed nor rendered by this timing test.\\n filtered.pop(\"experimental_body3d\", None)\\n manifest = export_previews(video, filtered, destination, max_clips=max_clips)\\n selections, needed = [], set()\\n for rep in track[\"reps\"][:max_clips]:\\n for name, event in rep[\"events\"].items():\\n center = event[\"frame\"]\\n frames = list(range(max(rep[\"start_frame\"], center-2), min(rep[\"end_frame\"], center+2)+1))\\n selections.append((rep, name, center, frames))\\n needed.update(frames)\\n snapshots = {}\\n if needed:\\n info = track[\"video\"]\\n decoded = iter_frames(video, info[\"rotation_degrees_applied\"], max_pixels=8294400)\\n try:\\n for index, pts, base, image in decoded:\\n if index > max(needed):\\n break\\n if index not in needed:\\n continue\\n expected = track[\"frames\"][\"playback_t_s\"][index]\\n if (pts is None or expected is None or (image.shape[1], image.shape[0]) != (info[\"width\"], info[\"height\"])\\n or abs(float(pts*base)-expected) > float(base)+1e-6):\\n raise ValueError(\"Event frames do not match the original video timestamps and size.\")\\n scale = min(1., 256/image.shape[1], 320/image.shape[0])\\n snapshots[index] = cv2.resize(image, (max(1, round(image.shape[1]*scale)),\\n max(1, round(image.shape[0]*scale))))\\n finally:\\n decoded.close()\\n if needed-set(snapshots):\\n raise ValueError(\"Source video is missing expected event frames.\")\\n records = []\\n for rep, name, center, frames in selections:\\n tiles = []\\n for index in frames:\\n image = snapshots[index]\\n canvas = np.full((380, 280, 3), 20, np.uint8)\\n x, y = (280-image.shape[1])//2, 42\\n canvas[y:y+image.shape[0], x:x+image.shape[1]] = image\\n color = (0, 230, 255) if index == center else (255, 255, 255)\\n cv2.putText(canvas, f\"frame {index}\" + (\" (event)\" if index == center else \"\"),\\n (8, 24), cv2.FONT_HERSHEY_SIMPLEX, .5, color, 1, cv2.LINE_AA)\\n real = track[\"frames\"][\"t_s\"][index]\\n stamp = f\"capture {real:.4f}s\" if real is not None else \"capture time unknown\"\\n cv2.putText(canvas, stamp, (8, 366), cv2.FONT_HERSHEY_SIMPLEX, .43, color, 1, cv2.LINE_AA)\\n tiles.append(canvas)\\n image = np.concatenate(tiles, axis=1)\\n filename = f\"swing-{rep[\\'rep\\']:03d}-{name}-frames.png\"\\n if not cv2.imwrite(str(destination/filename), image):\\n raise OSError(\"Could not write event frame review.\")\\n records.append({\"rep\": rep[\"rep\"], \"event\": name, \"frame\": center, \"neighbor_frames\": frames,\\n \"file\": filename, \"sha256\": sha256_file(destination/filename)})\\n manifest[\"event_snapshots\"] = records\\n manifest[\"purpose\"] = \"Load/timing event inspection; body_extension_proxy is not ball contact.\"\\n atomic_json(destination/\"previews.json\", manifest)\\n return manifest\\n\\n\\ndef main():\\n parser = argparse.ArgumentParser(description=__doc__)\\n parser.add_argument(\"--video\", required=True)\\n parser.add_argument(\"--result\", required=True)\\n parser.add_argument(\"--report\", required=True)\\n parser.add_argument(\"--output\", required=True)\\n parser.add_argument(\"--max-clips\", type=int, default=10)\\n args = parser.parse_args()\\n manifest = export_timing_review(args.video, read_json(args.result), read_json(args.report),\\n args.output, args.max_clips)\\n print(f\"Saved {len(manifest[\\'previews\\'])} preview records and {len(manifest[\\'event_snapshots\\'])} event frame sequences.\")\\n\\n\\nif __name__ == \"__main__\":\\n main()\\n'\n",
|
| 636 |
"TIMING_REPORT[\"helper_sha256\"] = {\n",
|
| 637 |
" \"calculations\": hashlib.sha256(TIMING_HELPER_SOURCE.encode()).hexdigest(),\n",
|
requirements-tracking-export.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Build-time only: the server runs the exported models with ONNX Runtime CUDA.
|
| 2 |
+
ultralytics==8.4.175
|
| 3 |
+
onnx==1.17.0
|
| 4 |
+
numpy==2.2.6
|
| 5 |
+
opencv-python-headless==4.11.0.86
|
tests/test_2d_regressions.py
CHANGED
|
@@ -174,7 +174,7 @@ def test_outdoor_reset_never_replaces_the_actual_swing(outdoor, declared):
|
|
| 174 |
assert events["contact"]["estimated"] is True
|
| 175 |
assert "primary" in events["contact"]["method"]
|
| 176 |
assert "finish" not in events # no finish fabricated from the end of the clip
|
| 177 |
-
assert method["version"] == "batting-2d-
|
| 178 |
assert reps[0]["events_ms"] == {}
|
| 179 |
assert all("t_s" not in event for event in events.values())
|
| 180 |
# The feet overlap in projection at the real swing, unlike the later reset.
|
|
|
|
| 174 |
assert events["contact"]["estimated"] is True
|
| 175 |
assert "primary" in events["contact"]["method"]
|
| 176 |
assert "finish" not in events # no finish fabricated from the end of the clip
|
| 177 |
+
assert method["version"] == "batting-2d-v6"
|
| 178 |
assert reps[0]["events_ms"] == {}
|
| 179 |
assert all("t_s" not in event for event in events.values())
|
| 180 |
# The feet overlap in projection at the real swing, unlike the later reset.
|
tests/test_api.py
CHANGED
|
@@ -29,6 +29,7 @@ def wait_until(predicate, timeout=5):
|
|
| 29 |
|
| 30 |
|
| 31 |
def settings(tmp_path, **overrides):
|
|
|
|
| 32 |
return ApiSettings(api_key=KEY, data_root=tmp_path, minimum_free_bytes=0, **overrides)
|
| 33 |
|
| 34 |
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
def settings(tmp_path, **overrides):
|
| 32 |
+
overrides.setdefault('model_root', tmp_path/'models')
|
| 33 |
return ApiSettings(api_key=KEY, data_root=tmp_path, minimum_free_bytes=0, **overrides)
|
| 34 |
|
| 35 |
|
tests/test_bat_ball_timing.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
from baseball_batting.bat_ball_timing import visual_contact, physical_shift
|
| 5 |
+
from baseball_batting.api_contract import AnalysisInput
|
| 6 |
+
from baseball_batting.load_timing import build_load_timing_report
|
| 7 |
+
from baseball_batting.timing_evidence import build_timing_evidence, TimingEvidencePayload
|
| 8 |
+
from test_load_timing import timing_result, metrics
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def contact_sequence(*, tee=False, fps=120):
|
| 12 |
+
result = timing_result(fps)
|
| 13 |
+
track = result['pose_track']; rep = track['reps'][0]
|
| 14 |
+
rep['events']['finish'] = {'frame': 125, 'method': 'test'}
|
| 15 |
+
rows = []
|
| 16 |
+
# A directly observed ball changes direction at frame 100; bat crosses
|
| 17 |
+
# that location. This is a geometry fixture, not an accuracy benchmark.
|
| 18 |
+
for i, t in enumerate(track['frames']['t_s']):
|
| 19 |
+
phase = t-100/fps
|
| 20 |
+
xy = [100 + (0 if tee else 300*phase), 80] if phase <= 0 else [100-400*phase, 80-300*phase]
|
| 21 |
+
rows.append({'frame': i, 'capture_time_s': t,
|
| 22 |
+
'bat': [{'points': [[100-800*phase, 20], [100-800*phase, 130]]}],
|
| 23 |
+
'ball': [{'point': xy, 'radius_px': 2.}]})
|
| 24 |
+
return result, {'frames': rows}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize('tee', [False, True])
|
| 28 |
+
def test_actual_visual_endpoint_supplies_duration_and_rich_event(tee):
|
| 29 |
+
result, observed = contact_sequence(tee=tee)
|
| 30 |
+
track = result['pose_track']; rep = track['reps'][0]
|
| 31 |
+
hit = visual_contact(observed, track, rep, practice_type='tee' if tee else 'live')
|
| 32 |
+
assert hit['outcome'] == 'hit'
|
| 33 |
+
assert hit['time_interval_s'][0] <= 100/120 <= hit['time_interval_s'][1]
|
| 34 |
+
report = build_load_timing_report(result, ball_evidence={1: hit})
|
| 35 |
+
values = metrics(report)
|
| 36 |
+
assert values['swing_duration_ms']['value'] == pytest.approx(333.333)
|
| 37 |
+
assert values['swing_duration_ms']['end_event'] == 'contact'
|
| 38 |
+
assert values['early_late_shift_ms']['status'] == 'not_applicable'
|
| 39 |
+
rich = TimingEvidencePayload.model_validate(build_timing_evidence(report, result, AnalysisInput(practice_type='tee' if tee else 'live')))
|
| 40 |
+
assert rich.legacy() == report['payload']
|
| 41 |
+
assert all(e.event != 'body_extension_proxy' for e in rich.reps[0].events)
|
| 42 |
+
endpoint = next(e for e in rich.reps[0].events if e.event == 'contact')
|
| 43 |
+
assert endpoint.accuracy_validated is False
|
| 44 |
+
assert ('tee_ball_departure' in endpoint.method) is tee
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@pytest.mark.parametrize('failure', ['no_bat', 'gap', 'no_deflection', 'two_balls', 'tee_without_context', 'clock', 'low_fps'])
|
| 48 |
+
def test_projection_overlap_or_missing_objects_never_proves_a_hit_or_miss(failure):
|
| 49 |
+
result, observed = contact_sequence(tee=failure == 'tee_without_context', fps=25 if failure == 'low_fps' else 120)
|
| 50 |
+
if failure == 'no_bat':
|
| 51 |
+
for r in observed['frames']: r['bat'] = []
|
| 52 |
+
if failure == 'gap':
|
| 53 |
+
for i in range(97, 105): observed['frames'][i]['ball'] = []
|
| 54 |
+
if failure == 'no_deflection':
|
| 55 |
+
for i, r in enumerate(observed['frames']): r['ball'][0]['point'] = [100+(i-100)*3, 80]
|
| 56 |
+
if failure == 'two_balls':
|
| 57 |
+
for r in observed['frames']: r['ball'].append({'point': [p+.7 for p in r['ball'][0]['point']], 'radius_px': 2.})
|
| 58 |
+
if failure == 'clock': result['pose_track']['frames']['t_s'] = [None]*150
|
| 59 |
+
hit = visual_contact(observed, result['pose_track'], result['pose_track']['reps'][0])
|
| 60 |
+
assert hit['outcome'] == 'unknown' and hit['reason_code']
|
| 61 |
+
report = build_load_timing_report(result, ball_evidence={1: hit})
|
| 62 |
+
assert metrics(report)['swing_duration_ms']['value'] is None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def paths(crossing=.45, fps=60, speed=4.):
|
| 66 |
+
times = np.arange(fps+1)/fps
|
| 67 |
+
bat = np.zeros((len(times),2,3)); bat[:,:,0] = speed*(times[:,None]-crossing)
|
| 68 |
+
bat[:,1,1] = 1.; bat[:,:,2] = 5.
|
| 69 |
+
ball = np.column_stack([np.zeros(len(times)), np.full(len(times),.7), 5+speed*(times-.55)])
|
| 70 |
+
return times, bat, ball
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def shift(t,b,p,**overrides):
|
| 74 |
+
kw = dict(bat_radius_m=.03, ball_radius_m=.0366, position_bound_m=.001)
|
| 75 |
+
return physical_shift(t,b,p,**(kw|overrides))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize('crossing,sign', [(.45,1), (.65,-1)])
|
| 79 |
+
def test_timing_shift_sign_and_certified_feasible_value(crossing,sign):
|
| 80 |
+
t,b,p=paths(crossing)
|
| 81 |
+
out=shift(t,b,p)
|
| 82 |
+
assert out['reason_code'] is None
|
| 83 |
+
assert sign*out['value'] > 0
|
| 84 |
+
assert abs(out['value']-(.55-crossing)*1000) < 35
|
| 85 |
+
assert len(out['feasible_shift_intervals_ms']) == 1
|
| 86 |
+
a,z=out['feasible_shift_intervals_ms'][0]
|
| 87 |
+
assert a <= out['value'] <= z
|
| 88 |
+
assert out['selection_policy'] == 'closest_to_zero_certified_feasible_shift'
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_realistic_pitch_and_bat_speed_fit_search_budget():
|
| 92 |
+
t,b,p=paths(speed=40.)
|
| 93 |
+
out=shift(t,b,p)
|
| 94 |
+
assert out['value'] is not None and out['value'] > 0
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_unreachable_is_limited_to_observed_window_not_a_global_claim():
|
| 98 |
+
t,b,p=paths(); p[:,1]=2
|
| 99 |
+
out=shift(t,b,p)
|
| 100 |
+
assert out['value'] is None
|
| 101 |
+
assert out['reason_code'] == 'no_feasible_shift_in_observed_window'
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@pytest.mark.parametrize('failure,reason', [('gap','spatial_track_incomplete'),('nan','spatial_track_incomplete'),
|
| 105 |
+
('budget','search_resolution_insufficient'),('bound','shift_unresolved_under_position_error'),
|
| 106 |
+
('edge','shift_search_boundary'),('zero','ambiguous_time_shift')])
|
| 107 |
+
def test_unresolved_search_never_invents_shift(failure,reason):
|
| 108 |
+
t,b,p=paths(crossing=.55 if failure=='zero' else .31 if failure=='edge' else .45)
|
| 109 |
+
kw={}
|
| 110 |
+
if failure=='gap': t=t[::3]; b=b[::3]; p=p[::3]
|
| 111 |
+
if failure=='nan': b[20,0,0]=np.nan
|
| 112 |
+
if failure=='budget': kw['max_cells']=10
|
| 113 |
+
if failure=='bound': kw['position_bound_m']=.03
|
| 114 |
+
out=shift(t,b,p,**kw)
|
| 115 |
+
assert out['value'] is None and out['reason_code']==reason
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_disconnected_shift_bands_are_retained_without_average():
|
| 119 |
+
t,b,p=paths(); b[:,:,0] = (20*(t-.3)*(t-.8))[:,None]
|
| 120 |
+
out=shift(t,b,p,max_shift_s=.4)
|
| 121 |
+
assert out['value'] is None and out['reason_code']=='ambiguous_time_shift'
|
| 122 |
+
assert len(out['feasible_shift_intervals_ms'])==2
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_background_ball_bounce_near_stationary_bat_is_not_swing_contact():
|
| 126 |
+
result,observed=contact_sequence()
|
| 127 |
+
for row in observed['frames']:
|
| 128 |
+
row['bat']=[{'points':[[100,20],[100,130]]}]
|
| 129 |
+
out=visual_contact(observed,result['pose_track'],result['pose_track']['reps'][0])
|
| 130 |
+
assert out['outcome']=='unknown'
|
tests/test_load_timing_api.py
CHANGED
|
@@ -44,7 +44,8 @@ def test_timing_contract_schema_and_openapi_are_consistent(tmp_path):
|
|
| 44 |
app = create_app(settings(tmp_path), fake_service(settings(tmp_path)))
|
| 45 |
spec = app.openapi()
|
| 46 |
response = spec["paths"]["/v1/analyses/{job_id}/load-timing"]["get"]["responses"]["200"]
|
| 47 |
-
|
|
|
|
| 48 |
assert spec["paths"]["/v1/analyses/{job_id}/load-timing"]["get"]["security"]
|
| 49 |
|
| 50 |
|
|
|
|
| 44 |
app = create_app(settings(tmp_path), fake_service(settings(tmp_path)))
|
| 45 |
spec = app.openapi()
|
| 46 |
response = spec["paths"]["/v1/analyses/{job_id}/load-timing"]["get"]["responses"]["200"]
|
| 47 |
+
variants = response['content']['application/json']['schema']['anyOf']
|
| 48 |
+
assert {v['$ref'].split('/')[-1] for v in variants} == {'LoadTimingPayload', 'TimingEvidencePayload'}
|
| 49 |
assert spec["paths"]["/v1/analyses/{job_id}/load-timing"]["get"]["security"]
|
| 50 |
|
| 51 |
|
tests/test_measurement_backends.py
CHANGED
|
@@ -416,6 +416,11 @@ def test_docker_build_context_includes_every_local_copy_source():
|
|
| 416 |
for dockerfile in ("Dockerfile", "Dockerfile.sam"):
|
| 417 |
for line in (ROOT/dockerfile).read_text().splitlines():
|
| 418 |
if not line.startswith("COPY "): continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
for source in shlex.split(line)[1:-1]:
|
| 420 |
assert (ROOT/source).exists(), source
|
| 421 |
allowed = True
|
|
|
|
| 416 |
for dockerfile in ("Dockerfile", "Dockerfile.sam"):
|
| 417 |
for line in (ROOT/dockerfile).read_text().splitlines():
|
| 418 |
if not line.startswith("COPY "): continue
|
| 419 |
+
if shlex.split(line)[1].startswith('--from='):
|
| 420 |
+
assert shlex.split(line)[1] == '--from=tracking-export'
|
| 421 |
+
assert ' AS tracking-export' in (ROOT/dockerfile).read_text()
|
| 422 |
+
assert shlex.split(line)[2].startswith('/tracking-models/tracking_')
|
| 423 |
+
continue
|
| 424 |
for source in shlex.split(line)[1:-1]:
|
| 425 |
assert (ROOT/source).exists(), source
|
| 426 |
allowed = True
|
tests/test_timing_tracking_api.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import json
|
| 3 |
+
import shutil
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import pytest
|
| 6 |
+
from fastapi.testclient import TestClient
|
| 7 |
+
from baseball_batting.api import create_app
|
| 8 |
+
from baseball_batting.api_contract import AnalysisInput
|
| 9 |
+
from baseball_batting.storage import atomic_json, sha256_file
|
| 10 |
+
from baseball_batting.timing_evidence import build_timing_evidence, TimingEvidencePayload
|
| 11 |
+
from baseball_batting.load_timing import build_load_timing_report
|
| 12 |
+
from test_api import settings, fake_service, AUTH, wait_until
|
| 13 |
+
from test_bat_ball_timing import contact_sequence
|
| 14 |
+
from test_load_timing_api import completed_timing_job
|
| 15 |
+
from test_tracking_geometry import two_view_fixture
|
| 16 |
+
|
| 17 |
+
OPTIONS=dict(view='face_on',handedness='right',pitcher_direction='image_left',camera_stability='fixed_verified',
|
| 18 |
+
timing={'kind':'unretimed','source':'Original recording'},single_swing=False,measurement_backend='2d')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_new_route_rejects_missing_settings_before_creating_job(video,tmp_path):
|
| 22 |
+
s=settings(tmp_path); service=fake_service(s)
|
| 23 |
+
with TestClient(create_app(s,service)) as client:
|
| 24 |
+
wait_until(lambda:service.ready)
|
| 25 |
+
files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
|
| 26 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files)
|
| 27 |
+
assert r.status_code==422
|
| 28 |
+
assert r.json()['detail']['code']=='timing_settings_required'
|
| 29 |
+
assert set(r.json()['detail']['fields'])=={'view','timing','handedness','pitcher_direction'}
|
| 30 |
+
assert not list(service.jobs_root.iterdir())
|
| 31 |
+
# Existing upload still accepts legacy clients and now explains omissions.
|
| 32 |
+
r=client.post('/v1/analyses',headers=AUTH,files=files)
|
| 33 |
+
assert r.status_code==202
|
| 34 |
+
assert r.json()['warnings'][0]['code']=='timing_settings_missing'
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_new_route_requires_actual_tracking_preflight_and_no_sam(video,tmp_path):
|
| 38 |
+
s=settings(tmp_path); service=fake_service(s)
|
| 39 |
+
with TestClient(create_app(s,service)) as client:
|
| 40 |
+
wait_until(lambda:service.ready)
|
| 41 |
+
files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
|
| 42 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files,data={'options':json.dumps(OPTIONS)})
|
| 43 |
+
assert r.status_code==503 and r.json()['detail']['code']=='tracking_models_unavailable'
|
| 44 |
+
service.tracking_ready=True # Mock GPU execution, never accuracy evidence.
|
| 45 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files,data={'options':json.dumps(OPTIONS|{'measurement_backend':'sam3d'})})
|
| 46 |
+
assert r.status_code==422 and r.json()['detail']['code']=='timing_uses_2d_body'
|
| 47 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files,data={'options':json.dumps(OPTIONS)})
|
| 48 |
+
assert r.status_code==202 and not r.json()['warnings']
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_secondary_pair_validation_and_terminal_cleanup(video,tmp_path):
|
| 52 |
+
s=settings(tmp_path); service=fake_service(s,delay=.15)
|
| 53 |
+
_,_,config=two_view_fixture()
|
| 54 |
+
files={'video':('swing.mp4',video.read_bytes(),'video/mp4'),'secondary_video':('other.mp4',video.read_bytes(),'video/mp4')}
|
| 55 |
+
with TestClient(create_app(s,service)) as client:
|
| 56 |
+
wait_until(lambda:service.ready); service.tracking_ready=True
|
| 57 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files,data={'options':json.dumps(OPTIONS)})
|
| 58 |
+
assert r.status_code==422 and r.json()['detail']['code']=='stereo_input_incomplete'
|
| 59 |
+
opts=OPTIONS|{'stereo_tracking':config.model_dump(mode='json')}
|
| 60 |
+
r=client.post('/v1/load-timing/analyses',headers=AUTH,files=files,data={'options':json.dumps(opts)})
|
| 61 |
+
assert r.status_code==202,r.text
|
| 62 |
+
job=service.job_directory(r.json()['job_id'])
|
| 63 |
+
assert (job/'secondary.mp4').exists()
|
| 64 |
+
wait_until(lambda:service.store.get(r.json()['job_id'])['status']=='completed')
|
| 65 |
+
wait_until(lambda:not (job/'secondary.mp4').exists())
|
| 66 |
+
assert not (job/'input.mp4').exists()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_opt_in_31_preserves_30_and_checks_stored_integrity(tmp_path):
|
| 70 |
+
from baseball_batting.bat_ball_timing import visual_contact
|
| 71 |
+
result,observed=contact_sequence()
|
| 72 |
+
hit=visual_contact(observed,result['pose_track'],result['pose_track']['reps'][0])
|
| 73 |
+
report=build_load_timing_report(result,ball_evidence={1:hit})
|
| 74 |
+
rich=build_timing_evidence(report,result,AnalysisInput(**OPTIONS,practice_type='live'))
|
| 75 |
+
service=fake_service(settings(tmp_path))
|
| 76 |
+
identifier,job,_=completed_timing_job(service,report['payload'])
|
| 77 |
+
atomic_json(job/'load-timing-evidence.json',rich)
|
| 78 |
+
service.store.update(identifier,'completed',timing_hash=sha256_file(job/'load-timing.json'),evidence_hash=sha256_file(job/'load-timing-evidence.json'))
|
| 79 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 80 |
+
url=f'/v1/analyses/{identifier}/load-timing'
|
| 81 |
+
assert client.get(url,headers=AUTH).json()==report['payload']
|
| 82 |
+
r=client.get(url+'?include_evidence=true',headers=AUTH)
|
| 83 |
+
assert r.status_code==200 and r.json()==rich
|
| 84 |
+
assert r.headers['cache-control']=='no-store'
|
| 85 |
+
assert client.get('/v1/load-timing-schema?include_evidence=true',headers=AUTH).json()==TimingEvidencePayload.model_json_schema()
|
| 86 |
+
assert client.get(f'/v1/analyses/{identifier}',headers=AUTH).json()['load_timing_evidence_url']==url+'?include_evidence=true'
|
| 87 |
+
(job/'load-timing-evidence.json').write_text('{}')
|
| 88 |
+
assert client.get(url+'?include_evidence=true',headers=AUTH).status_code==500
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@pytest.mark.parametrize('bad', ['pitch_source','same_camera','bad_rotation','unknown_clock','blank_bounds'])
|
| 92 |
+
def test_physical_inputs_reject_undocumented_or_invalid_geometry(bad):
|
| 93 |
+
_,_,config=two_view_fixture(); options=OPTIONS|{'stereo_tracking':config.model_dump(mode='json')}
|
| 94 |
+
c=options['stereo_tracking']
|
| 95 |
+
if bad=='pitch_source': options['pitch_speed_mps']=40
|
| 96 |
+
if bad=='same_camera': c['cameras'][1]=deepcopy(c['cameras'][0])
|
| 97 |
+
if bad=='bad_rotation': c['cameras'][1]['rotation'][0][0]=2
|
| 98 |
+
if bad=='unknown_clock': c['secondary_timing']={'kind':'unknown'}
|
| 99 |
+
if bad=='blank_bounds': c['position_bound_source']=' '
|
| 100 |
+
with pytest.raises(ValueError): AnalysisInput.model_validate(options)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_worker_writes_contact_duration_from_actual_tracking_adapter(video,tmp_path,monkeypatch):
|
| 104 |
+
import baseball_batting.api_worker as worker
|
| 105 |
+
import baseball_batting.observations as body
|
| 106 |
+
import baseball_batting.tracking_vision as objects
|
| 107 |
+
import baseball_batting.measurement_quality as quality
|
| 108 |
+
result,observed=contact_sequence()
|
| 109 |
+
# The real worker routes the observations through event detection, timing,
|
| 110 |
+
# strict contracts and persistence. Model outputs are a deterministic seam.
|
| 111 |
+
shutil.copy2(video,tmp_path/'input.mp4'); atomic_json(tmp_path/'request.json',OPTIONS)
|
| 112 |
+
models=tmp_path/'models'
|
| 113 |
+
for name in ('bat','ball'):
|
| 114 |
+
p=models/('tracking_'+name); p.mkdir(parents=True); (p/'model.json').write_text('{}')
|
| 115 |
+
monkeypatch.setattr(worker,'model_files',lambda _:({'body_pose':'pose','person_detector':'person'},{}))
|
| 116 |
+
monkeypatch.setattr(body,'run_observations',lambda *a,**kw:{'branch_status':{'body_pose':{'status':'ready'},'person_detector':{'status':'ready'}}})
|
| 117 |
+
monkeypatch.setattr(worker,'build_api_result',lambda *a:deepcopy(result)|{'coach_payload':{'schema_version':'2.0'}})
|
| 118 |
+
monkeypatch.setattr(quality,'apply_measurement_quality',lambda r,*a:r)
|
| 119 |
+
monkeypatch.setattr(objects,'track_video',lambda *a,**kw:deepcopy(observed))
|
| 120 |
+
worker.run_analysis(tmp_path,models,device='cpu')
|
| 121 |
+
rich=TimingEvidencePayload.model_validate_json((tmp_path/'load-timing-evidence.json').read_text())
|
| 122 |
+
assert rich.reps[0].outcome=='hit'
|
| 123 |
+
assert rich.reps[0].metrics[2].value==pytest.approx(333.333)
|
| 124 |
+
assert rich.legacy()==json.loads((tmp_path/'load-timing.json').read_text())
|
| 125 |
+
assert (tmp_path/'bat-ball-observations.json').is_file()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_two_video_worker_to_http_produces_all_four_metrics(tmp_path,monkeypatch):
|
| 129 |
+
from fractions import Fraction
|
| 130 |
+
import av
|
| 131 |
+
import numpy as np
|
| 132 |
+
import baseball_batting.api_worker as worker
|
| 133 |
+
import baseball_batting.observations as body
|
| 134 |
+
import baseball_batting.tracking_vision as objects
|
| 135 |
+
import baseball_batting.measurement_quality as quality
|
| 136 |
+
result,(primary,secondary),config=two_view_fixture()
|
| 137 |
+
s=settings(tmp_path); service=fake_service(s)
|
| 138 |
+
identifier=service.store.create(8); job=service.job_directory(identifier); job.mkdir()
|
| 139 |
+
options=OPTIONS|{'stereo_tracking':config.model_dump(mode='json'),'practice_type':'live'}
|
| 140 |
+
atomic_json(job/'request.json',options)
|
| 141 |
+
for name in ('input.mp4','secondary.mp4'):
|
| 142 |
+
with av.open(str(job/name),'w') as container:
|
| 143 |
+
stream=container.add_stream('mpeg4',rate=120); stream.width=16; stream.height=16; stream.pix_fmt='yuv420p'
|
| 144 |
+
for i in range(150):
|
| 145 |
+
frame=av.VideoFrame.from_ndarray(np.full((16,16,3),i%255,np.uint8),format='rgb24')
|
| 146 |
+
frame.pts=i; frame.time_base=Fraction(1,120)
|
| 147 |
+
for packet in stream.encode(frame): container.mux(packet)
|
| 148 |
+
for packet in stream.encode(): container.mux(packet)
|
| 149 |
+
models=tmp_path/'models'
|
| 150 |
+
for name in ('bat','ball'):
|
| 151 |
+
p=models/('tracking_'+name); p.mkdir(parents=True); (p/'model.json').write_text('{}')
|
| 152 |
+
monkeypatch.setattr(worker,'model_files',lambda _:({'body_pose':'pose','person_detector':'person'},{}))
|
| 153 |
+
monkeypatch.setattr(body,'run_observations',lambda *a,**kw:{'branch_status':{'body_pose':{'status':'ready'},'person_detector':{'status':'ready'}}})
|
| 154 |
+
monkeypatch.setattr(worker,'build_api_result',lambda *a:deepcopy(result)|{'coach_payload':{'schema_version':'2.0'}})
|
| 155 |
+
monkeypatch.setattr(quality,'apply_measurement_quality',lambda r,*a:r)
|
| 156 |
+
def tracking(video,result,*a,**kw):
|
| 157 |
+
assert result['pose_track']['video']['frame_count']==150
|
| 158 |
+
return deepcopy(secondary if Path(video).name.startswith('secondary') else primary)
|
| 159 |
+
monkeypatch.setattr(objects,'track_video',tracking)
|
| 160 |
+
worker.run_analysis(job,models,device='cpu')
|
| 161 |
+
service.store.update(identifier,'completed',result_hash=sha256_file(job/'result.json'),
|
| 162 |
+
timing_hash=sha256_file(job/'load-timing.json'),evidence_hash=sha256_file(job/'load-timing-evidence.json'))
|
| 163 |
+
with TestClient(create_app(s,service)) as client:
|
| 164 |
+
r=client.get(f'/v1/analyses/{identifier}/load-timing?include_evidence=true',headers=AUTH)
|
| 165 |
+
assert r.status_code==200,r.text
|
| 166 |
+
rich=TimingEvidencePayload.model_validate(r.json())
|
| 167 |
+
assert rich.reps[0].outcome=='miss'
|
| 168 |
+
assert all(m.value is not None for m in rich.reps[0].metrics)
|
| 169 |
+
assert rich.reps[0].metrics[3].value > 0
|
| 170 |
+
assert client.get(f'/v1/analyses/{identifier}/load-timing',headers=AUTH).json()==rich.legacy()
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_evidence_intervals_cannot_claim_accuracy_or_exclude_the_estimate():
|
| 174 |
+
from baseball_batting.bat_ball_timing import visual_contact
|
| 175 |
+
result,observed=contact_sequence()
|
| 176 |
+
hit=visual_contact(observed,result['pose_track'],result['pose_track']['reps'][0])
|
| 177 |
+
report=build_load_timing_report(result,ball_evidence={1:hit})
|
| 178 |
+
rich=build_timing_evidence(report,result,AnalysisInput(**OPTIONS))
|
| 179 |
+
for change in ('bounds','accuracy','duplicate'):
|
| 180 |
+
bad=deepcopy(rich)
|
| 181 |
+
if change=='bounds': bad['reps'][0]['metrics'][0]['uncertainty']['interval_ms']=[0.,1.]
|
| 182 |
+
if change=='accuracy': bad['reps'][0]['metrics'][0]['uncertainty']['accuracy_validated']=True
|
| 183 |
+
if change=='duplicate': bad['reps'][0]['metrics'][1]=deepcopy(bad['reps'][0]['metrics'][0])
|
| 184 |
+
with pytest.raises(ValueError): TimingEvidencePayload.model_validate(bad)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_evidence_examples_and_schema_match_current_contract():
|
| 188 |
+
import jsonschema
|
| 189 |
+
root=Path(__file__).resolve().parents[1]
|
| 190 |
+
example=json.loads((root/'docs/load-timing-evidence.example.json').read_text())
|
| 191 |
+
schema=json.loads((root/'docs/load-timing-evidence.schema.json').read_text())
|
| 192 |
+
assert schema==TimingEvidencePayload.model_json_schema()
|
| 193 |
+
jsonschema.validate(example,schema)
|
| 194 |
+
TimingEvidencePayload.model_validate(example)
|
tests/test_tracking_export.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
+
import pytest
|
| 7 |
+
from tools import setup_tracking_models as exporter
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_trusted_replacement_checkpoints_record_hashes_without_download(tmp_path,monkeypatch):
|
| 11 |
+
bat=tmp_path/'replacement-bat.pt'; ball=tmp_path/'replacement-ball.pt'
|
| 12 |
+
bat.write_bytes(b'bat fixture checkpoint'); ball.write_bytes(b'ball fixture checkpoint')
|
| 13 |
+
class Model:
|
| 14 |
+
def __init__(self,path,task):
|
| 15 |
+
self.path=Path(path); self.task=task
|
| 16 |
+
self.names={0:'bat'} if task=='pose' else {0:'ball',1:'glove'}
|
| 17 |
+
self.model=SimpleNamespace(model=[SimpleNamespace(kpt_shape=[2,3] if task=='pose' else None)])
|
| 18 |
+
def export(self,**kwargs):
|
| 19 |
+
assert kwargs==dict(format='onnx',imgsz=640,opset=17,simplify=False,dynamic=False,nms=False,device='cpu')
|
| 20 |
+
path=self.path.with_suffix('.onnx'); path.write_bytes(b'ONNX fixture '+self.path.read_bytes()); return str(path)
|
| 21 |
+
monkeypatch.setitem(sys.modules,'ultralytics',SimpleNamespace(YOLO=Model))
|
| 22 |
+
monkeypatch.setattr(exporter.urllib.request,'urlopen',lambda *a,**kw:pytest.fail('Local checkpoints must not download'))
|
| 23 |
+
output=tmp_path/'models'
|
| 24 |
+
monkeypatch.setattr(sys,'argv',['export','--output',str(output),'--weights',str(tmp_path/'weights'),
|
| 25 |
+
'--bat-checkpoint',str(bat),'--ball-checkpoint',str(ball)])
|
| 26 |
+
exporter.main()
|
| 27 |
+
for name,source in [('bat',bat),('ball',ball)]:
|
| 28 |
+
folder=output/('tracking_'+name); manifest=json.loads((folder/'model.json').read_text())
|
| 29 |
+
assert manifest['checkpoint_sha256']==hashlib.sha256(source.read_bytes()).hexdigest()
|
| 30 |
+
assert manifest['onnx_sha256']==exporter.checksum(folder/'model.onnx')
|
| 31 |
+
assert manifest['registry_revision'] is None
|
| 32 |
+
assert manifest['source']=='trusted_local_checkpoint:'+source.name
|
| 33 |
+
assert json.loads((output/'tracking_bat/model.json').read_text())['keypoint_shape']==[2,3]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_bad_download_never_loads_or_exports_checkpoint(tmp_path,monkeypatch):
|
| 37 |
+
import io
|
| 38 |
+
monkeypatch.setitem(sys.modules,'ultralytics',SimpleNamespace(YOLO=lambda *a,**kw:pytest.fail('Checksum mismatch must stop model loading')))
|
| 39 |
+
monkeypatch.setattr(exporter.urllib.request,'urlopen',lambda *a,**kw:io.BytesIO(b'incorrect checkpoint'))
|
| 40 |
+
monkeypatch.setattr(sys,'argv',['export','--weights',str(tmp_path/'weights'),'--output',str(tmp_path/'models')])
|
| 41 |
+
with pytest.raises(ValueError,match='checksum mismatch'): exporter.main()
|
| 42 |
+
assert not (tmp_path/'weights/bat.pt').exists()
|
| 43 |
+
assert not (tmp_path/'models').exists()
|
tests/test_tracking_geometry.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from baseball_batting.api_contract import StereoTrackingInput, AnalysisInput
|
| 4 |
+
from baseball_batting.tracking_geometry import reconstruct_rep, _sample
|
| 5 |
+
from baseball_batting.load_timing import build_load_timing_report
|
| 6 |
+
from baseball_batting.timing_evidence import build_timing_evidence, TimingEvidencePayload
|
| 7 |
+
from test_load_timing import timing_result, metrics
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def two_view_fixture(fps=120):
|
| 11 |
+
n=150; t=np.arange(n)/fps
|
| 12 |
+
result=timing_result(fps); track=result['pose_track']; rep=track['reps'][0]
|
| 13 |
+
rep['events']['swing_start']['frame']=45
|
| 14 |
+
rep['events']['load_start']['frame']=15
|
| 15 |
+
rep['events']['foot_contact']['frame']=30
|
| 16 |
+
rep['events']['finish']={'frame':125,'method':'test'}
|
| 17 |
+
k=np.array([[1000.,0,640],[0,1000.,480],[0,0,1]])
|
| 18 |
+
r=np.eye(3)
|
| 19 |
+
translations=[np.array([0.,0,0]),np.array([-1.,.3,0])]
|
| 20 |
+
config=StereoTrackingInput.model_validate(dict(
|
| 21 |
+
cameras=[{'intrinsics':k.tolist(),'rotation':r.tolist(),'translation_m':v.tolist()} for v in translations],
|
| 22 |
+
source='Synthetic calibration fixture',synchronization_source='Same fixture clock',
|
| 23 |
+
secondary_offset_s=0.,synchronization_bound_ms=0.,position_bound_m=.001,
|
| 24 |
+
position_bound_source='Exact linear fixture paths; includes interpolation',bat_length_m=1.,
|
| 25 |
+
barrel_radius_m=.03,secondary_timing={'kind':'unretimed','source':'Fixture clock'}))
|
| 26 |
+
# A miss: bat crosses x=0 at .65s, ball crosses z=5 at .75s.
|
| 27 |
+
bat=np.zeros((n,2,3)); bat[:,:,0]=4*(t[:,None]-.65); bat[:,1,1]=1.; bat[:,:,2]=5.
|
| 28 |
+
ball=np.column_stack([np.zeros(n),np.full(n,.7),5+4*(t-.75)])
|
| 29 |
+
def project(p,v):
|
| 30 |
+
h=(p+v)@k.T
|
| 31 |
+
return (h[...,:2]/h[...,2:3]).tolist()
|
| 32 |
+
observations=[]
|
| 33 |
+
for v in translations:
|
| 34 |
+
frames=[]
|
| 35 |
+
for i in range(n):
|
| 36 |
+
bp=project(bat[i],v); pp=project(ball[i],v)
|
| 37 |
+
frames.append({'capture_time_s':float(t[i]),'bat':[{'points':bp}], 'ball':[{'point':pp, 'radius_px':3.}]})
|
| 38 |
+
if len(observations)==0:
|
| 39 |
+
track['frames']['kp'][i][9]=bp[0]; track['frames']['kp'][i][10]=bp[0]
|
| 40 |
+
observations.append({'frames':frames})
|
| 41 |
+
return result,observations,config
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_two_views_supply_physical_miss_and_nonempty_shift():
|
| 45 |
+
result,(a,b),config=two_view_fixture()
|
| 46 |
+
rep=result['pose_track']['reps'][0]
|
| 47 |
+
out=reconstruct_rep(a,b,result['pose_track'],rep,config)
|
| 48 |
+
assert out['outcome']=='miss',out
|
| 49 |
+
assert out['end_event']=='closest_approach'
|
| 50 |
+
assert out['shift']['value'] is not None and out['shift']['value'] > 0
|
| 51 |
+
assert out['spatial']['max_reprojection_px'] < 1e-6
|
| 52 |
+
report=build_load_timing_report(result,ball_evidence={1:out})
|
| 53 |
+
assert all(v['value'] is not None for v in metrics(report).values())
|
| 54 |
+
options=AnalysisInput(timing={'kind':'unretimed','source':'Fixture'},stereo_tracking=config,practice_type='live',camera_stability='fixed_verified')
|
| 55 |
+
rich=TimingEvidencePayload.model_validate(build_timing_evidence(report,result,options))
|
| 56 |
+
assert rich.legacy()==report['payload']
|
| 57 |
+
assert rich.reps[0].metrics[3].uncertainty.kind=='supplied_geometry_bound'
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@pytest.mark.parametrize('failure,reason',[('ball_gap','spatial_track_incomplete'),
|
| 61 |
+
('bat_gap','spatial_track_incomplete'),('multiple','ball_identity_ambiguous'),
|
| 62 |
+
('hands','barrel_identity_unresolved'),('clock','synchronization_unresolved'),
|
| 63 |
+
('length','bat_geometry_ambiguous')])
|
| 64 |
+
def test_missing_or_ambiguous_two_view_evidence_withholds(failure,reason):
|
| 65 |
+
result,(a,b),config=two_view_fixture()
|
| 66 |
+
if failure=='ball_gap': b['frames'][60]['ball']=[]
|
| 67 |
+
if failure=='bat_gap': b['frames'][60]['bat'][0]['points']=None
|
| 68 |
+
if failure=='multiple': b['frames'][60]['ball'] *= 2
|
| 69 |
+
if failure=='hands':
|
| 70 |
+
for row in result['pose_track']['frames']['kp']: row[9:11]=[None,None]
|
| 71 |
+
if failure=='clock': b['frames'][60]['capture_time_s']=b['frames'][59]['capture_time_s']
|
| 72 |
+
if failure=='length': config.bat_length_m=.4
|
| 73 |
+
out=reconstruct_rep(a,b,result['pose_track'],result['pose_track']['reps'][0],config)
|
| 74 |
+
assert out['outcome']=='unknown' and out['reason_code']==reason
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_interpolation_state_and_no_gap_fill():
|
| 78 |
+
rows=[{'ball':[{'point':[0.,0]}]}, {'ball':[{'point':[2.,2]}]}]
|
| 79 |
+
got=_sample(rows,np.array([0.,1/60]),1/120,'ball')
|
| 80 |
+
assert got[0]['point']==[1.,1.] and got[0]['state']=='interpolated_between_observed_frames'
|
| 81 |
+
rows[1]['ball']=[]
|
| 82 |
+
assert _sample(rows,np.array([0.,1/60]),1/120,'ball')==[]
|
| 83 |
+
assert _sample(rows,np.array([0.,1/60]),-1/120,'ball')==[]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_return_from_net_does_not_supply_an_early_late_correction():
|
| 87 |
+
result,(a,b),config=two_view_fixture()
|
| 88 |
+
# Reverse the observed flight after the approach window, preserving valid
|
| 89 |
+
# camera projections/scale. This is another interaction, not this pitch.
|
| 90 |
+
for frames in (a['frames'],b['frames']):
|
| 91 |
+
for i in range(100,126):
|
| 92 |
+
frames[i]['ball']=frames[200-i]['ball']
|
| 93 |
+
out=reconstruct_rep(a,b,result['pose_track'],result['pose_track']['reps'][0],config)
|
| 94 |
+
assert out['outcome']=='unknown' and out['reason_code']=='incoming_ball_motion_unresolved'
|
tests/test_tracking_vision.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import SimpleNamespace
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pytest
|
| 4 |
+
from baseball_batting.tracking_vision import TrackingModel, deduplicate, track_video
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RawSession:
|
| 8 |
+
def __init__(self, rows): self.rows=rows; self.inputs=[]
|
| 9 |
+
def get_inputs(self): return [SimpleNamespace(name='images')]
|
| 10 |
+
def run(self, _, feed):
|
| 11 |
+
self.inputs.append(feed['images'])
|
| 12 |
+
return [np.array(self.rows,dtype=np.float32).T[None]]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def adapter(kind, rows):
|
| 16 |
+
model=TrackingModel.__new__(TrackingModel)
|
| 17 |
+
model.name=kind; model.size=640; model.device='cpu'; model.verified=False
|
| 18 |
+
model.classes=2 if kind=='bat' else 4
|
| 19 |
+
model.target_class=0 if kind=='bat' else 2
|
| 20 |
+
model.record={'classes': {'0':'bat','1':'hitter'} if kind=='bat' else {'0':'glove','1':'homeplate','2':'baseball','3':'rubber'},'keypoint_shape':[4,3] if kind=='bat' else None}
|
| 21 |
+
model.session=RawSession(rows)
|
| 22 |
+
return model
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def batrow(*, score=.9, visibility=1., y=320):
|
| 26 |
+
return [320,y,200,30,score,.01, 240,y,visibility, 280,y,visibility, 330,y,visibility, 400,y,visibility]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_bat_uses_four_observed_landmarks_and_original_crop_pixels():
|
| 30 |
+
m=adapter('bat',[batrow()])
|
| 31 |
+
im=np.zeros((200,400,3),np.uint8); im[:,:,0]=255
|
| 32 |
+
row=m(im,(10,20))[0]
|
| 33 |
+
# Scale 1.6, centered vertical padding 160. RGB from BGR verified.
|
| 34 |
+
assert row['points'] == [[160.,120.],[260.,120.]]
|
| 35 |
+
assert len(row['shaft_points'])==4 and row['endpoint_indices']==[0,3]
|
| 36 |
+
assert m.session.inputs[0][0,2,200,100]==1.
|
| 37 |
+
assert m.session.inputs[0][0,0,200,100]==0.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@pytest.mark.parametrize('failure',['invisible','curved','outside','short','nan'])
|
| 41 |
+
def test_invalid_bat_endpoints_do_not_become_geometry(failure):
|
| 42 |
+
r=batrow(visibility=.1 if failure=='invisible' else 1.)
|
| 43 |
+
if failure=='curved': r[10]=500
|
| 44 |
+
if failure=='outside': r[6]=700
|
| 45 |
+
if failure=='short': r[6:]=[320,320,1]*4
|
| 46 |
+
if failure=='nan': r[6]=np.nan
|
| 47 |
+
output=adapter('bat',[r])(np.zeros((640,640,3),np.uint8))
|
| 48 |
+
assert not output or output[0]['points'] is None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_ball_selects_baseball_score_and_ignores_glove_and_plate():
|
| 52 |
+
m=adapter('ball',[[100,100,20,20,.99,.1,.6,0], [200,200,10,8,.1,.2,.8,.1]])
|
| 53 |
+
rows=m(np.zeros((640,640,3),np.uint8))
|
| 54 |
+
assert len(rows)==1 and rows[0]['point']==[200.,200.]
|
| 55 |
+
assert rows[0]['radius_px']==5
|
| 56 |
+
assert rows[0]['score']==pytest.approx(.8)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_visible_crop_landmarks_survive_higher_scored_empty_fullframe_box():
|
| 60 |
+
invalid={'box':[100,100,200,200],'score':.9,'points':None}
|
| 61 |
+
valid={'box':[102,101,199,200],'score':.7,'points':[[100,100],[200,200]],
|
| 62 |
+
'point_scores':[.9,.9],'shaft_points':[[100,100],[200,200]],'endpoint_indices':[0,1]}
|
| 63 |
+
out=deduplicate([invalid,valid])
|
| 64 |
+
assert len(out)==1 and out[0]['points'] == valid['points']
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_tracking_window_keeps_endpoint_context_and_empty_frames(monkeypatch):
|
| 68 |
+
import baseball_batting.tracking_vision as vision
|
| 69 |
+
import baseball_batting.ingest as ingest
|
| 70 |
+
monkeypatch.setattr(vision,'TrackingModel',lambda *a: SimpleNamespace(record={}))
|
| 71 |
+
monkeypatch.setattr(vision,'frame_detections',lambda *a: {'bat':[{'observed':True}],'ball':[]})
|
| 72 |
+
monkeypatch.setattr(ingest,'iter_frames',lambda *a: ((i,None,None,np.zeros((4,4,3))) for i in range(30)))
|
| 73 |
+
result={'pose_track':{'video':{'rotation_degrees_applied':0,'frame_count':30},
|
| 74 |
+
'frames':{'box':[None]*30,'t_s':[i/60 for i in range(30)]},
|
| 75 |
+
'reps':[{'start_frame':0,'end_frame':29,'events':{'swing_start':{'frame':10},'finish':{'frame':20}}}]}}
|
| 76 |
+
out=track_video('ignored',result,'ignored','cpu')
|
| 77 |
+
assert len(out['frames'])==30
|
| 78 |
+
assert [r['frame'] for r in out['frames'] if r['bat']]==list(range(7,24))
|
| 79 |
+
assert out['gap_filling'] is False
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_hitter_class_cannot_become_a_bat_from_its_secondary_score():
|
| 83 |
+
r=batrow(); r[5]=.95
|
| 84 |
+
assert adapter('bat',[r])(np.zeros((640,640,3),np.uint8)) == []
|
tools/setup_tracking_models.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Acquire pinned BaseballCV weights and export raw, static ONNX for the GPU worker.
|
| 2 |
+
|
| 3 |
+
PyTorch/Ultralytics are build dependencies only. Inference uses ONNX Runtime.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import urllib.request
|
| 10 |
+
|
| 11 |
+
SOURCES = {
|
| 12 |
+
"bat": ("https://data.balldatalab.com/index.php/s/jsLpPR8rXrk5Ndr/download/bat_tracking_v2.pt", "774eda0281c3485e4a8dd620280fd90c79b15783c7cd6de965a937ee46d793bb"),
|
| 13 |
+
"ball": ("https://data.balldatalab.com/index.php/s/YkGBwbFtsf34ky3/download/ball_tracking_v4-YOLOv11.pt", "00faa0a129ef4b25bcc4f4610d70211efed6470d89225618cc6ffab000f507d0"),
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def checksum(path):
|
| 18 |
+
h = hashlib.sha256()
|
| 19 |
+
with Path(path).open('rb') as source:
|
| 20 |
+
for block in iter(lambda: source.read(1024*1024), b''):
|
| 21 |
+
h.update(block)
|
| 22 |
+
return h.hexdigest()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
parser = argparse.ArgumentParser()
|
| 27 |
+
parser.add_argument('--output', default='downloads')
|
| 28 |
+
parser.add_argument('--weights', default='downloads/load_timing_models')
|
| 29 |
+
parser.add_argument('--bat-checkpoint', type=Path, help='Trusted local YOLO pose checkpoint with actual shaft endpoints')
|
| 30 |
+
parser.add_argument('--ball-checkpoint', type=Path, help='Trusted local YOLO detection checkpoint with baseball/ball class')
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
weights = Path(args.weights)
|
| 33 |
+
weights.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
from ultralytics import YOLO
|
| 35 |
+
for name, (url, expected) in SOURCES.items():
|
| 36 |
+
override = getattr(args, name+'_checkpoint')
|
| 37 |
+
source = override if override is not None else weights/(name+'.pt')
|
| 38 |
+
if override is not None:
|
| 39 |
+
expected = checksum(source)
|
| 40 |
+
url = 'trusted_local_checkpoint:'+source.name
|
| 41 |
+
if override is None and not source.exists():
|
| 42 |
+
temporary = source.with_suffix('.partial')
|
| 43 |
+
with urllib.request.urlopen(url, timeout=60) as response, temporary.open('wb') as out:
|
| 44 |
+
for block in iter(lambda: response.read(1024*1024), b''):
|
| 45 |
+
out.write(block)
|
| 46 |
+
if checksum(temporary) != expected:
|
| 47 |
+
temporary.unlink()
|
| 48 |
+
raise ValueError(f'{name} checkpoint checksum mismatch')
|
| 49 |
+
temporary.replace(source)
|
| 50 |
+
if checksum(source) != expected:
|
| 51 |
+
raise ValueError(f'{name} checkpoint checksum mismatch')
|
| 52 |
+
model = YOLO(str(source), task='pose' if name == 'bat' else 'detect')
|
| 53 |
+
shape = getattr(model.model.model[-1], 'kpt_shape', None)
|
| 54 |
+
if name == 'bat' and (shape is None or shape[0] < 2 or shape[1] != 3):
|
| 55 |
+
raise ValueError(f'Expected visible shaft keypoints, got {shape}')
|
| 56 |
+
labels = {'bat'} if name == 'bat' else {'baseball', 'ball'}
|
| 57 |
+
if sum(label in labels for label in model.names.values()) != 1:
|
| 58 |
+
raise ValueError(f'Expected one unambiguous target class for {name}')
|
| 59 |
+
exported = Path(model.export(format='onnx', imgsz=640, opset=17,
|
| 60 |
+
simplify=False, dynamic=False, nms=False, device='cpu'))
|
| 61 |
+
target = Path(args.output)/('tracking_'+name)
|
| 62 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
(target/'model.onnx').write_bytes(exported.read_bytes())
|
| 64 |
+
record = {'name': name, 'checkpoint_sha256': expected,
|
| 65 |
+
'onnx_sha256': checksum(target/'model.onnx'), 'source': url,
|
| 66 |
+
'registry_revision': None if override is not None else 'c3c26c979766b28e0c78c3fee2edc2aa3dad571e',
|
| 67 |
+
'input_size': 640, 'classes': model.names, 'keypoint_shape': shape,
|
| 68 |
+
'endpoint_order': 'extreme observed shaft landmarks; barrel identity requires hand proximity evidence',
|
| 69 |
+
'export': 'ultralytics-8.4.175; opset17; static; raw; float32'}
|
| 70 |
+
(target/'model.json').write_text(json.dumps(record, indent=2)+'\n')
|
| 71 |
+
print(name, record['onnx_sha256'], flush=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == '__main__':
|
| 75 |
+
main()
|