baseball-engine / docs /LEGACY_SWING_COACH_INTEGRATION.md
github-actions[bot]
Automated Deploy: e8f9b601dd5464c98dfeaaab4cccd6af68ee2d82
6b95c6c
|
Raw History Blame Contribute Delete
27.9 kB

App integration: swing analysis, coaching and swing clips

This guide covers the existing swing-coach /product flow. For the current SAM/GVHMR motion player, use the frontend integration guide. These APIs have separate contracts.

For the coding agent updating the app's previous engine → separate coach flow.

Engine base URL: https://modventures-baseball-engine.hf.space

Use one upload and one combined result. The engine now runs the coach internally. The result includes measurements, the coach's existing response, experimental video feedback for the three features, and a playable clip for each detected swing.

App → app backend → upload video to engine → poll job
                                           ↓
                         combined product + individual swing clips
                                           ↓
                              app shows swing cards and feedback

1. Change the old integration

Previous integration Current integration
Upload to POST /v1/analyses Upload to POST /v1/swing-coach/analyses
Fetch /coach-payload, then call the standalone coach Fetch /product; coaching is already included
Read only the coach response Read product.coaching and product.visual_review
Use frame ranges or still images as swing previews Read product.swings; each available clip has an MP4 endpoint
App receives coach response version 2.0 That same response remains inside product.coaching

For this new flow, remove the extra standalone coach request. Do not pass the whole product into the old coach input: it already contains that coach's output.

Do not hide the entire result when coaching.score.value is null or coaching.focus is empty. The experimental video observations and swing clips can still be available. Fetching /coaching alone also misses the new video feedback and clips; fetch /product for the app screen.

Old engine upload/result routes and standalone coach routes remain available. Legacy measurements stay at schema 2.0; timing defaults to 3.0, with 3.1 when evidence is requested. The combined product is now schema_version: "1.1". Its new swings and swings_url fields are additive to product 1.0. Accept both product versions and treat a missing swings field as an older result.

2. Authentication and app backend

Every engine /v1/... request uses:

Authorization: Bearer <ENGINE_SERVER_KEY>

Store this key in your app backend's environment, for example BASEBALL_ENGINE_API_KEY. Use the same key for uploads, status, JSON results, images and MP4 clips. The old standalone coach's X-API-Key header is not used for this combined flow.

The Gemini key stays in the engine's GOOGLE_API_KEY secret. The app does not send it. Browser uploads should go through your app backend: the engine does not enable cross-origin browser requests.

Authenticate your app user and store which user owns each returned job_id. Check that ownership before proxying status, results, clips, frames, retry or delete. The engine's shared key does not provide per-user access control.

3. Upload one video

POST /v1/swing-coach/analyses

Body: multipart form data, with these two fields:

Field Form-data type Value
video File The original video file
options Text A JSON string containing the recording facts

Example options for a known right-handed batter, with the ball coming from the right side of the image and a fixed camera facing the batter's chest:

{
  "measurement_backend": "2d",
  "coaching_mode": "poc_video",
  "view": "face_on",
  "handedness": "right",
  "pitcher_direction": "image_right",
  "practice_type": "front_toss",
  "camera_stability": "fixed_verified",
  "timing": {
    "kind": "unretimed",
    "source": "Uploader confirms original recording; no speed changes"
  },
  "single_swing": false
}

These are example facts, not defaults to apply to every player. Ask the player for the facts the app does not know.

Option Meaning and accepted values
measurement_backend Use "2d" for this POC. It runs pose and bat/ball models on GPU without SAM.
coaching_mode "poc_video" includes the coach and sampled-image Gemini review; this is the new route's default. "measurements_only" includes the existing coach without Gemini images. "disabled" produces measurements and clips without a product.
view "face_on" when the camera faces the batter's chest; otherwise "unknown". Do not infer this only because a person is visible.
handedness "left", "right", or null: the side the player bats from.
pitcher_direction "image_left", "image_right", or null: direction toward the pitcher/tee in the image, not the player's handedness.
practice_type "tee", "soft_toss", "front_toss", "live", "machine", or "unknown".
camera_stability "fixed_verified" if the camera stays still, "moving" if it moves, otherwise "unknown".
timing {"kind":"unknown"} if speed changes are uncertain. Use documented "unretimed" only when the recording has no speed changes.
single_swing false for a video containing multiple swings. true treats the entire recording as one supplied swing range; it does not split it.

Unknown recording facts are accepted by the combined route. They can make measurements unavailable, so show upload warnings instead of silently changing the facts. The strict /v1/load-timing/analyses route can reject missing timing settings; it is not the recommended upload route for the combined app screen.

