Spaces:
Running on T4
Running on T4
File size: 14,424 Bytes
1558b6d | 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 | """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("<th>" + html.escape(str(v)) + "</th>" for v in headers)
body = "".join("<tr>" + "".join("<td>" + html.escape(str(v)) + "</td>" for v in row) + "</tr>" for row in rows)
return "<table border='1' cellpadding='6'><tr>" + head + "</tr>" + body + "</table>"
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 = "<h3>Swing " + str(swing["rep"]) + "</h3>"
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 += "<p>Raw horizontal hand position relative to hips; x-axis is original frame number. This is a movement trace, not bat speed.</p>"
svg = f'<svg viewBox="0 0 800 205" width="100%"><path d="{html.escape(" ".join(path))}" stroke="#168aad" fill="none" stroke-width="2"/>'
for name, event in audit["events"].items():
x = 45+700*(event["frame"]-first)/(last-first)
svg += f'<line x1="{x}" x2="{x}" y1="30" y2="160" stroke="#b5651d"/><text x="{x}" y="20" font-size="10" transform="rotate(-12 {x} 20)">{html.escape(name)}</text>'
svg += f'<text x="45" y="190">frame {first}</text><text x="660" y="190">frame {last}</text></svg>'
content += svg
sections.append(content)
summary_html = "<h1>Load and swing timing test</h1><p>Estimates; proposed payload version 3.0. No automatic bat/ball tracking.</p>" + "".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()
|