baseball-engine / docs /APP_API_INTEGRATION.md
github-actions[bot]
Automated Deploy: 83dd0e037548607e097653f87bce7ef9d342efc6
9ec8d34
|
Raw History Blame Contribute Delete
37.8 kB

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

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 still supplies its four groups' coaching/reviews/scores. It is SAM-only and has its own processing path.
  • The previous swing-coach integration 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:

Authorization: Bearer <ENGINE_SERVER_KEY>

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:

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:

{
  "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 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 and the complete input schema. 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:

{
  "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:

{
  "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. 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:

{
  "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:

{
  "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.

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.

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 <video src="https://...hf.space/..."> cannot attach the engine Bearer header. Use your authenticated app media proxy. Native app players should also use app authentication, not a bundled engine key.

The proxy forwards Range and If-Range and preserves the upstream status and Content-Type, Content-Length, Content-Range, Accept-Ranges, and ETag. Support HEAD, 206 partial responses, and 416 range errors. Stream media instead of buffering every MP4 into app-server memory. Check ownership on every range request.

After implementing the proxy from section 2:

<video id="rotation-video" controls playsinline preload="metadata"></video>
const artifact = manifest.artifacts.annotated_rotation;
if (artifact?.status === "available" && artifact.url) {
  document.querySelector("#rotation-video").src = engineProxyPath(artifact.url);
}

Annotations are silent H.264 MP4s at up to 1280 pixels on the longest side. They preserve source playback timing, including variable spacing and slow playback. Their dimensions can differ from the source; preserve aspect ratio. The original source can use a codec/container unsupported by the browser; prefer the annotated MP4 for browser playback.

8. Multiple swings, events and per-swing playback

With single_swing: false, automatic hand-motion analysis proposes windows. These are motion candidates, not a guaranteed complete swing count. Reviewed windows supply explicit boundaries. Frame indices are zero-based, inclusive; rep IDs are one-based, local to the job.

Reviewed range example; replace every frame number with actual reviewed values:

{
  "single_swing": false,
  "windows": [
    {"start_frame": 0, "end_frame": 119, "source": "Reviewed recording"},
    {"start_frame": 150, "end_frame": 269, "source": "Reviewed recording"}
  ]
}

Build the rep list from events.events entries with type: "swing_window" and present start/end. Each event includes rep, status, source, source_detail, and timestamped start/end. Other types include baseline, forward_swing_window, stride_start, foot_plant, hip_speed_peak, shoulder_speed_peak, hands_speed_peak, and ball_contact. Only draw events with an actual start sample. Distinguish reviewed from estimated events. Body landmarks do not establish bat-ball impact. With single_swing: true, an optional contact_frame creates a manually reviewed ball_contact event; otherwise it remains unavailable.

The four motion API videos cover the complete recording. This route does not currently return a separately encoded annotated MP4 for every swing. For a selected rep, reuse each group video, seek to the swing window's start video_time_s, and stop/loop at its end. The final included frame starts at the event end timestamp; the exclusive stop is the next source frame's video_time_s, or source_video.duration_s at the end of the recording. Use the motion/projection timestamp list, not nominal FPS, to find that stop. This is range playback in the same media, not a downloadable swing cut.

For individual downloadable annotated swing files from this motion, your app backend must cut returned videos using the reviewed ranges, or this must be added as a separate engine feature. Do not invent motion /swings/{rep}/clip URLs. The older swing-coach API has its own clip endpoints with its own detection and annotations.

9. Interactive skeleton and synchronized graphs

Parse motion and projections as JSONL/NDJSON: each nonempty line is a JSON object, not one JSON array. For larger recordings, stream/index data or parse it in a worker rather than blocking the main UI thread.

motion records every decoded source frame, with every declared joint name:

  • analysis_revision, source_frame_index, source_pts, source_time_base;
  • elapsed video_time_s and capture_time_s or null;
  • segment_id, joints, separate root_translation, and frame_quality.

Each joint has position: [x,y,z] | null, status (estimated, interpolated, rejected, missing), confidence, and reasons. Use skeleton.joint_order and skeleton.bones, not native model indices. Left/right are the athlete's anatomical sides, not screen sides. Draw a bone only when both endpoints are usable. Model-resampled interpolated points are explicitly labelled; they do not supply extra independent high-speed observations.

For a 3D player, positions are hip-relative in the declared fixed frame. Read coordinates.axes and coordinates.unit; do not assume Z-up or calibrated metres. Any visualization rotation for Three.js/Unity must apply uniformly to all joints. root_translation is separate model-estimated camera placement, not measured ground travel. A centered skeleton viewer can leave it out; camera-scene reconstruction adds it exactly once.

For 2D overlays, use projections.joints[name].pixel when both valid and in_frame are true. These project the same corrected 3D motion; they are not an unrelated detector's skeleton. Scale upright image pixels to the displayed video content rectangle and account for letterboxing. Read projection image_width/image_height; do not apply a second source rotation/mirror. Respect source_video orientation metadata when displaying raw source bytes.

Synchronize video, skeleton, events and graphs using video_time_s. During playback choose the sample at/before video.currentTime, using actual timestamps. Never use frame_index / nominal_fps or seek media with capture_time_s. Capture time is for physical rates. Hide/break motion over unusable gaps and never interpolate across missing/rejected data or segment boundaries. Optional interpolation between valid neighboring samples is display-only; never recalculate submitted measurements from it.

GVHMR uses 30-Hz temporal conditioning and maps poses to source timestamps. A 60/120-FPS upload therefore does not provide independent 60/120-Hz GVHMR observations. Preserve sample_spacing_ms, temporal_model_sample_spacing_ms, and interpolation labels in measurement details.

10. Revisions, model comparison and retention

To compare the same video using the other model, upload no file and send:

Form-data field Value
source_asset_id Completed manifest's source_video.asset_id.
options {"model":"gvhmr","annotated_videos":true} plus recording facts from the original request.

Exactly one of video and source_asset_id is required. A new analysis does not inherit original options. To retain facts automatically, create a revision:

POST /v1/motion-analyses/{parent_job_id}/revisions, JSON body:

{
  "options": {
    "model": "gvhmr",
    "annotated_videos": true
  }
}

Unspecified inputs are inherited. The response retains analysis_id, creates a new job_id/analysis_revision, and reruns inference for a model switch. The parent stays unchanged. Poll the new returned URLs. Reviewed windows/recording corrections also use revisions. Changing athlete_box requires a new analysis using the source asset. Calibration/model changes can require full inference; revisions are not guaranteed instant.

Cache by job/revision. Retain model, anatomical definition, reference frame, scale, timing and recording conditions in session comparisons. SAM/MHR and GVHMR/SMPL-X define landmarks differently; switching models is not player improvement. Do not average their points or combine their numbers in an unlabeled trend.

Artifacts expire according to expires_at and may disappear earlier on an ephemeral Space restart. Retention defaults to 24 hours. A cached job ID/URL is not permanent app storage: the app backend should retain required results/media under its own retention policy. Source reuse/revisions require the original job to still exist and be completed.

DELETE /v1/motion-analyses/{job_id} returns 202 with cancel_requested or cancelled. Running work is stopped and files are removed. Continue polling until cancellation settles. A browser AbortController only stops that request or polling; it does not cancel the GPU job. Check app-user ownership before deletion. Later cleanup can make expired/deleted jobs return 404.

11. Measurement catalogue

Read each returned label, unit, statistic, reference_frame, and status. This catalogue identifies group membership, not guaranteed availability.

Group metric_id Unit
rotation hip_heading_deg deg
rotation shoulder_heading_deg deg
rotation hip_shoulder_separation_deg deg
rotation hip_rotation_from_start_deg deg
rotation shoulder_rotation_from_start_deg deg
rotation hip_angular_velocity_deg_s deg/s
rotation shoulder_angular_velocity_deg_s deg/s
timing hand_speed_relative_m_s m/s
timing hip_peak_time_ms ms
timing shoulder_peak_time_ms ms
timing hands_peak_time_ms ms
timing hip_to_shoulder_ms ms
timing shoulder_to_hands_ms ms
posture forward_lean_deg deg
posture side_lean_deg deg
posture head_excursion_relative_cm cm
posture head_horizontal_relative_cm cm
posture head_vertical_relative_cm cm
posture head_excursion_ground_cm cm
posture pelvis_ground_displacement_cm cm
posture center_of_mass_displacement_cm cm
stance stance_span_cm cm
stance stance_width_baseline_cm cm
stance left_foot_heading_deg deg
stance right_foot_heading_deg deg
stance stride_relative_forward_cm cm
stance stride_relative_lateral_cm cm
stance stride_relative_length_cm cm
stance stride_duration_ms ms
stance stride_ground_length_cm cm

Hand speed is wrist-midpoint speed relative to hips, not bat speed. Separation is a signed body-line angle, not a quality score. Ground movement/centre of mass require evidence this API does not currently reconstruct. Displayed decimals do not establish real-world accuracy.

12. Minimal browser JavaScript client

This example uses the app backend proxy from section 2 and your existing app session, with no engine credential. Retain its returned job so a screen can resume polling after a network interruption.

const APP_PROXY = "/api/baseball";
const MOTION = "/v1/motion-analyses";

function engineProxyPath(enginePath) {
  if (enginePath !== MOTION && !enginePath.startsWith(MOTION + "/")) {
    throw new Error("Unexpected engine route");
  }
  return APP_PROXY + enginePath;
}

async function engineJSON(enginePath, init = {}) {
  const response = await fetch(engineProxyPath(enginePath), {
    ...init,
    credentials: "include"
  });
  const body = await response.json().catch(() => null);
  if (!response.ok) {
    const detail = body?.detail ?? body?.error ?? `HTTP ${response.status}`;
    const error = new Error(typeof detail === "string" ? detail : JSON.stringify(detail));
    error.httpStatus = response.status;
    error.detail = detail;
    error.retryAfter = response.headers.get("Retry-After");
    throw error;
  }
  return body;
}

async function uploadMotion(file, options, signal) {
  const form = new FormData();
  form.append("video", file);
  form.append("options", JSON.stringify(options));
  return engineJSON(MOTION, {method: "POST", body: form, signal});
}

async function waitForMotion(job, onProgress, signal) {
  let delayMs = 2000;
  while (true) {
    const status = await engineJSON(job.status_url, {signal});
    onProgress?.(status);
    if (status.status === "completed") {
      return engineJSON(status.result_url ?? job.result_url, {signal});
    }
    if (["failed", "cancelled"].includes(status.status)) {
      throw new Error(status.failure?.reason_code ?? status.error ?? status.status);
    }
    await new Promise(resolve => setTimeout(resolve, delayMs));
    delayMs = Math.min(5000, Math.round(delayMs * 1.2));
  }
}

async function fetchJSONArtifact(manifest, name, signal) {
  const artifact = manifest.artifacts[name];
  if (artifact?.status !== "available" || !artifact.url) return null;
  if (artifact.format !== "json") throw new Error("Use a line parser for JSONL artifacts");
  return engineJSON(artifact.url, {signal});
}

function formatMetric(metric) {
  if (metric.value == null || !Number.isFinite(metric.value) || metric.status === "unavailable") {
    return "—";
  }
  return `${metric.value} ${metric.unit}`;
}

// On the app's upload action, using this user's recording facts:
// const job = await uploadMotion(file, options, abortController.signal);
// await saveJobForCurrentAppUser(job); // implement in your app
// const manifest = await waitForMotion(job, showProgress, abortController.signal);
// const measurements = await fetchJSONArtifact(manifest, "measurements");
// const events = await fetchJSONArtifact(manifest, "events");
// const rotationVideo = manifest.artifacts.annotated_rotation;
// video.src = engineProxyPath(rotationVideo.url); // only when available

For transient network/502/503 polling failures, keep the job and resume with backoff; this compact helper surfaces them for the app to handle. Do not blindly repeat a POST after a timeout: it may already have created a job. There is no upload idempotency key or job-list lookup in this contract. Your backend should retain received job IDs before replying to its frontend.

The frontend path check is convenience, not authorization. The backend still validates route/ownership and adds the engine key. Apply app CSRF protection to cookie-authenticated upload, revision and delete operations.

13. Errors and frontend acceptance checks

HTTP status Meaning / action
401 Engine credential missing/incorrect; do not ask the player for it.
404 Unknown/wrong-flow/expired/deleted job or unknown artifact. Show an unavailable-session state.
409 Result not completed, or requested artifact unavailable. Inspect job/artifact status.
413 Upload/options exceed limits.
415 Unsupported video extension.
422 Invalid options/ranges. detail may be a string, object or validation-error array.
429 Queue full; respect Retry-After. Avoid duplicate uploads.
503 GPU/model setup not ready; refresh capabilities and back off.
507 Engine storage insufficient; surface a service issue.
500 Server/integrity failure; retain the job ID for support.

The Space proxy can return non-JSON 502/503 during wake-up/restart. Handle HTTP status even when JSON parsing fails. Preserve failure.code, failure.reason_code, failure.error_type, and error for support without showing raw internal logs to players.

Before shipping the frontend, verify:

  • SAM/GVHMR selection uses the same upload flow and the actual returned model labels the result.
  • One-swing and multiple-window results render per rep, with correct range seeking inside each full group video.
  • All four annotated videos play and seek through the app media proxy.
  • Cards display zero, label estimated/partial numbers, and keep available data visible when another metric is null.
  • Skeleton, graphs and events follow source timestamps; invalid points/gaps are not replaced with invented coordinates or connected curves.
  • Model switches/revisions do not display stale cached artifacts as new results.
  • Polling survives leaving/resuming the screen and temporary network errors.
  • Cancellation, expiry and unavailable models have clear app states.
  • One app user cannot request another user's job, source, JSON or videos.

Backend details and coordinate formulas: Motion-player API. Model setup: GVHMR setup. Legacy coaching: SAM batting API and swing-coach integration.