Spaces:
Running on T4
Running on T4
|
Download docs/MOTION_PLAYER_API.md from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 22.1 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/fe40b87ae08cb37d62b88a8e607f4dfd9282afba/docs/MOTION_PLAYER_API.md
- Command line
-
hf download hf://spaces/modventures/baseball-engine@fe40b87ae08cb37d62b88a8e607f4dfd9282afba/docs/MOTION_PLAYER_API.md
-
curl -L -o MOTION_PLAYER_API.md https://huggingface.co/spaces/modventures/baseball-engine/resolve/fe40b87ae08cb37d62b88a8e607f4dfd9282afba/docs/MOTION_PLAYER_API.md
22.1 kB
| # Motion-player backend API | |
| Contract 1.0 · SAM and GVHMR adapters · native-body refinement · 23 October 2026 | |
| For app implementation, start with the [frontend integration guide](APP_API_INTEGRATION.md), | |
| updated 19 October 2026. It covers migration, authenticated video playback, | |
| multi-swing range playback, measurement cards and skeleton/graph synchronization. | |
| Base URL: `https://modventures-baseball-engine.hf.space`. Use the existing server | |
| Bearer key for every `/v1/` request. Keep that shared credential in your app's | |
| backend. This separate API preserves the current engine/product/SAM contracts. | |
| It exports actual corrected motion for an interactive skeleton player, using | |
| SAM 3D Body or GVHMR through the same routes. A client frontend and animated | |
| body mesh are outside this version. Existing callers continue to default to SAM. | |
| For the AI coach's strict three-measurement payload, see | |
| [single-swing coach export](MOTION_COACH_PAYLOAD.md). Add player information and | |
| an optional reviewed `contact_frame` to the existing request; previous options | |
| and motion artifacts are preserved. | |
| ## Choose the model | |
| Set `model` inside the existing form-data `options` JSON: | |
| ```json | |
| {"model": "sam3d", "annotated_videos": true} | |
| ``` | |
| or: | |
| ```json | |
| {"model": "gvhmr", "annotated_videos": true} | |
| ``` | |
| Every recording fact, polling route and artifact format stays the same. Read | |
| `GET /v1/motion-analyses/capabilities`: `models` lists both adapters with their | |
| individual `configured` status and setup reason. One unavailable model does not | |
| disable the other. An unconfigured selection returns 503 before reserving a job. | |
| Unknown model names return 422. There is no silent fallback to another model. | |
| GVHMR needs a licensed SMPL-X neutral file; see [GVHMR setup](GVHMR_SETUP.md). | |
| To compare the **same recording**, first run either model, then submit a new | |
| analysis with the completed manifest's `source_video.asset_id` in the | |
| `source_asset_id` form field and the other model in `options`. This reuses the | |
| original bytes without another upload. Alternatively change `model` through | |
| `/revisions`; it creates a new immutable revision and runs fresh inference. | |
| The parent artifacts remain unchanged. This API does not use Gemini. | |
| Both adapters declare the same 20 canonical names. Their native anatomical | |
| definitions differ: SAM uses MHR70 landmarks; GVHMR uses SMPL-X joint centers | |
| and its explicitly documented ear/foot surface landmarks. The SMPL-X adapter has | |
| its own `batting-corrected-points-smplx-v1` measurement definition revision, | |
| retaining the companion document's formulas. Do not pool numbers from different | |
| models as interchangeable measurements or use a model switch as evidence of | |
| player improvement. Each manifest records the actual native indices/definitions. | |
| ## Routes | |
| | Method and path | Purpose | | |
| | --- | --- | | |
| | `POST /v1/motion-analyses` | Multipart video or existing source asset; returns 202. | | |
| | `GET /v1/motion-analyses/{job_id}` | Status, progress, immutable revision and failure reason. | | |
| | `GET /v1/motion-analyses/{job_id}/result` | Completed manifest and artifact URLs. | | |
| | `GET /v1/motion-analyses/{job_id}/coach-payload` | Opt-in single-swing measurement payload matching the coach's contract 1.0. | | |
| | `GET` / `HEAD /v1/motion-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; byte ranges supported. | | |
| | `POST /v1/motion-analyses/{job_id}/revisions` | Recording-fact/correction/event patch into a new immutable revision. | | |
| | `DELETE /v1/motion-analyses/{job_id}` | Cancel/delete this execution and its retained files. | | |
| | `GET /v1/motion-analyses/capabilities` | Model/configuration, limits and retention. | | |
| | `GET /v1/motion-analyses/input-schema` | Recording options schema. | | |
| | `GET /v1/motion-analyses/output-schema` | Manifest, motion-frame, projection-frame and coach-payload schemas. | | |
| ## Upload and polling | |
| In form-data, `video` is a File and `options` is Text containing JSON. Alternatively | |
| omit `video` and send `source_asset_id` from a completed motion manifest. Exactly | |
| one source is required; remote URLs and server paths are not accepted. | |
| Example options, **only when these recording facts are known**: | |
| ```json | |
| { | |
| "model": "sam3d", | |
| "handedness": "right", | |
| "handedness_source": "Uploader supplied", | |
| "camera_stability": "fixed_verified", | |
| "timing": {"kind": "unretimed", "source": "Original speed verified by uploader"}, | |
| "single_swing": false, | |
| "annotated_videos": true | |
| } | |
| ``` | |
| Other options reuse the SAM input: upright-image camera intrinsics; documented | |
| `up_vector` and `pitcher_vector`; uniform `scale_factor` and its source; | |
| `lead_foot`, `athlete_box`, correction settings and reviewed `windows` in decoded | |
| source-frame indices. `scale_status` defaults to `model_estimated`; `calibrated` | |
| requires a calibration source; `unknown` exports model units and disables absolute | |
| distances/linear speeds. Height alone is not camera calibration. `source_mirrored` | |
| records the source information; the adapter does not silently flip/relabel it. | |
| `camera.distortion` optionally supplies five Brown–Conrady coefficients in | |
| `[k1,k2,p1,p2,k3]` order, calibrated in the upright displayed image convention. | |
| Fitting and projections use the same distortion model; the source video is not | |
| warped. With no coefficients the pinhole assumption remains explicit. Calibrated | |
| ground translation is not supplied. Missing calibration does not prevent motion export. | |
| Coaching/LLM calls are disabled on this path. | |
| When `up_vector` is omitted/null, the shared pipeline estimates it from sampled | |
| video frames using GeoCalib. Reliable estimates populate effective calculation | |
| inputs, with `up_source` and diagnostics in `coordinates.up_estimation`; submitted | |
| inputs stay unchanged. Explicit vectors take priority. Unreliable estimates stay | |
| unknown, and camera stability, scale and timing checks still apply. A declared | |
| pitcher direction may be supplied before vertical is resolved. See | |
| [automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates, | |
| acceptance checks, FE labels and the `up_estimation.enabled` opt-out. | |
| When no pitcher vector or floor points are supplied, both models automatically | |
| estimate hitting direction from a stable batting setup followed by hand and | |
| torso movement (`automatic_body_swing_direction_v2`). No plate, field markings, | |
| handedness, camera intrinsics, or user direction input is required. The existing | |
| automatic up estimate is used. Missing or conflicting evidence leaves direction | |
| unknown without stopping the job. This is an approximate batting direction based | |
| on the setup hip line, not a measurement of an unseen pitcher's location. The | |
| output names this reference `estimated_batting_axes`, records the supporting | |
| frames in `coordinates.pitcher_estimation`, and flags affected measurements with | |
| `pitcher_reference_estimated_from_body_motion` and `target_alignment_unverified`. | |
| Accuracy on real labelled videos has not been validated. | |
| For an optional manual override, send `pitcher_floor_points` with `source_frame_index`, | |
| `near_batter` and `toward_pitcher` in upright source pixels. This uses supplied | |
| camera calibration marked `camera.calibration_status: "calibrated"` and supplied | |
| or accepted estimated up. Explicit pitcher vectors take priority. Returned | |
| `coordinates.pitcher_estimation` records the source, assumptions and rejection | |
| reasons. See [floor-point direction and FE integration](PITCHER_FLOOR_DIRECTION.md). | |
| ## Native-body refinement | |
| New motion jobs enable `refinement.enabled` by default. Existing engine and SAM | |
| coaching APIs retain their processing paths. To compare against the previous | |
| correction, create a revision with `{"refinement":{"enabled":false}}`; the native | |
| model outputs are reused when their integrity and recording facts still match. | |
| Processing is: native reconstruction → independent RTMW image observations and | |
| forward/backward optical-flow checks → native-rig fitting → acceptance checks → | |
| one corrected sequence for motion, measurements, projections, and annotation. | |
| SAM now retains its native shape/motion parameters and exact MHR landmark | |
| regressor. GVHMR fits SMPL-X parameters in its own isolated interpreter. Their | |
| anatomical definitions remain separate; model outputs are never averaged. | |
| Each continuous identity/model segment uses a shared robust body-shape estimate. | |
| The optimizer changes native pose and camera translation, using soft image | |
| constraints, initializer priors and timestamp-aware temporal penalties. RTMW | |
| landmarks are homologous observations, not asserted identical anatomical joint | |
| centres or calibrated visibility/depth scores. LK checks both neighboring images; | |
| only reliable forward/backward cycles can contradict a detector, and either | |
| neighbor can corroborate it. A tracking failure alone does not invalidate a 2D | |
| observation. These checks adjust weights and never create a missing landmark. Shape/scale priors do | |
| not establish physical calibration. Native rig constraints and initializer priors | |
| apply; no unsupported anatomical angle limits are invented. | |
| Fitting optimizes one continuous native-parameter trajectory per valid segment. | |
| Native rig evaluation and gradient recomputation use batches of eight frames, | |
| bounding mesh activation memory without splicing separately fitted trajectories. | |
| Vector–Jacobian products use the full trajectory's point gradients, including | |
| temporal terms across batch boundaries; this is the same gradient as one complete | |
| native evaluation, verified by a cross-boundary gradient-equivalence test. | |
| Overlapping quality windows accept/reject regions of that same fit; they do not | |
| introduce processing seams or derivative gaps by themselves. Missing observations, | |
| identity/model boundaries, clock gaps and actual raw/refined switches remain | |
| derivative boundaries. No pose | |
| is generated through a missing interval. Rapid movement receives weaker temporal | |
| regularization. Image-supported fast hand peaks are checked for timing and speed | |
| distortion. Accepted fitted points bypass the old independent-joint filter so | |
| their rig geometry is preserved. Rejected windows retain native predictions; | |
| strong image disagreement additionally disables the conflicting joints. | |
| `pipeline.refinement` (also in `quality.correction.whole_body_refinement`) records | |
| accepted/fallback frame counts, per-window reasons, settings, implementation | |
| hash, image evidence and diagnostics. Each frame reports | |
| `whole_body_refinement_accepted`; joint reasons distinguish an accepted fit from | |
| native fallback. Fallback is not presented as verified motion. Native parameters, | |
| fitting candidates, evidence and raw debug arrays remain private. | |
| Robust background image displacement checks a declared static camera. Multiple | |
| contradictory observations set `declared_static_camera_conflict`; calculation | |
| inputs then use moving/uncertain camera semantics and dependent measurements are | |
| withheld. Original submitted inputs and effective `calculation_inputs` are both | |
| recorded, so measurements remain reproducible. Background displacement is not a | |
| calibrated camera trajectory or ground frame. No unsupported foot locking or | |
| field direction is inferred. | |
| Each supported continuous trajectory is fitted again with temporal-weight factors 0.5 and 2.0. | |
| Summary `stability` gives the resulting minimum/maximum in the metric's own units | |
| only when both alternative fits and the complete swing are supported. Otherwise | |
| it supplies `not_evaluated` with a reason. This is sensitivity to regularization, | |
| **not a confidence interval or independent accuracy validation**. No numerical | |
| uncertainty is fabricated for unsupported sections. Acceptance defaults are | |
| configurable engineering gates, not established biomechanical error limits. | |
| Defaults are eight native frames/batch, 48 frames/quality window, eight context | |
| frames/side and 25 optimizer steps per continuous fit. Three fits are performed | |
| for each supported continuous segment. This adds GPU work; | |
| the actual inference/refinement runtime must be evaluated on the deployed GPU. | |
| Options and bounds are published in `/input-schema`. Progress includes | |
| `image_motion_evidence`, `loading_native_refinement`, and `whole_body_refinement`. | |
| The 3D initializer anchor has an explicit body-relative scale | |
| (`initializer_scale_body_fraction`, default 0.03), rather than an implicit metre | |
| of uncertainty. This is a regularization parameter, not a measured accuracy | |
| bound. Candidate selection respects the pose-adjustment trust region throughout | |
| optimization. Shared-shape normalization and subsequent pose adjustment are | |
| reported separately; long-limb diagnostics compare the same pose's normalized | |
| body, not a constant shoulder/torso span. Native MHR parameters must reproduce | |
| every fitted source frame within the arithmetic tolerance before fitting. | |
| Short person-detection losses can be recovered through consistent predicted box | |
| motion, size and torso appearance. Maximum recovery gap defaults to 0.2 s of | |
| video time. Ambiguous overlapping people are never recovered on clothing alone. | |
| Lost frames remain gaps. `tracking` settings are versioned native-inference inputs. | |
| The 202 response includes `analysis_id`, `job_id`, `analysis_revision`, | |
| `parent_job_id`, `status_url`, `result_url` and `retention_hours`. The first | |
| analysis ID equals its job ID. Poll the supplied status URL until `completed` or | |
| `failed`; active work reports `processing`. Queued/uploading/cancelled states are | |
| explicit. Completed results can contain unavailable individual measurements. | |
| No usable motion, fewer than four decoded frames, invalid timestamps, ambiguous | |
| athlete selection or inference failure produces a failed job with a reason. | |
| Multiple plausible athletes require `athlete_box`. Tracking uses conservative | |
| box, motion and appearance agreement, not biometric identity recognition. | |
| Bounded short losses may be recovered; ambiguous crossings and uncertain frames | |
| remain unusable. | |
| ## Manifest and artifacts | |
| The manifest declares the ordered 20-joint anatomical skeleton, actual native | |
| mapping, bones, fixed coordinates, scale interpretation, source orientation, | |
| timing map, model/checkpoint hashes, adapter/correction revisions and settings, | |
| measurement-definition version, quality segments and artifact integrity details. | |
| | Artifact name | Content | | |
| | --- | --- | | |
| | `motion` | `motion.jsonl`: one corrected joint record per decoded source frame. | | |
| | `source` | Original uploaded video bytes, with orientation/display dimensions. | | |
| | `measurements` | `measurements.json`: four groups' summaries and graph series. | | |
| | `events` | `events.json`: windows, baseline, stride/foot plant and speed peaks. | | |
| | `quality` | `quality.json`: segments, corrections and identity/accuracy limitations. | | |
| | `projections` | `projections.jsonl`: projections of the same corrected joints, when valid. | | |
| | `annotated_rotation`, `annotated_timing`, `annotated_posture`, `annotated_stance` | Optional MP4s with group skeleton overlays; no bottom panel. | | |
| | `mesh` | Unavailable with reason `animated_mesh_second_phase`. | | |
| Each artifact includes status, format, media type, authenticated relative URL, | |
| size, SHA-256 and `expires_at`, or an unavailable reason. All referenced files | |
| are ready before completion. Only allowlisted artifacts are downloadable; raw | |
| inference/debugging arrays remain private. Follow returned URLs with the Bearer | |
| header. Source videos and artifacts expire after the configured retention | |
| (24 hours by default), cancellation or deletion. Ephemeral hosting can lose jobs | |
| on redeployment; configure persistent `BASEBALL_DATA_ROOT` for durable replay. | |
| ## Replay and alignment | |
| Every frame includes source-frame index, original PTS/time base, elapsed | |
| `video_time_s`, elapsed `capture_time_s` or null, `segment_id`, every declared | |
| joint, separate root translation and frame quality. Every joint has a finite | |
| position or explicit null, status, null confidence when the model supplies none, and | |
| reason codes. Gaps and filter boundaries remain explicit; there is no intentional | |
| source-frame skipping, invented confidence or gap interpolation. | |
| GVHMR additionally records its 30-Hz temporal conditioning grid and source-time | |
| mapping. The grid uses physical capture time when known, otherwise playback | |
| time. Rotation parameters use SO(3) interpolation back to source timestamps; | |
| affected joints carry `interpolated` status and explicit provenance, and dependent | |
| metrics record interpolated input. This does not fill missing athlete tracks or | |
| source clock gaps. Long sequences use bounded windows with context; window | |
| boundaries start new segments and are excluded from derivative evidence. | |
| The effective GVHMR timing sample spacing is at least 33.333 ms even when the | |
| source has more frames; resampling does not invent high-speed timing evidence. | |
| The `gvhmr` options expose batch size, window/context sizes and input-2D quality | |
| thresholds. These scores gate model inputs; they are not calibrated 3D confidence. | |
| Background camera-rotation failures remain unusable frames. Camera rotation and | |
| the model's native global prediction do not become calibrated ground coordinates. | |
| Use **video time** to synchronize with the original recording, including variable | |
| cadence. Capture time is for physical rates; constant slowdown and explicit maps | |
| are recorded. Never assume index divided by nominal FPS is the timeline. Never | |
| interpolate replay across segment/gap boundaries. Client playback interpolation | |
| must not become measurement evidence. | |
| Positions are hip-relative, in a fixed right-handed orientation. With supplied | |
| field vectors, X is toward the pitcher, Z is declared up and Y = Z × X. With | |
| only up, the starting hip axis supplies the fixed horizontal reference. Otherwise | |
| the real camera axes (right/down/away) are exported without claiming gravity or | |
| field direction. Native model scale remains estimated unless calibrated. | |
| `root_translation_included` is false. The separate root is a model-estimated | |
| camera root in the same export axes/units, **not ground motion**. For projection: | |
| ```text | |
| camera_point = (joint.position + frame.root_translation) @ camera_to_export_rotation | |
| pixel = project(camera_point, projection_frame.camera_intrinsics, optional_camera_distortion) | |
| ``` | |
| Add root exactly once. Uniform scale cancels in perspective division. Projections | |
| include source IDs/times, per-frame camera intrinsics, upright image dimensions, | |
| validity and in-frame flags. Apply declared source orientation once. Raw detected | |
| 2D points are not substituted for corrected projections. Overlay videos use those | |
| same projections and original playback timing, at most 1280 pixels on the longest | |
| side, without audio. | |
| ## Measurements and events | |
| The existing `sam_measurements.py` calculator implements the supplied companion | |
| document's definitions. Summaries contain metric ID, definition version, value, | |
| unit, reference, statistic, baseline, window, exact source samples/times, reasons | |
| and interpolation provenance. Series contain shared definitions/units/references | |
| and timestamped samples. Event-only values remain summaries; their curve samples | |
| use `event_summary_only` rather than repeating a summary as continuous motion. | |
| Head movement uses the ear midpoint; hand speed uses the wrist midpoint relative | |
| to hips. Neither is bat speed, eye tracking or foot pressure. Sampled peak order | |
| does not prove onset order/energy transfer. Body points alone do not establish | |
| ball contact. Missing ground translation or a segment-mass model leaves ground | |
| displacement/COM unavailable. Unknown scale disables cm and m/s values; unknown | |
| physical timing disables rates/durations. Joint gaps and correction boundaries | |
| block derivative evidence. | |
| The backend exposes a reproduction helper using only public artifacts: | |
| ```python | |
| from baseball_batting.motion_export import reproduce_measurements | |
| groups = reproduce_measurements(manifest_dict, "motion.jsonl") | |
| ``` | |
| Events identify type, status, source, start/end source samples, revision and | |
| reasons. Sources distinguish manual review, pose-estimated windows and sampled | |
| speed peaks. Automatic windows remain candidates. An unavailable foot-plant | |
| event does not prove that no step occurred. | |
| For one swing, a supplied `contact_frame` creates a reviewed `ball_contact` event; | |
| without it contact remains unavailable. Player information under `athlete` enables | |
| the separate coach payload, sampled at the reviewed stride/landing/contact frames. | |
| It does not change the existing maximum-separation summary. See the | |
| [request, event definitions and reliability mapping](MOTION_COACH_PAYLOAD.md). | |
| ## Immutable reviewed revisions | |
| Send a JSON patch to the parent's `/revisions` endpoint. Unchanged options are | |
| inherited. Example: | |
| ```json | |
| { | |
| "options": { | |
| "windows": [{ | |
| "start_frame": 20, | |
| "end_frame": 150, | |
| "baseline_frame": 25, | |
| "forward_start_frame": 75, | |
| "forward_end_frame": 115, | |
| "stride_start_frame": 45, | |
| "landing_frame": 70, | |
| "source": "Coach reviewed source recording" | |
| }] | |
| } | |
| } | |
| ``` | |
| The response retains the analysis ID, allocates a new job ID/revision and supplies | |
| new URLs. The parent is unchanged. Native inference is reusable after integrity | |
| checks when camera/crop/orientation/adapter inputs match. Changing the athlete | |
| requires a new analysis using `source_asset_id`, giving it a new person ID. | |
| Changing the reconstruction model, checkpoint, or GVHMR temporal conditioning | |
| (clock, camera stability, gap threshold, native settings) prevents inference reuse. | |
| Correction-only changes can reuse the selected model's verified native output. | |
| ## Verification limits | |
| Tests cover joint completeness/mapping, axes/scale, variable cadence/retiming, | |
| source/overlay synchronization, public-point reprojection, measurement reproduction, | |
| explicit gaps/identity uncertainty, missing wrists, unknown camera/clock/scale, | |
| immutable concurrent revisions, source retention, cancellation, authentication, | |
| artifact checksums and byte ranges. These check implementation behavior. Hidden | |
| depth, anatomical assignment in arbitrary real clips and real-world measurement | |
| accuracy still need independent reference data. Smooth replay and image alignment | |
| alone do not prove accurate 3D motion. | |