Spaces:
Running on T4
Running on T4
File size: 6,860 Bytes
3192171 16459e8 3192171 16459e8 3192171 16459e8 3192171 | 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 | """Colab entry point with selectable 2D, RTMW3D and SAM event measurements."""
import json
from pathlib import Path
from tools.build_2d_notebook import build as build_2d
ROOT = Path(__file__).resolve().parents[1]
def build():
notebook = build_2d()
for cell in notebook["cells"]:
source = "".join(cell["source"])
if cell["cell_type"] == "markdown":
source = source.replace("# Test batting swing separation on GPU", "# Test nine batting measurements: choose a 3D model")
source = source.replace("All 3D and coaching stages stay disabled.",
"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.")
source = source.replace("This does not build SAM, MHR or OpenSim.",
"The lightweight mode needs no PyTorch. SAM setup is isolated and runs only if selected; it skips OpenSim and temporal fitting.")
source = source.replace("Only the person detector and 2D pose model are downloaded, with verified hashes.",
"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.")
source = source.replace("## 5. Run 2D analysis", "## 5. Run the selected measurement backend")
source = source.replace("## 3. Download the two models and check GPU execution", "## 3. Choose a model, download weights and check GPU execution")
source = source.replace("Progress shows decoding, 2D pose extraction, measurement calculation and completion.",
"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.")
if "## 4." in source:
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"
if "## 7." in source:
source += "\nAt sampled 3D frames, purple rings show the model's image projection. Red lines mark disagreement greater than 5% of image stature. Contact and plant comparison PNGs are shown below and included in the ZIP. They help locate disagreement; they do not identify which model is correct.\n"
elif 'MODEL_ROOT = ' in source:
source = '''MEASUREMENT_BACKEND = "rtmw3d" # "rtmw3d", "sam3d", or "2d"
EXISTING_SAM_RECORD = "" # e.g. "/content/baseball_batting_engine/full-worker.json"
assert MEASUREMENT_BACKEND in {"2d", "rtmw3d", "sam3d"}
''' + source
source = source.replace('worker_command("tools.setup_api_models", "--output", MODEL_ROOT)',
'worker_command("tools.setup_api_models", "--output", MODEL_ROOT, *(["--with-3d"] if MEASUREMENT_BACKEND == "rtmw3d" else []))')
source += '\nprint("This preflight checked the required 2D CUDA models. The selected 3D model is checked during step 5.")\n'
source += '''
if MEASUREMENT_BACKEND == "sam3d":
if not EXISTING_SAM_RECORD:
if not os.environ.get("HF_TOKEN"):
try:
from google.colab import userdata
os.environ["HF_TOKEN"] = userdata.get("HF_TOKEN")
except Exception:
from getpass import getpass
os.environ["HF_TOKEN"] = getpass("Hugging Face token with approved SAM access: ")
WORKER_ENV["HF_TOKEN"] = os.environ["HF_TOKEN"]
worker_command("tools.setup_sam_api_worker", "--workspace", WORKSPACE_ROOT / "sam-api",
*(["--reuse-record", EXISTING_SAM_RECORD] if EXISTING_SAM_RECORD else []))
WORKER_ENV["BASEBALL_SAM_WORKER_RECORD"] = str(WORKSPACE_ROOT / "sam-api/sam-api-worker.json")
WORKER_ENV.pop("HF_TOKEN", None)
os.environ.pop("HF_TOKEN", None)
'''
elif 'VIDEO_PATH = ' in source:
source = source.replace('SINGLE_SWING = False # False tests automatic separation of multiple swings.',
'''SINGLE_SWING = False # False tests automatic separation of multiple swings.
HEIGHT_M = None # Actual player height in metres, when known.
CAMERA = None # {"fx": 1500, "fy": 1500, "cx": 720, "cy": 1280, "source": "upright camera calibration"}
ROOT_DEPTH_M = None # Distance along camera Z to pelvis, when measured.
ROOT_DEPTH_SOURCE = None''')
source = source.replace('"single_swing": SINGLE_SWING}',
'"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}')
source = source.replace('"mode": "gpu_api_worker_2d_only"', '"mode": "gpu_api_worker_" + MEASUREMENT_BACKEND')
elif 'from IPython.display' in source:
source += '''
body3d = result.get("experimental_body3d", {})
print("Selected 3D backend:", body3d.get("backend"), "|", body3d.get("status"))
print("3D frames:", len(body3d.get("frames", [])), "| 3D elapsed:", body3d.get("elapsed_s"), "seconds")
print("3D reason:", body3d.get("reason"))
print("Camera assumptions:", json.dumps(body3d.get("geometry", {}), indent=2))
for rep in result.get("measurement_diagnostics", [])[:10]:
print("Stability evidence for swing", rep["rep"])
for item in rep["metrics"]:
if item.get("status") == "withheld" or "nearby_frame_sensitivity" in item or "event_frame_sensitivity_range" in item:
print(json.dumps(item, indent=2))
'''
elif 'PREVIEW_LIMIT = ' in source:
source += '''
from IPython.display import Image
for comparison in previews.get("model_comparisons", [])[:6]:
print("Model comparison: swing", comparison["rep"], "frame", comparison["frame"], comparison["events"])
display(Image(filename=str(PREVIEW_ROOT / comparison["file"])))
'''
elif 'ARCHIVE_PATH = ' in source:
source = source.replace('JOB_ROOT.name + "-2d-results.zip"',
'JOB_ROOT.name + "-" + MEASUREMENT_BACKEND + "-results.zip"')
cell["source"] = source.splitlines(keepends=True)
cell["id"] = cell["id"].replace("batting-2d", "batting-measurements")
notebook["metadata"]["colab"]["name"] = "batting_measurements_test.ipynb"
return notebook
if __name__ == "__main__":
path = ROOT/"notebooks/batting_measurements_test.ipynb"
path.write_text(json.dumps(build(), indent=1)+"\n")
print("Built", path)
|