baseball-engine / docs /SAM_BATTING_API.md
github-actions[bot]
Automated Deploy: 5f5a7796b033a641e2d36ba6ab13a6325199a1a5
ae695bd
|
Raw History Blame
17.2 kB
# Corrected SAM batting API
Test page: `/sam-batting`. Existing Swing Lab and its endpoints keep their own contracts.
One video runs through person-box tracking, **one SAM 3D Body pose model** (body and
hand decoders), temporal correction, calculations, four annotated videos, and the
existing coach service's per-measurement review. The person detector chooses the
athlete crop; it does not supply a second skeleton. No bat/ball or Gemini image
review runs in this flow. Coaching receives calculated numbers only.
## Requests
All `/v1/` calls require `Authorization: Bearer <BASEBALL_API_KEY>`. Keep this key
in the app's backend, not in a distributed mobile app. The HTML page accepts it
for testing, holds it in memory and sends it only to this server.
| Method and path | Purpose |
| --- | --- |
| `GET /v1/sam-batting/capabilities` | Configuration, queue readiness, limits and schema links |
| `POST /v1/sam-batting/analyses` | Multipart `video` file plus one JSON-text `options` field; returns HTTP 202 and a job ID |
| `GET /v1/sam-batting/analyses/{job_id}` | Poll status/progress; completed jobs include `result_url` |
| `GET /v1/sam-batting/analyses/{job_id}/result` | Four groups, per-swing measurements/coaching, quality flags and video links |
| `GET` or `HEAD /v1/sam-batting/analyses/{job_id}/videos/{group}` | Authenticated MP4; supports byte ranges |
| `POST /v1/sam-batting/group-reviews` | Add/refresh four group scores and coaching from existing measurement groups; no GPU/video upload required |
| `GET /v1/sam-batting/group-review-schema` | Input/output schemas for refreshing group reviews |
| `DELETE /v1/sam-batting/analyses/{job_id}` | Cancel and remove the retained recording/results |
Group keys: `rotation`, `timing`, `posture`, `stance`.
Postman: Body → form-data → `video` type File and `options` type Text. Example
options **only if these declarations describe the actual recording**:
```json
{
"timing": {"kind": "unretimed", "source": "Original camera recording; no speed changes"},
"camera_stability": "fixed_verified",
"up_vector": [0, -1, 0],
"up_source": "Camera verified upright and level; approximate vertical",
"handedness": "right",
"single_swing": true,
"coaching": true
}
```
Image-up is not automatically gravity. An upright, level camera declaration is
an explicit approximation, not recovered calibration. Leave vertical unknown for
a tilted camera unless you can supply a reliable vector in SAM camera axes.
When vertical is known but 3D pitcher direction is unknown, headings use the fixed
starting hip axis. Field-forward/lateral stride remain unavailable. An image-left
or image-right label cannot supply a full 3D field direction.
Optional fields:
- `camera`: `fx`, `fy`, `cx`, `cy`, `source`, in upright decoded pixels.
- `pitcher_vector` and `pitcher_source`: a known 3D direction in camera axes.
- `scale_factor` and `scale_source`: a documented uniform correction of SAM's
metre-scale estimates. Changing scale alone does not validate depth.
- `lead_foot`: `left` or `right`; otherwise handedness supplies the conventional lead.
- `athlete_box`: `[x1,y1,x2,y2]` in upright pixels to disambiguate multiple people.
- `windows`: up to twenty reviewed, ordered, nonoverlapping swing windows.
- `correction` and `measurement`: explicit algorithm settings; defaults appear in
the input schema and the result. They are engineering defaults, not validated
universal thresholds or coaching standards.
Reviewed window example (replace every frame number with reviewed values):
```json
{
"windows": [{
"start_frame": 0,
"end_frame": 240,
"baseline_frame": 20,
"forward_start_frame": 140,
"forward_end_frame": 220,
"stride_start_frame": 90,
"landing_frame": 150,
"source": "Reviewed original video"
}]
}
```
Without windows, hand-motion peaks propose automatic windows. These are explicitly
unreviewed candidates, not verified swing/foot-contact labels. Reviewed stride-start
and landing frames are required for stride calculations. A heading or settled pose
does not prove ground contact. Corrected-point retention permits forensic review;
the current API accepts reviewed windows on a new upload, not an in-place edit.
Set `single_swing: true` only when the recording contains exactly one swing. This
keeps one complete recording window and selects the strongest hand-motion candidate
for its estimated forward interval, rather than counting preparation/recovery
movements as additional repetitions. This declaration does not validate the forward
start/end events. With the default `false`, the page labels unreviewed intervals
**motion candidates**, not confirmed swings. For a reliable per-swing count in a
multi-swing recording, supply reviewed windows. Rotation from baseline ends at the
selected window boundary; that boundary is not automatically actual swing completion.
## Result contract
Schemas: `/v1/sam-batting/input-schema` and `/v1/sam-batting/output-schema`.
Published copies: `sam-batting-input.schema.json`, `sam-batting-result.schema.json`.
```text
schema_version: "1.1" # Reads previous 1.0 results too
algorithm_version: "batting-corrected-points-v1"
session_id
model # pinned SAM source, weight hashes, precision
correction # version, settings, rejection/smoothing counts, bad sections
calculation_settings
coordinates # axes, origin, scale and reference sources
capture # frame count, clock known, local cadence summary
quality_flags
groups[]
key, label
score # Estimated coaching score, 0–10; graded aspects and evidence
coaching # Summary, what_went_well, what_needs_work, next_step
annotated_video # status, url, checksum, dimensions and duration
swings[]
rep, start_frame, end_frame, baseline_frame, window_source
forward_rotation_sign, lead_foot
movement_peak_order, peak_order_reason_code
measurements[]
key, label, value, unit, statistic, reference
status # estimated, partial or unavailable
reason_code, quality_flags, source_frame_ids, sample_spacing_ms
formula, accuracy_validated: false
coaching
explanation, review, source, model, assessment, reason_code
```
**No raw/corrected joint arrays or per-frame timestamps are returned.** Private
source-timed trajectories and metric curves drive calculations and video overlays.
Frame IDs, scalar movement timing measurements, and cadence metadata remain in
the public result so values can be interpreted and inspected. Playback preserves
original video timing, including slow motion; physical calculations use declared
capture timing. An unknown capture clock withholds physical speeds and durations.
Every metric states its statistic. Hip/shoulder headings are sampled at maximum
absolute observed separation; rotation-from-start uses the end of the selected window;
lean/head excursions report maximum absolute values, marking incomplete windows
partial; stance is sampled at baseline and foot headings at reviewed landing or
baseline. Speeds and peak delays require usable continuous forward-window data.
Peak order is sorted from observed sampled peak times, never forced into a
hip-first pattern. Identical-frame peaks leave order unresolved. Local sample
spacing is not an accuracy bound; millisecond formatting does not create finer
capture resolution.
Missing data is per metric. Missing wrists do not invalidate usable foot geometry.
Return `null`, not zero, for unavailable measurements. Zero is a valid value.
Do not hide an entire group merely because one of its values is unavailable.
Show the exact reason and its coaching explanation.
Each group has its own version of the complete recording, without audio, with
relevant skeleton markings over the original picture. No bottom information
panel or measurement text is added; values remain in the JSON and page cards.
The videos use the same corrected 3D points, projected through the matching SAM
camera model. Native prediction coordinates never replace failed
corrected coordinates. Videos resize to at most 1280 pixels on the longest side.
## Correction, geometry and conditional values
SAM's first seventy `pred_keypoints_3d` points use the pinned MHR-70 mapping.
The model's axes/metre conversion is already applied. Camera translation is
applied once for rendering, not interpreted as ground displacement. A projection
convention check must pass before using a frame. SAM supplies no calibrated
per-joint confidence; it stays unknown.
Correction checks finite points, image visibility, consistent person tracking,
timestamp gaps, and isolated reversals corroborated by unusual bone length for
that recording. It does not reject a point merely for moving quickly. A centered
quadratic fit narrows its time support during faster motion. Gaps remain gaps;
there is no interpolation. Raw predictions, corrected points, point-validity bits
and filter boundaries remain private. Derivatives use the nonuniform three-point
formula at the middle sample and never cross gaps or filter boundaries.
The reference definitions are supplied in
`SAM3D_Batting_Measurements_From_Corrected_Points.md` (14 October 2026). We implement
line headings/separation, angular and hip-relative wrist speeds, peak timing,
torso centerline lean, ear-midpoint displacement, stance/foot headings, and relative
stride. A shoulder-line separation is not a clinical spine angle; hand speed is
not bat speed; head excursion is not path length or foot pressure.
Ground-relative head/pelvis displacement and absolute stride return
`missing_ground_reference`: this API does not reconstruct validated ground
translation. Whole-body center of mass returns `missing_mass_model`: no complete,
population-appropriate segment mass model was supplied. Vertical, pitch direction,
capture clock and reviewed stride events have their own missing-data reasons.
The existing coach service is extended for this contract rather than relabelling
new metrics as legacy measurements with different definitions. It uses the shared
provider configuration and daily usage ledger. Every metric gets a deterministic
explanation; optional Gemini text adds short descriptive interpretation for usable
values. Invalid/provider-failed notes fall back independently without losing any
numbers. Per-measurement explanations remain descriptive. Separate group coaching
now gives an **estimated AI score out of ten**, strengths, points to work on and a
next action, using the available values. These are POC coaching judgments, not
validated numerical performance benchmarks. The HTML page marks the distinction.
## Four group scores and coaching (result version 1.1)
For the app, display `groups[i].score.value` with `score.max_value` (ten), then
`groups[i].coaching.summary`, `what_went_well`, `what_needs_work`, and `next_step`.
Each coaching point is `{ "text": "...", "evidence": [...], "source": "coach_agent" }`. The backend supplies
the exact measurement value, unit, rep, statistic, reference and frame IDs in each
evidence item. Do not interpret a null individual metric as a missing group score.
Do not display unavailable individual measurements in the player’s main cards;
they remain in the complete API result for diagnostics. Zero is a valid score.
The `sam-groups-v3` rubric has named aspects for each group:
| Group | Aspects |
| --- | --- |
| Hips and shoulders | Hip/shoulder differentiation; rotation through the selected interval |
| Movement timing | Relationships between movement speed peaks; hip-relative hand movement |
| Posture and head | Torso position; hip-relative head movement; ground displacement only if supplied |
| Stance and stride | Starting base geometry; foot orientation; stride only if supplied |
Gemini grades each assessable aspect from zero to four: priority for practice,
substantial work, developing/mixed, useful pattern with a refinement, or strong
pattern to preserve. Python computes `round(10 * sum(grades) / (4 * aspect_count), 1)`.
The rubric version, individual grades and supporting evidence are returned. A grade
is an AI coaching opinion about the measured pattern, not a population percentile,
age comparison, diagnosis, player-ability rating or objective proof of a fault.
Temporal claims such as acceleration, deceleration, maintained posture and repeatability cannot be inferred from scalar summaries. Strengths describe supplied geometry/peak relationships; improvement points are practical refinements. Different toe headings are not a proven fault or a demand for matching angles. There are no invented ideal angle/speed bands. More separation, faster movement or
smaller head motion is not automatically better. Suggestions can be refinements
to try; the agent must not invent a mistake simply to fill a list.
Only non-null available values enter the provider input and cache key. Missing
measurements/aspects add neither zeros nor penalties. The remaining aspects are
weighted equally. All four groups in the verified example have usable evidence,
so all four can receive a score while the twelve missing measurements stay unchanged.
Every strength, improvement point and next step cites evidence from its own group;
the server resolves those IDs to the original numbers. Cross-group evidence,
invented evidence IDs and changed aspect IDs are rejected and retried once.
Prose is checked independently: an unsupported paragraph is replaced with a
source-defined factual explanation or practical rehearsal suggestion, while valid
grades and other paragraphs remain. `summary_source`, point `source`, and aspect
`explanation_source` identify `coach_agent` or `rules`; the group coaching source
is `mixed` when both occur. This fallback does not invent grades or measurements.
Use the same Bearer key to refresh a saved result without running SAM again:
```text
POST /v1/sam-batting/group-reviews
Content-Type: application/json
Body: { "groups": <groups array from a SAM result> }
Response: { "schema_version": "1.0", "groups": [{ "key": ..., "score": ..., "coaching": ... }, ...] }
```
Merge those returned fields into the matching original group by `key`; videos and
measurements are unchanged. The HTML page has a refresh button and can open a
saved result JSON. Refresh is a measurement-only Gemini call, uses the shared daily
budget/cache, and is capped at four MiB, four groups and twenty windows per group.
An already configured GPU is not needed for this route. The API never fetches
submitted video URLs. The page accepts API media URLs only on its own origin.
The preserved 1.0 fields remain usable; new jobs produce the additive 1.1 result.
A provider/key/budget failure does not create a fabricated default score or erase
the measurements. Its score stays pending and the refresh route returns a retriable
503 for affected groups with evidence. `coaching: false` makes no Gemini calls.
An entirely empty group cannot support a truthful assessment; that exceptional
case is separate from the normal partial-data scoring described above.
Qualitative background, not validation of this scoring rubric: [USA Baseball on
individual stance choices](https://www.usabaseball.com/news/topic/article/general/the-art-of-the-batting-stance-at-the-ntis-champions-cup),
[MLB’s stance definitions and variation](https://www.mlb.com/glossary/statcast/batting-stance),
and [WRSSBA’s coaching discussion of stance and turning](https://wrssba.com/coaches/skills-and-drills/hitting-mechanics/).
These sources do not supply or validate the out-of-ten scoring formula above.
## Deployment
The default Docker build includes an isolated Python 3.11/Torch CUDA SAM runtime
and the pinned source. It does not embed gated weights or credentials. At startup,
`tools.start_api` prepares normally approved assets using the Space's `HF_TOKEN`,
records their revision/checksums, then starts the API. A configured external
`BASEBALL_SAM_WORKER_RECORD` can reuse an existing worker. `BASEBALL_SAM_SKIP_SETUP=1`
skips automatic setup. Optional `BASEBALL_SAM_MODEL_REVISION` pins the provider model
commit; otherwise its resolved commit is recorded. Missing access leaves the old
API usable and the new upload route returns an explicit 503.
All jobs share the existing single-GPU queue, upload limits, cancellation,
timeouts and retention. The default job timeout is 1800 seconds. Full-recording
SAM can be slower than sparse event inference; benchmark your GPU and recordings.
Source uploads are removed when a job terminates; private arrays, JSON and videos
are removed on cancellation or normal retention expiry. Space disk is ephemeral
unless persistent storage is enabled. Download results you need to retain.
Verification covers analytic angle/stride/velocity examples, nonuniform timing,
translation invariance, missing joints, ambiguous peaks, fast-motion preservation,
four-video source timing, API authentication/ranges/integrity and legacy regression
checks. These verify implementation behavior; they do not establish real-video
measurement accuracy.