github-actions[bot] commited on
Commit
4800905
·
1 Parent(s): 40fe6bf

Automated Deploy: 906afeaa3692cf6c932cc26af26234c5c86d9e08

Browse files
baseball_batting/api.py CHANGED
@@ -19,6 +19,8 @@ from .api_jobs import ApiSettings, JobService, QueueFull
19
  from .load_timing_contract import LoadTimingPayload
20
  from .timing_evidence import TimingEvidencePayload
21
  from .storage import atomic_json, read_json, sha256_file
 
 
22
 
23
  ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
24
  BEARER = HTTPBearer(auto_error=False)
@@ -74,7 +76,7 @@ def create_app(settings=None, service=None):
74
  service.start()
75
  try: yield
76
  finally: service.stop()
77
- app = FastAPI(title="Baseball Swing Engine and Coach", version="1.5.0", lifespan=lifespan,
78
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
79
  app.state.service = service
80
  app.add_middleware(UploadGuard, settings=settings, service=service)
@@ -99,7 +101,7 @@ def create_app(settings=None, service=None):
99
  def home():
100
  return HTMLResponse(Path(__file__).with_name("product.html").read_text(), headers={
101
  "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
102
- "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"})
103
 
104
  @app.get("/healthz")
105
  def health():
@@ -132,6 +134,9 @@ def create_app(settings=None, service=None):
132
  "body_3d_scope": "experimental sparse contact/foot-plant windows; actual CUDA checked during inference",
133
  "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
134
  "automatic_events": True, "swing_metrics": True, "estimated_only": True,
 
 
 
135
  "measurement_validation": "reference_validation_pending", "coaching": coaching_available(),
136
  "swing_coach": {"upload_route": "/v1/swing-coach/analyses",
137
  "product_route": "/v1/analyses/{job_id}/product",
@@ -160,6 +165,10 @@ def create_app(settings=None, service=None):
160
  def coach_schema():
161
  return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json")
162
 
 
 
 
 
163
  @app.get("/v1/load-timing-schema", dependencies=[Depends(authenticated)])
164
  def timing_schema(include_evidence: bool = False):
165
  if include_evidence:
@@ -248,6 +257,7 @@ def create_app(settings=None, service=None):
248
  "load_timing_url": f"/v1/analyses/{identifier}/load-timing",
249
  'load_timing_evidence_url': f'/v1/analyses/{identifier}/load-timing?include_evidence=true',
250
  'product_url': f'/v1/analyses/{identifier}/product' if parsed.coaching_mode != 'disabled' else None,
 
251
  'coaching_url': f'/v1/analyses/{identifier}/coaching' if parsed.coaching_mode != 'disabled' else None,
252
  'warnings': ([{'code': 'timing_settings_missing', 'fields': missing,
253
  'message': 'Timing measurements may be unavailable. Supply recording facts in options.'}] if missing else []) +
@@ -275,6 +285,7 @@ def create_app(settings=None, service=None):
275
  'load_timing_evidence_url': f'/v1/analyses/{job_id}/load-timing?include_evidence=true' if record['status'] == 'completed' and record.get('timing_evidence_sha256') else None,
276
  "coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None,
277
  "product_url": f"/v1/analyses/{job_id}/product" if record["status"] == "completed" and record.get("product_sha256") else None,
 
278
  "coaching_url": f"/v1/analyses/{job_id}/coaching" if record["status"] == "completed" and record.get("product_sha256") else None}
279
 
280
  def stored_product(job_id):
@@ -342,6 +353,45 @@ def create_app(settings=None, service=None):
342
  return Response(path.read_bytes(), media_type='image/jpeg', headers={
343
  'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  @app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)])
346
  def get_coach_payload(job_id: str):
347
  with service.mutation_lock:
 
19
  from .load_timing_contract import LoadTimingPayload
20
  from .timing_evidence import TimingEvidencePayload
21
  from .storage import atomic_json, read_json, sha256_file
22
+ from .swing_clips import SwingsManifest
23
+ from .media import open_verified_media, media_response
24
 
25
  ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
26
  BEARER = HTTPBearer(auto_error=False)
 
76
  service.start()
77
  try: yield
78
  finally: service.stop()
79
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.6.0", lifespan=lifespan,
80
  description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
81
  app.state.service = service
82
  app.add_middleware(UploadGuard, settings=settings, service=service)
 
101
  def home():
102
  return HTMLResponse(Path(__file__).with_name("product.html").read_text(), headers={
103
  "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
104
+ "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' blob:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"})
105
 
106
  @app.get("/healthz")
107
  def health():
 
134
  "body_3d_scope": "experimental sparse contact/foot-plant windows; actual CUDA checked during inference",
135
  "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
136
  "automatic_events": True, "swing_metrics": True, "estimated_only": True,
137
+ "swing_clips": {"configured": True, "route": "/v1/analyses/{job_id}/swings",
138
+ "content_type": "video/mp4", "codec": "h264", "audio": False,
139
+ "max_dimension": 1280, "time_basis": "playback", "byte_ranges": True},
140
  "measurement_validation": "reference_validation_pending", "coaching": coaching_available(),
141
  "swing_coach": {"upload_route": "/v1/swing-coach/analyses",
142
  "product_route": "/v1/analyses/{job_id}/product",
 
165
  def coach_schema():
166
  return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json")
167
 
168
+ @app.get("/v1/swings-schema", dependencies=[Depends(authenticated)])
169
+ def swings_schema():
170
+ return SwingsManifest.model_json_schema()
171
+
172
  @app.get("/v1/load-timing-schema", dependencies=[Depends(authenticated)])
173
  def timing_schema(include_evidence: bool = False):
174
  if include_evidence:
 
257
  "load_timing_url": f"/v1/analyses/{identifier}/load-timing",
258
  'load_timing_evidence_url': f'/v1/analyses/{identifier}/load-timing?include_evidence=true',
259
  'product_url': f'/v1/analyses/{identifier}/product' if parsed.coaching_mode != 'disabled' else None,
260
+ 'swings_url': f'/v1/analyses/{identifier}/swings',
261
  'coaching_url': f'/v1/analyses/{identifier}/coaching' if parsed.coaching_mode != 'disabled' else None,
262
  'warnings': ([{'code': 'timing_settings_missing', 'fields': missing,
263
  'message': 'Timing measurements may be unavailable. Supply recording facts in options.'}] if missing else []) +
 
285
  'load_timing_evidence_url': f'/v1/analyses/{job_id}/load-timing?include_evidence=true' if record['status'] == 'completed' and record.get('timing_evidence_sha256') else None,
286
  "coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None,
287
  "product_url": f"/v1/analyses/{job_id}/product" if record["status"] == "completed" and record.get("product_sha256") else None,
288
+ "swings_url": f"/v1/analyses/{job_id}/swings" if record["status"] == "completed" and record.get("swings_sha256") else None,
289
  "coaching_url": f"/v1/analyses/{job_id}/coaching" if record["status"] == "completed" and record.get("product_sha256") else None}
290
 
291
  def stored_product(job_id):
 
353
  return Response(path.read_bytes(), media_type='image/jpeg', headers={
354
  'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
355
 
356
+ def stored_swings(job_id):
357
+ directory, record = job_record(job_id)
358
+ if record['status'] != 'completed':
359
+ raise HTTPException(409, 'Job has no completed result; check job status')
360
+ if not record.get('swings_sha256'):
361
+ raise HTTPException(409, 'This older job has no swing clips; submit the video again')
362
+ path = directory/'swings.json'
363
+ if not path.is_file() or sha256_file(path) != record['swings_sha256']:
364
+ raise HTTPException(500, 'Stored swing manifest failed its integrity check')
365
+ try:
366
+ payload = SwingsManifest.model_validate(read_json(path))
367
+ except (ValidationError, ValueError):
368
+ raise HTTPException(500, 'Stored swing manifest has invalid structure') from None
369
+ return directory, payload
370
+
371
+ @app.get('/v1/analyses/{job_id}/swings', response_model=SwingsManifest,
372
+ dependencies=[Depends(authenticated)], summary='List every detected swing and its playable clip')
373
+ def get_swings(job_id: str):
374
+ with service.mutation_lock:
375
+ _, payload = stored_swings(job_id)
376
+ return JSONResponse(payload.model_dump(mode='json'), headers={'Cache-Control': 'no-store'})
377
+
378
+ @app.get('/v1/analyses/{job_id}/swings/{rep}/clip', dependencies=[Depends(authenticated)],
379
+ response_class=StreamingResponse, responses={200: {'content': {'video/mp4': {}}},
380
+ 206: {'description': 'Requested byte range', 'content': {'video/mp4': {}}},
381
+ 416: {'description': 'Unsatisfiable byte range'}}, summary='Play or download a swing MP4')
382
+ @app.head('/v1/analyses/{job_id}/swings/{rep}/clip', dependencies=[Depends(authenticated)], include_in_schema=False)
383
+ def get_swing_clip(job_id: str, rep: int, request: Request):
384
+ with service.mutation_lock:
385
+ directory, payload = stored_swings(job_id)
386
+ swing = next((s for s in payload.swings if s.rep == rep), None)
387
+ if swing is None:
388
+ raise HTTPException(404, 'Swing not found')
389
+ if swing.clip.status != 'available':
390
+ raise HTTPException(409, {'code': swing.clip.reason_code, 'message': 'Swing clip is unavailable'})
391
+ handle, size = open_verified_media(directory/'swing-clips'/f'{rep}.mp4',
392
+ swing.clip.sha256, swing.clip.size_bytes)
393
+ return media_response(request, handle, size, swing.clip.sha256)
394
+
395
  @app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)])
396
  def get_coach_payload(job_id: str):
397
  with service.mutation_lock:
baseball_batting/api_jobs.py CHANGED
@@ -82,6 +82,8 @@ class JobStore:
82
  db.execute('ALTER TABLE jobs ADD COLUMN timing_evidence_sha256 TEXT')
83
  if 'product_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
84
  db.execute('ALTER TABLE jobs ADD COLUMN product_sha256 TEXT')
 
 
85
 
86
  @contextmanager
87
  def connect(self):
@@ -107,10 +109,10 @@ class JobStore:
107
  value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
108
  return dict(value) if value else None
109
 
110
- def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None, product_hash=None):
111
  with self.connect() as db:
112
- db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=?, product_sha256=? WHERE id=?",
113
- (status, time.time(), error, result_hash, coach_hash, timing_hash, evidence_hash, product_hash, identifier))
114
 
115
  def claim(self):
116
  with self.connect() as db:
@@ -132,7 +134,7 @@ class JobStore:
132
  row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
133
  if not row: return None
134
  status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
135
- db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL, product_sha256=NULL WHERE id=?",
136
  (status, time.time(), identifier))
137
  return status
138
 
@@ -327,7 +329,8 @@ class JobService:
327
  coach_hash=sha256_file(coach_path) if coach_path.is_file() else None,
328
  timing_hash=sha256_file(timing_path) if timing_path.is_file() else None,
329
  evidence_hash=sha256_file(directory/'load-timing-evidence.json') if (directory/'load-timing-evidence.json').is_file() else None,
330
- product_hash=sha256_file(directory/'product.json') if (directory/'product.json').is_file() else None)
 
331
  else:
332
  error = read_json(directory / "error.json") if (directory / "error.json").exists() else {}
333
  code = error.get("code")
 
82
  db.execute('ALTER TABLE jobs ADD COLUMN timing_evidence_sha256 TEXT')
83
  if 'product_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
84
  db.execute('ALTER TABLE jobs ADD COLUMN product_sha256 TEXT')
