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

Automated Deploy: 006019bfd20b8e3208f90c1e8c91601248bd7447

Browse files
.dockerignore CHANGED
@@ -1,8 +1,10 @@
1
  *
2
  !Dockerfile
 
3
  !requirements-core.txt
4
  !requirements-api.txt
5
  !requirements-api-gpu.txt
 
6
  !pyproject.toml
7
  !baseball_batting/
8
  !baseball_batting/*.py
@@ -10,6 +12,9 @@
10
  !configs/*.yaml
11
  !tools/
12
  !tools/setup_api_models.py
 
 
 
13
  !tools/__init__.py
14
  !docs/
15
  !docs/api-result.schema.json
 
1
  *
2
  !Dockerfile
3
+ !Dockerfile.sam
4
  !requirements-core.txt
5
  !requirements-api.txt
6
  !requirements-api-gpu.txt
7
+ !requirements-sam.txt
8
  !pyproject.toml
9
  !baseball_batting/
10
  !baseball_batting/*.py
 
12
  !configs/*.yaml
13
  !tools/
14
  !tools/setup_api_models.py
15
+ !tools/setup_full_worker.py
16
+ !tools/setup_sam_api_worker.py
17
+ !tools/register_sam_api_worker.py
18
  !tools/__init__.py
19
  !docs/
20
  !docs/api-result.schema.json
BUILD_STATUS.md CHANGED
@@ -1,8 +1,26 @@
1
  # Build status
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  Updated: 2026-10-11. The initial backend build has now been followed by investigation of two supplied Colab result archives. The user-edited plans remain unchanged. Implementation, runtime qualification and measurement/coaching validation are separate outcomes.
4
 
5
- ## 2D GPU API and Docker deployment
6
 
7
  The API is prepared for the requested Linux NVIDIA GPU server with Docker. It directly runs the person detector and RTMW-x pose adapter, exports COCO-17 body points and six foot points, and disables all SAM/temporal/anatomical 3D and coaching stages. Its new 2D calculation layer produces estimated swing measurements; the friend's separate coach agent owns problems, priority, drills, explanations and progress. The Colab notebook remains a separate entry point.
8
 
 
1
  # Build status
2
 
3
+ ## Nine measurements and optional 3D — 2026-10-11
4
+
5
+ The GPU API now accepts `measurement_backend: "2d" | "rtmw3d" | "sam3d"`. [batting_measurements_test.ipynb](notebooks/batting_measurements_test.ipynb) provides the same choice in step 3. The original 2D-only notebook remains separate. [NINE_MEASUREMENTS.md](docs/NINE_MEASUREMENTS.md) specifies calculations, camera assumptions, rejection gates and model comparison.
6
+
7
+ All nine entries have conditional calculation paths: the existing six distance/timing/head fields plus 3D knee, trunk and horizontal hip/shoulder landmark angles. The existing 2D projected knee remains available in 2D mode. The coach payload keeps its nine keys and `est` labels; sparse unvalidated 3D points and per-metric sensitivity diagnostics stay in the full result. Unknown capture timing, missing events, moving-camera restrictions and insufficient geometry still cause nulls.
8
+
9
+ 3D requests at most five frames per contact/plant event, at most 300 selected frames overall. SAM uses body-only inference in a separate interpreter, with a 600-second subprocess timeout and no OpenSim/temporal fitting. The lightweight model uses the same event windows. Model setup and initialization remain separate costs; target GPU performance is not yet established.
10
+
11
+ Executed evidence:
12
+
13
+ - **154 tests passed, 4 skipped**, one existing Starlette/httpx deprecation warning. This includes independent constructed 3D angles and a constructed swing returning all nine values, units/mapping, left/right sign, camera rotation, image resizing, score decoding, missing support/depth/length rejection, physical variable-cadence timing, budget selection, both JSON schemas, notebook generation, Docker COPY context checks, HTTP backend selection and failure without CPU substitution. Synthetic cases are not accuracy validation.
14
+ - The pinned 369,330,857-byte RTMW3D ONNX artifact was downloaded and SHA-256 verified. Real CPU ONNX inference returned the expected 133 native joints with three SimCC distributions; the adapter exports COCO-17 in consistent camera metre coordinates. It matches the provider's XY confidence scoring and keeps depth response separate.
15
+ - A local CPU replay of five event frames (77–81) from the supplied outdoor video completed in **3.353 seconds**, including model initialization and sequential decoding to those frames. Saved GPU 2D observations were reused; GPU inference was not rerun locally. It produced an experimental trunk landmark estimate (-23.586°), with nearby-frame sensitivity 2.374° and camera-prior sensitivity 0.381°. The knee was withheld because nearby-frame sensitivity reached 39.451°. Other missing fields remain unsupported by this moving-camera, unknown-clock recording. This demonstrates execution and rejection behavior, not correctness of that angle or a target-GPU benchmark.
16
+ - The base/SAM Compose overlay parses with the correct build context, asset mount and worker-record path. The local Docker daemon did not respond, so image builds were not executed.
17
+
18
+ Still to execute: the new notebook on Colab CUDA for both models, the optional SAM image on a target GPU with approved model assets, and independent real batting measurement/error validation. All methods continue to report `reference_validation_pending`. No high/medium confidence or accuracy guarantees are claimed.
19
+
20
+
21
  Updated: 2026-10-11. The initial backend build has now been followed by investigation of two supplied Colab result archives. The user-edited plans remain unchanged. Implementation, runtime qualification and measurement/coaching validation are separate outcomes.
22
 
23
+ ## Initial 2D GPU API and Docker delivery
24
 
25
  The API is prepared for the requested Linux NVIDIA GPU server with Docker. It directly runs the person detector and RTMW-x pose adapter, exports COCO-17 body points and six foot points, and disables all SAM/temporal/anatomical 3D and coaching stages. Its new 2D calculation layer produces estimated swing measurements; the friend's separate coach agent owns problems, priority, drills, explanations and progress. The Colab notebook remains a separate entry point.
26
 
Dockerfile CHANGED
@@ -12,11 +12,11 @@ RUN python -m pip install --only-binary=:all: -r requirements-api-gpu.txt \
12
  COPY pyproject.toml ./
13
  COPY baseball_batting ./baseball_batting
14
  COPY configs ./configs
15
- COPY tools/setup_api_models.py ./tools/setup_api_models.py
16
  COPY tools/__init__.py ./tools/__init__.py
17
  COPY docs/api-result.schema.json ./docs/api-result.schema.json
18
  COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
19
- RUN python -m tools.setup_api_models --output /opt/models \
20
  && python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \
21
  && groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \
22
  && mkdir -p /data && chown baseball:baseball /data
 
12
  COPY pyproject.toml ./
13
  COPY baseball_batting ./baseball_batting
14
  COPY configs ./configs
15
+ COPY tools/setup_api_models.py tools/setup_full_worker.py tools/setup_sam_api_worker.py tools/register_sam_api_worker.py ./tools/
16
  COPY tools/__init__.py ./tools/__init__.py
17
  COPY docs/api-result.schema.json ./docs/api-result.schema.json
18
  COPY docs/coach-payload.schema.json ./docs/coach-payload.schema.json
19
+ RUN python -m tools.setup_api_models --output /opt/models --with-3d \
20
  && python -c "from rtmlib.tools.pose_estimation.pre_processings import top_down_affine; from baseball_batting.api import create_app" \
21
  && groupadd --gid 1000 baseball && useradd --uid 1000 --gid baseball --create-home baseball \
22
  && mkdir -p /data && chown baseball:baseball /data
Dockerfile.sam ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build the ordinary image first; this adds an isolated SAM runtime.
2
+ # SAM weights are mounted at runtime, never embedded using a build-time token.
3
+ ARG BASE_IMAGE=baseball-engine-api:local
4
+ FROM ${BASE_IMAGE}
5
+ USER root
6
+ RUN apt-get update && apt-get install -y --no-install-recommends git build-essential libgl1 libegl1 libglib2.0-0 \
7
+ && rm -rf /var/lib/apt/lists/*
8
+ COPY requirements-sam.txt ./
9
+ RUN python -m venv /opt/sam-runtime \
10
+ && /opt/sam-runtime/bin/python -m pip install torch==2.9.1 torchvision==0.24.1 --index-url https://download.pytorch.org/whl/cu128 \
11
+ && /opt/sam-runtime/bin/python -m pip install -r requirements-core.txt -r requirements-sam.txt \
12
+ && /opt/sam-runtime/bin/python -m pip install git+https://github.com/facebookresearch/detectron2.git@a1ce2f9 --no-build-isolation --no-deps \
13
+ && git clone https://github.com/facebookresearch/sam-3d-body.git /opt/sam-source \
14
+ && git -C /opt/sam-source checkout b5c765a0d89d789985e186d396315e7590887b94 \
15
+ && chown -R baseball:baseball /opt/sam-source
16
+ ENV BASEBALL_SAM_WORKER_RECORD=/opt/sam-assets/sam-api-worker.json
17
+ USER baseball
baseball_batting/api.py CHANGED
@@ -3,6 +3,7 @@ from contextlib import asynccontextmanager
3
  import asyncio
4
  import hmac
5
  import json
 
6
  from pathlib import Path
7
  import shutil
8
  from typing import Annotated
@@ -69,8 +70,8 @@ def create_app(settings=None, service=None):
69
  service.start()
70
  try: yield
71
  finally: service.stop()
72
- app = FastAPI(title="Baseball 2D GPU API", version="1.1.0", lifespan=lifespan,
73
- description="Batting points and estimated swing measurements for a separate coach agent. GPU required; all 3D stages disabled.")
74
  app.state.service = service
75
  app.add_middleware(UploadGuard, settings=settings, service=service)
76
 
@@ -97,7 +98,19 @@ def create_app(settings=None, service=None):
97
 
98
  @app.get("/v1/capabilities", dependencies=[Depends(authenticated)])
99
  def capabilities():
100
- return {"discipline": "hitting", "device": "cuda", "body_3d": False,
 
 
 
 
 
 
 
 
 
 
 
 
101
  "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
102
  "automatic_events": True, "swing_metrics": True, "estimated_only": True,
103
  "measurement_validation": "reference_validation_pending", "coaching": False,
 
3
  import asyncio
4
  import hmac
5
  import json
6
+ import os
7
  from pathlib import Path
8
  import shutil
9
  from typing import Annotated
 
70
  service.start()
71
  try: yield
72
  finally: service.stop()
73
+ app = FastAPI(title="Baseball GPU Measurement API", version="1.2.0", lifespan=lifespan,
74
+ description="Batting points and nine conditional measurements. Select 2D, RTMW3D or isolated SAM event inference. GPU required; accuracy validation pending.")
75
  app.state.service = service
76
  app.add_middleware(UploadGuard, settings=settings, service=service)
77
 
 
98
 
99
  @app.get("/v1/capabilities", dependencies=[Depends(authenticated)])
100
  def capabilities():
101
+ sam_record = os.environ.get("BASEBALL_SAM_WORKER_RECORD")
102
+ sam_configured = False
103
+ if sam_record and Path(sam_record).is_file():
104
+ try:
105
+ record = read_json(sam_record)
106
+ sam_configured = all(Path(record[key]).exists() for key in
107
+ ("worker_python", "sam_repo", "sam_checkpoint", "sam_config", "mhr_path"))
108
+ except (ValueError, KeyError, TypeError, OSError): pass
109
+ return {"discipline": "hitting", "device": "cuda", "body_3d": True,
110
+ "measurement_backends": {"2d": {"configured": True},
111
+ "rtmw3d": {"configured": (settings.model_root/"body_pose_3d/model.onnx").is_file()},
112
+ "sam3d": {"configured": sam_configured}},
113
+ "body_3d_scope": "experimental sparse contact/foot-plant windows; actual CUDA checked during inference",
114
  "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True,
115
  "automatic_events": True, "swing_metrics": True, "estimated_only": True,
116
  "measurement_validation": "reference_validation_pending", "coaching": False,
baseball_batting/api_contract.py CHANGED
@@ -1,4 +1,4 @@
1
- """Public inputs: clients cannot supply paths, models, devices or 3D switches."""
2
  from typing import Literal
3
  from pydantic import BaseModel, ConfigDict, Field, model_validator
4
 
@@ -37,6 +37,16 @@ class RepRange(BaseModel):
37
  return self
38
 
39
 
 
 
 
 
 
 
 
 
 
 
40
  class AnalysisInput(BaseModel):
41
  model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
42
  discipline: Literal["hitting"] = "hitting"
@@ -48,12 +58,23 @@ class AnalysisInput(BaseModel):
48
  body_height_source: str | None = Field(default=None, min_length=1, max_length=512)
49
  rotation_degrees: Literal[0, 90, 180, 270] | None = None
50
  camera_stability: Literal["unknown", "fixed_verified", "moving"] = "unknown"
 
 
 
 
 
 
51
  timing: TimingInput = Field(default_factory=TimingInput)
52
  single_swing: bool = False
53
  reps: list[RepRange] = Field(default_factory=list, max_length=100)
54
 
55
  @model_validator(mode="after")
56
  def ranges(self):
 
 
 
 
 
57
  if self.body_height_px is not None and not (self.body_height_source and self.body_height_source.strip()):
58
  raise ValueError("A supplied image height needs a source description")
59
  if self.single_swing and self.reps:
@@ -69,4 +90,6 @@ class AnalysisInput(BaseModel):
69
  value["rotation_degrees"] = self.rotation_degrees
70
  if self.handedness:
71
  value["handedness"] = self.handedness
 
 
72
  return value
 
1
+ """Public recording inputs. Model paths and worker executables stay server-side."""
2
  from typing import Literal
3
  from pydantic import BaseModel, ConfigDict, Field, model_validator
4
 
 
37
  return self
38
 
39
 
40
+ class CameraInput(BaseModel):
41
+ """Intrinsics refer to the upright decoded image, after rotation."""
42
+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
43
+ fx: float = Field(gt=0)
44
+ fy: float = Field(gt=0)
45
+ cx: float = Field(ge=0)
46
+ cy: float = Field(ge=0)
47
+ source: str = Field(min_length=1, max_length=512)
48
+
49
+
50
  class AnalysisInput(BaseModel):
51
  model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
52
  discipline: Literal["hitting"] = "hitting"
 
58
  body_height_source: str | None = Field(default=None, min_length=1, max_length=512)
59
  rotation_degrees: Literal[0, 90, 180, 270] | None = None
60
  camera_stability: Literal["unknown", "fixed_verified", "moving"] = "unknown"
61
+ measurement_backend: Literal["2d", "rtmw3d", "sam3d"] = "2d"
62
+ height_m: float | None = Field(default=None, ge=.5, le=2.5)
63
+ camera: CameraInput | None = None
64
+ root_depth_m: float | None = Field(default=None, gt=.5, le=100)
65
+ root_depth_source: str | None = Field(default=None, min_length=1, max_length=512)
66
+ camera_up: tuple[float, float, float] = (0., -1., 0.)
67
  timing: TimingInput = Field(default_factory=TimingInput)
68
  single_swing: bool = False
69
  reps: list[RepRange] = Field(default_factory=list, max_length=100)
70
 
71
  @model_validator(mode="after")
72
  def ranges(self):
73
+ import math
74
+ if self.root_depth_m is not None and not (self.root_depth_source and self.root_depth_source.strip()):
75
+ raise ValueError("A supplied pelvis depth needs a source description")
76
+ if sum(x*x for x in self.camera_up) < .5 or not all(math.isfinite(x) for x in self.camera_up):
77
+ raise ValueError("camera_up must be a finite nonzero direction in camera coordinates")
78
  if self.body_height_px is not None and not (self.body_height_source and self.body_height_source.strip()):
79
  raise ValueError("A supplied image height needs a source description")
80
  if self.single_swing and self.reps:
 
90
  value["rotation_degrees"] = self.rotation_degrees
91
  if self.handedness:
92
  value["handedness"] = self.handedness
93
+ if self.height_m is not None:
94
+ value["height_m"] = self.height_m
95
  return value
baseball_batting/api_worker.py CHANGED
@@ -1,4 +1,4 @@
1
- """GPU-only service worker. Never imports SAM, torch, OpenSim or coaching."""
2
  import argparse
3
  from pathlib import Path
4
  import time
@@ -31,6 +31,7 @@ def gpu_preflight(models):
31
  pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480])
32
  # Both adapters check that actual operators executed on CUDA.
33
  return {"ready": True, "device": "cuda", "body_3d": False,
 
34
  "pose_providers": pose.session.get_providers(), "detector_providers": detector.providers}
35
 
36
 
@@ -80,6 +81,10 @@ def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_durati
80
  # coach, not a worker crash. Preserve the record-again payload.
81
  progress("measurements_2d", n, n)
82
  result = build_api_result(capture, observations, options, hashes)
 
 
 
 
83
  atomic_json(job / "coach-payload.json", result["coach_payload"])
84
  atomic_json(job / "result.json", result)
85
  progress("complete", n, n)
 
1
+ """GPU service worker; optional sparse 3D, isolated SAM, no coaching or IK."""
2
  import argparse
3
  from pathlib import Path
4
  import time
 
31
  pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480])
32
  # Both adapters check that actual operators executed on CUDA.
33
  return {"ready": True, "device": "cuda", "body_3d": False,
34
+ "scope": "required_2d_models; selected_3d_verified_during_job",
35
  "pose_providers": pose.session.get_providers(), "detector_providers": detector.providers}
36
 
37
 
 
81
  # coach, not a worker crash. Preserve the record-again payload.
82
  progress("measurements_2d", n, n)
83
  result = build_api_result(capture, observations, options, hashes)
84
+ from .event_body3d import reconstruct_events
85
+ from .measurement_quality import apply_measurement_quality
86
+ report = reconstruct_events(video, result, options, models, job, device=device, progress=progress)
87
+ result = apply_measurement_quality(result, options, report)
88
  atomic_json(job / "coach-payload.json", result["coach_payload"])
89
  atomic_json(job / "result.json", result)
90
  progress("complete", n, n)
baseball_batting/batting_measurements.py CHANGED
@@ -9,7 +9,7 @@ import math
9
  import numpy as np
10
  from scipy.ndimage import median_filter
11
 
12
- VERSION = "batting-2d-v3"
13
  EVENT_ORDER = ["stance_set", "load_start", "stride", "foot_contact", "foot_plant",
14
  "swing_start", "contact", "finish"]
15
  METRICS = {
@@ -315,7 +315,7 @@ def capture_checks(track, options, height, selected_frames):
315
  if fps < 30-1e-6: reasons.append("very_low_fps")
316
  elif fps < 60-1e-6: reasons.append("low_fps")
317
  else:
318
- diagnostics.append("Capture FPS is unknown or variable; timing metrics are withheld.")
319
  if options.view != "face_on": reasons.append("view_uncertain")
320
  if options.camera_stability != "fixed_verified":
321
  diagnostics.append("Camera stability is unverified or moving; ground-foot events and head path are withheld. Within-frame body positions and projected angles do not require a fixed camera.")
@@ -555,10 +555,12 @@ def rep_metrics(track, points, options, height, height_method, direction, events
555
  notes[key] = "Lead-leg geometry is ambiguous or conflicts with handedness/pitcher direction; check those inputs."
556
  if plant is not None and not lead_agrees(plant):
557
  notes["stride_pct_height"] = "Lead-leg geometry is ambiguous or conflicts with handedness/pitcher direction; check those inputs."
558
- fps = track["video"]["capture_fps"]
559
- timing_reason = ("Real capture timing is unknown or variable." if fps is None else
560
- "Timing measurements require real capture FPS >= 60." if fps < 60-1e-6 else None)
561
  real_times = np.asarray(track["frames"]["t_s"], float)
 
 
 
 
 
562
  if timing_reason is None and reason is None:
563
  if plant is not None and contact is not None:
564
  values["foot_plant_to_contact_ms"] = (real_times[contact]-real_times[plant])*1000
 
9
  import numpy as np
10
  from scipy.ndimage import median_filter
11
 
12
+ VERSION = "batting-2d-v4"
13
  EVENT_ORDER = ["stance_set", "load_start", "stride", "foot_contact", "foot_plant",
14
  "swing_start", "contact", "finish"]
15
  METRICS = {
 
315
  if fps < 30-1e-6: reasons.append("very_low_fps")
316
  elif fps < 60-1e-6: reasons.append("low_fps")
317
  else:
318
+ diagnostics.append("Constant capture FPS is unknown or variable; timing requires documented per-frame capture times with adequate local cadence.")
319
  if options.view != "face_on": reasons.append("view_uncertain")
320
  if options.camera_stability != "fixed_verified":
321
  diagnostics.append("Camera stability is unverified or moving; ground-foot events and head path are withheld. Within-frame body positions and projected angles do not require a fixed camera.")
 
555
  notes[key] = "Lead-leg geometry is ambiguous or conflicts with handedness/pitcher direction; check those inputs."
556
  if plant is not None and not lead_agrees(plant):
557
  notes["stride_pct_height"] = "Lead-leg geometry is ambiguous or conflicts with handedness/pitcher direction; check those inputs."
 
 
 
558
  real_times = np.asarray(track["frames"]["t_s"], float)
559
+ deltas = np.diff(real_times[start:end+1])
560
+ known_clock = len(deltas) > 0 and np.isfinite(deltas).all() and (deltas > 0).all()
561
+ timing_reason = ("Real capture timing is unknown." if not known_clock else
562
+ "Timing requires capture intervals no longer than 1/60 second; missing frames or low capture rate limit resolution."
563
+ if deltas.max() > 1/60+1e-6 else None)
564
  if timing_reason is None and reason is None:
565
  if plant is not None and contact is not None:
566
  values["foot_plant_to_contact_ms"] = (real_times[contact]-real_times[plant])*1000
baseball_batting/event_body3d.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sparse GPU body reconstruction at events, with explicit camera assumptions.
2
+
3
+ RTMW3D's native XY outputs are crop pixels; Z is pelvis-relative metres.
4
+ They MUST be unwarped and back-projected, not used as mixed-unit 3D points.
5
+ SAM runs in its separate installed interpreter; no anatomy/temporal fit runs.
6
+ """
7
+ from pathlib import Path
8
+ import gc
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import time
13
+ import numpy as np
14
+ import yaml
15
+ from .config import CONFIG_ROOT
16
+ from .storage import atomic_json, read_json, sha256_file
17
+ from .ingest import iter_frames
18
+
19
+ SAM_COCO = [0, 1, 2, 3, 4, 5, 6, 7, 8, 62, 41, 9, 10, 11, 12, 13, 14]
20
+ RADIUS = 2
21
+
22
+
23
+ def selected_event_frames(result, limit=300):
24
+ """Whole windows only, capped by the server; never substitute nearby events."""
25
+ selected, omitted = set(), []
26
+ for rep in result["pose_track"]["reps"]:
27
+ for name in ("contact", "foot_plant"):
28
+ if name not in rep["events"]:
29
+ continue
30
+ frame = rep["events"][name]["frame"]
31
+ window = set(range(max(rep["start_frame"], frame-RADIUS),
32
+ min(rep["end_frame"], frame+RADIUS)+1))
33
+ if len(selected | window) > limit:
34
+ omitted.append({"rep": rep["rep"], "event": name})
35
+ else:
36
+ selected.update(window)
37
+ return sorted(selected), omitted
38
+
39
+
40
+ def camera_geometry(track, options, height_px):
41
+ w, h = track["video"]["width"], track["video"]["height"]
42
+ if options.camera:
43
+ c = options.camera
44
+ if c.cx >= w or c.cy >= h:
45
+ raise ValueError("Camera principal point is outside the upright image")
46
+ k = np.array([[c.fx, 0, c.cx], [0, c.fy, c.cy], [0, 0, 1.]])
47
+ camera_source = c.source
48
+ else:
49
+ # A declared prior, not recovered calibration. Sensitivity is evaluated
50
+ # below; its survival still does not establish accuracy.
51
+ f = 1.2*max(w, h)
52
+ k = np.array([[f, 0, w/2], [0, f, h/2], [0, 0, 1.]])
53
+ camera_source = "assumed focal length 1.2 × longest image dimension"
54
+ if options.root_depth_m is not None:
55
+ depth, source = options.root_depth_m, options.root_depth_source
56
+ elif height_px:
57
+ stature_m = options.height_m if options.height_m is not None else 1.75
58
+ depth = float(k[1, 1]*stature_m/height_px)
59
+ source = ("weak-perspective depth from declared height" if options.height_m is not None else
60
+ "weak-perspective depth from assumed 1.75 m stature") + " and projected standing-height scale"
61
+ else:
62
+ depth, source = 5.14388, "RTMW3D training-set pelvis-depth prior; actual distance unknown"
63
+ return k, float(depth), {"intrinsics": k.tolist(), "camera_source": camera_source,
64
+ "pelvis_depth_m": float(depth), "depth_source": source,
65
+ "assumed": options.camera is None or options.root_depth_m is None,
66
+ "up": list(options.camera_up), "up_source": "caller direction; default assumes an upright, level camera"}
67
+
68
+
69
+ def backproject(points_px, relative_depth_m, k, pelvis_depth):
70
+ z = np.asarray(relative_depth_m, float)+pelvis_depth
71
+ xy = np.asarray(points_px, float)
72
+ xyz = np.column_stack(((xy[:, 0]-k[0, 2])/k[0, 0]*z,
73
+ (xy[:, 1]-k[1, 2])/k[1, 1]*z, z))
74
+ xyz[z <= 0] = np.nan
75
+ return xyz
76
+
77
+
78
+ class RTMW3DPose:
79
+ def __init__(self, path, device="cuda"):
80
+ from .detection import ort_session
81
+ from rtmlib.tools.pose_estimation.pre_processings import bbox_xyxy2cs, top_down_affine
82
+ self.session, self.device = ort_session(path, device), device
83
+ self.bbox_transform, self.affine = bbox_xyxy2cs, top_down_affine
84
+ self.cuda_verified = False
85
+ if self.session.get_inputs()[0].shape[1:] != [3, 384, 288]:
86
+ raise ValueError("Unexpected RTMW3D input dimensions")
87
+
88
+ def __call__(self, image, box, k, depth):
89
+ from .detection import verify_cuda_nodes
90
+ center, scale = self.bbox_transform(np.asarray(box), padding=1.25)
91
+ crop, scale = self.affine((288, 384), scale, center, image)
92
+ tensor = (crop-np.array([123.675, 116.28, 103.53]))/np.array([58.395, 57.12, 57.375])
93
+ tensor = np.ascontiguousarray(tensor.transpose(2, 0, 1)[None], dtype=np.float32)
94
+ outputs = self.session.run(None, {self.session.get_inputs()[0].name: tensor})
95
+ if len(outputs) != 3 or any(o.shape[:2] != (1, 133) for o in outputs):
96
+ raise ValueError("RTMW3D must return three native 133-joint SimCC distributions")
97
+ if self.device == "cuda" and not self.cuda_verified:
98
+ verify_cuda_nodes(self.session); self.cuda_verified = True
99
+ loc = np.stack([o.argmax(axis=-1)[0] for o in outputs], axis=-1)/2
100
+ # Match RTMLib's 3D decoder: its point score is min(X,Y), not min(X,Y,Z).
101
+ # Z responses have a different scale and cannot share the 2D 0.35 gate.
102
+ scores = np.min(np.stack([o.max(axis=-1)[0] for o in outputs[:2]]), axis=0)
103
+ depth_response = outputs[2].max(axis=-1)[0]
104
+ # The Z grid is 288 bins before the ×2 SimCC split, unlike image height.
105
+ dz = (loc[:, 2]/144-1)*2.1744869
106
+ px = loc[:, :2]/[288, 384]*scale+center-scale/2
107
+ points = backproject(px, dz, k, depth)
108
+ points[scores <= 0] = np.nan
109
+ return {"points": points[:17].tolist(), "projection": px[:17].tolist(),
110
+ "scores": np.clip(scores[:17], 0, 1).tolist(),
111
+ "relative_depth_m": dz[:17].tolist(),
112
+ "depth_peak_response": depth_response[:17].tolist()}
113
+
114
+
115
+ def reconstruct_events(video, result, options, models, job, *, device="cuda", progress=None,
116
+ max_frames=300, timeout_s=600):
117
+ backend = options.measurement_backend
118
+ selected, omitted = selected_event_frames(result, max_frames)
119
+ report = {"backend": backend, "status": "disabled" if backend == "2d" else "unavailable",
120
+ "reason": "2D selected" if backend == "2d" else "Not run",
121
+ "validation": "reference_validation_pending", "unit": "m",
122
+ "frame_of_reference": "camera", "axes": "x right, y down, z away",
123
+ "frames": [], "requested_frames": selected if backend != "2d" else [],
124
+ "omitted_windows": omitted if backend != "2d" else [], "elapsed_s": 0.}
125
+ if backend == "2d": return report
126
+ if not selected:
127
+ report["reason"] = "No contact/foot-plant event windows available"
128
+ return report
129
+ started = time.monotonic()
130
+ try:
131
+ track = result["pose_track"]
132
+ k, depth, geometry = camera_geometry(track, options, result["measurement_method"]["body_height_px"])
133
+ report["geometry"] = geometry
134
+ if progress: progress("loading_3d", 0, len(selected))
135
+ if backend == "sam3d":
136
+ manifest = os.environ.get("BASEBALL_SAM_WORKER_RECORD")
137
+ if not manifest or not Path(manifest).is_file():
138
+ raise ValueError("SAM worker is not configured: set BASEBALL_SAM_WORKER_RECORD to sam-api-worker.json")
139
+ record = read_json(manifest)
140
+ request = Path(job)/"sam-events-request.json"
141
+ output = Path(job)/"sam-events-output.json"
142
+ output.unlink(missing_ok=True)
143
+ atomic_json(request, {"video": str(Path(video).resolve()), "rotation": track["video"]["rotation_degrees_applied"],
144
+ "frames": [{"frame": i, "box": track["frames"]["box"][i]} for i in selected],
145
+ "worker_record": str(Path(manifest).resolve()),
146
+ "intrinsics": k.tolist() if options.camera else None,
147
+ "progress_path": str(Path(job).resolve()/"progress.json")})
148
+ env = dict(os.environ, MPLBACKEND="Agg", PYTHONUNBUFFERED="1")
149
+ env.pop("BASEBALL_API_KEY", None)
150
+ command = [record["worker_python"], "-m", "baseball_batting.sam_event_worker",
151
+ "--request", str(request.resolve()), "--output", str(output.resolve())]
152
+ completed = subprocess.run(command, env=env, cwd=Path(__file__).resolve().parents[1], timeout=timeout_s)
153
+ if not output.is_file(): raise RuntimeError("SAM worker produced no result; see worker log")
154
+ sam = read_json(output)
155
+ if completed.returncode or sam.get("status") not in {"ready", "partial"}:
156
+ raise RuntimeError(sam.get("reason", "SAM inference failed"))
157
+ report.update(sam)
158
+ if omitted and report["status"] == "ready": report["status"] = "partial"
159
+ report["geometry"]["depth_source"] = "SAM predicted camera translation"
160
+ report["geometry"]["camera_source"] = "caller calibration" if options.camera else "SAM default FOV"
161
+ report["geometry"]["assumed"] = options.camera is None
162
+ report["geometry"]["pelvis_depth_m"] = None
163
+ report["geometry"]["intrinsics"] = k.tolist() if options.camera else None
164
+ else:
165
+ registry = yaml.safe_load((CONFIG_ROOT/"resources.yaml").read_text())["resources"]["body_pose_3d"]
166
+ path = Path(models)/"body_pose_3d/model.onnx"
167
+ if not path.is_file() or sha256_file(path) != registry["sha256"]:
168
+ raise ValueError("Lightweight 3D model missing or incorrect; run setup_api_models --with-3d")
169
+ report["model"] = {"name": "RTMW3D-x", "sha256": registry["sha256"], "version": registry["version"],
170
+ "score_definition": "min native X/Y peak responses, clipped to 0–1; depth peak response separate; no calibrated 3D confidence"}
171
+ adapter = RTMW3DPose(str(path), device)
172
+ wanted = set(selected)
173
+ for frame, _, _, image in iter_frames(video, track["video"]["rotation_degrees_applied"]):
174
+ if frame > selected[-1]: break
175
+ if time.monotonic()-started > timeout_s: raise TimeoutError("3D frame-window budget exceeded")
176
+ if frame not in wanted: continue
177
+ box = track["frames"]["box"][frame]
178
+ if box is None: continue
179
+ predicted = adapter(image, box, k, depth)
180
+ report["frames"].append({"frame": frame, **predicted})
181
+ if progress: progress("pose_3d", len(report["frames"]), len(selected))
182
+ del adapter
183
+ gc.collect()
184
+ report["status"] = "ready" if len(report["frames"]) == len(selected) and not omitted else "partial"
185
+ report["reason"] = "Sparse event-window inference completed; accuracy unvalidated"
186
+ except Exception as error:
187
+ # Other seven estimates can still be returned. Never switch providers or
188
+ # turn failed 3D into an unlabeled projected angle.
189
+ report["status"] = "unavailable"
190
+ report["reason"] = str(error)[:500]
191
+ report["frames"] = []
192
+ report["elapsed_s"] = round(time.monotonic()-started, 3)
193
+ return report
baseball_batting/measurement_quality.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks and sensitivity evidence for all nine fields, without accuracy claims.
2
+
3
+ Nearby frames and camera-prior perturbations measure sensitivity, not validated
4
+ error bars. Anatomical angles are explicit 3D landmark constructions, not IK or
5
+ clinical joint-coordinate-system measurements. The coach always receives est.
6
+ """
7
+ import math
8
+ import numpy as np
9
+ from .batting_measurements import METRICS, analysis_body_points, analysis_points, included_angle, point_array
10
+ from .event_body3d import backproject
11
+
12
+ ANGLE_KEYS = {"lead_knee_angle_contact_deg", "lateral_trunk_tilt_contact_deg",
13
+ "hip_shoulder_separation_foot_plant_deg"}
14
+ ANGLE_LIMITS = {"lead_knee_angle_contact_deg": 15., "lateral_trunk_tilt_contact_deg": 12.,
15
+ "hip_shoulder_separation_foot_plant_deg": 20.}
16
+ SUPPORT = {
17
+ "stride_pct_height": ("foot_plant", [15, 16]),
18
+ "com_drift_pct_height": ("contact", [11, 12, 15, 16]),
19
+ "head_movement_pct_height": ("contact", [0]),
20
+ "lead_knee_angle_contact_deg": ("contact", [11, 12, 13, 14, 15, 16]),
21
+ "lateral_trunk_tilt_contact_deg": ("contact", [5, 6, 11, 12]),
22
+ "hip_shoulder_separation_foot_plant_deg": ("foot_plant", [5, 6, 11, 12]),
23
+ }
24
+
25
+
26
+ def angle_value(key, points, options):
27
+ p = np.asarray(points, float)
28
+ lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None
29
+ if lead is None: return None
30
+ if key == "lead_knee_angle_contact_deg":
31
+ joints = [11+lead, 13+lead, 15+lead]
32
+ if not np.isfinite(p[joints]).all(): return None
33
+ value = included_angle(*p[joints])
34
+ return float(value) if math.isfinite(float(value)) else None
35
+ up = np.asarray(options.camera_up, float); up /= np.linalg.norm(up)
36
+ hips = (p[11]+p[12])/2
37
+ shoulders = (p[5]+p[6])/2
38
+ lateral = p[11]-p[12] # Anatomical right -> left.
39
+ lateral -= up*np.dot(lateral, up)
40
+ shoulder_axis = p[5]-p[6]
41
+ shoulder_axis -= up*np.dot(shoulder_axis, up)
42
+ if not np.isfinite([hips, shoulders, lateral, shoulder_axis]).all(): return None
43
+ if np.linalg.norm(lateral) < .08 or np.linalg.norm(shoulder_axis) < .08: return None
44
+ lateral /= np.linalg.norm(lateral)
45
+ if key == "lateral_trunk_tilt_contact_deg":
46
+ trunk = shoulders-hips
47
+ vertical = np.dot(trunk, up)
48
+ if vertical <= .05: return None
49
+ # Positive toward the anatomical lead side, not screen-left/right.
50
+ toward_lead = lateral if lead == 0 else -lateral
51
+ return float(np.degrees(np.arctan2(np.dot(trunk, toward_lead), vertical)))
52
+ shoulder_axis /= np.linalg.norm(shoulder_axis)
53
+ twist = np.degrees(np.arctan2(np.dot(up, np.cross(lateral, shoulder_axis)),
54
+ np.dot(lateral, shoulder_axis)))
55
+ # Undirected segment lines, modulo 180 degrees. This is horizontal landmark
56
+ # separation; it does not claim thorax/pelvis anatomical axial rotation.
57
+ return float((twist+90) % 180-90)
58
+
59
+
60
+ def checked_3d_rows(report, track, height):
61
+ rows, reasons = {}, {}
62
+ raw = point_array(track["frames"]["kp"], 17)
63
+ if not height: return rows, reasons
64
+ for row in report.get("frames", []):
65
+ i = row["frame"]
66
+ p, px = np.asarray(row["points"], float), np.asarray(row["projection"], float)
67
+ if p.shape != (17, 3) or px.shape != (17, 2) or not 0 <= i < len(raw):
68
+ reasons[i] = "Invalid 3D row dimensions"; continue
69
+ # Per-joint rejection preserves supported measurements on other limbs.
70
+ valid = np.isfinite(p).all(axis=1) & np.isfinite(px).all(axis=1) & (p[:, 2] > 0)
71
+ valid &= np.isfinite(raw[i]).all(axis=1)
72
+ residual = np.linalg.norm(px-raw[i], axis=1)/height
73
+ valid &= residual <= .05
74
+ scores = row.get("scores", [None]*17)
75
+ for j, score in enumerate(scores):
76
+ if score is not None and (not math.isfinite(score) or score < .35): valid[j] = False
77
+ p = p.copy(); p[~valid] = np.nan
78
+ rows[i] = p
79
+ reasons[i] = "3D joints must agree with raw 2D observations within 5% of image stature; model agreement is not truth"
80
+ return rows, reasons
81
+
82
+
83
+ def metric_3d(key, rep, track, options, report, height):
84
+ event_name, joints = SUPPORT[key]
85
+ diagnostic = {"key": key, "method": "3d_landmark_geometry_v1", "status": "withheld",
86
+ "validation": "reference_validation_pending"}
87
+ if event_name not in rep["events"]:
88
+ return None, f"Missing {event_name} event.", diagnostic
89
+ if not options.handedness:
90
+ return None, "Handedness is required for anatomical lead-side angles.", diagnostic
91
+ i = rep["events"][event_name]["frame"]
92
+ if key == "lead_knee_angle_contact_deg":
93
+ lead = 0 if options.handedness == "right" else 1
94
+ joints = [11+lead, 13+lead, 15+lead]
95
+ rows, reasons = checked_3d_rows(report, track, height)
96
+ ids = list(range(max(rep["start_frame"], i-2), min(rep["end_frame"], i+2)+1))
97
+ if i not in rows or not np.isfinite(rows[i][joints]).all():
98
+ return None, "3D event joints are missing, weak, or disagree with the 2D track.", diagnostic
99
+ supported = [j for j in ids if j in rows and np.isfinite(rows[j][joints]).all()]
100
+ # Require raw adjacent support, not interpolation across missing frames.
101
+ if not all(j in supported for j in (i-1, i, i+1)):
102
+ return None, "Three consecutive supported 3D frames around the event are required.", diagnostic
103
+ samples = [angle_value(key, rows[j], options) for j in supported]
104
+ if any(v is None for v in samples):
105
+ return None, "3D body axes or limb geometry are degenerate.", diagnostic
106
+ # Check local limb/axis lengths before filtering; prevent a smooth angle
107
+ # concealing a depth flip or changing body proportions.
108
+ links = [(11, 13), (13, 15)] if options.handedness == "right" else [(12, 14), (14, 16)]
109
+ if key != "lead_knee_angle_contact_deg": links = [(5, 6), (11, 12)]
110
+ for a, b in links:
111
+ lengths = np.array([np.linalg.norm(rows[j][a]-rows[j][b]) for j in supported])
112
+ if not np.isfinite(lengths).all() or lengths.min() < .08 or lengths.max() > 1.2 or lengths.max()/lengths.min() > 1.25:
113
+ return None, "3D segment lengths change too much or fall outside broad geometry limits.", diagnostic
114
+ relative = np.stack([rows[j]-(rows[j][11]+rows[j][12])/2 for j in (i-1, i, i+1)])
115
+ filtered = np.median(relative, axis=0)
116
+ value = angle_value(key, filtered, options)
117
+ if value is None: return None, "Filtered 3D geometry is unavailable.", diagnostic
118
+ # Circular differences avoid treating +89/-89 separation as a 178° jump.
119
+ difference = lambda v: abs((v-value+90) % 180-90) if key.startswith("hip_") else abs(v-value)
120
+ sensitivity = max(difference(v) for v in samples)
121
+ diagnostic.update({"event_frame": i, "support_frames": supported,
122
+ "nearby_frame_sensitivity": round(sensitivity, 3), "unit": "deg",
123
+ "sensitivity_limit": ANGLE_LIMITS[key]})
124
+ if sensitivity > ANGLE_LIMITS[key]:
125
+ return None, "Angle changes too much across nearby event frames; event or pose is unstable.", diagnostic
126
+ geometry = report.get("geometry", {})
127
+ camera_sensitivity = 0.
128
+ if report["backend"] == "rtmw3d" and geometry.get("assumed"):
129
+ native = {r["frame"]: r for r in report["frames"]}[i]
130
+ dz = native.get("relative_depth_m")
131
+ if dz is None: return None, "Lightweight 3D camera sensitivity cannot be checked.", diagnostic
132
+ k, depth = np.asarray(geometry["intrinsics"], float), geometry["pelvis_depth_m"]
133
+ # Independent ±15% focal/depth perturbations; a heuristic stress test,
134
+ # never a confidence interval or proof the true camera lies in this band.
135
+ for focal_factor in (.85, 1.15):
136
+ for depth_factor in (.85, 1.15):
137
+ perturbed = k.copy(); perturbed[0, 0] *= focal_factor; perturbed[1, 1] *= focal_factor
138
+ v = angle_value(key, backproject(native["projection"], dz, perturbed, depth*depth_factor), options)
139
+ if v is None: return None, "Angle is undefined under camera-prior perturbation.", diagnostic
140
+ camera_sensitivity = max(camera_sensitivity, difference(v))
141
+ diagnostic["camera_prior_sensitivity"] = round(camera_sensitivity, 3)
142
+ if camera_sensitivity > ANGLE_LIMITS[key]:
143
+ return None, "Angle is too sensitive to assumed camera geometry; supply camera/depth information.", diagnostic
144
+ low, high = METRICS[key][1:]
145
+ if not low <= value <= high: return None, "3D angle is outside supplied plausible bounds.", diagnostic
146
+ diagnostic["status"] = "estimated"
147
+ definition = {"lead_knee_angle_contact_deg": "3D interior hip-knee-ankle angle; 180° is straight",
148
+ "lateral_trunk_tilt_contact_deg": "3D trunk lean in pelvis lateral plane; positive toward the anatomical lead side",
149
+ "hip_shoulder_separation_foot_plant_deg": "3D hip/shoulder landmark-line separation about declared vertical, modulo 180°"}[key]
150
+ note = f"{report['backend']} estimate: {definition}. Three-frame pelvis-relative median; event and angle accuracy unvalidated."
151
+ if geometry.get("assumed"): note += " Camera/depth assumptions used; sensitivity checks do not establish accuracy."
152
+ return round(value, 3), note, diagnostic
153
+
154
+
155
+ def apply_measurement_quality(result, options, report):
156
+ """Keep the coach schema unchanged; expose evidence in the full result only."""
157
+ track = result["pose_track"]
158
+ height = result["measurement_method"]["body_height_px"]
159
+ raw = point_array(track["frames"]["kp"], 17)
160
+ smoothed = analysis_body_points(raw)
161
+ diagnostics = []
162
+ for pose_rep, rep in zip(track["reps"], result["measurements"]["reps"]):
163
+ evidence = []
164
+ for metric in rep["metrics"]:
165
+ key = metric["key"]
166
+ item = {"key": key, "status": "estimated" if metric["value"] is not None else "withheld",
167
+ "method": "2d_estimate_v3", "validation": "reference_validation_pending"}
168
+ if options.measurement_backend != "2d" and key in ANGLE_KEYS:
169
+ item["method"] = "3d_landmark_geometry_v1"
170
+ if report["status"] not in {"ready", "partial"}:
171
+ metric.update(value=None, note="Selected 3D backend unavailable: "+report["reason"])
172
+ elif not result["measurements"]["capture"]["ok"] or options.view != "face_on":
173
+ metric.update(value=None, note="Capture/view checks failed; 3D does not override them.")
174
+ else:
175
+ value, note, item = metric_3d(key, pose_rep, track, options, report, height)
176
+ metric.update(value=value, note=note)
177
+ elif metric["value"] is not None and key in SUPPORT:
178
+ event, joints = SUPPORT[key]
179
+ i = pose_rep["events"][event]["frame"]
180
+ ids = list(range(max(pose_rep["start_frame"], i-1), min(pose_rep["end_frame"], i+1)+1))
181
+ supported = np.isfinite(raw[ids][:, joints]).all(axis=(1, 2))
182
+ item.update(event_frame=i, support_frames=[j for j, valid in zip(ids, supported) if valid])
183
+ if not np.isfinite(raw[i, joints]).all() or supported.sum() < 2:
184
+ metric.update(value=None, note="Raw joints near the event do not provide enough consecutive support.")
185
+ elif height:
186
+ change = np.linalg.norm(raw[i, joints]-smoothed[i, joints], axis=-1).max()/height*100
187
+ item["raw_filter_change_pct_height"] = round(float(change), 3)
188
+ if change > 3:
189
+ metric.update(value=None, note="Joint positions change too much under filtering; tracking is unstable.")
190
+ if key in {"stride_pct_height", "com_drift_pct_height"}:
191
+ p = smoothed[ids]
192
+ if key == "stride_pct_height":
193
+ samples = np.abs(p[:, 15, 0]-p[:, 16, 0])/height*100
194
+ else:
195
+ lead = 15 if options.handedness == "right" else 16
196
+ sign = -1 if result["measurement_method"]["pitcher_direction"] == "image_left" else 1
197
+ samples = sign*((p[:, 11, 0]+p[:, 12, 0])/2-p[:, lead, 0])/height*100
198
+ finite = samples[np.isfinite(samples)]
199
+ if len(finite) >= 2:
200
+ item["nearby_frame_range"] = [round(float(finite.min()), 3), round(float(finite.max()), 3)]
201
+ item["sensitivity_scope"] = "nearby event frames; not a measured error bound"
202
+ if np.ptp(finite) > 6:
203
+ metric.update(value=None, note="Position changes by more than six percentage points near the event; estimate is unstable.")
204
+ if key == "head_movement_pct_height":
205
+ start = pose_rep["events"]["stance_set"]["frame"]
206
+ nose = raw[start:i+1, 0]
207
+ adjacent = np.isfinite(nose[:-1]).all(axis=1) & np.isfinite(nose[1:]).all(axis=1)
208
+ raw_path = float(np.linalg.norm(np.diff(nose, axis=0)[adjacent], axis=1).sum()/height*100)
209
+ filtered = analysis_points(raw)[start:i+1, 0]
210
+ filtered_path = float(np.linalg.norm(np.diff(filtered, axis=0), axis=1).sum()/height*100)
211
+ item.update(raw_head_path_pct_height=round(raw_path, 3), filtered_head_path_pct_height=round(filtered_path, 3))
212
+ if raw_path > 2*filtered_path and raw_path-filtered_path > 3:
213
+ metric.update(value=None, note="Head path is dominated by tracking noise removed by filtering; movement cannot be measured reliably.")
214
+ if key in {"foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio"}:
215
+ names = {"foot_plant_to_contact_ms": ("foot_plant", "contact"),
216
+ "load_tempo_s": ("load_start", "swing_start"),
217
+ "load_launch_ratio": ("load_start", "swing_start", "contact")}[key]
218
+ if all(name in pose_rep["events"] for name in names):
219
+ t = track["frames"]["t_s"]
220
+ intervals = []
221
+ for name in names:
222
+ i = pose_rep["events"][name]["frame"]
223
+ a, b = max(pose_rep["start_frame"], i-1), min(pose_rep["end_frame"], i+1)
224
+ if t[a] is not None and t[b] is not None: intervals.append((t[a], t[b]))
225
+ if len(intervals) == len(names):
226
+ scale = 1000 if key.endswith("_ms") else 1
227
+ if len(names) == 2:
228
+ interval = [(intervals[1][0]-intervals[0][1])*scale,
229
+ (intervals[1][1]-intervals[0][0])*scale]
230
+ else:
231
+ denominator = (intervals[2][0]-intervals[1][1], intervals[2][1]-intervals[1][0])
232
+ interval = ([(intervals[1][0]-intervals[0][1])/denominator[1],
233
+ (intervals[1][1]-intervals[0][0])/denominator[0]] if denominator[0] > 0 else None)
234
+ item.update(event_frame_sensitivity_range=interval,
235
+ sensitivity_scope="each event shifted ±1 frame; detection error may be larger")
236
+ if interval is None and metric["value"] is not None:
237
+ metric.update(value=None, note="Launch duration is too short to resolve under ±1-frame event shifts.")
238
+ elif interval is not None and metric["value"] is not None:
239
+ width = interval[1]-interval[0]
240
+ if interval[0] <= 0 or width > .5*metric["value"]:
241
+ metric.update(value=None, note="Timing changes too much under ±1-frame event shifts; recording/event resolution is insufficient.")
242
+ item["status"] = "estimated" if metric["value"] is not None else "withheld"
243
+ item["note"] = metric["note"]
244
+ evidence.append(item)
245
+ diagnostics.append({"rep": rep["rep"], "metrics": evidence})
246
+ result["measurement_diagnostics"] = diagnostics
247
+ result["experimental_body3d"] = report
248
+ result["capabilities"]["body_3d"] = report["status"] in {"ready", "partial"} and bool(report["frames"])
249
+ result["measurement_method"]["backend"] = options.measurement_backend
250
+ result["measurement_method"]["quality_version"] = "measurement-quality-v1"
251
+ if options.measurement_backend != "2d":
252
+ result["warnings"].append("3D angles are experimental landmark estimates, not validated anatomical measurements. See measurement_diagnostics and experimental_body3d.")
253
+ if report["status"] == "unavailable": result["warnings"].append("3D unavailable: "+report["reason"])
254
+ from .batting_measurements import coach_payload
255
+ result["coach_payload"] = coach_payload(result["measurements"])
256
+ from .contracts import json_safe
257
+ return json_safe(result)
baseball_batting/sam_event_worker.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated SAM body-only inference for selected event frames; no OpenSim fit."""
2
+ import argparse
3
+ import contextlib
4
+ import io
5
+ import os
6
+ from pathlib import Path
7
+ import subprocess
8
+ import sys
9
+ import numpy as np
10
+ from .event_body3d import SAM_COCO
11
+ from .ingest import iter_frames
12
+ from .storage import atomic_json, read_json, sha256_file
13
+
14
+
15
+ def sam_to_coco(prediction, image_shape=None, intrinsics=None):
16
+ """SAM already returns metres in flipped camera axes; translate exactly once."""
17
+ xyz = np.asarray(prediction["pred_keypoints_3d"], float)[SAM_COCO]
18
+ xy = np.asarray(prediction["pred_keypoints_2d"], float)[SAM_COCO]
19
+ camera = np.asarray(prediction["pred_cam_t"], float).reshape(3)
20
+ if xyz.shape != (17, 3) or xy.shape != (17, 2) or not np.isfinite(xyz).all() or not np.isfinite(xy).all():
21
+ raise ValueError("Invalid SAM landmark output")
22
+ row = {"points": (xyz+camera).tolist(), "projection": xy.tolist(), "scores": [None]*17}
23
+ if image_shape is not None:
24
+ h, w = image_shape[:2]
25
+ f = float(np.asarray(prediction["focal_length"]).reshape(-1)[0])
26
+ k = np.asarray(intrinsics, float) if intrinsics is not None else np.array([[f, 0, w/2], [0, f, h/2], [0, 0, 1.]])
27
+ from .geometry import project
28
+ residual = np.linalg.norm(project(xyz+camera, k)-xy, axis=-1)
29
+ if not np.isfinite(residual).all() or residual.max() > 1:
30
+ raise ValueError("SAM camera/metres/translation convention check failed")
31
+ row["camera_intrinsics"] = k.tolist()
32
+ return row
33
+
34
+
35
+ def run(request):
36
+ # Configure before importing torch/SAM or plotting helpers.
37
+ os.environ["MPLBACKEND"] = "Agg"
38
+ os.environ["MOMENTUM_ENABLED"] = "0"
39
+ record = read_json(request["worker_record"])
40
+ for field in ("sam_repo", "sam_checkpoint", "sam_config", "mhr_path"):
41
+ if not Path(record[field]).exists(): raise ValueError(f"Missing configured {field}")
42
+ revision = subprocess.check_output(["git", "-C", record["sam_repo"], "rev-parse", "HEAD"], text=True).strip()
43
+ from tools.setup_full_worker import SAM_REVISION
44
+ if revision != SAM_REVISION: raise ValueError("SAM source revision differs from pinned adapter")
45
+ expected = record.get("artifact_hashes", {})
46
+ hashes = {key: sha256_file(record[key]) for key in ("sam_checkpoint", "sam_config", "mhr_path")}
47
+ if any(expected.get(key) != value for key, value in hashes.items()):
48
+ raise ValueError("SAM assets need recorded, matching checksums")
49
+ import torch
50
+ if not torch.cuda.is_available(): raise RuntimeError("SAM requires CUDA")
51
+ torch.backends.cuda.matmul.allow_tf32 = False
52
+ torch.backends.cudnn.allow_tf32 = False
53
+ sys.path.insert(0, str(Path(record["sam_repo"]).resolve()))
54
+ from sam_3d_body.utils.config import get_config
55
+ from sam_3d_body.models.meta_arch import SAM3DBody
56
+ from sam_3d_body.utils.checkpoint import load_state_dict
57
+ from sam_3d_body.sam_3d_body_estimator import SAM3DBodyEstimator
58
+ cfg = get_config(record["sam_config"])
59
+ cfg.defrost(); cfg.TRAIN.USE_FP16 = False
60
+ cfg.MODEL.MHR_HEAD.MHR_MODEL_PATH = str(Path(record["mhr_path"]).resolve())
61
+ cfg.freeze()
62
+ model = SAM3DBody(cfg)
63
+ checkpoint = torch.load(record["sam_checkpoint"], map_location="cpu", weights_only=False)
64
+ load_state_dict(model, checkpoint.get("state_dict", checkpoint), strict=False)
65
+ del checkpoint
66
+ model = model.to("cuda").eval()
67
+ if {str(p.dtype) for p in model.parameters() if p.is_floating_point()} != {"torch.float32"}:
68
+ raise ValueError("SAM must initialize in FP32 for the selected runtime")
69
+ estimator = SAM3DBodyEstimator(model, cfg, human_detector=None, human_segmentor=None, fov_estimator=None)
70
+ camera = request.get("intrinsics")
71
+ if camera is not None: camera = torch.tensor(camera, dtype=torch.float32)[None]
72
+ wanted = {r["frame"]: r["box"] for r in request["frames"]}
73
+ rows = []
74
+ for frame, _, _, image in iter_frames(request["video"], request["rotation"]):
75
+ if frame > max(wanted): break
76
+ if frame not in wanted or wanted[frame] is None: continue
77
+ kwargs = {"bboxes": np.asarray(wanted[frame], np.float32)[None], "inference_type": "body"}
78
+ if camera is not None: kwargs["cam_int"] = camera
79
+ with contextlib.redirect_stdout(io.StringIO()), torch.inference_mode():
80
+ predictions = estimator.process_one_image(image[..., ::-1].copy(), **kwargs)
81
+ if len(predictions) != 1: continue
82
+ rows.append({"frame": frame, **sam_to_coco(predictions[0], image.shape, request.get("intrinsics"))})
83
+ atomic_json(request["progress_path"], {"stage": "pose_3d_sam", "completed_frames": len(rows),
84
+ "total_frames": len(wanted), "stage_progress": len(rows)/len(wanted)})
85
+ print(f"SAM event frames: {len(rows)}/{len(wanted)}", flush=True)
86
+ return {"status": "ready" if len(rows) == len(wanted) else "partial",
87
+ "reason": "SAM body-only sparse event-window inference; accuracy unvalidated", "frames": rows,
88
+ "model": {"name": "SAM 3D Body ViT-H", "source_revision": revision, "artifact_hashes": hashes,
89
+ "score_definition": "SAM does not supply calibrated per-joint scores; null", "precision": "fp32"}}
90
+
91
+
92
+ def main():
93
+ parser = argparse.ArgumentParser()
94
+ parser.add_argument("--request", required=True); parser.add_argument("--output", required=True)
95
+ args = parser.parse_args()
96
+ try:
97
+ result = run(read_json(args.request))
98
+ except Exception as error:
99
+ print(f"{type(error).__name__}: {error}", flush=True)
100
+ result = {"status": "unavailable", "reason": str(error)[:500], "frames": []}
101
+ atomic_json(args.output, result)
102
+ return 0 if result["status"] in {"ready", "partial"} else 1
103
+
104
+
105
+ if __name__ == "__main__": raise SystemExit(main())
configs/resources.yaml CHANGED
@@ -38,6 +38,13 @@ resources:
38
  source_url: https://download.openmmlab.com/mmpose/v1/projects/rtmposev1/onnx_sdk/yolox_m_8xb8-300e_humanart-c2c7a14a.zip
39
  version: yolox-m-humanart-c2c7a14a
40
  intended_role: person proposals; not bat or ball detection
 
 
 
 
 
 
 
41
  object_detector:
42
  type: checkpoint
43
  source_url: https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx
 
38
  source_url: https://download.openmmlab.com/mmpose/v1/projects/rtmposev1/onnx_sdk/yolox_m_8xb8-300e_humanart-c2c7a14a.zip
39
  version: yolox-m-humanart-c2c7a14a
40
  intended_role: person proposals; not bat or ball detection
41
+ body_pose_3d:
42
+ type: checkpoint
43
+ source_url: https://huggingface.co/Soykaf/RTMW3D-x/resolve/a4f0d54c52ee44ee4e1dda1936d714490c6234d2/onnx/rtmw3d-x_8xb64_cocktail14-384x288-b0a0eab7_20240626.onnx
44
+ sha256: 4a289c0e99d47eb595e99679d9d4a2d1def1b4241f9adcbafba44b9ff585ebcd
45
+ version: rtmw3d-x-20240626-onnx-a4f0d54
46
+ intended_role: optional sparse event-window monocular depth; camera conversion required; unvalidated
47
+ dependency_ids: [rtmlib]
48
  object_detector:
49
  type: checkpoint
50
  source_url: https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_s.onnx
deploy/compose.sam.yaml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build baseball-engine-api:local with the base Compose file before this overlay.
2
+ services:
3
+ api:
4
+ build:
5
+ context: .
6
+ dockerfile: Dockerfile.sam
7
+ args:
8
+ BASE_IMAGE: baseball-engine-api:local
9
+ image: baseball-engine-api-sam:local
10
+ environment:
11
+ BASEBALL_SAM_WORKER_RECORD: /data/sam-api-worker.json
12
+ volumes:
13
+ - ${BASEBALL_SAM_ASSET_DIRECTORY:?Set the directory holding your approved SAM assets}:/opt/sam-assets:ro
docs/API_FOR_COACH.md CHANGED
@@ -1,6 +1,6 @@
1
  # Connect the batting engine to the coach API
2
 
3
- The engine extracts 2D points on GPU, estimates separate swings/events, and calculates supported swing numbers. Your coach agent chooses problems, priority, drill, explanation and progress. All 3D and coaching stages are disabled in this engine API.
4
 
5
  ## Calls
6
 
@@ -51,11 +51,11 @@ Supported values, subject to event/view/quality evidence:
51
 
52
  - `stride_pct_height`: horizontal ankle-to-ankle span at estimated foot plant.
53
  - `com_drift_pct_height`: hip midpoint relative to the front ankle at estimated contact; negative is behind.
54
- - `foot_plant_to_contact_ms`, `load_tempo_s`, `load_launch_ratio`: timing quantities only with a known constant capture rate >= 60 FPS.
55
  - `head_movement_pct_height`: reference-only nose path from stance to estimated contact.
56
  - `lead_knee_angle_contact_deg`: reference-only projected interior knee angle.
57
 
58
- `lateral_trunk_tilt_contact_deg` and `hip_shoulder_separation_foot_plant_deg` are null: face-on 2D cannot establish those anatomical 3D quantities. Foot plant is a settled-foot proxy and does not prove full body-weight loading. Contact is always an estimated lead-arm-extension proxy, with no bat-ball collision confirmation. See [exact definitions](BATTING_2D_MEASUREMENTS.md).
59
 
60
  Measurement method `batting-2d-v3` restricts swing onset and contact to the primary swinging movement. A later return/lowering of the hands cannot replace the swing just because it travels toward the declared pitcher direction. Missing extension during the actual swing leaves contact-dependent numbers null. Correct event selection can therefore remove numbers that older versions incorrectly calculated after the swing. The coach payload's schema and nine metric keys are unchanged; submit a new analysis to update an already completed API job.
61
 
@@ -67,6 +67,8 @@ An example computed from constructed trajectories is in [coach-payload.example.j
67
 
68
  | Option | Meaning |
69
  |---|---|
 
 
70
  | `discipline` | `hitting` only |
71
  | `view` | Known `face_on`, otherwise `unknown` |
72
  | `handedness` | `left` or `right`; identifies lead arm/foot |
@@ -95,13 +97,13 @@ Capture-clock declarations:
95
  {"kind":"explicit","source":"camera timestamp file","physical_times_s":[0.0,0.00417,0.00833]}
96
  ```
97
 
98
- Explicit times must match the decoded frame count and increase strictly. Unknown timing produces null capture timestamps in the pose track, no `events_ms`, and null timing metrics. Variable cadence is retained per frame, but no constant FPS or timing metrics are asserted. Capture-quality, event and boundary checks are heuristics, not validated classifiers.
99
 
100
  ## Full result and Python client
101
 
102
- The full result includes `pose_track` (17 COCO body points + six foot points, upright pixels, boxes, detected person counts, brightness and heuristic blur), `measurements`, `coach_payload`, `measurement_method`, capabilities, warnings and `validation: "reference_validation_pending"`. `status: "partial"` describes unresolved accuracy/unsupported quantities; it does not mean the HTTP job failed.
103
 
104
- Raw pose points are exported without smoothing or gap filling, filtered at model score 0.35 and image bounds. Missing points are null with confidence exactly zero. Measurement calculations use a separate copy with interior gaps up to three frames filled and a three-frame median on finite runs. Scores are model scores, not calibrated probabilities or verified visibility. No `kp3d` or bat/ball objects are emitted.
105
 
106
  Download only the coach payload with the example client:
107
 
 
1
  # Connect the batting engine to the coach API
2
 
3
+ The engine extracts 2D points on GPU, estimates separate swings/events, and calculates supported swing numbers. Your coach agent chooses problems, priority, drill, explanation and progress. Optional RTMW3D and SAM event-window inference supplies the three body-angle estimates; coaching stays in your service. See [all nine definitions and model selection](NINE_MEASUREMENTS.md).
4
 
5
  ## Calls
6
 
 
51
 
52
  - `stride_pct_height`: horizontal ankle-to-ankle span at estimated foot plant.
53
  - `com_drift_pct_height`: hip midpoint relative to the front ankle at estimated contact; negative is behind.
54
+ - `foot_plant_to_contact_ms`, `load_tempo_s`, `load_launch_ratio`: timing quantities with documented capture timestamps and every capture interval in the rep <= 1/60 s.
55
  - `head_movement_pct_height`: reference-only nose path from stance to estimated contact.
56
  - `lead_knee_angle_contact_deg`: reference-only projected interior knee angle.
57
 
58
+ In default `2d` mode, `lateral_trunk_tilt_contact_deg` and `hip_shoulder_separation_foot_plant_deg` remain null. Select `measurement_backend: "rtmw3d"` or `"sam3d"` to attempt those angles and a 3D knee angle, subject to stability/geometry checks. These are unvalidated landmark estimates and remain reference-only. Foot plant is a settled-foot proxy and does not prove full body-weight loading. Contact is always an estimated lead-arm-extension proxy, with no bat-ball collision confirmation. See [exact definitions](BATTING_2D_MEASUREMENTS.md).
59
 
60
  Measurement method `batting-2d-v3` restricts swing onset and contact to the primary swinging movement. A later return/lowering of the hands cannot replace the swing just because it travels toward the declared pitcher direction. Missing extension during the actual swing leaves contact-dependent numbers null. Correct event selection can therefore remove numbers that older versions incorrectly calculated after the swing. The coach payload's schema and nine metric keys are unchanged; submit a new analysis to update an already completed API job.
61
 
 
67
 
68
  | Option | Meaning |
69
  |---|---|
70
+ | `measurement_backend` | `2d` (default), `rtmw3d`, or `sam3d`; optional sparse event-window 3D |
71
+ | `height_m`, `camera`, `root_depth_m` + `root_depth_source`, `camera_up` | Optional geometry declarations; see [definitions](NINE_MEASUREMENTS.md) |
72
  | `discipline` | `hitting` only |
73
  | `view` | Known `face_on`, otherwise `unknown` |
74
  | `handedness` | `left` or `right`; identifies lead arm/foot |
 
97
  {"kind":"explicit","source":"camera timestamp file","physical_times_s":[0.0,0.00417,0.00833]}
98
  ```
99
 
100
+ Explicit times must match the decoded frame count and increase strictly. Unknown timing produces null capture timestamps in the pose track, no `events_ms`, and null timing metrics. Variable cadence is retained per frame without asserting constant FPS. Version 4 can calculate timing from those documented timestamps when every capture interval in the rep is <= 1/60 s; poor frame resolution still withholds a metric. Capture-quality, event and boundary checks are heuristics, not validated classifiers.
101
 
102
  ## Full result and Python client
103
 
104
+ The full result includes `pose_track` (17 COCO body points + six foot points, upright pixels, boxes, detected person counts, brightness and heuristic blur), `measurements`, `coach_payload`, `measurement_method`, `measurement_diagnostics`, `experimental_body3d`, capabilities, warnings and `validation: "reference_validation_pending"`. `status: "partial"` describes unresolved accuracy/unsupported quantities; it does not mean the HTTP job failed.
105
 
106
+ Raw pose points are exported without smoothing or gap filling, filtered at model score 0.35 and image bounds. Missing points are null with confidence exactly zero. Measurement calculations use a separate copy with interior gaps up to three frames filled and a three-frame median on finite runs. Scores are model scores, not calibrated probabilities or verified visibility. No validated `kp3d` or bat/ball objects are emitted. Sparse unvalidated 3D points are exposed separately in `experimental_body3d`; `measurement_diagnostics` explains the stability/sensitivity checks. Both are excluded from the coach payload.
107
 
108
  Download only the coach payload with the example client:
109
 
docs/BATTING_2D_MEASUREMENTS.md CHANGED
@@ -1,6 +1,6 @@
1
  # 2D batting measurement definitions
2
 
3
- Version: `batting-2d-v3`. Scope: face-on batting, with fixed-camera requirements only for ground-foot events and head movement. This module uses GPU pose/person outputs and CPU arithmetic, with no SAM, temporal 3D fitting, OpenSim or coaching decisions.
4
 
5
  ## Pose checkpoint and foot points
6
 
@@ -53,9 +53,9 @@ Events must be inside their rep and follow the requested order. Conflicting cand
53
  |---|---|---|
54
  | `stride_pct_height` | `100 × abs(lead_ankle_x - back_ankle_x) / image_height_scale` at estimated foot plant | Lead side, plant and scale |
55
  | `com_drift_pct_height` | `100 × pitcher_direction × (hip_midpoint_x - lead_ankle_x) / scale` at estimated contact | Negative is behind; hip proxy, not whole-body center of mass; same-frame estimate eligible with a moving camera |
56
- | `foot_plant_to_contact_ms` | Physical contact time minus physical plant time, ×1000 | Both events; constant capture FPS >=60 |
57
- | `load_tempo_s` | Physical forward-onset time minus physical hand-load-start time | Both events; constant capture FPS >=60 |
58
- | `load_launch_ratio` | Load duration / physical onset-to-contact duration | All events; positive denominator; constant capture FPS >=60 |
59
  | `head_movement_pct_height` | Sum of consecutive analytical nose displacements from stance to estimated contact, /scale ×100 | Fixed camera, complete analytical path; reference-only |
60
  | `lead_knee_angle_contact_deg` | Interior projected hip-knee-ankle angle at estimated contact | Reference-only; not anatomical 3D flexion; eligible with a moving camera |
61
  | `lateral_trunk_tilt_contact_deg` | Null | Requested anatomical tilt not established by face-on 2D |
@@ -77,6 +77,10 @@ Blur is the existing uncalibrated `1/(1+Laplacian variance/100)` heuristic. Pose
77
 
78
  `tests/fixtures/outdoor_swing_pose.json` contains numeric pose observations from the supplied 25-playback-FPS outdoor recording. Its Colab run used the corrected pose checkpoint. Broad visually reviewed frame windows catch the old failure: swing start/contact were assigned to bat lowering at frames 105/110 instead of the swinging movement around 75–82. Version 3 replays the saved points with onset at 75 and estimated extension/contact at 79; the walkthrough contact proxy moves from 76 to 75. These checks establish the regression repair, not independently measured contact accuracy. The outdoor lead feet overlap in projection at frame 79, so its at-contact hip/knee measurements are now withheld by the existing lead-leg ambiguity check instead of being calculated during the later reset. Tests also cover caller-declared ranges, unknown view, mirroring/camera translation, raw-point gaps, contradictory projected direction and extension available only during reset.
79
 
 
 
 
 
80
  ## Validation remaining
81
 
82
  The exact external `ai_coach.validate` and schemas were not supplied. Engine tests check its own matching payload schema, units, supplied plausible bounds, known capture reasons, timing gates, null notes, numerical trajectories, abstention and HTTP delivery. Deployment still needs target-GPU execution and original-video checks. Real baseball point/event/metric errors and confidence calibration remain unmeasured; the separate coach should treat current values as estimates.
 
1
  # 2D batting measurement definitions
2
 
3
+ Version: `batting-2d-v4`. Scope: face-on batting, with fixed-camera requirements only for ground-foot events and head movement. This module uses GPU pose/person outputs and CPU arithmetic, with no SAM, temporal 3D fitting, OpenSim or coaching decisions.
4
 
5
  ## Pose checkpoint and foot points
6
 
 
53
  |---|---|---|
54
  | `stride_pct_height` | `100 × abs(lead_ankle_x - back_ankle_x) / image_height_scale` at estimated foot plant | Lead side, plant and scale |
55
  | `com_drift_pct_height` | `100 × pitcher_direction × (hip_midpoint_x - lead_ankle_x) / scale` at estimated contact | Negative is behind; hip proxy, not whole-body center of mass; same-frame estimate eligible with a moving camera |
56
+ | `foot_plant_to_contact_ms` | Physical contact time minus physical plant time, ×1000 | Both events; documented capture intervals <=1/60 s |
57
+ | `load_tempo_s` | Physical forward-onset time minus physical hand-load-start time | Both events; documented capture intervals <=1/60 s |
58
+ | `load_launch_ratio` | Load duration / physical onset-to-contact duration | All events; positive denominator; documented capture intervals <=1/60 s |
59
  | `head_movement_pct_height` | Sum of consecutive analytical nose displacements from stance to estimated contact, /scale ×100 | Fixed camera, complete analytical path; reference-only |
60
  | `lead_knee_angle_contact_deg` | Interior projected hip-knee-ankle angle at estimated contact | Reference-only; not anatomical 3D flexion; eligible with a moving camera |
61
  | `lateral_trunk_tilt_contact_deg` | Null | Requested anatomical tilt not established by face-on 2D |
 
77
 
78
  `tests/fixtures/outdoor_swing_pose.json` contains numeric pose observations from the supplied 25-playback-FPS outdoor recording. Its Colab run used the corrected pose checkpoint. Broad visually reviewed frame windows catch the old failure: swing start/contact were assigned to bat lowering at frames 105/110 instead of the swinging movement around 75–82. Version 3 replays the saved points with onset at 75 and estimated extension/contact at 79; the walkthrough contact proxy moves from 76 to 75. These checks establish the regression repair, not independently measured contact accuracy. The outdoor lead feet overlap in projection at frame 79, so its at-contact hip/knee measurements are now withheld by the existing lead-leg ambiguity check instead of being calculated during the later reset. Tests also cover caller-declared ranges, unknown view, mirroring/camera translation, raw-point gaps, contradictory projected direction and extension available only during reset.
79
 
80
+ ## Optional 3D and quality layer
81
+
82
+ The API can now apply `measurement-quality-v1` and optional RTMW3D/SAM event-window estimates after this 2D stage. See [NINE_MEASUREMENTS.md](NINE_MEASUREMENTS.md) for all nine definitions, camera assumptions, rejection gates and Colab/model choices. Version 4 supports documented variable-cadence physical timestamps at sufficient cadence; unknown clocks still withhold timing. This module itself does not infer 3D.
83
+
84
  ## Validation remaining
85
 
86
  The exact external `ai_coach.validate` and schemas were not supplied. Engine tests check its own matching payload schema, units, supplied plausible bounds, known capture reasons, timing gates, null notes, numerical trajectories, abstention and HTTP delivery. Deployment still needs target-GPU execution and original-video checks. Real baseball point/event/metric errors and confidence calibration remain unmeasured; the separate coach should treat current values as estimates.
docs/GPU_API_DEPLOYMENT.md CHANGED
@@ -1,12 +1,12 @@
1
- # Deploy the 2D GPU API
2
 
3
- This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. SAM 3D Body, temporal 3D fitting, OpenSim, bat 3D, and coaching are disabled. The Colab notebook remains available separately.
4
 
5
  Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain `est` pending independent validation. Weak events and unsupported angles are withheld. See [API_FOR_COACH.md](API_FOR_COACH.md) for the handoff and [BATTING_2D_MEASUREMENTS.md](BATTING_2D_MEASUREMENTS.md) for definitions and limitations.
6
 
7
  ## GPU server with Docker
8
 
9
- Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the two model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee.
10
 
11
  Install Docker with Compose and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see [ONNX CUDA requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html). The image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras, with no PyTorch or SAM installation.
12
 
@@ -31,7 +31,7 @@ docker compose up -d --build
31
  curl --fail http://127.0.0.1:8000/readyz
32
  ```
33
 
34
- The image build downloads only the RTMW-x and HumanArt person models and verifies their SHA-256 values. A build fails if a required download or checksum fails. Startup runs actual pose and person inference on CUDA; `/readyz` returns 503 until it passes. A missing GPU or broken CUDA setup prevents video jobs from being accepted. This confirms GPU execution, not measurement accuracy.
35
 
36
  RTMLib is installed with `--no-deps` for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently `pip check` reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution.
37
 
@@ -94,3 +94,29 @@ Errors include `invalid_video_or_capture`, `inference_failed`, `job_timeout`, an
94
  Automated tests cover the HTTP/job lifecycle, authorization, size limits, cancellation, timeout, retention, restart recovery, output mapping, null points, and physical timing. CPU inference can exercise the data path locally. The deployment still needs its real CUDA startup check and one real uploaded recording to finish on the target GPU.
95
 
96
  The service returns `validation: reference_validation_pending` and `estimated_only: true`. Pose scores and measurement estimates have not been calibrated against baseball reference labels. Missing events and null metrics carry reasons. The separate coach payload is checksummed and excludes pose data; jobs completed with the older pose-only image have no coach payload and must be resubmitted after updating the image.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploy the GPU measurement API
2
 
3
+ This service accepts batting recordings and returns body/foot points and estimated swing measurements for the separate coach agent. The API always uses CUDA for pose/person inference; measurement arithmetic uses the resulting 2D points. Lightweight RTMW3D is optional per request. SAM can be added in a separate worker/image; temporal fitting, OpenSim, bat 3D and coaching do not run. The Colab notebook remains available separately.
4
 
5
  Automatic rep/event detection is a versioned 2D heuristic, and all computed measurements remain `est` pending independent validation. Weak events and unsupported angles are withheld. See [API_FOR_COACH.md](API_FOR_COACH.md) for the handoff and [BATTING_2D_MEASUREMENTS.md](BATTING_2D_MEASUREMENTS.md) for definitions and limitations.
6
 
7
  ## GPU server with Docker
8
 
9
+ Use a Linux x86-64 NVIDIA GPU server. A T4 is the GPU already used successfully for this project's 2D models in Colab. Have sufficient RAM and disk for the three model files, their temporary downloads, uploads, and results; start with 8 GB host RAM and 20 GB free disk, then size storage for your workload. These are deployment starting points, not a tested throughput guarantee.
10
 
11
  Install Docker with Compose and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html). Configure the Docker runtime for GPU access as described there. The host driver must support the CUDA libraries used by ONNX Runtime 1.26.0; see [ONNX CUDA requirements](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html). The image installs the GPU runtime and NVIDIA CUDA/cuDNN pip extras, with no PyTorch or SAM installation.
12
 
 
31
  curl --fail http://127.0.0.1:8000/readyz
32
  ```
33
 
34
+ The image build downloads the RTMW-x, HumanArt person and optional RTMW3D models and verifies their SHA-256 values. A build fails if a required download or checksum fails. Startup runs actual pose and person inference on CUDA; `/readyz` returns 503 until it passes. A missing GPU or broken CUDA setup prevents video jobs from being accepted. This confirms GPU execution, not measurement accuracy.
35
 
36
  RTMLib is installed with `--no-deps` for its preprocessing and decoder helpers. Its metadata asks for CPU ONNX and two GUI OpenCV distributions; this service uses GPU ONNX and headless OpenCV. Consequently `pip check` reports those distribution mismatches. The image checks the actual helper imports, and startup checks actual model execution.
37
 
 
94
  Automated tests cover the HTTP/job lifecycle, authorization, size limits, cancellation, timeout, retention, restart recovery, output mapping, null points, and physical timing. CPU inference can exercise the data path locally. The deployment still needs its real CUDA startup check and one real uploaded recording to finish on the target GPU.
95
 
96
  The service returns `validation: reference_validation_pending` and `estimated_only: true`. Pose scores and measurement estimates have not been calibrated against baseball reference labels. Missing events and null metrics carry reasons. The separate coach payload is checksummed and excludes pose data; jobs completed with the older pose-only image have no coach payload and must be resubmitted after updating the image.
97
+
98
+ ## Optional SAM on Docker
99
+
100
+ The standard image already supports `measurement_backend: "rtmw3d"`. To offer SAM as well, obtain the normally approved SAM snapshot (`model.ckpt`, `model_config.yaml`, `assets/mhr_model.pt`) on your server and set `BASEBALL_SAM_ASSET_DIRECTORY` to that directory. Keep it outside Git. Credentials are not passed into Docker builds.
101
+
102
+ Build the base image first, then the SAM overlay:
103
+
104
+ ```bash
105
+ docker compose build api
106
+ docker compose -f compose.yaml -f deploy/compose.sam.yaml build api
107
+ ```
108
+
109
+ Register the installed runtime and mounted assets once. This records checksums without loading the model:
110
+
111
+ ```bash
112
+ docker compose -f compose.yaml -f deploy/compose.sam.yaml run --rm --no-deps --entrypoint python api \
113
+ -m tools.register_sam_api_worker \
114
+ --worker-python /opt/sam-runtime/bin/python --sam-repo /opt/sam-source \
115
+ --sam-checkpoint /opt/sam-assets/model.ckpt --sam-config /opt/sam-assets/model_config.yaml \
116
+ --mhr-path /opt/sam-assets/assets/mhr_model.pt --output /data/sam-api-worker.json
117
+ docker compose -f compose.yaml -f deploy/compose.sam.yaml up -d api
118
+ ```
119
+
120
+ The overlay mounts assets read-only and reads `/data/sam-api-worker.json`. SAM is loaded only when a request selects `sam3d`. Lightweight/2D jobs do not load PyTorch. The optional image needs more build time, RAM, disk and GPU memory; its target-GPU inference still needs testing. No OpenSim or temporal fitting is installed/run by this path.
121
+
122
+ `/v1/capabilities` lists configured measurement backends. `/readyz` verifies the required 2D CUDA worker; optional 3D CUDA execution is verified during the selected inference. A failed optional backend returns partial measurements with a reason, not silent CPU/model fallback. See [NINE_MEASUREMENTS.md](NINE_MEASUREMENTS.md) for selection and experimental accuracy status.
docs/NINE_MEASUREMENTS.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nine batting measurements and selectable 3D
2
+
3
+ The API now has calculation paths for all nine fields. A value is returned only when its recording, event, geometry and stability checks pass. Every value remains `confidence: "est"`. Implemented calculations, a successful GPU run and stable numbers do not establish real-world accuracy.
4
+
5
+ ## Choose a model
6
+
7
+ Set the upload option `measurement_backend`:
8
+
9
+ | Value | What runs |
10
+ |---|---|
11
+ | `2d` | Existing RTMW-x body/foot tracking and 2D estimates; anatomical trunk/separation fields remain unavailable |
12
+ | `rtmw3d` | Same 2D tracking, then RTMW3D-x ONNX on short contact/foot-plant windows |
13
+ | `sam3d` | Same 2D tracking, then SAM 3D Body in a separate interpreter on the same event windows |
14
+
15
+ The default remains `2d` for existing clients. The standard Docker image includes the public lightweight model. SAM is optional and requires an installed worker plus normal approved provider access to its weights. A missing/failed selected model is reported explicitly; it never silently switches to another model. Supported 2D fields can still be returned.
16
+
17
+ API upload options are ordinary JSON alongside the video:
18
+
19
+ ```json
20
+ {
21
+ "measurement_backend": "rtmw3d",
22
+ "handedness": "right",
23
+ "pitcher_direction": "image_left",
24
+ "view": "face_on",
25
+ "camera_stability": "fixed_verified",
26
+ "timing": {"kind": "unretimed", "source": "original camera file; no retiming"}
27
+ }
28
+ ```
29
+
30
+ Use those recording declarations only when they describe the video. Changing `measurement_backend` to `sam3d` selects SAM; the three HTTP endpoints for upload, status and coach payload are unchanged.
31
+
32
+ ## What each field means
33
+
34
+ | Field | Calculation | Main requirements |
35
+ |---|---|---|
36
+ | `stride_pct_height` | Horizontal ankle-to-ankle span at estimated settled foot plant, divided by image stature | Fixed camera, identified lead leg, observed plant, valid scale |
37
+ | `foot_plant_to_contact_ms` | Actual capture-time difference between estimated plant and contact | Both events, documented timestamps, capture intervals <= 1/60 s, adequate event resolution |
38
+ | `com_drift_pct_height` | Hip midpoint horizontal position relative to lead ankle at estimated contact | Identified lead leg, pitcher direction, scale; this follows the coach contract and is not whole-body centre of mass |
39
+ | `load_tempo_s` | Hand-load start to swing onset in capture seconds | Both events, documented timestamps and adequate resolution |
40
+ | `load_launch_ratio` | Load duration / onset-to-contact duration | Three events, documented timestamps, denominator resolved under frame shifts |
41
+ | `head_movement_pct_height` | Smoothed nose path from stance to estimated contact, divided by image stature | Fixed camera, complete analytical path, scale; noise-dominated paths withheld; reference-only |
42
+ | `lead_knee_angle_contact_deg` | 3D interior hip-knee-ankle angle at estimated contact; 180° straight | Supported adjacent 3D frames and identified lead leg; 2D mode retains only its explicitly projected reference estimate |
43
+ | `lateral_trunk_tilt_contact_deg` | Midhip-to-midshoulder lean in the pelvis lateral plane; positive toward the anatomical lead side | Stable 3D hip/shoulder axes and camera vertical |
44
+ | `hip_shoulder_separation_foot_plant_deg` | Angle between hip/shoulder landmark lines projected onto the plane perpendicular to vertical, modulo 180°, in [-90,90) | Estimated plant and stable 3D hip/shoulder axes |
45
+
46
+ These last two definitions are explicit landmark constructions. They do not claim clinical joint-coordinate-system angles or an OpenSim anatomical fit. The detailed external `POSE_DATA_SPEC.md` and coach validator were not supplied; the coach developer should confirm the signed-angle conventions. The coach's documented policy should continue treating unvalidated 3D as reference-only.
47
+
48
+ Contact still means estimated lead-arm extension during the primary swing, not confirmed bat-ball impact. Plant means a settled-foot proxy, not measured full body-weight loading. A no-stride/no-load swing may legitimately lack those events. 3D cannot recover an unknown capture clock or prove ground force.
49
+
50
+ ## Stability checks and evidence
51
+
52
+ The raw exported 2D track stays unchanged. The analytical track retains bounded three-frame interpolation/median filtering and the v3 event repair. Version `batting-2d-v4` additionally permits documented variable-cadence timestamps when every capture interval in the rep is <= 1/60 s; playback time still never supplies physical swing time.
53
+
54
+ `measurement-quality-v1` adds:
55
+
56
+ - Raw joint support near measurement events; large raw-versus-filtered joint changes withhold a value.
57
+ - Nearby-frame position sensitivity for stride and hip position. More than six percentage points of variation withholds the value.
58
+ - Raw-versus-filtered head path checks to reject noise-dominated paths.
59
+ - Timing sensitivity when each event shifts by one frame. Nonpositive/poorly resolved durations or ratios are withheld.
60
+ - 3D projections must agree with raw 2D joints within 5% of image stature. This is agreement between models, not comparison to truth.
61
+ - Three consecutive supported 3D frames around the actual event. No missing-event substitution or interpolation of unavailable 3D.
62
+ - Broad segment-length bounds and at most 25% local length variation.
63
+ - A pelvis-relative three-frame median before 3D angle calculation; raw model points remain in the experimental export.
64
+ - Nearby-frame angle sensitivity limits: knee 15°, trunk 12°, separation 20°. These are initial conservative engineering gates, not measured error limits.
65
+
66
+ `measurement_diagnostics` in the full result explains each value or omission. Frame-shift ranges and camera-prior sensitivity are stress checks, **not accuracy confidence intervals**. The compact coach payload keeps exactly its existing nine entries, units and `est` labels; no new keys are required by the coach.
67
+
68
+ ## Camera assumptions in lightweight 3D
69
+
70
+ The pinned RTMW3D model predicts image/crop XY and pelvis-relative Z in metres. Crop pixels must never be combined directly with depth in metres. The adapter unwarps XY into the upright image and back-projects with camera intrinsics and an estimated pelvis depth.
71
+
72
+ Optional upload inputs improve the geometry declaration:
73
+
74
+ - `camera`: `{fx, fy, cx, cy, source}` in upright decoded pixels, after any rotation.
75
+ - `height_m`: actual player height when known. Height alone is not camera calibration.
76
+ - `root_depth_m` and `root_depth_source`: measured pelvis distance along camera Z.
77
+ - `camera_up`: direction of vertical in camera axes; defaults to `[0,-1,0]`, assuming a level upright camera.
78
+
79
+ Without intrinsics the declared prior is focal length `1.2 × max(width,height)` and image-centre principal point. Without measured pelvis depth, a weak-perspective depth uses declared player height, or an explicitly assumed 1.75 m stature, and the projected skeleton scale. If scale is unavailable the model's training-set depth prior is recorded. These are assumptions, not recovered camera calibration.
80
+
81
+ When geometry is assumed, lightweight angles are stressed with independent ±15% focal/depth changes and withheld if they exceed the same angle sensitivity limits. The true camera can lie outside that perturbation band. Supplying accurate calibration/depth removes that particular prior check but does not validate model predictions. Inferred metre coordinates remain experimental.
82
+
83
+ SAM supplies its own predicted camera translation. The adapter verifies its projection/unit convention and maps native MHR landmarks to COCO-17. It does not divide already converted coordinates by 100 or flip their axes again. SAM provides no calibrated joint confidence; its exported scores remain null. 2D agreement and stability gates still apply. Its default FOV is recorded when camera calibration is absent.
84
+
85
+ ## Colab comparison
86
+
87
+ Open [batting_measurements_test.ipynb](../notebooks/batting_measurements_test.ipynb). It has the familiar eight steps. In step 3 set `MEASUREMENT_BACKEND` to `rtmw3d`, `sam3d` or `2d`.
88
+
89
+ Run steps 1–8 for the first test. To compare another model on the same recording, change step 3 and rerun steps 3–8. A fresh job and backend-labelled ZIP are created, retaining source commit, input hash, recording options, raw points, measurements, 3D diagnostics and previews. The existing 2D-only notebook remains available separately.
90
+
91
+ For SAM, set `EXISTING_SAM_RECORD` to an earlier installed `full-worker.json` to reuse that environment/assets. Otherwise setup installs only the isolated SAM inference environment and reads `HF_TOKEN` from a Colab secret or hidden input. Provider approval is still required. Setup never runs anatomy checks or temporal reconstruction.
92
+
93
+ Each detected contact/plant requests at most five frames, deduplicated across events. The worker processes at most 300 selected frames; excess complete windows are recorded as omitted. SAM's subprocess has a 600-second timeout; the lightweight worker checks a 600-second budget between frames. The enclosing API job has its own configurable timeout. Thus a one-swing recording with only contact normally requests five 3D frames rather than every frame. These limits are not a performance guarantee. Model loading/setup remain separate costs.
94
+
95
+ The full result stores selected camera-coordinate points in `experimental_body3d`, outside the validated-only `pose_track.kp3d` contract. No unvalidated dense `kp3d` block is claimed or sent to the coach. A `ready` 3D status means inference produced the requested frames, not that all measurements passed their checks.
96
+
97
+ ## Accuracy status
98
+
99
+ Constructed geometry tests check all nine calculation paths, known 3D angles, units, side/sign conventions, frame resolution, missing support and rejection behavior. A real ONNX run checks execution and output topology. Neither replaces an independently measured batting reference. All outputs still report `reference_validation_pending`; no high/medium labels or claimed accuracy percentages are introduced.
100
+
101
+ Upstream references: [RTMW3D model definitions](https://github.com/open-mmlab/mmpose/tree/main/projects/rtmpose3d), [RTMLib 3D decoder](https://github.com/Tau-J/rtmlib/blob/03a1693e59e4f7cd84582c0fb30459b3bf18ad42/rtmlib/tools/pose_estimation/rtmpose3d.py), [pinned ONNX export](https://huggingface.co/Soykaf/RTMW3D-x/tree/a4f0d54c52ee44ee4e1dda1936d714490c6234d2), [SAM 3D Body](https://github.com/facebookresearch/sam-3d-body/tree/b5c765a0d89d789985e186d396315e7590887b94).
docs/api-result.schema.json CHANGED
@@ -47,7 +47,7 @@
47
  "const": true
48
  },
49
  "body_3d": {
50
- "const": false
51
  },
52
  "automatic_rep_splitting": {
53
  "const": true
@@ -629,7 +629,12 @@
629
  ],
630
  "properties": {
631
  "version": {
632
- "enum": ["batting-2d-v1", "batting-2d-v2", "batting-2d-v3"]
 
 
 
 
 
633
  },
634
  "body_height_px": {
635
  "type": [
@@ -656,6 +661,242 @@
656
  },
657
  "validation": {
658
  "const": "reference_validation_pending"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
659
  }
660
  }
661
  }
 
47
  "const": true
48
  },
49
  "body_3d": {
50
+ "type": "boolean"
51
  },
52
  "automatic_rep_splitting": {
53
  "const": true
 
629
  ],
630
  "properties": {
631
  "version": {
632
+ "enum": [
633
+ "batting-2d-v1",
634
+ "batting-2d-v2",
635
+ "batting-2d-v3",
636
+ "batting-2d-v4"
637
+ ]
638
  },
639
  "body_height_px": {
640
  "type": [
 
661
  },
662
  "validation": {
663
  "const": "reference_validation_pending"
664
+ },
665
+ "backend": {
666
+ "enum": [
667
+ "2d",
668
+ "rtmw3d",
669
+ "sam3d"
670
+ ]
671
+ },
672
+ "quality_version": {
673
+ "const": "measurement-quality-v1"
674
+ }
675
+ }
676
+ },
677
+ "experimental_body3d": {
678
+ "type": "object",
679
+ "additionalProperties": false,
680
+ "required": [
681
+ "backend",
682
+ "status",
683
+ "reason",
684
+ "validation",
685
+ "unit",
686
+ "frame_of_reference",
687
+ "axes",
688
+ "frames",
689
+ "requested_frames",
690
+ "omitted_windows",
691
+ "elapsed_s"
692
+ ],
693
+ "properties": {
694
+ "backend": {
695
+ "enum": [
696
+ "2d",
697
+ "rtmw3d",
698
+ "sam3d"
699
+ ]
700
+ },
701
+ "status": {
702
+ "enum": [
703
+ "disabled",
704
+ "unavailable",
705
+ "ready",
706
+ "partial"
707
+ ]
708
+ },
709
+ "reason": {
710
+ "type": "string"
711
+ },
712
+ "validation": {
713
+ "const": "reference_validation_pending"
714
+ },
715
+ "unit": {
716
+ "const": "m"
717
+ },
718
+ "frame_of_reference": {
719
+ "const": "camera"
720
+ },
721
+ "axes": {
722
+ "const": "x right, y down, z away"
723
+ },
724
+ "frames": {
725
+ "type": "array",
726
+ "items": {
727
+ "type": "object",
728
+ "required": [
729
+ "frame",
730
+ "points",
731
+ "projection",
732
+ "scores"
733
+ ],
734
+ "additionalProperties": false,
735
+ "properties": {
736
+ "frame": {
737
+ "type": "integer",
738
+ "minimum": 0
739
+ },
740
+ "points": {
741
+ "type": "array",
742
+ "minItems": 17,
743
+ "maxItems": 17,
744
+ "items": {
745
+ "type": "array",
746
+ "minItems": 3,
747
+ "maxItems": 3,
748
+ "items": {
749
+ "type": [
750
+ "number",
751
+ "null"
752
+ ]
753
+ }
754
+ }
755
+ },
756
+ "projection": {
757
+ "type": "array",
758
+ "minItems": 17,
759
+ "maxItems": 17,
760
+ "items": {
761
+ "type": "array",
762
+ "minItems": 2,
763
+ "maxItems": 2,
764
+ "items": {
765
+ "type": [
766
+ "number",
767
+ "null"
768
+ ]
769
+ }
770
+ }
771
+ },
772
+ "scores": {
773
+ "type": "array",
774
+ "minItems": 17,
775
+ "maxItems": 17,
776
+ "items": {
777
+ "type": [
778
+ "number",
779
+ "null"
780
+ ],
781
+ "minimum": 0,
782
+ "maximum": 1
783
+ }
784
+ },
785
+ "relative_depth_m": {
786
+ "type": "array",
787
+ "minItems": 17,
788
+ "maxItems": 17,
789
+ "items": {
790
+ "type": [
791
+ "number",
792
+ "null"
793
+ ]
794
+ }
795
+ },
796
+ "camera_intrinsics": {
797
+ "type": "array",
798
+ "minItems": 3,
799
+ "maxItems": 3,
800
+ "items": {
801
+ "type": "array",
802
+ "minItems": 3,
803
+ "maxItems": 3,
804
+ "items": {
805
+ "type": [
806
+ "number",
807
+ "null"
808
+ ]
809
+ }
810
+ }
811
+ },
812
+ "depth_peak_response": {
813
+ "type": "array",
814
+ "minItems": 17,
815
+ "maxItems": 17,
816
+ "items": {
817
+ "type": [
818
+ "number",
819
+ "null"
820
+ ]
821
+ }
822
+ }
823
+ }
824
+ }
825
+ },
826
+ "requested_frames": {
827
+ "type": "array",
828
+ "items": {
829
+ "type": "integer",
830
+ "minimum": 0
831
+ }
832
+ },
833
+ "omitted_windows": {
834
+ "type": "array",
835
+ "items": {
836
+ "type": "object"
837
+ }
838
+ },
839
+ "elapsed_s": {
840
+ "type": "number",
841
+ "minimum": 0
842
+ },
843
+ "model": {
844
+ "type": "object"
845
+ },
846
+ "geometry": {
847
+ "type": "object"
848
+ }
849
+ }
850
+ },
851
+ "measurement_diagnostics": {
852
+ "type": "array",
853
+ "items": {
854
+ "type": "object",
855
+ "additionalProperties": false,
856
+ "required": [
857
+ "rep",
858
+ "metrics"
859
+ ],
860
+ "properties": {
861
+ "rep": {
862
+ "type": "integer",
863
+ "minimum": 1
864
+ },
865
+ "metrics": {
866
+ "type": "array",
867
+ "minItems": 9,
868
+ "maxItems": 9,
869
+ "items": {
870
+ "type": "object",
871
+ "required": [
872
+ "key",
873
+ "status",
874
+ "method",
875
+ "validation",
876
+ "note"
877
+ ],
878
+ "properties": {
879
+ "key": {
880
+ "type": "string"
881
+ },
882
+ "status": {
883
+ "enum": [
884
+ "estimated",
885
+ "withheld"
886
+ ]
887
+ },
888
+ "method": {
889
+ "type": "string"
890
+ },
891
+ "validation": {
892
+ "const": "reference_validation_pending"
893
+ },
894
+ "note": {
895
+ "type": "string"
896
+ }
897
+ }
898
+ }
899
+ }
900
  }
901
  }
902
  }
notebooks/batting_measurements_test.ipynb ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 5,
4
+ "metadata": {
5
+ "kernelspec": {
6
+ "display_name": "Python 3",
7
+ "language": "python",
8
+ "name": "python3"
9
+ },
10
+ "language_info": {
11
+ "name": "python"
12
+ },
13
+ "accelerator": "GPU",
14
+ "colab": {
15
+ "name": "batting_measurements_test.ipynb",
16
+ "provenance": []
17
+ }
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {},
23
+ "source": [
24
+ "# Test nine batting measurements: choose a 3D model\n",
25
+ "\n",
26
+ "This runs the **same 2D worker used by the engine API**. Upload one video with several swings, inspect the detected ranges and their clip previews, and download `coach-payload.json`. Choose `rtmw3d` (lightweight GPU ONNX), `sam3d` (SAM 3D Body), or `2d`. 3D runs only around detected contact/foot-plant events. Coaching stays in your friend's service. It tests the engine's calculations; Docker/HTTP deployment is a separate check.\n",
27
+ "\n",
28
+ "1. In Colab select **Runtime \u2192 Change runtime type \u2192 GPU** (T4 if available), then run the cells in order.\n",
29
+ "2. Start with a short video containing 2\u20133 swings. The whole batter, hands and feet should be visible, with a fixed camera and a known face-on view.\n",
30
+ "3. Enter recording settings only when known. Leave `SINGLE_SWING=False` to test automatic splitting.\n",
31
+ "4. Watch each candidate preview. Check that each contains one swing and includes preparation/finish. Check for missed swings and setup movements mistaken for swings.\n",
32
+ "5. Download the ZIP. It contains measurements, ranges, previews and logs. The original video and model weights are excluded.\n",
33
+ "\n",
34
+ "Swings, events and measurements remain estimates. A clean run or plausible preview does not establish accuracy. GPU availability is controlled by Colab; see [Colab's help](https://research.google.com/colaboratory/faq.html).\n"
35
+ ],
36
+ "id": "batting-measurements-000"
37
+ },
38
+ {
39
+ "cell_type": "markdown",
40
+ "metadata": {},
41
+ "source": [
42
+ "## 1. Get the current engine\n",
43
+ "\n",
44
+ "Use a GitHub token with read access to your private repository. The hidden token is used only during checkout and is not saved in the Git URL or results. Setup records the resolved commit. This notebook uses a separate workspace from the full pipeline notebook.\n"
45
+ ],
46
+ "id": "batting-measurements-001"
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "\"\"\"Readable GitHub bootstrap, copied into the first Colab code cell by the builder.\"\"\"\n",
53
+ "from pathlib import Path\n",
54
+ "from contextlib import contextmanager\n",
55
+ "import base64\n",
56
+ "import json\n",
57
+ "import os\n",
58
+ "import re\n",
59
+ "import subprocess\n",
60
+ "import sys\n",
61
+ "\n",
62
+ "\n",
63
+ "def _git(directory, *arguments, auth_env=None):\n",
64
+ " environment = {**os.environ, \"GIT_TERMINAL_PROMPT\": \"0\", **(auth_env or {})}\n",
65
+ " result = subprocess.run(\n",
66
+ " [\"git\", \"-C\", str(directory), *arguments], text=True,\n",
67
+ " stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,\n",
68
+ " )\n",
69
+ " if result.returncode:\n",
70
+ " detail = result.stderr.strip() or result.stdout.strip() or \"Git returned no error detail\"\n",
71
+ " secret = (auth_env or {}).get(\"BATTING_GITHUB_TOKEN\")\n",
72
+ " if secret:\n",
73
+ " encoded = base64.b64encode(f\"x-access-token:{secret}\".encode()).decode()\n",
74
+ " detail = detail.replace(secret, \"[REDACTED]\").replace(encoded, \"[REDACTED]\")\n",
75
+ " detail = re.sub(r\"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+\", \"[REDACTED]\", detail)\n",
76
+ " raise RuntimeError(f\"Git failed (exit {result.returncode}):\\n{detail[-4000:]}\") from None\n",
77
+ " return result.stdout.strip()\n",
78
+ "\n",
79
+ "\n",
80
+ "@contextmanager\n",
81
+ "def _github_credentials(token, scope=\"https://github.com/\"):\n",
82
+ " if not token:\n",
83
+ " yield {}\n",
84
+ " return\n",
85
+ " # Git reads these settings only for this subprocess; no token is stored in its URL/config.\n",
86
+ " count = int(os.environ.get(\"GIT_CONFIG_COUNT\", \"0\"))\n",
87
+ " encoded = base64.b64encode(f\"x-access-token:{token}\".encode()).decode()\n",
88
+ " yield {\n",
89
+ " \"GIT_CONFIG_COUNT\": str(count + 2),\n",
90
+ " f\"GIT_CONFIG_KEY_{count}\": f\"http.{scope}.extraHeader\",\n",
91
+ " f\"GIT_CONFIG_VALUE_{count}\": \"\",\n",
92
+ " f\"GIT_CONFIG_KEY_{count + 1}\": f\"http.{scope}.extraHeader\",\n",
93
+ " f\"GIT_CONFIG_VALUE_{count + 1}\": f\"Authorization: Basic {encoded}\",\n",
94
+ " \"BATTING_GITHUB_TOKEN\": token,\n",
95
+ " }\n",
96
+ "\n",
97
+ "\n",
98
+ "def checkout_github(repository_url, revision, workspace, token=None):\n",
99
+ " \"\"\"Fetch an explicit ref and stop before replacing modified source files.\"\"\"\n",
100
+ " if token is not None:\n",
101
+ " token = token.strip()\n",
102
+ " if not token:\n",
103
+ " raise ValueError(\"Enter a token with read access to this repository\")\n",
104
+ " if not re.fullmatch(r\"https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\\.git)?/?\", repository_url):\n",
105
+ " raise ValueError(\"Use an HTTPS GitHub repository URL without credentials or query parameters\")\n",
106
+ " if any(part in {\".\", \"..\"} for part in repository_url.split(\"/\")[3:]):\n",
107
+ " raise ValueError(\"Use an owner/repository GitHub URL\")\n",
108
+ " if not revision or revision.startswith(\"-\") or any(c.isspace() for c in revision):\n",
109
+ " raise ValueError(\"Set a branch, tag, or full commit SHA\")\n",
110
+ " workspace = Path(workspace).resolve()\n",
111
+ " source = workspace / \"source\"\n",
112
+ " workspace.mkdir(parents=True, exist_ok=True)\n",
113
+ " with _github_credentials(token) as authentication:\n",
114
+ " options = (\"-c\", \"credential.helper=\") if token else ()\n",
115
+ " fresh_checkout = False\n",
116
+ " if not (source / \".git\").exists():\n",
117
+ " if source.exists() and any(source.iterdir()):\n",
118
+ " raise ValueError(f\"Source directory is not an empty Git checkout: {source}\")\n",
119
+ " _git(workspace, *options, \"clone\", \"--no-checkout\", \"--depth=1\", repository_url,\n",
120
+ " str(source), auth_env=authentication)\n",
121
+ " fresh_checkout = True\n",
122
+ " if _git(source, \"config\", \"--get\", \"remote.origin.url\") != repository_url:\n",
123
+ " raise ValueError(\"Existing checkout uses a different repository; choose another workspace\")\n",
124
+ " # A newly cloned --no-checkout repository has no populated index yet.\n",
125
+ " if not fresh_checkout and _git(source, \"status\", \"--porcelain\", \"--untracked-files=no\"):\n",
126
+ " raise ValueError(\"Source has local edits; save them or choose another workspace before updating\")\n",
127
+ " _git(source, *options, \"fetch\", \"--depth=1\", \"origin\", revision, auth_env=authentication)\n",
128
+ " commit = _git(source, \"rev-parse\", \"FETCH_HEAD^{commit}\")\n",
129
+ " if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) and commit.lower() != revision.lower():\n",
130
+ " raise ValueError(\"Fetched commit does not match the requested SHA\")\n",
131
+ " _git(source, \"checkout\", \"--quiet\", \"--detach\", commit)\n",
132
+ " required = [\"baseball_batting/cli.py\", \"requirements-core.txt\", \"configs/resources.yaml\"]\n",
133
+ " if not all((source / name).is_file() for name in required):\n",
134
+ " raise ValueError(\"Selected repository revision does not contain the batting engine\")\n",
135
+ " record = {\"repository_url\": repository_url, \"requested_revision\": revision, \"commit_sha\": commit}\n",
136
+ " (workspace / \"source_checkout.json\").write_text(json.dumps(record, indent=2))\n",
137
+ " print(\"Engine source:\", source)\n",
138
+ " print(\"Resolved commit:\", commit, \"(use this SHA as REVISION to reproduce this run)\")\n",
139
+ " return source, record\n",
140
+ "\n",
141
+ "\n",
142
+ "REPOSITORY_URL = 'https://github.com/usmanthesuper/baseball-engine.git'\n",
143
+ "REVISION = 'main' # Use the recorded full SHA to reproduce a run.\n",
144
+ "PRIVATE_REPOSITORY = True\n",
145
+ "WORKSPACE_ROOT = Path(\"/content/baseball_batting_2d\") if Path(\"/content\").exists() else Path.cwd() / \"batting_notebook_runtime\" / \"2d_test\"\n",
146
+ "from getpass import getpass\n",
147
+ "GITHUB_TOKEN = getpass(\"GitHub token with read access to this repository: \") if PRIVATE_REPOSITORY else None\n",
148
+ "try:\n",
149
+ " if PRIVATE_REPOSITORY and not GITHUB_TOKEN:\n",
150
+ " raise ValueError(\"A token is required for this private repository\")\n",
151
+ " ENGINE_ROOT, SOURCE_CHECKOUT = checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)\n",
152
+ "finally:\n",
153
+ " del GITHUB_TOKEN\n"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": [],
157
+ "id": "batting-measurements-002"
158
+ },
159
+ {
160
+ "cell_type": "markdown",
161
+ "metadata": {},
162
+ "source": [
163
+ "## 2. Install the GPU worker\n",
164
+ "\n",
165
+ "Dependencies are installed in a separate environment. The lightweight mode needs no PyTorch. SAM setup is isolated and runs only if selected; it skips OpenSim and temporal fitting. Installation must finish before continuing.\n"
166
+ ],
167
+ "id": "batting-measurements-003"
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "import shutil\n",
174
+ "\n",
175
+ "if not shutil.which(\"nvidia-smi\"):\n",
176
+ " raise RuntimeError(\"Select Runtime > Change runtime type > GPU, then reconnect and rerun.\")\n",
177
+ "subprocess.run([\"nvidia-smi\"], check=True)\n",
178
+ "runtime = WORKSPACE_ROOT / \".runtime-api-2d\"\n",
179
+ "worker_path = runtime / \"bin/python\"\n",
180
+ "if runtime.exists() and (not worker_path.is_file() or subprocess.run(\n",
181
+ " [str(worker_path), \"-m\", \"pip\", \"--version\"], capture_output=True).returncode != 0):\n",
182
+ " shutil.rmtree(runtime)\n",
183
+ "if not worker_path.exists():\n",
184
+ " subprocess.run([sys.executable, \"-m\", \"venv\", \"--system-site-packages\", \"--without-pip\",\n",
185
+ " str(runtime)], check=True)\n",
186
+ "WORKER_PYTHON = str(worker_path)\n",
187
+ "WORKER_ENV = {**os.environ, \"MPLBACKEND\": \"Agg\", \"PYTHONUNBUFFERED\": \"1\",\n",
188
+ " \"PYTHONNOUSERSITE\": \"1\", \"PIP_REQUIRE_VIRTUALENV\": \"true\"}\n",
189
+ "WORKER_ENV.pop(\"PYTHONPATH\", None)\n",
190
+ "# Install locally even when Colab has inherited CPU ORT/numpy packages.\n",
191
+ "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n",
192
+ " \"--ignore-installed\", \"-r\", str(ENGINE_ROOT / \"requirements-api-gpu.txt\")],\n",
193
+ " env=WORKER_ENV, check=True)\n",
194
+ "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--ignore-installed\", \"--no-deps\", \"rtmlib==0.0.16\"],\n",
195
+ " env=WORKER_ENV, check=True)\n",
196
+ "def worker_command(module, *arguments):\n",
197
+ " return subprocess.run([WORKER_PYTHON, \"-m\", module, *map(str, arguments)],\n",
198
+ " cwd=ENGINE_ROOT, env=WORKER_ENV, check=True)\n",
199
+ "print(\"2D worker installed. Actual CUDA execution is checked in the next cell.\")\n"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": [],
203
+ "id": "batting-measurements-004"
204
+ },
205
+ {
206
+ "cell_type": "markdown",
207
+ "metadata": {},
208
+ "source": [
209
+ "## 3. Choose a model, download weights and check GPU execution\n",
210
+ "\n",
211
+ "2D models are always downloaded with verified hashes. RTMW3D adds a pinned 369 MB ONNX model. SAM needs approved model access; you may reuse the earlier full-worker installation. This cell must report `ready: true`. It refuses to silently run on CPU.\n"
212
+ ],
213
+ "id": "batting-measurements-005"
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "MEASUREMENT_BACKEND = \"rtmw3d\" # \"rtmw3d\", \"sam3d\", or \"2d\"\n",
220
+ "EXISTING_SAM_RECORD = \"\" # e.g. \"/content/baseball_batting_engine/full-worker.json\"\n",
221
+ "assert MEASUREMENT_BACKEND in {\"2d\", \"rtmw3d\", \"sam3d\"}\n",
222
+ "MODEL_ROOT = WORKSPACE_ROOT / \"models\"\n",
223
+ "worker_command(\"tools.setup_api_models\", \"--output\", MODEL_ROOT, *([\"--with-3d\"] if MEASUREMENT_BACKEND == \"rtmw3d\" else []))\n",
224
+ "PREFLIGHT_PATH = WORKSPACE_ROOT / \"gpu-preflight.json\"\n",
225
+ "worker_command(\"baseball_batting.api_worker\", \"--models\", MODEL_ROOT,\n",
226
+ " \"--preflight\", \"--output\", PREFLIGHT_PATH)\n",
227
+ "preflight = json.loads(PREFLIGHT_PATH.read_text())\n",
228
+ "if not preflight.get(\"ready\") or preflight.get(\"device\") != \"cuda\":\n",
229
+ " raise RuntimeError(\"Actual CUDA preflight did not pass.\")\n",
230
+ "print(json.dumps(preflight, indent=2))\n",
231
+ "\n",
232
+ "print(\"This preflight checked the required 2D CUDA models. The selected 3D model is checked during step 5.\")\n",
233
+ "\n",
234
+ "if MEASUREMENT_BACKEND == \"sam3d\":\n",
235
+ " if not EXISTING_SAM_RECORD:\n",
236
+ " if not os.environ.get(\"HF_TOKEN\"):\n",
237
+ " try:\n",
238
+ " from google.colab import userdata\n",
239
+ " os.environ[\"HF_TOKEN\"] = userdata.get(\"HF_TOKEN\")\n",
240
+ " except Exception:\n",
241
+ " from getpass import getpass\n",
242
+ " os.environ[\"HF_TOKEN\"] = getpass(\"Hugging Face token with approved SAM access: \")\n",
243
+ " WORKER_ENV[\"HF_TOKEN\"] = os.environ[\"HF_TOKEN\"]\n",
244
+ " worker_command(\"tools.setup_sam_api_worker\", \"--workspace\", WORKSPACE_ROOT / \"sam-api\",\n",
245
+ " *([\"--reuse-record\", EXISTING_SAM_RECORD] if EXISTING_SAM_RECORD else []))\n",
246
+ " WORKER_ENV[\"BASEBALL_SAM_WORKER_RECORD\"] = str(WORKSPACE_ROOT / \"sam-api/sam-api-worker.json\")\n",
247
+ " WORKER_ENV.pop(\"HF_TOKEN\", None)\n",
248
+ " os.environ.pop(\"HF_TOKEN\", None)\n"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": [],
252
+ "id": "batting-measurements-006"
253
+ },
254
+ {
255
+ "cell_type": "markdown",
256
+ "metadata": {},
257
+ "source": [
258
+ "## 4. Upload a video and set its recording information\n",
259
+ "\n",
260
+ "You can enter an existing `VIDEO_PATH` or leave it empty to upload. Set `HANDEDNESS` to the batter's own handedness when known. `PITCHER_DIRECTION` is the direction toward the pitcher/tee in the image: `\"image_left\"` or `\"image_right\"`. Leave it `None` if unknown. Cross-step drills can confuse automatic ankle ordering, so an explicit known direction helps.\n",
261
+ "\n",
262
+ "Set `VIEW=\"face_on\"` only for a known face-on recording. Unknown view keeps measurements empty, while ranges and generic motion events can still be inspected. Set `CAMERA_STABILITY=\"moving\"` for a moving camera and `\"fixed_verified\"` only when the camera stays still. Moving/unknown cameras can still return within-frame body positions and projected knee angles when the required events are found. Ground-foot events and head movement require a fixed camera.\n",
263
+ "\n",
264
+ "Keep `TIMING={\"kind\":\"unknown\"}` unless capture timing is known. For an original unretimed recording use `{\"kind\":\"unretimed\",\"source\":\"original camera file; no retiming\"}`. For documented constant slow motion use `{\"kind\":\"constant_slowdown\",\"source\":\"documented camera/export settings\",\"factor\":8,\"all_captured_frames_retained\":True}` with the real factor. Playback FPS is not capture FPS. Timing numbers require a known constant capture rate of at least 60 FPS.\n",
265
+ "\n",
266
+ "Leave `SINGLE_SWING=False` for this multi-swing test. A new upload cell run creates a new job; rerunning only the analysis cell resumes the same job and verified observation cache. The current worker limits are 7,200 frames, 120 playback seconds and 8.3 megapixels per frame.\n",
267
+ "\n",
268
+ "Camera intrinsics, player height and pelvis distance are optional. They refer to the upright video. Leave them empty when unknown: the lightweight model reports its camera/depth assumptions and tests sensitivity. Unknown timing still withholds timing values; 3D cannot recover it. A moving camera still withholds ground-foot and head-path measurements.\n"
269
+ ],
270
+ "id": "batting-measurements-007"
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "from google.colab import files\n",
277
+ "import hashlib\n",
278
+ "import uuid\n",
279
+ "\n",
280
+ "VIDEO_PATH = \"\" # Or, for example: \"/content/IMG_1640.mp4\"\n",
281
+ "HANDEDNESS = None # Set to \"right\" or \"left\" when known.\n",
282
+ "PITCHER_DIRECTION = None # \"image_left\" or \"image_right\" toward the pitcher/tee, when known.\n",
283
+ "VIEW = \"unknown\" # Change to \"face_on\" when known.\n",
284
+ "CAMERA_STABILITY = \"unknown\" # Change to \"fixed_verified\" when the camera stays still.\n",
285
+ "TIMING = {\"kind\": \"unknown\"}\n",
286
+ "SINGLE_SWING = False # False tests automatic separation of multiple swings.\n",
287
+ "HEIGHT_M = None # Actual player height in metres, when known.\n",
288
+ "CAMERA = None # {\"fx\": 1500, \"fy\": 1500, \"cx\": 720, \"cy\": 1280, \"source\": \"upright camera calibration\"}\n",
289
+ "ROOT_DEPTH_M = None # Distance along camera Z to pelvis, when measured.\n",
290
+ "ROOT_DEPTH_SOURCE = None\n",
291
+ "\n",
292
+ "if not VIDEO_PATH:\n",
293
+ " uploaded = files.upload()\n",
294
+ " videos = [name for name in uploaded if name.lower().endswith((\".mp4\", \".mov\", \".mkv\", \".avi\", \".webm\"))]\n",
295
+ " if len(videos) != 1:\n",
296
+ " raise ValueError(\"Upload exactly one video containing the swings.\")\n",
297
+ " VIDEO_PATH = str(Path(videos[0]).resolve())\n",
298
+ " del uploaded\n",
299
+ "source_video = Path(VIDEO_PATH).resolve()\n",
300
+ "if not source_video.is_file():\n",
301
+ " raise ValueError(\"VIDEO_PATH does not exist. Upload the video or correct its path.\")\n",
302
+ "OPTIONS = {\"discipline\": \"hitting\", \"handedness\": HANDEDNESS, \"view\": VIEW,\n",
303
+ " \"pitcher_direction\": PITCHER_DIRECTION,\n",
304
+ " \"camera_stability\": CAMERA_STABILITY, \"timing\": TIMING, \"single_swing\": SINGLE_SWING, \"measurement_backend\": MEASUREMENT_BACKEND,\n",
305
+ " \"height_m\": HEIGHT_M, \"camera\": CAMERA, \"root_depth_m\": ROOT_DEPTH_M,\n",
306
+ " \"root_depth_source\": ROOT_DEPTH_SOURCE}\n",
307
+ "JOB_ROOT = WORKSPACE_ROOT / \"results\" / (\"session-\" + uuid.uuid4().hex[:12])\n",
308
+ "JOB_ROOT.mkdir(parents=True)\n",
309
+ "INPUT_VIDEO = JOB_ROOT / (\"input\" + source_video.suffix.lower())\n",
310
+ "shutil.copy2(source_video, INPUT_VIDEO)\n",
311
+ "(JOB_ROOT / \"request.json\").write_text(json.dumps(OPTIONS, indent=2))\n",
312
+ "(JOB_ROOT / \"source_checkout.json\").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))\n",
313
+ "checksum = hashlib.sha256()\n",
314
+ "with INPUT_VIDEO.open(\"rb\") as stream:\n",
315
+ " for block in iter(lambda: stream.read(1024 * 1024), b\"\"):\n",
316
+ " checksum.update(block)\n",
317
+ "(JOB_ROOT / \"run-context.json\").write_text(json.dumps({\"input_sha256\": checksum.hexdigest(),\n",
318
+ " \"source_video_name\": source_video.name, \"mode\": \"gpu_api_worker_\" + MEASUREMENT_BACKEND}, indent=2))\n",
319
+ "print(\"Job:\", JOB_ROOT.name)\n",
320
+ "print(\"Recording options:\", json.dumps(OPTIONS, indent=2))\n"
321
+ ],
322
+ "execution_count": null,
323
+ "outputs": [],
324
+ "id": "batting-measurements-008"
325
+ },
326
+ {
327
+ "cell_type": "markdown",
328
+ "metadata": {},
329
+ "source": [
330
+ "## 5. Run the selected measurement backend\n",
331
+ "\n",
332
+ "Progress shows decoding, 2D pose extraction, optional 3D event windows and completion. SAM setup/model initialization still costs time, but this run does not reconstruct every video frame. Setup time and video analysis are separate. The worker log is retained if the job fails. Stop this cell to interrupt a run; the observation cache is retained for a rerun in the same runtime.\n"
333
+ ],
334
+ "id": "batting-measurements-009"
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "metadata": {},
339
+ "source": [
340
+ "import signal\n",
341
+ "import time\n",
342
+ "\n",
343
+ "RUN_TIMEOUT_S = 1800\n",
344
+ "WORKER_LOG = JOB_ROOT / \"worker.log\"\n",
345
+ "(JOB_ROOT / \"error.json\").unlink(missing_ok=True)\n",
346
+ "(JOB_ROOT / \"progress.json\").unlink(missing_ok=True)\n",
347
+ "command = [WORKER_PYTHON, \"-m\", \"baseball_batting.api_worker\", \"--models\", str(MODEL_ROOT),\n",
348
+ " \"--job\", str(JOB_ROOT)]\n",
349
+ "started = time.monotonic()\n",
350
+ "with WORKER_LOG.open(\"w\") as log:\n",
351
+ " process = subprocess.Popen(command, cwd=ENGINE_ROOT, env=WORKER_ENV,\n",
352
+ " stdout=log, stderr=subprocess.STDOUT, start_new_session=True)\n",
353
+ " last_print, last_stage = 0., None\n",
354
+ " try:\n",
355
+ " while process.poll() is None:\n",
356
+ " elapsed = time.monotonic()-started\n",
357
+ " if elapsed > RUN_TIMEOUT_S:\n",
358
+ " raise TimeoutError(\"Analysis timed out; inspect worker.log and try a shorter recording.\")\n",
359
+ " progress_path = JOB_ROOT / \"progress.json\"\n",
360
+ " progress = json.loads(progress_path.read_text()) if progress_path.exists() else {\"stage\": \"starting\"}\n",
361
+ " if progress[\"stage\"] != last_stage or elapsed-last_print >= 15:\n",
362
+ " print(f\"{elapsed:.0f}s | {progress['stage']} | \"\n",
363
+ " f\"{progress.get('completed_frames', 0)}/{progress.get('total_frames') or '?'} frames\", flush=True)\n",
364
+ " last_print, last_stage = elapsed, progress[\"stage\"]\n",
365
+ " time.sleep(2)\n",
366
+ " finally:\n",
367
+ " if process.poll() is None:\n",
368
+ " os.killpg(process.pid, signal.SIGTERM)\n",
369
+ " try:\n",
370
+ " process.wait(timeout=5)\n",
371
+ " except subprocess.TimeoutExpired:\n",
372
+ " os.killpg(process.pid, signal.SIGKILL)\n",
373
+ " process.wait()\n",
374
+ "if process.returncode != 0:\n",
375
+ " print(WORKER_LOG.read_text(errors=\"replace\")[-8000:])\n",
376
+ " raise RuntimeError(\"2D analysis failed. The worker log above contains the actual error.\")\n",
377
+ "result = json.loads((JOB_ROOT / \"result.json\").read_text())\n",
378
+ "print(f\"Finished in {time.monotonic()-started:.1f}s. Detected {len(result['pose_track']['reps'])} swing candidates.\")\n"
379
+ ],
380
+ "execution_count": null,
381
+ "outputs": [],
382
+ "id": "batting-measurements-010"
383
+ },
384
+ {
385
+ "cell_type": "markdown",
386
+ "metadata": {},
387
+ "source": [
388
+ "## 6. Inspect swing ranges and measurements\n",
389
+ "\n",
390
+ "The range table uses **video playback positions** for locating clips. Those positions are not physical swing timing. `events_ms` in the coach payload uses the separate physical capture clock when known. `capture.ok:false` asks for a better recording; missing numbers have reasons. All available numbers are marked `est`.\n",
391
+ "\n",
392
+ "Check the number of detected ranges against the swings you can actually see. A zero-candidate result means the algorithm did not separate any swings; it does not prove the video contains none. The first ten reps are displayed below; the JSON download contains all results.\n"
393
+ ],
394
+ "id": "batting-measurements-011"
395
+ },
396
+ {
397
+ "cell_type": "code",
398
+ "metadata": {},
399
+ "source": [
400
+ "from IPython.display import HTML, Video, display\n",
401
+ "import html\n",
402
+ "\n",
403
+ "def table(headers, rows):\n",
404
+ " head = \"\".join(\"<th>\" + html.escape(str(value)) + \"</th>\" for value in headers)\n",
405
+ " body = \"\".join(\"<tr>\" + \"\".join(\"<td>\" + html.escape(str(value)) + \"</td>\" for value in row) + \"</tr>\" for row in rows)\n",
406
+ " display(HTML(\"<table border='1' cellpadding='6'><thead><tr>\" + head + \"</tr></thead><tbody>\" + body + \"</tbody></table>\"))\n",
407
+ "\n",
408
+ "track = result[\"pose_track\"]\n",
409
+ "print(\"Swing candidates:\", len(track[\"reps\"]))\n",
410
+ "print(\"Capture check:\", result[\"measurements\"][\"capture\"])\n",
411
+ "print(\"Real capture FPS:\", track[\"video\"][\"capture_fps\"])\n",
412
+ "for warning in result[\"warnings\"]: print(\"\u2022\", warning)\n",
413
+ "playback = track[\"frames\"][\"playback_t_s\"]\n",
414
+ "def position(index):\n",
415
+ " return round(playback[index]-playback[0], 3) if playback[index] is not None and playback[0] is not None else \"unknown\"\n",
416
+ "table([\"Swing\", \"First frame\", \"Last frame (included)\", \"Video start (s)\", \"Video end (s)\", \"Boundary method\"],\n",
417
+ " [[rep[\"rep\"], rep[\"start_frame\"], rep[\"end_frame\"], position(rep[\"start_frame\"]),\n",
418
+ " position(rep[\"end_frame\"]), rep[\"boundary_method\"]] for rep in track[\"reps\"]])\n",
419
+ "for rep in result[\"measurements\"][\"reps\"][:10]:\n",
420
+ " print(\"Swing\", rep[\"rep\"], \"| estimated physical events_ms:\", rep[\"events_ms\"])\n",
421
+ " detected = next(p for p in track[\"reps\"] if p[\"rep\"] == rep[\"rep\"])\n",
422
+ " table([\"Estimated moment\", \"Video frame\", \"Video position (s)\"],\n",
423
+ " [[key, event[\"frame\"], position(event[\"frame\"])] for key, event in detected[\"events\"].items()])\n",
424
+ " table([\"Measurement\", \"Value\", \"Unit\", \"Confidence\", \"Explanation\"],\n",
425
+ " [[m[\"key\"], m[\"value\"], m[\"unit\"], m[\"confidence\"], m[\"note\"]] for m in rep[\"metrics\"]])\n",
426
+ "print(\"Coach JSON:\", JOB_ROOT / \"coach-payload.json\")\n",
427
+ "\n",
428
+ "body3d = result.get(\"experimental_body3d\", {})\n",
429
+ "print(\"Selected 3D backend:\", body3d.get(\"backend\"), \"|\", body3d.get(\"status\"))\n",
430
+ "print(\"3D frames:\", len(body3d.get(\"frames\", [])), \"| 3D elapsed:\", body3d.get(\"elapsed_s\"), \"seconds\")\n",
431
+ "print(\"3D reason:\", body3d.get(\"reason\"))\n",
432
+ "print(\"Camera assumptions:\", json.dumps(body3d.get(\"geometry\", {}), indent=2))\n",
433
+ "for rep in result.get(\"measurement_diagnostics\", [])[:10]:\n",
434
+ " print(\"Stability evidence for swing\", rep[\"rep\"])\n",
435
+ " for item in rep[\"metrics\"]:\n",
436
+ " if \"nearby_frame_sensitivity\" in item or \"event_frame_sensitivity_range\" in item:\n",
437
+ " print(json.dumps(item, indent=2))\n"
438
+ ],
439
+ "execution_count": null,
440
+ "outputs": [],
441
+ "id": "batting-measurements-012"
442
+ },
443
+ {
444
+ "cell_type": "markdown",
445
+ "metadata": {},
446
+ "source": [
447
+ "## 7. Watch previews of the detected swings\n",
448
+ "\n",
449
+ "These inspection clips show body points in green, toe/heel points in orange, and estimated event labels. They preserve playback presentation positions relative to each clip's first frame. They are resized to at most 960 pixels wide, have no audio, and are separate from the API's measurement output. Preview rendering does not alter measurement results. Invalid source timestamps cause a preview to be withheld rather than retimed.\n",
450
+ "\n",
451
+ "The default limit is ten clips; increase it up to 100 if needed. Inspect each range for missed preparation, truncated finish, merged swings or unrelated movements.\n"
452
+ ],
453
+ "id": "batting-measurements-013"
454
+ },
455
+ {
456
+ "cell_type": "code",
457
+ "metadata": {},
458
+ "source": [
459
+ "PREVIEW_LIMIT = 10\n",
460
+ "PREVIEW_ROOT = JOB_ROOT / \"previews\"\n",
461
+ "worker_command(\"tools.preview_swing_ranges\", \"--video\", INPUT_VIDEO,\n",
462
+ " \"--result\", JOB_ROOT / \"result.json\", \"--output\", PREVIEW_ROOT,\n",
463
+ " \"--max-clips\", PREVIEW_LIMIT)\n",
464
+ "previews = json.loads((PREVIEW_ROOT / \"previews.json\").read_text())\n",
465
+ "for preview in previews[\"previews\"]:\n",
466
+ " print(\"Swing\", preview[\"rep\"], \"| frames\", preview[\"start_frame\"], \"to\", preview[\"end_frame\"])\n",
467
+ " if preview[\"status\"] == \"complete\":\n",
468
+ " display(Video(str(PREVIEW_ROOT / preview[\"file\"]), embed=True, width=720))\n",
469
+ " else:\n",
470
+ " print(\"Preview unavailable:\", preview[\"reason\"])\n"
471
+ ],
472
+ "execution_count": null,
473
+ "outputs": [],
474
+ "id": "batting-measurements-014"
475
+ },
476
+ {
477
+ "cell_type": "markdown",
478
+ "metadata": {},
479
+ "source": [
480
+ "## 8. Download the test results\n",
481
+ "\n",
482
+ "The ZIP contains `result.json`, `coach-payload.json`, recording options, source commit/input hash, progress, worker log and any preview clips. It excludes the original recording, repository credentials, observation cache and models. Download before Colab deletes the runtime. Share this ZIP to investigate a bad result; retain the original recording separately.\n"
483
+ ],
484
+ "id": "batting-measurements-015"
485
+ },
486
+ {
487
+ "cell_type": "code",
488
+ "metadata": {},
489
+ "source": [
490
+ "import zipfile\n",
491
+ "\n",
492
+ "ARCHIVE_PATH = WORKSPACE_ROOT / (JOB_ROOT.name + \"-\" + MEASUREMENT_BACKEND + \"-results.zip\")\n",
493
+ "names = (\"result.json\", \"coach-payload.json\", \"request.json\", \"source_checkout.json\",\n",
494
+ " \"run-context.json\", \"progress.json\", \"worker.log\", \"error.json\")\n",
495
+ "with zipfile.ZipFile(ARCHIVE_PATH, \"w\", zipfile.ZIP_DEFLATED) as archive:\n",
496
+ " for name in names:\n",
497
+ " path = JOB_ROOT / name\n",
498
+ " if path.is_file(): archive.write(path, name)\n",
499
+ " manifest_path = JOB_ROOT / \"previews/previews.json\"\n",
500
+ " if manifest_path.is_file():\n",
501
+ " archive.write(manifest_path, \"previews/previews.json\")\n",
502
+ " manifest = json.loads(manifest_path.read_text())\n",
503
+ " for preview in manifest[\"previews\"]:\n",
504
+ " if preview[\"status\"] == \"complete\":\n",
505
+ " path = JOB_ROOT / \"previews\" / preview[\"file\"]\n",
506
+ " archive.write(path, path.relative_to(JOB_ROOT))\n",
507
+ "print(\"Saved:\", ARCHIVE_PATH)\n",
508
+ "files.download(str(ARCHIVE_PATH))\n"
509
+ ],
510
+ "execution_count": null,
511
+ "outputs": [],
512
+ "id": "batting-measurements-016"
513
+ }
514
+ ]
515
+ }
tests/test_api.py CHANGED
@@ -97,6 +97,24 @@ def test_invalid_options_forbid_3d_and_paths(video, tmp_path):
97
  assert list(service.jobs_root.iterdir()) == []
98
 
99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  def test_gpu_readiness_fails_closed(video, tmp_path):
101
  s = settings(tmp_path)
102
  service = fake_service(s, preflight_ok=False)
 
97
  assert list(service.jobs_root.iterdir()) == []
98
 
99
 
100
+ def test_selectable_3d_backend_preserves_options_and_reports_configuration(video, tmp_path, monkeypatch):
101
+ s = settings(tmp_path, model_root=tmp_path/"models")
102
+ monkeypatch.delenv("BASEBALL_SAM_WORKER_RECORD", raising=False)
103
+ service = fake_service(s)
104
+ with TestClient(create_app(s, service)) as client:
105
+ wait_until(lambda: service.ready)
106
+ capability = client.get("/v1/capabilities", headers=AUTH).json()
107
+ assert capability["body_3d"] is True
108
+ assert capability["measurement_backends"]["rtmw3d"]["configured"] is False
109
+ assert capability["measurement_backends"]["sam3d"]["configured"] is False
110
+ for backend in ("2d", "rtmw3d", "sam3d"):
111
+ response = upload(client, video, data={"options": json.dumps({"measurement_backend": backend})})
112
+ assert response.status_code == 202
113
+ job = service.job_directory(response.json()["job_id"])
114
+ assert json.loads((job/"request.json").read_text())["measurement_backend"] == backend
115
+ assert upload(client, video, data={"options": '{"measurement_backend":"sam3d","sam_repo":"/tmp"}'}).status_code == 422
116
+
117
+
118
  def test_gpu_readiness_fails_closed(video, tmp_path):
119
  s = settings(tmp_path)
120
  service = fake_service(s, preflight_ok=False)
tests/test_measurement_backends.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent geometry, uncertainty, provider failure and notebook checks.
2
+
3
+ Constructed cases verify definitions and stability, never real-world accuracy.
4
+ """
5
+ import ast
6
+ from copy import deepcopy
7
+ import json
8
+ from pathlib import Path
9
+ import numpy as np
10
+ import nbformat
11
+ import pytest
12
+ from baseball_batting.api_contract import AnalysisInput
13
+ from baseball_batting.batting_measurements import analyze_batting, coach_payload
14
+ from baseball_batting.event_body3d import backproject, camera_geometry, reconstruct_events, selected_event_frames
15
+ from baseball_batting.measurement_quality import angle_value, apply_measurement_quality
16
+ from baseball_batting.sam_event_worker import sam_to_coco
17
+ from test_batting_measurements import swing_track, options, metric_map
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+
21
+
22
+ def measurement_result(track=None, opt=None):
23
+ track = track or swing_track()
24
+ opt = opt or options(single_swing=True, measurement_backend="sam3d")
25
+ pose, reps, capture, warnings, method = analyze_batting(track, opt)
26
+ track = deepcopy(track); track["reps"] = pose
27
+ result = {"pose_track": track, "measurements": {"schema_version": "2.0", "discipline": "hitting",
28
+ "view": "face_on", "fps": track["video"]["capture_fps"], "capture": capture, "reps": reps},
29
+ "measurement_method": method, "capabilities": {"body_3d": False}, "warnings": warnings}
30
+ result["coach_payload"] = coach_payload(result["measurements"])
31
+ ids, omitted = selected_event_frames(result)
32
+ rows = []
33
+ for i in ids:
34
+ px = np.asarray(track["frames"]["kp"][i])
35
+ xyz = np.column_stack(((px[:, 0]-330)*.003, (px[:, 1]-350)*.003, np.full(17, 5.)))
36
+ rows.append({"frame": i, "points": xyz.tolist(), "projection": px.tolist(), "scores": [None]*17})
37
+ report = {"backend": opt.measurement_backend, "status": "ready", "reason": "constructed geometry",
38
+ "frames": rows, "geometry": {"assumed": False}, "requested_frames": ids, "omitted_windows": omitted}
39
+ return result, opt, report
40
+
41
+
42
+ def test_known_three_dimensional_angles_and_handedness():
43
+ p = np.zeros((17, 3)); p[:, 2] = 5
44
+ p[11], p[12] = [.15, 0, 5], [-.15, 0, 5]
45
+ centre = np.array([.5*np.tan(np.radians(20)), -.5, 5])
46
+ axis = np.array([np.cos(np.radians(30)), 0, np.sin(np.radians(30))])*.2
47
+ p[5], p[6] = centre+axis, centre-axis
48
+ p[13] = p[11]+[0, .4, 0]
49
+ p[15] = p[13]+[.2, .4*np.sqrt(3)/2, 0]
50
+ opt = options()
51
+ assert angle_value("lead_knee_angle_contact_deg", p, opt) == pytest.approx(150)
52
+ assert angle_value("lateral_trunk_tilt_contact_deg", p, opt) == pytest.approx(20)
53
+ assert angle_value("hip_shoulder_separation_foot_plant_deg", p, opt) == pytest.approx(30)
54
+ opt.handedness = "left"
55
+ assert angle_value("lateral_trunk_tilt_contact_deg", p, opt) == pytest.approx(-20)
56
+ # A rigid camera rotation must not change the angles when up is transformed.
57
+ r = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]])
58
+ opt.handedness = "right"; opt.camera_up = tuple(r @ [0, -1, 0])
59
+ assert angle_value("lateral_trunk_tilt_contact_deg", p @ r.T, opt) == pytest.approx(20)
60
+ assert angle_value("hip_shoulder_separation_foot_plant_deg", p @ r.T, opt) == pytest.approx(30)
61
+
62
+
63
+ def test_all_nine_have_values_when_constructed_evidence_supports_them():
64
+ result, opt, report = measurement_result()
65
+ raw = deepcopy(result["pose_track"])
66
+ result = apply_measurement_quality(result, opt, report)
67
+ metrics = metric_map(result["measurements"]["reps"][0])
68
+ assert len(metrics) == 9 and all(m["value"] is not None for m in metrics.values())
69
+ assert all(m["confidence"] == "est" for m in metrics.values())
70
+ assert metrics["lateral_trunk_tilt_contact_deg"]["value"] == 0
71
+ assert metrics["hip_shoulder_separation_foot_plant_deg"]["value"] == 0
72
+ assert result["pose_track"] == raw
73
+ assert result["coach_payload"] == coach_payload(result["measurements"])
74
+ assert result["capabilities"]["body_3d"] is True
75
+ assert len(result["measurement_diagnostics"][0]["metrics"]) == 9
76
+ import jsonschema
77
+ jsonschema.validate(result["coach_payload"], json.loads((ROOT/"docs/coach-payload.schema.json").read_text()))
78
+
79
+
80
+ def test_sam_mapping_units_and_translation_are_not_applied_twice():
81
+ points = np.arange(70*3).reshape(70, 3)/100
82
+ pixels = np.arange(70*2).reshape(70, 2)
83
+ row = sam_to_coco({"pred_keypoints_3d": points, "pred_keypoints_2d": pixels, "pred_cam_t": [1, 2, 3]})
84
+ np.testing.assert_allclose(row["points"][9], points[62]+[1, 2, 3])
85
+ np.testing.assert_allclose(row["points"][10], points[41]+[1, 2, 3])
86
+ np.testing.assert_allclose(row["points"][11], points[9]+[1, 2, 3])
87
+ assert row["scores"] == [None]*17 # no invented 3D confidence
88
+
89
+
90
+ def test_lightweight_backprojection_uses_same_units_on_all_axes():
91
+ k = np.array([[1000, 0, 500], [0, 1000, 400], [0, 0, 1.]])
92
+ points = backproject([[600, 500], [400, 300]], [.5, -.5], k, 5)
93
+ np.testing.assert_allclose(points, [[.55, .55, 5.5], [-.45, -.45, 4.5]])
94
+ assert np.isnan(backproject([[600, 500]], [-6], k, 5)).all()
95
+
96
+
97
+ def test_lightweight_decoder_does_not_treat_depth_response_as_2d_confidence(monkeypatch):
98
+ pytest.importorskip("rtmlib")
99
+ from types import SimpleNamespace
100
+ from baseball_batting.event_body3d import RTMW3DPose
101
+ outputs = []
102
+ for bins, index, peak in ((576, 200, .9), (768, 300, .95), (576, 200, .08)):
103
+ axis = np.zeros((1, 133, bins), np.float32); axis[:, :, index] = peak; outputs.append(axis)
104
+ class Session:
105
+ def get_inputs(self): return [SimpleNamespace(name="input", shape=[1, 3, 384, 288])]
106
+ def run(self, names, values): return outputs
107
+ monkeypatch.setattr("baseball_batting.detection.ort_session", lambda *a: Session())
108
+ adapter = RTMW3DPose("fixture.onnx", "cpu")
109
+ row = adapter(np.zeros((384, 288, 3), np.uint8), [0, 0, 288, 384],
110
+ np.array([[1000, 0, 144], [0, 1000, 192], [0, 0, 1.]]), 5)
111
+ assert row["scores"] == pytest.approx([.9]*17)
112
+ assert row["depth_peak_response"] == pytest.approx([.08]*17)
113
+ assert np.asarray(row["points"]).shape == (17, 3)
114
+
115
+
116
+ def test_geometry_prior_is_invariant_to_image_resizing():
117
+ track = swing_track(); doubled = deepcopy(track)
118
+ doubled["video"]["width"] *= 2; doubled["video"]["height"] *= 2
119
+ opt = options()
120
+ k, depth, _ = camera_geometry(track, opt, 400)
121
+ k2, depth2, _ = camera_geometry(doubled, opt, 800)
122
+ px = np.array([[400, 450], [300, 250]])
123
+ np.testing.assert_allclose(backproject(px, [.1, -.2], k, depth),
124
+ backproject(px*2, [.1, -.2], k2, depth2))
125
+
126
+
127
+ def test_camera_declarations_and_priors_are_distinguished():
128
+ track = swing_track()
129
+ k, depth, geometry = camera_geometry(track, options(), 400)
130
+ assert geometry["assumed"] is True and depth == pytest.approx(k[1, 1]*1.75/400)
131
+ assert "assumed 1.75" in geometry["depth_source"]
132
+ opt = options(camera={"fx": 1000, "fy": 1200, "cx": 640, "cy": 360, "source": "calibration"},
133
+ root_depth_m=6, root_depth_source="measured distance")
134
+ k, depth, geometry = camera_geometry(track, opt, 400)
135
+ assert geometry["assumed"] is False and depth == 6 and k[1, 1] == 1200
136
+ opt.root_depth_m = None; opt.height_m = 1.8
137
+ assert camera_geometry(track, opt, 400)[1] == pytest.approx(5.4)
138
+ for kwargs in ({"measurement_backend": "magic"}, {"root_depth_m": 4},
139
+ {"camera_up": [0, 0, 0]}, {"camera_up": [float("nan"), 0, 0]}):
140
+ with pytest.raises(ValueError): AnalysisInput(**kwargs)
141
+
142
+
143
+ @pytest.mark.parametrize("failure", ["missing", "disagreement", "scores", "depth_flip", "length_jump"])
144
+ def test_bad_3d_never_falls_back_to_a_projected_anatomical_angle(failure):
145
+ result, opt, report = measurement_result()
146
+ contact = result["pose_track"]["reps"][0]["events"]["contact"]["frame"]
147
+ for row in report["frames"]:
148
+ if abs(row["frame"]-contact) > 1: continue
149
+ if failure == "missing": row["points"][13] = [None]*3
150
+ elif failure == "disagreement": row["projection"][13][0] += 100
151
+ elif failure == "scores": row["scores"][13] = .1
152
+ elif failure == "depth_flip": row["points"][13][2] = -1
153
+ elif row["frame"] == contact: row["points"][13][2] += 1
154
+ apply_measurement_quality(result, opt, report)
155
+ metrics = metric_map(result["coach_payload"]["reps"][0])
156
+ assert metrics["lead_knee_angle_contact_deg"]["value"] is None
157
+ assert metrics["stride_pct_height"]["value"] is not None
158
+
159
+
160
+ def test_unknown_timing_and_moving_camera_remain_withheld_with_3d():
161
+ track = swing_track(); track["frames"]["t_s"] = [None]*180; track["video"]["capture_fps"] = None
162
+ opt = options(single_swing=True, measurement_backend="sam3d"); opt.camera_stability = "moving"
163
+ result, opt, report = measurement_result(track, opt)
164
+ apply_measurement_quality(result, opt, report)
165
+ metrics = metric_map(result["coach_payload"]["reps"][0])
166
+ for key in ("stride_pct_height", "head_movement_pct_height", "foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio", "hip_shoulder_separation_foot_plant_deg"):
167
+ assert metrics[key]["value"] is None
168
+ assert metrics["lead_knee_angle_contact_deg"]["value"] is not None
169
+
170
+
171
+ def test_known_variable_capture_clock_uses_original_timestamps():
172
+ track = swing_track(); track["video"]["capture_fps"] = None
173
+ intervals = np.resize([1/100, 1/120], 179)
174
+ track["frames"]["t_s"] = np.r_[0, np.cumsum(intervals)].tolist()
175
+ pose, reps, _, _, _ = analyze_batting(track, options(single_swing=True))
176
+ a, b = (pose[0]["events"][key]["frame"] for key in ("foot_plant", "contact"))
177
+ expected = (track["frames"]["t_s"][b]-track["frames"]["t_s"][a])*1000
178
+ assert metric_map(reps[0])["foot_plant_to_contact_ms"]["value"] == pytest.approx(expected, abs=.001)
179
+ track["frames"]["t_s"][90:] = [t+.1 for t in track["frames"]["t_s"][90:]]
180
+ metrics = metric_map(analyze_batting(track, options(single_swing=True))[1][0])
181
+ assert metrics["foot_plant_to_contact_ms"]["value"] is None
182
+
183
+
184
+ def test_frame_budget_keeps_complete_event_windows():
185
+ result, _, _ = measurement_result()
186
+ frames, omitted = selected_event_frames(result, limit=5)
187
+ assert len(frames) == 5 and len(omitted) == 1
188
+ contact = result["pose_track"]["reps"][0]["events"]["contact"]["frame"]
189
+ assert frames == list(range(contact-2, contact+3))
190
+
191
+
192
+ def test_missing_models_sam_access_and_2d_selection_do_not_download(tmp_path, monkeypatch):
193
+ result, opt, _ = measurement_result()
194
+ monkeypatch.delenv("BASEBALL_SAM_WORKER_RECORD", raising=False)
195
+ for backend in ("sam3d", "rtmw3d", "2d"):
196
+ opt.measurement_backend = backend
197
+ report = reconstruct_events(tmp_path/"missing.mp4", result, opt, tmp_path, tmp_path)
198
+ assert report["status"] == ("disabled" if backend == "2d" else "unavailable")
199
+ if backend != "2d":
200
+ apply_measurement_quality(result, opt, report)
201
+ metrics = metric_map(result["coach_payload"]["reps"][0])
202
+ assert metrics["lead_knee_angle_contact_deg"]["value"] is None
203
+ assert metrics["foot_plant_to_contact_ms"]["value"] is not None
204
+
205
+
206
+ def test_cuda_failure_in_optional_model_returns_partial_data_without_cpu_fallback(tmp_path, monkeypatch):
207
+ from baseball_batting import event_body3d
208
+ result, opt, _ = measurement_result(); opt.measurement_backend = "rtmw3d"
209
+ result["pose_track"]["video"]["rotation_degrees_applied"] = 0
210
+ model = tmp_path/"body_pose_3d/model.onnx"; model.parent.mkdir(); model.write_bytes(b"fixture")
211
+ import yaml
212
+ expected = yaml.safe_load((ROOT/"configs/resources.yaml").read_text())["resources"]["body_pose_3d"]["sha256"]
213
+ monkeypatch.setattr(event_body3d, "sha256_file", lambda _: expected)
214
+ monkeypatch.setattr(event_body3d, "selected_event_frames", lambda *args: ([0, 1, 2], []))
215
+ monkeypatch.setattr(event_body3d, "iter_frames", lambda *args: iter([(0, None, None, np.zeros((8, 8, 3), np.uint8))]))
216
+ devices = []
217
+ class Model:
218
+ def __init__(self, path, device): devices.append(device)
219
+ def __call__(self, *args): raise RuntimeError("CUDA operator verification failed")
220
+ monkeypatch.setattr(event_body3d, "RTMW3DPose", Model)
221
+ report = reconstruct_events(tmp_path/"video.mp4", result, opt, tmp_path, tmp_path)
222
+ assert devices == ["cuda"] and report["status"] == "unavailable"
223
+ assert "CUDA" in report["reason"]
224
+ result = apply_measurement_quality(result, opt, report)
225
+ assert metric_map(result["coach_payload"]["reps"][0])["stride_pct_height"]["value"] == 42.5
226
+
227
+
228
+ def test_new_notebook_and_legacy_notebook_are_valid_and_separate():
229
+ from tools.build_measurement_notebook import build
230
+ notebook = nbformat.read(ROOT/"notebooks/batting_measurements_test.ipynb", as_version=4)
231
+ nbformat.validate(notebook)
232
+ assert json.loads(nbformat.writes(notebook)) == build()
233
+ source = []
234
+ for cell in notebook.cells:
235
+ if cell.cell_type == "code":
236
+ ast.parse(cell.source); source.append(cell.source)
237
+ assert cell.outputs == []
238
+ source = "\n".join(source)
239
+ assert 'MEASUREMENT_BACKEND = "rtmw3d"' in source
240
+ assert '"measurement_backend": MEASUREMENT_BACKEND' in source
241
+ assert "tools.setup_sam_api_worker" in source
242
+ assert "setup_full_worker" not in source and "opensim" not in source.lower()
243
+
244
+
245
+ def test_full_result_with_quality_and_sparse_3d_matches_both_schemas():
246
+ from baseball_batting.api_output import build_api_result
247
+ import jsonschema
248
+ result, opt, report = measurement_result()
249
+ track = result["pose_track"]
250
+ capture = {"frame_count": 180, "rotation_degrees": 0,
251
+ "frames": [{"width": 1280, "height": 720, "physical_s": i/120, "playback_s": i/30} for i in range(180)],
252
+ "quality": [{"blur_laplacian_variance": 900, "mean_luminance": 128} for _ in range(180)]}
253
+ observations = {"frames": [{"frame_id": i, "body_points": track["frames"]["kp"][i]+track["frames"]["kp_extra"][i]+[None]*110,
254
+ "body_scores": [.9]*23+[0]*110, "body_states": ["model_inferred"]*23+["unknown"]*110,
255
+ "person": {"box": track["frames"]["box"][i]}, "people_count": 1} for i in range(180)]}
256
+ full = build_api_result(capture, observations, opt, {"body_pose": "fixture", "person_detector": "fixture"})
257
+ report.update(validation="reference_validation_pending", unit="m", frame_of_reference="camera",
258
+ axes="x right, y down, z away", elapsed_s=0.)
259
+ full = apply_measurement_quality(full, opt, report)
260
+ jsonschema.validate(full, json.loads((ROOT/"docs/api-result.schema.json").read_text()))
261
+ jsonschema.validate(full["coach_payload"], json.loads((ROOT/"docs/coach-payload.schema.json").read_text()))
262
+ assert "experimental_body3d" not in full["coach_payload"] and "kp3d" not in full["pose_track"]
263
+ assert all(m["value"] is not None for m in full["coach_payload"]["reps"][0]["metrics"])
264
+
265
+
266
+ def test_docker_build_context_includes_every_local_copy_source():
267
+ import fnmatch, shlex
268
+ patterns = (ROOT/".dockerignore").read_text().splitlines()
269
+ for dockerfile in ("Dockerfile", "Dockerfile.sam"):
270
+ for line in (ROOT/dockerfile).read_text().splitlines():
271
+ if not line.startswith("COPY "): continue
272
+ for source in shlex.split(line)[1:-1]:
273
+ assert (ROOT/source).exists(), source
274
+ allowed = True
275
+ for pattern in patterns:
276
+ if not pattern or pattern.startswith("#"): continue
277
+ negated = pattern.startswith("!")
278
+ name = pattern[1:] if negated else pattern
279
+ if fnmatch.fnmatch(source, name.rstrip("/")):
280
+ allowed = negated
281
+ assert allowed, f"{source} excluded from {dockerfile} build context"
tools/build_measurement_notebook.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Colab entry point with selectable 2D, RTMW3D and SAM event measurements."""
2
+ import json
3
+ from pathlib import Path
4
+ from tools.build_2d_notebook import build as build_2d
5
+
6
+ ROOT = Path(__file__).resolve().parents[1]
7
+
8
+
9
+ def build():
10
+ notebook = build_2d()
11
+ for cell in notebook["cells"]:
12
+ source = "".join(cell["source"])
13
+ if cell["cell_type"] == "markdown":
14
+ source = source.replace("# Test batting swing separation on GPU", "# Test nine batting measurements: choose a 3D model")
15
+ source = source.replace("All 3D and coaching stages stay disabled.",
16
+ "Choose `rtmw3d` (lightweight GPU ONNX), `sam3d` (SAM 3D Body), or `2d`. 3D runs only around detected contact/foot-plant events. Coaching stays in your friend's service.")
17
+ source = source.replace("This does not build SAM, MHR or OpenSim.",
18
+ "The lightweight mode needs no PyTorch. SAM setup is isolated and runs only if selected; it skips OpenSim and temporal fitting.")
19
+ source = source.replace("Only the person detector and 2D pose model are downloaded, with verified hashes.",
20
+ "2D models are always downloaded with verified hashes. RTMW3D adds a pinned 369 MB ONNX model. SAM needs approved model access; you may reuse the earlier full-worker installation.")
21
+ source = source.replace("## 5. Run 2D analysis", "## 5. Run the selected measurement backend")
22
+ source = source.replace("## 3. Download the two models and check GPU execution", "## 3. Choose a model, download weights and check GPU execution")
23
+ source = source.replace("Progress shows decoding, 2D pose extraction, measurement calculation and completion.",
24
+ "Progress shows decoding, 2D pose extraction, optional 3D event windows and completion. SAM setup/model initialization still costs time, but this run does not reconstruct every video frame.")
25
+ if "## 4." in source:
26
+ source += "\nCamera intrinsics, player height and pelvis distance are optional. They refer to the upright video. Leave them empty when unknown: the lightweight model reports its camera/depth assumptions and tests sensitivity. Unknown timing still withholds timing values; 3D cannot recover it. A moving camera still withholds ground-foot and head-path measurements.\n"
27
+ elif 'MODEL_ROOT = ' in source:
28
+ source = '''MEASUREMENT_BACKEND = "rtmw3d" # "rtmw3d", "sam3d", or "2d"
29
+ EXISTING_SAM_RECORD = "" # e.g. "/content/baseball_batting_engine/full-worker.json"
30
+ assert MEASUREMENT_BACKEND in {"2d", "rtmw3d", "sam3d"}
31
+ ''' + source
32
+ source = source.replace('worker_command("tools.setup_api_models", "--output", MODEL_ROOT)',
33
+ 'worker_command("tools.setup_api_models", "--output", MODEL_ROOT, *(["--with-3d"] if MEASUREMENT_BACKEND == "rtmw3d" else []))')
34
+ source += '\nprint("This preflight checked the required 2D CUDA models. The selected 3D model is checked during step 5.")\n'
35
+ source += '''
36
+ if MEASUREMENT_BACKEND == "sam3d":
37
+ if not EXISTING_SAM_RECORD:
38
+ if not os.environ.get("HF_TOKEN"):
39
+ try:
40
+ from google.colab import userdata
41
+ os.environ["HF_TOKEN"] = userdata.get("HF_TOKEN")
42
+ except Exception:
43
+ from getpass import getpass
44
+ os.environ["HF_TOKEN"] = getpass("Hugging Face token with approved SAM access: ")
45
+ WORKER_ENV["HF_TOKEN"] = os.environ["HF_TOKEN"]
46
+ worker_command("tools.setup_sam_api_worker", "--workspace", WORKSPACE_ROOT / "sam-api",
47
+ *(["--reuse-record", EXISTING_SAM_RECORD] if EXISTING_SAM_RECORD else []))
48
+ WORKER_ENV["BASEBALL_SAM_WORKER_RECORD"] = str(WORKSPACE_ROOT / "sam-api/sam-api-worker.json")
49
+ WORKER_ENV.pop("HF_TOKEN", None)
50
+ os.environ.pop("HF_TOKEN", None)
51
+ '''
52
+ elif 'VIDEO_PATH = ' in source:
53
+ source = source.replace('SINGLE_SWING = False # False tests automatic separation of multiple swings.',
54
+ '''SINGLE_SWING = False # False tests automatic separation of multiple swings.
55
+ HEIGHT_M = None # Actual player height in metres, when known.
56
+ CAMERA = None # {"fx": 1500, "fy": 1500, "cx": 720, "cy": 1280, "source": "upright camera calibration"}
57
+ ROOT_DEPTH_M = None # Distance along camera Z to pelvis, when measured.
58
+ ROOT_DEPTH_SOURCE = None''')
59
+ source = source.replace('"single_swing": SINGLE_SWING}',
60
+ '"single_swing": SINGLE_SWING, "measurement_backend": MEASUREMENT_BACKEND,\n "height_m": HEIGHT_M, "camera": CAMERA, "root_depth_m": ROOT_DEPTH_M,\n "root_depth_source": ROOT_DEPTH_SOURCE}')
61
+ source = source.replace('"mode": "gpu_api_worker_2d_only"', '"mode": "gpu_api_worker_" + MEASUREMENT_BACKEND')
62
+ elif 'from IPython.display' in source:
63
+ source += '''
64
+ body3d = result.get("experimental_body3d", {})
65
+ print("Selected 3D backend:", body3d.get("backend"), "|", body3d.get("status"))
66
+ print("3D frames:", len(body3d.get("frames", [])), "| 3D elapsed:", body3d.get("elapsed_s"), "seconds")
67
+ print("3D reason:", body3d.get("reason"))
68
+ print("Camera assumptions:", json.dumps(body3d.get("geometry", {}), indent=2))
69
+ for rep in result.get("measurement_diagnostics", [])[:10]:
70
+ print("Stability evidence for swing", rep["rep"])
71
+ for item in rep["metrics"]:
72
+ if "nearby_frame_sensitivity" in item or "event_frame_sensitivity_range" in item:
73
+ print(json.dumps(item, indent=2))
74
+ '''
75
+ elif 'ARCHIVE_PATH = ' in source:
76
+ source = source.replace('JOB_ROOT.name + "-2d-results.zip"',
77
+ 'JOB_ROOT.name + "-" + MEASUREMENT_BACKEND + "-results.zip"')
78
+ cell["source"] = source.splitlines(keepends=True)
79
+ cell["id"] = cell["id"].replace("batting-2d", "batting-measurements")
80
+ notebook["metadata"]["colab"]["name"] = "batting_measurements_test.ipynb"
81
+ return notebook
82
+
83
+
84
+ if __name__ == "__main__":
85
+ path = ROOT/"notebooks/batting_measurements_test.ipynb"
86
+ path.write_text(json.dumps(build(), indent=1)+"\n")
87
+ print("Built", path)
tools/register_sam_api_worker.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Register installed SAM runtime/assets without downloading or loading weights."""
2
+ import argparse
3
+ from pathlib import Path
4
+ import subprocess
5
+ from baseball_batting.storage import atomic_json, sha256_file
6
+ from tools.setup_full_worker import SAM_REVISION
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser()
11
+ for argument in ("worker-python", "sam-repo", "sam-checkpoint", "sam-config", "mhr-path", "output"):
12
+ parser.add_argument("--"+argument, required=True)
13
+ args = parser.parse_args()
14
+ record = {key: str(Path(getattr(args, key)).resolve()) for key in
15
+ ("worker_python", "sam_repo", "sam_checkpoint", "sam_config", "mhr_path")}
16
+ if not all(Path(value).exists() for value in record.values()): raise ValueError("Configured SAM files are missing")
17
+ revision = subprocess.check_output(["git", "-C", record["sam_repo"], "rev-parse", "HEAD"], text=True).strip()
18
+ if revision != SAM_REVISION: raise ValueError("SAM source revision differs from pinned adapter")
19
+ record.update(source_revision=revision, status="installed_requires_inference",
20
+ artifact_hashes={key: sha256_file(record[key]) for key in ("sam_checkpoint", "sam_config", "mhr_path")})
21
+ atomic_json(args.output, record)
22
+ print("Registered SAM:", args.output)
23
+
24
+
25
+ if __name__ == "__main__": main()
tools/setup_api_models.py CHANGED
@@ -1,4 +1,4 @@
1
- """Explicit, checksummed acquisition of the API's two public 2D models."""
2
  import argparse
3
  from baseball_batting.config import CONFIG_ROOT
4
  from baseball_batting.resources import fetch_artifact
@@ -7,9 +7,20 @@ from baseball_batting.resources import fetch_artifact
7
  def main():
8
  parser = argparse.ArgumentParser()
9
  parser.add_argument("--output", default="downloads")
 
10
  args = parser.parse_args()
11
- for name in ("body_pose", "person_detector"):
 
12
  record = fetch_artifact(name, CONFIG_ROOT / "resources.yaml", args.output)
 
 
 
 
 
 
 
 
 
13
  print(f"{name}: verified {record['sha256']}", flush=True)
14
 
15
 
 
1
+ """Checksummed acquisition; optional public lightweight 3D model."""
2
  import argparse
3
  from baseball_batting.config import CONFIG_ROOT
4
  from baseball_batting.resources import fetch_artifact
 
7
  def main():
8
  parser = argparse.ArgumentParser()
9
  parser.add_argument("--output", default="downloads")
10
+ parser.add_argument("--with-3d", action="store_true")
11
  args = parser.parse_args()
12
+ names = ["body_pose", "person_detector"] + (["body_pose_3d"] if args.with_3d else [])
13
+ for name in names:
14
  record = fetch_artifact(name, CONFIG_ROOT / "resources.yaml", args.output)
15
+ # Public .onnx downloads can have arbitrary filenames; worker paths are
16
+ # fixed, just like extracted ZIP artifacts.
17
+ from pathlib import Path
18
+ from baseball_batting.storage import atomic_json
19
+ model = Path(args.output)/name/"model.onnx"
20
+ if Path(record["artifact_path"]).resolve() != model.resolve():
21
+ Path(record["artifact_path"]).replace(model)
22
+ record["artifact_path"] = str(model.resolve())
23
+ atomic_json(model.parent/"resource.json", record)
24
  print(f"{name}: verified {record['sha256']}", flush=True)
25
 
26
 
tools/setup_sam_api_worker.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Install isolated SAM event inference, or reuse an existing full-worker record.
2
+
3
+ No OpenSim, anatomy checks, temporal fitting, MS-TCN or segmentation models.
4
+ Model acquisition uses normal HF_TOKEN/provider access, outside inference.
5
+ """
6
+ import argparse
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import subprocess
11
+ import sys
12
+ from tools.setup_full_worker import ROOT, SAM_REVISION, clone, checksum, run
13
+
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser()
17
+ parser.add_argument("--workspace", required=True)
18
+ parser.add_argument("--reuse-record")
19
+ args = parser.parse_args()
20
+ workspace = Path(args.workspace).resolve(); workspace.mkdir(parents=True, exist_ok=True)
21
+ destination = workspace/"sam-api-worker.json"
22
+ try:
23
+ if args.reuse_record:
24
+ old = json.loads(Path(args.reuse_record).read_text())
25
+ keys = ("worker_python", "sam_repo", "sam_checkpoint", "sam_config", "mhr_path")
26
+ record = {k: old[k] for k in keys}
27
+ if not all(Path(value).exists() for value in record.values()):
28
+ raise ValueError("Existing SAM record has missing files")
29
+ else:
30
+ if not sys.platform.startswith("linux"): raise ValueError("SAM setup requires Linux with NVIDIA GPU")
31
+ run(sys.executable, "-m", "pip", "install", "uv==0.9.10")
32
+ env = dict(os.environ, UV_PYTHON_INSTALL_DIR=str(workspace/"python-runtimes"))
33
+ run(sys.executable, "-m", "uv", "python", "install", "3.11", env=env)
34
+ worker = workspace/".runtime-sam-api/bin/python"
35
+ if not worker.exists(): run(sys.executable, "-m", "uv", "venv", "--python", "3.11", "--seed", worker.parent.parent, env=env)
36
+ run(worker, "-m", "pip", "install", "torch==2.9.1", "torchvision==0.24.1", "--index-url", "https://download.pytorch.org/whl/cu128")
37
+ run(worker, "-m", "pip", "install", "-r", ROOT/"requirements-core.txt", "-r", ROOT/"requirements-sam.txt")
38
+ run(worker, "-m", "pip", "install", "git+https://github.com/facebookresearch/detectron2.git@a1ce2f9", "--no-build-isolation", "--no-deps")
39
+ sam = workspace/"source-sam"
40
+ clone("https://github.com/facebookresearch/sam-3d-body.git", SAM_REVISION, sam)
41
+ # Read credentials only through normal provider authentication. No
42
+ # token is put in CLI arguments, result files or download errors.
43
+ script = 'from huggingface_hub import HfApi,snapshot_download; import json; repo="facebook/sam-3d-body-vith"; rev=HfApi().model_info(repo).sha; p=snapshot_download(repo,revision=rev,allow_patterns=["model.ckpt","model_config.yaml","assets/*"]); print(json.dumps({"path":p,"revision":rev}))'
44
+ download = subprocess.run([str(worker), "-c", script], text=True, capture_output=True)
45
+ if download.returncode: raise RuntimeError("SAM model access unavailable; approved provider access and HF_TOKEN are required")
46
+ model = json.loads(download.stdout.splitlines()[-1]); snapshot = Path(model["path"])
47
+ record = {"worker_python": str(worker), "sam_repo": str(sam),
48
+ "sam_checkpoint": str(snapshot/"model.ckpt"), "sam_config": str(snapshot/"model_config.yaml"),
49
+ "mhr_path": str(snapshot/"assets/mhr_model.pt"), "hf_revision": model["revision"]}
50
+ revision = subprocess.check_output(["git", "-C", record["sam_repo"], "rev-parse", "HEAD"], text=True).strip()
51
+ if revision != SAM_REVISION: raise ValueError("SAM source does not match pinned adapter revision")
52
+ record["artifact_hashes"] = {k: checksum(Path(record[k])) for k in ("sam_checkpoint", "sam_config", "mhr_path")}
53
+ record.update(status="installed_requires_inference", source_revision=revision,
54
+ scope="sparse_body_only_event_windows; no anatomy or temporal fitting")
55
+ destination.write_text(json.dumps(record, indent=2)+"\n")
56
+ print("SAM configured:", destination, flush=True)
57
+ return 0
58
+ except Exception as error:
59
+ destination.write_text(json.dumps({"status": "unavailable", "reason": str(error)[:300]}, indent=2)+"\n")
60
+ print("SAM setup failed:", str(error)[:300], flush=True)
61
+ return 1
62
+
63
+
64
+ if __name__ == "__main__": raise SystemExit(main())