Spaces:
Running on T4
Running on T4
File size: 17,989 Bytes
326d3cc f771d3b 326d3cc 999db75 326d3cc f771d3b 326d3cc f771d3b 326d3cc f771d3b 326d3cc f771d3b 326d3cc 16459e8 326d3cc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | """Build the Colab test notebook for the GPU API's 2D measurement worker."""
import argparse
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def build(repo_url="https://github.com/usmanthesuper/baseball-engine.git", revision="main", private=True):
bootstrap = (ROOT / "tools/colab_github.py").read_text()
setup = bootstrap + f'''
REPOSITORY_URL = {repo_url!r}
REVISION = {revision!r} # Use the recorded full SHA to reproduce a run.
PRIVATE_REPOSITORY = {private!r}
WORKSPACE_ROOT = Path("/content/baseball_batting_2d") if Path("/content").exists() else Path.cwd() / "batting_notebook_runtime" / "2d_test"
from getpass import getpass
GITHUB_TOKEN = getpass("GitHub token with read access to this repository: ") if PRIVATE_REPOSITORY else None
try:
if PRIVATE_REPOSITORY and not GITHUB_TOKEN:
raise ValueError("A token is required for this private repository")
ENGINE_ROOT, SOURCE_CHECKOUT = checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)
finally:
del GITHUB_TOKEN
'''
def markdown(text):
return {"cell_type": "markdown", "metadata": {}, "source": text.splitlines(keepends=True)}
def code(text):
return {"cell_type": "code", "metadata": {}, "source": text.splitlines(keepends=True),
"execution_count": None, "outputs": []}
cells = [markdown('''# Test batting swing separation on GPU
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`. All 3D and coaching stages stay disabled. It tests the engine's calculations; Docker/HTTP deployment is a separate check.
1. In Colab select **Runtime → Change runtime type → GPU** (T4 if available), then run the cells in order.
2. Start with a short video containing 2–3 swings. The whole batter, hands and feet should be visible, with a fixed camera and a known face-on view.
3. Enter recording settings only when known. Leave `SINGLE_SWING=False` to test automatic splitting.
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.
5. Download the ZIP. It contains measurements, ranges, previews and logs. The original video and model weights are excluded.
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).
'''), markdown('''## 1. Get the current engine
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.
'''), code(setup), markdown('''## 2. Install the GPU worker
Dependencies are installed in a separate environment. This does not build SAM, MHR or OpenSim. Installation must finish before continuing.
'''), code('''import shutil
if not shutil.which("nvidia-smi"):
raise RuntimeError("Select Runtime > Change runtime type > GPU, then reconnect and rerun.")
subprocess.run(["nvidia-smi"], check=True)
runtime = WORKSPACE_ROOT / ".runtime-api-2d"
worker_path = runtime / "bin/python"
if runtime.exists() and (not worker_path.is_file() or subprocess.run(
[str(worker_path), "-m", "pip", "--version"], capture_output=True).returncode != 0):
shutil.rmtree(runtime)
if not worker_path.exists():
subprocess.run([sys.executable, "-m", "venv", "--system-site-packages", "--without-pip",
str(runtime)], check=True)
WORKER_PYTHON = str(worker_path)
WORKER_ENV = {**os.environ, "MPLBACKEND": "Agg", "PYTHONUNBUFFERED": "1",
"PYTHONNOUSERSITE": "1", "PIP_REQUIRE_VIRTUALENV": "true"}
WORKER_ENV.pop("PYTHONPATH", None)
# Install locally even when Colab has inherited CPU ORT/numpy packages.
subprocess.run([WORKER_PYTHON, "-m", "pip", "install", "--only-binary=:all:",
"--ignore-installed", "-r", str(ENGINE_ROOT / "requirements-api-gpu.txt")],
env=WORKER_ENV, check=True)
subprocess.run([WORKER_PYTHON, "-m", "pip", "install", "--ignore-installed", "--no-deps", "rtmlib==0.0.16"],
env=WORKER_ENV, check=True)
def worker_command(module, *arguments):
return subprocess.run([WORKER_PYTHON, "-m", module, *map(str, arguments)],
cwd=ENGINE_ROOT, env=WORKER_ENV, check=True)
print("2D worker installed. Actual CUDA execution is checked in the next cell.")
'''), markdown('''## 3. Download the two models and check GPU execution
Only the person detector and 2D pose model are downloaded, with verified hashes. This cell must report `ready: true`. It refuses to silently run on CPU.
'''), code('''MODEL_ROOT = WORKSPACE_ROOT / "models"
worker_command("tools.setup_api_models", "--output", MODEL_ROOT)
PREFLIGHT_PATH = WORKSPACE_ROOT / "gpu-preflight.json"
worker_command("baseball_batting.api_worker", "--models", MODEL_ROOT,
"--preflight", "--output", PREFLIGHT_PATH)
preflight = json.loads(PREFLIGHT_PATH.read_text())
if not preflight.get("ready") or preflight.get("device") != "cuda":
raise RuntimeError("Actual CUDA preflight did not pass.")
print(json.dumps(preflight, indent=2))
'''), markdown('''## 4. Upload a video and set its recording information
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.
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.
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 estimates support documented nominal 30 FPS or higher cadence, including 29.97 FPS and variable cadence with no larger gaps. Each timing measurement is separately withheld if moving its events by one frame changes it too much. 60 FPS gives finer time resolution; it is no longer required.
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.
'''), code('''from google.colab import files
import hashlib
import uuid
VIDEO_PATH = "" # Or, for example: "/content/IMG_1640.mp4"
HANDEDNESS = None # Set to "right" or "left" when known.
PITCHER_DIRECTION = None # "image_left" or "image_right" toward the pitcher/tee, when known.
VIEW = "unknown" # Change to "face_on" when known.
CAMERA_STABILITY = "unknown" # Change to "fixed_verified" when the camera stays still.
TIMING = {"kind": "unknown"}
SINGLE_SWING = False # False tests automatic separation of multiple swings.
if not VIDEO_PATH:
uploaded = files.upload()
videos = [name for name in uploaded if name.lower().endswith((".mp4", ".mov", ".mkv", ".avi", ".webm"))]
if len(videos) != 1:
raise ValueError("Upload exactly one video containing the swings.")
VIDEO_PATH = str(Path(videos[0]).resolve())
del uploaded
source_video = Path(VIDEO_PATH).resolve()
if not source_video.is_file():
raise ValueError("VIDEO_PATH does not exist. Upload the video or correct its path.")
OPTIONS = {"discipline": "hitting", "handedness": HANDEDNESS, "view": VIEW,
"pitcher_direction": PITCHER_DIRECTION,
"camera_stability": CAMERA_STABILITY, "timing": TIMING, "single_swing": SINGLE_SWING}
JOB_ROOT = WORKSPACE_ROOT / "results" / ("session-" + uuid.uuid4().hex[:12])
JOB_ROOT.mkdir(parents=True)
INPUT_VIDEO = JOB_ROOT / ("input" + source_video.suffix.lower())
shutil.copy2(source_video, INPUT_VIDEO)
(JOB_ROOT / "request.json").write_text(json.dumps(OPTIONS, indent=2))
(JOB_ROOT / "source_checkout.json").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))
checksum = hashlib.sha256()
with INPUT_VIDEO.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
checksum.update(block)
(JOB_ROOT / "run-context.json").write_text(json.dumps({"input_sha256": checksum.hexdigest(),
"source_video_name": source_video.name, "mode": "gpu_api_worker_2d_only"}, indent=2))
print("Job:", JOB_ROOT.name)
print("Recording options:", json.dumps(OPTIONS, indent=2))
'''), markdown('''## 5. Run 2D analysis
Progress shows decoding, 2D pose extraction, measurement calculation and completion. 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.
'''), code('''import signal
import time
RUN_TIMEOUT_S = 1800
WORKER_LOG = JOB_ROOT / "worker.log"
(JOB_ROOT / "error.json").unlink(missing_ok=True)
(JOB_ROOT / "progress.json").unlink(missing_ok=True)
command = [WORKER_PYTHON, "-m", "baseball_batting.api_worker", "--models", str(MODEL_ROOT),
"--job", str(JOB_ROOT)]
started = time.monotonic()
with WORKER_LOG.open("w") as log:
process = subprocess.Popen(command, cwd=ENGINE_ROOT, env=WORKER_ENV,
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
last_print, last_stage = 0., None
try:
while process.poll() is None:
elapsed = time.monotonic()-started
if elapsed > RUN_TIMEOUT_S:
raise TimeoutError("Analysis timed out; inspect worker.log and try a shorter recording.")
progress_path = JOB_ROOT / "progress.json"
progress = json.loads(progress_path.read_text()) if progress_path.exists() else {"stage": "starting"}
if progress["stage"] != last_stage or elapsed-last_print >= 15:
print(f"{elapsed:.0f}s | {progress['stage']} | "
f"{progress.get('completed_frames', 0)}/{progress.get('total_frames') or '?'} frames", flush=True)
last_print, last_stage = elapsed, progress["stage"]
time.sleep(2)
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
if process.returncode != 0:
print(WORKER_LOG.read_text(errors="replace")[-8000:])
raise RuntimeError("2D analysis failed. The worker log above contains the actual error.")
result = json.loads((JOB_ROOT / "result.json").read_text())
print(f"Finished in {time.monotonic()-started:.1f}s. Detected {len(result['pose_track']['reps'])} swing candidates.")
'''), markdown('''## 6. Inspect swing ranges and measurements
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`.
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.
'''), code('''from IPython.display import HTML, Video, display
import html
def table(headers, rows):
head = "".join("<th>" + html.escape(str(value)) + "</th>" for value in headers)
body = "".join("<tr>" + "".join("<td>" + html.escape(str(value)) + "</td>" for value in row) + "</tr>" for row in rows)
display(HTML("<table border='1' cellpadding='6'><thead><tr>" + head + "</tr></thead><tbody>" + body + "</tbody></table>"))
track = result["pose_track"]
print("Swing candidates:", len(track["reps"]))
print("Capture check:", result["measurements"]["capture"])
print("Real capture FPS:", track["video"]["capture_fps"])
for warning in result["warnings"]: print("•", warning)
playback = track["frames"]["playback_t_s"]
def position(index):
return round(playback[index]-playback[0], 3) if playback[index] is not None and playback[0] is not None else "unknown"
table(["Swing", "First frame", "Last frame (included)", "Video start (s)", "Video end (s)", "Boundary method"],
[[rep["rep"], rep["start_frame"], rep["end_frame"], position(rep["start_frame"]),
position(rep["end_frame"]), rep["boundary_method"]] for rep in track["reps"]])
for rep in result["measurements"]["reps"][:10]:
print("Swing", rep["rep"], "| estimated physical events_ms:", rep["events_ms"])
detected = next(p for p in track["reps"] if p["rep"] == rep["rep"])
table(["Estimated moment", "Video frame", "Video position (s)"],
[[key, event["frame"], position(event["frame"])] for key, event in detected["events"].items()])
table(["Measurement", "Value", "Unit", "Confidence", "Explanation"],
[[m["key"], m["value"], m["unit"], m["confidence"], m["note"]] for m in rep["metrics"]])
print("Coach JSON:", JOB_ROOT / "coach-payload.json")
'''), markdown('''## 7. Watch previews of the detected swings
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.
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.
'''), code('''PREVIEW_LIMIT = 10
PREVIEW_ROOT = JOB_ROOT / "previews"
worker_command("tools.preview_swing_ranges", "--video", INPUT_VIDEO,
"--result", JOB_ROOT / "result.json", "--output", PREVIEW_ROOT,
"--max-clips", PREVIEW_LIMIT)
previews = json.loads((PREVIEW_ROOT / "previews.json").read_text())
for preview in previews["previews"]:
print("Swing", preview["rep"], "| frames", preview["start_frame"], "to", preview["end_frame"])
if preview["status"] == "complete":
display(Video(str(PREVIEW_ROOT / preview["file"]), embed=True, width=720))
else:
print("Preview unavailable:", preview["reason"])
'''), markdown('''## 8. Download the test results
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.
'''), code('''import zipfile
ARCHIVE_PATH = WORKSPACE_ROOT / (JOB_ROOT.name + "-2d-results.zip")
names = ("result.json", "coach-payload.json", "request.json", "source_checkout.json",
"run-context.json", "progress.json", "worker.log", "error.json")
with zipfile.ZipFile(ARCHIVE_PATH, "w", zipfile.ZIP_DEFLATED) as archive:
for name in names:
path = JOB_ROOT / name
if path.is_file(): archive.write(path, name)
manifest_path = JOB_ROOT / "previews/previews.json"
if manifest_path.is_file():
archive.write(manifest_path, "previews/previews.json")
manifest = json.loads(manifest_path.read_text())
for preview in manifest["previews"]:
if preview["status"] == "complete":
path = JOB_ROOT / "previews" / preview["file"]
archive.write(path, path.relative_to(JOB_ROOT))
for comparison in manifest.get("model_comparisons", []):
path = JOB_ROOT / "previews" / comparison["file"]
archive.write(path, path.relative_to(JOB_ROOT))
print("Saved:", ARCHIVE_PATH)
files.download(str(ARCHIVE_PATH))
''')]
for index, cell in enumerate(cells):
cell["id"] = f"batting-2d-{index:03d}"
return {"nbformat": 4, "nbformat_minor": 5, "metadata": {
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
"language_info": {"name": "python"}, "accelerator": "GPU",
"colab": {"name": "batting_2d_test.ipynb", "provenance": []}}, "cells": cells}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo-url", default="https://github.com/usmanthesuper/baseball-engine.git")
parser.add_argument("--revision", default="main")
parser.add_argument("--public", action="store_true")
args = parser.parse_args()
notebook = build(args.repo_url, args.revision, not args.public)
destination = ROOT / "notebooks/batting_2d_test.ipynb"
destination.write_text(json.dumps(notebook, indent=1)+"\n")
print(f"Built {destination.name}: {len(notebook['cells'])} cells; source {args.repo_url} at {args.revision}")
if __name__ == "__main__":
main()
|