Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
326d3cc
1
Parent(s): ff40c32
Automated Deploy: a19ede424a80b7b8d7f6978585141d1bb45de69c
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +17 -0
- .env.example +10 -0
- .gitignore +26 -0
- BUILD_STATUS.md +72 -0
- Dockerfile +28 -0
- README.md +11 -6
- baseball_batting/__init__.py +4 -0
- baseball_batting/advanced_metrics.py +146 -0
- baseball_batting/anatomy.py +273 -0
- baseball_batting/annotations.py +54 -0
- baseball_batting/api.py +214 -0
- baseball_batting/api_contract.py +72 -0
- baseball_batting/api_jobs.py +318 -0
- baseball_batting/api_output.py +105 -0
- baseball_batting/api_worker.py +116 -0
- baseball_batting/assessment.py +39 -0
- baseball_batting/bat2d.py +83 -0
- baseball_batting/bat3d.py +94 -0
- baseball_batting/batting_measurements.py +519 -0
- baseball_batting/body2d.py +33 -0
- baseball_batting/body3d.py +143 -0
- baseball_batting/cli.py +80 -0
- baseball_batting/config.py +80 -0
- baseball_batting/contracts.py +87 -0
- baseball_batting/dataset.py +81 -0
- baseball_batting/detection.py +121 -0
- baseball_batting/diagnostics.py +39 -0
- baseball_batting/events.py +132 -0
- baseball_batting/geometry.py +108 -0
- baseball_batting/history.py +30 -0
- baseball_batting/ingest.py +169 -0
- baseball_batting/learning.py +157 -0
- baseball_batting/metrics.py +116 -0
- baseball_batting/motion.py +58 -0
- baseball_batting/objects.py +55 -0
- baseball_batting/observations.py +183 -0
- baseball_batting/optional_preflight.py +47 -0
- baseball_batting/pipeline.py +91 -0
- baseball_batting/preflight.py +109 -0
- baseball_batting/reports.py +152 -0
- baseball_batting/resources.py +63 -0
- baseball_batting/review.py +69 -0
- baseball_batting/sensitivity.py +28 -0
- baseball_batting/storage.py +99 -0
- baseball_batting/temporal3d.py +269 -0
- baseball_batting/training.py +144 -0
- baseball_batting/validation.py +48 -0
- baseball_batting/worker.py +139 -0
- compose.yaml +29 -0
- configs/anatomical_model.yaml +27 -0
.dockerignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*
|
| 2 |
+
!Dockerfile
|
| 3 |
+
!requirements-core.txt
|
| 4 |
+
!requirements-api.txt
|
| 5 |
+
!requirements-api-gpu.txt
|
| 6 |
+
!pyproject.toml
|
| 7 |
+
!baseball_batting/
|
| 8 |
+
!baseball_batting/*.py
|
| 9 |
+
!configs/
|
| 10 |
+
!configs/*.yaml
|
| 11 |
+
!tools/
|
| 12 |
+
!tools/setup_api_models.py
|
| 13 |
+
!tools/__init__.py
|
| 14 |
+
!docs/
|
| 15 |
+
!docs/api-result.schema.json
|
| 16 |
+
!docs/coach-payload.schema.json
|
| 17 |
+
**/__pycache__
|
.env.example
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generate your own random secret; do not commit the real .env file.
|
| 2 |
+
BASEBALL_API_KEY=
|
| 3 |
+
BASEBALL_MAX_UPLOAD_MB=512
|
| 4 |
+
BASEBALL_MAX_ACTIVE_JOBS=8
|
| 5 |
+
BASEBALL_MAX_FRAMES=7200
|
| 6 |
+
BASEBALL_MAX_DURATION_S=120
|
| 7 |
+
BASEBALL_JOB_TIMEOUT_S=1800
|
| 8 |
+
BASEBALL_RETENTION_HOURS=24
|
| 9 |
+
# Required only for the optional HTTPS proxy. Point its DNS at your GPU server.
|
| 10 |
+
BASEBALL_DOMAIN=
|
.gitignore
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
.anatomy-venv/
|
| 3 |
+
__pycache__/
|
| 4 |
+
.pytest_cache/
|
| 5 |
+
*.egg-info/
|
| 6 |
+
.ipynb_checkpoints/
|
| 7 |
+
artifacts/
|
| 8 |
+
downloads/
|
| 9 |
+
dist/
|
| 10 |
+
*.pyc
|
| 11 |
+
.DS_Store
|
| 12 |
+
.runtime-*/
|
| 13 |
+
batting_notebook_runtime/
|
| 14 |
+
engine-config.json
|
| 15 |
+
capture-metadata.json
|
| 16 |
+
source_checkout.json
|
| 17 |
+
*-reviewed.json
|
| 18 |
+
*.mp4
|
| 19 |
+
*.mov
|
| 20 |
+
*.mkv
|
| 21 |
+
*.avi
|
| 22 |
+
*.webm
|
| 23 |
+
api-data/
|
| 24 |
+
.env
|
| 25 |
+
.env.*
|
| 26 |
+
!.env.example
|
BUILD_STATUS.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Build status
|
| 2 |
+
|
| 3 |
+
Updated: 2026-10-11. The initial backend build has now been followed by investigation of two supplied Colab result archives. The user-edited plans remain unchanged. Implementation, runtime qualification and measurement/coaching validation are separate outcomes.
|
| 4 |
+
|
| 5 |
+
## 2D GPU API and Docker deployment
|
| 6 |
+
|
| 7 |
+
The API is prepared for the requested Linux NVIDIA GPU server with Docker. It directly runs the person detector and RTMW-x pose adapter, exports COCO-17 body points and six foot points, and disables all SAM/temporal/anatomical 3D and coaching stages. Its new 2D calculation layer produces estimated swing measurements; the friend's separate coach agent owns problems, priority, drills, explanations and progress. The Colab notebook remains a separate entry point.
|
| 8 |
+
|
| 9 |
+
The service includes authenticated uploads, asynchronous progress/status/results, a persistent single-GPU queue, cancellation and process timeouts, restart recovery, checksummed models/results/coach payloads, bounded decoding, local-only media protocols, upload cleanup and artifact retention. CUDA readiness requires actual operator execution; an unavailable GPU produces 503 responses for new jobs. Docker/Compose files, an optional HTTPS proxy, full-result and coach-payload schemas, and a Python client are provided. See [deployment instructions](docs/GPU_API_DEPLOYMENT.md) and [the friend-facing API guide](docs/API_FOR_COACH.md).
|
| 10 |
+
|
| 11 |
+
The API now supplies heuristic swing candidates, estimated visible swing events and nine metric entries per rep. Conditional values include horizontal ankle-to-ankle stride, hip position relative to the lead ankle, eligible physical timing, reference-only nose path and projected knee angle. Anatomical hip-shoulder separation and lateral trunk tilt remain null. Every non-null value is labeled `est`; weak evidence produces nulls with notes. Foot plant does not establish full body-weight loading, and contact does not confirm a bat-ball collision. Unknown capture clocks stay null, and timing metrics require a known constant capture rate of at least 60 FPS. Caller-declared ranges remain supported. See [measurement definitions](docs/BATTING_2D_MEASUREMENTS.md).
|
| 12 |
+
|
| 13 |
+
`GET /v1/analyses/{job_id}/coach-payload` returns only the measurement body for the friend's `POST /v1/coach`; the engine does not call that external service. A [constructed example](examples/coach-payload.example.json) contains one rep and seven non-null estimates. It is demonstration data, not an analysis of the player's video. The friend's supplied documents inform this contract, but their actual validator/service source was unavailable for exact compatibility testing. Their confidence policy may return `nothing_to_judge` for these unvalidated estimates.
|
| 14 |
+
|
| 15 |
+
Engineering evidence for this deployment:
|
| 16 |
+
|
| 17 |
+
- **118 tests passed, 2 skipped** across the current repository suite. In addition to the existing API lifecycle/security checks, tests cover coach-payload delivery and integrity, database migration, no-person capture results, constructed swing arithmetic, separate reps, mirrored/left-handed motion, timing gates, missing-point gaps, capture exclusion, both JSON schemas and the new Colab test/preview path.
|
| 18 |
+
- A fresh Python 3.11 environment with the selected core/API versions passed all **34 API/measurement tests**. Actual CPU inference on a 12-frame derivative diagnostic clip produced body points in 12/12 frames, 17 body points and six foot points per frame, and schema-valid full and coach-only results without PyTorch installed. Its undeclared view correctly produced a capture failure. This is integration evidence, not original-recording accuracy or GPU qualification.
|
| 19 |
+
- Actual Uvicorn HTTP startup returned health 200, GPU readiness 503, unauthenticated requests 401 and authenticated uploads 503 on this CPU-only machine. Both Compose configurations parse successfully.
|
| 20 |
+
- The Docker daemon was unavailable locally, so the Linux image build and API-specific GPU inference were not executed here. The target server still needs the image build, successful CUDA readiness and one original-video upload that completes. Previous Colab evidence confirms these 2D model adapters ran on a T4, but it does not substitute for that deployment check.
|
| 21 |
+
|
| 22 |
+
## Colab test of 2D swing separation
|
| 23 |
+
|
| 24 |
+
[notebooks/batting_2d_test.ipynb](notebooks/batting_2d_test.ipynb) now exposes the same GPU 2D worker directly. Its eight numbered steps cover authenticated source checkout, isolated GPU dependencies, two verified model downloads and actual CUDA preflight, one multi-swing video upload, progress, range/metric tables, optional inspection clips and selective ZIP download. It does not initialize 3D models or call the coach API. The old full-pipeline notebook remains separate.
|
| 25 |
+
|
| 26 |
+
The inspection helper encodes each selected inclusive frame range into an MP4 with raw body points and estimated event labels. It preserves source playback presentation positions relative to the clip start, verifies encoded frame counts/timestamps, handles image rotation and records resizing/audio omissions. These previews do not modify measurement data or add clip export to the HTTP API. Missing/nonmonotonic playback timestamps withhold a preview. Downloads exclude the original video, credentials, models and stale previews.
|
| 27 |
+
|
| 28 |
+
All **7 Colab/preview checks** passed in the local core and separate Python 3.11 environments. They validate the notebook schema/cell syntax and deterministic builder, real encoding of variable-cadence fixture frame ranges, pixel/frame identity, rotation, overlays, preview limits, timestamp abstention, empty/overlapping ranges and ZIP contents. Actual execution of this new notebook on Colab CUDA and split/event accuracy on original baseball footage remain pending. This notebook tests the direct worker, not the Docker HTTP server.
|
| 29 |
+
|
| 30 |
+
## Supplied Colab report and runtime repair
|
| 31 |
+
|
| 32 |
+
The supplied `session-001-results (1).zip` was produced from commit `04515c0`. Its final run contained 338 frames, zero usable observations, and all three ONNX branches marked `failed_preflight`: "Requested CUDA session did not initialize on CUDA". Body reconstruction was disabled. The archive did not contain the original recording or native CUDA loader logs, so the precise driver/library failure is not established by that archive alone.
|
| 33 |
+
|
| 34 |
+
The updated GPU installer explicitly includes ONNX CUDA/cuDNN extras and installs ONNX locally in the chosen worker, checks GPU availability, and requires actual vision preflight before automatic analysis. Full-worker observations and their preflight use the full environment. Reports distinguish empty/failed observations from usable coverage, show setup issues, and save the actual observation environment. Failed observation chunks are retried after repair. No silent CPU substitution was introduced.
|
| 35 |
+
|
| 36 |
+
The archive's exported annotated video was decoded and rerun as a diagnostic on the local CPU using the same three artifact hashes. That derivative recording produced body observations in **338/338 frames**, five projected metrics and 282 bat proposals across 244 frames. It produced no measured bat endpoints or ball observations. Bat identity requires a reviewed endpoint seed or a qualified trained endpoint checkpoint. This diagnostic is not an original-recording, physical-clock, GPU or measurement-accuracy validation.
|
| 37 |
+
|
| 38 |
+
The newer `session-001-results (3).zip`, from commit `0eb70ee`, records a Tesla T4 / Python 3.11 full worker with all three ONNX branches ready. Its 1,898-frame recording produced supported core-body observations in 1,859 frames, including all 19 core landmarks in 1,609 frames. There were 433 bat proposals across 431 frames, zero supported bat endpoint frames, seven ball candidate frames, and five available projected metrics out of 27. All five reported swing events remained unknown. Visual inspection shows multiple practice swings and setup/walking footage within the 64.275-second clip, so whole-clip medians do not describe a single swing. The 60 active observation artifacts passed their archived SHA256 checks.
|
| 39 |
+
|
| 40 |
+
These coverage counts describe score-qualified model outputs, not verified visible joints. Sampled setup frame 17 includes inferred leg positions despite the legs being outside the view; its projected left-knee value is 170.91 degrees. The sampled ball candidate at frame 1886 falls on a toe. Automatic visibility/quality exclusion and ball identity qualification remain gaps, alongside per-swing splitting and a qualified automatic endpoint model.
|
| 41 |
+
|
| 42 |
+
SAM initialization stopped before model inference because the isolated worker inherited `MPLBACKEND=module://matplotlib_inline.backend_inline` from Colab. Temporal fitting and anatomy were consequently unavailable. Worker subprocesses now explicitly use `MPLBACKEND=Agg`, leaving the notebook's own environment unchanged. Real local stage launches with the poisoned parent backend passed, as did eight relevant runtime/recovery/anatomy tests (one OpenSim test skipped in the core environment). Full SAM inference on the supplied T4 runtime still requires a rerun; this fix does not qualify 3D measurements or add automatic bat endpoints, contact confirmation, or repetition splitting.
|
| 43 |
+
|
| 44 |
+
| Area | Implementation delivered | Remaining execution/validation |
|
| 45 |
+
|---|---|---|
|
| 46 |
+
| Contracts/resources | Capture/observation/motion/event/metric/finding records; versions, provenance and pinned resource/configuration definitions | Provider-dependent readiness is established by actual preflight, not package names. |
|
| 47 |
+
| Ingestion/runtime | Source PTS, separate physical clock, orientation/quality, isolated workers, candidate Python 3.11 full-worker installer and durable/exportable caches | Supplied T4 archive confirms successful 2D GPU execution. Full SAM/temporal/anatomy clip execution remains pending after the plotting-backend repair. |
|
| 48 |
+
| Body/bat/ball observations | Explicit RTMW/YOLOX adapters, stable identity, review, seeded contour/flow, variable-time ball association, qualified endpoint CNN inference | Generic models are available; baseball accuracy and learned endpoint generalization require reviewed footage. |
|
| 49 |
+
| Events/reporting | Directional load/onset, grounded foot candidates, closest projected approach, interaction/outgoing-ball candidate, synchronized reviewed audio corroboration, follow-through settling, reviewed outcomes and qualified trained candidates | Automatic candidates never force a confirmed contact. Real event accuracy remains unmeasured. |
|
| 50 |
+
| Temporal body fitting | Exact loaded MHR regressor, shared clip shape/scales, batched differentiable forward, Adam/L-BFGS, robust reprojection, priors/limits, real-time penalties, gaps, residuals and sensitivity | Synthetic optimizer checks pass. Actual bundled MHR/SAM GPU/full-clip differentiation and memory qualification need accessible assets/CUDA. |
|
| 51 |
+
| Anatomy | Generated project-owned 35-DOF `.osim`, explicit frames/markers, per-subject neutral proportions, weighted OpenSim IK, sparse refinement and rollback | Local OpenSim/FK/IK/refinement checks pass. Real-video anatomical accuracy and integrated GPU-memory qualification remain pending. |
|
| 52 |
+
| Independent bat 3D | Documented independent grip or synchronized calibrated multiview; ambiguity/ray/cheirality/reprojection/length gates | Disabled without independent geometry. Real calibrated-recording validation remains pending. |
|
| 53 |
+
| Measurements | Continuous raw/fitted curves, event-aligned projected/3D flexion, ground geometry, axial twist/heading, rotation-log velocity and peak timing, independent bat speed/attack direction with gates | Outputs remain experimental/reference-validation-pending. Physical timing/world/contact omissions produce nulls. |
|
| 54 |
+
| Feedback/history | Template rule engine, source/context/repeated-trial/uncertainty gates, sourced tee-practice educational hypothesis and version-matched supplied-ID history | No coach review, corrective benefit, persistent fault, ideal angle or overall score is claimed. |
|
| 55 |
+
| Training/evaluation | Reviewed crop/heatmap and phase/boundary/presence datasets, athlete/session split checks, actual optimization, validation selection, held-out metrics and hash-bound qualification | No pretrained baseball custom-head weights are fabricated. Suitable reviewed datasets and passed evaluation are required for activation. |
|
| 56 |
+
| Reliability/reference tooling | Verified chunk recovery/export, forced termination/resume checks, grouped data, independent-reference and distribution-table evaluation tools | Independent synchronized biomechanical references, preregistered requirements and coaching studies remain to be acquired/evaluated. |
|
| 57 |
+
|
| 58 |
+
## Executed engineering evidence
|
| 59 |
+
|
| 60 |
+
- The earlier core build passed **78 engineering tests, with 1 skipped**. The skipped test requires OpenSim in that environment and was executed separately in the anatomical environment. These checks cover source timing, transforms, null/failure behavior, reviewed outcomes, actual training steps, official MS-TCN++ forward/gradients, geometry ambiguity, triangulation, optimizer arithmetic, feedback gates, chunk equivalence, forced worker termination/recovery, notebook/Git setup and exports. The current combined suite count is recorded in the API section above.
|
| 61 |
+
- The separate OpenSim 4.6/macOS Python 3.13 environment passed the two anatomical test functions: neutral 35-DOF topology/mapping, OpenSim versus independent primitive FK, weighted IK and sparse refinement. A 180° camera-axis-flip IK check also passed. The earlier five-frame weighted IK fixture's maximum marker residual was approximately 0.00005 m; primitive FK agreement was within floating-point roundoff. This is synthetic arithmetic, not anatomical accuracy.
|
| 62 |
+
- All 33 selected direct SAM worker/installer version pins were found in official PyPI metadata. The complete Linux CUDA dependency combination remains a candidate until installed and executed in Colab.
|
| 63 |
+
- The three selected ONNX artifacts previously passed local CPU smoke inference; the RTMW adapter matched pinned RTMLib on a blank-image fixture. That does not validate baseball poses.
|
| 64 |
+
- Notebook schema/cell syntax and source checkout pinning are checked locally. The user-supplied venv repair remains; the GPU install now includes CUDA/cuDNN extras and installs ONNX locally to avoid inherited-package conflicts.
|
| 65 |
+
|
| 66 |
+
## Runtime boundaries
|
| 67 |
+
|
| 68 |
+
The local core uses Python 3.10 / ONNX Runtime 1.23.2; local anatomy checks use a separate Python 3.13 / OpenSim 4.6 environment. Neither qualifies the selected Colab Python 3.11 / CUDA 12.8 / ONNX GPU 1.26 / SAM profile. RTMLib is deliberately installed with `--no-deps` against headless OpenCV; its GUI OpenCV distribution metadata mismatch remains separately recorded.
|
| 69 |
+
|
| 70 |
+
SAM source revision is pinned to `b5c765a0d89d789985e186d396315e7590887b94`. Its estimator/MHR/projection APIs were checked against primary source. Actual provider assets were not downloaded or GPU-executed here. MS-TCN++ uses valid revision `aef4e46c31bc7b2462065354054f968f91e54be1`; the current upstream tip contains a syntax error and is not imported.
|
| 71 |
+
|
| 72 |
+
The supplied archive includes an exported annotated batting clip, used for a local diagnostic rerun. No original user recording or independent paired biomechanics reference is available. Therefore clean-session GPU integration, real-recording accuracy, custom-weight generalization, expert agreement and exercise effectiveness remain unverified. The backend implementation and evaluation tools are supplied so these next tests can be performed explicitly.
|
Dockerfile
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim-bookworm
|
| 2 |
+
|
| 3 |
+
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
|
| 4 |
+
PIP_NO_CACHE_DIR=1 BASEBALL_MODEL_ROOT=/opt/models BASEBALL_DATA_ROOT=/data \
|
| 5 |
+
NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility
|
| 6 |
+
WORKDIR /app
|
| 7 |
+
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini \
|
| 8 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 9 |
+
COPY requirements-core.txt requirements-api.txt requirements-api-gpu.txt ./
|
| 10 |
+
RUN python -m pip install --only-binary=:all: -r requirements-api-gpu.txt \
|
| 11 |
+
&& python -m pip install --no-deps rtmlib==0.0.16
|
| 12 |
+
COPY pyproject.toml ./
|
| 13 |
+
COPY baseball_batting ./baseball_batting
|
| 14 |
+
COPY configs ./configs
|
| 15 |
+
COPY tools/setup_api_models.py ./tools/setup_api_models.py
|
| 16 |
+
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 |
+
RUN python -m tools.setup_api_models --output /opt/models \
|
| 20 |
+
&& python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \
|
| 21 |
+
&& groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \
|
| 22 |
+
&& mkdir -p /data && chown baseball:baseball /data
|
| 23 |
+
USER baseball
|
| 24 |
+
EXPOSE 8000
|
| 25 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=180s --retries=3 \
|
| 26 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/readyz', timeout=3)"
|
| 27 |
+
ENTRYPOINT ["/usr/bin/tini", "--"]
|
| 28 |
+
CMD ["python", "-m", "uvicorn", "baseball_batting.api:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--timeout-graceful-shutdown", "20", "--no-access-log"]
|
README.md
CHANGED
|
@@ -1,11 +1,16 @@
|
|
| 1 |
---
|
| 2 |
-
title: Baseball Engine
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
-
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Baseball Engine 2D API
|
| 3 |
+
emoji: ⚾
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 8000
|
| 8 |
pinned: false
|
| 9 |
+
short_description: GPU 2D batting analysis API
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Baseball engine 2D API
|
| 13 |
+
|
| 14 |
+
GPU API for batting recordings: upload a swing, poll the job, and download the result or the coach payload. Every `/v1/` call needs `Authorization: Bearer <BASEBALL_API_KEY>`. `/readyz` returns 200 once CUDA inference has passed at startup.
|
| 15 |
+
|
| 16 |
+
This file becomes the Space's `README.md` on deploy. The GitHub workflow `.github/workflows/deploy-huggingface.yml` copies `main` on top of the Space when a push changes the app, replacing same-named files edited directly on Hugging Face. See `docs/GPU_API_DEPLOYMENT.md` and `docs/API_FOR_COACH.md`.
|
baseball_batting/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batting research engine. Importing this package never loads or downloads models."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.2.0"
|
| 4 |
+
|
baseball_batting/advanced_metrics.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event-aligned, model-based and independent geometry measurements with explicit gates."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .contracts import Metric, RTMW_CORE
|
| 5 |
+
from .geometry import ground_pixels_to_metres, to_world, rotation
|
| 6 |
+
from .motion import angular_velocity, heading, wrapped_difference
|
| 7 |
+
from .metrics import flexion_degrees, derivative
|
| 8 |
+
from .storage import read_json
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def event_indices(events,name,max_width=2):
|
| 12 |
+
eligible=[e for e in events if e.type==name and e.state=="confirmed" and e.frame_interval]
|
| 13 |
+
if len(eligible)!=1:return None,None,"event_unconfirmed_or_ambiguous"
|
| 14 |
+
e=eligible[0];a,b=e.frame_interval
|
| 15 |
+
if b-a>max_width:return None,e.event_id,"event_interval_too_wide"
|
| 16 |
+
return np.arange(a,b+1),e.event_id,None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def augment(root,curves,metrics,events,capture,quality,enabled=None):
|
| 20 |
+
root=Path(root);clock=capture["timing_source"].get("kind","unknown")
|
| 21 |
+
calibration=capture["metadata"].get("calibration",{})
|
| 22 |
+
n=capture["frame_count"]
|
| 23 |
+
enabled=enabled or {}
|
| 24 |
+
if enabled.get("anatomy") and (root/"temporal3d_status.json").exists():
|
| 25 |
+
temporal=read_json(root/"temporal3d_status.json")
|
| 26 |
+
if temporal.get("status") in {"complete","partial"}:
|
| 27 |
+
data=np.load(root/temporal["trajectory_path"],allow_pickle=False)
|
| 28 |
+
curves["raw_body3d_camera_m"]=data["raw_camera_m"]
|
| 29 |
+
curves["fitted_body3d_camera_m"]=data["keypoints_camera_m"]
|
| 30 |
+
curves["body3d_reprojection_px"]=data["reprojection_px"]
|
| 31 |
+
physical=np.array([f["physical_s"] for f in capture["frames"]],float)
|
| 32 |
+
timing_ok=capture["physical_clock_known"] and not any({"duplicate_pts","nonmonotonic_pts","missing_pts","duplicate_image","timestamp_gap_or_variable_cadence"}&set(f["flags"]) for f in capture["frames"])
|
| 33 |
+
def emit(name,values,unit,geometry,event=None,reason=None,provenance=None,summary="mean",uncertainty="unknown"):
|
| 34 |
+
used=np.arange(n) if event is None else event[0]
|
| 35 |
+
event_id=None if event is None else event[1]
|
| 36 |
+
if event is not None:reason=reason or event[2]
|
| 37 |
+
value=None;valid=np.array([],int)
|
| 38 |
+
if reason is None and values is not None and used is not None:
|
| 39 |
+
used=np.asarray(used,int);v=np.asarray(values)[used];valid=used[np.isfinite(v)]
|
| 40 |
+
if event is not None and len(valid)!=len(used):reason="event_samples_missing"
|
| 41 |
+
elif not len(valid):reason="missing_supported_samples"
|
| 42 |
+
else:
|
| 43 |
+
sample=np.asarray(values)[valid]
|
| 44 |
+
value=float(np.max(sample) if summary=="max" else np.median(sample) if summary=="median" else np.mean(sample))
|
| 45 |
+
elif reason is None:reason="stage_unavailable"
|
| 46 |
+
metrics[:]=[m for m in metrics if m.metric_id!=name]
|
| 47 |
+
metrics.append(Metric(name,"1.1",value,unit,"supported" if value is not None else "unsupported",
|
| 48 |
+
provenance or [],valid.tolist(),geometry,clock,reason,event_id,uncertainty))
|
| 49 |
+
# Event-aligned image measures preserve the distinction from full-recording summaries.
|
| 50 |
+
contact=event_indices(events,"contact",quality["max_event_interval_frames"])
|
| 51 |
+
foot=event_indices(events,"lead_foot_contact",quality["max_event_interval_frames"])
|
| 52 |
+
onset=event_indices(events,"forward_swing_onset",quality["max_event_interval_frames"])
|
| 53 |
+
for side in ("left","right"):
|
| 54 |
+
for joint in ("knee","elbow"):
|
| 55 |
+
emit(f"{side}_{joint}_fitted_3d_flexion_median",None,"deg","not_established",reason="anatomical_fit_unavailable")
|
| 56 |
+
for name,unit in (("pelvis_thorax_axial_twist_at_contact","deg"),("thorax_peak_angular_velocity","deg/s"),("thorax_minus_pelvis_peak_time","s")):
|
| 57 |
+
emit(name,None,unit,"not_established",reason="anatomical_fit_or_required_context_unavailable")
|
| 58 |
+
for side in ("left","right"):
|
| 59 |
+
for joint in ("knee","elbow"):
|
| 60 |
+
emit(f"{side}_{joint}_projected_flexion_at_contact",curves[f"{side}_{joint}_projected_flexion_deg"],"deg_projected",
|
| 61 |
+
"oriented_image_projection",contact,provenance=["body_observations"])
|
| 62 |
+
try:
|
| 63 |
+
feet=np.stack([curves["body_pixels"][:,RTMW_CORE[s+"_big_toe"]] for s in ("left","right")],1)
|
| 64 |
+
feet=ground_pixels_to_metres(feet,calibration)
|
| 65 |
+
# A calibrated planar result requires independently reviewed on-ground support.
|
| 66 |
+
ground_context=capture["metadata"].get("event_context",{})
|
| 67 |
+
if not ground_context.get("source"):raise ValueError("ground_contact_review_source_missing")
|
| 68 |
+
support=ground_context.get("ground_contact_frames",[])
|
| 69 |
+
if any(not isinstance(i,int) or not 0<=i<n for i in support):raise ValueError("ground_contact_frame_outside_video")
|
| 70 |
+
grounded=np.zeros(n,bool);grounded[np.asarray(support,int)]=True
|
| 71 |
+
feet[~grounded]=np.nan
|
| 72 |
+
span=np.linalg.norm(feet[:,0]-feet[:,1],axis=1);curves["ground_plane_stance_span_m"]=span
|
| 73 |
+
emit("ground_plane_stance_span",span,"m","verified_ground_homography",foot,provenance=["ground_contact_review","body_observations"])
|
| 74 |
+
lead=capture["metadata"].get("event_context",{}).get("lead_side")
|
| 75 |
+
if lead not in {"left","right"}:raise ValueError("lead_side_unknown")
|
| 76 |
+
if onset[2] or foot[2]:raise ValueError("stride_events_unconfirmed")
|
| 77 |
+
a,b=onset[0][0],foot[0][-1]
|
| 78 |
+
displacement=np.linalg.norm(feet[b,0 if lead=="left" else 1]-feet[a,0 if lead=="left" else 1])
|
| 79 |
+
if not np.isfinite(displacement):raise ValueError("stride_endpoints_not_ground_supported")
|
| 80 |
+
emit("ground_plane_stride_length",np.full(n,displacement),"m","verified_ground_homography",foot,provenance=["ground_contact_review","body_observations"])
|
| 81 |
+
except (ValueError,KeyError,IndexError) as error:
|
| 82 |
+
emit("ground_plane_stride_length",None,"m","not_established",reason=str(error))
|
| 83 |
+
# Frame rotations are exported by our explicit proxy model. World headings
|
| 84 |
+
# require documented calibration; flexion itself is rigid-transform invariant.
|
| 85 |
+
try:
|
| 86 |
+
if not enabled.get("anatomy") or not (root/"anatomy_status.json").exists():raise ValueError("anatomical_fit_unavailable")
|
| 87 |
+
status=read_json(root/"anatomy_status.json")
|
| 88 |
+
if status["status"] not in {"complete","partial"}:raise ValueError("anatomical_fit_unavailable")
|
| 89 |
+
sensitivity=status.get("maximum_regularization_sensitivity_m")
|
| 90 |
+
if sensitivity is not None and sensitivity>quality["max_regularization_sensitivity_m"]:
|
| 91 |
+
raise ValueError("anatomical_regularization_sensitivity_exceeds_profile_limit")
|
| 92 |
+
data=np.load(root/status["trajectory_path"],allow_pickle=False)
|
| 93 |
+
names=data["marker_names"].tolist();points=data["marker_positions_m"]
|
| 94 |
+
for side in ("left","right"):
|
| 95 |
+
for joint,parts in (("elbow",("shoulder","elbow","wrist")),("knee",("hip","knee","ankle"))):
|
| 96 |
+
values=flexion_degrees(*[points[:,names.index(side+"_"+p)] for p in parts])
|
| 97 |
+
curves[f"{side}_{joint}_fitted_3d_flexion_deg"]=values
|
| 98 |
+
emit(f"{side}_{joint}_fitted_3d_flexion_median",values,"deg",status["geometry_source"],summary="median",provenance=["MHR_fitted_proxy","OpenSim_IK"],uncertainty="fit_and_regularization_sensitivity")
|
| 99 |
+
segments=data["segment_names"].tolist();r=data["segment_rotations"]
|
| 100 |
+
from scipy.spatial.transform import Rotation
|
| 101 |
+
relative=r[:,segments.index("pelvis")].transpose(0,2,1)@r[:,segments.index("thorax")]
|
| 102 |
+
valid=np.isfinite(relative).all(axis=(1,2));twist=np.full(n,np.nan)
|
| 103 |
+
quaternion=Rotation.from_matrix(relative[valid]).as_quat()
|
| 104 |
+
# Twist about pelvis-local cranial Y, separate from horizontal headings.
|
| 105 |
+
twist[valid]=np.degrees(2*np.arctan2(quaternion[:,1],quaternion[:,3]))
|
| 106 |
+
twist=np.degrees(np.arctan2(np.sin(np.radians(twist)),np.cos(np.radians(twist))))
|
| 107 |
+
curves["pelvis_thorax_axial_twist_deg"]=twist
|
| 108 |
+
emit("pelvis_thorax_axial_twist_at_contact",twist,"deg",status["geometry_source"],contact,provenance=["MHR_fitted_proxy","pelvis_local_Y_swing_twist"],uncertainty="fit_and_regularization_sensitivity")
|
| 109 |
+
to_world(np.zeros((1,3)),calibration) # Validate world convention before rotations.
|
| 110 |
+
transform=rotation(calibration["world_from_camera"]["rotation"])
|
| 111 |
+
pelvis=transform@r[:,segments.index("pelvis")];thorax=transform@r[:,segments.index("thorax")]
|
| 112 |
+
separation=np.degrees(wrapped_difference(heading(thorax),heading(pelvis)))
|
| 113 |
+
curves["pelvis_thorax_heading_separation_deg"]=separation
|
| 114 |
+
emit("pelvis_thorax_heading_separation",separation,"deg","calibrated_world_model_proxy",contact,provenance=["MHR_fitted_proxy","OpenSim_IK"],uncertainty="fit_and_regularization_sensitivity")
|
| 115 |
+
if not timing_ok:raise ValueError("physical_clock_or_timing_integrity_failed")
|
| 116 |
+
velocity=angular_velocity(pelvis,physical);curves["pelvis_angular_velocity_world_rad_s"]=velocity
|
| 117 |
+
speed=np.degrees(np.linalg.norm(velocity,axis=1))
|
| 118 |
+
emit("pelvis_peak_angular_velocity",speed,"deg/s","calibrated_world_model_proxy",summary="max",provenance=["MHR_fitted_proxy","rotation_log_derivative"],uncertainty="position_and_derivative_sensitivity_pending")
|
| 119 |
+
thorax_velocity=angular_velocity(thorax,physical);curves["thorax_angular_velocity_world_rad_s"]=thorax_velocity
|
| 120 |
+
thorax_speed=np.degrees(np.linalg.norm(thorax_velocity,axis=1))
|
| 121 |
+
emit("thorax_peak_angular_velocity",thorax_speed,"deg/s","calibrated_world_model_proxy",summary="max",provenance=["MHR_fitted_proxy","rotation_log_derivative"],uncertainty="position_and_derivative_sensitivity_pending")
|
| 122 |
+
good_p,good_t=np.flatnonzero(np.isfinite(speed)),np.flatnonzero(np.isfinite(thorax_speed))
|
| 123 |
+
if len(good_p) and len(good_t):
|
| 124 |
+
p,t=good_p[np.argmax(speed[good_p])],good_t[np.argmax(thorax_speed[good_t])]
|
| 125 |
+
emit("thorax_minus_pelvis_peak_time",np.full(n,physical[t]-physical[p]),"s","calibrated_world_model_proxy",provenance=["MHR_fitted_proxy","rotation_log_peak_timing"],uncertainty="derivative_sensitivity_pending")
|
| 126 |
+
except (ValueError,KeyError,FileNotFoundError) as error:
|
| 127 |
+
for name,unit in (("pelvis_thorax_heading_separation","deg"),("pelvis_peak_angular_velocity","deg/s")):
|
| 128 |
+
if not any(m.metric_id==name and m.value is not None for m in metrics):emit(name,None,unit,"not_established",reason=str(error))
|
| 129 |
+
try:
|
| 130 |
+
if not enabled.get("bat3d") or not (root/"bat3d_status.json").exists():raise ValueError("independent_bat_geometry_unavailable")
|
| 131 |
+
status=read_json(root/"bat3d_status.json")
|
| 132 |
+
if status["status"] not in {"partial","complete"}:raise ValueError("independent_bat_geometry_unavailable")
|
| 133 |
+
data=np.load(root/status["trajectory_path"],allow_pickle=False);sweet=data["sweet_spot_world_m"]
|
| 134 |
+
curves["bat_sweet_spot_world_m"]=sweet
|
| 135 |
+
if not np.isfinite(sweet).any():raise ValueError("bat_world_frame_unavailable")
|
| 136 |
+
if not timing_ok:raise ValueError("physical_clock_or_timing_integrity_failed")
|
| 137 |
+
velocity=derivative(sweet,physical);curves["bat_sweet_spot_velocity_world_m_s"]=velocity
|
| 138 |
+
speed=np.linalg.norm(velocity,axis=1)
|
| 139 |
+
attack=np.degrees(np.arctan2(velocity[:,1],np.linalg.norm(velocity[:,[0,2]],axis=1)))
|
| 140 |
+
attack[speed<1e-6]=np.nan;curves["bat_attack_direction_deg"]=attack
|
| 141 |
+
emit("bat_sweet_spot_speed_at_contact",speed,"m/s",status["geometry_source"],contact,provenance=["independent_bat_geometry","nonuniform_time_derivative"],uncertainty="geometry_and_event_sensitivity_pending")
|
| 142 |
+
emit("bat_attack_angle_at_contact",attack,"deg",status["geometry_source"],contact,provenance=["independent_bat_geometry","velocity_direction"],uncertainty="geometry_and_event_sensitivity_pending")
|
| 143 |
+
except (ValueError,KeyError,FileNotFoundError) as error:
|
| 144 |
+
for name,unit in (("bat_sweet_spot_speed_at_contact","m/s"),("bat_attack_angle_at_contact","deg")):
|
| 145 |
+
emit(name,None,unit,"not_established",reason=str(error))
|
| 146 |
+
return metrics
|
baseball_batting/anatomy.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit 35-DOF OpenSim kinematic proxy, weighted IK and sparse sequence refinement."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.optimize import least_squares
|
| 5 |
+
from scipy.spatial.transform import Rotation
|
| 6 |
+
from .temporal3d import MHR_CORE
|
| 7 |
+
from .motion import contiguous_segments, sparse_temporal_pattern
|
| 8 |
+
from .storage import StageCache, digest, atomic_json, read_json, sha256_file
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def unit(vector):
|
| 12 |
+
vector = np.asarray(vector, float)
|
| 13 |
+
if np.linalg.norm(vector) < 1e-8:
|
| 14 |
+
raise ValueError("Degenerate neutral segment frame")
|
| 15 |
+
return vector/np.linalg.norm(vector)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pin_frame(axis, reference):
|
| 19 |
+
z = unit(axis)
|
| 20 |
+
x = np.asarray(reference)-z*np.dot(reference, z)
|
| 21 |
+
if np.linalg.norm(x) < 1e-8:
|
| 22 |
+
x = np.eye(3)[np.argmin(np.abs(z))]; x -= z*np.dot(x, z)
|
| 23 |
+
x = unit(x)
|
| 24 |
+
return np.column_stack([x, np.cross(z, x), z])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def model_spec(neutral, settings):
|
| 28 |
+
"""Landmark-derived origins/offsets are proxies, never assumed native rig centres."""
|
| 29 |
+
neutral = np.asarray(neutral, float)
|
| 30 |
+
if neutral.shape != (70, 3) or not np.isfinite(neutral).all():
|
| 31 |
+
raise ValueError("Neutral MHR70 must contain 70 finite metre positions")
|
| 32 |
+
p = {name: neutral[index] for name, index in MHR_CORE.items()}
|
| 33 |
+
hip = (p["left_hip"]+p["right_hip"])/2
|
| 34 |
+
shoulders = (p["left_shoulder"]+p["right_shoulder"])/2
|
| 35 |
+
y = unit(shoulders-hip)
|
| 36 |
+
x = unit(p["left_hip"]-p["right_hip"])
|
| 37 |
+
x = unit(x-y*np.dot(x, y)); z = unit(np.cross(x, y))
|
| 38 |
+
basis = np.column_stack([x, y, z])
|
| 39 |
+
bodies = {"pelvis": {"origin": hip.tolist(), "rotation": basis.tolist()},
|
| 40 |
+
"thorax": {"origin": shoulders.tolist(), "rotation": basis.tolist()}}
|
| 41 |
+
joints, coordinates, markers = [], [], {}
|
| 42 |
+
|
| 43 |
+
def joint(name, kind, parent, child, centre, frame):
|
| 44 |
+
if child not in bodies:
|
| 45 |
+
bodies[child] = {"origin": np.asarray(centre).tolist(), "rotation": basis.tolist()}
|
| 46 |
+
parent_origin = np.zeros(3) if parent == "ground" else np.array(bodies[parent]["origin"])
|
| 47 |
+
parent_rotation = np.eye(3) if parent == "ground" else np.array(bodies[parent]["rotation"])
|
| 48 |
+
child_origin, child_rotation = np.array(bodies[child]["origin"]), np.array(bodies[child]["rotation"])
|
| 49 |
+
n = {"FreeJoint": 6, "BallJoint": 3, "PinJoint": 1, "UniversalJoint": 2}[kind]
|
| 50 |
+
ids = list(range(len(coordinates), len(coordinates)+n))
|
| 51 |
+
for i in range(n):
|
| 52 |
+
bounds = [-100, 100] if kind == "FreeJoint" and i >= 3 else settings["soft_coordinate_range_rad"]
|
| 53 |
+
if kind == "UniversalJoint": bounds = settings["universal_range_rad"]
|
| 54 |
+
coordinates.append({"name": name+"_"+str(i), "unit": "m" if kind == "FreeJoint" and i >= 3 else "rad", "range": bounds})
|
| 55 |
+
joints.append({"name": name, "kind": kind, "parent": parent, "child": child, "coordinates": ids,
|
| 56 |
+
"parent_location": (parent_rotation.T@(centre-parent_origin)).tolist(),
|
| 57 |
+
"child_location": (child_rotation.T@(centre-child_origin)).tolist(),
|
| 58 |
+
"parent_orientation": (parent_rotation.T@frame).tolist(),
|
| 59 |
+
"child_orientation": (child_rotation.T@frame).tolist()})
|
| 60 |
+
|
| 61 |
+
# Root at its neutral origin: the six coordinates encode changes from neutral.
|
| 62 |
+
joint("root", "FreeJoint", "ground", "pelvis", hip, basis)
|
| 63 |
+
joint("pelvis_thorax", "BallJoint", "pelvis", "thorax", (hip+shoulders)/2, basis)
|
| 64 |
+
for side in ("left", "right"):
|
| 65 |
+
hip_p, knee, ankle = [p[side+"_"+n] for n in ("hip", "knee", "ankle")]
|
| 66 |
+
shoulder, elbow, wrist = [p[side+"_"+n] for n in ("shoulder", "elbow", "wrist")]
|
| 67 |
+
joint(side+"_hip", "BallJoint", "pelvis", side+"_thigh", hip_p, basis)
|
| 68 |
+
joint(side+"_knee", "PinJoint", side+"_thigh", side+"_shank", knee, pin_frame(x, y))
|
| 69 |
+
joint(side+"_ankle", "UniversalJoint", side+"_shank", side+"_foot", ankle, basis)
|
| 70 |
+
joint(side+"_shoulder", "BallJoint", "thorax", side+"_upper_arm", shoulder, basis)
|
| 71 |
+
# Flexion plane is defined explicitly in the neutral frame; no scapular DoF.
|
| 72 |
+
hinge = np.cross(unit(elbow-shoulder), y)
|
| 73 |
+
joint(side+"_elbow", "PinJoint", side+"_upper_arm", side+"_forearm", elbow, pin_frame(hinge, y))
|
| 74 |
+
joint(side+"_forearm_rotor", "PinJoint", side+"_forearm", side+"_rotor", elbow, pin_frame(wrist-elbow, y))
|
| 75 |
+
joint(side+"_wrist", "UniversalJoint", side+"_rotor", side+"_hand", wrist, basis)
|
| 76 |
+
assignments = {"hip": "pelvis", "knee": side+"_thigh", "ankle": side+"_shank",
|
| 77 |
+
"big_toe": side+"_foot", "small_toe": side+"_foot", "heel": side+"_foot",
|
| 78 |
+
"shoulder": "thorax", "elbow": side+"_upper_arm", "wrist": side+"_rotor"}
|
| 79 |
+
for part, body in assignments.items():
|
| 80 |
+
name = side+"_"+part
|
| 81 |
+
markers[name] = {"body": body, "offset": (basis.T@(p[name]-bodies[body]["origin"])).tolist(), "mhr70_index": MHR_CORE[name]}
|
| 82 |
+
# Dorsal hand regression proxies give wrist/rotor some orientation support.
|
| 83 |
+
for name, index in ((side+"_index_mcp", 49 if side == "left" else 28),
|
| 84 |
+
(side+"_little_mcp", 61 if side == "left" else 40)):
|
| 85 |
+
markers[name] = {"body": side+"_hand", "offset": (basis.T@(neutral[index]-wrist)).tolist(), "mhr70_index": index}
|
| 86 |
+
if len(coordinates) != 35:
|
| 87 |
+
raise AssertionError("Model must have exactly 35 coordinates")
|
| 88 |
+
return {"schema_version": "1.0", "model_id": settings["model_id"], "version": settings["version"],
|
| 89 |
+
"bodies": bodies, "joints": joints, "coordinates": coordinates, "markers": markers,
|
| 90 |
+
"source_kind": "model_regression_proxy", "independent_observation": False,
|
| 91 |
+
"neutral_basis_definition": "x toward anatomical left; y cranial; z x cross y",
|
| 92 |
+
"coordinate_definition": "primitive coordinates; named measurements derive from segment frames",
|
| 93 |
+
"dynamics": "disabled; placeholder masses and inertia"}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def forward_kinematics(spec, q):
|
| 97 |
+
"""Mirror the documented Free/Ball XYZ, Pin Z and Universal XY primitives."""
|
| 98 |
+
transforms = {"ground": (np.eye(3), np.zeros(3))}
|
| 99 |
+
for j in spec["joints"]:
|
| 100 |
+
r_parent, t_parent = transforms[j["parent"]]
|
| 101 |
+
values = np.asarray(q)[j["coordinates"]]
|
| 102 |
+
if j["kind"] in {"BallJoint", "FreeJoint"}:
|
| 103 |
+
rotation = Rotation.from_euler("XYZ", values[:3]).as_matrix()
|
| 104 |
+
elif j["kind"] == "PinJoint":
|
| 105 |
+
rotation = Rotation.from_euler("Z", values[0]).as_matrix()
|
| 106 |
+
else:
|
| 107 |
+
rotation = Rotation.from_euler("XY", values).as_matrix()
|
| 108 |
+
r = r_parent@j["parent_orientation"]@rotation@np.asarray(j["child_orientation"]).T
|
| 109 |
+
shift = values[3:] if j["kind"] == "FreeJoint" else np.zeros(3)
|
| 110 |
+
t = t_parent+r_parent@np.asarray(j["parent_location"])+r_parent@j["parent_orientation"]@shift-r@j["child_location"]
|
| 111 |
+
transforms[j["child"]] = (r, t)
|
| 112 |
+
markers = np.array([transforms[m["body"]][1]+transforms[m["body"]][0]@m["offset"] for m in spec["markers"].values()])
|
| 113 |
+
return markers, transforms
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def build_opensim(spec, path=None):
|
| 117 |
+
import opensim as osim
|
| 118 |
+
model = osim.Model(); model.setName(spec["model_id"])
|
| 119 |
+
bodies = {}
|
| 120 |
+
def vec(v): return osim.Vec3(*map(float, v))
|
| 121 |
+
for name in spec["bodies"]:
|
| 122 |
+
body = osim.Body(name, 1., osim.Vec3(0), osim.Inertia(1., 1., 1.))
|
| 123 |
+
model.addBody(body); bodies[name] = body
|
| 124 |
+
for j in spec["joints"]:
|
| 125 |
+
parent = model.getGround() if j["parent"] == "ground" else bodies[j["parent"]]
|
| 126 |
+
joint = getattr(osim, j["kind"])(j["name"], parent, vec(j["parent_location"]),
|
| 127 |
+
vec(Rotation.from_matrix(j["parent_orientation"]).as_euler("XYZ")), bodies[j["child"]],
|
| 128 |
+
vec(j["child_location"]), vec(Rotation.from_matrix(j["child_orientation"]).as_euler("XYZ")))
|
| 129 |
+
for i, index in enumerate(j["coordinates"]):
|
| 130 |
+
coordinate = joint.upd_coordinates(i)
|
| 131 |
+
coordinate.setName(spec["coordinates"][index]["name"])
|
| 132 |
+
coordinate.setRangeMin(spec["coordinates"][index]["range"][0])
|
| 133 |
+
coordinate.setRangeMax(spec["coordinates"][index]["range"][1])
|
| 134 |
+
coordinate.setDefaultValue(0.)
|
| 135 |
+
model.addJoint(joint)
|
| 136 |
+
for name, marker in spec["markers"].items():
|
| 137 |
+
model.addMarker(osim.Marker(name, bodies[marker["body"]], vec(marker["offset"])))
|
| 138 |
+
model.finalizeConnections(); model.initSystem()
|
| 139 |
+
if path: model.printToXML(str(path))
|
| 140 |
+
return model
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def trc(path, names, targets, times):
|
| 144 |
+
n = len(times); dt = np.median(np.diff(times)) if n > 1 else 1.
|
| 145 |
+
header = ["PathFileType\t4\t(X/Y/Z)\tmarkers.trc", "DataRate\tCameraRate\tNumFrames\tNumMarkers\tUnits\tOrigDataRate\tOrigDataStartFrame\tOrigNumFrames",
|
| 146 |
+
f"{1/dt}\t{1/dt}\t{n}\t{len(names)}\tm\t{1/dt}\t1\t{n}",
|
| 147 |
+
"Frame#\tTime\t"+"\t".join(name+"\t\t" for name in names),
|
| 148 |
+
"\t\t"+"\t".join(f"X{i+1}\tY{i+1}\tZ{i+1}" for i in range(len(names))), ""]
|
| 149 |
+
for i, (row, time) in enumerate(zip(targets, times)):
|
| 150 |
+
header.append(f"{i+1}\t{time:.10f}\t"+"\t".join(f"{v:.10f}" for v in row.reshape(-1)))
|
| 151 |
+
Path(path).write_text("\n".join(header)+"\n")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def weighted_ik(model, spec, targets, weights, times, workdir):
|
| 155 |
+
import opensim as osim
|
| 156 |
+
names = list(spec["markers"])
|
| 157 |
+
neutral, _ = forward_kinematics(spec, np.zeros(35))
|
| 158 |
+
safe = np.where(np.isfinite(targets), targets, neutral[None])
|
| 159 |
+
marker_file = Path(workdir)/"ik_targets.trc"; trc(marker_file, names, safe, times)
|
| 160 |
+
marker_weights = osim.SetMarkerWeights()
|
| 161 |
+
supported=np.flatnonzero((weights>0).sum(axis=1)>=6)
|
| 162 |
+
if not len(supported):return np.full((len(times),35),np.nan)
|
| 163 |
+
first=int(supported[0])
|
| 164 |
+
for j,name in enumerate(names): marker_weights.cloneAndAppend(osim.MarkerWeight(name, float(weights[first,j])))
|
| 165 |
+
reference = osim.MarkersReference(str(marker_file), marker_weights)
|
| 166 |
+
solver = osim.InverseKinematicsSolver(model, reference, osim.SimTKArrayCoordinateReference())
|
| 167 |
+
solver.setAccuracy(1e-6)
|
| 168 |
+
state = model.initSystem(); coordinates = model.getCoordinateSet()
|
| 169 |
+
out = np.full((len(times), 35), np.nan)
|
| 170 |
+
initialized=False
|
| 171 |
+
for i, time in enumerate(times):
|
| 172 |
+
state.setTime(float(time))
|
| 173 |
+
if (weights[i] > 0).sum() < 6: continue
|
| 174 |
+
try:
|
| 175 |
+
# OpenSim creates its marker goal during assemble(); updating weights
|
| 176 |
+
# before the first assemble dereferences an uninitialized native goal.
|
| 177 |
+
if initialized:
|
| 178 |
+
for j,name in enumerate(names):solver.updateMarkerWeight(name,float(weights[i,j]))
|
| 179 |
+
if i == 0 or not np.isfinite(out[i-1]).all(): solver.assemble(state)
|
| 180 |
+
else: solver.track(state)
|
| 181 |
+
initialized=True
|
| 182 |
+
out[i] = [coordinates.get(c["name"]).getValue(state) for c in spec["coordinates"]]
|
| 183 |
+
except RuntimeError:
|
| 184 |
+
continue
|
| 185 |
+
return out
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def refine_trajectory(spec, initial, targets, weights, times, settings):
|
| 189 |
+
out = initial.copy(); diagnostic = []
|
| 190 |
+
for a, b in contiguous_segments(np.isfinite(initial).all(axis=1), times):
|
| 191 |
+
if b-a < 3: continue
|
| 192 |
+
start = initial[a:b]
|
| 193 |
+
dt = np.diff(times[a:b])
|
| 194 |
+
safe = np.nan_to_num(targets[a:b]); w = np.sqrt(weights[a:b])[..., None]
|
| 195 |
+
lower,upper=np.array([c["range"] for c in spec["coordinates"]]).T
|
| 196 |
+
def data(q): return (np.array([forward_kinematics(spec, row)[0] for row in q])-safe)*w
|
| 197 |
+
def objective(flat):
|
| 198 |
+
q = flat.reshape(-1, 35)
|
| 199 |
+
velocity = np.diff(q, axis=0)/dt[:, None]
|
| 200 |
+
acceleration = np.diff(velocity, axis=0)/((dt[1:]+dt[:-1])/2)[:, None]
|
| 201 |
+
limits=np.maximum(lower-q,0)+np.maximum(q-upper,0)
|
| 202 |
+
return np.r_[data(q).reshape(-1), np.sqrt(settings["temporal_weight"])*acceleration.reshape(-1),.01*limits.reshape(-1)]
|
| 203 |
+
from scipy.sparse import vstack,eye
|
| 204 |
+
pattern=vstack([sparse_temporal_pattern(b-a,35,targets.shape[1]),eye((b-a)*35)],format="csr")
|
| 205 |
+
candidate = least_squares(objective, start.reshape(-1), jac_sparsity=pattern,
|
| 206 |
+
max_nfev=settings["refinement_max_evaluations"], loss="soft_l1", f_scale=.02).x.reshape(-1, 35)
|
| 207 |
+
before, after = np.sqrt(np.mean(data(start)**2)), np.sqrt(np.mean(data(candidate)**2))
|
| 208 |
+
retained = after <= before+settings["refinement_observation_tolerance_m"]
|
| 209 |
+
if retained: out[a:b] = candidate
|
| 210 |
+
diagnostic.append({"frames": [a,b-1], "weighted_coordinate_rmse_before_m": float(before),
|
| 211 |
+
"weighted_coordinate_rmse_after_m": float(after), "accepted": bool(retained)})
|
| 212 |
+
return out, diagnostic
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def run_anatomy(request, capture, config):
|
| 216 |
+
root = Path(request["root"])
|
| 217 |
+
try:
|
| 218 |
+
import yaml
|
| 219 |
+
status = read_json(root/"temporal3d_status.json")
|
| 220 |
+
if status.get("status") not in {"partial", "complete"}: raise ValueError("Temporal trajectory unavailable")
|
| 221 |
+
source = root/status["trajectory_path"]
|
| 222 |
+
settings = yaml.safe_load(Path(config.anatomical_config_path).read_text())
|
| 223 |
+
cache = StageCache(root, "anatomy", digest({"upstream": status["cache_key"], "settings": settings}))
|
| 224 |
+
if cache.valid("trajectory"):
|
| 225 |
+
atomic_json(root/"anatomy_status.json", read_json(cache.root/"status.json")); return
|
| 226 |
+
data = np.load(source, allow_pickle=False)
|
| 227 |
+
# Convert camera neutral axes back once. Model targets remain in camera axes:
|
| 228 |
+
# a FreeJoint rotates/translates the neutral model to those proxy targets.
|
| 229 |
+
neutral = data["neutral_mhr70_m"]*np.array([1., -1., -1.])
|
| 230 |
+
spec = model_spec(neutral, settings)
|
| 231 |
+
atomic_json(cache.root/"model_spec.json", spec)
|
| 232 |
+
model = build_opensim(spec, cache.root/"BattingKinematics-v1.osim")
|
| 233 |
+
indices = [m["mhr70_index"] for m in spec["markers"].values()]
|
| 234 |
+
targets = data["keypoints_camera_m"][:, indices]
|
| 235 |
+
# 3D targets are fitted model proxies. Weights reflect their 2D support where
|
| 236 |
+
# available; hand-only proxy markers receive a weak explicitly recorded prior.
|
| 237 |
+
weights = data["observation_weights"][:, indices].copy()
|
| 238 |
+
for j, name in enumerate(spec["markers"]):
|
| 239 |
+
if name.endswith("_mcp"): weights[:, j] = np.maximum(weights[:, j], .1)
|
| 240 |
+
weights *= data["accepted_frames"][:, None]
|
| 241 |
+
weights[~np.isfinite(targets).all(axis=2)] = 0
|
| 242 |
+
times = data["fitting_times"]
|
| 243 |
+
q = weighted_ik(model, spec, targets, weights, times, cache.root)
|
| 244 |
+
q, refinement = refine_trajectory(spec, q, targets, weights, times, settings)
|
| 245 |
+
positions = np.full_like(targets, np.nan)
|
| 246 |
+
rotations = np.full((len(q), len(spec["bodies"]), 3, 3), np.nan)
|
| 247 |
+
accepted = np.zeros(len(q), bool); residual = np.full(targets.shape[:2], np.nan)
|
| 248 |
+
for i in np.flatnonzero(np.isfinite(q).all(axis=1)):
|
| 249 |
+
markers, transforms = forward_kinematics(spec, q[i])
|
| 250 |
+
error = np.linalg.norm(markers-targets[i], axis=-1)
|
| 251 |
+
residual[i] = error
|
| 252 |
+
eligible = weights[i] > 0
|
| 253 |
+
if not eligible.any() or np.sqrt(np.mean(error[eligible]**2)) > settings["marker_fit_max_rmse_m"]: continue
|
| 254 |
+
accepted[i] = True; positions[i] = markers
|
| 255 |
+
rotations[i] = np.array([transforms[name][0] for name in spec["bodies"]])
|
| 256 |
+
if not accepted.any(): raise ValueError("No IK frames passed marker agreement")
|
| 257 |
+
path = cache.root/"trajectory.npz"
|
| 258 |
+
np.savez_compressed(path, coordinates=q, marker_positions_m=positions, segment_rotations=rotations,
|
| 259 |
+
residual_m=residual, accepted_frames=accepted, fitting_times=times,
|
| 260 |
+
marker_names=np.array(list(spec["markers"])), segment_names=np.array(list(spec["bodies"])))
|
| 261 |
+
result = {"status": "complete" if accepted.all() else "partial", "frames_fitted": int(accepted.sum()),
|
| 262 |
+
"cache_key": cache.key, "trajectory_path": str(path.relative_to(root)), "model_id": spec["model_id"],
|
| 263 |
+
"model_sha256": sha256_file(cache.root/"BattingKinematics-v1.osim"), "spec_sha256": digest(spec),
|
| 264 |
+
"dof": 35, "target_source": "MHR70_model_regression_proxy_not_independent_reference",
|
| 265 |
+
"coordinate_space": "camera_x_right_y_down_z_forward_metres", "refinement": refinement,
|
| 266 |
+
"geometry_source": status["geometry_source"], "validation": "reference-validation-pending",
|
| 267 |
+
"maximum_regularization_sensitivity_m":status.get("maximum_regularization_sensitivity_m"),
|
| 268 |
+
"dynamics": "disabled", "rotation_coordinates": "primitive_intrinsic_XYZ_XY_Z"}
|
| 269 |
+
atomic_json(cache.root/"status.json", result)
|
| 270 |
+
cache.commit("trajectory", [path, cache.root/"status.json", cache.root/"model_spec.json", cache.root/"BattingKinematics-v1.osim"])
|
| 271 |
+
except Exception as error:
|
| 272 |
+
result = {"status": "unavailable", "reason": str(error)[:300], "error_type": type(error).__name__}
|
| 273 |
+
atomic_json(root/"anatomy_status.json", result)
|
baseball_batting/annotations.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reviewed labels are immutable input records, separate from automatic observations."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from .contracts import RTMW_CORE
|
| 6 |
+
|
| 7 |
+
def load_annotations(path, input_hash, frame_count, width, height):
|
| 8 |
+
if not path:
|
| 9 |
+
return {"schema_version": "1.0", "frames": {}, "events": [], "annotator": None}
|
| 10 |
+
data = json.loads(Path(path).read_text())
|
| 11 |
+
if data.get("schema_version") != "1.0" or data.get("input_sha256") != input_hash:
|
| 12 |
+
raise ValueError("Annotations must identify this exact video and schema")
|
| 13 |
+
if not data.get("annotator"):
|
| 14 |
+
raise ValueError("Reviewed labels require an annotator ID")
|
| 15 |
+
for raw_id, frame in data.get("frames", {}).items():
|
| 16 |
+
index = int(raw_id)
|
| 17 |
+
if str(index) != raw_id or not 0 <= index < frame_count:
|
| 18 |
+
raise ValueError("Invalid annotation frame ID")
|
| 19 |
+
for name, p in frame.get("landmarks", {}).items():
|
| 20 |
+
if name not in RTMW_CORE:
|
| 21 |
+
raise ValueError(f"Unknown RTMW landmark {name}")
|
| 22 |
+
_point(p, width, height)
|
| 23 |
+
if any(name not in RTMW_CORE for name in frame.get("occluded_landmarks", [])):
|
| 24 |
+
raise ValueError("Unknown occluded RTMW landmark")
|
| 25 |
+
for name in ("knob", "barrel", "ball"):
|
| 26 |
+
if frame.get(name) is not None:
|
| 27 |
+
_point(frame[name], width, height)
|
| 28 |
+
if "crop" in frame:
|
| 29 |
+
a, b, c, d = frame["crop"]
|
| 30 |
+
if not 0 <= a < c <= width or not 0 <= b < d <= height:
|
| 31 |
+
raise ValueError("Crop must lie in oriented image bounds")
|
| 32 |
+
known_events = {"contact", "forward_swing_onset", "lead_foot_lift", "lead_foot_contact", "load", "follow_through", "miss", "dry_swing", "contact_unknown"}
|
| 33 |
+
for event in data.get("events", []):
|
| 34 |
+
if event.get("type") not in known_events or event.get("state") not in {"confirmed", "unknown", "absent"}:
|
| 35 |
+
raise ValueError("Invalid reviewed event type/state")
|
| 36 |
+
interval = event.get("frame_interval")
|
| 37 |
+
if interval is not None and (len(interval) != 2 or any(not isinstance(f, int) for f in interval)
|
| 38 |
+
or not 0 <= interval[0] <= interval[1] < frame_count):
|
| 39 |
+
raise ValueError("Reviewed event interval is outside the recording")
|
| 40 |
+
if event["state"] == "confirmed":
|
| 41 |
+
if not interval or len(interval) != 2 or not 0 <= interval[0] <= interval[1] < frame_count:
|
| 42 |
+
raise ValueError("Confirmed event needs an in-range frame interval")
|
| 43 |
+
if not event.get("evidence_frames") or not event.get("evidence_description"):
|
| 44 |
+
raise ValueError("Confirmed events need observable evidence and a description")
|
| 45 |
+
for f in event.get("evidence_frames", []):
|
| 46 |
+
if not isinstance(f, int) or not 0 <= f < frame_count:
|
| 47 |
+
raise ValueError("Invalid event evidence frame")
|
| 48 |
+
return data
|
| 49 |
+
|
| 50 |
+
def _point(p, width, height):
|
| 51 |
+
if len(p) != 2 or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in p):
|
| 52 |
+
raise ValueError("Annotation points must be finite x,y pairs")
|
| 53 |
+
if not 0 <= p[0] < width or not 0 <= p[1] < height:
|
| 54 |
+
raise ValueError("Annotation lies outside oriented frame")
|
baseball_batting/api.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTTP upload/status/result API. Start with Uvicorn --factory --workers 1."""
|
| 2 |
+
from contextlib import asynccontextmanager
|
| 3 |
+
import asyncio
|
| 4 |
+
import hmac
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import shutil
|
| 8 |
+
from typing import Annotated
|
| 9 |
+
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile
|
| 10 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 11 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 12 |
+
from pydantic import ValidationError
|
| 13 |
+
from starlette.background import BackgroundTask
|
| 14 |
+
from starlette.concurrency import run_in_threadpool
|
| 15 |
+
from .api_contract import AnalysisInput
|
| 16 |
+
from .api_jobs import ApiSettings, JobService, QueueFull
|
| 17 |
+
from .storage import atomic_json, read_json, sha256_file
|
| 18 |
+
|
| 19 |
+
ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
|
| 20 |
+
BEARER = HTTPBearer(auto_error=False)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class UploadGuard:
|
| 24 |
+
"""Authenticate before multipart parsing and limit its total streamed body."""
|
| 25 |
+
def __init__(self, app, settings, service):
|
| 26 |
+
self.app, self.settings, self.service = app, settings, service
|
| 27 |
+
self.upload_slots = asyncio.Semaphore(2)
|
| 28 |
+
|
| 29 |
+
async def __call__(self, scope, receive, send):
|
| 30 |
+
if scope["type"] != "http" or not scope["path"].startswith("/v1/"):
|
| 31 |
+
return await self.app(scope, receive, send)
|
| 32 |
+
headers = dict(scope["headers"])
|
| 33 |
+
authorization = headers.get(b"authorization", b"")
|
| 34 |
+
supplied = authorization[7:] if authorization.lower().startswith(b"bearer ") else b""
|
| 35 |
+
if not hmac.compare_digest(supplied, self.settings.api_key.encode()):
|
| 36 |
+
return await JSONResponse({"detail": "Invalid or missing API key"}, status_code=401,
|
| 37 |
+
headers={"WWW-Authenticate": "Bearer"})(scope, receive, send)
|
| 38 |
+
limit = self.settings.max_upload_bytes + 1024 * 1024
|
| 39 |
+
size = headers.get(b"content-length")
|
| 40 |
+
if size:
|
| 41 |
+
try: oversized = int(size) > limit or int(size) < 0
|
| 42 |
+
except ValueError: oversized = True
|
| 43 |
+
if oversized:
|
| 44 |
+
return await JSONResponse({"detail": "Request exceeds upload limit"}, status_code=413)(scope, receive, send)
|
| 45 |
+
received = 0
|
| 46 |
+
async def limited_receive():
|
| 47 |
+
nonlocal received
|
| 48 |
+
message = await receive()
|
| 49 |
+
received += len(message.get("body", b""))
|
| 50 |
+
if received > limit:
|
| 51 |
+
raise HTTPException(413, "Request exceeds upload limit")
|
| 52 |
+
return message
|
| 53 |
+
is_upload = scope["method"] == "POST" and scope["path"] == "/v1/analyses"
|
| 54 |
+
if is_upload:
|
| 55 |
+
if not self.service.ready:
|
| 56 |
+
return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
|
| 57 |
+
if self.upload_slots.locked():
|
| 58 |
+
return await JSONResponse({"detail": "Too many concurrent uploads"}, status_code=429)(scope, receive, send)
|
| 59 |
+
async with self.upload_slots:
|
| 60 |
+
return await self.app(scope, limited_receive, send)
|
| 61 |
+
return await self.app(scope, limited_receive, send)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def create_app(settings=None, service=None):
|
| 65 |
+
settings = settings or ApiSettings.from_env()
|
| 66 |
+
service = service or JobService(settings)
|
| 67 |
+
@asynccontextmanager
|
| 68 |
+
async def lifespan(app):
|
| 69 |
+
service.start()
|
| 70 |
+
try: yield
|
| 71 |
+
finally: service.stop()
|
| 72 |
+
app = FastAPI(title="Baseball 2D GPU API", version="1.1.0", lifespan=lifespan,
|
| 73 |
+
description="Batting points and estimated swing measurements for a separate coach agent. GPU required; all 3D stages disabled.")
|
| 74 |
+
app.state.service = service
|
| 75 |
+
app.add_middleware(UploadGuard, settings=settings, service=service)
|
| 76 |
+
|
| 77 |
+
def authenticated(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(BEARER)]):
|
| 78 |
+
# Documents Bearer authorization in OpenAPI; UploadGuard also checks before body parsing.
|
| 79 |
+
if credentials is None or not hmac.compare_digest(credentials.credentials.encode(), settings.api_key.encode()):
|
| 80 |
+
raise HTTPException(401, "Invalid or missing API key", headers={"WWW-Authenticate": "Bearer"})
|
| 81 |
+
|
| 82 |
+
def job_record(job_id):
|
| 83 |
+
try: directory = service.job_directory(job_id)
|
| 84 |
+
except ValueError: raise HTTPException(404, "Job not found")
|
| 85 |
+
record = service.store.get(job_id)
|
| 86 |
+
if not record: raise HTTPException(404, "Job not found")
|
| 87 |
+
return directory, record
|
| 88 |
+
|
| 89 |
+
@app.get("/healthz")
|
| 90 |
+
def health():
|
| 91 |
+
return {"status": "alive", "gpu_ready": service.ready, "body_3d": False}
|
| 92 |
+
|
| 93 |
+
@app.get("/readyz")
|
| 94 |
+
def ready():
|
| 95 |
+
return JSONResponse({"ready": service.ready, "reason": service.readiness_reason,
|
| 96 |
+
"device": "cuda", "body_3d": False}, status_code=200 if service.ready else 503)
|
| 97 |
+
|
| 98 |
+
@app.get("/v1/capabilities", dependencies=[Depends(authenticated)])
|
| 99 |
+
def capabilities():
|
| 100 |
+
return {"discipline": "hitting", "device": "cuda", "body_3d": False,
|
| 101 |
+
"body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
|
| 102 |
+
"automatic_events": True, "swing_metrics": True, "estimated_only": True,
|
| 103 |
+
"measurement_validation": "reference_validation_pending", "coaching": False,
|
| 104 |
+
"limits": {"upload_bytes": settings.max_upload_bytes, "duration_s": settings.max_duration_s,
|
| 105 |
+
"frames": settings.max_frames, "pixels": settings.max_pixels},
|
| 106 |
+
"retention_hours": settings.retention_s / 3600}
|
| 107 |
+
|
| 108 |
+
@app.get("/v1/input-schema", dependencies=[Depends(authenticated)])
|
| 109 |
+
def input_schema():
|
| 110 |
+
return AnalysisInput.model_json_schema()
|
| 111 |
+
|
| 112 |
+
@app.get("/v1/output-schema", dependencies=[Depends(authenticated)])
|
| 113 |
+
def output_schema():
|
| 114 |
+
return read_json(Path(__file__).resolve().parents[1] / "docs/api-result.schema.json")
|
| 115 |
+
|
| 116 |
+
@app.get("/v1/coach-payload-schema", dependencies=[Depends(authenticated)])
|
| 117 |
+
def coach_schema():
|
| 118 |
+
return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json")
|
| 119 |
+
|
| 120 |
+
@app.post("/v1/analyses", status_code=202, dependencies=[Depends(authenticated)])
|
| 121 |
+
async def create_analysis(video: Annotated[UploadFile, File(description="Original recording")],
|
| 122 |
+
options: Annotated[str, Form(description="AnalysisInput as a JSON string")] = "{}"):
|
| 123 |
+
identifier = None
|
| 124 |
+
try:
|
| 125 |
+
if not service.ready: raise HTTPException(503, "GPU worker is not ready; check /readyz")
|
| 126 |
+
if len(options.encode()) > 512 * 1024: raise HTTPException(413, "Options exceed size limit")
|
| 127 |
+
try: parsed = AnalysisInput.model_validate_json(options)
|
| 128 |
+
except ValidationError as error:
|
| 129 |
+
# No echo of arbitrary client inputs in error responses.
|
| 130 |
+
details = [{"loc": list(item["loc"]), "type": item["type"], "msg": item["msg"]}
|
| 131 |
+
for item in error.errors(include_url=False, include_input=False)]
|
| 132 |
+
raise HTTPException(422, details)
|
| 133 |
+
suffix = Path(video.filename or "").suffix.lower()
|
| 134 |
+
if suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, "Unsupported video extension")
|
| 135 |
+
if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes:
|
| 136 |
+
raise HTTPException(507, "Insufficient storage")
|
| 137 |
+
try: identifier = service.store.create(settings.max_active_jobs)
|
| 138 |
+
except QueueFull: raise HTTPException(429, "GPU queue is full", headers={"Retry-After": "30"})
|
| 139 |
+
directory = service.job_directory(identifier)
|
| 140 |
+
directory.mkdir()
|
| 141 |
+
size = 0
|
| 142 |
+
with (directory / ("input" + suffix)).open("wb") as destination:
|
| 143 |
+
while block := await video.read(1024 * 1024):
|
| 144 |
+
size += len(block)
|
| 145 |
+
if size > settings.max_upload_bytes: raise HTTPException(413, "Video exceeds upload limit")
|
| 146 |
+
if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes + len(block):
|
| 147 |
+
raise HTTPException(507, "Insufficient storage")
|
| 148 |
+
destination.write(block)
|
| 149 |
+
if size == 0: raise HTTPException(422, "Video is empty")
|
| 150 |
+
atomic_json(directory / "request.json", parsed.model_dump(exclude_none=True))
|
| 151 |
+
service.store.update(identifier, "queued")
|
| 152 |
+
service.wakeup.set()
|
| 153 |
+
return {"job_id": identifier, "status": "queued",
|
| 154 |
+
"status_url": f"/v1/analyses/{identifier}", "result_url": f"/v1/analyses/{identifier}/result",
|
| 155 |
+
"coach_payload_url": f"/v1/analyses/{identifier}/coach-payload"}
|
| 156 |
+
except BaseException:
|
| 157 |
+
if identifier:
|
| 158 |
+
service.store.forget(identifier)
|
| 159 |
+
shutil.rmtree(service.job_directory(identifier), ignore_errors=True)
|
| 160 |
+
raise
|
| 161 |
+
finally:
|
| 162 |
+
await video.close()
|
| 163 |
+
|
| 164 |
+
@app.get("/v1/analyses/{job_id}", dependencies=[Depends(authenticated)])
|
| 165 |
+
def status(job_id: str):
|
| 166 |
+
with service.mutation_lock:
|
| 167 |
+
directory, record = job_record(job_id)
|
| 168 |
+
progress = read_json(directory / "progress.json") if (directory / "progress.json").is_file() else None
|
| 169 |
+
return {"job_id": job_id, "status": record["status"], "created_at": record["created"],
|
| 170 |
+
"updated_at": record["updated"], "progress": progress, "error": record["error"],
|
| 171 |
+
"result_url": f"/v1/analyses/{job_id}/result" if record["status"] == "completed" else None,
|
| 172 |
+
"coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None}
|
| 173 |
+
|
| 174 |
+
@app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)])
|
| 175 |
+
def get_coach_payload(job_id: str):
|
| 176 |
+
with service.mutation_lock:
|
| 177 |
+
directory, record = job_record(job_id)
|
| 178 |
+
if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status")
|
| 179 |
+
path = directory / "coach-payload.json"
|
| 180 |
+
if record.get("coach_payload_sha256") is None:
|
| 181 |
+
raise HTTPException(409, "This older job has no coach payload; submit the video again")
|
| 182 |
+
if not path.is_file() or sha256_file(path) != record["coach_payload_sha256"]:
|
| 183 |
+
raise HTTPException(500, "Stored coach payload failed its integrity check")
|
| 184 |
+
payload = read_json(path)
|
| 185 |
+
return JSONResponse(payload, headers={"Cache-Control": "no-store"})
|
| 186 |
+
|
| 187 |
+
@app.get("/v1/analyses/{job_id}/result", dependencies=[Depends(authenticated)])
|
| 188 |
+
def result(job_id: str):
|
| 189 |
+
with service.mutation_lock:
|
| 190 |
+
directory, record = job_record(job_id)
|
| 191 |
+
if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status")
|
| 192 |
+
path = directory / "result.json"
|
| 193 |
+
if not path.is_file() or sha256_file(path) != record["result_sha256"]:
|
| 194 |
+
raise HTTPException(500, "Stored result failed its integrity check")
|
| 195 |
+
# An open descriptor stays usable when DELETE/retention removes the path.
|
| 196 |
+
handle = path.open("rb")
|
| 197 |
+
size = path.stat().st_size
|
| 198 |
+
async def stream():
|
| 199 |
+
try:
|
| 200 |
+
while block := await run_in_threadpool(handle.read, 64 * 1024):
|
| 201 |
+
yield block
|
| 202 |
+
finally:
|
| 203 |
+
handle.close()
|
| 204 |
+
return StreamingResponse(stream(), media_type="application/json",
|
| 205 |
+
headers={"Cache-Control": "no-store", "Content-Length": str(size)},
|
| 206 |
+
background=BackgroundTask(handle.close))
|
| 207 |
+
|
| 208 |
+
@app.delete("/v1/analyses/{job_id}", status_code=202, dependencies=[Depends(authenticated)])
|
| 209 |
+
def delete(job_id: str):
|
| 210 |
+
job_record(job_id)
|
| 211 |
+
status = service.delete(job_id)
|
| 212 |
+
return {"job_id": job_id, "status": status}
|
| 213 |
+
|
| 214 |
+
return app
|
baseball_batting/api_contract.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Public inputs: clients cannot supply paths, models, devices or 3D switches."""
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TimingInput(BaseModel):
|
| 7 |
+
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 8 |
+
kind: Literal["unknown", "unretimed", "constant_slowdown", "explicit"] = "unknown"
|
| 9 |
+
source: str | None = Field(default=None, min_length=1, max_length=512)
|
| 10 |
+
factor: float | None = Field(default=None, gt=0)
|
| 11 |
+
all_captured_frames_retained: bool | None = None
|
| 12 |
+
physical_times_s: list[float] | None = Field(default=None, min_length=1, max_length=20000)
|
| 13 |
+
|
| 14 |
+
@model_validator(mode="after")
|
| 15 |
+
def check_evidence(self):
|
| 16 |
+
if self.kind != "unknown" and not (self.source and self.source.strip()):
|
| 17 |
+
raise ValueError("Known capture timing requires a source description")
|
| 18 |
+
if self.kind == "constant_slowdown":
|
| 19 |
+
if self.factor is None or self.all_captured_frames_retained is not True:
|
| 20 |
+
raise ValueError("Slow motion requires its factor and all captured frames retained")
|
| 21 |
+
if self.kind == "explicit":
|
| 22 |
+
if not self.physical_times_s or any(b <= a for a, b in
|
| 23 |
+
zip(self.physical_times_s, self.physical_times_s[1:])):
|
| 24 |
+
raise ValueError("Explicit capture times must increase strictly")
|
| 25 |
+
return self
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RepRange(BaseModel):
|
| 29 |
+
model_config = ConfigDict(extra="forbid")
|
| 30 |
+
start_frame: int = Field(ge=0, strict=True)
|
| 31 |
+
end_frame: int = Field(ge=0, strict=True)
|
| 32 |
+
|
| 33 |
+
@model_validator(mode="after")
|
| 34 |
+
def ordered(self):
|
| 35 |
+
if self.end_frame < self.start_frame:
|
| 36 |
+
raise ValueError("end_frame precedes start_frame")
|
| 37 |
+
return self
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class AnalysisInput(BaseModel):
|
| 41 |
+
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
|
| 42 |
+
discipline: Literal["hitting"] = "hitting"
|
| 43 |
+
view: Literal["face_on", "unknown"] = "unknown"
|
| 44 |
+
handedness: Literal["left", "right"] | None = None
|
| 45 |
+
level: Literal["hs_jv", "hs_varsity", "college"] | None = None
|
| 46 |
+
pitcher_direction: Literal["image_left", "image_right"] | None = None
|
| 47 |
+
body_height_px: float | None = Field(default=None, gt=0)
|
| 48 |
+
body_height_source: str | None = Field(default=None, min_length=1, max_length=512)
|
| 49 |
+
rotation_degrees: Literal[0, 90, 180, 270] | None = None
|
| 50 |
+
camera_stability: Literal["unknown", "fixed_verified", "moving"] = "unknown"
|
| 51 |
+
timing: TimingInput = Field(default_factory=TimingInput)
|
| 52 |
+
single_swing: bool = False
|
| 53 |
+
reps: list[RepRange] = Field(default_factory=list, max_length=100)
|
| 54 |
+
|
| 55 |
+
@model_validator(mode="after")
|
| 56 |
+
def ranges(self):
|
| 57 |
+
if self.body_height_px is not None and not (self.body_height_source and self.body_height_source.strip()):
|
| 58 |
+
raise ValueError("A supplied image height needs a source description")
|
| 59 |
+
if self.single_swing and self.reps:
|
| 60 |
+
raise ValueError("Use single_swing or explicit rep ranges, not both")
|
| 61 |
+
if any(b.start_frame <= a.end_frame for a, b in zip(self.reps, self.reps[1:])):
|
| 62 |
+
raise ValueError("Rep ranges must be ordered and must not overlap")
|
| 63 |
+
return self
|
| 64 |
+
|
| 65 |
+
def engine_metadata(self):
|
| 66 |
+
value = {"timing": self.timing.model_dump(exclude_none=True),
|
| 67 |
+
"camera_stability": self.camera_stability, "intended_use": "research"}
|
| 68 |
+
if self.rotation_degrees is not None:
|
| 69 |
+
value["rotation_degrees"] = self.rotation_degrees
|
| 70 |
+
if self.handedness:
|
| 71 |
+
value["handedness"] = self.handedness
|
| 72 |
+
return value
|
baseball_batting/api_jobs.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Durable single-GPU queue with isolated, cancellable subprocesses."""
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
import fcntl
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
import signal
|
| 10 |
+
import sqlite3
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
import uuid
|
| 16 |
+
from .storage import read_json, sha256_file
|
| 17 |
+
|
| 18 |
+
LOG = logging.getLogger(__name__)
|
| 19 |
+
ACTIVE = ("uploading", "queued", "running", "cancel_requested")
|
| 20 |
+
TERMINAL = ("completed", "failed", "cancelled")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class ApiSettings:
|
| 25 |
+
api_key: str
|
| 26 |
+
data_root: Path = Path("api-data")
|
| 27 |
+
model_root: Path = Path("downloads")
|
| 28 |
+
max_upload_bytes: int = 512 * 1024 * 1024
|
| 29 |
+
max_active_jobs: int = 8
|
| 30 |
+
max_frames: int = 7200
|
| 31 |
+
max_pixels: int = 8294400
|
| 32 |
+
max_duration_s: float = 120
|
| 33 |
+
job_timeout_s: float = 1800
|
| 34 |
+
retention_s: float = 86400
|
| 35 |
+
minimum_free_bytes: int = 1024 * 1024 * 1024
|
| 36 |
+
|
| 37 |
+
def __post_init__(self):
|
| 38 |
+
if len(self.api_key) < 16:
|
| 39 |
+
raise ValueError("Set BASEBALL_API_KEY to a secret of at least 16 characters")
|
| 40 |
+
self.data_root, self.model_root = Path(self.data_root).resolve(), Path(self.model_root).resolve()
|
| 41 |
+
for value in (self.max_upload_bytes, self.max_active_jobs, self.max_frames,
|
| 42 |
+
self.max_pixels, self.max_duration_s, self.job_timeout_s, self.retention_s):
|
| 43 |
+
if value <= 0:
|
| 44 |
+
raise ValueError("API limits must be positive")
|
| 45 |
+
if self.minimum_free_bytes < 0:
|
| 46 |
+
raise ValueError("Free disk reserve must not be negative")
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def from_env(cls):
|
| 50 |
+
return cls(api_key=os.environ.get("BASEBALL_API_KEY", ""),
|
| 51 |
+
data_root=Path(os.environ.get("BASEBALL_DATA_ROOT", "/data")),
|
| 52 |
+
model_root=Path(os.environ.get("BASEBALL_MODEL_ROOT", "/opt/models")),
|
| 53 |
+
max_upload_bytes=int(os.environ.get("BASEBALL_MAX_UPLOAD_MB", "512")) * 1024 * 1024,
|
| 54 |
+
max_active_jobs=int(os.environ.get("BASEBALL_MAX_ACTIVE_JOBS", "8")),
|
| 55 |
+
max_frames=int(os.environ.get("BASEBALL_MAX_FRAMES", "7200")),
|
| 56 |
+
max_pixels=int(os.environ.get("BASEBALL_MAX_PIXELS", "8294400")),
|
| 57 |
+
max_duration_s=float(os.environ.get("BASEBALL_MAX_DURATION_S", "120")),
|
| 58 |
+
job_timeout_s=float(os.environ.get("BASEBALL_JOB_TIMEOUT_S", "1800")),
|
| 59 |
+
retention_s=float(os.environ.get("BASEBALL_RETENTION_HOURS", "24")) * 3600,
|
| 60 |
+
minimum_free_bytes=int(os.environ.get("BASEBALL_DISK_RESERVE_MB", "1024")) * 1024 * 1024)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class QueueFull(Exception): pass
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class JobStore:
|
| 67 |
+
def __init__(self, root):
|
| 68 |
+
self.root = Path(root)
|
| 69 |
+
self.root.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
self.path = self.root / "jobs.sqlite3"
|
| 71 |
+
with self.connect() as db:
|
| 72 |
+
db.execute("PRAGMA journal_mode=WAL")
|
| 73 |
+
db.execute("""CREATE TABLE IF NOT EXISTS jobs (
|
| 74 |
+
id TEXT PRIMARY KEY, status TEXT NOT NULL, created REAL NOT NULL,
|
| 75 |
+
updated REAL NOT NULL, error TEXT, result_sha256 TEXT, coach_payload_sha256 TEXT)""")
|
| 76 |
+
if "coach_payload_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}:
|
| 77 |
+
db.execute("ALTER TABLE jobs ADD COLUMN coach_payload_sha256 TEXT")
|
| 78 |
+
|
| 79 |
+
@contextmanager
|
| 80 |
+
def connect(self):
|
| 81 |
+
db = sqlite3.connect(self.path, timeout=30)
|
| 82 |
+
try:
|
| 83 |
+
with db:
|
| 84 |
+
yield db
|
| 85 |
+
finally:
|
| 86 |
+
db.close()
|
| 87 |
+
|
| 88 |
+
def create(self, max_active):
|
| 89 |
+
now, identifier = time.time(), uuid.uuid4().hex
|
| 90 |
+
with self.connect() as db:
|
| 91 |
+
db.execute("BEGIN IMMEDIATE")
|
| 92 |
+
active = db.execute("SELECT COUNT(*) FROM jobs WHERE status IN (?,?,?,?)", ACTIVE).fetchone()[0]
|
| 93 |
+
if active >= max_active: raise QueueFull()
|
| 94 |
+
db.execute("INSERT INTO jobs (id,status,created,updated) VALUES (?, 'uploading', ?, ?)", (identifier, now, now))
|
| 95 |
+
return identifier
|
| 96 |
+
|
| 97 |
+
def get(self, identifier):
|
| 98 |
+
with self.connect() as db:
|
| 99 |
+
db.row_factory = sqlite3.Row
|
| 100 |
+
value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 101 |
+
return dict(value) if value else None
|
| 102 |
+
|
| 103 |
+
def update(self, identifier, status, error=None, result_hash=None, coach_hash=None):
|
| 104 |
+
with self.connect() as db:
|
| 105 |
+
db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=? WHERE id=?",
|
| 106 |
+
(status, time.time(), error, result_hash, coach_hash, identifier))
|
| 107 |
+
|
| 108 |
+
def claim(self):
|
| 109 |
+
with self.connect() as db:
|
| 110 |
+
db.execute("BEGIN IMMEDIATE")
|
| 111 |
+
row = db.execute("SELECT id FROM jobs WHERE status='queued' ORDER BY created LIMIT 1").fetchone()
|
| 112 |
+
if row:
|
| 113 |
+
db.execute("UPDATE jobs SET status='running', updated=? WHERE id=?", (time.time(), row[0]))
|
| 114 |
+
return row[0]
|
| 115 |
+
|
| 116 |
+
def cancel(self, identifier):
|
| 117 |
+
with self.connect() as db:
|
| 118 |
+
db.execute("BEGIN IMMEDIATE")
|
| 119 |
+
row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
|
| 120 |
+
if not row: return None
|
| 121 |
+
status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
|
| 122 |
+
db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL WHERE id=?",
|
| 123 |
+
(status, time.time(), identifier))
|
| 124 |
+
return status
|
| 125 |
+
|
| 126 |
+
def recover(self):
|
| 127 |
+
with self.connect() as db:
|
| 128 |
+
uploads = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='uploading'")]
|
| 129 |
+
cancellations = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='cancel_requested'")]
|
| 130 |
+
db.execute("DELETE FROM jobs WHERE status='uploading'")
|
| 131 |
+
db.execute("UPDATE jobs SET status='queued', updated=? WHERE status='running'", (time.time(),))
|
| 132 |
+
db.execute("UPDATE jobs SET status='cancelled', updated=? WHERE status='cancel_requested'", (time.time(),))
|
| 133 |
+
return uploads + cancellations
|
| 134 |
+
|
| 135 |
+
def forget(self, identifier):
|
| 136 |
+
with self.connect() as db:
|
| 137 |
+
db.execute("DELETE FROM jobs WHERE id=?", (identifier,))
|
| 138 |
+
|
| 139 |
+
def expired(self, cutoff):
|
| 140 |
+
with self.connect() as db:
|
| 141 |
+
return [r[0] for r in db.execute(
|
| 142 |
+
"SELECT id FROM jobs WHERE status IN (?,?,?) AND updated < ?", (*TERMINAL, cutoff))]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def stop_process(process):
|
| 146 |
+
if process.poll() is not None: return
|
| 147 |
+
try:
|
| 148 |
+
os.killpg(process.pid, signal.SIGTERM)
|
| 149 |
+
process.wait(timeout=3)
|
| 150 |
+
except subprocess.TimeoutExpired:
|
| 151 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 152 |
+
process.wait(timeout=3)
|
| 153 |
+
except ProcessLookupError:
|
| 154 |
+
process.wait(timeout=3)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class JobService:
|
| 158 |
+
def __init__(self, settings, command_factory=None, preflight_command=None):
|
| 159 |
+
self.settings = settings
|
| 160 |
+
self.store = JobStore(settings.data_root)
|
| 161 |
+
self.jobs_root = settings.data_root / "jobs"
|
| 162 |
+
self.jobs_root.mkdir(exist_ok=True)
|
| 163 |
+
self.command_factory = command_factory or self.job_command
|
| 164 |
+
self.preflight_command = preflight_command or [sys.executable, "-m", "baseball_batting.api_worker",
|
| 165 |
+
"--preflight", "--models", str(settings.model_root), "--output", str(settings.data_root / "gpu-ready.json")]
|
| 166 |
+
self.ready = False
|
| 167 |
+
self.readiness_reason = "gpu_preflight_pending"
|
| 168 |
+
self.stopping = threading.Event()
|
| 169 |
+
self.wakeup = threading.Event()
|
| 170 |
+
self.thread = None
|
| 171 |
+
self.lock = None
|
| 172 |
+
# Serializes completion/cancellation and deletion against result downloads.
|
| 173 |
+
self.mutation_lock = threading.RLock()
|
| 174 |
+
|
| 175 |
+
def job_directory(self, identifier):
|
| 176 |
+
if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier):
|
| 177 |
+
raise ValueError("Invalid job ID")
|
| 178 |
+
return self.jobs_root / identifier
|
| 179 |
+
|
| 180 |
+
def job_command(self, directory):
|
| 181 |
+
s = self.settings
|
| 182 |
+
return [sys.executable, "-m", "baseball_batting.api_worker", "--models", str(s.model_root),
|
| 183 |
+
"--job", str(directory), "--max-frames", str(s.max_frames),
|
| 184 |
+
"--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
|
| 185 |
+
|
| 186 |
+
def start(self):
|
| 187 |
+
self.lock = (self.settings.data_root / ".service.lock").open("a")
|
| 188 |
+
try:
|
| 189 |
+
fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 190 |
+
except BlockingIOError:
|
| 191 |
+
self.lock.close()
|
| 192 |
+
raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker")
|
| 193 |
+
for identifier in self.store.recover():
|
| 194 |
+
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 195 |
+
self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True)
|
| 196 |
+
self.thread.start()
|
| 197 |
+
|
| 198 |
+
def stop(self):
|
| 199 |
+
self.ready = False
|
| 200 |
+
self.stopping.set(); self.wakeup.set()
|
| 201 |
+
if self.thread:
|
| 202 |
+
self.thread.join(timeout=15)
|
| 203 |
+
if self.thread.is_alive():
|
| 204 |
+
raise RuntimeError("GPU worker did not stop")
|
| 205 |
+
if self.lock:
|
| 206 |
+
self.lock.close()
|
| 207 |
+
|
| 208 |
+
def environment(self):
|
| 209 |
+
env = dict(os.environ)
|
| 210 |
+
# The inference subprocess does not need the service credential.
|
| 211 |
+
env.pop("BASEBALL_API_KEY", None)
|
| 212 |
+
env["MPLBACKEND"] = "Agg"; env["PYTHONUNBUFFERED"] = "1"
|
| 213 |
+
repo = str(Path(__file__).resolve().parents[1])
|
| 214 |
+
env["PYTHONPATH"] = repo + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
|
| 215 |
+
return env
|
| 216 |
+
|
| 217 |
+
def launch(self, command, log_path):
|
| 218 |
+
with Path(log_path).open("wb") as log:
|
| 219 |
+
return subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT,
|
| 220 |
+
env=self.environment(), start_new_session=True)
|
| 221 |
+
|
| 222 |
+
def delete(self, identifier):
|
| 223 |
+
with self.mutation_lock:
|
| 224 |
+
status = self.store.cancel(identifier)
|
| 225 |
+
if status == "cancelled":
|
| 226 |
+
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 227 |
+
self.wakeup.set()
|
| 228 |
+
return status
|
| 229 |
+
|
| 230 |
+
def cleanup(self):
|
| 231 |
+
with self.mutation_lock:
|
| 232 |
+
for identifier in self.store.expired(time.time() - self.settings.retention_s):
|
| 233 |
+
shutil.rmtree(self.job_directory(identifier), ignore_errors=True)
|
| 234 |
+
self.store.forget(identifier)
|
| 235 |
+
|
| 236 |
+
def finish_failed(self, identifier, directory, code):
|
| 237 |
+
with self.mutation_lock:
|
| 238 |
+
if self.store.get(identifier)["status"] == "cancel_requested":
|
| 239 |
+
self.store.update(identifier, "cancelled")
|
| 240 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 241 |
+
else:
|
| 242 |
+
self.store.update(identifier, "failed", code)
|
| 243 |
+
|
| 244 |
+
def loop(self):
|
| 245 |
+
try:
|
| 246 |
+
preflight = self.launch(self.preflight_command, self.settings.data_root / "gpu-preflight.log")
|
| 247 |
+
start = time.monotonic()
|
| 248 |
+
while preflight.poll() is None:
|
| 249 |
+
if self.stopping.wait(.1) or time.monotonic() - start > 300:
|
| 250 |
+
stop_process(preflight)
|
| 251 |
+
self.readiness_reason = "gpu_preflight_timeout"
|
| 252 |
+
return
|
| 253 |
+
if preflight.returncode:
|
| 254 |
+
self.readiness_reason = "gpu_preflight_failed"
|
| 255 |
+
return
|
| 256 |
+
self.ready = True; self.readiness_reason = "ready"
|
| 257 |
+
while not self.stopping.is_set():
|
| 258 |
+
self.cleanup()
|
| 259 |
+
identifier = self.store.claim()
|
| 260 |
+
if identifier:
|
| 261 |
+
self.execute(identifier)
|
| 262 |
+
else:
|
| 263 |
+
self.wakeup.wait(.5); self.wakeup.clear()
|
| 264 |
+
except Exception:
|
| 265 |
+
self.readiness_reason = "queue_worker_failed"
|
| 266 |
+
LOG.exception("GPU job queue stopped")
|
| 267 |
+
finally:
|
| 268 |
+
self.ready = False
|
| 269 |
+
|
| 270 |
+
def execute(self, identifier):
|
| 271 |
+
directory = self.job_directory(identifier)
|
| 272 |
+
process = None
|
| 273 |
+
try:
|
| 274 |
+
process = self.launch(self.command_factory(directory), directory / "worker.log")
|
| 275 |
+
started = time.monotonic()
|
| 276 |
+
while process.poll() is None:
|
| 277 |
+
current = self.store.get(identifier)
|
| 278 |
+
if current["status"] == "cancel_requested":
|
| 279 |
+
stop_process(process)
|
| 280 |
+
with self.mutation_lock:
|
| 281 |
+
self.store.update(identifier, "cancelled")
|
| 282 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 283 |
+
return
|
| 284 |
+
if self.stopping.wait(.1):
|
| 285 |
+
stop_process(process)
|
| 286 |
+
with self.mutation_lock:
|
| 287 |
+
if self.store.get(identifier)["status"] == "cancel_requested":
|
| 288 |
+
self.store.update(identifier, "cancelled")
|
| 289 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 290 |
+
else:
|
| 291 |
+
self.store.update(identifier, "queued")
|
| 292 |
+
return
|
| 293 |
+
if time.monotonic() - started > self.settings.job_timeout_s:
|
| 294 |
+
stop_process(process)
|
| 295 |
+
self.finish_failed(identifier, directory, "job_timeout")
|
| 296 |
+
return
|
| 297 |
+
with self.mutation_lock:
|
| 298 |
+
if self.store.get(identifier)["status"] == "cancel_requested":
|
| 299 |
+
self.store.update(identifier, "cancelled")
|
| 300 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 301 |
+
elif process.returncode == 0 and (directory / "result.json").is_file():
|
| 302 |
+
coach_path = directory / "coach-payload.json"
|
| 303 |
+
self.store.update(identifier, "completed", result_hash=sha256_file(directory / "result.json"),
|
| 304 |
+
coach_hash=sha256_file(coach_path) if coach_path.is_file() else None)
|
| 305 |
+
else:
|
| 306 |
+
error = read_json(directory / "error.json") if (directory / "error.json").exists() else {}
|
| 307 |
+
code = error.get("code")
|
| 308 |
+
if code not in {"invalid_video_or_capture", "inference_failed"}: code = "inference_failed"
|
| 309 |
+
self.store.update(identifier, "failed", code)
|
| 310 |
+
except Exception:
|
| 311 |
+
if process: stop_process(process)
|
| 312 |
+
LOG.exception("Analysis job %s failed", identifier)
|
| 313 |
+
self.finish_failed(identifier, directory, "worker_error")
|
| 314 |
+
finally:
|
| 315 |
+
# Keep uploads only when a server restart will retry the job.
|
| 316 |
+
if self.store.get(identifier)["status"] in TERMINAL:
|
| 317 |
+
for video in directory.glob("input.*"):
|
| 318 |
+
video.unlink(missing_ok=True)
|
baseball_batting/api_output.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Raw 2D pose plus estimated swing measurements; no coaching decisions."""
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .contracts import json_safe
|
| 5 |
+
from .batting_measurements import analyze_batting, coach_payload
|
| 6 |
+
|
| 7 |
+
KEYPOINT_ORDER = ["nose", "left_eye", "right_eye", "left_ear", "right_ear",
|
| 8 |
+
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
|
| 9 |
+
"left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee",
|
| 10 |
+
"right_knee", "left_ankle", "right_ankle"]
|
| 11 |
+
EXTRA_ORDER = ["left_big_toe", "left_small_toe", "left_heel",
|
| 12 |
+
"right_big_toe", "right_small_toe", "right_heel"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def constant_fps(times):
|
| 16 |
+
if len(times) < 2 or any(t is None or not math.isfinite(t) for t in times):
|
| 17 |
+
return None
|
| 18 |
+
delta = np.diff(times)
|
| 19 |
+
if np.any(delta <= 0) or not np.allclose(delta, np.median(delta), rtol=.01, atol=1e-6):
|
| 20 |
+
return None
|
| 21 |
+
return round(float(1 / np.median(delta)), 6)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def build_api_result(capture, observations, options, model_hashes):
|
| 25 |
+
n = capture["frame_count"]
|
| 26 |
+
if len(observations["frames"]) != n:
|
| 27 |
+
raise ValueError("Observation and capture frame counts differ")
|
| 28 |
+
width, height = capture["frames"][0]["width"], capture["frames"][0]["height"]
|
| 29 |
+
if any(f["width"] != width or f["height"] != height for f in capture["frames"]):
|
| 30 |
+
raise ValueError("Changing frame dimensions are unsupported")
|
| 31 |
+
frames = {k: [] for k in ("t_s", "playback_t_s", "kp", "conf", "kp_extra", "conf_extra",
|
| 32 |
+
"box", "track_id", "people_count", "blur", "brightness")}
|
| 33 |
+
real_times = [f["physical_s"] for f in capture["frames"]]
|
| 34 |
+
known_clock = (all(t is not None and math.isfinite(t) for t in real_times)
|
| 35 |
+
and all(b > a for a, b in zip(real_times, real_times[1:])))
|
| 36 |
+
if not known_clock:
|
| 37 |
+
real_times = [None] * n
|
| 38 |
+
for i, observed in enumerate(observations["frames"]):
|
| 39 |
+
if observed["frame_id"] != i:
|
| 40 |
+
raise ValueError("Observation frame order differs from capture")
|
| 41 |
+
points, scores = [], []
|
| 42 |
+
for j in range(23):
|
| 43 |
+
point, score = observed["body_points"][j], observed["body_scores"][j]
|
| 44 |
+
supported = (observed["body_states"][j] == "model_inferred"
|
| 45 |
+
and point is not None and all(x is not None and math.isfinite(x) for x in point)
|
| 46 |
+
and 0 <= point[0] < width and 0 <= point[1] < height
|
| 47 |
+
and score is not None and math.isfinite(score))
|
| 48 |
+
points.append(list(map(float, point)) if supported else None)
|
| 49 |
+
scores.append(float(np.clip(score, 0, 1)) if supported else 0.)
|
| 50 |
+
frames["kp"].append(points[:17]); frames["conf"].append(scores[:17])
|
| 51 |
+
frames["kp_extra"].append(points[17:23]); frames["conf_extra"].append(scores[17:23])
|
| 52 |
+
person = observed.get("person")
|
| 53 |
+
box = person["box"] if person else None
|
| 54 |
+
if box is not None:
|
| 55 |
+
box = np.asarray(box, float)
|
| 56 |
+
if box.shape != (4,) or not np.isfinite(box).all():
|
| 57 |
+
box = None
|
| 58 |
+
else:
|
| 59 |
+
box = np.clip(box, [0, 0, 0, 0], [width, height, width, height]).tolist()
|
| 60 |
+
if box[2] <= box[0] or box[3] <= box[1]:
|
| 61 |
+
box = None
|
| 62 |
+
frames["box"].append(box)
|
| 63 |
+
frames["track_id"].append(1 if box else None)
|
| 64 |
+
frames["people_count"].append(observed.get("people_count"))
|
| 65 |
+
quality = capture["quality"][i]
|
| 66 |
+
variance = quality["blur_laplacian_variance"]
|
| 67 |
+
frames["blur"].append(float(1 / (1 + max(0, variance) / 100)))
|
| 68 |
+
frames["brightness"].append(float(quality["mean_luminance"]))
|
| 69 |
+
frames["t_s"].append(real_times[i])
|
| 70 |
+
frames["playback_t_s"].append(capture["frames"][i]["playback_s"])
|
| 71 |
+
warnings = ["Point scores are model scores; their accuracy has not been calibrated."]
|
| 72 |
+
if not known_clock:
|
| 73 |
+
warnings.append("Capture time is unknown: t_s and capture_fps are null. playback_t_s is not capture time.")
|
| 74 |
+
result = {"schema_version": "1.0", "status": "partial", "warnings": warnings,
|
| 75 |
+
"pose_track": {"schema_version": "1.0", "discipline": "hitting", "view": options.view,
|
| 76 |
+
"video": {"width": width, "height": height, "frame_count": n,
|
| 77 |
+
"capture_fps": constant_fps(real_times),
|
| 78 |
+
"playback_fps": constant_fps(frames["playback_t_s"]),
|
| 79 |
+
"rotation_degrees_applied": capture["rotation_degrees"],
|
| 80 |
+
"time_source": ("original_pts" if options.timing.kind == "unretimed" else
|
| 81 |
+
"slowmo_rescaled" if options.timing.kind == "constant_slowdown" else
|
| 82 |
+
"explicit_capture_times" if options.timing.kind == "explicit" else "unknown") if known_clock else "unknown"},
|
| 83 |
+
"model": {"name": "RTMW-x", "version": "0949e3a9-20230925",
|
| 84 |
+
"sha256": model_hashes["body_pose"], "person_detector": "YOLOX-m HumanArt c2c7a14a",
|
| 85 |
+
"person_detector_sha256": model_hashes["person_detector"],
|
| 86 |
+
"processing": ["score_threshold_0.35", "out_of_image_points_removed", "scores_clipped_0_1", "no_smoothing_or_gap_filling"],
|
| 87 |
+
"people_rule": "largest area times score initially; maximum overlap thereafter; reject overlap below 0.05",
|
| 88 |
+
"blur_definition": "1/(1+grayscale_laplacian_variance/100); heuristic, not calibrated"},
|
| 89 |
+
"keypoint_order": KEYPOINT_ORDER, "extra_keypoint_order": EXTRA_ORDER,
|
| 90 |
+
"frames": frames, "reps": []},
|
| 91 |
+
"capabilities": {"gpu_2d": True, "body_3d": False, "automatic_rep_splitting": True,
|
| 92 |
+
"automatic_events": True, "swing_metrics": True,
|
| 93 |
+
"estimated_only": True,
|
| 94 |
+
"coaching": False, "pitching": False},
|
| 95 |
+
"validation": "reference_validation_pending"}
|
| 96 |
+
pose_reps, measurement_reps, capture_check, diagnostic, method = analyze_batting(result["pose_track"], options)
|
| 97 |
+
result["pose_track"]["reps"] = pose_reps
|
| 98 |
+
result["measurement_method"] = method
|
| 99 |
+
result["warnings"].extend(diagnostic)
|
| 100 |
+
measurements = {"schema_version": "2.0", "discipline": "hitting", "view": options.view,
|
| 101 |
+
"fps": constant_fps(real_times), "capture": capture_check, "reps": measurement_reps}
|
| 102 |
+
if options.level: measurements["level"] = options.level
|
| 103 |
+
result["measurements"] = measurements
|
| 104 |
+
result["coach_payload"] = coach_payload(measurements)
|
| 105 |
+
return json_safe(result)
|
baseball_batting/api_worker.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GPU-only service worker. Never imports SAM, torch, OpenSim or coaching."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import time
|
| 5 |
+
import numpy as np
|
| 6 |
+
import yaml
|
| 7 |
+
from .api_contract import AnalysisInput
|
| 8 |
+
from .api_output import build_api_result
|
| 9 |
+
from .config import CONFIG_ROOT, EngineConfig
|
| 10 |
+
from .storage import StageCache, atomic_json, code_hash, digest, read_json, sha256_file
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def model_files(directory):
|
| 14 |
+
registry = yaml.safe_load((CONFIG_ROOT / "resources.yaml").read_text())["resources"]
|
| 15 |
+
paths, hashes = {}, {}
|
| 16 |
+
for name in ("body_pose", "person_detector"):
|
| 17 |
+
path = Path(directory) / name / "model.onnx"
|
| 18 |
+
if not path.is_file() or sha256_file(path) != registry[name]["sha256"]:
|
| 19 |
+
raise ValueError(f"Missing or incorrect {name} model; run setup_api_models")
|
| 20 |
+
paths[name], hashes[name] = str(path), registry[name]["sha256"]
|
| 21 |
+
return paths, hashes
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def gpu_preflight(models):
|
| 25 |
+
from .body2d import RTMWPose
|
| 26 |
+
from .detection import YOLOXDetector
|
| 27 |
+
paths, _ = model_files(models)
|
| 28 |
+
detector = YOLOXDetector(paths["person_detector"], "cuda", classes=[0])
|
| 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 |
+
"pose_providers": pose.session.get_providers(), "detector_providers": detector.providers}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_duration_s=120,
|
| 38 |
+
device="cuda"):
|
| 39 |
+
"""device is an internal test seam; the public CLI and HTTP API always use CUDA."""
|
| 40 |
+
from .ingest import ingest
|
| 41 |
+
from .observations import run_observations
|
| 42 |
+
job = Path(job)
|
| 43 |
+
options = AnalysisInput.model_validate(read_json(job / "request.json"))
|
| 44 |
+
paths, hashes = model_files(models)
|
| 45 |
+
started = time.monotonic()
|
| 46 |
+
def progress(stage, completed=0, total=None):
|
| 47 |
+
atomic_json(job / "progress.json", {"stage": stage, "completed_frames": completed,
|
| 48 |
+
"total_frames": total, "stage_progress": completed / total if total else None,
|
| 49 |
+
"elapsed_s": round(time.monotonic() - started, 2)})
|
| 50 |
+
video = next(job.glob("input.*"))
|
| 51 |
+
capture_cache = StageCache(job, "ingest", digest({"input": sha256_file(video),
|
| 52 |
+
"metadata": options.engine_metadata(), "code": code_hash(),
|
| 53 |
+
"limits": [max_frames, max_pixels, max_duration_s]}))
|
| 54 |
+
progress("decoding")
|
| 55 |
+
if capture_cache.valid("capture"):
|
| 56 |
+
capture = read_json(capture_cache.root / "capture.json")
|
| 57 |
+
else:
|
| 58 |
+
capture = ingest(video, options.engine_metadata(), max_frames=max_frames,
|
| 59 |
+
max_pixels=max_pixels, max_duration_s=max_duration_s,
|
| 60 |
+
progress=lambda done: progress("decoding", done))
|
| 61 |
+
atomic_json(capture_cache.root / "capture.json", capture)
|
| 62 |
+
capture_cache.commit("capture", [capture_cache.root / "capture.json"])
|
| 63 |
+
n = capture["frame_count"]
|
| 64 |
+
if any(rep.end_frame >= n for rep in options.reps):
|
| 65 |
+
raise ValueError("Rep range exceeds decoded frame count")
|
| 66 |
+
config = EngineConfig(device=device, body_pose_path=paths["body_pose"],
|
| 67 |
+
person_detector_path=paths["person_detector"], object_detector_path=None,
|
| 68 |
+
body3d_enabled=False, temporal3d_enabled=False, anatomy_enabled=False,
|
| 69 |
+
learned_events_enabled=False, bat_3d_mode="disabled", export_video=False,
|
| 70 |
+
coaching_mode="descriptive_only")
|
| 71 |
+
cache = StageCache(job, "observations", digest({"capture": capture_cache.key,
|
| 72 |
+
"models": hashes, "config": config.to_dict(), "code": code_hash()}))
|
| 73 |
+
progress("pose_2d", 0, n)
|
| 74 |
+
observations = run_observations(video, capture, config, cache,
|
| 75 |
+
progress=lambda done, total: progress("pose_2d", done, total))
|
| 76 |
+
if any(observations["branch_status"].get(name, {}).get("status") != "ready"
|
| 77 |
+
for name in ("body_pose", "person_detector")):
|
| 78 |
+
raise RuntimeError("GPU pose or person inference failed")
|
| 79 |
+
# A successfully executed model with no athlete is a capture failure for the
|
| 80 |
+
# coach, not a worker crash. Preserve the record-again payload.
|
| 81 |
+
progress("measurements_2d", n, n)
|
| 82 |
+
result = build_api_result(capture, observations, options, hashes)
|
| 83 |
+
atomic_json(job / "coach-payload.json", result["coach_payload"])
|
| 84 |
+
atomic_json(job / "result.json", result)
|
| 85 |
+
progress("complete", n, n)
|
| 86 |
+
return result
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main():
|
| 90 |
+
parser = argparse.ArgumentParser()
|
| 91 |
+
parser.add_argument("--models", required=True)
|
| 92 |
+
parser.add_argument("--preflight", action="store_true")
|
| 93 |
+
parser.add_argument("--output")
|
| 94 |
+
parser.add_argument("--job")
|
| 95 |
+
parser.add_argument("--max-frames", type=int, default=7200)
|
| 96 |
+
parser.add_argument("--max-pixels", type=int, default=8294400)
|
| 97 |
+
parser.add_argument("--max-duration", type=float, default=120)
|
| 98 |
+
args = parser.parse_args()
|
| 99 |
+
try:
|
| 100 |
+
if args.preflight:
|
| 101 |
+
atomic_json(args.output, gpu_preflight(args.models))
|
| 102 |
+
else:
|
| 103 |
+
run_analysis(args.job, args.models, max_frames=args.max_frames,
|
| 104 |
+
max_pixels=args.max_pixels, max_duration_s=args.max_duration)
|
| 105 |
+
except Exception as error:
|
| 106 |
+
# Logs stay server-side; the public error never includes paths or a traceback.
|
| 107 |
+
print(f"{type(error).__name__}: {error}", flush=True)
|
| 108 |
+
if args.job:
|
| 109 |
+
atomic_json(Path(args.job) / "error.json", {"code": "invalid_video_or_capture" if isinstance(error, ValueError)
|
| 110 |
+
else "inference_failed", "message": "Analysis could not finish. Check the recording, capture metadata and server logs."})
|
| 111 |
+
return 1
|
| 112 |
+
return 0
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
raise SystemExit(main())
|
baseball_batting/assessment.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .contracts import Finding
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import yaml
|
| 4 |
+
|
| 5 |
+
def evaluate_rules(metrics,events,context,trials,path):
|
| 6 |
+
catalogue=yaml.safe_load(Path(path).read_text());findings=[]
|
| 7 |
+
current={m.metric_id:m for m in metrics}
|
| 8 |
+
for rule in catalogue.get("rules",[]):
|
| 9 |
+
required=("id","version","required_metrics","required_events","geometry_sources","validation_scopes",
|
| 10 |
+
"maximum_sensitivity","minimum_trials","context","source","evidence_strength","interpretation","exercise","objective")
|
| 11 |
+
if any(name not in rule for name in required):raise ValueError("Incomplete coaching rule contract")
|
| 12 |
+
source=rule["source"]
|
| 13 |
+
if not source.get("url") or source.get("supports_intervention") is not True or not source.get("context"):continue
|
| 14 |
+
if any(context.get(k)!=v for k,v in rule["context"].items()):continue
|
| 15 |
+
if any(not any(e.type==name and e.state=="confirmed" for e in events) for name in rule["required_events"]):continue
|
| 16 |
+
selected=[current.get(name) for name in rule["required_metrics"]]
|
| 17 |
+
if any(m is None or m.value is None or m.suitability!="supported" for m in selected):continue
|
| 18 |
+
if any(m.geometry_source not in rule["geometry_sources"] or m.validation_status not in rule["validation_scopes"] for m in selected):continue
|
| 19 |
+
if rule["maximum_sensitivity"] is not None and any(m.sensitivity is None or m.sensitivity["maximum_value_change"]>rule["maximum_sensitivity"] for m in selected):continue
|
| 20 |
+
comparable=[trial for trial in trials if all(any(m["metric_id"]==name and m["value"] is not None for m in trial["metrics"]) for name in rule["required_metrics"])]
|
| 21 |
+
if len(comparable)+1<rule["minimum_trials"]:continue
|
| 22 |
+
exercise={**rule["exercise"],"source":source,"objective":rule["objective"],
|
| 23 |
+
"status":"educational_research_hypothesis","expected_benefit":"not_established","comparable_trial_count":len(comparable)+1}
|
| 24 |
+
findings.append(Finding("rule_"+rule["id"],rule["required_metrics"],rule["id"],rule["version"],rule["interpretation"],
|
| 25 |
+
sorted({i for m in selected for i in m.evidence_frames}),"not_reviewed",rule["evidence_strength"],exercise))
|
| 26 |
+
return findings
|
| 27 |
+
|
| 28 |
+
def assess(metrics, context, events=None, trials=None, rules_path=None, mode="descriptive_only"):
|
| 29 |
+
findings = []
|
| 30 |
+
for m in metrics:
|
| 31 |
+
if m.value is None or m.suitability != "supported":
|
| 32 |
+
continue
|
| 33 |
+
findings.append(Finding("observation_"+m.metric_id, [m.metric_id], "describe_available_measurement", "1.0",
|
| 34 |
+
f"{m.metric_id.replace('_', ' ')}: {m.value:.2f} {m.unit}. "
|
| 35 |
+
"This describes this recording; no persistent fault or benefit is established.",
|
| 36 |
+
m.evidence_frames))
|
| 37 |
+
if mode=="evidence_linked_experimental" and rules_path:
|
| 38 |
+
findings.extend(evaluate_rules(metrics,events or [],context,trials or [],rules_path))
|
| 39 |
+
return findings
|
baseball_batting/bat2d.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contour and optical-flow proposals. Boxes never become measured endpoints."""
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
def contour_endpoints(image, box, previous=None):
|
| 6 |
+
h, w = image.shape[:2]
|
| 7 |
+
x1, y1, x2, y2 = np.rint(box).astype(int)
|
| 8 |
+
x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
|
| 9 |
+
if x2-x1 < 8 or y2-y1 < 8:
|
| 10 |
+
return None
|
| 11 |
+
roi = image[y1:y2, x1:x2]
|
| 12 |
+
mask = np.zeros(roi.shape[:2], np.uint8)
|
| 13 |
+
bg, fg = np.zeros((1, 65), np.float64), np.zeros((1, 65), np.float64)
|
| 14 |
+
cv2.grabCut(roi, mask, (1, 1, roi.shape[1]-2, roi.shape[0]-2), bg, fg, 2, cv2.GC_INIT_WITH_RECT)
|
| 15 |
+
foreground = np.where((mask == 1) | (mask == 3), 255, 0).astype(np.uint8)
|
| 16 |
+
contours, _ = cv2.findContours(foreground, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
|
| 17 |
+
options = []
|
| 18 |
+
for c in contours:
|
| 19 |
+
points = c.reshape(-1, 2).astype(float)
|
| 20 |
+
if len(points) < 8:
|
| 21 |
+
continue
|
| 22 |
+
vx, vy, ax, ay = cv2.fitLine(c, cv2.DIST_HUBER, 0, .01, .01).ravel()
|
| 23 |
+
axis = np.array([vx, vy]); origin = np.array([ax, ay])
|
| 24 |
+
along = (points-origin) @ axis
|
| 25 |
+
across = (points-origin) @ np.array([-vy, vx])
|
| 26 |
+
length, width = np.ptp(along), np.ptp(across)
|
| 27 |
+
if length < 20 or length / max(width, 1) < 4:
|
| 28 |
+
continue
|
| 29 |
+
ends = origin + np.array([[along.min()], [along.max()]])*axis + [x1, y1]
|
| 30 |
+
# Reject contours truncated by the ROI: true ends are not visible.
|
| 31 |
+
if np.any(points[:, 0] < 2) or np.any(points[:, 0] > roi.shape[1]-3) or np.any(points[:, 1] < 2) or np.any(points[:, 1] > roi.shape[0]-3):
|
| 32 |
+
continue
|
| 33 |
+
options.append((length, ends))
|
| 34 |
+
if len(options) != 1 or previous is None:
|
| 35 |
+
return None # Endpoint identity needs a seed, not an arbitrary left/right choice.
|
| 36 |
+
ends = options[0][1]
|
| 37 |
+
if np.linalg.norm(ends-np.array(previous)) > np.linalg.norm(ends[::-1]-np.array(previous)):
|
| 38 |
+
ends = ends[::-1]
|
| 39 |
+
return ends
|
| 40 |
+
|
| 41 |
+
class BatTracker:
|
| 42 |
+
def __init__(self, state=None):
|
| 43 |
+
self.points = None if not state or not state.get("points") else np.array(state["points"], dtype=np.float32)
|
| 44 |
+
self.previous_gray = None
|
| 45 |
+
|
| 46 |
+
def snapshot(self):
|
| 47 |
+
return {"points": None if self.points is None else self.points.tolist()}
|
| 48 |
+
|
| 49 |
+
def update(self, image, proposals, manual=None):
|
| 50 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 51 |
+
result = {"points": None, "states": ["unknown", "unknown"], "method": "no_supported_endpoints"}
|
| 52 |
+
if manual is not None:
|
| 53 |
+
self.points = np.array(manual, np.float32)
|
| 54 |
+
result = {"points": self.points.tolist(), "states": ["manual", "manual"], "method": "reviewed_seed"}
|
| 55 |
+
else:
|
| 56 |
+
boxes = [d["box"] for d in proposals if d["class_id"] == 34]
|
| 57 |
+
fitted = None
|
| 58 |
+
if self.points is not None and len(boxes) == 1:
|
| 59 |
+
try:
|
| 60 |
+
fitted = contour_endpoints(image, boxes[0], self.points)
|
| 61 |
+
except cv2.error:
|
| 62 |
+
pass
|
| 63 |
+
if fitted is not None:
|
| 64 |
+
self.points = fitted.astype(np.float32)
|
| 65 |
+
result = {"points": fitted.tolist(), "states": ["image_supported"]*2, "method": "seeded_contour_axis"}
|
| 66 |
+
elif self.points is not None and self.previous_gray is not None:
|
| 67 |
+
seed = self.points.reshape(-1, 1, 2)
|
| 68 |
+
forward, ok, _ = cv2.calcOpticalFlowPyrLK(self.previous_gray, gray, seed, None)
|
| 69 |
+
if forward is not None:
|
| 70 |
+
backward, back_ok, _ = cv2.calcOpticalFlowPyrLK(gray, self.previous_gray, forward, None)
|
| 71 |
+
consistent = backward is not None and np.all(ok) and np.all(back_ok) and np.max(np.linalg.norm(backward-seed, axis=2)) < 1.5
|
| 72 |
+
points = forward.reshape(2, 2)
|
| 73 |
+
in_bounds = np.all(points >= 0) and np.all(points[:, 0] < gray.shape[1]) and np.all(points[:, 1] < gray.shape[0])
|
| 74 |
+
if consistent and in_bounds:
|
| 75 |
+
self.points = points
|
| 76 |
+
result = {"points": points.tolist(), "states": ["propagated"]*2, "method": "LK_forward_backward_proposal"}
|
| 77 |
+
else:
|
| 78 |
+
self.points = None
|
| 79 |
+
else:
|
| 80 |
+
self.points = None
|
| 81 |
+
self.previous_gray = gray
|
| 82 |
+
return result
|
| 83 |
+
|
baseball_batting/bat3d.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent rigid-bat geometry. Monocular body depth is never an independent grip."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.optimize import least_squares
|
| 5 |
+
from .geometry import project, intrinsics, triangulate, barrel_from_independent_knob, to_world
|
| 6 |
+
from .storage import StageCache, digest, atomic_json, read_json
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def reconstruct_frame(record, mode, calibration, length, max_error_px=3.):
|
| 10 |
+
if not record.get("source") or record.get("independent") is not True:
|
| 11 |
+
raise ValueError("Bat geometry requires documented independent measurements")
|
| 12 |
+
if length <= .1524: raise ValueError("Known bat length must exceed the measurement-point offset")
|
| 13 |
+
if mode == "calibrated_multiview":
|
| 14 |
+
if record.get("world_axes")!="x_pitcher_y_up_z_right_handed":
|
| 15 |
+
raise ValueError("Multiview projections must identify the calibrated world axes")
|
| 16 |
+
if record.get("synchronization_verified") is not True:
|
| 17 |
+
raise ValueError("Multiview endpoints must have verified synchronization")
|
| 18 |
+
cameras = np.asarray(record["projection_matrices"], float)
|
| 19 |
+
endpoints = np.asarray(record["endpoints_pixels"], float) # views x knob/barrel x xy
|
| 20 |
+
if endpoints.shape != (len(cameras), 2, 2): raise ValueError("Invalid multiview endpoints")
|
| 21 |
+
points = np.array([triangulate(endpoints[:, j], cameras, max_error_px)[0] for j in range(2)])
|
| 22 |
+
if abs(np.linalg.norm(points[1]-points[0])-length) > .03:
|
| 23 |
+
raise ValueError("Triangulated endpoints disagree with measured bat length")
|
| 24 |
+
def residual(flat):
|
| 25 |
+
xyz = flat.reshape(2, 3); errors = []
|
| 26 |
+
for view, camera in enumerate(cameras):
|
| 27 |
+
h = np.c_[xyz, np.ones(2)]@camera.T
|
| 28 |
+
valid = np.isfinite(endpoints[view]).all(axis=1)
|
| 29 |
+
errors.extend((h[valid,:2]/h[valid,2:3]-endpoints[view,valid]).ravel())
|
| 30 |
+
return np.r_[errors, (np.linalg.norm(xyz[1]-xyz[0])-length)/.001]
|
| 31 |
+
points = least_squares(residual, points.ravel(), loss="soft_l1").x.reshape(2,3)
|
| 32 |
+
error = float(np.max(np.abs(residual(points.ravel())[:-1])))
|
| 33 |
+
if error > max_error_px or abs(np.linalg.norm(points[1]-points[0])-length) > .003:
|
| 34 |
+
raise ValueError("Rigid bat fit failed observation/length agreement")
|
| 35 |
+
return points, error, "world_x_pitcher_y_up_z_right_handed"
|
| 36 |
+
if mode != "calibrated_independent_grip": raise ValueError("Unknown bat reconstruction mode")
|
| 37 |
+
k = intrinsics(calibration["intrinsics_oriented_pixels"])
|
| 38 |
+
if not calibration.get("source"): raise ValueError("Documented camera calibration is required")
|
| 39 |
+
pixels = np.asarray(record["endpoints_pixels"], float)
|
| 40 |
+
knob = np.asarray(record["knob_camera_m"], float)
|
| 41 |
+
barrel = barrel_from_independent_knob(knob, pixels[1], k, length, record.get("barrel_anchor_camera_m"))
|
| 42 |
+
points = np.stack([knob, barrel]); error = float(np.linalg.norm(project(points,k)-pixels,axis=1).max())
|
| 43 |
+
if error > max_error_px: raise ValueError("Independent knob measurement fails reprojection")
|
| 44 |
+
return points, error, "camera_x_right_y_down_z_forward_metres"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def run_bat3d(request, capture, config):
|
| 48 |
+
root = Path(request["root"])
|
| 49 |
+
try:
|
| 50 |
+
if config.bat_3d_mode not in {"calibrated_multiview","calibrated_independent_grip"}:
|
| 51 |
+
raise ValueError("independent_geometry_not_qualified")
|
| 52 |
+
geometry = capture["metadata"].get("bat_geometry", {})
|
| 53 |
+
length = capture["metadata"].get("bat_length_m")
|
| 54 |
+
if not length: raise ValueError("Measured bat length unavailable")
|
| 55 |
+
calibration = capture["metadata"].get("calibration", {})
|
| 56 |
+
cache = StageCache(root, "bat3d", digest({"capture": capture["input_sha256"], "geometry": geometry,
|
| 57 |
+
"code_hash":request["code_hash"],"environment":request.get("environment"),
|
| 58 |
+
"mode": config.bat_3d_mode, "length": length, "calibration": calibration}))
|
| 59 |
+
if cache.valid("trajectory"):
|
| 60 |
+
atomic_json(root/"bat3d_status.json",read_json(cache.root/"status.json")); return
|
| 61 |
+
count = capture["frame_count"]
|
| 62 |
+
points = np.full((count,2,3),np.nan); errors = np.full(count,np.nan); rejected = {}
|
| 63 |
+
space = None
|
| 64 |
+
for key, record in geometry.get("frames", {}).items():
|
| 65 |
+
index = int(key)
|
| 66 |
+
if not 0 <= index < count: raise ValueError("Independent bat frame outside video")
|
| 67 |
+
try:
|
| 68 |
+
value, error, coordinates = reconstruct_frame(record,config.bat_3d_mode,calibration,length)
|
| 69 |
+
if space and coordinates != space: raise ValueError("Mixed bat coordinate systems")
|
| 70 |
+
points[index], errors[index], space = value,error,coordinates
|
| 71 |
+
except (ValueError,KeyError) as error:
|
| 72 |
+
rejected[str(index)] = str(error)
|
| 73 |
+
valid = np.isfinite(points).all(axis=(1,2))
|
| 74 |
+
if not valid.any(): raise ValueError("No independently supported unambiguous bat frames")
|
| 75 |
+
world = np.full_like(points,np.nan)
|
| 76 |
+
if space.startswith("world"): world = points.copy()
|
| 77 |
+
else:
|
| 78 |
+
try: world = to_world(points,calibration)
|
| 79 |
+
except (ValueError,KeyError): pass
|
| 80 |
+
direction = (points[:,1]-points[:,0])/length
|
| 81 |
+
sweet = points[:,1]-.1524*direction
|
| 82 |
+
world_sweet = world[:,1]-.1524*(world[:,1]-world[:,0])/length
|
| 83 |
+
path = cache.root/"trajectory.npz"
|
| 84 |
+
np.savez_compressed(path,endpoints_m=points,endpoints_world_m=world,sweet_spot_m=sweet,
|
| 85 |
+
sweet_spot_world_m=world_sweet,reprojection_px=errors,accepted_frames=valid)
|
| 86 |
+
result = {"status":"complete" if valid.all() else "partial","cache_key":cache.key,
|
| 87 |
+
"trajectory_path":str(path.relative_to(root)),"frames_fitted":int(valid.sum()),
|
| 88 |
+
"coordinate_space":space,"geometry_source":config.bat_3d_mode,"rejected_frames":rejected,
|
| 89 |
+
"measurement_point":"0.1524m_inward_from_barrel_along_shaft",
|
| 90 |
+
"validation":"reference-validation-pending","independent_geometry":True}
|
| 91 |
+
atomic_json(cache.root/"status.json",result);cache.commit("trajectory",[path,cache.root/"status.json"])
|
| 92 |
+
except Exception as error:
|
| 93 |
+
result={"status":"unavailable","reason":str(error)[:300],"error_type":type(error).__name__}
|
| 94 |
+
atomic_json(root/"bat3d_status.json",result)
|
baseball_batting/batting_measurements.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned 2D batting estimates. No 3D, faults, drills or calibrated accuracy.
|
| 2 |
+
|
| 3 |
+
Raw exported points are untouched. Analysis fills at most three missing frames,
|
| 4 |
+
then applies a three-frame median on contiguous finite runs. Swing candidates
|
| 5 |
+
need a sustained hand excursion; event evidence and all non-null metrics remain
|
| 6 |
+
estimates until independently validated. Physical times never use playback FPS.
|
| 7 |
+
"""
|
| 8 |
+
import math
|
| 9 |
+
import numpy as np
|
| 10 |
+
from scipy.ndimage import median_filter
|
| 11 |
+
|
| 12 |
+
VERSION = "batting-2d-v1"
|
| 13 |
+
EVENT_ORDER = ["stance_set", "load_start", "stride", "foot_contact", "foot_plant",
|
| 14 |
+
"swing_start", "contact", "finish"]
|
| 15 |
+
METRICS = {
|
| 16 |
+
"stride_pct_height": ("%", 10, 120),
|
| 17 |
+
"foot_plant_to_contact_ms": ("ms", 30, 800),
|
| 18 |
+
"com_drift_pct_height": ("%", -80, 80),
|
| 19 |
+
"load_tempo_s": ("s", .05, 3),
|
| 20 |
+
"load_launch_ratio": ("ratio", .1, 20),
|
| 21 |
+
"head_movement_pct_height": ("%", 0, 40),
|
| 22 |
+
"lead_knee_angle_contact_deg": ("deg", 60, 200),
|
| 23 |
+
"lateral_trunk_tilt_contact_deg": ("deg", -90, 90),
|
| 24 |
+
"hip_shoulder_separation_foot_plant_deg": ("deg", -90, 90),
|
| 25 |
+
}
|
| 26 |
+
CAPTURE_REASONS = {"no_person", "multiple_people", "player_switched", "person_too_small",
|
| 27 |
+
"partly_out_of_frame", "too_dark", "a_bit_dark", "too_blurry", "a_bit_blurry",
|
| 28 |
+
"low_pose_confidence", "pose_confidence_fair", "low_fps", "very_low_fps",
|
| 29 |
+
"wrong_view", "view_uncertain"}
|
| 30 |
+
FATAL_REASONS = {"no_person", "multiple_people", "player_switched", "person_too_small",
|
| 31 |
+
"partly_out_of_frame", "too_dark", "too_blurry", "low_pose_confidence",
|
| 32 |
+
"very_low_fps", "wrong_view", "view_uncertain"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def runs(mask):
|
| 36 |
+
edges = np.diff(np.r_[False, np.asarray(mask, bool), False].astype(int))
|
| 37 |
+
return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def point_array(rows, joints):
|
| 41 |
+
"""JSON null points become NaN pairs, preserving rectangular frame arrays."""
|
| 42 |
+
output = np.full((len(rows), joints, 2), np.nan)
|
| 43 |
+
for i, row in enumerate(rows):
|
| 44 |
+
for j, point in enumerate(row):
|
| 45 |
+
if point is not None:
|
| 46 |
+
output[i, j] = point
|
| 47 |
+
return output
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def analysis_points(points, max_gap=3):
|
| 51 |
+
result = np.asarray(points, float).copy()
|
| 52 |
+
# No extrapolation, or interpolation over gaps longer than three frames.
|
| 53 |
+
for j in range(result.shape[1]):
|
| 54 |
+
valid = np.isfinite(result[:, j]).all(axis=1)
|
| 55 |
+
for a, b in runs(~valid):
|
| 56 |
+
if b-a <= max_gap and a > 0 and b < len(result) and valid[a-1] and valid[b]:
|
| 57 |
+
fraction = np.arange(1, b-a+1) / (b-a+1)
|
| 58 |
+
result[a:b, j] = result[a-1, j] + fraction[:, None] * (result[b, j]-result[a-1, j])
|
| 59 |
+
for a, b in runs(np.isfinite(result[:, j]).all(axis=1)):
|
| 60 |
+
if b-a >= 3:
|
| 61 |
+
result[a:b, j] = median_filter(result[a:b, j], size=(3, 1), mode="nearest")
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def included_angle(a, b, c):
|
| 66 |
+
u, v = np.asarray(a)-b, np.asarray(c)-b
|
| 67 |
+
den = np.linalg.norm(u, axis=-1) * np.linalg.norm(v, axis=-1)
|
| 68 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 69 |
+
return np.degrees(np.arccos(np.clip(np.sum(u*v, axis=-1) / den, -1, 1)))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def stature(points, options):
|
| 73 |
+
if options.body_height_px is not None:
|
| 74 |
+
return float(options.body_height_px), "caller supplied standing image height"
|
| 75 |
+
shoulders = (points[:, 5]+points[:, 6]) / 2
|
| 76 |
+
hips = (points[:, 11]+points[:, 12]) / 2
|
| 77 |
+
legs = (np.linalg.norm(points[:, 11]-points[:, 13], axis=1)
|
| 78 |
+
+ np.linalg.norm(points[:, 13]-points[:, 15], axis=1)
|
| 79 |
+
+ np.linalg.norm(points[:, 12]-points[:, 14], axis=1)
|
| 80 |
+
+ np.linalg.norm(points[:, 14]-points[:, 16], axis=1)) / 2
|
| 81 |
+
# Nose-to-shoulder + torso + leg chain. The 1.08 correction is a declared
|
| 82 |
+
# heuristic for the unobserved head/foot extent, not measured body stature.
|
| 83 |
+
values = 1.08 * (np.linalg.norm(points[:, 0]-shoulders, axis=1)
|
| 84 |
+
+ np.linalg.norm(shoulders-hips, axis=1) + legs)
|
| 85 |
+
values = values[np.isfinite(values) & (values > 0)]
|
| 86 |
+
if len(values) < 5:
|
| 87 |
+
return None, "body height unavailable"
|
| 88 |
+
return float(np.percentile(values, 90)), "projected skeleton length × 1.08; standing height unmeasured"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def motion_clock(frames):
|
| 92 |
+
for name in ("t_s", "playback_t_s"):
|
| 93 |
+
values = np.asarray(frames[name], float)
|
| 94 |
+
if np.isfinite(values).all() and len(values) > 1 and np.all(np.diff(values) > 0):
|
| 95 |
+
return values, float(np.median(np.diff(values)))
|
| 96 |
+
return np.arange(len(frames["kp"]), dtype=float), 1.
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def direction_from_stance(points, options, height):
|
| 100 |
+
if options.pitcher_direction:
|
| 101 |
+
return -1 if options.pitcher_direction == "image_left" else 1
|
| 102 |
+
if not options.handedness or height is None:
|
| 103 |
+
return None
|
| 104 |
+
lead, back = (15, 16) if options.handedness == "right" else (16, 15)
|
| 105 |
+
delta = points[:, lead, 0] - points[:, back, 0]
|
| 106 |
+
finite = delta[np.isfinite(delta)]
|
| 107 |
+
if len(finite) < 5 or abs(float(np.median(finite))) < .04*height:
|
| 108 |
+
return None
|
| 109 |
+
return int(np.sign(np.median(finite)))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def hand_motion(points, height, direction):
|
| 113 |
+
hands = (points[:, 9]+points[:, 10]) / 2
|
| 114 |
+
hips = (points[:, 11]+points[:, 12]) / 2
|
| 115 |
+
relative = (hands-hips) / (height or 1)
|
| 116 |
+
change = np.diff(relative, axis=0)
|
| 117 |
+
magnitude = np.r_[0., np.linalg.norm(change, axis=1)]
|
| 118 |
+
forward = np.r_[0., direction*change[:, 0]] if direction else magnitude.copy()
|
| 119 |
+
values = magnitude[np.isfinite(magnitude)]
|
| 120 |
+
if len(values) < 5:
|
| 121 |
+
return hands, relative, magnitude, forward, math.inf
|
| 122 |
+
median = np.median(values)
|
| 123 |
+
mad = np.median(np.abs(values-median))
|
| 124 |
+
threshold = max(float(median+2*mad), float(np.percentile(values, 90)*.3), .0005)
|
| 125 |
+
return hands, relative, magnitude, forward, threshold
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def candidate_bursts(relative, magnitude, forward, threshold, dt, direction):
|
| 129 |
+
mask = np.isfinite(forward) & (forward > threshold)
|
| 130 |
+
# Merge brief within-swing pauses, but never bridge unavailable hand points.
|
| 131 |
+
gap = max(1, min(12, round(.06 / dt)))
|
| 132 |
+
for a, b in runs(~mask):
|
| 133 |
+
if b-a <= gap and a > 0 and b < len(mask) and np.isfinite(relative[a:b]).all():
|
| 134 |
+
mask[a:b] = True
|
| 135 |
+
minimum = max(3, min(20, round(.025 / dt)))
|
| 136 |
+
bursts = []
|
| 137 |
+
for a, b in runs(mask):
|
| 138 |
+
if b-a < minimum or a == 0 or not np.isfinite(relative[a-1:b]).all():
|
| 139 |
+
continue
|
| 140 |
+
path = relative[a-1:b]
|
| 141 |
+
excursion = (direction * (path[-1, 0]-path[0, 0]) if direction
|
| 142 |
+
else float(np.linalg.norm(path[-1]-path[0])))
|
| 143 |
+
if excursion < .12:
|
| 144 |
+
continue
|
| 145 |
+
# Motion without direction is only a generic rep candidate. It never
|
| 146 |
+
# establishes a forward-swing event or contact by itself.
|
| 147 |
+
peak = a+int(np.nanargmax(magnitude[a:b]))
|
| 148 |
+
if bursts and a-bursts[-1][1] <= gap:
|
| 149 |
+
bursts[-1] = (bursts[-1][0], b, peak)
|
| 150 |
+
else:
|
| 151 |
+
bursts.append((a, b, peak))
|
| 152 |
+
return bursts
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def automatic_ranges(bursts, motion, dt, direction, n):
|
| 156 |
+
"""Trim unrelated leading/trailing footage using observed quiet intervals."""
|
| 157 |
+
_, relative, magnitude, _, threshold = motion
|
| 158 |
+
minimum = max(3, min(12, round(.035/dt)))
|
| 159 |
+
quiet = np.isfinite(magnitude) & (magnitude < threshold*.3)
|
| 160 |
+
backward = (np.r_[False, direction*np.diff(relative[:, 0]) < -threshold*.6]
|
| 161 |
+
if direction else np.zeros(n, bool))
|
| 162 |
+
margin = max(minimum+2, min(60, round(.15/dt)))
|
| 163 |
+
output = []
|
| 164 |
+
for index, (a, b, peak) in enumerate(bursts):
|
| 165 |
+
left = 0 if index == 0 else (bursts[index-1][2]+peak)//2+1
|
| 166 |
+
right = n-1 if index+1 == len(bursts) else (peak+bursts[index+1][2])//2
|
| 167 |
+
if left > a or right < b-1: continue
|
| 168 |
+
load_runs = [(s+left, e+left) for s, e in runs(backward[left:a]) if e-s >= minimum]
|
| 169 |
+
anchor = load_runs[-1][0] if load_runs else a
|
| 170 |
+
before = [(s+left, e+left) for s, e in runs(quiet[left:anchor]) if e-s >= minimum]
|
| 171 |
+
start = max(before[-1][0], anchor-margin) if before else left
|
| 172 |
+
after = [(s+b, e+b) for s, e in runs(quiet[b:right+1]) if e-s >= minimum]
|
| 173 |
+
end = min(right, after[0][0]+minimum+2) if after else right
|
| 174 |
+
output.append((start, end))
|
| 175 |
+
return output
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def capture_checks(track, options, height, selected_frames):
|
| 179 |
+
f = track["frames"]
|
| 180 |
+
ids = np.asarray(sorted(set(selected_frames)), int)
|
| 181 |
+
if not len(ids): ids = np.arange(track["video"]["frame_count"])
|
| 182 |
+
reasons, diagnostics = [], []
|
| 183 |
+
boxes = [f["box"][i] for i in ids]
|
| 184 |
+
present = [b for b in boxes if b is not None]
|
| 185 |
+
counts = [f["people_count"][i] for i in ids]
|
| 186 |
+
if not present:
|
| 187 |
+
reasons.append("no_person")
|
| 188 |
+
elif sum(x is not None and x > 1 for x in counts) > .1*len(ids):
|
| 189 |
+
reasons.append("multiple_people")
|
| 190 |
+
if any(x is None for x in counts):
|
| 191 |
+
diagnostics.append("Person counts are unavailable for some analyzed frames.")
|
| 192 |
+
width, video_height = track["video"]["width"], track["video"]["height"]
|
| 193 |
+
if present:
|
| 194 |
+
if np.median([b[3]-b[1] for b in present]) < .18*video_height or (height and height < 120):
|
| 195 |
+
reasons.append("person_too_small")
|
| 196 |
+
if sum(b[0] <= 2 or b[1] <= 2 or b[2] >= width-2 or b[3] >= video_height-2
|
| 197 |
+
for b in present) > .1*len(ids):
|
| 198 |
+
reasons.append("partly_out_of_frame")
|
| 199 |
+
jumps = 0
|
| 200 |
+
for previous, current, a, b in zip(ids, ids[1:], boxes, boxes[1:]):
|
| 201 |
+
if current == previous+1 and a is not None and b is not None:
|
| 202 |
+
distance = np.linalg.norm((np.array(a[:2])+a[2:])/2 - (np.array(b[:2])+b[2:])/2)
|
| 203 |
+
jumps += distance > .5*(height or video_height)
|
| 204 |
+
if jumps:
|
| 205 |
+
reasons.append("player_switched")
|
| 206 |
+
diagnostics.append("A large adjacent-frame box jump suggests a camera cut or identity change.")
|
| 207 |
+
kp = point_array(f["kp"], 17)[ids]
|
| 208 |
+
core = [0, 5, 6, 11, 12, 15, 16]
|
| 209 |
+
complete = np.isfinite(kp[:, core]).all(axis=(1, 2))
|
| 210 |
+
if complete.mean() < .8: reasons.append("low_pose_confidence")
|
| 211 |
+
elif complete.mean() < .95: reasons.append("pose_confidence_fair")
|
| 212 |
+
brightness = float(np.median(np.asarray(f["brightness"])[ids]))
|
| 213 |
+
blur = float(np.median(np.asarray(f["blur"])[ids]))
|
| 214 |
+
if brightness < 30: reasons.append("too_dark")
|
| 215 |
+
elif brightness < 60: reasons.append("a_bit_dark")
|
| 216 |
+
if blur > .9: reasons.append("too_blurry")
|
| 217 |
+
elif blur > .75: reasons.append("a_bit_blurry")
|
| 218 |
+
fps = track["video"]["capture_fps"]
|
| 219 |
+
if fps is not None:
|
| 220 |
+
if fps < 30-1e-6: reasons.append("very_low_fps")
|
| 221 |
+
elif fps < 60-1e-6: reasons.append("low_fps")
|
| 222 |
+
else:
|
| 223 |
+
diagnostics.append("Capture FPS is unknown or variable; timing metrics are withheld.")
|
| 224 |
+
if options.view != "face_on": reasons.append("view_uncertain")
|
| 225 |
+
if options.camera_stability != "fixed_verified":
|
| 226 |
+
diagnostics.append("Camera stability is unverified or moving; image-motion measurements are withheld.")
|
| 227 |
+
reasons = list(dict.fromkeys(reasons))
|
| 228 |
+
return {"ok": not any(r in FATAL_REASONS for r in reasons), "reasons": reasons}, diagnostics
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def infer_events(track, points, options, height, direction, motion, start, end):
|
| 232 |
+
hands, relative, magnitude, forward, threshold = motion
|
| 233 |
+
_, dt = motion_clock(track["frames"])
|
| 234 |
+
raw = point_array(track["frames"]["kp"], 17)
|
| 235 |
+
raw_feet = point_array(track["frames"]["kp_extra"], 6)
|
| 236 |
+
feet = analysis_points(raw_feet)
|
| 237 |
+
events, missing = {}, {key: "No sufficient 2D evidence." for key in EVENT_ORDER}
|
| 238 |
+
if options.view != "face_on" or options.camera_stability != "fixed_verified":
|
| 239 |
+
return events, {key: "A declared face-on, fixed-camera recording is required." for key in EVENT_ORDER}
|
| 240 |
+
if height is None:
|
| 241 |
+
return events, {key: "Body scale is unavailable." for key in EVENT_ORDER}
|
| 242 |
+
minimum = max(3, min(12, round(.035 / dt)))
|
| 243 |
+
positive = candidate_bursts(relative[start:end+1], magnitude[start:end+1],
|
| 244 |
+
forward[start:end+1], threshold, dt, direction)
|
| 245 |
+
if not positive:
|
| 246 |
+
return events, missing
|
| 247 |
+
# A caller-declared range with two clear drives is ambiguous. Never silently
|
| 248 |
+
# select the best peak and call that range one swing.
|
| 249 |
+
if len(positive) != 1:
|
| 250 |
+
return events, {key: "More than one hand-motion burst in this rep range." for key in EVENT_ORDER}
|
| 251 |
+
a, b, peak = positive[0]
|
| 252 |
+
a, b, peak = a+start, b+start, peak+start
|
| 253 |
+
def add(name, frame, method, note, joints=(9, 10, 11, 12)):
|
| 254 |
+
if frame < start or frame > end or not np.isfinite(raw[frame, list(joints)]).all():
|
| 255 |
+
return
|
| 256 |
+
score = min(.5, float(np.min(np.asarray(track["frames"]["conf"])[frame, list(joints)])))
|
| 257 |
+
event = {"frame": int(frame), "confidence": score, "estimated": True,
|
| 258 |
+
"method": method, "note": note}
|
| 259 |
+
t = track["frames"]["t_s"][frame]
|
| 260 |
+
if t is not None: event["t_s"] = float(t)
|
| 261 |
+
events[name] = event; missing.pop(name, None)
|
| 262 |
+
if direction is not None:
|
| 263 |
+
add("swing_start", a, "sustained_forward_hand_motion_v1",
|
| 264 |
+
"Estimated onset of sustained forward hand displacement; acceleration onset is not validated.")
|
| 265 |
+
else:
|
| 266 |
+
missing["swing_start"] = "Pitcher direction could not be established."
|
| 267 |
+
quiet = np.isfinite(magnitude) & (magnitude < threshold*.3)
|
| 268 |
+
quiet_runs = [(s, e) for s, e in runs(quiet[start:a]) if e-s >= minimum]
|
| 269 |
+
# Last visible backward hand excursion before the forward drive.
|
| 270 |
+
if direction is not None:
|
| 271 |
+
backward = np.r_[False, direction*np.diff(relative[:, 0]) < -threshold*.6]
|
| 272 |
+
loads = []
|
| 273 |
+
for s, e in runs(backward[start:a]):
|
| 274 |
+
s, e = s+start, e+start
|
| 275 |
+
if e-s >= minimum and s > start and np.isfinite(relative[s-1:e]).all():
|
| 276 |
+
if direction*(relative[s-1, 0]-relative[e-1, 0]) >= .025:
|
| 277 |
+
loads.append(s)
|
| 278 |
+
if loads:
|
| 279 |
+
add("load_start", loads[-1], "backward_hand_excursion_v1",
|
| 280 |
+
"Estimated hand load start; does not establish whole-body loading.")
|
| 281 |
+
else:
|
| 282 |
+
missing["load_start"] = "No sustained backward hand load was found."
|
| 283 |
+
preparation_end = events.get("load_start", {"frame": a})["frame"]
|
| 284 |
+
quiet_runs = [(s, e) for s, e in quiet_runs if start+e <= preparation_end]
|
| 285 |
+
if quiet_runs:
|
| 286 |
+
q, stop = quiet_runs[-1]
|
| 287 |
+
add("stance_set", start+q, "pre_drive_quiet_hands_v1",
|
| 288 |
+
"Stable hands are a stance estimate, not proof of a complete stance.")
|
| 289 |
+
lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None
|
| 290 |
+
contact = None
|
| 291 |
+
if lead is not None and direction is not None:
|
| 292 |
+
shoulder, elbow, wrist = ((5, 7, 9) if lead == 0 else (6, 8, 10))
|
| 293 |
+
ids = np.arange(max(a, peak), min(b+minimum, end)+1)
|
| 294 |
+
angle = included_angle(points[ids, shoulder], points[ids, elbow], points[ids, wrist])
|
| 295 |
+
front = direction*(hands[ids, 0]-points[ids, shoulder, 0]) > .04*height
|
| 296 |
+
eligible = np.isfinite(angle) & front & (angle >= 140)
|
| 297 |
+
if eligible.any():
|
| 298 |
+
best = float(np.max(angle[eligible]))
|
| 299 |
+
choices = ids[eligible & (angle >= best-2)]
|
| 300 |
+
# Boundary maxima are incomplete evidence, not forced contact.
|
| 301 |
+
contact = int(choices[0])
|
| 302 |
+
if contact == end: contact = None
|
| 303 |
+
if contact is not None:
|
| 304 |
+
add("contact", contact, "lead_arm_extension_proxy_v1",
|
| 305 |
+
"Estimated maximum lead-arm extension with hands forward; no bat-ball contact confirmed.",
|
| 306 |
+
(shoulder, elbow, wrist, 9, 10))
|
| 307 |
+
if "contact" not in events: contact = None
|
| 308 |
+
if contact is None:
|
| 309 |
+
missing["contact"] = "A visible forward lead-arm extension peak was not found."
|
| 310 |
+
else:
|
| 311 |
+
missing["contact"] = "Handedness and pitcher direction are required for the contact estimate."
|
| 312 |
+
if lead is not None:
|
| 313 |
+
ankle = 15+lead
|
| 314 |
+
back_ankle = 16-lead
|
| 315 |
+
prep_end = events.get("load_start", events.get("swing_start", {"frame": a}))["frame"]
|
| 316 |
+
baseline_start = events.get("stance_set", {"frame": start})["frame"]
|
| 317 |
+
baseline_ids = np.arange(baseline_start, max(baseline_start+1, prep_end))
|
| 318 |
+
baseline = points[baseline_ids, ankle]
|
| 319 |
+
valid = np.isfinite(baseline).all(axis=1)
|
| 320 |
+
if valid.sum() >= minimum:
|
| 321 |
+
baseline = np.median(baseline[valid], axis=0)
|
| 322 |
+
foot = points[:, ankle]
|
| 323 |
+
displacement = np.linalg.norm(foot-baseline, axis=1)
|
| 324 |
+
lifted = (baseline[1]-foot[:, 1]) > .018*height
|
| 325 |
+
stride_ids = np.flatnonzero((displacement[start:a+1] > .025*height)
|
| 326 |
+
& np.isfinite(foot[start:a+1]).all(axis=1)) + start
|
| 327 |
+
if len(stride_ids):
|
| 328 |
+
stride = int(stride_ids[0])
|
| 329 |
+
if stride > start:
|
| 330 |
+
add("stride", stride, "lead_ankle_departure_v1",
|
| 331 |
+
"Estimated departure from the preparation foot position.", (ankle, back_ankle))
|
| 332 |
+
# The visible ground reference is the preparation foot's toe/heel
|
| 333 |
+
# level. Touchdown and subsequent settled ankle remain estimates
|
| 334 |
+
# and do not measure ground force or full body weight.
|
| 335 |
+
extra = np.arange(3*lead, 3*lead+3)
|
| 336 |
+
baseline_feet = feet[baseline_ids][:, extra, 1]
|
| 337 |
+
levels = np.max(np.where(np.isfinite(baseline_feet), baseline_feet, -np.inf), axis=1)
|
| 338 |
+
levels = levels[np.isfinite(levels)]
|
| 339 |
+
foot_level = float(np.median(levels)) if len(levels) else None
|
| 340 |
+
touchdown = None
|
| 341 |
+
limit = min(a, end) # Preserve the requested foot-plant-before-drive convention.
|
| 342 |
+
airborne = np.flatnonzero(lifted[stride:limit+1]) + stride
|
| 343 |
+
if foot_level is not None and len(airborne):
|
| 344 |
+
last_air = int(airborne[-1])
|
| 345 |
+
for i in range(last_air+1, limit+1):
|
| 346 |
+
y = feet[i, extra, 1]
|
| 347 |
+
if np.isfinite(raw_feet[i, extra]).all() and np.max(y) >= foot_level-.012*height:
|
| 348 |
+
touchdown = i
|
| 349 |
+
add("foot_contact", i, "lead_foot_ground_return_v1",
|
| 350 |
+
"Estimated first toe/heel return to the preparation ground level.", (ankle,))
|
| 351 |
+
break
|
| 352 |
+
planted = None
|
| 353 |
+
for i in range(touchdown if touchdown is not None else stride+1, limit-minimum+2):
|
| 354 |
+
segment = foot[i:i+minimum]
|
| 355 |
+
if not np.isfinite(segment).all(): continue
|
| 356 |
+
settled = np.max(np.linalg.norm(segment-segment[0], axis=1)) <= .012*height
|
| 357 |
+
ground_near = abs(segment[0, 1]-baseline[1]) <= .025*height
|
| 358 |
+
advanced = displacement[i] > .025*height
|
| 359 |
+
if settled and ground_near and advanced:
|
| 360 |
+
planted = i
|
| 361 |
+
add("foot_plant", i, "settled_lead_ankle_ground_proxy_v1",
|
| 362 |
+
"Estimated settled foot near ground; full body-weight loading is unobservable.",
|
| 363 |
+
(ankle, back_ankle))
|
| 364 |
+
break
|
| 365 |
+
if planted is None:
|
| 366 |
+
missing["foot_plant"] = "No settled, grounded lead foot before the forward drive."
|
| 367 |
+
if touchdown is None:
|
| 368 |
+
missing["foot_contact"] = "No clear lift and toe/heel touchdown; settled foot is not first contact."
|
| 369 |
+
else:
|
| 370 |
+
missing["stride"] = "No lead-foot displacement before the forward drive."
|
| 371 |
+
else:
|
| 372 |
+
missing["stride"] = missing["foot_contact"] = missing["foot_plant"] = "Preparation foot reference is unavailable."
|
| 373 |
+
else:
|
| 374 |
+
for key in ("stride", "foot_contact", "foot_plant"):
|
| 375 |
+
missing[key] = "Handedness is required to identify the lead foot."
|
| 376 |
+
for s, e in runs(quiet[max(b, start):end+1]):
|
| 377 |
+
if e-s >= minimum and max(b, start)+s+minimum-1 < end:
|
| 378 |
+
add("finish", max(b, start)+s, "post_drive_quiet_hands_v1",
|
| 379 |
+
"Estimated post-swing settling; the last clip frame is not used as finish.")
|
| 380 |
+
break
|
| 381 |
+
prior = start
|
| 382 |
+
for key in EVENT_ORDER:
|
| 383 |
+
if key not in events: continue
|
| 384 |
+
if events[key]["frame"] < prior:
|
| 385 |
+
events.pop(key); missing[key] = "Candidate conflicts with the required event order."
|
| 386 |
+
else: prior = events[key]["frame"]
|
| 387 |
+
return events, missing
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def rep_metrics(track, points, options, height, height_method, direction, events, start, end, capture):
|
| 391 |
+
values, notes = {}, {}
|
| 392 |
+
fixed = options.camera_stability == "fixed_verified"
|
| 393 |
+
lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None
|
| 394 |
+
scale_note = f"2D estimate; scale: {height_method}."
|
| 395 |
+
if not capture["ok"]:
|
| 396 |
+
reason = "Capture failed: " + ", ".join(capture["reasons"])
|
| 397 |
+
elif options.view != "face_on": reason = "A declared face-on recording is required."
|
| 398 |
+
elif not fixed: reason = "Fixed-camera evidence is required."
|
| 399 |
+
elif height is None: reason = "Body-height scale is unavailable."
|
| 400 |
+
else: reason = None
|
| 401 |
+
def frame(name): return events[name]["frame"] if name in events else None
|
| 402 |
+
plant, contact, stance, load, onset = map(frame, ("foot_plant", "contact", "stance_set", "load_start", "swing_start"))
|
| 403 |
+
if reason is None and lead is not None:
|
| 404 |
+
ankle, back = 15+lead, 16-lead
|
| 405 |
+
if plant is not None and np.isfinite(points[plant, [ankle, back]]).all():
|
| 406 |
+
values["stride_pct_height"] = abs(points[plant, ankle, 0]-points[plant, back, 0]) / height*100
|
| 407 |
+
notes["stride_pct_height"] = scale_note + " Horizontal ankle span at settled-foot proxy; full body-weight loading unmeasured."
|
| 408 |
+
if contact is not None and direction is not None and np.isfinite(points[contact, [11, 12, ankle]]).all():
|
| 409 |
+
hip_x = (points[contact, 11, 0]+points[contact, 12, 0])/2
|
| 410 |
+
values["com_drift_pct_height"] = direction*(hip_x-points[contact, ankle, 0]) / height*100
|
| 411 |
+
notes["com_drift_pct_height"] = scale_note + " Hip midpoint relative to front ankle; negative means behind; not whole-body center of mass."
|
| 412 |
+
if contact is not None:
|
| 413 |
+
hip, knee = (11, 13) if lead == 0 else (12, 14)
|
| 414 |
+
values["lead_knee_angle_contact_deg"] = included_angle(points[contact, hip], points[contact, knee], points[contact, ankle])
|
| 415 |
+
notes["lead_knee_angle_contact_deg"] = "Reference only: projected interior knee angle at estimated contact; face-on projection does not measure anatomical flexion."
|
| 416 |
+
fps = track["video"]["capture_fps"]
|
| 417 |
+
timing_reason = ("Real capture timing is unknown or variable." if fps is None else
|
| 418 |
+
"Timing measurements require real capture FPS >= 60." if fps < 60-1e-6 else None)
|
| 419 |
+
real_times = np.asarray(track["frames"]["t_s"], float)
|
| 420 |
+
if timing_reason is None and reason is None:
|
| 421 |
+
if plant is not None and contact is not None:
|
| 422 |
+
values["foot_plant_to_contact_ms"] = (real_times[contact]-real_times[plant])*1000
|
| 423 |
+
notes["foot_plant_to_contact_ms"] = "Settled-foot to lead-arm-extension proxy; full loading and ball contact unconfirmed; event error uncalibrated."
|
| 424 |
+
if load is not None and onset is not None:
|
| 425 |
+
duration = real_times[onset]-real_times[load]
|
| 426 |
+
values["load_tempo_s"] = duration
|
| 427 |
+
notes["load_tempo_s"] = "Estimated backward-hand load start to forward-hand onset."
|
| 428 |
+
if contact is not None and real_times[contact] > real_times[onset]:
|
| 429 |
+
values["load_launch_ratio"] = duration / (real_times[contact]-real_times[onset])
|
| 430 |
+
notes["load_launch_ratio"] = "Estimated load duration divided by forward onset-to-contact duration."
|
| 431 |
+
if reason is None and stance is not None and contact is not None:
|
| 432 |
+
nose = points[stance:contact+1, 0]
|
| 433 |
+
if len(nose) >= 2 and np.isfinite(nose).all():
|
| 434 |
+
values["head_movement_pct_height"] = np.linalg.norm(np.diff(nose, axis=0), axis=1).sum() / height*100
|
| 435 |
+
notes["head_movement_pct_height"] = scale_note + " Reference-only smoothed nose path from stance to estimated contact; not calibrated for judging."
|
| 436 |
+
missing = {
|
| 437 |
+
"stride_pct_height": "Lead-foot identity, body scale or estimated foot plant is missing.",
|
| 438 |
+
"com_drift_pct_height": "Lead-foot identity, pitcher direction or estimated contact is missing.",
|
| 439 |
+
"foot_plant_to_contact_ms": timing_reason or "Estimated foot plant or contact is missing.",
|
| 440 |
+
"load_tempo_s": timing_reason or "Load start or forward swing onset is missing.",
|
| 441 |
+
"load_launch_ratio": timing_reason or "Load start, forward swing onset or contact is missing.",
|
| 442 |
+
"head_movement_pct_height": "Stance, estimated contact or a contiguous head path is missing.",
|
| 443 |
+
"lead_knee_angle_contact_deg": "Lead-leg identity or estimated contact is missing.",
|
| 444 |
+
"lateral_trunk_tilt_contact_deg": "Unavailable: face-on 2D cannot establish the requested anatomical trunk tilt.",
|
| 445 |
+
"hip_shoulder_separation_foot_plant_deg": "Unavailable: image-plane line angles do not measure axial hip-shoulder twist.",
|
| 446 |
+
}
|
| 447 |
+
output = []
|
| 448 |
+
for key, (unit, low, high) in METRICS.items():
|
| 449 |
+
value = values.get(key)
|
| 450 |
+
note = notes.get(key, reason or missing[key])
|
| 451 |
+
if value is not None:
|
| 452 |
+
if not math.isfinite(float(value)) or not low <= value <= high:
|
| 453 |
+
value = None; note = "Withheld: computed value is outside the supplied plausible bounds."
|
| 454 |
+
else: value = round(float(value), 3)
|
| 455 |
+
output.append({"key": key, "value": value, "unit": unit, "confidence": "est", "note": note})
|
| 456 |
+
return output
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def analyze_batting(track, options):
|
| 460 |
+
raw = point_array(track["frames"]["kp"], 17)
|
| 461 |
+
points = analysis_points(raw)
|
| 462 |
+
height, height_method = stature(points, options)
|
| 463 |
+
if height is not None and height > 2*math.hypot(track["video"]["width"], track["video"]["height"]):
|
| 464 |
+
height, height_method = None, "body-height scale exceeds the image geometry"
|
| 465 |
+
direction = direction_from_stance(points, options, height)
|
| 466 |
+
motion = hand_motion(points, height, direction)
|
| 467 |
+
_, dt = motion_clock(track["frames"])
|
| 468 |
+
n = len(raw)
|
| 469 |
+
declared = [(r.start_frame, r.end_frame) for r in options.reps]
|
| 470 |
+
if options.single_swing: declared = [(0, n-1)]
|
| 471 |
+
if declared:
|
| 472 |
+
ranges = declared
|
| 473 |
+
boundary_method = "caller_declared_single_swing" if options.single_swing else "caller_supplied"
|
| 474 |
+
elif height is not None:
|
| 475 |
+
bursts = candidate_bursts(motion[1], motion[2], motion[3], motion[4], dt, direction)
|
| 476 |
+
ranges = automatic_ranges(bursts, motion, dt, direction, n)
|
| 477 |
+
boundary_method = "automatic_2d_hand_motion_candidate"
|
| 478 |
+
else:
|
| 479 |
+
ranges = []; boundary_method = "automatic_2d_hand_motion_candidate"
|
| 480 |
+
limit_warning = []
|
| 481 |
+
if len(ranges) > 100:
|
| 482 |
+
ranges = ranges[:100]
|
| 483 |
+
limit_warning.append("Only the first 100 swing candidates were analyzed; submit shorter clips.")
|
| 484 |
+
pose_reps, measurement_reps, selected = [], [], []
|
| 485 |
+
for rep, (start, end) in enumerate(ranges, 1):
|
| 486 |
+
if end >= n: raise ValueError("A rep range exceeds the decoded frame count")
|
| 487 |
+
selected.extend(range(start, end+1))
|
| 488 |
+
capture, _ = capture_checks(track, options, height, range(start, end+1))
|
| 489 |
+
events, missing = infer_events(track, points, options, height, direction, motion, start, end)
|
| 490 |
+
pose_reps.append({"rep": rep, "start_frame": start, "end_frame": end, "events": events,
|
| 491 |
+
"missing_events": missing, "boundary_method": boundary_method})
|
| 492 |
+
real_start = track["frames"]["t_s"][start]
|
| 493 |
+
events_ms = ({key: round((event["t_s"]-real_start)*1000, 3)
|
| 494 |
+
for key, event in events.items() if "t_s" in event} if real_start is not None else {})
|
| 495 |
+
measurement_reps.append({"rep": rep, "events_ms": events_ms,
|
| 496 |
+
"metrics": rep_metrics(track, points, options, height, height_method, direction,
|
| 497 |
+
events, start, end, capture),
|
| 498 |
+
"quality": {"pose_conf": float(np.mean(track["frames"]["conf"][start:end+1])),
|
| 499 |
+
"blur": float(np.mean(track["frames"]["blur"][start:end+1]))}})
|
| 500 |
+
capture, diagnostics = capture_checks(track, options, height, selected)
|
| 501 |
+
warnings = ["All event detections and non-null swing measurements are unvalidated 2D estimates.",
|
| 502 |
+
"Foot plant is a settled-foot proxy; full body-weight loading is not measured.",
|
| 503 |
+
"Contact is a lead-arm extension estimate; no bat-ball collision is confirmed."] + diagnostics + limit_warning
|
| 504 |
+
if not ranges: warnings.append("No separable swing candidates found; no rep or measurements fabricated.")
|
| 505 |
+
return pose_reps, measurement_reps, capture, warnings, {
|
| 506 |
+
"version": VERSION, "body_height_px": height, "body_height_method": height_method,
|
| 507 |
+
"pitcher_direction": "image_right" if direction == 1 else "image_left" if direction == -1 else None,
|
| 508 |
+
"processing": ["interior_gap_fill_max_3_frames", "contiguous_3_frame_median", "raw_pose_track_unchanged"],
|
| 509 |
+
"validation": "reference_validation_pending"}
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def coach_payload(measurements):
|
| 513 |
+
"""Only the fields requested by the coach API; no pose, IDs, faults or advice."""
|
| 514 |
+
payload = {"schema_version": "2.0", "discipline": "hitting",
|
| 515 |
+
"capture": measurements["capture"], "reps": measurements["reps"]}
|
| 516 |
+
for key in ("level", "fps"):
|
| 517 |
+
if measurements.get(key) is not None: payload[key] = measurements[key]
|
| 518 |
+
if measurements.get("view") == "face_on": payload["view"] = "face_on"
|
| 519 |
+
return payload
|
baseball_batting/body2d.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .detection import ort_session, verify_cuda_nodes
|
| 4 |
+
|
| 5 |
+
class RTMWPose:
|
| 6 |
+
def __init__(self, path, device="cpu"):
|
| 7 |
+
if not Path(path).is_file() or Path(path).suffix != ".onnx":
|
| 8 |
+
raise ValueError("Explicit local .onnx pose artifact required")
|
| 9 |
+
self.session = ort_session(path, device)
|
| 10 |
+
self.device, self.cuda_verified = device, False
|
| 11 |
+
shape = self.session.get_inputs()[0].shape
|
| 12 |
+
if shape[1:] != [3, 384, 288]:
|
| 13 |
+
raise ValueError(f"Unexpected RTMW input {shape}")
|
| 14 |
+
# Reuse the pinned RTMLib transforms/decoder with our scored/profilable session.
|
| 15 |
+
from rtmlib.tools.pose_estimation.pre_processings import bbox_xyxy2cs, top_down_affine
|
| 16 |
+
from rtmlib.tools.pose_estimation.post_processings import get_simcc_maximum
|
| 17 |
+
self.bbox_transform, self.affine, self.decode = bbox_xyxy2cs, top_down_affine, get_simcc_maximum
|
| 18 |
+
|
| 19 |
+
def __call__(self, image, box):
|
| 20 |
+
center, scale = self.bbox_transform(np.asarray(box), padding=1.25)
|
| 21 |
+
crop, scale = self.affine((288,384), scale, center, image)
|
| 22 |
+
normalized = (crop-np.array([123.675,116.28,103.53]))/np.array([58.395,57.12,57.375])
|
| 23 |
+
tensor = np.ascontiguousarray(normalized.transpose(2,0,1)[None],dtype=np.float32)
|
| 24 |
+
x, y = self.session.run(None,{self.session.get_inputs()[0].name:tensor})
|
| 25 |
+
locations, scores = self.decode(x,y)
|
| 26 |
+
points = locations / 2 / np.array([288,384]) * scale + center - scale/2
|
| 27 |
+
points, scores = points[0], scores[0]
|
| 28 |
+
if self.device == "cuda" and not self.cuda_verified:
|
| 29 |
+
verify_cuda_nodes(self.session)
|
| 30 |
+
self.cuda_verified = True
|
| 31 |
+
if points.shape != (133, 2) or scores.shape != (133,):
|
| 32 |
+
raise ValueError("RTMW must preserve 133-point native topology")
|
| 33 |
+
return points, scores
|
baseball_batting/body3d.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional framewise SAM initializer with an exact loaded MHR adapter export."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import contextlib
|
| 4 |
+
import io
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import numpy as np
|
| 8 |
+
from .ingest import iter_frames
|
| 9 |
+
from .storage import atomic_json, read_json, StageCache, digest, sha256_file
|
| 10 |
+
from .observations import collect_observations
|
| 11 |
+
|
| 12 |
+
def native_mhr_positions_to_sam_camera(points):
|
| 13 |
+
"""Only for *native* centimetre MHR positions, never already-converted SAM exports."""
|
| 14 |
+
return np.asarray(points, dtype=float) / 100 * np.array([1., -1., -1.])
|
| 15 |
+
|
| 16 |
+
def translate_sam_positions(points, translation):
|
| 17 |
+
return np.asarray(points, dtype=float) + np.asarray(translation, dtype=float)
|
| 18 |
+
|
| 19 |
+
def run_initializer(request, capture, config, observation_cache):
|
| 20 |
+
root = Path(request["root"])
|
| 21 |
+
status_path = root / "body3d_status.json"
|
| 22 |
+
status = {"status": "unavailable", "reason": "initializer_not_run"}
|
| 23 |
+
try:
|
| 24 |
+
if config.device != "cuda":
|
| 25 |
+
raise RuntimeError("sam_requires_cuda_profile")
|
| 26 |
+
import torch
|
| 27 |
+
if not torch.cuda.is_available():
|
| 28 |
+
raise RuntimeError("cuda_unavailable")
|
| 29 |
+
torch.backends.cuda.matmul.allow_tf32=False
|
| 30 |
+
torch.backends.cudnn.allow_tf32=False
|
| 31 |
+
required = [config.sam_repo, config.sam_checkpoint, config.sam_config, config.mhr_path]
|
| 32 |
+
if not all(required) or not all(Path(p).exists() for p in required):
|
| 33 |
+
raise RuntimeError("accessible_pinned_sam_artifacts_not_configured")
|
| 34 |
+
revision = subprocess.run(["git", "-C", config.sam_repo, "rev-parse", "HEAD"],
|
| 35 |
+
capture_output=True, text=True, check=True).stdout.strip()
|
| 36 |
+
if len(revision) != 40:
|
| 37 |
+
raise ValueError("SAM source revision must resolve to a commit")
|
| 38 |
+
sys.path.insert(0, str(Path(config.sam_repo).resolve()))
|
| 39 |
+
import os
|
| 40 |
+
os.environ["MOMENTUM_ENABLED"] = "0" # Use the bundled TorchScript asset.
|
| 41 |
+
from sam_3d_body.utils.config import get_config
|
| 42 |
+
from sam_3d_body.models.meta_arch import SAM3DBody
|
| 43 |
+
from sam_3d_body.utils.checkpoint import load_state_dict
|
| 44 |
+
from sam_3d_body.sam_3d_body_estimator import SAM3DBodyEstimator
|
| 45 |
+
model_cfg = get_config(config.sam_config)
|
| 46 |
+
model_cfg.defrost()
|
| 47 |
+
model_cfg.TRAIN.USE_FP16 = False
|
| 48 |
+
model_cfg.MODEL.MHR_HEAD.MHR_MODEL_PATH = str(Path(config.mhr_path).resolve())
|
| 49 |
+
model_cfg.freeze()
|
| 50 |
+
effective_config = model_cfg.dump()
|
| 51 |
+
model = SAM3DBody(model_cfg)
|
| 52 |
+
checkpoint = torch.load(config.sam_checkpoint, map_location="cpu", weights_only=False)
|
| 53 |
+
load_state_dict(model, checkpoint.get("state_dict", checkpoint), strict=False)
|
| 54 |
+
del checkpoint
|
| 55 |
+
model = model.to("cuda").eval()
|
| 56 |
+
if getattr(model, "backbone_dtype", torch.float32) != torch.float32:
|
| 57 |
+
raise ValueError("FP32 backbone initialization check failed")
|
| 58 |
+
float_dtypes = {str(p.dtype) for p in model.parameters() if p.is_floating_point()}
|
| 59 |
+
if float_dtypes != {"torch.float32"}:
|
| 60 |
+
raise ValueError(f"Unexpected model parameter dtypes: {float_dtypes}")
|
| 61 |
+
estimator = SAM3DBodyEstimator(model, model_cfg, human_detector=None,
|
| 62 |
+
human_segmentor=None, fov_estimator=None)
|
| 63 |
+
count = (capture["frame_count"]+config.chunk_size-1)//config.chunk_size
|
| 64 |
+
observations = collect_observations(observation_cache, count)
|
| 65 |
+
cache = StageCache(root, "body3d", digest({"upstream": observation_cache.key,
|
| 66 |
+
"sam_revision": revision, "assets": request["model_hashes"],
|
| 67 |
+
"effective_config": effective_config, "environment": request["environment"],
|
| 68 |
+
"calibration":capture["metadata"].get("calibration",{})}))
|
| 69 |
+
calibration = capture["metadata"].get("calibration", {})
|
| 70 |
+
intrinsics = calibration.get("intrinsics_oriented_pixels")
|
| 71 |
+
if intrinsics is not None:
|
| 72 |
+
intrinsics = np.array(intrinsics, dtype=float)
|
| 73 |
+
if intrinsics.shape != (3, 3) or not np.isfinite(intrinsics).all():
|
| 74 |
+
raise ValueError("Camera intrinsics must be a finite 3x3 matrix in oriented pixels")
|
| 75 |
+
completed = 0
|
| 76 |
+
adapter_record = None
|
| 77 |
+
intrinsics_used = intrinsics
|
| 78 |
+
camera_record=cache.root/"camera_intrinsics.json"
|
| 79 |
+
if camera_record.exists():intrinsics_used=np.array(read_json(camera_record)["intrinsics_used"])
|
| 80 |
+
for frame_id, _, _, image in iter_frames(request["video"], capture["rotation_degrees"]):
|
| 81 |
+
name = f"frame_{frame_id:06d}"
|
| 82 |
+
if cache.valid(name):
|
| 83 |
+
completed += 1
|
| 84 |
+
continue
|
| 85 |
+
person = observations["frames"][frame_id]["person"]
|
| 86 |
+
if not person:
|
| 87 |
+
continue
|
| 88 |
+
kwargs = {"bboxes": np.asarray(person["box"], np.float32).reshape(1, 4),
|
| 89 |
+
"inference_type": "full"}
|
| 90 |
+
if intrinsics is not None:
|
| 91 |
+
# Current estimator internally calls tensor.to(); not a numpy argument.
|
| 92 |
+
kwargs["cam_int"] = torch.tensor(intrinsics, dtype=torch.float32).unsqueeze(0)
|
| 93 |
+
# Published estimator prints per-frame diagnostics; do not retain that text.
|
| 94 |
+
with contextlib.redirect_stdout(io.StringIO()):
|
| 95 |
+
predictions = estimator.process_one_image(image[..., ::-1].copy(), **kwargs)
|
| 96 |
+
if len(predictions) != 1:
|
| 97 |
+
continue
|
| 98 |
+
pred = predictions[0]
|
| 99 |
+
if intrinsics_used is None:
|
| 100 |
+
focal = float(np.asarray(pred["focal_length"]).reshape(-1)[0])
|
| 101 |
+
h, w = image.shape[:2]
|
| 102 |
+
intrinsics_used = np.array([[focal, 0, w/2], [0, focal, h/2], [0, 0, 1.]])
|
| 103 |
+
atomic_json(camera_record,{"intrinsics_used":intrinsics_used.tolist(),"source":"calibration" if intrinsics is not None else "published_default_focal_and_image_centre"})
|
| 104 |
+
if adapter_record is None:
|
| 105 |
+
from .temporal3d import export_mhr_adapter
|
| 106 |
+
adapter_record = export_mhr_adapter(model, cache.root / "mhr_adapter.npz", pred, config.mhr_path)
|
| 107 |
+
atomic_json(cache.root / "mhr_adapter.json", adapter_record)
|
| 108 |
+
arrays = {k: np.asarray(pred[k]) for k in ("pred_keypoints_3d", "pred_keypoints_2d", "pred_cam_t",
|
| 109 |
+
"mhr_model_params", "shape_params", "scale_params", "global_rot", "pred_joint_coords",
|
| 110 |
+
"pred_global_rots")}
|
| 111 |
+
if not all(np.isfinite(a).all() for a in arrays.values()):
|
| 112 |
+
raise ValueError("Nonfinite SAM initializer output")
|
| 113 |
+
arrays["camera_keypoints_m"] = translate_sam_positions(arrays["pred_keypoints_3d"], arrays["pred_cam_t"])
|
| 114 |
+
from .geometry import project
|
| 115 |
+
projected=project(arrays["camera_keypoints_m"],intrinsics_used)
|
| 116 |
+
projection_error=float(np.nanmax(np.linalg.norm(projected-arrays["pred_keypoints_2d"],axis=-1)))
|
| 117 |
+
if not np.isfinite(projection_error) or projection_error>1.:
|
| 118 |
+
raise ValueError("SAM projection/translation convention check failed")
|
| 119 |
+
p = cache.root / f"{name}.npz"
|
| 120 |
+
tmp = cache.root / f"{name}.tmp.npz"
|
| 121 |
+
np.savez_compressed(tmp, **arrays)
|
| 122 |
+
tmp.replace(p)
|
| 123 |
+
cache.commit(name, [p, camera_record, cache.root/"mhr_adapter.npz",cache.root/"mhr_adapter.json"], frame_id=frame_id, representation="sam_camera_axes_metres",
|
| 124 |
+
camera_translation_applied_to="camera_keypoints_m_only",
|
| 125 |
+
array_conventions={"pred_keypoints_3d": "SAM flipped axes, metres, before camera translation",
|
| 126 |
+
"pred_joint_coords": "SAM flipped axes, metres, before camera translation",
|
| 127 |
+
"camera_keypoints_m": "SAM flipped axes, metres, camera translation once",
|
| 128 |
+
"pred_global_rots": "native MHR rotation basis; not transformed to camera/anatomy",
|
| 129 |
+
"mhr_model_params": "native rig parameter vector; not anatomical angles"})
|
| 130 |
+
completed += 1
|
| 131 |
+
status = {"status": "complete" if completed == capture["frame_count"] else "partial",
|
| 132 |
+
"frames_initialized": completed, "frame_count": capture["frame_count"],
|
| 133 |
+
"source_revision": revision, "precision": "fp32",
|
| 134 |
+
"configuration_sha256": digest(effective_config), "cache_key": cache.key,
|
| 135 |
+
"intrinsics_used": intrinsics_used.tolist() if intrinsics_used is not None else None,
|
| 136 |
+
"adapter": adapter_record or (read_json(cache.root / "mhr_adapter.json") if (cache.root / "mhr_adapter.json").exists() else None),
|
| 137 |
+
"geometry_source": "calibrated_intrinsics" if intrinsics is not None else "assumed_camera",
|
| 138 |
+
"validation": "reference-validation-pending",
|
| 139 |
+
"capability": "framewise_initializer; native regressor exported for separate temporal fitting"}
|
| 140 |
+
except Exception as e:
|
| 141 |
+
status = {"status": "unavailable", "reason": str(e)[:300], "error_type": type(e).__name__}
|
| 142 |
+
atomic_json(status_path, status)
|
| 143 |
+
return status
|
baseball_batting/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from .config import EngineConfig
|
| 5 |
+
from .storage import atomic_json
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
parser = argparse.ArgumentParser(description="Batting analysis engine; experimental measurements stay labelled")
|
| 9 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 10 |
+
analyze = commands.add_parser("analyze")
|
| 11 |
+
analyze.add_argument("video")
|
| 12 |
+
analyze.add_argument("--output", required=True)
|
| 13 |
+
analyze.add_argument("--config")
|
| 14 |
+
analyze.add_argument("--metadata")
|
| 15 |
+
preflight = commands.add_parser("preflight")
|
| 16 |
+
preflight.add_argument("--config")
|
| 17 |
+
preflight.add_argument("--output", required=True)
|
| 18 |
+
preflight.add_argument("--require-vision", action="store_true",
|
| 19 |
+
help="Exit with an error unless real pose/detector inference passed")
|
| 20 |
+
fetch = commands.add_parser("fetch")
|
| 21 |
+
fetch.add_argument("resource", choices=["body_pose", "person_detector", "object_detector"])
|
| 22 |
+
fetch.add_argument("--registry", default="configs/resources.yaml")
|
| 23 |
+
fetch.add_argument("--output", default="downloads")
|
| 24 |
+
export = commands.add_parser("export")
|
| 25 |
+
export.add_argument("directory")
|
| 26 |
+
export.add_argument("destination")
|
| 27 |
+
optional=commands.add_parser("preflight-optional");optional.add_argument("--config");optional.add_argument("--output",required=True)
|
| 28 |
+
dataset=commands.add_parser("dataset");dataset.add_argument("index");dataset.add_argument("--output",required=True)
|
| 29 |
+
dataset.add_argument("--kind",choices=["endpoint_cnn","mstcn_events"],required=True)
|
| 30 |
+
train=commands.add_parser("train");train.add_argument("dataset");train.add_argument("--output",required=True)
|
| 31 |
+
train.add_argument("--kind",choices=["endpoint_cnn","mstcn_events"],required=True);train.add_argument("--epochs",type=int,default=30)
|
| 32 |
+
train.add_argument("--device",choices=["cpu","cuda"],default="cpu");train.add_argument("--mstcn-repo")
|
| 33 |
+
evaluate=commands.add_parser("evaluate-checkpoint");evaluate.add_argument("dataset");evaluate.add_argument("checkpoint_directory")
|
| 34 |
+
evaluate.add_argument("--thresholds",required=True);evaluate.add_argument("--scope",required=True);evaluate.add_argument("--mstcn-repo")
|
| 35 |
+
reference=commands.add_parser("evaluate-reference");reference.add_argument("pairs");reference.add_argument("--gates",required=True);reference.add_argument("--output",required=True)
|
| 36 |
+
args = parser.parse_args()
|
| 37 |
+
if args.command == "fetch":
|
| 38 |
+
from .resources import fetch_artifact
|
| 39 |
+
record = fetch_artifact(args.resource, args.registry, args.output)
|
| 40 |
+
print(json.dumps({"artifact_path": record["artifact_path"], "sha256": record["sha256"]}))
|
| 41 |
+
elif args.command == "export":
|
| 42 |
+
from .storage import export_archive
|
| 43 |
+
print(export_archive(args.directory, args.destination))
|
| 44 |
+
elif args.command=="dataset":
|
| 45 |
+
from .dataset import make_dataset
|
| 46 |
+
record=make_dataset(args.index,args.output,args.kind);print(json.dumps({"samples":len(record["samples"]),"output":args.output}))
|
| 47 |
+
elif args.command=="train":
|
| 48 |
+
from .training import train
|
| 49 |
+
print(json.dumps(train(args.dataset,args.output,args.kind,args.epochs,device=args.device,mstcn_repo=args.mstcn_repo)))
|
| 50 |
+
elif args.command=="evaluate-checkpoint":
|
| 51 |
+
from .training import evaluate
|
| 52 |
+
print(json.dumps(evaluate(args.dataset,args.checkpoint_directory,args.thresholds,args.scope,args.mstcn_repo)))
|
| 53 |
+
elif args.command=="evaluate-reference":
|
| 54 |
+
from .validation import evaluate_reference
|
| 55 |
+
print(json.dumps(evaluate_reference(args.pairs,args.gates,args.output)))
|
| 56 |
+
else:
|
| 57 |
+
config = EngineConfig.load(args.config) if args.config else EngineConfig()
|
| 58 |
+
if args.command=="preflight-optional":
|
| 59 |
+
from .optional_preflight import run
|
| 60 |
+
print(json.dumps(run(config,args.output)["tests"],indent=2))
|
| 61 |
+
elif args.command == "preflight":
|
| 62 |
+
from .preflight import run_preflight
|
| 63 |
+
profile = run_preflight(config, args.output)
|
| 64 |
+
print(json.dumps(profile["tests"], indent=2))
|
| 65 |
+
if args.require_vision and not profile["vision_ready"]:
|
| 66 |
+
parser.exit(2, "Vision preflight failed. See runtime_profile.json. For CPU use cpu_reference; "
|
| 67 |
+
"for GPU select a Colab GPU and install the CUDA/cuDNN runtime libraries.\n")
|
| 68 |
+
else:
|
| 69 |
+
from .pipeline import run_engine
|
| 70 |
+
metadata = json.loads(Path(args.metadata).read_text()) if args.metadata else {}
|
| 71 |
+
result = run_engine(args.video, args.output, config, metadata)
|
| 72 |
+
print(json.dumps({"status": result["status"], "frames": result["capture"]["frame_count"],
|
| 73 |
+
"available_metrics": sum(m["value"] is not None for m in result["metrics"]),
|
| 74 |
+
"diagnostics": result["diagnostics"],
|
| 75 |
+
"report": str(Path(args.output)/"report.html")}))
|
| 76 |
+
if result["status"] == "failed":
|
| 77 |
+
parser.exit(2, "Analysis failed: vision initialization/inference produced no usable observations.\n")
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
main()
|
baseball_batting/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import asdict, dataclass, field, fields
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
CONFIG_ROOT = Path(__file__).resolve().parents[1] / "configs"
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class EngineConfig:
|
| 10 |
+
mode: str = "automatic"
|
| 11 |
+
chunk_size: int = 64
|
| 12 |
+
device: str = "cpu"
|
| 13 |
+
score_threshold: float = 0.35
|
| 14 |
+
detector_threshold: float = 0.3
|
| 15 |
+
body_pose_path: str | None = None
|
| 16 |
+
person_detector_path: str | None = None
|
| 17 |
+
object_detector_path: str | None = None
|
| 18 |
+
annotations_path: str | None = None
|
| 19 |
+
body3d_enabled: bool = False
|
| 20 |
+
sam_repo: str | None = None
|
| 21 |
+
sam_checkpoint: str | None = None
|
| 22 |
+
sam_config: str | None = None
|
| 23 |
+
mhr_path: str | None = None
|
| 24 |
+
temporal3d_enabled: bool = True
|
| 25 |
+
anatomy_enabled: bool = True
|
| 26 |
+
fitting_config_path: str = str(CONFIG_ROOT / "fitting.yaml")
|
| 27 |
+
anatomical_config_path: str = str(CONFIG_ROOT / "anatomical_model.yaml")
|
| 28 |
+
mhr_limits_path: str | None = None
|
| 29 |
+
endpoint_checkpoint_path: str | None = None
|
| 30 |
+
endpoint_manifest_path: str | None = None
|
| 31 |
+
event_checkpoint_path: str | None = None
|
| 32 |
+
event_manifest_path: str | None = None
|
| 33 |
+
mstcn_repo: str | None = None
|
| 34 |
+
coaching_rules_path: str = str(CONFIG_ROOT.parent / "rules/coaching_rules.yaml")
|
| 35 |
+
coaching_mode: str = "evidence_linked_experimental"
|
| 36 |
+
quality_config_path: str = str(CONFIG_ROOT / "quality.yaml")
|
| 37 |
+
stage_python: dict[str, str] = field(default_factory=dict)
|
| 38 |
+
learned_events_enabled: bool = False
|
| 39 |
+
bat_3d_mode: str = "disabled"
|
| 40 |
+
export_video: bool = True
|
| 41 |
+
event_parameters: dict = field(default_factory=lambda: {
|
| 42 |
+
"version": "2.0", "ground_tolerance_px":5.0, "interaction_distance_px":8.0, "outgoing_direction_cosine_max":.5, "motion_threshold_px_per_frame": 3.0,
|
| 43 |
+
"sustained_frames": 3, "min_visible_frames": 4,
|
| 44 |
+
})
|
| 45 |
+
|
| 46 |
+
def validate(self):
|
| 47 |
+
if self.mode not in {"automatic", "operator_reviewed", "dataset"}:
|
| 48 |
+
raise ValueError("Unknown execution mode")
|
| 49 |
+
if self.chunk_size < 1 or self.device not in {"cpu", "cuda"}:
|
| 50 |
+
raise ValueError("Invalid chunk size or device")
|
| 51 |
+
if not 0 <= self.score_threshold <= 1 or not 0 <= self.detector_threshold <= 1:
|
| 52 |
+
raise ValueError("Score thresholds must lie in [0, 1]")
|
| 53 |
+
if self.mode == "automatic" and self.annotations_path:
|
| 54 |
+
raise ValueError("Human annotations require operator_reviewed or dataset mode")
|
| 55 |
+
for field_name in ("body3d_enabled", "temporal3d_enabled", "anatomy_enabled", "learned_events_enabled", "export_video"):
|
| 56 |
+
if not isinstance(getattr(self, field_name), bool):
|
| 57 |
+
raise ValueError(f"{field_name} must be a boolean")
|
| 58 |
+
if not isinstance(self.bat_3d_mode, str) or not self.bat_3d_mode:
|
| 59 |
+
raise ValueError("bat_3d_mode must identify a requested mode or disabled")
|
| 60 |
+
if self.coaching_mode not in {"descriptive_only", "evidence_linked_experimental"}:
|
| 61 |
+
raise ValueError("Unknown coaching mode")
|
| 62 |
+
# Unsupported optional branch requests are reported as unavailable by workers.
|
| 63 |
+
# They never execute unqualified weights and never block eligible 2D results.
|
| 64 |
+
p = self.event_parameters
|
| 65 |
+
if p.get("sustained_frames", 0) < 1 or p.get("min_visible_frames", 0) < 2:
|
| 66 |
+
raise ValueError("Invalid event support parameters")
|
| 67 |
+
if not math.isfinite(p.get("motion_threshold_px_per_frame", float("nan"))):
|
| 68 |
+
raise ValueError("Invalid event motion threshold")
|
| 69 |
+
return self
|
| 70 |
+
|
| 71 |
+
def to_dict(self):
|
| 72 |
+
return asdict(self)
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def load(cls, path: str | Path):
|
| 76 |
+
raw = json.loads(Path(path).read_text())
|
| 77 |
+
unexpected = set(raw) - {f.name for f in fields(cls)}
|
| 78 |
+
if unexpected:
|
| 79 |
+
raise ValueError(f"Unknown configuration keys: {sorted(unexpected)}")
|
| 80 |
+
return cls(**raw).validate()
|
baseball_batting/contracts.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serializable records; provenance, suitability and validation are independent."""
|
| 2 |
+
from dataclasses import asdict, dataclass, field
|
| 3 |
+
from typing import Any
|
| 4 |
+
import math
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
SCHEMA_VERSION = "1.0"
|
| 8 |
+
RTMW_CORE = {
|
| 9 |
+
"nose": 0, "left_shoulder": 5, "right_shoulder": 6,
|
| 10 |
+
"left_elbow": 7, "right_elbow": 8, "left_wrist": 9, "right_wrist": 10,
|
| 11 |
+
"left_hip": 11, "right_hip": 12, "left_knee": 13, "right_knee": 14,
|
| 12 |
+
"left_ankle": 15, "right_ankle": 16, "left_big_toe": 17,
|
| 13 |
+
"left_small_toe": 18, "left_heel": 19, "right_big_toe": 20,
|
| 14 |
+
"right_small_toe": 21, "right_heel": 22,
|
| 15 |
+
}
|
| 16 |
+
STATES = {"image_supported", "model_inferred", "manual", "propagated",
|
| 17 |
+
"interpolated", "occluded", "unknown"}
|
| 18 |
+
|
| 19 |
+
def json_safe(value: Any) -> Any:
|
| 20 |
+
if hasattr(value, "__dataclass_fields__"):
|
| 21 |
+
return json_safe(asdict(value))
|
| 22 |
+
if isinstance(value, dict):
|
| 23 |
+
return {str(k): json_safe(v) for k, v in value.items()}
|
| 24 |
+
if isinstance(value, (list, tuple, np.ndarray)):
|
| 25 |
+
return [json_safe(v) for v in value]
|
| 26 |
+
if isinstance(value, np.generic):
|
| 27 |
+
return json_safe(value.item())
|
| 28 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 29 |
+
return None
|
| 30 |
+
return value
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class FrameTiming:
|
| 34 |
+
frame_id: int
|
| 35 |
+
pts: int | None
|
| 36 |
+
time_base: str | None
|
| 37 |
+
playback_s: float | None
|
| 38 |
+
physical_s: float | None
|
| 39 |
+
width: int
|
| 40 |
+
height: int
|
| 41 |
+
flags: list[str] = field(default_factory=list)
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class Event:
|
| 45 |
+
event_id: str
|
| 46 |
+
type: str
|
| 47 |
+
state: str
|
| 48 |
+
frame_interval: list[int] | None
|
| 49 |
+
evidence_frames: list[int]
|
| 50 |
+
method: str
|
| 51 |
+
review_status: str = "not_reviewed"
|
| 52 |
+
annotator: str | None = None
|
| 53 |
+
playback_interval_s: list[float | None] | None = None
|
| 54 |
+
physical_interval_s: list[float | None] | None = None
|
| 55 |
+
notes: list[str] = field(default_factory=list)
|
| 56 |
+
confidence_interpretation: str = "candidate evidence; no calibrated probability"
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class Metric:
|
| 60 |
+
metric_id: str
|
| 61 |
+
definition_version: str
|
| 62 |
+
value: float | None
|
| 63 |
+
unit: str
|
| 64 |
+
suitability: str
|
| 65 |
+
provenance: list[str]
|
| 66 |
+
evidence_frames: list[int]
|
| 67 |
+
geometry_source: str
|
| 68 |
+
timing_source: str
|
| 69 |
+
unavailable_reason: str | None = None
|
| 70 |
+
event_id: str | None = None
|
| 71 |
+
uncertainty_kind: str = "unknown"
|
| 72 |
+
validation_status: str = "reference-validation-pending"
|
| 73 |
+
validation_scope: str | None = None
|
| 74 |
+
feedback_eligibility: str = "descriptive-only"
|
| 75 |
+
sensitivity: dict | None = None
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class Finding:
|
| 79 |
+
finding_id: str
|
| 80 |
+
supporting_metric_ids: list[str]
|
| 81 |
+
rule_id: str
|
| 82 |
+
rule_version: str
|
| 83 |
+
description: str
|
| 84 |
+
evidence_frames: list[int]
|
| 85 |
+
expert_review: str = "not_reviewed"
|
| 86 |
+
evidence_strength: str = "descriptive observation"
|
| 87 |
+
research_exercise: dict | None = None
|
baseball_batting/dataset.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproducible grouped datasets from exact-video reviewed labels and source frames."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .storage import read_json, atomic_json, sha256_file, digest, StageCache
|
| 5 |
+
from .ingest import ingest, iter_frames
|
| 6 |
+
from .annotations import load_annotations
|
| 7 |
+
from .learning import PHASES, BOUNDARIES, FEATURE_VERSION, features
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def validate_splits(records):
|
| 11 |
+
seen={};sessions={};videos={}
|
| 12 |
+
for record in records:
|
| 13 |
+
player,session,split=record.get("player_id"),record.get("session_id"),record.get("split")
|
| 14 |
+
if not player or not session or split not in {"train","validation","test"}:raise ValueError("Explicit athlete/session and split required")
|
| 15 |
+
if player in seen and seen[player]!=split:raise ValueError("Athlete leakage across splits")
|
| 16 |
+
if session in sessions and sessions[session]!=split:raise ValueError("Session leakage across splits")
|
| 17 |
+
seen[player]=split;sessions[session]=split
|
| 18 |
+
fingerprint=sha256_file(record["video_path"])
|
| 19 |
+
if fingerprint in videos and videos[fingerprint]!=split:raise ValueError("Identical video leakage across splits")
|
| 20 |
+
videos[fingerprint]=split
|
| 21 |
+
if set(seen.values())!={"train","validation","test"}:raise ValueError("Three nonempty grouped partitions required")
|
| 22 |
+
return seen
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def make_dataset(index_path,output,kind):
|
| 26 |
+
import cv2
|
| 27 |
+
records=read_json(index_path);validate_splits(records)
|
| 28 |
+
output=Path(output);output.mkdir(parents=True,exist_ok=True);samples=[]
|
| 29 |
+
for number,record in enumerate(records):
|
| 30 |
+
capture=ingest(record["video_path"],record.get("metadata",{}))
|
| 31 |
+
labels=load_annotations(record["annotations_path"],capture["input_sha256"],capture["frame_count"],capture["frames"][0]["width"],capture["frames"][0]["height"])
|
| 32 |
+
common={"player_id":record["player_id"],"session_id":record["session_id"],"split":record["split"],
|
| 33 |
+
"input_sha256":capture["input_sha256"],"annotations_sha256":sha256_file(record["annotations_path"])}
|
| 34 |
+
if kind=="endpoint_cnn":
|
| 35 |
+
for i,_,_,image in iter_frames(record["video_path"],capture["rotation_degrees"]):
|
| 36 |
+
label=labels.get("frames",{}).get(str(i),{});box=label.get("crop")
|
| 37 |
+
if not box or not any(label.get(k) is not None for k in ("knob","barrel")):continue
|
| 38 |
+
x1,y1,x2,y2=map(int,box);crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy()
|
| 39 |
+
target=np.zeros((2,64,64),np.float32);visible=np.zeros(2,np.float32);visibility_mask=np.zeros(2,np.float32)
|
| 40 |
+
yy,xx=np.mgrid[:64,:64]
|
| 41 |
+
for j,name in enumerate(("knob","barrel")):
|
| 42 |
+
point=label.get(name)
|
| 43 |
+
if point is not None:
|
| 44 |
+
xy=(np.array(point)-[x1,y1])/[x2-x1,y2-y1]*64-.5
|
| 45 |
+
if not np.all((xy>=0)&(xy<64)):raise ValueError("Endpoint label lies outside its training crop")
|
| 46 |
+
target[j]=np.exp(-((xx-xy[0])**2+(yy-xy[1])**2)/(2*1.5**2));visible[j]=1;visibility_mask[j]=1
|
| 47 |
+
elif label.get("bat_occluded") is True:visibility_mask[j]=1
|
| 48 |
+
path=output/f"endpoint_{number:05d}_{i:06d}.npz"
|
| 49 |
+
np.savez_compressed(path,image=crop,heatmaps=target,visible=visible,visibility_mask=visibility_mask)
|
| 50 |
+
samples.append({**common,"path":path.name,"frame_id":i})
|
| 51 |
+
else:
|
| 52 |
+
directory=Path(record["analysis_directory"])
|
| 53 |
+
cache_index=read_json(directory/"observation_index.json")
|
| 54 |
+
cache=StageCache(directory,"observations",cache_index["cache_key"])
|
| 55 |
+
from .observations import collect_observations
|
| 56 |
+
observations=collect_observations(cache,cache_index["chunk_count"])
|
| 57 |
+
if cache_index["input_sha256"]!=capture["input_sha256"]:raise ValueError("Analysis/label video mismatch")
|
| 58 |
+
x=features(observations,capture);n=capture["frame_count"]
|
| 59 |
+
phase=np.full(n,-100,np.int64)
|
| 60 |
+
for interval in labels.get("phases",[]):
|
| 61 |
+
if interval["phase"] not in PHASES:raise ValueError("Unknown reviewed phase")
|
| 62 |
+
a,b=interval["frame_interval"]
|
| 63 |
+
if not 0<=a<=b<n or np.any(phase[a:b+1]!=-100):raise ValueError("Invalid/overlapping reviewed phases")
|
| 64 |
+
phase[a:b+1]=PHASES.index(interval["phase"])
|
| 65 |
+
boundary=np.zeros((len(BOUNDARIES),n),np.float32);mask=np.zeros_like(boundary)
|
| 66 |
+
presence=np.zeros(len(BOUNDARIES),np.float32);presence_mask=np.zeros_like(presence)
|
| 67 |
+
for event in labels.get("events",[]):
|
| 68 |
+
if event["type"] not in BOUNDARIES or event["state"]=="unknown":continue
|
| 69 |
+
j=BOUNDARIES.index(event["type"]);presence_mask[j]=1;mask[j]=1
|
| 70 |
+
if event["state"]=="confirmed":
|
| 71 |
+
a,b=event["frame_interval"];boundary[j,a:b+1]=1;presence[j]=1
|
| 72 |
+
if not np.any(phase!=-100):raise ValueError("Event training requires reviewed phase intervals")
|
| 73 |
+
path=output/f"events_{number:05d}.npz"
|
| 74 |
+
np.savez_compressed(path,features=x,phase=phase,boundary=boundary,boundary_mask=mask,
|
| 75 |
+
presence=presence,presence_mask=presence_mask,frame_ids=np.arange(n))
|
| 76 |
+
samples.append({**common,"path":path.name})
|
| 77 |
+
if not samples:raise ValueError("No eligible reviewed training examples")
|
| 78 |
+
manifest={"schema_version":"1.0","kind":kind,"feature_version":FEATURE_VERSION if kind=="mstcn_events" else None,
|
| 79 |
+
"samples":samples,"index_sha256":sha256_file(index_path),"split_unit":"athlete_and_session",
|
| 80 |
+
"artifact_hashes":{r["path"]:sha256_file(output/r["path"]) for r in samples}}
|
| 81 |
+
atomic_json(output/"dataset.json",manifest);return manifest
|
baseball_batting/detection.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""YOLOX ONNX adapter retaining scores, classes and original image coordinates."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import uuid
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def iou(box, boxes):
|
| 9 |
+
boxes = np.asarray(boxes, dtype=float).reshape(-1, 4)
|
| 10 |
+
if not len(boxes):
|
| 11 |
+
return np.empty(0)
|
| 12 |
+
intersection = np.maximum(0, np.minimum(box[2:], boxes[:, 2:]) - np.maximum(box[:2], boxes[:, :2])).prod(axis=1)
|
| 13 |
+
a = max(0, box[2]-box[0]) * max(0, box[3]-box[1])
|
| 14 |
+
b = np.maximum(0, boxes[:, 2:]-boxes[:, :2]).prod(axis=1)
|
| 15 |
+
return intersection / np.maximum(a+b-intersection, 1e-9)
|
| 16 |
+
|
| 17 |
+
def decode_yolox(raw, size=640, ratio=1.0, threshold=0.3, classes=(0, 32, 34), nms=0.45):
|
| 18 |
+
p = np.asarray(raw, dtype=np.float32).reshape(-1, np.asarray(raw).shape[-1]).copy()
|
| 19 |
+
if p.shape[1] == 5:
|
| 20 |
+
if list(classes) != [0]:
|
| 21 |
+
raise ValueError("NMS-integrated person export cannot supply COCO object classes")
|
| 22 |
+
# The selected HumanArt export contains x1,y1,x2,y2,score after NMS.
|
| 23 |
+
return [{"class_id": 0, "score": float(row[4]), "box": (row[:4]/ratio).tolist()}
|
| 24 |
+
for row in p if np.isfinite(row).all() and row[4] >= threshold]
|
| 25 |
+
expected = sum((size//stride)**2 for stride in (8, 16, 32))
|
| 26 |
+
if p.shape[0] != expected or p.shape[1] not in (6, 85):
|
| 27 |
+
raise ValueError(f"Unsupported raw YOLOX schema: {p.shape}; expected {expected}x6 or x85")
|
| 28 |
+
if p.shape[1] == 6 and list(classes) != [0]:
|
| 29 |
+
raise ValueError("Person-only raw export cannot supply COCO bat or ball classes")
|
| 30 |
+
grids, strides = [], []
|
| 31 |
+
for stride in (8, 16, 32):
|
| 32 |
+
y, x = np.indices((size//stride, size//stride))
|
| 33 |
+
grids.append(np.column_stack((x.ravel(), y.ravel())))
|
| 34 |
+
strides.append(np.full((x.size, 1), stride))
|
| 35 |
+
grid, step = np.concatenate(grids), np.concatenate(strides)
|
| 36 |
+
centers = (p[:, :2] + grid) * step
|
| 37 |
+
wh = np.exp(np.clip(p[:, 2:4], -30, 30)) * step
|
| 38 |
+
boxes = np.concatenate((centers-wh/2, centers+wh/2), axis=1) / ratio
|
| 39 |
+
all_scores = p[:, 4:5] * p[:, 5:]
|
| 40 |
+
result = []
|
| 41 |
+
for cls in classes:
|
| 42 |
+
if cls >= all_scores.shape[1]:
|
| 43 |
+
continue
|
| 44 |
+
scores = all_scores[:, cls]
|
| 45 |
+
order = np.flatnonzero(np.isfinite(scores) & (scores >= threshold))
|
| 46 |
+
order = order[np.argsort(scores[order])[::-1]]
|
| 47 |
+
while len(order):
|
| 48 |
+
k = order[0]
|
| 49 |
+
if np.isfinite(boxes[k]).all():
|
| 50 |
+
result.append({"class_id": int(cls), "score": float(scores[k]), "box": boxes[k].tolist()})
|
| 51 |
+
order = order[1:][iou(boxes[k], boxes[order[1:]]) <= nms]
|
| 52 |
+
return result
|
| 53 |
+
|
| 54 |
+
def ort_session(path, device):
|
| 55 |
+
import onnxruntime as ort
|
| 56 |
+
if not Path(path).is_file() or Path(path).suffix != ".onnx":
|
| 57 |
+
raise ValueError("Explicit local .onnx model required; inference never downloads artifacts")
|
| 58 |
+
if device == "cuda" and "CUDAExecutionProvider" not in ort.get_available_providers():
|
| 59 |
+
raise RuntimeError("CUDA execution provider is unavailable; no silent CPU fallback")
|
| 60 |
+
if device=="cuda" and hasattr(ort,"preload_dlls"):
|
| 61 |
+
ort.preload_dlls()
|
| 62 |
+
providers = [("CUDAExecutionProvider",{"use_tf32":0})] if device == "cuda" else ["CPUExecutionProvider"]
|
| 63 |
+
options = ort.SessionOptions()
|
| 64 |
+
options.intra_op_num_threads = 2
|
| 65 |
+
if device == "cuda":
|
| 66 |
+
options.enable_profiling = True
|
| 67 |
+
options.profile_file_prefix = str(Path(tempfile.gettempdir()) / ("batting-ort-"+uuid.uuid4().hex))
|
| 68 |
+
session = ort.InferenceSession(str(path), sess_options=options, providers=providers)
|
| 69 |
+
if device == "cuda" and session.get_providers()[0] != "CUDAExecutionProvider":
|
| 70 |
+
try:
|
| 71 |
+
Path(session.end_profiling()).unlink(missing_ok=True)
|
| 72 |
+
except Exception:
|
| 73 |
+
pass
|
| 74 |
+
raise RuntimeError(f"Requested CUDA session did not initialize on CUDA (ONNX {ort.__version__}). "
|
| 75 |
+
"Check GPU runtime and CUDA/cuDNN libraries; rerun vision preflight.")
|
| 76 |
+
return session
|
| 77 |
+
|
| 78 |
+
def verify_cuda_nodes(session):
|
| 79 |
+
"""Provider registration alone is not proof that CUDA actually executed an operator."""
|
| 80 |
+
path = Path(session.end_profiling())
|
| 81 |
+
try:
|
| 82 |
+
events = json.loads(path.read_text())
|
| 83 |
+
if not any(e.get("args", {}).get("provider") == "CUDAExecutionProvider" for e in events):
|
| 84 |
+
raise RuntimeError("No CUDA operator execution was observed in ONNX profiling")
|
| 85 |
+
finally:
|
| 86 |
+
path.unlink(missing_ok=True)
|
| 87 |
+
|
| 88 |
+
class YOLOXDetector:
|
| 89 |
+
def __init__(self, path, device="cpu", threshold=0.3, classes=(0, 32, 34)):
|
| 90 |
+
self.session = ort_session(path, device)
|
| 91 |
+
self.providers = self.session.get_providers()
|
| 92 |
+
self.threshold, self.classes = threshold, classes
|
| 93 |
+
self.device, self.cuda_verified = device, False
|
| 94 |
+
shape = self.session.get_inputs()[0].shape
|
| 95 |
+
if shape[1:] != [3, 640, 640]:
|
| 96 |
+
raise ValueError(f"Unexpected detector input {shape}")
|
| 97 |
+
|
| 98 |
+
def __call__(self, image):
|
| 99 |
+
import cv2
|
| 100 |
+
h, w = image.shape[:2]
|
| 101 |
+
ratio = min(640/h, 640/w)
|
| 102 |
+
canvas = np.full((640, 640, 3), 114, np.uint8)
|
| 103 |
+
resized = cv2.resize(image, (int(w*ratio), int(h*ratio)))
|
| 104 |
+
canvas[:resized.shape[0], :resized.shape[1]] = resized
|
| 105 |
+
tensor = canvas.transpose(2, 0, 1)[None].astype(np.float32)
|
| 106 |
+
raw = self.session.run(None, {self.session.get_inputs()[0].name: tensor})[0]
|
| 107 |
+
if self.device == "cuda" and not self.cuda_verified:
|
| 108 |
+
verify_cuda_nodes(self.session)
|
| 109 |
+
self.cuda_verified = True
|
| 110 |
+
return decode_yolox(raw, ratio=ratio, threshold=self.threshold, classes=self.classes)
|
| 111 |
+
|
| 112 |
+
def select_person(detections, previous=None):
|
| 113 |
+
candidates = [d for d in detections if d["class_id"] == 0]
|
| 114 |
+
if not candidates:
|
| 115 |
+
return None
|
| 116 |
+
if previous is not None:
|
| 117 |
+
overlaps = iou(np.array(previous), [d["box"] for d in candidates])
|
| 118 |
+
if max(overlaps) < 0.05:
|
| 119 |
+
return None # Do not silently jump to a different person.
|
| 120 |
+
return candidates[int(np.argmax(overlaps))]
|
| 121 |
+
return max(candidates, key=lambda d: max(0, d["box"][2]-d["box"][0]) * max(0, d["box"][3]-d["box"][1]) * d["score"])
|
baseball_batting/diagnostics.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Separate frame processing from actual observation and measurement coverage."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .contracts import RTMW_CORE
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
SUPPORTED = {"manual", "image_supported", "model_inferred"}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def observation_summary(observations):
|
| 10 |
+
counts = {"body_frames": 0, "body_landmarks": 0, "person_frames": 0,
|
| 11 |
+
"bat_box_frames": 0, "bat_endpoint_frames": 0, "ball_frames": 0}
|
| 12 |
+
frames = observations["frames"]
|
| 13 |
+
for frame in frames:
|
| 14 |
+
points = np.asarray(frame["body_points"], float)
|
| 15 |
+
supported = [j for j in RTMW_CORE.values() if frame["body_states"][j] in SUPPORTED
|
| 16 |
+
and np.isfinite(points[j]).all()]
|
| 17 |
+
counts["body_frames"] += bool(supported)
|
| 18 |
+
counts["body_landmarks"] += len(supported)
|
| 19 |
+
counts["person_frames"] += frame["person"] is not None
|
| 20 |
+
counts["bat_box_frames"] += any(p["class_id"] == 34 for p in frame["proposals"])
|
| 21 |
+
bat = frame["bat"]
|
| 22 |
+
counts["bat_endpoint_frames"] += bool(bat["points"] is not None
|
| 23 |
+
and all(s in SUPPORTED for s in bat["states"])
|
| 24 |
+
and np.isfinite(np.asarray(bat["points"], float)).all())
|
| 25 |
+
ball = frame["ball"]
|
| 26 |
+
counts["ball_frames"] += bool(ball["point"] is not None and ball["state"] in SUPPORTED
|
| 27 |
+
and np.isfinite(np.asarray(ball["point"], float)).all())
|
| 28 |
+
failures = {name: status for name, status in observations["branch_status"].items()
|
| 29 |
+
if status["status"] in {"failed", "failed_preflight"}}
|
| 30 |
+
any_support = any(counts[k] for k in ("body_frames", "bat_endpoint_frames", "ball_frames"))
|
| 31 |
+
state = "complete" if any_support else ("failed" if failures else "empty")
|
| 32 |
+
if state == "failed":
|
| 33 |
+
message = "Analysis failed: vision models could not run and no usable observations were produced."
|
| 34 |
+
elif state == "empty":
|
| 35 |
+
message = "No usable body, bat or ball observations were produced. Check model setup and subject visibility."
|
| 36 |
+
else:
|
| 37 |
+
message = "Observation coverage is available; individual measurements still require their evidence gates."
|
| 38 |
+
return {"status": state, "frame_count": len(frames), **counts,
|
| 39 |
+
"model_failures": failures, "message": message}
|
baseball_batting/events.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conservative candidates. Projected overlap is never converted into contact."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .contracts import Event, RTMW_CORE
|
| 4 |
+
|
| 5 |
+
def sustained(mask, length):
|
| 6 |
+
return [i for i in range(max(0,len(mask)-length+1)) if np.all(mask[i:i+length])]
|
| 7 |
+
|
| 8 |
+
def additional_candidates(curves, observations, capture, parameters):
|
| 9 |
+
"""Observable intervals with explicit context; these never assert contact."""
|
| 10 |
+
output = []
|
| 11 |
+
frames = observations["frames"]; n = len(frames)
|
| 12 |
+
context = capture.get("metadata",{}).get("event_context", {})
|
| 13 |
+
run = parameters["sustained_frames"]
|
| 14 |
+
hands = (curves["left_hand_path_pixels"]+curves["right_hand_path_pixels"])/2
|
| 15 |
+
delta = np.diff(hands,axis=0)
|
| 16 |
+
threshold = parameters["motion_threshold_px_per_frame"]
|
| 17 |
+
fixed = capture["camera_stability"] == "fixed_verified"
|
| 18 |
+
direction = context.get("pitcher_direction_image")
|
| 19 |
+
if fixed and context.get("source") and direction is not None:
|
| 20 |
+
direction = np.asarray(direction,float)
|
| 21 |
+
if direction.shape != (2,) or not np.isfinite(direction).all() or np.linalg.norm(direction)<1e-8:
|
| 22 |
+
raise ValueError("Pitcher image direction must be a documented finite nonzero xy vector")
|
| 23 |
+
along = delta@(direction/np.linalg.norm(direction))
|
| 24 |
+
forward = sustained(np.isfinite(along)&(along>threshold),run)
|
| 25 |
+
load = sustained(np.isfinite(along)&(along<-threshold),run)
|
| 26 |
+
if forward:
|
| 27 |
+
a=forward[0];output.append(Event("forward_candidate","forward_swing_onset","candidate",[a,a+run],list(range(a,a+run+1)),"documented_direction_projected_hand_motion_v2"))
|
| 28 |
+
if load:
|
| 29 |
+
a=load[0];end=next((i for i in forward if i>a),min(a+run,n-1))
|
| 30 |
+
output.append(Event("load_candidate","load","candidate",[a,end],list(range(a,end+1)),"documented_opposing_projected_hand_motion_v2"))
|
| 31 |
+
lead = context.get("lead_side")
|
| 32 |
+
ground = context.get("ground_line_image")
|
| 33 |
+
if fixed and context.get("source") and lead in {"left","right"} and ground is not None:
|
| 34 |
+
line=np.asarray(ground,float)
|
| 35 |
+
if line.shape!=(3,) or not np.isfinite(line).all() or np.linalg.norm(line[:2])<1e-8: raise ValueError("Ground line requires finite ax+by+c=0 coefficients")
|
| 36 |
+
foot=curves["body_pixels"][:,RTMW_CORE[lead+"_big_toe"]]
|
| 37 |
+
height=np.abs(np.c_[foot,np.ones(n)]@line)/np.linalg.norm(line[:2])
|
| 38 |
+
tolerance=parameters.get("ground_tolerance_px",5.)
|
| 39 |
+
lifted=sustained(np.isfinite(height)&(height>2*tolerance),run)
|
| 40 |
+
landed=sustained(np.isfinite(height)&(height<tolerance),run)
|
| 41 |
+
if lifted:
|
| 42 |
+
a=lifted[0];output.append(Event("foot_lift_candidate","lead_foot_lift","candidate",[a,a+run],list(range(a,a+run+1)),"documented_ground_projected_foot_distance_v2"))
|
| 43 |
+
landing=next((i for i in landed if i>a+run),None)
|
| 44 |
+
if landing is not None:
|
| 45 |
+
output.append(Event("foot_contact_candidate","lead_foot_contact","candidate",[landing,landing+run],list(range(landing,landing+run+1)),"projected_ground_return_v2",notes=["Projected ground return alone does not prove physical foot contact"]))
|
| 46 |
+
bat=curves.get("bat_endpoints_pixels")
|
| 47 |
+
if bat is None:
|
| 48 |
+
bat=np.full((n,2,2),np.nan)
|
| 49 |
+
for i,f in enumerate(frames):
|
| 50 |
+
if f["bat"].get("points") is not None and all(s in {"manual","image_supported"} for s in f["bat"]["states"]):bat[i]=f["bat"]["points"]
|
| 51 |
+
ball=np.full((n,2),np.nan)
|
| 52 |
+
for i,f in enumerate(frames):
|
| 53 |
+
if f["ball"].get("point") is not None and f["ball"]["state"] in {"manual","model_inferred","image_supported"}:
|
| 54 |
+
ball[i]=f["ball"]["point"]
|
| 55 |
+
shaft=bat[:,1]-bat[:,0];length2=np.sum(shaft**2,axis=1)
|
| 56 |
+
fraction=np.clip(np.sum((ball-bat[:,0])*shaft,axis=1)/np.where(length2>1e-8,length2,np.nan),0,1)
|
| 57 |
+
distance=np.linalg.norm(ball-(bat[:,0]+fraction[:,None]*shaft),axis=1)
|
| 58 |
+
eligible=np.flatnonzero(np.isfinite(distance)&(fraction>=.5))
|
| 59 |
+
if len(eligible):
|
| 60 |
+
i=int(eligible[np.argmin(distance[eligible])])
|
| 61 |
+
output.append(Event("closest_projected_approach","closest_projected_approach","candidate",[i,i],[i],"measured_projected_ball_shaft_distance_v2",notes=[f"Projected distance {distance[i]:.2f}px; no physical collision established"]))
|
| 62 |
+
radius=parameters.get("interaction_distance_px",8.)
|
| 63 |
+
if distance[i]<=radius and 1<=i<n-3 and np.isfinite(ball[i-1:i+4]).all():
|
| 64 |
+
outgoing=np.diff(ball[i:i+4],axis=0)
|
| 65 |
+
incoming=ball[i]-ball[i-1]
|
| 66 |
+
if np.linalg.norm(incoming)>1 and np.all(np.linalg.norm(outgoing,axis=1)>1):
|
| 67 |
+
cosine=np.dot(incoming,outgoing[0])/(np.linalg.norm(incoming)*np.linalg.norm(outgoing[0]))
|
| 68 |
+
if cosine < parameters.get("outgoing_direction_cosine_max",.5):
|
| 69 |
+
output.append(Event("interaction_candidate","bat_ball_interaction","candidate",[max(i-1,0),i+1],list(range(i-1,i+4)),"projected_approach_and_changed_outgoing_ball_v2",notes=["Requires review; detector association and image projection may mimic interaction"]))
|
| 70 |
+
movement=np.linalg.norm(delta,axis=1)
|
| 71 |
+
high=sustained(np.isfinite(movement)&(movement>threshold),run)
|
| 72 |
+
settled=sustained(np.isfinite(movement)&(movement<threshold*.5),run)
|
| 73 |
+
if fixed and high:
|
| 74 |
+
end=next((i for i in settled if i>high[-1]+run),None)
|
| 75 |
+
if end is not None and end+run<n-1:
|
| 76 |
+
output.append(Event("follow_candidate","follow_through","candidate",[end,end+run],list(range(end,end+run+1)),"visible_post_motion_settling_v2",notes=["Visible settling candidate; not inferred from clip termination"]))
|
| 77 |
+
audio=capture.get("metadata",{}).get("audio",{})
|
| 78 |
+
if audio.get("source") and audio.get("synchronization_verified") is True:
|
| 79 |
+
offset=audio.get("offset_to_video_s");delay=audio.get("propagation_delay_s")
|
| 80 |
+
if isinstance(offset,(int,float)) and isinstance(delay,(int,float)):
|
| 81 |
+
times=np.array([f["playback_s"] for f in capture["frames"]],float)
|
| 82 |
+
for peak in audio.get("reviewed_impulse_times_s",[]):
|
| 83 |
+
time=float(peak)+offset-delay
|
| 84 |
+
for event in output:
|
| 85 |
+
if event.type=="bat_ball_interaction" and event.frame_interval:
|
| 86 |
+
a,b=event.frame_interval
|
| 87 |
+
if times[a]-.05<=time<=times[b]+.05: event.notes.append("Synchronized reviewed audio impulse corroborates candidate; audio alone cannot confirm contact")
|
| 88 |
+
return output
|
| 89 |
+
|
| 90 |
+
def detect_events(curves, observations, capture, annotations, parameters):
|
| 91 |
+
events = []
|
| 92 |
+
# Hand motion supports a generic onset candidate; direction is not inferred from view.
|
| 93 |
+
left, right = curves["left_hand_path_pixels"], curves["right_hand_path_pixels"]
|
| 94 |
+
with np.errstate(invalid="ignore"):
|
| 95 |
+
hands = (left+right)/2
|
| 96 |
+
movement = np.linalg.norm(np.diff(hands, axis=0), axis=1)
|
| 97 |
+
threshold = parameters["motion_threshold_px_per_frame"]
|
| 98 |
+
run = parameters["sustained_frames"]
|
| 99 |
+
onset = None
|
| 100 |
+
if capture["camera_stability"] == "fixed_verified" and np.isfinite(hands).all(axis=1).sum() >= parameters["min_visible_frames"]:
|
| 101 |
+
for i in range(max(0, len(movement)-run+1)):
|
| 102 |
+
if np.all(np.isfinite(movement[i:i+run])) and np.all(movement[i:i+run] > threshold):
|
| 103 |
+
onset = i
|
| 104 |
+
break
|
| 105 |
+
if onset is not None:
|
| 106 |
+
events.append(Event("hand_motion_onset_candidate", "hand_motion_onset", "candidate", [onset, onset+run],
|
| 107 |
+
list(range(onset, onset+run+1)), "sustained_projected_hand_motion_v1",
|
| 108 |
+
notes=["May be loading or forward motion; not a confirmed forward-swing boundary"]))
|
| 109 |
+
events.append(Event("forward_swing_onset", "forward_swing_onset", "unknown", None, [], "directional_evidence_not_established"))
|
| 110 |
+
events.append(Event("contact", "contact", "unknown", None, [], "no_qualified_contact_evidence",
|
| 111 |
+
notes=["Missing contact evidence does not prove a miss or a dry swing"]))
|
| 112 |
+
events.append(Event("lead_foot_contact", "lead_foot_contact", "unknown", None, [], "ground_and_visibility_not_established"))
|
| 113 |
+
events.append(Event("load", "load", "unknown", None, [], "phase_not_confirmed"))
|
| 114 |
+
events.append(Event("follow_through", "follow_through", "unknown", None, [], "clip_end_is_not_biomechanical_endpoint"))
|
| 115 |
+
for candidate in additional_candidates(curves,observations,capture,parameters):
|
| 116 |
+
events=[e for e in events if not (e.type==candidate.type and e.state=="unknown")]
|
| 117 |
+
events.append(candidate)
|
| 118 |
+
for i, label in enumerate(annotations.get("events", [])):
|
| 119 |
+
event_type = label["type"]
|
| 120 |
+
events = [e for e in events if e.type != event_type]
|
| 121 |
+
events.append(Event(f"reviewed_{event_type}_{i}", event_type, label["state"], label.get("frame_interval"),
|
| 122 |
+
label.get("evidence_frames", []), "human_review", "reviewed", annotations["annotator"],
|
| 123 |
+
notes=[label.get("evidence_description", "Footage does not establish this event")]))
|
| 124 |
+
outcome = [e for e in events if e.type in {"contact", "miss", "dry_swing"} and e.state == "confirmed"]
|
| 125 |
+
if len({e.type for e in outcome}) > 1:
|
| 126 |
+
raise ValueError("Conflicting confirmed hit/miss/dry outcomes; resolve review")
|
| 127 |
+
for e in events:
|
| 128 |
+
if e.frame_interval:
|
| 129 |
+
a, b = e.frame_interval
|
| 130 |
+
e.playback_interval_s = [capture["frames"][a]["playback_s"], capture["frames"][b]["playback_s"]]
|
| 131 |
+
e.physical_interval_s = [capture["frames"][a]["physical_s"], capture["frames"][b]["physical_s"]]
|
| 132 |
+
return events
|
baseball_batting/geometry.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit camera geometry, rigid-bat reconstruction and calibrated planar mapping."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.optimize import least_squares
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def matrix(value, shape, name):
|
| 7 |
+
array = np.asarray(value, float)
|
| 8 |
+
if array.shape != shape or not np.isfinite(array).all():
|
| 9 |
+
raise ValueError(f"{name} must be a finite {shape} matrix")
|
| 10 |
+
return array
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def intrinsics(value):
|
| 14 |
+
k = matrix(value, (3, 3), "intrinsics")
|
| 15 |
+
if k[0, 0] <= 0 or k[1, 1] <= 0 or not np.allclose(k[2], [0, 0, 1]):
|
| 16 |
+
raise ValueError("Intrinsics require positive focal lengths and homogeneous row [0,0,1]")
|
| 17 |
+
return k
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def rotation(value):
|
| 21 |
+
r = matrix(value, (3, 3), "rotation")
|
| 22 |
+
if not np.allclose(r.T @ r, np.eye(3), atol=1e-6) or not np.isclose(np.linalg.det(r), 1, atol=1e-6):
|
| 23 |
+
raise ValueError("Rotation must be orthonormal and right-handed")
|
| 24 |
+
return r
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def project(points, k):
|
| 28 |
+
points = np.asarray(points, float)
|
| 29 |
+
homogeneous = points @ intrinsics(k).T
|
| 30 |
+
result = np.full(points.shape[:-1] + (2,), np.nan)
|
| 31 |
+
valid = np.isfinite(points).all(axis=-1) & (points[..., 2] > 1e-8)
|
| 32 |
+
result[valid] = homogeneous[valid, :2] / homogeneous[valid, 2:3]
|
| 33 |
+
return result
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def to_world(points, calibration):
|
| 37 |
+
transform = calibration.get("world_from_camera")
|
| 38 |
+
if not transform or not calibration.get("source") or calibration.get("world_axes") != "x_pitcher_y_up_z_right_handed":
|
| 39 |
+
raise ValueError("A documented camera-to-world transform and world axes are required")
|
| 40 |
+
r = rotation(transform["rotation"])
|
| 41 |
+
t = matrix(transform["translation_m"], (3,), "world translation")
|
| 42 |
+
return np.asarray(points) @ r.T + t
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def ground_pixels_to_metres(points, calibration):
|
| 46 |
+
if not calibration.get("source") or calibration.get("ground_plane_verified") is not True:
|
| 47 |
+
raise ValueError("Documented ground-plane calibration is required")
|
| 48 |
+
h = matrix(calibration["ground_homography_pixels_to_xz_metres"], (3, 3), "homography")
|
| 49 |
+
if abs(np.linalg.det(h)) < 1e-12:
|
| 50 |
+
raise ValueError("Ground homography is singular")
|
| 51 |
+
points = np.asarray(points, float)
|
| 52 |
+
homogeneous = np.concatenate([points, np.ones(points.shape[:-1] + (1,))], axis=-1) @ h.T
|
| 53 |
+
return homogeneous[..., :2] / np.where(abs(homogeneous[..., 2:3]) > 1e-12, homogeneous[..., 2:3], np.nan)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def triangulate(pixels, cameras, max_reprojection_px=3., min_ray_angle_deg=2.):
|
| 57 |
+
"""Calibrated synchronized views; reject degenerate ray geometry and behind-camera points."""
|
| 58 |
+
pixels, cameras = np.asarray(pixels, float), np.asarray(cameras, float)
|
| 59 |
+
valid = np.isfinite(pixels).all(axis=1)
|
| 60 |
+
if cameras.shape != (len(pixels), 3, 4) or valid.sum() < 2:
|
| 61 |
+
raise ValueError("At least two calibrated synchronized endpoint observations are required")
|
| 62 |
+
pixels, cameras = pixels[valid], cameras[valid]
|
| 63 |
+
centers, rays, equations = [], [], []
|
| 64 |
+
for point, camera in zip(pixels, cameras):
|
| 65 |
+
if np.linalg.matrix_rank(camera[:, :3]) < 3:
|
| 66 |
+
raise ValueError("Degenerate camera projection")
|
| 67 |
+
centers.append(-np.linalg.solve(camera[:, :3], camera[:, 3]))
|
| 68 |
+
direction = np.linalg.solve(camera[:, :3], [*point, 1.])
|
| 69 |
+
rays.append(direction / np.linalg.norm(direction))
|
| 70 |
+
equations.extend([point[0]*camera[2]-camera[0], point[1]*camera[2]-camera[1]])
|
| 71 |
+
angles = [np.degrees(np.arccos(np.clip(abs(np.dot(a, b)), -1, 1)))
|
| 72 |
+
for i, a in enumerate(rays) for b in rays[i+1:]]
|
| 73 |
+
if max(angles) < min_ray_angle_deg:
|
| 74 |
+
raise ValueError("Triangulation rays are too nearly parallel")
|
| 75 |
+
_, _, vectors = np.linalg.svd(equations)
|
| 76 |
+
if abs(vectors[-1, 3]) < 1e-10:
|
| 77 |
+
raise ValueError("Triangulation is at infinity")
|
| 78 |
+
initial = vectors[-1, :3] / vectors[-1, 3]
|
| 79 |
+
def residual(point):
|
| 80 |
+
image = cameras @ np.r_[point, 1.]
|
| 81 |
+
return (image[:, :2] / image[:, 2:3] - pixels).ravel()
|
| 82 |
+
fit = least_squares(residual, initial, loss="soft_l1")
|
| 83 |
+
depths = (cameras @ np.r_[fit.x, 1.])[:, 2]
|
| 84 |
+
errors = np.linalg.norm(residual(fit.x).reshape(-1, 2), axis=1)
|
| 85 |
+
if not fit.success or (depths <= 0).any() or errors.max() > max_reprojection_px:
|
| 86 |
+
raise ValueError("Triangulation failed cheirality or reprojection checks")
|
| 87 |
+
return fit.x, float(errors.max())
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def barrel_from_independent_knob(knob, barrel_pixel, k, length, anchor=None, tolerance_m=.03):
|
| 91 |
+
"""Sphere/ray intersection; two positive solutions remain ambiguous without an anchor."""
|
| 92 |
+
knob = matrix(knob, (3,), "independent knob position")
|
| 93 |
+
ray = np.linalg.solve(intrinsics(k), [*barrel_pixel, 1.])
|
| 94 |
+
ray /= np.linalg.norm(ray)
|
| 95 |
+
along = np.dot(ray, knob)
|
| 96 |
+
discriminant = along**2 - np.dot(knob, knob) + length**2
|
| 97 |
+
if discriminant < -1e-10:
|
| 98 |
+
raise ValueError("Endpoint ray and known bat length disagree")
|
| 99 |
+
depths = [along + np.sqrt(max(discriminant, 0)), along - np.sqrt(max(discriminant, 0))]
|
| 100 |
+
candidates = [depth*ray for depth in depths if depth > 0]
|
| 101 |
+
if len(candidates) == 2 and np.linalg.norm(candidates[0]-candidates[1]) < 1e-6:
|
| 102 |
+
candidates = candidates[:1]
|
| 103 |
+
if anchor is not None:
|
| 104 |
+
errors = [np.linalg.norm(point - np.asarray(anchor)) for point in candidates]
|
| 105 |
+
candidates = [point for point, error in zip(candidates, errors) if error <= tolerance_m]
|
| 106 |
+
if len(candidates) != 1:
|
| 107 |
+
raise ValueError("Bat endpoint depths remain ambiguous")
|
| 108 |
+
return candidates[0]
|
baseball_batting/history.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Only explicit identity and matching context/processing support trial comparisons."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from .storage import read_json, digest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def comparison_key(result):
|
| 7 |
+
capture=result["capture"];metadata=capture["metadata"]
|
| 8 |
+
return digest({"engine_code_hash":result["engine_code_hash"],"models":result["model_hashes"],
|
| 9 |
+
"geometry":metadata.get("calibration"),"task":metadata.get("swing_task"),
|
| 10 |
+
"context":{k:v for k,v in metadata.get("event_context",{}).items() if k in
|
| 11 |
+
{"intended_contact_location","pitch_location","pitch_type","lead_side","pitcher_direction_image"}},
|
| 12 |
+
"handedness":metadata.get("handedness"),
|
| 13 |
+
"resolution":[capture["frames"][0]["width"],capture["frames"][0]["height"]],
|
| 14 |
+
"timing":capture["timing_source"].get("kind"),"review":result["provenance"],
|
| 15 |
+
"configuration":result["configuration"],"metric_versions":{m["metric_id"]:m["definition_version"] for m in result["metrics"]}})
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def compatible_trials(root,result):
|
| 19 |
+
root=Path(root);player=result["capture"]["metadata"].get("player_id")
|
| 20 |
+
if not player or not result["capture"]["metadata"].get("swing_task"):return []
|
| 21 |
+
index=root.parent/"history.json"
|
| 22 |
+
if not index.exists():return []
|
| 23 |
+
key=comparison_key(result);trials=[]
|
| 24 |
+
for record in read_json(index):
|
| 25 |
+
if record.get("player_id")!=player or record.get("input_sha256")==result["capture"]["input_sha256"]:continue
|
| 26 |
+
target=(root.parent/record["result_path"]).resolve()
|
| 27 |
+
if not target.is_relative_to(root.parent.resolve()) or not target.exists():continue
|
| 28 |
+
previous=read_json(target)
|
| 29 |
+
if comparison_key(previous)==key:trials.append(previous)
|
| 30 |
+
return trials
|
baseball_batting/ingest.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source-timed decoding. Container FPS is never presumed to be the capture clock."""
|
| 2 |
+
from fractions import Fraction
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import numpy as np
|
| 10 |
+
from .contracts import FrameTiming, json_safe
|
| 11 |
+
from .storage import sha256_file
|
| 12 |
+
|
| 13 |
+
def validate_metadata(metadata):
|
| 14 |
+
allowed = {"player_id", "session_id", "handedness", "height_m", "bat_length_m",
|
| 15 |
+
"age", "experience_level", "consent", "timing", "rotation_degrees",
|
| 16 |
+
"calibration", "camera_stability", "swing_task", "intended_use", "audio", "event_context", "bat_geometry", "uncertainty"}
|
| 17 |
+
extra = set(metadata) - allowed
|
| 18 |
+
if extra:
|
| 19 |
+
raise ValueError(f"Unsupported metadata fields (avoid credentials): {sorted(extra)}")
|
| 20 |
+
if metadata.get("handedness") not in {None, "left", "right"}:
|
| 21 |
+
raise ValueError("handedness must be left or right")
|
| 22 |
+
for field in ("height_m", "bat_length_m"):
|
| 23 |
+
v = metadata.get(field)
|
| 24 |
+
if v is not None and (not isinstance(v, (int, float)) or not math.isfinite(v) or v <= 0):
|
| 25 |
+
raise ValueError(f"{field} must be positive and finite")
|
| 26 |
+
angle = metadata.get("rotation_degrees", 0)
|
| 27 |
+
if angle not in {0, 90, 180, 270}:
|
| 28 |
+
raise ValueError("rotation_degrees must be 0, 90, 180 or 270 clockwise")
|
| 29 |
+
timing = metadata.get("timing", {"kind": "unknown"})
|
| 30 |
+
if timing.get("kind") not in {"unknown", "unretimed", "constant_slowdown", "explicit"}:
|
| 31 |
+
raise ValueError("Unsupported timing kind")
|
| 32 |
+
if timing.get("kind") != "unknown" and not timing.get("source"):
|
| 33 |
+
raise ValueError("Known physical timing requires a documented source")
|
| 34 |
+
if timing.get("kind") == "constant_slowdown":
|
| 35 |
+
factor = timing.get("factor")
|
| 36 |
+
if not isinstance(factor, (int, float)) or not math.isfinite(factor) or factor <= 0:
|
| 37 |
+
raise ValueError("slowdown factor must be positive and finite")
|
| 38 |
+
if timing.get("all_captured_frames_retained") is not True:
|
| 39 |
+
raise ValueError("Constant slowdown requires all captured frames retained")
|
| 40 |
+
if timing.get("kind") == "explicit":
|
| 41 |
+
values = timing.get("physical_times_s", [])
|
| 42 |
+
if not values or any(not isinstance(x, (int, float)) or not math.isfinite(x) for x in values):
|
| 43 |
+
raise ValueError("Explicit physical times must be finite")
|
| 44 |
+
if any(b <= a for a, b in zip(values, values[1:])):
|
| 45 |
+
raise ValueError("Explicit physical times must increase strictly")
|
| 46 |
+
if metadata.get("camera_stability") not in {None, "unknown", "fixed_verified", "moving"}:
|
| 47 |
+
raise ValueError("Invalid camera stability state")
|
| 48 |
+
return metadata
|
| 49 |
+
|
| 50 |
+
def physical_time(playback, index, timing):
|
| 51 |
+
kind = timing.get("kind", "unknown")
|
| 52 |
+
if kind == "explicit":
|
| 53 |
+
values = timing["physical_times_s"]
|
| 54 |
+
if index >= len(values):
|
| 55 |
+
raise ValueError("Physical-time map is shorter than the decoded video")
|
| 56 |
+
return float(values[index])
|
| 57 |
+
if playback is None or kind == "unknown":
|
| 58 |
+
return None
|
| 59 |
+
if kind == "unretimed":
|
| 60 |
+
return playback
|
| 61 |
+
return playback / timing["factor"]
|
| 62 |
+
|
| 63 |
+
def orientation_matrix(width, height, rotation):
|
| 64 |
+
return {
|
| 65 |
+
0: np.eye(3),
|
| 66 |
+
90: np.array([[0, -1, height-1], [1, 0, 0], [0, 0, 1]]),
|
| 67 |
+
180: np.array([[-1, 0, width-1], [0, -1, height-1], [0, 0, 1]]),
|
| 68 |
+
270: np.array([[0, 1, 0], [-1, 0, width-1], [0, 0, 1]]),
|
| 69 |
+
}[rotation].astype(float)
|
| 70 |
+
|
| 71 |
+
def probe(path):
|
| 72 |
+
if not shutil.which("ffprobe"):
|
| 73 |
+
return {"status": "unavailable", "reason": "ffprobe_not_installed"}
|
| 74 |
+
result = subprocess.run(["ffprobe", "-v", "error", "-protocol_whitelist", "file,pipe", "-show_streams", "-show_format",
|
| 75 |
+
"-of", "json", str(path)], capture_output=True, text=True)
|
| 76 |
+
if result.returncode:
|
| 77 |
+
return {"status": "failed", "reason": "ffprobe_failed"}
|
| 78 |
+
value = json.loads(result.stdout)
|
| 79 |
+
# Avoid arbitrary file tags in exported manifests.
|
| 80 |
+
return {"status": "ready", "streams": [{k: s[k] for k in
|
| 81 |
+
("index", "codec_name", "codec_type", "width", "height", "time_base",
|
| 82 |
+
"r_frame_rate", "avg_frame_rate", "duration", "side_data_list") if k in s}
|
| 83 |
+
for s in value.get("streams", [])]}
|
| 84 |
+
|
| 85 |
+
def iter_frames(path, rotation=0, max_pixels=None):
|
| 86 |
+
import av
|
| 87 |
+
import cv2
|
| 88 |
+
# Uploaded recordings must not trigger network requests through a playlist.
|
| 89 |
+
with av.open(str(path), options={"protocol_whitelist": "file,pipe"}) as container:
|
| 90 |
+
if not container.streams.video:
|
| 91 |
+
raise ValueError("No video stream")
|
| 92 |
+
stream = container.streams.video[0]
|
| 93 |
+
if max_pixels is not None and stream.width * stream.height > max_pixels:
|
| 94 |
+
raise ValueError("Video exceeds the configured pixel limit")
|
| 95 |
+
for index, frame in enumerate(container.decode(stream)):
|
| 96 |
+
if max_pixels is not None and frame.width * frame.height > max_pixels:
|
| 97 |
+
raise ValueError("Video exceeds the configured pixel limit")
|
| 98 |
+
image = frame.to_ndarray(format="bgr24")
|
| 99 |
+
if rotation:
|
| 100 |
+
image = np.ascontiguousarray(np.rot90(image, -(rotation // 90)))
|
| 101 |
+
yield index, frame.pts, frame.time_base or stream.time_base, image
|
| 102 |
+
|
| 103 |
+
def ingest(path, metadata, *, max_frames=None, max_pixels=None, max_duration_s=None, progress=None):
|
| 104 |
+
import cv2
|
| 105 |
+
validate_metadata(metadata)
|
| 106 |
+
timings, quality = [], []
|
| 107 |
+
prior_time, prior_hash = None, None
|
| 108 |
+
rotation = metadata.get("rotation_degrees", 0)
|
| 109 |
+
probe_result = probe(path)
|
| 110 |
+
if "rotation_degrees" not in metadata and probe_result.get("status") == "ready":
|
| 111 |
+
for s in probe_result["streams"]:
|
| 112 |
+
if s.get("codec_type") == "video":
|
| 113 |
+
for side in s.get("side_data_list", []):
|
| 114 |
+
if "rotation" in side:
|
| 115 |
+
rotation = int(-side["rotation"]) % 360
|
| 116 |
+
if rotation not in {0, 90, 180, 270}:
|
| 117 |
+
raise ValueError("Non-right-angle orientation needs an explicit tested transform")
|
| 118 |
+
raw_shape = None
|
| 119 |
+
first_time = None
|
| 120 |
+
for index, pts, base, image in iter_frames(path, rotation, max_pixels=max_pixels):
|
| 121 |
+
if max_frames is not None and index >= max_frames:
|
| 122 |
+
raise ValueError("Video exceeds the configured frame limit")
|
| 123 |
+
raw_shape = (image.shape[1], image.shape[0]) if not rotation % 180 else (image.shape[0], image.shape[1])
|
| 124 |
+
playback = float(pts * base) if pts is not None and base else None
|
| 125 |
+
if first_time is None and playback is not None:
|
| 126 |
+
first_time = playback
|
| 127 |
+
if (max_duration_s is not None and playback is not None and first_time is not None
|
| 128 |
+
and playback - first_time > max_duration_s):
|
| 129 |
+
raise ValueError("Video exceeds the configured duration limit")
|
| 130 |
+
flags = []
|
| 131 |
+
if playback is None:
|
| 132 |
+
flags.append("missing_pts")
|
| 133 |
+
elif prior_time is not None and playback <= prior_time:
|
| 134 |
+
flags.append("duplicate_pts" if playback == prior_time else "nonmonotonic_pts")
|
| 135 |
+
if playback is not None:
|
| 136 |
+
prior_time = playback
|
| 137 |
+
image_hash = hashlib.sha256(image.tobytes()).hexdigest()
|
| 138 |
+
if image_hash == prior_hash:
|
| 139 |
+
flags.append("duplicate_image")
|
| 140 |
+
prior_hash = image_hash
|
| 141 |
+
t = physical_time(playback, index, metadata.get("timing", {"kind": "unknown"}))
|
| 142 |
+
timings.append(FrameTiming(index, pts, str(base) if base else None, playback,
|
| 143 |
+
t, image.shape[1], image.shape[0], flags))
|
| 144 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 145 |
+
quality.append({"frame_id": index, "blur_laplacian_variance": float(cv2.Laplacian(gray, cv2.CV_64F).var()),
|
| 146 |
+
"mean_luminance": float(gray.mean())})
|
| 147 |
+
if progress and (index + 1) % 64 == 0:
|
| 148 |
+
progress(index + 1)
|
| 149 |
+
if not timings:
|
| 150 |
+
raise ValueError("No decodable video frames")
|
| 151 |
+
timing_meta = metadata.get("timing", {"kind": "unknown"})
|
| 152 |
+
if timing_meta.get("kind") == "explicit" and len(timing_meta["physical_times_s"]) != len(timings):
|
| 153 |
+
raise ValueError("Physical-time map must match decoded frame count")
|
| 154 |
+
intervals = [b.playback_s-a.playback_s for a, b in zip(timings, timings[1:])
|
| 155 |
+
if a.playback_s is not None and b.playback_s is not None and b.playback_s > a.playback_s]
|
| 156 |
+
if intervals:
|
| 157 |
+
nominal = float(np.median(intervals))
|
| 158 |
+
for a, b in zip(timings, timings[1:]):
|
| 159 |
+
if a.playback_s is not None and b.playback_s is not None and b.playback_s-a.playback_s > 1.5*nominal:
|
| 160 |
+
b.flags.append("timestamp_gap_or_variable_cadence")
|
| 161 |
+
return json_safe({"schema_version": "1.0", "input_sha256": sha256_file(path),
|
| 162 |
+
"frame_count": len(timings), "frames": timings, "quality": quality,
|
| 163 |
+
"metadata": metadata, "probe": probe_result, "rotation_degrees": rotation,
|
| 164 |
+
"orientation_transform": orientation_matrix(*raw_shape, rotation),
|
| 165 |
+
"coordinate_space": "oriented_image_pixels_x_right_y_down",
|
| 166 |
+
"timing_source": timing_meta, "participant_consent_record": metadata.get("consent", "not_supplied"),
|
| 167 |
+
"camera_stability": metadata.get("camera_stability", "unknown"),
|
| 168 |
+
"physical_clock_known": all(t.physical_s is not None for t in timings),
|
| 169 |
+
"resource_registry_ids": ["pyav", "opencv", "ffmpeg"]})
|
baseball_batting/learning.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trainable endpoints and phase/boundary heads. Candidate weights do not auto-activate."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import importlib.util
|
| 4 |
+
import subprocess
|
| 5 |
+
import numpy as np
|
| 6 |
+
from .storage import read_json, sha256_file, digest, atomic_json
|
| 7 |
+
from .contracts import RTMW_CORE, Event
|
| 8 |
+
|
| 9 |
+
MS_TCN_REVISION = "aef4e46c31bc7b2462065354054f968f91e54be1"
|
| 10 |
+
PHASES = ["setup", "load", "stride", "forward_swing", "follow_through"]
|
| 11 |
+
BOUNDARIES = ["load", "lead_foot_lift", "lead_foot_contact", "forward_swing_onset", "contact", "follow_through"]
|
| 12 |
+
FEATURE_VERSION = "body_object_visual_v1"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def endpoint_network():
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
class EndpointCNN(nn.Module):
|
| 18 |
+
def __init__(self):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.stem = nn.Sequential(nn.Conv2d(3,32,5,2,2),nn.ReLU(),nn.Conv2d(32,64,3,2,1),nn.ReLU(),
|
| 21 |
+
nn.Conv2d(64,64,3,1,1),nn.ReLU())
|
| 22 |
+
self.heatmap = nn.Conv2d(64,2,1)
|
| 23 |
+
self.visible = nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(64,2))
|
| 24 |
+
def forward(self,x):
|
| 25 |
+
features=self.stem(x)
|
| 26 |
+
return self.heatmap(features),self.visible(features)
|
| 27 |
+
return EndpointCNN()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def temporal_network(repository, architecture):
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn as nn
|
| 33 |
+
repository=Path(repository)
|
| 34 |
+
revision=subprocess.run(["git","-C",str(repository),"rev-parse","HEAD"],capture_output=True,text=True,check=True).stdout.strip()
|
| 35 |
+
if revision != MS_TCN_REVISION:
|
| 36 |
+
raise ValueError("MS-TCN++ source must be the selected valid pinned revision")
|
| 37 |
+
source=repository/"model.py"
|
| 38 |
+
module_spec=importlib.util.spec_from_file_location("batting_official_mstcn",source)
|
| 39 |
+
module=importlib.util.module_from_spec(module_spec);module_spec.loader.exec_module(module)
|
| 40 |
+
class TemporalHead(nn.Module):
|
| 41 |
+
def __init__(self):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.phases=module.MS_TCN2(architecture["prediction_layers"],architecture["refinement_layers"],
|
| 44 |
+
architecture["refinements"],architecture["channels"],architecture["feature_dim"],len(PHASES))
|
| 45 |
+
self.boundaries=nn.Conv1d(len(PHASES),len(BOUNDARIES),1)
|
| 46 |
+
self.presence=nn.Linear(len(PHASES),len(BOUNDARIES))
|
| 47 |
+
def forward(self,x):
|
| 48 |
+
phases=self.phases(x)
|
| 49 |
+
probability=torch.softmax(phases[-1],dim=1)
|
| 50 |
+
return phases,self.boundaries(probability),self.presence(probability.mean(-1))
|
| 51 |
+
return TemporalHead(), {"revision":revision,"model_source_sha256":sha256_file(source)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def features(observations,capture):
|
| 55 |
+
values=[]
|
| 56 |
+
indices=list(RTMW_CORE.values())
|
| 57 |
+
for frame, timing in zip(observations["frames"],capture["frames"]):
|
| 58 |
+
scale=np.array([timing["width"],timing["height"]],float)
|
| 59 |
+
points=np.asarray(frame["body_points"],float)[indices]/scale
|
| 60 |
+
valid=np.array([frame["body_states"][i] in {"manual","image_supported","model_inferred"} for i in indices])
|
| 61 |
+
valid &= np.isfinite(points).all(1);points[~valid]=0
|
| 62 |
+
bat=np.zeros((2,2));bat_mask=np.zeros(2)
|
| 63 |
+
if frame["bat"].get("points") is not None:
|
| 64 |
+
bat=np.asarray(frame["bat"]["points"],float)/scale
|
| 65 |
+
bat_mask=np.array([s in {"manual","image_supported"} for s in frame["bat"]["states"]],float)
|
| 66 |
+
bat[bat_mask==0]=0
|
| 67 |
+
ball=np.zeros(2);ball_mask=0
|
| 68 |
+
if frame["ball"].get("point") is not None:
|
| 69 |
+
ball=np.asarray(frame["ball"]["point"],float)/scale;ball_mask=1
|
| 70 |
+
visual=np.asarray(frame.get("visual_feature",np.zeros(64)),float)
|
| 71 |
+
values.append(np.r_[points.ravel(),valid,bat.ravel(),bat_mask,ball,ball_mask,visual])
|
| 72 |
+
return np.asarray(values,np.float32).T
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def qualification(manifest_path,checkpoint,kind):
|
| 76 |
+
manifest=read_json(manifest_path)
|
| 77 |
+
if manifest.get("kind")!=kind or manifest.get("checkpoint_sha256")!=sha256_file(checkpoint):
|
| 78 |
+
raise ValueError("Checkpoint kind/hash does not match manifest")
|
| 79 |
+
record=manifest.get("qualification",{})
|
| 80 |
+
if record.get("status")!="passed" or record.get("held_out_athletes") is not True or not record.get("evaluation_sha256"):
|
| 81 |
+
raise ValueError("Checkpoint has no passed held-out technical qualification")
|
| 82 |
+
# Qualification is explicit experimental scope, never proof of biomechanical validity.
|
| 83 |
+
if not record.get("scope"): raise ValueError("Checkpoint qualification scope missing")
|
| 84 |
+
evidence_path=Path(manifest_path).resolve().parent/"evaluation.json"
|
| 85 |
+
if not evidence_path.is_file() or sha256_file(evidence_path)!=record["evaluation_sha256"]:
|
| 86 |
+
raise ValueError("Checkpoint qualification evidence missing or changed")
|
| 87 |
+
evidence=read_json(evidence_path)
|
| 88 |
+
if evidence.get("passed") is not True or evidence.get("checkpoint_sha256")!=manifest["checkpoint_sha256"] or evidence.get("scope")!=record["scope"]:
|
| 89 |
+
raise ValueError("Checkpoint qualification evidence mismatch")
|
| 90 |
+
return manifest
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class EndpointPredictor:
|
| 94 |
+
def __init__(self,checkpoint,manifest_path,device):
|
| 95 |
+
import torch
|
| 96 |
+
self.torch=torch;self.device=device
|
| 97 |
+
self.manifest=qualification(manifest_path,checkpoint,"endpoint_cnn")
|
| 98 |
+
self.model=endpoint_network().to(device).eval()
|
| 99 |
+
self.model.load_state_dict(torch.load(checkpoint,map_location=device,weights_only=True))
|
| 100 |
+
|
| 101 |
+
def __call__(self,image,box):
|
| 102 |
+
import cv2
|
| 103 |
+
x1,y1,x2,y2=np.asarray(box,int)
|
| 104 |
+
h,w=image.shape[:2];x1=max(x1,0);y1=max(y1,0);x2=min(x2,w);y2=min(y2,h)
|
| 105 |
+
if x2-x1<8 or y2-y1<8: return None
|
| 106 |
+
crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy()/255.
|
| 107 |
+
x=self.torch.tensor(crop.transpose(2,0,1),dtype=self.torch.float32,device=self.device)[None]
|
| 108 |
+
with self.torch.no_grad(): heatmap,visibility=self.model(x)
|
| 109 |
+
if (visibility.sigmoid()<self.manifest.get("visibility_threshold",.5)).any(): return None
|
| 110 |
+
maps=heatmap[0].cpu().numpy();flat=maps.reshape(2,-1).argmax(1)
|
| 111 |
+
xy=np.stack([flat%64,flat//64],1).astype(float)+.5
|
| 112 |
+
points=xy/64*[x2-x1,y2-y1]+[x1,y1]
|
| 113 |
+
# Reject border predictions where a true endpoint may lie outside the crop.
|
| 114 |
+
if np.any(xy<2) or np.any(xy>62): return None
|
| 115 |
+
return {"points":points.tolist(),"states":["model_inferred"]*2,"method":"qualified_endpoint_cnn_v1",
|
| 116 |
+
"qualification_scope":self.manifest["qualification"]["scope"]}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def run_learned_events(request,capture,config,observations):
|
| 120 |
+
root=Path(request["root"])
|
| 121 |
+
try:
|
| 122 |
+
if not config.event_manifest_path or not config.event_checkpoint_path:
|
| 123 |
+
raise ValueError("no_qualified_checkpoint")
|
| 124 |
+
import torch
|
| 125 |
+
manifest=qualification(config.event_manifest_path,config.event_checkpoint_path,"mstcn_events")
|
| 126 |
+
if manifest.get("feature_version")!=FEATURE_VERSION: raise ValueError("Event feature definition mismatch")
|
| 127 |
+
model,source=temporal_network(config.mstcn_repo,manifest["architecture"])
|
| 128 |
+
if source!=manifest["source"]: raise ValueError("Event source hash mismatch")
|
| 129 |
+
model.load_state_dict(torch.load(config.event_checkpoint_path,map_location="cpu",weights_only=True))
|
| 130 |
+
model=model.to(config.device).eval()
|
| 131 |
+
x=features(observations,capture)
|
| 132 |
+
with torch.no_grad(): phase,boundary,presence=model(torch.tensor(x,device=config.device)[None])
|
| 133 |
+
phase=phase[-1].softmax(1)[0].cpu().numpy(); boundary=boundary.sigmoid()[0].cpu().numpy();presence=presence.sigmoid()[0].cpu().numpy()
|
| 134 |
+
candidates=[]
|
| 135 |
+
for i,name in enumerate(BOUNDARIES):
|
| 136 |
+
if presence[i]<manifest.get("presence_threshold",.5): continue
|
| 137 |
+
index=int(boundary[i].argmax())
|
| 138 |
+
if boundary[i,index]<manifest.get("boundary_threshold",.5):continue
|
| 139 |
+
candidates.append({"type":name,"frame_interval":[max(index-1,0),min(index+1,capture["frame_count"]-1)],
|
| 140 |
+
"evidence_frames":[index],"state":"candidate"})
|
| 141 |
+
np.savez_compressed(root/"learned_events.npz",phase_probability=phase,boundary_score=boundary,presence_score=presence)
|
| 142 |
+
status={"status":"complete","candidates":candidates,"checkpoint_sha256":manifest["checkpoint_sha256"],
|
| 143 |
+
"qualification_scope":manifest["qualification"]["scope"],"source":source,
|
| 144 |
+
"confidence_interpretation":"network_scores_not_calibrated_contact_probabilities"}
|
| 145 |
+
except Exception as error:
|
| 146 |
+
status={"status":"unavailable","reason":str(error)[:300],"error_type":type(error).__name__}
|
| 147 |
+
atomic_json(root/"learned_events_status.json",status)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def merge_learned(events,status):
|
| 151 |
+
if status.get("status")!="complete":return events
|
| 152 |
+
for i,candidate in enumerate(status["candidates"]):
|
| 153 |
+
# Human-reviewed absence/unknown/confirmation is never overwritten.
|
| 154 |
+
if any(e.type==candidate["type"] and e.review_status=="reviewed" for e in events):continue
|
| 155 |
+
events.append(Event("learned_"+str(i),candidate["type"],"candidate",candidate["frame_interval"],
|
| 156 |
+
candidate["evidence_frames"],"qualified_mstcn_v1",notes=["Experimental trained candidate; requires visible evidence/review"]))
|
| 157 |
+
return events
|
baseball_batting/metrics.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuous projected curves, then summaries with independent evidence gates."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .contracts import Metric, RTMW_CORE
|
| 4 |
+
|
| 5 |
+
def flexion_degrees(a, b, c):
|
| 6 |
+
a, b, c = np.asarray(a, float), np.asarray(b, float), np.asarray(c, float)
|
| 7 |
+
u, v = a-b, c-b
|
| 8 |
+
denominator = np.linalg.norm(u, axis=-1)*np.linalg.norm(v, axis=-1)
|
| 9 |
+
cosine = np.sum(u*v, axis=-1)/np.where(denominator > 1e-9, denominator, np.nan)
|
| 10 |
+
return 180-np.degrees(np.arccos(np.clip(cosine, -1, 1)))
|
| 11 |
+
|
| 12 |
+
def derivative(values, times):
|
| 13 |
+
"""Differentiate only contiguous finite increasing intervals; do not bridge gaps."""
|
| 14 |
+
values, times = np.asarray(values, float), np.asarray(times, float)
|
| 15 |
+
result = np.full_like(values, np.nan)
|
| 16 |
+
valid = np.isfinite(times) & np.isfinite(values).reshape(len(times), -1).all(axis=1)
|
| 17 |
+
start = 0
|
| 18 |
+
for k in range(len(times)+1):
|
| 19 |
+
boundary = k == len(times) or not valid[k] or (k > start and times[k] <= times[k-1])
|
| 20 |
+
if boundary:
|
| 21 |
+
if k-start >= 3:
|
| 22 |
+
result[start:k] = np.gradient(values[start:k], times[start:k], axis=0, edge_order=2)
|
| 23 |
+
start = k+1 if k < len(times) and not valid[k] else k
|
| 24 |
+
return result
|
| 25 |
+
|
| 26 |
+
def continuous_curves(observations, capture):
|
| 27 |
+
frames = observations["frames"]
|
| 28 |
+
n = len(frames)
|
| 29 |
+
body = np.array([f["body_points"] for f in frames], dtype=float)
|
| 30 |
+
for i, f in enumerate(frames):
|
| 31 |
+
for j, state in enumerate(f["body_states"]):
|
| 32 |
+
if state not in {"model_inferred", "image_supported", "manual"}:
|
| 33 |
+
body[i, j] = np.nan
|
| 34 |
+
bat = np.full((n, 2, 2), np.nan)
|
| 35 |
+
for i, f in enumerate(frames):
|
| 36 |
+
qualified=f["bat"].get("method")=="qualified_endpoint_cnn_v1"
|
| 37 |
+
if f["bat"]["points"] is not None and all(s in ({"image_supported", "manual", "model_inferred"} if qualified else {"image_supported", "manual"}) for s in f["bat"]["states"]):
|
| 38 |
+
bat[i] = f["bat"]["points"]
|
| 39 |
+
time = np.array([f["physical_s"] for f in capture["frames"]], dtype=float)
|
| 40 |
+
curves = {"physical_time_s": time, "body_pixels": body, "bat_endpoints_pixels": bat}
|
| 41 |
+
for side in ("left", "right"):
|
| 42 |
+
for joint, names in (("elbow", ("shoulder", "elbow", "wrist")), ("knee", ("hip", "knee", "ankle"))):
|
| 43 |
+
a, b, c = [body[:, RTMW_CORE[f"{side}_{name}"]] for name in names]
|
| 44 |
+
curves[f"{side}_{joint}_projected_flexion_deg"] = flexion_degrees(a, b, c)
|
| 45 |
+
curves[f"{side}_hand_path_pixels"] = body[:, RTMW_CORE[f"{side}_wrist"]]
|
| 46 |
+
curves["projected_ankle_span_px"] = np.linalg.norm(body[:, 15]-body[:, 16], axis=1)
|
| 47 |
+
shaft = bat[:, 1]-bat[:, 0]
|
| 48 |
+
curves["projected_bat_shaft_angle_deg"] = np.degrees(np.arctan2(-shaft[:, 1], shaft[:, 0]))
|
| 49 |
+
if capture["physical_clock_known"] and capture["camera_stability"] == "fixed_verified" and not any(
|
| 50 |
+
{"duplicate_pts", "nonmonotonic_pts", "duplicate_image", "missing_pts", "timestamp_gap_or_variable_cadence"} & set(f["flags"]) for f in capture["frames"]):
|
| 51 |
+
for side in ("left", "right"):
|
| 52 |
+
curves[f"{side}_hand_projected_velocity_px_s"] = derivative(curves[f"{side}_hand_path_pixels"], time)
|
| 53 |
+
return curves
|
| 54 |
+
|
| 55 |
+
def summarize(curves, observations, capture, events):
|
| 56 |
+
output = []
|
| 57 |
+
timing_source = capture["timing_source"].get("kind", "unknown")
|
| 58 |
+
def sources(indices, landmark_indices):
|
| 59 |
+
return sorted({observations["frames"][int(i)]["body_states"][j]
|
| 60 |
+
for i in indices for j in landmark_indices
|
| 61 |
+
if observations["frames"][int(i)]["body_states"][j] in {"manual", "model_inferred", "image_supported"}})
|
| 62 |
+
for name in [k for k in curves if k.endswith("flexion_deg") or k == "projected_ankle_span_px"]:
|
| 63 |
+
v = curves[name]
|
| 64 |
+
indices = np.flatnonzero(np.isfinite(v))
|
| 65 |
+
if name == "projected_ankle_span_px":
|
| 66 |
+
used = [15,16]
|
| 67 |
+
else:
|
| 68 |
+
side, joint = name.split("_")[:2]
|
| 69 |
+
names = ("shoulder", "elbow", "wrist") if joint == "elbow" else ("hip", "knee", "ankle")
|
| 70 |
+
used = [RTMW_CORE[f"{side}_{j}"] for j in names]
|
| 71 |
+
provenance = sources(indices, used)
|
| 72 |
+
output.append(Metric(name+"_median", "1.0", float(np.median(v[indices])) if len(indices) else None,
|
| 73 |
+
"deg_projected" if name.endswith("deg") else "px", "supported" if len(indices) else "unsupported",
|
| 74 |
+
provenance, indices.tolist(), "oriented_image_projection", timing_source,
|
| 75 |
+
unavailable_reason=None if len(indices) else "missing_joint_observations"))
|
| 76 |
+
bat_angle = curves["projected_bat_shaft_angle_deg"]
|
| 77 |
+
indices = np.flatnonzero(np.isfinite(bat_angle))
|
| 78 |
+
# Median of directional angles must use circular arithmetic across ±180°.
|
| 79 |
+
value = None
|
| 80 |
+
if len(indices):
|
| 81 |
+
rad = np.radians(bat_angle[indices])
|
| 82 |
+
value = float(np.degrees(np.arctan2(np.sin(rad).mean(), np.cos(rad).mean())))
|
| 83 |
+
output.append(Metric("projected_bat_shaft_angle_circular_mean", "1.0", value, "deg_projected",
|
| 84 |
+
"supported" if value is not None else "unsupported",
|
| 85 |
+
sorted({s for i in indices for s in observations["frames"][i]["bat"]["states"]}), indices.tolist(),
|
| 86 |
+
"image_plane_x_right_y_up", timing_source,
|
| 87 |
+
unavailable_reason=None if value is not None else "no_supported_bat_endpoints"))
|
| 88 |
+
for side in ("left", "right"):
|
| 89 |
+
path = curves[f"{side}_hand_path_pixels"]
|
| 90 |
+
valid = np.isfinite(path).all(axis=1)
|
| 91 |
+
reason = None
|
| 92 |
+
if capture["camera_stability"] != "fixed_verified":
|
| 93 |
+
reason = "camera_stability_unverified"
|
| 94 |
+
elif not valid.all() or len(path) < 2:
|
| 95 |
+
reason = "incomplete_hand_path"
|
| 96 |
+
distance = float(np.linalg.norm(np.diff(path, axis=0), axis=1).sum()) if reason is None else None
|
| 97 |
+
output.append(Metric(f"{side}_hand_projected_path_length", "1.0", distance, "px",
|
| 98 |
+
"supported" if reason is None else "unsupported", sources(np.flatnonzero(valid), [RTMW_CORE[f"{side}_wrist"]]),
|
| 99 |
+
np.flatnonzero(valid).tolist(), "fixed_camera_image_plane", timing_source, reason))
|
| 100 |
+
velocity = curves.get(f"{side}_hand_projected_velocity_px_s")
|
| 101 |
+
indices = np.flatnonzero(np.isfinite(velocity).all(axis=1)) if velocity is not None else np.array([], int)
|
| 102 |
+
reason = None if len(indices) else ("physical_clock_unknown" if not capture["physical_clock_known"] else "timing_or_camera_or_observation_support_failed")
|
| 103 |
+
speed = float(np.linalg.norm(velocity[indices], axis=1).max()) if len(indices) else None
|
| 104 |
+
output.append(Metric(f"{side}_hand_peak_projected_speed", "1.0", speed, "px/s",
|
| 105 |
+
"supported" if speed is not None else "unsupported", sources(indices, [RTMW_CORE[f"{side}_wrist"]]), indices.tolist(),
|
| 106 |
+
"fixed_camera_image_plane", timing_source, reason))
|
| 107 |
+
for name, unit, reason in (
|
| 108 |
+
("ground_plane_stride_length", "m", "ground_calibration_and_event_not_qualified"),
|
| 109 |
+
("pelvis_thorax_heading_separation", "deg", "anatomical_3d_method_not_qualified"),
|
| 110 |
+
("pelvis_peak_angular_velocity", "deg/s", "anatomical_3d_method_not_qualified"),
|
| 111 |
+
("bat_sweet_spot_speed_at_contact", "m/s", "independent_bat_3d_geometry_not_qualified"),
|
| 112 |
+
("bat_attack_angle_at_contact", "deg", "independent_bat_3d_geometry_not_qualified"),
|
| 113 |
+
("exit_velocity", "m/s", "outcome_module_not_supported"),
|
| 114 |
+
):
|
| 115 |
+
output.append(Metric(name, "1.0", None, unit, "unsupported", [], [], "not_established", timing_source, reason))
|
| 116 |
+
return output
|
baseball_batting/motion.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Time-aware penalties and segment-frame measurements with explicit geometry."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.spatial.transform import Rotation
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def contiguous_segments(valid, times, max_gap=None):
|
| 7 |
+
valid, times = np.asarray(valid, bool), np.asarray(times, float)
|
| 8 |
+
result, start = [], None
|
| 9 |
+
for i in range(len(times)):
|
| 10 |
+
supported = valid[i] and np.isfinite(times[i])
|
| 11 |
+
connected = i == 0 or (times[i] > times[i-1] and (max_gap is None or times[i]-times[i-1] <= max_gap))
|
| 12 |
+
if start is not None and (not supported or not connected):
|
| 13 |
+
result.append((start, i)); start = None
|
| 14 |
+
if supported and start is None:
|
| 15 |
+
start = i
|
| 16 |
+
if start is not None:
|
| 17 |
+
result.append((start, len(times)))
|
| 18 |
+
return result
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def angular_velocity(rotations, times, valid=None):
|
| 22 |
+
"""World angular-velocity vectors from rotation logarithms, never Euler derivatives."""
|
| 23 |
+
rotations, times = np.asarray(rotations), np.asarray(times, float)
|
| 24 |
+
valid = np.isfinite(rotations).all(axis=(1, 2)) if valid is None else np.asarray(valid, bool)
|
| 25 |
+
velocity = np.full((len(times), 3), np.nan)
|
| 26 |
+
for a, b in contiguous_segments(valid, times):
|
| 27 |
+
if b-a < 3:
|
| 28 |
+
continue
|
| 29 |
+
intervals = Rotation.from_matrix(rotations[a+1:b] @ rotations[a:b-1].transpose(0, 2, 1)).as_rotvec()
|
| 30 |
+
rates = intervals / np.diff(times[a:b])[:, None]
|
| 31 |
+
velocity[a], velocity[b-1] = rates[0], rates[-1]
|
| 32 |
+
left, right = np.diff(times[a:b])[:-1], np.diff(times[a:b])[1:]
|
| 33 |
+
velocity[a+1:b-1] = (rates[:-1]*right[:, None] + rates[1:]*left[:, None])/(left+right)[:, None]
|
| 34 |
+
return velocity
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def heading(rotations, forward_axis=2):
|
| 38 |
+
vector = np.asarray(rotations)[..., :, forward_axis]
|
| 39 |
+
result = np.arctan2(vector[..., 2], vector[..., 0])
|
| 40 |
+
return np.where(np.linalg.norm(vector[..., [0, 2]], axis=-1) > 1e-8, result, np.nan)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def wrapped_difference(a, b):
|
| 44 |
+
return np.arctan2(np.sin(np.asarray(a)-b), np.cos(np.asarray(a)-b))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def sparse_temporal_pattern(frame_count, coordinate_count, marker_count):
|
| 48 |
+
from scipy.sparse import lil_matrix
|
| 49 |
+
rows = frame_count*marker_count*3 + max(frame_count-2, 0)*coordinate_count
|
| 50 |
+
pattern = lil_matrix((rows, frame_count*coordinate_count), dtype=int)
|
| 51 |
+
for frame in range(frame_count):
|
| 52 |
+
pattern[frame*marker_count*3:(frame+1)*marker_count*3,
|
| 53 |
+
frame*coordinate_count:(frame+1)*coordinate_count] = 1
|
| 54 |
+
offset = frame_count*marker_count*3
|
| 55 |
+
for frame in range(max(frame_count-2, 0)):
|
| 56 |
+
pattern[offset+frame*coordinate_count:offset+(frame+1)*coordinate_count,
|
| 57 |
+
frame*coordinate_count:(frame+3)*coordinate_count] = 1
|
| 58 |
+
return pattern.tocsr()
|
baseball_batting/objects.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline association of generic sports-ball candidates, without fabricated positions."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def possible_impact_reset(proposals, bat):
|
| 5 |
+
"""Projected proximity can reset a motion predictor, never confirm contact."""
|
| 6 |
+
if bat.get("points") is None:
|
| 7 |
+
return False
|
| 8 |
+
a, b = np.array(bat["points"], dtype=float)
|
| 9 |
+
shaft = b-a
|
| 10 |
+
length_squared = float(shaft@shaft)
|
| 11 |
+
if length_squared < 1e-9:
|
| 12 |
+
return False
|
| 13 |
+
for candidate in proposals:
|
| 14 |
+
if candidate["class_id"] != 32:
|
| 15 |
+
continue
|
| 16 |
+
center = (np.array(candidate["box"][:2])+candidate["box"][2:])/2
|
| 17 |
+
fraction = np.clip((center-a)@shaft/length_squared,0,1)
|
| 18 |
+
if np.linalg.norm(center-(a+fraction*shaft)) <= 8:
|
| 19 |
+
return True
|
| 20 |
+
return False
|
| 21 |
+
|
| 22 |
+
class BallTracker:
|
| 23 |
+
def __init__(self, state=None):
|
| 24 |
+
self.state = state or {"last": None, "previous": None}
|
| 25 |
+
|
| 26 |
+
def update(self, proposals, time_s, frame_id, manual=None, restart=False):
|
| 27 |
+
if restart:
|
| 28 |
+
self.state = {"last": None, "previous": None}
|
| 29 |
+
if manual is not None:
|
| 30 |
+
point, score, source = manual, None, "manual"
|
| 31 |
+
else:
|
| 32 |
+
options = [d for d in proposals if d["class_id"] == 32]
|
| 33 |
+
if not options:
|
| 34 |
+
return {"point": None, "state": "unknown", "score": None}
|
| 35 |
+
last, previous = self.state["last"], self.state["previous"]
|
| 36 |
+
centers = [((np.array(d["box"][:2])+d["box"][2:])/2) for d in options]
|
| 37 |
+
if last:
|
| 38 |
+
predicted = np.array(last["point"], dtype=float)
|
| 39 |
+
if previous and time_s is not None and last["time_s"] is not None and previous["time_s"] is not None:
|
| 40 |
+
dt = last["time_s"]-previous["time_s"]
|
| 41 |
+
if dt > 0 and 0 < time_s-last["time_s"] < 0.15:
|
| 42 |
+
predicted += (predicted-np.array(previous["point"]))/dt*(time_s-last["time_s"])
|
| 43 |
+
distances = np.linalg.norm(np.array(centers)-predicted, axis=1)
|
| 44 |
+
best = int(np.argmin(distances))
|
| 45 |
+
if distances[best] > 120:
|
| 46 |
+
return {"point": None, "state": "unknown", "score": None, "reason": "association_ambiguous"}
|
| 47 |
+
elif len(options) > 1:
|
| 48 |
+
return {"point": None, "state": "unknown", "score": None, "reason": "multiple_unidentified_balls"}
|
| 49 |
+
else:
|
| 50 |
+
best = 0
|
| 51 |
+
point, score, source = centers[best].tolist(), options[best]["score"], "model_inferred"
|
| 52 |
+
self.state["previous"] = self.state["last"]
|
| 53 |
+
self.state["last"] = {"point": point, "time_s": time_s, "frame_id": frame_id}
|
| 54 |
+
return {"point": point, "state": source, "score": score,
|
| 55 |
+
"identity": "baseball_candidate" if source != "manual" else "reviewed_ball"}
|
baseball_batting/observations.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Streaming observation worker with stable tracking and verified chunk resuming."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .annotations import load_annotations
|
| 5 |
+
from .bat2d import BatTracker
|
| 6 |
+
from .body2d import RTMWPose
|
| 7 |
+
from .contracts import RTMW_CORE
|
| 8 |
+
from .detection import YOLOXDetector, select_person
|
| 9 |
+
from .ingest import iter_frames
|
| 10 |
+
from .objects import BallTracker, possible_impact_reset
|
| 11 |
+
from .storage import StageCache, atomic_json, read_json
|
| 12 |
+
|
| 13 |
+
def run_observations(video, capture, config, cache, progress=None):
|
| 14 |
+
annotations = load_annotations(config.annotations_path, capture["input_sha256"],
|
| 15 |
+
capture["frame_count"], capture["frames"][0]["width"],
|
| 16 |
+
capture["frames"][0]["height"])
|
| 17 |
+
errors = {}
|
| 18 |
+
from .preflight import environment_snapshot
|
| 19 |
+
runtime_environment = environment_snapshot()
|
| 20 |
+
def load(name, path, factory):
|
| 21 |
+
if not path:
|
| 22 |
+
errors[name] = {"status": "unavailable", "reason": "artifact_not_configured"}
|
| 23 |
+
return None
|
| 24 |
+
try:
|
| 25 |
+
model = factory(path)
|
| 26 |
+
errors[name] = {"status": "ready"}
|
| 27 |
+
return model
|
| 28 |
+
except Exception as e:
|
| 29 |
+
errors[name] = {"status": "failed_preflight", "reason": str(e)[:300]}
|
| 30 |
+
return None
|
| 31 |
+
pose, person, objects, endpoint = None, None, None, None
|
| 32 |
+
# Initialize models only if at least one chunk needs inference.
|
| 33 |
+
chunk_count = (capture["frame_count"] + config.chunk_size-1)//config.chunk_size
|
| 34 |
+
# A valid checksum means the failure was saved correctly, not that inference
|
| 35 |
+
# succeeded. Re-run failed chunks after a runtime/library repair.
|
| 36 |
+
def reusable(chunk_id):
|
| 37 |
+
name = f"chunk_{chunk_id:06d}"
|
| 38 |
+
manifest = cache.valid(name)
|
| 39 |
+
if manifest:
|
| 40 |
+
statuses = read_json(cache.root / f"{name}.json")["branch_status"]
|
| 41 |
+
if any(s["status"] in {"failed", "failed_preflight"} for s in statuses.values()):
|
| 42 |
+
return None
|
| 43 |
+
return manifest
|
| 44 |
+
pending = any(reusable(k) is None for k in range(chunk_count))
|
| 45 |
+
if pending:
|
| 46 |
+
pose = load("body_pose", config.body_pose_path, lambda p: RTMWPose(p, config.device))
|
| 47 |
+
person = load("person_detector", config.person_detector_path,
|
| 48 |
+
lambda p: YOLOXDetector(p, config.device, config.detector_threshold, [0]))
|
| 49 |
+
objects = load("object_detector", config.object_detector_path,
|
| 50 |
+
lambda p: YOLOXDetector(p, config.device, config.detector_threshold, [0, 32, 34]))
|
| 51 |
+
if config.endpoint_checkpoint_path:
|
| 52 |
+
from .learning import EndpointPredictor
|
| 53 |
+
endpoint=load("learned_endpoints",config.endpoint_checkpoint_path,lambda p:EndpointPredictor(p,config.endpoint_manifest_path,config.device))
|
| 54 |
+
state = {"person_box": None, "crop": None, "ball": None, "bat": None}
|
| 55 |
+
ball, bat = BallTracker(), BatTracker()
|
| 56 |
+
buffer, current, cached = [], -1, None
|
| 57 |
+
reviewed_contact = {e["frame_interval"][1]+1 for e in annotations.get("events", [])
|
| 58 |
+
if e["type"] == "contact" and e["state"] == "confirmed"}
|
| 59 |
+
def flush(chunk_id):
|
| 60 |
+
name = f"chunk_{chunk_id:06d}"
|
| 61 |
+
p = cache.root / f"{name}.json"
|
| 62 |
+
s = cache.root / f"{name}.state.json"
|
| 63 |
+
state["ball"], state["bat"] = ball.state, bat.snapshot()
|
| 64 |
+
atomic_json(p, {"frames": buffer, "branch_status": errors,
|
| 65 |
+
"runtime_environment": runtime_environment,
|
| 66 |
+
"annotator": annotations.get("annotator"), "topology": "rtmw133_native",
|
| 67 |
+
"track_id": "batter_0", "coordinate_space": capture["coordinate_space"]})
|
| 68 |
+
atomic_json(s, state)
|
| 69 |
+
cache.commit(name, [p, s], start_frame=buffer[0]["frame_id"], end_frame=buffer[-1]["frame_id"])
|
| 70 |
+
if progress:
|
| 71 |
+
progress(buffer[-1]["frame_id"] + 1, capture["frame_count"])
|
| 72 |
+
for frame_id, pts, base, image in iter_frames(video, capture["rotation_degrees"]):
|
| 73 |
+
chunk_id = frame_id//config.chunk_size
|
| 74 |
+
if chunk_id != current:
|
| 75 |
+
if current >= 0 and not cached:
|
| 76 |
+
flush(current)
|
| 77 |
+
buffer = []
|
| 78 |
+
current = chunk_id
|
| 79 |
+
cached = reusable(chunk_id)
|
| 80 |
+
if cached:
|
| 81 |
+
state = read_json(cache.root / f"chunk_{chunk_id:06d}.state.json")
|
| 82 |
+
ball, bat = BallTracker(state["ball"]), BatTracker(state["bat"])
|
| 83 |
+
prior = read_json(cache.root / f"chunk_{chunk_id:06d}.json")
|
| 84 |
+
# Keep current initialization results when later chunks need a
|
| 85 |
+
# retry; cached status must not overwrite the repaired runtime.
|
| 86 |
+
if not pending:
|
| 87 |
+
errors = prior["branch_status"]
|
| 88 |
+
if cached:
|
| 89 |
+
# Restore the final image needed for LK at the next non-cached chunk.
|
| 90 |
+
if frame_id == cached["end_frame"]:
|
| 91 |
+
import cv2
|
| 92 |
+
bat.previous_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 93 |
+
if progress:
|
| 94 |
+
progress(frame_id + 1, capture["frame_count"])
|
| 95 |
+
continue
|
| 96 |
+
label = annotations.get("frames", {}).get(str(frame_id), {})
|
| 97 |
+
if label.get("crop"):
|
| 98 |
+
state["crop"] = label["crop"]
|
| 99 |
+
proposals = []
|
| 100 |
+
try:
|
| 101 |
+
if objects:
|
| 102 |
+
proposals = objects(image)
|
| 103 |
+
except Exception as e:
|
| 104 |
+
errors["object_detector"] = {"status": "failed", "reason": str(e)[:300]}
|
| 105 |
+
objects = None
|
| 106 |
+
selected = None
|
| 107 |
+
people_count = None
|
| 108 |
+
if state["crop"]:
|
| 109 |
+
box = state["crop"]
|
| 110 |
+
selected = {"box": box, "score": None, "source": "manual_crop"}
|
| 111 |
+
else:
|
| 112 |
+
try:
|
| 113 |
+
candidates = person(image) if person else proposals
|
| 114 |
+
if person or objects:
|
| 115 |
+
people_count = sum(d["class_id"] == 0 for d in candidates)
|
| 116 |
+
selected = select_person(candidates, state["person_box"])
|
| 117 |
+
except Exception as e:
|
| 118 |
+
errors["person_detector"] = {"status": "failed", "reason": str(e)[:300]}
|
| 119 |
+
person = None
|
| 120 |
+
if selected:
|
| 121 |
+
state["person_box"] = selected["box"]
|
| 122 |
+
points, scores = np.full((133, 2), np.nan), np.full(133, np.nan)
|
| 123 |
+
states = ["unknown"]*133
|
| 124 |
+
if pose and selected:
|
| 125 |
+
try:
|
| 126 |
+
points, scores = pose(image, selected["box"])
|
| 127 |
+
states = ["model_inferred" if np.isfinite(points[k]).all() and scores[k] >= config.score_threshold else "unknown" for k in range(133)]
|
| 128 |
+
except Exception as e:
|
| 129 |
+
errors["body_pose"] = {"status": "failed", "reason": str(e)[:300]}
|
| 130 |
+
pose = None
|
| 131 |
+
for name, point in label.get("landmarks", {}).items():
|
| 132 |
+
i = RTMW_CORE[name]
|
| 133 |
+
points[i], states[i] = point, "manual"
|
| 134 |
+
for name in label.get("occluded_landmarks", []):
|
| 135 |
+
if name not in RTMW_CORE:
|
| 136 |
+
raise ValueError(f"Unknown occluded landmark: {name}")
|
| 137 |
+
states[RTMW_CORE[name]] = "occluded"
|
| 138 |
+
manual_bat = [label["knob"], label["barrel"]] if label.get("knob") is not None and label.get("barrel") is not None else None
|
| 139 |
+
bat_result = bat.update(image, proposals, manual_bat)
|
| 140 |
+
if endpoint and manual_bat is None:
|
| 141 |
+
boxes=[d["box"] for d in proposals if d["class_id"]==34]
|
| 142 |
+
if len(boxes)==1:
|
| 143 |
+
try:
|
| 144 |
+
predicted=endpoint(image,boxes[0])
|
| 145 |
+
if predicted:bat_result=predicted;bat.points=np.array(predicted["points"],np.float32)
|
| 146 |
+
except Exception as error:
|
| 147 |
+
errors["learned_endpoints"]={"status":"failed","reason":str(error)[:300]};endpoint=None
|
| 148 |
+
if label.get("bat_occluded"):
|
| 149 |
+
bat_result = {"points": None, "states": ["occluded"]*2, "method": "reviewed_occlusion"}
|
| 150 |
+
bat.points = None
|
| 151 |
+
t = capture["frames"][frame_id]["playback_s"]
|
| 152 |
+
reset = frame_id in reviewed_contact or possible_impact_reset(proposals, bat_result)
|
| 153 |
+
ball_result = ball.update(proposals, t, frame_id, label.get("ball"), reset)
|
| 154 |
+
if reset:
|
| 155 |
+
ball_result["predictor_reset"] = "possible_interaction_only_not_confirmed_contact"
|
| 156 |
+
if label.get("ball_occluded"):
|
| 157 |
+
ball_result = {"point": None, "state": "occluded", "score": None}
|
| 158 |
+
import cv2
|
| 159 |
+
visual=cv2.resize(cv2.cvtColor(image,cv2.COLOR_BGR2GRAY),(8,8)).astype(float).ravel()/255.
|
| 160 |
+
buffer.append({"frame_id": frame_id, "track_id": "batter_0", "body_points": points, "visual_feature":visual,
|
| 161 |
+
"body_scores": scores, "body_states": states,
|
| 162 |
+
"people_count": people_count,
|
| 163 |
+
"visibility_review": label.get("occluded_landmarks", []),
|
| 164 |
+
"person": selected, "proposals": proposals, "bat": bat_result, "ball": ball_result})
|
| 165 |
+
if buffer and not cached:
|
| 166 |
+
flush(current)
|
| 167 |
+
return collect_observations(cache, chunk_count)
|
| 168 |
+
|
| 169 |
+
def collect_observations(cache, chunk_count):
|
| 170 |
+
frames, statuses, environment = [], {}, None
|
| 171 |
+
for k in range(chunk_count):
|
| 172 |
+
name = f"chunk_{k:06d}"
|
| 173 |
+
if not cache.valid(name):
|
| 174 |
+
raise ValueError(f"Unverified observation chunk {k}")
|
| 175 |
+
chunk = read_json(cache.root / f"{name}.json")
|
| 176 |
+
frames.extend(chunk["frames"])
|
| 177 |
+
statuses.update(chunk["branch_status"])
|
| 178 |
+
environment = chunk.get("runtime_environment", environment)
|
| 179 |
+
return {"frames": frames, "branch_status": statuses, "topology": "rtmw133_native",
|
| 180 |
+
"runtime_environment": environment,
|
| 181 |
+
"track_id": "batter_0", "provenance": "human_assisted" if any(
|
| 182 |
+
"manual" in f["body_states"] or "manual" in f["bat"]["states"] or f["ball"]["state"] == "manual"
|
| 183 |
+
or (f["person"] and f["person"].get("source") == "manual_crop") for f in frames) else "automatic"}
|
baseball_batting/optional_preflight.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Separate heavy-worker smoke checks with observed results, never package-name qualification."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import tempfile
|
| 4 |
+
import time
|
| 5 |
+
import numpy as np
|
| 6 |
+
from .storage import atomic_json
|
| 7 |
+
from .preflight import environment_snapshot
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def run(config,directory):
|
| 11 |
+
start=time.perf_counter();tests={}
|
| 12 |
+
try:
|
| 13 |
+
import torch
|
| 14 |
+
if config.device=="cuda" and not torch.cuda.is_available():raise ValueError("cuda_unavailable")
|
| 15 |
+
x=torch.tensor([1.],requires_grad=True,device=config.device);(x*x).sum().backward()
|
| 16 |
+
tests["torch"]={"status":"ready","device":str(x.device),"gradient":float(x.grad)}
|
| 17 |
+
if config.mhr_path:
|
| 18 |
+
asset=torch.jit.load(config.mhr_path,map_location=config.device).eval()
|
| 19 |
+
shape=torch.zeros(1,45,device=config.device,requires_grad=True)
|
| 20 |
+
motion=torch.zeros(1,204,device=config.device,requires_grad=True)
|
| 21 |
+
vertices,skeleton=asset(shape,motion,torch.zeros(1,72,device=config.device))
|
| 22 |
+
vertices.square().mean().backward()
|
| 23 |
+
if shape.grad is None or motion.grad is None or not torch.isfinite(motion.grad).all():raise ValueError("MHR differentiation failed")
|
| 24 |
+
tests["mhr"]={"status":"ready","test":"native_forward_and_gradient","vertices":list(vertices.shape),"skeleton":list(skeleton.shape),"native_units":"cm"}
|
| 25 |
+
del asset,vertices,skeleton
|
| 26 |
+
except Exception as error:tests["torch_mhr"]={"status":"failed_preflight","reason":str(error)[:250]}
|
| 27 |
+
try:
|
| 28 |
+
import yaml
|
| 29 |
+
from .anatomy import model_spec,build_opensim,forward_kinematics,weighted_ik
|
| 30 |
+
from tools.build_anatomical_model import reference_neutral
|
| 31 |
+
spec=model_spec(reference_neutral(),yaml.safe_load(Path(config.anatomical_config_path).read_text()))
|
| 32 |
+
model=build_opensim(spec);state=model.initSystem();q=np.zeros(35);q[3:6]=[.1,.2,1]
|
| 33 |
+
for i,c in enumerate(spec["coordinates"]):model.getCoordinateSet().get(c["name"]).setValue(state,float(q[i]),False)
|
| 34 |
+
model.realizePosition(state)
|
| 35 |
+
expected=forward_kinematics(spec,q)[0]
|
| 36 |
+
actual=np.array([[model.getMarkerSet().get(name).getLocationInGround(state).get(i) for i in range(3)] for name in spec["markers"]])
|
| 37 |
+
if np.max(np.abs(actual-expected))>1e-8:raise ValueError("OpenSim/FK convention mismatch")
|
| 38 |
+
with tempfile.TemporaryDirectory() as work:
|
| 39 |
+
target=np.repeat(expected[None],3,0);fit=weighted_ik(model,spec,target,np.ones(target.shape[:2]),np.arange(3)*.01,work)
|
| 40 |
+
error=max(np.linalg.norm(forward_kinematics(spec,f)[0]-expected,axis=-1).max() for f in fit)
|
| 41 |
+
if not np.isfinite(error) or error>.001:raise ValueError("OpenSim synthetic IK failed")
|
| 42 |
+
tests["anatomy"]={"status":"ready","test":"35DOF_FK_roundtrip_and_weighted_IK","max_error_m":float(error)}
|
| 43 |
+
except Exception as error:tests["anatomy"]={"status":"failed_preflight","reason":str(error)[:250]}
|
| 44 |
+
report={"environment":environment_snapshot(),"tests":tests,"elapsed_s":time.perf_counter()-start,
|
| 45 |
+
"qualification_scope":"dependency_and_synthetic_arithmetic_only","sam_full_image":"requires_accessible_assets_and_cuda_recording_run"}
|
| 46 |
+
Path(directory).mkdir(parents=True,exist_ok=True);atomic_json(Path(directory)/"optional_runtime_profile.json",report)
|
| 47 |
+
return report
|
baseball_batting/pipeline.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Orchestration calls isolated workers so model lifetimes end at stage boundaries."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
import os
|
| 6 |
+
from .config import EngineConfig
|
| 7 |
+
from .preflight import environment_snapshot
|
| 8 |
+
from .storage import StageCache, atomic_json, code_hash, digest, read_json, sha256_file
|
| 9 |
+
|
| 10 |
+
def run_engine(video, output_directory, config=None, metadata=None):
|
| 11 |
+
from .ingest import validate_metadata
|
| 12 |
+
config = (config or EngineConfig()).validate()
|
| 13 |
+
metadata = metadata or {}
|
| 14 |
+
validate_metadata(metadata)
|
| 15 |
+
video = Path(video).resolve()
|
| 16 |
+
if not video.is_file():
|
| 17 |
+
raise FileNotFoundError(video)
|
| 18 |
+
root = Path(output_directory).resolve()
|
| 19 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
model_hashes = {name: sha256_file(path) if path and Path(path).is_file() else None for name, path in
|
| 21 |
+
(("body_pose", config.body_pose_path), ("person_detector", config.person_detector_path),
|
| 22 |
+
("object_detector", config.object_detector_path), ("sam_checkpoint", config.sam_checkpoint),
|
| 23 |
+
("sam_config", config.sam_config), ("mhr", config.mhr_path),
|
| 24 |
+
("endpoint_checkpoint",config.endpoint_checkpoint_path),("endpoint_manifest",config.endpoint_manifest_path),
|
| 25 |
+
("event_checkpoint",config.event_checkpoint_path),("event_manifest",config.event_manifest_path),
|
| 26 |
+
("fitting_config",config.fitting_config_path),("anatomical_config",config.anatomical_config_path),
|
| 27 |
+
("quality_config",config.quality_config_path),("coaching_rules",config.coaching_rules_path))}
|
| 28 |
+
environment = environment_snapshot()
|
| 29 |
+
common = {"input_hash": sha256_file(video), "metadata": metadata, "code_hash": code_hash()}
|
| 30 |
+
ingest_key = digest(common)
|
| 31 |
+
ingestion = StageCache(root, "ingest", ingest_key)
|
| 32 |
+
annotations_hash = sha256_file(config.annotations_path) if config.annotations_path else None
|
| 33 |
+
observation_config = {k: v for k,v in config.to_dict().items() if k in {
|
| 34 |
+
"mode", "chunk_size", "device", "score_threshold", "detector_threshold", "stage_python"}}
|
| 35 |
+
observation_key = digest({"input_hash":common["input_hash"],"code_hash":common["code_hash"],
|
| 36 |
+
"rotation_override":metadata.get("rotation_degrees"),"config":observation_config,
|
| 37 |
+
"environment":environment,"models":{k:v for k,v in model_hashes.items() if k in
|
| 38 |
+
{"body_pose","person_detector","object_detector","endpoint_checkpoint","endpoint_manifest"}},
|
| 39 |
+
"annotations":annotations_hash})
|
| 40 |
+
observations = StageCache(root, "observations", observation_key)
|
| 41 |
+
request = {"video": str(video), "root": str(root), "config": config.to_dict(), "metadata": metadata,
|
| 42 |
+
"ingest_key": ingest_key, "observation_key": observation_key,
|
| 43 |
+
"model_hashes": model_hashes, "environment": environment, "code_hash": common["code_hash"]}
|
| 44 |
+
# Keep machine-specific paths out of exported artifacts.
|
| 45 |
+
request_file = root / ".worker_request.tmp"
|
| 46 |
+
atomic_json(request_file, request)
|
| 47 |
+
def worker(stage):
|
| 48 |
+
interpreter = config.stage_python.get(stage, sys.executable)
|
| 49 |
+
env = dict(os.environ)
|
| 50 |
+
# Colab's inline backend belongs to its notebook environment, not the
|
| 51 |
+
# isolated model workers. SAM imports plotting dependencies during setup.
|
| 52 |
+
env["MPLBACKEND"] = "Agg"
|
| 53 |
+
repo = str(Path(__file__).parent.parent)
|
| 54 |
+
env["PYTHONPATH"] = repo + (os.pathsep+env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
|
| 55 |
+
result = subprocess.run([interpreter, "-m", "baseball_batting.worker", stage, str(request_file)],
|
| 56 |
+
env=env, capture_output=True, text=True)
|
| 57 |
+
if result.returncode:
|
| 58 |
+
# Workers only print their sanitized error class/message.
|
| 59 |
+
raise RuntimeError(f"{stage} worker failed: {result.stderr[-1000:]}")
|
| 60 |
+
try:
|
| 61 |
+
if not ingestion.valid("capture"):
|
| 62 |
+
worker("ingest")
|
| 63 |
+
worker("observations")
|
| 64 |
+
if config.body3d_enabled:
|
| 65 |
+
try:
|
| 66 |
+
worker("body3d")
|
| 67 |
+
except (RuntimeError, OSError) as error:
|
| 68 |
+
atomic_json(root / "body3d_status.json", {"status": "failed", "reason": "isolated_worker_failed",
|
| 69 |
+
"detail": str(error)[:300]})
|
| 70 |
+
for stage, enabled in (("temporal3d",config.temporal3d_enabled),("anatomy",config.anatomy_enabled and config.temporal3d_enabled)):
|
| 71 |
+
if enabled:
|
| 72 |
+
try: worker(stage)
|
| 73 |
+
except (RuntimeError,OSError) as error:
|
| 74 |
+
atomic_json(root / (stage+"_status.json"),{"status":"failed","reason":"isolated_worker_failed","detail":str(error)[:300]})
|
| 75 |
+
if config.bat_3d_mode != "disabled": worker("bat3d")
|
| 76 |
+
if config.learned_events_enabled: worker("learned_events")
|
| 77 |
+
worker("report")
|
| 78 |
+
result = read_json(root / "result.json")
|
| 79 |
+
session_id = metadata.get("session_id") or common["input_hash"][:12]
|
| 80 |
+
history = root.parent / "history.json"
|
| 81 |
+
records = read_json(history) if history.exists() else []
|
| 82 |
+
records = [r for r in records if not (r["session_id"] == session_id and r["player_id"] == metadata.get("player_id"))]
|
| 83 |
+
records.append({"session_id": session_id, "player_id": metadata.get("player_id"),
|
| 84 |
+
"input_sha256": common["input_hash"], "engine_code_hash": common["code_hash"],
|
| 85 |
+
"result_path": str(root.name)+"/result.json", "metric_definition_version": "1.0",
|
| 86 |
+
"review_status": result["provenance"], "status": result["status"]})
|
| 87 |
+
atomic_json(history, records)
|
| 88 |
+
return result
|
| 89 |
+
finally:
|
| 90 |
+
if request_file.exists():
|
| 91 |
+
request_file.unlink()
|
baseball_batting/preflight.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timezone
|
| 2 |
+
from importlib import metadata, util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import platform
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
from .storage import atomic_json, sha256_file
|
| 10 |
+
|
| 11 |
+
PACKAGES = ("numpy", "scipy", "opencv-python-headless", "av", "PyYAML",
|
| 12 |
+
"rtmlib", "onnxruntime", "onnxruntime-gpu", "torch", "torchvision", "opensim",
|
| 13 |
+
"nvidia-cuda-runtime-cu12", "nvidia-cublas-cu12", "nvidia-cudnn-cu12",
|
| 14 |
+
"nvidia-cufft-cu12", "nvidia-curand-cu12", "nvidia-nvjitlink-cu12")
|
| 15 |
+
|
| 16 |
+
def environment_snapshot():
|
| 17 |
+
versions = {}
|
| 18 |
+
for name in PACKAGES:
|
| 19 |
+
try:
|
| 20 |
+
versions[name] = metadata.version(name)
|
| 21 |
+
except metadata.PackageNotFoundError:
|
| 22 |
+
versions[name] = None
|
| 23 |
+
gpu = {"available": False, "reason": "nvidia_smi_unavailable"}
|
| 24 |
+
if shutil.which("nvidia-smi"):
|
| 25 |
+
result = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total",
|
| 26 |
+
"--format=csv,noheader"], capture_output=True, text=True)
|
| 27 |
+
gpu = {"available": result.returncode == 0, "summary": result.stdout.strip()}
|
| 28 |
+
onnx = {"status": "unavailable"}
|
| 29 |
+
try:
|
| 30 |
+
import onnxruntime as ort
|
| 31 |
+
onnx = {"version": ort.__version__, "providers": ort.get_available_providers(),
|
| 32 |
+
"module_path": ort.__file__}
|
| 33 |
+
except Exception as error:
|
| 34 |
+
onnx["reason"] = str(error)[:300]
|
| 35 |
+
return {"python": platform.python_version(), "executable": sys.executable, "onnxruntime": onnx,
|
| 36 |
+
"platform": platform.platform(), "packages": versions, "gpu": gpu,
|
| 37 |
+
"ffprobe": bool(shutil.which("ffprobe"))}
|
| 38 |
+
|
| 39 |
+
def run_preflight(config, directory):
|
| 40 |
+
from .detection import YOLOXDetector
|
| 41 |
+
import numpy as np
|
| 42 |
+
start = time.perf_counter()
|
| 43 |
+
snapshot = environment_snapshot()
|
| 44 |
+
tests = {}
|
| 45 |
+
for name, module in (("numpy", "numpy"), ("scipy", "scipy"), ("opencv", "cv2"), ("pyav", "av")):
|
| 46 |
+
try:
|
| 47 |
+
__import__(module)
|
| 48 |
+
tests[name] = {"status": "ready", "test": "import"}
|
| 49 |
+
except Exception as e:
|
| 50 |
+
tests[name] = {"status": "unavailable", "reason": type(e).__name__}
|
| 51 |
+
for name, path, classes in (("person_detector", config.person_detector_path, [0]),
|
| 52 |
+
("object_detector", config.object_detector_path, [0, 32, 34])):
|
| 53 |
+
if not path:
|
| 54 |
+
tests[name] = {"status": "unavailable", "reason": "artifact_not_configured"}
|
| 55 |
+
continue
|
| 56 |
+
try:
|
| 57 |
+
detector = YOLOXDetector(path, config.device, classes=classes)
|
| 58 |
+
detector(np.zeros((640, 640, 3), dtype=np.uint8))
|
| 59 |
+
tests[name] = {"status": "ready", "test": "standalone_onnx_inference",
|
| 60 |
+
"sha256": sha256_file(path), "providers": detector.providers}
|
| 61 |
+
del detector
|
| 62 |
+
except Exception as e:
|
| 63 |
+
tests[name] = {"status": "failed_preflight", "reason": str(e)[:300]}
|
| 64 |
+
if config.body_pose_path:
|
| 65 |
+
try:
|
| 66 |
+
from .body2d import RTMWPose
|
| 67 |
+
pose = RTMWPose(config.body_pose_path, config.device)
|
| 68 |
+
points, scores = pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480])
|
| 69 |
+
if points.shape != (133, 2) or scores.shape != (133,):
|
| 70 |
+
raise ValueError("RTMW native topology mismatch")
|
| 71 |
+
tests["body_pose"] = {"status": "ready", "test": "133_point_shape_and_inference",
|
| 72 |
+
"sha256": sha256_file(config.body_pose_path)}
|
| 73 |
+
tests["body_pose"]["providers"] = pose.session.get_providers()
|
| 74 |
+
del pose
|
| 75 |
+
except Exception as e:
|
| 76 |
+
tests["body_pose"] = {"status": "failed_preflight", "reason": str(e)[:300]}
|
| 77 |
+
else:
|
| 78 |
+
tests["body_pose"] = {"status": "unavailable", "reason": "artifact_not_configured"}
|
| 79 |
+
tests["body3d"] = {"status": "candidate" if config.body3d_enabled else "disabled_by_configuration",
|
| 80 |
+
"reason": "full_hand_and_mhr_tests_require_separate_3d_worker"}
|
| 81 |
+
tests["anatomy"] = {"status": "candidate" if config.body3d_enabled and config.anatomy_enabled else "disabled_by_configuration",
|
| 82 |
+
"reason": "run_preflight_optional_in_selected_worker"}
|
| 83 |
+
tests["learned_events"] = {"status": "unavailable" if config.learned_events_enabled else "disabled_by_configuration",
|
| 84 |
+
"reason": "no_qualified_checkpoint"}
|
| 85 |
+
report = {"environment": snapshot, "tests": tests, "vision_ready": vision_ready(tests),
|
| 86 |
+
"requested_device": config.device, "elapsed_s": time.perf_counter()-start,
|
| 87 |
+
"date_utc": datetime.now(timezone.utc).isoformat(),
|
| 88 |
+
"validation": "dependency execution only; no baseball accuracy claim"}
|
| 89 |
+
dependency_check = subprocess.run([sys.executable, "-m", "pip", "check"], capture_output=True, text=True)
|
| 90 |
+
report["dependency_metadata_check"] = {"status": "passed" if dependency_check.returncode == 0 else "failed",
|
| 91 |
+
"details": dependency_check.stdout.splitlines()}
|
| 92 |
+
root = Path(directory)
|
| 93 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
atomic_json(root / "runtime_profile.json", report)
|
| 95 |
+
# A real package inventory, not a claim that every optional branch passed.
|
| 96 |
+
result = subprocess.run([sys.executable, "-m", "pip", "freeze", "--all"], capture_output=True, text=True)
|
| 97 |
+
if all(tests[x]["status"] == "ready" for x in ("numpy", "scipy", "opencv", "pyav")) and not result.returncode:
|
| 98 |
+
atomic_json(root / "environment.lock.json", {"environment": snapshot,
|
| 99 |
+
"freeze": result.stdout.splitlines(), "qualified_scope": "core_imports",
|
| 100 |
+
"branch_tests": tests})
|
| 101 |
+
return report
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def vision_ready(tests):
|
| 105 |
+
"""Pose needs a usable person proposal; object-only failure can be partial."""
|
| 106 |
+
return (all(tests.get(name, {}).get("status") == "ready" for name in
|
| 107 |
+
("numpy", "scipy", "opencv", "pyav", "body_pose"))
|
| 108 |
+
and any(tests.get(name, {}).get("status") == "ready" for name in
|
| 109 |
+
("person_detector", "object_detector")))
|
baseball_batting/reports.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full and partial exports share the same schema. All user text is HTML escaped."""
|
| 2 |
+
from fractions import Fraction
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import csv
|
| 5 |
+
import html
|
| 6 |
+
import os
|
| 7 |
+
import numpy as np
|
| 8 |
+
from .contracts import json_safe, RTMW_CORE
|
| 9 |
+
from .ingest import iter_frames
|
| 10 |
+
from .storage import atomic_json
|
| 11 |
+
|
| 12 |
+
BODY_EDGES = [(5,7),(7,9),(6,8),(8,10),(5,6),(5,11),(6,12),(11,12),(11,13),(13,15),(12,14),(14,16)]
|
| 13 |
+
|
| 14 |
+
def annotate_image(image, observation):
|
| 15 |
+
import cv2
|
| 16 |
+
image = image.copy()
|
| 17 |
+
points = np.array(observation["body_points"], dtype=float)
|
| 18 |
+
states = observation["body_states"]
|
| 19 |
+
valid = [s in {"model_inferred", "manual", "image_supported"} and np.isfinite(points[j]).all()
|
| 20 |
+
for j, s in enumerate(states)]
|
| 21 |
+
for a, b in BODY_EDGES:
|
| 22 |
+
if valid[a] and valid[b]:
|
| 23 |
+
cv2.line(image, tuple(np.rint(points[a]).astype(int)), tuple(np.rint(points[b]).astype(int)), (80,230,90), 2)
|
| 24 |
+
for j in RTMW_CORE.values():
|
| 25 |
+
if valid[j]:
|
| 26 |
+
color = (0,180,255) if states[j] == "manual" else (80,230,90)
|
| 27 |
+
cv2.circle(image, tuple(np.rint(points[j]).astype(int)), 3, color, -1)
|
| 28 |
+
bat = observation["bat"]
|
| 29 |
+
if bat["points"] is None:
|
| 30 |
+
for proposal in observation["proposals"]:
|
| 31 |
+
if proposal["class_id"] == 34:
|
| 32 |
+
a, b = np.rint(proposal["box"]).astype(int).reshape(2, 2)
|
| 33 |
+
cv2.rectangle(image, tuple(a), tuple(b), (255,150,70), 1)
|
| 34 |
+
cv2.putText(image, "bat proposal", tuple(a), cv2.FONT_HERSHEY_SIMPLEX, .35, (255,150,70), 1)
|
| 35 |
+
if bat["points"] is not None:
|
| 36 |
+
a, b = np.rint(bat["points"]).astype(int)
|
| 37 |
+
color = (0,200,255) if "manual" in bat["states"] else (255,150,70)
|
| 38 |
+
cv2.line(image, tuple(a), tuple(b), color, 2)
|
| 39 |
+
cv2.putText(image, "knob", tuple(a), cv2.FONT_HERSHEY_SIMPLEX, .35, color, 1)
|
| 40 |
+
cv2.putText(image, "barrel", tuple(b), cv2.FONT_HERSHEY_SIMPLEX, .35, color, 1)
|
| 41 |
+
if observation["ball"]["point"] is not None:
|
| 42 |
+
cv2.circle(image, tuple(np.rint(observation["ball"]["point"]).astype(int)), 4, (230,210,50), 1)
|
| 43 |
+
cv2.putText(image, f"Frame {observation['frame_id']} | research observations", (8,20),
|
| 44 |
+
cv2.FONT_HERSHEY_SIMPLEX, .5, (255,255,255), 1)
|
| 45 |
+
return image
|
| 46 |
+
|
| 47 |
+
def export_video(video, capture, observations, destination):
|
| 48 |
+
import av
|
| 49 |
+
frames = capture["frames"]
|
| 50 |
+
if any(f["pts"] is None or not f["time_base"] or {"duplicate_pts", "nonmonotonic_pts"} & set(f["flags"]) for f in frames):
|
| 51 |
+
return {"status": "unavailable", "reason": "source_pts_not_encodable_without_retiming"}
|
| 52 |
+
shape = frames[0]
|
| 53 |
+
if shape["width"] % 2 or shape["height"] % 2:
|
| 54 |
+
return {"status": "unavailable", "reason": "odd_dimensions_require_a_separately_recorded_export_transform"}
|
| 55 |
+
destination = Path(destination)
|
| 56 |
+
temporary = destination.with_suffix(".tmp.mp4")
|
| 57 |
+
base = Fraction(frames[0]["time_base"])
|
| 58 |
+
try:
|
| 59 |
+
with av.open(str(temporary), "w") as out:
|
| 60 |
+
stream = out.add_stream("libx264", rate=None)
|
| 61 |
+
stream.width, stream.height = shape["width"], shape["height"]
|
| 62 |
+
stream.pix_fmt = "yuv420p"
|
| 63 |
+
stream.time_base = base
|
| 64 |
+
stream.codec_context.time_base = base
|
| 65 |
+
stream.options = {"crf": "21", "preset": "fast", "bf": "0"}
|
| 66 |
+
for index, pts, time_base, image in iter_frames(video, capture["rotation_degrees"]):
|
| 67 |
+
frame = av.VideoFrame.from_ndarray(annotate_image(image, observations["frames"][index]), format="bgr24")
|
| 68 |
+
frame.pts = pts
|
| 69 |
+
frame.time_base = time_base
|
| 70 |
+
for packet in stream.encode(frame):
|
| 71 |
+
out.mux(packet)
|
| 72 |
+
for packet in stream.encode():
|
| 73 |
+
out.mux(packet)
|
| 74 |
+
# Verify all source presentation positions survived muxer time-base rescaling.
|
| 75 |
+
exported = list((pts, tb) for _, pts, tb, _ in iter_frames(temporary))
|
| 76 |
+
if len(exported) != len(frames):
|
| 77 |
+
raise ValueError("Export changed frame count")
|
| 78 |
+
for original, (pts, tb) in zip(frames, exported):
|
| 79 |
+
tolerance = max(float(tb), float(Fraction(original["time_base"])))
|
| 80 |
+
if abs(float(pts*tb)-original["playback_s"]) > tolerance:
|
| 81 |
+
raise ValueError("Export changed source presentation timing")
|
| 82 |
+
os.replace(temporary, destination)
|
| 83 |
+
return {"status": "complete", "path": destination.name, "audio": "not_included",
|
| 84 |
+
"timing": "source_pts_verified_within_muxer_tick"}
|
| 85 |
+
except Exception as e:
|
| 86 |
+
if temporary.exists():
|
| 87 |
+
temporary.unlink()
|
| 88 |
+
return {"status": "failed", "reason": str(e)[:300]}
|
| 89 |
+
|
| 90 |
+
def write_reports(root, result, curves):
|
| 91 |
+
root = Path(root)
|
| 92 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 93 |
+
atomic_json(root / "result.json", result)
|
| 94 |
+
tmp = root / "curves.tmp.npz"
|
| 95 |
+
np.savez_compressed(tmp, **curves)
|
| 96 |
+
tmp.replace(root / "curves.npz")
|
| 97 |
+
metrics = result["metrics"]
|
| 98 |
+
columns = ["metric_id", "value", "unit", "suitability", "unavailable_reason", "validation_status", "feedback_eligibility", "event_id", "uncertainty_kind", "geometry_source", "timing_source", "definition_version"]
|
| 99 |
+
with (root / "metrics.csv").open("w", newline="") as f:
|
| 100 |
+
writer = csv.DictWriter(f, fieldnames=columns)
|
| 101 |
+
writer.writeheader()
|
| 102 |
+
for m in metrics:
|
| 103 |
+
writer.writerow({k: m.get(k) for k in columns})
|
| 104 |
+
def esc(x):
|
| 105 |
+
return html.escape(str(x))
|
| 106 |
+
diagnostics = result.get("diagnostics", {})
|
| 107 |
+
coverage = ""
|
| 108 |
+
if diagnostics:
|
| 109 |
+
coverage = (f"<h2>Analysis coverage</h2><p class='notice'>{esc(diagnostics['message'])}</p>"
|
| 110 |
+
f"<p>Usable body observations: {diagnostics['body_frames']} / {diagnostics['frame_count']} frames. "
|
| 111 |
+
f"Bat endpoints: {diagnostics['bat_endpoint_frames']} frames. "
|
| 112 |
+
f"Ball observations: {diagnostics['ball_frames']} frames. "
|
| 113 |
+
f"Available measurements: {diagnostics.get('available_metrics', 0)}.</p>")
|
| 114 |
+
if diagnostics.get("source_note"):
|
| 115 |
+
coverage += f"<p class='notice'>{esc(diagnostics['source_note'])}</p>"
|
| 116 |
+
actions = []
|
| 117 |
+
if diagnostics.get("bat_box_frames", 0) and not diagnostics.get("bat_endpoint_frames", 0):
|
| 118 |
+
actions.append("Bat boxes were detected, but knob/barrel identity was not established. Supply a reviewed endpoint seed or a qualified trained endpoint checkpoint to activate endpoint tracking. Bat boxes are proposals, not measured endpoints.")
|
| 119 |
+
failed = [s for s in result["stages"].values() if s["status"] in {"failed", "failed_preflight"}]
|
| 120 |
+
if any("CUDA" in s.get("reason", "") for s in failed):
|
| 121 |
+
actions.append("Vision models failed on CUDA. Select a Colab GPU runtime, install the GPU profile with CUDA/cuDNN libraries, and pass vision preflight before rerunning. CPU projected analysis is available through cpu_reference.")
|
| 122 |
+
if result["stages"].get("body3d", {}).get("status") == "disabled_by_configuration":
|
| 123 |
+
actions.append("Body reconstruction was disabled. Enable BUILD_FULL_WORKER with accessible SAM assets for the 3D body stages.")
|
| 124 |
+
if not result["capture"]["physical_clock_known"]:
|
| 125 |
+
actions.append("Capture timing is undocumented. Physical durations and velocities remain unavailable until timing evidence is supplied.")
|
| 126 |
+
if result["capture"]["camera_stability"] != "fixed_verified":
|
| 127 |
+
actions.append("Camera stability is unverified. Hand path and motion measurements that require a fixed camera are withheld.")
|
| 128 |
+
next_steps = "<h2>What needs attention</h2><ul>" + "".join(f"<li>{esc(a)}</li>" for a in actions) + "</ul>" if actions else ""
|
| 129 |
+
rows = []
|
| 130 |
+
for m in metrics:
|
| 131 |
+
value = "Unavailable" if m["value"] is None else f"{m['value']:.3f} {esc(m['unit'])}"
|
| 132 |
+
rows.append(f"<tr><td>{esc(m['metric_id'])}</td><td>{value}</td><td>{esc(m['suitability'])}</td><td>{esc(m['unavailable_reason'] or m['validation_status'])}</td><td>{esc(m['evidence_frames'])}</td></tr>")
|
| 133 |
+
stages = "".join(f"<li>{esc(k)}: {esc(v['status'])} — {esc(v.get('reason', ''))}</li>" for k,v in result["stages"].items())
|
| 134 |
+
event_rows = "".join(f"<li>{esc(e['type'])}: {esc(e['state'])}; frames {esc(e['frame_interval'])}; {esc(e['method'])}; {esc(e['review_status'])}</li>" for e in result["events"])
|
| 135 |
+
findings = ""
|
| 136 |
+
for f in result["findings"]:
|
| 137 |
+
exercise=f.get("research_exercise")
|
| 138 |
+
detail=""
|
| 139 |
+
if exercise:
|
| 140 |
+
source=exercise["source"];url=source["url"]
|
| 141 |
+
if url.startswith("https://"):
|
| 142 |
+
detail=f"<p>Educational research hypothesis: {esc(exercise['instruction'])} <a href='{esc(url)}' rel='noreferrer'>{esc(source['title'])}</a>. Objective: {esc(exercise['objective'])}. Benefit not established.</p>"
|
| 143 |
+
findings+=f"<li>{esc(f['description'])}{detail}</li>"
|
| 144 |
+
page = f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 145 |
+
<title>Batting research report</title><style>body{{font:16px system-ui;max-width:1100px;margin:40px auto;padding:0 20px;color:#182435}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #ccd5df;padding:8px;text-align:left;vertical-align:top}}.notice{{background:#fff0ce;padding:16px}}td:last-child{{max-width:220px;overflow-wrap:anywhere}}</style>
|
| 146 |
+
<h1>Batting research report</h1>{coverage}{next_steps}<p class="notice">{esc(result['status'])} · {esc(result['provenance'])}. Reference validation pending. Expert review: not reviewed. Projected measurements describe this recording; no personalized corrective diagnosis is established.</p>
|
| 147 |
+
<p>Physical clock: {esc(result['capture']['timing_source'])}. Input SHA-256: {esc(result['capture']['input_sha256'])}</p>
|
| 148 |
+
<h2>Executed stages</h2><ul>{stages}</ul><h2>Events and review</h2><ul>{event_rows}</ul>
|
| 149 |
+
<h2>Metrics</h2><table><thead><tr><th>Definition</th><th>Value</th><th>Suitability</th><th>Reason / validation</th><th>Evidence frames</th></tr></thead><tbody>{''.join(rows)}</tbody></table>
|
| 150 |
+
<h2>Evidence-linked observations</h2><ul>{findings}</ul><p>Machine-readable provenance, definitions and timing are in result.json; continuous curves are in curves.npz.</p></html>'''
|
| 151 |
+
(root / "report.html").write_text(page)
|
| 152 |
+
return [root / n for n in ("result.json", "curves.npz", "metrics.csv", "report.html")]
|
baseball_batting/resources.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit artifact acquisition, separate from inference. No credentials in records."""
|
| 2 |
+
from datetime import datetime, timezone
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import shutil
|
| 5 |
+
import urllib.request
|
| 6 |
+
import zipfile
|
| 7 |
+
import yaml
|
| 8 |
+
from .storage import atomic_json, sha256_file, read_json
|
| 9 |
+
|
| 10 |
+
def fetch_artifact(resource_id, registry_path, directory):
|
| 11 |
+
resource = yaml.safe_load(Path(registry_path).read_text())["resources"][resource_id]
|
| 12 |
+
url = resource["source_url"]
|
| 13 |
+
if resource["type"] != "checkpoint" or not url.endswith((".zip", ".onnx")):
|
| 14 |
+
raise ValueError("This downloader only handles explicit public ONNX artifacts")
|
| 15 |
+
folder = Path(directory) / resource_id
|
| 16 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
archive = folder / url.rsplit("/", 1)[-1]
|
| 18 |
+
record_path = folder / "resource.json"
|
| 19 |
+
if record_path.is_file():
|
| 20 |
+
cached = read_json(record_path)
|
| 21 |
+
cached_model = Path(cached["artifact_path"])
|
| 22 |
+
if cached_model.resolve().is_relative_to(folder.resolve()) and cached_model.is_file() and cached.get("source_url") == url:
|
| 23 |
+
if sha256_file(cached_model) == cached.get("sha256") and (not resource.get("sha256") or resource["sha256"] == cached["sha256"]):
|
| 24 |
+
return cached
|
| 25 |
+
expected = resource.get("archive_sha256") or (resource.get("sha256") if archive.suffix != ".zip" else None)
|
| 26 |
+
if not archive.is_file() or (expected and sha256_file(archive) != expected):
|
| 27 |
+
temporary = archive.with_suffix(archive.suffix + ".tmp")
|
| 28 |
+
request = urllib.request.Request(url, headers={"User-Agent": "baseball-batting-research/0.1"})
|
| 29 |
+
with urllib.request.urlopen(request, timeout=120) as src, temporary.open("wb") as dst:
|
| 30 |
+
shutil.copyfileobj(src, dst)
|
| 31 |
+
if expected and sha256_file(temporary) != expected:
|
| 32 |
+
temporary.unlink()
|
| 33 |
+
raise ValueError("Published artifact checksum mismatch")
|
| 34 |
+
temporary.replace(archive)
|
| 35 |
+
if archive.suffix == ".zip":
|
| 36 |
+
with zipfile.ZipFile(archive) as z:
|
| 37 |
+
onnx_members = [i for i in z.infolist() if i.filename.endswith(".onnx")]
|
| 38 |
+
if len(onnx_members) != 1:
|
| 39 |
+
raise ValueError("Expected exactly one ONNX model in artifact")
|
| 40 |
+
info = onnx_members[0]
|
| 41 |
+
if info.file_size > 2_000_000_000:
|
| 42 |
+
raise ValueError("Unexpectedly large ONNX artifact")
|
| 43 |
+
# Flatten explicitly; never extract untrusted archive paths.
|
| 44 |
+
model = folder / "model.onnx"
|
| 45 |
+
temporary = model.with_suffix(".tmp")
|
| 46 |
+
with z.open(info) as src, temporary.open("wb") as dst:
|
| 47 |
+
shutil.copyfileobj(src, dst)
|
| 48 |
+
temporary.replace(model)
|
| 49 |
+
else:
|
| 50 |
+
model = archive
|
| 51 |
+
if resource.get("sha256") and sha256_file(model) != resource["sha256"]:
|
| 52 |
+
model.unlink()
|
| 53 |
+
raise ValueError("Extracted model checksum mismatch")
|
| 54 |
+
record = {**resource, "resource_id": resource_id, "access_status": "accessible",
|
| 55 |
+
"technical_test_status": "candidate", "sha256": sha256_file(model),
|
| 56 |
+
"archive_sha256": sha256_file(archive), "artifact_path": str(model.resolve()),
|
| 57 |
+
"date": datetime.now(timezone.utc).isoformat(),
|
| 58 |
+
"integrity_basis": "registry_sha256" if expected or resource.get("sha256") else "first_download_sha256_recorded",
|
| 59 |
+
"commercial_license_review": "deferred"}
|
| 60 |
+
atomic_json(record_path, record)
|
| 61 |
+
if archive.suffix == ".zip":
|
| 62 |
+
archive.unlink() # Keep its recorded hash, not a duplicate several-hundred-MB file.
|
| 63 |
+
return record
|
baseball_batting/review.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Notebook-native frame-by-frame review, using coordinates in the oriented image."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .ingest import iter_frames
|
| 5 |
+
from .storage import atomic_json
|
| 6 |
+
from .annotations import load_annotations
|
| 7 |
+
from .contracts import RTMW_CORE
|
| 8 |
+
|
| 9 |
+
def annotation_template(capture, annotator):
|
| 10 |
+
return {"schema_version": "1.0", "input_sha256": capture["input_sha256"],
|
| 11 |
+
"coordinate_space": capture["coordinate_space"], "annotator": annotator,
|
| 12 |
+
"frames": {}, "events": []}
|
| 13 |
+
|
| 14 |
+
def show_review_widget(video, capture, destination, annotator="operator"):
|
| 15 |
+
"""Lazy widget imports so the backend needs neither a web server nor UI packages."""
|
| 16 |
+
import cv2
|
| 17 |
+
import ipywidgets as widgets
|
| 18 |
+
from IPython.display import display, clear_output
|
| 19 |
+
destination = Path(destination)
|
| 20 |
+
labels = load_annotations(destination, capture["input_sha256"], capture["frame_count"],
|
| 21 |
+
capture["frames"][0]["width"], capture["frames"][0]["height"]) if destination.exists() else annotation_template(capture, annotator)
|
| 22 |
+
slider = widgets.IntSlider(min=0, max=capture["frame_count"]-1, description="Frame")
|
| 23 |
+
frame_json = widgets.Textarea(value="{}", description="Labels", layout=widgets.Layout(width="100%", height="180px"))
|
| 24 |
+
event_json = widgets.Textarea(value="[]", description="Events", layout=widgets.Layout(width="100%", height="140px"))
|
| 25 |
+
button = widgets.Button(description="Save reviewed labels")
|
| 26 |
+
image = widgets.Image(format="png")
|
| 27 |
+
output = widgets.Output()
|
| 28 |
+
import json
|
| 29 |
+
def display_frame(change=None):
|
| 30 |
+
k = slider.value
|
| 31 |
+
for frame_id, _, _, img in iter_frames(video, capture["rotation_degrees"]):
|
| 32 |
+
if frame_id == k:
|
| 33 |
+
# Coordinate grid helps read exact positions without a custom browser service.
|
| 34 |
+
h, w = img.shape[:2]
|
| 35 |
+
for x in range(0, w, 50):
|
| 36 |
+
cv2.line(img, (x,0), (x,h-1), (80,80,80), 1)
|
| 37 |
+
cv2.putText(img, str(x), (x,15), cv2.FONT_HERSHEY_SIMPLEX, .4, (255,255,255), 1)
|
| 38 |
+
for y in range(50, h, 50):
|
| 39 |
+
cv2.line(img, (0,y), (w-1,y), (80,80,80), 1)
|
| 40 |
+
cv2.putText(img, str(y), (0,y), cv2.FONT_HERSHEY_SIMPLEX, .4, (255,255,255), 1)
|
| 41 |
+
image.value = cv2.imencode(".png", img)[1].tobytes()
|
| 42 |
+
break
|
| 43 |
+
frame_json.value = json.dumps(labels["frames"].get(str(k), {}), indent=2)
|
| 44 |
+
event_json.value = json.dumps(labels["events"], indent=2)
|
| 45 |
+
def save(_):
|
| 46 |
+
with output:
|
| 47 |
+
clear_output()
|
| 48 |
+
try:
|
| 49 |
+
candidate = dict(labels)
|
| 50 |
+
candidate["frames"] = {**labels["frames"], str(slider.value): json.loads(frame_json.value)}
|
| 51 |
+
candidate["events"] = json.loads(event_json.value)
|
| 52 |
+
temp = destination.with_suffix(".review.tmp.json")
|
| 53 |
+
atomic_json(temp, candidate)
|
| 54 |
+
try:
|
| 55 |
+
load_annotations(temp, capture["input_sha256"], capture["frame_count"],
|
| 56 |
+
capture["frames"][0]["width"], capture["frames"][0]["height"])
|
| 57 |
+
finally:
|
| 58 |
+
temp.unlink(missing_ok=True)
|
| 59 |
+
atomic_json(destination, candidate)
|
| 60 |
+
labels.update(candidate)
|
| 61 |
+
print(f"Saved frame {slider.value} and reviewed events")
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"Labels not saved: {e}")
|
| 64 |
+
slider.observe(display_frame, names="value")
|
| 65 |
+
button.on_click(save)
|
| 66 |
+
display_frame()
|
| 67 |
+
display(widgets.VBox([slider, image, frame_json, event_json, button, output]))
|
| 68 |
+
return labels
|
| 69 |
+
|
baseball_batting/sensitivity.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Documented perturbation experiments; their spread is not an accuracy interval."""
|
| 2 |
+
import copy
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .metrics import continuous_curves, summarize
|
| 5 |
+
from .contracts import RTMW_CORE
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def apply_image_sensitivity(metrics,observations,capture,events):
|
| 9 |
+
supplied=capture["metadata"].get("uncertainty",{})
|
| 10 |
+
magnitude=supplied.get("landmark_pixel_perturbation")
|
| 11 |
+
if not supplied.get("source") or not isinstance(magnitude,(int,float)) or not np.isfinite(magnitude) or magnitude<=0:return
|
| 12 |
+
scenarios=[]
|
| 13 |
+
# Opposing endpoint/joint perturbations alter geometry rather than translating
|
| 14 |
+
# the whole skeleton, which would misleadingly report zero angle sensitivity.
|
| 15 |
+
for sign in (-1,1):
|
| 16 |
+
scenario=copy.deepcopy(observations)
|
| 17 |
+
for frame in scenario["frames"]:
|
| 18 |
+
points=np.array(frame["body_points"],float)
|
| 19 |
+
for j in RTMW_CORE.values():points[j]+=sign*magnitude*np.array([1 if j%2 else -1,1 if j%3 else -1])/np.sqrt(2)
|
| 20 |
+
frame["body_points"]=points.tolist()
|
| 21 |
+
scenarios.append({m.metric_id:m.value for m in summarize(continuous_curves(scenario,capture),scenario,capture,events)})
|
| 22 |
+
for metric in metrics:
|
| 23 |
+
values=[s.get(metric.metric_id) for s in scenarios]
|
| 24 |
+
if metric.value is None or any(v is None for v in values):continue
|
| 25 |
+
metric.sensitivity={"source":supplied["source"],"method":"opposing_xy_landmark_perturbation_v1",
|
| 26 |
+
"input_magnitude_px":magnitude,"maximum_value_change":max(abs(v-metric.value) for v in values),
|
| 27 |
+
"unit":metric.unit,"interpretation":"two_scenarios_not_calibrated_error_bounds"}
|
| 28 |
+
metric.uncertainty_kind="documented_input_sensitivity"
|
baseball_batting/storage.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Atomic manifests, input-sensitive keys and checksummed chunk recovery."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import tempfile
|
| 7 |
+
import zipfile
|
| 8 |
+
from .contracts import json_safe
|
| 9 |
+
|
| 10 |
+
def sha256_file(path):
|
| 11 |
+
h = hashlib.sha256()
|
| 12 |
+
with open(path, "rb") as f:
|
| 13 |
+
for block in iter(lambda: f.read(1024 * 1024), b""):
|
| 14 |
+
h.update(block)
|
| 15 |
+
return h.hexdigest()
|
| 16 |
+
|
| 17 |
+
def digest(value):
|
| 18 |
+
return hashlib.sha256(json.dumps(json_safe(value), sort_keys=True,
|
| 19 |
+
allow_nan=False, separators=(",", ":")).encode()).hexdigest()
|
| 20 |
+
|
| 21 |
+
def code_hash():
|
| 22 |
+
root = Path(__file__).parent
|
| 23 |
+
return digest({p.name: sha256_file(p) for p in sorted(root.glob("*.py"))})
|
| 24 |
+
|
| 25 |
+
def atomic_json(path, value):
|
| 26 |
+
path = Path(path)
|
| 27 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
fd, temp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
|
| 29 |
+
try:
|
| 30 |
+
with os.fdopen(fd, "w") as f:
|
| 31 |
+
json.dump(json_safe(value), f, indent=2, sort_keys=True, allow_nan=False)
|
| 32 |
+
f.flush()
|
| 33 |
+
os.fsync(f.fileno())
|
| 34 |
+
os.replace(temp, path)
|
| 35 |
+
finally:
|
| 36 |
+
if os.path.exists(temp):
|
| 37 |
+
os.unlink(temp)
|
| 38 |
+
|
| 39 |
+
def read_json(path):
|
| 40 |
+
return json.loads(Path(path).read_text())
|
| 41 |
+
|
| 42 |
+
class StageCache:
|
| 43 |
+
def __init__(self, root, stage, key):
|
| 44 |
+
self.root = Path(root) / "stages" / stage / key
|
| 45 |
+
self.root.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
self.key = key
|
| 47 |
+
self.stage = stage
|
| 48 |
+
|
| 49 |
+
def valid(self, name):
|
| 50 |
+
manifest_path = self.root / f"{name}.manifest.json"
|
| 51 |
+
if not manifest_path.exists():
|
| 52 |
+
return None
|
| 53 |
+
try:
|
| 54 |
+
m = read_json(manifest_path)
|
| 55 |
+
if m.get("status") != "complete" or m.get("key") != self.key:
|
| 56 |
+
return None
|
| 57 |
+
for relative, checksum in m["artifacts"].items():
|
| 58 |
+
p = (self.root / relative).resolve()
|
| 59 |
+
if not p.is_relative_to(self.root.resolve()) or not p.is_file():
|
| 60 |
+
return None
|
| 61 |
+
if sha256_file(p) != checksum:
|
| 62 |
+
return None
|
| 63 |
+
return m
|
| 64 |
+
except (OSError, ValueError, KeyError):
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
def commit(self, name, artifacts, **details):
|
| 68 |
+
m = {"stage": self.stage, "key": self.key, "status": "complete",
|
| 69 |
+
"artifacts": {str(Path(p).relative_to(self.root)): sha256_file(p)
|
| 70 |
+
for p in artifacts}, **details}
|
| 71 |
+
atomic_json(self.root / f"{name}.manifest.json", m)
|
| 72 |
+
return m
|
| 73 |
+
|
| 74 |
+
def failure(self, reason, detail):
|
| 75 |
+
atomic_json(self.root / "failure.json", {"stage": self.stage, "key": self.key,
|
| 76 |
+
"status": "failed", "reason": reason, "detail": str(detail)[:1000]})
|
| 77 |
+
|
| 78 |
+
def export_archive(root, destination):
|
| 79 |
+
"""Export results and verified state only. Input videos/credentials are never bundled."""
|
| 80 |
+
root, destination = Path(root).resolve(), Path(destination).resolve()
|
| 81 |
+
verified=set()
|
| 82 |
+
stages=root/"stages"
|
| 83 |
+
if stages.exists():
|
| 84 |
+
for manifest in stages.rglob("*.manifest.json"):
|
| 85 |
+
try:
|
| 86 |
+
record=read_json(manifest)
|
| 87 |
+
cache=StageCache(root,record["stage"],record["key"])
|
| 88 |
+
if cache.valid(manifest.name.removesuffix(".manifest.json")):
|
| 89 |
+
verified.add(manifest.resolve())
|
| 90 |
+
verified.update((manifest.parent/name).resolve() for name in record["artifacts"])
|
| 91 |
+
except (ValueError,KeyError,OSError):continue
|
| 92 |
+
with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as z:
|
| 93 |
+
for p in sorted(root.rglob("*")):
|
| 94 |
+
if not p.is_file() or p.resolve()==destination or ".tmp" in p.name:continue
|
| 95 |
+
if stages in p.parents and p.resolve() not in verified:continue
|
| 96 |
+
if p.name.startswith("."):continue
|
| 97 |
+
if p.is_file():
|
| 98 |
+
z.write(p, p.relative_to(root))
|
| 99 |
+
return destination
|
baseball_batting/temporal3d.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared-shape differentiable MHR sequence fitting, independent of SAM inference lifetime."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .contracts import RTMW_CORE
|
| 5 |
+
from .motion import contiguous_segments
|
| 6 |
+
from .storage import StageCache, atomic_json, digest, read_json, sha256_file
|
| 7 |
+
|
| 8 |
+
MHR_CORE = {"nose": 0, "left_shoulder": 5, "right_shoulder": 6, "left_elbow": 7,
|
| 9 |
+
"right_elbow": 8, "left_hip": 9, "right_hip": 10, "left_knee": 11,
|
| 10 |
+
"right_knee": 12, "left_ankle": 13, "right_ankle": 14,
|
| 11 |
+
"left_big_toe": 15, "left_small_toe": 16, "left_heel": 17,
|
| 12 |
+
"right_big_toe": 18, "right_small_toe": 19, "right_heel": 20,
|
| 13 |
+
"right_wrist": 41, "left_wrist": 62}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MHRForward:
|
| 17 |
+
def __init__(self, asset, adapter, device):
|
| 18 |
+
import torch
|
| 19 |
+
self.torch = torch
|
| 20 |
+
self.device = device
|
| 21 |
+
self.model = torch.jit.load(str(asset), map_location=device).eval()
|
| 22 |
+
for parameter in self.model.parameters():
|
| 23 |
+
parameter.requires_grad_(False)
|
| 24 |
+
data = np.load(adapter, allow_pickle=False)
|
| 25 |
+
indices = torch.tensor(np.stack([data["regressor_rows"], data["regressor_columns"]]), device=device)
|
| 26 |
+
values = torch.tensor(data["regressor_values"], device=device, dtype=torch.float32)
|
| 27 |
+
self.regressor = torch.sparse_coo_tensor(indices, values, tuple(data["regressor_shape"]), device=device).coalesce()
|
| 28 |
+
self.flip = torch.tensor([1., -1., -1.], device=device)
|
| 29 |
+
|
| 30 |
+
def __call__(self, shape, motion, scales, camera):
|
| 31 |
+
torch = self.torch
|
| 32 |
+
parameters = torch.cat([motion, scales.expand(len(motion), -1)], dim=1)
|
| 33 |
+
vertices, skeleton = self.model(shape.expand(len(motion), -1), parameters,
|
| 34 |
+
torch.zeros(len(motion), 72, device=motion.device))
|
| 35 |
+
combined = torch.cat([vertices, skeleton[..., :3]], dim=1) / 100
|
| 36 |
+
landmarks = torch.sparse.mm(self.regressor, combined.transpose(0, 1).reshape(combined.shape[1], -1))
|
| 37 |
+
landmarks = landmarks.reshape(70, len(motion), 3).transpose(0, 1)
|
| 38 |
+
return landmarks*self.flip + camera[:, None, :]
|
| 39 |
+
|
| 40 |
+
def neutral_height(self,shape,scales):
|
| 41 |
+
torch=self.torch
|
| 42 |
+
parameters=torch.cat([torch.zeros(1,136,device=self.device),scales[None]],1)
|
| 43 |
+
vertices,_=self.model(shape[None],parameters,torch.zeros(1,72,device=self.device))
|
| 44 |
+
return (vertices[...,1].max()-vertices[...,1].min())/100
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def fit_sequence(forward, initial, pixels, weights, times, settings, limits=None, temporal_factor=1., frame_ids=None):
|
| 48 |
+
import torch
|
| 49 |
+
device = initial["motion"].device
|
| 50 |
+
motion0 = initial["motion"].detach()
|
| 51 |
+
motion = torch.nn.Parameter(motion0[:, 3:].clone())
|
| 52 |
+
shape0, scale0 = initial["shape"].median(dim=0).values, initial["scales"].median(dim=0).values
|
| 53 |
+
shape, scales = torch.nn.Parameter(shape0.clone()), torch.nn.Parameter(scale0.clone())
|
| 54 |
+
camera = torch.nn.Parameter(initial["camera"].clone())
|
| 55 |
+
pixels = torch.as_tensor(pixels, dtype=torch.float32, device=device)
|
| 56 |
+
weights = torch.as_tensor(weights, dtype=torch.float32, device=device)
|
| 57 |
+
safe_pixels = torch.nan_to_num(pixels)
|
| 58 |
+
k = initial["intrinsics"]
|
| 59 |
+
target3d = initial["keypoints"].detach()
|
| 60 |
+
time = torch.as_tensor(times, dtype=torch.float32, device=device)
|
| 61 |
+
scale_px = settings["robust_pixel_scale"]
|
| 62 |
+
temporal_weight = settings["temporal_weight"]*temporal_factor
|
| 63 |
+
initial_weights = initial.get("valid", torch.ones(len(motion), device=device))
|
| 64 |
+
ids = np.arange(len(motion)) if frame_ids is None else np.asarray(frame_ids)
|
| 65 |
+
triples = torch.as_tensor((np.diff(ids)[:-1] == 1) & (np.diff(ids)[1:] == 1), device=device)
|
| 66 |
+
parameters = [motion, shape, scales, camera]
|
| 67 |
+
|
| 68 |
+
def evaluate():
|
| 69 |
+
terms = {"reprojection": [], "initializer": [], "cheirality": []}
|
| 70 |
+
points = []
|
| 71 |
+
for a in range(0, len(motion), settings["batch_size"]):
|
| 72 |
+
b = min(a+settings["batch_size"], len(motion))
|
| 73 |
+
# Native root translation remains fixed; camera translation supplies the single translation gauge.
|
| 74 |
+
full_motion = torch.cat([motion0[a:b, :3], motion[a:b]], dim=1)
|
| 75 |
+
xyz = forward(shape, full_motion, scales, camera[a:b])
|
| 76 |
+
points.append(xyz)
|
| 77 |
+
homogeneous = xyz @ k.T
|
| 78 |
+
projected = homogeneous[..., :2]/homogeneous[..., 2:3].clamp(min=1e-5)
|
| 79 |
+
error = (projected-safe_pixels[a:b])/scale_px
|
| 80 |
+
terms["reprojection"].append((torch.sqrt(1+error.square())-1).sum(-1)*weights[a:b])
|
| 81 |
+
terms["initializer"].append((xyz-target3d[a:b]).square().sum(-1)*initial_weights[a:b, None])
|
| 82 |
+
terms["cheirality"].append(torch.relu(.01-xyz[..., 2]).square())
|
| 83 |
+
xyz = torch.cat(points)
|
| 84 |
+
losses = {"reprojection": torch.cat(terms["reprojection"]).sum()/weights.sum().clamp(min=1),
|
| 85 |
+
"initializer": torch.cat(terms["initializer"]).sum()/(initial_weights.sum()*70).clamp(min=1),
|
| 86 |
+
"cheirality": torch.cat(terms["cheirality"]).mean(),
|
| 87 |
+
"shape_prior": (shape-shape0).square().mean()+(scales-scale0).square().mean(),
|
| 88 |
+
"motion_prior": (motion-motion0[:, 3:]).square().mean(),
|
| 89 |
+
"temporal": torch.zeros((), device=device), "limits": torch.zeros((), device=device),
|
| 90 |
+
"height_prior":torch.zeros((),device=device)}
|
| 91 |
+
if initial.get("height_prior") is not None:
|
| 92 |
+
value,scale=initial["height_prior"]
|
| 93 |
+
losses["height_prior"]=((forward.neutral_height(shape,scales)-value)/scale).square()
|
| 94 |
+
if len(time) >= 3:
|
| 95 |
+
dt = time[1:]-time[:-1]
|
| 96 |
+
if (dt <= 0).any():
|
| 97 |
+
raise ValueError("Fitting clock must increase without duplicate samples")
|
| 98 |
+
velocity = (xyz[1:]-xyz[:-1])/dt[:, None, None]
|
| 99 |
+
acceleration = (velocity[1:]-velocity[:-1])/((dt[1:]+dt[:-1])/2)[:, None, None]
|
| 100 |
+
if triples.any():
|
| 101 |
+
losses["temporal"] = acceleration[triples].square().mean()
|
| 102 |
+
if limits is not None:
|
| 103 |
+
lower, upper = [torch.as_tensor(v, device=device) for v in limits]
|
| 104 |
+
losses["limits"] = (torch.relu(lower-motion).square()+torch.relu(motion-upper).square()).mean()
|
| 105 |
+
total = (settings["reprojection_weight"]*losses["reprojection"]+
|
| 106 |
+
settings["initializer_weight"]*losses["initializer"]+
|
| 107 |
+
settings["shape_prior_weight"]*losses["shape_prior"]+
|
| 108 |
+
settings["motion_prior_weight"]*losses["motion_prior"]+
|
| 109 |
+
temporal_weight*losses["temporal"]+settings["limit_weight"]*losses["limits"]+
|
| 110 |
+
settings.get("height_prior_weight",.01)*losses["height_prior"]+
|
| 111 |
+
100*losses["cheirality"])
|
| 112 |
+
return total, losses, xyz
|
| 113 |
+
|
| 114 |
+
optimizer = torch.optim.Adam(parameters, lr=settings["learning_rate"])
|
| 115 |
+
for _ in range(settings["adam_steps"]):
|
| 116 |
+
optimizer.zero_grad(); loss, _, _ = evaluate()
|
| 117 |
+
if not torch.isfinite(loss):
|
| 118 |
+
raise ValueError("Nonfinite MHR objective")
|
| 119 |
+
loss.backward(); torch.nn.utils.clip_grad_norm_(parameters, 10.); optimizer.step()
|
| 120 |
+
optimizer = torch.optim.LBFGS(parameters, max_iter=settings["lbfgs_steps"], line_search_fn="strong_wolfe")
|
| 121 |
+
def closure():
|
| 122 |
+
optimizer.zero_grad(); loss, _, _ = evaluate(); loss.backward(); return loss
|
| 123 |
+
if settings["lbfgs_steps"]:
|
| 124 |
+
optimizer.step(closure)
|
| 125 |
+
with torch.no_grad():
|
| 126 |
+
_, penalties, xyz = evaluate()
|
| 127 |
+
h = xyz @ k.T
|
| 128 |
+
reprojection = torch.linalg.vector_norm(h[..., :2]/h[..., 2:3]-safe_pixels, dim=-1)
|
| 129 |
+
residual = torch.where(weights > 0, reprojection, torch.full_like(reprojection, float("nan")))
|
| 130 |
+
return {"keypoints_m": xyz.detach().cpu().numpy(), "motion_params": torch.cat([motion0[:, :3], motion], 1).detach().cpu().numpy(),
|
| 131 |
+
"shared_shape": shape.detach().cpu().numpy(), "shared_scales": scales.detach().cpu().numpy(),
|
| 132 |
+
"camera_translation_m": camera.detach().cpu().numpy(), "reprojection_px": residual.cpu().numpy(),
|
| 133 |
+
"objective_terms": {name: float(value.detach()) for name, value in penalties.items()},
|
| 134 |
+
"limit_source": "explicit_asset_parameter_bounds" if limits is not None else "not_available; initializer_prior_only"}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def export_mhr_adapter(model, destination, prediction, asset):
|
| 138 |
+
"""Export the exact loaded body regressor, not an invented rig/landmark correspondence."""
|
| 139 |
+
candidates = [module for module in model.modules() if hasattr(module, "keypoint_mapping")
|
| 140 |
+
and hasattr(module, "mhr") and getattr(module, "enable_hand_model", None) is False]
|
| 141 |
+
if len(candidates) != 1:
|
| 142 |
+
raise ValueError("Cannot uniquely identify the loaded full-body MHR regressor")
|
| 143 |
+
head = candidates[0]
|
| 144 |
+
mapping = head.keypoint_mapping.detach().cpu().numpy()[:70]
|
| 145 |
+
if (np.abs(mapping).sum(axis=1) == 0).any():
|
| 146 |
+
raise ValueError("Loaded MHR landmark regressor contains empty rows")
|
| 147 |
+
rows, columns = np.nonzero(mapping)
|
| 148 |
+
np.savez_compressed(destination, regressor_rows=rows, regressor_columns=columns,
|
| 149 |
+
regressor_values=mapping[rows, columns], regressor_shape=mapping.shape)
|
| 150 |
+
return {"mhr_asset_sha256": sha256_file(asset), "regressor_sha256": sha256_file(destination),
|
| 151 |
+
"rig_joint_count": int(np.asarray(prediction["pred_joint_coords"]).shape[-2]),
|
| 152 |
+
"regressor_shape": list(mapping.shape), "keypoint_names": MHR_CORE,
|
| 153 |
+
"source_kind": "model_regression_proxy", "independent_observation": False}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def run_temporal(request, capture, config, observation_cache):
|
| 157 |
+
root = Path(request["root"])
|
| 158 |
+
status_path = root / "temporal3d_status.json"
|
| 159 |
+
try:
|
| 160 |
+
import torch, yaml
|
| 161 |
+
torch.backends.cuda.matmul.allow_tf32=False
|
| 162 |
+
torch.backends.cudnn.allow_tf32=False
|
| 163 |
+
from .observations import collect_observations
|
| 164 |
+
initializer = read_json(root / "body3d_status.json")
|
| 165 |
+
if initializer.get("status") not in {"complete", "partial"}:
|
| 166 |
+
raise ValueError("SAM initializer unavailable")
|
| 167 |
+
source = root / "stages/body3d" / initializer["cache_key"]
|
| 168 |
+
adapter = source / "mhr_adapter.npz"
|
| 169 |
+
if not adapter.exists():
|
| 170 |
+
raise ValueError("Exact loaded MHR regressor has not been exported")
|
| 171 |
+
settings = yaml.safe_load(Path(config.fitting_config_path).read_text())
|
| 172 |
+
calibration = capture["metadata"].get("calibration", {})
|
| 173 |
+
from .geometry import intrinsics
|
| 174 |
+
k = calibration.get("intrinsics_oriented_pixels") or initializer.get("intrinsics_used")
|
| 175 |
+
if k is None:
|
| 176 |
+
raise ValueError("Initializer camera intrinsics are missing")
|
| 177 |
+
key = digest({"initializer": initializer["cache_key"], "adapter": sha256_file(adapter),
|
| 178 |
+
"settings": settings, "limits": sha256_file(config.mhr_limits_path) if config.mhr_limits_path else None})
|
| 179 |
+
cache = StageCache(root, "temporal3d", key)
|
| 180 |
+
if cache.valid("trajectory"):
|
| 181 |
+
atomic_json(status_path, read_json(cache.root / "status.json")); return
|
| 182 |
+
count = capture["frame_count"]
|
| 183 |
+
observations = collect_observations(observation_cache, (count+config.chunk_size-1)//config.chunk_size)
|
| 184 |
+
available = np.array([(source / f"frame_{i:06d}.npz").exists() for i in range(count)])
|
| 185 |
+
if available.sum() < 3:
|
| 186 |
+
raise ValueError("At least three initialized frames are required")
|
| 187 |
+
clock = "physical" if capture["physical_clock_known"] else "playback"
|
| 188 |
+
times = np.array([f["physical_s"] if clock == "physical" else f["playback_s"] for f in capture["frames"]], float)
|
| 189 |
+
all_points, all_raw, all_residual = np.full((count, 70, 3), np.nan), np.full((count, 70, 3), np.nan), np.full((count, 70), np.nan)
|
| 190 |
+
device = "cuda" if config.device == "cuda" else "cpu"
|
| 191 |
+
forward = MHRForward(config.mhr_path, adapter, device)
|
| 192 |
+
weights = np.zeros((count, 70)); pixels = np.full((count, 70, 2), np.nan)
|
| 193 |
+
for i, frame in enumerate(observations["frames"]):
|
| 194 |
+
for name, target in MHR_CORE.items():
|
| 195 |
+
index = RTMW_CORE[name]
|
| 196 |
+
if frame["body_states"][index] in {"model_inferred", "manual", "image_supported"}:
|
| 197 |
+
pixels[i, target] = frame["body_points"][index]
|
| 198 |
+
score = frame["body_scores"][index]
|
| 199 |
+
weights[i, target] = 1 if frame["body_states"][index] == "manual" else np.clip(score, 0, 1)
|
| 200 |
+
# Optimize the whole observed short clip with ONE shape/scales vector. Missing
|
| 201 |
+
# frames are never synthesized; temporal triplets exclude every source-frame gap.
|
| 202 |
+
ids = np.flatnonzero(available & np.isfinite(times))
|
| 203 |
+
data = [np.load(source / f"frame_{i:06d}.npz", allow_pickle=False) for i in ids]
|
| 204 |
+
initial = {"motion": np.stack([d["mhr_model_params"].reshape(-1)[:136] for d in data]),
|
| 205 |
+
"scales": np.stack([d["mhr_model_params"].reshape(-1)[136:] for d in data]),
|
| 206 |
+
"shape": np.stack([d["shape_params"].reshape(-1) for d in data]),
|
| 207 |
+
"camera": np.stack([d["pred_cam_t"].reshape(3) for d in data]),
|
| 208 |
+
"keypoints": np.stack([d["camera_keypoints_m"].reshape(70, 3) for d in data]),
|
| 209 |
+
"intrinsics": intrinsics(k)}
|
| 210 |
+
initial = {name: torch.tensor(value, dtype=torch.float32, device=device) for name, value in initial.items()}
|
| 211 |
+
if initial["scales"].shape[1] != 68 or initial["motion"].shape[1] != 136:
|
| 212 |
+
raise ValueError("Unexpected bundled MHR parameter topology")
|
| 213 |
+
with torch.no_grad():
|
| 214 |
+
raw=forward(initial["shape"][0],initial["motion"][:1],initial["scales"][0],initial["camera"][:1])
|
| 215 |
+
if torch.linalg.vector_norm(raw-initial["keypoints"][:1],dim=-1).max()>.001:
|
| 216 |
+
raise ValueError("Exact native MHR forward does not reproduce SAM landmarks within 1mm")
|
| 217 |
+
height=capture["metadata"].get("height_m")
|
| 218 |
+
uncertainty=capture["metadata"].get("uncertainty",{})
|
| 219 |
+
height_scale=uncertainty.get("height_prior_scale_m")
|
| 220 |
+
if height and uncertainty.get("height_source") and isinstance(height_scale,(int,float)) and height_scale>0:
|
| 221 |
+
initial["height_prior"]=(height,height_scale)
|
| 222 |
+
limits = None
|
| 223 |
+
if config.mhr_limits_path:
|
| 224 |
+
bounds = read_json(config.mhr_limits_path)
|
| 225 |
+
if bounds.get("asset_sha256") != sha256_file(config.mhr_path) or not bounds.get("source"):
|
| 226 |
+
raise ValueError("MHR limits must identify this exact asset and their source")
|
| 227 |
+
limits = (bounds["lower"], bounds["upper"])
|
| 228 |
+
if any(len(v) != 133 for v in limits):
|
| 229 |
+
raise ValueError("MHR motion limits require 133 entries excluding root translation")
|
| 230 |
+
fit = fit_sequence(forward, initial, pixels[ids], weights[ids], times[ids], settings, limits, frame_ids=ids)
|
| 231 |
+
all_raw[ids] = initial["keypoints"].cpu().numpy()
|
| 232 |
+
residuals = fit["reprojection_px"]
|
| 233 |
+
support = (np.isfinite(residuals).sum(axis=1) >= settings.get("minimum_observed_landmarks", 6))
|
| 234 |
+
error = np.sqrt(np.divide(np.nansum(residuals**2, axis=1), np.maximum(np.isfinite(residuals).sum(axis=1), 1)))
|
| 235 |
+
accepted = np.zeros(count, bool)
|
| 236 |
+
accepted[ids] = support & (error <= settings["max_reprojection_rmse_px"])
|
| 237 |
+
if not accepted.any():
|
| 238 |
+
raise ValueError("No fitted frame passed observation agreement checks")
|
| 239 |
+
all_points[ids[accepted[ids]]] = fit["keypoints_m"][accepted[ids]]
|
| 240 |
+
all_residual[ids] = residuals
|
| 241 |
+
penalties = {"terms": fit["objective_terms"], "limit_source": fit["limit_source"]}
|
| 242 |
+
solution = cache.root / "solution.npz"
|
| 243 |
+
np.savez_compressed(solution, frame_ids=ids, **{name: value for name, value in fit.items() if isinstance(value, np.ndarray)})
|
| 244 |
+
sensitivities = []
|
| 245 |
+
for factor in settings.get("sensitivity_temporal_factors", []):
|
| 246 |
+
scenario = fit_sequence(forward, initial, pixels[ids], weights[ids], times[ids], settings, limits, factor, ids)
|
| 247 |
+
sensitivities.append({"temporal_factor": factor,
|
| 248 |
+
"max_landmark_change_m": float(np.linalg.norm(scenario["keypoints_m"]-fit["keypoints_m"], axis=-1).max())})
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
neutral = forward(torch.tensor(fit["shared_shape"], device=device),
|
| 251 |
+
torch.zeros(1, 136, device=device), torch.tensor(fit["shared_scales"], device=device),
|
| 252 |
+
torch.zeros(1, 3, device=device)).cpu().numpy()[0]
|
| 253 |
+
trajectory = cache.root / "trajectory.npz"
|
| 254 |
+
np.savez_compressed(trajectory, keypoints_camera_m=all_points, raw_camera_m=all_raw,
|
| 255 |
+
reprojection_px=all_residual, accepted_frames=accepted, fitting_times=times, neutral_mhr70_m=neutral, observation_weights=weights)
|
| 256 |
+
status = {"status": "complete" if accepted.all() else "partial", "cache_key": key,
|
| 257 |
+
"frames_fitted": int(accepted.sum()), "frame_count": count, "objective_terms": penalties,
|
| 258 |
+
"sensitivity": sensitivities, "uncertainty_kind": "regularization_sensitivity; not calibrated accuracy",
|
| 259 |
+
"maximum_regularization_sensitivity_m":max((s["max_landmark_change_m"] for s in sensitivities),default=None),
|
| 260 |
+
"coordinate_space": "camera_x_right_y_down_z_forward_metres", "regularization_clock": clock,
|
| 261 |
+
"shape_scope": "shared_across_complete_observed_clip",
|
| 262 |
+
"height_prior_source":uncertainty.get("height_source") if initial.get("height_prior") else None,
|
| 263 |
+
"geometry_source": "calibrated_intrinsics_model_scale" if calibration.get("intrinsics_oriented_pixels") else "assumed_intrinsics_model_scale",
|
| 264 |
+
"validation": "reference-validation-pending", "trajectory_path": str(trajectory.relative_to(root))}
|
| 265 |
+
atomic_json(cache.root / "status.json", status)
|
| 266 |
+
cache.commit("trajectory", [trajectory, solution, cache.root / "status.json"])
|
| 267 |
+
except Exception as error:
|
| 268 |
+
status = {"status": "unavailable", "reason": str(error)[:300], "error_type": type(error).__name__}
|
| 269 |
+
atomic_json(status_path, status)
|
baseball_batting/training.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Actual optimization, held-out evaluation and explicit checkpoint activation records."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import copy
|
| 4 |
+
import random
|
| 5 |
+
import numpy as np
|
| 6 |
+
from .storage import read_json, atomic_json, sha256_file, digest
|
| 7 |
+
from .learning import endpoint_network, temporal_network, BOUNDARIES, PHASES, FEATURE_VERSION
|
| 8 |
+
from .dataset import validate_splits
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_dataset(directory,kind):
|
| 12 |
+
directory=Path(directory);manifest=read_json(directory/"dataset.json")
|
| 13 |
+
if manifest["kind"]!=kind:raise ValueError("Training dataset kind mismatch")
|
| 14 |
+
players={}
|
| 15 |
+
for sample in manifest["samples"]:
|
| 16 |
+
if sample["player_id"] in players and players[sample["player_id"]]!=sample["split"]:raise ValueError("Athlete leakage")
|
| 17 |
+
players[sample["player_id"]]=sample["split"]
|
| 18 |
+
if sha256_file(directory/sample["path"])!=manifest["artifact_hashes"][sample["path"]]:raise ValueError("Dataset artifact changed")
|
| 19 |
+
if set(players.values())!={"train","validation","test"}:raise ValueError("Nonempty grouped partitions required")
|
| 20 |
+
return manifest
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def sample_loss(model,data,kind,device):
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
tensor=lambda value:torch.as_tensor(value,dtype=torch.float32,device=device)
|
| 27 |
+
if kind=="endpoint_cnn":
|
| 28 |
+
image=tensor(data["image"].transpose(2,0,1)/255.)[None]
|
| 29 |
+
heat,visible=model(image)
|
| 30 |
+
support=tensor(data["visible"])[None,:,None,None]
|
| 31 |
+
heat_loss=((heat.sigmoid()-tensor(data["heatmaps"])[None])**2*support).sum()/(support.sum()*4096).clamp(min=1)
|
| 32 |
+
mask=tensor(data["visibility_mask"])[None]
|
| 33 |
+
visibility=(F.binary_cross_entropy_with_logits(visible,tensor(data["visible"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1)
|
| 34 |
+
return heat_loss+visibility
|
| 35 |
+
phase,boundary,presence=model(tensor(data["features"])[None])
|
| 36 |
+
target=torch.as_tensor(data["phase"],dtype=torch.long,device=device)[None]
|
| 37 |
+
loss=sum(F.cross_entropy(p,target,ignore_index=-100) for p in phase)
|
| 38 |
+
# Adjacent high-cadence source samples are retained; never invent negative
|
| 39 |
+
# boundaries for unknown events or substitute clip-wide contact presence.
|
| 40 |
+
mask=tensor(data["boundary_mask"])[None]
|
| 41 |
+
loss+=(F.binary_cross_entropy_with_logits(boundary,tensor(data["boundary"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1)
|
| 42 |
+
mask=tensor(data["presence_mask"])[None]
|
| 43 |
+
loss+=(F.binary_cross_entropy_with_logits(presence,tensor(data["presence"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1)
|
| 44 |
+
if target.shape[1]>1:
|
| 45 |
+
known=(target[:,1:]!=-100)&(target[:,:-1]!=-100)
|
| 46 |
+
logp=phase[-1].log_softmax(1)
|
| 47 |
+
smooth=(logp[:,:,1:]-logp[:,:,:-1].detach()).square().clamp(max=16)
|
| 48 |
+
loss+=.15*(smooth*known[:,None]).sum()/(known.sum()*len(PHASES)).clamp(min=1)
|
| 49 |
+
return loss
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def train(directory,output,kind,epochs=30,learning_rate=.001,device="cpu",mstcn_repo=None,seed=17):
|
| 53 |
+
import torch
|
| 54 |
+
if epochs<1:raise ValueError("Positive epoch count required")
|
| 55 |
+
torch.manual_seed(seed);np.random.seed(seed);random.seed(seed)
|
| 56 |
+
manifest=load_dataset(directory,kind);directory=Path(directory);output=Path(output);output.mkdir(parents=True,exist_ok=True)
|
| 57 |
+
architecture=None;source=None
|
| 58 |
+
if kind=="endpoint_cnn":model=endpoint_network()
|
| 59 |
+
else:
|
| 60 |
+
first=np.load(directory/manifest["samples"][0]["path"])
|
| 61 |
+
architecture={"prediction_layers":6,"refinement_layers":6,"refinements":3,"channels":64,"feature_dim":first["features"].shape[0]}
|
| 62 |
+
model,source=temporal_network(mstcn_repo,architecture)
|
| 63 |
+
model=model.to(device);optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate)
|
| 64 |
+
partitions={name:[s for s in manifest["samples"] if s["split"]==name] for name in ("train","validation","test")}
|
| 65 |
+
if any(not p for p in partitions.values()):raise ValueError("No eligible samples in a partition")
|
| 66 |
+
best=float("inf");history=[]
|
| 67 |
+
for epoch in range(epochs):
|
| 68 |
+
model.train();order=partitions["train"].copy();random.shuffle(order);losses=[]
|
| 69 |
+
for sample in order:
|
| 70 |
+
data=np.load(directory/sample["path"],allow_pickle=False)
|
| 71 |
+
optimizer.zero_grad();loss=sample_loss(model,data,kind,device)
|
| 72 |
+
if not torch.isfinite(loss):raise ValueError("Nonfinite training loss")
|
| 73 |
+
loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5.);optimizer.step();losses.append(float(loss.detach()))
|
| 74 |
+
model.eval()
|
| 75 |
+
with torch.no_grad(): val=np.mean([float(sample_loss(model,np.load(directory/s["path"]),kind,device)) for s in partitions["validation"]])
|
| 76 |
+
history.append({"epoch":epoch+1,"training_loss":float(np.mean(losses)),"validation_loss":float(val)})
|
| 77 |
+
if val<best:
|
| 78 |
+
best=val;torch.save(model.state_dict(),output/"checkpoint.tmp.pt");(output/"checkpoint.tmp.pt").replace(output/"checkpoint.pt")
|
| 79 |
+
atomic_json(output/"training_history.json",history)
|
| 80 |
+
result={"schema_version":"1.0","kind":kind,"checkpoint_sha256":sha256_file(output/"checkpoint.pt"),
|
| 81 |
+
"architecture":architecture,"source":source,"feature_version":FEATURE_VERSION if kind=="mstcn_events" else None,
|
| 82 |
+
"dataset_sha256":sha256_file(directory/"dataset.json"),"seed":seed,"epochs":epochs,"selection":"lowest_validation_loss",
|
| 83 |
+
"qualification":{"status":"candidate","reason":"held_out_evaluation_and_preregistered_gates_required"}}
|
| 84 |
+
atomic_json(output/"checkpoint.json",result);return result
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def evaluate(directory,checkpoint_directory,thresholds_path,scope,mstcn_repo=None,device="cpu"):
|
| 88 |
+
import torch
|
| 89 |
+
checkpoint_directory=Path(checkpoint_directory);directory=Path(directory)
|
| 90 |
+
manifest=read_json(checkpoint_directory/"checkpoint.json");kind=manifest["kind"]
|
| 91 |
+
if not scope:raise ValueError("Explicit evaluation scope required")
|
| 92 |
+
dataset=load_dataset(directory,kind)
|
| 93 |
+
if manifest["dataset_sha256"]!=sha256_file(directory/"dataset.json"):raise ValueError("Checkpoint dataset mismatch")
|
| 94 |
+
gates=read_json(thresholds_path)
|
| 95 |
+
if not gates.get("source") or gates.get("preregistered") is not True:raise ValueError("Documented preregistered qualification gates required")
|
| 96 |
+
model=endpoint_network() if kind=="endpoint_cnn" else temporal_network(mstcn_repo,manifest["architecture"])[0]
|
| 97 |
+
model.load_state_dict(torch.load(checkpoint_directory/"checkpoint.pt",map_location=device,weights_only=True));model=model.to(device).eval()
|
| 98 |
+
tests=[s for s in dataset["samples"] if s["split"]=="test"]
|
| 99 |
+
errors=[];missed=extra=expected=negative=correct_negative=correct=total=0
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
for sample in tests:
|
| 102 |
+
data=np.load(directory/sample["path"])
|
| 103 |
+
if kind=="endpoint_cnn":
|
| 104 |
+
x=torch.tensor(data["image"].transpose(2,0,1)/255.,dtype=torch.float32,device=device)[None]
|
| 105 |
+
heat,visibility=model(x);predicted=heat[0].cpu().numpy().reshape(2,-1).argmax(1);present=visibility.sigmoid()[0].cpu().numpy()>=.5
|
| 106 |
+
target=data["heatmaps"].reshape(2,-1).argmax(1)
|
| 107 |
+
for j in range(2):
|
| 108 |
+
if not data["visibility_mask"][j]:continue
|
| 109 |
+
if data["visible"][j]:
|
| 110 |
+
expected+=1
|
| 111 |
+
if not present[j]:missed+=1;continue
|
| 112 |
+
errors.append(float(np.linalg.norm([predicted[j]%64-target[j]%64,predicted[j]//64-target[j]//64])*4))
|
| 113 |
+
else:
|
| 114 |
+
negative+=1;extra+=int(present[j]);correct_negative+=int(not present[j])
|
| 115 |
+
else:
|
| 116 |
+
phase,boundary,presence=model(torch.tensor(data["features"],device=device)[None])
|
| 117 |
+
predicted=phase[-1][0].argmax(0).cpu().numpy();mask=data["phase"]!=-100
|
| 118 |
+
correct+=int((predicted[mask]==data["phase"][mask]).sum());total+=int(mask.sum())
|
| 119 |
+
score=boundary.sigmoid()[0].cpu().numpy();present=presence.sigmoid()[0].cpu().numpy()>=.5
|
| 120 |
+
for j in range(len(BOUNDARIES)):
|
| 121 |
+
if not data["presence_mask"][j]:continue
|
| 122 |
+
if data["presence"][j]:
|
| 123 |
+
expected+=1
|
| 124 |
+
if not present[j] or score[j].max()<.5:missed+=1;continue
|
| 125 |
+
i=int(score[j].argmax());reference=np.flatnonzero(data["boundary"][j]>0)
|
| 126 |
+
errors.append(float(np.abs(reference-i).min()))
|
| 127 |
+
else:
|
| 128 |
+
negative+=1;extra+=int(present[j] and score[j].max()>=.5)
|
| 129 |
+
metrics={"median_error":float(np.median(errors)) if errors else None,"p95_error":float(np.percentile(errors,95)) if errors else None,
|
| 130 |
+
"miss_rate":missed/expected if expected else None,"extra_rate":extra/negative if negative else None,
|
| 131 |
+
"phase_accuracy":correct/total if total else None,"held_out_athlete_count":len({s["player_id"] for s in tests}),
|
| 132 |
+
"positive_labels":expected,"absent_labels":negative,"error_units":"256_crop_pixels" if kind=="endpoint_cnn" else "source_frames"}
|
| 133 |
+
checks={}
|
| 134 |
+
for name,limit in gates.get("maximum",{}).items():checks[name]=metrics.get(name) is not None and metrics[name]<=limit
|
| 135 |
+
for name,limit in gates.get("minimum",{}).items():checks[name]=metrics.get(name) is not None and metrics[name]>=limit
|
| 136 |
+
if not checks:raise ValueError("No qualification thresholds supplied")
|
| 137 |
+
result={"metrics":metrics,"checks":checks,"passed":all(checks.values()),"scope":scope,
|
| 138 |
+
"thresholds_sha256":sha256_file(thresholds_path),"checkpoint_sha256":sha256_file(checkpoint_directory/"checkpoint.pt"),
|
| 139 |
+
"dataset_sha256":sha256_file(directory/"dataset.json"),"validation":"experimental_detection_only"}
|
| 140 |
+
atomic_json(checkpoint_directory/"evaluation.json",result)
|
| 141 |
+
manifest["qualification"]={"status":"passed" if result["passed"] else "failed_preflight","held_out_athletes":True,
|
| 142 |
+
"evaluation_sha256":sha256_file(checkpoint_directory/"evaluation.json"),"scope":scope,
|
| 143 |
+
"thresholds_sha256":result["thresholds_sha256"]}
|
| 144 |
+
atomic_json(checkpoint_directory/"checkpoint.json",manifest);return result
|
baseball_batting/validation.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent paired-reference evaluation. Distribution tables cannot qualify videos."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .storage import read_json,atomic_json,sha256_file
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def evaluate_reference(pairs_path,gates_path,output):
|
| 8 |
+
pairs=read_json(pairs_path);gates=read_json(gates_path)
|
| 9 |
+
if gates.get("preregistered") is not True or not gates.get("source") or not gates.get("scope"):
|
| 10 |
+
raise ValueError("Preregistered gates with source and explicit population/task/view scope required")
|
| 11 |
+
records={name:[] for name in gates.get("metrics",{})};coverage={name:0 for name in records};eligible={name:0 for name in records}
|
| 12 |
+
for pair in pairs:
|
| 13 |
+
if pair.get("independent_reference") is not True or pair.get("synchronization_verified") is not True or not pair.get("reference_source"):
|
| 14 |
+
raise ValueError("Every pair needs independent reference provenance and verified synchronization")
|
| 15 |
+
result=read_json(pair["result_path"])
|
| 16 |
+
if result["capture"]["input_sha256"]!=pair["input_sha256"]:raise ValueError("Reference pair video mismatch")
|
| 17 |
+
if not pair.get("player_id") or not pair.get("session_id"):raise ValueError("Held-out athlete/session identity required")
|
| 18 |
+
metrics={m["metric_id"]:m for m in result["metrics"]}
|
| 19 |
+
for name in records:
|
| 20 |
+
reference=pair.get("metrics",{}).get(name)
|
| 21 |
+
if reference is None:continue
|
| 22 |
+
eligible[name]+=1
|
| 23 |
+
measurement=metrics.get(name)
|
| 24 |
+
if measurement is None or measurement["value"] is None:continue
|
| 25 |
+
if measurement["unit"]!=reference["unit"]:raise ValueError("Reference units mismatch")
|
| 26 |
+
if reference.get("definition_version")!=measurement["definition_version"]:raise ValueError("Reference metric definition mismatch")
|
| 27 |
+
records[name].append({"error":measurement["value"]-reference["value"],"player_id":pair["player_id"],
|
| 28 |
+
"repeatability_group":pair.get("repeatability_group"),"result_code_hash":result["engine_code_hash"]})
|
| 29 |
+
coverage[name]+=1
|
| 30 |
+
evaluations={}
|
| 31 |
+
for name,rows in records.items():
|
| 32 |
+
errors=np.array([r["error"] for r in rows]);groups={r["repeatability_group"] for r in rows if r["repeatability_group"]}
|
| 33 |
+
repeat=[np.std([r["error"] for r in rows if r["repeatability_group"]==group],ddof=1) for group in groups if sum(r["repeatability_group"]==group for r in rows)>1]
|
| 34 |
+
stats={"bias":float(np.mean(errors)) if len(errors) else None,"mae":float(np.mean(abs(errors))) if len(errors) else None,
|
| 35 |
+
"p95_absolute_error":float(np.percentile(abs(errors),95)) if len(errors) else None,
|
| 36 |
+
"measurement_coverage":coverage[name]/eligible[name] if eligible[name] else None,
|
| 37 |
+
"error_repeatability_sd":float(np.mean(repeat)) if repeat else None,
|
| 38 |
+
"athlete_count":len({r["player_id"] for r in rows}),"pair_count":len(rows),
|
| 39 |
+
"calibrated_uncertainty_coverage":None}
|
| 40 |
+
checks={};requirements=gates["metrics"][name]
|
| 41 |
+
for k,v in requirements.get("maximum",{}).items():checks[k]=stats.get(k) is not None and abs(stats[k])<=v
|
| 42 |
+
for k,v in requirements.get("minimum",{}).items():checks[k]=stats.get(k) is not None and stats[k]>=v
|
| 43 |
+
evaluations[name]={"statistics":stats,"checks":checks,"passed":bool(checks) and all(checks.values()),
|
| 44 |
+
"processing_code_hashes":sorted({r["result_code_hash"] for r in rows})}
|
| 45 |
+
report={"schema_version":"1.0","scope":gates["scope"],"evaluations":evaluations,
|
| 46 |
+
"pairs_sha256":sha256_file(pairs_path),"gates_sha256":sha256_file(gates_path),
|
| 47 |
+
"promotion":"evaluation_evidence_only; explicit_method_and_rule_review_required"}
|
| 48 |
+
atomic_json(output,report);return report
|
baseball_batting/worker.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import traceback
|
| 4 |
+
from .config import EngineConfig
|
| 5 |
+
from .storage import StageCache, atomic_json, read_json, digest
|
| 6 |
+
|
| 7 |
+
def run_stage(stage, request):
|
| 8 |
+
config = EngineConfig(**request["config"]).validate()
|
| 9 |
+
root = Path(request["root"])
|
| 10 |
+
ingestion = StageCache(root, "ingest", request["ingest_key"])
|
| 11 |
+
observation_cache = StageCache(root, "observations", request["observation_key"])
|
| 12 |
+
capture_path = ingestion.root / "capture.json"
|
| 13 |
+
if stage == "ingest":
|
| 14 |
+
from .ingest import ingest
|
| 15 |
+
capture = ingest(request["video"], request["metadata"])
|
| 16 |
+
atomic_json(capture_path, capture)
|
| 17 |
+
ingestion.commit("capture", [capture_path], input_hash=capture["input_sha256"])
|
| 18 |
+
return
|
| 19 |
+
capture = read_json(capture_path)
|
| 20 |
+
if stage == "observations":
|
| 21 |
+
from .observations import run_observations
|
| 22 |
+
run_observations(request["video"], capture, config, observation_cache)
|
| 23 |
+
return
|
| 24 |
+
if stage == "body3d":
|
| 25 |
+
from .body3d import run_initializer
|
| 26 |
+
run_initializer(request, capture, config, observation_cache)
|
| 27 |
+
return
|
| 28 |
+
if stage == "temporal3d":
|
| 29 |
+
from .temporal3d import run_temporal
|
| 30 |
+
run_temporal(request,capture,config,observation_cache);return
|
| 31 |
+
if stage == "anatomy":
|
| 32 |
+
from .anatomy import run_anatomy
|
| 33 |
+
run_anatomy(request,capture,config);return
|
| 34 |
+
if stage == "bat3d":
|
| 35 |
+
from .bat3d import run_bat3d
|
| 36 |
+
run_bat3d(request,capture,config);return
|
| 37 |
+
from .observations import collect_observations
|
| 38 |
+
from .annotations import load_annotations
|
| 39 |
+
from .metrics import continuous_curves, summarize
|
| 40 |
+
from .events import detect_events
|
| 41 |
+
from .assessment import assess
|
| 42 |
+
from .reports import write_reports, export_video
|
| 43 |
+
from .contracts import json_safe
|
| 44 |
+
count = (capture["frame_count"]+config.chunk_size-1)//config.chunk_size
|
| 45 |
+
observations = collect_observations(observation_cache, count)
|
| 46 |
+
if stage == "learned_events":
|
| 47 |
+
from .learning import run_learned_events
|
| 48 |
+
run_learned_events(request,capture,config,observations);return
|
| 49 |
+
annotations = load_annotations(config.annotations_path, capture["input_sha256"], capture["frame_count"],
|
| 50 |
+
capture["frames"][0]["width"], capture["frames"][0]["height"])
|
| 51 |
+
curves = continuous_curves(observations, capture)
|
| 52 |
+
events = detect_events(curves, observations, capture, annotations, config.event_parameters)
|
| 53 |
+
if config.learned_events_enabled:
|
| 54 |
+
from .learning import merge_learned
|
| 55 |
+
p=root/"learned_events_status.json"
|
| 56 |
+
events=merge_learned(events,read_json(p) if p.exists() else {})
|
| 57 |
+
for event in events:
|
| 58 |
+
if event.frame_interval:
|
| 59 |
+
a,b=event.frame_interval
|
| 60 |
+
event.playback_interval_s=[capture["frames"][a]["playback_s"],capture["frames"][b]["playback_s"]]
|
| 61 |
+
event.physical_interval_s=[capture["frames"][a]["physical_s"],capture["frames"][b]["physical_s"]]
|
| 62 |
+
metrics = summarize(curves, observations, capture, events)
|
| 63 |
+
import yaml
|
| 64 |
+
from .advanced_metrics import augment
|
| 65 |
+
from .sensitivity import apply_image_sensitivity
|
| 66 |
+
quality=yaml.safe_load(Path(config.quality_config_path).read_text())
|
| 67 |
+
metrics=augment(root,curves,metrics,events,capture,quality,{"anatomy":config.body3d_enabled and config.temporal3d_enabled and config.anatomy_enabled,
|
| 68 |
+
"bat3d":config.bat_3d_mode!="disabled"})
|
| 69 |
+
apply_image_sensitivity(metrics,observations,capture,events)
|
| 70 |
+
from .diagnostics import observation_summary
|
| 71 |
+
diagnostics = observation_summary(observations)
|
| 72 |
+
diagnostics["available_metrics"] = sum(m.value is not None for m in metrics)
|
| 73 |
+
diagnostics["requested_device"] = config.device
|
| 74 |
+
diagnostics["observation_environment"] = observations.get("runtime_environment")
|
| 75 |
+
stages = {"ingest": {"status": "complete"}, **observations["branch_status"],
|
| 76 |
+
"observations": {"status": diagnostics["status"], "reason": diagnostics["message"]},
|
| 77 |
+
"events": {"status": "complete", "method": "candidates_plus_review"},
|
| 78 |
+
"body3d": {"status": "disabled_by_configuration"},
|
| 79 |
+
"temporal_3d_fitting": {"status": "disabled_by_configuration"},
|
| 80 |
+
"anatomy": {"status": "disabled_by_configuration"},
|
| 81 |
+
"bat3d": {"status": "disabled_by_configuration" if config.bat_3d_mode == "disabled" else "unavailable",
|
| 82 |
+
"reason": "independent_geometry_not_qualified"},
|
| 83 |
+
"learned_events": {"status": "unavailable" if config.learned_events_enabled else "disabled_by_configuration",
|
| 84 |
+
"reason": "no_qualified_checkpoint"}}
|
| 85 |
+
if config.body3d_enabled:
|
| 86 |
+
p = root / "body3d_status.json"
|
| 87 |
+
stages["body3d"] = read_json(p) if p.exists() else {"status": "failed", "reason": "initializer_did_not_write_status"}
|
| 88 |
+
for name,filename,enabled in (("temporal_3d_fitting","temporal3d",config.body3d_enabled and config.temporal3d_enabled),
|
| 89 |
+
("anatomy","anatomy",config.body3d_enabled and config.anatomy_enabled and config.temporal3d_enabled),
|
| 90 |
+
("bat3d","bat3d",config.bat_3d_mode!="disabled"),
|
| 91 |
+
("learned_events","learned_events",config.learned_events_enabled)):
|
| 92 |
+
if enabled:
|
| 93 |
+
p=root/(filename+"_status.json")
|
| 94 |
+
stages[name]=read_json(p) if p.exists() else {"status":"failed","reason":"worker_did_not_write_status"}
|
| 95 |
+
video_status = {"status": "disabled_by_configuration"}
|
| 96 |
+
if config.export_video:
|
| 97 |
+
video_status = export_video(request["video"], capture, observations, root / "annotated.mp4")
|
| 98 |
+
stages["video_export"] = video_status
|
| 99 |
+
assisted = observations["provenance"] == "human_assisted" or bool(annotations.get("events"))
|
| 100 |
+
result = json_safe({"schema_version": "1.0", "engine_version": "0.2.0",
|
| 101 |
+
"engine_code_hash": request["code_hash"], "status": "failed" if diagnostics["status"] == "failed" else "partial",
|
| 102 |
+
"provenance": "human_assisted" if assisted else "automatic", "capture": capture,
|
| 103 |
+
"stages": stages, "events": events, "metrics": metrics,
|
| 104 |
+
"model_hashes": request["model_hashes"], "configuration": {
|
| 105 |
+
k: v for k,v in config.to_dict().items() if not k.endswith("path") and k not in
|
| 106 |
+
{"sam_repo", "sam_checkpoint", "sam_config", "stage_python", "mstcn_repo"}},
|
| 107 |
+
"diagnostics": diagnostics, "annotation_hash": None,
|
| 108 |
+
"validation": "reference-validation-pending"})
|
| 109 |
+
if config.annotations_path:
|
| 110 |
+
from .storage import sha256_file
|
| 111 |
+
result["annotation_hash"] = sha256_file(config.annotations_path)
|
| 112 |
+
from .history import compatible_trials
|
| 113 |
+
trials=compatible_trials(root,result)
|
| 114 |
+
result["findings"]=json_safe(assess(metrics,capture["metadata"],events,trials,config.coaching_rules_path,config.coaching_mode))
|
| 115 |
+
result["history_comparison"]={"compatible_trial_count":len(trials),"basis":"explicit_identity_matched_task_context_processing_versions"}
|
| 116 |
+
write_reports(root, result, curves)
|
| 117 |
+
atomic_json(root / "observation_index.json", {"cache_key": observation_cache.key,
|
| 118 |
+
"chunk_count": count, "topology": "rtmw133_native", "input_sha256": capture["input_sha256"]})
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
import time,platform,resource
|
| 122 |
+
started=time.perf_counter()
|
| 123 |
+
request=read_json(sys.argv[2])
|
| 124 |
+
try:
|
| 125 |
+
run_stage(sys.argv[1], request)
|
| 126 |
+
except Exception as error:
|
| 127 |
+
print(f"{type(error).__name__}: {error}", file=sys.stderr)
|
| 128 |
+
sys.exit(1)
|
| 129 |
+
finally:
|
| 130 |
+
rss=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
| 131 |
+
profile={"stage":sys.argv[1],"elapsed_s":time.perf_counter()-started,
|
| 132 |
+
"peak_process_rss_mb":rss/(1024*1024 if sys.platform=="darwin" else 1024),
|
| 133 |
+
"python":platform.python_version(),"device_requested":request["config"]["device"],
|
| 134 |
+
"gpu_memory_scope":"torch_allocator_only; excludes ONNX/native allocations"}
|
| 135 |
+
torch=sys.modules.get("torch")
|
| 136 |
+
if torch is not None and torch.cuda.is_available():
|
| 137 |
+
profile["torch_peak_allocated_mb"]=torch.cuda.max_memory_allocated()/1024**2
|
| 138 |
+
profile["torch_peak_reserved_mb"]=torch.cuda.max_memory_reserved()/1024**2
|
| 139 |
+
atomic_json(Path(request["root"])/"runtime_profiles"/(sys.argv[1]+".json"),profile)
|
compose.yaml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
api:
|
| 3 |
+
build: .
|
| 4 |
+
image: baseball-engine-api:local
|
| 5 |
+
platform: linux/amd64
|
| 6 |
+
gpus: all
|
| 7 |
+
restart: unless-stopped
|
| 8 |
+
environment:
|
| 9 |
+
BASEBALL_API_KEY: ${BASEBALL_API_KEY:?Set BASEBALL_API_KEY in .env}
|
| 10 |
+
BASEBALL_MAX_UPLOAD_MB: ${BASEBALL_MAX_UPLOAD_MB:-512}
|
| 11 |
+
BASEBALL_MAX_ACTIVE_JOBS: ${BASEBALL_MAX_ACTIVE_JOBS:-8}
|
| 12 |
+
BASEBALL_MAX_FRAMES: ${BASEBALL_MAX_FRAMES:-7200}
|
| 13 |
+
BASEBALL_MAX_DURATION_S: ${BASEBALL_MAX_DURATION_S:-120}
|
| 14 |
+
BASEBALL_JOB_TIMEOUT_S: ${BASEBALL_JOB_TIMEOUT_S:-1800}
|
| 15 |
+
BASEBALL_RETENTION_HOURS: ${BASEBALL_RETENTION_HOURS:-24}
|
| 16 |
+
ports:
|
| 17 |
+
- "127.0.0.1:8000:8000"
|
| 18 |
+
volumes:
|
| 19 |
+
- baseball-data:/data
|
| 20 |
+
read_only: true
|
| 21 |
+
tmpfs:
|
| 22 |
+
- /tmp:size=2147483648,mode=1777
|
| 23 |
+
cap_drop:
|
| 24 |
+
- ALL
|
| 25 |
+
security_opt:
|
| 26 |
+
- no-new-privileges:true
|
| 27 |
+
stop_grace_period: 30s
|
| 28 |
+
volumes:
|
| 29 |
+
baseball-data:
|
configs/anatomical_model.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version: '1.0'
|
| 2 |
+
model_id: BattingKinematics-v1
|
| 3 |
+
version: '1.0'
|
| 4 |
+
dof: 35
|
| 5 |
+
purpose: kinematic_proxy_only
|
| 6 |
+
units: metres_radians
|
| 7 |
+
mass_inertia: placeholders_not_for_dynamics
|
| 8 |
+
root: FreeJoint
|
| 9 |
+
torso: BallJoint
|
| 10 |
+
hip: BallJoint
|
| 11 |
+
knee: PinJoint
|
| 12 |
+
ankle: UniversalJoint
|
| 13 |
+
shoulder: BallJoint
|
| 14 |
+
elbow: PinJoint
|
| 15 |
+
forearm_rotor: PinJoint
|
| 16 |
+
wrist: UniversalJoint
|
| 17 |
+
ball_coordinates: intrinsic_XYZ_not_anatomical_angles
|
| 18 |
+
universal_coordinates: intrinsic_XY
|
| 19 |
+
pin_axis: joint_local_Z
|
| 20 |
+
soft_coordinate_range_rad: [-3.05, 3.05]
|
| 21 |
+
universal_range_rad: [-1.35, 1.35]
|
| 22 |
+
marker_fit_max_rmse_m: 0.05
|
| 23 |
+
temporal_weight: 0.0001
|
| 24 |
+
refinement_max_evaluations: 50
|
| 25 |
+
refinement_observation_tolerance_m: 0.0001
|
| 26 |
+
source_kind: MHR70_model_regression_proxy
|
| 27 |
+
excluded: [scapula, fingers, muscles, forces, torques, injury_inference]
|