Spaces:
Running on T4
Download docs/API_FOR_COACH.md from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/API_FOR_COACH.md
- Command line
-
hf download hf://spaces/modventures/baseball-engine@3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/API_FOR_COACH.md
-
curl -L -o API_FOR_COACH.md https://huggingface.co/spaces/modventures/baseball-engine/resolve/3249fe49e382459cd4ccd5ca1883f14ffd8b5ab4/docs/API_FOR_COACH.md
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. Optional RTMW3D and SAM event-window inference supplies the three body-angle estimates; coaching stays in your service. See all nine definitions and model selection.
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 |
GET /v1/analyses/{job_id}/load-timing |
Download the separate four-field timing JSON, version 3.0 |
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 /v1/load-timing-schema |
Four-field timing response schema |
GET /readyz |
200 after actual CUDA inference passes |
For Load and timing, use measurement_backend: "2d" on upload and download load_timing_url after completion. This returns the four calculations discussed with the coach developer rather than the existing nine-field payload. Actual contact and early/late correction remain unclear without bat/ball tracking. See LOAD_TIMING_API.md for the response shape and testing through the API documentation.
Upload example for an original, unretimed right-handed batting recording:
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. Unknown view withholds technique measurements but still permits generic motion events at video frames. With a known face-on view, moving/unknown cameras can return within-frame body positions and projected knee-angle estimates when the required events are found; ground-foot events and head paths remain withheld. 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:
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 estimates with documented nominal 30 FPS or higher capture timestamps, including 29.97 FPS. Each quantity must also pass its ±1-frame sensitivity check; shorter durations/ratios may be withheld even at higher 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.
In default 2d mode, lateral_trunk_tilt_contact_deg and hip_shoulder_separation_foot_plant_deg remain null. Select measurement_backend: "rtmw3d" or "sam3d" to attempt those angles and a 3D knee angle, subject to stability/geometry checks. These are unvalidated landmark estimates and remain reference-only. 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.
Measurement method batting-2d-v3 restricts swing onset and contact to the primary swinging movement. A later return/lowering of the hands cannot replace the swing just because it travels toward the declared pitcher direction. Missing extension during the actual swing leaves contact-dependent numbers null. Correct event selection can therefore remove numbers that older versions incorrectly calculated after the swing. The coach payload's schema and nine metric keys are unchanged; submit a new analysis to update an already completed API job.
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; 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 |
|---|---|
measurement_backend |
2d (default), rtmw3d, or sam3d; optional sparse event-window 3D |
height_m, camera, root_depth_m + root_depth_source, camera_up |
Optional geometry declarations; see definitions |
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 toward pitcher/tee; otherwise ankle ordering must agree with strong hand motion. Conflicts leave direction unknown. |
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:
{"kind":"unretimed","source":"description of the original capture evidence"}
{"kind":"constant_slowdown","source":"documented export settings","factor":8,"all_captured_frames_retained":true}
{"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 without asserting constant FPS. Version 5 supports nominal 30 FPS or higher timing when every capture interval in the rep is <= 1.01/30 seconds (1% tolerance for fractional frame rates/jitter). Missing frames, poor resolution and large ±1-frame sensitivity still withhold a metric. Full-result diagnostics expose actual frame intervals and shifted-event ranges; those ranges are not accuracy confidence intervals. An advisory low_fps reason at 30 FPS does not mean capture failed. 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, measurement_diagnostics, experimental_body3d, 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 validated kp3d or bat/ball objects are emitted. Sparse unvalidated 3D points are exposed separately in experimental_body3d; measurement_diagnostics explains the stability/sensitivity checks. Both are excluded from the coach payload.
Download only the coach payload with the example client:
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.