85
+ if 'swings_sha256' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
86
+ db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT')
87
 
88
  @contextmanager
89
  def connect(self):
 
109
  value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
110
  return dict(value) if value else None
111
 
112
+ def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None, product_hash=None, swings_hash=None):
113
  with self.connect() as db:
114
+ db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=?, product_sha256=?, swings_sha256=? WHERE id=?",
115
+ (status, time.time(), error, result_hash, coach_hash, timing_hash, evidence_hash, product_hash, swings_hash, identifier))
116
 
117
  def claim(self):
118
  with self.connect() as db:
 
134
  row = db.execute("SELECT status FROM jobs WHERE id=?", (identifier,)).fetchone()
135
  if not row: return None
136
  status = "cancel_requested" if row[0] in ("running", "cancel_requested") else "cancelled"
137
+ db.execute("UPDATE jobs SET status=?, updated=?, result_sha256=NULL, coach_payload_sha256=NULL, load_timing_sha256=NULL, timing_evidence_sha256=NULL, product_sha256=NULL, swings_sha256=NULL WHERE id=?",
138
  (status, time.time(), identifier))
139
  return status
140
 
 
329
  coach_hash=sha256_file(coach_path) if coach_path.is_file() else None,
330
  timing_hash=sha256_file(timing_path) if timing_path.is_file() else None,
331
  evidence_hash=sha256_file(directory/'load-timing-evidence.json') if (directory/'load-timing-evidence.json').is_file() else None,
332
+ product_hash=sha256_file(directory/'product.json') if (directory/'product.json').is_file() else None,
333
+ swings_hash=sha256_file(directory/'swings.json') if (directory/'swings.json').is_file() else None)
334
  else:
335
  error = read_json(directory / "error.json") if (directory / "error.json").exists() else {}
336
  code = error.get("code")
baseball_batting/api_worker.py CHANGED
@@ -158,6 +158,9 @@ def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_durati
158
  atomic_json(job/'load-timing-evidence.json', rich_timing)
159
  atomic_json(job / "coach-payload.json", result["coach_payload"])
160
  atomic_json(job / "result.json", result)
 
 
 
161
  if options.coaching_mode != "disabled":
162
  progress("coaching", n, n)
163
  from .product import build_product
 
158
  atomic_json(job/'load-timing-evidence.json', rich_timing)
159
  atomic_json(job / "coach-payload.json", result["coach_payload"])
160
  atomic_json(job / "result.json", result)
161
+ progress("swing_clips", 0, n)
162
+ from .swing_clips import export_swing_clips
163
+ export_swing_clips(video, capture, result["pose_track"], job, progress=progress)
164
  if options.coaching_mode != "disabled":
165
  progress("coaching", n, n)
166
  from .product import build_product
baseball_batting/ingest.py CHANGED
@@ -82,7 +82,7 @@ def probe(path):
82
  "r_frame_rate", "avg_frame_rate", "duration", "side_data_list") if k in s}
83
  for s in value.get("streams", [])]}
84
 
85
- def iter_frames(path, rotation=0, max_pixels=None):
86
  import av
87
  import cv2
88
  # Uploaded recordings must not trigger network requests through a playlist.
@@ -98,7 +98,8 @@ def iter_frames(path, rotation=0, max_pixels=None):
98
  image = frame.to_ndarray(format="bgr24")
99
  if rotation:
100
  image = np.ascontiguousarray(np.rot90(image, -(rotation // 90)))
101
- yield index, frame.pts, frame.time_base or stream.time_base, image
 
102
 
103
  def ingest(path, metadata, *, max_frames=None, max_pixels=None, max_duration_s=None, progress=None):
104
  import cv2
 
82
  "r_frame_rate", "avg_frame_rate", "duration", "side_data_list") if k in s}
83
  for s in value.get("streams", [])]}
84
 
85
+ def iter_frames(path, rotation=0, max_pixels=None, *, include_duration=False):
86
  import av
87
  import cv2
88
  # Uploaded recordings must not trigger network requests through a playlist.
 
98
  image = frame.to_ndarray(format="bgr24")
99
  if rotation:
