Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
7b016f3
1
Parent(s): 35e80ff
Automated Deploy: 7c860d1533bba8cf56be38bfca5dbd8e3ae20fca
Browse files- AI-coach-agent/src/ai_coach/video_review.py +65 -1
- baseball_batting/api.py +34 -0
- baseball_batting/api_jobs.py +6 -0
- baseball_batting/product.html +4 -3
- baseball_batting/product.py +22 -0
- docs/SWING_COACH_PRODUCT.md +13 -0
- tests/test_product.py +126 -0
AI-coach-agent/src/ai_coach/video_review.py
CHANGED
|
@@ -19,6 +19,23 @@ from .knowledge import all_drills
|
|
| 19 |
from .schemas import Usage
|
| 20 |
|
| 21 |
FEATURES = ("load_timing", "hip_shoulder_separation", "bat_path_contact")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
DRILLS = {
|
| 23 |
"load_timing": {"hit_04", "hit_06"},
|
| 24 |
"hip_shoulder_separation": {"hit_13", "hit_14"},
|
|
@@ -78,10 +95,53 @@ class VisualNote(BaseModel):
|
|
| 78 |
|
| 79 |
def unavailable(reason: str) -> dict:
|
| 80 |
return {"status": "unavailable", "reason_code": reason, "source": "poc_video_review",
|
|
|
|
| 81 |
"accuracy_validated": False, "judgment_eligible": False,
|
| 82 |
"features": [], "priority": None, "drill": None}
|
| 83 |
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
def validate_note(note: VisualNote, frames: list[dict]) -> None:
|
| 86 |
by_id = {f["frame"]: f for f in frames}
|
| 87 |
for feature in note.features:
|
|
@@ -183,9 +243,13 @@ def review_video(frames: list[dict], facts: dict, settings: Settings,
|
|
| 183 |
"notice": "Experimental video observations and a practice suggestion; accuracy has not been validated.",
|
| 184 |
**note.model_dump(mode="json"), "drill": drill,
|
| 185 |
"latency_ms": int((time.monotonic()-started)*1000)}
|
| 186 |
-
except Exception:
|
| 187 |
# Provider errors can include credentials and uploaded content. Public
|
| 188 |
# responses carry a fixed code, never provider text or a traceback.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
return unavailable(outcome)
|
| 190 |
finally:
|
| 191 |
usage.cost_usd = compute_cost(settings.video_review_model, usage, settings.prices)
|
|
|
|
| 19 |
from .schemas import Usage
|
| 20 |
|
| 21 |
FEATURES = ("load_timing", "hip_shoulder_separation", "bat_path_contact")
|
| 22 |
+
FAILURE_MESSAGES = {
|
| 23 |
+
"provider_timeout": "Google did not finish the video review in time. Try the video feedback again.",
|
| 24 |
+
"provider_rate_limited": "Google's quota or rate limit for this model was reached. Check its quota in Google AI Studio.",
|
| 25 |
+
"provider_auth_failed": "Google rejected the API key. Check the GOOGLE_API_KEY secret and restart the Space.",
|
| 26 |
+
"provider_access_denied": "The Google key cannot use this model. Check the key restrictions and model access.",
|
| 27 |
+
"provider_model_unavailable": "The configured Google model is unavailable for this key.",
|
| 28 |
+
"provider_request_rejected": "Google rejected the video-review request. The server needs its request configuration checked.",
|
| 29 |
+
"provider_unavailable": "Google's service is temporarily unavailable. Try the video feedback again.",
|
| 30 |
+
"provider_client_error": "The video-review request failed inside the Google client. The server needs checking.",
|
| 31 |
+
"provider_failed": "The Google video-review call failed. Try again; measurements are still available.",
|
| 32 |
+
"invalid_visual_response": "Google returned feedback that did not pass the evidence checks. Try the video feedback again.",
|
| 33 |
+
"model_not_configured": "Add GOOGLE_API_KEY as a Space secret and restart the Space to enable video feedback.",
|
| 34 |
+
"daily_budget_exhausted": "The configured daily AI budget was reached. Measurements are still available.",
|
| 35 |
+
"no_swing_evidence": "No swing images were available for video feedback.",
|
| 36 |
+
"review_frames_unavailable": "The original video images could not be prepared for feedback.",
|
| 37 |
+
"disabled": "Video feedback was disabled for this analysis.",
|
| 38 |
+
}
|
| 39 |
DRILLS = {
|
| 40 |
"load_timing": {"hit_04", "hit_06"},
|
| 41 |
"hip_shoulder_separation": {"hit_13", "hit_14"},
|
|
|
|
| 95 |
|
| 96 |
def unavailable(reason: str) -> dict:
|
| 97 |
return {"status": "unavailable", "reason_code": reason, "source": "poc_video_review",
|
| 98 |
+
"message": FAILURE_MESSAGES.get(reason, FAILURE_MESSAGES["provider_failed"]),
|
| 99 |
"accuracy_validated": False, "judgment_eligible": False,
|
| 100 |
"features": [], "priority": None, "drill": None}
|
| 101 |
|
| 102 |
|
| 103 |
+
def provider_failure(error: Exception) -> dict:
|
| 104 |
+
"""Report allowlisted error categories, never provider messages or credentials."""
|
| 105 |
+
import httpx
|
| 106 |
+
from google.genai.errors import APIError
|
| 107 |
+
try:
|
| 108 |
+
import httpx2
|
| 109 |
+
timeouts = (TimeoutError, httpx.TimeoutException, httpx2.TimeoutException)
|
| 110 |
+
except ImportError:
|
| 111 |
+
timeouts = (TimeoutError, httpx.TimeoutException)
|
| 112 |
+
if isinstance(error, timeouts):
|
| 113 |
+
return {**unavailable("provider_timeout"), "retryable": True}
|
| 114 |
+
if not isinstance(error, APIError):
|
| 115 |
+
return {**unavailable("provider_client_error" if isinstance(error, (ValueError, TypeError)) else "provider_failed"),
|
| 116 |
+
"retryable": False}
|
| 117 |
+
code = error.code
|
| 118 |
+
reason = {400: "provider_request_rejected", 401: "provider_auth_failed",
|
| 119 |
+
403: "provider_access_denied", 404: "provider_model_unavailable",
|
| 120 |
+
429: "provider_rate_limited"}.get(code, "provider_unavailable" if code >= 500 else "provider_failed")
|
| 121 |
+
details = error.details if isinstance(error.details, dict) else {}
|
| 122 |
+
details = details.get("error", details)
|
| 123 |
+
quota_metrics = []
|
| 124 |
+
for detail in details.get("details", []) if isinstance(details, dict) else []:
|
| 125 |
+
if not isinstance(detail, dict):
|
| 126 |
+
continue
|
| 127 |
+
if detail.get("reason") in {"API_KEY_INVALID", "API_KEY_EXPIRED"}:
|
| 128 |
+
reason = "provider_auth_failed"
|
| 129 |
+
for violation in detail.get("violations", []) if isinstance(detail.get("violations"), list) else []:
|
| 130 |
+
metric = violation.get("quotaMetric") if isinstance(violation, dict) else None
|
| 131 |
+
if isinstance(metric, str) and re.fullmatch(r"generativelanguage\.googleapis\.com/[a-z_]{1,100}", metric):
|
| 132 |
+
quota_metrics.append(metric)
|
| 133 |
+
result = {**unavailable(reason), "provider_http_status": code, "retryable": code == 429 or code >= 500}
|
| 134 |
+
message = error.message if isinstance(error.message, str) else ""
|
| 135 |
+
if code == 400:
|
| 136 |
+
for component in ("response_schema", "response_json_schema", "thinking", "max_output_tokens", "response_mime_type"):
|
| 137 |
+
if component in message:
|
| 138 |
+
result["request_component"] = component
|
| 139 |
+
break
|
| 140 |
+
if quota_metrics:
|
| 141 |
+
result["quota_metrics"] = sorted(set(quota_metrics))
|
| 142 |
+
return result
|
| 143 |
+
|
| 144 |
+
|
| 145 |
def validate_note(note: VisualNote, frames: list[dict]) -> None:
|
| 146 |
by_id = {f["frame"]: f for f in frames}
|
| 147 |
for feature in note.features:
|
|
|
|
| 243 |
"notice": "Experimental video observations and a practice suggestion; accuracy has not been validated.",
|
| 244 |
**note.model_dump(mode="json"), "drill": drill,
|
| 245 |
"latency_ms": int((time.monotonic()-started)*1000)}
|
| 246 |
+
except Exception as error:
|
| 247 |
# Provider errors can include credentials and uploaded content. Public
|
| 248 |
# responses carry a fixed code, never provider text or a traceback.
|
| 249 |
+
if outcome == "provider_failed":
|
| 250 |
+
result = provider_failure(error)
|
| 251 |
+
outcome = result["reason_code"]
|
| 252 |
+
return result
|
| 253 |
return unavailable(outcome)
|
| 254 |
finally:
|
| 255 |
usage.cost_usd = compute_cost(settings.video_review_model, usage, settings.prices)
|
baseball_batting/api.py
CHANGED
|
@@ -6,6 +6,7 @@ import json
|
|
| 6 |
import os
|
| 7 |
from pathlib import Path
|
| 8 |
import shutil
|
|
|
|
| 9 |
from typing import Annotated
|
| 10 |
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile, Request
|
| 11 |
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
|
|
@@ -67,6 +68,7 @@ class UploadGuard:
|
|
| 67 |
def create_app(settings=None, service=None):
|
| 68 |
settings = settings or ApiSettings.from_env()
|
| 69 |
service = service or JobService(settings)
|
|
|
|
| 70 |
@asynccontextmanager
|
| 71 |
async def lifespan(app):
|
| 72 |
service.start()
|
|
@@ -296,6 +298,38 @@ def create_app(settings=None, service=None):
|
|
| 296 |
_, payload = stored_product(job_id)
|
| 297 |
return JSONResponse(payload['coaching'], headers={'Cache-Control': 'no-store'})
|
| 298 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
@app.get('/v1/analyses/{job_id}/frames/{frame_id}', dependencies=[Depends(authenticated)])
|
| 300 |
def get_frame(job_id: str, frame_id: int):
|
| 301 |
with service.mutation_lock:
|
|
|
|
| 6 |
import os
|
| 7 |
from pathlib import Path
|
| 8 |
import shutil
|
| 9 |
+
import threading
|
| 10 |
from typing import Annotated
|
| 11 |
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile, Request
|
| 12 |
from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse
|
|
|
|
| 68 |
def create_app(settings=None, service=None):
|
| 69 |
settings = settings or ApiSettings.from_env()
|
| 70 |
service = service or JobService(settings)
|
| 71 |
+
review_lock = threading.Lock()
|
| 72 |
@asynccontextmanager
|
| 73 |
async def lifespan(app):
|
| 74 |
service.start()
|
|
|
|
| 298 |
_, payload = stored_product(job_id)
|
| 299 |
return JSONResponse(payload['coaching'], headers={'Cache-Control': 'no-store'})
|
| 300 |
|
| 301 |
+
@app.post('/v1/analyses/{job_id}/video-review', dependencies=[Depends(authenticated)])
|
| 302 |
+
def retry_review(job_id: str):
|
| 303 |
+
if not review_lock.acquire(blocking=False):
|
| 304 |
+
raise HTTPException(429, 'A video review is already running; try again later', headers={'Retry-After': '30'})
|
| 305 |
+
try:
|
| 306 |
+
with service.mutation_lock:
|
| 307 |
+
directory, payload = stored_product(job_id)
|
| 308 |
+
if payload['visual_review']['status'] == 'completed':
|
| 309 |
+
return JSONResponse(payload, headers={'Cache-Control': 'no-store'})
|
| 310 |
+
if not payload['evidence']['frames']:
|
| 311 |
+
raise HTTPException(409, 'No retained video frames; upload again with video feedback enabled')
|
| 312 |
+
options = AnalysisInput.model_validate(read_json(directory/'request.json'))
|
| 313 |
+
previous_hash = service.store.get(job_id)['product_sha256']
|
| 314 |
+
from .product import retry_video_review
|
| 315 |
+
try:
|
| 316 |
+
updated = retry_video_review(directory, payload, options)
|
| 317 |
+
except ValueError:
|
| 318 |
+
raise HTTPException(500, 'Stored review frames failed their integrity check') from None
|
| 319 |
+
with service.mutation_lock:
|
| 320 |
+
_, current = stored_product(job_id)
|
| 321 |
+
if service.store.get(job_id)['product_sha256'] != previous_hash:
|
| 322 |
+
raise HTTPException(409, 'Product changed while review was running; reload its result')
|
| 323 |
+
atomic_json(directory/'product.json', updated)
|
| 324 |
+
try:
|
| 325 |
+
service.store.update_product(job_id, sha256_file(directory/'product.json'))
|
| 326 |
+
except Exception:
|
| 327 |
+
atomic_json(directory/'product.json', current)
|
| 328 |
+
raise HTTPException(500, 'Could not save video feedback; the previous result was kept') from None
|
| 329 |
+
return JSONResponse(updated, headers={'Cache-Control': 'no-store'})
|
| 330 |
+
finally:
|
| 331 |
+
review_lock.release()
|
| 332 |
+
|
| 333 |
@app.get('/v1/analyses/{job_id}/frames/{frame_id}', dependencies=[Depends(authenticated)])
|
| 334 |
def get_frame(job_id: str, frame_id: int):
|
| 335 |
with service.mutation_lock:
|
baseball_batting/api_jobs.py
CHANGED
|
@@ -120,6 +120,12 @@ class JobStore:
|
|
| 120 |
db.execute("UPDATE jobs SET status='running', updated=? WHERE id=?", (time.time(), row[0]))
|
| 121 |
return row[0]
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def cancel(self, identifier):
|
| 124 |
with self.connect() as db:
|
| 125 |
db.execute("BEGIN IMMEDIATE")
|
|
|
|
| 120 |
db.execute("UPDATE jobs SET status='running', updated=? WHERE id=?", (time.time(), row[0]))
|
| 121 |
return row[0]
|
| 122 |
|
| 123 |
+
def update_product(self, identifier, product_hash):
|
| 124 |
+
"""Preserve all measurement checksums when retrying optional video feedback."""
|
| 125 |
+
with self.connect() as db:
|
| 126 |
+
db.execute("UPDATE jobs SET updated=?, product_sha256=? WHERE id=? AND status='completed'",
|
| 127 |
+
(time.time(), product_hash, identifier))
|
| 128 |
+
|
| 129 |
def cancel(self, identifier):
|
| 130 |
with self.connect() as db:
|
| 131 |
db.execute("BEGIN IMMEDIATE")
|
baseball_batting/product.html
CHANGED
|
@@ -19,7 +19,7 @@
|
|
| 19 |
<details><summary>Open an existing analysis</summary><label for="jobId">Job ID</label><input id="jobId" maxlength="32" autocomplete="off"><button id="load" type="button">Open result</button><small>Use the job ID returned by an upload to reopen its result or follow its progress.</small></details>
|
| 20 |
</form>
|
| 21 |
<p id="state" role="status" aria-live="polite"></p><button id="cancel" hidden>Cancel analysis</button>
|
| 22 |
-
<section id="results" hidden><p class="warning">Measurements are estimates. Video feedback has not been validated for accuracy. A missing value means the evidence did not support it.</p><div class="grid" id="features"></div><div class="card" id="timing"></div><div class="card" id="advice"></div><details><summary>Sampled evidence frames</summary><div id="frames"></div></details><details><summary>Complete API result</summary><pre id="json"></pre></details><button id="download">Download JSON</button></section>
|
| 23 |
<script>
|
| 24 |
const $=id=>document.getElementById(id); let active=null, payload=null, busy=false, images=[];
|
| 25 |
async function api(path,options={}){const response=await fetch(path,{...options,headers:{...options.headers,Authorization:'Bearer '+$('key').value}});if(!response.ok){let detail;try{detail=(await response.json()).detail}catch{detail=response.statusText}throw Error(response.status+': '+(typeof detail==='string'?detail:JSON.stringify(detail)))}return response}
|
|
@@ -29,13 +29,14 @@ function show(product){payload=product;$('results').hidden=false;for(const id of
|
|
| 29 |
const fallback={load_timing:'Timing estimates are listed below. Ball-arrival timing needs visible bat and ball evidence.',hip_shoulder_separation:'A true separation angle cannot be measured from this face-on 2D analysis.',bat_path_contact:'Bat route and contact need clear bat and ball evidence.'};
|
| 30 |
for(const [key,name] of Object.entries(names)){const card=text('article','',$('features'));card.className='card';text('h2',name,card);const f=product.visual_review.features.find(x=>x.key===key);text('span',f?('Experimental · '+f.status):'Video review unavailable',card).className='tag';text('p',f?f.observation:fallback[key],card);if(f)text('small','Swing '+f.rep+' · frames '+f.evidence_frame_ids.join(', '),card)}
|
| 31 |
text('h2','Timing estimates',$('timing'));const t=product.coaching.timing;if(t){text('p',t.summary,$('timing'));for(const o of t.observations)text('p',o.text,$('timing'));for(const u of t.unavailable)text('p',u.label+': '+u.text,$('timing'))}else text('p','No supported timing values. Check the recording settings.',$('timing'));
|
| 32 |
-
text('h2','Practice suggestion',$('advice'));const v=product.visual_review;if(v.priority&&v.drill){text('p',v.priority.reason,$('advice'));text('h3',v.drill.name,$('advice'));text('p',v.drill.instructions,$('advice'));text('p','Cue: '+v.drill.cue,$('advice'));text('small','Experimental suggestion from visible movement; not a validated fault.',$('advice'))}else if(product.coaching.drill){text('p',product.coaching.summary,$('advice'));text('h3',product.coaching.drill.name,$('advice'));text('p',product.coaching.drill.how,$('advice'))}else{text('p','No supported practice priority from this recording.',$('advice'));if(v.status==='unavailable')text('
|
| 33 |
-
$('json').textContent=JSON.stringify(product,null,2);text('p','Only sampled frames were reviewed.',$('frames'));for(const f of product.evidence.frames){const b=text('button','Show frame '+f.frame,$('frames'));b.style.width='auto';b.onclick=async()=>{b.disabled=true;try{const blob=await(await api(f.url)).blob();const url=URL.createObjectURL(blob);images.push(url);const image=document.createElement('img');image.src=url;image.alt='Swing evidence frame '+f.frame;b.replaceWith(image)}catch(e){b.disabled=false;$('state').textContent=e.message}}}}
|
| 34 |
async function watch(url){active=url;$('cancel').hidden=false;while(active){const s=await(await api(active)).json();$('state').textContent=s.status+' · job '+s.job_id+(s.progress?' · '+s.progress.stage+(s.progress.total_frames?' · '+s.progress.completed_frames+'/'+s.progress.total_frames+' frames':''):'');if(s.status==='completed'){if(!s.product_url)throw Error('This analysis has measurements only. Upload again with coaching enabled.');show(await(await api(s.product_url)).json());break}if(['failed','cancelled'].includes(s.status))throw Error(s.error||s.status);await new Promise(r=>setTimeout(r,2000))}}
|
| 35 |
function reset(){active=null;busy=false;$('cancel').hidden=true;$('run').disabled=false;$('load').disabled=false}
|
| 36 |
$('upload').onsubmit=async e=>{e.preventDefault();if(busy)return;busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;$('state').textContent='Uploading…';const options={coaching_mode:$('visual').checked?'poc_video':'measurements_only',view:$('face').checked?'face_on':'unknown',handedness:$('hand').value||null,pitcher_direction:$('direction').value||null,practice_type:$('practice').value,camera_stability:$('fixed').checked?'fixed_verified':'unknown',single_swing:$('single').checked,timing:$('original').checked?{kind:'unretimed',source:'Uploader confirms original recording; no speed changes'}:{kind:'unknown'}};const form=new FormData;form.append('video',$('video').files[0]);form.append('options',JSON.stringify(options));try{const job=await(await api('/v1/swing-coach/analyses',{method:'POST',body:form})).json();$('jobId').value=job.job_id;await watch(job.status_url)}catch(e){$('state').textContent=e.message}finally{reset()}};
|
| 37 |
$('load').onclick=async()=>{if(busy)return;const id=$('jobId').value.trim();if(!/^[a-f0-9]{32}$/.test(id)){$('state').textContent='Enter a valid job ID.';return}busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;try{await watch('/v1/analyses/'+id)}catch(e){$('state').textContent=e.message}finally{reset()}};
|
| 38 |
$('cancel').onclick=async()=>{if(active)try{await api(active,{method:'DELETE'});active=null;$('state').textContent='Cancelled'}catch(e){$('state').textContent=e.message}};
|
|
|
|
| 39 |
$('download').onclick=()=>{if(!payload)return;const u=URL.createObjectURL(new Blob([JSON.stringify(payload,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=u;a.download='swing-product.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)};
|
| 40 |
</script>
|
| 41 |
</html>
|
|
|
|
| 19 |
<details><summary>Open an existing analysis</summary><label for="jobId">Job ID</label><input id="jobId" maxlength="32" autocomplete="off"><button id="load" type="button">Open result</button><small>Use the job ID returned by an upload to reopen its result or follow its progress.</small></details>
|
| 20 |
</form>
|
| 21 |
<p id="state" role="status" aria-live="polite"></p><button id="cancel" hidden>Cancel analysis</button>
|
| 22 |
+
<section id="results" hidden><p class="warning">Measurements are estimates. Video feedback has not been validated for accuracy. A missing value means the evidence did not support it.</p><div class="grid" id="features"></div><div class="card" id="timing"></div><div class="card" id="advice"></div><details><summary>Sampled evidence frames</summary><div id="frames"></div></details><details><summary>Complete API result</summary><pre id="json"></pre></details><button id="retry" hidden>Retry video feedback only</button><button id="download">Download JSON</button></section>
|
| 23 |
<script>
|
| 24 |
const $=id=>document.getElementById(id); let active=null, payload=null, busy=false, images=[];
|
| 25 |
async function api(path,options={}){const response=await fetch(path,{...options,headers:{...options.headers,Authorization:'Bearer '+$('key').value}});if(!response.ok){let detail;try{detail=(await response.json()).detail}catch{detail=response.statusText}throw Error(response.status+': '+(typeof detail==='string'?detail:JSON.stringify(detail)))}return response}
|
|
|
|
| 29 |
const fallback={load_timing:'Timing estimates are listed below. Ball-arrival timing needs visible bat and ball evidence.',hip_shoulder_separation:'A true separation angle cannot be measured from this face-on 2D analysis.',bat_path_contact:'Bat route and contact need clear bat and ball evidence.'};
|
| 30 |
for(const [key,name] of Object.entries(names)){const card=text('article','',$('features'));card.className='card';text('h2',name,card);const f=product.visual_review.features.find(x=>x.key===key);text('span',f?('Experimental · '+f.status):'Video review unavailable',card).className='tag';text('p',f?f.observation:fallback[key],card);if(f)text('small','Swing '+f.rep+' · frames '+f.evidence_frame_ids.join(', '),card)}
|
| 31 |
text('h2','Timing estimates',$('timing'));const t=product.coaching.timing;if(t){text('p',t.summary,$('timing'));for(const o of t.observations)text('p',o.text,$('timing'));for(const u of t.unavailable)text('p',u.label+': '+u.text,$('timing'))}else text('p','No supported timing values. Check the recording settings.',$('timing'));
|
| 32 |
+
text('h2','Practice suggestion',$('advice'));const v=product.visual_review;if(v.priority&&v.drill){text('p',v.priority.reason,$('advice'));text('h3',v.drill.name,$('advice'));text('p',v.drill.instructions,$('advice'));text('p','Cue: '+v.drill.cue,$('advice'));text('small','Experimental suggestion from visible movement; not a validated fault.',$('advice'))}else if(product.coaching.drill){text('p',product.coaching.summary,$('advice'));text('h3',product.coaching.drill.name,$('advice'));text('p',product.coaching.drill.how,$('advice'))}else{text('p','No supported practice priority from this recording.',$('advice'));if(v.status==='unavailable')text('p',v.message||('Video review: '+v.reason_code),$('advice'))}
|
| 33 |
+
$('retry').hidden=product.visual_review.status!=='unavailable'||!product.evidence.frames.length; $('json').textContent=JSON.stringify(product,null,2);text('p','Only sampled frames were reviewed.',$('frames'));for(const f of product.evidence.frames){const b=text('button','Show frame '+f.frame,$('frames'));b.style.width='auto';b.onclick=async()=>{b.disabled=true;try{const blob=await(await api(f.url)).blob();const url=URL.createObjectURL(blob);images.push(url);const image=document.createElement('img');image.src=url;image.alt='Swing evidence frame '+f.frame;b.replaceWith(image)}catch(e){b.disabled=false;$('state').textContent=e.message}}}}
|
| 34 |
async function watch(url){active=url;$('cancel').hidden=false;while(active){const s=await(await api(active)).json();$('state').textContent=s.status+' · job '+s.job_id+(s.progress?' · '+s.progress.stage+(s.progress.total_frames?' · '+s.progress.completed_frames+'/'+s.progress.total_frames+' frames':''):'');if(s.status==='completed'){if(!s.product_url)throw Error('This analysis has measurements only. Upload again with coaching enabled.');show(await(await api(s.product_url)).json());break}if(['failed','cancelled'].includes(s.status))throw Error(s.error||s.status);await new Promise(r=>setTimeout(r,2000))}}
|
| 35 |
function reset(){active=null;busy=false;$('cancel').hidden=true;$('run').disabled=false;$('load').disabled=false}
|
| 36 |
$('upload').onsubmit=async e=>{e.preventDefault();if(busy)return;busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;$('state').textContent='Uploading…';const options={coaching_mode:$('visual').checked?'poc_video':'measurements_only',view:$('face').checked?'face_on':'unknown',handedness:$('hand').value||null,pitcher_direction:$('direction').value||null,practice_type:$('practice').value,camera_stability:$('fixed').checked?'fixed_verified':'unknown',single_swing:$('single').checked,timing:$('original').checked?{kind:'unretimed',source:'Uploader confirms original recording; no speed changes'}:{kind:'unknown'}};const form=new FormData;form.append('video',$('video').files[0]);form.append('options',JSON.stringify(options));try{const job=await(await api('/v1/swing-coach/analyses',{method:'POST',body:form})).json();$('jobId').value=job.job_id;await watch(job.status_url)}catch(e){$('state').textContent=e.message}finally{reset()}};
|
| 37 |
$('load').onclick=async()=>{if(busy)return;const id=$('jobId').value.trim();if(!/^[a-f0-9]{32}$/.test(id)){$('state').textContent='Enter a valid job ID.';return}busy=true;$('run').disabled=true;$('load').disabled=true;$('results').hidden=true;try{await watch('/v1/analyses/'+id)}catch(e){$('state').textContent=e.message}finally{reset()}};
|
| 38 |
$('cancel').onclick=async()=>{if(active)try{await api(active,{method:'DELETE'});active=null;$('state').textContent='Cancelled'}catch(e){$('state').textContent=e.message}};
|
| 39 |
+
$('retry').onclick=async()=>{if(busy||!payload)return;busy=true;$('retry').disabled=true;$('run').disabled=true;$('load').disabled=true;$('state').textContent='Retrying video feedback… Measurements will be kept.';try{const updated=await(await api('/v1/analyses/'+payload.session_id+'/video-review',{method:'POST'})).json();show(updated);$('state').textContent=updated.visual_review.status==='completed'?'Video feedback completed':updated.visual_review.message||updated.visual_review.reason_code}catch(e){$('state').textContent=e.message}finally{$('retry').disabled=false;reset()}};
|
| 40 |
$('download').onclick=()=>{if(!payload)return;const u=URL.createObjectURL(new Blob([JSON.stringify(payload,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=u;a.download='swing-product.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)};
|
| 41 |
</script>
|
| 42 |
</html>
|
baseball_batting/product.py
CHANGED
|
@@ -153,3 +153,25 @@ def build_product(job, video, result, timing, options, *, service=None, generato
|
|
| 153 |
"notice": "Review covers sampled frames only. Estimated swing boundaries and events may be wrong."}}
|
| 154 |
atomic_json(job/"product.json", product)
|
| 155 |
return product
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
"notice": "Review covers sampled frames only. Estimated swing boundaries and events may be wrong."}}
|
| 154 |
atomic_json(job/"product.json", product)
|
| 155 |
return product
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def retry_video_review(job, product, options):
|
| 159 |
+
"""Retry only the retained original images; no pose inference or original upload."""
|
| 160 |
+
from ai_coach.config import Settings
|
| 161 |
+
from ai_coach.cost import UsageLedger
|
| 162 |
+
from ai_coach.video_review import review_video
|
| 163 |
+
job = Path(job)
|
| 164 |
+
settings = Settings(cache_path=job.parents[1]/"coach-cache/responses.sqlite3",
|
| 165 |
+
log_dir=job.parents[1]/"coach-cache/logs")
|
| 166 |
+
frames = []
|
| 167 |
+
for frame in product["evidence"]["frames"]:
|
| 168 |
+
path = job/"review-frames"/f"{frame['frame']}.jpg"
|
| 169 |
+
if not path.is_file() or sha256_file(path) != frame["sha256"]:
|
| 170 |
+
raise ValueError("Stored frame failed its integrity check")
|
| 171 |
+
frames.append({**frame, "jpeg": path.read_bytes()})
|
| 172 |
+
facts = {k: getattr(options, k) for k in ("handedness", "pitcher_direction", "view", "practice_type", "camera_stability")}
|
| 173 |
+
facts["capture_clock_known"] = options.timing.kind != "unknown"
|
| 174 |
+
ledger = UsageLedger(settings.resolved_ledger_path, settings.daily_budget_usd)
|
| 175 |
+
updated = copy.deepcopy(product)
|
| 176 |
+
updated["visual_review"] = review_video(frames, facts, settings, ledger=ledger)
|
| 177 |
+
return updated
|
docs/SWING_COACH_PRODUCT.md
CHANGED
|
@@ -51,6 +51,11 @@ Use Bearer authorization with the **engine** API key for these endpoints:
|
|
| 51 |
`response_version: "2.0"` coaching response.
|
| 52 |
5. `GET /v1/analyses/{job_id}/frames/{frame}`: authenticated evidence JPEGs.
|
| 53 |
6. `DELETE /v1/analyses/{job_id}`: cancel and delete results and evidence.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
Recording options example; replace the values to match the recording:
|
| 56 |
|
|
@@ -125,6 +130,14 @@ explicit `visual_review.status: unavailable` with a reason code, while engine
|
|
| 125 |
measurements and the coach's descriptive response still return. No sample
|
| 126 |
feedback is substituted for an unavailable live result.
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
Results and evidence follow the engine retention period (default 24 hours), are
|
| 129 |
checksum verified on retrieval, and require authentication. Original uploads
|
| 130 |
are removed after jobs finish; sampled evidence is retained until deletion or
|
|
|
|
| 51 |
`response_version: "2.0"` coaching response.
|
| 52 |
5. `GET /v1/analyses/{job_id}/frames/{frame}`: authenticated evidence JPEGs.
|
| 53 |
6. `DELETE /v1/analyses/{job_id}`: cancel and delete results and evidence.
|
| 54 |
+
7. `POST /v1/analyses/{job_id}/video-review`: retry unavailable video feedback
|
| 55 |
+
using retained, checksum-verified original images. It preserves measurements
|
| 56 |
+
and returns the updated product. A completed review is returned without a
|
| 57 |
+
further model call; only one retry runs at a time. No retained images means
|
| 58 |
+
a new upload is required. The upload screen provides this retry button.
|
| 59 |
|
| 60 |
Recording options example; replace the values to match the recording:
|
| 61 |
|
|
|
|
| 130 |
measurements and the coach's descriptive response still return. No sample
|
| 131 |
feedback is substituted for an unavailable live result.
|
| 132 |
|
| 133 |
+
Provider failures report fixed human-readable messages and safe categories such
|
| 134 |
+
as `provider_timeout`, `provider_rate_limited`, `provider_auth_failed`,
|
| 135 |
+
`provider_request_rejected` or `provider_unavailable`. When Google returns an
|
| 136 |
+
HTTP error, `provider_http_status` is included. Quota metric names may be included;
|
| 137 |
+
provider messages, credentials, project identifiers and uploaded content are
|
| 138 |
+
never forwarded in error diagnostics. Model metadata availability alone does
|
| 139 |
+
not establish generation quota or that a video-review call will succeed.
|
| 140 |
+
|
| 141 |
Results and evidence follow the engine retention period (default 24 hours), are
|
| 142 |
checksum verified on retrieval, and require authentication. Original uploads
|
| 143 |
are removed after jobs finish; sampled evidence is retained until deletion or
|
tests/test_product.py
CHANGED
|
@@ -266,3 +266,129 @@ def test_product_upload_default_and_legacy_opt_in(video,tmp_path):
|
|
| 266 |
assert old.json()['product_url'] is None
|
| 267 |
assert json.loads((service.job_directory(old.json()['job_id'])/'request.json').read_text())['coaching_mode']=='disabled'
|
| 268 |
for response in (r,old):client.delete(response.json()['status_url'],headers=AUTH)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
assert old.json()['product_url'] is None
|
| 267 |
assert json.loads((service.job_directory(old.json()['job_id'])/'request.json').read_text())['coaching_mode']=='disabled'
|
| 268 |
for response in (r,old):client.delete(response.json()['status_url'],headers=AUTH)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@pytest.mark.parametrize('code,reason',[(400,'provider_request_rejected'),(401,'provider_auth_failed'),
|
| 272 |
+
(403,'provider_access_denied'),(404,'provider_model_unavailable'),(429,'provider_rate_limited'),(503,'provider_unavailable')])
|
| 273 |
+
def test_google_failures_have_safe_actionable_reasons(tmp_path,code,reason):
|
| 274 |
+
from google.genai.errors import APIError
|
| 275 |
+
def broken(*args):
|
| 276 |
+
raise APIError(code,{'error':{'message':'private-key-and-user-image','details':[
|
| 277 |
+
{'violations':[{'quotaMetric':'generativelanguage.googleapis.com/generate_content_free_tier_requests'},
|
| 278 |
+
{'quotaMetric':'private-project-id'}]}]}})
|
| 279 |
+
result=review_video(frames(),{},coach_settings(tmp_path),generator=broken)
|
| 280 |
+
assert result['reason_code']==reason and result['provider_http_status']==code
|
| 281 |
+
assert 'private' not in json.dumps(result)
|
| 282 |
+
assert result['message'] and result['quota_metrics']==['generativelanguage.googleapis.com/generate_content_free_tier_requests']
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_google_timeout_and_invalid_key_are_distinguished(tmp_path):
|
| 286 |
+
import httpx
|
| 287 |
+
from google.genai.errors import APIError
|
| 288 |
+
def timeout(*args):raise httpx.ReadTimeout('secret-key')
|
| 289 |
+
result=review_video(frames(),{},coach_settings(tmp_path),generator=timeout)
|
| 290 |
+
assert result['reason_code']=='provider_timeout' and result['retryable']
|
| 291 |
+
def bad_key(*args):raise APIError(400,{'error':{'message':'private','details':[{'reason':'API_KEY_INVALID'}]}})
|
| 292 |
+
assert review_video(frames(),{},coach_settings(tmp_path),generator=bad_key)['reason_code']=='provider_auth_failed'
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def retained_review_job(tmp_path):
|
| 296 |
+
service=fake_service(settings(tmp_path))
|
| 297 |
+
identifier=service.store.create(8);job=service.job_directory(identifier);job.mkdir()
|
| 298 |
+
(job/'review-frames').mkdir();(job/'review-frames/0.jpg').write_bytes(b'original-image')
|
| 299 |
+
atomic_json(job/'request.json',AnalysisInput(coaching_mode='poc_video').model_dump(mode='json'))
|
| 300 |
+
product={'session_id':identifier,'coaching':{'response_version':'2.0'},
|
| 301 |
+
'visual_review':{'status':'unavailable','reason_code':'provider_failed'},
|
| 302 |
+
'evidence':{'frames':[{'frame':0,'reps':[1],'sha256':sha256_file(job/'review-frames/0.jpg')}]}}
|
| 303 |
+
atomic_json(job/'product.json',product)
|
| 304 |
+
service.store.update(identifier,'completed',result_hash='original-result-hash',coach_hash='original-coach-hash',
|
| 305 |
+
timing_hash='original-timing-hash',evidence_hash='original-evidence-hash',product_hash=sha256_file(job/'product.json'))
|
| 306 |
+
return service,identifier,job,product
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def test_retry_review_preserves_measurements_auth_and_checksums(tmp_path,monkeypatch):
|
| 310 |
+
from fastapi.testclient import TestClient
|
| 311 |
+
from baseball_batting.api import create_app
|
| 312 |
+
from baseball_batting.product import retry_video_review
|
| 313 |
+
import ai_coach.video_review as review
|
| 314 |
+
service,identifier,job,product=retained_review_job(tmp_path)
|
| 315 |
+
calls=[]
|
| 316 |
+
def fake_review(frames,facts,*args,**kwargs):
|
| 317 |
+
calls.append(frames)
|
| 318 |
+
assert frames[0]['jpeg']==b'original-image'
|
| 319 |
+
return {'status':'completed','features':[]}
|
| 320 |
+
monkeypatch.setattr(review,'review_video',fake_review)
|
| 321 |
+
# Exercise the actual retained-frame loader, not a replacement retry handler.
|
| 322 |
+
assert retry_video_review(job,product,AnalysisInput())['visual_review']['status']=='completed'
|
| 323 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 324 |
+
wait_until(lambda:service.ready)
|
| 325 |
+
url=f'/v1/analyses/{identifier}/video-review'
|
| 326 |
+
assert client.post(url).status_code==401
|
| 327 |
+
r=client.post(url,headers=AUTH)
|
| 328 |
+
assert r.status_code==200 and r.json()['coaching']==product['coaching']
|
| 329 |
+
saved=service.store.get(identifier)
|
| 330 |
+
assert saved['result_sha256']=='original-result-hash'
|
| 331 |
+
assert saved['coach_payload_sha256']=='original-coach-hash'
|
| 332 |
+
assert saved['load_timing_sha256']=='original-timing-hash'
|
| 333 |
+
assert saved['timing_evidence_sha256']=='original-evidence-hash'
|
| 334 |
+
assert saved['product_sha256']==sha256_file(job/'product.json')
|
| 335 |
+
assert client.post(url,headers=AUTH).status_code==200
|
| 336 |
+
assert len(calls)==2 # Completed retries are idempotent; no extra billed call.
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def test_retry_never_resurrects_deleted_job_or_accepts_bad_frames(tmp_path,monkeypatch):
|
| 340 |
+
from fastapi.testclient import TestClient
|
| 341 |
+
from baseball_batting.api import create_app
|
| 342 |
+
import ai_coach.video_review as review
|
| 343 |
+
service,identifier,job,product=retained_review_job(tmp_path)
|
| 344 |
+
def cancelled(*args,**kw):
|
| 345 |
+
service.delete(identifier)
|
| 346 |
+
return {'status':'completed','features':[]}
|
| 347 |
+
monkeypatch.setattr(review,'review_video',cancelled)
|
| 348 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 349 |
+
wait_until(lambda:service.ready)
|
| 350 |
+
(job/'review-frames/0.jpg').write_bytes(b'tampered')
|
| 351 |
+
url=f'/v1/analyses/{identifier}/video-review'
|
| 352 |
+
assert client.post(url,headers=AUTH).status_code==500
|
| 353 |
+
assert service.store.get(identifier)['status']=='completed'
|
| 354 |
+
(job/'review-frames/0.jpg').write_bytes(b'original-image')
|
| 355 |
+
assert client.post(url,headers=AUTH).status_code==409
|
| 356 |
+
assert not job.exists() and service.store.get(identifier)['status']=='cancelled'
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def test_retry_storage_failure_keeps_the_previous_product(tmp_path,monkeypatch):
|
| 360 |
+
from fastapi.testclient import TestClient
|
| 361 |
+
from baseball_batting.api import create_app
|
| 362 |
+
import ai_coach.video_review as review
|
| 363 |
+
service,identifier,job,product=retained_review_job(tmp_path)
|
| 364 |
+
monkeypatch.setattr(review,'review_video',lambda *a,**k:{'status':'completed','features':[]})
|
| 365 |
+
def broken(*args):raise OSError('database unavailable')
|
| 366 |
+
monkeypatch.setattr(service.store,'update_product',broken)
|
| 367 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 368 |
+
wait_until(lambda:service.ready)
|
| 369 |
+
url=f'/v1/analyses/{identifier}'
|
| 370 |
+
assert client.post(url+'/video-review',headers=AUTH).status_code==500
|
| 371 |
+
assert client.get(url+'/product',headers=AUTH).json()==product
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_real_google_sdk_serializes_our_schema_and_decodes_response(tmp_path,monkeypatch):
|
| 375 |
+
from google import genai
|
| 376 |
+
from google.genai import types
|
| 377 |
+
from pydantic import SecretStr
|
| 378 |
+
from ai_coach.video_review import gemini_generate
|
| 379 |
+
sdk_client=genai.Client
|
| 380 |
+
requests=[]
|
| 381 |
+
def make_client(**kw):
|
| 382 |
+
client=sdk_client(**kw)
|
| 383 |
+
def transport(method,path,body,*args):
|
| 384 |
+
requests.append(body)
|
| 385 |
+
return types.HttpResponse(body=json.dumps({'candidates':[{'content':{'parts':[{'text':json.dumps(note())}]},
|
| 386 |
+
'finishReason':'STOP'}], 'usageMetadata':{'promptTokenCount':50,'candidatesTokenCount':20}}))
|
| 387 |
+
client._api_client.request=transport
|
| 388 |
+
return client
|
| 389 |
+
monkeypatch.setattr(genai,'Client',make_client)
|
| 390 |
+
configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key')})
|
| 391 |
+
raw,usage=gemini_generate(configured,frames(),{})
|
| 392 |
+
assert json.loads(raw)['features'][0]['key']=='load_timing'
|
| 393 |
+
assert usage.input_tokens==50 and usage.output_tokens==20
|
| 394 |
+
assert requests[0]['generationConfig']['responseSchema']['properties']['features']['min_items']==3
|