"""Standalone Colab timing test; new helpers are embedded, not fetched from main.""" import json from pathlib import Path from tools.build_2d_notebook import build as build_2d ROOT = Path(__file__).resolve().parents[1] def markdown(source): return {"cell_type": "markdown", "metadata": {}, "source": source.splitlines(keepends=True)} def code(source): return {"cell_type": "code", "metadata": {}, "source": source.splitlines(keepends=True), "execution_count": None, "outputs": []} def build(): notebook = build_2d() cells = notebook["cells"][:11] cells[0] = markdown('''# Test load and swing timing on Colab Run the cells in order with **Runtime → Change runtime type → GPU**. This notebook uses the existing GPU person/2D body models, with **no SAM or other 3D model**. The displayed results contain only the four Load and timing fields. **What runs automatically:** estimated preparation/load start, estimated forward swing start, and front-foot contact when supported. You get the timing table, raw hand-movement graph, swing clips, and neighboring frames around each detected moment. **What is still missing:** the engine does not track the bat and ball. Actual swing-to-contact time and early/late correction cannot be obtained from body points alone. They remain `unclear`. You may optionally enter a visible contact/closest-approach frame in cell 6 to test the duration calculation. The arm-extension guess is clearly labeled **body_extension_proxy** in previews and is never used as ball contact. Start with a short recording of **one swing**, with preparation and finish included. For multiple swings, set `SINGLE_SWING=False`. Declaring one swing does not make the detector invent missing events. The JSON uses the **proposed 3.0 contract**. The existing API/coach integration still uses 2.0; do not send this test payload to that validator until it is updated. No ready/pause metrics, coaching decisions, or accuracy claims are produced. The timing and preview helpers are embedded in this notebook, so it works with the current GitHub engine without first pushing those helpers. ''') for cell in cells: source = "".join(cell["source"]) source = source.replace('Path("/content/baseball_batting_2d")', 'Path("/content/baseball_batting_load_timing")') source = source.replace('/ "2d_test"', '/ "load_timing_test"') source = source.replace('".runtime-api-2d"', '".runtime-load-timing"') source = source.replace('SINGLE_SWING = False # False tests automatic separation of multiple swings.', 'SINGLE_SWING = True # True only for a video containing exactly one swing.') source = source.replace('"single_swing": SINGLE_SWING}', '"single_swing": SINGLE_SWING, "measurement_backend": "2d"}') source = source.replace('"mode": "gpu_api_worker_2d_only"', '"mode": "load_and_swing_timing_test"') if cell["cell_type"] == "markdown": source = source.replace('Leave `SINGLE_SWING=False` for this multi-swing test.', 'Use `SINGLE_SWING=True` for exactly one swing, or `False` for automatic splitting.') source = source.replace('## 5. Run 2D analysis', '## 5. Detect the body movements') cell["source"] = source.splitlines(keepends=True) cells[9] = markdown('''## 5. Detect the body movements This reuses the current API's 2D worker to detect swing ranges and moments. It also produces its normal internal result, but this notebook exports a separate timing payload. 3D is explicitly disabled. Progress and a 30-minute timeout prevent a silent indefinite run; failed runs retain the worker log. Rerun this cell to reuse its verified pose cache. Rerun cell 4 only when changing recording settings or selecting a new video; it creates a new job. ''') helper = (ROOT/"baseball_batting/load_timing.py").read_text() preview_helper = (ROOT/"tools/preview_load_timing.py").read_text() cells += [markdown('''## 6. Calculate only the four timing fields Run this cell as-is for automatic results. It shows each missing value's reason and the effect of moving each detected moment by one recorded frame. Those ranges are **sensitivity checks**, not proven accuracy limits. Optional: after watching cell 7, enter visible event frame numbers in `REVIEWED_EVENTS` and rerun cells **6, 7 and 8**. Use the **original video frame numbers** printed in the clips, not local clip frame numbers. No GPU analysis rerun is needed. Only mark an event when you can see it; leave uncertain events empty. A source description records what was checked. - `outcome`: `"hit"`, `"miss"`, or `"unknown"`. - `stepped`: `True`, `False`, or `None` when unknown. Missing foot events do not prove no step. - Optional frames: `load_start_frame`, `swing_start_frame`, `foot_contact_frame`, `contact_frame` for a hit, or `closest_approach_frame` for a miss. - Forward swing start is the start of the forward movement, rather than any generic hand movement. - Load-to-swing = swing start − load start. Foot-down-to-swing = swing start − first ground contact, and can be negative. - Swing duration ends at reviewed ball contact or closest approach. Early/late correction stays unclear because no reliable bat/ball paths exist in this worker. No manual fields are required. This is an optional way to inspect and test the calculations, not automatic impact detection. '''), code('''REVIEWED_EVENTS = {} # Optional template; replace comments with visible frame numbers, not guesses: # REVIEWED_EVENTS = { # 1: { # "source": "Frame-by-frame inspection of the original recording", # "outcome": "hit", # "stepped": True, # "load_start_frame": ..., # Optional # "swing_start_frame": ..., # Optional # "foot_contact_frame": ..., # Optional # "contact_frame": ..., # Only when actual ball contact is visible # } # } # Bundled timing calculations below; no edits needed to run the automatic test. ''' + helper + ''' from IPython.display import HTML, Image, Video, display import html result = json.loads((JOB_ROOT / "result.json").read_text()) TIMING_REPORT = build_load_timing_report(result, REVIEWED_EVENTS) TIMING_REPORT["source_checkout"] = SOURCE_CHECKOUT TIMING_REPORT["run_context"] = json.loads((JOB_ROOT / "run-context.json").read_text()) ''' + f'''TIMING_HELPER_SOURCE = {helper!r} PREVIEW_HELPER_SOURCE = {preview_helper!r} ''' + '''TIMING_REPORT["helper_sha256"] = { "calculations": hashlib.sha256(TIMING_HELPER_SOURCE.encode()).hexdigest(), "previews": hashlib.sha256(PREVIEW_HELPER_SOURCE.encode()).hexdigest(), } for filename, data in (("load-timing-results.json", TIMING_REPORT), ("load-timing-payload.json", TIMING_REPORT["payload"]), ("reviewed-events.json", REVIEWED_EVENTS)): (JOB_ROOT / filename).write_text(json.dumps(data, indent=2, allow_nan=False)) (JOB_ROOT / "timing_calculations.py").write_text(TIMING_HELPER_SOURCE) (JOB_ROOT / "timing_preview.py").write_text(PREVIEW_HELPER_SOURCE) def timing_table(headers, rows): head = "".join("" + html.escape(str(v)) + "" for v in headers) body = "".join("" + "".join("" + html.escape(str(v)) + "" for v in row) + "" for row in rows) return "" + head + "" + body + "
" print("Capture check:", TIMING_REPORT["payload"]["capture"]) print("Capture time source:", result["pose_track"]["video"]["time_source"]) print("Detected swing candidates:", len(TIMING_REPORT["payload"]["reps"])) sections = [] for swing, audit in zip(TIMING_REPORT["payload"]["reps"], TIMING_REPORT["diagnostics"]): content = "

Swing " + str(swing["rep"]) + "

" content += timing_table(["Calculation", "Value (ms)", "Status", "Meaning / reason"], [[m["key"], "—" if m["value"] is None else m["value"], m["status"], m["note"]] for m in swing["metrics"]]) content += timing_table(["Moment", "Original frame", "Capture time (s)", "Method"], [[name, e["frame"], e["capture_time_s"], e["method"]] for name, e in audit["events"].items()]) content += timing_table(["Calculation", "Range under ±1-frame shifts (ms)"], [[name, check.get("frame_sensitivity_range_ms", "unavailable")] for name, check in audit["timing_checks"].items()]) # Raw hand position relative to hips. Missing samples break the line. frames = result["pose_track"]["frames"] first, last = audit["start_frame"], audit["end_frame"] samples = [] for index in range(first, last+1): points = frames["kp"][index] ids = [9, 10, 11, 12] samples.append(((points[9][0]+points[10][0]-points[11][0]-points[12][0])/2) if all(points[j] is not None for j in ids) else None) finite = [v for v in samples if v is not None] if finite and last > first: low, high = min(finite), max(finite) path, drawing = [], False for i, value in enumerate(samples): if value is None: drawing = False continue x, y = 45+700*i/(last-first), 155-120*(value-low)/max(high-low, 1.) path.append(("L" if drawing else "M") + f"{x:.2f},{y:.2f}") drawing = True content += "

Raw horizontal hand position relative to hips; x-axis is original frame number. This is a movement trace, not bat speed.

" svg = f'' for name, event in audit["events"].items(): x = 45+700*(event["frame"]-first)/(last-first) svg += f'{html.escape(name)}' svg += f'frame {first}frame {last}' content += svg sections.append(content) summary_html = "

Load and swing timing test

Estimates; proposed payload version 3.0. No automatic bat/ball tracking.

" + "".join(sections) (JOB_ROOT / "timing-summary.html").write_text(summary_html) display(HTML(summary_html)) print("Payload:", JOB_ROOT / "load-timing-payload.json") '''), markdown('''## 7. Watch the swings and inspect the event frames Yellow text marks the selected event frame in each neighboring-frame image. Check whether the load and forward swing starts match what you see, and whether the detected landing is the front foot's first ground contact. **body_extension_proxy** is only an arm movement guess. Preview timing is the source's playback timing for finding moments. Measurements use the separate capture clock. Ten swings are displayed by default; increase `PREVIEW_LIMIT` up to 100 if needed. A zero-candidate result means none were separated by this detector, not that the recording contains no swings. '''), code('''PREVIEW_LIMIT = 10 PREVIEW_ROOT = JOB_ROOT / "timing-previews" preview_script = WORKSPACE_ROOT / "timing-preview-helper.py" preview_script.write_text(PREVIEW_HELPER_SOURCE) subprocess.run([WORKER_PYTHON, "-c", "import runpy,sys; runpy.run_path(sys.argv.pop(1), run_name='__main__')", str(preview_script), "--video", str(INPUT_VIDEO), "--result", str(JOB_ROOT / "result.json"), "--report", str(JOB_ROOT / "load-timing-results.json"), "--output", str(PREVIEW_ROOT), "--max-clips", str(PREVIEW_LIMIT)], cwd=ENGINE_ROOT, env=WORKER_ENV, check=True) timing_previews = json.loads((PREVIEW_ROOT / "previews.json").read_text()) for preview in timing_previews["previews"]: print("Swing", preview["rep"], "| original 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"]) for snapshot in timing_previews["event_snapshots"]: if snapshot["rep"] == preview["rep"]: print(snapshot["event"], "| selected original frame", snapshot["frame"]) display(Image(filename=str(PREVIEW_ROOT / snapshot["file"]))) '''), markdown('''## 8. Download the timing test The ZIP contains the four-field payload, calculation evidence, recording settings, source commit, helper code/hashes, worker logs, summary HTML and current previews. The full 2D result is included for investigating event detection. The original recording, credentials, model weights and observation cache are excluded. No request is sent to the coach API. After updating reviewed frames, rerun cells 6, 7 and 8 so the payload and previews describe the same results. '''), code('''import zipfile ARCHIVE_PATH = WORKSPACE_ROOT / (JOB_ROOT.name + "-load-timing-results.zip") names = ("load-timing-results.json", "load-timing-payload.json", "reviewed-events.json", "timing-summary.html", "timing_calculations.py", "timing_preview.py", "result.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 / "timing-previews/previews.json" if manifest_path.is_file(): archive.write(manifest_path, "timing-previews/previews.json") manifest = json.loads(manifest_path.read_text()) for item in manifest["previews"] + manifest.get("event_snapshots", []): if "file" in item and item.get("status", "complete") == "complete": path = JOB_ROOT / "timing-previews" / item["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"load-timing-{index:03d}" notebook["cells"] = cells notebook["metadata"]["colab"]["name"] = "load_and_swing_test.ipynb" return notebook def main(): path = ROOT/"notebooks/load_and_swing_test.ipynb" path.write_text(json.dumps(build(), indent=2)+"\n") print(path) if __name__ == "__main__": main()