100
  image = np.ascontiguousarray(np.rot90(image, -(rotation // 90)))
101
+ values = (index, frame.pts, frame.time_base or stream.time_base, image)
102
+ yield (*values, frame.duration) if include_duration else values
103
 
104
  def ingest(path, metadata, *, max_frames=None, max_pixels=None, max_duration_s=None, progress=None):
105
  import cv2
baseball_batting/media.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authenticated media streaming, including byte ranges used by video players."""
2
+ import hashlib
3
+ import os
4
+ import re
5
+
6
+ from fastapi import HTTPException
7
+ from fastapi.responses import Response, StreamingResponse
8
+ from starlette.background import BackgroundTask
9
+ from starlette.concurrency import run_in_threadpool
10
+
11
+
12
+ def open_verified_media(path, checksum, expected_size):
13
+ """Call while holding the job mutation lock; retain the descriptor for playback."""
14
+ try:
15
+ handle = path.open("rb")
16
+ except OSError:
17
+ raise HTTPException(500, "Stored clip failed its integrity check") from None
18
+ digest = hashlib.sha256()
19
+ try:
20
+ size = os.fstat(handle.fileno()).st_size
21
+ for block in iter(lambda: handle.read(1024*1024), b""):
22
+ digest.update(block)
23
+ if size != expected_size or digest.hexdigest() != checksum:
24
+ raise HTTPException(500, "Stored clip failed its integrity check")
25
+ handle.seek(0)
26
+ return handle, size
27
+ except BaseException:
28
+ handle.close()
29
+ raise
30
+
31
+
32
+ def media_response(request, handle, size, checksum):
33
+ etag = f'"{checksum}"'
34
+ headers = {"Content-Type": "video/mp4", "Content-Length": str(size),
35
+ "Accept-Ranges": "bytes", "ETag": etag, "Cache-Control": "private, no-store",
36
+ "X-Content-Type-Options": "nosniff"}
37
+ if request.method == "HEAD":
38
+ handle.close()
39
+ return Response(headers=headers)
40
+ start, end, status = 0, size-1, 200
41
+ value = request.headers.get("range")
42
+ if_range = request.headers.get("if-range")
43
+ if value and (if_range is None or if_range == etag) and value.startswith("bytes="):
44
+ match = re.fullmatch(r"bytes=(\d*)-(\d*)", value)
45
+ try:
46
+ if not match or not any(match.groups()):
47
+ raise ValueError()
48
+ a, b = match.groups()
49
+ if a:
50
+ start = int(a)
51
+ end = min(int(b), size-1) if b else size-1
52
+ else:
53
+ suffix = int(b)
54
+ if suffix == 0:
55
+ raise ValueError()
56
+ start = max(0, size-suffix)
57
+ if start >= size or end < start:
58
+ raise ValueError()
59
+ except ValueError:
60
+ handle.close()
61
+ headers.update({"Content-Range": f"bytes */{size}", "Content-Length": "0"})
62
+ return Response(status_code=416, headers=headers)
63
+ status = 206
64
+ headers.update({"Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end-start+1)})
65
+ async def stream():
66
+ try:
67
+ handle.seek(start)
68
+ remaining = end-start+1
69
+ while remaining:
70
+ block = await run_in_threadpool(handle.read, min(64*1024, remaining))
71
+ if not block:
72
+ break
73
+ remaining -= len(block)
74
+ yield block
75
+ finally:
76
+ handle.close()
77
+ return StreamingResponse(stream(), status_code=status, headers=headers,
78
+ background=BackgroundTask(handle.close))
baseball_batting/product.html CHANGED
@@ -19,12 +19,14 @@
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}
26
  function text(tag,value,parent){const e=document.createElement(tag);e.textContent=value;parent.appendChild(e);return e}
27
- function show(product){payload=product;$('results').hidden=false;for(const id of ['features','timing','advice','frames'])$(id).replaceChildren();images.forEach(URL.revokeObjectURL);images=[];
 
 
28
  const names={load_timing:'Load and timing',hip_shoulder_separation:'Hips and shoulders',bat_path_contact:'Bat path and contact'};
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)}
 
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><h2>Your swings</h2><p>Each clip uses the detected swing range. Check that the whole swing is included.</p><div class="grid" id="swings"></div><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}
26
  function text(tag,value,parent){const e=document.createElement(tag);e.textContent=value;parent.appendChild(e);return e}
27
+ function show(product){payload=product;$('results').hidden=false;for(const id of ['swings','features','timing','advice','frames'])$(id).replaceChildren();images.forEach(URL.revokeObjectURL);images=[];
28
+ for(const swing of product.swings||[]){const card=text('article','',$('swings'));card.className='card';text('h3','Swing '+swing.rep,card);if(swing.clip.status!=='available'){text('p','Clip unavailable: '+swing.clip.reason_code,card);continue}text('small',swing.clip.duration_s.toFixed(2)+' seconds · no audio',card);const player=document.createElement('video');player.controls=true;player.playsInline=true;player.preload='metadata';player.style.width='100%';player.style.marginTop='12px';player.hidden=true;card.appendChild(player);const b=text('button','Load swing '+swing.rep,card);b.onclick=async()=>{b.disabled=true;try{const blob=await(await api(swing.clip.url)).blob();if(payload!==product)return;const url=URL.createObjectURL(blob);images.push(url);player.src=url;player.hidden=false;b.remove()}catch(e){b.disabled=false;text('p',e.message,card)}}}
29
+ if(!(product.swings||[]).length)text('p',product.schema_version==='1.0'?'This older result has no swing clips. Upload again to create them.':'No swing clips were detected.',$('swings'));
30
  const names={load_timing:'Load and timing',hip_shoulder_separation:'Hips and shoulders',bat_path_contact:'Bat path and contact'};
31
  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.'};
32
  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)}
baseball_batting/product.py CHANGED
@@ -7,7 +7,7 @@ import copy
7
  from pathlib import Path
8
  import statistics
9
 
10
- from .storage import atomic_json, sha256_file
11
 
12
 
13
  def coach_input(result, timing, session_id):
@@ -144,9 +144,11 @@ def build_product(job, video, result, timing, options, *, service=None, generato
144
  public_frames = [{k: v for k, v in f.items() if k != "jpeg"} for f in frames]
145
  for f in public_frames:
146
  f["url"] = f"/v1/analyses/{job.name}/frames/{f['frame']}"
147
- product = {"schema_version": "1.0", "session_id": job.name, "discipline": "hitting",
 
148
  "coaching_mode": options.coaching_mode, "measurements": result["coach_payload"],
149
  "timing": timing, "coaching": response, "visual_review": review,
 
150
  "evidence": {"frames": public_frames,
151
  "reviewed_reps": sorted({r for f in frames for r in f["reps"]}),
152
  "total_reps": len(result["pose_track"]["reps"]), "sampled": True,
 
7
  from pathlib import Path
8
  import statistics
9
 
10
+ from .storage import atomic_json, read_json, sha256_file
11
 
12
 
13
  def coach_input(result, timing, session_id):
 
144
  public_frames = [{k: v for k, v in f.items() if k != "jpeg"} for f in frames]
145
  for f in public_frames:
146
  f["url"] = f"/v1/analyses/{job.name}/frames/{f['frame']}"
147
+ swings = read_json(job/"swings.json")["swings"] if (job/"swings.json").is_file() else []
148
+ product = {"schema_version": "1.1", "session_id": job.name, "discipline": "hitting",
149
  "coaching_mode": options.coaching_mode, "measurements": result["coach_payload"],
150
  "timing": timing, "coaching": response, "visual_review": review,
151
+ "swings": swings, "swings_url": f"/v1/analyses/{job.name}/swings",
152
  "evidence": {"frames": public_frames,
153
  "reviewed_reps": sorted({r for f in frames for r in f["reps"]}),
154
  "total_reps": len(result["pose_track"]["reps"]), "sampled": True,
baseball_batting/swing_clips.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Playable per-rep exports using source frames and playback presentation times.
2
+
3
+ Cut decoded frames, not keyframes. Never replace a missing clock with assumed
4
+ FPS, or alter a clip to the inferred capture speed. The final frame's duration
5
+ comes from the next source timestamp or its recorded sample duration.
6
+ """
7
+ from fractions import Fraction
8
+ import logging
9
+ import os
10
+ from pathlib import Path
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
13
+ from typing import Literal
14
+
15
+ from .ingest import iter_frames
16
+ from .storage import atomic_json, sha256_file
17
+
18
+ LOG = logging.getLogger(__name__)
19
+ TIME_BASE = Fraction(1, 1_000_000)
20
+ MAX_DIMENSION = 1280
21
+
22
+
23
+ class Clip(BaseModel):
24
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
25
+ status: Literal["available", "unavailable"]
26
+ reason_code: str | None = None
27
+ url: str | None = None
28
+ content_type: Literal["video/mp4"] = "video/mp4"
29
+ duration_s: float | None = Field(default=None, gt=0)
30
+ frame_count: int | None = Field(default=None, ge=1)
31
+ width: int | None = Field(default=None, ge=1)
32
+ height: int | None = Field(default=None, ge=1)
33
+ has_audio: Literal[False] = False
34
+ size_bytes: int | None = Field(default=None, gt=0)
35
+ sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
36
+
37
+ @model_validator(mode="after")
38
+ def complete(self):
39
+ if self.status == "available":
40
+ if self.reason_code or any(getattr(self, k) is None for k in
41
+ ("url", "duration_s", "frame_count", "width", "height", "size_bytes", "sha256")):
42
+ raise ValueError("Available clips need complete media metadata")
43
+ elif not self.reason_code or self.url is not None:
44
+ raise ValueError("Unavailable clips need a reason and no playable URL")
45
+ return self
46
+
47
+
48
+ class Swing(BaseModel):
49
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
50
+ rep: int = Field(ge=1)
51
+ start_frame: int = Field(ge=0)
52
+ end_frame: int = Field(ge=0)
53
+ boundary_method: str
54
+ boundary_accuracy_validated: Literal[False] = False
55
+ source_start_playback_s: float | None
56
+ source_end_playback_s: float | None
57
+ clip: Clip
58
+
59
+ @model_validator(mode="after")
60
+ def bounds(self):
61
+ if self.end_frame < self.start_frame:
62
+ raise ValueError("Reversed swing boundary")
63
+ if self.clip.status == "available" and self.clip.frame_count != self.end_frame-self.start_frame+1:
64
+ raise ValueError("Clip must retain every frame in the inclusive swing range")
65
+ return self
66
+
67
+
68
+ class SwingsManifest(BaseModel):
69
+ model_config = ConfigDict(extra="forbid")
70
+ schema_version: Literal["1.0"] = "1.0"
71
+ session_id: str
72
+ swings: list[Swing] = Field(max_length=100)
73
+ notice: str = ("Swing boundaries are detection candidates or supplied ranges, not validated labels. "
74
+ "Clips preserve recorded playback timing, are upright, resized to at most 1280 pixels "
75
+ "on the longest side, and have no audio.")
76
+
77
+ @model_validator(mode="after")
78
+ def ordered(self):
79
+ if len({s.rep for s in self.swings}) != len(self.swings):
80
+ raise ValueError("Duplicate rep ID")
81
+ if any(b.start_frame <= a.end_frame for a, b in zip(self.swings, self.swings[1:])):
82
+ raise ValueError("Swing ranges must be ordered and non-overlapping")
83
+ return self
84
+
85
+
86
+ class ClipError(Exception):
87
+ pass
88
+
89
+
90
+ def _ticks(value):
91
+ return round(value / TIME_BASE)
92
+
93
+
94
+ def _source_time(frame):
95
+ if frame.get("pts") is None or not frame.get("time_base"):
96
+ raise ClipError("source_timestamps_unavailable")
97
+ return frame["pts"] * Fraction(frame["time_base"])
98
+
99
+
100
+ class _Writer:
101
+ def __init__(self, temporary, shape):
102
+ import av
103
+ import cv2
104
+ self.av, self.cv2 = av, cv2
105
+ height, width = shape[:2]
106
+ scale = min(1., MAX_DIMENSION / max(width, height))
107
+ self.resized = (max(1, round(width*scale)), max(1, round(height*scale)))
108
+ # Pad at most one pixel per dimension so H.264/yuv420p works on odd sizes.
109
+ self.width, self.height = [v + v % 2 for v in self.resized]
110
+ self.out = av.open(str(temporary), "w", format="mp4", options={"movflags": "+faststart"})
111
+ try:
112
+ self.stream = self.out.add_stream("libx264", rate=None)
113
+ self.stream.width, self.stream.height = self.width, self.height
114
+ self.stream.pix_fmt = "yuv420p"
115
+ self.stream.time_base = self.stream.codec_context.time_base = TIME_BASE
116
+ self.stream.options = {"crf": "20", "preset": "veryfast", "bf": "0", "threads": "2"}
117
+ except Exception:
118
+ self.out.close()
119
+ raise
120
+ self.durations = {}
121
+ self.count = self.packets = 0
122
+ self.end = 0
123
+
124
+ def mux(self, packets):
125
+ for packet in packets:
126
+ # Encoder defaults must not stretch the last sample to 1/24 s.
127
+ pts = _ticks(packet.pts * packet.time_base)
128
+ packet.duration = round(self.durations.pop(pts) * TIME_BASE / packet.time_base)
129
+ self.out.mux(packet)
130
+ self.packets += 1
131
+
132
+ def write(self, image, timestamp, duration):
133
+ if image.shape[1::-1] != self.resized:
134
+ image = self.cv2.resize(image, self.resized, interpolation=self.cv2.INTER_AREA)
135
+ image = self.cv2.copyMakeBorder(image, 0, self.height-self.resized[1],
136
+ 0, self.width-self.resized[0], self.cv2.BORDER_REPLICATE)
137
+ frame = self.av.VideoFrame.from_ndarray(image, format="bgr24")
138
+ frame.pts, frame.time_base, frame.duration = timestamp, TIME_BASE, duration
139
+ self.durations[timestamp] = duration
140
+ self.mux(self.stream.encode(frame))
141
+ self.count += 1
142
+ self.end = timestamp + duration
143
+
144
+ def finish(self):
145
+ self.mux(self.stream.encode())
146
+ self.out.close()
147
+ if self.count != self.packets or self.durations:
148
+ raise ClipError("clip_frame_count_mismatch")
149
+
150
+ def abort(self):
151
+ try:
152
+ self.out.close()
153
+ except Exception:
154
+ LOG.warning("Could not finalize failed clip output")
155
+
156
+
157
+ def export_swing_clips(video, capture, track, job, *, progress=None):
158
+ """One decode pass for all reps. A failed clip never erases measurement data."""
159
+ job = Path(job)
160
+ frames = capture["frames"]
161
+ def playback(index):
162
+ return frames[index]["playback_s"] if 0 <= index < len(frames) else None
163
+ swings = [Swing(rep=r["rep"], start_frame=r["start_frame"], end_frame=r["end_frame"],
164
+ boundary_method=r.get("boundary_method", "unknown"),
165
+ source_start_playback_s=playback(r["start_frame"]),
166
+ source_end_playback_s=playback(r["end_frame"]),
167
+ clip=Clip(status="unavailable", reason_code="clip_export_failed")) for r in track["reps"]]
168
+ manifest = SwingsManifest(session_id=job.name, swings=swings)
169
+ directory = job/"swing-clips"
170
+ directory.mkdir(parents=True, exist_ok=True)
171
+ wanted = []
172
+ timelines = {}
173
+ for swing in swings:
174
+ try:
175
+ if swing.end_frame >= len(frames):
176
+ raise ClipError("source_video_mismatch")
177
+ source = [_source_time(f) for f in frames[swing.start_frame:swing.end_frame+1]]
178
+ if any(b <= a for a, b in zip(source, source[1:])):
179
+ raise ClipError("source_timestamps_invalid")
180
+ timeline = [_ticks(t-source[0]) for t in source]
181
+ if any(b <= a for a, b in zip(timeline, timeline[1:])):
182
+ raise ClipError("source_timestamps_invalid")
183
+ timelines[swing.rep] = (source, timeline)
184
+ wanted.append(swing)
185
+ except ClipError as exc:
186
+ swing.clip.reason_code = str(exc)
187
+ writer = None
188
+ temporary = None
189
+ position = 0
190
+ try:
191
+ if wanted:
192
+ for index, pts, base, image, sample_duration in iter_frames(video,
193
+ capture["rotation_degrees"], include_duration=True):
194
+ if position == len(wanted):
195
+ break
196
+ swing = wanted[position]
197
+ if index < swing.start_frame:
198
+ continue
199
+ try:
200
+ source, timeline = timelines[swing.rep]
201
+ local = index - swing.start_frame
202
+ if local >= len(source) or pts is None or not base or pts*base != source[local]:
203
+ raise ClipError("source_video_mismatch")
204
+ if writer is None:
205
+ temporary = directory/f".{swing.rep}.tmp.mp4"
206
+ writer = _Writer(temporary, image.shape)
207
+ if local+1 < len(source):
208
+ duration = timeline[local+1] - timeline[local]
209
+ elif index+1 < len(frames):
210
+ duration = _ticks(_source_time(frames[index+1])-source[0])-timeline[local]
211
+ elif sample_duration and sample_duration > 0:
212
+ duration = _ticks(sample_duration*base)
213
+ else:
214
+ raise ClipError("last_frame_duration_unavailable")
215
+ if duration <= 0:
216
+ raise ClipError("source_timestamps_invalid")
217
+ writer.write(image, timeline[local], duration)
218
+ if index == swing.end_frame:
219
+ writer.finish()
220
+ final = directory/f"{swing.rep}.mp4"
221
+ os.replace(temporary, final)
222
+ swing.clip = Clip(status="available",
223
+ url=f"/v1/analyses/{job.name}/swings/{swing.rep}/clip",
224
+ duration_s=writer.end*float(TIME_BASE), frame_count=writer.count,
225
+ width=writer.width, height=writer.height, size_bytes=final.stat().st_size,
226
+ sha256=sha256_file(final))
227
+ writer = None
228
+ position += 1
229
+ except Exception as exc:
230
+ LOG.warning("Swing %s clip export failed: %s", swing.rep, type(exc).__name__)
231
+ swing.clip = Clip(status="unavailable", reason_code=(str(exc) if isinstance(exc, ClipError)
232
+ else "clip_export_failed"))
233
+ if writer is not None:
234
+ writer.abort()
235
+ writer = None
236
+ if temporary is not None:
237
+ temporary.unlink(missing_ok=True)
238
+ # Skip the rest of this rep; continue to the next range.
239
+ position += 1
240
+ if progress and ((index+1) % 64 == 0 or index == swing.end_frame):
241
+ progress("swing_clips", index+1, capture["frame_count"])
242
+ except Exception:
243
+ LOG.exception("Source decode failed during swing clip export")
244
+ finally:
245
+ if writer is not None:
246
+ writer.abort()
247
+ if temporary is not None:
248
+ temporary.unlink(missing_ok=True)
249
+ # Any undecoded/uncompleted ranges retain an explicit unavailable entry.
250
+ payload = manifest.model_dump(mode="json")
251
+ atomic_json(job/"swings.json", payload)
252
+ return payload
docs/APP_API_INTEGRATION.md ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # App integration: swing analysis, coaching and swing clips
2
+
3
+ For the coding agent updating the app's previous engine → separate coach flow.
4
+
5
+ **Engine base URL:** `https://modventures-baseball-engine.hf.space`
6
+
7
+ Use one upload and one combined result. The engine now runs the coach internally.
8
+ The result includes measurements, the coach's existing response, experimental
9
+ video feedback for the three features, and a playable clip for each detected swing.
10
+
11
+ ```text
12
+ App → app backend → upload video to engine → poll job
13
+ ↓
14
+ combined product + individual swing clips
15
+ ↓
16
+ app shows swing cards and feedback
17
+ ```
18
+
19
+ ## 1. Change the old integration
20
+
21
+ | Previous integration | Current integration |
22
+ | --- | --- |
23
+ | Upload to `POST /v1/analyses` | Upload to `POST /v1/swing-coach/analyses` |
24
+ | Fetch `/coach-payload`, then call the standalone coach | Fetch `/product`; coaching is already included |
25
+ | Read only the coach response | Read `product.coaching` **and** `product.visual_review` |
26
+ | Use frame ranges or still images as swing previews | Read `product.swings`; each available clip has an MP4 endpoint |
27
+ | App receives coach response version `2.0` | That same response remains inside `product.coaching` |
28
+
29
+ For this new flow, remove the extra standalone coach request. Do not pass the
30
+ whole product into the old coach input: it already contains that coach's output.
31
+
32
+ **Do not hide the entire result when `coaching.score.value` is null or
33
+ `coaching.focus` is empty.** The experimental video observations and swing clips
34
+ can still be available. Fetching `/coaching` alone also misses the new video
35
+ feedback and clips; fetch `/product` for the app screen.
36
+
37
+ Old engine upload/result routes and standalone coach routes remain available.
38
+ Legacy measurements stay at schema `2.0`; timing defaults to `3.0`, with `3.1`
39
+ when evidence is requested. The combined product is now **`schema_version: "1.1"`**.
40
+ Its new `swings` and `swings_url` fields are additive to product `1.0`. Accept
41
+ both product versions and treat a missing `swings` field as an older result.
42
+
43
+ ## 2. Authentication and app backend
44
+
45
+ Every engine `/v1/...` request uses:
46
+
47
+ ```http
48
+ Authorization: Bearer <ENGINE_SERVER_KEY>
49
+ ```
50
+
51
+ Store this key in your **app backend's environment**, for example
52
+ `BASEBALL_ENGINE_API_KEY`. Use the same key for uploads, status, JSON results,
53
+ images and MP4 clips. The old standalone coach's `X-API-Key` header is not used
54
+ for this combined flow.
55
+
56
+ The Gemini key stays in the engine's `GOOGLE_API_KEY` secret. The app does not
57
+ send it. Browser uploads should go through your app backend: the engine does
58
+ not enable cross-origin browser requests.
59
+
60
+ Authenticate your app user and store which user owns each returned `job_id`.
61
+ Check that ownership before proxying status, results, clips, frames, retry or
62
+ delete. The engine's shared key does not provide per-user access control.
63
+
64
+ ## 3. Upload one video
65
+
66
+ **`POST /v1/swing-coach/analyses`**
67
+
68
+ Body: **multipart form data**, with these two fields:
69
+
70
+ | Field | Form-data type | Value |
71
+ | --- | --- | --- |
72
+ | `video` | File | The original video file |
73
+ | `options` | Text | A JSON string containing the recording facts |
74
+
75
+ Example options for a known right-handed batter, with the ball coming from the
76
+ right side of the image and a fixed camera facing the batter's chest:
77
+
78
+ ```json
79
+ {
80
+ "measurement_backend": "2d",
81
+ "coaching_mode": "poc_video",
82
+ "view": "face_on",
83
+ "handedness": "right",
84
+ "pitcher_direction": "image_right",
85
+ "practice_type": "front_toss",
86
+ "camera_stability": "fixed_verified",
87
+ "timing": {
88
+ "kind": "unretimed",
89
+ "source": "Uploader confirms original recording; no speed changes"
90
+ },
91
+ "single_swing": false
92
+ }
93
+ ```
94
+
95
+ These are example facts, not defaults to apply to every player. Ask the player
96
+ for the facts the app does not know.
97
+
98
+ | Option | Meaning and accepted values |
99
+ | --- | --- |
100
+ | `measurement_backend` | Use `"2d"` for this POC. It runs pose and bat/ball models on GPU without SAM. |
101
+ | `coaching_mode` | `"poc_video"` includes the coach and sampled-image Gemini review; this is the new route's default. `"measurements_only"` includes the existing coach without Gemini images. `"disabled"` produces measurements and clips without a product. |
102
+ | `view` | `"face_on"` when the camera faces the batter's chest; otherwise `"unknown"`. Do not infer this only because a person is visible. |
103
+ | `handedness` | `"left"`, `"right"`, or `null`: the side the player bats from. |
104
+ | `pitcher_direction` | `"image_left"`, `"image_right"`, or `null`: direction toward the pitcher/tee in the image, not the player's handedness. |
105
+ | `practice_type` | `"tee"`, `"soft_toss"`, `"front_toss"`, `"live"`, `"machine"`, or `"unknown"`. |
106
+ | `camera_stability` | `"fixed_verified"` if the camera stays still, `"moving"` if it moves, otherwise `"unknown"`. |
107
+ | `timing` | `{"kind":"unknown"}` if speed changes are uncertain. Use documented `"unretimed"` only when the recording has no speed changes. |
108
+ | `single_swing` | **`false` for a video containing multiple swings.** `true` treats the entire recording as one supplied swing range; it does not split it. |
109
+
110
+ Unknown recording facts are accepted by the combined route. They can make
111
+ measurements unavailable, so show upload `warnings` instead of silently changing
112
+ the facts. The strict `/v1/load-timing/analyses` route can reject missing timing
113
+ settings; it is not the recommended upload route for the combined app screen.
114
+
115
+ If the recording is documented constant slow motion, the supported timing shape is:
116
+
117
+ ```json
118
+ {
119
+ "kind": "constant_slowdown",
120
+ "source": "Documented camera recording setting",
121
+ "factor": 4,
122
+ "all_captured_frames_retained": true
123
+ }
124
+ ```
125
+
126
+ Do not set that flag if frames were removed or the slowdown is uncertain.
127
+
128
+ If your app already knows the cuts, it may supply `reps` as sorted,
129
+ non-overlapping, **zero-based inclusive** frame ranges:
130
+
131
+ ```json
132
+ {
133
+ "single_swing": false,
134
+ "reps": [
135
+ {"start_frame": 0, "end_frame": 119},
136
+ {"start_frame": 120, "end_frame": 239}
137
+ ]
138
+ }
139
+ ```
140
+
141
+ Omit `reps` to let the engine detect swings. Do not send `single_swing: true`
142
+ together with `reps`. Only send ranges that fit the actual source video.
143
+
144
+ Successful upload returns **HTTP 202**, including:
145
+
146
+ ```json
147
+ {
148
+ "job_id": "0123456789abcdef0123456789abcdef",
149
+ "status": "queued",
150
+ "status_url": "/v1/analyses/0123456789abcdef0123456789abcdef",
151
+ "product_url": "/v1/analyses/0123456789abcdef0123456789abcdef/product",
152
+ "swings_url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings",
153
+ "coaching_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coaching",
154
+ "result_url": "/v1/analyses/0123456789abcdef0123456789abcdef/result",
155
+ "coach_payload_url": "/v1/analyses/0123456789abcdef0123456789abcdef/coach-payload",
156
+ "load_timing_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing",
157
+ "load_timing_evidence_url": "/v1/analyses/0123456789abcdef0123456789abcdef/load-timing?include_evidence=true",
158
+ "warnings": []
159
+ }
160
+ ```
161
+
162
+ The job ID here is illustrative. Save the real ID returned by your upload.
163
+ All returned URLs are relative to the engine base URL.
164
+
165
+ ## 4. Poll the job, then fetch the product
166
+
167
+ **`GET /v1/analyses/{job_id}`**
168
+
169
+ Poll about every two seconds; back off during a long wait. An upload response
170
+ does not mean analysis has finished. GPU work can take several minutes.
171
+
172
+ | Job status | App behavior |
173
+ | --- | --- |
174
+ | `queued` | Show “Waiting to analyze”. |
175
+ | `running` | Show “Analyzing”, optionally with the current `progress.stage`. |
176
+ | `completed` | Fetch `product_url`, then render the result. |
177
+ | `failed` | Show the returned `error`; allow a new upload. |
178
+ | `cancel_requested` | Show “Cancelling” and continue polling. |
179
+ | `cancelled` | Stop polling; the result files are removed. |
180
+
181
+ `progress` can be null. Stages include decoding, pose, measurements, tracking,
182
+ `swing_clips`, coaching and complete. `completed_frames`, `total_frames` and
183
+ `stage_progress` describe the current stage, not the whole job. Do not present
184
+ a stage's percentage as an overall completion percentage.
185
+
186
+ Preserve the job ID if the user leaves the screen or a polling request fails;
187
+ resume polling rather than uploading the same video again automatically.
188
+
189
+ Once complete:
190
+
191
+ **`GET /v1/analyses/{job_id}/product`**
192
+
193
+ | Product field | What the app uses it for |
194
+ | --- | --- |
195
+ | `schema_version` | Product version `"1.1"`; also accept older `"1.0"`. |
196
+ | `session_id` | Same ID as the analysis job. |
197
+ | `discipline` | `"hitting"`. |
198
+ | `coaching_mode` | The requested mode. |
199
+ | `swings` | Every detected/supplied rep, with its boundaries and clip metadata. |
200
+ | `swings_url` | Separate swing-list endpoint, if needed. |
201
+ | `measurements` | Existing `2.0` per-rep nine-measurement payload. |
202
+ | `timing` | `3.1` per-rep timing, event intervals, context and reason codes. |
203
+ | `coaching` | Existing coach response, `response_version: "2.0"`. |
204
+ | `visual_review` | Experimental observations and optional priority/drill for the three features. |
205
+ | `evidence` | Retained sampled frame images and review coverage. |
206
+
207
+ There is no second upload or separate endpoint for each of the three feedback
208
+ features. They are returned together in `visual_review.features`.
209
+
210
+ ## 5. Show an individual video for each swing
211
+
212
+ `product.swings` contains entries shaped like this. Numbers and checksum below
213
+ are illustrative, not a real downloadable recording:
214
+
215
+ ```json
216
+ {
217
+ "rep": 1,
218
+ "start_frame": 0,
219
+ "end_frame": 119,
220
+ "boundary_method": "automatic_2d_hand_motion_candidate",
221
+ "boundary_accuracy_validated": false,
222
+ "source_start_playback_s": 0.0,
223
+ "source_end_playback_s": 3.966667,
224
+ "clip": {
225
+ "status": "available",
226
+ "reason_code": null,
227
+ "url": "/v1/analyses/0123456789abcdef0123456789abcdef/swings/1/clip",
228
+ "content_type": "video/mp4",
229
+ "duration_s": 4.0,
230
+ "frame_count": 120,
231
+ "width": 1280,
232
+ "height": 720,
233
+ "has_audio": false,
234
+ "size_bytes": 524288,
235
+ "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
236
+ }
237
+ }
238
+ ```
239
+
240
+ Build the swing list from `swings`, ordered as returned. Labels are “Swing 1”,
241
+ “Swing 2”, etc. Rep IDs are **one-based**; source frame IDs are **zero-based**.
242
+
243
+ - `start_frame` and `end_frame` include both endpoint frames.
244
+ - `boundary_method` is `automatic_2d_hand_motion_candidate`, `caller_supplied`,
245
+ or `caller_declared_single_swing` for the current engine.
246
+ - Automatic cuts are candidates. Detection may miss/merge movements; clips do
247
+ not establish that every actual swing was found.
248
+ - Clips contain the original video images, without skeleton annotations. They
249
+ are upright H.264 MP4s, resized to at most 1280 pixels on the longest side,
250
+ with at most one pixel of padding for odd dimensions. They have **no audio**.
251
+ - Every source frame in the range is retained. Each clip starts at playback
252
+ time zero and preserves the source's variable frame spacing and playback
253
+ speed. An uploaded slow-motion video stays slow motion in the clip.
254
+ - Capture-time measurements and clip playback time are separate clocks.
255
+ `source_end_playback_s` is the last frame's timestamp; `duration_s` also
256
+ includes that last frame's display duration.
257
+
258
+ The clip endpoint is:
259
+
260
+ **`GET /v1/analyses/{job_id}/swings/{rep}/clip`**
261
+
262
+ It requires the same Bearer key and returns `video/mp4`. It supports normal GET
263
+ (`200`), single byte ranges (`206`), suffix/open-ended ranges, and HEAD. Invalid
264
+ or unsatisfiable byte ranges return `416` with `Content-Range: bytes */<size>`.
265
+ Multiple ranges are unsupported. `Accept-Ranges`, `Content-Length`, `ETag` and
266
+ `Content-Range` on partial responses support player seeking.
267
+
268
+ **Use an app-backend media proxy for playback.** Browser `<video src>` cannot
269
+ attach the engine's Bearer header. The proxy should authenticate the app user,
270
+ check job ownership, add the engine key, forward `Range`/`If-Range`, and stream
271
+ the response without buffering the whole video. Pass through the response
272
+ status and media/range headers. Never put the engine key in the video URL.
273
+
274
+ For a small internal browser test, fetching the authenticated clip into a Blob
275
+ and setting `video.src = URL.createObjectURL(blob)` also works. Revoke the Blob
276
+ URL when the result is replaced. This downloads the entire clip first; the
277
+ backend proxy is the preferred app integration.
278
+
279
+ For a separate swing-list request:
280
+
281
+ **`GET /v1/analyses/{job_id}/swings`** returns:
282
+
283
+ ```text
284
+ schema_version: "1.0" # This is the swing-list version, not the product version.
285
+ session_id: job ID
286
+ swings: same array as product.swings
287
+ notice: boundary/timing/format explanation
288
+ ```
289
+
290
+ New jobs on the legacy upload routes also create this manifest and clips.
291
+ Older completed jobs cannot create clips after their original upload was
292
+ removed. Their swing endpoint returns `409`; upload again to create clips.
293
+
294
+ If a particular clip cannot be exported, its rep remains in `swings` with
295
+ `clip.status: "unavailable"`, a `reason_code`, and `url: null`. Hide that rep's
296
+ player and show “Clip unavailable”; retain its measurements and feedback.
297
+ Reasons include missing/invalid source timestamps, source mismatch,
298
+ unavailable last-frame duration, and `clip_export_failed`. An empty `swings`
299
+ array means no rep was detected; do not invent a swing card.
300
+
301
+ ## 6. Match each swing to its measurements and feedback
302
+
303
+ Join by **`rep`**, not by array position:
304
+
305
+ ```javascript
306
+ const cards = (product.swings ?? []).map(swing => ({
307
+ ...swing,
308
+ measurements: product.measurements.reps.find(r => r.rep === swing.rep) ?? null,
309
+ timing: product.timing.reps.find(r => r.rep === swing.rep) ?? null,
310
+ observations: product.visual_review.features.filter(f => f.rep === swing.rep)
311
+ }));
312
+ ```
313
+
314
+ The current Gemini review returns **three feature observations for the session**,
315
+ each referring to one rep. It does not promise all three observations for every
316
+ swing. The configured default reviews sampled images from at most six reps;
317
+ **clips are exported for all detected reps**, including unreviewed ones.
318
+ Use `evidence.reviewed_reps` and `evidence.total_reps` to show that coverage.
319
+ Label a swing without a visual observation “Not individually reviewed” rather
320
+ than copying another swing's advice onto it.
321
+
322
+ ### Three feedback cards
323
+
324
+ When `visual_review.status` is `"completed"`, render its features:
325
+
326
+ | `feature.key` | App label | Text |
327
+ | --- | --- | --- |
328
+ | `load_timing` | Load and timing | `feature.observation` |
329
+ | `hip_shoulder_separation` | Hips and shoulders | `feature.observation` |
330
+ | `bat_path_contact` | Bat path and contact | `feature.observation` |
331
+
332
+ Each feature also contains `status` (`"observed"` or `"unclear"`), `rep`,
333
+ `evidence_frame_ids`, and `ball_interaction_visible`. Show unclear observations
334
+ as uncertainty, not as a diagnosed problem. Label this section “Experimental
335
+ video feedback”; `accuracy_validated` and `judgment_eligible` remain false.
336
+
337
+ `ball_interaction_visible` is the visual review's interpretation. It does not
338
+ change `timing.reps[].outcome` into a measured hit or turn an unavailable timing
339
+ number into a measured value. Hips/shoulders feedback describes visible turning
340
+ order, not a measured 3D separation angle. No validated score against exact pitch
341
+ location is supplied by this one-camera visual review.
342
+
343
+ When `visual_review.status` is `"unavailable"`, show its safe `message` or
344
+ `reason_code`. Keep showing clips, supported measurements and `coaching`.
345
+
346
+ ### Practice suggestion
347
+
348
+ If both `visual_review.priority` and `visual_review.drill` exist, show:
349
+
350
+ ```text
351
+ Why: visual_review.priority.reason
352
+ Drill: visual_review.drill.name
353
+ How: visual_review.drill.instructions
354
+ Cue: visual_review.drill.cue
355
+ ```
356
+
357
+ This is one experimental session suggestion, not one drill for every swing.
358
+ If no visual suggestion exists, your previous `coaching.drill` display can be
359
+ used when non-null (`name`, `how`, `cue`). Otherwise hide the drill area.
360
+
361
+ ### Timing and older coach fields
362
+
363
+ For a plain-language timing summary, keep using `coaching.timing.summary`,
364
+ `observations[].text`, `unavailable[].text` and `data_quality` when present.
365
+ For each swing's actual four values, read `timing.reps[].metrics` by key:
366
+
367
+ | Key | Label |
368
+ | --- | --- |
369
+ | `load_to_swing_ms` | Preparation to forward swing |
370
+ | `foot_down_to_swing_ms` | Front foot down to forward swing |
371
+ | `swing_duration_ms` | Forward swing to contact/closest approach |
372
+ | `early_late_shift_ms` | Estimated timing shift needed to meet the ball |
373
+
374
+ Render a number only when `value` is non-null, with its `status`/`confidence`.
375
+ Use “Unavailable” with the `note`/`reason_code` for unclear metrics, and “Not
376
+ applicable” when stated. Null is not zero. Keep signed foot-down differences;
377
+ negative means the swing began before the foot landed.
378
+
379
+ The original `coaching.summary`, `score`, `focus`, `strengths`, `drill`, and
380
+ `data_quality` remain available in the same coach response shape. A null score
381
+ must stay unavailable. Do not generate a score from the visual observations.
382
+
383
+ ### Evidence frames and seeking inside a clip
384
+
385
+ `evidence.frames[]` includes `frame`, `reps`, `url`, `playback_t_s`,
386
+ `capture_t_s`, `athlete_box` and `sha256`. Images use
387
+ `GET /v1/analyses/{job_id}/frames/{frame}` and require Bearer authentication.
388
+ Match `evidence_frame_ids` to this list, not to array indices.
389
+
390
+ For a frame belonging to a swing, the clip's local frame index is:
391
+
392
+ ```text
393
+ local_frame = source_frame - swing.start_frame
394
+ clip_seek_seconds = evidence_frame.playback_t_s - swing.source_start_playback_s
395
+ ```
396
+
397
+ Use the playback timestamps for seeking; do not divide capture milliseconds
398
+ by 1000 and assume they are clip times. Check the frame belongs to the swing
399
+ and both timestamps are available. Capture-time intervals remain in
400
+ `timing.reps[].events`; they describe uncertainty, not exact measured contact.
401
+
402
+ ## 7. Request examples in application code
403
+
404
+ The frontend below calls **your app's authenticated backend proxy**, which maps
405
+ `/api/baseball/v1/...` onto engine `/v1/...`. Adapt the prefix to your app. The
406
+ browser never receives the engine key.
407
+
408
+ ```javascript
409
+ async function uploadSwingVideo(file, recordingFacts, signal) {
410
+ const form = new FormData();
411
+ form.append("video", file);
412
+ form.append("options", JSON.stringify({
413
+ ...recordingFacts,
414
+ measurement_backend: "2d",
415
+ coaching_mode: "poc_video"
416
+ }));
417
+ const response = await fetch("/api/baseball/v1/swing-coach/analyses", {
418
+ method: "POST", body: form, signal
419
+ });
420
+ // Let fetch set the multipart boundary; do not set Content-Type manually.
421
+ if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
422
+ return response.json();
423
+ }
424
+
425
+ async function readAnalysis(jobId, signal) {
426
+ const response = await fetch(`/api/baseball/v1/analyses/${jobId}`, { signal });
427
+ if (!response.ok) throw new Error(`Status failed: ${response.status}`);
428
+ return response.json();
429
+ }
430
+
431
+ async function readProduct(jobId, signal) {
432
+ const response = await fetch(`/api/baseball/v1/analyses/${jobId}/product`, { signal });
433
+ if (!response.ok) throw new Error(`Result failed: ${response.status}`);
434
+ return response.json();
435
+ }
436
+
437
+ // After a completed status, each available clip can use your same-origin proxy:
438
+ function appClipUrl(jobId, swing) {
439
+ return `/api/baseball/v1/analyses/${jobId}/swings/${swing.rep}/clip`;
440
+ }
441
+ ```
442
+
443
+ Backend-only example for an engine request, using Node's built-in fetch:
444
+
445
+ ```javascript
446
+ const ENGINE_ORIGIN = "https://modventures-baseball-engine.hf.space";
447
+
448
+ async function engineRequest(relativePath, init = {}) {
449
+ const url = new URL(relativePath, ENGINE_ORIGIN);
450
+ if (url.origin !== ENGINE_ORIGIN || !url.pathname.startsWith("/v1/")) {
451
+ throw new Error("Unexpected engine path");
452
+ }
453
+ const key = process.env.BASEBALL_ENGINE_API_KEY;
454
+ if (!key) throw new Error("Engine key not configured");
455
+ const headers = new Headers(init.headers);
456
+ headers.set("Authorization", `Bearer ${key}`);
457
+ return fetch(url, { ...init, headers, redirect: "error" });
458
+ }
459
+
460
+ // Inside your authenticated/ownership-checked media route:
461
+ // 1. Validate jobId as 32 lowercase hex characters and rep as a positive integer.
462
+ // 2. Confirm the logged-in user owns that job.
463
+ // 3. Construct the path yourself; do not accept an arbitrary upstream URL.
464
+ // 4. Forward only supported request headers such as Range and If-Range.
465
+ // 5. Stream upstream.body using your framework's Web-to-Node stream adapter.
466
+ async function fetchClipForProxy(jobId, rep, requestHeaders) {
467
+ const headers = new Headers();
468
+ for (const name of ["Range", "If-Range"]) {
469
+ const value = requestHeaders.get(name);
470
+ if (value) headers.set(name, value);
471
+ }
472
+ return engineRequest(`/v1/analyses/${jobId}/swings/${rep}/clip`, { headers });
473
+ }
474
+ ```
475
+
476
+ The media proxy must pass through `200`, `206` and `416`, plus `Content-Type`,
477
+ `Content-Length`, `Content-Range`, `Accept-Ranges`, `ETag` and `Cache-Control`.
478
+ Do not convert every upstream response to HTTP 200. Support HEAD if the app's
479
+ player uses it. Forward authenticated JSON error responses for failed requests.
480
+
481
+ ## 8. Retry, cancel and retain results
482
+
483
+ **Retry optional video feedback:**
484
+ `POST /v1/analyses/{job_id}/video-review`, no request body.
485
+
486
+ This returns the updated whole product. It reuses retained images and keeps
487
+ the measurements and swing clips. It does not repeat pose inference. A completed
488
+ review is returned unchanged, without another Gemini call. An unavailable review
489
+ can be retried; a genuine retry consumes Gemini quota. Allow a longer request
490
+ timeout for this synchronous route and show “Retrying video feedback”. Do not
491
+ retry it continuously on every poll. No retained images returns `409`.
492
+
493
+ **Cancel/delete:** `DELETE /v1/analyses/{job_id}`, returning HTTP 202.
494
+ Running jobs first return `cancel_requested`; completed jobs become cancelled
495
+ and their JSON, images and clips are removed.
496
+
497
+ **Storage:** default engine retention is 24 hours; check `/v1/capabilities` for
498
+ the actual value. Hugging Face ephemeral storage can disappear during rebuilds
499
+ or restarts. Clip URLs are authenticated engine resources, not permanent media
500
+ hosting URLs. After completion, copy the product and each available clip into
501
+ your app's persistent storage if the user should revisit sessions later. Keep
502
+ rep IDs with those copies. An engine rebuild can erase jobs before 24 hours.
503
+
504
+ ## 9. Errors and limits
505
+
506
+ | HTTP status | Meaning |
507
+ | --- | --- |
508
+ | `401` | Invalid/missing engine Bearer key. |
509
+ | `404` | Job, rep or evidence frame not found. |
510
+ | `409` | Result not complete, older artifact missing, or requested clip unavailable. Check `detail`. |
511
+ | `413` | Upload/options/request too large. |
512
+ | `415` | Unsupported video extension. |
513
+ | `416` | Invalid/unsupported/unsatisfiable byte range. |
514
+ | `422` | Bad options, missing upload field, empty file, or invalid explicit ranges. |
515
+ | `429` | Queue, upload slots or review already busy. Respect `Retry-After` when provided. |
516
+ | `500` | Stored artifact failed integrity/structure checks, or review could not be saved. |
517
+ | `503` | GPU not ready or requested server component unavailable. |
518
+ | `507` | Insufficient engine storage. |
519
+
520
+ Errors use `{"detail": ...}`; `detail` can be a string, object or validation
521
+ list. Parse safely. A job can later fail with `error` codes such as
522
+ `invalid_video_or_capture`, `inference_failed`, `job_timeout`, or `worker_error`.
523
+ Optional Gemini failure is instead reported within `visual_review`; it does
524
+ not automatically make the analysis job fail.
525
+
526
+ Default limits: 512 MiB upload, 120 seconds of playback, 7200 decoded frames,
527
+ 8,294,400 pixels per source frame. Supported extensions: `.mp4`, `.mov`, `.mkv`,
528
+ `.avi`, `.webm`. Limits can be configured; read `/v1/capabilities` rather than
529
+ assuming these values forever.
530
+
531
+ Public `/healthz` checks liveness; `/readyz` checks GPU readiness and reports
532
+ visual model configuration/provider status. `/docs` serves interactive engine
533
+ API documentation. Authenticated `/v1/input-schema` and `/v1/swings-schema`
534
+ return the current input and swing-list schemas.
535
+
536
+ ## 10. Integration acceptance checks
537
+
538
+ - Upload a multi-swing video with `single_swing: false`; store the returned job
539
+ ID and poll it to completion without sending a second coach request.
540
+ - Show all returned swing entries, each with its own rep ID and playable clip
541
+ when available. Test seeking, and check HTTP 206 through the media proxy.
542
+ - Match each swing's timing/measurements by `rep`; attach only visual features
543
+ that cite that rep. Show review coverage for unreviewed swings.
544
+ - Show the three experimental feedback cards even when the older coach's score
545
+ and focus are unavailable.
546
+ - Handle unclear/null metrics, unavailable video review, unavailable individual
547
+ clips, an empty swing list, and an older product with no `swings` field.
548
+ - Retry feedback without re-uploading or losing existing clips/measurements.
549
+ - Keep the engine key in the backend; test user ownership on results and media.
550
+ - Copy retained sessions to app storage; handle expired/rebuilt engine jobs.
551
+
552
+ Do not fill unavailable measurements with visual guesses. This integration
553
+ provides the working POC's visible observations, supported estimates and clips;
554
+ it does not establish validated one-camera measurement accuracy.
docs/SWING_COACH_PRODUCT.md CHANGED
@@ -3,6 +3,10 @@
3
  The measurement engine and `AI-coach-agent` now run in the same GPU service.
4
  The standalone coach service and the existing engine routes still work.
5
 
 
 
 
 
6
  The full flow is: upload one video → detect swings and body movement → track bat
7
  and ball when possible → build measurements → run the coach → optionally review
8
  sampled original video frames → return one app response.
@@ -86,10 +90,12 @@ swings were found. Explicit `reps` can be supplied using the existing contract.
86
  Product shape:
87
 
88
  ```text
89
- schema_version: "1.0"
90
  session_id
91
  discipline: "hitting"
92
  coaching_mode
 
 
93
  measurements: existing engine 2.0 measurement payload
94
  timing: existing engine 3.1 timing evidence payload
95
  coaching: existing coach 2.0 app response
 
3
  The measurement engine and `AI-coach-agent` now run in the same GPU service.
4
  The standalone coach service and the existing engine routes still work.
5
 
6
+ For app migration and individual swing video playback, use
7
+ [APP_API_INTEGRATION.md](APP_API_INTEGRATION.md). Product `1.1` adds `swings`
8
+ and `swings_url`; new API jobs export an authenticated MP4 for every detected rep.
9
+
10
  The full flow is: upload one video → detect swings and body movement → track bat
11
  and ball when possible → build measurements → run the coach → optionally review
12
  sampled original video frames → return one app response.
 
90
  Product shape:
91
 
92
  ```text
93
+ schema_version: "1.1"
94
  session_id
95
  discipline: "hitting"
96
  coaching_mode
97
+ swings: per-rep boundaries and clip status, URL, duration, frame count, size and SHA-256
98
+ swings_url: /v1/analyses/{job_id}/swings
99
  measurements: existing engine 2.0 measurement payload
100
  timing: existing engine 3.1 timing evidence payload
101
  coaching: existing coach 2.0 app response
docs/swings.schema.json ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "Clip": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "status": {
7
+ "enum": [
8
+ "available",
9
+ "unavailable"
10
+ ],
11
+ "title": "Status",
12
+ "type": "string"
13
+ },
14
+ "reason_code": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string"
18
+ },
19
+ {
20
+ "type": "null"
21
+ }
22
+ ],
23
+ "default": null,
24
+ "title": "Reason Code"
25
+ },
26
+ "url": {
27
+ "anyOf": [
28
+ {
29
+ "type": "string"
30
+ },
31
+ {
32
+ "type": "null"
33
+ }
34
+ ],
35
+ "default": null,
36
+ "title": "Url"
37
+ },
38
+ "content_type": {
39
+ "const": "video/mp4",
40
+ "default": "video/mp4",
41
+ "title": "Content Type",
42
+ "type": "string"
43
+ },
44
+ "duration_s": {
45
+ "anyOf": [
46
+ {
47
+ "exclusiveMinimum": 0,
48
+ "type": "number"
49
+ },
50
+ {
51
+ "type": "null"
52
+ }
53
+ ],
54
+ "default": null,
55
+ "title": "Duration S"
56
+ },
57
+ "frame_count": {
58
+ "anyOf": [
59
+ {
60
+ "minimum": 1,
61
+ "type": "integer"
62
+ },
63
+ {
64
+ "type": "null"
65
+ }
66
+ ],
67
+ "default": null,
68
+ "title": "Frame Count"
69
+ },
70
+ "width": {
71
+ "anyOf": [
72
+ {
73
+ "minimum": 1,
74
+ "type": "integer"
75
+ },
76
+ {
77
+ "type": "null"
78
+ }
79
+ ],
80
+ "default": null,
81
+ "title": "Width"
82
+ },
83
+ "height": {
84
+ "anyOf": [
85
+ {
86
+ "minimum": 1,
87
+ "type": "integer"
88
+ },
89
+ {
90
+ "type": "null"
91
+ }
92
+ ],
93
+ "default": null,
94
+ "title": "Height"
95
+ },
96
+ "has_audio": {
97
+ "const": false,
98
+ "default": false,
99
+ "title": "Has Audio",
100
+ "type": "boolean"
101
+ },
102
+ "size_bytes": {
103
+ "anyOf": [
104
+ {
105
+ "exclusiveMinimum": 0,
106
+ "type": "integer"
107
+ },
108
+ {
109
+ "type": "null"
110
+ }
111
+ ],
112
+ "default": null,
113
+ "title": "Size Bytes"
114
+ },
115
+ "sha256": {
116
+ "anyOf": [
117
+ {
118
+ "pattern": "^[a-f0-9]{64}$",
119
+ "type": "string"
120
+ },
121
+ {
122
+ "type": "null"
123
+ }
124
+ ],
125
+ "default": null,
126
+ "title": "Sha256"
127
+ }
128
+ },
129
+ "required": [
130
+ "status"
131
+ ],
132
+ "title": "Clip",
133
+ "type": "object"
134
+ },
135
+ "Swing": {
136
+ "additionalProperties": false,
137
+ "properties": {
138
+ "rep": {
139
+ "minimum": 1,
140
+ "title": "Rep",
141
+ "type": "integer"
142
+ },
143
+ "start_frame": {
144
+ "minimum": 0,
145
+ "title": "Start Frame",
146
+ "type": "integer"
147
+ },
148
+ "end_frame": {
149
+ "minimum": 0,
150
+ "title": "End Frame",
151
+ "type": "integer"
152
+ },
153
+ "boundary_method": {
154
+ "title": "Boundary Method",
155
+ "type": "string"
156
+ },
157
+ "boundary_accuracy_validated": {
158
+ "const": false,
159
+ "default": false,
160
+ "title": "Boundary Accuracy Validated",
161
+ "type": "boolean"
162
+ },
163
+ "source_start_playback_s": {
164
+ "anyOf": [
165
+ {
166
+ "type": "number"
167
+ },
168
+ {
169
+ "type": "null"
170
+ }
171
+ ],
172
+ "title": "Source Start Playback S"
173
+ },
174
+ "source_end_playback_s": {
175
+ "anyOf": [
176
+ {
177
+ "type": "number"
178
+ },
179
+ {
180
+ "type": "null"
181
+ }
182
+ ],
183
+ "title": "Source End Playback S"
184
+ },
185
+ "clip": {
186
+ "$ref": "#/$defs/Clip"
187
+ }
188
+ },
189
+ "required": [
190
+ "rep",
191
+ "start_frame",
192
+ "end_frame",
193
+ "boundary_method",
194
+ "source_start_playback_s",
195
+ "source_end_playback_s",
196
+ "clip"
197
+ ],
198
+ "title": "Swing",
199
+ "type": "object"
200
+ }
201
+ },
202
+ "additionalProperties": false,
203
+ "properties": {
204
+ "schema_version": {
205
+ "const": "1.0",
206
+ "default": "1.0",
207
+ "title": "Schema Version",
208
+ "type": "string"
209
+ },
210
+ "session_id": {
211
+ "title": "Session Id",
212
+ "type": "string"
213
+ },
214
+ "swings": {
215
+ "items": {
216
+ "$ref": "#/$defs/Swing"
217
+ },
218
+ "maxItems": 100,
219
+ "title": "Swings",
220
+ "type": "array"
221
+ },
222
+ "notice": {
223
+ "default": "Swing boundaries are detection candidates or supplied ranges, not validated labels. Clips preserve recorded playback timing, are upright, resized to at most 1280 pixels on the longest side, and have no audio.",
224
+ "title": "Notice",
225
+ "type": "string"
226
+ }
227
+ },
228
+ "required": [
229
+ "session_id",
230
+ "swings"
231
+ ],
232
+ "title": "SwingsManifest",
233
+ "type": "object"
234
+ }
tests/test_api.py CHANGED
@@ -322,6 +322,7 @@ def test_existing_job_database_migrates_without_losing_records(tmp_path):
322
  store = JobStore(tmp_path)
