diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..fe3a3b4561850efbd656337cd5a90f8ce180c7b0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +* +!Dockerfile +!requirements-core.txt +!requirements-api.txt +!requirements-api-gpu.txt +!pyproject.toml +!baseball_batting/ +!baseball_batting/*.py +!configs/ +!configs/*.yaml +!tools/ +!tools/setup_api_models.py +!tools/__init__.py +!docs/ +!docs/api-result.schema.json +!docs/coach-payload.schema.json +**/__pycache__ diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..baa38d7ab3826aca8a8e22d753a4f990d5d83495 --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +# Generate your own random secret; do not commit the real .env file. +BASEBALL_API_KEY= +BASEBALL_MAX_UPLOAD_MB=512 +BASEBALL_MAX_ACTIVE_JOBS=8 +BASEBALL_MAX_FRAMES=7200 +BASEBALL_MAX_DURATION_S=120 +BASEBALL_JOB_TIMEOUT_S=1800 +BASEBALL_RETENTION_HOURS=24 +# Required only for the optional HTTPS proxy. Point its DNS at your GPU server. +BASEBALL_DOMAIN= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ae5623960c483cd3d5e4d4016fb43592c6c1a11a --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.venv/ +.anatomy-venv/ +__pycache__/ +.pytest_cache/ +*.egg-info/ +.ipynb_checkpoints/ +artifacts/ +downloads/ +dist/ +*.pyc +.DS_Store +.runtime-*/ +batting_notebook_runtime/ +engine-config.json +capture-metadata.json +source_checkout.json +*-reviewed.json +*.mp4 +*.mov +*.mkv +*.avi +*.webm +api-data/ +.env +.env.* +!.env.example diff --git a/BUILD_STATUS.md b/BUILD_STATUS.md new file mode 100644 index 0000000000000000000000000000000000000000..ff8b93f2713d610bf679c3fccf04a7c4a4df7cfd --- /dev/null +++ b/BUILD_STATUS.md @@ -0,0 +1,72 @@ +# Build status + +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. + +## 2D GPU API and Docker deployment + +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. + +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). + +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). + +`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. + +Engineering evidence for this deployment: + +- **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. +- 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. +- 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. +- 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. + +## Colab test of 2D swing separation + +[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. + +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. + +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. + +## Supplied Colab report and runtime repair + +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. + +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. + +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. + +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. + +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. + +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. + +| Area | Implementation delivered | Remaining execution/validation | +|---|---|---| +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | +| 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. | + +## Executed engineering evidence + +- 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. +- 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. +- 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. +- 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. +- 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. + +## Runtime boundaries + +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. + +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. + +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. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8ccd3ff141061084af15c35b7389268b0f9b750f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +FROM python:3.11-slim-bookworm + +ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \ + PIP_NO_CACHE_DIR=1 BASEBALL_MODEL_ROOT=/opt/models BASEBALL_DATA_ROOT=/data \ + NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility +WORKDIR /app +RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini \ + && rm -rf /var/lib/apt/lists/* +COPY requirements-core.txt requirements-api.txt requirements-api-gpu.txt ./ +RUN python -m pip install --only-binary=:all: -r requirements-api-gpu.txt \ + && python -m pip install --no-deps rtmlib==0.0.16 +COPY pyproject.toml ./ +COPY baseball_batting ./baseball_batting +COPY configs ./configs +COPY tools/setup_api_models.py ./tools/setup_api_models.py +COPY tools/__init__.py ./tools/__init__.py +COPY docs/api-result.schema.json ./docs/api-result.schema.json +COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json +RUN python -m tools.setup_api_models --output /opt/models \ + && python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \ + && groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \ + && mkdir -p /data && chown baseball:baseball /data +USER baseball +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=180s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/readyz', timeout=3)" +ENTRYPOINT ["/usr/bin/tini", "--"] +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"] diff --git a/README.md b/README.md index e8351374ec97660c98d405bd6c98fd0de3704f84..dec8db577fdd811ed292367fac7830436fff486e 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,16 @@ --- -title: Baseball Engine -emoji: 📉 -colorFrom: red -colorTo: blue +title: Baseball Engine 2D API +emoji: ⚾ +colorFrom: blue +colorTo: gray sdk: docker +app_port: 8000 pinned: false -license: mit +short_description: GPU 2D batting analysis API --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Baseball engine 2D API + +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 `. `/readyz` returns 200 once CUDA inference has passed at startup. + +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`. diff --git a/baseball_batting/__init__.py b/baseball_batting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51254abdeffa72a98ae655b265804d3cec83558d --- /dev/null +++ b/baseball_batting/__init__.py @@ -0,0 +1,4 @@ +"""Batting research engine. Importing this package never loads or downloads models.""" + +__version__ = "0.2.0" + diff --git a/baseball_batting/advanced_metrics.py b/baseball_batting/advanced_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..531a68c07d141d674533e88aec4e0b7ac595d68a --- /dev/null +++ b/baseball_batting/advanced_metrics.py @@ -0,0 +1,146 @@ +"""Event-aligned, model-based and independent geometry measurements with explicit gates.""" +from pathlib import Path +import numpy as np +from .contracts import Metric, RTMW_CORE +from .geometry import ground_pixels_to_metres, to_world, rotation +from .motion import angular_velocity, heading, wrapped_difference +from .metrics import flexion_degrees, derivative +from .storage import read_json + + +def event_indices(events,name,max_width=2): + eligible=[e for e in events if e.type==name and e.state=="confirmed" and e.frame_interval] + if len(eligible)!=1:return None,None,"event_unconfirmed_or_ambiguous" + e=eligible[0];a,b=e.frame_interval + if b-a>max_width:return None,e.event_id,"event_interval_too_wide" + return np.arange(a,b+1),e.event_id,None + + +def augment(root,curves,metrics,events,capture,quality,enabled=None): + root=Path(root);clock=capture["timing_source"].get("kind","unknown") + calibration=capture["metadata"].get("calibration",{}) + n=capture["frame_count"] + enabled=enabled or {} + if enabled.get("anatomy") and (root/"temporal3d_status.json").exists(): + temporal=read_json(root/"temporal3d_status.json") + if temporal.get("status") in {"complete","partial"}: + data=np.load(root/temporal["trajectory_path"],allow_pickle=False) + curves["raw_body3d_camera_m"]=data["raw_camera_m"] + curves["fitted_body3d_camera_m"]=data["keypoints_camera_m"] + curves["body3d_reprojection_px"]=data["reprojection_px"] + physical=np.array([f["physical_s"] for f in capture["frames"]],float) + 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"]) + def emit(name,values,unit,geometry,event=None,reason=None,provenance=None,summary="mean",uncertainty="unknown"): + used=np.arange(n) if event is None else event[0] + event_id=None if event is None else event[1] + if event is not None:reason=reason or event[2] + value=None;valid=np.array([],int) + if reason is None and values is not None and used is not None: + used=np.asarray(used,int);v=np.asarray(values)[used];valid=used[np.isfinite(v)] + if event is not None and len(valid)!=len(used):reason="event_samples_missing" + elif not len(valid):reason="missing_supported_samples" + else: + sample=np.asarray(values)[valid] + value=float(np.max(sample) if summary=="max" else np.median(sample) if summary=="median" else np.mean(sample)) + elif reason is None:reason="stage_unavailable" + metrics[:]=[m for m in metrics if m.metric_id!=name] + metrics.append(Metric(name,"1.1",value,unit,"supported" if value is not None else "unsupported", + provenance or [],valid.tolist(),geometry,clock,reason,event_id,uncertainty)) + # Event-aligned image measures preserve the distinction from full-recording summaries. + contact=event_indices(events,"contact",quality["max_event_interval_frames"]) + foot=event_indices(events,"lead_foot_contact",quality["max_event_interval_frames"]) + onset=event_indices(events,"forward_swing_onset",quality["max_event_interval_frames"]) + for side in ("left","right"): + for joint in ("knee","elbow"): + emit(f"{side}_{joint}_fitted_3d_flexion_median",None,"deg","not_established",reason="anatomical_fit_unavailable") + for name,unit in (("pelvis_thorax_axial_twist_at_contact","deg"),("thorax_peak_angular_velocity","deg/s"),("thorax_minus_pelvis_peak_time","s")): + emit(name,None,unit,"not_established",reason="anatomical_fit_or_required_context_unavailable") + for side in ("left","right"): + for joint in ("knee","elbow"): + emit(f"{side}_{joint}_projected_flexion_at_contact",curves[f"{side}_{joint}_projected_flexion_deg"],"deg_projected", + "oriented_image_projection",contact,provenance=["body_observations"]) + try: + feet=np.stack([curves["body_pixels"][:,RTMW_CORE[s+"_big_toe"]] for s in ("left","right")],1) + feet=ground_pixels_to_metres(feet,calibration) + # A calibrated planar result requires independently reviewed on-ground support. + ground_context=capture["metadata"].get("event_context",{}) + if not ground_context.get("source"):raise ValueError("ground_contact_review_source_missing") + support=ground_context.get("ground_contact_frames",[]) + if any(not isinstance(i,int) or not 0<=iquality["max_regularization_sensitivity_m"]: + raise ValueError("anatomical_regularization_sensitivity_exceeds_profile_limit") + data=np.load(root/status["trajectory_path"],allow_pickle=False) + names=data["marker_names"].tolist();points=data["marker_positions_m"] + for side in ("left","right"): + for joint,parts in (("elbow",("shoulder","elbow","wrist")),("knee",("hip","knee","ankle"))): + values=flexion_degrees(*[points[:,names.index(side+"_"+p)] for p in parts]) + curves[f"{side}_{joint}_fitted_3d_flexion_deg"]=values + 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") + segments=data["segment_names"].tolist();r=data["segment_rotations"] + from scipy.spatial.transform import Rotation + relative=r[:,segments.index("pelvis")].transpose(0,2,1)@r[:,segments.index("thorax")] + valid=np.isfinite(relative).all(axis=(1,2));twist=np.full(n,np.nan) + quaternion=Rotation.from_matrix(relative[valid]).as_quat() + # Twist about pelvis-local cranial Y, separate from horizontal headings. + twist[valid]=np.degrees(2*np.arctan2(quaternion[:,1],quaternion[:,3])) + twist=np.degrees(np.arctan2(np.sin(np.radians(twist)),np.cos(np.radians(twist)))) + curves["pelvis_thorax_axial_twist_deg"]=twist + 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") + to_world(np.zeros((1,3)),calibration) # Validate world convention before rotations. + transform=rotation(calibration["world_from_camera"]["rotation"]) + pelvis=transform@r[:,segments.index("pelvis")];thorax=transform@r[:,segments.index("thorax")] + separation=np.degrees(wrapped_difference(heading(thorax),heading(pelvis))) + curves["pelvis_thorax_heading_separation_deg"]=separation + emit("pelvis_thorax_heading_separation",separation,"deg","calibrated_world_model_proxy",contact,provenance=["MHR_fitted_proxy","OpenSim_IK"],uncertainty="fit_and_regularization_sensitivity") + if not timing_ok:raise ValueError("physical_clock_or_timing_integrity_failed") + velocity=angular_velocity(pelvis,physical);curves["pelvis_angular_velocity_world_rad_s"]=velocity + speed=np.degrees(np.linalg.norm(velocity,axis=1)) + 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") + thorax_velocity=angular_velocity(thorax,physical);curves["thorax_angular_velocity_world_rad_s"]=thorax_velocity + thorax_speed=np.degrees(np.linalg.norm(thorax_velocity,axis=1)) + 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") + good_p,good_t=np.flatnonzero(np.isfinite(speed)),np.flatnonzero(np.isfinite(thorax_speed)) + if len(good_p) and len(good_t): + p,t=good_p[np.argmax(speed[good_p])],good_t[np.argmax(thorax_speed[good_t])] + 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") + except (ValueError,KeyError,FileNotFoundError) as error: + for name,unit in (("pelvis_thorax_heading_separation","deg"),("pelvis_peak_angular_velocity","deg/s")): + 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)) + try: + if not enabled.get("bat3d") or not (root/"bat3d_status.json").exists():raise ValueError("independent_bat_geometry_unavailable") + status=read_json(root/"bat3d_status.json") + if status["status"] not in {"partial","complete"}:raise ValueError("independent_bat_geometry_unavailable") + data=np.load(root/status["trajectory_path"],allow_pickle=False);sweet=data["sweet_spot_world_m"] + curves["bat_sweet_spot_world_m"]=sweet + if not np.isfinite(sweet).any():raise ValueError("bat_world_frame_unavailable") + if not timing_ok:raise ValueError("physical_clock_or_timing_integrity_failed") + velocity=derivative(sweet,physical);curves["bat_sweet_spot_velocity_world_m_s"]=velocity + speed=np.linalg.norm(velocity,axis=1) + attack=np.degrees(np.arctan2(velocity[:,1],np.linalg.norm(velocity[:,[0,2]],axis=1))) + attack[speed<1e-6]=np.nan;curves["bat_attack_direction_deg"]=attack + 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") + emit("bat_attack_angle_at_contact",attack,"deg",status["geometry_source"],contact,provenance=["independent_bat_geometry","velocity_direction"],uncertainty="geometry_and_event_sensitivity_pending") + except (ValueError,KeyError,FileNotFoundError) as error: + for name,unit in (("bat_sweet_spot_speed_at_contact","m/s"),("bat_attack_angle_at_contact","deg")): + emit(name,None,unit,"not_established",reason=str(error)) + return metrics diff --git a/baseball_batting/anatomy.py b/baseball_batting/anatomy.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a49d0a92b158999ef8314d8b769fe0bd8d179c --- /dev/null +++ b/baseball_batting/anatomy.py @@ -0,0 +1,273 @@ +"""Explicit 35-DOF OpenSim kinematic proxy, weighted IK and sparse sequence refinement.""" +from pathlib import Path +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation +from .temporal3d import MHR_CORE +from .motion import contiguous_segments, sparse_temporal_pattern +from .storage import StageCache, digest, atomic_json, read_json, sha256_file + + +def unit(vector): + vector = np.asarray(vector, float) + if np.linalg.norm(vector) < 1e-8: + raise ValueError("Degenerate neutral segment frame") + return vector/np.linalg.norm(vector) + + +def pin_frame(axis, reference): + z = unit(axis) + x = np.asarray(reference)-z*np.dot(reference, z) + if np.linalg.norm(x) < 1e-8: + x = np.eye(3)[np.argmin(np.abs(z))]; x -= z*np.dot(x, z) + x = unit(x) + return np.column_stack([x, np.cross(z, x), z]) + + +def model_spec(neutral, settings): + """Landmark-derived origins/offsets are proxies, never assumed native rig centres.""" + neutral = np.asarray(neutral, float) + if neutral.shape != (70, 3) or not np.isfinite(neutral).all(): + raise ValueError("Neutral MHR70 must contain 70 finite metre positions") + p = {name: neutral[index] for name, index in MHR_CORE.items()} + hip = (p["left_hip"]+p["right_hip"])/2 + shoulders = (p["left_shoulder"]+p["right_shoulder"])/2 + y = unit(shoulders-hip) + x = unit(p["left_hip"]-p["right_hip"]) + x = unit(x-y*np.dot(x, y)); z = unit(np.cross(x, y)) + basis = np.column_stack([x, y, z]) + bodies = {"pelvis": {"origin": hip.tolist(), "rotation": basis.tolist()}, + "thorax": {"origin": shoulders.tolist(), "rotation": basis.tolist()}} + joints, coordinates, markers = [], [], {} + + def joint(name, kind, parent, child, centre, frame): + if child not in bodies: + bodies[child] = {"origin": np.asarray(centre).tolist(), "rotation": basis.tolist()} + parent_origin = np.zeros(3) if parent == "ground" else np.array(bodies[parent]["origin"]) + parent_rotation = np.eye(3) if parent == "ground" else np.array(bodies[parent]["rotation"]) + child_origin, child_rotation = np.array(bodies[child]["origin"]), np.array(bodies[child]["rotation"]) + n = {"FreeJoint": 6, "BallJoint": 3, "PinJoint": 1, "UniversalJoint": 2}[kind] + ids = list(range(len(coordinates), len(coordinates)+n)) + for i in range(n): + bounds = [-100, 100] if kind == "FreeJoint" and i >= 3 else settings["soft_coordinate_range_rad"] + if kind == "UniversalJoint": bounds = settings["universal_range_rad"] + coordinates.append({"name": name+"_"+str(i), "unit": "m" if kind == "FreeJoint" and i >= 3 else "rad", "range": bounds}) + joints.append({"name": name, "kind": kind, "parent": parent, "child": child, "coordinates": ids, + "parent_location": (parent_rotation.T@(centre-parent_origin)).tolist(), + "child_location": (child_rotation.T@(centre-child_origin)).tolist(), + "parent_orientation": (parent_rotation.T@frame).tolist(), + "child_orientation": (child_rotation.T@frame).tolist()}) + + # Root at its neutral origin: the six coordinates encode changes from neutral. + joint("root", "FreeJoint", "ground", "pelvis", hip, basis) + joint("pelvis_thorax", "BallJoint", "pelvis", "thorax", (hip+shoulders)/2, basis) + for side in ("left", "right"): + hip_p, knee, ankle = [p[side+"_"+n] for n in ("hip", "knee", "ankle")] + shoulder, elbow, wrist = [p[side+"_"+n] for n in ("shoulder", "elbow", "wrist")] + joint(side+"_hip", "BallJoint", "pelvis", side+"_thigh", hip_p, basis) + joint(side+"_knee", "PinJoint", side+"_thigh", side+"_shank", knee, pin_frame(x, y)) + joint(side+"_ankle", "UniversalJoint", side+"_shank", side+"_foot", ankle, basis) + joint(side+"_shoulder", "BallJoint", "thorax", side+"_upper_arm", shoulder, basis) + # Flexion plane is defined explicitly in the neutral frame; no scapular DoF. + hinge = np.cross(unit(elbow-shoulder), y) + joint(side+"_elbow", "PinJoint", side+"_upper_arm", side+"_forearm", elbow, pin_frame(hinge, y)) + joint(side+"_forearm_rotor", "PinJoint", side+"_forearm", side+"_rotor", elbow, pin_frame(wrist-elbow, y)) + joint(side+"_wrist", "UniversalJoint", side+"_rotor", side+"_hand", wrist, basis) + assignments = {"hip": "pelvis", "knee": side+"_thigh", "ankle": side+"_shank", + "big_toe": side+"_foot", "small_toe": side+"_foot", "heel": side+"_foot", + "shoulder": "thorax", "elbow": side+"_upper_arm", "wrist": side+"_rotor"} + for part, body in assignments.items(): + name = side+"_"+part + markers[name] = {"body": body, "offset": (basis.T@(p[name]-bodies[body]["origin"])).tolist(), "mhr70_index": MHR_CORE[name]} + # Dorsal hand regression proxies give wrist/rotor some orientation support. + for name, index in ((side+"_index_mcp", 49 if side == "left" else 28), + (side+"_little_mcp", 61 if side == "left" else 40)): + markers[name] = {"body": side+"_hand", "offset": (basis.T@(neutral[index]-wrist)).tolist(), "mhr70_index": index} + if len(coordinates) != 35: + raise AssertionError("Model must have exactly 35 coordinates") + return {"schema_version": "1.0", "model_id": settings["model_id"], "version": settings["version"], + "bodies": bodies, "joints": joints, "coordinates": coordinates, "markers": markers, + "source_kind": "model_regression_proxy", "independent_observation": False, + "neutral_basis_definition": "x toward anatomical left; y cranial; z x cross y", + "coordinate_definition": "primitive coordinates; named measurements derive from segment frames", + "dynamics": "disabled; placeholder masses and inertia"} + + +def forward_kinematics(spec, q): + """Mirror the documented Free/Ball XYZ, Pin Z and Universal XY primitives.""" + transforms = {"ground": (np.eye(3), np.zeros(3))} + for j in spec["joints"]: + r_parent, t_parent = transforms[j["parent"]] + values = np.asarray(q)[j["coordinates"]] + if j["kind"] in {"BallJoint", "FreeJoint"}: + rotation = Rotation.from_euler("XYZ", values[:3]).as_matrix() + elif j["kind"] == "PinJoint": + rotation = Rotation.from_euler("Z", values[0]).as_matrix() + else: + rotation = Rotation.from_euler("XY", values).as_matrix() + r = r_parent@j["parent_orientation"]@rotation@np.asarray(j["child_orientation"]).T + shift = values[3:] if j["kind"] == "FreeJoint" else np.zeros(3) + t = t_parent+r_parent@np.asarray(j["parent_location"])+r_parent@j["parent_orientation"]@shift-r@j["child_location"] + transforms[j["child"]] = (r, t) + markers = np.array([transforms[m["body"]][1]+transforms[m["body"]][0]@m["offset"] for m in spec["markers"].values()]) + return markers, transforms + + +def build_opensim(spec, path=None): + import opensim as osim + model = osim.Model(); model.setName(spec["model_id"]) + bodies = {} + def vec(v): return osim.Vec3(*map(float, v)) + for name in spec["bodies"]: + body = osim.Body(name, 1., osim.Vec3(0), osim.Inertia(1., 1., 1.)) + model.addBody(body); bodies[name] = body + for j in spec["joints"]: + parent = model.getGround() if j["parent"] == "ground" else bodies[j["parent"]] + joint = getattr(osim, j["kind"])(j["name"], parent, vec(j["parent_location"]), + vec(Rotation.from_matrix(j["parent_orientation"]).as_euler("XYZ")), bodies[j["child"]], + vec(j["child_location"]), vec(Rotation.from_matrix(j["child_orientation"]).as_euler("XYZ"))) + for i, index in enumerate(j["coordinates"]): + coordinate = joint.upd_coordinates(i) + coordinate.setName(spec["coordinates"][index]["name"]) + coordinate.setRangeMin(spec["coordinates"][index]["range"][0]) + coordinate.setRangeMax(spec["coordinates"][index]["range"][1]) + coordinate.setDefaultValue(0.) + model.addJoint(joint) + for name, marker in spec["markers"].items(): + model.addMarker(osim.Marker(name, bodies[marker["body"]], vec(marker["offset"]))) + model.finalizeConnections(); model.initSystem() + if path: model.printToXML(str(path)) + return model + + +def trc(path, names, targets, times): + n = len(times); dt = np.median(np.diff(times)) if n > 1 else 1. + header = ["PathFileType\t4\t(X/Y/Z)\tmarkers.trc", "DataRate\tCameraRate\tNumFrames\tNumMarkers\tUnits\tOrigDataRate\tOrigDataStartFrame\tOrigNumFrames", + f"{1/dt}\t{1/dt}\t{n}\t{len(names)}\tm\t{1/dt}\t1\t{n}", + "Frame#\tTime\t"+"\t".join(name+"\t\t" for name in names), + "\t\t"+"\t".join(f"X{i+1}\tY{i+1}\tZ{i+1}" for i in range(len(names))), ""] + for i, (row, time) in enumerate(zip(targets, times)): + header.append(f"{i+1}\t{time:.10f}\t"+"\t".join(f"{v:.10f}" for v in row.reshape(-1))) + Path(path).write_text("\n".join(header)+"\n") + + +def weighted_ik(model, spec, targets, weights, times, workdir): + import opensim as osim + names = list(spec["markers"]) + neutral, _ = forward_kinematics(spec, np.zeros(35)) + safe = np.where(np.isfinite(targets), targets, neutral[None]) + marker_file = Path(workdir)/"ik_targets.trc"; trc(marker_file, names, safe, times) + marker_weights = osim.SetMarkerWeights() + supported=np.flatnonzero((weights>0).sum(axis=1)>=6) + if not len(supported):return np.full((len(times),35),np.nan) + first=int(supported[0]) + for j,name in enumerate(names): marker_weights.cloneAndAppend(osim.MarkerWeight(name, float(weights[first,j]))) + reference = osim.MarkersReference(str(marker_file), marker_weights) + solver = osim.InverseKinematicsSolver(model, reference, osim.SimTKArrayCoordinateReference()) + solver.setAccuracy(1e-6) + state = model.initSystem(); coordinates = model.getCoordinateSet() + out = np.full((len(times), 35), np.nan) + initialized=False + for i, time in enumerate(times): + state.setTime(float(time)) + if (weights[i] > 0).sum() < 6: continue + try: + # OpenSim creates its marker goal during assemble(); updating weights + # before the first assemble dereferences an uninitialized native goal. + if initialized: + for j,name in enumerate(names):solver.updateMarkerWeight(name,float(weights[i,j])) + if i == 0 or not np.isfinite(out[i-1]).all(): solver.assemble(state) + else: solver.track(state) + initialized=True + out[i] = [coordinates.get(c["name"]).getValue(state) for c in spec["coordinates"]] + except RuntimeError: + continue + return out + + +def refine_trajectory(spec, initial, targets, weights, times, settings): + out = initial.copy(); diagnostic = [] + for a, b in contiguous_segments(np.isfinite(initial).all(axis=1), times): + if b-a < 3: continue + start = initial[a:b] + dt = np.diff(times[a:b]) + safe = np.nan_to_num(targets[a:b]); w = np.sqrt(weights[a:b])[..., None] + lower,upper=np.array([c["range"] for c in spec["coordinates"]]).T + def data(q): return (np.array([forward_kinematics(spec, row)[0] for row in q])-safe)*w + def objective(flat): + q = flat.reshape(-1, 35) + velocity = np.diff(q, axis=0)/dt[:, None] + acceleration = np.diff(velocity, axis=0)/((dt[1:]+dt[:-1])/2)[:, None] + limits=np.maximum(lower-q,0)+np.maximum(q-upper,0) + return np.r_[data(q).reshape(-1), np.sqrt(settings["temporal_weight"])*acceleration.reshape(-1),.01*limits.reshape(-1)] + from scipy.sparse import vstack,eye + pattern=vstack([sparse_temporal_pattern(b-a,35,targets.shape[1]),eye((b-a)*35)],format="csr") + candidate = least_squares(objective, start.reshape(-1), jac_sparsity=pattern, + max_nfev=settings["refinement_max_evaluations"], loss="soft_l1", f_scale=.02).x.reshape(-1, 35) + before, after = np.sqrt(np.mean(data(start)**2)), np.sqrt(np.mean(data(candidate)**2)) + retained = after <= before+settings["refinement_observation_tolerance_m"] + if retained: out[a:b] = candidate + diagnostic.append({"frames": [a,b-1], "weighted_coordinate_rmse_before_m": float(before), + "weighted_coordinate_rmse_after_m": float(after), "accepted": bool(retained)}) + return out, diagnostic + + +def run_anatomy(request, capture, config): + root = Path(request["root"]) + try: + import yaml + status = read_json(root/"temporal3d_status.json") + if status.get("status") not in {"partial", "complete"}: raise ValueError("Temporal trajectory unavailable") + source = root/status["trajectory_path"] + settings = yaml.safe_load(Path(config.anatomical_config_path).read_text()) + cache = StageCache(root, "anatomy", digest({"upstream": status["cache_key"], "settings": settings})) + if cache.valid("trajectory"): + atomic_json(root/"anatomy_status.json", read_json(cache.root/"status.json")); return + data = np.load(source, allow_pickle=False) + # Convert camera neutral axes back once. Model targets remain in camera axes: + # a FreeJoint rotates/translates the neutral model to those proxy targets. + neutral = data["neutral_mhr70_m"]*np.array([1., -1., -1.]) + spec = model_spec(neutral, settings) + atomic_json(cache.root/"model_spec.json", spec) + model = build_opensim(spec, cache.root/"BattingKinematics-v1.osim") + indices = [m["mhr70_index"] for m in spec["markers"].values()] + targets = data["keypoints_camera_m"][:, indices] + # 3D targets are fitted model proxies. Weights reflect their 2D support where + # available; hand-only proxy markers receive a weak explicitly recorded prior. + weights = data["observation_weights"][:, indices].copy() + for j, name in enumerate(spec["markers"]): + if name.endswith("_mcp"): weights[:, j] = np.maximum(weights[:, j], .1) + weights *= data["accepted_frames"][:, None] + weights[~np.isfinite(targets).all(axis=2)] = 0 + times = data["fitting_times"] + q = weighted_ik(model, spec, targets, weights, times, cache.root) + q, refinement = refine_trajectory(spec, q, targets, weights, times, settings) + positions = np.full_like(targets, np.nan) + rotations = np.full((len(q), len(spec["bodies"]), 3, 3), np.nan) + accepted = np.zeros(len(q), bool); residual = np.full(targets.shape[:2], np.nan) + for i in np.flatnonzero(np.isfinite(q).all(axis=1)): + markers, transforms = forward_kinematics(spec, q[i]) + error = np.linalg.norm(markers-targets[i], axis=-1) + residual[i] = error + eligible = weights[i] > 0 + if not eligible.any() or np.sqrt(np.mean(error[eligible]**2)) > settings["marker_fit_max_rmse_m"]: continue + accepted[i] = True; positions[i] = markers + rotations[i] = np.array([transforms[name][0] for name in spec["bodies"]]) + if not accepted.any(): raise ValueError("No IK frames passed marker agreement") + path = cache.root/"trajectory.npz" + np.savez_compressed(path, coordinates=q, marker_positions_m=positions, segment_rotations=rotations, + residual_m=residual, accepted_frames=accepted, fitting_times=times, + marker_names=np.array(list(spec["markers"])), segment_names=np.array(list(spec["bodies"]))) + result = {"status": "complete" if accepted.all() else "partial", "frames_fitted": int(accepted.sum()), + "cache_key": cache.key, "trajectory_path": str(path.relative_to(root)), "model_id": spec["model_id"], + "model_sha256": sha256_file(cache.root/"BattingKinematics-v1.osim"), "spec_sha256": digest(spec), + "dof": 35, "target_source": "MHR70_model_regression_proxy_not_independent_reference", + "coordinate_space": "camera_x_right_y_down_z_forward_metres", "refinement": refinement, + "geometry_source": status["geometry_source"], "validation": "reference-validation-pending", + "maximum_regularization_sensitivity_m":status.get("maximum_regularization_sensitivity_m"), + "dynamics": "disabled", "rotation_coordinates": "primitive_intrinsic_XYZ_XY_Z"} + atomic_json(cache.root/"status.json", result) + cache.commit("trajectory", [path, cache.root/"status.json", cache.root/"model_spec.json", cache.root/"BattingKinematics-v1.osim"]) + except Exception as error: + result = {"status": "unavailable", "reason": str(error)[:300], "error_type": type(error).__name__} + atomic_json(root/"anatomy_status.json", result) diff --git a/baseball_batting/annotations.py b/baseball_batting/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1b09ff8e61d8b257f3f8ec94b808f1f747ddb4 --- /dev/null +++ b/baseball_batting/annotations.py @@ -0,0 +1,54 @@ +"""Reviewed labels are immutable input records, separate from automatic observations.""" +from pathlib import Path +import json +import math +from .contracts import RTMW_CORE + +def load_annotations(path, input_hash, frame_count, width, height): + if not path: + return {"schema_version": "1.0", "frames": {}, "events": [], "annotator": None} + data = json.loads(Path(path).read_text()) + if data.get("schema_version") != "1.0" or data.get("input_sha256") != input_hash: + raise ValueError("Annotations must identify this exact video and schema") + if not data.get("annotator"): + raise ValueError("Reviewed labels require an annotator ID") + for raw_id, frame in data.get("frames", {}).items(): + index = int(raw_id) + if str(index) != raw_id or not 0 <= index < frame_count: + raise ValueError("Invalid annotation frame ID") + for name, p in frame.get("landmarks", {}).items(): + if name not in RTMW_CORE: + raise ValueError(f"Unknown RTMW landmark {name}") + _point(p, width, height) + if any(name not in RTMW_CORE for name in frame.get("occluded_landmarks", [])): + raise ValueError("Unknown occluded RTMW landmark") + for name in ("knob", "barrel", "ball"): + if frame.get(name) is not None: + _point(frame[name], width, height) + if "crop" in frame: + a, b, c, d = frame["crop"] + if not 0 <= a < c <= width or not 0 <= b < d <= height: + raise ValueError("Crop must lie in oriented image bounds") + known_events = {"contact", "forward_swing_onset", "lead_foot_lift", "lead_foot_contact", "load", "follow_through", "miss", "dry_swing", "contact_unknown"} + for event in data.get("events", []): + if event.get("type") not in known_events or event.get("state") not in {"confirmed", "unknown", "absent"}: + raise ValueError("Invalid reviewed event type/state") + interval = event.get("frame_interval") + if interval is not None and (len(interval) != 2 or any(not isinstance(f, int) for f in interval) + or not 0 <= interval[0] <= interval[1] < frame_count): + raise ValueError("Reviewed event interval is outside the recording") + if event["state"] == "confirmed": + if not interval or len(interval) != 2 or not 0 <= interval[0] <= interval[1] < frame_count: + raise ValueError("Confirmed event needs an in-range frame interval") + if not event.get("evidence_frames") or not event.get("evidence_description"): + raise ValueError("Confirmed events need observable evidence and a description") + for f in event.get("evidence_frames", []): + if not isinstance(f, int) or not 0 <= f < frame_count: + raise ValueError("Invalid event evidence frame") + return data + +def _point(p, width, height): + if len(p) != 2 or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in p): + raise ValueError("Annotation points must be finite x,y pairs") + if not 0 <= p[0] < width or not 0 <= p[1] < height: + raise ValueError("Annotation lies outside oriented frame") diff --git a/baseball_batting/api.py b/baseball_batting/api.py new file mode 100644 index 0000000000000000000000000000000000000000..043b7e7df881c156e0b67925d7023938717f4d8f --- /dev/null +++ b/baseball_batting/api.py @@ -0,0 +1,214 @@ +"""HTTP upload/status/result API. Start with Uvicorn --factory --workers 1.""" +from contextlib import asynccontextmanager +import asyncio +import hmac +import json +from pathlib import Path +import shutil +from typing import Annotated +from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile +from fastapi.responses import JSONResponse, StreamingResponse +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from pydantic import ValidationError +from starlette.background import BackgroundTask +from starlette.concurrency import run_in_threadpool +from .api_contract import AnalysisInput +from .api_jobs import ApiSettings, JobService, QueueFull +from .storage import atomic_json, read_json, sha256_file + +ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"} +BEARER = HTTPBearer(auto_error=False) + + +class UploadGuard: + """Authenticate before multipart parsing and limit its total streamed body.""" + def __init__(self, app, settings, service): + self.app, self.settings, self.service = app, settings, service + self.upload_slots = asyncio.Semaphore(2) + + async def __call__(self, scope, receive, send): + if scope["type"] != "http" or not scope["path"].startswith("/v1/"): + return await self.app(scope, receive, send) + headers = dict(scope["headers"]) + authorization = headers.get(b"authorization", b"") + supplied = authorization[7:] if authorization.lower().startswith(b"bearer ") else b"" + if not hmac.compare_digest(supplied, self.settings.api_key.encode()): + return await JSONResponse({"detail": "Invalid or missing API key"}, status_code=401, + headers={"WWW-Authenticate": "Bearer"})(scope, receive, send) + limit = self.settings.max_upload_bytes + 1024 * 1024 + size = headers.get(b"content-length") + if size: + try: oversized = int(size) > limit or int(size) < 0 + except ValueError: oversized = True + if oversized: + return await JSONResponse({"detail": "Request exceeds upload limit"}, status_code=413)(scope, receive, send) + received = 0 + async def limited_receive(): + nonlocal received + message = await receive() + received += len(message.get("body", b"")) + if received > limit: + raise HTTPException(413, "Request exceeds upload limit") + return message + is_upload = scope["method"] == "POST" and scope["path"] == "/v1/analyses" + if is_upload: + if not self.service.ready: + return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send) + if self.upload_slots.locked(): + return await JSONResponse({"detail": "Too many concurrent uploads"}, status_code=429)(scope, receive, send) + async with self.upload_slots: + return await self.app(scope, limited_receive, send) + return await self.app(scope, limited_receive, send) + + +def create_app(settings=None, service=None): + settings = settings or ApiSettings.from_env() + service = service or JobService(settings) + @asynccontextmanager + async def lifespan(app): + service.start() + try: yield + finally: service.stop() + app = FastAPI(title="Baseball 2D GPU API", version="1.1.0", lifespan=lifespan, + description="Batting points and estimated swing measurements for a separate coach agent. GPU required; all 3D stages disabled.") + app.state.service = service + app.add_middleware(UploadGuard, settings=settings, service=service) + + def authenticated(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(BEARER)]): + # Documents Bearer authorization in OpenAPI; UploadGuard also checks before body parsing. + if credentials is None or not hmac.compare_digest(credentials.credentials.encode(), settings.api_key.encode()): + raise HTTPException(401, "Invalid or missing API key", headers={"WWW-Authenticate": "Bearer"}) + + def job_record(job_id): + try: directory = service.job_directory(job_id) + except ValueError: raise HTTPException(404, "Job not found") + record = service.store.get(job_id) + if not record: raise HTTPException(404, "Job not found") + return directory, record + + @app.get("/healthz") + def health(): + return {"status": "alive", "gpu_ready": service.ready, "body_3d": False} + + @app.get("/readyz") + def ready(): + return JSONResponse({"ready": service.ready, "reason": service.readiness_reason, + "device": "cuda", "body_3d": False}, status_code=200 if service.ready else 503) + + @app.get("/v1/capabilities", dependencies=[Depends(authenticated)]) + def capabilities(): + return {"discipline": "hitting", "device": "cuda", "body_3d": False, + "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True, + "automatic_events": True, "swing_metrics": True, "estimated_only": True, + "measurement_validation": "reference_validation_pending", "coaching": False, + "limits": {"upload_bytes": settings.max_upload_bytes, "duration_s": settings.max_duration_s, + "frames": settings.max_frames, "pixels": settings.max_pixels}, + "retention_hours": settings.retention_s / 3600} + + @app.get("/v1/input-schema", dependencies=[Depends(authenticated)]) + def input_schema(): + return AnalysisInput.model_json_schema() + + @app.get("/v1/output-schema", dependencies=[Depends(authenticated)]) + def output_schema(): + return read_json(Path(__file__).resolve().parents[1] / "docs/api-result.schema.json") + + @app.get("/v1/coach-payload-schema", dependencies=[Depends(authenticated)]) + def coach_schema(): + return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json") + + @app.post("/v1/analyses", status_code=202, dependencies=[Depends(authenticated)]) + async def create_analysis(video: Annotated[UploadFile, File(description="Original recording")], + options: Annotated[str, Form(description="AnalysisInput as a JSON string")] = "{}"): + identifier = None + try: + if not service.ready: raise HTTPException(503, "GPU worker is not ready; check /readyz") + if len(options.encode()) > 512 * 1024: raise HTTPException(413, "Options exceed size limit") + try: parsed = AnalysisInput.model_validate_json(options) + except ValidationError as error: + # No echo of arbitrary client inputs in error responses. + details = [{"loc": list(item["loc"]), "type": item["type"], "msg": item["msg"]} + for item in error.errors(include_url=False, include_input=False)] + raise HTTPException(422, details) + suffix = Path(video.filename or "").suffix.lower() + if suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, "Unsupported video extension") + if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes: + raise HTTPException(507, "Insufficient storage") + try: identifier = service.store.create(settings.max_active_jobs) + except QueueFull: raise HTTPException(429, "GPU queue is full", headers={"Retry-After": "30"}) + directory = service.job_directory(identifier) + directory.mkdir() + size = 0 + with (directory / ("input" + suffix)).open("wb") as destination: + while block := await video.read(1024 * 1024): + size += len(block) + if size > settings.max_upload_bytes: raise HTTPException(413, "Video exceeds upload limit") + if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes + len(block): + raise HTTPException(507, "Insufficient storage") + destination.write(block) + if size == 0: raise HTTPException(422, "Video is empty") + atomic_json(directory / "request.json", parsed.model_dump(exclude_none=True)) + service.store.update(identifier, "queued") + service.wakeup.set() + return {"job_id": identifier, "status": "queued", + "status_url": f"/v1/analyses/{identifier}", "result_url": f"/v1/analyses/{identifier}/result", + "coach_payload_url": f"/v1/analyses/{identifier}/coach-payload"} + except BaseException: + if identifier: + service.store.forget(identifier) + shutil.rmtree(service.job_directory(identifier), ignore_errors=True) + raise + finally: + await video.close() + + @app.get("/v1/analyses/{job_id}", dependencies=[Depends(authenticated)]) + def status(job_id: str): + with service.mutation_lock: + directory, record = job_record(job_id) + progress = read_json(directory / "progress.json") if (directory / "progress.json").is_file() else None + return {"job_id": job_id, "status": record["status"], "created_at": record["created"], + "updated_at": record["updated"], "progress": progress, "error": record["error"], + "result_url": f"/v1/analyses/{job_id}/result" if record["status"] == "completed" else None, + "coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None} + + @app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)]) + def get_coach_payload(job_id: str): + with service.mutation_lock: + directory, record = job_record(job_id) + if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status") + path = directory / "coach-payload.json" + if record.get("coach_payload_sha256") is None: + raise HTTPException(409, "This older job has no coach payload; submit the video again") + if not path.is_file() or sha256_file(path) != record["coach_payload_sha256"]: + raise HTTPException(500, "Stored coach payload failed its integrity check") + payload = read_json(path) + return JSONResponse(payload, headers={"Cache-Control": "no-store"}) + + @app.get("/v1/analyses/{job_id}/result", dependencies=[Depends(authenticated)]) + def result(job_id: str): + with service.mutation_lock: + directory, record = job_record(job_id) + if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status") + path = directory / "result.json" + if not path.is_file() or sha256_file(path) != record["result_sha256"]: + raise HTTPException(500, "Stored result failed its integrity check") + # An open descriptor stays usable when DELETE/retention removes the path. + handle = path.open("rb") + size = path.stat().st_size + async def stream(): + try: + while block := await run_in_threadpool(handle.read, 64 * 1024): + yield block + finally: + handle.close() + return StreamingResponse(stream(), media_type="application/json", + headers={"Cache-Control": "no-store", "Content-Length": str(size)}, + background=BackgroundTask(handle.close)) + + @app.delete("/v1/analyses/{job_id}", status_code=202, dependencies=[Depends(authenticated)]) + def delete(job_id: str): + job_record(job_id) + status = service.delete(job_id) + return {"job_id": job_id, "status": status} + + return app diff --git a/baseball_batting/api_contract.py b/baseball_batting/api_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..6950b5c4a498882e6df42cee2fa80f939cf31f11 --- /dev/null +++ b/baseball_batting/api_contract.py @@ -0,0 +1,72 @@ +"""Public inputs: clients cannot supply paths, models, devices or 3D switches.""" +from typing import Literal +from pydantic import BaseModel, ConfigDict, Field, model_validator + + +class TimingInput(BaseModel): + model_config = ConfigDict(extra="forbid", allow_inf_nan=False) + kind: Literal["unknown", "unretimed", "constant_slowdown", "explicit"] = "unknown" + source: str | None = Field(default=None, min_length=1, max_length=512) + factor: float | None = Field(default=None, gt=0) + all_captured_frames_retained: bool | None = None + physical_times_s: list[float] | None = Field(default=None, min_length=1, max_length=20000) + + @model_validator(mode="after") + def check_evidence(self): + if self.kind != "unknown" and not (self.source and self.source.strip()): + raise ValueError("Known capture timing requires a source description") + if self.kind == "constant_slowdown": + if self.factor is None or self.all_captured_frames_retained is not True: + raise ValueError("Slow motion requires its factor and all captured frames retained") + if self.kind == "explicit": + if not self.physical_times_s or any(b <= a for a, b in + zip(self.physical_times_s, self.physical_times_s[1:])): + raise ValueError("Explicit capture times must increase strictly") + return self + + +class RepRange(BaseModel): + model_config = ConfigDict(extra="forbid") + start_frame: int = Field(ge=0, strict=True) + end_frame: int = Field(ge=0, strict=True) + + @model_validator(mode="after") + def ordered(self): + if self.end_frame < self.start_frame: + raise ValueError("end_frame precedes start_frame") + return self + + +class AnalysisInput(BaseModel): + model_config = ConfigDict(extra="forbid", allow_inf_nan=False) + discipline: Literal["hitting"] = "hitting" + view: Literal["face_on", "unknown"] = "unknown" + handedness: Literal["left", "right"] | None = None + level: Literal["hs_jv", "hs_varsity", "college"] | None = None + pitcher_direction: Literal["image_left", "image_right"] | None = None + body_height_px: float | None = Field(default=None, gt=0) + body_height_source: str | None = Field(default=None, min_length=1, max_length=512) + rotation_degrees: Literal[0, 90, 180, 270] | None = None + camera_stability: Literal["unknown", "fixed_verified", "moving"] = "unknown" + timing: TimingInput = Field(default_factory=TimingInput) + single_swing: bool = False + reps: list[RepRange] = Field(default_factory=list, max_length=100) + + @model_validator(mode="after") + def ranges(self): + if self.body_height_px is not None and not (self.body_height_source and self.body_height_source.strip()): + raise ValueError("A supplied image height needs a source description") + if self.single_swing and self.reps: + raise ValueError("Use single_swing or explicit rep ranges, not both") + if any(b.start_frame <= a.end_frame for a, b in zip(self.reps, self.reps[1:])): + raise ValueError("Rep ranges must be ordered and must not overlap") + return self + + def engine_metadata(self): + value = {"timing": self.timing.model_dump(exclude_none=True), + "camera_stability": self.camera_stability, "intended_use": "research"} + if self.rotation_degrees is not None: + value["rotation_degrees"] = self.rotation_degrees + if self.handedness: + value["handedness"] = self.handedness + return value diff --git a/baseball_batting/api_jobs.py b/baseball_batting/api_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..4273b31da5f6dffb35a746fb667c0fd4c87fb5c6 --- /dev/null +++ b/baseball_batting/api_jobs.py @@ -0,0 +1,318 @@ +"""Durable single-GPU queue with isolated, cancellable subprocesses.""" +from dataclasses import dataclass +from contextlib import contextmanager +import fcntl +import logging +import os +from pathlib import Path +import shutil +import signal +import sqlite3 +import subprocess +import sys +import threading +import time +import uuid +from .storage import read_json, sha256_file + +LOG = logging.getLogger(__name__) +ACTIVE = ("uploading", "queued", "running", "cancel_requested") +TERMINAL = ("completed", "failed", "cancelled") + + +@dataclass +class ApiSettings: + api_key: str + data_root: Path = Path("api-data") + model_root: Path = Path("downloads") + max_upload_bytes: int = 512 * 1024 * 1024 + max_active_jobs: int = 8 + max_frames: int = 7200 + max_pixels: int = 8294400 + max_duration_s: float = 120 + job_timeout_s: float = 1800 + retention_s: float = 86400 + minimum_free_bytes: int = 1024 * 1024 * 1024 + + def __post_init__(self): + if len(self.api_key) < 16: + raise ValueError("Set BASEBALL_API_KEY to a secret of at least 16 characters") + self.data_root, self.model_root = Path(self.data_root).resolve(), Path(self.model_root).resolve() + for value in (self.max_upload_bytes, self.max_active_jobs, self.max_frames, + self.max_pixels, self.max_duration_s, self.job_timeout_s, self.retention_s): + if value <= 0: + raise ValueError("API limits must be positive") + if self.minimum_free_bytes < 0: + raise ValueError("Free disk reserve must not be negative") + + @classmethod + def from_env(cls): + return cls(api_key=os.environ.get("BASEBALL_API_KEY", ""), + data_root=Path(os.environ.get("BASEBALL_DATA_ROOT", "/data")), + model_root=Path(os.environ.get("BASEBALL_MODEL_ROOT", "/opt/models")), + max_upload_bytes=int(os.environ.get("BASEBALL_MAX_UPLOAD_MB", "512")) * 1024 * 1024, + max_active_jobs=int(os.environ.get("BASEBALL_MAX_ACTIVE_JOBS", "8")), + max_frames=int(os.environ.get("BASEBALL_MAX_FRAMES", "7200")), + max_pixels=int(os.environ.get("BASEBALL_MAX_PIXELS", "8294400")), + max_duration_s=float(os.environ.get("BASEBALL_MAX_DURATION_S", "120")), + job_timeout_s=float(os.environ.get("BASEBALL_JOB_TIMEOUT_S", "1800")), + retention_s=float(os.environ.get("BASEBALL_RETENTION_HOURS", "24")) * 3600, + minimum_free_bytes=int(os.environ.get("BASEBALL_DISK_RESERVE_MB", "1024")) * 1024 * 1024) + + +class QueueFull(Exception): pass + + +class JobStore: + def __init__(self, root): + self.root = Path(root) + self.root.mkdir(parents=True, exist_ok=True) + self.path = self.root / "jobs.sqlite3" + with self.connect() as db: + db.execute("PRAGMA journal_mode=WAL") + db.execute("""CREATE TABLE IF NOT EXISTS jobs ( + id TEXT PRIMARY KEY, status TEXT NOT NULL, created REAL NOT NULL, + updated REAL NOT NULL, error TEXT, result_sha256 TEXT, coach_payload_sha256 TEXT)""") + if "coach_payload_sha256" not in {r[1] for r in db.execute("PRAGMA table_info(jobs)")}: + db.execute("ALTER TABLE jobs ADD COLUMN coach_payload_sha256 TEXT") + + @contextmanager + def connect(self): + db = sqlite3.connect(self.path, timeout=30) + try: + with db: + yield db + finally: + db.close() + + def create(self, max_active): + now, identifier = time.time(), uuid.uuid4().hex + with self.connect() as db: + db.execute("BEGIN IMMEDIATE") + active = db.execute("SELECT COUNT(*) FROM jobs WHERE status IN (?,?,?,?)", ACTIVE).fetchone()[0] + if active >= max_active: raise QueueFull() + db.execute("INSERT INTO jobs (id,status,created,updated) VALUES (?, 'uploading', ?, ?)", (identifier, now, now)) + return identifier + + def get(self, identifier): + with self.connect() as db: + db.row_factory = sqlite3.Row + value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone() + return dict(value) if value else None + + def update(self, identifier, status, error=None, result_hash=None, coach_hash=None): + with self.connect() as db: + db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=? WHERE id=?", + (status, time.time(), error, result_hash, coach_hash, identifier)) + + def claim(self): + with self.connect() as db: + db.execute("BEGIN IMMEDIATE") + row = db.execute("SELECT id FROM jobs WHERE status='queued' ORDER BY created LIMIT 1").fetchone() + if row: + db.execute("UPDATE jobs SET status='running', updated=? WHERE id=?", (time.time(), row[0])) + return row[0] + + def cancel(self, identifier): + with self.connect() as db: + db.execute("BEGIN IMMEDIATE") + row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone() + if not row: return None + status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled" + db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL WHERE id=?", + (status, time.time(), identifier)) + return status + + def recover(self): + with self.connect() as db: + uploads = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='uploading'")] + cancellations = [r[0] for r in db.execute("SELECT id FROM jobs WHERE status='cancel_requested'")] + db.execute("DELETE FROM jobs WHERE status='uploading'") + db.execute("UPDATE jobs SET status='queued', updated=? WHERE status='running'", (time.time(),)) + db.execute("UPDATE jobs SET status='cancelled', updated=? WHERE status='cancel_requested'", (time.time(),)) + return uploads + cancellations + + def forget(self, identifier): + with self.connect() as db: + db.execute("DELETE FROM jobs WHERE id=?", (identifier,)) + + def expired(self, cutoff): + with self.connect() as db: + return [r[0] for r in db.execute( + "SELECT id FROM jobs WHERE status IN (?,?,?) AND updated < ?", (*TERMINAL, cutoff))] + + +def stop_process(process): + if process.poll() is not None: return + try: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=3) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=3) + except ProcessLookupError: + process.wait(timeout=3) + + +class JobService: + def __init__(self, settings, command_factory=None, preflight_command=None): + self.settings = settings + self.store = JobStore(settings.data_root) + self.jobs_root = settings.data_root / "jobs" + self.jobs_root.mkdir(exist_ok=True) + self.command_factory = command_factory or self.job_command + self.preflight_command = preflight_command or [sys.executable, "-m", "baseball_batting.api_worker", + "--preflight", "--models", str(settings.model_root), "--output", str(settings.data_root / "gpu-ready.json")] + self.ready = False + self.readiness_reason = "gpu_preflight_pending" + self.stopping = threading.Event() + self.wakeup = threading.Event() + self.thread = None + self.lock = None + # Serializes completion/cancellation and deletion against result downloads. + self.mutation_lock = threading.RLock() + + def job_directory(self, identifier): + if len(identifier) != 32 or any(c not in "0123456789abcdef" for c in identifier): + raise ValueError("Invalid job ID") + return self.jobs_root / identifier + + def job_command(self, directory): + s = self.settings + return [sys.executable, "-m", "baseball_batting.api_worker", "--models", str(s.model_root), + "--job", str(directory), "--max-frames", str(s.max_frames), + "--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)] + + def start(self): + self.lock = (self.settings.data_root / ".service.lock").open("a") + try: + fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + self.lock.close() + raise RuntimeError("This data directory already has an API worker; use one Uvicorn worker") + for identifier in self.store.recover(): + shutil.rmtree(self.job_directory(identifier), ignore_errors=True) + self.thread = threading.Thread(target=self.loop, name="gpu-job-queue", daemon=True) + self.thread.start() + + def stop(self): + self.ready = False + self.stopping.set(); self.wakeup.set() + if self.thread: + self.thread.join(timeout=15) + if self.thread.is_alive(): + raise RuntimeError("GPU worker did not stop") + if self.lock: + self.lock.close() + + def environment(self): + env = dict(os.environ) + # The inference subprocess does not need the service credential. + env.pop("BASEBALL_API_KEY", None) + env["MPLBACKEND"] = "Agg"; env["PYTHONUNBUFFERED"] = "1" + repo = str(Path(__file__).resolve().parents[1]) + env["PYTHONPATH"] = repo + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") + return env + + def launch(self, command, log_path): + with Path(log_path).open("wb") as log: + return subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, + env=self.environment(), start_new_session=True) + + def delete(self, identifier): + with self.mutation_lock: + status = self.store.cancel(identifier) + if status == "cancelled": + shutil.rmtree(self.job_directory(identifier), ignore_errors=True) + self.wakeup.set() + return status + + def cleanup(self): + with self.mutation_lock: + for identifier in self.store.expired(time.time() - self.settings.retention_s): + shutil.rmtree(self.job_directory(identifier), ignore_errors=True) + self.store.forget(identifier) + + def finish_failed(self, identifier, directory, code): + with self.mutation_lock: + if self.store.get(identifier)["status"] == "cancel_requested": + self.store.update(identifier, "cancelled") + shutil.rmtree(directory, ignore_errors=True) + else: + self.store.update(identifier, "failed", code) + + def loop(self): + try: + preflight = self.launch(self.preflight_command, self.settings.data_root / "gpu-preflight.log") + start = time.monotonic() + while preflight.poll() is None: + if self.stopping.wait(.1) or time.monotonic() - start > 300: + stop_process(preflight) + self.readiness_reason = "gpu_preflight_timeout" + return + if preflight.returncode: + self.readiness_reason = "gpu_preflight_failed" + return + self.ready = True; self.readiness_reason = "ready" + while not self.stopping.is_set(): + self.cleanup() + identifier = self.store.claim() + if identifier: + self.execute(identifier) + else: + self.wakeup.wait(.5); self.wakeup.clear() + except Exception: + self.readiness_reason = "queue_worker_failed" + LOG.exception("GPU job queue stopped") + finally: + self.ready = False + + def execute(self, identifier): + directory = self.job_directory(identifier) + process = None + try: + process = self.launch(self.command_factory(directory), directory / "worker.log") + started = time.monotonic() + while process.poll() is None: + current = self.store.get(identifier) + if current["status"] == "cancel_requested": + stop_process(process) + with self.mutation_lock: + self.store.update(identifier, "cancelled") + shutil.rmtree(directory, ignore_errors=True) + return + if self.stopping.wait(.1): + stop_process(process) + with self.mutation_lock: + if self.store.get(identifier)["status"] == "cancel_requested": + self.store.update(identifier, "cancelled") + shutil.rmtree(directory, ignore_errors=True) + else: + self.store.update(identifier, "queued") + return + if time.monotonic() - started > self.settings.job_timeout_s: + stop_process(process) + self.finish_failed(identifier, directory, "job_timeout") + return + with self.mutation_lock: + if self.store.get(identifier)["status"] == "cancel_requested": + self.store.update(identifier, "cancelled") + shutil.rmtree(directory, ignore_errors=True) + elif process.returncode == 0 and (directory / "result.json").is_file(): + coach_path = directory / "coach-payload.json" + self.store.update(identifier, "completed", result_hash=sha256_file(directory / "result.json"), + coach_hash=sha256_file(coach_path) if coach_path.is_file() else None) + else: + error = read_json(directory / "error.json") if (directory / "error.json").exists() else {} + code = error.get("code") + if code not in {"invalid_video_or_capture", "inference_failed"}: code = "inference_failed" + self.store.update(identifier, "failed", code) + except Exception: + if process: stop_process(process) + LOG.exception("Analysis job %s failed", identifier) + self.finish_failed(identifier, directory, "worker_error") + finally: + # Keep uploads only when a server restart will retry the job. + if self.store.get(identifier)["status"] in TERMINAL: + for video in directory.glob("input.*"): + video.unlink(missing_ok=True) diff --git a/baseball_batting/api_output.py b/baseball_batting/api_output.py new file mode 100644 index 0000000000000000000000000000000000000000..4e450b4922b0658279612062ebd8ae0ca32c99d8 --- /dev/null +++ b/baseball_batting/api_output.py @@ -0,0 +1,105 @@ +"""Raw 2D pose plus estimated swing measurements; no coaching decisions.""" +import math +import numpy as np +from .contracts import json_safe +from .batting_measurements import analyze_batting, coach_payload + +KEYPOINT_ORDER = ["nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee", + "right_knee", "left_ankle", "right_ankle"] +EXTRA_ORDER = ["left_big_toe", "left_small_toe", "left_heel", + "right_big_toe", "right_small_toe", "right_heel"] + + +def constant_fps(times): + if len(times) < 2 or any(t is None or not math.isfinite(t) for t in times): + return None + delta = np.diff(times) + if np.any(delta <= 0) or not np.allclose(delta, np.median(delta), rtol=.01, atol=1e-6): + return None + return round(float(1 / np.median(delta)), 6) + + +def build_api_result(capture, observations, options, model_hashes): + n = capture["frame_count"] + if len(observations["frames"]) != n: + raise ValueError("Observation and capture frame counts differ") + width, height = capture["frames"][0]["width"], capture["frames"][0]["height"] + if any(f["width"] != width or f["height"] != height for f in capture["frames"]): + raise ValueError("Changing frame dimensions are unsupported") + frames = {k: [] for k in ("t_s", "playback_t_s", "kp", "conf", "kp_extra", "conf_extra", + "box", "track_id", "people_count", "blur", "brightness")} + real_times = [f["physical_s"] for f in capture["frames"]] + known_clock = (all(t is not None and math.isfinite(t) for t in real_times) + and all(b > a for a, b in zip(real_times, real_times[1:]))) + if not known_clock: + real_times = [None] * n + for i, observed in enumerate(observations["frames"]): + if observed["frame_id"] != i: + raise ValueError("Observation frame order differs from capture") + points, scores = [], [] + for j in range(23): + point, score = observed["body_points"][j], observed["body_scores"][j] + supported = (observed["body_states"][j] == "model_inferred" + and point is not None and all(x is not None and math.isfinite(x) for x in point) + and 0 <= point[0] < width and 0 <= point[1] < height + and score is not None and math.isfinite(score)) + points.append(list(map(float, point)) if supported else None) + scores.append(float(np.clip(score, 0, 1)) if supported else 0.) + frames["kp"].append(points[:17]); frames["conf"].append(scores[:17]) + frames["kp_extra"].append(points[17:23]); frames["conf_extra"].append(scores[17:23]) + person = observed.get("person") + box = person["box"] if person else None + if box is not None: + box = np.asarray(box, float) + if box.shape != (4,) or not np.isfinite(box).all(): + box = None + else: + box = np.clip(box, [0, 0, 0, 0], [width, height, width, height]).tolist() + if box[2] <= box[0] or box[3] <= box[1]: + box = None + frames["box"].append(box) + frames["track_id"].append(1 if box else None) + frames["people_count"].append(observed.get("people_count")) + quality = capture["quality"][i] + variance = quality["blur_laplacian_variance"] + frames["blur"].append(float(1 / (1 + max(0, variance) / 100))) + frames["brightness"].append(float(quality["mean_luminance"])) + frames["t_s"].append(real_times[i]) + frames["playback_t_s"].append(capture["frames"][i]["playback_s"]) + warnings = ["Point scores are model scores; their accuracy has not been calibrated."] + if not known_clock: + warnings.append("Capture time is unknown: t_s and capture_fps are null. playback_t_s is not capture time.") + result = {"schema_version": "1.0", "status": "partial", "warnings": warnings, + "pose_track": {"schema_version": "1.0", "discipline": "hitting", "view": options.view, + "video": {"width": width, "height": height, "frame_count": n, + "capture_fps": constant_fps(real_times), + "playback_fps": constant_fps(frames["playback_t_s"]), + "rotation_degrees_applied": capture["rotation_degrees"], + "time_source": ("original_pts" if options.timing.kind == "unretimed" else + "slowmo_rescaled" if options.timing.kind == "constant_slowdown" else + "explicit_capture_times" if options.timing.kind == "explicit" else "unknown") if known_clock else "unknown"}, + "model": {"name": "RTMW-x", "version": "0949e3a9-20230925", + "sha256": model_hashes["body_pose"], "person_detector": "YOLOX-m HumanArt c2c7a14a", + "person_detector_sha256": model_hashes["person_detector"], + "processing": ["score_threshold_0.35", "out_of_image_points_removed", "scores_clipped_0_1", "no_smoothing_or_gap_filling"], + "people_rule": "largest area times score initially; maximum overlap thereafter; reject overlap below 0.05", + "blur_definition": "1/(1+grayscale_laplacian_variance/100); heuristic, not calibrated"}, + "keypoint_order": KEYPOINT_ORDER, "extra_keypoint_order": EXTRA_ORDER, + "frames": frames, "reps": []}, + "capabilities": {"gpu_2d": True, "body_3d": False, "automatic_rep_splitting": True, + "automatic_events": True, "swing_metrics": True, + "estimated_only": True, + "coaching": False, "pitching": False}, + "validation": "reference_validation_pending"} + pose_reps, measurement_reps, capture_check, diagnostic, method = analyze_batting(result["pose_track"], options) + result["pose_track"]["reps"] = pose_reps + result["measurement_method"] = method + result["warnings"].extend(diagnostic) + measurements = {"schema_version": "2.0", "discipline": "hitting", "view": options.view, + "fps": constant_fps(real_times), "capture": capture_check, "reps": measurement_reps} + if options.level: measurements["level"] = options.level + result["measurements"] = measurements + result["coach_payload"] = coach_payload(measurements) + return json_safe(result) diff --git a/baseball_batting/api_worker.py b/baseball_batting/api_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..900efd6ea944fcb02182007ee68161f52b3fedbc --- /dev/null +++ b/baseball_batting/api_worker.py @@ -0,0 +1,116 @@ +"""GPU-only service worker. Never imports SAM, torch, OpenSim or coaching.""" +import argparse +from pathlib import Path +import time +import numpy as np +import yaml +from .api_contract import AnalysisInput +from .api_output import build_api_result +from .config import CONFIG_ROOT, EngineConfig +from .storage import StageCache, atomic_json, code_hash, digest, read_json, sha256_file + + +def model_files(directory): + registry = yaml.safe_load((CONFIG_ROOT / "resources.yaml").read_text())["resources"] + paths, hashes = {}, {} + for name in ("body_pose", "person_detector"): + path = Path(directory) / name / "model.onnx" + if not path.is_file() or sha256_file(path) != registry[name]["sha256"]: + raise ValueError(f"Missing or incorrect {name} model; run setup_api_models") + paths[name], hashes[name] = str(path), registry[name]["sha256"] + return paths, hashes + + +def gpu_preflight(models): + from .body2d import RTMWPose + from .detection import YOLOXDetector + paths, _ = model_files(models) + detector = YOLOXDetector(paths["person_detector"], "cuda", classes=[0]) + detector(np.zeros((640, 640, 3), np.uint8)) + pose = RTMWPose(paths["body_pose"], "cuda") + pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480]) + # Both adapters check that actual operators executed on CUDA. + return {"ready": True, "device": "cuda", "body_3d": False, + "pose_providers": pose.session.get_providers(), "detector_providers": detector.providers} + + +def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_duration_s=120, + device="cuda"): + """device is an internal test seam; the public CLI and HTTP API always use CUDA.""" + from .ingest import ingest + from .observations import run_observations + job = Path(job) + options = AnalysisInput.model_validate(read_json(job / "request.json")) + paths, hashes = model_files(models) + started = time.monotonic() + def progress(stage, completed=0, total=None): + atomic_json(job / "progress.json", {"stage": stage, "completed_frames": completed, + "total_frames": total, "stage_progress": completed / total if total else None, + "elapsed_s": round(time.monotonic() - started, 2)}) + video = next(job.glob("input.*")) + capture_cache = StageCache(job, "ingest", digest({"input": sha256_file(video), + "metadata": options.engine_metadata(), "code": code_hash(), + "limits": [max_frames, max_pixels, max_duration_s]})) + progress("decoding") + if capture_cache.valid("capture"): + capture = read_json(capture_cache.root / "capture.json") + else: + capture = ingest(video, options.engine_metadata(), max_frames=max_frames, + max_pixels=max_pixels, max_duration_s=max_duration_s, + progress=lambda done: progress("decoding", done)) + atomic_json(capture_cache.root / "capture.json", capture) + capture_cache.commit("capture", [capture_cache.root / "capture.json"]) + n = capture["frame_count"] + if any(rep.end_frame >= n for rep in options.reps): + raise ValueError("Rep range exceeds decoded frame count") + config = EngineConfig(device=device, body_pose_path=paths["body_pose"], + person_detector_path=paths["person_detector"], object_detector_path=None, + body3d_enabled=False, temporal3d_enabled=False, anatomy_enabled=False, + learned_events_enabled=False, bat_3d_mode="disabled", export_video=False, + coaching_mode="descriptive_only") + cache = StageCache(job, "observations", digest({"capture": capture_cache.key, + "models": hashes, "config": config.to_dict(), "code": code_hash()})) + progress("pose_2d", 0, n) + observations = run_observations(video, capture, config, cache, + progress=lambda done, total: progress("pose_2d", done, total)) + if any(observations["branch_status"].get(name, {}).get("status") != "ready" + for name in ("body_pose", "person_detector")): + raise RuntimeError("GPU pose or person inference failed") + # A successfully executed model with no athlete is a capture failure for the + # coach, not a worker crash. Preserve the record-again payload. + progress("measurements_2d", n, n) + result = build_api_result(capture, observations, options, hashes) + atomic_json(job / "coach-payload.json", result["coach_payload"]) + atomic_json(job / "result.json", result) + progress("complete", n, n) + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--models", required=True) + parser.add_argument("--preflight", action="store_true") + parser.add_argument("--output") + parser.add_argument("--job") + parser.add_argument("--max-frames", type=int, default=7200) + parser.add_argument("--max-pixels", type=int, default=8294400) + parser.add_argument("--max-duration", type=float, default=120) + args = parser.parse_args() + try: + if args.preflight: + atomic_json(args.output, gpu_preflight(args.models)) + else: + run_analysis(args.job, args.models, max_frames=args.max_frames, + max_pixels=args.max_pixels, max_duration_s=args.max_duration) + except Exception as error: + # Logs stay server-side; the public error never includes paths or a traceback. + print(f"{type(error).__name__}: {error}", flush=True) + if args.job: + atomic_json(Path(args.job) / "error.json", {"code": "invalid_video_or_capture" if isinstance(error, ValueError) + else "inference_failed", "message": "Analysis could not finish. Check the recording, capture metadata and server logs."}) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/baseball_batting/assessment.py b/baseball_batting/assessment.py new file mode 100644 index 0000000000000000000000000000000000000000..96d3f27d12330c9f19b8c75afebc48ee5686d054 --- /dev/null +++ b/baseball_batting/assessment.py @@ -0,0 +1,39 @@ +from .contracts import Finding +from pathlib import Path +import yaml + +def evaluate_rules(metrics,events,context,trials,path): + catalogue=yaml.safe_load(Path(path).read_text());findings=[] + current={m.metric_id:m for m in metrics} + for rule in catalogue.get("rules",[]): + required=("id","version","required_metrics","required_events","geometry_sources","validation_scopes", + "maximum_sensitivity","minimum_trials","context","source","evidence_strength","interpretation","exercise","objective") + if any(name not in rule for name in required):raise ValueError("Incomplete coaching rule contract") + source=rule["source"] + if not source.get("url") or source.get("supports_intervention") is not True or not source.get("context"):continue + if any(context.get(k)!=v for k,v in rule["context"].items()):continue + if any(not any(e.type==name and e.state=="confirmed" for e in events) for name in rule["required_events"]):continue + selected=[current.get(name) for name in rule["required_metrics"]] + if any(m is None or m.value is None or m.suitability!="supported" for m in selected):continue + if any(m.geometry_source not in rule["geometry_sources"] or m.validation_status not in rule["validation_scopes"] for m in selected):continue + 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 + 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"])] + if len(comparable)+1 roi.shape[1]-3) or np.any(points[:, 1] < 2) or np.any(points[:, 1] > roi.shape[0]-3): + continue + options.append((length, ends)) + if len(options) != 1 or previous is None: + return None # Endpoint identity needs a seed, not an arbitrary left/right choice. + ends = options[0][1] + if np.linalg.norm(ends-np.array(previous)) > np.linalg.norm(ends[::-1]-np.array(previous)): + ends = ends[::-1] + return ends + +class BatTracker: + def __init__(self, state=None): + self.points = None if not state or not state.get("points") else np.array(state["points"], dtype=np.float32) + self.previous_gray = None + + def snapshot(self): + return {"points": None if self.points is None else self.points.tolist()} + + def update(self, image, proposals, manual=None): + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + result = {"points": None, "states": ["unknown", "unknown"], "method": "no_supported_endpoints"} + if manual is not None: + self.points = np.array(manual, np.float32) + result = {"points": self.points.tolist(), "states": ["manual", "manual"], "method": "reviewed_seed"} + else: + boxes = [d["box"] for d in proposals if d["class_id"] == 34] + fitted = None + if self.points is not None and len(boxes) == 1: + try: + fitted = contour_endpoints(image, boxes[0], self.points) + except cv2.error: + pass + if fitted is not None: + self.points = fitted.astype(np.float32) + result = {"points": fitted.tolist(), "states": ["image_supported"]*2, "method": "seeded_contour_axis"} + elif self.points is not None and self.previous_gray is not None: + seed = self.points.reshape(-1, 1, 2) + forward, ok, _ = cv2.calcOpticalFlowPyrLK(self.previous_gray, gray, seed, None) + if forward is not None: + backward, back_ok, _ = cv2.calcOpticalFlowPyrLK(gray, self.previous_gray, forward, None) + 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 + points = forward.reshape(2, 2) + in_bounds = np.all(points >= 0) and np.all(points[:, 0] < gray.shape[1]) and np.all(points[:, 1] < gray.shape[0]) + if consistent and in_bounds: + self.points = points + result = {"points": points.tolist(), "states": ["propagated"]*2, "method": "LK_forward_backward_proposal"} + else: + self.points = None + else: + self.points = None + self.previous_gray = gray + return result + diff --git a/baseball_batting/bat3d.py b/baseball_batting/bat3d.py new file mode 100644 index 0000000000000000000000000000000000000000..a959f2307816eb078792f1f1ae25cca45f889ecd --- /dev/null +++ b/baseball_batting/bat3d.py @@ -0,0 +1,94 @@ +"""Independent rigid-bat geometry. Monocular body depth is never an independent grip.""" +from pathlib import Path +import numpy as np +from scipy.optimize import least_squares +from .geometry import project, intrinsics, triangulate, barrel_from_independent_knob, to_world +from .storage import StageCache, digest, atomic_json, read_json + + +def reconstruct_frame(record, mode, calibration, length, max_error_px=3.): + if not record.get("source") or record.get("independent") is not True: + raise ValueError("Bat geometry requires documented independent measurements") + if length <= .1524: raise ValueError("Known bat length must exceed the measurement-point offset") + if mode == "calibrated_multiview": + if record.get("world_axes")!="x_pitcher_y_up_z_right_handed": + raise ValueError("Multiview projections must identify the calibrated world axes") + if record.get("synchronization_verified") is not True: + raise ValueError("Multiview endpoints must have verified synchronization") + cameras = np.asarray(record["projection_matrices"], float) + endpoints = np.asarray(record["endpoints_pixels"], float) # views x knob/barrel x xy + if endpoints.shape != (len(cameras), 2, 2): raise ValueError("Invalid multiview endpoints") + points = np.array([triangulate(endpoints[:, j], cameras, max_error_px)[0] for j in range(2)]) + if abs(np.linalg.norm(points[1]-points[0])-length) > .03: + raise ValueError("Triangulated endpoints disagree with measured bat length") + def residual(flat): + xyz = flat.reshape(2, 3); errors = [] + for view, camera in enumerate(cameras): + h = np.c_[xyz, np.ones(2)]@camera.T + valid = np.isfinite(endpoints[view]).all(axis=1) + errors.extend((h[valid,:2]/h[valid,2:3]-endpoints[view,valid]).ravel()) + return np.r_[errors, (np.linalg.norm(xyz[1]-xyz[0])-length)/.001] + points = least_squares(residual, points.ravel(), loss="soft_l1").x.reshape(2,3) + error = float(np.max(np.abs(residual(points.ravel())[:-1]))) + if error > max_error_px or abs(np.linalg.norm(points[1]-points[0])-length) > .003: + raise ValueError("Rigid bat fit failed observation/length agreement") + return points, error, "world_x_pitcher_y_up_z_right_handed" + if mode != "calibrated_independent_grip": raise ValueError("Unknown bat reconstruction mode") + k = intrinsics(calibration["intrinsics_oriented_pixels"]) + if not calibration.get("source"): raise ValueError("Documented camera calibration is required") + pixels = np.asarray(record["endpoints_pixels"], float) + knob = np.asarray(record["knob_camera_m"], float) + barrel = barrel_from_independent_knob(knob, pixels[1], k, length, record.get("barrel_anchor_camera_m")) + points = np.stack([knob, barrel]); error = float(np.linalg.norm(project(points,k)-pixels,axis=1).max()) + if error > max_error_px: raise ValueError("Independent knob measurement fails reprojection") + return points, error, "camera_x_right_y_down_z_forward_metres" + + +def run_bat3d(request, capture, config): + root = Path(request["root"]) + try: + if config.bat_3d_mode not in {"calibrated_multiview","calibrated_independent_grip"}: + raise ValueError("independent_geometry_not_qualified") + geometry = capture["metadata"].get("bat_geometry", {}) + length = capture["metadata"].get("bat_length_m") + if not length: raise ValueError("Measured bat length unavailable") + calibration = capture["metadata"].get("calibration", {}) + cache = StageCache(root, "bat3d", digest({"capture": capture["input_sha256"], "geometry": geometry, + "code_hash":request["code_hash"],"environment":request.get("environment"), + "mode": config.bat_3d_mode, "length": length, "calibration": calibration})) + if cache.valid("trajectory"): + atomic_json(root/"bat3d_status.json",read_json(cache.root/"status.json")); return + count = capture["frame_count"] + points = np.full((count,2,3),np.nan); errors = np.full(count,np.nan); rejected = {} + space = None + for key, record in geometry.get("frames", {}).items(): + index = int(key) + if not 0 <= index < count: raise ValueError("Independent bat frame outside video") + try: + value, error, coordinates = reconstruct_frame(record,config.bat_3d_mode,calibration,length) + if space and coordinates != space: raise ValueError("Mixed bat coordinate systems") + points[index], errors[index], space = value,error,coordinates + except (ValueError,KeyError) as error: + rejected[str(index)] = str(error) + valid = np.isfinite(points).all(axis=(1,2)) + if not valid.any(): raise ValueError("No independently supported unambiguous bat frames") + world = np.full_like(points,np.nan) + if space.startswith("world"): world = points.copy() + else: + try: world = to_world(points,calibration) + except (ValueError,KeyError): pass + direction = (points[:,1]-points[:,0])/length + sweet = points[:,1]-.1524*direction + world_sweet = world[:,1]-.1524*(world[:,1]-world[:,0])/length + path = cache.root/"trajectory.npz" + np.savez_compressed(path,endpoints_m=points,endpoints_world_m=world,sweet_spot_m=sweet, + sweet_spot_world_m=world_sweet,reprojection_px=errors,accepted_frames=valid) + result = {"status":"complete" if valid.all() else "partial","cache_key":cache.key, + "trajectory_path":str(path.relative_to(root)),"frames_fitted":int(valid.sum()), + "coordinate_space":space,"geometry_source":config.bat_3d_mode,"rejected_frames":rejected, + "measurement_point":"0.1524m_inward_from_barrel_along_shaft", + "validation":"reference-validation-pending","independent_geometry":True} + atomic_json(cache.root/"status.json",result);cache.commit("trajectory",[path,cache.root/"status.json"]) + except Exception as error: + result={"status":"unavailable","reason":str(error)[:300],"error_type":type(error).__name__} + atomic_json(root/"bat3d_status.json",result) diff --git a/baseball_batting/batting_measurements.py b/baseball_batting/batting_measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..7b28ade4c7176731c542a534b72ed0c7baea9677 --- /dev/null +++ b/baseball_batting/batting_measurements.py @@ -0,0 +1,519 @@ +"""Versioned 2D batting estimates. No 3D, faults, drills or calibrated accuracy. + +Raw exported points are untouched. Analysis fills at most three missing frames, +then applies a three-frame median on contiguous finite runs. Swing candidates +need a sustained hand excursion; event evidence and all non-null metrics remain +estimates until independently validated. Physical times never use playback FPS. +""" +import math +import numpy as np +from scipy.ndimage import median_filter + +VERSION = "batting-2d-v1" +EVENT_ORDER = ["stance_set", "load_start", "stride", "foot_contact", "foot_plant", + "swing_start", "contact", "finish"] +METRICS = { + "stride_pct_height": ("%", 10, 120), + "foot_plant_to_contact_ms": ("ms", 30, 800), + "com_drift_pct_height": ("%", -80, 80), + "load_tempo_s": ("s", .05, 3), + "load_launch_ratio": ("ratio", .1, 20), + "head_movement_pct_height": ("%", 0, 40), + "lead_knee_angle_contact_deg": ("deg", 60, 200), + "lateral_trunk_tilt_contact_deg": ("deg", -90, 90), + "hip_shoulder_separation_foot_plant_deg": ("deg", -90, 90), +} +CAPTURE_REASONS = {"no_person", "multiple_people", "player_switched", "person_too_small", + "partly_out_of_frame", "too_dark", "a_bit_dark", "too_blurry", "a_bit_blurry", + "low_pose_confidence", "pose_confidence_fair", "low_fps", "very_low_fps", + "wrong_view", "view_uncertain"} +FATAL_REASONS = {"no_person", "multiple_people", "player_switched", "person_too_small", + "partly_out_of_frame", "too_dark", "too_blurry", "low_pose_confidence", + "very_low_fps", "wrong_view", "view_uncertain"} + + +def runs(mask): + edges = np.diff(np.r_[False, np.asarray(mask, bool), False].astype(int)) + return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1))) + + +def point_array(rows, joints): + """JSON null points become NaN pairs, preserving rectangular frame arrays.""" + output = np.full((len(rows), joints, 2), np.nan) + for i, row in enumerate(rows): + for j, point in enumerate(row): + if point is not None: + output[i, j] = point + return output + + +def analysis_points(points, max_gap=3): + result = np.asarray(points, float).copy() + # No extrapolation, or interpolation over gaps longer than three frames. + for j in range(result.shape[1]): + valid = np.isfinite(result[:, j]).all(axis=1) + for a, b in runs(~valid): + if b-a <= max_gap and a > 0 and b < len(result) and valid[a-1] and valid[b]: + fraction = np.arange(1, b-a+1) / (b-a+1) + result[a:b, j] = result[a-1, j] + fraction[:, None] * (result[b, j]-result[a-1, j]) + for a, b in runs(np.isfinite(result[:, j]).all(axis=1)): + if b-a >= 3: + result[a:b, j] = median_filter(result[a:b, j], size=(3, 1), mode="nearest") + return result + + +def included_angle(a, b, c): + u, v = np.asarray(a)-b, np.asarray(c)-b + den = np.linalg.norm(u, axis=-1) * np.linalg.norm(v, axis=-1) + with np.errstate(invalid="ignore", divide="ignore"): + return np.degrees(np.arccos(np.clip(np.sum(u*v, axis=-1) / den, -1, 1))) + + +def stature(points, options): + if options.body_height_px is not None: + return float(options.body_height_px), "caller supplied standing image height" + shoulders = (points[:, 5]+points[:, 6]) / 2 + hips = (points[:, 11]+points[:, 12]) / 2 + legs = (np.linalg.norm(points[:, 11]-points[:, 13], axis=1) + + np.linalg.norm(points[:, 13]-points[:, 15], axis=1) + + np.linalg.norm(points[:, 12]-points[:, 14], axis=1) + + np.linalg.norm(points[:, 14]-points[:, 16], axis=1)) / 2 + # Nose-to-shoulder + torso + leg chain. The 1.08 correction is a declared + # heuristic for the unobserved head/foot extent, not measured body stature. + values = 1.08 * (np.linalg.norm(points[:, 0]-shoulders, axis=1) + + np.linalg.norm(shoulders-hips, axis=1) + legs) + values = values[np.isfinite(values) & (values > 0)] + if len(values) < 5: + return None, "body height unavailable" + return float(np.percentile(values, 90)), "projected skeleton length × 1.08; standing height unmeasured" + + +def motion_clock(frames): + for name in ("t_s", "playback_t_s"): + values = np.asarray(frames[name], float) + if np.isfinite(values).all() and len(values) > 1 and np.all(np.diff(values) > 0): + return values, float(np.median(np.diff(values))) + return np.arange(len(frames["kp"]), dtype=float), 1. + + +def direction_from_stance(points, options, height): + if options.pitcher_direction: + return -1 if options.pitcher_direction == "image_left" else 1 + if not options.handedness or height is None: + return None + lead, back = (15, 16) if options.handedness == "right" else (16, 15) + delta = points[:, lead, 0] - points[:, back, 0] + finite = delta[np.isfinite(delta)] + if len(finite) < 5 or abs(float(np.median(finite))) < .04*height: + return None + return int(np.sign(np.median(finite))) + + +def hand_motion(points, height, direction): + hands = (points[:, 9]+points[:, 10]) / 2 + hips = (points[:, 11]+points[:, 12]) / 2 + relative = (hands-hips) / (height or 1) + change = np.diff(relative, axis=0) + magnitude = np.r_[0., np.linalg.norm(change, axis=1)] + forward = np.r_[0., direction*change[:, 0]] if direction else magnitude.copy() + values = magnitude[np.isfinite(magnitude)] + if len(values) < 5: + return hands, relative, magnitude, forward, math.inf + median = np.median(values) + mad = np.median(np.abs(values-median)) + threshold = max(float(median+2*mad), float(np.percentile(values, 90)*.3), .0005) + return hands, relative, magnitude, forward, threshold + + +def candidate_bursts(relative, magnitude, forward, threshold, dt, direction): + mask = np.isfinite(forward) & (forward > threshold) + # Merge brief within-swing pauses, but never bridge unavailable hand points. + gap = max(1, min(12, round(.06 / dt))) + for a, b in runs(~mask): + if b-a <= gap and a > 0 and b < len(mask) and np.isfinite(relative[a:b]).all(): + mask[a:b] = True + minimum = max(3, min(20, round(.025 / dt))) + bursts = [] + for a, b in runs(mask): + if b-a < minimum or a == 0 or not np.isfinite(relative[a-1:b]).all(): + continue + path = relative[a-1:b] + excursion = (direction * (path[-1, 0]-path[0, 0]) if direction + else float(np.linalg.norm(path[-1]-path[0]))) + if excursion < .12: + continue + # Motion without direction is only a generic rep candidate. It never + # establishes a forward-swing event or contact by itself. + peak = a+int(np.nanargmax(magnitude[a:b])) + if bursts and a-bursts[-1][1] <= gap: + bursts[-1] = (bursts[-1][0], b, peak) + else: + bursts.append((a, b, peak)) + return bursts + + +def automatic_ranges(bursts, motion, dt, direction, n): + """Trim unrelated leading/trailing footage using observed quiet intervals.""" + _, relative, magnitude, _, threshold = motion + minimum = max(3, min(12, round(.035/dt))) + quiet = np.isfinite(magnitude) & (magnitude < threshold*.3) + backward = (np.r_[False, direction*np.diff(relative[:, 0]) < -threshold*.6] + if direction else np.zeros(n, bool)) + margin = max(minimum+2, min(60, round(.15/dt))) + output = [] + for index, (a, b, peak) in enumerate(bursts): + left = 0 if index == 0 else (bursts[index-1][2]+peak)//2+1 + right = n-1 if index+1 == len(bursts) else (peak+bursts[index+1][2])//2 + if left > a or right < b-1: continue + load_runs = [(s+left, e+left) for s, e in runs(backward[left:a]) if e-s >= minimum] + anchor = load_runs[-1][0] if load_runs else a + before = [(s+left, e+left) for s, e in runs(quiet[left:anchor]) if e-s >= minimum] + start = max(before[-1][0], anchor-margin) if before else left + after = [(s+b, e+b) for s, e in runs(quiet[b:right+1]) if e-s >= minimum] + end = min(right, after[0][0]+minimum+2) if after else right + output.append((start, end)) + return output + + +def capture_checks(track, options, height, selected_frames): + f = track["frames"] + ids = np.asarray(sorted(set(selected_frames)), int) + if not len(ids): ids = np.arange(track["video"]["frame_count"]) + reasons, diagnostics = [], [] + boxes = [f["box"][i] for i in ids] + present = [b for b in boxes if b is not None] + counts = [f["people_count"][i] for i in ids] + if not present: + reasons.append("no_person") + elif sum(x is not None and x > 1 for x in counts) > .1*len(ids): + reasons.append("multiple_people") + if any(x is None for x in counts): + diagnostics.append("Person counts are unavailable for some analyzed frames.") + width, video_height = track["video"]["width"], track["video"]["height"] + if present: + if np.median([b[3]-b[1] for b in present]) < .18*video_height or (height and height < 120): + reasons.append("person_too_small") + if sum(b[0] <= 2 or b[1] <= 2 or b[2] >= width-2 or b[3] >= video_height-2 + for b in present) > .1*len(ids): + reasons.append("partly_out_of_frame") + jumps = 0 + for previous, current, a, b in zip(ids, ids[1:], boxes, boxes[1:]): + if current == previous+1 and a is not None and b is not None: + distance = np.linalg.norm((np.array(a[:2])+a[2:])/2 - (np.array(b[:2])+b[2:])/2) + jumps += distance > .5*(height or video_height) + if jumps: + reasons.append("player_switched") + diagnostics.append("A large adjacent-frame box jump suggests a camera cut or identity change.") + kp = point_array(f["kp"], 17)[ids] + core = [0, 5, 6, 11, 12, 15, 16] + complete = np.isfinite(kp[:, core]).all(axis=(1, 2)) + if complete.mean() < .8: reasons.append("low_pose_confidence") + elif complete.mean() < .95: reasons.append("pose_confidence_fair") + brightness = float(np.median(np.asarray(f["brightness"])[ids])) + blur = float(np.median(np.asarray(f["blur"])[ids])) + if brightness < 30: reasons.append("too_dark") + elif brightness < 60: reasons.append("a_bit_dark") + if blur > .9: reasons.append("too_blurry") + elif blur > .75: reasons.append("a_bit_blurry") + fps = track["video"]["capture_fps"] + if fps is not None: + if fps < 30-1e-6: reasons.append("very_low_fps") + elif fps < 60-1e-6: reasons.append("low_fps") + else: + diagnostics.append("Capture FPS is unknown or variable; timing metrics are withheld.") + if options.view != "face_on": reasons.append("view_uncertain") + if options.camera_stability != "fixed_verified": + diagnostics.append("Camera stability is unverified or moving; image-motion measurements are withheld.") + reasons = list(dict.fromkeys(reasons)) + return {"ok": not any(r in FATAL_REASONS for r in reasons), "reasons": reasons}, diagnostics + + +def infer_events(track, points, options, height, direction, motion, start, end): + hands, relative, magnitude, forward, threshold = motion + _, dt = motion_clock(track["frames"]) + raw = point_array(track["frames"]["kp"], 17) + raw_feet = point_array(track["frames"]["kp_extra"], 6) + feet = analysis_points(raw_feet) + events, missing = {}, {key: "No sufficient 2D evidence." for key in EVENT_ORDER} + if options.view != "face_on" or options.camera_stability != "fixed_verified": + return events, {key: "A declared face-on, fixed-camera recording is required." for key in EVENT_ORDER} + if height is None: + return events, {key: "Body scale is unavailable." for key in EVENT_ORDER} + minimum = max(3, min(12, round(.035 / dt))) + positive = candidate_bursts(relative[start:end+1], magnitude[start:end+1], + forward[start:end+1], threshold, dt, direction) + if not positive: + return events, missing + # A caller-declared range with two clear drives is ambiguous. Never silently + # select the best peak and call that range one swing. + if len(positive) != 1: + return events, {key: "More than one hand-motion burst in this rep range." for key in EVENT_ORDER} + a, b, peak = positive[0] + a, b, peak = a+start, b+start, peak+start + def add(name, frame, method, note, joints=(9, 10, 11, 12)): + if frame < start or frame > end or not np.isfinite(raw[frame, list(joints)]).all(): + return + score = min(.5, float(np.min(np.asarray(track["frames"]["conf"])[frame, list(joints)]))) + event = {"frame": int(frame), "confidence": score, "estimated": True, + "method": method, "note": note} + t = track["frames"]["t_s"][frame] + if t is not None: event["t_s"] = float(t) + events[name] = event; missing.pop(name, None) + if direction is not None: + add("swing_start", a, "sustained_forward_hand_motion_v1", + "Estimated onset of sustained forward hand displacement; acceleration onset is not validated.") + else: + missing["swing_start"] = "Pitcher direction could not be established." + quiet = np.isfinite(magnitude) & (magnitude < threshold*.3) + quiet_runs = [(s, e) for s, e in runs(quiet[start:a]) if e-s >= minimum] + # Last visible backward hand excursion before the forward drive. + if direction is not None: + backward = np.r_[False, direction*np.diff(relative[:, 0]) < -threshold*.6] + loads = [] + for s, e in runs(backward[start:a]): + s, e = s+start, e+start + if e-s >= minimum and s > start and np.isfinite(relative[s-1:e]).all(): + if direction*(relative[s-1, 0]-relative[e-1, 0]) >= .025: + loads.append(s) + if loads: + add("load_start", loads[-1], "backward_hand_excursion_v1", + "Estimated hand load start; does not establish whole-body loading.") + else: + missing["load_start"] = "No sustained backward hand load was found." + preparation_end = events.get("load_start", {"frame": a})["frame"] + quiet_runs = [(s, e) for s, e in quiet_runs if start+e <= preparation_end] + if quiet_runs: + q, stop = quiet_runs[-1] + add("stance_set", start+q, "pre_drive_quiet_hands_v1", + "Stable hands are a stance estimate, not proof of a complete stance.") + lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None + contact = None + if lead is not None and direction is not None: + shoulder, elbow, wrist = ((5, 7, 9) if lead == 0 else (6, 8, 10)) + ids = np.arange(max(a, peak), min(b+minimum, end)+1) + angle = included_angle(points[ids, shoulder], points[ids, elbow], points[ids, wrist]) + front = direction*(hands[ids, 0]-points[ids, shoulder, 0]) > .04*height + eligible = np.isfinite(angle) & front & (angle >= 140) + if eligible.any(): + best = float(np.max(angle[eligible])) + choices = ids[eligible & (angle >= best-2)] + # Boundary maxima are incomplete evidence, not forced contact. + contact = int(choices[0]) + if contact == end: contact = None + if contact is not None: + add("contact", contact, "lead_arm_extension_proxy_v1", + "Estimated maximum lead-arm extension with hands forward; no bat-ball contact confirmed.", + (shoulder, elbow, wrist, 9, 10)) + if "contact" not in events: contact = None + if contact is None: + missing["contact"] = "A visible forward lead-arm extension peak was not found." + else: + missing["contact"] = "Handedness and pitcher direction are required for the contact estimate." + if lead is not None: + ankle = 15+lead + back_ankle = 16-lead + prep_end = events.get("load_start", events.get("swing_start", {"frame": a}))["frame"] + baseline_start = events.get("stance_set", {"frame": start})["frame"] + baseline_ids = np.arange(baseline_start, max(baseline_start+1, prep_end)) + baseline = points[baseline_ids, ankle] + valid = np.isfinite(baseline).all(axis=1) + if valid.sum() >= minimum: + baseline = np.median(baseline[valid], axis=0) + foot = points[:, ankle] + displacement = np.linalg.norm(foot-baseline, axis=1) + lifted = (baseline[1]-foot[:, 1]) > .018*height + stride_ids = np.flatnonzero((displacement[start:a+1] > .025*height) + & np.isfinite(foot[start:a+1]).all(axis=1)) + start + if len(stride_ids): + stride = int(stride_ids[0]) + if stride > start: + add("stride", stride, "lead_ankle_departure_v1", + "Estimated departure from the preparation foot position.", (ankle, back_ankle)) + # The visible ground reference is the preparation foot's toe/heel + # level. Touchdown and subsequent settled ankle remain estimates + # and do not measure ground force or full body weight. + extra = np.arange(3*lead, 3*lead+3) + baseline_feet = feet[baseline_ids][:, extra, 1] + levels = np.max(np.where(np.isfinite(baseline_feet), baseline_feet, -np.inf), axis=1) + levels = levels[np.isfinite(levels)] + foot_level = float(np.median(levels)) if len(levels) else None + touchdown = None + limit = min(a, end) # Preserve the requested foot-plant-before-drive convention. + airborne = np.flatnonzero(lifted[stride:limit+1]) + stride + if foot_level is not None and len(airborne): + last_air = int(airborne[-1]) + for i in range(last_air+1, limit+1): + y = feet[i, extra, 1] + if np.isfinite(raw_feet[i, extra]).all() and np.max(y) >= foot_level-.012*height: + touchdown = i + add("foot_contact", i, "lead_foot_ground_return_v1", + "Estimated first toe/heel return to the preparation ground level.", (ankle,)) + break + planted = None + for i in range(touchdown if touchdown is not None else stride+1, limit-minimum+2): + segment = foot[i:i+minimum] + if not np.isfinite(segment).all(): continue + settled = np.max(np.linalg.norm(segment-segment[0], axis=1)) <= .012*height + ground_near = abs(segment[0, 1]-baseline[1]) <= .025*height + advanced = displacement[i] > .025*height + if settled and ground_near and advanced: + planted = i + add("foot_plant", i, "settled_lead_ankle_ground_proxy_v1", + "Estimated settled foot near ground; full body-weight loading is unobservable.", + (ankle, back_ankle)) + break + if planted is None: + missing["foot_plant"] = "No settled, grounded lead foot before the forward drive." + if touchdown is None: + missing["foot_contact"] = "No clear lift and toe/heel touchdown; settled foot is not first contact." + else: + missing["stride"] = "No lead-foot displacement before the forward drive." + else: + missing["stride"] = missing["foot_contact"] = missing["foot_plant"] = "Preparation foot reference is unavailable." + else: + for key in ("stride", "foot_contact", "foot_plant"): + missing[key] = "Handedness is required to identify the lead foot." + for s, e in runs(quiet[max(b, start):end+1]): + if e-s >= minimum and max(b, start)+s+minimum-1 < end: + add("finish", max(b, start)+s, "post_drive_quiet_hands_v1", + "Estimated post-swing settling; the last clip frame is not used as finish.") + break + prior = start + for key in EVENT_ORDER: + if key not in events: continue + if events[key]["frame"] < prior: + events.pop(key); missing[key] = "Candidate conflicts with the required event order." + else: prior = events[key]["frame"] + return events, missing + + +def rep_metrics(track, points, options, height, height_method, direction, events, start, end, capture): + values, notes = {}, {} + fixed = options.camera_stability == "fixed_verified" + lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None + scale_note = f"2D estimate; scale: {height_method}." + if not capture["ok"]: + reason = "Capture failed: " + ", ".join(capture["reasons"]) + elif options.view != "face_on": reason = "A declared face-on recording is required." + elif not fixed: reason = "Fixed-camera evidence is required." + elif height is None: reason = "Body-height scale is unavailable." + else: reason = None + def frame(name): return events[name]["frame"] if name in events else None + plant, contact, stance, load, onset = map(frame, ("foot_plant", "contact", "stance_set", "load_start", "swing_start")) + if reason is None and lead is not None: + ankle, back = 15+lead, 16-lead + if plant is not None and np.isfinite(points[plant, [ankle, back]]).all(): + values["stride_pct_height"] = abs(points[plant, ankle, 0]-points[plant, back, 0]) / height*100 + notes["stride_pct_height"] = scale_note + " Horizontal ankle span at settled-foot proxy; full body-weight loading unmeasured." + if contact is not None and direction is not None and np.isfinite(points[contact, [11, 12, ankle]]).all(): + hip_x = (points[contact, 11, 0]+points[contact, 12, 0])/2 + values["com_drift_pct_height"] = direction*(hip_x-points[contact, ankle, 0]) / height*100 + notes["com_drift_pct_height"] = scale_note + " Hip midpoint relative to front ankle; negative means behind; not whole-body center of mass." + if contact is not None: + hip, knee = (11, 13) if lead == 0 else (12, 14) + values["lead_knee_angle_contact_deg"] = included_angle(points[contact, hip], points[contact, knee], points[contact, ankle]) + notes["lead_knee_angle_contact_deg"] = "Reference only: projected interior knee angle at estimated contact; face-on projection does not measure anatomical flexion." + fps = track["video"]["capture_fps"] + timing_reason = ("Real capture timing is unknown or variable." if fps is None else + "Timing measurements require real capture FPS >= 60." if fps < 60-1e-6 else None) + real_times = np.asarray(track["frames"]["t_s"], float) + if timing_reason is None and reason is None: + if plant is not None and contact is not None: + values["foot_plant_to_contact_ms"] = (real_times[contact]-real_times[plant])*1000 + notes["foot_plant_to_contact_ms"] = "Settled-foot to lead-arm-extension proxy; full loading and ball contact unconfirmed; event error uncalibrated." + if load is not None and onset is not None: + duration = real_times[onset]-real_times[load] + values["load_tempo_s"] = duration + notes["load_tempo_s"] = "Estimated backward-hand load start to forward-hand onset." + if contact is not None and real_times[contact] > real_times[onset]: + values["load_launch_ratio"] = duration / (real_times[contact]-real_times[onset]) + notes["load_launch_ratio"] = "Estimated load duration divided by forward onset-to-contact duration." + if reason is None and stance is not None and contact is not None: + nose = points[stance:contact+1, 0] + if len(nose) >= 2 and np.isfinite(nose).all(): + values["head_movement_pct_height"] = np.linalg.norm(np.diff(nose, axis=0), axis=1).sum() / height*100 + notes["head_movement_pct_height"] = scale_note + " Reference-only smoothed nose path from stance to estimated contact; not calibrated for judging." + missing = { + "stride_pct_height": "Lead-foot identity, body scale or estimated foot plant is missing.", + "com_drift_pct_height": "Lead-foot identity, pitcher direction or estimated contact is missing.", + "foot_plant_to_contact_ms": timing_reason or "Estimated foot plant or contact is missing.", + "load_tempo_s": timing_reason or "Load start or forward swing onset is missing.", + "load_launch_ratio": timing_reason or "Load start, forward swing onset or contact is missing.", + "head_movement_pct_height": "Stance, estimated contact or a contiguous head path is missing.", + "lead_knee_angle_contact_deg": "Lead-leg identity or estimated contact is missing.", + "lateral_trunk_tilt_contact_deg": "Unavailable: face-on 2D cannot establish the requested anatomical trunk tilt.", + "hip_shoulder_separation_foot_plant_deg": "Unavailable: image-plane line angles do not measure axial hip-shoulder twist.", + } + output = [] + for key, (unit, low, high) in METRICS.items(): + value = values.get(key) + note = notes.get(key, reason or missing[key]) + if value is not None: + if not math.isfinite(float(value)) or not low <= value <= high: + value = None; note = "Withheld: computed value is outside the supplied plausible bounds." + else: value = round(float(value), 3) + output.append({"key": key, "value": value, "unit": unit, "confidence": "est", "note": note}) + return output + + +def analyze_batting(track, options): + raw = point_array(track["frames"]["kp"], 17) + points = analysis_points(raw) + height, height_method = stature(points, options) + if height is not None and height > 2*math.hypot(track["video"]["width"], track["video"]["height"]): + height, height_method = None, "body-height scale exceeds the image geometry" + direction = direction_from_stance(points, options, height) + motion = hand_motion(points, height, direction) + _, dt = motion_clock(track["frames"]) + n = len(raw) + declared = [(r.start_frame, r.end_frame) for r in options.reps] + if options.single_swing: declared = [(0, n-1)] + if declared: + ranges = declared + boundary_method = "caller_declared_single_swing" if options.single_swing else "caller_supplied" + elif height is not None: + bursts = candidate_bursts(motion[1], motion[2], motion[3], motion[4], dt, direction) + ranges = automatic_ranges(bursts, motion, dt, direction, n) + boundary_method = "automatic_2d_hand_motion_candidate" + else: + ranges = []; boundary_method = "automatic_2d_hand_motion_candidate" + limit_warning = [] + if len(ranges) > 100: + ranges = ranges[:100] + limit_warning.append("Only the first 100 swing candidates were analyzed; submit shorter clips.") + pose_reps, measurement_reps, selected = [], [], [] + for rep, (start, end) in enumerate(ranges, 1): + if end >= n: raise ValueError("A rep range exceeds the decoded frame count") + selected.extend(range(start, end+1)) + capture, _ = capture_checks(track, options, height, range(start, end+1)) + events, missing = infer_events(track, points, options, height, direction, motion, start, end) + pose_reps.append({"rep": rep, "start_frame": start, "end_frame": end, "events": events, + "missing_events": missing, "boundary_method": boundary_method}) + real_start = track["frames"]["t_s"][start] + events_ms = ({key: round((event["t_s"]-real_start)*1000, 3) + for key, event in events.items() if "t_s" in event} if real_start is not None else {}) + measurement_reps.append({"rep": rep, "events_ms": events_ms, + "metrics": rep_metrics(track, points, options, height, height_method, direction, + events, start, end, capture), + "quality": {"pose_conf": float(np.mean(track["frames"]["conf"][start:end+1])), + "blur": float(np.mean(track["frames"]["blur"][start:end+1]))}}) + capture, diagnostics = capture_checks(track, options, height, selected) + warnings = ["All event detections and non-null swing measurements are unvalidated 2D estimates.", + "Foot plant is a settled-foot proxy; full body-weight loading is not measured.", + "Contact is a lead-arm extension estimate; no bat-ball collision is confirmed."] + diagnostics + limit_warning + if not ranges: warnings.append("No separable swing candidates found; no rep or measurements fabricated.") + return pose_reps, measurement_reps, capture, warnings, { + "version": VERSION, "body_height_px": height, "body_height_method": height_method, + "pitcher_direction": "image_right" if direction == 1 else "image_left" if direction == -1 else None, + "processing": ["interior_gap_fill_max_3_frames", "contiguous_3_frame_median", "raw_pose_track_unchanged"], + "validation": "reference_validation_pending"} + + +def coach_payload(measurements): + """Only the fields requested by the coach API; no pose, IDs, faults or advice.""" + payload = {"schema_version": "2.0", "discipline": "hitting", + "capture": measurements["capture"], "reps": measurements["reps"]} + for key in ("level", "fps"): + if measurements.get(key) is not None: payload[key] = measurements[key] + if measurements.get("view") == "face_on": payload["view"] = "face_on" + return payload diff --git a/baseball_batting/body2d.py b/baseball_batting/body2d.py new file mode 100644 index 0000000000000000000000000000000000000000..d46947d762f3a418cf904216bd83824682dd1fd5 --- /dev/null +++ b/baseball_batting/body2d.py @@ -0,0 +1,33 @@ +from pathlib import Path +import numpy as np +from .detection import ort_session, verify_cuda_nodes + +class RTMWPose: + def __init__(self, path, device="cpu"): + if not Path(path).is_file() or Path(path).suffix != ".onnx": + raise ValueError("Explicit local .onnx pose artifact required") + self.session = ort_session(path, device) + self.device, self.cuda_verified = device, False + shape = self.session.get_inputs()[0].shape + if shape[1:] != [3, 384, 288]: + raise ValueError(f"Unexpected RTMW input {shape}") + # Reuse the pinned RTMLib transforms/decoder with our scored/profilable session. + from rtmlib.tools.pose_estimation.pre_processings import bbox_xyxy2cs, top_down_affine + from rtmlib.tools.pose_estimation.post_processings import get_simcc_maximum + self.bbox_transform, self.affine, self.decode = bbox_xyxy2cs, top_down_affine, get_simcc_maximum + + def __call__(self, image, box): + center, scale = self.bbox_transform(np.asarray(box), padding=1.25) + crop, scale = self.affine((288,384), scale, center, image) + normalized = (crop-np.array([123.675,116.28,103.53]))/np.array([58.395,57.12,57.375]) + tensor = np.ascontiguousarray(normalized.transpose(2,0,1)[None],dtype=np.float32) + x, y = self.session.run(None,{self.session.get_inputs()[0].name:tensor}) + locations, scores = self.decode(x,y) + points = locations / 2 / np.array([288,384]) * scale + center - scale/2 + points, scores = points[0], scores[0] + if self.device == "cuda" and not self.cuda_verified: + verify_cuda_nodes(self.session) + self.cuda_verified = True + if points.shape != (133, 2) or scores.shape != (133,): + raise ValueError("RTMW must preserve 133-point native topology") + return points, scores diff --git a/baseball_batting/body3d.py b/baseball_batting/body3d.py new file mode 100644 index 0000000000000000000000000000000000000000..3e17986758d2b45dc9179f50dc3fa97e0d5c54be --- /dev/null +++ b/baseball_batting/body3d.py @@ -0,0 +1,143 @@ +"""Optional framewise SAM initializer with an exact loaded MHR adapter export.""" +from pathlib import Path +import contextlib +import io +import subprocess +import sys +import numpy as np +from .ingest import iter_frames +from .storage import atomic_json, read_json, StageCache, digest, sha256_file +from .observations import collect_observations + +def native_mhr_positions_to_sam_camera(points): + """Only for *native* centimetre MHR positions, never already-converted SAM exports.""" + return np.asarray(points, dtype=float) / 100 * np.array([1., -1., -1.]) + +def translate_sam_positions(points, translation): + return np.asarray(points, dtype=float) + np.asarray(translation, dtype=float) + +def run_initializer(request, capture, config, observation_cache): + root = Path(request["root"]) + status_path = root / "body3d_status.json" + status = {"status": "unavailable", "reason": "initializer_not_run"} + try: + if config.device != "cuda": + raise RuntimeError("sam_requires_cuda_profile") + import torch + if not torch.cuda.is_available(): + raise RuntimeError("cuda_unavailable") + torch.backends.cuda.matmul.allow_tf32=False + torch.backends.cudnn.allow_tf32=False + required = [config.sam_repo, config.sam_checkpoint, config.sam_config, config.mhr_path] + if not all(required) or not all(Path(p).exists() for p in required): + raise RuntimeError("accessible_pinned_sam_artifacts_not_configured") + revision = subprocess.run(["git", "-C", config.sam_repo, "rev-parse", "HEAD"], + capture_output=True, text=True, check=True).stdout.strip() + if len(revision) != 40: + raise ValueError("SAM source revision must resolve to a commit") + sys.path.insert(0, str(Path(config.sam_repo).resolve())) + import os + os.environ["MOMENTUM_ENABLED"] = "0" # Use the bundled TorchScript asset. + from sam_3d_body.utils.config import get_config + from sam_3d_body.models.meta_arch import SAM3DBody + from sam_3d_body.utils.checkpoint import load_state_dict + from sam_3d_body.sam_3d_body_estimator import SAM3DBodyEstimator + model_cfg = get_config(config.sam_config) + model_cfg.defrost() + model_cfg.TRAIN.USE_FP16 = False + model_cfg.MODEL.MHR_HEAD.MHR_MODEL_PATH = str(Path(config.mhr_path).resolve()) + model_cfg.freeze() + effective_config = model_cfg.dump() + model = SAM3DBody(model_cfg) + checkpoint = torch.load(config.sam_checkpoint, map_location="cpu", weights_only=False) + load_state_dict(model, checkpoint.get("state_dict", checkpoint), strict=False) + del checkpoint + model = model.to("cuda").eval() + if getattr(model, "backbone_dtype", torch.float32) != torch.float32: + raise ValueError("FP32 backbone initialization check failed") + float_dtypes = {str(p.dtype) for p in model.parameters() if p.is_floating_point()} + if float_dtypes != {"torch.float32"}: + raise ValueError(f"Unexpected model parameter dtypes: {float_dtypes}") + estimator = SAM3DBodyEstimator(model, model_cfg, human_detector=None, + human_segmentor=None, fov_estimator=None) + count = (capture["frame_count"]+config.chunk_size-1)//config.chunk_size + observations = collect_observations(observation_cache, count) + cache = StageCache(root, "body3d", digest({"upstream": observation_cache.key, + "sam_revision": revision, "assets": request["model_hashes"], + "effective_config": effective_config, "environment": request["environment"], + "calibration":capture["metadata"].get("calibration",{})})) + calibration = capture["metadata"].get("calibration", {}) + intrinsics = calibration.get("intrinsics_oriented_pixels") + if intrinsics is not None: + intrinsics = np.array(intrinsics, dtype=float) + if intrinsics.shape != (3, 3) or not np.isfinite(intrinsics).all(): + raise ValueError("Camera intrinsics must be a finite 3x3 matrix in oriented pixels") + completed = 0 + adapter_record = None + intrinsics_used = intrinsics + camera_record=cache.root/"camera_intrinsics.json" + if camera_record.exists():intrinsics_used=np.array(read_json(camera_record)["intrinsics_used"]) + for frame_id, _, _, image in iter_frames(request["video"], capture["rotation_degrees"]): + name = f"frame_{frame_id:06d}" + if cache.valid(name): + completed += 1 + continue + person = observations["frames"][frame_id]["person"] + if not person: + continue + kwargs = {"bboxes": np.asarray(person["box"], np.float32).reshape(1, 4), + "inference_type": "full"} + if intrinsics is not None: + # Current estimator internally calls tensor.to(); not a numpy argument. + kwargs["cam_int"] = torch.tensor(intrinsics, dtype=torch.float32).unsqueeze(0) + # Published estimator prints per-frame diagnostics; do not retain that text. + with contextlib.redirect_stdout(io.StringIO()): + predictions = estimator.process_one_image(image[..., ::-1].copy(), **kwargs) + if len(predictions) != 1: + continue + pred = predictions[0] + if intrinsics_used is None: + focal = float(np.asarray(pred["focal_length"]).reshape(-1)[0]) + h, w = image.shape[:2] + intrinsics_used = np.array([[focal, 0, w/2], [0, focal, h/2], [0, 0, 1.]]) + atomic_json(camera_record,{"intrinsics_used":intrinsics_used.tolist(),"source":"calibration" if intrinsics is not None else "published_default_focal_and_image_centre"}) + if adapter_record is None: + from .temporal3d import export_mhr_adapter + adapter_record = export_mhr_adapter(model, cache.root / "mhr_adapter.npz", pred, config.mhr_path) + atomic_json(cache.root / "mhr_adapter.json", adapter_record) + arrays = {k: np.asarray(pred[k]) for k in ("pred_keypoints_3d", "pred_keypoints_2d", "pred_cam_t", + "mhr_model_params", "shape_params", "scale_params", "global_rot", "pred_joint_coords", + "pred_global_rots")} + if not all(np.isfinite(a).all() for a in arrays.values()): + raise ValueError("Nonfinite SAM initializer output") + arrays["camera_keypoints_m"] = translate_sam_positions(arrays["pred_keypoints_3d"], arrays["pred_cam_t"]) + from .geometry import project + projected=project(arrays["camera_keypoints_m"],intrinsics_used) + projection_error=float(np.nanmax(np.linalg.norm(projected-arrays["pred_keypoints_2d"],axis=-1))) + if not np.isfinite(projection_error) or projection_error>1.: + raise ValueError("SAM projection/translation convention check failed") + p = cache.root / f"{name}.npz" + tmp = cache.root / f"{name}.tmp.npz" + np.savez_compressed(tmp, **arrays) + tmp.replace(p) + 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", + camera_translation_applied_to="camera_keypoints_m_only", + array_conventions={"pred_keypoints_3d": "SAM flipped axes, metres, before camera translation", + "pred_joint_coords": "SAM flipped axes, metres, before camera translation", + "camera_keypoints_m": "SAM flipped axes, metres, camera translation once", + "pred_global_rots": "native MHR rotation basis; not transformed to camera/anatomy", + "mhr_model_params": "native rig parameter vector; not anatomical angles"}) + completed += 1 + status = {"status": "complete" if completed == capture["frame_count"] else "partial", + "frames_initialized": completed, "frame_count": capture["frame_count"], + "source_revision": revision, "precision": "fp32", + "configuration_sha256": digest(effective_config), "cache_key": cache.key, + "intrinsics_used": intrinsics_used.tolist() if intrinsics_used is not None else None, + "adapter": adapter_record or (read_json(cache.root / "mhr_adapter.json") if (cache.root / "mhr_adapter.json").exists() else None), + "geometry_source": "calibrated_intrinsics" if intrinsics is not None else "assumed_camera", + "validation": "reference-validation-pending", + "capability": "framewise_initializer; native regressor exported for separate temporal fitting"} + except Exception as e: + status = {"status": "unavailable", "reason": str(e)[:300], "error_type": type(e).__name__} + atomic_json(status_path, status) + return status diff --git a/baseball_batting/cli.py b/baseball_batting/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..9fdf6ef2d75aa12abc15722ca8941df075c11886 --- /dev/null +++ b/baseball_batting/cli.py @@ -0,0 +1,80 @@ +import argparse +import json +from pathlib import Path +from .config import EngineConfig +from .storage import atomic_json + +def main(): + parser = argparse.ArgumentParser(description="Batting analysis engine; experimental measurements stay labelled") + commands = parser.add_subparsers(dest="command", required=True) + analyze = commands.add_parser("analyze") + analyze.add_argument("video") + analyze.add_argument("--output", required=True) + analyze.add_argument("--config") + analyze.add_argument("--metadata") + preflight = commands.add_parser("preflight") + preflight.add_argument("--config") + preflight.add_argument("--output", required=True) + preflight.add_argument("--require-vision", action="store_true", + help="Exit with an error unless real pose/detector inference passed") + fetch = commands.add_parser("fetch") + fetch.add_argument("resource", choices=["body_pose", "person_detector", "object_detector"]) + fetch.add_argument("--registry", default="configs/resources.yaml") + fetch.add_argument("--output", default="downloads") + export = commands.add_parser("export") + export.add_argument("directory") + export.add_argument("destination") + optional=commands.add_parser("preflight-optional");optional.add_argument("--config");optional.add_argument("--output",required=True) + dataset=commands.add_parser("dataset");dataset.add_argument("index");dataset.add_argument("--output",required=True) + dataset.add_argument("--kind",choices=["endpoint_cnn","mstcn_events"],required=True) + train=commands.add_parser("train");train.add_argument("dataset");train.add_argument("--output",required=True) + train.add_argument("--kind",choices=["endpoint_cnn","mstcn_events"],required=True);train.add_argument("--epochs",type=int,default=30) + train.add_argument("--device",choices=["cpu","cuda"],default="cpu");train.add_argument("--mstcn-repo") + evaluate=commands.add_parser("evaluate-checkpoint");evaluate.add_argument("dataset");evaluate.add_argument("checkpoint_directory") + evaluate.add_argument("--thresholds",required=True);evaluate.add_argument("--scope",required=True);evaluate.add_argument("--mstcn-repo") + reference=commands.add_parser("evaluate-reference");reference.add_argument("pairs");reference.add_argument("--gates",required=True);reference.add_argument("--output",required=True) + args = parser.parse_args() + if args.command == "fetch": + from .resources import fetch_artifact + record = fetch_artifact(args.resource, args.registry, args.output) + print(json.dumps({"artifact_path": record["artifact_path"], "sha256": record["sha256"]})) + elif args.command == "export": + from .storage import export_archive + print(export_archive(args.directory, args.destination)) + elif args.command=="dataset": + from .dataset import make_dataset + record=make_dataset(args.index,args.output,args.kind);print(json.dumps({"samples":len(record["samples"]),"output":args.output})) + elif args.command=="train": + from .training import train + print(json.dumps(train(args.dataset,args.output,args.kind,args.epochs,device=args.device,mstcn_repo=args.mstcn_repo))) + elif args.command=="evaluate-checkpoint": + from .training import evaluate + print(json.dumps(evaluate(args.dataset,args.checkpoint_directory,args.thresholds,args.scope,args.mstcn_repo))) + elif args.command=="evaluate-reference": + from .validation import evaluate_reference + print(json.dumps(evaluate_reference(args.pairs,args.gates,args.output))) + else: + config = EngineConfig.load(args.config) if args.config else EngineConfig() + if args.command=="preflight-optional": + from .optional_preflight import run + print(json.dumps(run(config,args.output)["tests"],indent=2)) + elif args.command == "preflight": + from .preflight import run_preflight + profile = run_preflight(config, args.output) + print(json.dumps(profile["tests"], indent=2)) + if args.require_vision and not profile["vision_ready"]: + parser.exit(2, "Vision preflight failed. See runtime_profile.json. For CPU use cpu_reference; " + "for GPU select a Colab GPU and install the CUDA/cuDNN runtime libraries.\n") + else: + from .pipeline import run_engine + metadata = json.loads(Path(args.metadata).read_text()) if args.metadata else {} + result = run_engine(args.video, args.output, config, metadata) + print(json.dumps({"status": result["status"], "frames": result["capture"]["frame_count"], + "available_metrics": sum(m["value"] is not None for m in result["metrics"]), + "diagnostics": result["diagnostics"], + "report": str(Path(args.output)/"report.html")})) + if result["status"] == "failed": + parser.exit(2, "Analysis failed: vision initialization/inference produced no usable observations.\n") + +if __name__ == "__main__": + main() diff --git a/baseball_batting/config.py b/baseball_batting/config.py new file mode 100644 index 0000000000000000000000000000000000000000..890af9048f236a4fd19d7ee113f7c44d309ca4a3 --- /dev/null +++ b/baseball_batting/config.py @@ -0,0 +1,80 @@ +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path +import json +import math + +CONFIG_ROOT = Path(__file__).resolve().parents[1] / "configs" + +@dataclass +class EngineConfig: + mode: str = "automatic" + chunk_size: int = 64 + device: str = "cpu" + score_threshold: float = 0.35 + detector_threshold: float = 0.3 + body_pose_path: str | None = None + person_detector_path: str | None = None + object_detector_path: str | None = None + annotations_path: str | None = None + body3d_enabled: bool = False + sam_repo: str | None = None + sam_checkpoint: str | None = None + sam_config: str | None = None + mhr_path: str | None = None + temporal3d_enabled: bool = True + anatomy_enabled: bool = True + fitting_config_path: str = str(CONFIG_ROOT / "fitting.yaml") + anatomical_config_path: str = str(CONFIG_ROOT / "anatomical_model.yaml") + mhr_limits_path: str | None = None + endpoint_checkpoint_path: str | None = None + endpoint_manifest_path: str | None = None + event_checkpoint_path: str | None = None + event_manifest_path: str | None = None + mstcn_repo: str | None = None + coaching_rules_path: str = str(CONFIG_ROOT.parent / "rules/coaching_rules.yaml") + coaching_mode: str = "evidence_linked_experimental" + quality_config_path: str = str(CONFIG_ROOT / "quality.yaml") + stage_python: dict[str, str] = field(default_factory=dict) + learned_events_enabled: bool = False + bat_3d_mode: str = "disabled" + export_video: bool = True + event_parameters: dict = field(default_factory=lambda: { + "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, + "sustained_frames": 3, "min_visible_frames": 4, + }) + + def validate(self): + if self.mode not in {"automatic", "operator_reviewed", "dataset"}: + raise ValueError("Unknown execution mode") + if self.chunk_size < 1 or self.device not in {"cpu", "cuda"}: + raise ValueError("Invalid chunk size or device") + if not 0 <= self.score_threshold <= 1 or not 0 <= self.detector_threshold <= 1: + raise ValueError("Score thresholds must lie in [0, 1]") + if self.mode == "automatic" and self.annotations_path: + raise ValueError("Human annotations require operator_reviewed or dataset mode") + for field_name in ("body3d_enabled", "temporal3d_enabled", "anatomy_enabled", "learned_events_enabled", "export_video"): + if not isinstance(getattr(self, field_name), bool): + raise ValueError(f"{field_name} must be a boolean") + if not isinstance(self.bat_3d_mode, str) or not self.bat_3d_mode: + raise ValueError("bat_3d_mode must identify a requested mode or disabled") + if self.coaching_mode not in {"descriptive_only", "evidence_linked_experimental"}: + raise ValueError("Unknown coaching mode") + # Unsupported optional branch requests are reported as unavailable by workers. + # They never execute unqualified weights and never block eligible 2D results. + p = self.event_parameters + if p.get("sustained_frames", 0) < 1 or p.get("min_visible_frames", 0) < 2: + raise ValueError("Invalid event support parameters") + if not math.isfinite(p.get("motion_threshold_px_per_frame", float("nan"))): + raise ValueError("Invalid event motion threshold") + return self + + def to_dict(self): + return asdict(self) + + @classmethod + def load(cls, path: str | Path): + raw = json.loads(Path(path).read_text()) + unexpected = set(raw) - {f.name for f in fields(cls)} + if unexpected: + raise ValueError(f"Unknown configuration keys: {sorted(unexpected)}") + return cls(**raw).validate() diff --git a/baseball_batting/contracts.py b/baseball_batting/contracts.py new file mode 100644 index 0000000000000000000000000000000000000000..57cf803214bf32cd3d17b575df6f06dd1b5205b8 --- /dev/null +++ b/baseball_batting/contracts.py @@ -0,0 +1,87 @@ +"""Serializable records; provenance, suitability and validation are independent.""" +from dataclasses import asdict, dataclass, field +from typing import Any +import math +import numpy as np + +SCHEMA_VERSION = "1.0" +RTMW_CORE = { + "nose": 0, "left_shoulder": 5, "right_shoulder": 6, + "left_elbow": 7, "right_elbow": 8, "left_wrist": 9, "right_wrist": 10, + "left_hip": 11, "right_hip": 12, "left_knee": 13, "right_knee": 14, + "left_ankle": 15, "right_ankle": 16, "left_big_toe": 17, + "left_small_toe": 18, "left_heel": 19, "right_big_toe": 20, + "right_small_toe": 21, "right_heel": 22, +} +STATES = {"image_supported", "model_inferred", "manual", "propagated", + "interpolated", "occluded", "unknown"} + +def json_safe(value: Any) -> Any: + if hasattr(value, "__dataclass_fields__"): + return json_safe(asdict(value)) + if isinstance(value, dict): + return {str(k): json_safe(v) for k, v in value.items()} + if isinstance(value, (list, tuple, np.ndarray)): + return [json_safe(v) for v in value] + if isinstance(value, np.generic): + return json_safe(value.item()) + if isinstance(value, float) and not math.isfinite(value): + return None + return value + +@dataclass +class FrameTiming: + frame_id: int + pts: int | None + time_base: str | None + playback_s: float | None + physical_s: float | None + width: int + height: int + flags: list[str] = field(default_factory=list) + +@dataclass +class Event: + event_id: str + type: str + state: str + frame_interval: list[int] | None + evidence_frames: list[int] + method: str + review_status: str = "not_reviewed" + annotator: str | None = None + playback_interval_s: list[float | None] | None = None + physical_interval_s: list[float | None] | None = None + notes: list[str] = field(default_factory=list) + confidence_interpretation: str = "candidate evidence; no calibrated probability" + +@dataclass +class Metric: + metric_id: str + definition_version: str + value: float | None + unit: str + suitability: str + provenance: list[str] + evidence_frames: list[int] + geometry_source: str + timing_source: str + unavailable_reason: str | None = None + event_id: str | None = None + uncertainty_kind: str = "unknown" + validation_status: str = "reference-validation-pending" + validation_scope: str | None = None + feedback_eligibility: str = "descriptive-only" + sensitivity: dict | None = None + +@dataclass +class Finding: + finding_id: str + supporting_metric_ids: list[str] + rule_id: str + rule_version: str + description: str + evidence_frames: list[int] + expert_review: str = "not_reviewed" + evidence_strength: str = "descriptive observation" + research_exercise: dict | None = None diff --git a/baseball_batting/dataset.py b/baseball_batting/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..c031f5b279fea80447b4f70a4ff6449059418c8d --- /dev/null +++ b/baseball_batting/dataset.py @@ -0,0 +1,81 @@ +"""Reproducible grouped datasets from exact-video reviewed labels and source frames.""" +from pathlib import Path +import numpy as np +from .storage import read_json, atomic_json, sha256_file, digest, StageCache +from .ingest import ingest, iter_frames +from .annotations import load_annotations +from .learning import PHASES, BOUNDARIES, FEATURE_VERSION, features + + +def validate_splits(records): + seen={};sessions={};videos={} + for record in records: + player,session,split=record.get("player_id"),record.get("session_id"),record.get("split") + if not player or not session or split not in {"train","validation","test"}:raise ValueError("Explicit athlete/session and split required") + if player in seen and seen[player]!=split:raise ValueError("Athlete leakage across splits") + if session in sessions and sessions[session]!=split:raise ValueError("Session leakage across splits") + seen[player]=split;sessions[session]=split + fingerprint=sha256_file(record["video_path"]) + if fingerprint in videos and videos[fingerprint]!=split:raise ValueError("Identical video leakage across splits") + videos[fingerprint]=split + if set(seen.values())!={"train","validation","test"}:raise ValueError("Three nonempty grouped partitions required") + return seen + + +def make_dataset(index_path,output,kind): + import cv2 + records=read_json(index_path);validate_splits(records) + output=Path(output);output.mkdir(parents=True,exist_ok=True);samples=[] + for number,record in enumerate(records): + capture=ingest(record["video_path"],record.get("metadata",{})) + labels=load_annotations(record["annotations_path"],capture["input_sha256"],capture["frame_count"],capture["frames"][0]["width"],capture["frames"][0]["height"]) + common={"player_id":record["player_id"],"session_id":record["session_id"],"split":record["split"], + "input_sha256":capture["input_sha256"],"annotations_sha256":sha256_file(record["annotations_path"])} + if kind=="endpoint_cnn": + for i,_,_,image in iter_frames(record["video_path"],capture["rotation_degrees"]): + label=labels.get("frames",{}).get(str(i),{});box=label.get("crop") + if not box or not any(label.get(k) is not None for k in ("knob","barrel")):continue + x1,y1,x2,y2=map(int,box);crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy() + target=np.zeros((2,64,64),np.float32);visible=np.zeros(2,np.float32);visibility_mask=np.zeros(2,np.float32) + yy,xx=np.mgrid[:64,:64] + for j,name in enumerate(("knob","barrel")): + point=label.get(name) + if point is not None: + xy=(np.array(point)-[x1,y1])/[x2-x1,y2-y1]*64-.5 + if not np.all((xy>=0)&(xy<64)):raise ValueError("Endpoint label lies outside its training crop") + target[j]=np.exp(-((xx-xy[0])**2+(yy-xy[1])**2)/(2*1.5**2));visible[j]=1;visibility_mask[j]=1 + elif label.get("bat_occluded") is True:visibility_mask[j]=1 + path=output/f"endpoint_{number:05d}_{i:06d}.npz" + np.savez_compressed(path,image=crop,heatmaps=target,visible=visible,visibility_mask=visibility_mask) + samples.append({**common,"path":path.name,"frame_id":i}) + else: + directory=Path(record["analysis_directory"]) + cache_index=read_json(directory/"observation_index.json") + cache=StageCache(directory,"observations",cache_index["cache_key"]) + from .observations import collect_observations + observations=collect_observations(cache,cache_index["chunk_count"]) + if cache_index["input_sha256"]!=capture["input_sha256"]:raise ValueError("Analysis/label video mismatch") + x=features(observations,capture);n=capture["frame_count"] + phase=np.full(n,-100,np.int64) + for interval in labels.get("phases",[]): + if interval["phase"] not in PHASES:raise ValueError("Unknown reviewed phase") + a,b=interval["frame_interval"] + if not 0<=a<=b= threshold] + expected = sum((size//stride)**2 for stride in (8, 16, 32)) + if p.shape[0] != expected or p.shape[1] not in (6, 85): + raise ValueError(f"Unsupported raw YOLOX schema: {p.shape}; expected {expected}x6 or x85") + if p.shape[1] == 6 and list(classes) != [0]: + raise ValueError("Person-only raw export cannot supply COCO bat or ball classes") + grids, strides = [], [] + for stride in (8, 16, 32): + y, x = np.indices((size//stride, size//stride)) + grids.append(np.column_stack((x.ravel(), y.ravel()))) + strides.append(np.full((x.size, 1), stride)) + grid, step = np.concatenate(grids), np.concatenate(strides) + centers = (p[:, :2] + grid) * step + wh = np.exp(np.clip(p[:, 2:4], -30, 30)) * step + boxes = np.concatenate((centers-wh/2, centers+wh/2), axis=1) / ratio + all_scores = p[:, 4:5] * p[:, 5:] + result = [] + for cls in classes: + if cls >= all_scores.shape[1]: + continue + scores = all_scores[:, cls] + order = np.flatnonzero(np.isfinite(scores) & (scores >= threshold)) + order = order[np.argsort(scores[order])[::-1]] + while len(order): + k = order[0] + if np.isfinite(boxes[k]).all(): + result.append({"class_id": int(cls), "score": float(scores[k]), "box": boxes[k].tolist()}) + order = order[1:][iou(boxes[k], boxes[order[1:]]) <= nms] + return result + +def ort_session(path, device): + import onnxruntime as ort + if not Path(path).is_file() or Path(path).suffix != ".onnx": + raise ValueError("Explicit local .onnx model required; inference never downloads artifacts") + if device == "cuda" and "CUDAExecutionProvider" not in ort.get_available_providers(): + raise RuntimeError("CUDA execution provider is unavailable; no silent CPU fallback") + if device=="cuda" and hasattr(ort,"preload_dlls"): + ort.preload_dlls() + providers = [("CUDAExecutionProvider",{"use_tf32":0})] if device == "cuda" else ["CPUExecutionProvider"] + options = ort.SessionOptions() + options.intra_op_num_threads = 2 + if device == "cuda": + options.enable_profiling = True + options.profile_file_prefix = str(Path(tempfile.gettempdir()) / ("batting-ort-"+uuid.uuid4().hex)) + session = ort.InferenceSession(str(path), sess_options=options, providers=providers) + if device == "cuda" and session.get_providers()[0] != "CUDAExecutionProvider": + try: + Path(session.end_profiling()).unlink(missing_ok=True) + except Exception: + pass + raise RuntimeError(f"Requested CUDA session did not initialize on CUDA (ONNX {ort.__version__}). " + "Check GPU runtime and CUDA/cuDNN libraries; rerun vision preflight.") + return session + +def verify_cuda_nodes(session): + """Provider registration alone is not proof that CUDA actually executed an operator.""" + path = Path(session.end_profiling()) + try: + events = json.loads(path.read_text()) + if not any(e.get("args", {}).get("provider") == "CUDAExecutionProvider" for e in events): + raise RuntimeError("No CUDA operator execution was observed in ONNX profiling") + finally: + path.unlink(missing_ok=True) + +class YOLOXDetector: + def __init__(self, path, device="cpu", threshold=0.3, classes=(0, 32, 34)): + self.session = ort_session(path, device) + self.providers = self.session.get_providers() + self.threshold, self.classes = threshold, classes + self.device, self.cuda_verified = device, False + shape = self.session.get_inputs()[0].shape + if shape[1:] != [3, 640, 640]: + raise ValueError(f"Unexpected detector input {shape}") + + def __call__(self, image): + import cv2 + h, w = image.shape[:2] + ratio = min(640/h, 640/w) + canvas = np.full((640, 640, 3), 114, np.uint8) + resized = cv2.resize(image, (int(w*ratio), int(h*ratio))) + canvas[:resized.shape[0], :resized.shape[1]] = resized + tensor = canvas.transpose(2, 0, 1)[None].astype(np.float32) + raw = self.session.run(None, {self.session.get_inputs()[0].name: tensor})[0] + if self.device == "cuda" and not self.cuda_verified: + verify_cuda_nodes(self.session) + self.cuda_verified = True + return decode_yolox(raw, ratio=ratio, threshold=self.threshold, classes=self.classes) + +def select_person(detections, previous=None): + candidates = [d for d in detections if d["class_id"] == 0] + if not candidates: + return None + if previous is not None: + overlaps = iou(np.array(previous), [d["box"] for d in candidates]) + if max(overlaps) < 0.05: + return None # Do not silently jump to a different person. + return candidates[int(np.argmax(overlaps))] + return max(candidates, key=lambda d: max(0, d["box"][2]-d["box"][0]) * max(0, d["box"][3]-d["box"][1]) * d["score"]) diff --git a/baseball_batting/diagnostics.py b/baseball_batting/diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..a11b8c475973fa01d90310298f01454dcbbc0ef0 --- /dev/null +++ b/baseball_batting/diagnostics.py @@ -0,0 +1,39 @@ +"""Separate frame processing from actual observation and measurement coverage.""" +import numpy as np +from .contracts import RTMW_CORE + + +SUPPORTED = {"manual", "image_supported", "model_inferred"} + + +def observation_summary(observations): + counts = {"body_frames": 0, "body_landmarks": 0, "person_frames": 0, + "bat_box_frames": 0, "bat_endpoint_frames": 0, "ball_frames": 0} + frames = observations["frames"] + for frame in frames: + points = np.asarray(frame["body_points"], float) + supported = [j for j in RTMW_CORE.values() if frame["body_states"][j] in SUPPORTED + and np.isfinite(points[j]).all()] + counts["body_frames"] += bool(supported) + counts["body_landmarks"] += len(supported) + counts["person_frames"] += frame["person"] is not None + counts["bat_box_frames"] += any(p["class_id"] == 34 for p in frame["proposals"]) + bat = frame["bat"] + counts["bat_endpoint_frames"] += bool(bat["points"] is not None + and all(s in SUPPORTED for s in bat["states"]) + and np.isfinite(np.asarray(bat["points"], float)).all()) + ball = frame["ball"] + counts["ball_frames"] += bool(ball["point"] is not None and ball["state"] in SUPPORTED + and np.isfinite(np.asarray(ball["point"], float)).all()) + failures = {name: status for name, status in observations["branch_status"].items() + if status["status"] in {"failed", "failed_preflight"}} + any_support = any(counts[k] for k in ("body_frames", "bat_endpoint_frames", "ball_frames")) + state = "complete" if any_support else ("failed" if failures else "empty") + if state == "failed": + message = "Analysis failed: vision models could not run and no usable observations were produced." + elif state == "empty": + message = "No usable body, bat or ball observations were produced. Check model setup and subject visibility." + else: + message = "Observation coverage is available; individual measurements still require their evidence gates." + return {"status": state, "frame_count": len(frames), **counts, + "model_failures": failures, "message": message} diff --git a/baseball_batting/events.py b/baseball_batting/events.py new file mode 100644 index 0000000000000000000000000000000000000000..a7fc256c781170c96d2dd77d79c446927e7b8a09 --- /dev/null +++ b/baseball_batting/events.py @@ -0,0 +1,132 @@ +"""Conservative candidates. Projected overlap is never converted into contact.""" +import numpy as np +from .contracts import Event, RTMW_CORE + +def sustained(mask, length): + return [i for i in range(max(0,len(mask)-length+1)) if np.all(mask[i:i+length])] + +def additional_candidates(curves, observations, capture, parameters): + """Observable intervals with explicit context; these never assert contact.""" + output = [] + frames = observations["frames"]; n = len(frames) + context = capture.get("metadata",{}).get("event_context", {}) + run = parameters["sustained_frames"] + hands = (curves["left_hand_path_pixels"]+curves["right_hand_path_pixels"])/2 + delta = np.diff(hands,axis=0) + threshold = parameters["motion_threshold_px_per_frame"] + fixed = capture["camera_stability"] == "fixed_verified" + direction = context.get("pitcher_direction_image") + if fixed and context.get("source") and direction is not None: + direction = np.asarray(direction,float) + if direction.shape != (2,) or not np.isfinite(direction).all() or np.linalg.norm(direction)<1e-8: + raise ValueError("Pitcher image direction must be a documented finite nonzero xy vector") + along = delta@(direction/np.linalg.norm(direction)) + forward = sustained(np.isfinite(along)&(along>threshold),run) + load = sustained(np.isfinite(along)&(along<-threshold),run) + if forward: + 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")) + if load: + a=load[0];end=next((i for i in forward if i>a),min(a+run,n-1)) + output.append(Event("load_candidate","load","candidate",[a,end],list(range(a,end+1)),"documented_opposing_projected_hand_motion_v2")) + lead = context.get("lead_side") + ground = context.get("ground_line_image") + if fixed and context.get("source") and lead in {"left","right"} and ground is not None: + line=np.asarray(ground,float) + 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") + foot=curves["body_pixels"][:,RTMW_CORE[lead+"_big_toe"]] + height=np.abs(np.c_[foot,np.ones(n)]@line)/np.linalg.norm(line[:2]) + tolerance=parameters.get("ground_tolerance_px",5.) + lifted=sustained(np.isfinite(height)&(height>2*tolerance),run) + landed=sustained(np.isfinite(height)&(heighta+run),None) + if landing is not None: + 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"])) + bat=curves.get("bat_endpoints_pixels") + if bat is None: + bat=np.full((n,2,2),np.nan) + for i,f in enumerate(frames): + 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"] + ball=np.full((n,2),np.nan) + for i,f in enumerate(frames): + if f["ball"].get("point") is not None and f["ball"]["state"] in {"manual","model_inferred","image_supported"}: + ball[i]=f["ball"]["point"] + shaft=bat[:,1]-bat[:,0];length2=np.sum(shaft**2,axis=1) + fraction=np.clip(np.sum((ball-bat[:,0])*shaft,axis=1)/np.where(length2>1e-8,length2,np.nan),0,1) + distance=np.linalg.norm(ball-(bat[:,0]+fraction[:,None]*shaft),axis=1) + eligible=np.flatnonzero(np.isfinite(distance)&(fraction>=.5)) + if len(eligible): + i=int(eligible[np.argmin(distance[eligible])]) + 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"])) + radius=parameters.get("interaction_distance_px",8.) + if distance[i]<=radius and 1<=i1 and np.all(np.linalg.norm(outgoing,axis=1)>1): + cosine=np.dot(incoming,outgoing[0])/(np.linalg.norm(incoming)*np.linalg.norm(outgoing[0])) + if cosine < parameters.get("outgoing_direction_cosine_max",.5): + 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"])) + movement=np.linalg.norm(delta,axis=1) + high=sustained(np.isfinite(movement)&(movement>threshold),run) + settled=sustained(np.isfinite(movement)&(movementhigh[-1]+run),None) + if end is not None and end+run= parameters["min_visible_frames"]: + for i in range(max(0, len(movement)-run+1)): + if np.all(np.isfinite(movement[i:i+run])) and np.all(movement[i:i+run] > threshold): + onset = i + break + if onset is not None: + events.append(Event("hand_motion_onset_candidate", "hand_motion_onset", "candidate", [onset, onset+run], + list(range(onset, onset+run+1)), "sustained_projected_hand_motion_v1", + notes=["May be loading or forward motion; not a confirmed forward-swing boundary"])) + events.append(Event("forward_swing_onset", "forward_swing_onset", "unknown", None, [], "directional_evidence_not_established")) + events.append(Event("contact", "contact", "unknown", None, [], "no_qualified_contact_evidence", + notes=["Missing contact evidence does not prove a miss or a dry swing"])) + events.append(Event("lead_foot_contact", "lead_foot_contact", "unknown", None, [], "ground_and_visibility_not_established")) + events.append(Event("load", "load", "unknown", None, [], "phase_not_confirmed")) + events.append(Event("follow_through", "follow_through", "unknown", None, [], "clip_end_is_not_biomechanical_endpoint")) + for candidate in additional_candidates(curves,observations,capture,parameters): + events=[e for e in events if not (e.type==candidate.type and e.state=="unknown")] + events.append(candidate) + for i, label in enumerate(annotations.get("events", [])): + event_type = label["type"] + events = [e for e in events if e.type != event_type] + events.append(Event(f"reviewed_{event_type}_{i}", event_type, label["state"], label.get("frame_interval"), + label.get("evidence_frames", []), "human_review", "reviewed", annotations["annotator"], + notes=[label.get("evidence_description", "Footage does not establish this event")])) + outcome = [e for e in events if e.type in {"contact", "miss", "dry_swing"} and e.state == "confirmed"] + if len({e.type for e in outcome}) > 1: + raise ValueError("Conflicting confirmed hit/miss/dry outcomes; resolve review") + for e in events: + if e.frame_interval: + a, b = e.frame_interval + e.playback_interval_s = [capture["frames"][a]["playback_s"], capture["frames"][b]["playback_s"]] + e.physical_interval_s = [capture["frames"][a]["physical_s"], capture["frames"][b]["physical_s"]] + return events diff --git a/baseball_batting/geometry.py b/baseball_batting/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..abe5209c33b5478a6a17ab2425ea1b68fb469a90 --- /dev/null +++ b/baseball_batting/geometry.py @@ -0,0 +1,108 @@ +"""Explicit camera geometry, rigid-bat reconstruction and calibrated planar mapping.""" +import numpy as np +from scipy.optimize import least_squares + + +def matrix(value, shape, name): + array = np.asarray(value, float) + if array.shape != shape or not np.isfinite(array).all(): + raise ValueError(f"{name} must be a finite {shape} matrix") + return array + + +def intrinsics(value): + k = matrix(value, (3, 3), "intrinsics") + if k[0, 0] <= 0 or k[1, 1] <= 0 or not np.allclose(k[2], [0, 0, 1]): + raise ValueError("Intrinsics require positive focal lengths and homogeneous row [0,0,1]") + return k + + +def rotation(value): + r = matrix(value, (3, 3), "rotation") + 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): + raise ValueError("Rotation must be orthonormal and right-handed") + return r + + +def project(points, k): + points = np.asarray(points, float) + homogeneous = points @ intrinsics(k).T + result = np.full(points.shape[:-1] + (2,), np.nan) + valid = np.isfinite(points).all(axis=-1) & (points[..., 2] > 1e-8) + result[valid] = homogeneous[valid, :2] / homogeneous[valid, 2:3] + return result + + +def to_world(points, calibration): + transform = calibration.get("world_from_camera") + if not transform or not calibration.get("source") or calibration.get("world_axes") != "x_pitcher_y_up_z_right_handed": + raise ValueError("A documented camera-to-world transform and world axes are required") + r = rotation(transform["rotation"]) + t = matrix(transform["translation_m"], (3,), "world translation") + return np.asarray(points) @ r.T + t + + +def ground_pixels_to_metres(points, calibration): + if not calibration.get("source") or calibration.get("ground_plane_verified") is not True: + raise ValueError("Documented ground-plane calibration is required") + h = matrix(calibration["ground_homography_pixels_to_xz_metres"], (3, 3), "homography") + if abs(np.linalg.det(h)) < 1e-12: + raise ValueError("Ground homography is singular") + points = np.asarray(points, float) + homogeneous = np.concatenate([points, np.ones(points.shape[:-1] + (1,))], axis=-1) @ h.T + return homogeneous[..., :2] / np.where(abs(homogeneous[..., 2:3]) > 1e-12, homogeneous[..., 2:3], np.nan) + + +def triangulate(pixels, cameras, max_reprojection_px=3., min_ray_angle_deg=2.): + """Calibrated synchronized views; reject degenerate ray geometry and behind-camera points.""" + pixels, cameras = np.asarray(pixels, float), np.asarray(cameras, float) + valid = np.isfinite(pixels).all(axis=1) + if cameras.shape != (len(pixels), 3, 4) or valid.sum() < 2: + raise ValueError("At least two calibrated synchronized endpoint observations are required") + pixels, cameras = pixels[valid], cameras[valid] + centers, rays, equations = [], [], [] + for point, camera in zip(pixels, cameras): + if np.linalg.matrix_rank(camera[:, :3]) < 3: + raise ValueError("Degenerate camera projection") + centers.append(-np.linalg.solve(camera[:, :3], camera[:, 3])) + direction = np.linalg.solve(camera[:, :3], [*point, 1.]) + rays.append(direction / np.linalg.norm(direction)) + equations.extend([point[0]*camera[2]-camera[0], point[1]*camera[2]-camera[1]]) + angles = [np.degrees(np.arccos(np.clip(abs(np.dot(a, b)), -1, 1))) + for i, a in enumerate(rays) for b in rays[i+1:]] + if max(angles) < min_ray_angle_deg: + raise ValueError("Triangulation rays are too nearly parallel") + _, _, vectors = np.linalg.svd(equations) + if abs(vectors[-1, 3]) < 1e-10: + raise ValueError("Triangulation is at infinity") + initial = vectors[-1, :3] / vectors[-1, 3] + def residual(point): + image = cameras @ np.r_[point, 1.] + return (image[:, :2] / image[:, 2:3] - pixels).ravel() + fit = least_squares(residual, initial, loss="soft_l1") + depths = (cameras @ np.r_[fit.x, 1.])[:, 2] + errors = np.linalg.norm(residual(fit.x).reshape(-1, 2), axis=1) + if not fit.success or (depths <= 0).any() or errors.max() > max_reprojection_px: + raise ValueError("Triangulation failed cheirality or reprojection checks") + return fit.x, float(errors.max()) + + +def barrel_from_independent_knob(knob, barrel_pixel, k, length, anchor=None, tolerance_m=.03): + """Sphere/ray intersection; two positive solutions remain ambiguous without an anchor.""" + knob = matrix(knob, (3,), "independent knob position") + ray = np.linalg.solve(intrinsics(k), [*barrel_pixel, 1.]) + ray /= np.linalg.norm(ray) + along = np.dot(ray, knob) + discriminant = along**2 - np.dot(knob, knob) + length**2 + if discriminant < -1e-10: + raise ValueError("Endpoint ray and known bat length disagree") + depths = [along + np.sqrt(max(discriminant, 0)), along - np.sqrt(max(discriminant, 0))] + candidates = [depth*ray for depth in depths if depth > 0] + if len(candidates) == 2 and np.linalg.norm(candidates[0]-candidates[1]) < 1e-6: + candidates = candidates[:1] + if anchor is not None: + errors = [np.linalg.norm(point - np.asarray(anchor)) for point in candidates] + candidates = [point for point, error in zip(candidates, errors) if error <= tolerance_m] + if len(candidates) != 1: + raise ValueError("Bat endpoint depths remain ambiguous") + return candidates[0] diff --git a/baseball_batting/history.py b/baseball_batting/history.py new file mode 100644 index 0000000000000000000000000000000000000000..664765fb22453f979db5aa3a5d94b747185ab0d7 --- /dev/null +++ b/baseball_batting/history.py @@ -0,0 +1,30 @@ +"""Only explicit identity and matching context/processing support trial comparisons.""" +from pathlib import Path +from .storage import read_json, digest + + +def comparison_key(result): + capture=result["capture"];metadata=capture["metadata"] + return digest({"engine_code_hash":result["engine_code_hash"],"models":result["model_hashes"], + "geometry":metadata.get("calibration"),"task":metadata.get("swing_task"), + "context":{k:v for k,v in metadata.get("event_context",{}).items() if k in + {"intended_contact_location","pitch_location","pitch_type","lead_side","pitcher_direction_image"}}, + "handedness":metadata.get("handedness"), + "resolution":[capture["frames"][0]["width"],capture["frames"][0]["height"]], + "timing":capture["timing_source"].get("kind"),"review":result["provenance"], + "configuration":result["configuration"],"metric_versions":{m["metric_id"]:m["definition_version"] for m in result["metrics"]}}) + + +def compatible_trials(root,result): + root=Path(root);player=result["capture"]["metadata"].get("player_id") + if not player or not result["capture"]["metadata"].get("swing_task"):return [] + index=root.parent/"history.json" + if not index.exists():return [] + key=comparison_key(result);trials=[] + for record in read_json(index): + if record.get("player_id")!=player or record.get("input_sha256")==result["capture"]["input_sha256"]:continue + target=(root.parent/record["result_path"]).resolve() + if not target.is_relative_to(root.parent.resolve()) or not target.exists():continue + previous=read_json(target) + if comparison_key(previous)==key:trials.append(previous) + return trials diff --git a/baseball_batting/ingest.py b/baseball_batting/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea81d088d763592448a1ac2599316dcc3729195 --- /dev/null +++ b/baseball_batting/ingest.py @@ -0,0 +1,169 @@ +"""Source-timed decoding. Container FPS is never presumed to be the capture clock.""" +from fractions import Fraction +from pathlib import Path +import hashlib +import json +import math +import shutil +import subprocess +import numpy as np +from .contracts import FrameTiming, json_safe +from .storage import sha256_file + +def validate_metadata(metadata): + allowed = {"player_id", "session_id", "handedness", "height_m", "bat_length_m", + "age", "experience_level", "consent", "timing", "rotation_degrees", + "calibration", "camera_stability", "swing_task", "intended_use", "audio", "event_context", "bat_geometry", "uncertainty"} + extra = set(metadata) - allowed + if extra: + raise ValueError(f"Unsupported metadata fields (avoid credentials): {sorted(extra)}") + if metadata.get("handedness") not in {None, "left", "right"}: + raise ValueError("handedness must be left or right") + for field in ("height_m", "bat_length_m"): + v = metadata.get(field) + if v is not None and (not isinstance(v, (int, float)) or not math.isfinite(v) or v <= 0): + raise ValueError(f"{field} must be positive and finite") + angle = metadata.get("rotation_degrees", 0) + if angle not in {0, 90, 180, 270}: + raise ValueError("rotation_degrees must be 0, 90, 180 or 270 clockwise") + timing = metadata.get("timing", {"kind": "unknown"}) + if timing.get("kind") not in {"unknown", "unretimed", "constant_slowdown", "explicit"}: + raise ValueError("Unsupported timing kind") + if timing.get("kind") != "unknown" and not timing.get("source"): + raise ValueError("Known physical timing requires a documented source") + if timing.get("kind") == "constant_slowdown": + factor = timing.get("factor") + if not isinstance(factor, (int, float)) or not math.isfinite(factor) or factor <= 0: + raise ValueError("slowdown factor must be positive and finite") + if timing.get("all_captured_frames_retained") is not True: + raise ValueError("Constant slowdown requires all captured frames retained") + if timing.get("kind") == "explicit": + values = timing.get("physical_times_s", []) + if not values or any(not isinstance(x, (int, float)) or not math.isfinite(x) for x in values): + raise ValueError("Explicit physical times must be finite") + if any(b <= a for a, b in zip(values, values[1:])): + raise ValueError("Explicit physical times must increase strictly") + if metadata.get("camera_stability") not in {None, "unknown", "fixed_verified", "moving"}: + raise ValueError("Invalid camera stability state") + return metadata + +def physical_time(playback, index, timing): + kind = timing.get("kind", "unknown") + if kind == "explicit": + values = timing["physical_times_s"] + if index >= len(values): + raise ValueError("Physical-time map is shorter than the decoded video") + return float(values[index]) + if playback is None or kind == "unknown": + return None + if kind == "unretimed": + return playback + return playback / timing["factor"] + +def orientation_matrix(width, height, rotation): + return { + 0: np.eye(3), + 90: np.array([[0, -1, height-1], [1, 0, 0], [0, 0, 1]]), + 180: np.array([[-1, 0, width-1], [0, -1, height-1], [0, 0, 1]]), + 270: np.array([[0, 1, 0], [-1, 0, width-1], [0, 0, 1]]), + }[rotation].astype(float) + +def probe(path): + if not shutil.which("ffprobe"): + return {"status": "unavailable", "reason": "ffprobe_not_installed"} + result = subprocess.run(["ffprobe", "-v", "error", "-protocol_whitelist", "file,pipe", "-show_streams", "-show_format", + "-of", "json", str(path)], capture_output=True, text=True) + if result.returncode: + return {"status": "failed", "reason": "ffprobe_failed"} + value = json.loads(result.stdout) + # Avoid arbitrary file tags in exported manifests. + return {"status": "ready", "streams": [{k: s[k] for k in + ("index", "codec_name", "codec_type", "width", "height", "time_base", + "r_frame_rate", "avg_frame_rate", "duration", "side_data_list") if k in s} + for s in value.get("streams", [])]} + +def iter_frames(path, rotation=0, max_pixels=None): + import av + import cv2 + # Uploaded recordings must not trigger network requests through a playlist. + with av.open(str(path), options={"protocol_whitelist": "file,pipe"}) as container: + if not container.streams.video: + raise ValueError("No video stream") + stream = container.streams.video[0] + if max_pixels is not None and stream.width * stream.height > max_pixels: + raise ValueError("Video exceeds the configured pixel limit") + for index, frame in enumerate(container.decode(stream)): + if max_pixels is not None and frame.width * frame.height > max_pixels: + raise ValueError("Video exceeds the configured pixel limit") + image = frame.to_ndarray(format="bgr24") + if rotation: + image = np.ascontiguousarray(np.rot90(image, -(rotation // 90))) + yield index, frame.pts, frame.time_base or stream.time_base, image + +def ingest(path, metadata, *, max_frames=None, max_pixels=None, max_duration_s=None, progress=None): + import cv2 + validate_metadata(metadata) + timings, quality = [], [] + prior_time, prior_hash = None, None + rotation = metadata.get("rotation_degrees", 0) + probe_result = probe(path) + if "rotation_degrees" not in metadata and probe_result.get("status") == "ready": + for s in probe_result["streams"]: + if s.get("codec_type") == "video": + for side in s.get("side_data_list", []): + if "rotation" in side: + rotation = int(-side["rotation"]) % 360 + if rotation not in {0, 90, 180, 270}: + raise ValueError("Non-right-angle orientation needs an explicit tested transform") + raw_shape = None + first_time = None + for index, pts, base, image in iter_frames(path, rotation, max_pixels=max_pixels): + if max_frames is not None and index >= max_frames: + raise ValueError("Video exceeds the configured frame limit") + raw_shape = (image.shape[1], image.shape[0]) if not rotation % 180 else (image.shape[0], image.shape[1]) + playback = float(pts * base) if pts is not None and base else None + if first_time is None and playback is not None: + first_time = playback + if (max_duration_s is not None and playback is not None and first_time is not None + and playback - first_time > max_duration_s): + raise ValueError("Video exceeds the configured duration limit") + flags = [] + if playback is None: + flags.append("missing_pts") + elif prior_time is not None and playback <= prior_time: + flags.append("duplicate_pts" if playback == prior_time else "nonmonotonic_pts") + if playback is not None: + prior_time = playback + image_hash = hashlib.sha256(image.tobytes()).hexdigest() + if image_hash == prior_hash: + flags.append("duplicate_image") + prior_hash = image_hash + t = physical_time(playback, index, metadata.get("timing", {"kind": "unknown"})) + timings.append(FrameTiming(index, pts, str(base) if base else None, playback, + t, image.shape[1], image.shape[0], flags)) + gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + quality.append({"frame_id": index, "blur_laplacian_variance": float(cv2.Laplacian(gray, cv2.CV_64F).var()), + "mean_luminance": float(gray.mean())}) + if progress and (index + 1) % 64 == 0: + progress(index + 1) + if not timings: + raise ValueError("No decodable video frames") + timing_meta = metadata.get("timing", {"kind": "unknown"}) + if timing_meta.get("kind") == "explicit" and len(timing_meta["physical_times_s"]) != len(timings): + raise ValueError("Physical-time map must match decoded frame count") + intervals = [b.playback_s-a.playback_s for a, b in zip(timings, timings[1:]) + if a.playback_s is not None and b.playback_s is not None and b.playback_s > a.playback_s] + if intervals: + nominal = float(np.median(intervals)) + for a, b in zip(timings, timings[1:]): + if a.playback_s is not None and b.playback_s is not None and b.playback_s-a.playback_s > 1.5*nominal: + b.flags.append("timestamp_gap_or_variable_cadence") + return json_safe({"schema_version": "1.0", "input_sha256": sha256_file(path), + "frame_count": len(timings), "frames": timings, "quality": quality, + "metadata": metadata, "probe": probe_result, "rotation_degrees": rotation, + "orientation_transform": orientation_matrix(*raw_shape, rotation), + "coordinate_space": "oriented_image_pixels_x_right_y_down", + "timing_source": timing_meta, "participant_consent_record": metadata.get("consent", "not_supplied"), + "camera_stability": metadata.get("camera_stability", "unknown"), + "physical_clock_known": all(t.physical_s is not None for t in timings), + "resource_registry_ids": ["pyav", "opencv", "ffmpeg"]}) diff --git a/baseball_batting/learning.py b/baseball_batting/learning.py new file mode 100644 index 0000000000000000000000000000000000000000..38d6a4d8385a1438194527697bd43ff1175f3216 --- /dev/null +++ b/baseball_batting/learning.py @@ -0,0 +1,157 @@ +"""Trainable endpoints and phase/boundary heads. Candidate weights do not auto-activate.""" +from pathlib import Path +import importlib.util +import subprocess +import numpy as np +from .storage import read_json, sha256_file, digest, atomic_json +from .contracts import RTMW_CORE, Event + +MS_TCN_REVISION = "aef4e46c31bc7b2462065354054f968f91e54be1" +PHASES = ["setup", "load", "stride", "forward_swing", "follow_through"] +BOUNDARIES = ["load", "lead_foot_lift", "lead_foot_contact", "forward_swing_onset", "contact", "follow_through"] +FEATURE_VERSION = "body_object_visual_v1" + + +def endpoint_network(): + import torch.nn as nn + class EndpointCNN(nn.Module): + def __init__(self): + super().__init__() + self.stem = nn.Sequential(nn.Conv2d(3,32,5,2,2),nn.ReLU(),nn.Conv2d(32,64,3,2,1),nn.ReLU(), + nn.Conv2d(64,64,3,1,1),nn.ReLU()) + self.heatmap = nn.Conv2d(64,2,1) + self.visible = nn.Sequential(nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(64,2)) + def forward(self,x): + features=self.stem(x) + return self.heatmap(features),self.visible(features) + return EndpointCNN() + + +def temporal_network(repository, architecture): + import torch + import torch.nn as nn + repository=Path(repository) + revision=subprocess.run(["git","-C",str(repository),"rev-parse","HEAD"],capture_output=True,text=True,check=True).stdout.strip() + if revision != MS_TCN_REVISION: + raise ValueError("MS-TCN++ source must be the selected valid pinned revision") + source=repository/"model.py" + module_spec=importlib.util.spec_from_file_location("batting_official_mstcn",source) + module=importlib.util.module_from_spec(module_spec);module_spec.loader.exec_module(module) + class TemporalHead(nn.Module): + def __init__(self): + super().__init__() + self.phases=module.MS_TCN2(architecture["prediction_layers"],architecture["refinement_layers"], + architecture["refinements"],architecture["channels"],architecture["feature_dim"],len(PHASES)) + self.boundaries=nn.Conv1d(len(PHASES),len(BOUNDARIES),1) + self.presence=nn.Linear(len(PHASES),len(BOUNDARIES)) + def forward(self,x): + phases=self.phases(x) + probability=torch.softmax(phases[-1],dim=1) + return phases,self.boundaries(probability),self.presence(probability.mean(-1)) + return TemporalHead(), {"revision":revision,"model_source_sha256":sha256_file(source)} + + +def features(observations,capture): + values=[] + indices=list(RTMW_CORE.values()) + for frame, timing in zip(observations["frames"],capture["frames"]): + scale=np.array([timing["width"],timing["height"]],float) + points=np.asarray(frame["body_points"],float)[indices]/scale + valid=np.array([frame["body_states"][i] in {"manual","image_supported","model_inferred"} for i in indices]) + valid &= np.isfinite(points).all(1);points[~valid]=0 + bat=np.zeros((2,2));bat_mask=np.zeros(2) + if frame["bat"].get("points") is not None: + bat=np.asarray(frame["bat"]["points"],float)/scale + bat_mask=np.array([s in {"manual","image_supported"} for s in frame["bat"]["states"]],float) + bat[bat_mask==0]=0 + ball=np.zeros(2);ball_mask=0 + if frame["ball"].get("point") is not None: + ball=np.asarray(frame["ball"]["point"],float)/scale;ball_mask=1 + visual=np.asarray(frame.get("visual_feature",np.zeros(64)),float) + values.append(np.r_[points.ravel(),valid,bat.ravel(),bat_mask,ball,ball_mask,visual]) + return np.asarray(values,np.float32).T + + +def qualification(manifest_path,checkpoint,kind): + manifest=read_json(manifest_path) + if manifest.get("kind")!=kind or manifest.get("checkpoint_sha256")!=sha256_file(checkpoint): + raise ValueError("Checkpoint kind/hash does not match manifest") + record=manifest.get("qualification",{}) + if record.get("status")!="passed" or record.get("held_out_athletes") is not True or not record.get("evaluation_sha256"): + raise ValueError("Checkpoint has no passed held-out technical qualification") + # Qualification is explicit experimental scope, never proof of biomechanical validity. + if not record.get("scope"): raise ValueError("Checkpoint qualification scope missing") + evidence_path=Path(manifest_path).resolve().parent/"evaluation.json" + if not evidence_path.is_file() or sha256_file(evidence_path)!=record["evaluation_sha256"]: + raise ValueError("Checkpoint qualification evidence missing or changed") + evidence=read_json(evidence_path) + if evidence.get("passed") is not True or evidence.get("checkpoint_sha256")!=manifest["checkpoint_sha256"] or evidence.get("scope")!=record["scope"]: + raise ValueError("Checkpoint qualification evidence mismatch") + return manifest + + +class EndpointPredictor: + def __init__(self,checkpoint,manifest_path,device): + import torch + self.torch=torch;self.device=device + self.manifest=qualification(manifest_path,checkpoint,"endpoint_cnn") + self.model=endpoint_network().to(device).eval() + self.model.load_state_dict(torch.load(checkpoint,map_location=device,weights_only=True)) + + def __call__(self,image,box): + import cv2 + x1,y1,x2,y2=np.asarray(box,int) + h,w=image.shape[:2];x1=max(x1,0);y1=max(y1,0);x2=min(x2,w);y2=min(y2,h) + if x2-x1<8 or y2-y1<8: return None + crop=cv2.resize(image[y1:y2,x1:x2],(256,256))[...,::-1].copy()/255. + x=self.torch.tensor(crop.transpose(2,0,1),dtype=self.torch.float32,device=self.device)[None] + with self.torch.no_grad(): heatmap,visibility=self.model(x) + if (visibility.sigmoid()62): return None + return {"points":points.tolist(),"states":["model_inferred"]*2,"method":"qualified_endpoint_cnn_v1", + "qualification_scope":self.manifest["qualification"]["scope"]} + + +def run_learned_events(request,capture,config,observations): + root=Path(request["root"]) + try: + if not config.event_manifest_path or not config.event_checkpoint_path: + raise ValueError("no_qualified_checkpoint") + import torch + manifest=qualification(config.event_manifest_path,config.event_checkpoint_path,"mstcn_events") + if manifest.get("feature_version")!=FEATURE_VERSION: raise ValueError("Event feature definition mismatch") + model,source=temporal_network(config.mstcn_repo,manifest["architecture"]) + if source!=manifest["source"]: raise ValueError("Event source hash mismatch") + model.load_state_dict(torch.load(config.event_checkpoint_path,map_location="cpu",weights_only=True)) + model=model.to(config.device).eval() + x=features(observations,capture) + with torch.no_grad(): phase,boundary,presence=model(torch.tensor(x,device=config.device)[None]) + phase=phase[-1].softmax(1)[0].cpu().numpy(); boundary=boundary.sigmoid()[0].cpu().numpy();presence=presence.sigmoid()[0].cpu().numpy() + candidates=[] + for i,name in enumerate(BOUNDARIES): + if presence[i] 1e-9, denominator, np.nan) + return 180-np.degrees(np.arccos(np.clip(cosine, -1, 1))) + +def derivative(values, times): + """Differentiate only contiguous finite increasing intervals; do not bridge gaps.""" + values, times = np.asarray(values, float), np.asarray(times, float) + result = np.full_like(values, np.nan) + valid = np.isfinite(times) & np.isfinite(values).reshape(len(times), -1).all(axis=1) + start = 0 + for k in range(len(times)+1): + boundary = k == len(times) or not valid[k] or (k > start and times[k] <= times[k-1]) + if boundary: + if k-start >= 3: + result[start:k] = np.gradient(values[start:k], times[start:k], axis=0, edge_order=2) + start = k+1 if k < len(times) and not valid[k] else k + return result + +def continuous_curves(observations, capture): + frames = observations["frames"] + n = len(frames) + body = np.array([f["body_points"] for f in frames], dtype=float) + for i, f in enumerate(frames): + for j, state in enumerate(f["body_states"]): + if state not in {"model_inferred", "image_supported", "manual"}: + body[i, j] = np.nan + bat = np.full((n, 2, 2), np.nan) + for i, f in enumerate(frames): + qualified=f["bat"].get("method")=="qualified_endpoint_cnn_v1" + 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"]): + bat[i] = f["bat"]["points"] + time = np.array([f["physical_s"] for f in capture["frames"]], dtype=float) + curves = {"physical_time_s": time, "body_pixels": body, "bat_endpoints_pixels": bat} + for side in ("left", "right"): + for joint, names in (("elbow", ("shoulder", "elbow", "wrist")), ("knee", ("hip", "knee", "ankle"))): + a, b, c = [body[:, RTMW_CORE[f"{side}_{name}"]] for name in names] + curves[f"{side}_{joint}_projected_flexion_deg"] = flexion_degrees(a, b, c) + curves[f"{side}_hand_path_pixels"] = body[:, RTMW_CORE[f"{side}_wrist"]] + curves["projected_ankle_span_px"] = np.linalg.norm(body[:, 15]-body[:, 16], axis=1) + shaft = bat[:, 1]-bat[:, 0] + curves["projected_bat_shaft_angle_deg"] = np.degrees(np.arctan2(-shaft[:, 1], shaft[:, 0])) + if capture["physical_clock_known"] and capture["camera_stability"] == "fixed_verified" and not any( + {"duplicate_pts", "nonmonotonic_pts", "duplicate_image", "missing_pts", "timestamp_gap_or_variable_cadence"} & set(f["flags"]) for f in capture["frames"]): + for side in ("left", "right"): + curves[f"{side}_hand_projected_velocity_px_s"] = derivative(curves[f"{side}_hand_path_pixels"], time) + return curves + +def summarize(curves, observations, capture, events): + output = [] + timing_source = capture["timing_source"].get("kind", "unknown") + def sources(indices, landmark_indices): + return sorted({observations["frames"][int(i)]["body_states"][j] + for i in indices for j in landmark_indices + if observations["frames"][int(i)]["body_states"][j] in {"manual", "model_inferred", "image_supported"}}) + for name in [k for k in curves if k.endswith("flexion_deg") or k == "projected_ankle_span_px"]: + v = curves[name] + indices = np.flatnonzero(np.isfinite(v)) + if name == "projected_ankle_span_px": + used = [15,16] + else: + side, joint = name.split("_")[:2] + names = ("shoulder", "elbow", "wrist") if joint == "elbow" else ("hip", "knee", "ankle") + used = [RTMW_CORE[f"{side}_{j}"] for j in names] + provenance = sources(indices, used) + output.append(Metric(name+"_median", "1.0", float(np.median(v[indices])) if len(indices) else None, + "deg_projected" if name.endswith("deg") else "px", "supported" if len(indices) else "unsupported", + provenance, indices.tolist(), "oriented_image_projection", timing_source, + unavailable_reason=None if len(indices) else "missing_joint_observations")) + bat_angle = curves["projected_bat_shaft_angle_deg"] + indices = np.flatnonzero(np.isfinite(bat_angle)) + # Median of directional angles must use circular arithmetic across ±180°. + value = None + if len(indices): + rad = np.radians(bat_angle[indices]) + value = float(np.degrees(np.arctan2(np.sin(rad).mean(), np.cos(rad).mean()))) + output.append(Metric("projected_bat_shaft_angle_circular_mean", "1.0", value, "deg_projected", + "supported" if value is not None else "unsupported", + sorted({s for i in indices for s in observations["frames"][i]["bat"]["states"]}), indices.tolist(), + "image_plane_x_right_y_up", timing_source, + unavailable_reason=None if value is not None else "no_supported_bat_endpoints")) + for side in ("left", "right"): + path = curves[f"{side}_hand_path_pixels"] + valid = np.isfinite(path).all(axis=1) + reason = None + if capture["camera_stability"] != "fixed_verified": + reason = "camera_stability_unverified" + elif not valid.all() or len(path) < 2: + reason = "incomplete_hand_path" + distance = float(np.linalg.norm(np.diff(path, axis=0), axis=1).sum()) if reason is None else None + output.append(Metric(f"{side}_hand_projected_path_length", "1.0", distance, "px", + "supported" if reason is None else "unsupported", sources(np.flatnonzero(valid), [RTMW_CORE[f"{side}_wrist"]]), + np.flatnonzero(valid).tolist(), "fixed_camera_image_plane", timing_source, reason)) + velocity = curves.get(f"{side}_hand_projected_velocity_px_s") + indices = np.flatnonzero(np.isfinite(velocity).all(axis=1)) if velocity is not None else np.array([], int) + reason = None if len(indices) else ("physical_clock_unknown" if not capture["physical_clock_known"] else "timing_or_camera_or_observation_support_failed") + speed = float(np.linalg.norm(velocity[indices], axis=1).max()) if len(indices) else None + output.append(Metric(f"{side}_hand_peak_projected_speed", "1.0", speed, "px/s", + "supported" if speed is not None else "unsupported", sources(indices, [RTMW_CORE[f"{side}_wrist"]]), indices.tolist(), + "fixed_camera_image_plane", timing_source, reason)) + for name, unit, reason in ( + ("ground_plane_stride_length", "m", "ground_calibration_and_event_not_qualified"), + ("pelvis_thorax_heading_separation", "deg", "anatomical_3d_method_not_qualified"), + ("pelvis_peak_angular_velocity", "deg/s", "anatomical_3d_method_not_qualified"), + ("bat_sweet_spot_speed_at_contact", "m/s", "independent_bat_3d_geometry_not_qualified"), + ("bat_attack_angle_at_contact", "deg", "independent_bat_3d_geometry_not_qualified"), + ("exit_velocity", "m/s", "outcome_module_not_supported"), + ): + output.append(Metric(name, "1.0", None, unit, "unsupported", [], [], "not_established", timing_source, reason)) + return output diff --git a/baseball_batting/motion.py b/baseball_batting/motion.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad7ffd857ea7e5719b9336097e18d85eb454ee3 --- /dev/null +++ b/baseball_batting/motion.py @@ -0,0 +1,58 @@ +"""Time-aware penalties and segment-frame measurements with explicit geometry.""" +import numpy as np +from scipy.spatial.transform import Rotation + + +def contiguous_segments(valid, times, max_gap=None): + valid, times = np.asarray(valid, bool), np.asarray(times, float) + result, start = [], None + for i in range(len(times)): + supported = valid[i] and np.isfinite(times[i]) + connected = i == 0 or (times[i] > times[i-1] and (max_gap is None or times[i]-times[i-1] <= max_gap)) + if start is not None and (not supported or not connected): + result.append((start, i)); start = None + if supported and start is None: + start = i + if start is not None: + result.append((start, len(times))) + return result + + +def angular_velocity(rotations, times, valid=None): + """World angular-velocity vectors from rotation logarithms, never Euler derivatives.""" + rotations, times = np.asarray(rotations), np.asarray(times, float) + valid = np.isfinite(rotations).all(axis=(1, 2)) if valid is None else np.asarray(valid, bool) + velocity = np.full((len(times), 3), np.nan) + for a, b in contiguous_segments(valid, times): + if b-a < 3: + continue + intervals = Rotation.from_matrix(rotations[a+1:b] @ rotations[a:b-1].transpose(0, 2, 1)).as_rotvec() + rates = intervals / np.diff(times[a:b])[:, None] + velocity[a], velocity[b-1] = rates[0], rates[-1] + left, right = np.diff(times[a:b])[:-1], np.diff(times[a:b])[1:] + velocity[a+1:b-1] = (rates[:-1]*right[:, None] + rates[1:]*left[:, None])/(left+right)[:, None] + return velocity + + +def heading(rotations, forward_axis=2): + vector = np.asarray(rotations)[..., :, forward_axis] + result = np.arctan2(vector[..., 2], vector[..., 0]) + return np.where(np.linalg.norm(vector[..., [0, 2]], axis=-1) > 1e-8, result, np.nan) + + +def wrapped_difference(a, b): + return np.arctan2(np.sin(np.asarray(a)-b), np.cos(np.asarray(a)-b)) + + +def sparse_temporal_pattern(frame_count, coordinate_count, marker_count): + from scipy.sparse import lil_matrix + rows = frame_count*marker_count*3 + max(frame_count-2, 0)*coordinate_count + pattern = lil_matrix((rows, frame_count*coordinate_count), dtype=int) + for frame in range(frame_count): + pattern[frame*marker_count*3:(frame+1)*marker_count*3, + frame*coordinate_count:(frame+1)*coordinate_count] = 1 + offset = frame_count*marker_count*3 + for frame in range(max(frame_count-2, 0)): + pattern[offset+frame*coordinate_count:offset+(frame+1)*coordinate_count, + frame*coordinate_count:(frame+3)*coordinate_count] = 1 + return pattern.tocsr() diff --git a/baseball_batting/objects.py b/baseball_batting/objects.py new file mode 100644 index 0000000000000000000000000000000000000000..997c2d21ece4d8843c6232b03fe6a91f85921e25 --- /dev/null +++ b/baseball_batting/objects.py @@ -0,0 +1,55 @@ +"""Offline association of generic sports-ball candidates, without fabricated positions.""" +import numpy as np + +def possible_impact_reset(proposals, bat): + """Projected proximity can reset a motion predictor, never confirm contact.""" + if bat.get("points") is None: + return False + a, b = np.array(bat["points"], dtype=float) + shaft = b-a + length_squared = float(shaft@shaft) + if length_squared < 1e-9: + return False + for candidate in proposals: + if candidate["class_id"] != 32: + continue + center = (np.array(candidate["box"][:2])+candidate["box"][2:])/2 + fraction = np.clip((center-a)@shaft/length_squared,0,1) + if np.linalg.norm(center-(a+fraction*shaft)) <= 8: + return True + return False + +class BallTracker: + def __init__(self, state=None): + self.state = state or {"last": None, "previous": None} + + def update(self, proposals, time_s, frame_id, manual=None, restart=False): + if restart: + self.state = {"last": None, "previous": None} + if manual is not None: + point, score, source = manual, None, "manual" + else: + options = [d for d in proposals if d["class_id"] == 32] + if not options: + return {"point": None, "state": "unknown", "score": None} + last, previous = self.state["last"], self.state["previous"] + centers = [((np.array(d["box"][:2])+d["box"][2:])/2) for d in options] + if last: + predicted = np.array(last["point"], dtype=float) + if previous and time_s is not None and last["time_s"] is not None and previous["time_s"] is not None: + dt = last["time_s"]-previous["time_s"] + if dt > 0 and 0 < time_s-last["time_s"] < 0.15: + predicted += (predicted-np.array(previous["point"]))/dt*(time_s-last["time_s"]) + distances = np.linalg.norm(np.array(centers)-predicted, axis=1) + best = int(np.argmin(distances)) + if distances[best] > 120: + return {"point": None, "state": "unknown", "score": None, "reason": "association_ambiguous"} + elif len(options) > 1: + return {"point": None, "state": "unknown", "score": None, "reason": "multiple_unidentified_balls"} + else: + best = 0 + point, score, source = centers[best].tolist(), options[best]["score"], "model_inferred" + self.state["previous"] = self.state["last"] + self.state["last"] = {"point": point, "time_s": time_s, "frame_id": frame_id} + return {"point": point, "state": source, "score": score, + "identity": "baseball_candidate" if source != "manual" else "reviewed_ball"} diff --git a/baseball_batting/observations.py b/baseball_batting/observations.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b21d95c9c40b1b1f87aec9e444b9f37c88892a --- /dev/null +++ b/baseball_batting/observations.py @@ -0,0 +1,183 @@ +"""Streaming observation worker with stable tracking and verified chunk resuming.""" +from pathlib import Path +import numpy as np +from .annotations import load_annotations +from .bat2d import BatTracker +from .body2d import RTMWPose +from .contracts import RTMW_CORE +from .detection import YOLOXDetector, select_person +from .ingest import iter_frames +from .objects import BallTracker, possible_impact_reset +from .storage import StageCache, atomic_json, read_json + +def run_observations(video, capture, config, cache, progress=None): + annotations = load_annotations(config.annotations_path, capture["input_sha256"], + capture["frame_count"], capture["frames"][0]["width"], + capture["frames"][0]["height"]) + errors = {} + from .preflight import environment_snapshot + runtime_environment = environment_snapshot() + def load(name, path, factory): + if not path: + errors[name] = {"status": "unavailable", "reason": "artifact_not_configured"} + return None + try: + model = factory(path) + errors[name] = {"status": "ready"} + return model + except Exception as e: + errors[name] = {"status": "failed_preflight", "reason": str(e)[:300]} + return None + pose, person, objects, endpoint = None, None, None, None + # Initialize models only if at least one chunk needs inference. + chunk_count = (capture["frame_count"] + config.chunk_size-1)//config.chunk_size + # A valid checksum means the failure was saved correctly, not that inference + # succeeded. Re-run failed chunks after a runtime/library repair. + def reusable(chunk_id): + name = f"chunk_{chunk_id:06d}" + manifest = cache.valid(name) + if manifest: + statuses = read_json(cache.root / f"{name}.json")["branch_status"] + if any(s["status"] in {"failed", "failed_preflight"} for s in statuses.values()): + return None + return manifest + pending = any(reusable(k) is None for k in range(chunk_count)) + if pending: + pose = load("body_pose", config.body_pose_path, lambda p: RTMWPose(p, config.device)) + person = load("person_detector", config.person_detector_path, + lambda p: YOLOXDetector(p, config.device, config.detector_threshold, [0])) + objects = load("object_detector", config.object_detector_path, + lambda p: YOLOXDetector(p, config.device, config.detector_threshold, [0, 32, 34])) + if config.endpoint_checkpoint_path: + from .learning import EndpointPredictor + endpoint=load("learned_endpoints",config.endpoint_checkpoint_path,lambda p:EndpointPredictor(p,config.endpoint_manifest_path,config.device)) + state = {"person_box": None, "crop": None, "ball": None, "bat": None} + ball, bat = BallTracker(), BatTracker() + buffer, current, cached = [], -1, None + reviewed_contact = {e["frame_interval"][1]+1 for e in annotations.get("events", []) + if e["type"] == "contact" and e["state"] == "confirmed"} + def flush(chunk_id): + name = f"chunk_{chunk_id:06d}" + p = cache.root / f"{name}.json" + s = cache.root / f"{name}.state.json" + state["ball"], state["bat"] = ball.state, bat.snapshot() + atomic_json(p, {"frames": buffer, "branch_status": errors, + "runtime_environment": runtime_environment, + "annotator": annotations.get("annotator"), "topology": "rtmw133_native", + "track_id": "batter_0", "coordinate_space": capture["coordinate_space"]}) + atomic_json(s, state) + cache.commit(name, [p, s], start_frame=buffer[0]["frame_id"], end_frame=buffer[-1]["frame_id"]) + if progress: + progress(buffer[-1]["frame_id"] + 1, capture["frame_count"]) + for frame_id, pts, base, image in iter_frames(video, capture["rotation_degrees"]): + chunk_id = frame_id//config.chunk_size + if chunk_id != current: + if current >= 0 and not cached: + flush(current) + buffer = [] + current = chunk_id + cached = reusable(chunk_id) + if cached: + state = read_json(cache.root / f"chunk_{chunk_id:06d}.state.json") + ball, bat = BallTracker(state["ball"]), BatTracker(state["bat"]) + prior = read_json(cache.root / f"chunk_{chunk_id:06d}.json") + # Keep current initialization results when later chunks need a + # retry; cached status must not overwrite the repaired runtime. + if not pending: + errors = prior["branch_status"] + if cached: + # Restore the final image needed for LK at the next non-cached chunk. + if frame_id == cached["end_frame"]: + import cv2 + bat.previous_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + if progress: + progress(frame_id + 1, capture["frame_count"]) + continue + label = annotations.get("frames", {}).get(str(frame_id), {}) + if label.get("crop"): + state["crop"] = label["crop"] + proposals = [] + try: + if objects: + proposals = objects(image) + except Exception as e: + errors["object_detector"] = {"status": "failed", "reason": str(e)[:300]} + objects = None + selected = None + people_count = None + if state["crop"]: + box = state["crop"] + selected = {"box": box, "score": None, "source": "manual_crop"} + else: + try: + candidates = person(image) if person else proposals + if person or objects: + people_count = sum(d["class_id"] == 0 for d in candidates) + selected = select_person(candidates, state["person_box"]) + except Exception as e: + errors["person_detector"] = {"status": "failed", "reason": str(e)[:300]} + person = None + if selected: + state["person_box"] = selected["box"] + points, scores = np.full((133, 2), np.nan), np.full(133, np.nan) + states = ["unknown"]*133 + if pose and selected: + try: + points, scores = pose(image, selected["box"]) + states = ["model_inferred" if np.isfinite(points[k]).all() and scores[k] >= config.score_threshold else "unknown" for k in range(133)] + except Exception as e: + errors["body_pose"] = {"status": "failed", "reason": str(e)[:300]} + pose = None + for name, point in label.get("landmarks", {}).items(): + i = RTMW_CORE[name] + points[i], states[i] = point, "manual" + for name in label.get("occluded_landmarks", []): + if name not in RTMW_CORE: + raise ValueError(f"Unknown occluded landmark: {name}") + states[RTMW_CORE[name]] = "occluded" + manual_bat = [label["knob"], label["barrel"]] if label.get("knob") is not None and label.get("barrel") is not None else None + bat_result = bat.update(image, proposals, manual_bat) + if endpoint and manual_bat is None: + boxes=[d["box"] for d in proposals if d["class_id"]==34] + if len(boxes)==1: + try: + predicted=endpoint(image,boxes[0]) + if predicted:bat_result=predicted;bat.points=np.array(predicted["points"],np.float32) + except Exception as error: + errors["learned_endpoints"]={"status":"failed","reason":str(error)[:300]};endpoint=None + if label.get("bat_occluded"): + bat_result = {"points": None, "states": ["occluded"]*2, "method": "reviewed_occlusion"} + bat.points = None + t = capture["frames"][frame_id]["playback_s"] + reset = frame_id in reviewed_contact or possible_impact_reset(proposals, bat_result) + ball_result = ball.update(proposals, t, frame_id, label.get("ball"), reset) + if reset: + ball_result["predictor_reset"] = "possible_interaction_only_not_confirmed_contact" + if label.get("ball_occluded"): + ball_result = {"point": None, "state": "occluded", "score": None} + import cv2 + visual=cv2.resize(cv2.cvtColor(image,cv2.COLOR_BGR2GRAY),(8,8)).astype(float).ravel()/255. + buffer.append({"frame_id": frame_id, "track_id": "batter_0", "body_points": points, "visual_feature":visual, + "body_scores": scores, "body_states": states, + "people_count": people_count, + "visibility_review": label.get("occluded_landmarks", []), + "person": selected, "proposals": proposals, "bat": bat_result, "ball": ball_result}) + if buffer and not cached: + flush(current) + return collect_observations(cache, chunk_count) + +def collect_observations(cache, chunk_count): + frames, statuses, environment = [], {}, None + for k in range(chunk_count): + name = f"chunk_{k:06d}" + if not cache.valid(name): + raise ValueError(f"Unverified observation chunk {k}") + chunk = read_json(cache.root / f"{name}.json") + frames.extend(chunk["frames"]) + statuses.update(chunk["branch_status"]) + environment = chunk.get("runtime_environment", environment) + return {"frames": frames, "branch_status": statuses, "topology": "rtmw133_native", + "runtime_environment": environment, + "track_id": "batter_0", "provenance": "human_assisted" if any( + "manual" in f["body_states"] or "manual" in f["bat"]["states"] or f["ball"]["state"] == "manual" + or (f["person"] and f["person"].get("source") == "manual_crop") for f in frames) else "automatic"} diff --git a/baseball_batting/optional_preflight.py b/baseball_batting/optional_preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..1464af9431280da07aa8acb039825740342f79d1 --- /dev/null +++ b/baseball_batting/optional_preflight.py @@ -0,0 +1,47 @@ +"""Separate heavy-worker smoke checks with observed results, never package-name qualification.""" +from pathlib import Path +import tempfile +import time +import numpy as np +from .storage import atomic_json +from .preflight import environment_snapshot + + +def run(config,directory): + start=time.perf_counter();tests={} + try: + import torch + if config.device=="cuda" and not torch.cuda.is_available():raise ValueError("cuda_unavailable") + x=torch.tensor([1.],requires_grad=True,device=config.device);(x*x).sum().backward() + tests["torch"]={"status":"ready","device":str(x.device),"gradient":float(x.grad)} + if config.mhr_path: + asset=torch.jit.load(config.mhr_path,map_location=config.device).eval() + shape=torch.zeros(1,45,device=config.device,requires_grad=True) + motion=torch.zeros(1,204,device=config.device,requires_grad=True) + vertices,skeleton=asset(shape,motion,torch.zeros(1,72,device=config.device)) + vertices.square().mean().backward() + if shape.grad is None or motion.grad is None or not torch.isfinite(motion.grad).all():raise ValueError("MHR differentiation failed") + tests["mhr"]={"status":"ready","test":"native_forward_and_gradient","vertices":list(vertices.shape),"skeleton":list(skeleton.shape),"native_units":"cm"} + del asset,vertices,skeleton + except Exception as error:tests["torch_mhr"]={"status":"failed_preflight","reason":str(error)[:250]} + try: + import yaml + from .anatomy import model_spec,build_opensim,forward_kinematics,weighted_ik + from tools.build_anatomical_model import reference_neutral + spec=model_spec(reference_neutral(),yaml.safe_load(Path(config.anatomical_config_path).read_text())) + model=build_opensim(spec);state=model.initSystem();q=np.zeros(35);q[3:6]=[.1,.2,1] + for i,c in enumerate(spec["coordinates"]):model.getCoordinateSet().get(c["name"]).setValue(state,float(q[i]),False) + model.realizePosition(state) + expected=forward_kinematics(spec,q)[0] + actual=np.array([[model.getMarkerSet().get(name).getLocationInGround(state).get(i) for i in range(3)] for name in spec["markers"]]) + if np.max(np.abs(actual-expected))>1e-8:raise ValueError("OpenSim/FK convention mismatch") + with tempfile.TemporaryDirectory() as work: + target=np.repeat(expected[None],3,0);fit=weighted_ik(model,spec,target,np.ones(target.shape[:2]),np.arange(3)*.01,work) + error=max(np.linalg.norm(forward_kinematics(spec,f)[0]-expected,axis=-1).max() for f in fit) + if not np.isfinite(error) or error>.001:raise ValueError("OpenSim synthetic IK failed") + tests["anatomy"]={"status":"ready","test":"35DOF_FK_roundtrip_and_weighted_IK","max_error_m":float(error)} + except Exception as error:tests["anatomy"]={"status":"failed_preflight","reason":str(error)[:250]} + report={"environment":environment_snapshot(),"tests":tests,"elapsed_s":time.perf_counter()-start, + "qualification_scope":"dependency_and_synthetic_arithmetic_only","sam_full_image":"requires_accessible_assets_and_cuda_recording_run"} + Path(directory).mkdir(parents=True,exist_ok=True);atomic_json(Path(directory)/"optional_runtime_profile.json",report) + return report diff --git a/baseball_batting/pipeline.py b/baseball_batting/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..416295197e8439a60a5bc9525ab83a57619a94c9 --- /dev/null +++ b/baseball_batting/pipeline.py @@ -0,0 +1,91 @@ +"""Orchestration calls isolated workers so model lifetimes end at stage boundaries.""" +from pathlib import Path +import subprocess +import sys +import os +from .config import EngineConfig +from .preflight import environment_snapshot +from .storage import StageCache, atomic_json, code_hash, digest, read_json, sha256_file + +def run_engine(video, output_directory, config=None, metadata=None): + from .ingest import validate_metadata + config = (config or EngineConfig()).validate() + metadata = metadata or {} + validate_metadata(metadata) + video = Path(video).resolve() + if not video.is_file(): + raise FileNotFoundError(video) + root = Path(output_directory).resolve() + root.mkdir(parents=True, exist_ok=True) + model_hashes = {name: sha256_file(path) if path and Path(path).is_file() else None for name, path in + (("body_pose", config.body_pose_path), ("person_detector", config.person_detector_path), + ("object_detector", config.object_detector_path), ("sam_checkpoint", config.sam_checkpoint), + ("sam_config", config.sam_config), ("mhr", config.mhr_path), + ("endpoint_checkpoint",config.endpoint_checkpoint_path),("endpoint_manifest",config.endpoint_manifest_path), + ("event_checkpoint",config.event_checkpoint_path),("event_manifest",config.event_manifest_path), + ("fitting_config",config.fitting_config_path),("anatomical_config",config.anatomical_config_path), + ("quality_config",config.quality_config_path),("coaching_rules",config.coaching_rules_path))} + environment = environment_snapshot() + common = {"input_hash": sha256_file(video), "metadata": metadata, "code_hash": code_hash()} + ingest_key = digest(common) + ingestion = StageCache(root, "ingest", ingest_key) + annotations_hash = sha256_file(config.annotations_path) if config.annotations_path else None + observation_config = {k: v for k,v in config.to_dict().items() if k in { + "mode", "chunk_size", "device", "score_threshold", "detector_threshold", "stage_python"}} + observation_key = digest({"input_hash":common["input_hash"],"code_hash":common["code_hash"], + "rotation_override":metadata.get("rotation_degrees"),"config":observation_config, + "environment":environment,"models":{k:v for k,v in model_hashes.items() if k in + {"body_pose","person_detector","object_detector","endpoint_checkpoint","endpoint_manifest"}}, + "annotations":annotations_hash}) + observations = StageCache(root, "observations", observation_key) + request = {"video": str(video), "root": str(root), "config": config.to_dict(), "metadata": metadata, + "ingest_key": ingest_key, "observation_key": observation_key, + "model_hashes": model_hashes, "environment": environment, "code_hash": common["code_hash"]} + # Keep machine-specific paths out of exported artifacts. + request_file = root / ".worker_request.tmp" + atomic_json(request_file, request) + def worker(stage): + interpreter = config.stage_python.get(stage, sys.executable) + env = dict(os.environ) + # Colab's inline backend belongs to its notebook environment, not the + # isolated model workers. SAM imports plotting dependencies during setup. + env["MPLBACKEND"] = "Agg" + repo = str(Path(__file__).parent.parent) + env["PYTHONPATH"] = repo + (os.pathsep+env["PYTHONPATH"] if env.get("PYTHONPATH") else "") + result = subprocess.run([interpreter, "-m", "baseball_batting.worker", stage, str(request_file)], + env=env, capture_output=True, text=True) + if result.returncode: + # Workers only print their sanitized error class/message. + raise RuntimeError(f"{stage} worker failed: {result.stderr[-1000:]}") + try: + if not ingestion.valid("capture"): + worker("ingest") + worker("observations") + if config.body3d_enabled: + try: + worker("body3d") + except (RuntimeError, OSError) as error: + atomic_json(root / "body3d_status.json", {"status": "failed", "reason": "isolated_worker_failed", + "detail": str(error)[:300]}) + for stage, enabled in (("temporal3d",config.temporal3d_enabled),("anatomy",config.anatomy_enabled and config.temporal3d_enabled)): + if enabled: + try: worker(stage) + except (RuntimeError,OSError) as error: + atomic_json(root / (stage+"_status.json"),{"status":"failed","reason":"isolated_worker_failed","detail":str(error)[:300]}) + if config.bat_3d_mode != "disabled": worker("bat3d") + if config.learned_events_enabled: worker("learned_events") + worker("report") + result = read_json(root / "result.json") + session_id = metadata.get("session_id") or common["input_hash"][:12] + history = root.parent / "history.json" + records = read_json(history) if history.exists() else [] + records = [r for r in records if not (r["session_id"] == session_id and r["player_id"] == metadata.get("player_id"))] + records.append({"session_id": session_id, "player_id": metadata.get("player_id"), + "input_sha256": common["input_hash"], "engine_code_hash": common["code_hash"], + "result_path": str(root.name)+"/result.json", "metric_definition_version": "1.0", + "review_status": result["provenance"], "status": result["status"]}) + atomic_json(history, records) + return result + finally: + if request_file.exists(): + request_file.unlink() diff --git a/baseball_batting/preflight.py b/baseball_batting/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..6a4e1aa8e2459912f8b0fb143b80d9f8dbd09d28 --- /dev/null +++ b/baseball_batting/preflight.py @@ -0,0 +1,109 @@ +from datetime import datetime, timezone +from importlib import metadata, util +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time +from .storage import atomic_json, sha256_file + +PACKAGES = ("numpy", "scipy", "opencv-python-headless", "av", "PyYAML", + "rtmlib", "onnxruntime", "onnxruntime-gpu", "torch", "torchvision", "opensim", + "nvidia-cuda-runtime-cu12", "nvidia-cublas-cu12", "nvidia-cudnn-cu12", + "nvidia-cufft-cu12", "nvidia-curand-cu12", "nvidia-nvjitlink-cu12") + +def environment_snapshot(): + versions = {} + for name in PACKAGES: + try: + versions[name] = metadata.version(name) + except metadata.PackageNotFoundError: + versions[name] = None + gpu = {"available": False, "reason": "nvidia_smi_unavailable"} + if shutil.which("nvidia-smi"): + result = subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version,memory.total", + "--format=csv,noheader"], capture_output=True, text=True) + gpu = {"available": result.returncode == 0, "summary": result.stdout.strip()} + onnx = {"status": "unavailable"} + try: + import onnxruntime as ort + onnx = {"version": ort.__version__, "providers": ort.get_available_providers(), + "module_path": ort.__file__} + except Exception as error: + onnx["reason"] = str(error)[:300] + return {"python": platform.python_version(), "executable": sys.executable, "onnxruntime": onnx, + "platform": platform.platform(), "packages": versions, "gpu": gpu, + "ffprobe": bool(shutil.which("ffprobe"))} + +def run_preflight(config, directory): + from .detection import YOLOXDetector + import numpy as np + start = time.perf_counter() + snapshot = environment_snapshot() + tests = {} + for name, module in (("numpy", "numpy"), ("scipy", "scipy"), ("opencv", "cv2"), ("pyav", "av")): + try: + __import__(module) + tests[name] = {"status": "ready", "test": "import"} + except Exception as e: + tests[name] = {"status": "unavailable", "reason": type(e).__name__} + for name, path, classes in (("person_detector", config.person_detector_path, [0]), + ("object_detector", config.object_detector_path, [0, 32, 34])): + if not path: + tests[name] = {"status": "unavailable", "reason": "artifact_not_configured"} + continue + try: + detector = YOLOXDetector(path, config.device, classes=classes) + detector(np.zeros((640, 640, 3), dtype=np.uint8)) + tests[name] = {"status": "ready", "test": "standalone_onnx_inference", + "sha256": sha256_file(path), "providers": detector.providers} + del detector + except Exception as e: + tests[name] = {"status": "failed_preflight", "reason": str(e)[:300]} + if config.body_pose_path: + try: + from .body2d import RTMWPose + pose = RTMWPose(config.body_pose_path, config.device) + points, scores = pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480]) + if points.shape != (133, 2) or scores.shape != (133,): + raise ValueError("RTMW native topology mismatch") + tests["body_pose"] = {"status": "ready", "test": "133_point_shape_and_inference", + "sha256": sha256_file(config.body_pose_path)} + tests["body_pose"]["providers"] = pose.session.get_providers() + del pose + except Exception as e: + tests["body_pose"] = {"status": "failed_preflight", "reason": str(e)[:300]} + else: + tests["body_pose"] = {"status": "unavailable", "reason": "artifact_not_configured"} + tests["body3d"] = {"status": "candidate" if config.body3d_enabled else "disabled_by_configuration", + "reason": "full_hand_and_mhr_tests_require_separate_3d_worker"} + tests["anatomy"] = {"status": "candidate" if config.body3d_enabled and config.anatomy_enabled else "disabled_by_configuration", + "reason": "run_preflight_optional_in_selected_worker"} + tests["learned_events"] = {"status": "unavailable" if config.learned_events_enabled else "disabled_by_configuration", + "reason": "no_qualified_checkpoint"} + report = {"environment": snapshot, "tests": tests, "vision_ready": vision_ready(tests), + "requested_device": config.device, "elapsed_s": time.perf_counter()-start, + "date_utc": datetime.now(timezone.utc).isoformat(), + "validation": "dependency execution only; no baseball accuracy claim"} + dependency_check = subprocess.run([sys.executable, "-m", "pip", "check"], capture_output=True, text=True) + report["dependency_metadata_check"] = {"status": "passed" if dependency_check.returncode == 0 else "failed", + "details": dependency_check.stdout.splitlines()} + root = Path(directory) + root.mkdir(parents=True, exist_ok=True) + atomic_json(root / "runtime_profile.json", report) + # A real package inventory, not a claim that every optional branch passed. + result = subprocess.run([sys.executable, "-m", "pip", "freeze", "--all"], capture_output=True, text=True) + if all(tests[x]["status"] == "ready" for x in ("numpy", "scipy", "opencv", "pyav")) and not result.returncode: + atomic_json(root / "environment.lock.json", {"environment": snapshot, + "freeze": result.stdout.splitlines(), "qualified_scope": "core_imports", + "branch_tests": tests}) + return report + + +def vision_ready(tests): + """Pose needs a usable person proposal; object-only failure can be partial.""" + return (all(tests.get(name, {}).get("status") == "ready" for name in + ("numpy", "scipy", "opencv", "pyav", "body_pose")) + and any(tests.get(name, {}).get("status") == "ready" for name in + ("person_detector", "object_detector"))) diff --git a/baseball_batting/reports.py b/baseball_batting/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..401aaf1340ee8154e92bc906a7162fc90c081c59 --- /dev/null +++ b/baseball_batting/reports.py @@ -0,0 +1,152 @@ +"""Full and partial exports share the same schema. All user text is HTML escaped.""" +from fractions import Fraction +from pathlib import Path +import csv +import html +import os +import numpy as np +from .contracts import json_safe, RTMW_CORE +from .ingest import iter_frames +from .storage import atomic_json + +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)] + +def annotate_image(image, observation): + import cv2 + image = image.copy() + points = np.array(observation["body_points"], dtype=float) + states = observation["body_states"] + valid = [s in {"model_inferred", "manual", "image_supported"} and np.isfinite(points[j]).all() + for j, s in enumerate(states)] + for a, b in BODY_EDGES: + if valid[a] and valid[b]: + cv2.line(image, tuple(np.rint(points[a]).astype(int)), tuple(np.rint(points[b]).astype(int)), (80,230,90), 2) + for j in RTMW_CORE.values(): + if valid[j]: + color = (0,180,255) if states[j] == "manual" else (80,230,90) + cv2.circle(image, tuple(np.rint(points[j]).astype(int)), 3, color, -1) + bat = observation["bat"] + if bat["points"] is None: + for proposal in observation["proposals"]: + if proposal["class_id"] == 34: + a, b = np.rint(proposal["box"]).astype(int).reshape(2, 2) + cv2.rectangle(image, tuple(a), tuple(b), (255,150,70), 1) + cv2.putText(image, "bat proposal", tuple(a), cv2.FONT_HERSHEY_SIMPLEX, .35, (255,150,70), 1) + if bat["points"] is not None: + a, b = np.rint(bat["points"]).astype(int) + color = (0,200,255) if "manual" in bat["states"] else (255,150,70) + cv2.line(image, tuple(a), tuple(b), color, 2) + cv2.putText(image, "knob", tuple(a), cv2.FONT_HERSHEY_SIMPLEX, .35, color, 1) + cv2.putText(image, "barrel", tuple(b), cv2.FONT_HERSHEY_SIMPLEX, .35, color, 1) + if observation["ball"]["point"] is not None: + cv2.circle(image, tuple(np.rint(observation["ball"]["point"]).astype(int)), 4, (230,210,50), 1) + cv2.putText(image, f"Frame {observation['frame_id']} | research observations", (8,20), + cv2.FONT_HERSHEY_SIMPLEX, .5, (255,255,255), 1) + return image + +def export_video(video, capture, observations, destination): + import av + frames = capture["frames"] + if any(f["pts"] is None or not f["time_base"] or {"duplicate_pts", "nonmonotonic_pts"} & set(f["flags"]) for f in frames): + return {"status": "unavailable", "reason": "source_pts_not_encodable_without_retiming"} + shape = frames[0] + if shape["width"] % 2 or shape["height"] % 2: + return {"status": "unavailable", "reason": "odd_dimensions_require_a_separately_recorded_export_transform"} + destination = Path(destination) + temporary = destination.with_suffix(".tmp.mp4") + base = Fraction(frames[0]["time_base"]) + try: + with av.open(str(temporary), "w") as out: + stream = out.add_stream("libx264", rate=None) + stream.width, stream.height = shape["width"], shape["height"] + stream.pix_fmt = "yuv420p" + stream.time_base = base + stream.codec_context.time_base = base + stream.options = {"crf": "21", "preset": "fast", "bf": "0"} + for index, pts, time_base, image in iter_frames(video, capture["rotation_degrees"]): + frame = av.VideoFrame.from_ndarray(annotate_image(image, observations["frames"][index]), format="bgr24") + frame.pts = pts + frame.time_base = time_base + for packet in stream.encode(frame): + out.mux(packet) + for packet in stream.encode(): + out.mux(packet) + # Verify all source presentation positions survived muxer time-base rescaling. + exported = list((pts, tb) for _, pts, tb, _ in iter_frames(temporary)) + if len(exported) != len(frames): + raise ValueError("Export changed frame count") + for original, (pts, tb) in zip(frames, exported): + tolerance = max(float(tb), float(Fraction(original["time_base"]))) + if abs(float(pts*tb)-original["playback_s"]) > tolerance: + raise ValueError("Export changed source presentation timing") + os.replace(temporary, destination) + return {"status": "complete", "path": destination.name, "audio": "not_included", + "timing": "source_pts_verified_within_muxer_tick"} + except Exception as e: + if temporary.exists(): + temporary.unlink() + return {"status": "failed", "reason": str(e)[:300]} + +def write_reports(root, result, curves): + root = Path(root) + root.mkdir(parents=True, exist_ok=True) + atomic_json(root / "result.json", result) + tmp = root / "curves.tmp.npz" + np.savez_compressed(tmp, **curves) + tmp.replace(root / "curves.npz") + metrics = result["metrics"] + columns = ["metric_id", "value", "unit", "suitability", "unavailable_reason", "validation_status", "feedback_eligibility", "event_id", "uncertainty_kind", "geometry_source", "timing_source", "definition_version"] + with (root / "metrics.csv").open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=columns) + writer.writeheader() + for m in metrics: + writer.writerow({k: m.get(k) for k in columns}) + def esc(x): + return html.escape(str(x)) + diagnostics = result.get("diagnostics", {}) + coverage = "" + if diagnostics: + coverage = (f"

Analysis coverage

{esc(diagnostics['message'])}

" + f"

Usable body observations: {diagnostics['body_frames']} / {diagnostics['frame_count']} frames. " + f"Bat endpoints: {diagnostics['bat_endpoint_frames']} frames. " + f"Ball observations: {diagnostics['ball_frames']} frames. " + f"Available measurements: {diagnostics.get('available_metrics', 0)}.

") + if diagnostics.get("source_note"): + coverage += f"

{esc(diagnostics['source_note'])}

" + actions = [] + if diagnostics.get("bat_box_frames", 0) and not diagnostics.get("bat_endpoint_frames", 0): + 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.") + failed = [s for s in result["stages"].values() if s["status"] in {"failed", "failed_preflight"}] + if any("CUDA" in s.get("reason", "") for s in failed): + 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.") + if result["stages"].get("body3d", {}).get("status") == "disabled_by_configuration": + actions.append("Body reconstruction was disabled. Enable BUILD_FULL_WORKER with accessible SAM assets for the 3D body stages.") + if not result["capture"]["physical_clock_known"]: + actions.append("Capture timing is undocumented. Physical durations and velocities remain unavailable until timing evidence is supplied.") + if result["capture"]["camera_stability"] != "fixed_verified": + actions.append("Camera stability is unverified. Hand path and motion measurements that require a fixed camera are withheld.") + next_steps = "

What needs attention

    " + "".join(f"
  • {esc(a)}
  • " for a in actions) + "
" if actions else "" + rows = [] + for m in metrics: + value = "Unavailable" if m["value"] is None else f"{m['value']:.3f} {esc(m['unit'])}" + rows.append(f"{esc(m['metric_id'])}{value}{esc(m['suitability'])}{esc(m['unavailable_reason'] or m['validation_status'])}{esc(m['evidence_frames'])}") + stages = "".join(f"
  • {esc(k)}: {esc(v['status'])} — {esc(v.get('reason', ''))}
  • " for k,v in result["stages"].items()) + event_rows = "".join(f"
  • {esc(e['type'])}: {esc(e['state'])}; frames {esc(e['frame_interval'])}; {esc(e['method'])}; {esc(e['review_status'])}
  • " for e in result["events"]) + findings = "" + for f in result["findings"]: + exercise=f.get("research_exercise") + detail="" + if exercise: + source=exercise["source"];url=source["url"] + if url.startswith("https://"): + detail=f"

    Educational research hypothesis: {esc(exercise['instruction'])} {esc(source['title'])}. Objective: {esc(exercise['objective'])}. Benefit not established.

    " + findings+=f"
  • {esc(f['description'])}{detail}
  • " + page = f''' +Batting research report +

    Batting research report

    {coverage}{next_steps}

    {esc(result['status'])} · {esc(result['provenance'])}. Reference validation pending. Expert review: not reviewed. Projected measurements describe this recording; no personalized corrective diagnosis is established.

    +

    Physical clock: {esc(result['capture']['timing_source'])}. Input SHA-256: {esc(result['capture']['input_sha256'])}

    +

    Executed stages

      {stages}

    Events and review

      {event_rows}
    +

    Metrics

    {''.join(rows)}
    DefinitionValueSuitabilityReason / validationEvidence frames
    +

    Evidence-linked observations

      {findings}

    Machine-readable provenance, definitions and timing are in result.json; continuous curves are in curves.npz.

    ''' + (root / "report.html").write_text(page) + return [root / n for n in ("result.json", "curves.npz", "metrics.csv", "report.html")] diff --git a/baseball_batting/resources.py b/baseball_batting/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..7af5cbfc208d0fae57ed7db3c596f15ff243f25e --- /dev/null +++ b/baseball_batting/resources.py @@ -0,0 +1,63 @@ +"""Explicit artifact acquisition, separate from inference. No credentials in records.""" +from datetime import datetime, timezone +from pathlib import Path +import shutil +import urllib.request +import zipfile +import yaml +from .storage import atomic_json, sha256_file, read_json + +def fetch_artifact(resource_id, registry_path, directory): + resource = yaml.safe_load(Path(registry_path).read_text())["resources"][resource_id] + url = resource["source_url"] + if resource["type"] != "checkpoint" or not url.endswith((".zip", ".onnx")): + raise ValueError("This downloader only handles explicit public ONNX artifacts") + folder = Path(directory) / resource_id + folder.mkdir(parents=True, exist_ok=True) + archive = folder / url.rsplit("/", 1)[-1] + record_path = folder / "resource.json" + if record_path.is_file(): + cached = read_json(record_path) + cached_model = Path(cached["artifact_path"]) + if cached_model.resolve().is_relative_to(folder.resolve()) and cached_model.is_file() and cached.get("source_url") == url: + if sha256_file(cached_model) == cached.get("sha256") and (not resource.get("sha256") or resource["sha256"] == cached["sha256"]): + return cached + expected = resource.get("archive_sha256") or (resource.get("sha256") if archive.suffix != ".zip" else None) + if not archive.is_file() or (expected and sha256_file(archive) != expected): + temporary = archive.with_suffix(archive.suffix + ".tmp") + request = urllib.request.Request(url, headers={"User-Agent": "baseball-batting-research/0.1"}) + with urllib.request.urlopen(request, timeout=120) as src, temporary.open("wb") as dst: + shutil.copyfileobj(src, dst) + if expected and sha256_file(temporary) != expected: + temporary.unlink() + raise ValueError("Published artifact checksum mismatch") + temporary.replace(archive) + if archive.suffix == ".zip": + with zipfile.ZipFile(archive) as z: + onnx_members = [i for i in z.infolist() if i.filename.endswith(".onnx")] + if len(onnx_members) != 1: + raise ValueError("Expected exactly one ONNX model in artifact") + info = onnx_members[0] + if info.file_size > 2_000_000_000: + raise ValueError("Unexpectedly large ONNX artifact") + # Flatten explicitly; never extract untrusted archive paths. + model = folder / "model.onnx" + temporary = model.with_suffix(".tmp") + with z.open(info) as src, temporary.open("wb") as dst: + shutil.copyfileobj(src, dst) + temporary.replace(model) + else: + model = archive + if resource.get("sha256") and sha256_file(model) != resource["sha256"]: + model.unlink() + raise ValueError("Extracted model checksum mismatch") + record = {**resource, "resource_id": resource_id, "access_status": "accessible", + "technical_test_status": "candidate", "sha256": sha256_file(model), + "archive_sha256": sha256_file(archive), "artifact_path": str(model.resolve()), + "date": datetime.now(timezone.utc).isoformat(), + "integrity_basis": "registry_sha256" if expected or resource.get("sha256") else "first_download_sha256_recorded", + "commercial_license_review": "deferred"} + atomic_json(record_path, record) + if archive.suffix == ".zip": + archive.unlink() # Keep its recorded hash, not a duplicate several-hundred-MB file. + return record diff --git a/baseball_batting/review.py b/baseball_batting/review.py new file mode 100644 index 0000000000000000000000000000000000000000..ceaa6229e402dba017b2fdd7084064603ca69c5a --- /dev/null +++ b/baseball_batting/review.py @@ -0,0 +1,69 @@ +"""Notebook-native frame-by-frame review, using coordinates in the oriented image.""" +from pathlib import Path +import numpy as np +from .ingest import iter_frames +from .storage import atomic_json +from .annotations import load_annotations +from .contracts import RTMW_CORE + +def annotation_template(capture, annotator): + return {"schema_version": "1.0", "input_sha256": capture["input_sha256"], + "coordinate_space": capture["coordinate_space"], "annotator": annotator, + "frames": {}, "events": []} + +def show_review_widget(video, capture, destination, annotator="operator"): + """Lazy widget imports so the backend needs neither a web server nor UI packages.""" + import cv2 + import ipywidgets as widgets + from IPython.display import display, clear_output + destination = Path(destination) + labels = load_annotations(destination, capture["input_sha256"], capture["frame_count"], + capture["frames"][0]["width"], capture["frames"][0]["height"]) if destination.exists() else annotation_template(capture, annotator) + slider = widgets.IntSlider(min=0, max=capture["frame_count"]-1, description="Frame") + frame_json = widgets.Textarea(value="{}", description="Labels", layout=widgets.Layout(width="100%", height="180px")) + event_json = widgets.Textarea(value="[]", description="Events", layout=widgets.Layout(width="100%", height="140px")) + button = widgets.Button(description="Save reviewed labels") + image = widgets.Image(format="png") + output = widgets.Output() + import json + def display_frame(change=None): + k = slider.value + for frame_id, _, _, img in iter_frames(video, capture["rotation_degrees"]): + if frame_id == k: + # Coordinate grid helps read exact positions without a custom browser service. + h, w = img.shape[:2] + for x in range(0, w, 50): + cv2.line(img, (x,0), (x,h-1), (80,80,80), 1) + cv2.putText(img, str(x), (x,15), cv2.FONT_HERSHEY_SIMPLEX, .4, (255,255,255), 1) + for y in range(50, h, 50): + cv2.line(img, (0,y), (w-1,y), (80,80,80), 1) + cv2.putText(img, str(y), (0,y), cv2.FONT_HERSHEY_SIMPLEX, .4, (255,255,255), 1) + image.value = cv2.imencode(".png", img)[1].tobytes() + break + frame_json.value = json.dumps(labels["frames"].get(str(k), {}), indent=2) + event_json.value = json.dumps(labels["events"], indent=2) + def save(_): + with output: + clear_output() + try: + candidate = dict(labels) + candidate["frames"] = {**labels["frames"], str(slider.value): json.loads(frame_json.value)} + candidate["events"] = json.loads(event_json.value) + temp = destination.with_suffix(".review.tmp.json") + atomic_json(temp, candidate) + try: + load_annotations(temp, capture["input_sha256"], capture["frame_count"], + capture["frames"][0]["width"], capture["frames"][0]["height"]) + finally: + temp.unlink(missing_ok=True) + atomic_json(destination, candidate) + labels.update(candidate) + print(f"Saved frame {slider.value} and reviewed events") + except Exception as e: + print(f"Labels not saved: {e}") + slider.observe(display_frame, names="value") + button.on_click(save) + display_frame() + display(widgets.VBox([slider, image, frame_json, event_json, button, output])) + return labels + diff --git a/baseball_batting/sensitivity.py b/baseball_batting/sensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..2b140bbef642411083df74ebef0a53c49daf1a00 --- /dev/null +++ b/baseball_batting/sensitivity.py @@ -0,0 +1,28 @@ +"""Documented perturbation experiments; their spread is not an accuracy interval.""" +import copy +import numpy as np +from .metrics import continuous_curves, summarize +from .contracts import RTMW_CORE + + +def apply_image_sensitivity(metrics,observations,capture,events): + supplied=capture["metadata"].get("uncertainty",{}) + magnitude=supplied.get("landmark_pixel_perturbation") + if not supplied.get("source") or not isinstance(magnitude,(int,float)) or not np.isfinite(magnitude) or magnitude<=0:return + scenarios=[] + # Opposing endpoint/joint perturbations alter geometry rather than translating + # the whole skeleton, which would misleadingly report zero angle sensitivity. + for sign in (-1,1): + scenario=copy.deepcopy(observations) + for frame in scenario["frames"]: + points=np.array(frame["body_points"],float) + 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) + frame["body_points"]=points.tolist() + scenarios.append({m.metric_id:m.value for m in summarize(continuous_curves(scenario,capture),scenario,capture,events)}) + for metric in metrics: + values=[s.get(metric.metric_id) for s in scenarios] + if metric.value is None or any(v is None for v in values):continue + metric.sensitivity={"source":supplied["source"],"method":"opposing_xy_landmark_perturbation_v1", + "input_magnitude_px":magnitude,"maximum_value_change":max(abs(v-metric.value) for v in values), + "unit":metric.unit,"interpretation":"two_scenarios_not_calibrated_error_bounds"} + metric.uncertainty_kind="documented_input_sensitivity" diff --git a/baseball_batting/storage.py b/baseball_batting/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b15b18797dc57d0b3caae2712e14b66d1404ed --- /dev/null +++ b/baseball_batting/storage.py @@ -0,0 +1,99 @@ +"""Atomic manifests, input-sensitive keys and checksummed chunk recovery.""" +from pathlib import Path +import hashlib +import json +import os +import tempfile +import zipfile +from .contracts import json_safe + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + +def digest(value): + return hashlib.sha256(json.dumps(json_safe(value), sort_keys=True, + allow_nan=False, separators=(",", ":")).encode()).hexdigest() + +def code_hash(): + root = Path(__file__).parent + return digest({p.name: sha256_file(p) for p in sorted(root.glob("*.py"))}) + +def atomic_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + fd, temp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") + try: + with os.fdopen(fd, "w") as f: + json.dump(json_safe(value), f, indent=2, sort_keys=True, allow_nan=False) + f.flush() + os.fsync(f.fileno()) + os.replace(temp, path) + finally: + if os.path.exists(temp): + os.unlink(temp) + +def read_json(path): + return json.loads(Path(path).read_text()) + +class StageCache: + def __init__(self, root, stage, key): + self.root = Path(root) / "stages" / stage / key + self.root.mkdir(parents=True, exist_ok=True) + self.key = key + self.stage = stage + + def valid(self, name): + manifest_path = self.root / f"{name}.manifest.json" + if not manifest_path.exists(): + return None + try: + m = read_json(manifest_path) + if m.get("status") != "complete" or m.get("key") != self.key: + return None + for relative, checksum in m["artifacts"].items(): + p = (self.root / relative).resolve() + if not p.is_relative_to(self.root.resolve()) or not p.is_file(): + return None + if sha256_file(p) != checksum: + return None + return m + except (OSError, ValueError, KeyError): + return None + + def commit(self, name, artifacts, **details): + m = {"stage": self.stage, "key": self.key, "status": "complete", + "artifacts": {str(Path(p).relative_to(self.root)): sha256_file(p) + for p in artifacts}, **details} + atomic_json(self.root / f"{name}.manifest.json", m) + return m + + def failure(self, reason, detail): + atomic_json(self.root / "failure.json", {"stage": self.stage, "key": self.key, + "status": "failed", "reason": reason, "detail": str(detail)[:1000]}) + +def export_archive(root, destination): + """Export results and verified state only. Input videos/credentials are never bundled.""" + root, destination = Path(root).resolve(), Path(destination).resolve() + verified=set() + stages=root/"stages" + if stages.exists(): + for manifest in stages.rglob("*.manifest.json"): + try: + record=read_json(manifest) + cache=StageCache(root,record["stage"],record["key"]) + if cache.valid(manifest.name.removesuffix(".manifest.json")): + verified.add(manifest.resolve()) + verified.update((manifest.parent/name).resolve() for name in record["artifacts"]) + except (ValueError,KeyError,OSError):continue + with zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as z: + for p in sorted(root.rglob("*")): + if not p.is_file() or p.resolve()==destination or ".tmp" in p.name:continue + if stages in p.parents and p.resolve() not in verified:continue + if p.name.startswith("."):continue + if p.is_file(): + z.write(p, p.relative_to(root)) + return destination diff --git a/baseball_batting/temporal3d.py b/baseball_batting/temporal3d.py new file mode 100644 index 0000000000000000000000000000000000000000..aac624af446cd722fc500fd580ac3f47eb994867 --- /dev/null +++ b/baseball_batting/temporal3d.py @@ -0,0 +1,269 @@ +"""Shared-shape differentiable MHR sequence fitting, independent of SAM inference lifetime.""" +from pathlib import Path +import numpy as np +from .contracts import RTMW_CORE +from .motion import contiguous_segments +from .storage import StageCache, atomic_json, digest, read_json, sha256_file + +MHR_CORE = {"nose": 0, "left_shoulder": 5, "right_shoulder": 6, "left_elbow": 7, + "right_elbow": 8, "left_hip": 9, "right_hip": 10, "left_knee": 11, + "right_knee": 12, "left_ankle": 13, "right_ankle": 14, + "left_big_toe": 15, "left_small_toe": 16, "left_heel": 17, + "right_big_toe": 18, "right_small_toe": 19, "right_heel": 20, + "right_wrist": 41, "left_wrist": 62} + + +class MHRForward: + def __init__(self, asset, adapter, device): + import torch + self.torch = torch + self.device = device + self.model = torch.jit.load(str(asset), map_location=device).eval() + for parameter in self.model.parameters(): + parameter.requires_grad_(False) + data = np.load(adapter, allow_pickle=False) + indices = torch.tensor(np.stack([data["regressor_rows"], data["regressor_columns"]]), device=device) + values = torch.tensor(data["regressor_values"], device=device, dtype=torch.float32) + self.regressor = torch.sparse_coo_tensor(indices, values, tuple(data["regressor_shape"]), device=device).coalesce() + self.flip = torch.tensor([1., -1., -1.], device=device) + + def __call__(self, shape, motion, scales, camera): + torch = self.torch + parameters = torch.cat([motion, scales.expand(len(motion), -1)], dim=1) + vertices, skeleton = self.model(shape.expand(len(motion), -1), parameters, + torch.zeros(len(motion), 72, device=motion.device)) + combined = torch.cat([vertices, skeleton[..., :3]], dim=1) / 100 + landmarks = torch.sparse.mm(self.regressor, combined.transpose(0, 1).reshape(combined.shape[1], -1)) + landmarks = landmarks.reshape(70, len(motion), 3).transpose(0, 1) + return landmarks*self.flip + camera[:, None, :] + + def neutral_height(self,shape,scales): + torch=self.torch + parameters=torch.cat([torch.zeros(1,136,device=self.device),scales[None]],1) + vertices,_=self.model(shape[None],parameters,torch.zeros(1,72,device=self.device)) + return (vertices[...,1].max()-vertices[...,1].min())/100 + + +def fit_sequence(forward, initial, pixels, weights, times, settings, limits=None, temporal_factor=1., frame_ids=None): + import torch + device = initial["motion"].device + motion0 = initial["motion"].detach() + motion = torch.nn.Parameter(motion0[:, 3:].clone()) + shape0, scale0 = initial["shape"].median(dim=0).values, initial["scales"].median(dim=0).values + shape, scales = torch.nn.Parameter(shape0.clone()), torch.nn.Parameter(scale0.clone()) + camera = torch.nn.Parameter(initial["camera"].clone()) + pixels = torch.as_tensor(pixels, dtype=torch.float32, device=device) + weights = torch.as_tensor(weights, dtype=torch.float32, device=device) + safe_pixels = torch.nan_to_num(pixels) + k = initial["intrinsics"] + target3d = initial["keypoints"].detach() + time = torch.as_tensor(times, dtype=torch.float32, device=device) + scale_px = settings["robust_pixel_scale"] + temporal_weight = settings["temporal_weight"]*temporal_factor + initial_weights = initial.get("valid", torch.ones(len(motion), device=device)) + ids = np.arange(len(motion)) if frame_ids is None else np.asarray(frame_ids) + triples = torch.as_tensor((np.diff(ids)[:-1] == 1) & (np.diff(ids)[1:] == 1), device=device) + parameters = [motion, shape, scales, camera] + + def evaluate(): + terms = {"reprojection": [], "initializer": [], "cheirality": []} + points = [] + for a in range(0, len(motion), settings["batch_size"]): + b = min(a+settings["batch_size"], len(motion)) + # Native root translation remains fixed; camera translation supplies the single translation gauge. + full_motion = torch.cat([motion0[a:b, :3], motion[a:b]], dim=1) + xyz = forward(shape, full_motion, scales, camera[a:b]) + points.append(xyz) + homogeneous = xyz @ k.T + projected = homogeneous[..., :2]/homogeneous[..., 2:3].clamp(min=1e-5) + error = (projected-safe_pixels[a:b])/scale_px + terms["reprojection"].append((torch.sqrt(1+error.square())-1).sum(-1)*weights[a:b]) + terms["initializer"].append((xyz-target3d[a:b]).square().sum(-1)*initial_weights[a:b, None]) + terms["cheirality"].append(torch.relu(.01-xyz[..., 2]).square()) + xyz = torch.cat(points) + losses = {"reprojection": torch.cat(terms["reprojection"]).sum()/weights.sum().clamp(min=1), + "initializer": torch.cat(terms["initializer"]).sum()/(initial_weights.sum()*70).clamp(min=1), + "cheirality": torch.cat(terms["cheirality"]).mean(), + "shape_prior": (shape-shape0).square().mean()+(scales-scale0).square().mean(), + "motion_prior": (motion-motion0[:, 3:]).square().mean(), + "temporal": torch.zeros((), device=device), "limits": torch.zeros((), device=device), + "height_prior":torch.zeros((),device=device)} + if initial.get("height_prior") is not None: + value,scale=initial["height_prior"] + losses["height_prior"]=((forward.neutral_height(shape,scales)-value)/scale).square() + if len(time) >= 3: + dt = time[1:]-time[:-1] + if (dt <= 0).any(): + raise ValueError("Fitting clock must increase without duplicate samples") + velocity = (xyz[1:]-xyz[:-1])/dt[:, None, None] + acceleration = (velocity[1:]-velocity[:-1])/((dt[1:]+dt[:-1])/2)[:, None, None] + if triples.any(): + losses["temporal"] = acceleration[triples].square().mean() + if limits is not None: + lower, upper = [torch.as_tensor(v, device=device) for v in limits] + losses["limits"] = (torch.relu(lower-motion).square()+torch.relu(motion-upper).square()).mean() + total = (settings["reprojection_weight"]*losses["reprojection"]+ + settings["initializer_weight"]*losses["initializer"]+ + settings["shape_prior_weight"]*losses["shape_prior"]+ + settings["motion_prior_weight"]*losses["motion_prior"]+ + temporal_weight*losses["temporal"]+settings["limit_weight"]*losses["limits"]+ + settings.get("height_prior_weight",.01)*losses["height_prior"]+ + 100*losses["cheirality"]) + return total, losses, xyz + + optimizer = torch.optim.Adam(parameters, lr=settings["learning_rate"]) + for _ in range(settings["adam_steps"]): + optimizer.zero_grad(); loss, _, _ = evaluate() + if not torch.isfinite(loss): + raise ValueError("Nonfinite MHR objective") + loss.backward(); torch.nn.utils.clip_grad_norm_(parameters, 10.); optimizer.step() + optimizer = torch.optim.LBFGS(parameters, max_iter=settings["lbfgs_steps"], line_search_fn="strong_wolfe") + def closure(): + optimizer.zero_grad(); loss, _, _ = evaluate(); loss.backward(); return loss + if settings["lbfgs_steps"]: + optimizer.step(closure) + with torch.no_grad(): + _, penalties, xyz = evaluate() + h = xyz @ k.T + reprojection = torch.linalg.vector_norm(h[..., :2]/h[..., 2:3]-safe_pixels, dim=-1) + residual = torch.where(weights > 0, reprojection, torch.full_like(reprojection, float("nan"))) + return {"keypoints_m": xyz.detach().cpu().numpy(), "motion_params": torch.cat([motion0[:, :3], motion], 1).detach().cpu().numpy(), + "shared_shape": shape.detach().cpu().numpy(), "shared_scales": scales.detach().cpu().numpy(), + "camera_translation_m": camera.detach().cpu().numpy(), "reprojection_px": residual.cpu().numpy(), + "objective_terms": {name: float(value.detach()) for name, value in penalties.items()}, + "limit_source": "explicit_asset_parameter_bounds" if limits is not None else "not_available; initializer_prior_only"} + + +def export_mhr_adapter(model, destination, prediction, asset): + """Export the exact loaded body regressor, not an invented rig/landmark correspondence.""" + candidates = [module for module in model.modules() if hasattr(module, "keypoint_mapping") + and hasattr(module, "mhr") and getattr(module, "enable_hand_model", None) is False] + if len(candidates) != 1: + raise ValueError("Cannot uniquely identify the loaded full-body MHR regressor") + head = candidates[0] + mapping = head.keypoint_mapping.detach().cpu().numpy()[:70] + if (np.abs(mapping).sum(axis=1) == 0).any(): + raise ValueError("Loaded MHR landmark regressor contains empty rows") + rows, columns = np.nonzero(mapping) + np.savez_compressed(destination, regressor_rows=rows, regressor_columns=columns, + regressor_values=mapping[rows, columns], regressor_shape=mapping.shape) + return {"mhr_asset_sha256": sha256_file(asset), "regressor_sha256": sha256_file(destination), + "rig_joint_count": int(np.asarray(prediction["pred_joint_coords"]).shape[-2]), + "regressor_shape": list(mapping.shape), "keypoint_names": MHR_CORE, + "source_kind": "model_regression_proxy", "independent_observation": False} + + +def run_temporal(request, capture, config, observation_cache): + root = Path(request["root"]) + status_path = root / "temporal3d_status.json" + try: + import torch, yaml + torch.backends.cuda.matmul.allow_tf32=False + torch.backends.cudnn.allow_tf32=False + from .observations import collect_observations + initializer = read_json(root / "body3d_status.json") + if initializer.get("status") not in {"complete", "partial"}: + raise ValueError("SAM initializer unavailable") + source = root / "stages/body3d" / initializer["cache_key"] + adapter = source / "mhr_adapter.npz" + if not adapter.exists(): + raise ValueError("Exact loaded MHR regressor has not been exported") + settings = yaml.safe_load(Path(config.fitting_config_path).read_text()) + calibration = capture["metadata"].get("calibration", {}) + from .geometry import intrinsics + k = calibration.get("intrinsics_oriented_pixels") or initializer.get("intrinsics_used") + if k is None: + raise ValueError("Initializer camera intrinsics are missing") + key = digest({"initializer": initializer["cache_key"], "adapter": sha256_file(adapter), + "settings": settings, "limits": sha256_file(config.mhr_limits_path) if config.mhr_limits_path else None}) + cache = StageCache(root, "temporal3d", key) + if cache.valid("trajectory"): + atomic_json(status_path, read_json(cache.root / "status.json")); return + count = capture["frame_count"] + observations = collect_observations(observation_cache, (count+config.chunk_size-1)//config.chunk_size) + available = np.array([(source / f"frame_{i:06d}.npz").exists() for i in range(count)]) + if available.sum() < 3: + raise ValueError("At least three initialized frames are required") + clock = "physical" if capture["physical_clock_known"] else "playback" + times = np.array([f["physical_s"] if clock == "physical" else f["playback_s"] for f in capture["frames"]], float) + 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) + device = "cuda" if config.device == "cuda" else "cpu" + forward = MHRForward(config.mhr_path, adapter, device) + weights = np.zeros((count, 70)); pixels = np.full((count, 70, 2), np.nan) + for i, frame in enumerate(observations["frames"]): + for name, target in MHR_CORE.items(): + index = RTMW_CORE[name] + if frame["body_states"][index] in {"model_inferred", "manual", "image_supported"}: + pixels[i, target] = frame["body_points"][index] + score = frame["body_scores"][index] + weights[i, target] = 1 if frame["body_states"][index] == "manual" else np.clip(score, 0, 1) + # Optimize the whole observed short clip with ONE shape/scales vector. Missing + # frames are never synthesized; temporal triplets exclude every source-frame gap. + ids = np.flatnonzero(available & np.isfinite(times)) + data = [np.load(source / f"frame_{i:06d}.npz", allow_pickle=False) for i in ids] + initial = {"motion": np.stack([d["mhr_model_params"].reshape(-1)[:136] for d in data]), + "scales": np.stack([d["mhr_model_params"].reshape(-1)[136:] for d in data]), + "shape": np.stack([d["shape_params"].reshape(-1) for d in data]), + "camera": np.stack([d["pred_cam_t"].reshape(3) for d in data]), + "keypoints": np.stack([d["camera_keypoints_m"].reshape(70, 3) for d in data]), + "intrinsics": intrinsics(k)} + initial = {name: torch.tensor(value, dtype=torch.float32, device=device) for name, value in initial.items()} + if initial["scales"].shape[1] != 68 or initial["motion"].shape[1] != 136: + raise ValueError("Unexpected bundled MHR parameter topology") + with torch.no_grad(): + raw=forward(initial["shape"][0],initial["motion"][:1],initial["scales"][0],initial["camera"][:1]) + if torch.linalg.vector_norm(raw-initial["keypoints"][:1],dim=-1).max()>.001: + raise ValueError("Exact native MHR forward does not reproduce SAM landmarks within 1mm") + height=capture["metadata"].get("height_m") + uncertainty=capture["metadata"].get("uncertainty",{}) + height_scale=uncertainty.get("height_prior_scale_m") + if height and uncertainty.get("height_source") and isinstance(height_scale,(int,float)) and height_scale>0: + initial["height_prior"]=(height,height_scale) + limits = None + if config.mhr_limits_path: + bounds = read_json(config.mhr_limits_path) + if bounds.get("asset_sha256") != sha256_file(config.mhr_path) or not bounds.get("source"): + raise ValueError("MHR limits must identify this exact asset and their source") + limits = (bounds["lower"], bounds["upper"]) + if any(len(v) != 133 for v in limits): + raise ValueError("MHR motion limits require 133 entries excluding root translation") + fit = fit_sequence(forward, initial, pixels[ids], weights[ids], times[ids], settings, limits, frame_ids=ids) + all_raw[ids] = initial["keypoints"].cpu().numpy() + residuals = fit["reprojection_px"] + support = (np.isfinite(residuals).sum(axis=1) >= settings.get("minimum_observed_landmarks", 6)) + error = np.sqrt(np.divide(np.nansum(residuals**2, axis=1), np.maximum(np.isfinite(residuals).sum(axis=1), 1))) + accepted = np.zeros(count, bool) + accepted[ids] = support & (error <= settings["max_reprojection_rmse_px"]) + if not accepted.any(): + raise ValueError("No fitted frame passed observation agreement checks") + all_points[ids[accepted[ids]]] = fit["keypoints_m"][accepted[ids]] + all_residual[ids] = residuals + penalties = {"terms": fit["objective_terms"], "limit_source": fit["limit_source"]} + solution = cache.root / "solution.npz" + np.savez_compressed(solution, frame_ids=ids, **{name: value for name, value in fit.items() if isinstance(value, np.ndarray)}) + sensitivities = [] + for factor in settings.get("sensitivity_temporal_factors", []): + scenario = fit_sequence(forward, initial, pixels[ids], weights[ids], times[ids], settings, limits, factor, ids) + sensitivities.append({"temporal_factor": factor, + "max_landmark_change_m": float(np.linalg.norm(scenario["keypoints_m"]-fit["keypoints_m"], axis=-1).max())}) + with torch.no_grad(): + neutral = forward(torch.tensor(fit["shared_shape"], device=device), + torch.zeros(1, 136, device=device), torch.tensor(fit["shared_scales"], device=device), + torch.zeros(1, 3, device=device)).cpu().numpy()[0] + trajectory = cache.root / "trajectory.npz" + np.savez_compressed(trajectory, keypoints_camera_m=all_points, raw_camera_m=all_raw, + reprojection_px=all_residual, accepted_frames=accepted, fitting_times=times, neutral_mhr70_m=neutral, observation_weights=weights) + status = {"status": "complete" if accepted.all() else "partial", "cache_key": key, + "frames_fitted": int(accepted.sum()), "frame_count": count, "objective_terms": penalties, + "sensitivity": sensitivities, "uncertainty_kind": "regularization_sensitivity; not calibrated accuracy", + "maximum_regularization_sensitivity_m":max((s["max_landmark_change_m"] for s in sensitivities),default=None), + "coordinate_space": "camera_x_right_y_down_z_forward_metres", "regularization_clock": clock, + "shape_scope": "shared_across_complete_observed_clip", + "height_prior_source":uncertainty.get("height_source") if initial.get("height_prior") else None, + "geometry_source": "calibrated_intrinsics_model_scale" if calibration.get("intrinsics_oriented_pixels") else "assumed_intrinsics_model_scale", + "validation": "reference-validation-pending", "trajectory_path": str(trajectory.relative_to(root))} + atomic_json(cache.root / "status.json", status) + cache.commit("trajectory", [trajectory, solution, cache.root / "status.json"]) + except Exception as error: + status = {"status": "unavailable", "reason": str(error)[:300], "error_type": type(error).__name__} + atomic_json(status_path, status) diff --git a/baseball_batting/training.py b/baseball_batting/training.py new file mode 100644 index 0000000000000000000000000000000000000000..c2113afe8674c15b26081e272ec2e544c9246408 --- /dev/null +++ b/baseball_batting/training.py @@ -0,0 +1,144 @@ +"""Actual optimization, held-out evaluation and explicit checkpoint activation records.""" +from pathlib import Path +import copy +import random +import numpy as np +from .storage import read_json, atomic_json, sha256_file, digest +from .learning import endpoint_network, temporal_network, BOUNDARIES, PHASES, FEATURE_VERSION +from .dataset import validate_splits + + +def load_dataset(directory,kind): + directory=Path(directory);manifest=read_json(directory/"dataset.json") + if manifest["kind"]!=kind:raise ValueError("Training dataset kind mismatch") + players={} + for sample in manifest["samples"]: + if sample["player_id"] in players and players[sample["player_id"]]!=sample["split"]:raise ValueError("Athlete leakage") + players[sample["player_id"]]=sample["split"] + if sha256_file(directory/sample["path"])!=manifest["artifact_hashes"][sample["path"]]:raise ValueError("Dataset artifact changed") + if set(players.values())!={"train","validation","test"}:raise ValueError("Nonempty grouped partitions required") + return manifest + + +def sample_loss(model,data,kind,device): + import torch + import torch.nn.functional as F + tensor=lambda value:torch.as_tensor(value,dtype=torch.float32,device=device) + if kind=="endpoint_cnn": + image=tensor(data["image"].transpose(2,0,1)/255.)[None] + heat,visible=model(image) + support=tensor(data["visible"])[None,:,None,None] + heat_loss=((heat.sigmoid()-tensor(data["heatmaps"])[None])**2*support).sum()/(support.sum()*4096).clamp(min=1) + mask=tensor(data["visibility_mask"])[None] + visibility=(F.binary_cross_entropy_with_logits(visible,tensor(data["visible"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1) + return heat_loss+visibility + phase,boundary,presence=model(tensor(data["features"])[None]) + target=torch.as_tensor(data["phase"],dtype=torch.long,device=device)[None] + loss=sum(F.cross_entropy(p,target,ignore_index=-100) for p in phase) + # Adjacent high-cadence source samples are retained; never invent negative + # boundaries for unknown events or substitute clip-wide contact presence. + mask=tensor(data["boundary_mask"])[None] + loss+=(F.binary_cross_entropy_with_logits(boundary,tensor(data["boundary"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1) + mask=tensor(data["presence_mask"])[None] + loss+=(F.binary_cross_entropy_with_logits(presence,tensor(data["presence"])[None],reduction="none")*mask).sum()/mask.sum().clamp(min=1) + if target.shape[1]>1: + known=(target[:,1:]!=-100)&(target[:,:-1]!=-100) + logp=phase[-1].log_softmax(1) + smooth=(logp[:,:,1:]-logp[:,:,:-1].detach()).square().clamp(max=16) + loss+=.15*(smooth*known[:,None]).sum()/(known.sum()*len(PHASES)).clamp(min=1) + return loss + + +def train(directory,output,kind,epochs=30,learning_rate=.001,device="cpu",mstcn_repo=None,seed=17): + import torch + if epochs<1:raise ValueError("Positive epoch count required") + torch.manual_seed(seed);np.random.seed(seed);random.seed(seed) + manifest=load_dataset(directory,kind);directory=Path(directory);output=Path(output);output.mkdir(parents=True,exist_ok=True) + architecture=None;source=None + if kind=="endpoint_cnn":model=endpoint_network() + else: + first=np.load(directory/manifest["samples"][0]["path"]) + architecture={"prediction_layers":6,"refinement_layers":6,"refinements":3,"channels":64,"feature_dim":first["features"].shape[0]} + model,source=temporal_network(mstcn_repo,architecture) + model=model.to(device);optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate) + partitions={name:[s for s in manifest["samples"] if s["split"]==name] for name in ("train","validation","test")} + if any(not p for p in partitions.values()):raise ValueError("No eligible samples in a partition") + best=float("inf");history=[] + for epoch in range(epochs): + model.train();order=partitions["train"].copy();random.shuffle(order);losses=[] + for sample in order: + data=np.load(directory/sample["path"],allow_pickle=False) + optimizer.zero_grad();loss=sample_loss(model,data,kind,device) + if not torch.isfinite(loss):raise ValueError("Nonfinite training loss") + loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5.);optimizer.step();losses.append(float(loss.detach())) + model.eval() + with torch.no_grad(): val=np.mean([float(sample_loss(model,np.load(directory/s["path"]),kind,device)) for s in partitions["validation"]]) + history.append({"epoch":epoch+1,"training_loss":float(np.mean(losses)),"validation_loss":float(val)}) + if val=.5 + target=data["heatmaps"].reshape(2,-1).argmax(1) + for j in range(2): + if not data["visibility_mask"][j]:continue + if data["visible"][j]: + expected+=1 + if not present[j]:missed+=1;continue + errors.append(float(np.linalg.norm([predicted[j]%64-target[j]%64,predicted[j]//64-target[j]//64])*4)) + else: + negative+=1;extra+=int(present[j]);correct_negative+=int(not present[j]) + else: + phase,boundary,presence=model(torch.tensor(data["features"],device=device)[None]) + predicted=phase[-1][0].argmax(0).cpu().numpy();mask=data["phase"]!=-100 + correct+=int((predicted[mask]==data["phase"][mask]).sum());total+=int(mask.sum()) + score=boundary.sigmoid()[0].cpu().numpy();present=presence.sigmoid()[0].cpu().numpy()>=.5 + for j in range(len(BOUNDARIES)): + if not data["presence_mask"][j]:continue + if data["presence"][j]: + expected+=1 + if not present[j] or score[j].max()<.5:missed+=1;continue + i=int(score[j].argmax());reference=np.flatnonzero(data["boundary"][j]>0) + errors.append(float(np.abs(reference-i).min())) + else: + negative+=1;extra+=int(present[j] and score[j].max()>=.5) + metrics={"median_error":float(np.median(errors)) if errors else None,"p95_error":float(np.percentile(errors,95)) if errors else None, + "miss_rate":missed/expected if expected else None,"extra_rate":extra/negative if negative else None, + "phase_accuracy":correct/total if total else None,"held_out_athlete_count":len({s["player_id"] for s in tests}), + "positive_labels":expected,"absent_labels":negative,"error_units":"256_crop_pixels" if kind=="endpoint_cnn" else "source_frames"} + checks={} + for name,limit in gates.get("maximum",{}).items():checks[name]=metrics.get(name) is not None and metrics[name]<=limit + for name,limit in gates.get("minimum",{}).items():checks[name]=metrics.get(name) is not None and metrics[name]>=limit + if not checks:raise ValueError("No qualification thresholds supplied") + result={"metrics":metrics,"checks":checks,"passed":all(checks.values()),"scope":scope, + "thresholds_sha256":sha256_file(thresholds_path),"checkpoint_sha256":sha256_file(checkpoint_directory/"checkpoint.pt"), + "dataset_sha256":sha256_file(directory/"dataset.json"),"validation":"experimental_detection_only"} + atomic_json(checkpoint_directory/"evaluation.json",result) + manifest["qualification"]={"status":"passed" if result["passed"] else "failed_preflight","held_out_athletes":True, + "evaluation_sha256":sha256_file(checkpoint_directory/"evaluation.json"),"scope":scope, + "thresholds_sha256":result["thresholds_sha256"]} + atomic_json(checkpoint_directory/"checkpoint.json",manifest);return result diff --git a/baseball_batting/validation.py b/baseball_batting/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b54d703b0b3bc8193ff4e374c8a18ef61e4cea78 --- /dev/null +++ b/baseball_batting/validation.py @@ -0,0 +1,48 @@ +"""Independent paired-reference evaluation. Distribution tables cannot qualify videos.""" +from pathlib import Path +import numpy as np +from .storage import read_json,atomic_json,sha256_file + + +def evaluate_reference(pairs_path,gates_path,output): + pairs=read_json(pairs_path);gates=read_json(gates_path) + if gates.get("preregistered") is not True or not gates.get("source") or not gates.get("scope"): + raise ValueError("Preregistered gates with source and explicit population/task/view scope required") + records={name:[] for name in gates.get("metrics",{})};coverage={name:0 for name in records};eligible={name:0 for name in records} + for pair in pairs: + if pair.get("independent_reference") is not True or pair.get("synchronization_verified") is not True or not pair.get("reference_source"): + raise ValueError("Every pair needs independent reference provenance and verified synchronization") + result=read_json(pair["result_path"]) + if result["capture"]["input_sha256"]!=pair["input_sha256"]:raise ValueError("Reference pair video mismatch") + if not pair.get("player_id") or not pair.get("session_id"):raise ValueError("Held-out athlete/session identity required") + metrics={m["metric_id"]:m for m in result["metrics"]} + for name in records: + reference=pair.get("metrics",{}).get(name) + if reference is None:continue + eligible[name]+=1 + measurement=metrics.get(name) + if measurement is None or measurement["value"] is None:continue + if measurement["unit"]!=reference["unit"]:raise ValueError("Reference units mismatch") + if reference.get("definition_version")!=measurement["definition_version"]:raise ValueError("Reference metric definition mismatch") + records[name].append({"error":measurement["value"]-reference["value"],"player_id":pair["player_id"], + "repeatability_group":pair.get("repeatability_group"),"result_code_hash":result["engine_code_hash"]}) + coverage[name]+=1 + evaluations={} + for name,rows in records.items(): + errors=np.array([r["error"] for r in rows]);groups={r["repeatability_group"] for r in rows if r["repeatability_group"]} + 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] + stats={"bias":float(np.mean(errors)) if len(errors) else None,"mae":float(np.mean(abs(errors))) if len(errors) else None, + "p95_absolute_error":float(np.percentile(abs(errors),95)) if len(errors) else None, + "measurement_coverage":coverage[name]/eligible[name] if eligible[name] else None, + "error_repeatability_sd":float(np.mean(repeat)) if repeat else None, + "athlete_count":len({r["player_id"] for r in rows}),"pair_count":len(rows), + "calibrated_uncertainty_coverage":None} + checks={};requirements=gates["metrics"][name] + for k,v in requirements.get("maximum",{}).items():checks[k]=stats.get(k) is not None and abs(stats[k])<=v + for k,v in requirements.get("minimum",{}).items():checks[k]=stats.get(k) is not None and stats[k]>=v + evaluations[name]={"statistics":stats,"checks":checks,"passed":bool(checks) and all(checks.values()), + "processing_code_hashes":sorted({r["result_code_hash"] for r in rows})} + report={"schema_version":"1.0","scope":gates["scope"],"evaluations":evaluations, + "pairs_sha256":sha256_file(pairs_path),"gates_sha256":sha256_file(gates_path), + "promotion":"evaluation_evidence_only; explicit_method_and_rule_review_required"} + atomic_json(output,report);return report diff --git a/baseball_batting/worker.py b/baseball_batting/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1531aa697d8cc1c8f8e796194167930e484d87 --- /dev/null +++ b/baseball_batting/worker.py @@ -0,0 +1,139 @@ +import sys +from pathlib import Path +import traceback +from .config import EngineConfig +from .storage import StageCache, atomic_json, read_json, digest + +def run_stage(stage, request): + config = EngineConfig(**request["config"]).validate() + root = Path(request["root"]) + ingestion = StageCache(root, "ingest", request["ingest_key"]) + observation_cache = StageCache(root, "observations", request["observation_key"]) + capture_path = ingestion.root / "capture.json" + if stage == "ingest": + from .ingest import ingest + capture = ingest(request["video"], request["metadata"]) + atomic_json(capture_path, capture) + ingestion.commit("capture", [capture_path], input_hash=capture["input_sha256"]) + return + capture = read_json(capture_path) + if stage == "observations": + from .observations import run_observations + run_observations(request["video"], capture, config, observation_cache) + return + if stage == "body3d": + from .body3d import run_initializer + run_initializer(request, capture, config, observation_cache) + return + if stage == "temporal3d": + from .temporal3d import run_temporal + run_temporal(request,capture,config,observation_cache);return + if stage == "anatomy": + from .anatomy import run_anatomy + run_anatomy(request,capture,config);return + if stage == "bat3d": + from .bat3d import run_bat3d + run_bat3d(request,capture,config);return + from .observations import collect_observations + from .annotations import load_annotations + from .metrics import continuous_curves, summarize + from .events import detect_events + from .assessment import assess + from .reports import write_reports, export_video + from .contracts import json_safe + count = (capture["frame_count"]+config.chunk_size-1)//config.chunk_size + observations = collect_observations(observation_cache, count) + if stage == "learned_events": + from .learning import run_learned_events + run_learned_events(request,capture,config,observations);return + annotations = load_annotations(config.annotations_path, capture["input_sha256"], capture["frame_count"], + capture["frames"][0]["width"], capture["frames"][0]["height"]) + curves = continuous_curves(observations, capture) + events = detect_events(curves, observations, capture, annotations, config.event_parameters) + if config.learned_events_enabled: + from .learning import merge_learned + p=root/"learned_events_status.json" + events=merge_learned(events,read_json(p) if p.exists() else {}) + for event in events: + if event.frame_interval: + a,b=event.frame_interval + event.playback_interval_s=[capture["frames"][a]["playback_s"],capture["frames"][b]["playback_s"]] + event.physical_interval_s=[capture["frames"][a]["physical_s"],capture["frames"][b]["physical_s"]] + metrics = summarize(curves, observations, capture, events) + import yaml + from .advanced_metrics import augment + from .sensitivity import apply_image_sensitivity + quality=yaml.safe_load(Path(config.quality_config_path).read_text()) + metrics=augment(root,curves,metrics,events,capture,quality,{"anatomy":config.body3d_enabled and config.temporal3d_enabled and config.anatomy_enabled, + "bat3d":config.bat_3d_mode!="disabled"}) + apply_image_sensitivity(metrics,observations,capture,events) + from .diagnostics import observation_summary + diagnostics = observation_summary(observations) + diagnostics["available_metrics"] = sum(m.value is not None for m in metrics) + diagnostics["requested_device"] = config.device + diagnostics["observation_environment"] = observations.get("runtime_environment") + stages = {"ingest": {"status": "complete"}, **observations["branch_status"], + "observations": {"status": diagnostics["status"], "reason": diagnostics["message"]}, + "events": {"status": "complete", "method": "candidates_plus_review"}, + "body3d": {"status": "disabled_by_configuration"}, + "temporal_3d_fitting": {"status": "disabled_by_configuration"}, + "anatomy": {"status": "disabled_by_configuration"}, + "bat3d": {"status": "disabled_by_configuration" if config.bat_3d_mode == "disabled" else "unavailable", + "reason": "independent_geometry_not_qualified"}, + "learned_events": {"status": "unavailable" if config.learned_events_enabled else "disabled_by_configuration", + "reason": "no_qualified_checkpoint"}} + if config.body3d_enabled: + p = root / "body3d_status.json" + stages["body3d"] = read_json(p) if p.exists() else {"status": "failed", "reason": "initializer_did_not_write_status"} + for name,filename,enabled in (("temporal_3d_fitting","temporal3d",config.body3d_enabled and config.temporal3d_enabled), + ("anatomy","anatomy",config.body3d_enabled and config.anatomy_enabled and config.temporal3d_enabled), + ("bat3d","bat3d",config.bat_3d_mode!="disabled"), + ("learned_events","learned_events",config.learned_events_enabled)): + if enabled: + p=root/(filename+"_status.json") + stages[name]=read_json(p) if p.exists() else {"status":"failed","reason":"worker_did_not_write_status"} + video_status = {"status": "disabled_by_configuration"} + if config.export_video: + video_status = export_video(request["video"], capture, observations, root / "annotated.mp4") + stages["video_export"] = video_status + assisted = observations["provenance"] == "human_assisted" or bool(annotations.get("events")) + result = json_safe({"schema_version": "1.0", "engine_version": "0.2.0", + "engine_code_hash": request["code_hash"], "status": "failed" if diagnostics["status"] == "failed" else "partial", + "provenance": "human_assisted" if assisted else "automatic", "capture": capture, + "stages": stages, "events": events, "metrics": metrics, + "model_hashes": request["model_hashes"], "configuration": { + k: v for k,v in config.to_dict().items() if not k.endswith("path") and k not in + {"sam_repo", "sam_checkpoint", "sam_config", "stage_python", "mstcn_repo"}}, + "diagnostics": diagnostics, "annotation_hash": None, + "validation": "reference-validation-pending"}) + if config.annotations_path: + from .storage import sha256_file + result["annotation_hash"] = sha256_file(config.annotations_path) + from .history import compatible_trials + trials=compatible_trials(root,result) + result["findings"]=json_safe(assess(metrics,capture["metadata"],events,trials,config.coaching_rules_path,config.coaching_mode)) + result["history_comparison"]={"compatible_trial_count":len(trials),"basis":"explicit_identity_matched_task_context_processing_versions"} + write_reports(root, result, curves) + atomic_json(root / "observation_index.json", {"cache_key": observation_cache.key, + "chunk_count": count, "topology": "rtmw133_native", "input_sha256": capture["input_sha256"]}) + +if __name__ == "__main__": + import time,platform,resource + started=time.perf_counter() + request=read_json(sys.argv[2]) + try: + run_stage(sys.argv[1], request) + except Exception as error: + print(f"{type(error).__name__}: {error}", file=sys.stderr) + sys.exit(1) + finally: + rss=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + profile={"stage":sys.argv[1],"elapsed_s":time.perf_counter()-started, + "peak_process_rss_mb":rss/(1024*1024 if sys.platform=="darwin" else 1024), + "python":platform.python_version(),"device_requested":request["config"]["device"], + "gpu_memory_scope":"torch_allocator_only; excludes ONNX/native allocations"} + torch=sys.modules.get("torch") + if torch is not None and torch.cuda.is_available(): + profile["torch_peak_allocated_mb"]=torch.cuda.max_memory_allocated()/1024**2 + profile["torch_peak_reserved_mb"]=torch.cuda.max_memory_reserved()/1024**2 + atomic_json(Path(request["root"])/"runtime_profiles"/(sys.argv[1]+".json"),profile) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12593c4f2b90fbd06bf142bc7238084dae0ece78 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,29 @@ +services: + api: + build: . + image: baseball-engine-api:local + platform: linux/amd64 + gpus: all + restart: unless-stopped + environment: + BASEBALL_API_KEY: ${BASEBALL_API_KEY:?Set BASEBALL_API_KEY in .env} + BASEBALL_MAX_UPLOAD_MB: ${BASEBALL_MAX_UPLOAD_MB:-512} + BASEBALL_MAX_ACTIVE_JOBS: ${BASEBALL_MAX_ACTIVE_JOBS:-8} + BASEBALL_MAX_FRAMES: ${BASEBALL_MAX_FRAMES:-7200} + BASEBALL_MAX_DURATION_S: ${BASEBALL_MAX_DURATION_S:-120} + BASEBALL_JOB_TIMEOUT_S: ${BASEBALL_JOB_TIMEOUT_S:-1800} + BASEBALL_RETENTION_HOURS: ${BASEBALL_RETENTION_HOURS:-24} + ports: + - "127.0.0.1:8000:8000" + volumes: + - baseball-data:/data + read_only: true + tmpfs: + - /tmp:size=2147483648,mode=1777 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + stop_grace_period: 30s +volumes: + baseball-data: diff --git a/configs/anatomical_model.yaml b/configs/anatomical_model.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af6c49286df362d224579a22a8329d8026c02271 --- /dev/null +++ b/configs/anatomical_model.yaml @@ -0,0 +1,27 @@ +schema_version: '1.0' +model_id: BattingKinematics-v1 +version: '1.0' +dof: 35 +purpose: kinematic_proxy_only +units: metres_radians +mass_inertia: placeholders_not_for_dynamics +root: FreeJoint +torso: BallJoint +hip: BallJoint +knee: PinJoint +ankle: UniversalJoint +shoulder: BallJoint +elbow: PinJoint +forearm_rotor: PinJoint +wrist: UniversalJoint +ball_coordinates: intrinsic_XYZ_not_anatomical_angles +universal_coordinates: intrinsic_XY +pin_axis: joint_local_Z +soft_coordinate_range_rad: [-3.05, 3.05] +universal_range_rad: [-1.35, 1.35] +marker_fit_max_rmse_m: 0.05 +temporal_weight: 0.0001 +refinement_max_evaluations: 50 +refinement_observation_tolerance_m: 0.0001 +source_kind: MHR70_model_regression_proxy +excluded: [scapula, fingers, muscles, forces, torques, injury_inference] diff --git a/configs/engine.example.json b/configs/engine.example.json new file mode 100644 index 0000000000000000000000000000000000000000..92ed1e39a53666607fff988a97d91d523a2f0041 --- /dev/null +++ b/configs/engine.example.json @@ -0,0 +1,15 @@ +{ + "mode": "automatic", + "chunk_size": 64, + "device": "cpu", + "body_pose_path": null, + "person_detector_path": null, + "object_detector_path": null, + "body3d_enabled": false, + "export_video": true, + "temporal3d_enabled": true, + "anatomy_enabled": true, + "learned_events_enabled": false, + "bat_3d_mode": "disabled", + "coaching_mode": "evidence_linked_experimental" +} diff --git a/configs/environment-candidate.yaml b/configs/environment-candidate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae4595984085dc6485f96ede7e80e4d915337d0b --- /dev/null +++ b/configs/environment-candidate.yaml @@ -0,0 +1,30 @@ +status: candidate_not_colab_qualified +selected_plan_gpu_profile: + python: '3.11' + torch: 2.9.1 + torchvision: 0.24.1 + cuda_wheels: cu128 + onnxruntime_gpu: 1.26.0 + opensim: '4.6' + rtmlib: 0.0.16 +local_cpu_test_profile: + python: '3.10' + onnxruntime: 1.23.2 + rtmlib: 0.0.16 + numpy: 2.2.6 + scipy: 1.15.3 + opencv_python_headless: 4.11.0.86 + av: 16.1.0 + PyYAML: 6.0.2 +notes: + - The local CPU profile is a separate recorded configuration, not GPU validation. + - The full selected GPU/SAM/OpenSim profile needs a Python 3.11 Colab worker and branch smoke tests. + - Never install both CPU and GPU ONNX Runtime packages into the same worker environment. + - Dependency imports and inference shapes do not validate baseball measurements. + +local_anatomy_test_profile: + python: '3.13' + opensim: '4.6' + numpy: 2.2.6 + scipy: 1.15.3 + scope: synthetic_FK_IK_refinement_only diff --git a/configs/events.yaml b/configs/events.yaml new file mode 100644 index 0000000000000000000000000000000000000000..57aae5544a79078eeb2a6868025131695a53a6bb --- /dev/null +++ b/configs/events.yaml @@ -0,0 +1,15 @@ +version: '2.0' +default_mode: candidate_plus_optional_confirmation +motion_threshold_px_per_frame: 3.0 +sustained_frames: 3 +min_visible_frames: 4 +automatic_contact_policy: abstain_without_qualified_image_evidence +learned_event_mode: disabled +notes: + - Hand motion onset is not automatically forward-swing onset. + - Projected overlap is not contact. + - Clip end is not a biomechanical endpoint. + +ground_tolerance_px: 5.0 +interaction_distance_px: 8.0 +outgoing_direction_cosine_max: 0.5 diff --git a/configs/fitting.yaml b/configs/fitting.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0cd83f56b3aa94687834dec3772cc5c564d3ade0 --- /dev/null +++ b/configs/fitting.yaml @@ -0,0 +1,18 @@ +version: '1.0' +adam_steps: 80 +lbfgs_steps: 20 +learning_rate: 0.01 +batch_size: 4 +reprojection_weight: 1.0 +initializer_weight: 0.25 +shape_prior_weight: 0.01 +height_prior_weight: 0.01 +motion_prior_weight: 0.005 +temporal_weight: 0.0001 +limit_weight: 0.01 +robust_pixel_scale: 5.0 +max_reprojection_rmse_px: 20.0 +minimum_observed_landmarks: 6 +max_initializer_gap_frames: 0 +sensitivity_temporal_factors: [0.5, 2.0] +reference_validation: pending diff --git a/configs/landmark_map.yaml b/configs/landmark_map.yaml new file mode 100644 index 0000000000000000000000000000000000000000..932994051e952d420882efbcb32226edf93818cb --- /dev/null +++ b/configs/landmark_map.yaml @@ -0,0 +1,32 @@ +version: '1.0' +source_topology: sam_mhr70 +source_kind: model_predicted_surface_or_rig_regression_proxy +source_units: metres +source_basis: camera_x_right_y_down_z_forward +independent_observations: false +indices: + nose: 0 + left_shoulder: 5 + right_shoulder: 6 + left_elbow: 7 + right_elbow: 8 + left_hip: 9 + right_hip: 10 + left_knee: 11 + right_knee: 12 + left_ankle: 13 + right_ankle: 14 + left_big_toe: 15 + left_small_toe: 16 + left_heel: 17 + right_big_toe: 18 + right_small_toe: 19 + right_heel: 20 + right_wrist: 41 + left_wrist: 62 + neck: 69 +source_url: https://github.com/facebookresearch/sam-3d-body/blob/main/sam_3d_body/metadata/mhr70.py +notes: + - These names identify model regressions, not independently measured anatomical joint centers. + - Exact keypoint-regressor and asset hashes are stored in each generated anatomical model. + - Native rig topology and surface-regression topology are kept separate. diff --git a/configs/metadata.example.json b/configs/metadata.example.json new file mode 100644 index 0000000000000000000000000000000000000000..d1005d4026169b6880a493f2e7646452bb0d2442 --- /dev/null +++ b/configs/metadata.example.json @@ -0,0 +1,14 @@ +{ + "player_id": "player-001", + "session_id": "session-001", + "handedness": "right", + "height_m": null, + "bat_length_m": null, + "age": null, + "experience_level": null, + "consent": "record participant permission here", + "camera_stability": "unknown", + "timing": {"kind": "unknown"}, + "intended_use": "research" +} + diff --git a/configs/metrics.yaml b/configs/metrics.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a017dafa2e755eda4e9565b056b5869466ff76e1 --- /dev/null +++ b/configs/metrics.yaml @@ -0,0 +1,48 @@ +definition_version: '1.1' +default_validation: reference-validation-pending +definitions: + projected_flexion: + formula: 180 degrees minus included joint angle + straight_value: 0 + coordinate_space: oriented image pixels + unit: deg_projected + boundary: distinct from anatomical 3D flexion + projected_ankle_span: + formula: Euclidean ankle distance within each frame + summary: median over available frames; not automatically a stance-phase summary + unit: px + projected_hand_path: + formula: sum of distances between consecutive observed wrist positions + unit: px + requirements: [fixed_verified_camera, complete_contiguous_observations] + projected_hand_speed: + formula: norm of nonuniform-time numerical derivative + unit: px/s + requirements: [physical_clock, fixed_verified_camera, no_timing_integrity_flags] + projected_bat_shaft_angle: + formula: atan2 negative image dy, image dx for knob-to-barrel vector + unit: deg_projected + summary: circular mean + requirements: [identified_endpoints, direct_or_manual_observations] + boundary: neither attack angle nor a 3D shaft tilt + physical_bat_speed: + requirements: [independent_calibrated_bat_3d, physical_clock, calibrated_world_frame, confirmed_contact, contiguous_endpoint_support] + measurement_point_m_inward_from_barrel: 0.1524 + + anatomical_flexion: + formula: 180 degrees minus included proxy marker angle + straight_value: 0 + unit: deg + source: fitted MHR70 proxies in our 35DOF model + pelvis_thorax_horizontal_heading: + formula: wrapped thorax-minus-pelvis heading of each segment local Z projected into world XZ + requirements: [accepted_anatomical_fit, documented_world_axes] + pelvis_thorax_axial_twist: + formula: quaternion swing-twist decomposition about pelvis-local cranial Y + boundary: separate from horizontal heading separation and primitive XYZ coordinates + angular_velocity: + formula: SO3 log of consecutive world rotations divided by actual timestamp interval + boundary: not Euler-coordinate derivatives + bat_attack_angle: + formula: atan2 vertical sweet-point velocity, norm of horizontal sweet-point velocity + boundary: velocity direction; not shaft tilt diff --git a/configs/models.yaml b/configs/models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..36ae92c48a992dc4394bf2d5786d8135ba52965f --- /dev/null +++ b/configs/models.yaml @@ -0,0 +1,7 @@ +version: '1.0' +body_pose: {topology: rtmw133_native, input_width: 288, input_height: 384} +sam: {revision: b5c765a0d89d789985e186d396315e7590887b94, precision: fp32, inference_type: full, duplicate_optional_networks: disabled} +mhr: {shape_parameters: 45, native_motion_parameters: 136, native_scale_parameters: 68, landmarks: 70, position_units: cm} +anatomy: {model: BattingKinematics-v1, dof: 35, dynamics: disabled} +endpoint_cnn: {input: [3, 256, 256], heatmaps: [2, 64, 64], pretrained_baseball_weights: absent, activation: held_out_qualification_required} +mstcn: {revision: aef4e46c31bc7b2462065354054f968f91e54be1, phase_classes: 5, boundary_classes: 6, feature_version: body_object_visual_v1, activation: held_out_qualification_required} diff --git a/configs/quality.yaml b/configs/quality.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f87f4fec724c439e3cf8590bc113a8037e67108 --- /dev/null +++ b/configs/quality.yaml @@ -0,0 +1,8 @@ +version: '1.0' +metric_validation: reference-validation-pending +max_event_interval_frames: 2 +max_regularization_sensitivity_m: 0.05 +minimum_velocity_frames: 3 +camera_must_be_fixed_for_image_motion: true +prior_dominated_policy: experimental_only +missing_uncertainty: unknown_no_numeric_bounds diff --git a/configs/reference-gates.example.json b/configs/reference-gates.example.json new file mode 100644 index 0000000000000000000000000000000000000000..450a1bdeae668ffe08a7f7004e03cf51664d49a6 --- /dev/null +++ b/configs/reference-gates.example.json @@ -0,0 +1,7 @@ +{ + "preregistered": false, + "source": "Replace with a preregistration document", + "scope": {"population": "define", "task": "define", "camera_views": "define"}, + "metrics": {}, + "notes": "Add each metric and its justified bias, absolute-error, repeatability, coverage and sample requirements before evaluation. No universal biological angle thresholds." +} diff --git a/configs/resources.yaml b/configs/resources.yaml new file mode 100644 index 0000000000000000000000000000000000000000..084f314dbffd5eb14a0445684e8b21ffe2e79306 --- /dev/null +++ b/configs/resources.yaml @@ -0,0 +1,84 @@ +schema_version: '1.0' +commercial_license_review: deferred +resources: + pyav: + type: code + source_url: https://pypi.org/project/av/16.1.0/ + version: 16.1.0 + intended_role: source-timed decoding and video encoding + opencv: + type: code + source_url: https://pypi.org/project/opencv-python-headless/4.11.0.86/ + version: 4.11.0.86 + intended_role: image operations and optical flow + ffmpeg: + type: code + source_url: https://ffmpeg.org/ + version: system-recorded-at-preflight + intended_role: ffprobe metadata cross-check + rtmlib: + type: code + source_url: https://pypi.org/project/rtmlib/0.0.16/ + version: 0.0.16 + revision: 03a1693e59e4f7cd84582c0fb30459b3bf18ad42 + intended_role: explicit RTMW pose adapter + body_pose: + type: checkpoint + sha256: b2dd00cce207d3c1503e35cc77a82ecd7092dcbdfe4a3c692ec4cdc3cf40c804 + source_url: https://download.openmmlab.com/mmpose/v1/projects/rtmw/onnx_sdk/rtmw-x_simcc-cocktail13_pt-ucoco_270e-384x288-0949e3a9_20230925.zip + version: rtmw-x-0949e3a9-20230925 + intended_role: native 133-landmark body observations + dependency_ids: [rtmlib] + person_detector: + type: checkpoint + sha256: 3dea6513388889f0fff4b77bf7a26013600321b9eb9ceb0e9a400a82572f5f23 + source_url: https://download.openmmlab.com/mmpose/v1/projects/rtmposev1/onnx_sdk/yolox_m_8xb8-300e_humanart-c2c7a14a.zip + version: yolox-m-humanart-c2c7a14a + intended_role: person proposals; not bat or ball detection + object_detector: + type: checkpoint + source_url: https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx + version: 0.1.1rc0 + intended_role: separate COCO person/bat/sports-ball proposals + sam: + type: code + source_url: https://github.com/facebookresearch/sam-3d-body + revision: b5c765a0d89d789985e186d396315e7590887b94 + intended_role: conditional single-frame body reconstruction + sam_checkpoint: + type: checkpoint + source_url: https://huggingface.co/facebook/sam-3d-body-vith + revision: provider-access-required + intended_role: ViT-H body initializer + dependency_ids: [sam, mhr] + mhr: + type: body_asset + source_url: https://huggingface.co/facebook/sam-3d-body-vith/tree/main/assets + revision: bundled-with-pinned-sam-checkpoint + intended_role: differentiable human rig; no dynamics claims + opensim: + type: code + source_url: https://pypi.org/project/opensim/4.6/ + version: '4.6' + intended_role: explicit 35-DOF kinematic proxy construction and weighted IK + ms_tcn: + type: code + source_url: https://github.com/sj-li/MS-TCN2 + revision: aef4e46c31bc7b2462065354054f968f91e54be1 + intended_role: trainable phase and boundary backend; inactive until qualified + openbiomechanics: + type: dataset + source_url: https://github.com/drivelineresearch/openbiomechanics + intended_role: reference candidate; not paired-video validation + terms_url: https://github.com/drivelineresearch/openbiomechanics/blob/main/LICENSE-DATA.md + batting_kinematics: + type: anatomical_model + source_url: project_owned_models/BattingKinematics-v1.osim + version: '1.0' + intended_role: explicit 35DOF kinematic proxy; placeholders not for dynamics + dependency_ids: [opensim, mhr] + usa_tee_instruction: + type: documentation + source_url: https://www.usabaseball.com/video/cuddyer-s-corner-using-the-tee + version: 2022-04-27 + intended_role: educational tee practice context; no intervention effectiveness claim diff --git a/configs/training-gates.example.json b/configs/training-gates.example.json new file mode 100644 index 0000000000000000000000000000000000000000..7790edf95ab5b55aebfc07746400dc066230afd2 --- /dev/null +++ b/configs/training-gates.example.json @@ -0,0 +1,7 @@ +{ + "preregistered": false, + "source": "Replace with the preregistration record before evaluation", + "maximum": {"median_error": 4.0, "p95_error": 8.0, "miss_rate": 0.1, "extra_rate": 0.1}, + "minimum": {"held_out_athlete_count": 3, "positive_labels": 30, "absent_labels": 10}, + "notes": "Example software configuration only. These are not established accuracy requirements. Endpoint error is in 256-crop pixels; event error is in source frames. Set task-specific gates first." +} diff --git a/deploy/Caddyfile b/deploy/Caddyfile new file mode 100644 index 0000000000000000000000000000000000000000..2748b73eda7a66b551fd03c53d291bbd3a510184 --- /dev/null +++ b/deploy/Caddyfile @@ -0,0 +1,6 @@ +{$BASEBALL_DOMAIN} { + request_body { + max_size 537919488 + } + reverse_proxy api:8000 +} diff --git a/deploy/compose.https.yaml b/deploy/compose.https.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a4c3a7b7723036a3cfa3e37c8ccc851b46656c24 --- /dev/null +++ b/deploy/compose.https.yaml @@ -0,0 +1,18 @@ +services: + proxy: + image: caddy:2-alpine + restart: unless-stopped + environment: + BASEBALL_DOMAIN: ${BASEBALL_DOMAIN:?Set BASEBALL_DOMAIN to your API hostname} + ports: + - "80:80" + - "443:443" + volumes: + - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro + - caddy-data:/data + - caddy-config:/config + depends_on: + - api +volumes: + caddy-data: + caddy-config: diff --git a/deploy/huggingface/README.md b/deploy/huggingface/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dec8db577fdd811ed292367fac7830436fff486e --- /dev/null +++ b/deploy/huggingface/README.md @@ -0,0 +1,16 @@ +--- +title: Baseball Engine 2D API +emoji: ⚾ +colorFrom: blue +colorTo: gray +sdk: docker +app_port: 8000 +pinned: false +short_description: GPU 2D batting analysis API +--- + +# Baseball engine 2D API + +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 `. `/readyz` returns 200 once CUDA inference has passed at startup. + +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`. diff --git a/docs/API_FOR_COACH.md b/docs/API_FOR_COACH.md new file mode 100644 index 0000000000000000000000000000000000000000..35fc8ffb17337d85c5a7f7cd239d37a9d260f0ea --- /dev/null +++ b/docs/API_FOR_COACH.md @@ -0,0 +1,111 @@ +# Connect the batting engine to the coach API + +The engine extracts 2D points on GPU, estimates separate swings/events, and calculates supported swing numbers. Your coach agent chooses problems, priority, drill, explanation and progress. All 3D and coaching stages are disabled in this engine API. + +## Calls + +Every engine `/v1/` request needs `Authorization: Bearer YOUR_ENGINE_API_KEY`. Your friend's coach API separately uses `X-API-Key`; these are different credentials. Keep both on the backend. + +| Method and path | Purpose | +|---|---| +| `POST /v1/analyses` | Upload a recording and JSON options; receive a job ID | +| `GET /v1/analyses/{job_id}` | Read status and progress | +| `GET /v1/analyses/{job_id}/result` | Download full points, events, measurements and diagnostics | +| `GET /v1/analyses/{job_id}/coach-payload` | Download only the body for your friend's `POST /v1/coach` | +| `DELETE /v1/analyses/{job_id}` | Cancel and remove the recording's artifacts | +| `GET /v1/capabilities` | Supported features and limits | +| `GET /v1/input-schema` | Exact upload-options schema | +| `GET /v1/output-schema` | Full-result schema | +| `GET /v1/coach-payload-schema` | Engine's measurement-only schema | +| `GET /readyz` | 200 after actual CUDA inference passes | + +Upload example for an original, unretimed right-handed batting recording: + +```bash +curl -X POST https://your-engine-hostname/v1/analyses \ + -H "Authorization: Bearer YOUR_ENGINE_API_KEY" \ + -F "video=@swing.mp4" \ + -F 'options={"view":"face_on","handedness":"right","level":"hs_varsity","camera_stability":"fixed_verified","timing":{"kind":"unretimed","source":"original camera recording; no retiming"}}' +``` + +Declare view, camera stability and timing only when known. `fixed_verified` means the camera stays still. Defaults leave these unknown and withhold dependent measurements. Supply `single_swing:true` when the entire clip is known to contain exactly one swing; otherwise automatic candidate splitting runs. You can alternatively supply rep ranges. + +HTTP 202 returns `job_id`, `status_url`, `result_url` and `coach_payload_url`. Poll `status_url` every 2–5 seconds. Once `status` is `completed`, download `coach_payload_url` into `session.json`, then send that file to your friend's API: + +```bash +curl -X POST https://your-coach-hostname/v1/coach \ + -H "X-API-Key: $COACH_API_KEY" \ + -H "Content-Type: application/json" \ + -d @session.json +``` + +No coach request is made by this engine. Your backend performs that call and displays the returned note. A premature download returns 409. An older job made by the pose-only image also returns 409 for the coach payload; resubmit it with the updated image. Failed jobs include a public error code in their status response. + +## Coach payload + +The payload contains `schema_version: "2.0"`, `discipline: "hitting"`, capture checks and one entry per swing candidate with `rep`, `events_ms`, nine `metrics`, and `quality`. Known level, view and physical FPS are included. Unknown FPS is omitted rather than replaced by playback FPS. Events are milliseconds from that rep's start, and are omitted when capture time or event evidence is unavailable. + +Each metric contains `key`, a number or `null`, `unit`, `confidence: "est"`, and a note. All current numbers are estimates, including those with a supplied image scale. No `high` or `medium` labels are fabricated from pose scores. Your coach's documented policy may therefore return `nothing_to_judge` or an estimate-only/rule-based note. This integration does not claim qualified coaching accuracy. + +Supported values, subject to event/view/quality evidence: + +- `stride_pct_height`: horizontal ankle-to-ankle span at estimated foot plant. +- `com_drift_pct_height`: hip midpoint relative to the front ankle at estimated contact; negative is behind. +- `foot_plant_to_contact_ms`, `load_tempo_s`, `load_launch_ratio`: timing quantities only with a known constant capture rate >= 60 FPS. +- `head_movement_pct_height`: reference-only nose path from stance to estimated contact. +- `lead_knee_angle_contact_deg`: reference-only projected interior knee angle. + +`lateral_trunk_tilt_contact_deg` and `hip_shoulder_separation_foot_plant_deg` are null: face-on 2D cannot establish those anatomical 3D quantities. Foot plant is a settled-foot proxy and does not prove full body-weight loading. Contact is always an estimated lead-arm-extension proxy, with no bat-ball collision confirmation. See [exact definitions](BATTING_2D_MEASUREMENTS.md). + +The coach payload excludes video, frames, keypoints, names/IDs, faults, priority, drills, ranges and advice. It uses only the capture-reason keys supplied in your document. A capture failure sets `ok:false`, supplies reasons and withholds the affected rep's numbers. A successfully running model that detects no athlete returns this record-again payload instead of crashing the job. + +An example computed from constructed trajectories is in [coach-payload.example.json](../examples/coach-payload.example.json); it is demonstration data. The engine's own JSON Schema is checked by automated tests. Your actual `ai_coach.validate`, detailed schemas and coach service source were not supplied, so exact external-validator acceptance remains to be checked with the coach developer. + +## Upload options + +| Option | Meaning | +|---|---| +| `discipline` | `hitting` only | +| `view` | Known `face_on`, otherwise `unknown` | +| `handedness` | `left` or `right`; identifies lead arm/foot | +| `level` | Optional `hs_jv`, `hs_varsity` or `college`; forwarded without assumption | +| `camera_stability` | `unknown`, `fixed_verified`, or `moving` | +| `pitcher_direction` | Optional `image_left` / `image_right`; otherwise inferred from lead/back ankle ordering when possible | +| `body_height_px` + `body_height_source` | Optional known standing image height and its source, in upright pixels; real height in meters alone is not camera calibration | +| `rotation_degrees` | Optional clockwise 0/90/180/270 override | +| `timing` | Capture-clock declaration, below; defaults to unknown | +| `single_swing` | Declare the entire clip as one swing | +| `reps` | Ordered, non-overlapping `{start_frame,end_frame}` ranges; inclusive end | + +Without a supplied image height, scale is an explicitly unvalidated projected skeleton-length estimate. It is reported in the full result's `measurement_method`; percentage metrics explain it in their notes. Do not send `single_swing:true` together with `reps`. Automatic boundaries are candidates and can miss or misclassify movements; a caller range that contains several motion bursts produces missing events rather than silently choosing one. + +Capture-clock declarations: + +```json +{"kind":"unretimed","source":"description of the original capture evidence"} +``` + +```json +{"kind":"constant_slowdown","source":"documented export settings","factor":8,"all_captured_frames_retained":true} +``` + +```json +{"kind":"explicit","source":"camera timestamp file","physical_times_s":[0.0,0.00417,0.00833]} +``` + +Explicit times must match the decoded frame count and increase strictly. Unknown timing produces null capture timestamps in the pose track, no `events_ms`, and null timing metrics. Variable cadence is retained per frame, but no constant FPS or timing metrics are asserted. Capture-quality, event and boundary checks are heuristics, not validated classifiers. + +## Full result and Python client + +The full result includes `pose_track` (17 COCO body points + six foot points, upright pixels, boxes, detected person counts, brightness and heuristic blur), `measurements`, `coach_payload`, `measurement_method`, capabilities, warnings and `validation: "reference_validation_pending"`. `status: "partial"` describes unresolved accuracy/unsupported quantities; it does not mean the HTTP job failed. + +Raw pose points are exported without smoothing or gap filling, filtered at model score 0.35 and image bounds. Missing points are null with confidence exactly zero. Measurement calculations use a separate copy with interior gaps up to three frames filled and a three-frame median on finite runs. Scores are model scores, not calibrated probabilities or verified visibility. No `kp3d` or bat/ball objects are emitted. + +Download only the coach payload with the example client: + +```bash +python examples/api_client.py swing.mp4 --url https://your-engine-hostname \ + --options capture-options.json --coach-payload --output session.json +``` + +Set `BASEBALL_API_KEY` for the engine first. Store results in your backend before their default 24-hour expiry. diff --git a/docs/BATTING_2D_MEASUREMENTS.md b/docs/BATTING_2D_MEASUREMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..ce2e501a466774fe5f8b98874247556ec168346f --- /dev/null +++ b/docs/BATTING_2D_MEASUREMENTS.md @@ -0,0 +1,62 @@ +# 2D batting measurement definitions + +Version: `batting-2d-v1`. Scope: fixed-camera face-on batting. This module uses existing GPU pose/person outputs and CPU arithmetic, with no SAM, temporal 3D fitting, OpenSim or coaching decisions. + +## Reliability + +All event detections and non-null metric values are estimates pending independent validation. Synthetic numerical checks validate arithmetic and abstention rules; they do not demonstrate accuracy on baseball videos. The event confidence number is capped at 0.5 and bounded by the supporting pose scores; it is a heuristic score, not a calibrated probability. No `high`/`medium` metric label is emitted. + +Raw points remain unchanged in `pose_track`. For calculations, only interior missing runs of at most three frames are interpolated. A three-frame median is applied to contiguous finite runs. Longer gaps remain missing, and a detected event needs raw supporting joints at that frame. Nose path is computed on this analytical copy, so smoothing affects its value. + +## Scale and direction + +A caller can provide a known standing image height in upright pixels with a source description. Physical player height alone does not provide that pixel scale. + +The fallback is the 90th percentile of `1.08 × (nose-to-midshoulder length + midshoulder-to-midhip length + mean hip-knee-ankle chain length)`. The 1.08 correction for missing head/foot extent is a declared heuristic, not a validated anthropometric calibration. This projected skeleton estimate can be biased by foreshortening and posture; percentage metrics remain `est` and carry a scale note. + +For right-handed hitters the left arm/foot leads; for left-handed hitters the right arm/foot leads. Pitcher direction may be supplied as image left/right. Otherwise it is the sign of median lead-minus-back ankle x, only when separation exceeds 4% of estimated height. Ambiguous direction/handedness withholds dependent events/numbers. + +## Swings and events + +Automatic splitting finds sustained forward hand excursions relative to the hip midpoint. The adaptive motion threshold uses median motion plus twice its median absolute deviation, with a 30%-of-90th-percentile floor. A burst requires at least a 12%-of-height excursion. Short pauses can be merged; gaps in hand evidence cannot. Without direction this is only generic motion candidate splitting. + +Inter-drive midpoints prevent overlap. Observed quiet intervals trim setup and trailing footage when available. At most 100 candidates are analyzed, with a warning if more were found. These are candidate boundaries, not qualified repetition labels. Caller-declared single-swing/range options remain available. A declared range with several clear bursts is ambiguous and produces no forced events. + +| Event | Evidence and limitation | +|---|---| +| `stance_set` | Quiet hands before loading/drive; estimated stance | +| `load_start` | Sustained backward hand excursion before forward motion | +| `stride` | Lead ankle departs preparation position by >2.5% of height | +| `foot_contact` | After a clear lift, toe/heel returns near preparation ground level; estimated touchdown | +| `foot_plant` | Displaced lead ankle settles near preparation ground level; does **not** measure full body-weight loading | +| `swing_start` | Sustained forward hand displacement; exact acceleration onset remains unvalidated | +| `contact` | Visible lead-arm extension peak with hands forward; always estimated, no ball/sensor confirmation | +| `finish` | Observed post-drive hand settling; clip end is never forced as finish | + +Events must be inside their rep and follow the requested order. Conflicting candidates are omitted with a reason. Foot-plant candidates after forward onset are withheld under this contract's ordering convention. Capture timestamps are included only from the declared physical clock. `events_ms` uses milliseconds from the rep's start; playback time never becomes physical event time. + +## Numbers + +| Key | Formula | Additional gate | +|---|---|---| +| `stride_pct_height` | `100 × abs(lead_ankle_x - back_ankle_x) / image_height_scale` at estimated foot plant | Lead side, plant and scale | +| `com_drift_pct_height` | `100 × pitcher_direction × (hip_midpoint_x - lead_ankle_x) / scale` at estimated contact | Negative is behind; hip proxy, not whole-body center of mass | +| `foot_plant_to_contact_ms` | Physical contact time minus physical plant time, ×1000 | Both events; constant capture FPS >=60 | +| `load_tempo_s` | Physical forward-onset time minus physical hand-load-start time | Both events; constant capture FPS >=60 | +| `load_launch_ratio` | Load duration / physical onset-to-contact duration | All events; positive denominator; constant capture FPS >=60 | +| `head_movement_pct_height` | Sum of consecutive analytical nose displacements from stance to estimated contact, /scale ×100 | Complete analytical path; reference-only | +| `lead_knee_angle_contact_deg` | Interior projected hip-knee-ankle angle at estimated contact | Reference-only; not anatomical 3D flexion | +| `lateral_trunk_tilt_contact_deg` | Null | Requested anatomical tilt not established by face-on 2D | +| `hip_shoulder_separation_foot_plant_deg` | Null | Image-plane segment angles do not measure axial twist | + +The load-duration/ratio definitions above are explicit implementation conventions; their exact agreement with the friend's missing detailed `POSE_DATA_SPEC.md` must be confirmed. Invalid, missing, out-of-bounds or unsupported values are null with notes. No normal ranges, faults, priority or drills are computed. + +## Capture checks + +Quality is checked over the selected rep ranges, or the complete clip when no candidates exist. Only the friend's recognized capture reason keys are returned. The heuristics flag no selected person, >10% multi-person frames, a large adjacent-frame box jump, a small athlete, boxes touching the image edge, insufficient full core joints, darkness, blur, low physical FPS and uncertain view. Mild reasons may accompany `ok:true`; fatal reasons set `ok:false` and withhold that rep's numbers. + +Blur is the existing uncalibrated `1/(1+Laplacian variance/100)` heuristic. Person counts/boxes do not establish athlete identity or visibility. Camera stability and view are caller declarations; the API does not silently claim a validated automatic angle/stability classifier. Unknown counts or recording timing are explained in full-result warnings. Moving/unverified cameras suppress image-motion calculations. + +## Validation remaining + +The exact external `ai_coach.validate` and schemas were not supplied. Engine tests check its own matching payload schema, units, supplied plausible bounds, known capture reasons, timing gates, null notes, numerical trajectories, abstention and HTTP delivery. Deployment still needs target-GPU execution and original-video checks. Real baseball point/event/metric errors and confidence calibration remain unmeasured; the separate coach should treat current values as estimates. diff --git a/docs/GEOMETRY.md b/docs/GEOMETRY.md new file mode 100644 index 0000000000000000000000000000000000000000..08ff9be55656203a259fde8fcd3544ded4ee1a8b --- /dev/null +++ b/docs/GEOMETRY.md @@ -0,0 +1,34 @@ +# Geometry and fitted motion + +The body chain is SAM full body/hand initialization → exact bundled MHR differentiation → one shared shape/scale trajectory fit → the project's 35-DOF OpenSim kinematic proxy. Native MHR centimetres are converted to metres and y/z flipped once. SAM camera translation is added once. Exported native rotations are not presumed anatomical rotations. + +The fitter batches the forward calculation while optimizing the complete observed short clip with one body shape. Missing source frames stay missing; temporal triplets cannot bridge gaps. Adam precedes L-BFGS. Reprojection residuals, initializer agreement, priors, limit penalties and temporal penalties remain separate. A loaded regressor must reproduce SAM's native parameters within the configured arithmetic check before optimization. Regularization sensitivity is reported, not a calibrated accuracy interval. + +`mhr_limits_path` optionally supplies lower/upper arrays for 133 motion parameters excluding native root translation, the exact `asset_sha256` and a documented `source`. Without asset-specific limits the initializer prior remains explicit; no rig coordinates are mislabeled anatomical angles. A height prior requires `height_m`, `uncertainty.height_source` and positive `uncertainty.height_prior_scale_m`. It is a scale prior, not camera calibration. + +`models/BattingKinematics-v1.osim` is the generated project reference template. At runtime, proxy origins/marker offsets are generated from the shared neutral MHR body. `configs/anatomical_model.yaml` names every primitive, convention and numerical fit gate; `configs/landmark_map.yaml` names the MHR70 correspondence. Masses/inertias are placeholders. No forces, tissue loads, scapular motion, fingers or injury inference are supported. A forearm longitudinal rotor is an approximation. + +OpenSim performs confidence-weighted frame IK. SciPy refines each contiguous accepted sequence with sparse time-aware penalties and soft coordinate limits. Refinement is retained only when observation agreement is preserved. The independent FK implementation is checked against OpenSim primitives. Flexion uses named proxy marker geometry; horizontal heading separation and pelvis-local axial twist are distinct definitions. Angular velocity uses rotation logarithms, not Euler derivatives. + +Camera intrinsics are in oriented source pixels: + +```json +{"calibration":{"source":"documented calibration record", + "intrinsics_oriented_pixels":[[1000,0,640],[0,1000,360],[0,0,1]], + "world_axes":"x_pitcher_y_up_z_right_handed", + "world_from_camera":{"rotation":[[1,0,0],[0,-1,0],[0,0,-1]],"translation_m":[0,0,0]}}} +``` + +This numeric transform is a schema example. Supply your measured transform and verify its x axis points toward the pitcher. The engine never invents a field frame. Intrinsics alone retain model-based scale; body outputs remain experimental. + +Ground-plane distances additionally require `ground_plane_verified=true`, a `ground_homography_pixels_to_xz_metres` 3×3 matrix, and reviewed `event_context.ground_contact_frames` with a source description. Applying a homography to an airborne foot does not establish ground distance. Event context can declare `lead_side`, a documented `pitcher_direction_image` vector and `ground_line_image` coefficients for projected candidates. + +## Independent bat reconstruction + +`bat_3d_mode` defaults to `disabled`. The engine does not use monocular wrist depth as independent grip geometry. Both enabled modes require measured `bat_length_m` and explicit independent per-frame records under `bat_geometry.frames`. + +For `calibrated_independent_grip`, each record contains `source`, `independent=true`, `knob_camera_m`, and `endpoints_pixels` in knob/barrel order. Use known camera intrinsics. If the barrel ray intersects the known-length sphere at two positive depths, it stays ambiguous unless an independent `barrel_anchor_camera_m` resolves a unique branch. A temporal prior is not independent disambiguation. + +For `calibrated_multiview`, each record contains `source`, `independent=true`, `synchronization_verified=true`, `world_axes="x_pitcher_y_up_z_right_handed"`, `projection_matrices` (views×3×4) and `endpoints_pixels` (views×2×2). Projection matrices map the stated metre world frame into each view's pixels. Triangulation checks ray angle, cheirality and reprojection; rigid fitting checks measured length. + +The measurement point lies 0.1524 m inward from the barrel along the shaft; the name "sweet spot" denotes this chosen point, not an experimentally verified optimum for every bat. Physical contact speed and attack direction additionally require valid world geometry, physical timestamps, contiguous direct support and a narrow confirmed contact interval. Attack angle is velocity direction relative to horizontal, not shaft tilt. Exit velocity remains unsupported. diff --git a/docs/GPU_API_DEPLOYMENT.md b/docs/GPU_API_DEPLOYMENT.md new file mode 100644 index 0000000000000000000000000000000000000000..800cf392ca85045b1a8f3de728ac1973d5ebb70e --- /dev/null +++ b/docs/GPU_API_DEPLOYMENT.md @@ -0,0 +1,96 @@ +# Deploy the 2D GPU API + +This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. SAM 3D Body, temporal 3D fitting, OpenSim, bat 3D, and coaching are disabled. The Colab notebook remains available separately. + +Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain `est` pending independent validation. Weak events and unsupported angles are withheld. See [API_FOR_COACH.md](API_FOR_COACH.md) for the handoff and [BATTING_2D_MEASUREMENTS.md](BATTING_2D_MEASUREMENTS.md) for definitions and limitations. + +## GPU server with Docker + +Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the two model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee. + +Install Docker with Compose and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see [ONNX CUDA requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html). The image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras, with no PyTorch or SAM installation. + +Clone your repository, enter its directory, then create your private configuration: + +```bash +cp .env.example .env +``` + +Generate a random API key: + +```bash +python3 -c 'import secrets; print(secrets.token_urlsafe(32))' +``` + +Put that value after `BASEBALL_API_KEY=` in `.env`. Keep the key in your friend's backend configuration. The real `.env` is ignored by Git and excluded from the Docker build context. + +Build and start: + +```bash +docker compose up -d --build +curl --fail http://127.0.0.1:8000/readyz +``` + +The image build downloads only the RTMW-x and HumanArt person models and verifies their SHA-256 values. A build fails if a required download or checksum fails. Startup runs actual pose and person inference on CUDA; `/readyz` returns 503 until it passes. A missing GPU or broken CUDA setup prevents video jobs from being accepted. This confirms GPU execution, not measurement accuracy. + +RTMLib is installed with `--no-deps` for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently `pip check` reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution. + +The default Compose setup binds port 8000 to localhost. For internet access, use your existing HTTPS proxy or the supplied Caddy configuration: + +1. Point a hostname at your server and allow inbound ports 80 and 443. +2. Set `BASEBALL_DOMAIN=your-api-hostname` in `.env`. +3. Start the HTTPS overlay: + +```bash +docker compose -f compose.yaml -f deploy/compose.https.yaml up -d --build +``` + +Your API and interactive documentation are then at `https://your-api-hostname` and `https://your-api-hostname/docs`. Caddy handles certificates; its [reverse proxy](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy) forwards to the API. Its fixed 537,919,488-byte (513 MiB) request limit covers the default upload size plus multipart overhead; adjust it if you raise the API's upload limit. + +## Other GPU hosting services + +Build and publish the same Linux x86-64 image in your private container registry, then deploy it on a GPU container host. Give the container NVIDIA GPU access, expose HTTP port 8000 behind the platform's HTTPS endpoint, and set `BASEBALL_API_KEY` as a platform secret. + +Mount a persistent writable volume at `/data`. The image runs as UID/GID 1000, matching the user Hugging Face Docker Spaces run containers as, so a bind-mounted directory must be writable by that user. `/tmp` must be writable for multipart uploads and ONNX profiling. Leave the image command in place: it starts one Uvicorn process and one GPU queue. A managed GPU pod can run this long-lived service; this image is not a platform-specific serverless handler. + +For a plain Docker host without Compose: + +```bash +docker build --platform linux/amd64 -t baseball-engine-api:local . +docker run -d --name baseball-api --gpus all --restart unless-stopped \ + --env-file .env -p 127.0.0.1:8000:8000 \ + -v baseball-data:/data baseball-engine-api:local +``` + +## Queue, limits, and retention + +One recording runs at a time. The default limit is eight active jobs, including queued jobs and uploads. Requests beyond that return 429; clients can retry after 30 seconds. Only two uploads are parsed concurrently. Processing is in an isolated subprocess, so cancelling or timing out a job releases its GPU allocations. + +Defaults are 512 MB per recording, 120 playback seconds, 7,200 decoded frames, and 8,294,400 pixels per frame. Slow-motion recordings can hit the frame limit before the duration limit. Jobs time out after 30 minutes. `.env.example` lists configurable limits; `BASEBALL_MAX_PIXELS` and `BASEBALL_DISK_RESERVE_MB` are also supported environment variables for direct/container deployment. The Compose setup keeps the pixel limit at its default. + +Uploads are removed after a completed, failed, or cancelled job. Queued jobs retain their uploads. On a normal restart, an interrupted job returns to the queue and reuses verified chunks. Incomplete uploads are discarded. Job records and remaining artifacts expire 24 hours after a terminal status; cleanup runs while the healthy service is active. `DELETE /v1/analyses/{job_id}` cancels processing and removes the job directory once its subprocess stops. + +Keep the persistent volume when updating: + +```bash +docker compose up -d --build +``` + +Use one Uvicorn worker and one service replica per data directory. A file lock prevents a second service from using the same queue. Scaling across several machines needs separate volumes and an external job router; that is outside this deployment. + +## Diagnose startup or a failed job + +```bash +docker compose logs --tail=100 api +docker compose exec api cat /data/gpu-preflight.log +``` + +For a failed recording, inspect `/data/jobs/JOB_ID/worker.log` inside the container. `/v1/analyses/JOB_ID` returns the public error code without exposing server paths or a traceback. Jobs return progress for decoding, 2D pose inference, measurement calculation and completion. Frame totals become known after decoding. `stage_progress` applies to the current stage; it is not a promised remaining-time estimate. + +Errors include `invalid_video_or_capture`, `inference_failed`, `job_timeout`, and `worker_error`. Check recording format, frame/duration limits, rotation, timing evidence, and server logs. There is no automatic CPU fallback. + +## Validation before calling the deployment live + +Automated tests cover the HTTP/job lifecycle, authorization, size limits, cancellation, timeout, retention, restart recovery, output mapping, null points, and physical timing. CPU inference can exercise the data path locally. The deployment still needs its real CUDA startup check and one real uploaded recording to finish on the target GPU. + +The service returns `validation: reference_validation_pending` and `estimated_only: true`. Pose scores and measurement estimates have not been calibrated against baseball reference labels. Missing events and null metrics carry reasons. The separate coach payload is checksummed and excludes pose data; jobs completed with the older pose-only image have no coach payload and must be resubmitted after updating the image. diff --git a/docs/TRAINING.md b/docs/TRAINING.md new file mode 100644 index 0000000000000000000000000000000000000000..d471ef69689a268497f5d48f3e313c4560b1d3a7 --- /dev/null +++ b/docs/TRAINING.md @@ -0,0 +1,33 @@ +# Reviewed data and trained backends + +The engine ships trainable code, not pretrained baseball endpoint/phase weights. RTMW and YOLOX are the initial generic observation models. Training on two or three clips cannot establish generalization. + +Each JSON dataset index record contains `video_path`, `annotations_path`, `player_id`, `session_id`, `split` (`train`, `validation`, `test`), and optional `metadata`. Event records additionally contain `analysis_directory`, an existing analysis of the exact source video. No athlete, session or identical video may cross partitions. Use enough independent athletes for the preregistered evaluation scope. Keep participant/footage provenance with the source index. + +Endpoint labels use oriented image pixels, separate `knob` and `barrel` identities, a crop enclosing both endpoints, and explicit `bat_occluded` for reviewed absent visibility. Unknown endpoints are not negative labels. The dataset builder produces RGB 256×256 crops, two 64×64 Gaussian heatmaps and visibility masks. The CNN learns both heatmaps and endpoint visibility. Its output remains model-inferred. + +For events, reviewed labels also contain nonoverlapping `phases`: + +```json +{"phases":[{"phase":"setup","frame_interval":[0,8]}, + {"phase":"load","frame_interval":[9,14]}, + {"phase":"stride","frame_interval":[15,18]}, + {"phase":"forward_swing","frame_interval":[19,25]}, + {"phase":"follow_through","frame_interval":[26,40]}]} +``` + +Unknown frames remain ignored (`-100`). Confirmed event intervals train boundary outputs; reviewed absence trains presence/absence. Unknown contact does not become a negative label. Features retain each source frame and combine named body/object coordinates, masks and a compact visual descriptor. Deterministic image/object candidates remain a separate high-cadence branch. Network scores are not calibrated contact probabilities. + +```bash +python -m baseball_batting.cli dataset index.json --kind endpoint_cnn --output endpoint-data +python -m baseball_batting.cli train endpoint-data --kind endpoint_cnn --output endpoint-model --epochs 30 --device cuda +python -m baseball_batting.cli evaluate-checkpoint endpoint-data endpoint-model --thresholds preregistered-gates.json --scope recorded-task-and-view +``` + +For phases use `--kind mstcn_events` and the pinned `--mstcn-repo` for training and evaluation. The full-worker installer fetches official MS-TCN++ revision `aef4e46c31bc7b2462065354054f968f91e54be1`. The current upstream tip contains a syntax error, so it is not the selected revision. The architecture is loaded from the pinned source, and its hash is checked at inference. + +Training selects the lowest validation loss and writes checkpoint/hash, dataset hash, source, seed, architecture and training history. It does not qualify its own weights. Evaluation uses held-out test athletes and task-specific preregistered gates for error, misses, extra events and coverage. The example gates are deliberately inactive (`preregistered=false`); replace them with justified requirements first. + +Configure `endpoint_checkpoint_path` / `endpoint_manifest_path`, or `event_checkpoint_path` / `event_manifest_path`, `mstcn_repo` and `learned_events_enabled=true` only after evaluation passes. Qualification verifies the checkpoint and evaluation-file hashes. Trained candidates never overwrite reviewed confirmation, absence or unknown. Endpoint inference needs a single unambiguous bat ROI; proposals may still require review. + +Use a worker containing PyTorch for trained endpoints (`stage_python.observations`) and the selected ONNX distribution. Do not put CPU and GPU ONNX Runtime distributions in one environment. Trained events can use `stage_python.learned_events` independently. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000000000000000000000000000000000000..4caead85f4545fd4a733c5c3f197fbf78ce96404 --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,23 @@ +# Implementation checks and later recording validation + +The current workflow finishes backend implementation before asking the user to test recordings. Automated synthetic/dependency checks verify arithmetic, wiring, checkpoint gating and failure recovery; they do not establish baseball accuracy. + +For later recording evaluation, save original footage, capture timing/calibration evidence, reviewed endpoints/ball identities/events and expected unavailable outputs. Include hits, misses, dry swings and occlusion. Provider/CUDA failures affect their branches, while supported 2D reports remain available. Inspect data residuals separately from priors and compare raw/fitted curves before using derivative peaks. + +`preflight` checks the core/ONNX worker; `preflight-optional` checks actual PyTorch/MHR differentiation and a constructed 35-DOF OpenSim/FK/IK fixture in its own worker. The installer records a candidate profile and its resolved package inventory. Each executed worker writes elapsed time and process RSS in `runtime_profiles/`; Torch allocation peaks are recorded for CUDA workers and explicitly exclude ONNX/native allocations. Installed packages are not a substitute for executing models; SAM full-image/full-hand and integrated GPU memory checks still require accessible assets and a suitable CUDA session. + +`tools/evaluation/evaluate_events.py` reports interval errors and unknown/absent/missed/extra events. Proposed one-frame/two-frame goals are targets, not achieved results. Evaluate in source frames and physical milliseconds where the capture clock is known; report abstention coverage and reference uncertainty separately. + +Independent biomechanical evaluation uses: + +```bash +python -m baseball_batting.cli evaluate-reference pairs.json --gates preregistered-metric-gates.json --output evaluation.json +``` + +Each pair identifies the exact `input_sha256`, `result_path`, player/session IDs, `independent_reference=true`, `synchronization_verified=true`, `reference_source`, and `metrics` containing reference value, unit and matching definition version. Optional `repeatability_group` identifies repeated controlled conditions. Gates must have `preregistered=true`, a source record, explicit population/task/view scope and per-metric `maximum`/`minimum` requirements. + +The evaluator reports bias, absolute error, p95 error, measurement coverage, athlete count and within-group error repeatability. It cannot fabricate calibrated uncertainty coverage; that remains unavailable without an independently calibrated uncertainty method. Results supply evidence for explicit method/rule review rather than silently promoting all metrics to validated status. + +OpenBiomechanics is an eligible reference-distribution candidate, with provenance/population limits and commercial-license review deferred as planned. It is not automatically paired video training data. `tools/evaluation/inspect_reference_csv.py` inventories supplied reference tables without inventing paired labels. Independent synchronized recordings remain necessary for video-pipeline accuracy evaluation. + +Feedback defaults to descriptive observations. The sourced tee-practice rule is an educational research hypothesis requiring matched tee trials and confirmed contact, not a knee-angle prescription or claimed benefit. No overall score, ideal swing, causal fault, force estimate or injury assessment is generated. Expert agreement and intervention effectiveness need their own later evaluation. diff --git a/docs/api-result.schema.json b/docs/api-result.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..871425483370cac090b624a116a7b3724ed7b752 --- /dev/null +++ b/docs/api-result.schema.json @@ -0,0 +1,1107 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Baseball 2D GPU result", + "type": "object", + "required": [ + "schema_version", + "status", + "pose_track", + "measurements", + "warnings", + "capabilities", + "validation", + "coach_payload", + "measurement_method" + ], + "additionalProperties": false, + "properties": { + "schema_version": { + "const": "1.0" + }, + "status": { + "const": "partial" + }, + "validation": { + "const": "reference_validation_pending" + }, + "warnings": { + "type": "array", + "items": { + "type": "string" + } + }, + "capabilities": { + "type": "object", + "required": [ + "gpu_2d", + "body_3d", + "automatic_rep_splitting", + "automatic_events", + "swing_metrics", + "coaching", + "pitching", + "estimated_only" + ], + "properties": { + "gpu_2d": { + "const": true + }, + "body_3d": { + "const": false + }, + "automatic_rep_splitting": { + "const": true + }, + "automatic_events": { + "const": true + }, + "swing_metrics": { + "const": true + }, + "coaching": { + "const": false + }, + "pitching": { + "const": false + }, + "estimated_only": { + "const": true + } + }, + "additionalProperties": false + }, + "pose_track": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "discipline", + "view", + "video", + "model", + "keypoint_order", + "extra_keypoint_order", + "frames", + "reps" + ], + "properties": { + "schema_version": { + "const": "1.0" + }, + "discipline": { + "const": "hitting" + }, + "view": { + "enum": [ + "face_on", + "unknown" + ] + }, + "video": { + "type": "object", + "additionalProperties": false, + "required": [ + "width", + "height", + "frame_count", + "capture_fps", + "playback_fps", + "rotation_degrees_applied", + "time_source" + ], + "properties": { + "width": { + "type": "integer", + "minimum": 1 + }, + "height": { + "type": "integer", + "minimum": 1 + }, + "frame_count": { + "type": "integer", + "minimum": 1 + }, + "capture_fps": { + "type": [ + "number", + "null" + ], + "exclusiveMinimum": 0 + }, + "playback_fps": { + "type": [ + "number", + "null" + ], + "exclusiveMinimum": 0 + }, + "rotation_degrees_applied": { + "enum": [ + 0, + 90, + 180, + 270 + ] + }, + "time_source": { + "enum": [ + "unknown", + "original_pts", + "slowmo_rescaled", + "explicit_capture_times" + ] + } + } + }, + "model": { + "type": "object", + "required": [ + "name", + "version", + "sha256", + "person_detector", + "person_detector_sha256", + "processing", + "people_rule", + "blur_definition" + ], + "properties": { + "name": { + "const": "RTMW-x" + }, + "version": { + "type": "string" + }, + "sha256": { + "type": "string" + }, + "person_detector": { + "type": "string" + }, + "person_detector_sha256": { + "type": "string" + }, + "processing": { + "type": "array", + "items": { + "type": "string" + } + }, + "people_rule": { + "type": "string" + }, + "blur_definition": { + "type": "string" + } + }, + "additionalProperties": false + }, + "keypoint_order": { + "const": [ + "nose", + "left_eye", + "right_eye", + "left_ear", + "right_ear", + "left_shoulder", + "right_shoulder", + "left_elbow", + "right_elbow", + "left_wrist", + "right_wrist", + "left_hip", + "right_hip", + "left_knee", + "right_knee", + "left_ankle", + "right_ankle" + ] + }, + "extra_keypoint_order": { + "const": [ + "left_big_toe", + "left_small_toe", + "left_heel", + "right_big_toe", + "right_small_toe", + "right_heel" + ] + }, + "frames": { + "type": "object", + "additionalProperties": false, + "required": [ + "t_s", + "playback_t_s", + "kp", + "conf", + "kp_extra", + "conf_extra", + "box", + "track_id", + "people_count", + "blur", + "brightness" + ], + "properties": { + "t_s": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "playback_t_s": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "kp": { + "type": "array", + "items": { + "type": "array", + "minItems": 17, + "maxItems": 17, + "items": { + "$ref": "#/$defs/point" + } + } + }, + "conf": { + "type": "array", + "items": { + "type": "array", + "minItems": 17, + "maxItems": 17, + "items": { + "$ref": "#/$defs/confidence" + } + } + }, + "kp_extra": { + "type": "array", + "items": { + "type": "array", + "minItems": 6, + "maxItems": 6, + "items": { + "$ref": "#/$defs/point" + } + } + }, + "conf_extra": { + "type": "array", + "items": { + "type": "array", + "minItems": 6, + "maxItems": 6, + "items": { + "$ref": "#/$defs/confidence" + } + } + }, + "box": { + "type": "array", + "items": { + "type": [ + "array", + "null" + ], + "minItems": 4, + "maxItems": 4, + "items": { + "type": "number" + } + } + }, + "track_id": { + "type": "array", + "items": { + "enum": [ + 1, + null + ] + } + }, + "people_count": { + "type": "array", + "items": { + "type": [ + "integer", + "null" + ], + "minimum": 0 + } + }, + "blur": { + "type": "array", + "items": { + "$ref": "#/$defs/confidence" + } + }, + "brightness": { + "type": "array", + "items": { + "type": "number", + "minimum": 0, + "maximum": 255 + } + } + } + }, + "reps": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "rep", + "start_frame", + "end_frame", + "events", + "missing_events", + "boundary_method" + ], + "properties": { + "rep": { + "type": "integer", + "minimum": 1 + }, + "start_frame": { + "type": "integer", + "minimum": 0 + }, + "end_frame": { + "type": "integer", + "minimum": 0 + }, + "events": { + "type": "object", + "additionalProperties": false, + "properties": { + "stance_set": { + "$ref": "#/$defs/event" + }, + "load_start": { + "$ref": "#/$defs/event" + }, + "stride": { + "$ref": "#/$defs/event" + }, + "foot_contact": { + "$ref": "#/$defs/event" + }, + "foot_plant": { + "$ref": "#/$defs/event" + }, + "swing_start": { + "$ref": "#/$defs/event" + }, + "contact": { + "$ref": "#/$defs/event" + }, + "finish": { + "$ref": "#/$defs/event" + } + } + }, + "missing_events": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "boundary_method": { + "enum": [ + "caller_declared_single_swing", + "caller_supplied", + "automatic_2d_hand_motion_candidate" + ] + } + } + } + } + } + }, + "measurements": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "discipline", + "capture", + "reps", + "view", + "fps" + ], + "properties": { + "schema_version": { + "const": "2.0" + }, + "discipline": { + "const": "hitting" + }, + "level": { + "enum": [ + "hs_jv", + "hs_varsity", + "college" + ] + }, + "view": { + "enum": [ + "face_on", + "unknown" + ] + }, + "fps": { + "type": [ + "number", + "null" + ], + "exclusiveMinimum": 0 + }, + "capture": { + "type": "object", + "additionalProperties": false, + "required": [ + "ok", + "reasons" + ], + "properties": { + "ok": { + "type": "boolean" + }, + "reasons": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "a_bit_blurry", + "a_bit_dark", + "low_fps", + "low_pose_confidence", + "multiple_people", + "no_person", + "partly_out_of_frame", + "person_too_small", + "player_switched", + "pose_confidence_fair", + "too_blurry", + "too_dark", + "very_low_fps", + "view_uncertain", + "wrong_view" + ] + } + } + }, + "if": { + "properties": { + "ok": { + "const": false + } + } + }, + "then": { + "properties": { + "reasons": { + "minItems": 1 + } + } + } + }, + "reps": { + "type": "array", + "maxItems": 100, + "items": { + "$ref": "#/$defs/measurement_rep" + } + } + } + }, + "coach_payload": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "discipline", + "capture", + "reps" + ], + "properties": { + "schema_version": { + "const": "2.0" + }, + "discipline": { + "const": "hitting" + }, + "level": { + "enum": [ + "hs_jv", + "hs_varsity", + "college" + ] + }, + "view": { + "const": "face_on" + }, + "fps": { + "type": "number", + "exclusiveMinimum": 0 + }, + "capture": { + "type": "object", + "additionalProperties": false, + "required": [ + "ok", + "reasons" + ], + "properties": { + "ok": { + "type": "boolean" + }, + "reasons": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "a_bit_blurry", + "a_bit_dark", + "low_fps", + "low_pose_confidence", + "multiple_people", + "no_person", + "partly_out_of_frame", + "person_too_small", + "player_switched", + "pose_confidence_fair", + "too_blurry", + "too_dark", + "very_low_fps", + "view_uncertain", + "wrong_view" + ] + } + } + }, + "if": { + "properties": { + "ok": { + "const": false + } + } + }, + "then": { + "properties": { + "reasons": { + "minItems": 1 + } + } + } + }, + "reps": { + "type": "array", + "maxItems": 100, + "items": { + "$ref": "#/$defs/measurement_rep" + } + } + } + }, + "measurement_method": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "body_height_px", + "body_height_method", + "pitcher_direction", + "processing", + "validation" + ], + "properties": { + "version": { + "const": "batting-2d-v1" + }, + "body_height_px": { + "type": [ + "number", + "null" + ], + "exclusiveMinimum": 0 + }, + "body_height_method": { + "type": "string" + }, + "pitcher_direction": { + "enum": [ + "image_left", + "image_right", + null + ] + }, + "processing": { + "type": "array", + "items": { + "type": "string" + } + }, + "validation": { + "const": "reference_validation_pending" + } + } + } + }, + "$defs": { + "point": { + "type": [ + "array", + "null" + ], + "minItems": 2, + "maxItems": 2, + "items": { + "type": "number" + } + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "event": { + "type": "object", + "additionalProperties": false, + "required": [ + "frame", + "confidence", + "estimated", + "method", + "note" + ], + "properties": { + "frame": { + "type": "integer", + "minimum": 0 + }, + "t_s": { + "type": "number" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "estimated": { + "const": true + }, + "method": { + "type": "string" + }, + "note": { + "type": "string" + } + } + }, + "metric": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "stride_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 10, + "maximum": 120 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "foot_plant_to_contact_ms" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 30, + "maximum": 800 + }, + "unit": { + "const": "ms" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "com_drift_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -80, + "maximum": 80 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "load_tempo_s" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0.05, + "maximum": 3 + }, + "unit": { + "const": "s" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "load_launch_ratio" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0.1, + "maximum": 20 + }, + "unit": { + "const": "ratio" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "head_movement_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0, + "maximum": 40 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "lead_knee_angle_contact_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 60, + "maximum": 200 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "lateral_trunk_tilt_contact_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -90, + "maximum": 90 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "hip_shoulder_separation_foot_plant_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -90, + "maximum": 90 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + } + ] + }, + "measurement_rep": { + "type": "object", + "additionalProperties": false, + "required": [ + "rep", + "events_ms", + "metrics", + "quality" + ], + "properties": { + "rep": { + "type": "integer", + "minimum": 1 + }, + "events_ms": { + "type": "object", + "additionalProperties": false, + "properties": { + "stance_set": { + "type": "number", + "minimum": 0 + }, + "load_start": { + "type": "number", + "minimum": 0 + }, + "stride": { + "type": "number", + "minimum": 0 + }, + "foot_contact": { + "type": "number", + "minimum": 0 + }, + "foot_plant": { + "type": "number", + "minimum": 0 + }, + "swing_start": { + "type": "number", + "minimum": 0 + }, + "contact": { + "type": "number", + "minimum": 0 + }, + "finish": { + "type": "number", + "minimum": 0 + } + } + }, + "metrics": { + "type": "array", + "minItems": 9, + "maxItems": 9, + "items": { + "$ref": "#/$defs/metric" + } + }, + "quality": { + "type": "object", + "additionalProperties": false, + "required": [ + "pose_conf", + "blur" + ], + "properties": { + "pose_conf": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "blur": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + } + } + } + } +} diff --git a/docs/coach-payload.schema.json b/docs/coach-payload.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..121a3180cd10d2223f74289bc6497aa70436e489 --- /dev/null +++ b/docs/coach-payload.schema.json @@ -0,0 +1,485 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Batting measurements for POST /v1/coach", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "discipline", + "capture", + "reps" + ], + "properties": { + "schema_version": { + "const": "2.0" + }, + "discipline": { + "const": "hitting" + }, + "level": { + "enum": [ + "hs_jv", + "hs_varsity", + "college" + ] + }, + "view": { + "const": "face_on" + }, + "fps": { + "type": "number", + "exclusiveMinimum": 0 + }, + "capture": { + "type": "object", + "additionalProperties": false, + "required": [ + "ok", + "reasons" + ], + "properties": { + "ok": { + "type": "boolean" + }, + "reasons": { + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "a_bit_blurry", + "a_bit_dark", + "low_fps", + "low_pose_confidence", + "multiple_people", + "no_person", + "partly_out_of_frame", + "person_too_small", + "player_switched", + "pose_confidence_fair", + "too_blurry", + "too_dark", + "very_low_fps", + "view_uncertain", + "wrong_view" + ] + } + } + }, + "if": { + "properties": { + "ok": { + "const": false + } + } + }, + "then": { + "properties": { + "reasons": { + "minItems": 1 + } + } + } + }, + "reps": { + "type": "array", + "maxItems": 100, + "items": { + "$ref": "#/$defs/measurement_rep" + } + } + }, + "$defs": { + "metric": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "stride_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 10, + "maximum": 120 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "foot_plant_to_contact_ms" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 30, + "maximum": 800 + }, + "unit": { + "const": "ms" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "com_drift_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -80, + "maximum": 80 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "load_tempo_s" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0.05, + "maximum": 3 + }, + "unit": { + "const": "s" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "load_launch_ratio" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0.1, + "maximum": 20 + }, + "unit": { + "const": "ratio" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "head_movement_pct_height" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 0, + "maximum": 40 + }, + "unit": { + "const": "%" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "lead_knee_angle_contact_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": 60, + "maximum": 200 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "lateral_trunk_tilt_contact_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -90, + "maximum": 90 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "key", + "value", + "unit", + "confidence", + "note" + ], + "properties": { + "key": { + "const": "hip_shoulder_separation_foot_plant_deg" + }, + "value": { + "type": [ + "number", + "null" + ], + "minimum": -90, + "maximum": 90 + }, + "unit": { + "const": "deg" + }, + "confidence": { + "const": "est" + }, + "note": { + "type": "string", + "minLength": 1 + } + } + } + ] + }, + "measurement_rep": { + "type": "object", + "additionalProperties": false, + "required": [ + "rep", + "events_ms", + "metrics", + "quality" + ], + "properties": { + "rep": { + "type": "integer", + "minimum": 1 + }, + "events_ms": { + "type": "object", + "additionalProperties": false, + "properties": { + "stance_set": { + "type": "number", + "minimum": 0 + }, + "load_start": { + "type": "number", + "minimum": 0 + }, + "stride": { + "type": "number", + "minimum": 0 + }, + "foot_contact": { + "type": "number", + "minimum": 0 + }, + "foot_plant": { + "type": "number", + "minimum": 0 + }, + "swing_start": { + "type": "number", + "minimum": 0 + }, + "contact": { + "type": "number", + "minimum": 0 + }, + "finish": { + "type": "number", + "minimum": 0 + } + } + }, + "metrics": { + "type": "array", + "minItems": 9, + "maxItems": 9, + "items": { + "$ref": "#/$defs/metric" + } + }, + "quality": { + "type": "object", + "additionalProperties": false, + "required": [ + "pose_conf", + "blur" + ], + "properties": { + "pose_conf": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "blur": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + } + } + } + } +} diff --git a/examples/api_client.py b/examples/api_client.py new file mode 100644 index 0000000000000000000000000000000000000000..def682c578781ae0659fcc5ccfb7577881a4c766 --- /dev/null +++ b/examples/api_client.py @@ -0,0 +1,52 @@ +"""Upload, poll and download. API key comes from the environment, not source.""" +import argparse +import json +import os +from pathlib import Path +import time +import requests + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("video", type=Path) + parser.add_argument("--url", required=True) + parser.add_argument("--options", type=Path) + parser.add_argument("--output", type=Path, default=Path("result.json")) + parser.add_argument("--coach-payload", action="store_true", help="Download only the body for POST /v1/coach") + parser.add_argument("--wait-seconds", type=float, default=1900) + args = parser.parse_args() + key = os.environ.get("BASEBALL_API_KEY") + if not key: parser.error("Set BASEBALL_API_KEY") + base = args.url.rstrip("/") + options = json.loads(args.options.read_text()) if args.options else {} + with requests.Session() as client: + client.headers["Authorization"] = "Bearer " + key + with args.video.open("rb") as video: + response = client.post(base + "/v1/analyses", files={"video": (args.video.name, video)}, + data={"options": json.dumps(options)}, timeout=(10, 300)) + response.raise_for_status() + job = response.json() + print("Job:", job["job_id"]) + deadline = time.monotonic() + args.wait_seconds + while time.monotonic() < deadline: + response = client.get(base + job["status_url"], timeout=30) + response.raise_for_status() + status = response.json() + print(status["status"], status.get("progress")) + if status["status"] == "completed": + target = job["coach_payload_url"] if args.coach_payload else job["result_url"] + with client.get(base + target, stream=True, timeout=60) as result: + result.raise_for_status() + with args.output.open("wb") as out: + for block in result.iter_content(64 * 1024): out.write(block) + print("Saved:", args.output) + return + if status["status"] in {"failed", "cancelled"}: + raise RuntimeError("Job ended: " + str(status.get("error") or status["status"])) + time.sleep(3) + raise TimeoutError("Client wait ended; the server job can still be polled using its ID") + + +if __name__ == "__main__": + main() diff --git a/examples/coach-payload.example.json b/examples/coach-payload.example.json new file mode 100644 index 0000000000000000000000000000000000000000..f451e87c55dd26ca3d83e79cc9d06d25d91c4c20 --- /dev/null +++ b/examples/coach-payload.example.json @@ -0,0 +1,95 @@ +{ + "schema_version": "2.0", + "discipline": "hitting", + "capture": { + "ok": true, + "reasons": [] + }, + "reps": [ + { + "rep": 1, + "events_ms": { + "swing_start": 508.333, + "load_start": 175.0, + "stance_set": 0.0, + "contact": 783.333, + "stride": 225.0, + "foot_contact": 375.0, + "foot_plant": 375.0, + "finish": 1091.667 + }, + "metrics": [ + { + "key": "stride_pct_height", + "value": 42.5, + "unit": "%", + "confidence": "est", + "note": "2D estimate; scale: caller supplied standing image height. Horizontal ankle span at settled-foot proxy; full body-weight loading unmeasured." + }, + { + "key": "foot_plant_to_contact_ms", + "value": 408.333, + "unit": "ms", + "confidence": "est", + "note": "Settled-foot to lead-arm-extension proxy; full loading and ball contact unconfirmed; event error uncalibrated." + }, + { + "key": "com_drift_pct_height", + "value": -25.0, + "unit": "%", + "confidence": "est", + "note": "2D estimate; scale: caller supplied standing image height. Hip midpoint relative to front ankle; negative means behind; not whole-body center of mass." + }, + { + "key": "load_tempo_s", + "value": 0.333, + "unit": "s", + "confidence": "est", + "note": "Estimated backward-hand load start to forward-hand onset." + }, + { + "key": "load_launch_ratio", + "value": 1.212, + "unit": "ratio", + "confidence": "est", + "note": "Estimated load duration divided by forward onset-to-contact duration." + }, + { + "key": "head_movement_pct_height", + "value": 0.493, + "unit": "%", + "confidence": "est", + "note": "2D estimate; scale: caller supplied standing image height. Reference-only smoothed nose path from stance to estimated contact; not calibrated for judging." + }, + { + "key": "lead_knee_angle_contact_deg", + "value": 167.358, + "unit": "deg", + "confidence": "est", + "note": "Reference only: projected interior knee angle at estimated contact; face-on projection does not measure anatomical flexion." + }, + { + "key": "lateral_trunk_tilt_contact_deg", + "value": null, + "unit": "deg", + "confidence": "est", + "note": "Unavailable: face-on 2D cannot establish the requested anatomical trunk tilt." + }, + { + "key": "hip_shoulder_separation_foot_plant_deg", + "value": null, + "unit": "deg", + "confidence": "est", + "note": "Unavailable: image-plane line angles do not measure axial hip-shoulder twist." + } + ], + "quality": { + "pose_conf": 0.9000000000000002, + "blur": 0.09999999999999998 + } + } + ], + "level": "hs_varsity", + "fps": 120, + "view": "face_on" +} diff --git a/models/BattingKinematics-v1.json b/models/BattingKinematics-v1.json new file mode 100644 index 0000000000000000000000000000000000000000..21a8c19b4c62ea3bbb93a588c548362731a1c44a --- /dev/null +++ b/models/BattingKinematics-v1.json @@ -0,0 +1,1748 @@ +{ + "bodies": { + "left_foot": { + "origin": [ + 0.15, + 0.1, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_forearm": { + "origin": [ + 0.5, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_hand": { + "origin": [ + 0.8, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_rotor": { + "origin": [ + 0.5, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_shank": { + "origin": [ + 0.15, + 0.5, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_thigh": { + "origin": [ + 0.15, + 0.9, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "left_upper_arm": { + "origin": [ + 0.2, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "pelvis": { + "origin": [ + 0.0, + 0.9, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_foot": { + "origin": [ + -0.15, + 0.1, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_forearm": { + "origin": [ + -0.5, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_hand": { + "origin": [ + -0.8, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_rotor": { + "origin": [ + -0.5, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_shank": { + "origin": [ + -0.15, + 0.5, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_thigh": { + "origin": [ + -0.15, + 0.9, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "right_upper_arm": { + "origin": [ + -0.2, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + "thorax": { + "origin": [ + 0.0, + 1.4, + 0.0 + ], + "rotation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + } + }, + "coordinate_definition": "primitive coordinates; named measurements derive from segment frames", + "coordinates": [ + { + "name": "root_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "root_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "root_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "root_3", + "range": [ + -100, + 100 + ], + "unit": "m" + }, + { + "name": "root_4", + "range": [ + -100, + 100 + ], + "unit": "m" + }, + { + "name": "root_5", + "range": [ + -100, + 100 + ], + "unit": "m" + }, + { + "name": "pelvis_thorax_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "pelvis_thorax_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "pelvis_thorax_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_hip_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_hip_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_hip_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_knee_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_ankle_0", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "left_ankle_1", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "left_shoulder_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_shoulder_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_shoulder_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_elbow_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_forearm_rotor_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "left_wrist_0", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "left_wrist_1", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "right_hip_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_hip_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_hip_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_knee_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_ankle_0", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "right_ankle_1", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "right_shoulder_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_shoulder_1", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_shoulder_2", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_elbow_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_forearm_rotor_0", + "range": [ + -3.05, + 3.05 + ], + "unit": "rad" + }, + { + "name": "right_wrist_0", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + }, + { + "name": "right_wrist_1", + "range": [ + -1.35, + 1.35 + ], + "unit": "rad" + } + ], + "dynamics": "disabled; placeholder masses and inertia", + "independent_observation": false, + "joints": [ + { + "child": "pelvis", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 0, + 1, + 2, + 3, + 4, + 5 + ], + "kind": "FreeJoint", + "name": "root", + "parent": "ground", + "parent_location": [ + 0.0, + 0.9, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "thorax", + "child_location": [ + 0.0, + -0.25, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 6, + 7, + 8 + ], + "kind": "BallJoint", + "name": "pelvis_thorax", + "parent": "pelvis", + "parent_location": [ + 0.0, + 0.2499999999999999, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "left_thigh", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 9, + 10, + 11 + ], + "kind": "BallJoint", + "name": "left_hip", + "parent": "pelvis", + "parent_location": [ + 0.15, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "left_shank", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ], + "coordinates": [ + 12 + ], + "kind": "PinJoint", + "name": "left_knee", + "parent": "left_thigh", + "parent_location": [ + 0.0, + -0.4, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ] + }, + { + "child": "left_foot", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 13, + 14 + ], + "kind": "UniversalJoint", + "name": "left_ankle", + "parent": "left_shank", + "parent_location": [ + 0.0, + -0.4, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "left_upper_arm", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 15, + 16, + 17 + ], + "kind": "BallJoint", + "name": "left_shoulder", + "parent": "thorax", + "parent_location": [ + 0.2, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "left_forearm", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + -1.0, + 0.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 18 + ], + "kind": "PinJoint", + "name": "left_elbow", + "parent": "left_upper_arm", + "parent_location": [ + 0.3, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + -1.0, + 0.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "left_rotor", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ], + "coordinates": [ + 19 + ], + "kind": "PinJoint", + "name": "left_forearm_rotor", + "parent": "left_forearm", + "parent_location": [ + 0.0, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ] + }, + { + "child": "left_hand", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 20, + 21 + ], + "kind": "UniversalJoint", + "name": "left_wrist", + "parent": "left_rotor", + "parent_location": [ + 0.30000000000000004, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "right_thigh", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 22, + 23, + 24 + ], + "kind": "BallJoint", + "name": "right_hip", + "parent": "pelvis", + "parent_location": [ + -0.15, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "right_shank", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ], + "coordinates": [ + 25 + ], + "kind": "PinJoint", + "name": "right_knee", + "parent": "right_thigh", + "parent_location": [ + 0.0, + -0.4, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + 0.0, + 1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ] + ] + }, + { + "child": "right_foot", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 26, + 27 + ], + "kind": "UniversalJoint", + "name": "right_ankle", + "parent": "right_shank", + "parent_location": [ + 0.0, + -0.4, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "right_upper_arm", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 28, + 29, + 30 + ], + "kind": "BallJoint", + "name": "right_shoulder", + "parent": "thorax", + "parent_location": [ + -0.2, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + }, + { + "child": "right_forearm", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + 1.0, + 0.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ], + "coordinates": [ + 31 + ], + "kind": "PinJoint", + "name": "right_elbow", + "parent": "right_upper_arm", + "parent_location": [ + -0.3, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + 1.0, + 0.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ] + }, + { + "child": "right_rotor", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + -1.0, + 0.0 + ] + ], + "coordinates": [ + 32 + ], + "kind": "PinJoint", + "name": "right_forearm_rotor", + "parent": "right_forearm", + "parent_location": [ + 0.0, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + -1.0, + 0.0 + ] + ] + }, + { + "child": "right_hand", + "child_location": [ + 0.0, + 0.0, + 0.0 + ], + "child_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "coordinates": [ + 33, + 34 + ], + "kind": "UniversalJoint", + "name": "right_wrist", + "parent": "right_rotor", + "parent_location": [ + -0.30000000000000004, + 0.0, + 0.0 + ], + "parent_orientation": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ] + } + ], + "markers": { + "left_ankle": { + "body": "left_shank", + "mhr70_index": 13, + "offset": [ + 0.0, + -0.4, + 0.0 + ] + }, + "left_big_toe": { + "body": "left_foot", + "mhr70_index": 15, + "offset": [ + 0.0, + -0.1, + 0.15 + ] + }, + "left_elbow": { + "body": "left_upper_arm", + "mhr70_index": 7, + "offset": [ + 0.3, + 0.0, + 0.0 + ] + }, + "left_heel": { + "body": "left_foot", + "mhr70_index": 17, + "offset": [ + 0.0, + -0.1, + -0.05 + ] + }, + "left_hip": { + "body": "pelvis", + "mhr70_index": 9, + "offset": [ + 0.15, + 0.0, + 0.0 + ] + }, + "left_index_mcp": { + "body": "left_hand", + "mhr70_index": 49, + "offset": [ + 0.06999999999999995, + 0.020000000000000018, + 0.03 + ] + }, + "left_knee": { + "body": "left_thigh", + "mhr70_index": 11, + "offset": [ + 0.0, + -0.4, + 0.0 + ] + }, + "left_little_mcp": { + "body": "left_hand", + "mhr70_index": 61, + "offset": [ + 0.06999999999999995, + -0.020000000000000018, + -0.03 + ] + }, + "left_shoulder": { + "body": "thorax", + "mhr70_index": 5, + "offset": [ + 0.2, + 0.0, + 0.0 + ] + }, + "left_small_toe": { + "body": "left_foot", + "mhr70_index": 16, + "offset": [ + 0.05000000000000002, + -0.1, + 0.15 + ] + }, + "left_wrist": { + "body": "left_rotor", + "mhr70_index": 62, + "offset": [ + 0.30000000000000004, + 0.0, + 0.0 + ] + }, + "right_ankle": { + "body": "right_shank", + "mhr70_index": 14, + "offset": [ + 0.0, + -0.4, + 0.0 + ] + }, + "right_big_toe": { + "body": "right_foot", + "mhr70_index": 18, + "offset": [ + 0.0, + -0.1, + 0.15 + ] + }, + "right_elbow": { + "body": "right_upper_arm", + "mhr70_index": 8, + "offset": [ + -0.3, + 0.0, + 0.0 + ] + }, + "right_heel": { + "body": "right_foot", + "mhr70_index": 20, + "offset": [ + 0.0, + -0.1, + -0.05 + ] + }, + "right_hip": { + "body": "pelvis", + "mhr70_index": 10, + "offset": [ + -0.15, + 0.0, + 0.0 + ] + }, + "right_index_mcp": { + "body": "right_hand", + "mhr70_index": 28, + "offset": [ + -0.06999999999999995, + 0.020000000000000018, + 0.03 + ] + }, + "right_knee": { + "body": "right_thigh", + "mhr70_index": 12, + "offset": [ + 0.0, + -0.4, + 0.0 + ] + }, + "right_little_mcp": { + "body": "right_hand", + "mhr70_index": 40, + "offset": [ + -0.06999999999999995, + -0.020000000000000018, + -0.03 + ] + }, + "right_shoulder": { + "body": "thorax", + "mhr70_index": 6, + "offset": [ + -0.2, + 0.0, + 0.0 + ] + }, + "right_small_toe": { + "body": "right_foot", + "mhr70_index": 19, + "offset": [ + -0.05000000000000002, + -0.1, + 0.15 + ] + }, + "right_wrist": { + "body": "right_rotor", + "mhr70_index": 41, + "offset": [ + -0.30000000000000004, + 0.0, + 0.0 + ] + } + }, + "model_id": "BattingKinematics-v1", + "neutral_basis_definition": "x toward anatomical left; y cranial; z x cross y", + "proportion_source": "synthetic_reference_template_replaced_per_subject_at_runtime", + "schema_version": "1.0", + "source_kind": "model_regression_proxy", + "version": "1.0" +} \ No newline at end of file diff --git a/models/BattingKinematics-v1.osim b/models/BattingKinematics-v1.osim new file mode 100644 index 0000000000000000000000000000000000000000..fdfa005ec7bb4a6ec703848f35439f4397b7456e --- /dev/null +++ b/models/BattingKinematics-v1.osim @@ -0,0 +1,1297 @@ + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + 1 + + 0 0 0 + + 1 1 1 0 0 0 + + + + + + + + + + ground_offset + + pelvis_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -100 100 + + + + 0 + + -100 100 + + + + 0 + + -100 100 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /ground + + 0 0.90000000000000002 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/pelvis + + 0 0 0 + + -0 0 0 + + + + + + pelvis_offset + + thorax_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/pelvis + + 0 0.24999999999999989 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/thorax + + 0 -0.25 0 + + -0 0 0 + + + + + + pelvis_offset + + left_thigh_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/pelvis + + 0.14999999999999999 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_thigh + + 0 0 0 + + -0 0 0 + + + + + + left_thigh_offset + + left_shank_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_thigh + + 0 -0.40000000000000002 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_shank + + 0 0 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + left_shank_offset + + left_foot_offset + + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_shank + + 0 -0.40000000000000002 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_foot + + 0 0 0 + + -0 0 0 + + + + + + thorax_offset + + left_upper_arm_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/thorax + + 0.20000000000000001 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_upper_arm + + 0 0 0 + + -0 0 0 + + + + + + left_upper_arm_offset + + left_forearm_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_upper_arm + + 0.29999999999999999 0 0 + + -0 0 1.5707963267948966 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_forearm + + 0 0 0 + + -0 0 1.5707963267948966 + + + + + + left_forearm_offset + + left_rotor_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_forearm + + 0 0 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_rotor + + 0 0 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + left_rotor_offset + + left_hand_offset + + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_rotor + + 0.30000000000000004 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/left_hand + + 0 0 0 + + -0 0 0 + + + + + + pelvis_offset + + right_thigh_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/pelvis + + -0.14999999999999999 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_thigh + + 0 0 0 + + -0 0 0 + + + + + + right_thigh_offset + + right_shank_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_thigh + + 0 -0.40000000000000002 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_shank + + 0 0 0 + + 1.5707963267948966 1.5707963267948966 0 + + + + + + right_shank_offset + + right_foot_offset + + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_shank + + 0 -0.40000000000000002 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_foot + + 0 0 0 + + -0 0 0 + + + + + + thorax_offset + + right_upper_arm_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/thorax + + -0.20000000000000001 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_upper_arm + + 0 0 0 + + -0 0 0 + + + + + + right_upper_arm_offset + + right_forearm_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_upper_arm + + -0.29999999999999999 0 0 + + 3.1415926535897931 0 -1.5707963267948966 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_forearm + + 0 0 0 + + 3.1415926535897931 0 -1.5707963267948966 + + + + + + right_forearm_offset + + right_rotor_offset + + + + + 0 + + -3.0499999999999998 3.0499999999999998 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_forearm + + 0 0 0 + + -1.5707963267948966 -1.5707963267948966 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_rotor + + 0 0 0 + + -1.5707963267948966 -1.5707963267948966 0 + + + + + + right_rotor_offset + + right_hand_offset + + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + 0 + + -1.3500000000000001 1.3500000000000001 + + + + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_rotor + + -0.30000000000000004 0 0 + + -0 0 0 + + + + + + .. + + 0.20000000000000001 0.20000000000000001 0.20000000000000001 + + + /bodyset/right_hand + + 0 0 0 + + -0 0 0 + + + + + + + + + + + + + + + + + + + + + + /bodyset/pelvis + + 0.14999999999999999 0 0 + + + + /bodyset/left_thigh + + 0 -0.40000000000000002 0 + + + + /bodyset/left_shank + + 0 -0.40000000000000002 0 + + + + /bodyset/left_foot + + 0 -0.10000000000000001 0.14999999999999999 + + + + /bodyset/left_foot + + 0.050000000000000017 -0.10000000000000001 0.14999999999999999 + + + + /bodyset/left_foot + + 0 -0.10000000000000001 -0.050000000000000003 + + + + /bodyset/thorax + + 0.20000000000000001 0 0 + + + + /bodyset/left_upper_arm + + 0.29999999999999999 0 0 + + + + /bodyset/left_rotor + + 0.30000000000000004 0 0 + + + + /bodyset/left_hand + + 0.069999999999999951 0.020000000000000018 0.029999999999999999 + + + + /bodyset/left_hand + + 0.069999999999999951 -0.020000000000000018 -0.029999999999999999 + + + + /bodyset/pelvis + + -0.14999999999999999 0 0 + + + + /bodyset/right_thigh + + 0 -0.40000000000000002 0 + + + + /bodyset/right_shank + + 0 -0.40000000000000002 0 + + + + /bodyset/right_foot + + 0 -0.10000000000000001 0.14999999999999999 + + + + /bodyset/right_foot + + -0.050000000000000017 -0.10000000000000001 0.14999999999999999 + + + + /bodyset/right_foot + + 0 -0.10000000000000001 -0.050000000000000003 + + + + /bodyset/thorax + + -0.20000000000000001 0 0 + + + + /bodyset/right_upper_arm + + -0.29999999999999999 0 0 + + + + /bodyset/right_rotor + + -0.30000000000000004 0 0 + + + + /bodyset/right_hand + + -0.069999999999999951 0.020000000000000018 0.029999999999999999 + + + + /bodyset/right_hand + + -0.069999999999999951 -0.020000000000000018 -0.029999999999999999 + + + + + + diff --git a/notebooks/batting_2d_test.ipynb b/notebooks/batting_2d_test.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..52c119d2eb7a9ec5e49ae9967cbbc5d923319b74 --- /dev/null +++ b/notebooks/batting_2d_test.ipynb @@ -0,0 +1,468 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + }, + "accelerator": "GPU", + "colab": { + "name": "batting_2d_test.ipynb", + "provenance": [] + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Test batting swing separation on GPU\n", + "\n", + "This runs the **same 2D worker used by the engine API**. Upload one video with several swings, inspect the detected ranges and their clip previews, and download `coach-payload.json`. All 3D and coaching stages stay disabled. It tests the engine's calculations; Docker/HTTP deployment is a separate check.\n", + "\n", + "1. In Colab select **Runtime \u2192 Change runtime type \u2192 GPU** (T4 if available), then run the cells in order.\n", + "2. Start with a short video containing 2\u20133 swings. The whole batter, hands and feet should be visible, with a fixed camera and a known face-on view.\n", + "3. Enter recording settings only when known. Leave `SINGLE_SWING=False` to test automatic splitting.\n", + "4. Watch each candidate preview. Check that each contains one swing and includes preparation/finish. Check for missed swings and setup movements mistaken for swings.\n", + "5. Download the ZIP. It contains measurements, ranges, previews and logs. The original video and model weights are excluded.\n", + "\n", + "Swings, events and measurements remain estimates. A clean run or plausible preview does not establish accuracy. GPU availability is controlled by Colab; see [Colab's help](https://research.google.com/colaboratory/faq.html).\n" + ], + "id": "batting-2d-000" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Get the current engine\n", + "\n", + "Use a GitHub token with read access to your private repository. The hidden token is used only during checkout and is not saved in the Git URL or results. Setup records the resolved commit. This notebook uses a separate workspace from the full pipeline notebook.\n" + ], + "id": "batting-2d-001" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\"\"\"Readable GitHub bootstrap, copied into the first Colab code cell by the builder.\"\"\"\n", + "from pathlib import Path\n", + "from contextlib import contextmanager\n", + "import base64\n", + "import json\n", + "import os\n", + "import re\n", + "import subprocess\n", + "import sys\n", + "\n", + "\n", + "def _git(directory, *arguments, auth_env=None):\n", + " environment = {**os.environ, \"GIT_TERMINAL_PROMPT\": \"0\", **(auth_env or {})}\n", + " result = subprocess.run(\n", + " [\"git\", \"-C\", str(directory), *arguments], text=True,\n", + " stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,\n", + " )\n", + " if result.returncode:\n", + " detail = result.stderr.strip() or result.stdout.strip() or \"Git returned no error detail\"\n", + " secret = (auth_env or {}).get(\"BATTING_GITHUB_TOKEN\")\n", + " if secret:\n", + " encoded = base64.b64encode(f\"x-access-token:{secret}\".encode()).decode()\n", + " detail = detail.replace(secret, \"[REDACTED]\").replace(encoded, \"[REDACTED]\")\n", + " detail = re.sub(r\"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+\", \"[REDACTED]\", detail)\n", + " raise RuntimeError(f\"Git failed (exit {result.returncode}):\\n{detail[-4000:]}\") from None\n", + " return result.stdout.strip()\n", + "\n", + "\n", + "@contextmanager\n", + "def _github_credentials(token, scope=\"https://github.com/\"):\n", + " if not token:\n", + " yield {}\n", + " return\n", + " # Git reads these settings only for this subprocess; no token is stored in its URL/config.\n", + " count = int(os.environ.get(\"GIT_CONFIG_COUNT\", \"0\"))\n", + " encoded = base64.b64encode(f\"x-access-token:{token}\".encode()).decode()\n", + " yield {\n", + " \"GIT_CONFIG_COUNT\": str(count + 2),\n", + " f\"GIT_CONFIG_KEY_{count}\": f\"http.{scope}.extraHeader\",\n", + " f\"GIT_CONFIG_VALUE_{count}\": \"\",\n", + " f\"GIT_CONFIG_KEY_{count + 1}\": f\"http.{scope}.extraHeader\",\n", + " f\"GIT_CONFIG_VALUE_{count + 1}\": f\"Authorization: Basic {encoded}\",\n", + " \"BATTING_GITHUB_TOKEN\": token,\n", + " }\n", + "\n", + "\n", + "def checkout_github(repository_url, revision, workspace, token=None):\n", + " \"\"\"Fetch an explicit ref and stop before replacing modified source files.\"\"\"\n", + " if token is not None:\n", + " token = token.strip()\n", + " if not token:\n", + " raise ValueError(\"Enter a token with read access to this repository\")\n", + " if not re.fullmatch(r\"https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\\.git)?/?\", repository_url):\n", + " raise ValueError(\"Use an HTTPS GitHub repository URL without credentials or query parameters\")\n", + " if any(part in {\".\", \"..\"} for part in repository_url.split(\"/\")[3:]):\n", + " raise ValueError(\"Use an owner/repository GitHub URL\")\n", + " if not revision or revision.startswith(\"-\") or any(c.isspace() for c in revision):\n", + " raise ValueError(\"Set a branch, tag, or full commit SHA\")\n", + " workspace = Path(workspace).resolve()\n", + " source = workspace / \"source\"\n", + " workspace.mkdir(parents=True, exist_ok=True)\n", + " with _github_credentials(token) as authentication:\n", + " options = (\"-c\", \"credential.helper=\") if token else ()\n", + " fresh_checkout = False\n", + " if not (source / \".git\").exists():\n", + " if source.exists() and any(source.iterdir()):\n", + " raise ValueError(f\"Source directory is not an empty Git checkout: {source}\")\n", + " _git(workspace, *options, \"clone\", \"--no-checkout\", \"--depth=1\", repository_url,\n", + " str(source), auth_env=authentication)\n", + " fresh_checkout = True\n", + " if _git(source, \"config\", \"--get\", \"remote.origin.url\") != repository_url:\n", + " raise ValueError(\"Existing checkout uses a different repository; choose another workspace\")\n", + " # A newly cloned --no-checkout repository has no populated index yet.\n", + " if not fresh_checkout and _git(source, \"status\", \"--porcelain\", \"--untracked-files=no\"):\n", + " raise ValueError(\"Source has local edits; save them or choose another workspace before updating\")\n", + " _git(source, *options, \"fetch\", \"--depth=1\", \"origin\", revision, auth_env=authentication)\n", + " commit = _git(source, \"rev-parse\", \"FETCH_HEAD^{commit}\")\n", + " if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) and commit.lower() != revision.lower():\n", + " raise ValueError(\"Fetched commit does not match the requested SHA\")\n", + " _git(source, \"checkout\", \"--quiet\", \"--detach\", commit)\n", + " required = [\"baseball_batting/cli.py\", \"requirements-core.txt\", \"configs/resources.yaml\"]\n", + " if not all((source / name).is_file() for name in required):\n", + " raise ValueError(\"Selected repository revision does not contain the batting engine\")\n", + " record = {\"repository_url\": repository_url, \"requested_revision\": revision, \"commit_sha\": commit}\n", + " (workspace / \"source_checkout.json\").write_text(json.dumps(record, indent=2))\n", + " print(\"Engine source:\", source)\n", + " print(\"Resolved commit:\", commit, \"(use this SHA as REVISION to reproduce this run)\")\n", + " return source, record\n", + "\n", + "\n", + "REPOSITORY_URL = 'https://github.com/usmanthesuper/baseball-engine.git'\n", + "REVISION = 'main' # Use the recorded full SHA to reproduce a run.\n", + "PRIVATE_REPOSITORY = True\n", + "WORKSPACE_ROOT = Path(\"/content/baseball_batting_2d\") if Path(\"/content\").exists() else Path.cwd() / \"batting_notebook_runtime\" / \"2d_test\"\n", + "from getpass import getpass\n", + "GITHUB_TOKEN = getpass(\"GitHub token with read access to this repository: \") if PRIVATE_REPOSITORY else None\n", + "try:\n", + " if PRIVATE_REPOSITORY and not GITHUB_TOKEN:\n", + " raise ValueError(\"A token is required for this private repository\")\n", + " ENGINE_ROOT, SOURCE_CHECKOUT = checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)\n", + "finally:\n", + " del GITHUB_TOKEN\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-002" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Install the GPU worker\n", + "\n", + "Dependencies are installed in a separate environment. This does not build SAM, MHR or OpenSim. Installation must finish before continuing.\n" + ], + "id": "batting-2d-003" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import shutil\n", + "\n", + "if not shutil.which(\"nvidia-smi\"):\n", + " raise RuntimeError(\"Select Runtime > Change runtime type > GPU, then reconnect and rerun.\")\n", + "subprocess.run([\"nvidia-smi\"], check=True)\n", + "runtime = WORKSPACE_ROOT / \".runtime-api-2d\"\n", + "worker_path = runtime / \"bin/python\"\n", + "if runtime.exists() and (not worker_path.is_file() or subprocess.run(\n", + " [str(worker_path), \"-m\", \"pip\", \"--version\"], capture_output=True).returncode != 0):\n", + " shutil.rmtree(runtime)\n", + "if not worker_path.exists():\n", + " subprocess.run([sys.executable, \"-m\", \"venv\", \"--system-site-packages\", \"--without-pip\",\n", + " str(runtime)], check=True)\n", + "WORKER_PYTHON = str(worker_path)\n", + "WORKER_ENV = {**os.environ, \"MPLBACKEND\": \"Agg\", \"PYTHONUNBUFFERED\": \"1\",\n", + " \"PYTHONNOUSERSITE\": \"1\", \"PIP_REQUIRE_VIRTUALENV\": \"true\"}\n", + "WORKER_ENV.pop(\"PYTHONPATH\", None)\n", + "# Install locally even when Colab has inherited CPU ORT/numpy packages.\n", + "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n", + " \"--ignore-installed\", \"-r\", str(ENGINE_ROOT / \"requirements-api-gpu.txt\")],\n", + " env=WORKER_ENV, check=True)\n", + "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--ignore-installed\", \"--no-deps\", \"rtmlib==0.0.16\"],\n", + " env=WORKER_ENV, check=True)\n", + "def worker_command(module, *arguments):\n", + " return subprocess.run([WORKER_PYTHON, \"-m\", module, *map(str, arguments)],\n", + " cwd=ENGINE_ROOT, env=WORKER_ENV, check=True)\n", + "print(\"2D worker installed. Actual CUDA execution is checked in the next cell.\")\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-004" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Download the two models and check GPU execution\n", + "\n", + "Only the person detector and 2D pose model are downloaded, with verified hashes. This cell must report `ready: true`. It refuses to silently run on CPU.\n" + ], + "id": "batting-2d-005" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "MODEL_ROOT = WORKSPACE_ROOT / \"models\"\n", + "worker_command(\"tools.setup_api_models\", \"--output\", MODEL_ROOT)\n", + "PREFLIGHT_PATH = WORKSPACE_ROOT / \"gpu-preflight.json\"\n", + "worker_command(\"baseball_batting.api_worker\", \"--models\", MODEL_ROOT,\n", + " \"--preflight\", \"--output\", PREFLIGHT_PATH)\n", + "preflight = json.loads(PREFLIGHT_PATH.read_text())\n", + "if not preflight.get(\"ready\") or preflight.get(\"device\") != \"cuda\":\n", + " raise RuntimeError(\"Actual CUDA preflight did not pass.\")\n", + "print(json.dumps(preflight, indent=2))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-006" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Upload a video and set its recording information\n", + "\n", + "You can enter an existing `VIDEO_PATH` or leave it empty to upload. `HANDEDNESS` is the batter's own handedness. Set `VIEW=\"face_on\"` only for a known face-on recording and `CAMERA_STABILITY=\"fixed_verified\"` only when the camera stays still. Their defaults are unknown: ranges can still be inspected, but dependent events/numbers are withheld.\n", + "\n", + "Keep `TIMING={\"kind\":\"unknown\"}` unless capture timing is known. For an original unretimed recording use `{\"kind\":\"unretimed\",\"source\":\"original camera file; no retiming\"}`. For documented constant slow motion use `{\"kind\":\"constant_slowdown\",\"source\":\"documented camera/export settings\",\"factor\":8,\"all_captured_frames_retained\":True}` with the real factor. Playback FPS is not capture FPS. Timing numbers require a known constant capture rate of at least 60 FPS.\n", + "\n", + "Leave `SINGLE_SWING=False` for this multi-swing test. A new upload cell run creates a new job; rerunning only the analysis cell resumes the same job and verified observation cache. The current worker limits are 7,200 frames, 120 playback seconds and 8.3 megapixels per frame.\n" + ], + "id": "batting-2d-007" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from google.colab import files\n", + "import hashlib\n", + "import uuid\n", + "\n", + "VIDEO_PATH = \"\" # Or, for example: \"/content/IMG_1640.mp4\"\n", + "HANDEDNESS = \"right\" # \"right\", \"left\", or None if unknown.\n", + "VIEW = \"unknown\" # Change to \"face_on\" when known.\n", + "CAMERA_STABILITY = \"unknown\" # Change to \"fixed_verified\" when the camera stays still.\n", + "TIMING = {\"kind\": \"unknown\"}\n", + "SINGLE_SWING = False # False tests automatic separation of multiple swings.\n", + "\n", + "if not VIDEO_PATH:\n", + " uploaded = files.upload()\n", + " videos = [name for name in uploaded if name.lower().endswith((\".mp4\", \".mov\", \".mkv\", \".avi\", \".webm\"))]\n", + " if len(videos) != 1:\n", + " raise ValueError(\"Upload exactly one video containing the swings.\")\n", + " VIDEO_PATH = str(Path(videos[0]).resolve())\n", + " del uploaded\n", + "source_video = Path(VIDEO_PATH).resolve()\n", + "if not source_video.is_file():\n", + " raise ValueError(\"VIDEO_PATH does not exist. Upload the video or correct its path.\")\n", + "OPTIONS = {\"discipline\": \"hitting\", \"handedness\": HANDEDNESS, \"view\": VIEW,\n", + " \"camera_stability\": CAMERA_STABILITY, \"timing\": TIMING, \"single_swing\": SINGLE_SWING}\n", + "JOB_ROOT = WORKSPACE_ROOT / \"results\" / (\"session-\" + uuid.uuid4().hex[:12])\n", + "JOB_ROOT.mkdir(parents=True)\n", + "INPUT_VIDEO = JOB_ROOT / (\"input\" + source_video.suffix.lower())\n", + "shutil.copy2(source_video, INPUT_VIDEO)\n", + "(JOB_ROOT / \"request.json\").write_text(json.dumps(OPTIONS, indent=2))\n", + "(JOB_ROOT / \"source_checkout.json\").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))\n", + "checksum = hashlib.sha256()\n", + "with INPUT_VIDEO.open(\"rb\") as stream:\n", + " for block in iter(lambda: stream.read(1024 * 1024), b\"\"):\n", + " checksum.update(block)\n", + "(JOB_ROOT / \"run-context.json\").write_text(json.dumps({\"input_sha256\": checksum.hexdigest(),\n", + " \"source_video_name\": source_video.name, \"mode\": \"gpu_api_worker_2d_only\"}, indent=2))\n", + "print(\"Job:\", JOB_ROOT.name)\n", + "print(\"Recording options:\", json.dumps(OPTIONS, indent=2))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-008" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Run 2D analysis\n", + "\n", + "Progress shows decoding, 2D pose extraction, measurement calculation and completion. Setup time and video analysis are separate. The worker log is retained if the job fails. Stop this cell to interrupt a run; the observation cache is retained for a rerun in the same runtime.\n" + ], + "id": "batting-2d-009" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import signal\n", + "import time\n", + "\n", + "RUN_TIMEOUT_S = 1800\n", + "WORKER_LOG = JOB_ROOT / \"worker.log\"\n", + "(JOB_ROOT / \"error.json\").unlink(missing_ok=True)\n", + "(JOB_ROOT / \"progress.json\").unlink(missing_ok=True)\n", + "command = [WORKER_PYTHON, \"-m\", \"baseball_batting.api_worker\", \"--models\", str(MODEL_ROOT),\n", + " \"--job\", str(JOB_ROOT)]\n", + "started = time.monotonic()\n", + "with WORKER_LOG.open(\"w\") as log:\n", + " process = subprocess.Popen(command, cwd=ENGINE_ROOT, env=WORKER_ENV,\n", + " stdout=log, stderr=subprocess.STDOUT, start_new_session=True)\n", + " last_print, last_stage = 0., None\n", + " try:\n", + " while process.poll() is None:\n", + " elapsed = time.monotonic()-started\n", + " if elapsed > RUN_TIMEOUT_S:\n", + " raise TimeoutError(\"Analysis timed out; inspect worker.log and try a shorter recording.\")\n", + " progress_path = JOB_ROOT / \"progress.json\"\n", + " progress = json.loads(progress_path.read_text()) if progress_path.exists() else {\"stage\": \"starting\"}\n", + " if progress[\"stage\"] != last_stage or elapsed-last_print >= 15:\n", + " print(f\"{elapsed:.0f}s | {progress['stage']} | \"\n", + " f\"{progress.get('completed_frames', 0)}/{progress.get('total_frames') or '?'} frames\", flush=True)\n", + " last_print, last_stage = elapsed, progress[\"stage\"]\n", + " time.sleep(2)\n", + " finally:\n", + " if process.poll() is None:\n", + " os.killpg(process.pid, signal.SIGTERM)\n", + " try:\n", + " process.wait(timeout=5)\n", + " except subprocess.TimeoutExpired:\n", + " os.killpg(process.pid, signal.SIGKILL)\n", + " process.wait()\n", + "if process.returncode != 0:\n", + " print(WORKER_LOG.read_text(errors=\"replace\")[-8000:])\n", + " raise RuntimeError(\"2D analysis failed. The worker log above contains the actual error.\")\n", + "result = json.loads((JOB_ROOT / \"result.json\").read_text())\n", + "print(f\"Finished in {time.monotonic()-started:.1f}s. Detected {len(result['pose_track']['reps'])} swing candidates.\")\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-010" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Inspect swing ranges and measurements\n", + "\n", + "The range table uses **video playback positions** for locating clips. Those positions are not physical swing timing. `events_ms` in the coach payload uses the separate physical capture clock when known. `capture.ok:false` asks for a better recording; missing numbers have reasons. All available numbers are marked `est`.\n", + "\n", + "Check the number of detected ranges against the swings you can actually see. A zero-candidate result means the algorithm did not separate any swings; it does not prove the video contains none. The first ten reps are displayed below; the JSON download contains all results.\n" + ], + "id": "batting-2d-011" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import HTML, Video, display\n", + "import html\n", + "\n", + "def table(headers, rows):\n", + " head = \"\".join(\"\" + html.escape(str(value)) + \"\" for value in headers)\n", + " body = \"\".join(\"\" + \"\".join(\"\" + html.escape(str(value)) + \"\" for value in row) + \"\" for row in rows)\n", + " display(HTML(\"\" + head + \"\" + body + \"
    \"))\n", + "\n", + "track = result[\"pose_track\"]\n", + "print(\"Swing candidates:\", len(track[\"reps\"]))\n", + "print(\"Capture check:\", result[\"measurements\"][\"capture\"])\n", + "print(\"Real capture FPS:\", track[\"video\"][\"capture_fps\"])\n", + "for warning in result[\"warnings\"]: print(\"\u2022\", warning)\n", + "playback = track[\"frames\"][\"playback_t_s\"]\n", + "def position(index):\n", + " return round(playback[index]-playback[0], 3) if playback[index] is not None and playback[0] is not None else \"unknown\"\n", + "table([\"Swing\", \"First frame\", \"Last frame (included)\", \"Video start (s)\", \"Video end (s)\", \"Boundary method\"],\n", + " [[rep[\"rep\"], rep[\"start_frame\"], rep[\"end_frame\"], position(rep[\"start_frame\"]),\n", + " position(rep[\"end_frame\"]), rep[\"boundary_method\"]] for rep in track[\"reps\"]])\n", + "for rep in result[\"measurements\"][\"reps\"][:10]:\n", + " print(\"Swing\", rep[\"rep\"], \"| estimated physical events_ms:\", rep[\"events_ms\"])\n", + " table([\"Measurement\", \"Value\", \"Unit\", \"Confidence\", \"Explanation\"],\n", + " [[m[\"key\"], m[\"value\"], m[\"unit\"], m[\"confidence\"], m[\"note\"]] for m in rep[\"metrics\"]])\n", + "print(\"Coach JSON:\", JOB_ROOT / \"coach-payload.json\")\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-012" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. Watch previews of the detected swings\n", + "\n", + "These inspection clips show raw model points and estimated event labels. They preserve playback presentation positions relative to each clip's first frame. They are resized to at most 960 pixels wide, have no audio, and are separate from the API's measurement output. Preview rendering does not alter measurement results. Invalid source timestamps cause a preview to be withheld rather than retimed.\n", + "\n", + "The default limit is ten clips; increase it up to 100 if needed. Inspect each range for missed preparation, truncated finish, merged swings or unrelated movements.\n" + ], + "id": "batting-2d-013" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "PREVIEW_LIMIT = 10\n", + "PREVIEW_ROOT = JOB_ROOT / \"previews\"\n", + "worker_command(\"tools.preview_swing_ranges\", \"--video\", INPUT_VIDEO,\n", + " \"--result\", JOB_ROOT / \"result.json\", \"--output\", PREVIEW_ROOT,\n", + " \"--max-clips\", PREVIEW_LIMIT)\n", + "previews = json.loads((PREVIEW_ROOT / \"previews.json\").read_text())\n", + "for preview in previews[\"previews\"]:\n", + " print(\"Swing\", preview[\"rep\"], \"| frames\", preview[\"start_frame\"], \"to\", preview[\"end_frame\"])\n", + " if preview[\"status\"] == \"complete\":\n", + " display(Video(str(PREVIEW_ROOT / preview[\"file\"]), embed=True, width=720))\n", + " else:\n", + " print(\"Preview unavailable:\", preview[\"reason\"])\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-014" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. Download the test results\n", + "\n", + "The ZIP contains `result.json`, `coach-payload.json`, recording options, source commit/input hash, progress, worker log and any preview clips. It excludes the original recording, repository credentials, observation cache and models. Download before Colab deletes the runtime. Share this ZIP to investigate a bad result; retain the original recording separately.\n" + ], + "id": "batting-2d-015" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import zipfile\n", + "\n", + "ARCHIVE_PATH = WORKSPACE_ROOT / (JOB_ROOT.name + \"-2d-results.zip\")\n", + "names = (\"result.json\", \"coach-payload.json\", \"request.json\", \"source_checkout.json\",\n", + " \"run-context.json\", \"progress.json\", \"worker.log\", \"error.json\")\n", + "with zipfile.ZipFile(ARCHIVE_PATH, \"w\", zipfile.ZIP_DEFLATED) as archive:\n", + " for name in names:\n", + " path = JOB_ROOT / name\n", + " if path.is_file(): archive.write(path, name)\n", + " manifest_path = JOB_ROOT / \"previews/previews.json\"\n", + " if manifest_path.is_file():\n", + " archive.write(manifest_path, \"previews/previews.json\")\n", + " manifest = json.loads(manifest_path.read_text())\n", + " for preview in manifest[\"previews\"]:\n", + " if preview[\"status\"] == \"complete\":\n", + " path = JOB_ROOT / \"previews\" / preview[\"file\"]\n", + " archive.write(path, path.relative_to(JOB_ROOT))\n", + "print(\"Saved:\", ARCHIVE_PATH)\n", + "files.download(str(ARCHIVE_PATH))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-2d-016" + } + ] +} diff --git a/notebooks/batting_engine.ipynb b/notebooks/batting_engine.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..5f270898bdbb28cccae3d52935a4f46cee928a28 --- /dev/null +++ b/notebooks/batting_engine.ipynb @@ -0,0 +1,489 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.11" + }, + "colab": { + "name": "batting_engine.ipynb", + "provenance": [] + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Baseball batting engine\n", + "\n", + "One batter / one swing. The first code cell fetches the engine from the configured GitHub repository and records its full commit SHA. All setup code is readable. For the private repository, enter a GitHub token in the hidden prompt; it needs repository Contents read access. The token is passed temporarily to Git and is not saved in source/configuration/results.\n", + "\n", + "**Engine implementation:** streaming body/bat/ball observations, shared-shape MHR trajectory fitting, project-owned 35-DOF OpenSim IK, independent calibrated bat reconstruction, event candidates/review, qualified-checkpoint inference, training/evaluation, measurement gates, sourced educational hypotheses, history and recoverable exports. GPU/provider-dependent stages return explicit partial results when unavailable. Model training and reference/coaching validation require suitable data; a successful run does not establish accuracy.\n", + "\n", + "Run the cells in order. Physical time is unknown by default. Enter documented capture timing before requesting physical durations or velocities. A successful run is not evidence of baseball measurement accuracy.\n" + ], + "id": "batting-000" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "\"\"\"Readable GitHub bootstrap, copied into the first Colab code cell by the builder.\"\"\"\n", + "from pathlib import Path\n", + "from contextlib import contextmanager\n", + "import base64\n", + "import json\n", + "import os\n", + "import re\n", + "import subprocess\n", + "import sys\n", + "\n", + "\n", + "def _git(directory, *arguments, auth_env=None):\n", + " environment = {**os.environ, \"GIT_TERMINAL_PROMPT\": \"0\", **(auth_env or {})}\n", + " result = subprocess.run(\n", + " [\"git\", \"-C\", str(directory), *arguments], text=True,\n", + " stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,\n", + " )\n", + " if result.returncode:\n", + " detail = result.stderr.strip() or result.stdout.strip() or \"Git returned no error detail\"\n", + " secret = (auth_env or {}).get(\"BATTING_GITHUB_TOKEN\")\n", + " if secret:\n", + " encoded = base64.b64encode(f\"x-access-token:{secret}\".encode()).decode()\n", + " detail = detail.replace(secret, \"[REDACTED]\").replace(encoded, \"[REDACTED]\")\n", + " detail = re.sub(r\"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+\", \"[REDACTED]\", detail)\n", + " raise RuntimeError(f\"Git failed (exit {result.returncode}):\\n{detail[-4000:]}\") from None\n", + " return result.stdout.strip()\n", + "\n", + "\n", + "@contextmanager\n", + "def _github_credentials(token, scope=\"https://github.com/\"):\n", + " if not token:\n", + " yield {}\n", + " return\n", + " # Git reads these settings only for this subprocess; no token is stored in its URL/config.\n", + " count = int(os.environ.get(\"GIT_CONFIG_COUNT\", \"0\"))\n", + " encoded = base64.b64encode(f\"x-access-token:{token}\".encode()).decode()\n", + " yield {\n", + " \"GIT_CONFIG_COUNT\": str(count + 2),\n", + " f\"GIT_CONFIG_KEY_{count}\": f\"http.{scope}.extraHeader\",\n", + " f\"GIT_CONFIG_VALUE_{count}\": \"\",\n", + " f\"GIT_CONFIG_KEY_{count + 1}\": f\"http.{scope}.extraHeader\",\n", + " f\"GIT_CONFIG_VALUE_{count + 1}\": f\"Authorization: Basic {encoded}\",\n", + " \"BATTING_GITHUB_TOKEN\": token,\n", + " }\n", + "\n", + "\n", + "def checkout_github(repository_url, revision, workspace, token=None):\n", + " \"\"\"Fetch an explicit ref and stop before replacing modified source files.\"\"\"\n", + " if token is not None:\n", + " token = token.strip()\n", + " if not token:\n", + " raise ValueError(\"Enter a token with read access to this repository\")\n", + " if not re.fullmatch(r\"https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\\.git)?/?\", repository_url):\n", + " raise ValueError(\"Use an HTTPS GitHub repository URL without credentials or query parameters\")\n", + " if any(part in {\".\", \"..\"} for part in repository_url.split(\"/\")[3:]):\n", + " raise ValueError(\"Use an owner/repository GitHub URL\")\n", + " if not revision or revision.startswith(\"-\") or any(c.isspace() for c in revision):\n", + " raise ValueError(\"Set a branch, tag, or full commit SHA\")\n", + " workspace = Path(workspace).resolve()\n", + " source = workspace / \"source\"\n", + " workspace.mkdir(parents=True, exist_ok=True)\n", + " with _github_credentials(token) as authentication:\n", + " options = (\"-c\", \"credential.helper=\") if token else ()\n", + " fresh_checkout = False\n", + " if not (source / \".git\").exists():\n", + " if source.exists() and any(source.iterdir()):\n", + " raise ValueError(f\"Source directory is not an empty Git checkout: {source}\")\n", + " _git(workspace, *options, \"clone\", \"--no-checkout\", \"--depth=1\", repository_url,\n", + " str(source), auth_env=authentication)\n", + " fresh_checkout = True\n", + " if _git(source, \"config\", \"--get\", \"remote.origin.url\") != repository_url:\n", + " raise ValueError(\"Existing checkout uses a different repository; choose another workspace\")\n", + " # A newly cloned --no-checkout repository has no populated index yet.\n", + " if not fresh_checkout and _git(source, \"status\", \"--porcelain\", \"--untracked-files=no\"):\n", + " raise ValueError(\"Source has local edits; save them or choose another workspace before updating\")\n", + " _git(source, *options, \"fetch\", \"--depth=1\", \"origin\", revision, auth_env=authentication)\n", + " commit = _git(source, \"rev-parse\", \"FETCH_HEAD^{commit}\")\n", + " if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) and commit.lower() != revision.lower():\n", + " raise ValueError(\"Fetched commit does not match the requested SHA\")\n", + " _git(source, \"checkout\", \"--quiet\", \"--detach\", commit)\n", + " required = [\"baseball_batting/cli.py\", \"requirements-core.txt\", \"configs/resources.yaml\"]\n", + " if not all((source / name).is_file() for name in required):\n", + " raise ValueError(\"Selected repository revision does not contain the batting engine\")\n", + " record = {\"repository_url\": repository_url, \"requested_revision\": revision, \"commit_sha\": commit}\n", + " (workspace / \"source_checkout.json\").write_text(json.dumps(record, indent=2))\n", + " print(\"Engine source:\", source)\n", + " print(\"Resolved commit:\", commit, \"(use this SHA as REVISION to reproduce this run)\")\n", + " return source, record\n", + "\n", + "\n", + "REPOSITORY_URL = 'https://github.com/usmanthesuper/baseball-engine.git' # Set to your published engine repository.\n", + "REVISION = 'main' # Use a full commit SHA for a reproducible run.\n", + "PRIVATE_REPOSITORY = True\n", + "WORKSPACE_ROOT = Path(\"/content/baseball_batting_engine\") if Path(\"/content\").exists() else Path.cwd() / \"batting_notebook_runtime\"\n", + "if not REPOSITORY_URL:\n", + " raise ValueError(\"Set REPOSITORY_URL to the GitHub repository containing the engine\")\n", + "from getpass import getpass\n", + "GITHUB_TOKEN = getpass(\"GitHub token with read access to this repository: \") if PRIVATE_REPOSITORY else None\n", + "try:\n", + " if PRIVATE_REPOSITORY and not GITHUB_TOKEN:\n", + " raise ValueError(\"A token is required for this private repository\")\n", + " ENGINE_ROOT, SOURCE_CHECKOUT = checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)\n", + "finally:\n", + " del GITHUB_TOKEN\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-001" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Install a worker environment\n", + "\n", + "The notebook kernel orchestrates subprocesses. Core dependencies run in a separate virtual environment.\n", + "`cpu_reference` uses the separately recorded CPU ONNX profile. `gpu_candidate` installs the ONNX GPU pin with CUDA/cuDNN libraries and requires a GPU runtime. Vision preflight must pass before automatic analysis starts. The full GPU/SAM profile still requires Colab qualification. No silent profile substitution occurs.\n" + ], + "id": "batting-002" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "import shutil\n", + "\n", + "PROFILE = \"cpu_reference\" # Change explicitly to \"gpu_candidate\" for GPU preflight.\n", + "# PROFILE = \"gpu_candidate\" # Change explicitly to \"gpu_candidate\" for GPU preflight.\n", + "assert PROFILE in {\"cpu_reference\", \"gpu_candidate\"}\n", + "if PROFILE == \"gpu_candidate\" and (not shutil.which(\"nvidia-smi\") or\n", + " subprocess.run([\"nvidia-smi\"], capture_output=True).returncode != 0):\n", + " raise RuntimeError(\"Select Runtime > Change runtime type > GPU in Colab, or use cpu_reference\")\n", + "runtime = WORKSPACE_ROOT / (\".runtime-\" + PROFILE)\n", + "\n", + "# Remove the broken environment left by the failed run\n", + "if runtime.exists() and subprocess.run([str(runtime / \"bin/python\"), \"-m\", \"pip\", \"--version\"],\n", + " capture_output=True).returncode != 0:\n", + " shutil.rmtree(runtime)\n", + "\n", + "if not (runtime / \"bin/python\").exists():\n", + " # Skip ensurepip; Colab's system pip is visible through --system-site-packages\n", + " subprocess.run([sys.executable, \"-m\", \"venv\", \"--system-site-packages\", \"--without-pip\",\n", + " str(runtime)], check=True)\n", + "WORKER_PYTHON = str(runtime / \"bin/python\")\n", + "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n", + " \"-r\", str(ENGINE_ROOT / \"requirements-core.txt\")], check=True)\n", + "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--no-deps\", \"rtmlib==0.0.16\"], check=True)\n", + "onnx_package = \"onnxruntime==1.23.2\" if PROFILE == \"cpu_reference\" else \"onnxruntime-gpu[cuda,cudnn]==1.26.0\"\n", + "# Force a local ONNX installation so inherited Colab packages cannot shadow this profile.\n", + "install = subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n", + " \"--force-reinstall\", \"-c\", str(ENGINE_ROOT / \"requirements-core.txt\"),\n", + " onnx_package, \"requests==2.32.5\", \"tqdm==4.67.1\"])\n", + "print(\"ONNX installation:\", \"installed; still needs preflight\" if install.returncode == 0 else \"unavailable; automatic model branches will abstain\")\n", + "def engine_command(*arguments, check=True):\n", + " return subprocess.run([WORKER_PYTHON, \"-m\", \"baseball_batting.cli\", *map(str,arguments)],\n", + " cwd=ENGINE_ROOT, check=check)\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-003" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Persistent output directory\n", + "\n", + "Local `/content` is scratch storage. For cross-session resume, mount Drive and set `OUTPUT_ROOT` to a persistent directory. Otherwise download the result archive before the runtime disappears. Source videos are not included in result archives.\n" + ], + "id": "batting-004" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "USE_DRIVE = False\n", + "if USE_DRIVE:\n", + " from google.colab import drive\n", + " drive.mount(\"/content/drive\")\n", + "OUTPUT_ROOT = Path(\"/content/drive/MyDrive/baseball_batting_results\") if USE_DRIVE else WORKSPACE_ROOT / \"artifacts\"\n", + "OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)\n", + "print(\"Durable mounted Drive\" if USE_DRIVE else \"Scratch output; export to preserve across sessions:\", OUTPUT_ROOT)\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-005" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download explicit model artifacts\n", + "\n", + "Downloads happen here, never inside inference. Each artifact's source and SHA-256 are recorded. Models can be reused across runs. If access fails, reviewed annotations and partial exports still work.\n" + ], + "id": "batting-006" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "DOWNLOAD_MODELS = True\n", + "artifacts = {}\n", + "if DOWNLOAD_MODELS:\n", + " for resource in (\"body_pose\", \"person_detector\", \"object_detector\"):\n", + " status = engine_command(\"fetch\", resource, \"--registry\", ENGINE_ROOT / \"configs/resources.yaml\",\n", + " \"--output\", WORKSPACE_ROOT / \"downloads\", check=False)\n", + " record = WORKSPACE_ROOT / \"downloads\" / resource / \"resource.json\"\n", + " if status.returncode == 0 and record.exists():\n", + " artifacts[resource] = json.loads(record.read_text())[\"artifact_path\"]\n", + " else:\n", + " print(resource, \"unavailable; branch will return an explicit reason\")\n", + "config = {\n", + " \"mode\": \"automatic\", \"chunk_size\": 64,\n", + " \"device\": \"cpu\" if PROFILE == \"cpu_reference\" else \"cuda\",\n", + " \"body_pose_path\": artifacts.get(\"body_pose\"),\n", + " \"person_detector_path\": artifacts.get(\"person_detector\"),\n", + " \"object_detector_path\": artifacts.get(\"object_detector\"),\n", + " \"body3d_enabled\": False, \"export_video\": True,\n", + "}\n", + "CONFIG_PATH = WORKSPACE_ROOT / \"engine-config.json\"\n", + "CONFIG_PATH.write_text(json.dumps(config, indent=2))\n", + "engine_command(\"preflight\", \"--config\", CONFIG_PATH, \"--output\", OUTPUT_ROOT / \"preflight\", \"--require-vision\")\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-007" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Full GPU worker and body reconstruction\n", + "\n", + "For the 3D body stages choose a Colab GPU runtime and `PROFILE=\"gpu_candidate\"` above, then set `BUILD_FULL_WORKER=True`. This explicit setup creates Python 3.11, pins SAM/MS-TCN++ sources, installs the candidate CUDA/OpenSim profile, and downloads SAM assets through normal Hugging Face access. It can take substantial setup time and disk space in a free session. Add `HF_TOKEN` to Colab Secrets after obtaining normal access to `facebook/sam-3d-body-vith`; credentials are not written into engine configuration or reports.\n", + "\n", + "CPU mode remains useful for projected analysis. Physical bat metrics additionally require documented independent bat geometry/calibration; body-estimated wrist depth is not enough. Trained heads remain inactive until reviewed data and held-out qualification exist.\n" + ], + "id": "batting-008" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "BUILD_FULL_WORKER = False # Set True with a GPU runtime and accessible SAM assets.\n", + "if BUILD_FULL_WORKER:\n", + " if PROFILE != \"gpu_candidate\":\n", + " raise ValueError('Set PROFILE=\"gpu_candidate\", select a Colab GPU runtime, and rerun setup first')\n", + " import os\n", + " setup_environment = dict(os.environ)\n", + " try:\n", + " from google.colab import userdata\n", + " hf_secret = userdata.get(\"HF_TOKEN\")\n", + " if hf_secret:\n", + " setup_environment[\"HF_TOKEN\"] = hf_secret\n", + " del hf_secret\n", + " except Exception:\n", + " print(\"Using existing provider login/environment if available\")\n", + " status = subprocess.run([sys.executable, str(ENGINE_ROOT / \"tools/setup_full_worker.py\"),\n", + " \"--workspace\", str(WORKSPACE_ROOT), \"--download-models\"],\n", + " env=setup_environment)\n", + " setup_environment.pop(\"HF_TOKEN\", None)\n", + " full_record = json.loads((WORKSPACE_ROOT / \"full-worker.json\").read_text())\n", + " if status.returncode == 0:\n", + " config.update({name: full_record[name] for name in\n", + " (\"sam_repo\", \"sam_checkpoint\", \"sam_config\", \"mhr_path\", \"mstcn_repo\")})\n", + " full_python = full_record[\"worker_python\"]\n", + " config.update(body3d_enabled=True, temporal3d_enabled=True, anatomy_enabled=True, device=\"cuda\")\n", + " config[\"stage_python\"] = {stage: full_python for stage in\n", + " (\"observations\", \"body3d\", \"temporal3d\", \"anatomy\", \"learned_events\")}\n", + " CONFIG_PATH.write_text(json.dumps(config, indent=2))\n", + " subprocess.run([full_python, \"-m\", \"baseball_batting.cli\", \"preflight\", \"--config\", str(CONFIG_PATH),\n", + " \"--output\", str(OUTPUT_ROOT / \"preflight-full-vision\"), \"--require-vision\"], cwd=ENGINE_ROOT, check=True)\n", + " subprocess.run([full_python, \"-m\", \"baseball_batting.cli\", \"preflight-optional\", \"--config\", str(CONFIG_PATH),\n", + " \"--output\", str(OUTPUT_ROOT / \"preflight-full\")], cwd=ENGINE_ROOT, check=True)\n", + " optional = json.loads((OUTPUT_ROOT / \"preflight-full\" / \"optional_runtime_profile.json\").read_text())[\"tests\"]\n", + " required = (\"torch\", \"mhr\", \"anatomy\")\n", + " if \"torch_mhr\" in optional or any(optional.get(name, {}).get(\"status\") != \"ready\" for name in required):\n", + " raise RuntimeError(\"Full-worker component preflight failed; inspect preflight-full/optional_runtime_profile.json\")\n", + " else:\n", + " raise RuntimeError(\"Full worker setup failed: \" + str(full_record.get(\"reason\")))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-009" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Select a recording and metadata\n", + "\n", + "Upload an original video or enter its existing path. Set `GENERATED_FIXTURE=True` to test integration with a generated video first. That fixture does not validate real-world accuracy.\n", + "\n", + "Use `timing.kind=\"unknown\"` unless the original capture clock is documented. For an unretimed original: `{\"kind\":\"unretimed\",\"source\":\"description of capture evidence\"}`. For documented constant slowdown, also provide `factor` and `all_captured_frames_retained=true`. Height is not camera calibration.\n" + ], + "id": "batting-010" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "GENERATED_FIXTURE = False\n", + "VIDEO_PATH = \"\" # Alternatively enter an existing video path.\n", + "if GENERATED_FIXTURE:\n", + " VIDEO_PATH = str(WORKSPACE_ROOT / \"generated_fixture.mp4\")\n", + " subprocess.run([WORKER_PYTHON, str(ENGINE_ROOT / \"tools/make_fixture.py\"), VIDEO_PATH], check=True)\n", + "elif not VIDEO_PATH:\n", + " from google.colab import files\n", + " uploaded = files.upload()\n", + " videos = [name for name in uploaded if name.lower().endswith((\".mp4\", \".mov\", \".mkv\", \".avi\", \".webm\"))]\n", + " assert len(videos) == 1, \"Select exactly one video\"\n", + " VIDEO_PATH = str(Path(videos[0]).resolve())\n", + "METADATA = {\n", + " \"player_id\": \"player-001\", \"session_id\": \"session-001\", \"handedness\": \"right\",\n", + " \"height_m\": None, \"bat_length_m\": None,\n", + " \"consent\": \"not_supplied\", \"camera_stability\": \"unknown\", \"timing\": {\"kind\": \"unknown\"},\n", + " \"intended_use\": \"research\"\n", + "}\n", + "METADATA_PATH = WORKSPACE_ROOT / \"capture-metadata.json\"\n", + "METADATA_PATH.write_text(json.dumps(METADATA, indent=2))\n", + "SESSION_DIRECTORY = OUTPUT_ROOT / METADATA[\"session_id\"]\n", + "# Repeat preflight in the actual observation worker if configuration was edited.\n", + "vision_python = config.get(\"stage_python\", {}).get(\"observations\", WORKER_PYTHON)\n", + "subprocess.run([vision_python, \"-m\", \"baseball_batting.cli\", \"preflight\", \"--config\", str(CONFIG_PATH),\n", + " \"--output\", str(OUTPUT_ROOT / \"preflight-analysis\"), \"--require-vision\"], cwd=ENGINE_ROOT, check=True)\n", + "engine_command(\"analyze\", VIDEO_PATH, \"--config\", CONFIG_PATH, \"--metadata\", METADATA_PATH,\n", + " \"--output\", SESSION_DIRECTORY)\n", + "(SESSION_DIRECTORY / \"source_checkout.json\").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-011" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Inspect results\n", + "\n", + "Every unavailable metric has a null value and reason. JSON contains evidence, timing, versions and branch status; `curves.npz` stores continuous projected curves. `source_checkout.json` records the GitHub URL, requested revision and resolved commit. An annotated MP4 keeps source presentation timing when the source timestamps are encodable. Audio is not included in the annotated export.\n" + ], + "id": "batting-012" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "from IPython.display import display, HTML, Video\n", + "result = json.loads((SESSION_DIRECTORY / \"result.json\").read_text())\n", + "display(HTML((SESSION_DIRECTORY / \"report.html\").read_text()))\n", + "if (SESSION_DIRECTORY / \"annotated.mp4\").exists():\n", + " display(Video(str(SESSION_DIRECTORY / \"annotated.mp4\"), embed=True))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-013" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Optional operator review\n", + "\n", + "Review uses oriented-image pixels. Labels are separate files tied to the exact input hash. For a frame, enter for example:\n", + "`{\"knob\":[x,y],\"barrel\":[x,y],\"ball\":[x,y],\"landmarks\":{\"left_wrist\":[x,y]},\"crop\":[x1,y1,x2,y2]}`.\n", + "Confirm an event only if visible evidence supports it. Event example:\n", + "`[{\"type\":\"contact\",\"state\":\"confirmed\",\"frame_interval\":[12,13],\"evidence_frames\":[12,13,14],\"evidence_description\":\"Visible interaction followed by outgoing ball\"}]`.\n", + "Unknown remains unknown. Save before moving to another frame. Notebook widget use does not run a web service.\n" + ], + "id": "batting-014" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "RUN_REVIEW = False\n", + "ANNOTATIONS_PATH = OUTPUT_ROOT / (METADATA[\"session_id\"] + \"-reviewed.json\")\n", + "if RUN_REVIEW:\n", + " sys.path.insert(0, str(ENGINE_ROOT))\n", + " from baseball_batting.review import show_review_widget\n", + " show_review_widget(VIDEO_PATH, result[\"capture\"], ANNOTATIONS_PATH, annotator=\"operator-001\")\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-015" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "APPLY_REVIEWED_LABELS = False\n", + "if APPLY_REVIEWED_LABELS:\n", + " assert ANNOTATIONS_PATH.exists(), \"Save labels first\"\n", + " config[\"mode\"] = \"operator_reviewed\"\n", + " config[\"annotations_path\"] = str(ANNOTATIONS_PATH)\n", + " CONFIG_PATH.write_text(json.dumps(config, indent=2))\n", + " engine_command(\"analyze\", VIDEO_PATH, \"--config\", CONFIG_PATH, \"--metadata\", METADATA_PATH,\n", + " \"--output\", SESSION_DIRECTORY)\n", + " result = json.loads((SESSION_DIRECTORY / \"result.json\").read_text())\n", + " display(HTML((SESSION_DIRECTORY / \"report.html\").read_text()))\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-016" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dataset, training and evaluation commands\n", + "\n", + "The same backend CLI builds reviewed datasets and trains both custom heads. Dataset indexes supply `video_path`, `annotations_path`, `player_id`, `session_id`, and `split` (train/validation/test); event examples also supply `analysis_directory` and reviewed `phases`. Athletes/sessions cannot cross splits.\n", + "\n", + "```text\n", + "python -m baseball_batting.cli dataset index.json --kind endpoint_cnn --output endpoint-data\n", + "python -m baseball_batting.cli train endpoint-data --kind endpoint_cnn --output endpoint-model --epochs 30\n", + "python -m baseball_batting.cli evaluate-checkpoint endpoint-data endpoint-model --thresholds your-preregistered-gates.json --scope your-task-and-view\n", + "```\n", + "\n", + "For phases replace kind with `mstcn_events` and pass the pinned `--mstcn-repo` to training/evaluation. Configure checkpoint and manifest paths only after qualification passes. `configs/training-gates.example.json` is deliberately inactive until task-specific requirements are preregistered. Independent biomechanics evaluation uses `evaluate-reference`; distribution tables alone cannot validate phone recordings. See `docs/TRAINING.md` and `docs/VALIDATION.md`.\n" + ], + "id": "batting-017" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Download result archive\n", + "\n", + "Re-running analysis reuses verified observation chunks with matching hashes. To resume in another session, set `REVISION` to the full commit SHA in the exported `source_checkout.json`, reimport the result archive, use the same source video, metadata, model artifacts and profile, and rerun. Incompatible changes invalidate dependent stages.\n" + ], + "id": "batting-018" + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "ARCHIVE_PATH = OUTPUT_ROOT / (METADATA[\"session_id\"] + \"-results.zip\")\n", + "engine_command(\"export\", SESSION_DIRECTORY, ARCHIVE_PATH)\n", + "if \"google.colab\" in sys.modules or Path(\"/content\").exists():\n", + " from google.colab import files\n", + " files.download(str(ARCHIVE_PATH))\n", + "else:\n", + " print(ARCHIVE_PATH)\n" + ], + "execution_count": null, + "outputs": [], + "id": "batting-019" + } + ] +} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1a24189ccd291a9f484aaebbd9587e04cfc30a6c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,28 @@ +[build-system] +requires = ["setuptools==75.8.0", "wheel==0.45.1"] +build-backend = "setuptools.build_meta" + +[project] +name = "baseball-batting-engine" +version = "0.2.0" +description = "Evidence-linked batting video analysis with explicit partial-result behavior" +requires-python = ">=3.10" +dependencies = [ + "numpy==2.2.6", "scipy==1.15.3", "opencv-python-headless==4.11.0.86", + "av==16.1.0", "PyYAML==6.0.2" +] + +[project.optional-dependencies] +test = ["pytest==8.4.2", "nbformat==5.10.4"] +api = ["fastapi==0.143.0", "starlette==1.7.0", "pydantic==2.14.0", "uvicorn==0.54.0", "python-multipart==0.0.32"] +api-test = ["httpx==0.28.1"] + +[project.scripts] +batting-engine = "baseball_batting.cli:main" + +[tool.setuptools.packages.find] +include = ["baseball_batting*"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-q" diff --git a/requirements-api-gpu.txt b/requirements-api-gpu.txt new file mode 100644 index 0000000000000000000000000000000000000000..2dae34361e7ab21c76be077485d611946b0efd5a --- /dev/null +++ b/requirements-api-gpu.txt @@ -0,0 +1,9 @@ +-r requirements-core.txt +-r requirements-api.txt +# CUDA runtime libraries are supplied by the NVIDIA pip extras. No PyTorch/SAM. +onnxruntime-gpu[cuda,cudnn]==1.26.0 +requests==2.32.5 +tqdm==4.67.1 +loguru==0.7.3 +# RTMLib is installed separately with --no-deps to avoid installing CPU ORT and +# multiple conflicting OpenCV packages. Only its preprocessing/decoder is used. diff --git a/requirements-api.txt b/requirements-api.txt new file mode 100644 index 0000000000000000000000000000000000000000..582b3c0bb584cd6bf8033c38b2f03bb094dca9e5 --- /dev/null +++ b/requirements-api.txt @@ -0,0 +1,14 @@ +# HTTP service dependencies; separate from Colab/core installation. +fastapi==0.143.0 +starlette==1.7.0 +pydantic==2.14.0 +uvicorn==0.54.0 +python-multipart==0.0.32 +anyio==4.15.1 +click==8.5.0 +h11==0.16.0 +opentelemetry-api==1.45.1 +annotated-doc==0.0.5 +annotated-types==0.8.0 +typing-inspection==0.4.4 +typing_extensions==4.16.0 diff --git a/requirements-core.txt b/requirements-core.txt new file mode 100644 index 0000000000000000000000000000000000000000..ccc6b5b61ec8f6acec3e475d1029c7241ce39977 --- /dev/null +++ b/requirements-core.txt @@ -0,0 +1,5 @@ +numpy==2.2.6 +scipy==1.15.3 +opencv-python-headless==4.11.0.86 +av==16.1.0 +PyYAML==6.0.2 diff --git a/requirements-sam.txt b/requirements-sam.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4de22e612eef88bba59949d1d935a27900bef40 --- /dev/null +++ b/requirements-sam.txt @@ -0,0 +1,33 @@ +# Selected candidate direct dependencies. The setup exports the resolved freeze. +pytorch-lightning==2.5.5 +torchmetrics==1.8.2 +torchvision==0.24.1 +einops==0.8.1 +timm==1.0.22 +yacs==0.1.8 +scikit-image==0.25.2 +roma==1.5.4 +hydra-core==1.3.2 +hydra-submitit-launcher==1.2.0 +hydra-colorlog==1.2.0 +pyrootutils==1.0.4 +webdataset==1.0.2 +fvcore==0.1.5.post20221221 +iopath==0.1.10 +optree==0.17.0 +loguru==0.7.3 +xtcocotools==1.14.3 +pycocotools==2.0.10 +pandas==2.3.3 +rich==14.2.0 +joblib==1.5.2 +networkx==3.2.1 +huggingface-hub==0.35.3 +wandb==0.22.2 +tensorboard==2.20.0 +appdirs==1.4.4 +dill==0.4.0 +jsonlines==4.0.0 +chump==1.6.0 +seaborn==0.13.2 +pyrender==0.1.45 diff --git a/rules/coaching_rules.yaml b/rules/coaching_rules.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d3f4f1350637a100355abbc479eae62d044bdd80 --- /dev/null +++ b/rules/coaching_rules.yaml @@ -0,0 +1,29 @@ +version: '1.0' +coaching_mode: evidence_linked_experimental +expert_review: not_reviewed +rules: + - id: tee_measurement_repeatability + version: '1.0' + required_metrics: [left_knee_projected_flexion_at_contact, right_knee_projected_flexion_at_contact] + required_events: [contact] + geometry_sources: [oriented_image_projection] + validation_scopes: [reference-validation-pending] + maximum_sensitivity: null + minimum_trials: 3 + context: {swing_task: tee} + source: + title: "USA Baseball: Cuddyer's Corner — Using the Tee" + url: https://www.usabaseball.com/video/cuddyer-s-corner-using-the-tee + context: general tee practice + supports_intervention: true + strength: coaching_instruction_not_effectiveness_trial + evidence_strength: educational_source_and_descriptive_trials_not_causal_validation + interpretation: Comparable tee recordings provide a baseline for studying repeatability. No knee-angle target or persistent fault is established. + exercise: + name: Tee practice and repeat recording + instruction: Review the linked USA Baseball tee-work lesson and record comparable tee swings using the same setup. + objective: Compare within-player dispersion of the supported projected knee measures across matched recordings; do not optimize toward a universal angle. +notes: + - Current feedback consists of descriptive measurements only. + - The educational tee rule has no asserted corrective benefit and is not expert reviewed. + - Empty exercise output is intentional; do not fabricate drills or causal benefits. diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..1172337796e6dfffb7df9eeff84f16ce312e62e4 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,27 @@ +from fractions import Fraction +from pathlib import Path +import numpy as np +import pytest +import av + +@pytest.fixture +def video(tmp_path): + """Variable-cadence generated recording; no user footage or accuracy claims.""" + path = tmp_path / "synthetic.mp4" + with av.open(str(path), "w") as out: + stream = out.add_stream("libx264", rate=30) + stream.width, stream.height, stream.pix_fmt = 160, 120, "yuv420p" + stream.time_base = Fraction(1, 1000) + stream.codec_context.time_base = Fraction(1, 1000) + stream.options = {"bf": "0", "crf": "0"} + for i, time in enumerate([0, 33, 66, 100, 150, 183, 216, 250]): + img = np.full((120,160,3), i*20, np.uint8) + img[20:40, 20+i:50+i] = [255,30,60] + frame = av.VideoFrame.from_ndarray(img, format="bgr24") + frame.pts, frame.time_base = time, Fraction(1,1000) + for packet in stream.encode(frame): + out.mux(packet) + for packet in stream.encode(): + out.mux(packet) + return path + diff --git a/tests/test_advanced_metrics_feedback.py b/tests/test_advanced_metrics_feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..71fd9e32f2255888e9519541d1d0271b427bc4f7 --- /dev/null +++ b/tests/test_advanced_metrics_feedback.py @@ -0,0 +1,40 @@ +from pathlib import Path +import numpy as np +import yaml +from baseball_batting.advanced_metrics import augment +from baseball_batting.assessment import assess +from baseball_batting.contracts import Event,Metric +from baseball_batting.storage import atomic_json + +def test_independent_bat_velocity_and_contact_gates(tmp_path): + n=5;times=np.arange(n)*.01;sweet=np.c_[2*times,np.zeros(n),np.ones(n)*4] + np.savez_compressed(tmp_path/"bat.npz",sweet_spot_world_m=sweet) + atomic_json(tmp_path/"bat3d_status.json",{"status":"complete","trajectory_path":"bat.npz","geometry_source":"calibrated_multiview"}) + capture={"frame_count":n,"metadata":{},"physical_clock_known":True,"timing_source":{"kind":"unretimed"}, + "frames":[{"physical_s":float(t),"flags":[]} for t in times]} + curves={f"{side}_{joint}_projected_flexion_deg":np.zeros(n) for side in ("left","right") for joint in ("knee","elbow")} + curves["body_pixels"]=np.full((n,133,2),np.nan) + quality=yaml.safe_load((Path(__file__).resolve().parents[1]/"configs/quality.yaml").read_text()) + events=[Event("contact_fixture","contact","confirmed",[2,2],[2],"independent_synthetic_fixture")] + metrics=augment(tmp_path,curves,[],events,capture,quality,{"bat3d":True}) + values={m.metric_id:m for m in metrics} + assert np.isclose(values["bat_sweet_spot_speed_at_contact"].value,2) + assert np.isclose(values["bat_attack_angle_at_contact"].value,0) + assert values["bat_sweet_spot_speed_at_contact"].evidence_frames==[2] + for event_state,enabled in (("unknown",True),("confirmed",False)): + events[0].state=event_state + metrics=augment(tmp_path,curves,[],events,capture,quality,{"bat3d":enabled}) + assert next(m for m in metrics if m.metric_id=="bat_sweet_spot_speed_at_contact").value is None + +def test_educational_rule_requires_matched_repeated_context(): + path=Path(__file__).resolve().parents[1]/"rules/coaching_rules.yaml" + metrics=[Metric(side+"_knee_projected_flexion_at_contact","1.1",20.,"deg_projected","supported",["manual"],[2],"oriented_image_projection","unretimed") for side in ("left","right")] + events=[Event("reviewed","contact","confirmed",[2,2],[2],"human_review","reviewed")] + single=assess(metrics,{"swing_task":"tee"},events,[],path,"evidence_linked_experimental") + assert all(f.research_exercise is None for f in single) + trial={"metrics":[{"metric_id":m.metric_id,"value":m.value} for m in metrics]} + repeated=assess(metrics,{"swing_task":"tee"},events,[trial,trial],path,"evidence_linked_experimental") + exercises=[f.research_exercise for f in repeated if f.research_exercise] + assert len(exercises)==1 and exercises[0]["expected_benefit"]=="not_established" + different=assess(metrics,{"swing_task":"live_pitch"},events,[trial,trial],path,"evidence_linked_experimental") + assert all(f.research_exercise is None for f in different) diff --git a/tests/test_anatomy_optional.py b/tests/test_anatomy_optional.py new file mode 100644 index 0000000000000000000000000000000000000000..b52bff193a8ed14e000230a8948475baf7a818a2 --- /dev/null +++ b/tests/test_anatomy_optional.py @@ -0,0 +1,31 @@ +import numpy as np +import pytest +import yaml +from pathlib import Path +from tools.build_anatomical_model import reference_neutral +from baseball_batting.anatomy import model_spec,build_opensim,forward_kinematics,weighted_ik,refine_trajectory + +def test_reference_model_neutral_topology(): + settings=yaml.safe_load((Path(__file__).resolve().parents[1]/"configs/anatomical_model.yaml").read_text()) + spec=model_spec(reference_neutral(),settings) + assert len(spec["coordinates"])==35 + points,_=forward_kinematics(spec,np.zeros(35)) + expected=reference_neutral()[[m["mhr70_index"] for m in spec["markers"].values()]] + np.testing.assert_allclose(points,expected,atol=1e-12) + +def test_opensim_primitives_match_fk_and_ik(tmp_path): + pytest.importorskip("opensim") + settings=yaml.safe_load((Path(__file__).resolve().parents[1]/"configs/anatomical_model.yaml").read_text()) + spec=model_spec(reference_neutral(),settings);model=build_opensim(spec);state=model.initSystem() + q=np.random.default_rng(11).uniform(-.2,.2,35);q[3:6]=[.1,.2,2.] + for i,c in enumerate(spec["coordinates"]):model.getCoordinateSet().get(c["name"]).setValue(state,float(q[i]),False) + model.realizePosition(state) + expected=forward_kinematics(spec,q)[0] + actual=np.array([[model.getMarkerSet().get(name).getLocationInGround(state).get(i) for i in range(3)] for name in spec["markers"]]) + np.testing.assert_allclose(actual,expected,atol=1e-8) + target=np.repeat(expected[None],5,0);times=np.arange(5)*.01;weights=np.ones(target.shape[:2]) + fitted=weighted_ik(model,spec,target,weights,times,tmp_path) + assert np.isfinite(fitted).all() + for row in fitted:assert np.max(np.linalg.norm(forward_kinematics(spec,row)[0]-expected,axis=1))<.001 + refined,info=refine_trajectory(spec,fitted,target,weights,times,settings) + assert info and np.isfinite(refined).all() diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..44d6c4d9395ef0aa0c390ee24ee633e22a1999fe --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,332 @@ +import json +from pathlib import Path +import sys +import time +import numpy as np +import pytest + +pytest.importorskip("fastapi") +from fastapi.testclient import TestClient +from baseball_batting.api import create_app +from baseball_batting.api_contract import AnalysisInput +from baseball_batting.api_jobs import ApiSettings, JobService, JobStore, QueueFull +from baseball_batting.api_output import build_api_result +from baseball_batting.ingest import ingest +from baseball_batting.observations import run_observations +from baseball_batting.storage import StageCache, atomic_json + +KEY = "fixture-key-this-is-not-a-credential" +AUTH = {"Authorization": "Bearer " + KEY} + + +def wait_until(predicate, timeout=5): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + result = predicate() + if result: return result + time.sleep(.02) + raise AssertionError("Condition did not become true") + + +def settings(tmp_path, **overrides): + return ApiSettings(api_key=KEY, data_root=tmp_path, minimum_free_bytes=0, **overrides) + + +def fake_service(s, *, delay=0, preflight_ok=True): + def command(directory): + script = ("import json,time; from pathlib import Path; " + f"p=Path({str(directory)!r}); " + "(p/'progress.json').write_text(json.dumps({'stage':'pose_2d','completed_frames':1,'total_frames':2})); " + f"time.sleep({delay}); " + "(p/'result.json').write_text(json.dumps({'pose_track':{'frames':{'kp':[]}},'measurements':{'reps':[]}})); " + "(p/'coach-payload.json').write_text(json.dumps({'schema_version':'2.0','discipline':'hitting','capture':{'ok':False,'reasons':['no_person']},'reps':[]}))") + return [sys.executable, "-c", script] + return JobService(s, command_factory=command, + preflight_command=[sys.executable, "-c", f"raise SystemExit({0 if preflight_ok else 1})"]) + + +def upload(client, video, **kwargs): + return client.post("/v1/analyses", headers=AUTH, + files={"video": ("swing.mp4", video.read_bytes(), "video/mp4")}, **kwargs) + + +def test_upload_poll_fetch_delete_and_auth(video, tmp_path): + s = settings(tmp_path) + service = fake_service(s, delay=.2) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + assert client.get("/healthz").json()["body_3d"] is False + assert client.get("/v1/capabilities").status_code == 401 + assert client.post("/v1/analyses", content=b"malformed").status_code == 401 + assert client.get("/v1/capabilities", headers=AUTH).json()["device"] == "cuda" + assert client.get("/v1/input-schema", headers=AUTH).status_code == 200 + assert client.get("/v1/output-schema", headers=AUTH).status_code == 200 + assert client.get("/v1/coach-payload-schema", headers=AUTH).status_code == 200 + response = upload(client, video) + assert response.status_code == 202, response.text + job_id = response.json()["job_id"] + assert client.get(response.json()["result_url"], headers=AUTH).status_code == 409 + wait_until(lambda: service.store.get(job_id)["status"] == "completed") + status = client.get(response.json()["status_url"], headers=AUTH).json() + assert status["status"] == "completed" and status["progress"]["stage"] == "pose_2d" + result = client.get(response.json()["result_url"], headers=AUTH) + assert result.status_code == 200 and result.headers["cache-control"] == "no-store" + assert "pose_track" in result.json() + coach = client.get(response.json()["coach_payload_url"], headers=AUTH) + assert coach.status_code == 200 and coach.headers["cache-control"] == "no-store" + assert "pose_track" not in coach.json() and coach.json()["schema_version"] == "2.0" + wait_until(lambda: not list(service.job_directory(job_id).glob("input.*"))) + assert client.delete(response.json()["status_url"], headers=AUTH).status_code == 202 + assert not service.job_directory(job_id).exists() + assert client.get(response.json()["result_url"], headers=AUTH).status_code == 409 + + +def test_invalid_options_forbid_3d_and_paths(video, tmp_path): + s = settings(tmp_path) + service = fake_service(s) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + for options in ({"body3d_enabled": True}, {"device": "cpu"}, {"discipline": "pitching"}, + {"annotations_path": "/etc/passwd"}, {"timing": {"kind": "unretimed"}}, + {"body_height_px": 400}, {"level": "professional"}, + {"timing": {"kind": "constant_slowdown", "source": "camera", "factor": 8}}, + {"reps": [{"start_frame": 10, "end_frame": 2}]}, + {"reps": [{"start_frame": 0, "end_frame": 5}, {"start_frame": 3, "end_frame": 7}]}): + response = upload(client, video, data={"options": json.dumps(options)}) + assert response.status_code == 422, response.text + assert list(service.jobs_root.iterdir()) == [] + + +def test_gpu_readiness_fails_closed(video, tmp_path): + s = settings(tmp_path) + service = fake_service(s, preflight_ok=False) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.readiness_reason == "gpu_preflight_failed") + assert client.get("/readyz").status_code == 503 + assert upload(client, video).status_code == 503 + + +def test_upload_limits_and_empty_video(video, tmp_path): + s = settings(tmp_path, max_upload_bytes=32) + service = fake_service(s) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + assert upload(client, video).status_code == 413 + assert client.post("/v1/analyses", headers=AUTH, + files={"video": ("x.mp4", b"")}).status_code == 422 + assert client.post("/v1/analyses", headers=AUTH, + files={"video": ("x.py", b"123")}).status_code == 415 + assert list(service.jobs_root.iterdir()) == [] + + +def test_streamed_body_limit_without_content_length(tmp_path): + s = settings(tmp_path, max_upload_bytes=32) + service = fake_service(s) + def chunks(): + yield b'--boundary\r\nContent-Disposition: form-data; name="video"; filename="swing.mp4"\r\nContent-Type: video/mp4\r\n\r\n' + for _ in range(512): yield b"x" * 4096 + yield b"\r\n--boundary--\r\n" + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + response = client.post("/v1/analyses", headers={**AUTH, "Content-Type": "multipart/form-data; boundary=boundary"}, content=chunks()) + assert response.status_code == 413, response.text + + +def test_queue_full_and_cancel_running(video, tmp_path): + s = settings(tmp_path, max_active_jobs=1) + service = fake_service(s, delay=30) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + first = upload(client, video).json() + wait_until(lambda: service.store.get(first["job_id"])["status"] == "running") + second = upload(client, video) + assert second.status_code == 429 + assert client.delete(first["status_url"], headers=AUTH).json()["status"] == "cancel_requested" + wait_until(lambda: service.store.get(first["job_id"])["status"] == "cancelled") + assert not service.job_directory(first["job_id"]).exists() + + +def test_worker_timeout(video, tmp_path): + s = settings(tmp_path, job_timeout_s=.1) + service = fake_service(s, delay=30) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + job = upload(client, video).json() + wait_until(lambda: service.store.get(job["job_id"])["status"] == "failed") + assert client.get(job["status_url"], headers=AUTH).json()["error"] == "job_timeout" + + +def test_result_checksum_and_id_validation(video, tmp_path): + s = settings(tmp_path) + service = fake_service(s) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + job = upload(client, video).json() + wait_until(lambda: service.store.get(job["job_id"])["status"] == "completed") + (service.job_directory(job["job_id"]) / "result.json").write_text("corrupt") + assert client.get(job["result_url"], headers=AUTH).status_code == 500 + (service.job_directory(job["job_id"]) / "coach-payload.json").write_text("corrupt") + assert client.get(job["coach_payload_url"], headers=AUTH).status_code == 500 + assert client.get(job["coach_payload_url"]).status_code == 401 + assert client.get("/v1/analyses/bogus", headers=AUTH).status_code == 404 + + +def test_recovery_retention_and_single_worker_lock(tmp_path): + s = settings(tmp_path) + service = fake_service(s) + running = service.store.create(8); service.store.update(running, "running") + uploading = service.store.create(8) + directory = service.job_directory(uploading); directory.mkdir() + service.start() + try: + second = fake_service(s) + with pytest.raises(RuntimeError, match="already has an API worker"): second.start() + assert service.store.get(uploading) is None and not directory.exists() + # The recovered job has no fixture input, so fake runner fails normally. + wait_until(lambda: service.store.get(running)["status"] == "failed") + expired = service.store.create(8); service.store.update(expired, "completed") + with service.store.connect() as db: + db.execute("UPDATE jobs SET updated=0 WHERE id=?", (expired,)) + service.cleanup() + assert service.store.get(expired) is None + finally: + service.stop() + + +def test_shutdown_requeues_and_kills_worker(video, tmp_path): + s = settings(tmp_path) + service = fake_service(s, delay=30) + with TestClient(create_app(s, service)) as client: + wait_until(lambda: service.ready) + job = upload(client, video).json() + wait_until(lambda: service.store.get(job["job_id"])["status"] == "running") + assert service.store.get(job["job_id"])["status"] == "queued" + assert list(service.job_directory(job["job_id"]).glob("input.*")) + resumed = fake_service(s) + with TestClient(create_app(s, resumed)): + wait_until(lambda: resumed.store.get(job["job_id"])["status"] == "completed") + + +def test_pose_handoff_real_decoding_raw_points_and_unknown_time(video, tmp_path, monkeypatch): + import baseball_batting.observations as module + class Pose: + def __init__(self, *args): pass + def __call__(self, image, box): + points = np.column_stack([np.arange(133), np.arange(133)]) + 10. + points[0] = [-1, 10] # Out-of-image predictions must become null + zero. + scores = np.full(133, .8); scores[5] = .1 + return points, scores + class Detector: + def __init__(self, *args): pass + def __call__(self, image): + return [{"class_id": 0, "box": [10, 10, 110, 110], "score": .9}, + {"class_id": 0, "box": [1, 1, 20, 20], "score": .9}] + monkeypatch.setattr(module, "RTMWPose", Pose) + monkeypatch.setattr(module, "YOLOXDetector", Detector) + from baseball_batting.config import EngineConfig + capture = ingest(video, {}) + observations = run_observations(video, capture, + EngineConfig(body_pose_path="pose.onnx", person_detector_path="person.onnx"), + StageCache(tmp_path, "observations", "fixture")) + result = build_api_result(capture, observations, AnalysisInput(single_swing=True), + {"body_pose": "fixture", "person_detector": "fixture"}) + frames = result["pose_track"]["frames"] + assert all(len(value) == 8 for value in frames.values()) + assert frames["kp"][0][0] is None and frames["conf"][0][0] == 0 + assert frames["kp"][0][5] is None and frames["conf"][0][5] == 0 + assert len(frames["kp"][0]) == 17 and len(frames["kp_extra"][0]) == 6 + assert frames["kp_extra"][0][0] == [27., 27.] + assert frames["people_count"] == [2] * 8 + assert frames["t_s"] == [None] * 8 and frames["playback_t_s"][1] == pytest.approx(.033) + assert not result["measurements"]["capture"]["ok"] + assert result["pose_track"]["reps"][0]["events"] == {} + assert "kp3d" not in result["pose_track"] and "findings" not in result + json.dumps(result, allow_nan=False) + import jsonschema + schema = json.loads((Path(__file__).resolve().parents[1] / "docs/api-result.schema.json").read_text()) + jsonschema.Draft202012Validator.check_schema(schema) + jsonschema.validate(result, schema) + options = AnalysisInput(timing={"kind": "constant_slowdown", "source": "camera export", "factor": 4, + "all_captured_frames_retained": True}) + slow = ingest(video, options.engine_metadata()) + rescaled = build_api_result(slow, observations, options, {"body_pose": "fixture", "person_detector": "fixture"}) + assert rescaled["pose_track"]["frames"]["t_s"][1] == pytest.approx(.033 / 4) + # Variable frame intervals are preserved and not presented as constant capture FPS. + assert rescaled["pose_track"]["video"]["capture_fps"] is None + assert rescaled["pose_track"]["reps"] == [] + with pytest.raises(ValueError, match="exceeds"): + build_api_result(capture, observations, AnalysisInput(reps=[{"start_frame": 0, "end_frame": 99}]), + {"body_pose": "fixture", "person_detector": "fixture"}) + + +def test_bounded_decoding(video): + with pytest.raises(ValueError, match="frame limit"): ingest(video, {}, max_frames=2) + with pytest.raises(ValueError, match="pixel limit"): ingest(video, {}, max_pixels=10) + with pytest.raises(ValueError, match="duration limit"): ingest(video, {}, max_duration_s=.01) + + +def test_decoder_blocks_network_playlist_segments(tmp_path): + import av + from baseball_batting.ingest import iter_frames + playlist = tmp_path / "recording.m3u8" + playlist.write_text('#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-MEDIA-SEQUENCE:0\n' + '#EXT-X-TARGETDURATION:1\n#EXTINF:1.0,\n' + 'http://127.0.0.1:1/remote.ts\n#EXT-X-ENDLIST\n') + old_level = av.logging.get_level() + av.logging.set_level(av.logging.ERROR) + try: + with av.logging.Capture() as logs: + with pytest.raises(av.error.FFmpegError): list(iter_frames(playlist)) + assert any("Protocol 'http' not on whitelist" in line for _, _, line in logs) + finally: + av.logging.set_level(old_level) + + +def test_model_gate_requires_correct_checkpoints(tmp_path): + from baseball_batting.api_worker import model_files + with pytest.raises(ValueError, match="Missing or incorrect"): model_files(tmp_path) + + +def test_worker_environment_excludes_api_secret(tmp_path, monkeypatch): + monkeypatch.setenv("BASEBALL_API_KEY", KEY) + service = fake_service(settings(tmp_path)) + assert "BASEBALL_API_KEY" not in service.environment() + assert service.environment()["MPLBACKEND"] == "Agg" + + +def test_existing_job_database_migrates_without_losing_records(tmp_path): + import sqlite3 + identifier = "a"*32 + with sqlite3.connect(tmp_path / "jobs.sqlite3") as db: + db.execute("CREATE TABLE jobs (id TEXT PRIMARY KEY,status TEXT,created REAL,updated REAL,error TEXT,result_sha256 TEXT)") + db.execute("INSERT INTO jobs VALUES (?, 'completed', 1, 1, NULL, 'old-hash')", (identifier,)) + store = JobStore(tmp_path) + assert store.get(identifier)["result_sha256"] == "old-hash" + assert store.get(identifier)["coach_payload_sha256"] is None + fresh = store.create(8) + store.update(fresh, "completed", result_hash="result", coach_hash="coach") + assert store.get(fresh)["coach_payload_sha256"] == "coach" + + +def test_no_person_worker_returns_record_again_payload(video, tmp_path, monkeypatch): + from baseball_batting.api_worker import run_analysis + import baseball_batting.api_worker as worker + import baseball_batting.observations as observation_module + import shutil + shutil.copy2(video, tmp_path / "input.mp4") + atomic_json(tmp_path / "request.json", {}) + monkeypatch.setattr(worker, "model_files", lambda models: ({"body_pose":"pose", "person_detector":"person"}, + {"body_pose":"test", "person_detector":"test"})) + def absent(video, capture, config, cache, progress=None): + assert not config.body3d_enabled and not config.temporal3d_enabled and not config.anatomy_enabled + return {"branch_status":{"body_pose":{"status":"ready"},"person_detector":{"status":"ready"}}, + "frames":[{"frame_id":i,"body_points":[None]*133,"body_scores":[0]*133, + "body_states":["unknown"]*133,"person":None,"people_count":0} + for i in range(capture["frame_count"])]} + monkeypatch.setattr(observation_module, "run_observations", absent) + result = run_analysis(tmp_path, tmp_path, device="cpu") + payload = json.loads((tmp_path / "coach-payload.json").read_text()) + assert payload == result["coach_payload"] + assert payload["capture"]["ok"] is False and "no_person" in payload["capture"]["reasons"] + assert payload["reps"] == [] + assert "pose_track" not in payload diff --git a/tests/test_batting_measurements.py b/tests/test_batting_measurements.py new file mode 100644 index 0000000000000000000000000000000000000000..34fefcc46f7f9ee289c8000f60d3b0e6a6377c97 --- /dev/null +++ b/tests/test_batting_measurements.py @@ -0,0 +1,243 @@ +"""Numerical contract checks against constructed trajectories, not accuracy tests.""" +from copy import deepcopy +import json +from pathlib import Path +import numpy as np +import pytest +from baseball_batting.api_contract import AnalysisInput +from baseball_batting.batting_measurements import ( + analyze_batting, analysis_points, coach_payload, CAPTURE_REASONS) + + +def swing_track(fps=120, repeats=1, mirror=False): + n = 180 + kp, feet = [], [] + for i in range(n): + body = np.array([[330,150], [325,145], [335,145], [315,155], [345,155], + [300,250], [360,250], [320,290], [360,290], [330,260], [335,260], + [310,350], [350,350], [350,480], [260,480], [370,620], [260,620]], float) + hx = np.interp(i, [0,20,40,60,95,110,130,179], [330,330,280,280,500,510,430,430]) + body[9] = [hx,260]; body[10] = [hx+5,260] + bend = min(40, abs(i-95)*4) + body[7] = (body[5]+body[9])/2 + [0,bend] + progress = np.clip((i-25)/20, 0, 1) + body[15] += [60*progress, -40*np.sin(np.pi*progress)] + body[0,0] += np.clip((i-20)/75, 0, 1)*2 + extra = np.array([body[15]+[12,20], body[15]+[8,18], body[15]+[-8,15], + body[16]+[12,20], body[16]+[8,18], body[16]+[-8,15]]) + if mirror: + body[:,0] = 1280-body[:,0]; extra[:,0] = 1280-extra[:,0] + kp.append(body.tolist()); feet.append(extra.tolist()) + count = n*repeats + return {"video": {"width":1280, "height":720, "frame_count":count, "capture_fps":fps}, + "frames": {"kp":kp*repeats, "kp_extra":feet*repeats, + "conf":[[.9]*17 for _ in range(count)], + "box":[[200,130,580,660] for _ in range(count)], + "people_count":[1]*count, "blur":[.1]*count, "brightness":[128]*count, + "t_s":[i/fps for i in range(count)], + "playback_t_s":[i/30 for i in range(count)]}} + + +def options(**overrides): + return AnalysisInput(view="face_on", handedness="right", camera_stability="fixed_verified", + body_height_px=400, body_height_source="constructed 400-pixel standing stature", **overrides) + + +def metric_map(rep): + return {m["key"]:m for m in rep["metrics"]} + + +def test_constructed_swing_produces_events_and_independent_measurement_arithmetic(): + track = swing_track() + original = deepcopy(track) + pose, measurements, capture, warnings, method = analyze_batting(track, options(single_swing=True)) + assert track == original # raw points are never modified by analytical smoothing + assert capture == {"ok":True, "reasons":[]} + events = pose[0]["events"] + assert {"stance_set","load_start","stride","foot_contact","foot_plant","swing_start","contact","finish"} <= events.keys() + assert events["foot_contact"]["frame"] <= events["foot_plant"]["frame"] + assert 90 <= events["contact"]["frame"] <= 97 + assert events["finish"]["frame"] < 179 + metrics = metric_map(measurements[0]) + assert metrics["stride_pct_height"]["value"] == pytest.approx(42.5) + assert metrics["com_drift_pct_height"]["value"] == pytest.approx(-25) + timing = (events["contact"]["frame"]-events["foot_plant"]["frame"])/120*1000 + assert metrics["foot_plant_to_contact_ms"]["value"] == pytest.approx(timing, abs=.001) + assert metrics["load_tempo_s"]["value"] is not None + assert metrics["load_launch_ratio"]["value"] is not None + assert all(m["confidence"] == "est" for m in metrics.values()) + assert all(m["note"] for m in metrics.values()) + assert metrics["hip_shoulder_separation_foot_plant_deg"]["value"] is None + assert metrics["lateral_trunk_tilt_contact_deg"]["value"] is None + assert all(e["estimated"] for e in events.values()) + + +def test_automatic_two_swings_and_rep_relative_times(): + pose, reps, capture, _, _ = analyze_batting(swing_track(repeats=2), options()) + assert len(pose) == len(reps) == 2 + assert pose[0]["end_frame"] < pose[1]["start_frame"] + assert all(p["boundary_method"] == "automatic_2d_hand_motion_candidate" for p in pose) + for p, r in zip(pose, reps): + for key, value in r["events_ms"].items(): + assert value == pytest.approx((p["events"][key]["frame"]-p["start_frame"])/120*1000, abs=.001) + assert metric_map(r)["stride_pct_height"]["value"] == pytest.approx(42.5) + + +def test_unknown_or_low_capture_clock_never_uses_playback_time(): + for fps in (None, 30): + track = swing_track() + track["video"]["capture_fps"] = fps + if fps is None: track["frames"]["t_s"] = [None]*180 + else: track["frames"]["t_s"] = [i/fps for i in range(180)] + pose, reps, capture, _, _ = analyze_batting(track, options(single_swing=True)) + for key in ("foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio"): + assert metric_map(reps[0])[key]["value"] is None + if fps is None: + assert reps[0]["events_ms"] == {} + assert all("t_s" not in e for e in pose[0]["events"].values()) + + +def test_mirrored_image_keeps_stride_and_signed_body_position(): + original = analyze_batting(swing_track(), options(single_swing=True))[1][0] + mirrored = analyze_batting(swing_track(mirror=True), options(single_swing=True))[1][0] + for key in ("stride_pct_height", "com_drift_pct_height", "foot_plant_to_contact_ms"): + assert metric_map(mirrored)[key]["value"] == metric_map(original)[key]["value"] + + +def test_static_pose_and_ambiguous_declared_rep_never_force_a_contact(): + track = swing_track() + track["frames"]["kp"] = [track["frames"]["kp"][0]]*180 + track["frames"]["kp_extra"] = [track["frames"]["kp_extra"][0]]*180 + assert analyze_batting(track, options())[0] == [] + pose, reps, _, _, _ = analyze_batting(swing_track(repeats=2), options(single_swing=True)) + assert pose[0]["events"] == {} + assert all(m["value"] is None for m in reps[0]["metrics"]) + + +def test_short_gaps_are_filled_only_in_analysis_long_gaps_stay_missing(): + points = np.tile(np.arange(12)[:,None,None], (1,1,2)).astype(float) + points[2:5] = np.nan; points[7:11] = np.nan + filled = analysis_points(points) + assert np.isfinite(filled[2:5]).all() + assert np.isnan(filled[7:11]).all() + assert np.isnan(points[2:5]).all() + track = swing_track() + for i in range(55,110): + track["frames"]["kp"][i][9] = None + track["frames"]["conf"][i][9] = 0 + pose, reps, _, _, _ = analyze_batting(track, options(single_swing=True)) + assert "contact" not in pose[0]["events"] + assert metric_map(reps[0])["com_drift_pct_height"]["value"] is None + + +@pytest.mark.parametrize("change,reason", [("people","multiple_people"), ("dark","too_dark"), + ("blur","too_blurry"), ("crop","partly_out_of_frame"), ("empty","no_person")]) +def test_failed_capture_uses_only_coach_reason_keys_and_withholds_numbers(change,reason): + track = swing_track() + if change == "people": track["frames"]["people_count"] = [2]*180 + if change == "dark": track["frames"]["brightness"] = [10]*180 + if change == "blur": track["frames"]["blur"] = [.99]*180 + if change == "crop": track["frames"]["box"] = [[0,0,580,720]]*180 + if change == "empty": + track["frames"]["box"] = [None]*180 + track["frames"]["kp"] = [[None]*17 for _ in range(180)] + track["frames"]["conf"] = [[0]*17 for _ in range(180)] + _, reps, capture, _, _ = analyze_batting(track, options(single_swing=True)) + assert capture["ok"] is False and reason in capture["reasons"] + assert set(capture["reasons"]) <= CAPTURE_REASONS + assert all(m["value"] is None and m["note"] for m in reps[0]["metrics"]) + + +def test_absent_handedness_or_moving_camera_withholds_dependent_measurements(): + opt = options(single_swing=True) + opt.handedness = None + pose, reps, _, _, _ = analyze_batting(swing_track(), opt) + assert "contact" not in pose[0]["events"] + assert metric_map(reps[0])["stride_pct_height"]["value"] is None + opt = options(single_swing=True) + opt.camera_stability = "moving" + pose, reps, _, _, _ = analyze_batting(swing_track(), opt) + assert pose[0]["events"] == {} + assert all(m["value"] is None for m in reps[0]["metrics"]) + + +def test_payload_is_measurements_only_and_preserves_level(): + _, reps, capture, _, _ = analyze_batting(swing_track(), options(single_swing=True)) + payload = coach_payload({"reps":reps, "capture":capture, "fps":120, + "view":"face_on", "level":"college"}) + assert set(payload) == {"schema_version","discipline","level","view","fps","capture","reps"} + assert payload["level"] == "college" + assert len(json.dumps(payload).encode()) < 2*1024*1024 + unknown = coach_payload({"reps":reps,"capture":capture,"fps":None,"view":"unknown"}) + assert "fps" not in unknown and "view" not in unknown + import jsonschema + schema = json.loads((Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json").read_text()) + jsonschema.Draft202012Validator.check_schema(schema) + jsonschema.validate(payload, schema) + jsonschema.validate(unknown, schema) + wrong = deepcopy(payload) + wrong["reps"][0]["metrics"][0]["unit"] = "cm" + with pytest.raises(jsonschema.ValidationError): jsonschema.validate(wrong, schema) + + +def test_automatic_ranges_trim_setup_and_trailing_footage(): + pose, _, _, _, _ = analyze_batting(swing_track(), options()) + assert len(pose) == 1 + assert pose[0]["start_frame"] < pose[0]["events"]["load_start"]["frame"] + assert pose[0]["end_frame"] < 179 + for event in pose[0]["events"].values(): + assert pose[0]["start_frame"] <= event["frame"] <= pose[0]["end_frame"] + + +def test_separate_rep_ranges_do_not_create_a_false_adjacent_frame_identity_jump(): + from baseball_batting.batting_measurements import capture_checks + track = swing_track(repeats=2) + # A transition outside the submitted ranges is not an adjacent-frame jump. + track["frames"]["box"][180:] = [[500,130,880,660] for _ in range(180)] + capture, _ = capture_checks(track, options(), 400, list(range(30,100))+list(range(210,280))) + assert capture["ok"] is True and "player_switched" not in capture["reasons"] + capture, _ = capture_checks(track, options(), 400, range(360)) + assert capture["ok"] is False and "player_switched" in capture["reasons"] + + +def test_left_handed_lead_side_and_automatic_scale(): + track = swing_track() + for points in track["frames"]["kp"]: + for left,right in ((5,6),(7,8),(9,10),(11,12),(13,14),(15,16)): + points[left],points[right] = points[right],points[left] + for points in track["frames"]["kp_extra"]: + points[:3],points[3:] = points[3:],points[:3] + opt = options(single_swing=True) + opt.handedness = "left" + _, reps, _, _, _ = analyze_batting(track, opt) + assert metric_map(reps[0])["stride_pct_height"]["value"] == pytest.approx(42.5) + opt.body_height_px = opt.body_height_source = None + _, reps, _, _, method = analyze_batting(track, opt) + assert method["body_height_px"] > 120 + assert "unmeasured" in method["body_height_method"] + assert all(m["confidence"] == "est" for m in reps[0]["metrics"]) + + +def test_native_pose_to_full_result_and_exported_coach_schema(): + from baseball_batting.api_output import build_api_result + import jsonschema + track = swing_track() + capture = {"frame_count":180, "rotation_degrees":0, + "frames":[{"width":1280,"height":720,"physical_s":i/120,"playback_s":i/30} for i in range(180)], + "quality":[{"blur_laplacian_variance":900,"mean_luminance":128} for _ in range(180)]} + observations = {"frames":[]} + for i in range(180): + observations["frames"].append({"frame_id":i, + "body_points":track["frames"]["kp"][i]+track["frames"]["kp_extra"][i]+[None]*110, + "body_scores":[.9]*23+[0]*110,"body_states":["model_inferred"]*23+["unknown"]*110, + "person":{"box":track["frames"]["box"][i]},"people_count":1}) + opt = options(single_swing=True, level="hs_varsity", timing={"kind":"explicit", + "source":"constructed frame timestamps", "physical_times_s":[i/120 for i in range(180)]}) + result = build_api_result(capture, observations, opt, {"body_pose":"fixture","person_detector":"fixture"}) + root = Path(__file__).resolve().parents[1] + jsonschema.validate(result, json.loads((root/"docs/api-result.schema.json").read_text())) + jsonschema.validate(result["coach_payload"], json.loads((root/"docs/coach-payload.schema.json").read_text())) + assert result["coach_payload"] == result["measurements"] + assert result["coach_payload"]["fps"] == 120 + assert metric_map(result["coach_payload"]["reps"][0])["stride_pct_height"]["value"] == 42.5 + assert "kp3d" not in result["pose_track"] diff --git a/tests/test_colab_2d.py b/tests/test_colab_2d.py new file mode 100644 index 0000000000000000000000000000000000000000..93f708632d46d2873db1e21299d7cd0a13402a08 --- /dev/null +++ b/tests/test_colab_2d.py @@ -0,0 +1,119 @@ +"""Colab entry-point and actual clip encoding checks; no accuracy claims.""" +import ast +from copy import deepcopy +import json +from pathlib import Path +import nbformat +import pytest +from baseball_batting.ingest import ingest, iter_frames +from tools.build_2d_notebook import build +from tools.preview_swing_ranges import export_previews + +ROOT = Path(__file__).resolve().parents[1] + + +def preview_result(video, rotation=0): + capture = ingest(video, {"rotation_degrees": rotation}) + shape = capture["frames"][0] + return {"pose_track": {"video": {"width": shape["width"], "height": shape["height"], + "frame_count": capture["frame_count"], "rotation_degrees_applied": rotation, + "playback_fps": None, "capture_fps": None}, + "frames": {"kp": [[None]*17 for _ in capture["frames"]], + "playback_t_s": [f["playback_s"] for f in capture["frames"]]}, + "reps": [{"rep": 1, "start_frame": 2, "end_frame": 4, "events": {}}, + {"rep": 2, "start_frame": 6, "end_frame": 7, "events": {}}]}} + + +def test_generated_2d_notebook_is_valid_and_uses_api_worker(): + notebook = nbformat.read(ROOT / "notebooks/batting_2d_test.ipynb", as_version=4) + nbformat.validate(notebook) + assert json.loads(nbformat.writes(notebook)) == build() + code_cells = [cell.source for cell in notebook.cells if cell.cell_type == "code"] + for cell in code_cells: ast.parse(cell) + source = "\n".join(code_cells) + assert "baseball_batting.api_worker" in source + assert "tools.setup_api_models" in source + assert "tools.preview_swing_ranges" in source + assert "setup_full_worker" not in source + assert 'SINGLE_SWING = False' in source + assert 'TIMING = {"kind": "unknown"}' in source + assert not any(cell.outputs for cell in notebook.cells if cell.cell_type == "code") + + +def test_swing_previews_preserve_inclusive_frames_and_variable_playback_timing(video, tmp_path): + result = preview_result(video) + original = deepcopy(result) + manifest = export_previews(video, result, tmp_path / "clips", overlay=False) + assert result == original + assert len(manifest["previews"]) == 2 + source = list(iter_frames(video)) + for record in manifest["previews"]: + assert record["status"] == "complete", record + frames = list(iter_frames(tmp_path / "clips" / record["file"])) + start, end = record["start_frame"], record["end_frame"] + assert len(frames) == end-start+1 + for local, (_, pts, base, image) in enumerate(frames): + expected = result["pose_track"]["frames"]["playback_t_s"][start+local] + origin = result["pose_track"]["frames"]["playback_t_s"][start] + assert float(pts*base) == pytest.approx(expected-origin, abs=float(base)) + # Actual pixel content verifies that encoder selected the right frames. + assert float(image[70:90,90:110].mean()) == pytest.approx( + float(source[start+local][3][70:90,90:110].mean()), abs=4) + + +def test_preview_rotation_limit_and_raw_point_overlay(video, tmp_path): + result = preview_result(video, 90) + result["pose_track"]["frames"]["kp"][2][0] = [50, 70] + manifest = export_previews(video, result, tmp_path / "clips", max_clips=1) + assert manifest["swing_candidates_total"] == 2 + assert len(manifest["previews"]) == 1 + record = manifest["previews"][0] + assert record["status"] == "complete", record + assert (record["width"], record["height"]) == (120,160) + frames = list(iter_frames(tmp_path / "clips" / record["file"])) + assert frames[0][3].shape[:2] == (160,120) + assert frames[0][3][70,50,1] > 150 # Visible raw nose point. + + +@pytest.mark.parametrize("bad_clock", [None, 0.0]) +def test_bad_playback_timing_is_withheld_without_fabricating_preview(video, tmp_path, bad_clock): + result = preview_result(video) + result["pose_track"]["frames"]["playback_t_s"][3] = bad_clock + manifest = export_previews(video, result, tmp_path / "clips", max_clips=1) + assert manifest["previews"][0]["status"] == "unavailable" + assert not list((tmp_path / "clips").glob("*.mp4")) + + +def test_zero_candidates_and_wrong_ranges_never_invent_clips(video, tmp_path): + result = preview_result(video) + result["pose_track"]["reps"] = [] + assert export_previews(video, result, tmp_path / "none")["previews"] == [] + result = preview_result(video) + result["pose_track"]["reps"][1]["start_frame"] = 4 + with pytest.raises(ValueError, match="disjoint"): + export_previews(video, result, tmp_path / "overlap") + + +def test_notebook_download_contains_results_and_current_previews_only(tmp_path): + import zipfile + from types import SimpleNamespace + job = tmp_path / "results/session-example" + previews = job / "previews" + previews.mkdir(parents=True) + for name in ("result.json", "coach-payload.json", "request.json", "source_checkout.json", + "input.mp4", ".env", "worker.log"): + (job / name).write_text("fixture") + (previews / "swing-001.mp4").write_text("current preview") + (previews / "swing-002.mp4").write_text("stale previous preview") + (previews / "previews.json").write_text(json.dumps({"previews": [ + {"status": "complete", "file": "swing-001.mp4"}, {"status": "unavailable", "rep": 2}]})) + downloads = [] + scope = {"WORKSPACE_ROOT": tmp_path, "JOB_ROOT": job, "json": json, + "files": SimpleNamespace(download=downloads.append)} + download_cell = "".join(build()["cells"][-1]["source"]) + exec(compile(download_cell, "colab_download", "exec"), scope) + assert downloads == [str(scope["ARCHIVE_PATH"])] + with zipfile.ZipFile(downloads[0]) as archive: + names = set(archive.namelist()) + assert {"result.json", "coach-payload.json", "previews/previews.json", "previews/swing-001.mp4"} <= names + assert not {"input.mp4", ".env", "previews/swing-002.mp4"} & names diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..0919d1166ffe9ba4d273e43157a0a95fab4a9900 --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,135 @@ +import json +from pathlib import Path +import numpy as np +import pytest +from baseball_batting.ingest import ingest, physical_time, orientation_matrix, validate_metadata +from baseball_batting.storage import StageCache, atomic_json, digest, read_json +from baseball_batting.contracts import json_safe +from baseball_batting.metrics import flexion_degrees, derivative +from baseball_batting.config import EngineConfig +from baseball_batting.detection import decode_yolox, select_person, verify_cuda_nodes +from baseball_batting.body3d import native_mhr_positions_to_sam_camera, translate_sam_positions +from baseball_batting.annotations import load_annotations + +def test_decode_and_clock(video): + c = ingest(video, {}) + assert c["frame_count"] == 8 + assert not c["physical_clock_known"] + assert all(f["physical_s"] is None for f in c["frames"]) + np.testing.assert_allclose([f["playback_s"] for f in c["frames"]], [0,.033,.066,.1,.15,.183,.216,.25], atol=.001) + assert all(f["pts"] is not None for f in c["frames"]) + +def test_declared_clock(video): + c = ingest(video, {"timing": {"kind": "constant_slowdown", "factor": 4, + "source": "synthetic retained frames", "all_captured_frames_retained": True}}) + assert c["physical_clock_known"] + assert c["frames"][-1]["physical_s"] == pytest.approx(.25/4, abs=.001) + +@pytest.mark.parametrize("timing", [ + {"kind": "constant_slowdown", "factor": 0, "source": "test", "all_captured_frames_retained": True}, + {"kind": "constant_slowdown", "factor": 4, "source": "test"}, + {"kind": "unretimed"}, {"kind": "explicit", "source": "test", "physical_times_s": [0,0]}, + {"kind": "explicit", "source": "test", "physical_times_s": [0,float("nan")]}, +]) +def test_bad_timing_rejected(timing): + with pytest.raises(ValueError): + validate_metadata({"timing": timing}) + +def test_explicit_time_map_count(video): + with pytest.raises(ValueError, match="shorter"): + ingest(video, {"timing": {"kind": "explicit", "source": "test", "physical_times_s": [0,1]}}) + +@pytest.mark.parametrize("angle,expected", [(0,[10,20,1]),(90,[99,10,1]),(180,[149,99,1]),(270,[20,149,1])]) +def test_orientation(angle,expected): + np.testing.assert_allclose(orientation_matrix(160,120,angle) @ [10,20,1], expected) + +def test_stage_integrity_and_key(tmp_path): + cache = StageCache(tmp_path, "test", digest({"model": "one"})) + p = cache.root / "points.json" + atomic_json(p, [1,2]) + cache.commit("chunk_0", [p]) + assert cache.valid("chunk_0") + p.write_text("corrupt") + assert cache.valid("chunk_0") is None + assert StageCache(tmp_path, "test", digest({"model": "two"})).valid("chunk_0") is None + +def test_json_nulls(): + assert json_safe({"value": np.float64(np.nan)}) == {"value": None} + json.dumps(json_safe(np.array([np.nan, np.inf])), allow_nan=False) + +@pytest.mark.parametrize("a,b,c,expected", [([-1,0],[0,0],[1,0],0), ([0,1],[0,0],[1,0],90), ([1,0],[0,0],[1,0],180)]) +def test_flexion_convention(a,b,c,expected): + assert flexion_degrees(a,b,c) == pytest.approx(expected) + +def test_degenerate_joint(): + assert np.isnan(flexion_degrees([0,0],[0,0],[1,0])) + +def test_derivative_nonuniform_and_gaps(): + t = np.array([0,.1,.25,.4,.6,.8,1.0]) + values = t**2 + np.testing.assert_allclose(derivative(values,t), 2*t, atol=1e-12) + values[3] = np.nan + d = derivative(values,t) + assert np.isnan(d[3]) + np.testing.assert_allclose(d[:3], 2*t[:3], atol=1e-12) + np.testing.assert_allclose(d[4:], 2*t[4:], atol=1e-12) + +def test_detector_retains_class_scores(): + count = sum((640//s)**2 for s in (8,16,32)) + raw = np.zeros((1,count,85), np.float32) + raw[0,0,:4] = [10,10,1,1] + raw[0,0,4] = .8 + raw[0,0,5+34] = .9 + detections = decode_yolox(raw) + assert len(detections) == 1 + assert detections[0]["class_id"] == 34 + assert detections[0]["score"] == pytest.approx(.72) + +def test_person_identity_does_not_jump(): + assert select_person([{"class_id":0,"box":[100,100,200,200],"score":.9}], [0,0,20,20]) is None + +def test_integrated_nms_person_scores(): + raw = np.array([[[10,20,30,40,.8], [0,0,0,0,0]]], np.float32) + detections = decode_yolox(raw, ratio=.5, classes=[0]) + assert len(detections) == 1 + assert detections[0]["score"] == pytest.approx(.8) + assert detections[0]["box"] == [20,40,60,80] + with pytest.raises(ValueError): + decode_yolox(raw, classes=[0,32,34]) + +def test_person_only_raw_export_rejected_for_objects(): + raw = np.zeros((1,8400,6),np.float32) + with pytest.raises(ValueError,match="Person-only"): + decode_yolox(raw,classes=[0,32,34]) + +@pytest.mark.parametrize("provider", ["CPUExecutionProvider", "CUDAExecutionProvider"]) +def test_cuda_proof_requires_executed_node(tmp_path,provider): + profile = tmp_path/"profile.json" + profile.write_text(json.dumps([{"args":{"provider":provider}}])) + class Session: + def end_profiling(self): + return str(profile) + if provider == "CPUExecutionProvider": + with pytest.raises(RuntimeError,match="No CUDA"): + verify_cuda_nodes(Session()) + else: + verify_cuda_nodes(Session()) + assert not profile.exists() + +def test_mhr_units_and_translation_once(): + native = np.array([[100,200,300]]) + camera = native_mhr_positions_to_sam_camera(native) + np.testing.assert_allclose(camera, [[1,-2,-3]]) + np.testing.assert_allclose(translate_sam_positions(camera,[0,0,5]), [[1,-2,2]]) + +@pytest.mark.parametrize("cfg", [EngineConfig(learned_events_enabled="yes"), EngineConfig(bat_3d_mode=None), + EngineConfig(chunk_size=0), EngineConfig(annotations_path="x")]) +def test_invalid_configuration_rejected(cfg): + with pytest.raises(ValueError): + cfg.validate() + +def test_wrong_annotation_video(tmp_path): + p = tmp_path / "a.json" + atomic_json(p, {"schema_version":"1.0", "input_sha256":"wrong", "annotator":"test"}) + with pytest.raises(ValueError): + load_annotations(p,"expected",8,160,120) diff --git a/tests/test_events_review.py b/tests/test_events_review.py new file mode 100644 index 0000000000000000000000000000000000000000..682512afaa05c54907ae43ac6d02810fde7ba63e --- /dev/null +++ b/tests/test_events_review.py @@ -0,0 +1,43 @@ +import numpy as np +import pytest +from baseball_batting.events import detect_events +from baseball_batting.metrics import continuous_curves +from baseball_batting.objects import possible_impact_reset + +def inputs(): + frames = [{"frame_id":i,"body_points":[[0,0]]*133,"body_states":["model_inferred"]*133, + "bat":{"points":[[10,10],[20,20]],"states":["propagated"]*2}, + "ball":{"point":[20,20],"state":"model_inferred"}} for i in range(8)] + capture = {"frames":[{"physical_s":None,"playback_s":i/30,"flags":[]} for i in range(8)], + "physical_clock_known":False,"camera_stability":"fixed_verified"} + curves = {"left_hand_path_pixels":np.zeros((8,2)),"right_hand_path_pixels":np.zeros((8,2))} + params = {"motion_threshold_px_per_frame":3,"sustained_frames":3,"min_visible_frames":4} + return {"frames":frames},capture,curves,params + +def test_projected_overlap_is_not_contact(): + obs,capture,curves,params = inputs() + events = detect_events(curves,obs,capture,{"events":[]},params) + assert next(e for e in events if e.type == "contact").state == "unknown" + assert possible_impact_reset([{"class_id":32,"box":[18,18,22,22]}], obs["frames"][0]["bat"]) + +def test_propagated_bat_is_not_direct_measurement(): + obs,capture,_,_ = inputs() + curves = continuous_curves(obs,capture) + assert np.isnan(curves["bat_endpoints_pixels"]).all() + +@pytest.mark.parametrize("outcome", ["contact", "miss", "dry_swing"]) +def test_reviewed_outcome_preserved(outcome): + obs,capture,curves,params = inputs() + labels = {"annotator":"fixture", "events":[{"type":outcome,"state":"confirmed","frame_interval":[2,3], + "evidence_frames":[2,3],"evidence_description":"Test fixture"}]} + events = detect_events(curves,obs,capture,labels,params) + event = next(e for e in events if e.type == outcome) + assert event.state == "confirmed" and event.annotator == "fixture" + assert event.physical_interval_s == [None,None] + +def test_conflicting_reviewed_outcomes_rejected(): + obs,capture,curves,params = inputs() + labels = {"annotator":"fixture", "events":[{"type":outcome,"state":"confirmed","frame_interval":[2,3]} + for outcome in ("contact","miss")]} + with pytest.raises(ValueError,match="Conflicting"): + detect_events(curves,obs,capture,labels,params) diff --git a/tests/test_geometry_fitting.py b/tests/test_geometry_fitting.py new file mode 100644 index 0000000000000000000000000000000000000000..37bd0c8bb1582a0893442f2302d9d2c2581793b7 --- /dev/null +++ b/tests/test_geometry_fitting.py @@ -0,0 +1,56 @@ +import numpy as np +import pytest +import yaml +from pathlib import Path +from scipy.spatial.transform import Rotation +from baseball_batting.geometry import project,triangulate,barrel_from_independent_knob,to_world +from baseball_batting.motion import angular_velocity,wrapped_difference +from baseball_batting.bat3d import reconstruct_frame +from baseball_batting.temporal3d import fit_sequence + +def test_independent_knob_does_not_disambiguate_two_depths(): + k=np.diag([100.,100.,1.]) + with pytest.raises(ValueError,match="ambiguous"): + barrel_from_independent_knob([0,0,4],[0,0],k,1.) + np.testing.assert_allclose(barrel_from_independent_knob([0,0,4],[0,0],k,1.,anchor=[0,0,5]),[0,0,5]) + +def test_triangulation_known_geometry_and_parallel_rejection(): + k=np.array([[800,0,320],[0,800,240],[0,0,1.]]) + a=k@np.c_[np.eye(3),np.zeros(3)];b=k@np.c_[np.eye(3),[-1,0,0]] + point=np.array([.2,.4,4.]);pixels=np.array([project(point,k),project(point-[1,0,0],k)]) + fitted,error=triangulate(pixels,[a,b]) + np.testing.assert_allclose(fitted,point,atol=1e-8);assert error<1e-8 + with pytest.raises(ValueError,match="parallel"):triangulate([pixels[0],pixels[0]],[a,a]) + +def test_rotation_log_velocity_wrap_and_missing_interval(): + times=np.array([0,.02,.05,.1,.2]);r=Rotation.from_euler("y",170+times*100,degrees=True).as_matrix() + rate=angular_velocity(r,times) + np.testing.assert_allclose(rate[:,1],np.deg2rad(100),atol=1e-8) + r[2]=np.nan;assert np.isnan(angular_velocity(r,times)).all() + assert np.isclose(np.degrees(wrapped_difference(np.deg2rad(-179),np.deg2rad(179))),2) + +def test_bat_multiview_known_length_and_independence(): + k=np.diag([500.,500.,1.]);cams=[k@np.c_[np.eye(3),[0,0,0]],k@np.c_[np.eye(3),[-1,0,0]]] + xyz=np.array([[0,0,4],[.8,0,4.]]) + record={"source":"fixture calibrated cameras","independent":True,"synchronization_verified":True,"world_axes":"x_pitcher_y_up_z_right_handed", + "projection_matrices":np.array(cams).tolist(),"endpoints_pixels":[project(xyz,k).tolist(),project(xyz-[1,0,0],k).tolist()]} + points,error,space=reconstruct_frame(record,"calibrated_multiview",{},.8) + np.testing.assert_allclose(points,xyz,atol=1e-8) + record["independent"]=False + with pytest.raises(ValueError,match="independent"):reconstruct_frame(record,"calibrated_multiview",{},.8) + +def test_temporal_optimizer_reduces_reprojection_and_shares_shape(): + torch=pytest.importorskip("torch") + n=5;k=torch.tensor([[100.,0,50],[0,100,50],[0,0,1]]) + template=torch.zeros(70,3);template[:,0]=torch.linspace(-.5,.5,70);template[:,1]=torch.linspace(-.4,.4,70) + def forward(shape,motion,scales,camera): + return template[None]*(1+shape[0])+motion[:,3:6,None].transpose(1,2)*.01+camera[:,None] + initial={"motion":torch.zeros(n,136),"shape":torch.zeros(n,45),"scales":torch.zeros(n,68), + "camera":torch.tensor([[.1,0,3.]]*n),"keypoints":template[None].repeat(n,1,1)+torch.tensor([.1,0,3.]),"intrinsics":k} + target=template.numpy()+[0,0,3.];pixels=np.repeat(project(target,k.numpy())[None],n,0) + settings=yaml.safe_load((Path(__file__).resolve().parents[1]/"configs/fitting.yaml").read_text()) + settings.update(adam_steps=10,lbfgs_steps=5,initializer_weight=0,temporal_weight=0) + fit=fit_sequence(forward,initial,pixels,np.ones((n,70)),np.arange(n)*.01,settings,frame_ids=[0,1,4,5,6]) + assert np.nanmean(fit["reprojection_px"])<.5 + assert fit["shared_shape"].shape==(45,) + assert np.isfinite(fit["keypoints_m"]).all() diff --git a/tests/test_learning_validation.py b/tests/test_learning_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..1036a8b2c20e9d0d946e766d99b00b64eec1c891 --- /dev/null +++ b/tests/test_learning_validation.py @@ -0,0 +1,44 @@ +import os +from pathlib import Path +import numpy as np +import pytest +from baseball_batting.learning import endpoint_network,temporal_network,qualification +from baseball_batting.training import train,evaluate +from baseball_batting.storage import atomic_json,sha256_file +from baseball_batting.dataset import validate_splits + +def test_athlete_and_video_split_leakage_rejected(video): + records=[{"player_id":"a","session_id":"a1","split":"train","video_path":str(video)}, + {"player_id":"a","session_id":"a2","split":"test","video_path":str(video)}] + with pytest.raises(ValueError,match="Athlete leakage"):validate_splits(records) + records[1]["player_id"]="b" + with pytest.raises(ValueError,match="Identical video leakage"):validate_splits(records) + +def test_endpoint_training_and_inactive_checkpoint(tmp_path): + torch=pytest.importorskip("torch");torch.set_num_threads(1) + directory=tmp_path/"dataset";directory.mkdir();samples=[] + yy,xx=np.mgrid[:64,:64];target=np.array([np.exp(-((xx-15)**2+(yy-25)**2)/4),np.exp(-((xx-45)**2+(yy-35)**2)/4)],np.float32) + for i,split in enumerate(("train","validation","test")): + path=directory/f"{split}.npz" + np.savez_compressed(path,image=np.full((256,256,3),100+i,np.uint8),heatmaps=target,visible=np.ones(2),visibility_mask=np.ones(2)) + samples.append({"path":path.name,"player_id":split,"session_id":split,"split":split}) + atomic_json(directory/"dataset.json",{"kind":"endpoint_cnn","samples":samples,"artifact_hashes":{r["path"]:sha256_file(directory/r["path"]) for r in samples}}) + output=tmp_path/"model";record=train(directory,output,"endpoint_cnn",epochs=2) + assert record["qualification"]["status"]=="candidate" + with pytest.raises(ValueError,match="qualification"):qualification(output/"checkpoint.json",output/"checkpoint.pt","endpoint_cnn") + gates=tmp_path/"gates.json";atomic_json(gates,{"preregistered":True,"source":"synthetic implementation fixture; not accuracy qualification", "maximum":{"median_error":0},"minimum":{"absent_labels":1}}) + evaluation=evaluate(directory,output,gates,"synthetic_fixture_only") + assert evaluation["passed"] is False + assert evaluation["metrics"]["positive_labels"]==2 + assert evaluation["metrics"]["extra_rate"] is None + with pytest.raises(ValueError,match="qualification"):qualification(output/"checkpoint.json",output/"checkpoint.pt","endpoint_cnn") + +def test_mstcn_phase_boundary_presence_gradients(): + torch=pytest.importorskip("torch");torch.set_num_threads(1) + source=os.environ.get("BATTING_MSTCN_SOURCE") + if not source:pytest.skip("Pinned upstream source not configured for this test profile") + model,provenance=temporal_network(source,{"prediction_layers":2,"refinement_layers":2,"refinements":1,"channels":8,"feature_dim":12}) + phase,boundary,presence=model(torch.rand(1,12,17)) + assert phase.shape==(2,1,5,17) and boundary.shape==(1,6,17) and presence.shape==(1,6) + (phase.square().mean()+boundary.square().mean()+presence.square().mean()).backward() + assert all(p.grad is not None for p in model.parameters()) diff --git a/tests/test_notebook.py b/tests/test_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..542e186086f1421c5d3936dece1a61286229ee5b --- /dev/null +++ b/tests/test_notebook.py @@ -0,0 +1,175 @@ +import ast +import base64 +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import importlib.util +from pathlib import Path +import subprocess +from threading import Thread +import nbformat +import pytest + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("colab_github", ROOT / "tools/colab_github.py") +bootstrap = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bootstrap) + + +def test_notebook_schema_cells_and_readable_bootstrap(): + notebook = nbformat.read(ROOT / "notebooks/batting_engine.ipynb", as_version=4) + nbformat.validate(notebook) + cells = [cell.source for cell in notebook.cells if cell.cell_type == "code"] + for cell in cells: + ast.parse(cell) + assert cells[0].startswith((ROOT / "tools/colab_github.py").read_text()) + assert "checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)" in cells[0] + assert "base64.b64decode" not in cells[0] + assert '"clone", "--no-checkout"' in cells[0] + assert "source_checkout.json" in "\n".join(cells) + assert 'runtime = WORKSPACE_ROOT /' in cells[1] + + +def git(directory, *arguments): + return subprocess.run(["git", "-C", str(directory), *arguments], check=True, + capture_output=True, text=True).stdout.strip() + + +@pytest.fixture +def github_repository(tmp_path, monkeypatch): + """Exercise real Git fetch/checkout without a network or GitHub account.""" + remote = tmp_path / "remote" + remote.mkdir() + git(remote, "init", "--quiet", "--initial-branch=main") + for name in ("baseball_batting/cli.py", "requirements-core.txt", "configs/resources.yaml"): + path = remote / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("first version\n") + git(remote, "add", ".") + git(remote, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "commit", "--quiet", "-m", "First fixture") + first = git(remote, "rev-parse", "HEAD") + (remote / "baseball_batting/cli.py").write_text("second version\n") + git(remote, "add", ".") + git(remote, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "commit", "--quiet", "-m", "Second fixture") + second = git(remote, "rev-parse", "HEAD") + url = "https://github.com/fixture/batting-engine" + monkeypatch.setenv("GIT_CONFIG_COUNT", "1") + monkeypatch.setenv("GIT_CONFIG_KEY_0", f"url.{remote.as_uri()}.insteadOf") + monkeypatch.setenv("GIT_CONFIG_VALUE_0", url) + return url, first, second + + +def test_checkout_pins_revisions_and_preserves_runtime_files(tmp_path, github_repository): + url, first, second = github_repository + workspace = tmp_path / "workspace" + source, record = bootstrap.checkout_github(url, first, workspace) + assert record["commit_sha"] == first + assert (source / "baseball_batting/cli.py").read_text() == "first version\n" + outputs = workspace / "artifacts" + outputs.mkdir() + (outputs / "result.json").write_text("existing output") + source, record = bootstrap.checkout_github(url, "main", workspace) + assert record["commit_sha"] == second + assert git(source, "rev-parse", "HEAD") == second + assert (outputs / "result.json").read_text() == "existing output" + assert (workspace / "source_checkout.json").is_file() + + +def test_checkout_refuses_local_edits_and_different_repository(tmp_path, github_repository): + url, first, _ = github_repository + workspace = tmp_path / "workspace" + source, _ = bootstrap.checkout_github(url, first, workspace) + edited = source / "baseball_batting/cli.py" + edited.write_text("my local edits") + with pytest.raises(ValueError, match="local edits"): + bootstrap.checkout_github(url, "main", workspace) + assert edited.read_text() == "my local edits" + assert git(source, "rev-parse", "HEAD") == first + with pytest.raises(ValueError, match="different repository"): + bootstrap.checkout_github("https://github.com/fixture/other", "main", workspace) + assert edited.read_text() == "my local edits" + + +def test_private_credentials_are_transient(tmp_path, github_repository): + url, first, _ = github_repository + token = "fixture-secret-never-saved" + original_count = bootstrap.os.environ.get("GIT_CONFIG_COUNT") + with bootstrap._github_credentials(token) as environment: + assert "GIT_ASKPASS" not in environment + assert bootstrap.os.environ.get("GIT_CONFIG_COUNT") == original_count + workspace = tmp_path / "workspace" + source, record = bootstrap.checkout_github(url, first, workspace, token=token) + assert token not in (source / ".git/config").read_text() + assert token not in (workspace / "source_checkout.json").read_text() + assert "BATTING_GITHUB_TOKEN" not in bootstrap.os.environ + + +def test_git_sends_private_credentials_over_http(tmp_path): + """Exercise real Git HTTP authentication without a GitHub token or account.""" + token = "fixture-private-token" + expected = "Basic " + base64.b64encode(f"x-access-token:{token}".encode()).decode() + authenticated_requests = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *arguments): + pass + + def do_GET(self): + if self.headers.get("Authorization") != expected: + self.send_response(401) + self.send_header("WWW-Authenticate", 'Basic realm="fixture"') + self.end_headers() + return + authenticated_requests.append(self.path) + body = b"ref: refs/heads/main\n" if self.path.endswith("/HEAD") else b"0123456789012345678901234567890123456789\trefs/heads/main\n" + self.send_response(200) + self.send_header("Content-Type", "text/plain") + self.end_headers() + self.wfile.write(body) + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + scope = f"http://127.0.0.1:{server.server_port}/" + with bootstrap._github_credentials(token, scope=scope) as environment: + output = bootstrap._git(tmp_path, "-c", "credential.helper=", "ls-remote", + scope + "repo.git", auth_env=environment) + assert "0123456789012345678901234567890123456789\trefs/heads/main" in output + assert authenticated_requests + finally: + server.shutdown() + server.server_close() + thread.join() + + +@pytest.mark.parametrize("detail", [ + "fatal: Authentication failed", "remote: Repository not found", + "fatal: couldn't find remote ref missing", "fatal: Could not resolve host: github.com", +]) +def test_git_errors_include_detail_without_credentials(tmp_path, monkeypatch, detail): + token = "fixture-sensitive-token" + encoded = base64.b64encode(f"x-access-token:{token}".encode()).decode() + def fail(*arguments, **kwargs): + return subprocess.CompletedProcess(arguments[0], 128, "", detail + " " + token + " " + encoded) + monkeypatch.setattr(bootstrap.subprocess, "run", fail) + with pytest.raises(RuntimeError) as error: + bootstrap._git(tmp_path, "fetch", auth_env={"BATTING_GITHUB_TOKEN": token}) + assert detail in str(error.value) + assert token not in str(error.value) + assert encoded not in str(error.value) + + +@pytest.mark.parametrize("url,revision", [ + ("", "main"), + ("https://token@github.com/owner/repo", "main"), + ("https://github.com/owner/repo?token=example", "main"), + ("https://github.com/../repo", "main"), + ("https://github.com/owner/repo", "--help"), + ("https://github.com/owner/repo", "main extra"), +]) +def test_checkout_rejects_invalid_settings_before_writing(tmp_path, url, revision): + workspace = tmp_path / "workspace" + with pytest.raises(ValueError): + bootstrap.checkout_github(url, revision, workspace) + assert not workspace.exists() diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..754a5012d9977fa348a416a64644ce0f1cb13212 --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,96 @@ +from pathlib import Path +import json +import numpy as np +import pytest +from baseball_batting.pipeline import run_engine +from baseball_batting.config import EngineConfig +from baseball_batting.storage import sha256_file, atomic_json +from baseball_batting.ingest import iter_frames + +def reviewed_labels(video, tmp_path): + frames = {} + for i in range(8): + frames[str(i)] = {"landmarks": {"left_shoulder":[30,40], "left_elbow":[40,40], "left_wrist":[50+i,40], + "right_shoulder":[70,40], "right_elbow":[80,40], "right_wrist":[90+i,40], + "left_hip":[40,60], "left_knee":[40,80], "left_ankle":[40,100], + "right_hip":[80,60], "right_knee":[80,80], "right_ankle":[80,100]}, + "knob":[60+i,40], "barrel":[100+i,30]} + path = tmp_path / "reviewed.json" + atomic_json(path, {"schema_version":"1.0", "input_sha256":sha256_file(video), "annotator":"fixture_operator", + "frames":frames, "events":[{"type":"dry_swing","state":"confirmed","frame_interval":[0,7], + "evidence_frames":[0,1,2,3,4,5,6,7],"evidence_description":"Synthetic fixture has no ball"}]}) + return path + +def test_no_models_returns_honest_partial(video,tmp_path): + root = tmp_path / "out" + result = run_engine(video,root,EngineConfig(chunk_size=3)) + assert result["status"] == "partial" + assert all(m["value"] is None for m in result["metrics"]) + assert result["stages"]["body_pose"]["status"] == "unavailable" + assert next(e for e in result["events"] if e["type"] == "contact")["state"] == "unknown" + assert not result["findings"] + assert (root/"report.html").exists() + assert result["stages"]["video_export"]["status"] == "complete", result["stages"]["video_export"] + src = [(pts*tb) for _,pts,tb,_ in iter_frames(video)] + dst = [(pts*tb) for _,pts,tb,_ in iter_frames(root/"annotated.mp4")] + np.testing.assert_allclose([float(x) for x in src],[float(x) for x in dst],atol=.001) + +def test_reviewed_metrics_and_unknown_physical_speed(video,tmp_path): + labels = reviewed_labels(video,tmp_path) + result = run_engine(video,tmp_path/"out",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=3), + {"camera_stability":"fixed_verified", "player_id":"generated_fixture"}) + assert result["provenance"] == "human_assisted" + metrics = {m["metric_id"]:m for m in result["metrics"]} + assert metrics["left_elbow_projected_flexion_deg_median"]["value"] == pytest.approx(0) + assert metrics["left_hand_projected_path_length"]["value"] == pytest.approx(7) + assert metrics["left_hand_projected_path_length"]["provenance"] == ["manual"] + assert metrics["left_hand_peak_projected_speed"]["value"] is None + assert metrics["bat_sweet_spot_speed_at_contact"]["value"] is None + assert next(e for e in result["events"] if e["type"] == "dry_swing")["state"] == "confirmed" + assert all(f["expert_review"] == "not_reviewed" and f["research_exercise"] is None for f in result["findings"]) + +def test_resume_verifies_chunks_and_annotation_invalidates(video,tmp_path): + labels = reviewed_labels(video,tmp_path) + root = tmp_path/"out" + cfg = EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=3,export_video=False) + first = run_engine(video,root,cfg) + chunks = sorted((root/"stages"/"observations").rglob("chunk_*.json")) + before = {str(p):p.stat().st_mtime_ns for p in chunks} + second = run_engine(video,root,cfg) + assert first["metrics"] == second["metrics"] + assert before == {str(p):p.stat().st_mtime_ns for p in chunks} + # An incomplete/corrupt chunk is rerun instead of trusted. + record = next(p for p in chunks if p.name.endswith("000001.json")) + record.write_text("corrupt") + run_engine(video,root,cfg) + assert json.loads(record.read_text())["frames"][0]["frame_id"] == 3 + labels_data = json.loads(labels.read_text()) + labels_data["frames"]["0"]["landmarks"]["left_elbow"] = [40,50] + atomic_json(labels,labels_data) + run_engine(video,root,cfg) + assert len(list((root/"stages"/"observations").iterdir())) == 2 + +def test_chunk_equivalence(video,tmp_path): + labels = reviewed_labels(video,tmp_path) + a = run_engine(video,tmp_path/"a",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=2,export_video=False)) + b = run_engine(video,tmp_path/"b",EngineConfig(mode="operator_reviewed",annotations_path=str(labels),chunk_size=99,export_video=False)) + assert a["metrics"] == b["metrics"] + assert a["events"] == b["events"] + +def test_missing_gpu_does_not_block_2d(video,tmp_path): + result = run_engine(video,tmp_path/"out",EngineConfig(body3d_enabled=True,export_video=False)) + assert result["stages"]["body3d"]["status"] == "unavailable" + assert result["stages"]["observations"]["status"] == "empty" + +def test_untrained_and_unsupported_branches_return_partial(video,tmp_path): + result = run_engine(video,tmp_path/"out",EngineConfig(learned_events_enabled=True, + bat_3d_mode="requested",export_video=False)) + assert result["stages"]["learned_events"]["status"] == "unavailable" + assert result["stages"]["learned_events"]["reason"] == "no_qualified_checkpoint" + assert result["stages"]["bat3d"]["status"] == "unavailable" + assert result["stages"]["observations"]["status"] == "empty" + +def test_html_escapes_context(video,tmp_path): + root = tmp_path/"out" + run_engine(video,root,EngineConfig(export_video=False),{"timing":{"kind":"unretimed","source":""}}) + assert "