{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" }, "accelerator": "GPU", "colab": { "name": "load_and_swing_test.ipynb", "provenance": [] } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Test load and swing timing on Colab\n", "\n", "Run the cells in order with **Runtime \u2192 Change runtime type \u2192 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.\n", "\n", "**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.\n", "\n", "**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.\n", "\n", "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.\n", "\n", "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.\n", "\n", "The timing and preview helpers are embedded in this notebook, so it works with the current GitHub engine without first pushing those helpers.\n" ], "id": "load-timing-000" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Get the current engine\n", "\n", "Use a GitHub token with read access to your private repository. The hidden token is used only during checkout and is not saved in the Git URL or results. Setup records the resolved commit. This notebook uses a separate workspace from the full pipeline notebook.\n" ], "id": "load-timing-001" }, { "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'\n", "REVISION = 'main' # Use the recorded full SHA to reproduce a run.\n", "PRIVATE_REPOSITORY = True\n", "WORKSPACE_ROOT = Path(\"/content/baseball_batting_load_timing\") if Path(\"/content\").exists() else Path.cwd() / \"batting_notebook_runtime\" / \"load_timing_test\"\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": "load-timing-002" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Install the GPU worker\n", "\n", "Dependencies are installed in a separate environment. This does not build SAM, MHR or OpenSim. Installation must finish before continuing.\n" ], "id": "load-timing-003" }, { "cell_type": "code", "metadata": {}, "source": [ "import shutil\n", "\n", "if not shutil.which(\"nvidia-smi\"):\n", " raise RuntimeError(\"Select Runtime > Change runtime type > GPU, then reconnect and rerun.\")\n", "subprocess.run([\"nvidia-smi\"], check=True)\n", "runtime = WORKSPACE_ROOT / \".runtime-load-timing\"\n", "worker_path = runtime / \"bin/python\"\n", "if runtime.exists() and (not worker_path.is_file() or subprocess.run(\n", " [str(worker_path), \"-m\", \"pip\", \"--version\"], capture_output=True).returncode != 0):\n", " shutil.rmtree(runtime)\n", "if not worker_path.exists():\n", " subprocess.run([sys.executable, \"-m\", \"venv\", \"--system-site-packages\", \"--without-pip\",\n", " str(runtime)], check=True)\n", "WORKER_PYTHON = str(worker_path)\n", "WORKER_ENV = {**os.environ, \"MPLBACKEND\": \"Agg\", \"PYTHONUNBUFFERED\": \"1\",\n", " \"PYTHONNOUSERSITE\": \"1\", \"PIP_REQUIRE_VIRTUALENV\": \"true\"}\n", "WORKER_ENV.pop(\"PYTHONPATH\", None)\n", "# Install locally even when Colab has inherited CPU ORT/numpy packages.\n", "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--only-binary=:all:\",\n", " \"--ignore-installed\", \"-r\", str(ENGINE_ROOT / \"requirements-api-gpu.txt\")],\n", " env=WORKER_ENV, check=True)\n", "subprocess.run([WORKER_PYTHON, \"-m\", \"pip\", \"install\", \"--ignore-installed\", \"--no-deps\", \"rtmlib==0.0.16\"],\n", " env=WORKER_ENV, check=True)\n", "def worker_command(module, *arguments):\n", " return subprocess.run([WORKER_PYTHON, \"-m\", module, *map(str, arguments)],\n", " cwd=ENGINE_ROOT, env=WORKER_ENV, check=True)\n", "print(\"2D worker installed. Actual CUDA execution is checked in the next cell.\")\n" ], "execution_count": null, "outputs": [], "id": "load-timing-004" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Download the two models and check GPU execution\n", "\n", "Only the person detector and 2D pose model are downloaded, with verified hashes. This cell must report `ready: true`. It refuses to silently run on CPU.\n" ], "id": "load-timing-005" }, { "cell_type": "code", "metadata": {}, "source": [ "MODEL_ROOT = WORKSPACE_ROOT / \"models\"\n", "worker_command(\"tools.setup_api_models\", \"--output\", MODEL_ROOT)\n", "PREFLIGHT_PATH = WORKSPACE_ROOT / \"gpu-preflight.json\"\n", "worker_command(\"baseball_batting.api_worker\", \"--models\", MODEL_ROOT,\n", " \"--preflight\", \"--output\", PREFLIGHT_PATH)\n", "preflight = json.loads(PREFLIGHT_PATH.read_text())\n", "if not preflight.get(\"ready\") or preflight.get(\"device\") != \"cuda\":\n", " raise RuntimeError(\"Actual CUDA preflight did not pass.\")\n", "print(json.dumps(preflight, indent=2))\n" ], "execution_count": null, "outputs": [], "id": "load-timing-006" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Upload a video and set its recording information\n", "\n", "You can enter an existing `VIDEO_PATH` or leave it empty to upload. Set `HANDEDNESS` to the batter's own handedness when known. `PITCHER_DIRECTION` is the direction toward the pitcher/tee in the image: `\"image_left\"` or `\"image_right\"`. Leave it `None` if unknown. Cross-step drills can confuse automatic ankle ordering, so an explicit known direction helps.\n", "\n", "Set `VIEW=\"face_on\"` only for a known face-on recording. Unknown view keeps measurements empty, while ranges and generic motion events can still be inspected. Set `CAMERA_STABILITY=\"moving\"` for a moving camera and `\"fixed_verified\"` only when the camera stays still. Moving/unknown cameras can still return within-frame body positions and projected knee angles when the required events are found. Ground-foot events and head movement require a fixed camera.\n", "\n", "Keep `TIMING={\"kind\":\"unknown\"}` unless capture timing is known. For an original unretimed recording use `{\"kind\":\"unretimed\",\"source\":\"original camera file; no retiming\"}`. For documented constant slow motion use `{\"kind\":\"constant_slowdown\",\"source\":\"documented camera/export settings\",\"factor\":8,\"all_captured_frames_retained\":True}` with the real factor. Playback FPS is not capture FPS. Timing estimates support documented nominal 30 FPS or higher cadence, including 29.97 FPS and variable cadence with no larger gaps. Each timing measurement is separately withheld if moving its events by one frame changes it too much. 60 FPS gives finer time resolution; it is no longer required.\n", "\n", "Use `SINGLE_SWING=True` for exactly one swing, or `False` for automatic splitting. A new upload cell run creates a new job; rerunning only the analysis cell resumes the same job and verified observation cache. The current worker limits are 7,200 frames, 120 playback seconds and 8.3 megapixels per frame.\n" ], "id": "load-timing-007" }, { "cell_type": "code", "metadata": {}, "source": [ "from google.colab import files\n", "import hashlib\n", "import uuid\n", "\n", "VIDEO_PATH = \"\" # Or, for example: \"/content/IMG_1640.mp4\"\n", "HANDEDNESS = None # Set to \"right\" or \"left\" when known.\n", "PITCHER_DIRECTION = None # \"image_left\" or \"image_right\" toward the pitcher/tee, when known.\n", "VIEW = \"unknown\" # Change to \"face_on\" when known.\n", "CAMERA_STABILITY = \"unknown\" # Change to \"fixed_verified\" when the camera stays still.\n", "TIMING = {\"kind\": \"unknown\"}\n", "SINGLE_SWING = True # True only for a video containing exactly one swing.\n", "\n", "if not VIDEO_PATH:\n", " uploaded = files.upload()\n", " videos = [name for name in uploaded if name.lower().endswith((\".mp4\", \".mov\", \".mkv\", \".avi\", \".webm\"))]\n", " if len(videos) != 1:\n", " raise ValueError(\"Upload exactly one video containing the swings.\")\n", " VIDEO_PATH = str(Path(videos[0]).resolve())\n", " del uploaded\n", "source_video = Path(VIDEO_PATH).resolve()\n", "if not source_video.is_file():\n", " raise ValueError(\"VIDEO_PATH does not exist. Upload the video or correct its path.\")\n", "OPTIONS = {\"discipline\": \"hitting\", \"handedness\": HANDEDNESS, \"view\": VIEW,\n", " \"pitcher_direction\": PITCHER_DIRECTION,\n", " \"camera_stability\": CAMERA_STABILITY, \"timing\": TIMING, \"single_swing\": SINGLE_SWING, \"measurement_backend\": \"2d\"}\n", "JOB_ROOT = WORKSPACE_ROOT / \"results\" / (\"session-\" + uuid.uuid4().hex[:12])\n", "JOB_ROOT.mkdir(parents=True)\n", "INPUT_VIDEO = JOB_ROOT / (\"input\" + source_video.suffix.lower())\n", "shutil.copy2(source_video, INPUT_VIDEO)\n", "(JOB_ROOT / \"request.json\").write_text(json.dumps(OPTIONS, indent=2))\n", "(JOB_ROOT / \"source_checkout.json\").write_text(json.dumps(SOURCE_CHECKOUT, indent=2))\n", "checksum = hashlib.sha256()\n", "with INPUT_VIDEO.open(\"rb\") as stream:\n", " for block in iter(lambda: stream.read(1024 * 1024), b\"\"):\n", " checksum.update(block)\n", "(JOB_ROOT / \"run-context.json\").write_text(json.dumps({\"input_sha256\": checksum.hexdigest(),\n", " \"source_video_name\": source_video.name, \"mode\": \"load_and_swing_timing_test\"}, indent=2))\n", "print(\"Job:\", JOB_ROOT.name)\n", "print(\"Recording options:\", json.dumps(OPTIONS, indent=2))\n" ], "execution_count": null, "outputs": [], "id": "load-timing-008" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Detect the body movements\n", "\n", "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.\n", "\n", "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.\n" ], "id": "load-timing-009" }, { "cell_type": "code", "metadata": {}, "source": [ "import signal\n", "import time\n", "\n", "RUN_TIMEOUT_S = 1800\n", "WORKER_LOG = JOB_ROOT / \"worker.log\"\n", "(JOB_ROOT / \"error.json\").unlink(missing_ok=True)\n", "(JOB_ROOT / \"progress.json\").unlink(missing_ok=True)\n", "command = [WORKER_PYTHON, \"-m\", \"baseball_batting.api_worker\", \"--models\", str(MODEL_ROOT),\n", " \"--job\", str(JOB_ROOT)]\n", "started = time.monotonic()\n", "with WORKER_LOG.open(\"w\") as log:\n", " process = subprocess.Popen(command, cwd=ENGINE_ROOT, env=WORKER_ENV,\n", " stdout=log, stderr=subprocess.STDOUT, start_new_session=True)\n", " last_print, last_stage = 0., None\n", " try:\n", " while process.poll() is None:\n", " elapsed = time.monotonic()-started\n", " if elapsed > RUN_TIMEOUT_S:\n", " raise TimeoutError(\"Analysis timed out; inspect worker.log and try a shorter recording.\")\n", " progress_path = JOB_ROOT / \"progress.json\"\n", " progress = json.loads(progress_path.read_text()) if progress_path.exists() else {\"stage\": \"starting\"}\n", " if progress[\"stage\"] != last_stage or elapsed-last_print >= 15:\n", " print(f\"{elapsed:.0f}s | {progress['stage']} | \"\n", " f\"{progress.get('completed_frames', 0)}/{progress.get('total_frames') or '?'} frames\", flush=True)\n", " last_print, last_stage = elapsed, progress[\"stage\"]\n", " time.sleep(2)\n", " finally:\n", " if process.poll() is None:\n", " os.killpg(process.pid, signal.SIGTERM)\n", " try:\n", " process.wait(timeout=5)\n", " except subprocess.TimeoutExpired:\n", " os.killpg(process.pid, signal.SIGKILL)\n", " process.wait()\n", "if process.returncode != 0:\n", " print(WORKER_LOG.read_text(errors=\"replace\")[-8000:])\n", " raise RuntimeError(\"2D analysis failed. The worker log above contains the actual error.\")\n", "result = json.loads((JOB_ROOT / \"result.json\").read_text())\n", "print(f\"Finished in {time.monotonic()-started:.1f}s. Detected {len(result['pose_track']['reps'])} swing candidates.\")\n" ], "execution_count": null, "outputs": [], "id": "load-timing-010" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Calculate only the four timing fields\n", "\n", "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.\n", "\n", "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.\n", "\n", "- `outcome`: `\"hit\"`, `\"miss\"`, or `\"unknown\"`.\n", "- `stepped`: `True`, `False`, or `None` when unknown. Missing foot events do not prove no step.\n", "- Optional frames: `load_start_frame`, `swing_start_frame`, `foot_contact_frame`, `contact_frame` for a hit, or `closest_approach_frame` for a miss.\n", "- Forward swing start is the start of the forward movement, rather than any generic hand movement.\n", "- Load-to-swing = swing start \u2212 load start. Foot-down-to-swing = swing start \u2212 first ground contact, and can be negative.\n", "- 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.\n", "\n", "No manual fields are required. This is an optional way to inspect and test the calculations, not automatic impact detection.\n" ], "id": "load-timing-011" }, { "cell_type": "code", "metadata": {}, "source": [ "REVIEWED_EVENTS = {}\n", "# Optional template; replace comments with visible frame numbers, not guesses:\n", "# REVIEWED_EVENTS = {\n", "# 1: {\n", "# \"source\": \"Frame-by-frame inspection of the original recording\",\n", "# \"outcome\": \"hit\",\n", "# \"stepped\": True,\n", "# \"load_start_frame\": ..., # Optional\n", "# \"swing_start_frame\": ..., # Optional\n", "# \"foot_contact_frame\": ..., # Optional\n", "# \"contact_frame\": ..., # Only when actual ball contact is visible\n", "# }\n", "# }\n", "\n", "# Bundled timing calculations below; no edits needed to run the automatic test.\n", "\"\"\"Four experimental timing fields, without substituting body pose for impact.\n", "\n", "This module is also embedded verbatim in the standalone Colab test notebook.\n", "It uses only the standard library, reads an existing 2D result, and never alters\n", "the API's current nine-metric payload. Reviewed frames are optional test inputs.\n", "\"\"\"\n", "from copy import deepcopy\n", "import math\n", "\n", "LOAD_TIMING_VERSION = \"load-timing-test-v1\"\n", "LOAD_TIMING_KEYS = (\"load_to_swing_ms\", \"foot_down_to_swing_ms\",\n", " \"swing_duration_ms\", \"early_late_shift_ms\")\n", "REVIEW_FIELDS = {\"source\", \"load_start_frame\", \"swing_start_frame\",\n", " \"foot_contact_frame\", \"contact_frame\", \"closest_approach_frame\",\n", " \"stepped\", \"outcome\"}\n", "\n", "\n", "def _timing_metric(key, note, status=\"unclear\", **extra):\n", " return {\"key\": key, \"value\": None, \"unit\": \"ms\", \"status\": status,\n", " \"confidence\": \"est\", \"note\": note, **extra}\n", "\n", "\n", "def _frame_event(frame, method, note):\n", " return {\"frame\": frame, \"method\": method, \"estimated\": True, \"note\": note}\n", "\n", "\n", "def _timing_interval(track, rep, a, b, *, signed=False):\n", " \"\"\"Use capture timestamps and expose \u00b11-frame sensitivity, not error bars.\"\"\"\n", " diagnostic = {\"start_frame\": a, \"end_frame\": b,\n", " \"sensitivity_scope\": \"each event shifted \u00b11 frame; detection error may be larger\"}\n", " if a is None or b is None:\n", " return None, \"Required event is missing.\", diagnostic\n", " start, end = rep[\"start_frame\"], rep[\"end_frame\"]\n", " if not start <= a <= end or not start <= b <= end:\n", " return None, \"An event is outside this swing range.\", diagnostic\n", " if not signed and b <= a:\n", " return None, \"Event order does not give a positive duration.\", diagnostic\n", " times = track[\"frames\"][\"t_s\"]\n", " clock = times[start:end+1]\n", " if (len(clock) < 2 or any(t is None or not math.isfinite(t) for t in clock)\n", " or any(y <= x for x, y in zip(clock, clock[1:]))):\n", " return None, \"Actual recording time is unknown or invalid; playback time is not used.\", diagnostic\n", " steps = [y-x for x, y in zip(clock, clock[1:])]\n", " diagnostic[\"capture_interval_ms\"] = [round(min(steps)*1000, 3), round(max(steps)*1000, 3)]\n", " if max(steps) > 1.01/30 + 1e-6:\n", " return None, \"Capture cadence is below nominal 30 FPS or has large frame gaps.\", diagnostic\n", " a_window = [max(start, a-1), min(end, a+1)]\n", " b_window = [max(start, b-1), min(end, b+1)]\n", " low = (times[b_window[0]]-times[a_window[1]])*1000\n", " high = (times[b_window[1]]-times[a_window[0]])*1000\n", " value = (times[b]-times[a])*1000\n", " diagnostic.update(event_shift_frames=[a_window, b_window],\n", " frame_sensitivity_range_ms=[round(low, 3), round(high, 3)])\n", " if signed:\n", " diagnostic[\"order_resolved_under_frame_shift\"] = low > 0 or high < 0\n", " note = (\"Event order can change within \u00b11 frame; this estimate cannot establish which happened first.\"\n", " if low <= 0 <= high else \"Signed difference from capture timestamps.\")\n", " return round(value, 3), note, diagnostic\n", " width = (high-low)/value\n", " diagnostic[\"relative_sensitivity_width\"] = width\n", " diagnostic[\"relative_sensitivity_width_limit\"] = .5\n", " if low <= 0 or width > .5+1e-9:\n", " return None, \"Duration is unresolved under \u00b11-frame event shifts; inspect the event frames and sensitivity range.\", diagnostic\n", " return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\n", "\n", "\n", "def build_load_timing_report(result, reviewed=None, ball_evidence=None):\n", " \"\"\"Extract timing estimates from body events and separate bat/ball evidence.\n", "\n", " reviewed maps rep numbers to visible event frames and their source. It is\n", " empty by default. Manual labels never manufacture a clock or an early/late\n", " correction. Every supplied frame must be inside its existing rep range.\n", " \"\"\"\n", " if reviewed is None:\n", " reviewed = {}\n", " if not isinstance(reviewed, dict):\n", " raise ValueError(\"Reviewed events must be a dictionary keyed by swing number.\")\n", " track = result[\"pose_track\"]\n", " reps = track[\"reps\"]\n", " normalized = {}\n", " for key, label in reviewed.items():\n", " if isinstance(key, bool) or not str(key).isdigit():\n", " raise ValueError(\"Reviewed swing numbers must be positive integers.\")\n", " number = int(key)\n", " if number in normalized or number not in {r[\"rep\"] for r in reps}:\n", " raise ValueError(\"Reviewed events name a duplicate or nonexistent swing.\")\n", " if not isinstance(label, dict) or set(label)-REVIEW_FIELDS:\n", " raise ValueError(\"Unknown reviewed-event fields.\")\n", " if not isinstance(label.get(\"source\"), str) or not label[\"source\"].strip():\n", " raise ValueError(\"Reviewed events require a source describing what was checked.\")\n", " normalized[number] = label\n", " capture = deepcopy(result[\"measurements\"][\"capture\"])\n", " payload = {\"schema_version\": \"3.0\", \"discipline\": \"hitting\", \"time_basis\": \"capture\",\n", " \"capture\": capture, \"reps\": []}\n", " diagnostics = []\n", " for rep in reps:\n", " label = normalized.get(rep[\"rep\"], {})\n", " events = deepcopy(rep[\"events\"])\n", " for name in (\"load_start\", \"swing_start\", \"foot_contact\", \"contact\", \"closest_approach\"):\n", " key = name+\"_frame\"\n", " if key in label:\n", " frame = label[key]\n", " if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\n", " raise ValueError(f\"{key} must be an integer frame inside swing {rep['rep']}.\")\n", " events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\n", " evidence = (ball_evidence or {}).get(rep['rep'], {})\n", " outcome = label.get(\"outcome\", evidence.get('outcome', 'unknown'))\n", " if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\n", " raise ValueError(\"Outcome must be hit, miss or unknown.\")\n", " if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\n", " raise ValueError(\"A reviewed contact frame requires hit and no closest-approach frame.\")\n", " if \"closest_approach_frame\" in label and outcome != \"miss\":\n", " raise ValueError(\"A reviewed closest-approach frame requires miss.\")\n", " stepped = label.get(\"stepped\", True if \"stride\" in events and \"foot_contact\" in events else None)\n", " if stepped is not None and type(stepped) is not bool:\n", " raise ValueError(\"Stepped must be true, false or unknown (None).\")\n", " if stepped is False and \"foot_contact_frame\" in label:\n", " raise ValueError(\"A no-step swing cannot have a reviewed step landing.\")\n", " onset = events.get(\"swing_start\", {})\n", " forward = (onset.get(\"method\", \"\").startswith(\"primary_swing_forward_hand_motion_\")\n", " or onset.get(\"method\") == \"reviewed_video_frame\")\n", " block = (\"Capture check failed: \" + \", \".join(capture.get(\"reasons\", []))\n", " if not capture.get(\"ok\") else None)\n", " if not forward:\n", " block = block or \"Only generic hand movement was detected; forward swing start is not established.\"\n", " by_key, intervals = {}, {}\n", " def interval(key, first, last, description, signed=False, **extra):\n", " a, b = events.get(first, {}).get(\"frame\"), events.get(last, {}).get(\"frame\")\n", " value, reason, evidence = _timing_interval(track, rep, a, b, signed=signed)\n", " intervals[key] = evidence\n", " if block:\n", " value, reason = None, block\n", " elif a is None or b is None:\n", " absent = [n for n in (first, last) if n not in events]\n", " reason = \"Missing \" + \", \".join(absent) + \". \" + \" \".join(\n", " rep.get(\"missing_events\", {}).get(n, \"\") for n in absent)\n", " metric = _timing_metric(key, reason, **extra)\n", " if value is not None:\n", " metric.update(value=value, status=\"estimated\", note=description+\" \"+reason)\n", " by_key[key] = metric\n", " interval(\"load_to_swing_ms\", \"load_start\", \"swing_start\",\n", " \"Preparation (backward hand load) to estimated forward swing start.\")\n", " if stepped is False:\n", " by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Player did not step.\", \"not_applicable\")\n", " elif stepped is None:\n", " by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Whether the player stepped is unknown; missing foot events do not prove no step.\")\n", " else:\n", " interval(\"foot_down_to_swing_ms\", \"foot_contact\", \"swing_start\",\n", " \"First front-foot ground contact to estimated forward swing start; negative means swing began before landing.\", signed=True)\n", " end_name = \"contact\" if outcome == \"hit\" else \"closest_approach\" if outcome == \"miss\" else None\n", " # The 2D detector's contact field is an arm-extension proxy. It is\n", " # deliberately rejected here even when its score or timing looks good.\n", " actual_end = end_name and events.get(end_name, {}).get(\"method\") == \"reviewed_video_frame\"\n", " if actual_end:\n", " interval(\"swing_duration_ms\", \"swing_start\", end_name,\n", " \"Swing start to \" + (\"reviewed ball contact.\" if outcome == \"hit\" else \"reviewed closest bat-ball approach for a miss; this is a visual estimate.\"),\n", " end_event=end_name)\n", " else:\n", " by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\n", " \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\n", " if not actual_end and evidence.get('end_event') in {'contact', 'closest_approach'}:\n", " frame = events.get('swing_start', {}).get('frame')\n", " times = track['frames']['t_s']\n", " value, reason = None, block\n", " bounds = evidence.get('time_interval_s')\n", " interval_evidence = {'end_method': evidence['method'], 'end_interval_s': bounds,\n", " 'sensitivity_scope': 'endpoint interval plus \u00b11-frame start sensitivity; onset error unvalidated'}\n", " if not block and frame is not None and times[frame] is not None and bounds:\n", " a, b = max(rep['start_frame'], frame-1), min(rep['end_frame'], frame+1)\n", " if times[a] is not None and times[b] is not None:\n", " value = (evidence['time_s']-times[frame])*1000\n", " low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000\n", " interval_evidence['frame_sensitivity_range_ms'] = [round(low, 3), round(high, 3)]\n", " if value <= 0 or low <= 0 or (high-low)/value > .5:\n", " value, reason = None, 'Endpoint/start interval does not resolve swing duration.'\n", " note = reason or ('Forward hand onset to '+evidence['end_event']+' from bat/ball observations. Event accuracy remains unvalidated.')\n", " by_key['swing_duration_ms'] = _timing_metric('swing_duration_ms', note,\n", " status='estimated' if value is not None else 'unclear', end_event=evidence['end_event'] if value is not None else None)\n", " if value is not None:\n", " by_key['swing_duration_ms']['value'] = round(value, 3)\n", " intervals['swing_duration_ms'] = interval_evidence\n", " by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\n", " \"Only applies to misses.\" if outcome == \"hit\" else\n", " \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\n", " \"not_applicable\" if outcome == \"hit\" else \"unclear\")\n", " if outcome == 'miss':\n", " shift = evidence.get('shift', {})\n", " value = shift.get('value') if not block else None\n", " reason = block or shift.get('reason_code') or evidence.get('reason_code') or 'depth_unresolved'\n", " by_key['early_late_shift_ms'] = _timing_metric('early_late_shift_ms',\n", " 'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.' if value is not None else reason,\n", " 'estimated' if value is not None else 'unclear')\n", " if value is not None:\n", " by_key['early_late_shift_ms']['value'] = value\n", " intervals['early_late_shift_ms'] = deepcopy(shift)\n", " payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\n", " \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\n", " moments = {}\n", " for name in (\"load_start\", \"foot_contact\", \"swing_start\"):\n", " if name in events:\n", " moments[name] = deepcopy(events[name])\n", " proxy = rep[\"events\"].get(\"contact\")\n", " if proxy:\n", " moments[\"body_extension_proxy\"] = deepcopy(proxy)\n", " if actual_end:\n", " moments[\"reviewed_\"+end_name] = deepcopy(events[end_name])\n", " for event in moments.values():\n", " i = event[\"frame\"]\n", " event[\"capture_time_s\"] = track[\"frames\"][\"t_s\"][i]\n", " event[\"playback_time_s\"] = track[\"frames\"][\"playback_t_s\"][i]\n", " diagnostics.append({\"rep\": rep[\"rep\"], \"start_frame\": rep[\"start_frame\"],\n", " \"end_frame\": rep[\"end_frame\"], \"boundary_method\": rep[\"boundary_method\"],\n", " \"forward_swing_established\": forward, \"events\": moments,\n", " \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\n", " \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\n", " diagnostics[-1]['bat_ball_evidence'] = deepcopy(evidence)\n", " return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\n", " \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\n", " \"capabilities\": {\"automatic_body_events\": True,\n", " \"automatic_ball_contact\": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),\n", " \"automatic_bat_ball_tracking\": any(e.get('reason_code') != 'tracking_models_unavailable' for e in (ball_evidence or {}).values()),\n", " \"early_late_estimate\": any('shift' in e for e in (ball_evidence or {}).values())},\n", " \"diagnostics\": diagnostics,\n", " \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\n", " \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\n", " \"No ready, pause, rushed, fault, priority or drill decisions are produced.\"]}\n", "\n", "\n", "from IPython.display import HTML, Image, Video, display\n", "import html\n", "\n", "result = json.loads((JOB_ROOT / \"result.json\").read_text())\n", "TIMING_REPORT = build_load_timing_report(result, REVIEWED_EVENTS)\n", "TIMING_REPORT[\"source_checkout\"] = SOURCE_CHECKOUT\n", "TIMING_REPORT[\"run_context\"] = json.loads((JOB_ROOT / \"run-context.json\").read_text())\n", "TIMING_HELPER_SOURCE = '\"\"\"Four experimental timing fields, without substituting body pose for impact.\\n\\nThis module is also embedded verbatim in the standalone Colab test notebook.\\nIt uses only the standard library, reads an existing 2D result, and never alters\\nthe API\\'s current nine-metric payload. Reviewed frames are optional test inputs.\\n\"\"\"\\nfrom copy import deepcopy\\nimport math\\n\\nLOAD_TIMING_VERSION = \"load-timing-test-v1\"\\nLOAD_TIMING_KEYS = (\"load_to_swing_ms\", \"foot_down_to_swing_ms\",\\n \"swing_duration_ms\", \"early_late_shift_ms\")\\nREVIEW_FIELDS = {\"source\", \"load_start_frame\", \"swing_start_frame\",\\n \"foot_contact_frame\", \"contact_frame\", \"closest_approach_frame\",\\n \"stepped\", \"outcome\"}\\n\\n\\ndef _timing_metric(key, note, status=\"unclear\", **extra):\\n return {\"key\": key, \"value\": None, \"unit\": \"ms\", \"status\": status,\\n \"confidence\": \"est\", \"note\": note, **extra}\\n\\n\\ndef _frame_event(frame, method, note):\\n return {\"frame\": frame, \"method\": method, \"estimated\": True, \"note\": note}\\n\\n\\ndef _timing_interval(track, rep, a, b, *, signed=False):\\n \"\"\"Use capture timestamps and expose \u00b11-frame sensitivity, not error bars.\"\"\"\\n diagnostic = {\"start_frame\": a, \"end_frame\": b,\\n \"sensitivity_scope\": \"each event shifted \u00b11 frame; detection error may be larger\"}\\n if a is None or b is None:\\n return None, \"Required event is missing.\", diagnostic\\n start, end = rep[\"start_frame\"], rep[\"end_frame\"]\\n if not start <= a <= end or not start <= b <= end:\\n return None, \"An event is outside this swing range.\", diagnostic\\n if not signed and b <= a:\\n return None, \"Event order does not give a positive duration.\", diagnostic\\n times = track[\"frames\"][\"t_s\"]\\n clock = times[start:end+1]\\n if (len(clock) < 2 or any(t is None or not math.isfinite(t) for t in clock)\\n or any(y <= x for x, y in zip(clock, clock[1:]))):\\n return None, \"Actual recording time is unknown or invalid; playback time is not used.\", diagnostic\\n steps = [y-x for x, y in zip(clock, clock[1:])]\\n diagnostic[\"capture_interval_ms\"] = [round(min(steps)*1000, 3), round(max(steps)*1000, 3)]\\n if max(steps) > 1.01/30 + 1e-6:\\n return None, \"Capture cadence is below nominal 30 FPS or has large frame gaps.\", diagnostic\\n a_window = [max(start, a-1), min(end, a+1)]\\n b_window = [max(start, b-1), min(end, b+1)]\\n low = (times[b_window[0]]-times[a_window[1]])*1000\\n high = (times[b_window[1]]-times[a_window[0]])*1000\\n value = (times[b]-times[a])*1000\\n diagnostic.update(event_shift_frames=[a_window, b_window],\\n frame_sensitivity_range_ms=[round(low, 3), round(high, 3)])\\n if signed:\\n diagnostic[\"order_resolved_under_frame_shift\"] = low > 0 or high < 0\\n note = (\"Event order can change within \u00b11 frame; this estimate cannot establish which happened first.\"\\n if low <= 0 <= high else \"Signed difference from capture timestamps.\")\\n return round(value, 3), note, diagnostic\\n width = (high-low)/value\\n diagnostic[\"relative_sensitivity_width\"] = width\\n diagnostic[\"relative_sensitivity_width_limit\"] = .5\\n if low <= 0 or width > .5+1e-9:\\n return None, \"Duration is unresolved under \u00b11-frame event shifts; inspect the event frames and sensitivity range.\", diagnostic\\n return round(value, 3), \"Duration from capture timestamps; event detection remains unvalidated.\", diagnostic\\n\\n\\ndef build_load_timing_report(result, reviewed=None, ball_evidence=None):\\n \"\"\"Extract timing estimates from body events and separate bat/ball evidence.\\n\\n reviewed maps rep numbers to visible event frames and their source. It is\\n empty by default. Manual labels never manufacture a clock or an early/late\\n correction. Every supplied frame must be inside its existing rep range.\\n \"\"\"\\n if reviewed is None:\\n reviewed = {}\\n if not isinstance(reviewed, dict):\\n raise ValueError(\"Reviewed events must be a dictionary keyed by swing number.\")\\n track = result[\"pose_track\"]\\n reps = track[\"reps\"]\\n normalized = {}\\n for key, label in reviewed.items():\\n if isinstance(key, bool) or not str(key).isdigit():\\n raise ValueError(\"Reviewed swing numbers must be positive integers.\")\\n number = int(key)\\n if number in normalized or number not in {r[\"rep\"] for r in reps}:\\n raise ValueError(\"Reviewed events name a duplicate or nonexistent swing.\")\\n if not isinstance(label, dict) or set(label)-REVIEW_FIELDS:\\n raise ValueError(\"Unknown reviewed-event fields.\")\\n if not isinstance(label.get(\"source\"), str) or not label[\"source\"].strip():\\n raise ValueError(\"Reviewed events require a source describing what was checked.\")\\n normalized[number] = label\\n capture = deepcopy(result[\"measurements\"][\"capture\"])\\n payload = {\"schema_version\": \"3.0\", \"discipline\": \"hitting\", \"time_basis\": \"capture\",\\n \"capture\": capture, \"reps\": []}\\n diagnostics = []\\n for rep in reps:\\n label = normalized.get(rep[\"rep\"], {})\\n events = deepcopy(rep[\"events\"])\\n for name in (\"load_start\", \"swing_start\", \"foot_contact\", \"contact\", \"closest_approach\"):\\n key = name+\"_frame\"\\n if key in label:\\n frame = label[key]\\n if (type(frame) is not int or not rep[\"start_frame\"] <= frame <= rep[\"end_frame\"]):\\n raise ValueError(f\"{key} must be an integer frame inside swing {rep[\\'rep\\']}.\")\\n events[name] = _frame_event(frame, \"reviewed_video_frame\", label[\"source\"].strip())\\n evidence = (ball_evidence or {}).get(rep[\\'rep\\'], {})\\n outcome = label.get(\"outcome\", evidence.get(\\'outcome\\', \\'unknown\\'))\\n if not isinstance(outcome, str) or outcome not in {\"hit\", \"miss\", \"unknown\"}:\\n raise ValueError(\"Outcome must be hit, miss or unknown.\")\\n if \"contact_frame\" in label and (outcome != \"hit\" or \"closest_approach_frame\" in label):\\n raise ValueError(\"A reviewed contact frame requires hit and no closest-approach frame.\")\\n if \"closest_approach_frame\" in label and outcome != \"miss\":\\n raise ValueError(\"A reviewed closest-approach frame requires miss.\")\\n stepped = label.get(\"stepped\", True if \"stride\" in events and \"foot_contact\" in events else None)\\n if stepped is not None and type(stepped) is not bool:\\n raise ValueError(\"Stepped must be true, false or unknown (None).\")\\n if stepped is False and \"foot_contact_frame\" in label:\\n raise ValueError(\"A no-step swing cannot have a reviewed step landing.\")\\n onset = events.get(\"swing_start\", {})\\n forward = (onset.get(\"method\", \"\").startswith(\"primary_swing_forward_hand_motion_\")\\n or onset.get(\"method\") == \"reviewed_video_frame\")\\n block = (\"Capture check failed: \" + \", \".join(capture.get(\"reasons\", []))\\n if not capture.get(\"ok\") else None)\\n if not forward:\\n block = block or \"Only generic hand movement was detected; forward swing start is not established.\"\\n by_key, intervals = {}, {}\\n def interval(key, first, last, description, signed=False, **extra):\\n a, b = events.get(first, {}).get(\"frame\"), events.get(last, {}).get(\"frame\")\\n value, reason, evidence = _timing_interval(track, rep, a, b, signed=signed)\\n intervals[key] = evidence\\n if block:\\n value, reason = None, block\\n elif a is None or b is None:\\n absent = [n for n in (first, last) if n not in events]\\n reason = \"Missing \" + \", \".join(absent) + \". \" + \" \".join(\\n rep.get(\"missing_events\", {}).get(n, \"\") for n in absent)\\n metric = _timing_metric(key, reason, **extra)\\n if value is not None:\\n metric.update(value=value, status=\"estimated\", note=description+\" \"+reason)\\n by_key[key] = metric\\n interval(\"load_to_swing_ms\", \"load_start\", \"swing_start\",\\n \"Preparation (backward hand load) to estimated forward swing start.\")\\n if stepped is False:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Player did not step.\", \"not_applicable\")\\n elif stepped is None:\\n by_key[\"foot_down_to_swing_ms\"] = _timing_metric(\"foot_down_to_swing_ms\", \"Whether the player stepped is unknown; missing foot events do not prove no step.\")\\n else:\\n interval(\"foot_down_to_swing_ms\", \"foot_contact\", \"swing_start\",\\n \"First front-foot ground contact to estimated forward swing start; negative means swing began before landing.\", signed=True)\\n end_name = \"contact\" if outcome == \"hit\" else \"closest_approach\" if outcome == \"miss\" else None\\n # The 2D detector\\'s contact field is an arm-extension proxy. It is\\n # deliberately rejected here even when its score or timing looks good.\\n actual_end = end_name and events.get(end_name, {}).get(\"method\") == \"reviewed_video_frame\"\\n if actual_end:\\n interval(\"swing_duration_ms\", \"swing_start\", end_name,\\n \"Swing start to \" + (\"reviewed ball contact.\" if outcome == \"hit\" else \"reviewed closest bat-ball approach for a miss; this is a visual estimate.\"),\\n end_event=end_name)\\n else:\\n by_key[\"swing_duration_ms\"] = _timing_metric(\"swing_duration_ms\",\\n \"Actual ball contact or closest bat-ball approach is not established. The arm-extension proxy is not ball contact.\", end_event=None)\\n if not actual_end and evidence.get(\\'end_event\\') in {\\'contact\\', \\'closest_approach\\'}:\\n frame = events.get(\\'swing_start\\', {}).get(\\'frame\\')\\n times = track[\\'frames\\'][\\'t_s\\']\\n value, reason = None, block\\n bounds = evidence.get(\\'time_interval_s\\')\\n interval_evidence = {\\'end_method\\': evidence[\\'method\\'], \\'end_interval_s\\': bounds,\\n \\'sensitivity_scope\\': \\'endpoint interval plus \u00b11-frame start sensitivity; onset error unvalidated\\'}\\n if not block and frame is not None and times[frame] is not None and bounds:\\n a, b = max(rep[\\'start_frame\\'], frame-1), min(rep[\\'end_frame\\'], frame+1)\\n if times[a] is not None and times[b] is not None:\\n value = (evidence[\\'time_s\\']-times[frame])*1000\\n low, high = (bounds[0]-times[b])*1000, (bounds[1]-times[a])*1000\\n interval_evidence[\\'frame_sensitivity_range_ms\\'] = [round(low, 3), round(high, 3)]\\n if value <= 0 or low <= 0 or (high-low)/value > .5:\\n value, reason = None, \\'Endpoint/start interval does not resolve swing duration.\\'\\n note = reason or (\\'Forward hand onset to \\'+evidence[\\'end_event\\']+\\' from bat/ball observations. Event accuracy remains unvalidated.\\')\\n by_key[\\'swing_duration_ms\\'] = _timing_metric(\\'swing_duration_ms\\', note,\\n status=\\'estimated\\' if value is not None else \\'unclear\\', end_event=evidence[\\'end_event\\'] if value is not None else None)\\n if value is not None:\\n by_key[\\'swing_duration_ms\\'][\\'value\\'] = round(value, 3)\\n intervals[\\'swing_duration_ms\\'] = interval_evidence\\n by_key[\"early_late_shift_ms\"] = _timing_metric(\"early_late_shift_ms\",\\n \"Only applies to misses.\" if outcome == \"hit\" else\\n \"Reliable bat/ball paths are unavailable; shifting the same swing to meet the ball cannot be estimated.\",\\n \"not_applicable\" if outcome == \"hit\" else \"unclear\")\\n if outcome == \\'miss\\':\\n shift = evidence.get(\\'shift\\', {})\\n value = shift.get(\\'value\\') if not block else None\\n reason = block or shift.get(\\'reason_code\\') or evidence.get(\\'reason_code\\') or \\'depth_unresolved\\'\\n by_key[\\'early_late_shift_ms\\'] = _timing_metric(\\'early_late_shift_ms\\',\\n \\'Timing-only correction of the same recorded 3D bat movement against the recorded ball path; supplied geometry/error bounds.\\' if value is not None else reason,\\n \\'estimated\\' if value is not None else \\'unclear\\')\\n if value is not None:\\n by_key[\\'early_late_shift_ms\\'][\\'value\\'] = value\\n intervals[\\'early_late_shift_ms\\'] = deepcopy(shift)\\n payload[\"reps\"].append({\"rep\": rep[\"rep\"], \"outcome\": outcome, \"stepped\": stepped,\\n \"metrics\": [by_key[key] for key in LOAD_TIMING_KEYS]})\\n moments = {}\\n for name in (\"load_start\", \"foot_contact\", \"swing_start\"):\\n if name in events:\\n moments[name] = deepcopy(events[name])\\n proxy = rep[\"events\"].get(\"contact\")\\n if proxy:\\n moments[\"body_extension_proxy\"] = deepcopy(proxy)\\n if actual_end:\\n moments[\"reviewed_\"+end_name] = deepcopy(events[end_name])\\n for event in moments.values():\\n i = event[\"frame\"]\\n event[\"capture_time_s\"] = track[\"frames\"][\"t_s\"][i]\\n event[\"playback_time_s\"] = track[\"frames\"][\"playback_t_s\"][i]\\n diagnostics.append({\"rep\": rep[\"rep\"], \"start_frame\": rep[\"start_frame\"],\\n \"end_frame\": rep[\"end_frame\"], \"boundary_method\": rep[\"boundary_method\"],\\n \"forward_swing_established\": forward, \"events\": moments,\\n \"missing_events\": deepcopy(rep.get(\"missing_events\", {})), \"timing_checks\": intervals,\\n \"review_source\": label.get(\"source\"), \"reviewed_fields\": sorted(label)})\\n diagnostics[-1][\\'bat_ball_evidence\\'] = deepcopy(evidence)\\n return {\"version\": LOAD_TIMING_VERSION, \"validation\": \"reference_validation_pending\",\\n \"contract_status\": \"proposed_v3_not_current_coach_api_contract\", \"payload\": payload,\\n \"capabilities\": {\"automatic_body_events\": True,\\n \"automatic_ball_contact\": any(e.get(\\'reason_code\\') != \\'tracking_models_unavailable\\' for e in (ball_evidence or {}).values()),\\n \"automatic_bat_ball_tracking\": any(e.get(\\'reason_code\\') != \\'tracking_models_unavailable\\' for e in (ball_evidence or {}).values()),\\n \"early_late_estimate\": any(\\'shift\\' in e for e in (ball_evidence or {}).values())},\\n \"diagnostics\": diagnostics,\\n \"notes\": [\"All numbers are estimates; a successful run does not establish accuracy.\",\\n \"Sensitivity ranges are frame-shift checks, not validated error bounds.\",\\n \"No ready, pause, rushed, fault, priority or drill decisions are produced.\"]}\\n'\n", "PREVIEW_HELPER_SOURCE = '\"\"\"Timing-only previews and neighboring event frames, using the original PTS.\"\"\"\\nimport argparse\\nfrom copy import deepcopy\\nfrom pathlib import Path\\n\\nfrom baseball_batting.ingest import iter_frames\\nfrom baseball_batting.storage import atomic_json, read_json, sha256_file\\nfrom tools.preview_swing_ranges import export_previews\\n\\n\\ndef export_timing_review(video, result, report, destination, max_clips=10):\\n import cv2\\n import numpy as np\\n destination = Path(destination)\\n destination.mkdir(parents=True, exist_ok=True)\\n filtered = deepcopy(result)\\n track = filtered[\"pose_track\"]\\n diagnostics = {row[\"rep\"]: row for row in report[\"diagnostics\"]}\\n for rep in track[\"reps\"]:\\n row = diagnostics[rep[\"rep\"]]\\n rep[\"events\"] = deepcopy(row[\"events\"])\\n # 3D is neither needed nor rendered by this timing test.\\n filtered.pop(\"experimental_body3d\", None)\\n manifest = export_previews(video, filtered, destination, max_clips=max_clips)\\n selections, needed = [], set()\\n for rep in track[\"reps\"][:max_clips]:\\n for name, event in rep[\"events\"].items():\\n center = event[\"frame\"]\\n frames = list(range(max(rep[\"start_frame\"], center-2), min(rep[\"end_frame\"], center+2)+1))\\n selections.append((rep, name, center, frames))\\n needed.update(frames)\\n snapshots = {}\\n if needed:\\n info = track[\"video\"]\\n decoded = iter_frames(video, info[\"rotation_degrees_applied\"], max_pixels=8294400)\\n try:\\n for index, pts, base, image in decoded:\\n if index > max(needed):\\n break\\n if index not in needed:\\n continue\\n expected = track[\"frames\"][\"playback_t_s\"][index]\\n if (pts is None or expected is None or (image.shape[1], image.shape[0]) != (info[\"width\"], info[\"height\"])\\n or abs(float(pts*base)-expected) > float(base)+1e-6):\\n raise ValueError(\"Event frames do not match the original video timestamps and size.\")\\n scale = min(1., 256/image.shape[1], 320/image.shape[0])\\n snapshots[index] = cv2.resize(image, (max(1, round(image.shape[1]*scale)),\\n max(1, round(image.shape[0]*scale))))\\n finally:\\n decoded.close()\\n if needed-set(snapshots):\\n raise ValueError(\"Source video is missing expected event frames.\")\\n records = []\\n for rep, name, center, frames in selections:\\n tiles = []\\n for index in frames:\\n image = snapshots[index]\\n canvas = np.full((380, 280, 3), 20, np.uint8)\\n x, y = (280-image.shape[1])//2, 42\\n canvas[y:y+image.shape[0], x:x+image.shape[1]] = image\\n color = (0, 230, 255) if index == center else (255, 255, 255)\\n cv2.putText(canvas, f\"frame {index}\" + (\" (event)\" if index == center else \"\"),\\n (8, 24), cv2.FONT_HERSHEY_SIMPLEX, .5, color, 1, cv2.LINE_AA)\\n real = track[\"frames\"][\"t_s\"][index]\\n stamp = f\"capture {real:.4f}s\" if real is not None else \"capture time unknown\"\\n cv2.putText(canvas, stamp, (8, 366), cv2.FONT_HERSHEY_SIMPLEX, .43, color, 1, cv2.LINE_AA)\\n tiles.append(canvas)\\n image = np.concatenate(tiles, axis=1)\\n filename = f\"swing-{rep[\\'rep\\']:03d}-{name}-frames.png\"\\n if not cv2.imwrite(str(destination/filename), image):\\n raise OSError(\"Could not write event frame review.\")\\n records.append({\"rep\": rep[\"rep\"], \"event\": name, \"frame\": center, \"neighbor_frames\": frames,\\n \"file\": filename, \"sha256\": sha256_file(destination/filename)})\\n manifest[\"event_snapshots\"] = records\\n manifest[\"purpose\"] = \"Load/timing event inspection; body_extension_proxy is not ball contact.\"\\n atomic_json(destination/\"previews.json\", manifest)\\n return manifest\\n\\n\\ndef main():\\n parser = argparse.ArgumentParser(description=__doc__)\\n parser.add_argument(\"--video\", required=True)\\n parser.add_argument(\"--result\", required=True)\\n parser.add_argument(\"--report\", required=True)\\n parser.add_argument(\"--output\", required=True)\\n parser.add_argument(\"--max-clips\", type=int, default=10)\\n args = parser.parse_args()\\n manifest = export_timing_review(args.video, read_json(args.result), read_json(args.report),\\n args.output, args.max_clips)\\n print(f\"Saved {len(manifest[\\'previews\\'])} preview records and {len(manifest[\\'event_snapshots\\'])} event frame sequences.\")\\n\\n\\nif __name__ == \"__main__\":\\n main()\\n'\n", "TIMING_REPORT[\"helper_sha256\"] = {\n", " \"calculations\": hashlib.sha256(TIMING_HELPER_SOURCE.encode()).hexdigest(),\n", " \"previews\": hashlib.sha256(PREVIEW_HELPER_SOURCE.encode()).hexdigest(),\n", "}\n", "for filename, data in ((\"load-timing-results.json\", TIMING_REPORT),\n", " (\"load-timing-payload.json\", TIMING_REPORT[\"payload\"]),\n", " (\"reviewed-events.json\", REVIEWED_EVENTS)):\n", " (JOB_ROOT / filename).write_text(json.dumps(data, indent=2, allow_nan=False))\n", "(JOB_ROOT / \"timing_calculations.py\").write_text(TIMING_HELPER_SOURCE)\n", "(JOB_ROOT / \"timing_preview.py\").write_text(PREVIEW_HELPER_SOURCE)\n", "\n", "def timing_table(headers, rows):\n", " head = \"\".join(\"
Raw horizontal hand position relative to hips; x-axis is original frame number. This is a movement trace, not bat speed.
\"\n", " svg = f''\n", " content += svg\n", " sections.append(content)\n", "summary_html = \"Estimates; proposed payload version 3.0. No automatic bat/ball tracking.
\" + \"\".join(sections)\n", "(JOB_ROOT / \"timing-summary.html\").write_text(summary_html)\n", "display(HTML(summary_html))\n", "print(\"Payload:\", JOB_ROOT / \"load-timing-payload.json\")\n" ], "execution_count": null, "outputs": [], "id": "load-timing-012" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Watch the swings and inspect the event frames\n", "\n", "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.\n", "\n", "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.\n" ], "id": "load-timing-013" }, { "cell_type": "code", "metadata": {}, "source": [ "PREVIEW_LIMIT = 10\n", "PREVIEW_ROOT = JOB_ROOT / \"timing-previews\"\n", "preview_script = WORKSPACE_ROOT / \"timing-preview-helper.py\"\n", "preview_script.write_text(PREVIEW_HELPER_SOURCE)\n", "subprocess.run([WORKER_PYTHON, \"-c\", \"import runpy,sys; runpy.run_path(sys.argv.pop(1), run_name='__main__')\",\n", " str(preview_script), \"--video\", str(INPUT_VIDEO), \"--result\", str(JOB_ROOT / \"result.json\"),\n", " \"--report\", str(JOB_ROOT / \"load-timing-results.json\"), \"--output\", str(PREVIEW_ROOT),\n", " \"--max-clips\", str(PREVIEW_LIMIT)], cwd=ENGINE_ROOT, env=WORKER_ENV, check=True)\n", "timing_previews = json.loads((PREVIEW_ROOT / \"previews.json\").read_text())\n", "for preview in timing_previews[\"previews\"]:\n", " print(\"Swing\", preview[\"rep\"], \"| original frames\", preview[\"start_frame\"], \"to\", preview[\"end_frame\"])\n", " if preview[\"status\"] == \"complete\":\n", " display(Video(str(PREVIEW_ROOT / preview[\"file\"]), embed=True, width=720))\n", " else:\n", " print(\"Preview unavailable:\", preview[\"reason\"])\n", " for snapshot in timing_previews[\"event_snapshots\"]:\n", " if snapshot[\"rep\"] == preview[\"rep\"]:\n", " print(snapshot[\"event\"], \"| selected original frame\", snapshot[\"frame\"])\n", " display(Image(filename=str(PREVIEW_ROOT / snapshot[\"file\"])))\n" ], "execution_count": null, "outputs": [], "id": "load-timing-014" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Download the timing test\n", "\n", "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.\n", "\n", "After updating reviewed frames, rerun cells 6, 7 and 8 so the payload and previews describe the same results.\n" ], "id": "load-timing-015" }, { "cell_type": "code", "metadata": {}, "source": [ "import zipfile\n", "\n", "ARCHIVE_PATH = WORKSPACE_ROOT / (JOB_ROOT.name + \"-load-timing-results.zip\")\n", "names = (\"load-timing-results.json\", \"load-timing-payload.json\", \"reviewed-events.json\", \"timing-summary.html\",\n", " \"timing_calculations.py\", \"timing_preview.py\", \"result.json\", \"request.json\", \"source_checkout.json\",\n", " \"run-context.json\", \"progress.json\", \"worker.log\", \"error.json\")\n", "with zipfile.ZipFile(ARCHIVE_PATH, \"w\", zipfile.ZIP_DEFLATED) as archive:\n", " for name in names:\n", " path = JOB_ROOT / name\n", " if path.is_file():\n", " archive.write(path, name)\n", " manifest_path = JOB_ROOT / \"timing-previews/previews.json\"\n", " if manifest_path.is_file():\n", " archive.write(manifest_path, \"timing-previews/previews.json\")\n", " manifest = json.loads(manifest_path.read_text())\n", " for item in manifest[\"previews\"] + manifest.get(\"event_snapshots\", []):\n", " if \"file\" in item and item.get(\"status\", \"complete\") == \"complete\":\n", " path = JOB_ROOT / \"timing-previews\" / item[\"file\"]\n", " archive.write(path, path.relative_to(JOB_ROOT))\n", "print(\"Saved:\", ARCHIVE_PATH)\n", "files.download(str(ARCHIVE_PATH))\n" ], "execution_count": null, "outputs": [], "id": "load-timing-016" } ] }