If the recording is documented constant slow motion, the supported timing shape is:

{
  "kind": "constant_slowdown",
  "source": "Documented camera recording setting",
  "factor": 4,
  "all_captured_frames_retained": true
}

Do not set that flag if frames were removed or the slowdown is uncertain.

If your app already knows the cuts, it may supply reps as sorted, non-overlapping, zero-based inclusive frame ranges:

{
  "single_swing": false,
  "reps": [
    {"start_frame": 0, "end_frame": 119},
    {"start_frame": 120, "end_frame": 239}
  ]
}

Omit reps to let the engine detect swings. Do not send single_swing: true together with reps. Only send ranges that fit the actual source video.

Successful upload returns HTTP 202, including:

{
  "job_id": "0123456789abcdef0123456789abcdef",
  "status": "queued",
  "status_url": "/v1/analyses/0123456789abcdef0123456789abcdef",
  "product_url": "/v1/analyses/0123456789abcdef0123456789abcdef/product",
  "swings_url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings",
  "coaching_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coaching",
  "result_url": "/v1/analyses/0123456789abcdef0123456789abcdef/result",
  "coach_payload_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coach-payload",
  "load_timing_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing",
  "load_timing_evidence_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing?include_evidence=true",
  "warnings": []
}

The job ID here is illustrative. Save the real ID returned by your upload. All returned URLs are relative to the engine base URL.

4. Poll the job, then fetch the product

GET /v1/analyses/{job_id}

Poll about every two seconds; back off during a long wait. An upload response does not mean analysis has finished. GPU work can take several minutes.

Job status App behavior
queued Show “Waiting to analyze”.
running Show “Analyzing”, optionally with the current progress.stage.
completed Fetch product_url, then render the result.
failed Show the returned error; allow a new upload.
cancel_requested Show “Cancelling” and continue polling.
cancelled Stop polling; the result files are removed.

progress can be null. Stages include decoding, pose, measurements, tracking, swing_clips, coaching and complete. completed_frames, total_frames and stage_progress describe the current stage, not the whole job. Do not present a stage's percentage as an overall completion percentage.

Preserve the job ID if the user leaves the screen or a polling request fails; resume polling rather than uploading the same video again automatically.

Once complete:

GET /v1/analyses/{job_id}/product

Product field What the app uses it for
schema_version Product version "1.1"; also accept older "1.0".
session_id Same ID as the analysis job.
discipline "hitting".
coaching_mode The requested mode.
swings Every detected/supplied rep, with its boundaries and clip metadata.
swings_url Separate swing-list endpoint, if needed.
measurements Existing 2.0 per-rep nine-measurement payload.
timing 3.1 per-rep timing, event intervals, context and reason codes.
coaching Existing coach response, response_version: "2.0".
visual_review Experimental observations, separate visual rubric score and optional priority/drill for the three features.
evidence Retained sampled frame images and review coverage.

There is no second upload or separate endpoint for each of the three feedback features. They are returned together in visual_review.features.

5. Show an individual video for each swing

product.swings contains entries shaped like this. Numbers and checksum below are illustrative, not a real downloadable recording:

