# 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](APP_API_INTEGRATION.md). 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. ```text 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: ```http Authorization: Bearer ``` 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: ```json { "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: ```json { "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: ```json { "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: ```json { "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: ```json { "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 */`. 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 `