baseball-engine / docs /SWING_COACH_PRODUCT.md
github-actions[bot]
Automated Deploy: eee53c8cd123595b689e2ad05bf8c9bae3a82c9a
6686c0f
|
Raw History Blame Contribute Delete
9.84 kB

One-video swing POC

The measurement engine and AI-coach-agent now run in the same GPU service. The standalone coach service and the existing engine routes still work.

For app migration and individual swing video playback, use APP_API_INTEGRATION.md. Product 1.1 adds swings and swings_url; new API jobs export an authenticated MP4 for every detected rep. These clips now include the same skeleton, foot points and estimated event labels as the Colab previews (clip.overlay: true). The endpoint and app playback flow stay the same. Body contact proxies are explicitly labelled; unannotated original images still provide the Gemini review evidence.

The full flow is: upload one video → detect swings and body movement → track bat and ball when possible → build measurements → run the coach → optionally review sampled original video frames → return one app response.

Run it

Use the root Dockerfile and compose.yaml on an NVIDIA GPU server. The container checks actual CUDA execution before accepting uploads. The default measurement backend is 2D; SAM is not required.

Set BASEBALL_API_KEY to a random secret. Set GOOGLE_API_KEY on the server to enable experimental video feedback. On Hugging Face, add these as Space secrets, then rebuild. Never place Google credentials in Postman, frontend code, a notebook, or committed files.

Optional settings:

  • COACH_VIDEO_REVIEW_MODEL: default gemini-3.8-flash.
  • COACH_DAILY_BUDGET_USD: default 1; calls stop once recorded daily spend reaches this amount. This is a spend stop, not a hard per-call billing cap.
  • COACH_VIDEO_REVIEW_TIMEOUT_S: default 90, no transport retries.
  • COACH_VIDEO_REVIEW_MAX_OUTPUT_TOKENS: default 8000, maximum 16384; includes model reasoning as well as returned feedback.
  • COACH_VIDEO_REVIEW_THINKING_LEVEL: default low for Gemini 3.8 Flash. Use auto to omit this setting when switching to a model without level support.
  • COACH_VIDEO_REVIEW_MAX_FRAMES: default 72, maximum 96.
  • COACH_VIDEO_REVIEW_MAX_REPS: default 6, maximum 8.

The upload screen is at /. Enter the engine API key, choose the video, and select only recording facts you know. Unknown facts remain unknown. Enabling video feedback sends sampled images to Google Gemini; uncheck it to keep the request measurement-only. The key is not saved in browser storage. The same screen can reopen a result using its job ID.

/readyz reports actual CUDA readiness and visual_model_status. An available visual model passed an authenticated model-metadata lookup; this does not validate generation quota, inference results or coaching accuracy. Provider problems leave the measurement worker available. GitHub deployment checks both test suites before uploading the merged code to Hugging Face.

App integration

Use Bearer authorization with the engine API key for these endpoints:

  1. POST /v1/swing-coach/analyses: multipart form-data with a video file and optional options JSON text. Returns job_id, status_url, product_url.
  2. GET /v1/analyses/{job_id}: poll until completed, failed, or cancelled.
  3. GET /v1/analyses/{job_id}/product: the complete product JSON.
  4. GET /v1/analyses/{job_id}/coaching: your friend's unchanged response_version: "2.0" coaching response.
  5. GET /v1/analyses/{job_id}/frames/{frame}: authenticated evidence JPEGs.
  6. DELETE /v1/analyses/{job_id}: cancel and delete results and evidence.
  7. POST /v1/analyses/{job_id}/video-review: retry unavailable video feedback using retained, checksum-verified original images. It preserves measurements and returns the updated product. A completed review with the current rubric and wording style is returned without a further model call; older completed reviews can refresh their feedback using the retained images. New reviews include text_style_version: "concise-observations-v1". Only one retry runs at a time. No retained images means a new upload is required. The upload screen provides this retry button.

Recording options example; replace the values to match the recording:

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

On the new upload route, coaching_mode defaults to poc_video. Use measurements_only for the existing agent without images. Old upload routes default to disabled, preserving existing clients; they can opt in explicitly. single_swing: false allows automatic splitting. It does not guarantee all swings were found. Explicit reps can be supplied using the existing contract.

