# Frontend integration guide: SAM and GVHMR motion analysis Updated **19 October 2026**. Motion API contract **1.0**. For the coding agent updating the mobile/web app's previous engine integration. **Engine base URL:** `https://modventures-baseball-engine.hf.space` ```text App → app backend → upload recording with selected model → poll job ↓ result manifest with authenticated artifact URLs ↓ corrected motion + measurements + events + four annotated videos ``` SAM (`sam3d`) and GVHMR (`gvhmr`) use the **same routes and output structure**. SAM is the default. Both completed live GPU integration tests on 16 October 2026. Check capabilities at runtime: installation/readiness can change after a Space restart. Those tests verified execution and output consistency; independent 3D accuracy validation remains pending. ## 1. Migrate the correct flow | App currently uses | Change for the motion player | | --- | --- | | `/v1/analyses` or `/v1/swing-coach/analyses` and `/product` | Upload to `/v1/motion-analyses`; fetch the returned `result_url`. | | `/v1/sam-batting/analyses` and `groups[]` | The motion result is a manifest. Fetch its `measurements` artifact for summaries/series and its video artifacts for playback. | | `measurement_backend` | Use `model: "sam3d"` or `model: "gvhmr"`. This motion API has no `2d` model option. | | `reps` | Use `windows` for reviewed frame ranges, or omit windows for automatic motion candidates. | | `view`, `pitcher_direction`, `camera_up` | These old field names are not accepted here. Known camera-space references use `up_vector`/`up_source` and `pitcher_vector`/`pitcher_source`. An image-left/right direction is not a 3D vector. | | `coaching_mode`, `level`, other legacy options | Remove them from motion requests. Unknown fields return 422. Use the published input schema. | Existing APIs continue working. Their result formats are separate: - This **motion API** returns corrected points, measurements, graphs, events and annotated videos. It does **not** return `/product`, coaching paragraphs, drills, group scores, a swing-quality score, or bat/ball contact tracking. `coaching` is fixed to `false`; omit it or send `false`. - The existing [SAM batting API](SAM_BATTING_API.md) still supplies its four groups' coaching/reviews/scores. It is SAM-only and has its own processing path. - The previous [swing-coach integration](LEGACY_SWING_COACH_INTEGRATION.md) still documents `/product`, video feedback, and separately encoded per-swing clips. Keep these result screens/contracts distinct. A matching rep number from separate jobs does not establish matching swing boundaries or measurements. Do not present an old SAM review as a review of a new GVHMR result. ## 2. Authentication and app backend Every engine `/v1/...` request, including JSON and videos, requires: ```http Authorization: Bearer ``` Keep this shared key in the **app backend**, never in shipped mobile code, browser JavaScript, video URLs, or query strings. The frontend does not need `HF_TOKEN`, the SMPL-X file, or a Gemini key. The app backend proxies engine routes, authenticates your app user, records job ownership, and checks ownership on every job/result/artifact request. The engine's shared key does not identify individual app users. Restrict the proxy to expected engine paths and the requesting user's jobs; do not accept arbitrary upstream URLs. The JavaScript example below assumes your backend exposes engine routes under `/api/baseball`, for example: ```text App: /api/baseball/v1/motion-analyses Engine: https://modventures-baseball-engine.hf.space/v1/motion-analyses ``` That app prefix is an **integration example you implement**, not an existing engine endpoint. The proxy adds the engine Bearer header server-side. Browser requests use your normal app session. The engine does not enable browser CORS. ## 3. Check models before upload **`GET /v1/motion-analyses/capabilities`** Relevant fields, shown as an excerpt: ```json { "schema_version": "1.0", "default_model": "sam3d", "model_selector": "options.model", "gpu_queue_ready": true, "joint_count": 20, "models": [ {"id": "sam3d", "name": "SAM 3D Body", "configured": true}, {"id": "gvhmr", "name": "GVHMR", "configured": true} ], "whole_body_refinement": true, "refinement_default_enabled": true, "mesh_available": false, "retention_hours": 24, "max_frames": 7200, "max_duration_s": 120 } ``` Build the model selector from `models[].id` and `name`. Enable a selection when its `configured` value and `gpu_queue_ready` are true. Inspect `reason_code` when not ready; show a setup/warming state instead of submitting repeatedly. Never silently switch models. `inference_verified: false` in capabilities is a configuration-status field, not proof that a completed analysis failed; judge a specific execution using its job status and result. Read live limits instead of hardcoding the example defaults. The default upload limit is 512 MiB. Filename extensions: `.mp4`, `.mov`, `.mkv`, `.avi`, `.webm`; decoding is also checked. Schemas: - `GET /v1/motion-analyses/input-schema` - `GET /v1/motion-analyses/output-schema` ## 4. Upload a recording To also obtain the AI coach's single-swing contract, use the same upload with `single_swing: true`, `athlete` information and optional `contact_frame`. Keep all existing recording options and reviewed window fields. Follow [MOTION_COACH_PAYLOAD.md](MOTION_COACH_PAYLOAD.md) for the request and the new `GET /v1/motion-analyses/{job_id}/coach-payload` response, then forward that JSON unchanged to `POST /v1/sessions/{id}/swing-report` on the coach backend. **`POST /v1/motion-analyses`**, body **multipart form data**: | Field | Type | Value | | --- | --- | --- | | `video` | File | Original recording. | | `options` | Text | JSON string of recording facts and selected model. | Do not manually set the multipart `Content-Type`; the HTTP client supplies its boundary. All examples are illustrative, not downloadable jobs or values to reuse. The short examples below show common fields, not the entire options contract. See [all fields with defaults and GVHMR selected](motion-options.example.json) and the [complete input schema](motion-input.schema.json). Omitted fields use backend defaults. Null/unknown defaults are not calibration evidence and must not be copied as known recording facts. Safe request when recording facts are unknown: ```json { "model": "gvhmr", "annotated_videos": true, "handedness": null, "camera_stability": "unknown", "timing": {"kind": "unknown"}, "single_swing": false } ``` Example **only when the uploader confirms these recording facts**: ```json { "model": "sam3d", "annotated_videos": true, "handedness": "right", "handedness_source": "Uploader supplied", "camera_stability": "fixed_verified", "timing": { "kind": "unretimed", "source": "Uploader confirms original recording speed; no speed changes" }, "single_swing": true } ``` | Option | App behavior | | --- | --- | | `model` | `sam3d` or `gvhmr`. Omission defaults to SAM. | | `annotated_videos` | Keep `true` for four group videos. `false` leaves those artifacts unavailable with `not_requested`. | | `handedness` | `left`, `right`, or `null`; batting side, not image direction. | | `camera_stability` | `fixed_verified`, `moving`, or `unknown`. Never auto-fill verified merely to unlock values. | | `timing` | Unknown recording speed: `{"kind":"unknown"}`. Confirmed original speed: `unretimed` plus `source`. File FPS does not establish original speed. | | `single_swing` | `true` only for exactly one swing. Use `false` for multiple swings. | | `athlete_box` | Optional `[x1,y1,x2,y2]` rectangle in upright original-image pixels; needed for ambiguous athlete selection. | | `source_mirrored` | `true`, `false`, or `null`. Records mirror status; does not flip the image. | | `windows` | Optional reviewed swing/event ranges; see section 8. | | `refinement` | Leave defaults for normal app use. Motion checking/refinement is already enabled; frontend smoothing is not needed for calculations. | | `up_estimation` | Enabled by default. When `up_vector` is omitted/null, estimate camera-up from sampled scene frames. Normal users do not need to supply an angle. | | `pitcher_floor_points` | Optional source-frame index and two upright source-image floor points, first near the batter and second toward the pitcher. Derived camera-space field direction requires applicable `camera` calibration marked `calibration_status: "calibrated"` and a supplied/accepted estimated up reference. | Other supported calibration inputs: `camera`, `up_vector`/`up_source`, `pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`. Normal uploads should omit `pitcher_vector`, `pitcher_source`, and `pitcher_floor_points`. When all are absent, both models automatically estimate hitting direction from the batter's setup and subsequent hand/torso movement. A home plate, field markings, handedness, camera calibration, and user clicks are not required. The existing GeoCalib provider supplies missing up estimates; it must be installed on the server. This gives an approximate hitting direction, not the verified location of an unseen pitcher. The output reference is `estimated_batting_axes`, with `target_alignment_verified: false` in `coordinates.pitcher_estimation`. Missing or ambiguous evidence returns an unknown direction without interrupting the job or requesting user input. This does not bypass the existing camera-stability requirements for measurements. See [automatic direction behavior and limitations](PITCHER_FLOOR_DIRECTION.md#automatic-direction-default). Keep manual calibration overrides in a reviewed flow, not frontend guesses. Camera-up is now estimated automatically when omitted; explicit `up_vector` and `up_source` always take priority. Many body angles still require verified camera stability. Camera-up estimation does not declare the camera fixed. `up_vector: [0,-1,0]` is only an explicit camera-up approximation when an upright, level recording supports it; it is not recovered gravity. A pitcher vector is used once a supplied or accepted estimated vertical is available. Missing calibration can leave individual measurements unavailable while motion and videos remain usable. Documented constant slow motion uses: ```json { "timing": { "kind": "constant_slowdown", "source": "Documented camera slowdown setting", "factor": 4, "all_captured_frames_retained": true } } ``` Do not declare that all captured frames were retained unless that is known. Successful upload returns **202**: ```json { "analysis_id": "11111111111111111111111111111111", "job_id": "11111111111111111111111111111111", "analysis_revision": 1, "parent_job_id": null, "status": "queued", "status_url": "/v1/motion-analyses/11111111111111111111111111111111", "result_url": "/v1/motion-analyses/11111111111111111111111111111111/result", "retention_hours": 24 } ``` Save the real returned IDs and URLs with the app user's session. Use returned URLs rather than constructing paths from artifact filenames. ## 5. Poll, then fetch the manifest **`GET {status_url}`**. Start around every 2 seconds, backing off to 5 seconds. GPU processing can take minutes. A network timeout is not an analysis failure. | `status` | Screen behavior | | --- | --- | | `uploading` | Upload is being saved. | | `queued` | Waiting for GPU processing. | | `processing` | Analysis running; show its current stage if present. | | `completed` | Fetch `result_url`, then the needed artifacts. | | `failed` | Show a useful error from `failure.reason_code`/`error`; allow retry. | | `cancel_requested` | Cancelling; continue polling. | | `cancelled` | Stop polling; files are removed. | This route uses **`processing`**; the older product flow used `running`. `progress` can be null. Its `stage`, `completed_frames`, `total_frames`, and `elapsed_s` refer to the current stage. A stage fraction is not overall completion. Unknown stage names should use a generic “Analyzing” label. Stages include tracking, SAM/GVHMR reconstruction, image evidence, native refinement, motion artifacts, and annotated videos. **`GET {result_url}`** returns a **manifest**, not a measurement array: | Manifest field | Frontend use | | --- | --- | | `schema_version` | Motion contract `1.0`; tolerate additive fields. | | `analysis_id`, `job_id`, `analysis_revision`, `parent_job_id` | Session lineage and immutable cache identity. | | `person_id` | Athlete track identity within this analysis; not the app account ID. | | `pipeline.selected_model` | Actual `sam3d`/`gvhmr` selection. | | `pipeline.measurement_definition_version` | Keep with measurements/comparisons. | | `pipeline.refinement` | Acceptance/fallback diagnostics; acceptance does not establish anatomical accuracy. | | `coordinates` | Axes, units, scale and separate root translation. | | `coordinates.up_vector`, `coordinates.up_source` | Effective camera-up and provenance, in `up_vector_frame` camera axes rather than exported player axes. | | `coordinates.up_estimation` | `provided`, `estimated`, or `unknown`; acceptance, method, source-frame diagnostics and reason codes. | | `timing.physical_time_available` | Whether physical speeds/durations can be interpreted. | | `skeleton.joint_order`, `skeleton.bones` | Ordered joint names and bone connections. | | `source_video` | Source dimensions, orientation, asset ID and duration. | | `sampling` | Source frame count and sampling policy. | | `quality` | Usable frame count, segments and accuracy limitations. | | `artifacts` | JSON, JSONL, source and MP4 locations/availability. | | `expires_at` | Retention deadline. | Never mix artifacts from different job/revision pairs. Revisions can retain the same `analysis_id` while changing the job and its measurement results. ## 6. Fetch artifacts and build the four groups Artifact metadata includes `status`, `format`, `media_type`, `url`, `filename`, `size_bytes`, `sha256`, `expires_at`, and optionally `reason_code`. An unavailable artifact has no usable URL. Use **`url`**, not `filename`, for requests. | Artifact key | Content / use | | --- | --- | | `measurements` | JSON object: `summaries[]`, `series[]`, definition version and calculation inputs. | | `events` | JSON object: `events[]` with per-rep windows, times and reasons. | | `motion` | JSONL/NDJSON: corrected 3D joints for each source frame. | | `projections` | JSONL/NDJSON: corrected 2D image projections of that same motion; may be unavailable. | | `quality` | JSON object: tracking, segments and correction diagnostics. | | `source` | Exact uploaded bytes with original container/orientation. | | `annotated_rotation` | Hips and shoulders video. | | `annotated_timing` | Movement timing video. | | `annotated_posture` | Posture and head movement video. | | `annotated_stance` | Stance and stride video. | | `mesh` | Unavailable: `animated_mesh_second_phase`. Render joints/bones instead. | Group mapping: | `series[].group` | Screen title | Video artifact | | --- | --- | --- | | `rotation` | Hips and shoulders | `annotated_rotation` | | `timing` | Movement timing | `annotated_timing` | | `posture` | Posture and head movement | `annotated_posture` | | `stance` | Stance and stride | `annotated_stance` | The measurement response has **no `groups[]` wrapper**. Build groups from `series[].group` and match summaries using **`rep` + `metric_id`** within the same job/revision. Summaries include both `key` and `metric_id`; use `metric_id` as the stable UI measurement key. See the catalogue in section 11. Each summary supplies `label`, `value`, `unit`, `status`, `statistic`, `reference_frame`, `baseline_frame`, `window`, `source_samples`, `quality_flags`, `reason_code`, `uses_interpolated_input`, and `stability`, among other provenance. Keep the statistic/reference with the number: a peak, baseline, and end-of-window value describe different things. Each series includes `rep`, `metric_id`, `group`, `unit`, `reference_frame`, and `samples[]`. Samples contain `source_frame_index`, `video_time_s`, `capture_time_s`, `value`, `status`, `reasons`, and interpolation provenance. Use these backend values for graphs. Some event-only metrics have null curves with `event_summary_only`; show the summary/event marker instead of inventing a flat line from the summary. ### Display rules | Value/status | Display | | --- | --- | | Finite value, `estimated` | Number/unit with “Estimated”. | | Finite value, `partial` | Number/unit with “Partial data”; retain its explanation. | | Null or `unavailable` | `—` with a short reason, or omit the numeric card and retain the explanation in group details. | | Zero | Display zero; never treat it as missing. | | Joint `confidence: null` | Confidence was not supplied; do not convert it to 0% or 100%. | | Missing/rejected joint or invalid projection | Skip the point/affected bone; never substitute zero coordinates. | Keep usable cards/videos visible when another value is missing. Break graphs at null samples and invalid-data/segment gaps. An unavailable metric/artifact is not automatically a failed job. Suggested short reason labels: | Reason code | User-facing wording | | --- | --- | | `capture_time_unknown` | Recording speed was not confirmed. | | `missing_vertical_reference` | Camera vertical reference is missing. | | `camera_stability_unverified` | Camera stability is not verified. | | `missing_3d_pitcher_direction` | Direction toward the pitcher is not calibrated. | | `missing_reviewed_stride_events` | Step-start and landing frames need review. | | `missing_ground_reference` | Ground movement is not calibrated. | | `missing_mass_model` | Body mass distribution is not available. | | `incomplete_peak_window` | Tracking is incomplete around the speed peak. | | `peak_at_window_boundary` | The speed peak reaches the selected window edge. | | `scale_unknown` | Physical distance scale is unknown. | Use a generic fallback for other codes and preserve the exact code for support. `stability.minimum`/`maximum` describe sensitivity to alternative smoothing strengths **only when `stability.status === "evaluated"`**. They are not accuracy bounds, confidence intervals, or a player score. Measurements retain `accuracy_validated: false` in this release. ### Automatic camera-up in the frontend Leave `up_vector`/`up_source` omitted or null for automatic estimation. The backend uses GeoCalib on timestamp-spaced frames, checks background scene support, model uncertainty and agreement across frames, and only uses accepted estimates. Both SAM and GVHMR use the same estimator and camera-coordinate convention. Read `manifest.coordinates.up_estimation.status`: - `estimated`: show **Estimated camera-up** and the returned source/vector. `reliable: true` means the engineering checks passed, not a calibrated accuracy probability. `confidence` remains null. The vector is normalized. - `provided`: show **User-supplied camera-up**. Original inputs are preserved; their accuracy has not been independently verified (`reliable: null`). - `unknown`: keep camera-up unknown, show a short reason if useful, and do not substitute a default vector. Measurements requiring vertical remain unavailable. The vector frame is `upright_camera_x_right_y_down_z_away`. It is not in the exported skeleton's rotated coordinate axes. Diagnostics include sample and accepted-frame counts, temporal coverage, frame disagreement and provider uncertainty in degrees. Per-frame candidates are diagnostic only; use the effective `coordinates.up_vector` for display, never a rejected candidate. Submitted inputs remain in `pipeline.inputs`; effective inputs used for numbers are in `pipeline.calculation_inputs`. The same reference is also recorded in the measurements/quality artifacts. A gravity estimate does not supply pitcher direction, physical scale, a recording clock, or proof of a fixed camera. Additional reason codes: `camera_up_provider_unavailable`, `insufficient_reliable_frames`, `inconsistent_camera_up_across_frames`, `insufficient_camera_up_temporal_coverage`, `camera_up_estimation_failed`, and `automatic_up_estimation_disabled`. See [estimator details](CAMERA_UP_ESTIMATION.md). ### Pitcher direction from selected floor points Motion API 1.14.0 supports `pitcher_floor_points` for both models. The frontend sends `source_frame_index`, `near_batter: [x,y]`, and `toward_pitcher: [x,y]` in upright original source pixels. The camera needs `calibration_status: "calibrated"`; the default is `unknown`. Camera height is not required. Omitted up uses the existing automatic estimator; a manual pitcher vector always wins. Read `coordinates.pitcher_vector`, `pitcher_source`, `pitcher_vector_frame`, and `pitcher_estimation`. Display estimated/provided/unknown according to its `status`; unknown includes a reason and never substitutes a 2D arrow. Reliability checks are conditional engineering checks, not an accuracy probability. The derived vector/source enter `pipeline.calculation_inputs`; original inputs stay unchanged. See [request, response, coordinate mapping and reason codes](PITCHER_FLOOR_DIRECTION.md). ## 7. Play the annotated videos Only enable a player when its artifact has `status: "available"` and a URL. Each group video contains its skeleton/measurement overlay, with **no bottom information panel**. `source` is the original upload, not an annotated preview. Prefer the group artifact when the UI promises annotations. A plain `