323
  assert store.get(identifier)["result_sha256"] == "old-hash"
324
  assert store.get(identifier)["coach_payload_sha256"] is None
 
325
  fresh = store.create(8)
326
  store.update(fresh, "completed", result_hash="result", coach_hash="coach")
327
  assert store.get(fresh)["coach_payload_sha256"] == "coach"
@@ -349,3 +350,4 @@ def test_no_person_worker_returns_record_again_payload(video, tmp_path, monkeypa
349
  assert payload["capture"]["ok"] is False and "no_person" in payload["capture"]["reasons"]
350
  assert payload["reps"] == []
351
  assert "pose_track" not in payload
 
 
322
  store = JobStore(tmp_path)
323
  assert store.get(identifier)["result_sha256"] == "old-hash"
324
  assert store.get(identifier)["coach_payload_sha256"] is None
325
+ assert store.get(identifier)["swings_sha256"] is None
326
  fresh = store.create(8)
327
  store.update(fresh, "completed", result_hash="result", coach_hash="coach")
328
  assert store.get(fresh)["coach_payload_sha256"] == "coach"
 
350
  assert payload["capture"]["ok"] is False and "no_person" in payload["capture"]["reasons"]
351
  assert payload["reps"] == []
352
  assert "pose_track" not in payload
353
+ assert json.loads((tmp_path / "swings.json").read_text())["swings"] == []
tests/test_product.py CHANGED
@@ -110,9 +110,19 @@ def test_malformed_timing_still_returns_the_agents_input_error():
110
 
111
  def test_product_without_provider_preserves_coach_contract(tmp_path):
112
  result,rich=combined_fixture()
 
 
 
 
 
 
 
113
  svc=CoachService(settings=coach_settings(tmp_path))
114
  product=build_product(tmp_path,Path('unused.mp4'),result,rich,AnalysisInput(coaching_mode='poc_video'),service=svc)
115
  assert product['coaching']['response_version']=='2.0'
 
 
 
116
  assert product['coaching']['timing']['observations']
117
  assert product['visual_review']['reason_code']=='model_not_configured'
118
  assert product['coaching']['focus']==[] and product['coaching']['drill'] is None
@@ -302,11 +312,13 @@ def retained_review_job(tmp_path):
302
  (job/'review-frames').mkdir();(job/'review-frames/0.jpg').write_bytes(b'original-image')
303
  atomic_json(job/'request.json',AnalysisInput(coaching_mode='poc_video').model_dump(mode='json'))
304
  product={'session_id':identifier,'coaching':{'response_version':'2.0'},
 
305
  'visual_review':{'status':'unavailable','reason_code':'provider_failed'},
306
  'evidence':{'frames':[{'frame':0,'reps':[1],'sha256':sha256_file(job/'review-frames/0.jpg')}]}}
307
  atomic_json(job/'product.json',product)
308
  service.store.update(identifier,'completed',result_hash='original-result-hash',coach_hash='original-coach-hash',
309
- timing_hash='original-timing-hash',evidence_hash='original-evidence-hash',product_hash=sha256_file(job/'product.json'))
 
310
  return service,identifier,job,product
311
 
312
 
@@ -330,11 +342,13 @@ def test_retry_review_preserves_measurements_auth_and_checksums(tmp_path,monkeyp
330
  assert client.post(url).status_code==401
331
  r=client.post(url,headers=AUTH)
332
  assert r.status_code==200 and r.json()['coaching']==product['coaching']
 
333
  saved=service.store.get(identifier)
334
  assert saved['result_sha256']=='original-result-hash'
335
  assert saved['coach_payload_sha256']=='original-coach-hash'
336
  assert saved['load_timing_sha256']=='original-timing-hash'
337
  assert saved['timing_evidence_sha256']=='original-evidence-hash'
 
338
  assert saved['product_sha256']==sha256_file(job/'product.json')
339
  assert client.post(url,headers=AUTH).status_code==200
340
  assert len(calls)==2 # Completed retries are idempotent; no extra billed call.
 
110
 
111
  def test_product_without_provider_preserves_coach_contract(tmp_path):
112
  result,rich=combined_fixture()
113
+ from baseball_batting.swing_clips import SwingsManifest, Swing, Clip
114
+ bounds=result['pose_track']['reps'][0]
115
+ manifest=SwingsManifest(session_id=tmp_path.name,swings=[Swing(
116
+ rep=1,start_frame=bounds['start_frame'],end_frame=bounds['end_frame'],
117
+ boundary_method='caller_supplied',source_start_playback_s=None,source_end_playback_s=None,
118
+ clip=Clip(status='unavailable',reason_code='source_timestamps_unavailable'))]).model_dump(mode='json')
119
+ atomic_json(tmp_path/'swings.json',manifest)
120
  svc=CoachService(settings=coach_settings(tmp_path))
121
  product=build_product(tmp_path,Path('unused.mp4'),result,rich,AnalysisInput(coaching_mode='poc_video'),service=svc)
122
  assert product['coaching']['response_version']=='2.0'
123
+ assert product['schema_version']=='1.1'
124
+ assert product['swings']==manifest['swings']
125
+ assert product['swings_url']==f'/v1/analyses/{tmp_path.name}/swings'
126
  assert product['coaching']['timing']['observations']
127
  assert product['visual_review']['reason_code']=='model_not_configured'
128
  assert product['coaching']['focus']==[] and product['coaching']['drill'] is None
 
312
  (job/'review-frames').mkdir();(job/'review-frames/0.jpg').write_bytes(b'original-image')
313
  atomic_json(job/'request.json',AnalysisInput(coaching_mode='poc_video').model_dump(mode='json'))
314
  product={'session_id':identifier,'coaching':{'response_version':'2.0'},
315
+ 'swings':[{'rep':1,'clip':{'status':'available','url':f'/v1/analyses/{identifier}/swings/1/clip'}}],
316
  'visual_review':{'status':'unavailable','reason_code':'provider_failed'},
317
  'evidence':{'frames':[{'frame':0,'reps':[1],'sha256':sha256_file(job/'review-frames/0.jpg')}]}}
318
  atomic_json(job/'product.json',product)
319
  service.store.update(identifier,'completed',result_hash='original-result-hash',coach_hash='original-coach-hash',
320
+ timing_hash='original-timing-hash',evidence_hash='original-evidence-hash',product_hash=sha256_file(job/'product.json'),
321
+ swings_hash='original-swings-hash')
322
  return service,identifier,job,product
323
 
324
 
 
342
  assert client.post(url).status_code==401
343
  r=client.post(url,headers=AUTH)
344
  assert r.status_code==200 and r.json()['coaching']==product['coaching']
345
+ assert r.json()['swings']==product['swings']
346
  saved=service.store.get(identifier)
347
  assert saved['result_sha256']=='original-result-hash'
348
  assert saved['coach_payload_sha256']=='original-coach-hash'
349
  assert saved['load_timing_sha256']=='original-timing-hash'
350
  assert saved['timing_evidence_sha256']=='original-evidence-hash'
351
+ assert saved['swings_sha256']=='original-swings-hash'
352
  assert saved['product_sha256']==sha256_file(job/'product.json')
353
  assert client.post(url,headers=AUTH).status_code==200
354
  assert len(calls)==2 # Completed retries are idempotent; no extra billed call.
tests/test_swing_clips.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fractions import Fraction
2
+ import json
3
+
4
+ import av
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from baseball_batting.ingest import ingest
9
+ from baseball_batting.storage import sha256_file, read_json, atomic_json
10
+ from baseball_batting.swing_clips import export_swing_clips, SwingsManifest
11
+
12
+
13
+ def ranges(*pairs):
14
+ return {"reps": [{"rep": i+1, "start_frame": a, "end_frame": b,
15
+ "boundary_method": "caller_supplied"} for i, (a, b) in enumerate(pairs)]}
16
+
17
+
18
+ def decoded(path):
19
+ with av.open(str(path)) as container:
20
+ stream = container.streams.video[0]
21
+ assert stream.codec_context.name == "h264"
22
+ assert len(container.streams.audio) == 0
23
+ return [(float(f.pts*f.time_base), f.to_ndarray(format="bgr24")) for f in container.decode(stream)]
24
+
25
+
26
+ def test_exact_multiple_cuts_preserve_variable_playback_cadence_and_rotation(video, tmp_path):
27
+ capture = ingest(video, {"rotation_degrees": 90, "timing": {"kind": "constant_slowdown",
28
+ "factor": 4, "all_captured_frames_retained": True, "source": "Generated clock"}})
29
+ manifest = export_swing_clips(video, capture, ranges((1, 3), (4, 7)), tmp_path/"job")
30
+ assert SwingsManifest.model_validate(manifest).model_dump(mode="json") == manifest
31
+ assert read_json(tmp_path/"job/swings.json") == manifest
32
+ source_pixels = decoded(video)
33
+ for swing in manifest["swings"]:
34
+ clip = swing["clip"]
35
+ assert clip["status"] == "available", clip
36
+ path = tmp_path/"job/swing-clips"/f"{swing['rep']}.mp4"
37
+ frames = decoded(path)
38
+ source = capture["frames"][swing["start_frame"]:swing["end_frame"]+1]
39
+ expected_times = [f["playback_s"]-source[0]["playback_s"] for f in source]
40
+ assert [t for t, _ in frames] == pytest.approx(expected_times, abs=2e-6)
41
+ assert len(frames) == clip["frame_count"] == len(source)
42
+ assert frames[0][1].shape[:2] == (160, 120) # Upright, not container orientation.
43
+ assert clip["width"] == 120 and clip["height"] == 160
44
+ assert np.median(frames[0][1]) == pytest.approx(np.median(source_pixels[swing["start_frame"]][1]), abs=3)
45
+ assert np.median(frames[-1][1]) == pytest.approx(np.median(source_pixels[swing["end_frame"]][1]), abs=3)
46
+ assert clip["sha256"] == sha256_file(path)
47
+ with av.open(str(path)) as container:
48
+ stream = container.streams.video[0]
49
+ assert float(stream.duration*stream.time_base) == pytest.approx(clip["duration_s"], abs=2e-6)
50
+ # The first clip ends at the next sample's timestamp, not a hardcoded FPS.
51
+ assert manifest["swings"][0]["clip"]["duration_s"] == pytest.approx(.150-.033, abs=2e-6)
52
+
53
+
54
+ def test_all_reps_export_in_one_source_pass_and_one_frame_clips_work(video, tmp_path, monkeypatch):
55
+ import baseball_batting.swing_clips as module
56
+ capture = ingest(video, {})
57
+ original = module.iter_frames
58
+ calls = []
59
+ def once(*args, **kwargs):
60
+ calls.append(args[0])
61
+ yield from original(*args, **kwargs)
62
+ monkeypatch.setattr(module, "iter_frames", once)
63
+ manifest = export_swing_clips(video, capture, ranges(*[(i, i) for i in range(8)]), tmp_path/"job")
64
+ assert len(calls) == 1
65
+ assert all(s["clip"]["status"] == "available" and s["clip"]["frame_count"] == 1 for s in manifest["swings"])
66
+ assert len(list((tmp_path/"job/swing-clips").glob("*.mp4"))) == 8
67
+
68
+
69
+ def test_no_fake_clips_missing_timestamps_and_isolated_encoding_failure(video, tmp_path, monkeypatch):
70
+ import baseball_batting.swing_clips as module
71
+ capture = ingest(video, {})
72
+ assert export_swing_clips(video, capture, ranges(), tmp_path/"empty")["swings"] == []
73
+ capture["frames"][0]["pts"] = None
74
+ manifest = export_swing_clips(video, capture, ranges((0, 2), (3, 7)), tmp_path/"missing")
75
+ assert manifest["swings"][0]["clip"]["reason_code"] == "source_timestamps_unavailable"
76
+ assert manifest["swings"][1]["clip"]["status"] == "available"
77
+ capture = ingest(video, {})
78
+ original = module._Writer.write
79
+ def fail_first(self, image, *args):
80
+ if np.median(image) < 30:
81
+ raise OSError("Simulated encoder failure")
82
+ return original(self, image, *args)
83
+ monkeypatch.setattr(module._Writer, "write", fail_first)
84
+ manifest = export_swing_clips(video, capture, ranges((0, 2), (3, 7)), tmp_path/"failure")
85
+ assert manifest["swings"][0]["clip"]["status"] == "unavailable"
86
+ assert manifest["swings"][0]["clip"]["url"] is None
87
+ assert manifest["swings"][1]["clip"]["status"] == "available"
88
+ assert list((tmp_path/"failure/swing-clips").glob(".*tmp*")) == []
89
+
90
+
91
+ def test_odd_dimensions_are_padded_and_export_size_is_bounded(tmp_path):
92
+ path = tmp_path/"odd.mp4"
93
+ with av.open(str(path), "w") as out:
94
+ stream = out.add_stream("libx264", rate=30)
95
+ stream.width, stream.height, stream.pix_fmt = 1301, 733, "yuv444p"
96
+ stream.time_base = stream.codec_context.time_base = Fraction(1, 30)
97
+ for i in range(3):
98
+ frame = av.VideoFrame.from_ndarray(np.full((733, 1301, 3), i*70, np.uint8), format="bgr24")
99
+ frame.pts, frame.time_base = i, Fraction(1,30)
100
+ for packet in stream.encode(frame): out.mux(packet)
101
+ for packet in stream.encode(): out.mux(packet)
102
+ manifest = export_swing_clips(path, ingest(path, {}), ranges((0, 2)), tmp_path/"odd-job")
103
+ clip = manifest["swings"][0]["clip"]
104
+ assert clip["status"] == "available", clip
105
+ assert clip["width"] % 2 == clip["height"] % 2 == 0
106
+ assert max(clip["width"], clip["height"]) <= 1280
107
+ assert len(decoded(tmp_path/"odd-job/swing-clips/1.mp4")) == 3
108
+
109
+
110
+ @pytest.fixture
111
+ def clip_api(video, tmp_path):
112
+ pytest.importorskip("fastapi")
113
+ from fastapi.testclient import TestClient
114
+ from baseball_batting.api import create_app
115
+ from test_api import settings, fake_service, wait_until
116
+ s = settings(tmp_path/"api")
117
+ service = fake_service(s)
118
+ with TestClient(create_app(s, service)) as client:
119
+ wait_until(lambda: service.ready)
120
+ identifier = service.store.create(8)
121
+ job = service.job_directory(identifier)
122
+ job.mkdir()
123
+ manifest = export_swing_clips(video, ingest(video, {}), ranges((0, 3), (4, 7)), job)
124
+ service.store.update(identifier, "completed", swings_hash=sha256_file(job/"swings.json"))
125
+ yield client, service, job, manifest
126
+
127
+
128
+ def test_authenticated_playback_ranges_integrity_and_deletion(clip_api):
129
+ from test_api import AUTH
130
+ client, service, job, manifest = clip_api
131
+ url = manifest["swings"][0]["clip"]["url"]
132
+ data = (job/"swing-clips/1.mp4").read_bytes()
133
+ assert client.get(url).status_code == 401
134
+ assert client.head(url).status_code == 401
135
+ listing = client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH)
136
+ assert listing.json() == manifest
137
+ assert client.get(f"/v1/analyses/{job.name}", headers=AUTH).json()["swings_url"] == f"/v1/analyses/{job.name}/swings"
138
+ full = client.get(url, headers=AUTH)
139
+ assert full.status_code == 200 and full.content == data
140
+ assert full.headers["content-type"] == "video/mp4" and full.headers["accept-ranges"] == "bytes"
141
+ assert client.head(url, headers=AUTH).headers["content-length"] == str(len(data))
142
+ for value, expected, start, end in [("bytes=0-99", data[:100], 0, 99),
143
+ ("bytes=100-", data[100:], 100, len(data)-1), ("bytes=-50", data[-50:], len(data)-50, len(data)-1),
144
+ ("bytes=0-9999999", data, 0, len(data)-1)]:
145
+ response = client.get(url, headers={**AUTH, "Range": value})
146
+ assert response.status_code == 206 and response.content == expected
147
+ assert response.headers["content-range"] == f"bytes {start}-{end}/{len(data)}"
148
+ for value in (f"bytes={len(data)}-", "bytes=5-3", "bytes=-0", "bytes=", "bytes=0-1,3-4"):
149
+ response = client.get(url, headers={**AUTH, "Range": value})
150
+ assert response.status_code == 416 and response.headers["content-range"] == f"bytes */{len(data)}"
151
+ assert client.get(url, headers={**AUTH, "Range": "bytes=0-9", "If-Range": '"old"'}).status_code == 200
152
+ assert client.get(url, headers={**AUTH, "Range": "bytes=0-9", "If-Range": full.headers["etag"]}).status_code == 206
153
+ assert client.get(url.replace("/1/clip", "/99/clip"), headers=AUTH).status_code == 404
154
+ (job/"swing-clips/1.mp4").write_bytes(b"tampered")
155
+ assert client.get(url, headers=AUTH).status_code == 500
156
+ # A broken clip does not block the other swing.
157
+ assert client.get(manifest["swings"][1]["clip"]["url"], headers=AUTH).status_code == 200
158
+ client.delete(f"/v1/analyses/{job.name}", headers=AUTH)
159
+ assert not job.exists() and service.store.get(job.name)["swings_sha256"] is None
160
+ assert client.get(url, headers=AUTH).status_code == 409
161
+
162
+
163
+ def test_unavailable_and_old_jobs_do_not_expose_broken_media_links(clip_api):
164
+ from test_api import AUTH
165
+ client, service, job, manifest = clip_api
166
+ manifest["swings"][0]["clip"].update(status="unavailable", reason_code="clip_export_failed", url=None)
167
+ atomic_json(job/"swings.json", manifest)
168
+ service.store.update(job.name, "completed", swings_hash=sha256_file(job/"swings.json"))
169
+ url = f"/v1/analyses/{job.name}/swings/1/clip"
170
+ response = client.get(url, headers=AUTH)
171
+ assert response.status_code == 409 and response.json()["detail"]["code"] == "clip_export_failed"
172
+ service.store.update(job.name, "completed")
173
+ assert client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH).status_code == 409
174
+ service.store.update(job.name, "completed", swings_hash="wrong")
175
+ assert client.get(f"/v1/analyses/{job.name}/swings", headers=AUTH).status_code == 500
176
+
177
+
178
+ def test_already_open_clip_survives_job_deletion(clip_api):
179
+ import asyncio
180
+ from starlette.requests import Request
181
+ from baseball_batting.media import open_verified_media, media_response
182
+ client, service, job, manifest = clip_api
183
+ clip = manifest["swings"][0]["clip"]
184
+ data = (job/"swing-clips/1.mp4").read_bytes()
185
+ with service.mutation_lock:
186
+ handle, size = open_verified_media(job/"swing-clips/1.mp4", clip["sha256"], clip["size_bytes"])
187
+ service.delete(job.name)
188
+ response = media_response(Request({"type":"http", "method":"GET", "headers":[]}), handle, size, clip["sha256"])
189
+ async def consume():
190
+ return b"".join([block async for block in response.body_iterator])
191
+ assert asyncio.run(consume()) == data
192
+ assert handle.closed
193
+
194
+
195
+ def test_queue_keeps_clips_when_it_removes_the_original_upload(video, tmp_path):
196
+ import shutil
197
+ import sys
198
+ from fastapi.testclient import TestClient
199
+ from baseball_batting.api import create_app
200
+ from baseball_batting.api_jobs import JobService
201
+ from test_api import AUTH, settings, wait_until
202
+ s = settings(tmp_path/"queue")
203
+ def command(job):
204
+ script = ("from pathlib import Path; from baseball_batting.ingest import ingest; "
205
+ "from baseball_batting.swing_clips import export_swing_clips; "
206
+ "from baseball_batting.storage import atomic_json; "
207
+ f"job=Path({str(job)!r}); video=job/'input.mp4'; "
208
+ "export_swing_clips(video,ingest(video,{}),{'reps':[{'rep':1,'start_frame':0,'end_frame':3},"
209
+ "{'rep':2,'start_frame':4,'end_frame':7}]},job); atomic_json(job/'result.json',{})")
210
+ return [sys.executable, "-c", script]
211
+ service = JobService(s, command_factory=command, preflight_command=[sys.executable,"-c","pass"])
212
+ identifier = service.store.create(8)
213
+ job = service.job_directory(identifier)
214
+ job.mkdir()
215
+ shutil.copy2(video, job/"input.mp4")
216
+ service.store.update(identifier, "queued")
217
+ with TestClient(create_app(s, service)) as client:
218
+ wait_until(lambda: service.store.get(identifier)["status"] == "completed")
219
+ wait_until(lambda: not (job/"input.mp4").exists())
220
+ assert service.store.get(identifier)["swings_sha256"] == sha256_file(job/"swings.json")
221
+ listing = client.get(f"/v1/analyses/{identifier}/swings", headers=AUTH).json()
222
+ assert len(listing["swings"]) == 2
223
+ assert all(client.get(s["clip"]["url"], headers=AUTH).status_code == 200 for s in listing["swings"])
224
+
225
+
226
+ def test_published_swing_schema_matches_runtime():
227
+ from pathlib import Path
228
+ assert read_json(Path(__file__).resolve().parents[1]/"docs/swings.schema.json") == SwingsManifest.model_json_schema()