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

Automated Deploy: d53fdc0de8daf42660a59e3228e40730a734f701

Browse files
baseball_batting/api.py CHANGED
@@ -76,7 +76,7 @@ def create_app(settings=None, service=None):
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)
@@ -136,7 +136,8 @@ def create_app(settings=None, service=None):
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",
 
76
  service.start()
77
  try: yield
78
  finally: service.stop()
79
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.6.1", 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)
 
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
+ "overlay": True, "overlay_style": "colab_swing_preview"},
141
  "measurement_validation": "reference_validation_pending", "coaching": coaching_available(),
142
  "swing_coach": {"upload_route": "/v1/swing-coach/analyses",
143
  "product_route": "/v1/analyses/{job_id}/product",
baseball_batting/api_worker.py CHANGED
@@ -160,7 +160,7 @@ def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_durati
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
 
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, result=result)
164
  if options.coaching_mode != "disabled":
165
  progress("coaching", n, n)
166
  from .product import build_product
baseball_batting/preview_overlay.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared Colab/API inspection overlay; rendering never changes measurements."""
2
+ import numpy as np
3
+ from .reports import BODY_EDGES
4
+
5
+
6
+ def draw_points(image, points, rep, index, events, extra_points=None, projection_3d=None, body_height_px=None):
7
+ import cv2
8
+ image = image.copy()
9
+ display_scale = max(1., image.shape[1]/960)
10
+ # Unknown/nonfinite joints remain absent rather than being filled in.
11
+ def supported(point):
12
+ if point is None: return None
13
+ value = np.asarray(point, dtype=float)
14
+ return point if value.shape == (2,) and np.isfinite(value).all() and np.max(np.abs(value)) < 2**30 else None
15
+ points = [supported(p) for p in points]
16
+ points = (points + [None]*17)[:17]
17
+ if extra_points is not None:
18
+ extra_points = [supported(p) for p in extra_points]
19
+ thickness = max(1, round(2*display_scale))
20
+ cv2.rectangle(image, (0, 0), (image.shape[1], int((56 if projection_3d is not None else 32)*display_scale)), (20, 20, 20), -1)
21
+ for a, b in BODY_EDGES:
22
+ if points[a] is not None and points[b] is not None:
23
+ cv2.line(image, tuple(np.rint(points[a]).astype(int)),
24
+ tuple(np.rint(points[b]).astype(int)), (80, 230, 90), thickness)
25
+ for point in points:
26
+ if point is not None:
27
+ cv2.circle(image, tuple(np.rint(point).astype(int)), max(3, round(3*display_scale)), (80, 230, 90), -1)
28
+ if extra_points is not None:
29
+ for j, point in enumerate(extra_points):
30
+ if point is None: continue
31
+ pixel = tuple(np.rint(point).astype(int))
32
+ ankle = points[15 if j < 3 else 16]
33
+ if ankle is not None:
34
+ cv2.line(image, tuple(np.rint(ankle).astype(int)), pixel, (0, 180, 255), thickness)
35
+ cv2.circle(image, pixel, max(4, round(4*display_scale)), (0, 180, 255), -1)
36
+ if projection_3d is not None:
37
+ from baseball_batting.pose_agreement import AGREEMENT_LIMIT_PCT
38
+ for j, point in enumerate(projection_3d):
39
+ if j >= len(points) or supported(point) is None: continue
40
+ pixel = tuple(np.rint(point).astype(int))
41
+ cv2.circle(image, pixel, 5, (255, 90, 230), 2)
42
+ if points[j] is not None:
43
+ distance = np.linalg.norm(np.asarray(point)-points[j])
44
+ conflict = body_height_px and distance/body_height_px*100 > AGREEMENT_LIMIT_PCT
45
+ color = (50, 50, 255) if conflict else (180, 120, 180)
46
+ cv2.line(image, tuple(np.rint(points[j]).astype(int)), pixel, color, 1)
47
+ cv2.circle(image, tuple(np.rint(points[j]).astype(int)), 3, (80, 230, 90), -1)
48
+ if conflict:
49
+ from baseball_batting.pose_agreement import COCO_NAMES
50
+ label = f"{COCO_NAMES[j]} {distance/body_height_px*100:.1f}%"
51
+ cv2.putText(image, label, (pixel[0]+int(6*display_scale), pixel[1]), cv2.FONT_HERSHEY_SIMPLEX,
52
+ .4*display_scale, color, max(1, round(display_scale)), cv2.LINE_AA)
53
+ cv2.putText(image, "Green: raw 2D | Purple: 3D projection | Red: disagreement >5% stature",
54
+ (int(8*display_scale), int(48*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .45*display_scale,
55
+ (255, 255, 255), max(1, round(display_scale)), cv2.LINE_AA)
56
+ labels = []
57
+ for name, event in events.items():
58
+ if event.get("frame") != index: continue
59
+ method = event.get("method", "")
60
+ label = "contact proxy" if name == "contact" and ("proxy" in method or "arm_extension" in method) else name.replace("_", " ")
61
+ labels.append(label)
62
+ text = f"Swing candidate {rep} | frame {index}"
63
+ if labels: text += " | estimated " + ", ".join(labels)
64
+ cv2.putText(image, text, (int(8*display_scale), int(24*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .55*display_scale,
65
+ (255, 255, 255), max(1, round(2*display_scale)), cv2.LINE_AA)
66
+ return image
baseball_batting/product.html CHANGED
@@ -19,7 +19,7 @@
19
  <details><summary>Open an existing analysis</summary><label for="jobId">Job ID</label><input id="jobId" maxlength="32" autocomplete="off"><button id="load" type="button">Open result</button><small>Use the job ID returned by an upload to reopen its result or follow its progress.</small></details>
20
  </form>
21
  <p id="state" role="status" aria-live="polite"></p><button id="cancel" hidden>Cancel analysis</button>
22
- <section id="results" hidden><p class="warning">Measurements are estimates. Video feedback has not been validated for accuracy. A missing value means the evidence did not support it.</p><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}
 
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>Clips show the body skeleton, foot points and estimated moments. Contact proxy means estimated arm extension, not confirmed ball contact. 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}
baseball_batting/swing_clips.py CHANGED
@@ -14,6 +14,7 @@ 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)
@@ -31,6 +32,7 @@ class Clip(BaseModel):
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
 
@@ -72,7 +74,8 @@ class SwingsManifest(BaseModel):
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):
@@ -154,10 +157,18 @@ class _Writer:
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"],
@@ -214,6 +225,11 @@ def export_swing_clips(video, capture, track, job, *, progress=None):
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()
@@ -223,7 +239,7 @@ def export_swing_clips(video, capture, track, job, *, progress=None):
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:
 
14
 
15
  from .ingest import iter_frames
16
  from .storage import atomic_json, sha256_file
17
+ from .preview_overlay import draw_points
18
 
19
  LOG = logging.getLogger(__name__)
20
  TIME_BASE = Fraction(1, 1_000_000)
 
32
  width: int | None = Field(default=None, ge=1)
33
  height: int | None = Field(default=None, ge=1)
34
  has_audio: Literal[False] = False
35
+ overlay: bool = False
36
  size_bytes: int | None = Field(default=None, gt=0)
37
  sha256: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")
38
 
 
74
  swings: list[Swing] = Field(max_length=100)
75
  notice: str = ("Swing boundaries are detection candidates or supplied ranges, not validated labels. "
76
  "Clips preserve recorded playback timing, are upright, resized to at most 1280 pixels "
77
+ "on the longest side, and have no audio. New clips include the Colab body/foot overlay "
78
+ "and estimated event labels; a body contact proxy is not confirmed ball contact.")
79
 
80
  @model_validator(mode="after")
81
  def ordered(self):
 
157
  LOG.warning("Could not finalize failed clip output")
158
 
159
 
160
+ def export_swing_clips(video, capture, track, job, *, progress=None, result=None, overlay=True):
161
  """One decode pass for all reps. A failed clip never erases measurement data."""
162
  job = Path(job)
163
  frames = capture["frames"]
164
+ pose_frames = track.get("frames", {})
165
+ reps = {r["rep"]: r for r in track["reps"]}
166
+ result = result or {}
167
+ projections = {r["frame"]: r for r in result.get("experimental_body3d", {}).get("frames", [])}
168
+ body_height = result.get("measurement_method", {}).get("body_height_px")
169
+ def frame_points(key, index, fallback):
170
+ rows = pose_frames.get(key, [])
171
+ return rows[index] if index < len(rows) and rows[index] is not None else fallback
172
  def playback(index):
173
  return frames[index]["playback_s"] if 0 <= index < len(frames) else None
174
  swings = [Swing(rep=r["rep"], start_frame=r["start_frame"], end_frame=r["end_frame"],
 
225
  raise ClipError("last_frame_duration_unavailable")
226
  if duration <= 0:
227
  raise ClipError("source_timestamps_invalid")
228
+ if overlay:
229
+ image = draw_points(image, frame_points("kp", index, [None]*17),
230
+ swing.rep, index, reps[swing.rep].get("events", {}),
231
+ frame_points("kp_extra", index, None),
232
+ projections.get(index, {}).get("projection"), body_height)
233
  writer.write(image, timeline[local], duration)
234
  if index == swing.end_frame:
235
  writer.finish()
 
239
  url=f"/v1/analyses/{job.name}/swings/{swing.rep}/clip",
240
  duration_s=writer.end*float(TIME_BASE), frame_count=writer.count,
241
  width=writer.width, height=writer.height, size_bytes=final.stat().st_size,
242
+ sha256=sha256_file(final), overlay=overlay)
243
  writer = None
244
  position += 1
245
  except Exception as exc:
docs/APP_API_INTEGRATION.md CHANGED
@@ -231,6 +231,7 @@ are illustrative, not a real downloadable recording:
231
  "width": 1280,
232
  "height": 720,
233
  "has_audio": false,
 
234
  "size_bytes": 524288,
235
  "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
236
  }
@@ -245,8 +246,15 @@ Build the swing list from `swings`, ordered as returned. Labels are “Swing 1
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
@@ -290,6 +298,10 @@ notice: boundary/timing/format explanation
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
 
231
  "width": 1280,
232
  "height": 720,
233
  "has_audio": false,
234
+ "overlay": true,
235
  "size_bytes": 524288,
236
  "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
237
  }
 
246
  or `caller_declared_single_swing` for the current engine.
247
  - Automatic cuts are candidates. Detection may miss/merge movements; clips do
248
  not establish that every actual swing was found.
249
+ - New clips use the same overlay renderer as the Colab `previews` folder:
250
+ green body points/skeleton, orange toe/heel points, source frame numbers and
251
+ estimated event labels. `clip.overlay: true` identifies annotated previews.
252
+ A body-based contact event is labelled **estimated contact proxy**; it is not
253
+ confirmed bat-ball impact. Missing joints/events are not drawn or invented.
254
+ If a selected 3D backend produced projections, the clip also shows purple
255
+ projected joints and red disagreement connectors at those sampled frames.
256
+ The default 2D backend requires no SAM to draw the body skeleton.
257
+ - The clips are upright H.264 MP4s, resized to at most 1280 pixels on the longest side,
258
  with at most one pixel of padding for odd dimensions. They have **no audio**.
259
  - Every source frame in the range is retained. Each clip starts at playback
260
  time zero and preserves the source's variable frame spacing and playback
 
298
  New jobs on the legacy upload routes also create this manifest and clips.
299
  Older completed jobs cannot create clips after their original upload was
300
  removed. Their swing endpoint returns `409`; upload again to create clips.
301
+ Clips from before the overlay update stay plain (`overlay: false` or missing).
302
+ Upload again to generate annotated previews. Existing `clip.url` playback paths
303
+ and authentication are unchanged; the mobile app does not need to draw joints.
304
+ Gemini still receives unannotated original images, not these display overlays.
305
 
306
  If a particular clip cannot be exported, its rep remains in `swings` with
307
  `clip.status: "unavailable"`, a `reason_code`, and `url: null`. Hide that rep's
docs/SWING_COACH_PRODUCT.md CHANGED
@@ -6,6 +6,10 @@ The standalone coach service and the existing engine routes still work.
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
 
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
+ These clips now include the same skeleton, foot points and estimated event
10
+ labels as the Colab previews (`clip.overlay: true`). The endpoint and app
11
+ playback flow stay the same. Body contact proxies are explicitly labelled;
12
+ unannotated original images still provide the Gemini review evidence.
13
 
14
  The full flow is: upload one video → detect swings and body movement → track bat
15
  and ball when possible → build measurements → run the coach → optionally review
docs/swings.schema.json CHANGED
@@ -99,6 +99,11 @@
99
  "title": "Has Audio",
100
  "type": "boolean"
101
  },
 
 
 
 
 
102
  "size_bytes": {
103
  "anyOf": [
104
  {
@@ -220,7 +225,7 @@
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
  }
 
99
  "title": "Has Audio",
100
  "type": "boolean"
101
  },
102
+ "overlay": {
103
+ "default": false,
104
+ "title": "Overlay",
105
+ "type": "boolean"
106
+ },
107
  "size_bytes": {
108
  "anyOf": [
109
  {
 
225
  "type": "array"
226
  },
227
  "notice": {
228
+ "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. New clips include the Colab body/foot overlay and estimated event labels; a body contact proxy is not confirmed ball contact.",
229
  "title": "Notice",
230
  "type": "string"
231
  }
tests/test_swing_clips.py CHANGED
@@ -226,3 +226,73 @@ def test_queue_keeps_clips_when_it_removes_the_original_upload(video, tmp_path):
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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
229
+
230
+
231
+ def test_encoded_api_clip_shows_colab_skeleton_feet_and_optional_3d(video, tmp_path):
232
+ from copy import deepcopy
233
+ from test_colab_2d import preview_result
234
+ result = preview_result(video)
235
+ points = result['pose_track']['frames']['kp'][2]
236
+ points[0], points[5], points[7], points[9], points[15] = [50,70], [35,45], [65,65], [85,60], [50,80]
237
+ result['pose_track']['frames']['kp_extra'] = [[None]*6 for _ in range(8)]
238
+ result['pose_track']['frames']['kp_extra'][2][0] = [58,90]
239
+ result['pose_track']['reps'][0]['events'] = {'contact': {
240
+ 'frame':2,'method':'primary_swing_lead_arm_extension_proxy_v2'}}
241
+ projection = [None]*17; projection[0] = [70,70]
242
+ result['experimental_body3d'] = {'frames':[{'frame':2,'projection':projection}]}
243
+ result['measurement_method'] = {'body_height_px':100}
244
+ original = deepcopy(result)
245
+ manifest = export_swing_clips(video, ingest(video, {}), result['pose_track'], tmp_path/'annotated', result=result)
246
+ assert result == original # Overlays do not change measurements or event labels.
247
+ assert manifest['swings'][0]['clip']['overlay'] is True
248
+ assert manifest['swings'][0]['clip']['status'] == 'available'
249
+ frames = decoded(tmp_path/'annotated/swing-clips/1.mp4')
250
+ image = frames[0][1]
251
+ assert image[70,50,1] > 150 # Green raw nose point at the source frame's coordinate.
252
+ assert image[55,50,1] > 150 # Green shoulder/elbow skeleton edge.
253
+ foot = image[90,58]
254
+ assert foot[2] > int(foot[1])+20 and foot[1] > 120 # Orange toe point.
255
+ assert image[70,60,2] > 170 # Red disagreement connector.
256
+ assert image[70,75,0] > 150 # Purple 3D projected point.
257
+ # Source frame 3 has no body points: frame 2's skeleton is not carried forward.
258
+ assert frames[1][1][70,50,1] < 120
259
+
260
+
261
+ def test_shared_overlay_scales_with_upright_frames_and_labels_contact_proxy(video, tmp_path, monkeypatch):
262
+ from copy import deepcopy
263
+ import cv2
264
+ from test_colab_2d import preview_result
265
+ from baseball_batting.preview_overlay import draw_points
266
+ from tools.preview_swing_ranges import draw_points as colab_draw_points
267
+ assert draw_points is colab_draw_points
268
+ result = preview_result(video, 90)
269
+ result['pose_track']['frames']['kp'][2][0] = [50,70]
270
+ result['pose_track']['reps'][0]['events'] = {'contact':{'frame':2,'method':'arm_extension_proxy'}}
271
+ original = deepcopy(result)
272
+ labels = []
273
+ put_text = cv2.putText
274
+ def record(image, text, *args, **kw):
275
+ labels.append(text)
276
+ return put_text(image,text,*args,**kw)
277
+ monkeypatch.setattr(cv2,'putText',record)
278
+ manifest = export_swing_clips(video, ingest(video, {'rotation_degrees':90}),
279
+ result['pose_track'],tmp_path/'rotated',result=result)
280
+ assert result == original
281
+ assert any('estimated contact proxy' in label for label in labels)
282
+ frames = decoded(tmp_path/'rotated/swing-clips/1.mp4')
283
+ assert frames[0][1].shape[:2] == (160,120)
284
+ assert frames[0][1][70,50,1] > 150
285
+ plain = export_swing_clips(video,ingest(video,{'rotation_degrees':90}),
286
+ result['pose_track'],tmp_path/'plain',result=result,overlay=False)
287
+ assert plain['swings'][0]['clip']['overlay'] is False
288
+ assert decoded(tmp_path/'plain/swing-clips/1.mp4')[0][1][70,50,1] < 100
289
+
290
+
291
+ def test_missing_overlay_points_do_not_fabricate_a_skeleton():
292
+ from baseball_batting.preview_overlay import draw_points
293
+ source = np.zeros((160,120,3),np.uint8)
294
+ points = [None]*17; points[0] = [float('nan'),70]
295
+ extra = [None]*6; extra[0] = [float('inf'),90]
296
+ image = draw_points(source,points,1,0,{},extra_points=extra)
297
+ assert not np.any(source)
298
+ assert not np.any(image[40:])
tools/preview_swing_ranges.py CHANGED
@@ -4,60 +4,11 @@ from fractions import Fraction
4
  import math
5
  from pathlib import Path
6
  import os
7
- import numpy as np
8
  from baseball_batting.ingest import iter_frames
9
- from baseball_batting.reports import BODY_EDGES
10
  from baseball_batting.storage import atomic_json, read_json, sha256_file
11
 
12
 
13
- def draw_points(image, points, rep, index, events, extra_points=None, projection_3d=None, body_height_px=None):
14
- import cv2
15
- image = image.copy()
16
- display_scale = max(1., image.shape[1]/960)
17
- cv2.rectangle(image, (0, 0), (image.shape[1], int((56 if projection_3d is not None else 32)*display_scale)), (20, 20, 20), -1)
18
- for a, b in BODY_EDGES:
19
- if points[a] is not None and points[b] is not None:
20
- cv2.line(image, tuple(np.rint(points[a]).astype(int)),
21
- tuple(np.rint(points[b]).astype(int)), (80, 230, 90), 2)
22
- for point in points:
23
- if point is not None:
24
- cv2.circle(image, tuple(np.rint(point).astype(int)), 3, (80, 230, 90), -1)
25
- if extra_points is not None:
26
- for j, point in enumerate(extra_points):
27
- if point is None: continue
28
- pixel = tuple(np.rint(point).astype(int))
29
- ankle = points[15 if j < 3 else 16]
30
- if ankle is not None:
31
- cv2.line(image, tuple(np.rint(ankle).astype(int)), pixel, (0, 180, 255), 2)
32
- cv2.circle(image, pixel, 4, (0, 180, 255), -1)
33
- if projection_3d is not None:
34
- from baseball_batting.pose_agreement import AGREEMENT_LIMIT_PCT
35
- for j, point in enumerate(projection_3d):
36
- if point is None or not np.isfinite(point).all(): continue
37
- pixel = tuple(np.rint(point).astype(int))
38
- cv2.circle(image, pixel, 5, (255, 90, 230), 2)
39
- if points[j] is not None:
40
- distance = np.linalg.norm(np.asarray(point)-points[j])
41
- conflict = body_height_px and distance/body_height_px*100 > AGREEMENT_LIMIT_PCT
42
- color = (50, 50, 255) if conflict else (180, 120, 180)
43
- cv2.line(image, tuple(np.rint(points[j]).astype(int)), pixel, color, 1)
44
- cv2.circle(image, tuple(np.rint(points[j]).astype(int)), 3, (80, 230, 90), -1)
45
- if conflict:
46
- from baseball_batting.pose_agreement import COCO_NAMES
47
- label = f"{COCO_NAMES[j]} {distance/body_height_px*100:.1f}%"
48
- cv2.putText(image, label, (pixel[0]+int(6*display_scale), pixel[1]), cv2.FONT_HERSHEY_SIMPLEX,
49
- .4*display_scale, color, max(1, round(display_scale)), cv2.LINE_AA)
50
- cv2.putText(image, "Green: raw 2D | Purple: 3D projection | Red: disagreement >5% stature",
51
- (int(8*display_scale), int(48*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .45*display_scale,
52
- (255, 255, 255), max(1, round(display_scale)), cv2.LINE_AA)
53
- labels = [name for name, event in events.items() if event["frame"] == index]
54
- text = f"Swing candidate {rep} | frame {index}"
55
- if labels: text += " | estimated " + ", ".join(labels)
56
- cv2.putText(image, text, (int(8*display_scale), int(24*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .55*display_scale,
57
- (255, 255, 255), max(1, round(2*display_scale)), cv2.LINE_AA)
58
- return image
59
-
60
-
61
  def export_previews(video, result, destination, max_clips=10, overlay=True):
62
  import av
63
  import cv2
 
4
  import math
5
  from pathlib import Path
6
  import os
 
7
  from baseball_batting.ingest import iter_frames
8
+ from baseball_batting.preview_overlay import draw_points
9
  from baseball_batting.storage import atomic_json, read_json, sha256_file
10
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  def export_previews(video, result, destination, max_clips=10, overlay=True):
13
  import av
14
  import cv2