Spaces:
Running on T4
Running on T4
Download tools/build_2d_notebook.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/build_2d_notebook.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tools/build_2d_notebook.py
-
curl -L -o build_2d_notebook.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/build_2d_notebook.py
18 kB
| """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() | |