Spaces:
Running on T4
Download docs/LOAD_TIMING_API.md from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/LOAD_TIMING_API.md
- Command line
-
hf download hf://spaces/modventures/baseball-engine@3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/LOAD_TIMING_API.md
-
curl -L -o LOAD_TIMING_API.md https://huggingface.co/spaces/modventures/baseball-engine/resolve/3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/LOAD_TIMING_API.md
Load and swing timing API
This API measures swings for the separate coach agent. It does not choose faults, priorities or drills. Load/timing jobs use GPU person/2D pose inference plus separate GPU bat and baseball models. SAM is unnecessary for these jobs.
The four calculations now have implementation paths. That does not mean all four can be measured from every recording. Public detector accuracy on our phone footage is still unvalidated; a visible-looking preview does not validate the measurements.
Requests and versions
Every /v1/ request needs Bearer authorization with your engine API key.
| Request | Purpose |
|---|---|
POST /v1/load-timing/analyses |
Upload for timing. Rejects missing recording settings before queuing. |
GET /v1/analyses/{job_id} |
Poll status and frame progress. |
GET /v1/analyses/{job_id}/load-timing |
Existing version 3.0, four ordered metrics per swing. |
GET /v1/analyses/{job_id}/load-timing?include_evidence=true |
Opt-in version 3.1, with event intervals, metric reasons, sensitivity and practice context. |
GET /v1/load-timing-schema?include_evidence=true |
Exact schema for the evidence response. Omit the query for 3.0. |
DELETE /v1/analyses/{job_id} |
Cancel processing and delete artifacts. |
POST /v1/analyses remains compatible with previous clients, including optional body reconstruction. It now returns warnings when timing settings are missing. /coach-payload still returns version 2.0. The engine never calls the friend's coach API automatically.
Postman: one recording
Set Authorization → Bearer Token to the engine API key. In Body → form-data, add:
| Key | Type | Value |
|---|---|---|
video |
File | Original recording |
options |
Text | One JSON object, below |
Send to https://YOUR_ENGINE_HOST/v1/load-timing/analyses. This example assumes a right-handed hitter, pitcher/tee to image-left, a known face-on view and fixed camera. Change the declarations to match the actual recording.
{
"measurement_backend": "2d",
"handedness": "right",
"pitcher_direction": "image_left",
"view": "face_on",
"camera_stability": "fixed_verified",
"timing": {
"kind": "unretimed",
"source": "Original camera recording; no speed changes"
},
"single_swing": false,
"practice_type": "tee"
}
single_swing: false separates multiple swing candidates automatically; true declares exactly one. practice_type accepts tee, soft_toss, front_toss, live, machine or unknown. Tee contact needs the stationary ball before impact and its outgoing movement after impact. A disappearing ball alone is insufficient.
Optional pitch_speed_mps, pitch_location and pitch_context_source carry supplied practice information. They are not measured automatically. Unknown pitch conditions remain unknown so the agent can avoid comparing unlike sessions. Timing uses original capture timestamps; a downloaded or slowed video must not be declared unretimed without evidence. See capture clock options.
Wait for status: "completed", then request the returned load_timing_url or load_timing_evidence_url. The same flow is available in /docs using Authorize → Try it out.
What the calculations mean
| Metric | Calculation and interpretation |
|---|---|
load_to_swing_ms |
Forward hand-based swing onset minus the start of backward hand preparation. The existing onset definition is unchanged. |
foot_down_to_swing_ms |
Forward onset minus first front-foot landing, when a step is supported. Negative means the swing starts before landing. Missing foot events mean unknown, not no-step. |
swing_duration_ms |
Supported contact time minus forward onset. For a physical miss, uses closest_approach, explicitly separate from contact. |
early_late_shift_ms |
For a supported miss, shift the same observed bat path in time against the unchanged ball path. Negative means repeat earlier; positive means repeat later. This does not predict the player's ability to execute the adjustment. |
A single phone can support an estimated visual hit interval when actual bat landmarks and independently observed ball movement establish the interaction. The arm-extension proxy is never used as contact. Screen-space overlap does not establish a physical miss or timing correction.
All values stay confidence: "est". No independently validated accuracy class is available. Capture cadence, visibility, coverage and event-interval sensitivity can withhold individual values even when other metrics are available. The cadence floor is nominal 30 FPS (including 29.97), not a promise of useful contact detection at 30 FPS. Decimal milliseconds describe arithmetic, not millisecond accuracy.
Two views: physical misses and timing correction
Add a second form-data File named secondary_video and an options.stereo_tracking object. Both must be supplied together. The primary upload still uses the known face-on body view. Cameras must cover the same swing, remain fixed, and have measured intrinsics, lens distortion, relative position/rotation and time alignment.
Required stereo_tracking fields:
| Field | Meaning |
|---|---|
cameras |
Exactly two camera objects in primary/secondary order. Each has intrinsics (3×3), rotation (3×3), translation_m (3), and optional distortion (4, 5 or 8 coefficients). |
source |
How calibration was obtained. Coordinates refer to the upright decoded images. Extrinsics map world to camera: X_camera = rotation @ X_world + translation_m. |
secondary_offset_s |
Add this value to secondary capture time to align with the primary clock. |
synchronization_source, synchronization_bound_ms |
How alignment was measured and its supplied error bound. Starting both phones together is insufficient. |
position_bound_m, position_bound_source |
Supplied spatial error bound, including detection, calibration, bat endpoint definition and interpolation error. A model score is not this bound. |
bat_length_m, barrel_radius_m |
Measured dimensions. |
barrel_start_fraction |
Start of the target barrel along knob-to-cap length; default 0.5. |
ball_radius_m |
Default 0.0366; replace if appropriate to the recorded ball. |
secondary_timing |
Documented capture clock, same structure as primary timing. |
secondary_rotation_degrees |
Optional explicit orientation, 0/90/180/270 clockwise. |
max_shift_ms |
Search limit in each direction, default 250, maximum 1000. |
The API checks ray geometry, positive depth, reprojection agreement, measured bat length, endpoint identity, clock cadence, visibility and complete primary-swing coverage. Missing observations do not become filled-in impact evidence. Adjacent second-view samples may be interpolated only between directly observed detections with usable cadence; they retain their interpolation state.
The physical model is a bat capsule and ball sphere on piecewise linear paths. Closest approach uses the whole observed bat; timing correction targets the declared barrel. Spatial and synchronization bounds are propagated conservatively under this model. They remain supplied assumptions, not validated accuracy. Position error larger than the collision margin can make a correction unavailable.
The correction searches supported footage without extrapolation and retains disconnected feasible shift intervals. It returns a scalar only for one sign-stable interval with a certified interior solution under the supplied bounds. The policy is closest-to-zero certified feasible shift, not the centre of an assumed probability distribution. Coverage/search boundaries, ambiguity and insufficient resolution yield nulls.
Tee misses do not receive a moving-pitch early/late correction. Two-view reconstruction uses the objects, not a SAM body mesh.
Evidence response
Version 3.1 preserves the four metric meanings and adds:
context: supplied practice type/pitch facts and provenance.reps[].events: event method, frame/capture-time interval and uncertainty kind.reps[].outcome_method: how hit/miss evidence was established.- Each metric:
reason_code,uncertainty, and optionalfeasible_shift_intervals_ms.
uncertainty.accuracy_validated is always false. Frame sensitivity is not a calibrated accuracy interval. See the synthetic example and schema. Default 3.0 has exactly its previous structure, so old strict validators continue to work.
Common unavailable reasons include capture_failed, capture_time_unknown, forward_swing_unresolved, step_unresolved, timing_interval_unresolved, bat_endpoints_unobserved_or_ambiguous, ball_trajectory_unobserved_or_ambiguous, contact_evidence_insufficient, depth_unresolved, spatial_track_incomplete, bat_geometry_ambiguous, barrel_identity_unresolved, ball_identity_ambiguous, incoming_ball_motion_unresolved, camera_motion_unresolved, synchronization_unresolved, ambiguous_time_shift, shift_search_boundary, spatial_coverage_insufficient, shift_unresolved_under_position_error, and search_resolution_insufficient.
no_feasible_shift_in_observed_window is limited to the supported footage and search range; it is not a diagnosis of bad mechanics or a claim about unseen paths. stationary_tee_ball_no_pitch_timing, hit_no_correction_needed and no_step explain inapplicable calculations.
Deployment and artifacts
Rebuild the GPU Docker image. Its build downloads checksummed BaseballCV bat/ball checkpoints and exports static ONNX in a separate build stage. PyTorch/Ultralytics are build dependencies; inference uses ONNX Runtime CUDA. Startup executes all required models on CUDA. The timing upload route requires /readyz to report bat_ball_tracking_ready: true; legacy body-only installations remain compatible with the old upload route.
New jobs save checksummed load-timing.json and load-timing-evidence.json. Server diagnostics retain direct observations, model identities and calculation evidence. Database migration adds hashes without losing existing jobs. Original uploads, including the second view, are deleted after terminal jobs. Previous completed jobs need resubmission for new artifacts. Results before completion return 409; integrity failures return 500.
See deployment and validation results and remaining model limits. The Python client supports --load-timing, optional --include-evidence, and optional --secondary-video with calibration in its options file.