{
  "rep": 1,
  "start_frame": 0,
  "end_frame": 119,
  "boundary_method": "automatic_2d_hand_motion_candidate",
  "boundary_accuracy_validated": false,
  "source_start_playback_s": 0.0,
  "source_end_playback_s": 3.966667,
  "clip": {
    "status": "available",
    "reason_code": null,
    "url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings/1/clip",
    "content_type": "video/mp4",
    "duration_s": 4.0,
    "frame_count": 120,
    "width": 1280,
    "height": 720,
    "has_audio": false,
    "overlay": true,
    "size_bytes": 524288,
    "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  }
}

Build the swing list from swings, ordered as returned. Labels are “Swing 1”, “Swing 2”, etc. Rep IDs are one-based; source frame IDs are zero-based.

  • start_frame and end_frame include both endpoint frames.
  • boundary_method is automatic_2d_hand_motion_candidate, caller_supplied, or caller_declared_single_swing for the current engine.
  • Automatic cuts are candidates. Detection may miss/merge movements; clips do not establish that every actual swing was found.
  • New clips use the same overlay renderer as the Colab previews folder: green body points/skeleton, orange toe/heel points, source frame numbers and estimated event labels. clip.overlay: true identifies annotated previews. A body-based contact event is labelled estimated contact proxy; it is not confirmed bat-ball impact. Missing joints/events are not drawn or invented. If a selected 3D backend produced projections, the clip also shows purple projected joints and red disagreement connectors at those sampled frames. The default 2D backend requires no SAM to draw the body skeleton.
  • The clips are upright H.264 MP4s, resized to at most 1280 pixels on the longest side, with at most one pixel of padding for odd dimensions. They have no audio.
  • Every source frame in the range is retained. Each clip starts at playback time zero and preserves the source's variable frame spacing and playback speed. An uploaded slow-motion video stays slow motion in the clip.
  • Capture-time measurements and clip playback time are separate clocks. source_end_playback_s is the last frame's timestamp; duration_s also includes that last frame's display duration.

The clip endpoint is:

GET /v1/analyses/{job_id}/swings/{rep}/clip

It requires the same Bearer key and returns video/mp4. It supports normal GET (200), single byte ranges (206), suffix/open-ended ranges, and HEAD. Invalid or unsatisfiable byte ranges return 416 with Content-Range: bytes */<size>. Multiple ranges are unsupported. Accept-Ranges, Content-Length, ETag and Content-Range on partial responses support player seeking.

Use an app-backend media proxy for playback. Browser <video src> cannot attach the engine's Bearer header. The proxy should authenticate the app user, check job ownership, add the engine key, forward Range/If-Range, and stream the response without buffering the whole video. Pass through the response status and media/range headers. Never put the engine key in the video URL.

For a small internal browser test, fetching the authenticated clip into a Blob and setting video.src = URL.createObjectURL(blob) also works. Revoke the Blob URL when the result is replaced. This downloads the entire clip first; the backend proxy is the preferred app integration.

For a separate swing-list request:

GET /v1/analyses/{job_id}/swings returns:

schema_version: "1.0"       # This is the swing-list version, not the product version.
session_id: job ID
swings: same array as product.swings
notice: boundary/timing/format explanation

New jobs on the legacy upload routes also create this manifest and clips. Older completed jobs cannot create clips after their original upload was removed. Their swing endpoint returns 409; upload again to create clips. Clips from before the overlay update stay plain (overlay: false or missing). Upload again to generate annotated previews. Existing clip.url playback paths and authentication are unchanged; the mobile app does not need to draw joints. Gemini still receives unannotated original images, not these display overlays.

If a particular clip cannot be exported, its rep remains in swings with clip.status: "unavailable", a reason_code, and url: null. Hide that rep's player and show “Clip unavailable”; retain its measurements and feedback. Reasons include missing/invalid source timestamps, source mismatch, unavailable last-frame duration, and clip_export_failed. An empty swings array means no rep was detected; do not invent a swing card.

6. Match each swing to its measurements and feedback

Join by rep, not by array position:

const cards = (product.swings ?? []).map(swing => ({
  ...swing,
  measurements: product.measurements.reps.find(r => r.rep === swing.rep) ?? null,
  timing: product.timing.reps.find(r => r.rep === swing.rep) ?? null,
  observations: product.visual_review.features.filter(f => f.rep === swing.rep)
}));

The current Gemini review returns three feature observations for the session, each referring to one rep. It does not promise all three observations for every swing. The configured default reviews sampled images from at most six reps; clips are exported for all detected reps, including unreviewed ones. Use evidence.reviewed_reps and evidence.total_reps to show that coverage. Label a swing without a visual observation “Not individually reviewed” rather than copying another swing's advice onto it.

Three feedback cards

When visual_review.status is "completed", render its features:

feature.key App label Text
load_timing Load and timing feature.observation
hip_shoulder_separation Hips and shoulders feature.observation
bat_path_contact Bat path and contact feature.observation

New reviews include visual_review.text_style_version: "concise-observations-v1". The prompt asks for one or two complete sentences, at most thirty-five words per observation. Text describes the visible body part, movement direction and order, with a brief specific limitation when necessary. Render observation as returned; do not cut it mid-sentence. The numerical measurements and score rules are unchanged.

Each feature also contains status ("observed" or "unclear"), rep, evidence_frame_ids, and ball_interaction_visible. Show unclear observations as uncertainty, not as a diagnosed problem. Label this section “Experimental video feedback”; accuracy_validated and judgment_eligible remain false.

ball_interaction_visible is the visual review's interpretation. It does not change timing.reps[].outcome into a measured hit or turn an unavailable timing number into a measured value. Hips/shoulders feedback describes visible turning order, not a measured 3D separation angle. No validated score against exact pitch location is supplied by this one-camera visual review.

When visual_review.status is "unavailable", show its safe message or reason_code. Keep showing clips, supported measurements and coaching.

Experimental video score

Show product.visual_review.score separately from the original Mechanics score in coaching.score. When its status is "available" and value is non-null, display its name ("Experimental video score"), value / max_value, explanation and per-swing rep_scores matched by rep. Zero is a valid score; use value !== null, not a truthiness check. If unavailable, hide the number or show its explanation. Keep the rest of the result visible.

The model chooses fixed Clear/Mixed/Needs practice grades; the server calculates points. A swing needs two rateable features from that same swing. Unclear features are excluded, not graded zero. Only scored_reps contribute to the root score; it does not rate every swing or the player's overall ability. Both accuracy_validated and judgment_eligible remain false. See the scoring guide and full fields.

Practice suggestion

If both visual_review.priority and visual_review.drill exist, show:

Why:   visual_review.priority.reason
Drill: visual_review.drill.name
How:   visual_review.drill.instructions
Cue:   visual_review.drill.cue

This is one experimental session suggestion, not one drill for every swing. If no visual suggestion exists, your previous coaching.drill display can be used when non-null (name, how, cue). Otherwise hide the drill area.

Timing and older coach fields

For a plain-language timing summary, keep using coaching.timing.summary, observations[].text, unavailable[].text and data_quality when present. For each swing's actual four values, read timing.reps[].metrics by key:

Key Label
load_to_swing_ms Preparation to forward swing
foot_down_to_swing_ms Front foot down to forward swing
swing_duration_ms Forward swing to contact/closest approach
early_late_shift_ms Estimated timing shift needed to meet the ball

Render a number only when value is non-null, with its status/confidence. Use “Unavailable” with the note/reason_code for unclear metrics, and “Not applicable” when stated. Null is not zero. Keep signed foot-down differences; negative means the swing began before the foot landed.

The original coaching.summary, score, focus, strengths, drill, and data_quality remain available in the same coach response shape. A null score must stay unavailable. Use the separate visual_review.score for the experimental visual rating; do not put it into coaching.score or fill missing measurements.

Evidence frames and seeking inside a clip

evidence.frames[] includes frame, reps, url, playback_t_s, capture_t_s, athlete_box and sha256. Images use GET /v1/analyses/{job_id}/frames/{frame} and require Bearer authentication. Match evidence_frame_ids to this list, not to array indices.

For a frame belonging to a swing, the clip's local frame index is:

local_frame = source_frame - swing.start_frame
clip_seek_seconds = evidence_frame.playback_t_s - swing.source_start_playback_s

Use the playback timestamps for seeking; do not divide capture milliseconds by 1000 and assume they are clip times. Check the frame belongs to the swing and both timestamps are available. Capture-time intervals remain in timing.reps[].events; they describe uncertainty, not exact measured contact.

7. Request examples in application code

The frontend below calls your app's authenticated backend proxy, which maps /api/baseball/v1/... onto engine /v1/.... Adapt the prefix to your app. The browser never receives the engine key.

async function uploadSwingVideo(file, recordingFacts, signal) {
  const form = new FormData();
  form.append("video", file);
  form.append("options", JSON.stringify({
    ...recordingFacts,
    measurement_backend: "2d",
    coaching_mode: "poc_video"
  }));
  const response = await fetch("/api/baseball/v1/swing-coach/analyses", {
    method: "POST", body: form, signal
  });
  // Let fetch set the multipart boundary; do not set Content-Type manually.
  if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
  return response.json();
}

async function readAnalysis(jobId, signal) {
  const response = await fetch(`/api/baseball/v1/analyses/${jobId}`, { signal });
  if (!response.ok) throw new Error(`Status failed: ${response.status}`);
  return response.json();
}

async function readProduct(jobId, signal) {
  const response = await fetch(`/api/baseball/v1/analyses/${jobId}/product`, { signal });
  if (!response.ok) throw new Error(`Result failed: ${response.status}`);
  return response.json();
}

// After a completed status, each available clip can use your same-origin proxy:
function appClipUrl(jobId, swing) {
  return `/api/baseball/v1/analyses/${jobId}/swings/${swing.rep}/clip`;
}

Backend-only example for an engine request, using Node's built-in fetch:

const ENGINE_ORIGIN = "https://modventures-baseball-engine.hf.space";

async function engineRequest(relativePath, init = {}) {
  const url = new URL(relativePath, ENGINE_ORIGIN);
  if (url.origin !== ENGINE_ORIGIN || !url.pathname.startsWith("/v1/")) {
    throw new Error("Unexpected engine path");
  }
  const key = process.env.BASEBALL_ENGINE_API_KEY;
  if (!key) throw new Error("Engine key not configured");
  const headers = new Headers(init.headers);
  headers.set("Authorization", `Bearer ${key}`);
  return fetch(url, { ...init, headers, redirect: "error" });
}

// Inside your authenticated/ownership-checked media route:
// 1. Validate jobId as 32 lowercase hex characters and rep as a positive integer.
// 2. Confirm the logged-in user owns that job.
// 3. Construct the path yourself; do not accept an arbitrary upstream URL.
// 4. Forward only supported request headers such as Range and If-Range.
// 5. Stream upstream.body using your framework's Web-to-Node stream adapter.
async function fetchClipForProxy(jobId, rep, requestHeaders) {
  const headers = new Headers();
  for (const name of ["Range", "If-Range"]) {
    const value = requestHeaders.get(name);
    if (value) headers.set(name, value);
  }
  return engineRequest(`/v1/analyses/${jobId}/swings/${rep}/clip`, { headers });
}

The media proxy must pass through 200, 206 and 416, plus Content-Type, Content-Length, Content-Range, Accept-Ranges, ETag and Cache-Control. Do not convert every upstream response to HTTP 200. Support HEAD if the app's player uses it. Forward authenticated JSON error responses for failed requests.

8. Retry, cancel and retain results

Retry optional video feedback: POST /v1/analyses/{job_id}/video-review, no request body.

This returns the updated whole product. It reuses retained images and keeps the measurements and swing clips. It does not repeat pose inference. A completed review with the current visual-scoring rubric and wording style is returned unchanged, without another Gemini call. An older completed review with retained frames can be explicitly upgraded once using this route. An unavailable review can be retried; a genuine retry consumes Gemini quota. Allow a longer request timeout for this synchronous route and show “Retrying video feedback”. Do not retry it continuously on every poll. No retained images returns 409.

Cancel/delete: DELETE /v1/analyses/{job_id}, returning HTTP 202. Running jobs first return cancel_requested; completed jobs become cancelled and their JSON, images and clips are removed.

Storage: default engine retention is 24 hours; check /v1/capabilities for the actual value. Hugging Face ephemeral storage can disappear during rebuilds or restarts. Clip URLs are authenticated engine resources, not permanent media hosting URLs. After completion, copy the product and each available clip into your app's persistent storage if the user should revisit sessions later. Keep rep IDs with those copies. An engine rebuild can erase jobs before 24 hours.

9. Errors and limits

HTTP status Meaning
401 Invalid/missing engine Bearer key.
404 Job, rep or evidence frame not found.
409 Result not complete, older artifact missing, or requested clip unavailable. Check detail.
413 Upload/options/request too large.
415 Unsupported video extension.
416 Invalid/unsupported/unsatisfiable byte range.
422 Bad options, missing upload field, empty file, or invalid explicit ranges.
429 Queue, upload slots or review already busy. Respect Retry-After when provided.
500 Stored artifact failed integrity/structure checks, or review could not be saved.
503 GPU not ready or requested server component unavailable.
507 Insufficient engine storage.

Errors use {"detail": ...}; detail can be a string, object or validation list. Parse safely. A job can later fail with error codes such as invalid_video_or_capture, inference_failed, job_timeout, or worker_error. Optional Gemini failure is instead reported within visual_review; it does not automatically make the analysis job fail.

Default limits: 512 MiB upload, 120 seconds of playback, 7200 decoded frames, 8,294,400 pixels per source frame. Supported extensions: .mp4, .mov, .mkv, .avi, .webm. Limits can be configured; read /v1/capabilities rather than assuming these values forever.

Public /healthz checks liveness; /readyz checks GPU readiness and reports visual model configuration/provider status. /docs serves interactive engine API documentation. Authenticated /v1/input-schema and /v1/swings-schema return the current input and swing-list schemas.

10. Integration acceptance checks

  • Upload a multi-swing video with single_swing: false; store the returned job ID and poll it to completion without sending a second coach request.
  • Show all returned swing entries, each with its own rep ID and playable clip when available. Test seeking, and check HTTP 206 through the media proxy.
  • Match each swing's timing/measurements by rep; attach only visual features that cite that rep. Show review coverage for unreviewed swings.
  • Show the three experimental feedback cards even when the older coach's score and focus are unavailable.
  • Handle unclear/null metrics, unavailable video review, unavailable individual clips, an empty swing list, and an older product with no swings field.
  • Retry feedback without re-uploading or losing existing clips/measurements.
  • Keep the engine key in the backend; test user ownership on results and media.
  • Copy retained sessions to app storage; handle expired/rebuilt engine jobs.

Do not fill unavailable measurements with visual guesses. This integration provides the working POC's visible observations, supported estimates and clips; it does not establish validated one-camera measurement accuracy.