Product shape:

schema_version: "1.1"
session_id
discipline: "hitting"
coaching_mode
swings: per-rep boundaries and clip status, URL, duration, frame count, size and SHA-256
swings_url: /v1/analyses/{job_id}/swings
measurements: existing engine 2.0 measurement payload
timing: existing engine 3.1 timing evidence payload
coaching: existing coach 2.0 app response
visual_review:
  status: completed | unavailable
  source: poc_video_review
  accuracy_validated: false
  judgment_eligible: false
  score: separate experimental visual rubric score and per-rep breakdown
  features: [load_timing, hip_shoulder_separation, bat_path_contact]
    each: key, status, rep, observation, evidence_frame_ids,
          ball_interaction_visible
  priority: feature, reason, drill_id | null
  drill: id, name, instructions, cue | null
evidence:
  frames: frame, reps, playback_t_s, capture_t_s, athlete_box, sha256, url
  reviewed_reps
  total_reps
  sampled: true

What the app can claim

coaching keeps your friend's safeguards: estimated numbers are described but are not used to diagnose validated faults or assign a numerical score. The adapter preserves practice type, reason codes, actual frame cadence, and documented bat/ball endpoint sources. Arm extension never becomes ball contact.

visual_review is a separate experimental observation and practice suggestion for the three features. It can describe visible preparation, turning order, and bat movement. It cannot establish a true separation angle, pitch location, early/late correction, exact contact timing, or real-world accuracy. Do not display its observations as validated measurements or combine them into a validated score. Contact claims still depend on a model's visual interpretation.

visual_review.score now provides a separate Experimental video score. Gemini supplies fixed visual grades and Python computes the points, requiring two rateable features from the same swing. Unknown features stay unscored. Its coverage is explicit and it never becomes a Mechanics score or upgrades measurement confidence. See EXPERIMENTAL_VIDEO_SCORE.md.

Sampling includes whole-swing coverage and denser windows near estimated events. Frames retain original ordering, rotation, and separate playback/capture times. Review coverage is explicitly listed when a video exceeds the review rep limit. Bad detections and events remain possible and can also affect sample selection.

No key, budget exhaustion, bad model output, or provider failure produces an explicit visual_review.status: unavailable with a reason code, while engine measurements and the coach's descriptive response still return. No sample feedback is substituted for an unavailable live result.

Provider failures report fixed human-readable messages and safe categories such as provider_timeout, provider_rate_limited, provider_auth_failed, provider_request_rejected or provider_unavailable. When Google returns an HTTP error, provider_http_status is included. Quota metric names may be included; provider messages, credentials, project identifiers and uploaded content are never forwarded in error diagnostics. Model metadata availability alone does not establish generation quota or that a video-review call will succeed.

The video request uses response_json_schema, with only Google's supported JSON Schema constraints. Unsupported default and string-length keywords are removed from the provider request; the full Pydantic length, evidence and content checks still run locally before feedback is accepted. This avoids the rejected legacy OpenAPI response_schema request format. Incomplete model responses are rejected and reported as output_truncated or no_complete_text. Other validation failures expose only fixed reason codes, never rejected model text. Billed reasoning tokens are counted even when the response is incomplete.

Space results need persistent server storage to survive rebuilds. On a Space using temporary storage, save the product JSON and any needed evidence images before restarting or deploying. A job ID cannot recover files erased by a rebuild.

Results and evidence follow the engine retention period (default 24 hours), are checksum verified on retrieval, and require authentication. Original uploads are removed after jobs finish; sampled evidence is retained until deletion or expiry. Persistent coach cache/spend records live under /data/coach-cache.

Verification

Run engine tests and agent tests separately to avoid the two tests packages colliding. Install the root test/API dependencies, requirements-coach.txt, and AI-coach-agent[dev] in Python 3.11+ for combined tests. CPU inference on real recordings exercises data flow; fixture model responses exercise contracts and failure handling. Neither establishes coaching accuracy. Live Gemini and CUDA execution must be checked on the deployed server.