Spaces:
Running on T4
Running on T4
|
Download docs/PITCHING_APP_INTEGRATION.md from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 25.8 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/docs/PITCHING_APP_INTEGRATION.md
- Command line
-
hf download hf://spaces/modventures/baseball-engine/docs/PITCHING_APP_INTEGRATION.md
-
curl -L -o PITCHING_APP_INTEGRATION.md https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/docs/PITCHING_APP_INTEGRATION.md
25.8 kB
| # Pitching API integration | |
| The mobile app keeps its upload, polling and group-driven report screens. Hitting requests and saved reports remain supported. Pitching is selected explicitly; batting marks and batting-side defaults must never be used as pitching evidence. | |
| The pipeline is **video → ML pose/measurements → structured JSON → AI coach**. No pitching video, sampled image, media URL, or visual-model observation is supplied to the coach. This guide matches the deployed engine 1.21.7 and backend pitching contract verified on 2026-11-02; validation evidence is recorded in `PITCHING_VALIDATION.md`. | |
| The engine emits `pitch-1.1`, the only pitching contract the backend accepts. Forward each payload unchanged and render its returned groups. | |
| ## Changes to an already integrated mobile app | |
| Reuse account authentication, presigned uploads, video playback/frame selection, session storage, background polling and the group-driven report layout. Add a pitching branch to the request builders and report models; leave the hitting branch unchanged. | |
| | Integration point | Pitching change | | |
| |---|---| | |
| | Session | `mode: "p"`; pitching athlete and marks below | | |
| | Event picker | `leg_lift_frame`, `foot_strike_frame`, `release_frame`; each nullable | | |
| | Hand | Backend `throws: "L"/"R"` maps to engine `throwing_hand: "left"/"right"` | | |
| | ML request | `/v1/motion-analyses`, `discipline: "pitching"`, `single_pitch: true`, original video plus JSON options | | |
| | ML-to-coach handoff | Fetch `coach_payload_url`, forward its JSON unchanged to `/v1/sessions/{id}/pitch-report` | | |
| | Report | Four pitching group IDs; nullable scores, values, focus and drill; generated/unavailable coaching states | | |
| | Retry | `/v1/sessions/{id}/pitch-report/retry-coaching`; reruns interpretation from saved ML evidence | | |
| `/pitch-report` queues the report by default (202, then a `result` notification); add `?queue=false` to wait for the report in the request as described below. See `backend/docs/FRONTEND_INTEGRATION.md` §5. | |
| There is no mobile Gemini call and no new AI-provider key for the app. The backend generates and stores coaching when `/pitch-report` is called. | |
| ## Services and authentication | |
| | Service | Base URL | Authentication | | |
| |---|---|---| | |
| | App backend | `https://baseball-engine.scalethemod.online` | Existing account bearer token | | |
| | ML engine | `https://modventures-baseball-engine.hf.space` | Engine bearer credential through your existing engine transport | | |
| The account token and engine credential are different. Keep engine secrets in the existing server/proxy credential handling, rather than embedding a shared engine key in the mobile binary. All engine status, result, schema and coach-payload requests require engine authentication. Resolve the engine's relative URLs against the **engine** base URL, not the app backend. | |
| **SDK generation:** regenerate mobile API models from `https://baseball-engine.scalethemod.online/openapi.json` or the checked-in [backend OpenAPI snapshot](../backend/docs/openapi.json). The pitch-report request takes `pitch-1.1`; saved session reports support the existing hitting/legacy report, the current pitching report, or null. The pitching report and retry responses include the current pitching groups and nullable fields. Do not send the ML payload through an older hitting-only serializer that drops pitching fields. | |
| The report envelope still has `schema_version: "1.0"`, with `discipline: "pitching"` and `meta.input_schema_version: "pitch-1.1"` for current pitching. Only the incoming ML payload has `schema_version: "pitch-1.1"`. Do not dispatch report parsing on `report.schema_version` alone: use the current report's `discipline` when present and the session's `mode` for legacy reports. Standalone contracts remain available in [pitching-coach-payload.schema.json](pitching-coach-payload.schema.json) and [pitch-report.schema.json](pitch-report.schema.json). | |
| For `openapi-typescript`, generation was checked with version 7.13.0 and strict TypeScript compilation against current pitching, legacy pitching and hitting fixtures: | |
| ```sh | |
| npx openapi-typescript@7.13.0 https://baseball-engine.scalethemod.online/openapi.json --default-non-nullable false -o src/api/generated.ts | |
| ``` | |
| Choose the output path used by your app. The `--default-non-nullable false` option preserves optional fields with schema defaults; the generator's default setting otherwise makes some optional existing hitting/legacy fields required in generated types. No manual pitching type definitions are needed for these documented contracts. | |
| ## Player flow | |
| 1. Use the existing Pitching tab and `mode: "p"` when creating a session. The Home label can be “Delivery score”. A missing score is **Not rated**, not zero. | |
| 2. Confirm the **throwing hand** in the guide, seeded from `profile.throws`. Record one delivery from setup through finish, with the athlete fully visible. No batting-side question is needed. | |
| 3. Mark **Release**, **Peak leg lift**, and **Foot strike** on the original decoded frame list. Foot strike means the first visible lead-foot ground contact, not full weight acceptance. Each mark can be `null`: offer **Not visible / not part of this drill**. A rocker may have no leg lift; a dry delivery has no ball release. Never substitute frame zero or another event. Do not use audio contact detection. | |
| 4. Confirm recording speed and camera stability. Preserve the original video and timestamps. Playback FPS alone does not establish the physical recording speed of an edited/slow-motion clip. | |
| 5. Select practice and drill separately. Knowing “bullpen” alone does not identify a normal delivery versus a rocker. Unknown remains a valid answer. | |
| 6. Submit, poll, forward the immutable coach payload, and render the saved report. Report text and scores come from the server. | |
| ## Context values | |
| | Field | Supported values | | |
| |---|---| | |
| | `practice_type` | `bullpen`, `flat_ground`, `live_bp`, `game`, `dry_delivery`, `unknown` | | |
| | `drill_type` | `standard`, `step_back`, `rocker`, `other`, `unknown` | | |
| | `pitch_type` | `fastball`, `breaking_ball`, `changeup`, `other`, `unknown` | | |
| | `ball_type` | `baseball`, `training_ball`, `none`, `unknown` | | |
| Unknown values are allowed, but send the real values when the player picks them. Scoring: regular fastballs with a baseball (any practice type, `standard` drill) are compared with OBP college pitchers of the same throwing side. Unknown practice, drill, pitch or ball is compared as a regular fastball, but leg lift and stride results are not used for advice. `step_back` and `rocker` are compared except for the leg lift and stride results. `other` drills, `dry_delivery`, non-fastball pitches and training or no ball are described without scores. Every level is compared with college pitchers, with a note. Population percentiles are not ideal-technique targets. | |
| ## Backend: create the session | |
| Continue using `POST /v1/uploads` and its presigned video upload, then `POST /v1/sessions` at the app backend. Use the existing account bearer token. Example session fields: | |
| ```json | |
| { | |
| "video_upload_id": "<uploaded-video-uuid>", | |
| "mode": "p", | |
| "is_self": false, | |
| "athlete": { "name": "Pitching athlete", "throws": "L" }, | |
| "duration_sec": 3.747, | |
| "fps": 24, | |
| "frame_count": 88, | |
| "marks": { | |
| "leg_lift_frame": null, | |
| "foot_strike_frame": 58, | |
| "release_frame": 64 | |
| } | |
| } | |
| ``` | |
| These marks illustrate request shape, not reviewed event labels for an uploaded video. Supply actual marked frames. `frame_count` is the exact decoded count, not duration multiplied by rounded FPS. It is an additive field; legacy hitting clients remain supported. The engine independently decodes and validates the video. For someone else's pitching clip, age, height, weight, playing level and batting hand can be omitted rather than invented. For your own delivery, use `is_self: true, athlete: null` and the backend snapshots the account profile. The ML athlete must describe the filmed pitcher, not unrelated account demographics. | |
| Session creation returns HTTP **201** with `{"session": {...}}`; take the ID from `response.session.id`. Reuse the existing `Idempotency-Key` mechanism so a network retry does not create another session. `marks` is required, but individual pitching mark fields may be null or omitted. Frame indices are zero-based. Use the same reviewed marks for the backend session and engine options. | |
| ## ML: submit the delivery | |
| `POST https://modventures-baseball-engine.hf.space/v1/motion-analyses` | |
| Headers: `Accept: application/json`, `Authorization: Bearer <engine key>`. Let the multipart library set Content-Type and its boundary. Parts remain `video` (original clip) and `options` (one JSON string). | |
| ```json | |
| { | |
| "discipline": "pitching", | |
| "model": "sam3d", | |
| "single_pitch": true, | |
| "annotated_videos": false, | |
| "handedness": "left", | |
| "camera_stability": "fixed_verified", | |
| "timing": { "kind": "unknown" }, | |
| "athlete": { | |
| "athlete_id": "session:<session-id>:athlete", | |
| "throwing_hand": "left", | |
| "lead_foot": "right", | |
| "age_years": null, | |
| "height_cm": null | |
| }, | |
| "context": { | |
| "sport": "baseball", | |
| "practice_type": "unknown", | |
| "drill_type": "rocker", | |
| "pitch_type": "unknown", | |
| "ball_type": "unknown" | |
| }, | |
| "pitch_id": "<backend-session-id>", | |
| "release_frame": 64, | |
| "windows": [{ | |
| "start_frame": 0, | |
| "end_frame": 87, | |
| "leg_lift_frame": null, | |
| "foot_strike_frame": 58, | |
| "source": "Reviewed original decoded recording" | |
| }] | |
| } | |
| ``` | |
| Use `timing.kind: "unretimed"` only for a known original-speed recording; include a `source` explanation. Existing documented slowdown/explicit-capture-time options also work. No speed assumption is made for an unknown export. Set `camera_stability` to `fixed_verified` only after confirmation; otherwise use `unknown`, or `moving` for a moving camera. Camera evidence can contradict a `fixed_verified` declaration and withhold affected measurements. | |
| `handedness` and `athlete.throwing_hand` must agree. Lead foot is opposite the throwing hand. Pitching does not accept `contact_frame`, `swing_id` or `single_swing: true`. Marked indices must satisfy `0 <= frame < decoded frame_count`; `end_frame` is inclusive. Known marks must be ordered leg lift < foot strike < release. Missing marks are independent: foot strike/release can be measured without a leg lift. | |
| Include the engine `athlete` object with a nonempty `athlete_id`; without it, no coach payload is requested. Omit inherited `coaching`, or set it to `false`: `coaching: true` is invalid on this endpoint. Omit batting-specific options such as `contact_frame`, `swing_id`, and `single_swing` when constructing a pitching request. Keep `annotated_videos: false`. | |
| For `dry_delivery` or `ball_type: "none"`, release must be null. Mark the exact file that will be uploaded; if exporting or compressing changes its frame list, review the marks again against that file. | |
| ## Poll, fetch, save | |
| 1. The upload returns HTTP 202 with `job_id`, `status_url`, `result_url`, `coach_payload_url`. | |
| 2. Poll `GET /v1/motion-analyses/{job_id}`. `queued`, `processing` and `cancel_requested` are nonterminal; `completed`, `failed` and `cancelled` are terminal. For failure, use `failure?.reason_code`, then `failure?.code`, `error`, or a generic message. Failure details can be null. Stop polling terminal jobs. | |
| 3. Fetch `GET /v1/motion-analyses/{job_id}/coach-payload`. Pitching payloads have `schema_version: "pitch-1.1"`, `discipline: "pitching"`, `pitch_id`, and pitching events. Preserve the payload unchanged. | |
| 4. Send it to **`POST https://baseball-engine.scalethemod.online/v1/sessions/{session_id}/pitch-report`**, using the account bearer token and JSON Content-Type. `pitch_id` must equal the session id; the session must have `mode: "p"`. | |
| 5. The report POST returns HTTP **200** with the **bare report object**. `GET /v1/sessions/{session_id}` returns `{"session": {...}}`; read its report from `response.session.report`, with session `status: "done"` and synchronized pitching marks. Engine job completion and backend session completion are separate: the session is not done until the report is saved. Obsolete pitch-1.1 feedback is hidden until refreshed, as described below. Session lists and Home summaries expose its score, including null; use `GET /v1/sessions?mode=p` for pitching history. | |
| Poll at a bounded interval (for example, every 2–3 seconds), resume from the saved `job_id` after app interruption, and preserve the fetched coach payload for an identical report-save retry. Status responses have null result/payload URLs until ready. `result_url` returns an ML manifest, **not** the coach payload; use `coach_payload_url`. Do not send the manifest or rebuild measurements client-side. | |
| Retries of identical analysis/revision return a current stored report without charging again; obsolete pitch-1.1 coaching is rebuilt from the saved ML data. A different payload for the same revision is rejected. Higher revisions replace that analysis's report; older revisions and a different analysis id are rejected. Ownership, consent and existing plan limits apply. | |
| For changed marks, use `POST /v1/motion-analyses/{job_id}/revisions` with an `options` patch, then poll/fetch/save the new revision. Discipline, athlete identity and `pitch_id` stay fixed. The existing engine retention/restart limitations still apply; store completed reports promptly. | |
| Revision requests are JSON, not multipart. Objects merge, but arrays replace: resend the complete one-element `windows` array, including bounds and all retained marks. For example: | |
| ```json | |
| { | |
| "options": { | |
| "release_frame": 65, | |
| "windows": [{ | |
| "start_frame": 0, | |
| "end_frame": 87, | |
| "leg_lift_frame": null, | |
| "foot_strike_frame": 58, | |
| "source": "Reviewed correction on the original uploaded file" | |
| }] | |
| } | |
| } | |
| ``` | |
| Explicit null clears a mark. The response supplies a new `job_id`, the same `analysis_id`, and a higher `analysis_revision`; poll the new job and forward its new coach payload to the same backend session. Do not submit a brand-new analysis to replace an existing session's analysis. | |
| ## Four report groups, ten measurements | |
| | Group id | Label | Measurements | | |
| |---|---|---| | |
| | `gather` | Gather | Torso lean at peak leg lift; leg-lift-to-foot-strike time | | |
| | `stride_plant` | Stride and Plant | Horizontal ankle spacing at foot strike; front-knee bend; hip–shoulder separation | | |
| | `rotation_release` | Rotation and Release | Front-knee straightening to release; throwing-elbow bend at release; foot-strike-to-release time | | |
| | `release_finish` | Release and Finish | Torso lean at release; shoulder turn over approximately the first 100 ms after release | | |
| Ankle spacing is an absolute joint-centre distance, not distance travelled or a height-normalized stride grade. Knee straightening is an angle change, not blocking force. Elbow bend is not arm slot, stress or injury risk. The finish metric covers an early interval, not the quality of the entire finish. Ball speed, spin, pitch location, torque, force and injury predictions are not supplied. | |
| Render `groups` and `measurements` dynamically. Each group has `group`, `display_name`, `summary`, `metric_ids` and a nullable `score`. Match measurements using `metric_id` or `group`; render their server-provided `display_name`, `display_value`, `unit` and `limitations`. Show `score_is_tentative`/`rating_is_tentative`, limitation text, `not_rated_reason`, context and coverage warnings. A measurable value can have a null score because no suitable reference exists. `focus_area` and `focus_area.drill` may each be null: do not display or invent a corrective drill in that case. | |
| | Returned condition | Mobile display | | |
| |---|---| | |
| | `value: null` / unavailable measurement | “Unavailable” plus supplied limitation; never `0` | | |
| | Value present, `score: null` | Estimated measurement with “Not rated” | | |
| | `coaching.status: "generated"` | Returned summary and coaching cards | | |
| | `coaching.reason: "some_coaching_cards_withheld"` | Retained cards plus a partial-feedback notice | | |
| | `coaching.status: "unavailable"` | Measurements stay visible; show unavailable-AI state and retry action | | |
| | `coaching.reason: "coaching_refresh_required"` | “Refresh coaching” action; no stale advice | | |
| | Null `focus_area`, `drill_evaluation`, `delivery_evidence` or `coaching` | Omit that panel; no forced placeholder object | | |
| ### Motion evidence and personalized coaching | |
| The additive `delivery_evidence` contains frame-indexed knee, elbow, torso, pelvis and shoulder curves; phase summaries from setup through the recorded finish; source-clock information; and provisional rotation peak ordering when enough reliable timed samples exist. Null samples are tracking gaps. Coverage is **not confidence**. `consistency: not_assessable_single_delivery` means another comparable delivery is needed before discussing repeatability. | |
| `visual_evidence` is a deprecated compatibility input and is discarded. New payloads and reports return null. The coach receives only measurements, approximate event marks, quality reasons, phase summaries and task context; it cannot claim to have seen the video. `coaching.evidence_mode` is `ml_measurements_and_motion`. Unknown or unstable evidence cannot support a movement correction. | |
| `coaching.status: generated` and `meta.text_source: llm` mean a real model produced personalized coaching and an automated evidence critique accepted it. Render `coaching.cards` with `observation`, `why_it_matters`, `next_step`, `check`, and `evidence_ids`. Cards distinguish `positive`, `review`, and `limitation`; all remain provisional. The existing overview/focus fields also contain the generated summary and selected next step. Automated critique reduces unsupported claims but is not expert validation or a guarantee against model mistakes. | |
| Evidence IDs may refer to measurements, events, phases, drill criteria, clock information or limitations. Do not assume every ID maps to a measurement row. Charts are optional for initial integration; if shown, preserve null samples as gaps rather than drawing invented motion through them. | |
| When `coaching.reason` is `some_coaching_cards_withheld`, show that some feedback could not be verified. The returned summary and each returned card passed separate checks; rejected cards are omitted. Never infer a technique fault from withheld feedback. The same reason is preserved when an accepted partial report is served from cache. | |
| If generation is unavailable or rejected, `coaching.status: unavailable` includes a reason. Keep the measurements available and label the descriptions as non-AI fallback. Do not market them as personalized AI coaching. | |
| Offer **Retry AI coaching** using `POST /v1/sessions/{session_id}/pitch-report/retry-coaching` with the account bearer token and no body. By default it retries unavailable coaching and rebuilds reports with obsolete visual evidence or a superseded coaching prompt; it returns a current generated report unchanged. Reposting the identical analysis also rebuilds an obsolete report without another analysis charge. Use `?refresh=true` to explicitly reinterpret an existing report with the current coaching implementation. Ownership and consent still apply. Neither operation reruns pose estimation or consumes another analysis. The saved engine payload stays unchanged; current quality checks can withhold unreliable older estimates or visual claims from the displayed report. Refresh uses only the saved ML evidence and discards all legacy visual observations. | |
| Retry returns HTTP 200 with a **bare report**, which should replace the local displayed report. `refresh=true` can reuse accepted cached coaching (`meta.cache_hit: true`); it does not guarantee a new provider call. Retry requires a saved pitch-1.1 report: a missing report returns `409 REPORT_NOT_READY`,. | |
| Reading an obsolete pitch-1.1 report returns `coaching.status: "unavailable"` and `coaching.reason: "coaching_refresh_required"`. Superseded advice, visual observations and grades are hidden in session details and summaries, including coach views. Display a refresh action while retaining access to the saved measurements as provisional estimates. Reads do not call the coach, rewrite the stored analysis or consume quota; only the explicit retry/report routes regenerate feedback. Current pitching and hitting reports retain their existing read behavior. | |
| `drill_evaluation` provides source-backed objectives and observed/indeterminate findings for step-back, rocker and standard deliveries. Its `validation_status` is `provisional_qualitative`; its score is null. These are not validated drill scores. Other or unknown drills do not acquire made-up criteria. Do not convert missing scores to zero or assign a percentage based on checklist coverage. | |
| Angles with unusable neighboring frames, interpolated event landmarks, or more than twenty degrees of adjacent-event sensitivity are withheld. Phase movement direction is also withheld when shifting either event by one frame can reverse it. The last rule is a conservative **operational abstention threshold**, not a validated accuracy bound or a biomechanical normal range. Raw model curves remain available for review and retain their limitations. | |
| ### Capture-time examples | |
| - Known original-speed recording: `{"kind":"unretimed","source":"Original camera file; no speed changes"}`. Real PTS differences are used, including variable frame rate. | |
| - Confirmed uniform fourfold slow-motion export with every capture frame retained: `{"kind":"constant_slowdown","factor":4,"all_captured_frames_retained":true,"source":"Verified camera/export settings"}`. Capture time equals playback time divided by four. | |
| - Speed ramps or known resampling: `{"kind":"explicit","physical_times_s":[...],"source":"Documented per-decoded-frame capture map"}`. Supply one strictly increasing physical timestamp per decoded frame. Never build this map from a guessed FPS. | |
| - Missing provenance: `{"kind":"unknown"}`. Container FPS is displayed separately and cannot establish the capture clock. Absolute durations, rotation-speed sequencing and the timed early-finish metric are withheld. | |
| `value_interval` and `score_interval` describe sensitivity to moving marked events by one source frame. They are not confidence intervals or bounds on total 3D model error. Body measurements remain estimates; API success and formula tests do not establish physical accuracy. | |
| ## Discovery and errors | |
| - `GET /v1/motion-analyses/capabilities` advertises `supported_disciplines` and the pitching contract. | |
| - `GET /v1/motion-analyses/input-schema?discipline=pitching` gives exact upload fields. | |
| - `GET /v1/motion-analyses/output-schema` includes `pitching_coach_payload` alongside existing hitting schemas. | |
| - Local schemas: `pitching-input.schema.json`, `pitching-coach-payload.schema.json`, `pitch-report.schema.json`. | |
| - Invalid fields/order: HTTP 422. Window end past decoded video: `reviewed_frame_out_of_range`; release beyond it: `release_frame_out_of_range`. Do not clamp marks to make the request pass; review the uploaded file's frames. | |
| - Backend errors include `MODE_NOT_SUPPORTED`, `INVALID_PAYLOAD`, `ANALYSIS_MISMATCH`, `STALE_REVISION`, `REVISION_PAYLOAD_MISMATCH`, ownership/consent failures and existing plan limits. | |
| Backend errors use `{"error":{"code":"...","message":"...","fields":{...}}}`; engine HTTP errors use `{"detail":...}`, where detail may be a string, object or validation list. Handle engine `429` using `Retry-After`, `503` as temporarily unavailable, and `404` as missing/expired job instead of polling forever. A failed report save does not require another ML run when the original payload is already available. | |
| ## Mobile acceptance checklist | |
| - A pitching session uses `mode: "p"`, the filmed athlete's throwing hand, and pitching marks only. | |
| - Left/right hand mappings and zero-based frame bounds are correct; null marks survive JSON encoding. | |
| - A rocker without leg lift works; a dry delivery does not acquire a fake ball-release mark. | |
| - Unknown capture timing stays unknown; the app does not infer timing from exported FPS. | |
| - Engine completion is followed by fetching the coach payload and saving it through `/pitch-report`. | |
| - JSON forwarding preserves `pitch-1.1`, analysis identity/revision, measurements and motion evidence. | |
| - All four pitching groups render without hitting-only enum failures; null values/scores/focus/drills are supported. | |
| - Partial, unavailable and refresh-required coaching states remain distinguishable from a failed ML job. | |
| - Report-save retry, coaching retry, mark revision, history reload and app-resume polling work. | |
| - Hitting screens, request builders and existing reports retain their current behavior. | |
| ## Reference provenance | |
| Nine geometry/timing references are derived from [OpenBiomechanics dataset-v1](https://github.com/drivelineresearch/openbiomechanics/releases/tag/dataset-v1), using the same 3D joint-centre formulas and per-athlete medians. Ankle distance is deliberately ungraded. Generation is reproducible with `data_ref/scripts/compute_pitching_contract_benchmarks.py`; hashes and cohort counts are in `AI-coach-agent/src/ai_coach/knowledge/pitching_benchmarks.yaml`. Derived data retains CC BY-NC-SA 4.0 attribution and terms. Reference distributions describe the sampled pitchers, not ideal technique. Visual foot strike only approximates the laboratory force threshold. | |
| The supplied drill labels correspond to [Driveline's drill library](https://drivelinebaseball.com/blogs/blog/plyo-velocity-weighted-balls-replication). This does not establish the filmed athlete's identity, pitch type, ball weight, effort, age or skill level. Those details remain unknown. | |