Spaces:
Running on T4
Running on T4
Download tools/build_notebook.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 18.2 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/build_notebook.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tools/build_notebook.py
-
curl -L -o build_notebook.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/build_notebook.py
18.2 kB
| """Build a readable Colab entry notebook that fetches the engine from GitHub.""" | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--repo-url", default="https://github.com/usmanthesuper/baseball-engine.git", | |
| help="HTTPS GitHub engine repository URL") | |
| parser.add_argument("--revision", default="main", help="Branch, tag, or full commit SHA") | |
| parser.add_argument("--public", action="store_true", help="Skip the hidden private-repository token prompt") | |
| arguments = parser.parse_args() | |
| bootstrap = (ROOT / "tools/colab_github.py").read_text() | |
| setup = bootstrap + f''' | |
| REPOSITORY_URL = {arguments.repo_url!r} # Set to your published engine repository. | |
| REVISION = {arguments.revision!r} # Use a full commit SHA for a reproducible run. | |
| PRIVATE_REPOSITORY = {not arguments.public!r} | |
| WORKSPACE_ROOT = Path("/content/baseball_batting_engine") if Path("/content").exists() else Path.cwd() / "batting_notebook_runtime" | |
| if not REPOSITORY_URL: | |
| raise ValueError("Set REPOSITORY_URL to the GitHub repository containing the engine") | |
| 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('''# Baseball batting engine | |
| One batter / one swing. The first code cell fetches the engine from the configured GitHub repository and records its full commit SHA. All setup code is readable. For the private repository, enter a GitHub token in the hidden prompt; it needs repository Contents read access. The token is passed temporarily to Git and is not saved in source/configuration/results. | |
| **Engine implementation:** streaming body/bat/ball observations, shared-shape MHR trajectory fitting, project-owned 35-DOF OpenSim IK, independent calibrated bat reconstruction, event candidates/review, qualified-checkpoint inference, training/evaluation, measurement gates, sourced educational hypotheses, history and recoverable exports. GPU/provider-dependent stages return explicit partial results when unavailable. Model training and reference/coaching validation require suitable data; a successful run does not establish accuracy. | |
| Run the cells in order. Physical time is unknown by default. Enter documented capture timing before requesting physical durations or velocities. A successful run is not evidence of baseball measurement accuracy. | |
| '''), code(setup), markdown('''## Install a worker environment | |
| The notebook kernel orchestrates subprocesses. Core dependencies run in a separate virtual environment. | |
| `cpu_reference` uses the separately recorded CPU ONNX profile. `gpu_candidate` installs the ONNX GPU pin with CUDA/cuDNN libraries and requires a GPU runtime. Vision preflight must pass before automatic analysis starts. The full GPU/SAM profile still requires Colab qualification. No silent profile substitution occurs. | |
| '''), code('''import shutil | |
| PROFILE = "cpu_reference" # Change explicitly to "gpu_candidate" for GPU preflight. | |
| # PROFILE = "gpu_candidate" # Change explicitly to "gpu_candidate" for GPU preflight. | |
| assert PROFILE in {"cpu_reference", "gpu_candidate"} | |
| if PROFILE == "gpu_candidate" and (not shutil.which("nvidia-smi") or | |
| subprocess.run(["nvidia-smi"], capture_output=True).returncode != 0): | |
| raise RuntimeError("Select Runtime > Change runtime type > GPU in Colab, or use cpu_reference") | |
| runtime = WORKSPACE_ROOT / (".runtime-" + PROFILE) | |
| # Remove the broken environment left by the failed run | |
| if runtime.exists() and subprocess.run([str(runtime / "bin/python"), "-m", "pip", "--version"], | |
| capture_output=True).returncode != 0: | |
| shutil.rmtree(runtime) | |
| if not (runtime / "bin/python").exists(): | |
| # Skip ensurepip; Colab's system pip is visible through --system-site-packages | |
| subprocess.run([sys.executable, "-m", "venv", "--system-site-packages", "--without-pip", | |
| str(runtime)], check=True) | |
| WORKER_PYTHON = str(runtime / "bin/python") | |
| subprocess.run([WORKER_PYTHON, "-m", "pip", "install", "--only-binary=:all:", | |
| "-r", str(ENGINE_ROOT / "requirements-core.txt")], check=True) | |
| subprocess.run([WORKER_PYTHON, "-m", "pip", "install", "--no-deps", "rtmlib==0.0.16"], check=True) | |
| onnx_package = "onnxruntime==1.23.2" if PROFILE == "cpu_reference" else "onnxruntime-gpu[cuda,cudnn]==1.26.0" | |
| # Force a local ONNX installation so inherited Colab packages cannot shadow this profile. | |
| install = subprocess.run([WORKER_PYTHON, "-m", "pip", "install", "--only-binary=:all:", | |
| "--force-reinstall", "-c", str(ENGINE_ROOT / "requirements-core.txt"), | |
| onnx_package, "requests==2.32.5", "tqdm==4.67.1"]) | |
| print("ONNX installation:", "installed; still needs preflight" if install.returncode == 0 else "unavailable; automatic model branches will abstain") | |
| def engine_command(*arguments, check=True): | |
| return subprocess.run([WORKER_PYTHON, "-m", "baseball_batting.cli", *map(str,arguments)], | |
| cwd=ENGINE_ROOT, check=check) | |
| '''), markdown('''## Persistent output directory | |
| Local `/content` is scratch storage. For cross-session resume, mount Drive and set `OUTPUT_ROOT` to a persistent directory. Otherwise download the result archive before the runtime disappears. Source videos are not included in result archives. | |
| '''), code('''USE_DRIVE = False | |
| if USE_DRIVE: | |
| from google.colab import drive | |
| drive.mount("/content/drive") | |
| OUTPUT_ROOT = Path("/content/drive/MyDrive/baseball_batting_results") if USE_DRIVE else WORKSPACE_ROOT / "artifacts" | |
| OUTPUT_ROOT.mkdir(parents=True, exist_ok=True) | |
| print("Durable mounted Drive" if USE_DRIVE else "Scratch output; export to preserve across sessions:", OUTPUT_ROOT) | |
| '''), markdown('''## Download explicit model artifacts | |
| Downloads happen here, never inside inference. Each artifact's source and SHA-256 are recorded. Models can be reused across runs. If access fails, reviewed annotations and partial exports still work. | |
| '''), code('''DOWNLOAD_MODELS = True | |
| artifacts = {} | |
| if DOWNLOAD_MODELS: | |
| for resource in ("body_pose", "person_detector", "object_detector"): | |
| status = engine_command("fetch", resource, "--registry", ENGINE_ROOT / "configs/resources.yaml", | |
| "--output", WORKSPACE_ROOT / "downloads", check=False) | |
| record = WORKSPACE_ROOT / "downloads" / resource / "resource.json" | |
| if status.returncode == 0 and record.exists(): | |
| artifacts[resource] = json.loads(record.read_text())["artifact_path"] | |
| else: | |
| print(resource, "unavailable; branch will return an explicit reason") | |
| config = { | |
| "mode": "automatic", "chunk_size": 64, | |
| "device": "cpu" if PROFILE == "cpu_reference" else "cuda", | |
| "body_pose_path": artifacts.get("body_pose"), | |
| "person_detector_path": artifacts.get("person_detector"), | |
| "object_detector_path": artifacts.get("object_detector"), | |
| "body3d_enabled": False, "export_video": True, | |
| } | |
| CONFIG_PATH = WORKSPACE_ROOT / "engine-config.json" | |
| CONFIG_PATH.write_text(json.dumps(config, indent=2)) | |
| engine_command("preflight", "--config", CONFIG_PATH, "--output", OUTPUT_ROOT / "preflight", "--require-vision") | |
| '''), markdown('''## Full GPU worker and body reconstruction | |
| For the 3D body stages choose a Colab GPU runtime and `PROFILE="gpu_candidate"` above, then set `BUILD_FULL_WORKER=True`. This explicit setup creates Python 3.11, pins SAM/MS-TCN++ sources, installs the candidate CUDA/OpenSim profile, and downloads SAM assets through normal Hugging Face access. It can take substantial setup time and disk space in a free session. Add `HF_TOKEN` to Colab Secrets after obtaining normal access to `facebook/sam-3d-body-vith`; credentials are not written into engine configuration or reports. | |
| CPU mode remains useful for projected analysis. Physical bat metrics additionally require documented independent bat geometry/calibration; body-estimated wrist depth is not enough. Trained heads remain inactive until reviewed data and held-out qualification exist. | |
| '''), code('''BUILD_FULL_WORKER = False # Set True with a GPU runtime and accessible SAM assets. | |
| if BUILD_FULL_WORKER: | |
| if PROFILE != "gpu_candidate": | |
| raise ValueError('Set PROFILE="gpu_candidate", select a Colab GPU runtime, and rerun setup first') | |
| import os | |
| setup_environment = dict(os.environ) | |
| try: | |
| from google.colab import userdata | |
| hf_secret = userdata.get("HF_TOKEN") | |
| if hf_secret: | |
| setup_environment["HF_TOKEN"] = hf_secret | |
| del hf_secret | |
| except Exception: | |
| print("Using existing provider login/environment if available") | |
| status = subprocess.run([sys.executable, str(ENGINE_ROOT / "tools/setup_full_worker.py"), | |
| "--workspace", str(WORKSPACE_ROOT), "--download-models"], | |
| env=setup_environment) | |
| setup_environment.pop("HF_TOKEN", None) | |
| full_record = json.loads((WORKSPACE_ROOT / "full-worker.json").read_text()) | |
| if status.returncode == 0: | |
| config.update({name: full_record[name] for name in | |
| ("sam_repo", "sam_checkpoint", "sam_config", "mhr_path", "mstcn_repo")}) | |
| full_python = full_record["worker_python"] | |
| config.update(body3d_enabled=True, temporal3d_enabled=True, anatomy_enabled=True, device="cuda") | |
| config["stage_python"] = {stage: full_python for stage in | |
| ("observations", "body3d", "temporal3d", "anatomy", "learned_events")} | |
| CONFIG_PATH.write_text(json.dumps(config, indent=2)) | |
| subprocess.run([full_python, "-m", "baseball_batting.cli", "preflight", "--config", str(CONFIG_PATH), | |
| "--output", str(OUTPUT_ROOT / "preflight-full-vision"), "--require-vision"], cwd=ENGINE_ROOT, check=True) | |
| subprocess.run([full_python, "-m", "baseball_batting.cli", "preflight-optional", "--config", str(CONFIG_PATH), | |
| "--output", str(OUTPUT_ROOT / "preflight-full")], cwd=ENGINE_ROOT, check=True) | |
| optional = json.loads((OUTPUT_ROOT / "preflight-full" / "optional_runtime_profile.json").read_text())["tests"] | |
| required = ("torch", "mhr", "anatomy") | |
| if "torch_mhr" in optional or any(optional.get(name, {}).get("status") != "ready" for name in required): | |
| raise RuntimeError("Full-worker component preflight failed; inspect preflight-full/optional_runtime_profile.json") | |
| else: | |
| raise RuntimeError("Full worker setup failed: " + str(full_record.get("reason"))) | |
| '''), markdown('''## Select a recording and metadata | |
| Upload an original video or enter its existing path. Set `GENERATED_FIXTURE=True` to test integration with a generated video first. That fixture does not validate real-world accuracy. | |
| Use `timing.kind="unknown"` unless the original capture clock is documented. For an unretimed original: `{"kind":"unretimed","source":"description of capture evidence"}`. For documented constant slowdown, also provide `factor` and `all_captured_frames_retained=true`. Height is not camera calibration. | |
| '''), code('''GENERATED_FIXTURE = False | |
| VIDEO_PATH = "" # Alternatively enter an existing video path. | |
| if GENERATED_FIXTURE: | |
| VIDEO_PATH = str(WORKSPACE_ROOT / "generated_fixture.mp4") | |
| subprocess.run([WORKER_PYTHON, str(ENGINE_ROOT / "tools/make_fixture.py"), VIDEO_PATH], check=True) | |
| elif not VIDEO_PATH: | |
| from google.colab import files | |
| uploaded = files.upload() | |
| videos = [name for name in uploaded if name.lower().endswith((".mp4", ".mov", ".mkv", ".avi", ".webm"))] | |
| assert len(videos) == 1, "Select exactly one video" | |
| VIDEO_PATH = str(Path(videos[0]).resolve()) | |
| METADATA = { | |
| "player_id": "player-001", "session_id": "session-001", "handedness": "right", | |
| "height_m": None, "bat_length_m": None, | |
| "consent": "not_supplied", "camera_stability": "unknown", "timing": {"kind": "unknown"}, | |
| "intended_use": "research" | |
| } | |
| METADATA_PATH = WORKSPACE_ROOT / "capture-metadata.json" | |
| METADATA_PATH.write_text(json.dumps(METADATA, indent=2)) | |
| SESSION_DIRECTORY = OUTPUT_ROOT / METADATA["session_id"] | |
| # Repeat preflight in the actual observation worker if configuration was edited. | |
| vision_python = config.get("stage_python", {}).get("observations", WORKER_PYTHON) | |
| subprocess.run([vision_python, "-m", "baseball_batting.cli", "preflight", "--config", str(CONFIG_PATH), | |
| "--output", str(OUTPUT_ROOT / "preflight-analysis"), "--require-vision"], cwd=ENGINE_ROOT, check=True) | |
| engine_command("analyze", VIDEO_PATH, "--config", CONFIG_PATH, "--metadata", METADATA_PATH, | |
| "--output", SESSION_DIRECTORY) | |
| (SESSION_DIRECTORY / "source_checkout.json").write_text(json.dumps(SOURCE_CHECKOUT, indent=2)) | |
| '''), markdown('''## Inspect results | |
| Every unavailable metric has a null value and reason. JSON contains evidence, timing, versions and branch status; `curves.npz` stores continuous projected curves. `source_checkout.json` records the GitHub URL, requested revision and resolved commit. An annotated MP4 keeps source presentation timing when the source timestamps are encodable. Audio is not included in the annotated export. | |
| '''), code('''from IPython.display import display, HTML, Video | |
| result = json.loads((SESSION_DIRECTORY / "result.json").read_text()) | |
| display(HTML((SESSION_DIRECTORY / "report.html").read_text())) | |
| if (SESSION_DIRECTORY / "annotated.mp4").exists(): | |
| display(Video(str(SESSION_DIRECTORY / "annotated.mp4"), embed=True)) | |
| '''), markdown('''## Optional operator review | |
| Review uses oriented-image pixels. Labels are separate files tied to the exact input hash. For a frame, enter for example: | |
| `{"knob":[x,y],"barrel":[x,y],"ball":[x,y],"landmarks":{"left_wrist":[x,y]},"crop":[x1,y1,x2,y2]}`. | |
| Confirm an event only if visible evidence supports it. Event example: | |
| `[{"type":"contact","state":"confirmed","frame_interval":[12,13],"evidence_frames":[12,13,14],"evidence_description":"Visible interaction followed by outgoing ball"}]`. | |
| Unknown remains unknown. Save before moving to another frame. Notebook widget use does not run a web service. | |
| '''), code('''RUN_REVIEW = False | |
| ANNOTATIONS_PATH = OUTPUT_ROOT / (METADATA["session_id"] + "-reviewed.json") | |
| if RUN_REVIEW: | |
| sys.path.insert(0, str(ENGINE_ROOT)) | |
| from baseball_batting.review import show_review_widget | |
| show_review_widget(VIDEO_PATH, result["capture"], ANNOTATIONS_PATH, annotator="operator-001") | |
| '''), code('''APPLY_REVIEWED_LABELS = False | |
| if APPLY_REVIEWED_LABELS: | |
| assert ANNOTATIONS_PATH.exists(), "Save labels first" | |
| config["mode"] = "operator_reviewed" | |
| config["annotations_path"] = str(ANNOTATIONS_PATH) | |
| CONFIG_PATH.write_text(json.dumps(config, indent=2)) | |
| engine_command("analyze", VIDEO_PATH, "--config", CONFIG_PATH, "--metadata", METADATA_PATH, | |
| "--output", SESSION_DIRECTORY) | |
| result = json.loads((SESSION_DIRECTORY / "result.json").read_text()) | |
| display(HTML((SESSION_DIRECTORY / "report.html").read_text())) | |
| '''), markdown('''## Dataset, training and evaluation commands | |
| The same backend CLI builds reviewed datasets and trains both custom heads. Dataset indexes supply `video_path`, `annotations_path`, `player_id`, `session_id`, and `split` (train/validation/test); event examples also supply `analysis_directory` and reviewed `phases`. Athletes/sessions cannot cross splits. | |
| ```text | |
| python -m baseball_batting.cli dataset index.json --kind endpoint_cnn --output endpoint-data | |
| python -m baseball_batting.cli train endpoint-data --kind endpoint_cnn --output endpoint-model --epochs 30 | |
| python -m baseball_batting.cli evaluate-checkpoint endpoint-data endpoint-model --thresholds your-preregistered-gates.json --scope your-task-and-view | |
| ``` | |
| For phases replace kind with `mstcn_events` and pass the pinned `--mstcn-repo` to training/evaluation. Configure checkpoint and manifest paths only after qualification passes. `configs/training-gates.example.json` is deliberately inactive until task-specific requirements are preregistered. Independent biomechanics evaluation uses `evaluate-reference`; distribution tables alone cannot validate phone recordings. See `docs/TRAINING.md` and `docs/VALIDATION.md`. | |
| '''), markdown('''## Download result archive | |
| Re-running analysis reuses verified observation chunks with matching hashes. To resume in another session, set `REVISION` to the full commit SHA in the exported `source_checkout.json`, reimport the result archive, use the same source video, metadata, model artifacts and profile, and rerun. Incompatible changes invalidate dependent stages. | |
| '''), code('''ARCHIVE_PATH = OUTPUT_ROOT / (METADATA["session_id"] + "-results.zip") | |
| engine_command("export", SESSION_DIRECTORY, ARCHIVE_PATH) | |
| if "google.colab" in sys.modules or Path("/content").exists(): | |
| from google.colab import files | |
| files.download(str(ARCHIVE_PATH)) | |
| else: | |
| print(ARCHIVE_PATH) | |
| ''')] | |
| notebook = {"nbformat":4,"nbformat_minor":5,"metadata":{ | |
| "kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}, | |
| "language_info":{"name":"python","version":"3.11"}, | |
| "colab":{"name":"batting_engine.ipynb","provenance":[]}},"cells":cells} | |
| for i,c in enumerate(cells): | |
| c["id"] = f"batting-{i:03d}" | |
| destination = ROOT / "notebooks" / "batting_engine.ipynb" | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| destination.write_text(json.dumps(notebook, indent=1)) | |
| print(f"Built {destination.name}: {len(cells)} cells; GitHub source {arguments.repo_url or '(set repository URL)'} at {arguments.revision}") | |