File size: 27,060 Bytes
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
{
 "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": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Baseball batting engine\n",
    "\n",
    "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.\n",
    "\n",
    "**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.\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-000"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "\"\"\"Readable GitHub bootstrap, copied into the first Colab code cell by the builder.\"\"\"\n",
    "from pathlib import Path\n",
    "from contextlib import contextmanager\n",
    "import base64\n",
    "import json\n",
    "import os\n",
    "import re\n",
    "import subprocess\n",
    "import sys\n",
    "\n",
    "\n",
    "def _git(directory, *arguments, auth_env=None):\n",
    "    environment = {**os.environ, \"GIT_TERMINAL_PROMPT\": \"0\", **(auth_env or {})}\n",
    "    result = subprocess.run(\n",
    "        [\"git\", \"-C\", str(directory), *arguments], text=True,\n",
    "        stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,\n",
    "    )\n",
    "    if result.returncode:\n",
    "        detail = result.stderr.strip() or result.stdout.strip() or \"Git returned no error detail\"\n",
    "        secret = (auth_env or {}).get(\"BATTING_GITHUB_TOKEN\")\n",
    "        if secret:\n",
    "            encoded = base64.b64encode(f\"x-access-token:{secret}\".encode()).decode()\n",
    "            detail = detail.replace(secret, \"[REDACTED]\").replace(encoded, \"[REDACTED]\")\n",
    "        detail = re.sub(r\"(?:github_pat_|gh[pousr]_)[A-Za-z0-9_]+\", \"[REDACTED]\", detail)\n",
    "        raise RuntimeError(f\"Git failed (exit {result.returncode}):\\n{detail[-4000:]}\") from None\n",
    "    return result.stdout.strip()\n",
    "\n",
    "\n",
    "@contextmanager\n",
    "def _github_credentials(token, scope=\"https://github.com/\"):\n",
    "    if not token:\n",
    "        yield {}\n",
    "        return\n",
    "    # Git reads these settings only for this subprocess; no token is stored in its URL/config.\n",
    "    count = int(os.environ.get(\"GIT_CONFIG_COUNT\", \"0\"))\n",
    "    encoded = base64.b64encode(f\"x-access-token:{token}\".encode()).decode()\n",
    "    yield {\n",
    "        \"GIT_CONFIG_COUNT\": str(count + 2),\n",
    "        f\"GIT_CONFIG_KEY_{count}\": f\"http.{scope}.extraHeader\",\n",
    "        f\"GIT_CONFIG_VALUE_{count}\": \"\",\n",
    "        f\"GIT_CONFIG_KEY_{count + 1}\": f\"http.{scope}.extraHeader\",\n",
    "        f\"GIT_CONFIG_VALUE_{count + 1}\": f\"Authorization: Basic {encoded}\",\n",
    "        \"BATTING_GITHUB_TOKEN\": token,\n",
    "    }\n",
    "\n",
    "\n",
    "def checkout_github(repository_url, revision, workspace, token=None):\n",
    "    \"\"\"Fetch an explicit ref and stop before replacing modified source files.\"\"\"\n",
    "    if token is not None:\n",
    "        token = token.strip()\n",
    "        if not token:\n",
    "            raise ValueError(\"Enter a token with read access to this repository\")\n",
    "    if not re.fullmatch(r\"https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\\.git)?/?\", repository_url):\n",
    "        raise ValueError(\"Use an HTTPS GitHub repository URL without credentials or query parameters\")\n",
    "    if any(part in {\".\", \"..\"} for part in repository_url.split(\"/\")[3:]):\n",
    "        raise ValueError(\"Use an owner/repository GitHub URL\")\n",
    "    if not revision or revision.startswith(\"-\") or any(c.isspace() for c in revision):\n",
    "        raise ValueError(\"Set a branch, tag, or full commit SHA\")\n",
    "    workspace = Path(workspace).resolve()\n",
    "    source = workspace / \"source\"\n",
    "    workspace.mkdir(parents=True, exist_ok=True)\n",
    "    with _github_credentials(token) as authentication:\n",
    "        options = (\"-c\", \"credential.helper=\") if token else ()\n",
    "        fresh_checkout = False\n",
    "        if not (source / \".git\").exists():\n",
    "            if source.exists() and any(source.iterdir()):\n",
    "                raise ValueError(f\"Source directory is not an empty Git checkout: {source}\")\n",
    "            _git(workspace, *options, \"clone\", \"--no-checkout\", \"--depth=1\", repository_url,\n",
    "                 str(source), auth_env=authentication)\n",
    "            fresh_checkout = True\n",
    "        if _git(source, \"config\", \"--get\", \"remote.origin.url\") != repository_url:\n",
    "            raise ValueError(\"Existing checkout uses a different repository; choose another workspace\")\n",
    "        # A newly cloned --no-checkout repository has no populated index yet.\n",
    "        if not fresh_checkout and _git(source, \"status\", \"--porcelain\", \"--untracked-files=no\"):\n",
    "            raise ValueError(\"Source has local edits; save them or choose another workspace before updating\")\n",
    "        _git(source, *options, \"fetch\", \"--depth=1\", \"origin\", revision, auth_env=authentication)\n",
    "    commit = _git(source, \"rev-parse\", \"FETCH_HEAD^{commit}\")\n",
    "    if re.fullmatch(r\"[0-9a-fA-F]{40}\", revision) and commit.lower() != revision.lower():\n",
    "        raise ValueError(\"Fetched commit does not match the requested SHA\")\n",
    "    _git(source, \"checkout\", \"--quiet\", \"--detach\", commit)\n",
    "    required = [\"baseball_batting/cli.py\", \"requirements-core.txt\", \"configs/resources.yaml\"]\n",
    "    if not all((source / name).is_file() for name in required):\n",
    "        raise ValueError(\"Selected repository revision does not contain the batting engine\")\n",
    "    record = {\"repository_url\": repository_url, \"requested_revision\": revision, \"commit_sha\": commit}\n",
    "    (workspace / \"source_checkout.json\").write_text(json.dumps(record, indent=2))\n",
    "    print(\"Engine source:\", source)\n",
    "    print(\"Resolved commit:\", commit, \"(use this SHA as REVISION to reproduce this run)\")\n",
    "    return source, record\n",
    "\n",
    "\n",
    "REPOSITORY_URL = 'https://github.com/usmanthesuper/baseball-engine.git'  # Set to your published engine repository.\n",
    "REVISION = 'main'  # Use a full commit SHA for a reproducible run.\n",
    "PRIVATE_REPOSITORY = True\n",
    "WORKSPACE_ROOT = Path(\"/content/baseball_batting_engine\") if Path(\"/content\").exists() else Path.cwd() / \"batting_notebook_runtime\"\n",
    "if not REPOSITORY_URL:\n",
    "    raise ValueError(\"Set REPOSITORY_URL to the GitHub repository containing the engine\")\n",
    "from getpass import getpass\n",
    "GITHUB_TOKEN = getpass(\"GitHub token with read access to this repository: \") if PRIVATE_REPOSITORY else None\n",
    "try:\n",
    "    if PRIVATE_REPOSITORY and not GITHUB_TOKEN:\n",
    "        raise ValueError(\"A token is required for this private repository\")\n",
    "    ENGINE_ROOT, SOURCE_CHECKOUT = checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)\n",
    "finally:\n",
    "    del GITHUB_TOKEN\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-001"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Install a worker environment\n",
    "\n",
    "The notebook kernel orchestrates subprocesses. Core dependencies run in a separate virtual environment.\n",
    "`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.\n"
   ],
   "id": "batting-002"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import shutil\n",
    "\n",
    "PROFILE = \"cpu_reference\"  # Change explicitly to \"gpu_candidate\" for GPU preflight.\n",
    "# PROFILE = \"gpu_candidate\"  # Change explicitly to \"gpu_candidate\" for GPU preflight.\n",
    "assert PROFILE in {\"cpu_reference\", \"gpu_candidate\"}\n",
    "if PROFILE == \"gpu_candidate\" and (not shutil.which(\"nvidia-smi\") or\n",
    "        subprocess.run([\"nvidia-smi\"], capture_output=True).returncode != 0):\n",
    "    raise RuntimeError(\"Select Runtime > Change runtime type > GPU in Colab, or use cpu_reference\")\n",
    "runtime = WORKSPACE_ROOT / (\".runtime-\" + PROFILE)\n",
    "\n",
    "# Remove the broken environment left by the failed run\n",
    "if runtime.exists() and subprocess.run([str(runtime / \"bin/python\"), \"-m\", \"pip\", \"--version\"],\n",
    "                                       capture_output=True).returncode != 0:\n",
    "    shutil.rmtree(runtime)\n",
    "\n",
    "if not (runtime / \"bin/python\").exists():\n",
    "    # Skip ensurepip; Colab's system pip is visible through --system-site-packages\n",
    "    subprocess.run([sys.executable, \"-m\", \"venv\", \"--system-site-packages\", \"--without-pip\",\n",
    "                    str(runtime)], check=True)\n",
    "WORKER_PYTHON = str(runtime / \"bin/python\")\n",
    "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n",
    "                \"-r\", str(ENGINE_ROOT / \"requirements-core.txt\")], check=True)\n",
    "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--no-deps\", \"rtmlib==0.0.16\"], check=True)\n",
    "onnx_package = \"onnxruntime==1.23.2\" if PROFILE == \"cpu_reference\" else \"onnxruntime-gpu[cuda,cudnn]==1.26.0\"\n",
    "# Force a local ONNX installation so inherited Colab packages cannot shadow this profile.\n",
    "install = subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n",
    "                          \"--force-reinstall\", \"-c\", str(ENGINE_ROOT / \"requirements-core.txt\"),\n",
    "                          onnx_package, \"requests==2.32.5\", \"tqdm==4.67.1\"])\n",
    "print(\"ONNX installation:\", \"installed; still needs preflight\" if install.returncode == 0 else \"unavailable; automatic model branches will abstain\")\n",
    "def engine_command(*arguments, check=True):\n",
    "    return subprocess.run([WORKER_PYTHON, \"-m\", \"baseball_batting.cli\", *map(str,arguments)],\n",
    "                          cwd=ENGINE_ROOT, check=check)\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Persistent output directory\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-004"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "USE_DRIVE = False\n",
    "if USE_DRIVE:\n",
    "    from google.colab import drive\n",
    "    drive.mount(\"/content/drive\")\n",
    "OUTPUT_ROOT = Path(\"/content/drive/MyDrive/baseball_batting_results\") if USE_DRIVE else WORKSPACE_ROOT / \"artifacts\"\n",
    "OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)\n",
    "print(\"Durable mounted Drive\" if USE_DRIVE else \"Scratch output; export to preserve across sessions:\", OUTPUT_ROOT)\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-005"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download explicit model artifacts\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-006"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "DOWNLOAD_MODELS = True\n",
    "artifacts = {}\n",
    "if DOWNLOAD_MODELS:\n",
    "    for resource in (\"body_pose\", \"person_detector\", \"object_detector\"):\n",
    "        status = engine_command(\"fetch\", resource, \"--registry\", ENGINE_ROOT / \"configs/resources.yaml\",\n",
    "                                \"--output\", WORKSPACE_ROOT / \"downloads\", check=False)\n",
    "        record = WORKSPACE_ROOT / \"downloads\" / resource / \"resource.json\"\n",
    "        if status.returncode == 0 and record.exists():\n",
    "            artifacts[resource] = json.loads(record.read_text())[\"artifact_path\"]\n",
    "        else:\n",
    "            print(resource, \"unavailable; branch will return an explicit reason\")\n",
    "config = {\n",
    "    \"mode\": \"automatic\", \"chunk_size\": 64,\n",
    "    \"device\": \"cpu\" if PROFILE == \"cpu_reference\" else \"cuda\",\n",
    "    \"body_pose_path\": artifacts.get(\"body_pose\"),\n",
    "    \"person_detector_path\": artifacts.get(\"person_detector\"),\n",
    "    \"object_detector_path\": artifacts.get(\"object_detector\"),\n",
    "    \"body3d_enabled\": False, \"export_video\": True,\n",
    "}\n",
    "CONFIG_PATH = WORKSPACE_ROOT / \"engine-config.json\"\n",
    "CONFIG_PATH.write_text(json.dumps(config, indent=2))\n",
    "engine_command(\"preflight\", \"--config\", CONFIG_PATH, \"--output\", OUTPUT_ROOT / \"preflight\", \"--require-vision\")\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Full GPU worker and body reconstruction\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-008"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "BUILD_FULL_WORKER = False  # Set True with a GPU runtime and accessible SAM assets.\n",
    "if BUILD_FULL_WORKER:\n",
    "    if PROFILE != \"gpu_candidate\":\n",
    "        raise ValueError('Set PROFILE=\"gpu_candidate\", select a Colab GPU runtime, and rerun setup first')\n",
    "    import os\n",
    "    setup_environment = dict(os.environ)\n",
    "    try:\n",
    "        from google.colab import userdata\n",
    "        hf_secret = userdata.get(\"HF_TOKEN\")\n",
    "        if hf_secret:\n",
    "            setup_environment[\"HF_TOKEN\"] = hf_secret\n",
    "        del hf_secret\n",
    "    except Exception:\n",
    "        print(\"Using existing provider login/environment if available\")\n",
    "    status = subprocess.run([sys.executable, str(ENGINE_ROOT / \"tools/setup_full_worker.py\"),\n",
    "                             \"--workspace\", str(WORKSPACE_ROOT), \"--download-models\"],\n",
    "                            env=setup_environment)\n",
    "    setup_environment.pop(\"HF_TOKEN\", None)\n",
    "    full_record = json.loads((WORKSPACE_ROOT / \"full-worker.json\").read_text())\n",
    "    if status.returncode == 0:\n",
    "        config.update({name: full_record[name] for name in\n",
    "                       (\"sam_repo\", \"sam_checkpoint\", \"sam_config\", \"mhr_path\", \"mstcn_repo\")})\n",
    "        full_python = full_record[\"worker_python\"]\n",
    "        config.update(body3d_enabled=True, temporal3d_enabled=True, anatomy_enabled=True, device=\"cuda\")\n",
    "        config[\"stage_python\"] = {stage: full_python for stage in\n",
    "                                  (\"observations\", \"body3d\", \"temporal3d\", \"anatomy\", \"learned_events\")}\n",
    "        CONFIG_PATH.write_text(json.dumps(config, indent=2))\n",
    "        subprocess.run([full_python, \"-m\", \"baseball_batting.cli\", \"preflight\", \"--config\", str(CONFIG_PATH),\n",
    "                        \"--output\", str(OUTPUT_ROOT / \"preflight-full-vision\"), \"--require-vision\"], cwd=ENGINE_ROOT, check=True)\n",
    "        subprocess.run([full_python, \"-m\", \"baseball_batting.cli\", \"preflight-optional\", \"--config\", str(CONFIG_PATH),\n",
    "                        \"--output\", str(OUTPUT_ROOT / \"preflight-full\")], cwd=ENGINE_ROOT, check=True)\n",
    "        optional = json.loads((OUTPUT_ROOT / \"preflight-full\" / \"optional_runtime_profile.json\").read_text())[\"tests\"]\n",
    "        required = (\"torch\", \"mhr\", \"anatomy\")\n",
    "        if \"torch_mhr\" in optional or any(optional.get(name, {}).get(\"status\") != \"ready\" for name in required):\n",
    "            raise RuntimeError(\"Full-worker component preflight failed; inspect preflight-full/optional_runtime_profile.json\")\n",
    "    else:\n",
    "        raise RuntimeError(\"Full worker setup failed: \" + str(full_record.get(\"reason\")))\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Select a recording and metadata\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-010"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "GENERATED_FIXTURE = False\n",
    "VIDEO_PATH = \"\"  # Alternatively enter an existing video path.\n",
    "if GENERATED_FIXTURE:\n",
    "    VIDEO_PATH = str(WORKSPACE_ROOT / \"generated_fixture.mp4\")\n",
    "    subprocess.run([WORKER_PYTHON, str(ENGINE_ROOT / \"tools/make_fixture.py\"), VIDEO_PATH], check=True)\n",
    "elif not VIDEO_PATH:\n",
    "    from google.colab import files\n",
    "    uploaded = files.upload()\n",
    "    videos = [name for name in uploaded if name.lower().endswith((\".mp4\", \".mov\", \".mkv\", \".avi\", \".webm\"))]\n",
    "    assert len(videos) == 1, \"Select exactly one video\"\n",
    "    VIDEO_PATH = str(Path(videos[0]).resolve())\n",
    "METADATA = {\n",
    "    \"player_id\": \"player-001\", \"session_id\": \"session-001\", \"handedness\": \"right\",\n",
    "    \"height_m\": None, \"bat_length_m\": None,\n",
    "    \"consent\": \"not_supplied\", \"camera_stability\": \"unknown\", \"timing\": {\"kind\": \"unknown\"},\n",
    "    \"intended_use\": \"research\"\n",
    "}\n",
    "METADATA_PATH = WORKSPACE_ROOT / \"capture-metadata.json\"\n",
    "METADATA_PATH.write_text(json.dumps(METADATA, indent=2))\n",
    "SESSION_DIRECTORY = OUTPUT_ROOT / METADATA[\"session_id\"]\n",
    "# Repeat preflight in the actual observation worker if configuration was edited.\n",
    "vision_python = config.get(\"stage_python\", {}).get(\"observations\", WORKER_PYTHON)\n",
    "subprocess.run([vision_python, \"-m\", \"baseball_batting.cli\", \"preflight\", \"--config\", str(CONFIG_PATH),\n",
    "                \"--output\", str(OUTPUT_ROOT / \"preflight-analysis\"), \"--require-vision\"], cwd=ENGINE_ROOT, check=True)\n",
    "engine_command(\"analyze\", VIDEO_PATH, \"--config\", CONFIG_PATH, \"--metadata\", METADATA_PATH,\n",
    "               \"--output\", SESSION_DIRECTORY)\n",
    "(SESSION_DIRECTORY / \"source_checkout.json\").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-011"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inspect results\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-012"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from IPython.display import display, HTML, Video\n",
    "result = json.loads((SESSION_DIRECTORY / \"result.json\").read_text())\n",
    "display(HTML((SESSION_DIRECTORY / \"report.html\").read_text()))\n",
    "if (SESSION_DIRECTORY / \"annotated.mp4\").exists():\n",
    "    display(Video(str(SESSION_DIRECTORY / \"annotated.mp4\"), embed=True))\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optional operator review\n",
    "\n",
    "Review uses oriented-image pixels. Labels are separate files tied to the exact input hash. For a frame, enter for example:\n",
    "`{\"knob\":[x,y],\"barrel\":[x,y],\"ball\":[x,y],\"landmarks\":{\"left_wrist\":[x,y]},\"crop\":[x1,y1,x2,y2]}`.\n",
    "Confirm an event only if visible evidence supports it. Event example:\n",
    "`[{\"type\":\"contact\",\"state\":\"confirmed\",\"frame_interval\":[12,13],\"evidence_frames\":[12,13,14],\"evidence_description\":\"Visible interaction followed by outgoing ball\"}]`.\n",
    "Unknown remains unknown. Save before moving to another frame. Notebook widget use does not run a web service.\n"
   ],
   "id": "batting-014"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "RUN_REVIEW = False\n",
    "ANNOTATIONS_PATH = OUTPUT_ROOT / (METADATA[\"session_id\"] + \"-reviewed.json\")\n",
    "if RUN_REVIEW:\n",
    "    sys.path.insert(0, str(ENGINE_ROOT))\n",
    "    from baseball_batting.review import show_review_widget\n",
    "    show_review_widget(VIDEO_PATH, result[\"capture\"], ANNOTATIONS_PATH, annotator=\"operator-001\")\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-015"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "APPLY_REVIEWED_LABELS = False\n",
    "if APPLY_REVIEWED_LABELS:\n",
    "    assert ANNOTATIONS_PATH.exists(), \"Save labels first\"\n",
    "    config[\"mode\"] = \"operator_reviewed\"\n",
    "    config[\"annotations_path\"] = str(ANNOTATIONS_PATH)\n",
    "    CONFIG_PATH.write_text(json.dumps(config, indent=2))\n",
    "    engine_command(\"analyze\", VIDEO_PATH, \"--config\", CONFIG_PATH, \"--metadata\", METADATA_PATH,\n",
    "                   \"--output\", SESSION_DIRECTORY)\n",
    "    result = json.loads((SESSION_DIRECTORY / \"result.json\").read_text())\n",
    "    display(HTML((SESSION_DIRECTORY / \"report.html\").read_text()))\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dataset, training and evaluation commands\n",
    "\n",
    "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.\n",
    "\n",
    "```text\n",
    "python -m baseball_batting.cli dataset index.json --kind endpoint_cnn --output endpoint-data\n",
    "python -m baseball_batting.cli train endpoint-data --kind endpoint_cnn --output endpoint-model --epochs 30\n",
    "python -m baseball_batting.cli evaluate-checkpoint endpoint-data endpoint-model --thresholds your-preregistered-gates.json --scope your-task-and-view\n",
    "```\n",
    "\n",
    "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`.\n"
   ],
   "id": "batting-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download result archive\n",
    "\n",
    "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.\n"
   ],
   "id": "batting-018"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ARCHIVE_PATH = OUTPUT_ROOT / (METADATA[\"session_id\"] + \"-results.zip\")\n",
    "engine_command(\"export\", SESSION_DIRECTORY, ARCHIVE_PATH)\n",
    "if \"google.colab\" in sys.modules or Path(\"/content\").exists():\n",
    "    from google.colab import files\n",
    "    files.download(str(ARCHIVE_PATH))\n",
    "else:\n",
    "    print(ARCHIVE_PATH)\n"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "batting-019"
  }
 ]
}