diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..2637c39312318164559a57a2ba72a2275ef431a5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,35 +1,37 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +docs/FormScout-FMS-Spec.md.pdf filter=lfs diff=lfs merge=lfs -text +docs/plans/FormScout-Build-Prompt.md.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2e208e083bcdb79adf900e49cad7655a9917f8b3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ +dist/ +build/ +.eggs/ +*.egg +.env +.venv/ +venv/ +env/ +.DS_Store +checkpoints/ +*.pt +*.pth +*.gguf +*.bin +traces/ +*.mp4 +!tests/fixtures/*.mp4 diff --git a/.hfignore b/.hfignore new file mode 100644 index 0000000000000000000000000000000000000000..1f59b48dc5e3869b3792678542365a172e35d437 --- /dev/null +++ b/.hfignore @@ -0,0 +1,37 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +dist/ +build/ +.eggs/ +*.egg + +# Virtual environments +.venv/ +venv/ +env/ + +# Secrets / local config +.env +.env.* + +# Model weights (managed separately) +checkpoints/ +*.pt +*.pth +*.gguf +*.bin + +# Run artifacts +traces/ +*.mp4 + +# Dev tooling +.pytest_cache/ +.ruff_cache/ +.DS_Store +.claude/ + +# Git +.git/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..17b795a8527da614a6a3d98a52f3277cc45bc8fa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,199 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project overview + +FormScout is a Gradio app (Hugging Face Space) that scores Functional Movement Screen (FMS) videos 0–3 per test with a written rationale and an annotated overlay. It is a **screening aid** — not a diagnosis, not an injury predictor. Built for the Build Small Hackathon (Backyard AI track). Full product spec is in `docs/FormScout-FMS-Spec.md`; the engineering contract is in `docs/plans/FormScout-Build-Prompt.md`. + +**Current status:** Phase 2 complete. All 7 FMS test rubric scorers, JudgeAgent, MovementClassifierAgent, ReportAgent, PoseVisualizer (overlay video), and a user-selectable pose-model registry are implemented and tested (86/87 passing). Phase 3 is next (ST-GCN fine-tune + RAG retrieval). + +## Common commands + +```bash +# Run the Gradio app locally +python3 app.py + +# Headless pipeline test (no Gradio) +python3 -m formscout.run sample.mp4 + +# Run all tests +pytest tests/ + +# Run a single test file or test +pytest tests/test_phase2.py +pytest tests/test_biomechanics.py::TestBiomechanicsAgent::test_deep_squat_score + +# Lint / format +ruff check . && ruff format . + +# Start the local VLM judge server (llama.cpp, port 8080) +./scripts/serve_judge.sh + +# Push source tree to the HF model repo + Space (PRs; message from last commit) +./scripts/hf_upload.sh + +# Run Svelte component tests (when frontend work is added) +npx vitest run +``` + +## Architecture + +The pipeline is a sequence of **typed specialist agents**. Each agent accepts and returns a frozen dataclass from `formscout/types.py`. The Director in `formscout/pipeline.py` orchestrates them as a deterministic state machine (not an LLM). + +### Agent pipeline + +``` +IngestAgent → Pose2DAgent → [Body3DAgent — optional] +→ MovementClassifierAgent → BiomechanicsAgent +→ rubric/score_test() → JudgeAgent → ReportAgent +``` + +The **Director** (`pipeline.py`) owns the flow. `app.py` creates one `Director()` instance and calls `director.run(video_path, test_name, side, model_key)` per submission. The Gradio UI passes `test_name` directly (from dropdown), bypassing the classifier; `model_key` selects the pose backend from `config.POSE_MODELS`. + +`PoseVisualizer` (`formscout/agents/visualizer.py`) renders the annotated overlay video (skeleton, trails, velocity arrows) from `IngestResult` + `Pose2DResult`. It is called from `app.py` after the pipeline run — it is a UI-layer component, not a Director stage. It returns `None` on failure, never raises. + +### The tiering rule (most important invariant) + +**The 2D path is the default and must stand alone as a complete, functional pipeline.** `Body3DAgent` is only activated when `config.ENABLE_3D == True` AND the checkpoint loads successfully. If 3D is off or fails, `Body3DResult(used=False, ...)` is returned — this is a normal success path, not an error. `BiomechFeatures.view` is `"2d"` or `"3d"` so the `JudgeAgent` can caveat its rationale appropriately. Never put `Body3DAgent` on the critical path. + +### Feature flags in `config.py` and their current state + +| Flag | Default | Meaning | +|------|---------|---------| +| `ENABLE_JUDGE` | `True` | Judge/Classifier call Qwen3-VL via llama-server; graceful rubric fallback when the server is down | +| `ENABLE_3D` | `False` | When False, Body3DAgent returns `used=False` immediately | +| `ENABLE_STGCN` | `False` | Phase 3 — ST-GCN learned scoring head | +| `ENABLE_RAG` | `False` | Phase 3 — RetrievalAgent exemplar lookup | + +All model IDs, thresholds, k-values, and feature flags live in `config.py` — never scattered literals. + +### Judge backend selection (local vs Space) + +`config.resolve_judge_backend()` picks the VLM backend via `FORMSCOUT_JUDGE_BACKEND` (`llama_cpp` | `transformers` | `auto`). `auto` (default) uses **llama-server locally** and the **in-process transformers backend on a Space** (detected via `SPACE_ID`). `JudgeAgent` gets its client from `serving.get_vlm_client()`. + +- **`llama_cpp`** — `LlamaCppClient` → llama-server at `127.0.0.1:8080` (start with `scripts/serve_judge.sh`). The local path; works perfectly. +- **`transformers`** — `TransformersVLMClient` loads Qwen3-VL-8B via transformers, GPU-wrapped with `spaces.GPU` (ZeroGPU). Lazy model load, cached per process. On any load/inference failure it returns `{"fallback": True}` and the Judge falls back to the rubric. **Needs validation on real ZeroGPU hardware** — not exercised in CPU tests. + +### Fallback chain (important for local dev and Spaces) + +1. `ENABLE_JUDGE=False` → JudgeAgent returns rubric score wrapped as JudgeResult (no VLM needed) +2. `ENABLE_JUDGE=True` + selected backend unavailable / transformers load fails → same rubric fallback, logs a warning +3. `ENABLE_JUDGE=True` + backend available → calls Qwen3-VL-8B-Instruct (llama-server locally, transformers/ZeroGPU on a Space) + +Start the VLM server with `scripts/serve_judge.sh` (downloads live in `checkpoints/qwen3-vl/`, gitignored). To use a fine-tuned GGUF, set `FORMSCOUT_JUDGE_GGUF` (and `FORMSCOUT_JUDGE_MMPROJ` if it ships its own projector) — no code change needed. Multimodal requests go through the OpenAI-compatible `/v1/chat/completions` endpoint (the legacy `/completion` + `image_data` path does not work with modern llama-server). + +This means the app is **fully functional without any GPU or llama.cpp** — rubric scoring is pure Python. + +### Rubric scorers + +Each FMS test has a pure-function scorer in `formscout/rubric/`: + +``` +score_deep_squat / score_hurdle_step / score_inline_lunge / +score_shoulder_mobility / score_active_slr / +score_trunk_stability_pushup / score_rotary_stability +``` + +All accept `BiomechFeatures` and return `ScoreResult`. Dispatch via `rubric.score_test(features)`. **Rubric functions must remain pure** — no model calls, no I/O. + +### Bilateral tests + +`hurdle_step`, `inline_lunge`, `shoulder_mobility`, `active_slr` are bilateral. `ReportAgent` groups them by test name, takes the **lower** score, and always emits the asymmetry delta even when scores are equal. `composite` is `None` when any test is unscored. + +### Types contract + +Every agent I/O is a frozen dataclass from `formscout/types.py`. Key types: + +- `IngestResult` — decoded frames (np.ndarray list), fps, duration, dimensions +- `Pose2DResult` — per-frame keypoints as `dict[int, {x, y, conf}]` (COCO 17 joints) +- `Body3DResult` — optional 3D joints, always has `used: bool` +- `MovementResult` — `test_name` (validated enum), `side` ("left"|"right"|"na") +- `BiomechFeatures` — `angles: dict`, `alignments: dict`, `view: "2d"|"3d"`, `symmetry_delta` +- `ScoreResult` — `score: int` (0–3), `rationale`, `needs_human` +- `JudgeResult` — same as ScoreResult + `compensation_tags`, `corrective_hint`; `score=None` when `needs_human=True` +- `PipelineState` — mutable accumulator threaded through the Director + +`MovementResult` and `JudgeResult` validate their fields in `__post_init__` — passing invalid values raises immediately. + +### Pose model selection and checkpoints + +`config.POSE_MODELS` is a registry of pose backends: MediaPipe (CPU-friendly), five YOLO26 sizes (n/s/m/l/x), and Sapiens2 variants (Phase 3, need the custom `sapiens` repo installed). `config.DEFAULT_POSE_MODEL` is YOLO26n. The Gradio UI exposes a dropdown built from `config.available_pose_models()` (filters to checkpoints actually present) and passes the chosen `model_key` through `Director.run` to `Pose2DAgent`. `config.YOLO_POSE_MODEL` is a backward-compat alias only. + +Checkpoints are **not** committed (`checkpoints/` is gitignored). `formscout/startup.py:ensure_checkpoints()` downloads missing YOLO26/MediaPipe files from the `silas-therapy/formscout-checkpoints` HF repo once at app startup. Models load once per process and are cached — never inside the inference hot path. + +### llama.cpp serving + +`formscout/serving/llama_cpp.py` provides `LlamaCppClient` (VLM, port 8080) and `EmbeddingClient` (embeddings, port 8081). Both check `/health` before use and return safe error dicts when unavailable. Only active when the corresponding `ENABLE_*` flag is True. + +### Deploying to Hugging Face + +The repo deploys to both `silas-therapy/small-functional-movement-screening` (model repo) and the Space of the same name (README frontmatter is the Space config). Use `./scripts/hf_upload.sh` — never raw `hf upload .`: the `hf` CLI does **not** read `.hfignore`, so a raw upload hashes the entire `.venv` (~44k files) and pushes torch binaries. The script parses `.hfignore` into `--exclude` globs, preflights the file count, creates PRs on both repos, and auto-switches to `hf upload-large-folder` (resumable, but no PR / no commit message) above 500 files. + +## Key constraints and invariants + +- **No cloud model APIs.** All inference runs on-Space (ZeroGPU). No OpenAI/Anthropic/Gemini calls. +- **Pain is never auto-scored.** Any clearing test or visible distress sets `needs_human=True` — enforced in rubric functions and JudgeAgent. `JudgeResult.score` must be `None` when `needs_human=True`. +- **Quality gates (Director, never silently skip):** + - Any agent `confidence < config.MIN_CONFIDENCE` (0.6) → warn or stop + - `|rubric.score - judge.score| >= 1` → flag disagreement + - `MovementResult.test_name == "unknown"` → stop pipeline, surface manual override + - `JudgeAgent.needs_human == True` → no numeric score emitted +- **Composite is null** when any test is unscored. Never show a partial 0–21 as complete. +- **Pipeline runs headless.** No Gradio imports in any agent file. +- **Safety banner** ("Screening aid — not a diagnosis…") must always be visible in the UI — appears at top and bottom of `app.py`. + +## Engineering standards + +- Every agent: one public entrypoint, typed dataclass I/O from `types.py`, `confidence: float` and `notes: str` on every result. +- Models load once at module/instance init — never inside the inference hot path. +- Every agent module docstring states: purpose, inputs, outputs, failure behavior, model param count, license, and gated status. +- `tracing.py` records structured per-agent I/O for any run; one full run gets exported to the Hub. +- Every agent ships with a pytest in `tests/` that runs without model downloads and asserts the typed contract. + +## Model stack (~17.6B total — stay under 32B) + +| Component | Model | Params | Status | +|---|---|---|---| +| 2D pose (primary) | YOLO26-Pose n/s/m/l/x (default: n) | 0.0007–0.058B | Ready (auto-downloaded at startup) | +| 2D pose (CPU alt) | MediaPipe Pose Landmarker (full) | ~0.004B | Ready (auto-downloaded at startup) | +| 2D pose (HQ alt) | `facebook/sapiens2-pose-0.4b/0.8b/1b/5b` | 0.4–5B | Phase 3 — needs custom `sapiens` repo | +| Segmentation | SAM 3.1 base | ~0.85B | Access accepted | +| 3D biomechanics | `facebook/sam-3d-body-dinov3` | ~0.84B | **Access ACCEPTED Jun 4 2026** | +| Learned scoring | ST-GCN (pyskl) | ~0.03B | Phase 3 | +| Judge + Classifier | Qwen3-VL-8B-Instruct (llama.cpp) | 8B | **Online** — `scripts/serve_judge.sh`, ENABLE_JUDGE=True | +| Retrieval | Qwen3-VL-Embedding-8B (llama.cpp) | 8B | Phase 3 | + +Track the running sum in `MODEL_BUDGET.md`. The two Qwen3-VL-8B models share a backbone. + +## Gradio + Svelte UI guidance + +The UI uses **Gradio `gr.Blocks`** with custom CSS/theme (`formscout/ui/theme.py`). Custom Svelte components for score dial, asymmetry bars, rubric drawer are planned for Phase 4. Use `gradio-svelte-expert` agent for Svelte component work. + +- ZeroGPU: wrap heavy inference (`Pose2DAgent.run`, `Body3DAgent.run`) in `@spaces.GPU` before deploying to Spaces. +- Verify Gradio APIs against current docs before use — pin exact versions in `requirements.txt`. + +## Build phases + +1. **Phase 0 — Recon:** ✅ Complete. See `RECON.md`. +2. **Phase 1 — Spine:** ✅ Complete. Deep Squat end-to-end. +3. **Phase 2 — All 7 tests:** ✅ Complete. Classifier, Judge, Report agents; all rubric scorers; Gradio UI. +4. **Phase 3 — Learned scoring + retrieval:** ST-GCN fine-tune on physio clips, publish to Hub. RetrievalAgent with embedding index. +5. **Phase 4 — Polish + ship:** Custom Svelte UI components, agent trace to Hub, blog post. (Overlay video done via `PoseVisualizer`; full 7-test session + PDF export done via `formscout/session.py` + `PdfReportAgent`.) + +## Known issues + +- `tests/test_biomechanics.py::TestBiomechanicsAgent::test_unimplemented_test_returns_low_confidence` fails: expects `"not yet implemented"` in `result.notes` but biomechanics returns empty string. Minor — low priority. + +## Badge checklist (definition of done) + +- [ ] Space runs green; upload → scorecard works on real clips +- [ ] Param sum verified ≤ 32B in `MODEL_BUDGET.md` +- [ ] 🔌 **Off the Grid** — no cloud model APIs anywhere in the pipeline +- [ ] 🎯 **Well-Tuned** — fine-tuned ST-GCN head published to Hub with honest model card +- [ ] 🎨 **Off-Brand** — custom, non-default Gradio UI (scout/trail theme) +- [ ] 🦙 **Llama Champion** — VLM + embedder served via llama.cpp (GGUF) +- [ ] 📡 **Sharing is Caring** — one full agent trace (all I/O) published to Hub +- [ ] 📓 **Field Notes** — blog post written, honesty section (FMS limitations) front-and-center +- [ ] Demo video + social post recorded +- [ ] Safety banner present; pain/clearing never auto-scored; low-confidence flagged diff --git a/MODEL_BUDGET.md b/MODEL_BUDGET.md new file mode 100644 index 0000000000000000000000000000000000000000..0ab961381fb9e337c2a88e488a299f1e5e54a383 --- /dev/null +++ b/MODEL_BUDGET.md @@ -0,0 +1,24 @@ +# MODEL_BUDGET.md + +Running sum must stay ≤ 32B params. + +| Component | Model | Params | +|---|---|---| +| 2D Pose (primary) | YOLO26l-Pose | 0.026B | +| 2D Pose (HQ alt) | YOLO26x-Pose | 0.058B | +| 2D Pose (fallback) | Sapiens2 Pose | 0.6B | +| Segmentation | SAM 3.1 base | 0.85B | +| 3D Body (optional) | SAM 3D Body DINOv3-H+ | 0.84B | +| Scoring Head | ST-GCN (pyskl) | 0.03B | +| Judge/Classifier | Qwen3-VL-8B-Instruct (Q4_K_M GGUF + F16 mmproj, llama.cpp) | 8B | +| Retrieval | Qwen3-VL-Embedding-8B | 8B | +| **Total** | | **~18.37B** | + +Headroom: ~13.63B under 32B cap. + +Note: The two Qwen3-VL-8B models share a backbone (counted separately here for safety). +Only one pose backend runs at a time (YOLO or Sapiens2, not both). + +Judge/Classifier serving: `scripts/serve_judge.sh` (llama-server, port 8080). +Default GGUF: `Qwen/Qwen3-VL-8B-Instruct-GGUF` → `checkpoints/qwen3-vl/` (gitignored). +Fine-tuned swap: set `FORMSCOUT_JUDGE_GGUF` (+ `FORMSCOUT_JUDGE_MMPROJ`) — no code change. diff --git a/README.md b/README.md index 4c171aab2d87fcdccbb89ef0fddc40846edf8bbf..3ae6006de598862e3230551acac66f34b02e7fa2 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,118 @@ --- -title: Small Functional Movement Screening -emoji: 🦀 -colorFrom: blue -colorTo: blue +title: FormScout +emoji: 🏔️ +colorFrom: green +colorTo: yellow sdk: gradio -sdk_version: 6.18.0 -python_version: '3.13' app_file: app.py pinned: false +license: apache-2.0 +short_description: FMS video scoring — movement screen aid --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# FormScout + +FMS (Functional Movement Screen) scoring pipeline — a screening aid that scores movement videos 0–3 per test with a written rationale and annotated overlay. + +**⚠️ Screening aid — not a diagnosis. Pain or clearing tests require a clinician.** + +## Running locally + +### 1. Clone and install + +```bash +git clone https://huggingface.co/silas-therapy/small-functional-movement-screening +cd small-functional-movement-screening +python3 -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt +``` + +### 2. Start the VLM judge (optional but recommended) + +The judge uses Qwen3-VL-8B-Instruct via llama.cpp. Without it the app falls back to the deterministic rubric score — fully functional, no GPU needed. + +```bash +# Install llama.cpp once +brew install llama.cpp + +# Download the model (one-time, ~6 GB) +python3 -c " +from huggingface_hub import hf_hub_download +for f in ['Qwen3VL-8B-Instruct-Q4_K_M.gguf', 'mmproj-Qwen3VL-8B-Instruct-F16.gguf']: + hf_hub_download('Qwen/Qwen3-VL-8B-Instruct-GGUF', f, local_dir='checkpoints/qwen3-vl') +" + +# Start the server (keep this terminal open) +./scripts/serve_judge.sh +``` + +To use a fine-tuned GGUF instead of the default: +```bash +FORMSCOUT_JUDGE_GGUF=/path/to/finetuned.gguf ./scripts/serve_judge.sh +``` + +### 3. Launch the Gradio app + +```bash +python3 app.py +# → http://127.0.0.1:7860 +``` + +Upload a video, select the FMS test from the dropdown, and click **Analyze**. + +### 4. Headless pipeline (no Gradio) + +```bash +python3 -m formscout.run sample.mp4 +``` + +### 5. Tests + +```bash +pytest tests/ -v +``` + +### 6. Upload to Hugging Face + +```bash +# Pushes source to both model repo and Space, opens a PR on each +./scripts/hf_upload.sh + +# Or with a custom commit message +./scripts/hf_upload.sh "feat: my change" +``` + +## Architecture + +Typed specialist agents orchestrated by a deterministic Director: + +``` +Ingest → Pose2D → [Body3D optional] → Biomechanics → Rubric Score → [Judge] → Report +``` + +| Agent | Model | Status | +|---|---|---| +| Pose2D | YOLO26l-Pose (0.026B) + MediaPipe fallback | ✅ | +| Body3D | SAM 3D Body DINOv3 (0.84B) | gated, off by default | +| Judge + Classifier | Qwen3-VL-8B-Instruct via llama.cpp (8B) | ✅ | +| Scoring Head | ST-GCN (0.03B) | Phase 3 | +| Retrieval | Qwen3-VL-Embedding-8B (8B) | Phase 3 | + +See [CLAUDE.md](CLAUDE.md) for full architecture and invariants. + +## Feature flags (`formscout/config.py`) + +| Flag | Default | Meaning | +|---|---|---| +| `ENABLE_JUDGE` | `True` | VLM judge via llama-server; rubric fallback when server is down | +| `ENABLE_3D` | `False` | SAM 3D Body — off until integrated | +| `ENABLE_STGCN` | `False` | Phase 3 | +| `ENABLE_RAG` | `False` | Phase 3 | + +## Model budget + +~18B params total (under 32B cap). See [MODEL_BUDGET.md](MODEL_BUDGET.md). + +## License + +Apache-2.0. Built for the Build Small Hackathon (Backyard AI track). diff --git a/RECON.md b/RECON.md new file mode 100644 index 0000000000000000000000000000000000000000..fe63cd4e19dc3401221bd219b9fad03e837be358 --- /dev/null +++ b/RECON.md @@ -0,0 +1,57 @@ +# RECON.md + +Phase 0 reconnaissance findings — model verification, Gradio APIs, access status. +Updated: June 4, 2026. + +## Gradio +- Version: TBD (will verify on first `pip install gradio`) +- gr.Blocks: expected ✓ (used in app.py skeleton) +- gr.Video: expected ✓ +- gr.Walkthrough / gr.Step: TBD (verify in Phase 2) +- gr.Navbar: TBD (verify in Phase 2) +- UI approach: gr.Blocks + custom CSS/theme (escalate to Server only if needed) + +## Python +- Python 3.13.9 (local dev) +- pytest 9.0.2, numpy, opencv-python installed + +## Model Verification + +| Model | Params | License | GGUF | ZeroGPU | Status | +|---|---|---|---|---|---| +| YOLO26l-Pose (primary) | 0.026B | AGPL-3.0 | n/a | ✓ (6.5ms T4) | ready | +| YOLO26x-Pose (HQ alt) | 0.058B | AGPL-3.0 | n/a | ✓ (12.2ms T4) | ready | +| SAM 3.1 base (sam2.1_hiera_base_plus) | ~0.85B | SAM License | n/a | ✓ | access accepted | +| SAM 3D Body (facebook/sam-3d-body-dinov3) | 0.84B (DINOv3-H+) | SAM License | n/a | ✓ | **INTEGRATED** | +| Sapiens2 Pose (noahcao/sapiens-pose-coco) | ~0.6B | CC-BY-NC-4.0 | n/a | ✓ | access accepted | +| ST-GCN (pyskl) | ~0.03B | Apache-2.0 | n/a | ✓ | ready | +| Qwen3-VL-8B-Instruct | 8B | Apache-2.0 | ✓ | llama.cpp | ready | +| Qwen3-VL-Embedding-8B | 8B | Apache-2.0 | ✓ | llama.cpp | ready | + +## Param Sum +~17.63B — well under 32B limit. + +## Gated Access Status (as of Jun 4, 2026) +- [x] SAM 3.1 (facebookresearch/sam3) — accepted +- [x] SAM 3D Body (facebook/sam-3d-body-dinov3) — **ACCEPTED** (confirmed Jun 4) +- [x] Sapiens2 Pose (noahcao/sapiens-pose-coco) — accepted + +## Open Questions +- [ ] Confirm "≤32B" = summed vs per-model in Discord AMA +- [ ] AGPL-3.0 YOLO OK for hackathon submission? (Likely yes for non-commercial demo) + +## llama.cpp Build Plan +- CPU-only build first (avoids libcudart.so issues on Spaces) +- Fallback: transformers + spaces.GPU for VLM inference +- GGUF quantized Qwen3-VL-8B at Q4_K_M (~4.5GB) + +## Key Decisions +- Primary pose: YOLO11x-Pose (fastest, well-tested) +- Fallback pose: Sapiens2 (more keypoints, slower) +- 3D body: INTEGRATED — uses `setup_sam_3d_body()` from `notebook.utils`, outputs MHR joints + - API: `estimator.process_one_image(rgb_image)` — single RGB np.ndarray + - Model variants: DINOv3-H+ (840M) default, ViT-H (631M) smaller + - Temporal smoothing via EMA (alpha=0.3) to reduce single-frame jitter + - config.enable_3d=False by default; flipped when checkpoint verified on Space +- VLM: Qwen3-VL-8B via llama.cpp (Judge + Classifier) +- Embeddings: Qwen3-VL-Embedding-8B via llama.cpp (Retrieval) diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..5e58d74a52756d292ad480033ceb76f8e979c210 --- /dev/null +++ b/app.py @@ -0,0 +1,461 @@ +""" +FormScout — Gradio app entrypoint. +Screening aid for Functional Movement Screen (FMS) scoring. +NOT a diagnosis. NOT an injury predictor. + +Custom scout/trail themed UI with score dial, pipeline visualization, +rubric breakdown, and persistent safety banner. +""" +from __future__ import annotations + +import os +import tempfile + +import gradio as gr + +from formscout.pipeline import Director +from formscout.rubric import score_test +from formscout.ui.theme import formscout_theme, FORMSCOUT_CSS +from formscout import config +from formscout import session as session_mod +from formscout.startup import ensure_checkpoints + +ensure_checkpoints() + + +# ─── Constants ─────────────────────────────────────────────────────────────── + +DISCLAIMER = ( + "⚠️ **Screening aid — not a diagnosis. " + "Pain or clearing tests require a clinician.**" +) + +FMS_TESTS = [ + ("Deep Squat", "deep_squat"), + ("Hurdle Step", "hurdle_step"), + ("In-Line Lunge", "inline_lunge"), + ("Shoulder Mobility", "shoulder_mobility"), + ("Active Straight-Leg Raise", "active_slr"), + ("Trunk Stability Push-Up", "trunk_stability_pushup"), + ("Rotary Stability", "rotary_stability"), +] + +SCORE_DESCRIPTIONS = { + 3: "Movement performed to criterion — no compensation", + 2: "Movement completed with compensation or regression", + 1: "Unable to perform the movement pattern", + 0: "Pain reported — clinician referral required", +} + + +# ─── Processing ────────────────────────────────────────────────────────────── + +def process_video(video_path: str, test_name: str, side: str, model_key: str, + layers: list[str], session_state): + """Analyse one clip and accumulate it into the screening session.""" + if not video_path: + return ( + session_state, _render_empty_state(), "Upload a video to begin analysis.", + "", "", None, "", _render_session_table(session_state), + gr.update(visible=False), gr.update(visible=False), + ) + + if session_state is None: + session_state = session_mod.new_session() + + director = Director() + state = director.run(video_path, test_name=test_name, side=side, model_key=model_key) + + score_html = _render_empty_state() + score_details = "" + + if state.features: + result = score_test(state.features) + judge = state.judge + if judge and judge.score is not None: + score_html = _render_score_card(judge.score, judge.confidence, judge.needs_human) + score_details = _render_score_details_judge(judge, result, state.features) + elif judge and judge.needs_human: + score_html = _render_score_card(0, 0, True) + score_details = f"### Needs Clinician Review\n{judge.rationale}" + else: + score_html = _render_score_card(result.score, result.confidence, result.needs_human) + score_details = _render_score_details(result, state.features) + + # Accumulate into the session (only when we have a real analysis) + if state.ingest and state.pose2d and state.judge: + draw_trails = "trails" in {lbl.lower().replace(" ", "_") for lbl in (layers or [])} + try: + session_mod.add_analysis( + session_state, ingest=state.ingest, pose2d=state.pose2d, + features=state.features, judge=state.judge, + test_name=test_name, side=side, draw_trails=draw_trails, + ) + except Exception as e: + state.warnings.append(f"session accumulation failed: {e}") + + pipeline_md = _render_pipeline_status(state) + alerts = _render_alerts(state) + + overlay_path = None + vel_summary = "" + layer_set = {lbl.lower().replace(" ", "_") for lbl in (layers or [])} + if layer_set and state.ingest and state.pose2d: + try: + from formscout.agents.visualizer import PoseVisualizer, build_velocity_summary + vis = PoseVisualizer() + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + out_path = f.name + overlay_path = vis.render_video(state.ingest, state.pose2d, layer_set, out_path) + if overlay_path: + vel_summary = build_velocity_summary(state.pose2d.keypoints, vis.last_velocities) + except Exception as e: + alerts = (alerts or "") + f"\n⚠️ Visualizer error: {e}" + + has_entries = bool(session_state and session_state.entries) + return ( + session_state, score_html, pipeline_md, score_details, alerts, + overlay_path, vel_summary, _render_session_table(session_state), + gr.update(visible=has_entries), gr.update(visible=has_entries), + ) + + +def _render_score_card(score: int, confidence: float, needs_human: bool) -> str: + """Render the score dial as HTML.""" + if needs_human: + return """ +
+
⚠️ Needs Clinician Review
+
Pain or clearing test detected — cannot auto-score
+
+ """ + + conf_pct = int(confidence * 100) + conf_color = "#2b8a8a" if confidence >= 0.7 else "#cf922a" if confidence >= 0.4 else "#d9534f" + + return f""" +
+
{score}/3
+
+ {SCORE_DESCRIPTIONS.get(score, '')} +
+
+
+ Confidence + {conf_pct}% +
+
+
+
+
+
+ """ + + +def _render_empty_state() -> str: + """Render placeholder when no video processed yet.""" + return """ +
+
🏔️
+
Upload a video to begin
+
+ """ + + +def _render_score_details(result, features) -> str: + """Render the rubric breakdown.""" + parts = [f"### Rationale\n{result.rationale}\n"] + + if features.angles: + parts.append("### Measurements") + for key, val in features.angles.items(): + label = key.replace("_", " ").title() + parts.append(f"- **{label}:** {val:.1f}°") + + if features.alignments: + parts.append("\n### Alignment Checks") + for key, val in features.alignments.items(): + label = key.replace("_", " ").title() + icon = "✓" if val else "✗" + parts.append(f"- {icon} {label}") + + if features.view == "2d": + parts.append( + "\n> ⚠️ *2D estimate — angles are camera-angle dependent. " + "For best accuracy, film from the side at hip height.*" + ) + + return "\n".join(parts) + + +def _render_score_details_judge(judge, rubric, features) -> str: + """Render judge + rubric combined breakdown.""" + parts = [f"### Judge Rationale\n{judge.rationale}\n"] + + if judge.compensation_tags: + parts.append(f"**Compensations:** {', '.join(judge.compensation_tags)}") + if judge.corrective_hint: + parts.append(f"**Corrective:** {judge.corrective_hint}") + + parts.append(f"\n### Rubric Score: {rubric.score}/3") + parts.append(f"*{rubric.rationale}*") + + if features.angles: + parts.append("\n### Measurements") + for key, val in features.angles.items(): + label = key.replace("_", " ").title() + parts.append(f"- **{label}:** {val:.1f}°" if isinstance(val, float) else f"- **{label}:** {val}") + + if features.symmetry_delta is not None: + parts.append(f"\n### Asymmetry\n- **L/R Delta:** {features.symmetry_delta:.1f}°") + + if features.view == "2d": + parts.append( + "\n> ⚠️ *2D estimate — angles are camera-angle dependent.*" + ) + + return "\n".join(parts) + + +def _render_pipeline_status(state) -> str: + """Render pipeline step summary.""" + parts = [] + if state.ingest: + parts.append( + f"📹 **Ingest:** {len(state.ingest.frames)} frames · " + f"{state.ingest.fps:.0f}fps · {state.ingest.duration:.1f}s · " + f"{state.ingest.width}×{state.ingest.height}" + ) + if state.pose2d: + n = sum(1 for kps in state.pose2d.keypoints if kps) + parts.append( + f"🦴 **Pose2D:** {n}/{len(state.pose2d.keypoints)} frames detected · " + f"conf={state.pose2d.confidence:.0%}" + ) + if state.body3d: + if state.body3d.used: + parts.append(f"🧊 **Body3D:** active · conf={state.body3d.confidence:.0%}") + else: + parts.append("🧊 **Body3D:** 2D-only path (normal)") + if state.features: + parts.append( + f"📐 **Biomechanics:** view={state.features.view} · " + f"conf={state.features.confidence:.0%}" + ) + return "\n\n".join(parts) if parts else "*Processing...*" + + +def _render_alerts(state) -> str: + """Render errors and warnings.""" + parts = [] + if state.errors: + for e in state.errors: + parts.append(f"🚨 {e}") + if state.warnings: + for w in state.warnings: + parts.append(f"⚠️ {w}") + return "\n\n".join(parts) + + +def _render_session_table(session_state) -> str: + """Render the accumulated 'Session so far' table as markdown.""" + if not session_state or not session_state.entries: + return "*No clips analysed yet.*" + lines = ["| Test | Side | Score | Status |", "|---|---|---|---|"] + for e in session_state.entries: + test = e.test_name.replace("_", " ").title() + side = e.side if e.side in ("left", "right") else "—" + if e.needs_human: + score, status = "—", "⚠️ Clinician review" + else: + score, status = f"{e.score}/3", "✓ scored" + lines.append(f"| {test} | {side} | {score} | {status} |") + return "\n".join(lines) + + +def _finish_session(session_state): + """Build the composite report + PDF for the whole session.""" + if not session_state or not session_state.entries: + return ("⚠️ No clips analysed yet — analyse at least one clip first.", + None, None) + + report, pdf_path = session_mod.finish_session(session_state) + if report is None: + return ("⚠️ Nothing to report.", None, None) + + if report.composite is not None: + summary = [f"## Composite: {report.composite} / 21"] + else: + n = len(session_state.entries) + summary = [f"## Composite: Incomplete — {n}/7 tests scored", + "*(One or more tests need clinician review or were unscored.)*"] + + if report.asymmetries: + summary.append("\n### Asymmetries") + for a in report.asymmetries: + test = a["test"].replace("_", " ").title() + summary.append(f"- **{test}:** L={a['left_score']} R={a['right_score']} (Δ {a['delta']})") + + flags = list(report.low_confidence_flags) + list(report.disagreement_flags) + if flags: + summary.append("\n### Flags") + for fl in flags: + summary.append(f"- {fl}") + + md_path = os.path.join(session_state.session_dir, "analysis.md") + md_out = md_path if os.path.exists(md_path) else None + return "\n".join(summary), pdf_path, md_out + + +# ─── App Builder ───────────────────────────────────────────────────────────── + +def build_app() -> gr.Blocks: + """Build the FormScout Gradio app with custom scout/trail theme.""" + with gr.Blocks(title="FormScout — FMS Screening Aid") as app: + + session_state = gr.State(None) + + # Header + gr.HTML(""" +
+

🏔️ FormScout

+

+ Functional Movement Screen · Automated Scoring Aid +

+
+ """) + + # Safety banner (always visible — non-negotiable) + gr.HTML(f'
{DISCLAIMER}
') + + with gr.Row(equal_height=False): + # Left column: Input + with gr.Column(scale=2): + gr.Markdown("### 📹 Input") + video_input = gr.Video(label="Upload FMS Video") + + with gr.Row(): + test_dropdown = gr.Dropdown( + choices=[name for name, _ in FMS_TESTS], + value="Deep Squat", + label="FMS Test", + scale=2, + ) + side_dropdown = gr.Dropdown( + choices=["N/A", "Left", "Right"], + value="N/A", + label="Side", + scale=1, + ) + + _available_models = config.available_pose_models() or config.POSE_MODELS + _default_model = ( + config.DEFAULT_POSE_MODEL + if config.DEFAULT_POSE_MODEL in _available_models + else list(_available_models.keys())[0] + ) + pose_model_dropdown = gr.Dropdown( + choices=list(_available_models.keys()), + value=_default_model, + label="Pose Model", + ) + + overlay_layers = gr.CheckboxGroup( + choices=["Skeleton", "Trails", "Velocity arrows"], + value=["Skeleton", "Trails", "Velocity arrows"], + label="Overlay Layers", + ) + + submit_btn = gr.Button( + "🎯 Score Movement", + variant="primary", + size="lg", + ) + with gr.Row(): + new_clip_btn = gr.Button("➕ Analyse new clip", visible=False) + finish_btn = gr.Button("✅ Finish & generate PDF", + variant="primary", visible=False) + + gr.Markdown( + "*Tip: Film from the side at hip height for best accuracy. " + "One athlete, one rep per clip.*", + elem_classes=["topo-accent"], + ) + + # Right column: Results + with gr.Column(scale=3): + gr.Markdown("### 📊 Results") + + # Score display + score_html = gr.HTML(value=_render_empty_state()) + + # Tabs for details + with gr.Tabs(): + with gr.TabItem("📐 Rubric Breakdown"): + score_details = gr.Markdown("") + + with gr.TabItem("🔧 Pipeline"): + pipeline_md = gr.Markdown("*Waiting for video...*") + + with gr.TabItem("⚠️ Alerts"): + alerts_md = gr.Markdown("") + + with gr.TabItem("🎬 Overlay Video"): + overlay_video = gr.Video(label="Annotated Movement") + velocity_md = gr.Markdown("") + + with gr.TabItem("🗂️ Session"): + session_table = gr.Markdown("*No clips analysed yet.*") + finish_summary = gr.Markdown("") + pdf_file = gr.File(label="Screening Report (PDF)", visible=True) + md_file = gr.File(label="Analysis Log (Markdown)", visible=True) + + # Footer safety banner + gr.HTML(f'
{DISCLAIMER}
') + + gr.Markdown( + "
" + "FormScout · ~18B params · Off the Grid · " + "Silas Therapy · Build Small Hackathon" + "
" + ) + + # ─── Event wiring ──────────────────────────────────────────────────── + + def _map_inputs(video, test_display_name, side_display, pose_model_key, overlay_layers, sess): + """Map UI display values to internal values and accumulate into the session.""" + test_map = {name: val for name, val in FMS_TESTS} + test_name = test_map.get(test_display_name, "deep_squat") + side = {"N/A": "na", "Left": "left", "Right": "right"}.get(side_display, "na") + return process_video(video, test_name, side, pose_model_key, overlay_layers, sess) + + submit_btn.click( + fn=_map_inputs, + inputs=[video_input, test_dropdown, side_dropdown, pose_model_dropdown, + overlay_layers, session_state], + outputs=[session_state, score_html, pipeline_md, score_details, alerts_md, + overlay_video, velocity_md, session_table, new_clip_btn, finish_btn], + ) + + def _new_clip(): + """Clear inputs for the next clip; keep the session intact.""" + return None, _render_empty_state(), "" + + new_clip_btn.click( + fn=_new_clip, + inputs=[], + outputs=[video_input, score_html, score_details], + ) + + finish_btn.click( + fn=_finish_session, + inputs=[session_state], + outputs=[finish_summary, pdf_file, md_file], + ) + + return app + + +if __name__ == "__main__": + app = build_app() + app.launch(theme=formscout_theme(), css=FORMSCOUT_CSS) diff --git a/docs/FormScout-FMS-Spec.md b/docs/FormScout-FMS-Spec.md new file mode 100644 index 0000000000000000000000000000000000000000..e815f4266ca5eddacf1deae0073215b142fb36ec --- /dev/null +++ b/docs/FormScout-FMS-Spec.md @@ -0,0 +1,277 @@ +# FormScout — Functional Movement Screening, scored small + +**Project specification & architecture documentation** +*Build Small Hackathon (Gradio × Hugging Face) — Track: Backyard AI* +*Working title; rename freely. Doc version 0.1, June 2026.* + +--- + +## 1. One-paragraph pitch + +A basketball team's physiotherapist screens players with the **Functional Movement Screen (FMS)** — seven movement patterns, each scored 0–3 by eye. The scoring is slow, subjective, and hard to reproduce across raters or across months. FormScout is a Gradio app that takes a video of an athlete performing an FMS test, extracts 2D and 3D body pose, measures the biomechanics the FMS rubric actually cares about, and produces a 0–3 score *with a written rationale and an annotated overlay* — anchored to the physio's own previously-scored clips. It is a **screening aid that standardizes and speeds up the physio's first pass**, not a diagnosis and not an injury predictor. Everything runs on models that fit on a laptop. + +--- + +## 2. The problem, honestly + +The FMS is a seven-test battery (Deep Squat, Hurdle Step, In-Line Lunge, Shoulder Mobility, Active Straight-Leg Raise, Trunk Stability Push-Up, Rotary Stability), each scored 0–3 for a composite 0–21. A score of 0 means **pain** during the movement and is an automatic red flag for clinical referral. Three of the tests have associated **clearing tests** (shoulder, spinal extension, spinal flexion) that also force a 0 on pain. + +Two facts shape this project and should be stated plainly in the demo and the writeup: + +- **Inter-rater reliability is decent but not perfect.** Composite-score reliability is moderate-to-good (ICC roughly 0.7–0.8), but novice and less-experienced raters grade component scores inconsistently. This is the real, addressable pain point: **variance between raters and over time.** +- **Predictive validity for injury is weak/mixed.** The popular "≤14 = higher injury risk" cutoff is not a reliable predictor on its own. So FormScout must **not** be sold as injury prediction. + +**Where FormScout genuinely helps:** +1. A repeatable, objective **digital baseline** to track an athlete over a season. +2. **Asymmetry detection** (left vs. right), which is one of the FMS's most defensible outputs. +3. A fast, consistent **first-pass / second opinion** that reduces rater variance. +4. **Explainability** — it shows *which compensation* it saw, not just a number. + +This honest framing is also strategic: the Backyard AI track is judged partly on "honest fit between problem and the small-model constraint." Overclaiming clinical power would hurt the submission, not help it. + +--- + +## 3. Why this fits the hackathon + +| Hackathon rule | How FormScout satisfies it | +|---|---| +| **Total params ≤ 32B** | Recommended config sums to ~18B. A portfolio of small specialists beats one monolith — which is on-theme for "think small." | +| **Built on Gradio, hosted as a HF Space** | Gradio app with `gr.Video` input, a custom-styled results panel, on-Space inference (ZeroGPU or llama.cpp). | +| **Show, Don't Tell** | Demo video = physio uploads a real player clip, gets a scored overlay in seconds. Social post = before/after of a manual vs. assisted screening session. | +| **Track: Backyard AI** | The "someone you know" is the team physiotherapist. The deliverable is something they *actually use* on real players. | + +**Badge targets (aim for all six):** + +- 🔌 **Off the Grid** — no cloud APIs; all models served on the Space. +- 🎯 **Well-Tuned** — the skeletal-temporal scoring head is fine-tuned on the physio's labels and published to the Hub. +- 🎨 **Off-Brand** — custom Gradio frontend (scorecard UI, video overlay, per-test rubric panel), pushing past default Gradio. +- 🦙 **Llama Champion** — VLM + embedding model served through llama.cpp (GGUF builds exist for both). +- 📡 **Sharing is Caring** — publish the agent trace (one full screening run, agent by agent) to the Hub. +- 📓 **Field Notes** — a blog post on building a clinical-adjacent AQA pipeline under a 32B budget, with the honesty section front and center. + +--- + +## 4. Core technical framing: FMS *is* Action Quality Assessment + +Don't reinvent this from scratch. **Action Quality Assessment (AQA)** is the established field for "score how well a movement was performed." Skeleton-based AQA (sports scoring, surgical-skill and rehab assessment) is the directly relevant lineage. The "Skeletal-Temporal Transformer" idea maps onto the **AQA scoring head**. + +The key design constraint is the **tiny labeled dataset** (a couple of physio-scored videos). That rules out training a large score regressor from scratch and dictates a hybrid approach: + +1. **Deterministic biomechanics** carry most of the load. The FMS rubric is, to a large degree, a set of *angle and alignment thresholds* (e.g. Deep Squat "3" = femur below horizontal, torso parallel to tibia, knees tracking over feet, dowel over feet). These are computable from 3D pose with **zero training** and are inherently interpretable — exactly what earns a physio's trust. +2. **A small learned head** (ST-GCN or a compact temporal transformer) refines the score and captures the patterns rules miss. It is small enough to fine-tune on a few labeled clips, *especially* if pre-trained on public AQA/pose datasets first. +3. **Retrieval over the physio's labeled clips** (RAG) gives the language model few-shot anchors at judgment time — the right move when you have examples but not enough to train on. +4. **A VLM as the judge/explainer** synthesizes rubric + measurements + retrieved exemplars into a final score and a human-readable rationale, and conservatively flags anything pain-related for a human. + +--- + +## 5. Parameter budget (the single most important table) + +Assume "total parameters" = **sum of all model weights in the pipeline**. Design to this; confirm the exact interpretation in the Discord AMA. + +### Recommended config — "Portfolio of specialists" (~18B) + +| Component | Model | Params | Role | +|---|---|---:|---| +| 2D pose + tracking | YOLO26-Pose (L/X) | ~0.05B | Per-frame 17-keypoint skeletons, multi-person tracking | +| Segmentation | SAM 3.1 (base) | ~0.85B | Clean athlete mask, occlusion handling, prompt for 3D | +| 3D body | SAM 3D Body | ~0.7–1B* | Single-image 3D mesh → true joint angles, view-invariant | +| Scoring head | ST-GCN / temporal transformer (fine-tuned) | ~0.01–0.05B | Pose-sequence → candidate 0–3 + confidence | +| Judge / explainer | Qwen3-VL-8B-Instruct | 8B | Movement ID, rubric reasoning, final score + rationale | +| Retrieval | Qwen3-VL-Embedding-8B | 8B | Nearest physio-scored reference clips (RAG) | +| **Total** | | **~17.8B** | Comfortable headroom under 32B | + +\* SAM 3D Body's exact count isn't published prominently — verify on the model card. It's SAM-3-family and sub-billion-class; budget impact is small either way. The two 8B Qwen models **share the Qwen3-VL-8B backbone** (the embedder is built on the instruct model), which is conceptually clean and operationally efficient. + +### Alternative config — "Heavy reasoner" (~28.7B) + +Swap the 8B judge for **Qwen3.6-27B** (multimodal, strong tool-calling, MTP speedups on llama.cpp). Budget then = 27 + ~0.85 + ~1 + small ≈ **28.7B**. This **leaves no room for the 8B embedder**, so you'd drop RAG (or replace it with a sub-0.5B embedder, or use pose-feature similarity for retrieval). Note: Qwen3.6-27B's MTP speculative decoding currently can't run simultaneously with image input (`--mmproj`), so for vision you run it without MTP. + +**Recommendation: ship the ~18B portfolio config.** RAG over the physio's few labeled clips is worth more than raw reasoning horsepower on this task, the headroom de-risks the budget, and "many small specialists" is the better hackathon story. + +--- + +## 6. Model selection rationale + +**YOLO26-Pose** — current-generation YOLO pose; single forward pass for detection + keypoints, NMS-free, real-time even on edge. Tiny param cost. It also handles **multiple people in frame** (important: team videos often have other players/staff visible) and feeds keypoints downstream. Off-the-shelf it predicts COCO human keypoints; can be fine-tuned for custom landmarks (e.g. dowel endpoints) if needed. + +**SAM 3.1** — gives a clean athlete mask and stable multi-object video tracking (Object Multiplex makes it fast). Two jobs: (a) isolate the target athlete from teammates/background so pose and 3D aren't polluted, (b) provide the mask prompt that SAM 3D Body consumes. Concept prompts ("the person in the blue jersey performing the squat") are a bonus for disambiguation. + +**SAM 3D Body** — *the addition that makes the scores trustworthy.* FMS criteria are joint angles and symmetry; 2D pose can't measure these reliably across camera angles (projection ambiguity). 3D mesh recovery from a single image, promptable with the 2D keypoints + mask you already have, yields view-invariant joint angles (the MHR rig even separates skeletal structure from soft-tissue shape, which is convenient for angle extraction). This is the difference between "looks bent" and "femur is 4° above horizontal → not a 3." + +**Skeletal-temporal scoring head** — your AQA component and your **Well-Tuned** badge. Recommend a compact **ST-GCN** (graph conv over the skeleton, temporal conv over frames) over a from-scratch transformer, because it's far more data-efficient on a tiny labeled set. Pre-train on public AQA / pose-action data, then fine-tune on the physio's labels. Output: per-test candidate score + a confidence the judge can weigh. + +**Qwen3-VL-8B-Instruct** — the judge. Strong video temporal modeling (Interleaved-MRoPE, timestamp alignment) suits movement clips. It identifies which of the 7 tests is being performed, reads the biomechanics, considers retrieved exemplars and the head's candidate, and emits the final score + rationale + detected compensation. GGUF → llama.cpp → Llama Champion. + +**Qwen3-VL-Embedding-8B** — retrieval. Embeds the query clip (or its keyframes/pose-render) and finds the physio's most similar already-scored clips to anchor the judge. Top multimodal retriever on MMEB-V2; same backbone as the judge; GGUF available. + +--- + +## 7. Architecture — an agentic pipeline + +Structured as cooperating specialist agents (maps naturally onto an OFP-style orchestration, with a Director coordinating and quality-gating). Each agent has one job and a typed output. + +``` + ┌──────────────────────────────────────────────┐ + video upload ───────▶│ IngestAgent │ + │ decode, normalize FPS, sample frames │ + └───────────────┬──────────────────────────────┘ + ▼ + ┌──────────────────────────────────────────────┐ + │ SegmentationAgent (SAM 3.1) │ + │ athlete mask + track id (reject teammates) │ + └───────────────┬──────────────────────────────┘ + ▼ + ┌──────────────────────────┴──────────────────────────┐ + ▼ ▼ + ┌───────────────────────────┐ ┌───────────────────────────┐ + │ PoseAgent (YOLO26-Pose) │ │ Body3DAgent (SAM 3D Body) │ + │ 2D keypoints per frame │ ───keypoints+mask──▶ │ 3D mesh / joint angles │ + └───────────────┬───────────┘ └───────────────┬───────────┘ + └─────────────────────┬────────────────────────────┘ + ▼ + ┌──────────────────────────────────────────────┐ + │ MovementClassifierAgent │ + │ which of the 7 FMS tests? (VLM or small CLS) │ + └───────────────┬──────────────────────────────┘ + ▼ + ┌──────────────────────────┴──────────────────────────┐ + ▼ ▼ ▼ + ┌────────────────────┐ ┌─────────────────────────┐ ┌────────────────────────┐ + │ BiomechanicsAgent │ │ ScoringAgent (ST-GCN) │ │ RetrievalAgent │ + │ rubric angles, │ │ candidate 0–3 + conf │ │ (Qwen3-VL-Embedding) │ + │ ROM, symmetry, │ │ from pose sequence │ │ k nearest physio clips │ + │ alignment, timing │ │ │ │ + their scores │ + └─────────┬──────────┘ └───────────┬─────────────┘ └───────────┬────────────┘ + └───────────────────────────┴──────────────────────────┘ + ▼ + ┌──────────────────────────────────────────────┐ + │ JudgeAgent (Qwen3-VL-8B) │ + │ rubric + measurements + exemplars + candidate│ + │ → final 0–3, rationale, compensation tag, │ + │ corrective hint, PAIN/CLEARING → defer │ + └───────────────┬──────────────────────────────┘ + ▼ + ┌──────────────────────────────────────────────┐ + │ ReportAgent │ + │ per-test card, composite 0–21, asymmetry │ + │ flags, annotated video, exportable PDF │ + └──────────────────────────────────────────────┘ +``` + +**Agent contracts (sketch):** + +- `IngestAgent` → `{frames[], fps, duration, n_people}` +- `SegmentationAgent` → `{athlete_track_id, masks[]}` +- `PoseAgent` → `{keypoints_2d[frame][joint]={x,y,conf}}` +- `Body3DAgent` → `{joints_3d[frame][joint]={x,y,z}, mesh_optional}` +- `MovementClassifierAgent` → `{test_name, side: left|right|n/a, confidence}` +- `BiomechanicsAgent` → `{features: {torso_tibia_angle, hip_flexion_deg, knee_valgus_deg, dowel_alignment, L_R_symmetry, ...}}` +- `ScoringAgent` → `{candidate_score: 0–3, confidence}` +- `RetrievalAgent` → `{exemplars: [{clip_id, score, similarity}]}` +- `JudgeAgent` → `{score: 0–3, rationale, compensation_tags[], corrective_hint, needs_human: bool}` +- `ReportAgent` → `{per_test[], composite, asymmetries[], overlay_video, pdf}` + +**Quality gating:** if the ST-GCN candidate and the JudgeAgent disagree by ≥1 point, or any agent confidence is low, the report marks the test **"low confidence — physio review recommended."** This keeps the human in the loop and is itself a selling point. + +--- + +## 8. Scoring methodology, per test + +The seven tests reduce to measurable quantities. Build a small rubric module — one scoring function per test — that consumes the 3D features and returns a score with the triggering reason. Examples: + +- **Deep Squat (3):** femur below horizontal AND torso parallel to tibia AND knees tracking over feet AND dowel over feet. **(2):** same but achieved only with heels elevated. **(1):** criteria unmet even with heels elevated. → all four conditions are angle/alignment checks on the 3D pose. +- **Hurdle Step / In-Line Lunge / Shoulder Mobility / ASLR:** bilateral — score each side, **record the lower** as the test score, and **always emit the asymmetry** even when the score is the same. +- **Trunk Stability Push-Up / Rotary Stability:** trunk rigidity / timing of limb movement — temporal features from the pose sequence; the ST-GCN head is most valuable here. +- **Pain / clearing tests (0):** the system **cannot** detect pain. Any clearing test, or a visible distress/abort, sets `needs_human = true` and the test is **not auto-scored**. Defer to the physio. State this loudly. + +Final composite = sum of seven test scores (0–21), plus an asymmetry summary. The number is never shown without its rationale. + +--- + +## 9. Data & fine-tuning plan (tiny-dataset survival guide) + +You have "a couple" of physio-scored clips. Treat them as gold, not as a training set. + +1. **Deterministic backbone first.** Get the biomechanics rubric working with no training. Validate the measured angles against the physio's scores qualitatively. This alone may be demo-ready. +2. **Pre-train the ST-GCN** on public pose-action / AQA data (action recognition or generic AQA) so it learns temporal movement structure, not FMS labels. +3. **Fine-tune on the physio's clips** with heavy augmentation: temporal crops/speed jitter, mirror (left↔right, doubles your bilateral data), camera-angle perturbation in 3D, joint noise. Few-shot, regularized, early-stopped. +4. **Hold out at least one physio-scored clip** as a sanity check the judge never sees. +5. **RAG instead of more training.** Every labeled clip goes into the embedding index as a scoring anchor. New clips added later improve the system with no retraining — a nice longitudinal story for the physio. +6. **Publish the fine-tuned head** to the Hub with a model card (→ Well-Tuned badge). Include the augmentation recipe and the honest "trained on N clips, treat as assistive" caveat. + +**Label schema to collect from the physio** (if you can get a bit more data): `clip_id, athlete_id, test_name, side, score(0–3), pain(bool), compensation_notes, camera_view`. Even 20–30 well-labeled clips meaningfully helps. + +--- + +## 10. Gradio Space & deployment + +**UI (targets Off-Brand badge):** +- `gr.Video` upload (or webcam capture) + a test-type selector (auto-detect, with manual override). +- Results panel: the 0–3 score as a large dial/patch, the composite 0–21, an asymmetry strip (L/R bars), and the **rationale text**. +- The annotated overlay video: skeleton + the specific angle that decided the score drawn on the frame where it mattered. +- A rubric drawer that shows the official 3/2/1 criteria for the detected test, with the met/unmet conditions checked off. +- A persistent **"Screening aid — not a diagnosis. Pain or clearing tests require a clinician."** banner. +- Custom CSS / `gr.Server` for a non-default look (scout/trail-map theme would rhyme with the hackathon, and with your design instincts). + +**Compute:** +- ZeroGPU (H200 slice) can host the ~18B portfolio; load pose/SAM/3D eagerly, the VLM + embedder via llama.cpp. +- For **Off the Grid**, ensure zero external API calls — everything served on-Space. +- For **Llama Champion**, route the VLM + embedding through llama.cpp (GGUF builds exist for Qwen3-VL-8B-Instruct, Qwen3-VL-Embedding-8B, and Qwen3.6-27B). On a Space, watch the CUDA/llama-cpp build flags — recent hackathon Spaces hit `libcudart` issues; a CPU-only or pinned-CUDA build is the usual fix. +- Persist the embedding index and accumulated labels in Space storage for the longitudinal baseline. + +--- + +## 11. Clinical safety & ethics (bake this in, don't bolt it on) + +- **Not a medical device.** Screening aid only. No diagnosis, no injury prediction, no treatment advice beyond generic FMS-style correctives. +- **Pain is out of scope** for automatic scoring — always defer to the physio. +- **Human-in-the-loop by design:** low-confidence and disagreement cases are surfaced, not hidden. +- **Consent & privacy:** athlete videos are biometric data. Get consent; don't log/persist clips beyond what the physio approves; document retention in the writeup. +- **Honesty in the demo:** show a case the system gets right *and* one it flags as uncertain. Judges (and physios) trust calibrated tools more than confident ones. + +--- + +## 12. Build plan — two weekends (June 5–15) + +**Weekend 1 — the spine works end to end:** +- Day 1: Space scaffold, `gr.Video` in → skeleton overlay out (YOLO26-Pose). Ingest + Segmentation + Pose agents. +- Day 2: SAM 3D Body integrated; BiomechanicsAgent computing Deep-Squat angles; first deterministic score on a real clip. +- Goal: upload a squat video, get a rationalized 0–3. *This alone is a viable demo.* + +**Midweek:** wire the JudgeAgent (Qwen3-VL via llama.cpp), MovementClassifier, and the rubric module for all 7 tests. Attend the AMA — confirm the param-sum interpretation. + +**Weekend 2 — make it sing:** +- ST-GCN pre-train + few-shot fine-tune on physio clips; publish to Hub. +- RetrievalAgent + embedding index over labeled clips. +- Custom UI polish, asymmetry view, PDF export, safety banners. +- Record the demo video (physio uses it on a real player), write the social post, publish the agent trace and the blog post. + +--- + +## 13. Risks & open questions + +- **Param-sum interpretation** — biggest unknown. The ~18B config is safe under either reading; confirm anyway. +- **SAM 3D Body on a Space** — verify weights, license, and that it runs within ZeroGPU limits; have a 2D-only fallback (angles from 2D + camera-angle caveats) if it's too heavy. +- **Single-camera angle limits** even with 3D — note it; recommend a consistent capture protocol (fixed camera position) for the physio, which also improves the longitudinal baseline. +- **Tiny dataset** — the deterministic rubric must stand on its own so the demo doesn't hinge on the learned head generalizing from a few clips. +- **llama.cpp + vision build** on Spaces — budget time for the CUDA build dance; CPU fallback for the embedder is fine. +- **Movement misclassification** — if the wrong test is detected, scoring is meaningless; keep the manual override prominent. + +--- + +## 14. Quick reference — the stack + +| Layer | Choice | Badge it helps | +|---|---|---| +| 2D pose | YOLO26-Pose | — | +| Segmentation/track | SAM 3.1 | — | +| 3D biomechanics | SAM 3D Body | — | +| Learned scoring | ST-GCN (fine-tuned, published) | Well-Tuned | +| Judge/explainer | Qwen3-VL-8B-Instruct (llama.cpp) | Llama Champion | +| Retrieval | Qwen3-VL-Embedding-8B (llama.cpp) | Llama Champion | +| Serving | On-Space, no cloud APIs | Off the Grid | +| Frontend | Custom Gradio (scout theme) | Off-Brand | +| Trace | Published agent run on Hub | Sharing is Caring | +| Writeup | Blog post w/ honesty section | Field Notes | + +*Total ≈ 18B params. Honest, explainable, human-in-the-loop, runs on a laptop.* diff --git a/docs/FormScout-Starter-Kit.md b/docs/FormScout-Starter-Kit.md new file mode 100644 index 0000000000000000000000000000000000000000..58487a6cad77abc937fe4f805040673637935bc6 --- /dev/null +++ b/docs/FormScout-Starter-Kit.md @@ -0,0 +1,169 @@ +# FormScout — Starter Kit & Resource Pack + +Companion to `FormScout-FMS-Spec.md` and `FormScout-Build-Prompt.md`. Every link below was checked. Read §1 first — some items are time-sensitive and block the build if you leave them late. + +--- + +## 1. Do this NOW (before the hack window — some take hours to clear) + +- [ ] **Request access to the gated Meta checkpoints today.** Both are gated on Hugging Face and approval isn't instant: + - SAM 3 / SAM 3.1 — request on the SAM 3 repos (you need the latest code for the 3.1 checkpoints). + - SAM 3D Body — `facebook/sam-3d-body-dinov3` and `facebook/sam-3d-body-vith` both require an access request, then an authenticated download. **Note:** data/checkpoints are blocked in sanctioned jurisdictions — shouldn't affect SK, but verify. +- [ ] **Put your HF token in the Space secrets** so the Space can pull the gated weights at build time. +- [ ] **Check licenses before you commit to a model** (this affects whether you can even submit): + - Qwen3-VL-8B / Qwen3-VL-Embedding-8B / Qwen3.6 → **Apache-2.0** (clean). + - SAM 3 / SAM 3.1 / SAM 3D Body → **SAM License** (not Apache; read the terms — there are use restrictions). + - Ultralytics YOLO26 → historically **AGPL-3.0** (open-sourcing obligations; commercial license exists). Verify on the model/repo and make sure an AGPL dependency is OK for your submission. If it's a problem, RTMPose/ViTPose are alternatives. + - pyskl / MMAction2 → Apache-2.0. + - KIMORE / UI-PRMD → academic/research terms; check before redistributing anything derived. +- [ ] **Confirm the param-counting rule in the Discord AMA.** Specifically: (a) is it summed across the pipeline or per-model? (b) do **frozen** base models count? (c) does a LoRA adapter's base count? Your ~18B config is safe under the strict reading either way, but get it on record. + +--- + +## 2. Literature package + +### 2.1 The framing that wins — "evaluate like an FMS reliability study" + +The single most credible move in your writeup: evaluate FormScout the way the clinical literature evaluates human FMS raters. Treat the model as a *second rater* and report **weighted Cohen's κ** and **ICC** against the physio, the exact metrics the reliability papers use. That instantly makes your results legible to any sports-medicine reader and is far more honest than a vanity accuracy number. + +| Resource | What it gives you | Link | +|---|---|---| +| Physiopedia — FMS | Clean overview of the 7 tests + 0–21 scoring | https://www.physio-pedia.com/Functional_Movement_Screen_(FMS) | +| FMS reliability study (JOSPT 2012) | The ICC/κ numbers and method you'll mirror in your eval | https://www.jospt.org/doi/10.2519/jospt.2012.3838 | +| FMS in elite youth soccer (PMC) | Per-test scores, asymmetries, clearing-test order | https://pmc.ncbi.nlm.nih.gov/articles/PMC5675373/ | +| Clinician's guide to FMS scoring | Per-test 3/2/1 criteria in plain language (rubric source) | https://meloqdevices.com/blogs/meloq-updates/functional-movement-screening | + +> **Honesty anchor for the blog post:** the popular "≤14 → injury risk" cutoff has weak/mixed predictive validity. Sell standardization, asymmetry detection, and a repeatable baseline — not prediction. + +### 2.2 Action Quality Assessment — surveys & living lists + +| Resource | Why | Link | +|---|---|---| +| *A Decade of AQA* (survey, 2025, 200+ papers, PRISMA) | The map of the whole field; start here | https://arxiv.org/abs/2502.02817 · code: https://github.com/HaoYin116/Survey_of_AQA | +| *Comprehensive Survey of AQA: Method & Benchmark* (2024) | Taxonomy by modality (video / **skeleton** / multimodal) + unified benchmark | https://arxiv.org/abs/2412.11149 · page: https://zhoukanglei.github.io/AQA-Survey | +| Awesome-AQA (ZhouKanglei) | Curated, **has a Medical-Care/rehab section** — your closest analogues | https://github.com/ZhouKanglei/Awesome-AQA | +| Awesome-AQA (Lyman-Smoker) | Second list; catches papers the other misses (FLEX, ExAct, etc.) | https://github.com/Lyman-Smoker/Awesome-AQA | + +### 2.3 Skeleton-based scoring — the methods your head will borrow from + +| Paper | Relevance to FormScout | Link | +|---|---|---| +| ST-GCN (original) | The graph-over-skeleton + temporal-conv backbone | https://github.com/open-mmlab/mmaction2/blob/main/configs/skeleton/stgcn/README.md | +| AQA via Hierarchical **Pose-guided** Multi-Stage Contrastive Regression (TIP 2025) | Pose-guided + contrastive regression with few labels — close to your setup | https://arxiv.org/abs/2501.03674 | +| Attention-guided Movement **Quality** Assessment + skeletal augmentation (UI-PRMD/KIMORE) | Transformer MQA on clinician-scored rehab data; **augmentation recipe for tiny sets** | https://arxiv.org/pdf/2204.07840 | +| SSL-Rehab: self-supervised 3D skeleton + **LoRA** fine-tune (KIMORE/UI-PRMD) | Pretrain→LoRA recipe for small clinical datasets (uses your LoRA muscle) | https://www.sciencedirect.com/science/article/abs/pii/S1077314224003564 | +| Skeleton-based AQA w/ anomaly-aware DTW (Sensors 2025) | DTW alignment + anomaly scoring; cheap, label-light baseline | https://www.ncbi.nlm.nih.gov/pmc/articles/PMC12693942/ | + +--- + +## 3. Models & tooling (verified) + +| Component | Repo / card | Params | License | Gated? | +|---|---|---:|---|---| +| YOLO26-Pose | https://docs.ultralytics.com/tasks/pose | <0.1B | AGPL-3.0* | no | +| SAM 3.1 | https://github.com/facebookresearch/sam3 | ~0.85B | SAM License | **yes** | +| SAM 3D Body | https://github.com/facebookresearch/sam-3d-body · https://huggingface.co/facebook/sam-3d-body-dinov3 | sub-1B† | SAM License | **yes** | +| ST-GCN++ / PoseConv3D | https://github.com/kennymckormick/pyskl | ~0.01–0.05B | Apache-2.0 | no | +| Qwen3-VL-8B-Instruct | https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct | 8B | Apache-2.0 | no | +| Qwen3-VL-Embedding-8B | https://huggingface.co/Qwen/Qwen3-VL-Embedding-8B (GGUF: dam2452/...-GGUF) | 8B | Apache-2.0 | no | +| Qwen3.6-27B (alt brain) | https://huggingface.co/unsloth/Qwen3.6-27B-GGUF | 27B | Apache-2.0 | no | + +\* verify the current YOLO26 license. † two variants (`dinov3`, `vith`); confirm exact count on the card — budget impact is small either way. SAM 3 itself is 848M. + +**Useful extras:** SAM 3D Body uses a Momentum Human Rig (MHR) that separates skeleton from soft-tissue shape — convenient for clean joint-angle extraction. The repo ships a notebook combining SAM 3D Body + SAM 3D Objects in one frame of reference. SAM 3D Body demo: https://www.aidemos.meta.com/segment-anything/editor/convert-body-to-3d + +--- + +## 4. Datasets for transfer / pretraining + +You have a couple of labeled clips. Pretrain on clinician-scored movement-quality data first, then few-shot fine-tune. These are the most transferable to FMS (ranked by relevance): + +| Dataset | Why it's the closest analogue | Link | +|---|---|---| +| **KIMORE** | Clinician **scores** of low-back-pain rehab exercises (trunk control, multi-plane) — same "score movement quality" task as FMS; partially overlaps Deep Squat / Rotary Stability / TSPU mechanics | https://www.researchgate.net/publication/333791841 (search "KIMORE dataset") | +| **UI-PRMD** | 10 rehab movements, correct vs. incorrect executions; standard MQA benchmark, pairs with KIMORE | search "UI-PRMD University of Idaho Physical Rehabilitation Movements" | +| **Fitness-AQA** | Real gym **squat/deadlift form errors** — directly relevant to Deep Squat compensations | https://github.com/ParitoshParmar/MTL-AQA (links Fitness-AQA) | +| **FLEX** | Large multi-modal fitness AQA dataset | via Lyman-Smoker/Awesome-AQA | +| **MTL-AQA / AQA-7 / FineFS** | General sports AQA for backbone pretraining (diving, skating) | https://github.com/ParitoshParmar/MTL-AQA | + +**FMS-specific public video data is scarce** — don't expect a drop-in set. Your physio's clips are the gold; everything above is for pretraining the temporal backbone so it learns movement structure before it ever sees an FMS label. + +--- + +## 5. Build & deploy tooling + +| Need | Link | +|---|---| +| Gradio docs (v6) | https://www.gradio.app/docs | +| `gradio.Server` — custom frontend + Gradio backend (Off-Brand badge) | https://www.gradio.app/guides/server-mode · blog: https://huggingface.co/blog/introducing-gradio-server | +| Gradio AI coding-assistant skill | `gradio skills add --claude` (PyPI: https://pypi.org/project/gradio/) | +| Gradio changelog (confirm `gr.Walkthrough`, `gr.Navbar`, `gr.Video.playback_position`) | https://www.gradio.app/changelog | +| HF Spaces ZeroGPU (`@spaces.GPU`) | https://huggingface.co/docs/hub/spaces-zerogpu | +| llama.cpp | https://github.com/ggml-org/llama.cpp | +| pyskl (ST-GCN++/PoseConv3D, custom-video tutorial incl. diving48) | https://github.com/kennymckormick/pyskl | +| MMAction2 (broader video understanding) | https://github.com/open-mmlab/mmaction2 | +| Hackathon's own trailheads (ML Intern, Gradio guides) | https://github.com/huggingface/ml-intern | + +> **Hackathon-specific gotcha already seen in the org:** another team's Space hit `libcudart.so.12` errors and had to swap llama.cpp for transformers + `spaces.GPU`. Plan for it — isolate the llama.cpp build (CPU-only or pinned-CUDA) and keep a transformers fallback. For the scoring head, a small hand-rolled ST-GCN may deploy more cleanly on a Space than the full MMAction2/pyskl stack — prototype with pyskl, ship lean. + +--- + +## 6. Two artifacts you probably haven't made yet + +### 6.1 Data & capture protocol (highest-leverage non-code work) + +With a tiny dataset, controlling *how* clips are captured beats any model tweak. Give the physio a one-pager: + +- **Camera:** one fixed position, tripod, ~3 m back, lens at hip height, landscape, 1080p/30fps+. Same setup every session — this is what makes 3D consistent and the longitudinal baseline meaningful. +- **Framing:** whole body in frame for the whole rep, including the dowel. Plain-ish background, even lighting, no backlight. +- **One athlete in frame** at scoring time (or note who to track). For bilateral tests, capture **both sides** and label each. +- **Label schema (CSV):** `clip_id, athlete_id, date, test_name, side(L/R/NA), score(0–3), pain(bool), compensation_notes(free text), camera_view, consent_on_file(bool)`. +- **One rep per clip** to start (simplest). If sessions are continuous, you'll need temporal segmentation first — flag it to the build agent at Phase 1. + +### 6.2 Evaluation plan + +Define "good" before you train, given so few labels: + +- **Primary:** Spearman ρ between predicted and physio scores (the AQA-standard metric), plus **exact-match** and **±1 accuracy** per test. +- **Clinical credibility:** **weighted Cohen's κ** and **ICC** of model-vs-physio, reported alongside the human inter-rater numbers from the JOSPT study — i.e. "how does FormScout compare to a second human rater?" +- **Asymmetry:** detection rate of L/R asymmetries the physio flagged (this is one of the FMS's most defensible outputs). +- **Validation:** leave-one-clip-out CV (you can't afford a held-out test split). Keep ≥1 clip the judge never sees for the demo. +- **Calibration:** report when the system says "low confidence / physio review" and show it's right to do so. A well-calibrated, humble tool reads as more trustworthy than a confident one. + +--- + +## 7. Ethics, consent & data handling (EU / Slovakia) + +You're filming identifiable athletes, possibly **minors** on a youth team. This is biometric personal data under GDPR — treat it as first-class, and say so in your submission (judges and physios both reward it): + +- **Consent:** written consent from each athlete (and a parent/guardian for anyone under 18) before any footage is used. No consent → not in the dataset, not in the demo. +- **Data minimization & retention:** keep only what you need; don't persist raw clips on the Space beyond what's approved; document a retention/deletion policy. Prefer storing derived skeletons over raw video where possible. +- **Demo footage:** use a consenting adult (you, a teammate) for the public demo video rather than a minor athlete, even if you trained on team data privately. +- **Framing:** screening aid, not a medical device; pain/clearing tests always defer to the clinician; human-in-the-loop by design. + +--- + +## 8. The transfer-learning recipe (ties it together) + +1. **Backbone pretrain** — ST-GCN++ on a general skeleton-action set (NTU/Kinetics skeletons via pyskl) so it learns motion structure. +2. **Domain adapt** — continue on **KIMORE + UI-PRMD** (clinician-scored movement quality) so it learns *quality*, not just *what action*. +3. **Few-shot fine-tune** — **LoRA** on the physio's FMS clips with heavy augmentation (temporal jitter, **L↔R mirror** to double bilateral data, 3D camera-angle perturbation, joint noise). The SSL-Rehab paper (§2.3) is your blueprint and it's exactly your LoRA wheelhouse. +4. **Don't over-train the head** — let deterministic biomechanics carry the demo; the learned head and RAG are the refinement and the badges, not the foundation. + +--- + +## 9. Demo & submission storyboard (the "make it sing" 30%) + +The submission needs a demo video + social post; "Show, Don't Tell" is a literal rule. A tight 60–90s cut: + +1. **0–10s** — the problem: physio eyeballing a squat, scribbling a score. "Same player, two raters, two scores." +2. **10–35s** — upload the clip to FormScout → skeleton overlay → 0–3 with the *deciding angle drawn on the frame* (`playback_position` jump). The "aha" shot. +3. **35–55s** — the scorecard: composite 0–21, the L/R asymmetry strip, a "low confidence — physio review" flag on a borderline case (honesty sells). +4. **55–75s** — the physio reacting / using it on a real player (the Backyard AI "they actually used it" proof). +5. **End card** — "Runs on a laptop. ~18B params. Screening aid, not a diagnosis." Link the Space, the published head, the agent trace, the blog. + +Social post: lead with the overlay GIF + the asymmetry-detection angle; tag Gradio/HF; one line of honest framing. + +--- + +*Built to give FormScout the best shot. The two things most teams underinvest in — the capture protocol (§6.1) and the honest, clinical-style evaluation (§6.2, §2.1) — are exactly where this project can out-class flashier entries. Good luck. 🏀* diff --git a/docs/plans/FormScout-Build-Prompt.md b/docs/plans/FormScout-Build-Prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..d40d219cbcb2e9b4c91e8f157c5546e44e814cd1 --- /dev/null +++ b/docs/plans/FormScout-Build-Prompt.md @@ -0,0 +1,168 @@ +# Build Prompt — FormScout (FMS scoring on Gradio, ≤32B) + +> **How to use this:** paste everything below the line into your coding agent (Claude Code, Codex, Cursor, etc.) as the opening instruction. Attach `FormScout-FMS-Spec.md` alongside it — that file is the product source of truth; this file is the engineering contract and process. Work through it phase by phase. + +--- + +## ROLE + +You are a **senior Python + Gradio architect with ~10 years of shipping ML web apps**, including production Hugging Face Spaces, custom-frontend Gradio deployments, ZeroGPU services, and llama.cpp-served models. You are pragmatic, opinionated about defaults, allergic to dead code, and you **verify APIs against current docs instead of trusting your memory** — Gradio and the model ecosystem move fast and your training data may be stale. You build **vertical slices** that run end to end early, then deepen. You never hand back a broken app. + +## MISSION + +Build **FormScout**, a Gradio app hosted as a Hugging Face Space that scores Functional Movement Screen (FMS) videos 0–3 per test with an explainable rationale and an annotated overlay, for the Build Small Hackathon (Backyard AI track). Full product requirements are in the attached `FormScout-FMS-Spec.md`. Honor it; if you deviate, say why. + +## PRIME DIRECTIVES (read before writing any code) + +1. **Verify before you build.** Do Phase 0 recon first. Do not write against a Gradio/model API you have not confirmed exists in the current version. When unsure, read the doc or the model card, don't guess. +2. **Vertical slice first.** The fastest path to a working `video in → scored overlay out` for *one* test beats a half-built version of all seven. Get something running on day one, then expand. +3. **Stay under budget.** Total model parameters across the whole pipeline must be **≤ 32B**. Track a running sum in `MODEL_BUDGET.md` and update it whenever you add or swap a model. The target config is ~18B (see spec §5). If a choice would exceed 32B, stop and flag it. +4. **No cloud model APIs.** All inference runs on the Space (Off the Grid badge). No OpenAI/Anthropic/Gemini/etc. calls for the core pipeline. +5. **Honesty & safety are features, not footnotes.** This is a screening aid, not a diagnosis and not injury prediction. Pain and clearing tests are never auto-scored — they set `needs_human=true`. A safety banner is always visible. Low-confidence and agent-disagreement cases are surfaced, not hidden. +6. **Modular agents, typed contracts.** Each pipeline stage is an independent module with a typed input/output (see spec §7). No god-functions. The pipeline must be runnable headless (no Gradio) for testing. + +--- + +## PHASE 0 — Recon & environment (do this first, report findings before coding) + +**Goal:** confirm the ground truth, then write a short `RECON.md` summarizing what you found and any deviations from the spec. + +1. **Install the Gradio skill** for this agent so you get current Gradio knowledge: + `gradio skills add --claude` (use the right flag for your agent; `--global` is fine). +2. **Pin and confirm Gradio.** Determine the current major version (expect Gradio 6.x). Record the exact version you'll target in `requirements.txt`. Confirm these still exist and note their current signatures: + - `gr.Blocks`, `gr.Video` (incl. `playback_position` for jumping to the decisive frame), `gr.Walkthrough` / `gr.Step` (for the 7-test flow), `gr.Navbar` (multipage), custom theming / CSS. + - `gradio.Server` (custom-frontend mode) — decide **Blocks vs Server** for the UI (see UI section). + - ZeroGPU usage: the `@spaces.GPU` decorator pattern, and the caveat that with `gradio.Server` + ZeroGPU you must call endpoints via `@gradio/client` from the browser. +3. **Verify every model** on its Hugging Face card — confirm it exists, its **license**, its **parameter count**, and whether a **GGUF** build exists for llama.cpp: + - YOLO26-Pose (Ultralytics) — pick a variant (l/x) and confirm license implications. + - SAM 3.1 (`facebookresearch/sam3`) — base checkpoint size. + - **SAM 3D Body** — *this is the uncertain one.* Confirm weights are public, the license, the **exact param count**, and that it runs within a ZeroGPU slice. If it's too heavy or not usable, fall back to **2D-only biomechanics** (angles from 2D pose + explicit camera-angle caveats) and note it. + - Qwen3-VL-8B-Instruct + Qwen3-VL-Embedding-8B — confirm GGUF builds and that they share the Qwen3-VL backbone. +4. **llama.cpp on Spaces reality check.** Confirm a working install path; prior hackathon Spaces hit `libcudart.so` errors. Decide CPU-only vs pinned-CUDA build per model. Have a `transformers`/`spaces.GPU` fallback ready for any model that won't build under llama.cpp in time. +5. **Open question to surface, not solve:** does "total parameters ≤ 32B" mean *per model* or *summed across the pipeline*? Design for the **summed** reading (safe under either). Note in `RECON.md` to confirm via the Discord AMA. + +**Exit criteria for Phase 0:** `RECON.md` exists with the Gradio version, a verified model table (name, params, license, GGUF y/n, runs-on-ZeroGPU y/n), the running param sum, the chosen UI approach, and any fallbacks triggered. + +--- + +## PHASE 1 — The spine (one test, end to end, headless + Gradio) + +**Goal:** upload a Deep Squat clip → get a rationalized 0–3 + skeleton overlay. + +- Scaffold the repo (structure below). Pipeline runs **headless** via `python -m formscout.run sample.mp4` before any UI. +- Implement `IngestAgent` → `SegmentationAgent` (SAM 3.1) → `PoseAgent` (YOLO26-Pose). Reject non-target people via the mask/track id. +- Implement `Body3DAgent` (SAM 3D Body) **or** the 2D fallback from Phase 0. +- Implement `BiomechanicsAgent` for Deep Squat only: torso–tibia angle, hip-flexion depth (femur vs horizontal), knee tracking, dowel alignment. +- Implement a **deterministic** rubric scorer for Deep Squat (3/2/1 per spec §8). No ML scoring yet. +- Minimal Gradio UI: `gr.Video` in, score + rationale + overlay out. + +**Exit criteria:** a real squat clip produces a defensible score, a one-line reason citing the deciding measurement, and an overlay video. Runs on the Space. + +--- + +## PHASE 2 — All seven tests + the judge + +- Extend `BiomechanicsAgent` + rubric scorers to all 7 tests. Bilateral tests score each side, **report the lower**, and **always emit the asymmetry**. +- `MovementClassifierAgent`: identify which test is in the clip (VLM or a small classifier) with a **manual override** in the UI. +- `JudgeAgent` (Qwen3-VL-8B via llama.cpp): consumes rubric + measurements + the deterministic candidate → final 0–3, rationale, compensation tag, corrective hint. Pain/clearing → `needs_human=true`, **not scored**. +- `ReportAgent`: per-test card, composite 0–21, asymmetry strip, annotated overlay, PDF export. + +**Exit criteria:** a multi-test session produces a full scorecard with composite + asymmetries; pain/clearing cases defer to human; disagreements between deterministic and judge scores are flagged. + +--- + +## PHASE 3 — Learned scoring + retrieval (the badges) + +- `ScoringAgent`: compact **ST-GCN** scoring head. Pre-train on public AQA/pose data, then **few-shot fine-tune** on the physio's labeled clips with heavy augmentation (temporal jitter, **left↔right mirror**, 3D camera-angle perturbation, joint noise). Hold out ≥1 labeled clip. **Publish the fine-tuned head to the Hub** with an honest model card → *Well-Tuned*. +- `RetrievalAgent`: build a Qwen3-VL-Embedding-8B index over the physio's labeled clips; return k nearest + their scores to anchor the judge → RAG. +- Wire the judge to weigh: deterministic candidate + ST-GCN candidate + retrieved exemplars. + +**Exit criteria:** scores incorporate the learned head and exemplars; adding a new labeled clip improves retrieval with **no retraining**. + +--- + +## PHASE 4 — Polish, ship, document + +- Custom UI pass (Off-Brand): scout/trail theme, score dial, asymmetry bars, rubric drawer with met/unmet checkboxes, decisive-frame jump via `playback_position`, persistent safety banner. +- Persist the embedding index + accumulated labels in Space storage (longitudinal baseline). +- **Publish one full agent trace** to the Hub (every agent's I/O for one run) → *Sharing is Caring*. +- Write the **blog post / field notes** with the honesty section front-and-center → *Field Notes*. +- Record the demo video (physio scores a real player) + the social post. + +**Exit criteria:** all six badges attempted, Space is green, demo + post + trace + blog are linked from the README. + +--- + +## REPO STRUCTURE (target) + +``` +formscout/ + app.py # Gradio entrypoint (Blocks or Server) + formscout/ + __init__.py + config.py # paths, model ids, thresholds, feature flags + pipeline.py # Director: orchestrates agents, quality-gates + run.py # headless CLI entrypoint (no Gradio) + agents/ + ingest.py + segmentation.py # SAM 3.1 + pose2d.py # YOLO26-Pose + body3d.py # SAM 3D Body (+ 2d fallback) + classify.py # movement classifier + biomechanics.py # rubric features per test + scoring.py # ST-GCN learned head + retrieval.py # Qwen3-VL-Embedding index + judge.py # Qwen3-VL-8B judge + report.py # scorecard, overlay, pdf + rubric/ + deep_squat.py ... # one scorer per FMS test, pure functions + types.py # typed dataclasses for every agent contract + serving/ + llama_cpp.py # llama.cpp client wrappers + fallbacks + ui/ + theme.py, components.py, custom/ # frontend assets + tracing.py # structured per-agent I/O logging (for the trace badge) + tests/ # headless tests per agent + a golden-clip e2e test + requirements.txt + README.md # Space card: pitch, demo, trace, blog, safety + MODEL_BUDGET.md # running param sum, must stay ≤32B + RECON.md # Phase 0 findings +``` + +## ENGINEERING STANDARDS + +- **Typing everywhere.** Every agent takes and returns a dataclass from `types.py`. Validate at boundaries. +- **Pure rubric functions.** Each test scorer is a pure function `(features) -> ScoreResult` with the triggering reason. Unit-test each against hand-computed cases. +- **Defensive by default.** Handle: no person detected, multiple people, wrong/ambiguous test, occlusion, too-short clip, bad FPS, 3D model OOM. Degrade gracefully and tell the user what happened — never crash the Space. +- **Confidence is first-class.** Every agent emits a confidence; the Director flags low confidence and ≥1-point judge/ST-GCN disagreement as "physio review recommended." +- **Config over constants.** Thresholds, model ids, k for retrieval, feature flags live in `config.py`, not scattered literals. +- **Tracing for free badge.** `tracing.py` records structured per-agent inputs/outputs for any run; one run gets exported for the Hub trace. +- **Determinism in demos.** Fix seeds; cache model loads at startup; warm the pipeline so the demo isn't a cold-start. +- **Tests:** per-agent unit tests on fixtures + one golden-clip end-to-end test asserting score, `needs_human`, and overlay presence. Keep a tiny committed sample clip. + +## GRADIO-SPECIFIC GUIDANCE + +- **Blocks vs Server:** start with `gr.Blocks` + custom CSS/theme — fastest to a polished result and enough for Off-Brand. Escalate to `gradio.Server` with your own frontend **only if** Blocks can't express the UI; document the reason. (Server still gives queuing, ZeroGPU, MCP.) +- Use `gr.Walkthrough`/`gr.Step` to guide the physio through a 7-test session; `gr.Navbar` if you split pages. +- Use `gr.Video`'s `playback_position` to jump the result video to the frame that decided the score. +- ZeroGPU: wrap heavy inference in `@spaces.GPU`; load models once at module scope; mind the per-call GPU time limit. If using `gradio.Server` + ZeroGPU, call endpoints via `@gradio/client` from the browser. +- `requirements.txt`: pin Gradio and every model lib; isolate the llama.cpp build (CPU-only or pinned-CUDA) to dodge `libcudart` failures; keep a `transformers` + `spaces.GPU` fallback path. + +## DEFINITION OF DONE (badge checklist) + +- [ ] Space runs green; upload → scorecard works on real clips. +- [ ] Param sum verified ≤ 32B in `MODEL_BUDGET.md`. +- [ ] 🔌 No cloud model APIs anywhere in the pipeline. +- [ ] 🎯 Fine-tuned ST-GCN head published to the Hub w/ honest card. +- [ ] 🎨 Custom, non-default Gradio UI. +- [ ] 🦙 VLM + embedder served via llama.cpp. +- [ ] 📡 One full agent trace published to the Hub. +- [ ] 📓 Blog post / field notes written, honesty section included. +- [ ] Demo video + social post recorded. +- [ ] Safety banner present; pain/clearing never auto-scored; low-confidence flagged. + +## INTERACTION PROTOCOL + +- **After each phase**, post: what runs now, the updated param sum, deviations from the spec, and the next step. Don't silently change architecture. +- **Ask the human only when blocked on a real decision** — e.g. single-test clips vs continuous sessions (changes segmentation + UI), SAM 3D Body unusable (triggers 2D fallback), or the param-sum interpretation. Otherwise proceed with the spec's defaults and note your assumption inline. +- **Never claim a Gradio/model API works without having verified it** this session. If you didn't check it, say so. diff --git a/docs/superpowers/plans/2026-06-04-formscout-full-build.md b/docs/superpowers/plans/2026-06-04-formscout-full-build.md new file mode 100644 index 0000000000000000000000000000000000000000..0fd0365e7852bef08235f0d7b0b278c897ed7248 --- /dev/null +++ b/docs/superpowers/plans/2026-06-04-formscout-full-build.md @@ -0,0 +1,2813 @@ +# FormScout Full Build Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build a Gradio/HF Space app that scores FMS videos 0–3 per test with rationale and annotated overlay, running entirely on-Space with ~18B params, targeting all 6 hackathon badges. + +**Architecture:** Typed specialist agents orchestrated by a deterministic Director; 2D pose path is always the default; 3D is optional/gated; pure rubric functions carry the scoring load; VLM (llama.cpp) is the judge/explainer. + +**Tech Stack:** Python 3.11, Gradio 6.x, YOLO26-Pose, SAM 3.1, Qwen3-VL-8B (llama.cpp), pyskl ST-GCN, Qwen3-VL-Embedding-8B (llama.cpp), pytest, ruff/black + +--- + +## Milestone Map + +| Milestone | Phase | Exit Criteria | +|---|---|---| +| **M0** | Recon | `RECON.md` exists, all models verified, Gradio version pinned | +| **M1** | Spine | Deep Squat: `python -m formscout.run sample.mp4` → score + rationale | +| **M2** | Gradio MVP | Upload Deep Squat clip → score + overlay in browser | +| **M3** | All 7 Tests | Full scorecard, composite 0–21, asymmetry detection | +| **M4** | Judge Online | Qwen3-VL via llama.cpp scoring + rationale for all tests | +| **M5** | Learned Head | ST-GCN fine-tuned, published to Hub | +| **M6** | RAG Online | Retrieval over physio clips anchors judge | +| **M7** | Ship | All 6 badges, Space green, demo video, blog post | + +--- + +## Phase 0 — Recon + +### Task 0.1: Scaffold repo & verify Gradio + +**Files:** +- Create: `requirements.txt` +- Create: `RECON.md` +- Create: `MODEL_BUDGET.md` +- Create: `formscout/__init__.py` +- Create: `formscout/config.py` + +- [ ] **Step 1: Create the project scaffold** + +```bash +mkdir -p formscout/agents/prompts formscout/rubric formscout/serving formscout/ui/custom tests +touch formscout/__init__.py formscout/agents/__init__.py formscout/rubric/__init__.py +touch formscout/serving/__init__.py formscout/ui/__init__.py +touch app.py formscout/run.py formscout/pipeline.py formscout/types.py +touch formscout/config.py formscout/tracing.py +touch MODEL_BUDGET.md RECON.md README.md +``` + +- [ ] **Step 2: Verify current Gradio version and APIs** + +```bash +pip install gradio --dry-run 2>&1 | head -5 +python -c "import gradio; print(gradio.__version__)" +python -c "import gradio as gr; print(hasattr(gr, 'Walkthrough'), hasattr(gr, 'Navbar'), hasattr(gr.Video, 'playback_position') if hasattr(gr, 'Video') else 'no Video')" +``` + +Expected: version 6.x printed; note which APIs exist. + +- [ ] **Step 3: Write requirements.txt with pinned versions** + +``` +gradio== +ultralytics>=8.3 +torch>=2.3 +opencv-python>=4.10 +numpy>=1.26 +scipy>=1.13 +pillow>=10.3 +pytest>=8.2 +ruff>=0.4 +black>=24.4 +huggingface_hub>=0.23 +transformers>=4.44 +``` + +Note: llama.cpp added after build verification in Task 0.3. + +- [ ] **Step 4: Write config.py skeleton** + +```python +from pathlib import Path + +ROOT = Path(__file__).parent.parent + +# Model IDs +YOLO_POSE_MODEL = "yolo11x-pose.pt" +SAM_CHECKPOINT = "sam2.1_hiera_base_plus.pt" +QWEN_VLM_GGUF = "Qwen3-VL-8B-Instruct-Q4_K_M.gguf" +QWEN_EMBED_GGUF = "Qwen3-VL-Embedding-8B-Q4_K_M.gguf" +STGCN_CHECKPOINT = ROOT / "checkpoints" / "stgcn_fms.pth" + +# Pipeline flags +ENABLE_3D = False # SAM 3D Body — off until access granted +ENABLE_STGCN = False # Phase 3 +ENABLE_RAG = False # Phase 3 +ENABLE_JUDGE = False # Phase 2 + +# Thresholds +MIN_CONFIDENCE = 0.6 +SCORE_DISAGREE_THRESH = 1 # flag if |stgcn - judge| >= this +RETRIEVAL_K = 3 + +# Pose +POSE_BACKEND = "yolo" # "yolo" | "sapiens" +POSE_CONF_THRESHOLD = 0.5 +NUM_KEYPOINTS = 17 + +# Biomechanics +DEEP_SQUAT_FEMUR_HORIZONTAL_DEG = 90.0 # femur below horizontal +DEEP_SQUAT_TORSO_TIBIA_MAX_DEG = 15.0 # torso parallel to tibia +DEEP_SQUAT_KNEE_TRACKING_MARGIN_PX = 20 + +# Serving +LLAMA_CPP_HOST = "127.0.0.1" +LLAMA_CPP_PORT_VLM = 8080 +LLAMA_CPP_PORT_EMBED = 8081 +``` + +- [ ] **Step 5: Verify model cards for license + params** + +```bash +python -c " +from huggingface_hub import model_info +models = [ + 'Qwen/Qwen3-VL-8B-Instruct', + 'Qwen/Qwen3-VL-Embedding-8B', +] +for m in models: + info = model_info(m) + print(m, '|', info.card_data.license if info.card_data else 'unknown') +" +``` + +Manually check: `facebookresearch/sam3`, `facebook/sam-3d-body-dinov3` (gated), Ultralytics YOLO26. + +- [ ] **Step 6: Write RECON.md with findings** + +```markdown +# RECON.md + +## Gradio +- Version: +- gr.Blocks: ✓ +- gr.Video (playback_position): +- gr.Walkthrough / gr.Step: +- gr.Navbar: +- UI approach: gr.Blocks + custom CSS (escalate to Server only if needed) + +## Model Verification + +| Model | Params | License | GGUF | ZeroGPU | Status | +|---|---|---|---|---|---| +| YOLO26-Pose L | ~0.05B | AGPL-3.0 | n/a | ✓ | ready | +| SAM 3.1 base | ~0.85B | SAM License | n/a | ✓ | access pending | +| SAM 3D Body | ~0.7B | SAM License | n/a | tbd | access pending | +| ST-GCN (pyskl) | ~0.03B | Apache-2.0 | n/a | ✓ | ready | +| Qwen3-VL-8B-Instruct | 8B | Apache-2.0 | ✓ | llama.cpp | ready | +| Qwen3-VL-Embedding-8B | 8B | Apache-2.0 | ✓ | llama.cpp | ready | + +## Param Sum +~17.8B — well under 32B limit. + +## Open Questions +- [ ] Confirm "≤32B" = summed vs per-model in Discord AMA +- [ ] SAM 3D Body gated access status +- [ ] AGPL-3.0 YOLO OK for hackathon submission? + +## llama.cpp Build Plan +- CPU-only build first (avoids libcudart.so issues on Spaces) +- Fallback: transformers + spaces.GPU for VLM +``` + +- [ ] **Step 7: Write MODEL_BUDGET.md** + +```markdown +# MODEL_BUDGET.md + +Running sum must stay ≤ 32B params. + +| Component | Model | Params | +|---|---|---| +| 2D Pose | YOLO26-Pose L | 0.05B | +| Segmentation | SAM 3.1 base | 0.85B | +| 3D Body (optional) | SAM 3D Body | ~0.7B | +| Scoring Head | ST-GCN (pyskl) | 0.03B | +| Judge/Explainer | Qwen3-VL-8B-Instruct | 8B | +| Retrieval | Qwen3-VL-Embedding-8B | 8B | +| **Total** | | **~17.63B** | + +Headroom: ~14.37B under 32B cap. +``` + +- [ ] **Step 8: Commit Phase 0 scaffold** + +```bash +git init && git add -A +git commit -m "chore: Phase 0 scaffold — repo structure, config, recon, model budget" +``` + +**✅ MILESTONE M0: RECON.md exists, param sum tracked, Gradio version pinned** + +--- + +## Phase 1 — The Spine (Deep Squat, headless) + +### Task 1.1: types.py — all agent contracts + +**Files:** +- Create: `formscout/types.py` +- Create: `tests/test_types.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_types.py +from formscout.types import ( + IngestResult, SegmentResult, Pose2DResult, Body3DResult, + MovementResult, BiomechFeatures, ScoreResult, RetrievalResult, + JudgeResult, ReportResult, PipelineState, +) +import pytest + +def test_ingest_result_frozen(): + r = IngestResult(frames=[], fps=30.0, duration=2.0, n_people=1, width=1920, height=1080) + with pytest.raises(Exception): + r.fps = 60.0 + +def test_judge_result_needs_human_default_false(): + r = JudgeResult(score=2, rationale="ok", compensation_tags=[], corrective_hint="", confidence=0.9, needs_human=False, notes="") + assert r.needs_human is False + +def test_score_result_valid_range(): + with pytest.raises(ValueError): + ScoreResult(score=4, rationale="bad", confidence=0.9, needs_human=False, notes="") + +def test_bilateral_features_has_symmetry(): + f = BiomechFeatures( + test_name="hurdle_step", + view="2d", + side="left", + angles={"hip_flexion": 45.0}, + alignments={}, + symmetry_delta=None, + timing={}, + confidence=0.8, + notes="", + ) + assert f.side == "left" +``` + +- [ ] **Step 2: Run test — expect ImportError** + +```bash +pytest tests/test_types.py -v +``` + +Expected: `ImportError: cannot import name 'IngestResult'` + +- [ ] **Step 3: Implement types.py** + +```python +# formscout/types.py +from __future__ import annotations +from dataclasses import dataclass, field +from typing import Any + +@dataclass(frozen=True) +class IngestResult: + frames: list # list of np.ndarray HWC BGR + fps: float + duration: float + n_people: int + width: int + height: int + confidence: float = 1.0 + notes: str = "" + +@dataclass(frozen=True) +class SegmentResult: + athlete_track_id: int + masks: list # list of np.ndarray bool HW per frame + confidence: float + notes: str = "" + +@dataclass(frozen=True) +class Pose2DResult: + keypoints: list # list[dict[int, dict]] frame→joint→{x,y,conf} + fps: float + confidence: float + notes: str = "" + +@dataclass(frozen=True) +class Body3DResult: + used: bool + joints_3d: list # list[dict] frame→joint→{x,y,z} — empty if used=False + confidence: float = 0.0 + notes: str = "" + +@dataclass(frozen=True) +class MovementResult: + test_name: str # "deep_squat"|"hurdle_step"|...|"unknown" + side: str # "left"|"right"|"bilateral"|"na" + confidence: float + notes: str = "" + +@dataclass(frozen=True) +class BiomechFeatures: + test_name: str + view: str # "2d" | "3d" + side: str # "left"|"right"|"na" + angles: dict # named angle → degrees + alignments: dict # named alignment → value + symmetry_delta: float | None # |left - right| or None for non-bilateral + timing: dict # event name → frame index + confidence: float + notes: str = "" + +@dataclass(frozen=True) +class ScoreResult: + score: int # 0–3 + rationale: str + confidence: float + needs_human: bool + notes: str = "" + + def __post_init__(self): + if not 0 <= self.score <= 3: + raise ValueError(f"score must be 0–3, got {self.score}") + +@dataclass(frozen=True) +class RetrievalResult: + exemplars: list # list of {clip_id, score, similarity, rationale} + confidence: float = 1.0 + notes: str = "" + +@dataclass(frozen=True) +class JudgeResult: + score: int # 0–3; -1 if needs_human=True (not auto-scored) + rationale: str + compensation_tags: list + corrective_hint: str + confidence: float + needs_human: bool + notes: str = "" + + def __post_init__(self): + if not self.needs_human and not 0 <= self.score <= 3: + raise ValueError(f"score must be 0–3 when needs_human=False, got {self.score}") + +@dataclass(frozen=True) +class ReportResult: + per_test: list # list of dicts with test_name, score, judge_result, features + composite: int | None # None if any test unscored + asymmetries: list # list of {test, left_score, right_score, delta} + overlay_video_path: str | None + pdf_path: str | None + low_confidence_flags: list + disagreement_flags: list + notes: str = "" + +@dataclass +class PipelineState: + """Mutable state threaded through the Director.""" + video_path: str + ingest: IngestResult | None = None + segment: SegmentResult | None = None + pose2d: Pose2DResult | None = None + body3d: Body3DResult | None = None + movement: MovementResult | None = None + features: BiomechFeatures | None = None + stgcn_score: ScoreResult | None = None + retrieval: RetrievalResult | None = None + judge: JudgeResult | None = None + report: ReportResult | None = None + errors: list = field(default_factory=list) + warnings: list = field(default_factory=list) +``` + +- [ ] **Step 4: Run tests — expect PASS** + +```bash +pytest tests/test_types.py -v +``` + +Expected: 4 passed. + +- [ ] **Step 5: Commit** + +```bash +git add formscout/types.py tests/test_types.py +git commit -m "feat: typed agent contracts in types.py with validation" +``` + +--- + +### Task 1.2: IngestAgent + +**Files:** +- Create: `formscout/agents/ingest.py` +- Create: `tests/fixtures/sample_squat.mp4` (use any short video for testing) +- Create: `tests/test_ingest.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_ingest.py +import pytest +from pathlib import Path +from formscout.agents.ingest import IngestAgent +from formscout.types import IngestResult + +FIXTURE = Path("tests/fixtures/sample_squat.mp4") + +def test_ingest_returns_typed_result(tmp_path): + # Create a minimal 1-second test video using OpenCV + import cv2, numpy as np + p = tmp_path / "test.mp4" + out = cv2.VideoWriter(str(p), cv2.VideoWriter_fourcc(*'mp4v'), 30, (640, 480)) + for _ in range(30): + out.write(np.zeros((480, 640, 3), dtype=np.uint8)) + out.release() + + agent = IngestAgent() + result = agent.run(str(p)) + assert isinstance(result, IngestResult) + assert result.fps == pytest.approx(30.0, abs=2.0) + assert len(result.frames) > 0 + assert result.width == 640 + assert result.height == 480 + +def test_ingest_rejects_missing_file(): + agent = IngestAgent() + result = agent.run("/nonexistent/path.mp4") + assert result.confidence == 0.0 + assert "not found" in result.notes.lower() + +def test_ingest_result_is_frozen(): + import cv2, numpy as np, tempfile, os + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + p = f.name + out = cv2.VideoWriter(p, cv2.VideoWriter_fourcc(*'mp4v'), 30, (64, 64)) + for _ in range(10): + out.write(np.zeros((64, 64, 3), dtype=np.uint8)) + out.release() + agent = IngestAgent() + result = agent.run(p) + os.unlink(p) + with pytest.raises(Exception): + result.fps = 999.0 +``` + +- [ ] **Step 2: Run — expect ImportError** + +```bash +pytest tests/test_ingest.py -v +``` + +- [ ] **Step 3: Implement IngestAgent** + +```python +# formscout/agents/ingest.py +""" +IngestAgent — decodes video, normalizes FPS, samples frames. +Input: video file path (str) +Output: IngestResult(frames, fps, duration, n_people, width, height) +Failure: returns IngestResult with confidence=0.0 and notes explaining the error. +Params: 0 (no model — pure OpenCV). +License: n/a. +Gated: no. +""" +import cv2 +from pathlib import Path +from formscout.types import IngestResult +from formscout import config + +MAX_FRAMES = 300 # hard cap to avoid OOM on long videos + +class IngestAgent: + def run(self, video_path: str) -> IngestResult: + p = Path(video_path) + if not p.exists(): + return IngestResult(frames=[], fps=0.0, duration=0.0, n_people=0, + width=0, height=0, confidence=0.0, + notes=f"video not found: {video_path}") + cap = cv2.VideoCapture(str(p)) + if not cap.isOpened(): + return IngestResult(frames=[], fps=0.0, duration=0.0, n_people=0, + width=0, height=0, confidence=0.0, + notes=f"could not open video: {video_path}") + fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + duration = total / fps if fps > 0 else 0.0 + + step = max(1, total // MAX_FRAMES) + frames, idx = [], 0 + while True: + ret, frame = cap.read() + if not ret: + break + if idx % step == 0: + frames.append(frame) + idx += 1 + cap.release() + + if not frames: + return IngestResult(frames=[], fps=fps, duration=duration, n_people=0, + width=w, height=h, confidence=0.0, + notes="no frames decoded") + return IngestResult(frames=frames, fps=fps, duration=duration, + n_people=-1, # unknown until segmentation + width=w, height=h, confidence=1.0) +``` + +- [ ] **Step 4: Run tests — expect PASS** + +```bash +pytest tests/test_ingest.py -v +``` + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/ingest.py tests/test_ingest.py +git commit -m "feat: IngestAgent — OpenCV video decode with frame sampling" +``` + +--- + +### Task 1.3: Pose2DAgent (YOLO) + +**Files:** +- Create: `formscout/agents/pose2d.py` +- Create: `tests/test_pose2d.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_pose2d.py +import numpy as np +import pytest +from formscout.agents.pose2d import Pose2DAgent +from formscout.types import Pose2DResult, IngestResult + +def _blank_ingest(n_frames=5, w=640, h=480): + frames = [np.zeros((h, w, 3), dtype=np.uint8) for _ in range(n_frames)] + return IngestResult(frames=frames, fps=30.0, duration=n_frames/30.0, + n_people=1, width=w, height=h) + +def test_pose2d_returns_typed_result(): + agent = Pose2DAgent() + result = agent.run(_blank_ingest()) + assert isinstance(result, Pose2DResult) + assert isinstance(result.keypoints, list) + assert result.fps == pytest.approx(30.0) + +def test_pose2d_keypoints_per_frame(): + agent = Pose2DAgent() + ingest = _blank_ingest(n_frames=3) + result = agent.run(ingest) + # blank frames will have no detections — should return empty dicts, not crash + assert len(result.keypoints) == 3 + for frame_kps in result.keypoints: + assert isinstance(frame_kps, dict) + +def test_pose2d_graceful_on_empty_frames(): + empty = IngestResult(frames=[], fps=30.0, duration=0.0, + n_people=0, width=640, height=480) + agent = Pose2DAgent() + result = agent.run(empty) + assert result.confidence == 0.0 + assert "no frames" in result.notes.lower() +``` + +- [ ] **Step 2: Run — expect ImportError** + +```bash +pytest tests/test_pose2d.py -v +``` + +- [ ] **Step 3: Implement Pose2DAgent** + +```python +# formscout/agents/pose2d.py +""" +Pose2DAgent — 2D per-frame keypoint extraction. +Input: IngestResult +Output: Pose2DResult(keypoints per frame, fps, confidence) +Failure: returns Pose2DResult with confidence=0.0 and notes. +Model: YOLO26-Pose L (AGPL-3.0, ~0.05B params, public). +Gated: no. +""" +from __future__ import annotations +import numpy as np +from formscout import config +from formscout.types import IngestResult, Pose2DResult + +_model = None + +def _get_model(): + global _model + if _model is None: + from ultralytics import YOLO + _model = YOLO(config.YOLO_POSE_MODEL) + return _model + + +class Pose2DAgent: + def run(self, ingest: IngestResult) -> Pose2DResult: + if not ingest.frames: + return Pose2DResult(keypoints=[], fps=ingest.fps, + confidence=0.0, notes="no frames in ingest") + model = _get_model() + keypoints_per_frame: list[dict] = [] + total_conf = 0.0 + n_detected = 0 + + for frame in ingest.frames: + results = model(frame, verbose=False) + frame_kps: dict[int, dict] = {} + if results and results[0].keypoints is not None: + kps = results[0].keypoints + if len(kps) > 0: + # Take highest-confidence person (index 0 after YOLO NMS sort) + xy = kps.xy[0].cpu().numpy() # (17, 2) + conf = kps.conf[0].cpu().numpy() # (17,) + for j in range(len(xy)): + frame_kps[j] = {"x": float(xy[j, 0]), + "y": float(xy[j, 1]), + "conf": float(conf[j])} + total_conf += float(conf.mean()) + n_detected += 1 + keypoints_per_frame.append(frame_kps) + + overall_conf = (total_conf / n_detected) if n_detected > 0 else 0.0 + notes = "" if n_detected > 0 else "no person detected in any frame" + return Pose2DResult(keypoints=keypoints_per_frame, fps=ingest.fps, + confidence=overall_conf, notes=notes) +``` + +- [ ] **Step 4: Run tests — expect PASS** + +```bash +pytest tests/test_pose2d.py -v +``` + +Note: blank frames will yield no detections — that is correct behavior. + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/pose2d.py tests/test_pose2d.py +git commit -m "feat: Pose2DAgent — YOLO26-Pose keypoint extraction" +``` + +--- + +### Task 1.4: Body3DAgent (stub — gated model) + +**Files:** +- Create: `formscout/agents/body3d.py` +- Create: `tests/test_body3d.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_body3d.py +from formscout.agents.body3d import Body3DAgent +from formscout.types import Body3DResult, Pose2DResult + +def _dummy_pose(): + return Pose2DResult(keypoints=[{0: {"x": 320.0, "y": 240.0, "conf": 0.9}}], + fps=30.0, confidence=0.9) + +def test_body3d_disabled_returns_not_used(): + agent = Body3DAgent(enable_3d=False) + result = agent.run(_dummy_pose(), masks=[]) + assert isinstance(result, Body3DResult) + assert result.used is False + assert result.joints_3d == [] + +def test_body3d_unavailable_checkpoint_returns_not_used(monkeypatch): + monkeypatch.setattr("formscout.config.ENABLE_3D", True) + agent = Body3DAgent(enable_3d=True) + # No checkpoint present → graceful fallback + result = agent.run(_dummy_pose(), masks=[]) + assert result.used is False +``` + +- [ ] **Step 2: Run — expect ImportError** + +```bash +pytest tests/test_body3d.py -v +``` + +- [ ] **Step 3: Implement Body3DAgent stub** + +```python +# formscout/agents/body3d.py +""" +Body3DAgent — optional 3D mesh/joint angle recovery via SAM 3D Body. +Input: Pose2DResult, list of athlete masks +Output: Body3DResult(used, joints_3d, confidence) +Failure: ALWAYS returns Body3DResult(used=False) when enable_3d=False or + checkpoint unavailable — this is a normal success path, not an error. +Model: facebook/sam-3d-body-dinov3 (~0.7B, SAM License, GATED — access pending). +Gated: YES — access requested June 2026. +""" +from __future__ import annotations +from formscout.types import Pose2DResult, Body3DResult +from formscout import config + +_NOT_USED = Body3DResult(used=False, joints_3d=[], confidence=0.0, + notes="3D disabled or checkpoint unavailable") + + +class Body3DAgent: + def __init__(self, enable_3d: bool | None = None): + self._enabled = config.ENABLE_3D if enable_3d is None else enable_3d + self._model = None + if self._enabled: + self._model = self._try_load() + + def _try_load(self): + try: + # Placeholder: replace with actual SAM 3D Body load once access granted + from pathlib import Path + ckpt = Path("checkpoints/sam3d_body.pth") + if not ckpt.exists(): + return None + # TODO: load SAM 3D Body model here + return None + except Exception: + return None + + def run(self, pose2d: Pose2DResult, masks: list) -> Body3DResult: + if not self._enabled or self._model is None: + return _NOT_USED + # TODO: implement SAM 3D Body inference when access granted + return _NOT_USED +``` + +- [ ] **Step 4: Run tests — expect PASS** + +```bash +pytest tests/test_body3d.py -v +``` + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/body3d.py tests/test_body3d.py +git commit -m "feat: Body3DAgent stub — graceful fallback until SAM 3D Body access granted" +``` + +--- + +### Task 1.5: BiomechanicsAgent + Deep Squat rubric + +**Files:** +- Create: `formscout/rubric/deep_squat.py` +- Create: `formscout/agents/biomechanics.py` +- Create: `tests/test_biomechanics.py` + +- [ ] **Step 1: Write failing tests** + +```python +# tests/test_biomechanics.py +import pytest +from formscout.rubric.deep_squat import score_deep_squat +from formscout.types import BiomechFeatures, ScoreResult + +def _features(femur_below_horiz=True, torso_parallel_tibia=True, + knees_tracking=True, dowel_over_feet=True, + heels_elevated=False, view="2d"): + return BiomechFeatures( + test_name="deep_squat", + view=view, + side="na", + angles={ + "femur_from_horizontal_deg": 15.0 if femur_below_horiz else 95.0, + "torso_tibia_angle_deg": 10.0 if torso_parallel_tibia else 40.0, + }, + alignments={ + "knees_tracking_over_feet": knees_tracking, + "dowel_over_feet": dowel_over_feet, + "heels_elevated": heels_elevated, + }, + symmetry_delta=None, + timing={}, + confidence=0.9, + ) + +def test_deep_squat_score_3(): + result = score_deep_squat(_features()) + assert isinstance(result, ScoreResult) + assert result.score == 3 + assert not result.needs_human + +def test_deep_squat_score_2_heels_elevated(): + result = score_deep_squat(_features(heels_elevated=True)) + assert result.score == 2 + +def test_deep_squat_score_1_criteria_unmet_even_with_heels(): + result = score_deep_squat(_features( + femur_below_horiz=False, heels_elevated=True + )) + assert result.score == 1 + +def test_deep_squat_score_0_pain(): + f = _features() + # Override: simulate pain flag via needs_human in features + result = score_deep_squat(f, pain=True) + assert result.score == 0 + assert result.needs_human is True + +def test_deep_squat_rationale_mentions_deciding_factor(): + result = score_deep_squat(_features(femur_below_horiz=False)) + assert "femur" in result.rationale.lower() or "depth" in result.rationale.lower() +``` + +- [ ] **Step 2: Run — expect ImportError** + +```bash +pytest tests/test_biomechanics.py -v +``` + +- [ ] **Step 3: Implement deep_squat.py rubric** + +```python +# formscout/rubric/deep_squat.py +""" +Pure function: score_deep_squat(features, pain=False) -> ScoreResult. +FMS Deep Squat rubric (0–3). No model calls. +""" +from formscout.types import BiomechFeatures, ScoreResult + +# Thresholds +FEMUR_BELOW_HORIZ_DEG = 90.0 # femur angle from vertical; <90 = below horizontal +TORSO_TIBIA_MAX_DEG = 15.0 # degrees between torso and tibia long axis + + +def score_deep_squat(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain or clearing test flagged — defer to physio.", + confidence=1.0, needs_human=True) + + femur_deg = features.angles.get("femur_from_horizontal_deg", 999.0) + torso_tibia_deg = features.angles.get("torso_tibia_angle_deg", 999.0) + knees_ok = features.alignments.get("knees_tracking_over_feet", False) + dowel_ok = features.alignments.get("dowel_over_feet", False) + heels_elevated = features.alignments.get("heels_elevated", False) + + # 3: all four criteria met, flat feet + criteria_3 = (femur_deg < FEMUR_BELOW_HORIZ_DEG and + torso_tibia_deg < TORSO_TIBIA_MAX_DEG and + knees_ok and dowel_ok) + + # 2: criteria met only with heels elevated + criteria_2 = heels_elevated and ( + femur_deg < FEMUR_BELOW_HORIZ_DEG and + torso_tibia_deg < TORSO_TIBIA_MAX_DEG and + knees_ok and dowel_ok + ) + + view_note = " (2D measurement — camera angle may affect accuracy)" if features.view == "2d" else "" + + if criteria_3: + return ScoreResult( + score=3, + rationale=f"All criteria met: femur {femur_deg:.1f}° below horizontal, " + f"torso–tibia {torso_tibia_deg:.1f}°, knees tracking, dowel overhead.{view_note}", + confidence=features.confidence, + needs_human=False, + ) + elif criteria_2: + return ScoreResult( + score=2, + rationale=f"Criteria met only with heel elevation.{view_note}", + confidence=features.confidence, + needs_human=False, + ) + else: + # Identify the failing criterion for the rationale + failures = [] + if femur_deg >= FEMUR_BELOW_HORIZ_DEG: + failures.append(f"insufficient squat depth (femur {femur_deg:.1f}° — needs <{FEMUR_BELOW_HORIZ_DEG}°)") + if torso_tibia_deg >= TORSO_TIBIA_MAX_DEG: + failures.append(f"torso–tibia angle {torso_tibia_deg:.1f}° (needs <{TORSO_TIBIA_MAX_DEG}°)") + if not knees_ok: + failures.append("knees not tracking over feet") + if not dowel_ok: + failures.append("dowel not over feet") + reason = "; ".join(failures) if failures else "criteria not met" + return ScoreResult( + score=1, + rationale=f"Score 1: {reason}.{view_note}", + confidence=features.confidence, + needs_human=False, + ) +``` + +- [ ] **Step 4: Implement BiomechanicsAgent (Deep Squat)** + +```python +# formscout/agents/biomechanics.py +""" +BiomechanicsAgent — computes rubric-relevant measurements from pose keypoints. +Input: Pose2DResult, Body3DResult, MovementResult +Output: BiomechFeatures(test_name, view, side, angles, alignments, ...) +Failure: returns low-confidence BiomechFeatures with notes. +Params: 0 (geometry only). +Gated: no. +""" +from __future__ import annotations +import numpy as np +from formscout.types import Pose2DResult, Body3DResult, MovementResult, BiomechFeatures +from formscout import config + +# COCO keypoint indices +HIP_L, HIP_R = 11, 12 +KNEE_L, KNEE_R = 13, 14 +ANKLE_L, ANKLE_R = 15, 16 +SHOULDER_L, SHOULDER_R = 5, 6 +NOSE = 0 + + +def _angle_2d(a, b, c) -> float: + """Angle at vertex b formed by segments b→a and b→c, in degrees.""" + ba = np.array(a) - np.array(b) + bc = np.array(c) - np.array(b) + cos = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc) + 1e-9) + return float(np.degrees(np.arccos(np.clip(cos, -1.0, 1.0)))) + + +def _median_kp(keypoints: list[dict], joint: int) -> tuple[float, float, float]: + """Median x, y, conf across frames for a keypoint joint index.""" + xs, ys, cs = [], [], [] + for frame in keypoints: + kp = frame.get(joint) + if kp and kp["conf"] > config.POSE_CONF_THRESHOLD: + xs.append(kp["x"]); ys.append(kp["y"]); cs.append(kp["conf"]) + if not xs: + return 0.0, 0.0, 0.0 + return float(np.median(xs)), float(np.median(ys)), float(np.median(cs)) + + +def _compute_deep_squat_2d(pose2d: Pose2DResult) -> BiomechFeatures: + kps = pose2d.keypoints + hip_lx, hip_ly, hip_lc = _median_kp(kps, HIP_L) + knee_lx, knee_ly, knee_lc = _median_kp(kps, KNEE_L) + ankle_lx, ankle_ly, ankle_lc = _median_kp(kps, ANKLE_L) + shoulder_lx, shoulder_ly, _ = _median_kp(kps, SHOULDER_L) + + conf = np.mean([c for c in [hip_lc, knee_lc, ankle_lc] if c > 0] or [0.0]) + + # Femur angle from horizontal: angle of hip→knee vector from x-axis + femur_vec = np.array([knee_lx - hip_lx, knee_ly - hip_ly]) + femur_from_horiz = float(abs(np.degrees(np.arctan2( + abs(femur_vec[1]), abs(femur_vec[0]) + 1e-9 + )))) + + # Torso–tibia angle: angle between hip→shoulder and ankle→knee vectors + torso_vec = np.array([shoulder_lx - hip_lx, shoulder_ly - hip_ly]) + tibia_vec = np.array([knee_lx - ankle_lx, knee_ly - ankle_ly]) + cos_tt = np.dot(torso_vec, tibia_vec) / ( + np.linalg.norm(torso_vec) * np.linalg.norm(tibia_vec) + 1e-9 + ) + torso_tibia_deg = float(np.degrees(np.arccos(np.clip(cos_tt, -1, 1)))) + + # Knee tracking over foot: knee x should be within margin of ankle x + knees_tracking = abs(knee_lx - ankle_lx) < config.DEEP_SQUAT_KNEE_TRACKING_MARGIN_PX + + # Heels: if ankle is significantly above baseline (proxy for heel elevation) + heels_elevated = False # requires side-view calibration; set conservatively + + return BiomechFeatures( + test_name="deep_squat", + view="2d", + side="na", + angles={ + "femur_from_horizontal_deg": femur_from_horiz, + "torso_tibia_angle_deg": torso_tibia_deg, + }, + alignments={ + "knees_tracking_over_feet": knees_tracking, + "dowel_over_feet": False, # requires dowel detection (Phase 2+) + "heels_elevated": heels_elevated, + }, + symmetry_delta=None, + timing={}, + confidence=float(conf), + notes="2D measurements; heel elevation detection requires calibration", + ) + + +class BiomechanicsAgent: + def run(self, pose2d: Pose2DResult, body3d: Body3DResult, + movement: MovementResult) -> BiomechFeatures: + if movement.test_name == "deep_squat": + if body3d.used: + # TODO: implement 3D feature extraction (Phase 1.5+) + pass + return _compute_deep_squat_2d(pose2d) + # Other tests — Phase 2 + return BiomechFeatures( + test_name=movement.test_name, view="2d", side="na", + angles={}, alignments={}, symmetry_delta=None, timing={}, + confidence=0.0, notes=f"test '{movement.test_name}' not yet implemented", + ) +``` + +- [ ] **Step 5: Run tests — expect PASS** + +```bash +pytest tests/test_biomechanics.py -v +``` + +- [ ] **Step 6: Commit** + +```bash +git add formscout/rubric/deep_squat.py formscout/agents/biomechanics.py tests/test_biomechanics.py +git commit -m "feat: Deep Squat rubric (pure fn) + BiomechanicsAgent 2D geometry" +``` + +--- + +### Task 1.6: Headless pipeline (Director + run.py) + +**Files:** +- Create: `formscout/pipeline.py` +- Create: `formscout/run.py` +- Create: `tests/test_pipeline.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_pipeline.py +import numpy as np +import pytest +from unittest.mock import patch, MagicMock +from formscout.pipeline import Director +from formscout.types import ( + IngestResult, Pose2DResult, Body3DResult, MovementResult, + BiomechFeatures, ScoreResult, JudgeResult, PipelineState +) + +def _mock_ingest(): + frames = [np.zeros((480, 640, 3), dtype=np.uint8)] + return IngestResult(frames=frames, fps=30.0, duration=1.0, + n_people=1, width=640, height=480) + +def _mock_pose2d(): + return Pose2DResult( + keypoints=[{11: {"x": 320.0, "y": 200.0, "conf": 0.9}, + 13: {"x": 300.0, "y": 280.0, "conf": 0.9}, + 15: {"x": 295.0, "y": 360.0, "conf": 0.9}, + 5: {"x": 320.0, "y": 150.0, "conf": 0.9}}], + fps=30.0, confidence=0.9 + ) + +def test_director_runs_deep_squat_headless(tmp_path): + video = tmp_path / "test.mp4" + video.write_bytes(b"") # placeholder path + + with patch("formscout.pipeline.IngestAgent") as MockIngest, \ + patch("formscout.pipeline.Pose2DAgent") as MockPose, \ + patch("formscout.pipeline.Body3DAgent") as MockBody3D, \ + patch("formscout.pipeline.BiomechanicsAgent") as MockBiomech, \ + patch("formscout.pipeline.MovementClassifierAgent") as MockClassify: + + MockIngest.return_value.run.return_value = _mock_ingest() + MockPose.return_value.run.return_value = _mock_pose2d() + MockBody3D.return_value.run.return_value = Body3DResult(used=False, joints_3d=[], confidence=0.0) + MockClassify.return_value.run.return_value = MovementResult( + test_name="deep_squat", side="na", confidence=0.95) + mock_features = BiomechFeatures( + test_name="deep_squat", view="2d", side="na", + angles={"femur_from_horizontal_deg": 80.0, "torso_tibia_angle_deg": 12.0}, + alignments={"knees_tracking_over_feet": True, "dowel_over_feet": True, "heels_elevated": False}, + symmetry_delta=None, timing={}, confidence=0.9) + MockBiomech.return_value.run.return_value = mock_features + + director = Director() + state = director.run(str(video)) + + assert isinstance(state, PipelineState) + assert state.judge is not None or state.features is not None + assert not state.errors + +def test_director_flags_low_confidence(): + # If pose confidence < MIN_CONFIDENCE, warnings should be appended + from formscout import config + assert config.MIN_CONFIDENCE > 0 +``` + +- [ ] **Step 2: Run — expect ImportError** + +```bash +pytest tests/test_pipeline.py -v +``` + +- [ ] **Step 3: Implement pipeline.py Director** + +```python +# formscout/pipeline.py +""" +Director — deterministic state machine orchestrating all agents. +Not an LLM. Applies quality gates and builds PipelineState. +""" +from __future__ import annotations +from formscout import config +from formscout.types import PipelineState, JudgeResult, ScoreResult +from formscout.agents.ingest import IngestAgent +from formscout.agents.pose2d import Pose2DAgent +from formscout.agents.body3d import Body3DAgent +from formscout.agents.biomechanics import BiomechanicsAgent +from formscout.agents.classify import MovementClassifierAgent +from formscout.rubric.deep_squat import score_deep_squat +from formscout.tracing import Tracer + + +class Director: + def __init__(self): + self.ingest = IngestAgent() + self.pose2d = Pose2DAgent() + self.body3d = Body3DAgent() + self.classify = MovementClassifierAgent() + self.biomech = BiomechanicsAgent() + self.tracer = Tracer() + + def run(self, video_path: str) -> PipelineState: + state = PipelineState(video_path=video_path) + + # --- Ingest --- + state.ingest = self.ingest.run(video_path) + self.tracer.record("ingest", state.ingest) + if state.ingest.confidence == 0.0: + state.errors.append(f"Ingest failed: {state.ingest.notes}") + return state + + # --- 2D Pose --- + state.pose2d = self.pose2d.run(state.ingest) + self.tracer.record("pose2d", state.pose2d) + if state.pose2d.confidence < config.MIN_CONFIDENCE: + state.warnings.append( + f"Pose2D low confidence ({state.pose2d.confidence:.2f}) — physio review recommended" + ) + + # --- 3D Body (optional) --- + state.body3d = self.body3d.run(state.pose2d, []) + self.tracer.record("body3d", state.body3d) + + # --- Movement Classifier --- + state.movement = self.classify.run(state.ingest, state.pose2d) + self.tracer.record("movement", state.movement) + if state.movement.test_name == "unknown": + state.errors.append("Movement classification failed — manual override required") + return state + if state.movement.confidence < config.MIN_CONFIDENCE: + state.warnings.append( + f"Movement classifier low confidence ({state.movement.confidence:.2f})" + ) + + # --- Biomechanics --- + state.features = self.biomech.run(state.pose2d, state.body3d, state.movement) + self.tracer.record("biomechanics", state.features) + if state.features.confidence < config.MIN_CONFIDENCE: + state.warnings.append( + f"Biomechanics low confidence ({state.features.confidence:.2f})" + ) + + # --- Deterministic Rubric Score (Phase 1: no STGCN or Judge yet) --- + if state.movement.test_name == "deep_squat" and not config.ENABLE_JUDGE: + rubric_score = score_deep_squat(state.features) + state.judge = JudgeResult( + score=rubric_score.score, + rationale=rubric_score.rationale, + compensation_tags=[], + corrective_hint="", + confidence=rubric_score.confidence, + needs_human=rubric_score.needs_human, + notes="deterministic rubric (no VLM judge in Phase 1)", + ) + self.tracer.record("judge", state.judge) + + return state +``` + +- [ ] **Step 4: Implement MovementClassifierAgent stub** + +```python +# formscout/agents/classify.py +""" +MovementClassifierAgent — identifies which of 7 FMS tests is being performed. +Phase 1: returns 'deep_squat' stub (VLM classifier wired in Phase 2). +Input: IngestResult, Pose2DResult +Output: MovementResult(test_name, side, confidence) +""" +from formscout.types import IngestResult, Pose2DResult, MovementResult + + +class MovementClassifierAgent: + def run(self, ingest: IngestResult, pose2d: Pose2DResult) -> MovementResult: + # Phase 1 stub — always returns deep_squat + # Phase 2: replace with VLM or small classifier + return MovementResult( + test_name="deep_squat", + side="na", + confidence=0.5, + notes="Phase 1 stub — always deep_squat", + ) +``` + +- [ ] **Step 5: Implement tracing.py** + +```python +# formscout/tracing.py +"""Structured per-agent I/O logger. One full run can be exported to Hub.""" +import json +from dataclasses import asdict +from datetime import datetime +from pathlib import Path + + +class Tracer: + def __init__(self): + self._records: list[dict] = [] + self._run_id = datetime.utcnow().strftime("%Y%m%dT%H%M%S") + + def record(self, agent_name: str, result) -> None: + try: + data = asdict(result) + except Exception: + data = str(result) + self._records.append({"agent": agent_name, "result": data, + "ts": datetime.utcnow().isoformat()}) + + def export(self, path: str | None = None) -> str: + out = path or f"trace_{self._run_id}.json" + Path(out).write_text(json.dumps(self._records, indent=2, default=str)) + return out +``` + +- [ ] **Step 6: Implement run.py headless CLI** + +```python +# formscout/run.py +"""Headless CLI — no Gradio imports.""" +import sys +from formscout.pipeline import Director + +def main(video_path: str) -> None: + director = Director() + state = director.run(video_path) + if state.errors: + print("ERRORS:", state.errors) + sys.exit(1) + if state.warnings: + print("WARNINGS:", state.warnings) + if state.judge: + print(f"\nTest: {state.movement.test_name}") + print(f"Score: {state.judge.score}/3") + print(f"Rationale: {state.judge.rationale}") + print(f"Confidence:{state.judge.confidence:.2f}") + if state.judge.needs_human: + print("⚠️ Deferred to physio — do not use this score.") + else: + print("Pipeline incomplete — no judge result.") + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: python -m formscout.run ") + sys.exit(1) + main(sys.argv[1]) +``` + +- [ ] **Step 7: Run tests** + +```bash +pytest tests/test_pipeline.py -v +``` + +Expected: PASS. + +- [ ] **Step 8: Smoke-test headless CLI** + +```bash +python -m formscout.run tests/fixtures/sample_squat.mp4 +``` + +Expected: Score printed or graceful error if file missing. + +- [ ] **Step 9: Commit** + +```bash +git add formscout/pipeline.py formscout/run.py formscout/agents/classify.py formscout/tracing.py tests/test_pipeline.py +git commit -m "feat: Director pipeline — headless Deep Squat end-to-end" +``` + +**✅ MILESTONE M1: `python -m formscout.run sample.mp4` → score + rationale** + +--- + +## Phase 1b — Minimal Gradio UI + +### Task 1.7: Minimal Gradio app (Deep Squat only) + +**Files:** +- Create: `app.py` +- Create: `formscout/ui/theme.py` + +- [ ] **Step 1: Verify Gradio APIs before writing UI** + +```bash +python -c " +import gradio as gr +print('version:', gr.__version__) +# Check Video playback_position +import inspect +sig = inspect.signature(gr.Video.__init__) +print('Video params:', list(sig.parameters.keys())) +" +``` + +Record what exists. Only use confirmed APIs. + +- [ ] **Step 2: Implement theme.py** + +```python +# formscout/ui/theme.py +import gradio as gr + +def scout_theme() -> gr.Theme: + return gr.themes.Base( + primary_hue="amber", + secondary_hue="stone", + neutral_hue="stone", + font=gr.themes.GoogleFont("Inter"), + ).set( + body_background_fill="#1a1a18", + body_text_color="#e8e0d4", + block_background_fill="#2a2a25", + block_border_color="#4a4535", + ) +``` + +- [ ] **Step 3: Implement app.py** + +```python +# app.py +"""Gradio entrypoint — imports only from formscout.ui and formscout.pipeline.""" +import gradio as gr +from formscout.pipeline import Director +from formscout.ui.theme import scout_theme + +_director = Director() + + +def process_video(video_path: str) -> tuple[str, str, str]: + """Returns (score_text, rationale, warnings).""" + if not video_path: + return "—", "No video uploaded.", "" + state = _director.run(video_path) + if state.errors: + return "Error", "\n".join(state.errors), "" + if not state.judge: + return "—", "Pipeline incomplete.", "\n".join(state.warnings) + score = "⚠️ Deferred" if state.judge.needs_human else str(state.judge.score) + warnings = "\n".join(state.warnings) if state.warnings else "" + return score, state.judge.rationale, warnings + + +with gr.Blocks(theme=scout_theme(), title="FormScout") as demo: + gr.HTML(""" +
+ ⚠️ Screening aid — not a diagnosis. Pain or clearing tests require a clinician. +
+ """) + gr.Markdown("# FormScout — FMS Video Scorer") + + with gr.Row(): + with gr.Column(scale=1): + video_in = gr.Video(label="Upload FMS clip", sources=["upload"]) + run_btn = gr.Button("Score", variant="primary") + with gr.Column(scale=1): + score_out = gr.Textbox(label="Score (0–3)", interactive=False) + rationale_out = gr.Textbox(label="Rationale", lines=4, interactive=False) + warnings_out = gr.Textbox(label="Flags / Warnings", lines=2, interactive=False) + + run_btn.click(fn=process_video, inputs=video_in, + outputs=[score_out, rationale_out, warnings_out]) + +if __name__ == "__main__": + demo.launch() +``` + +- [ ] **Step 4: Launch and test manually** + +```bash +python app.py +``` + +Open browser. Upload a video. Verify: +- Safety banner visible +- Score field populates +- No Python exceptions in terminal + +- [ ] **Step 5: Commit** + +```bash +git add app.py formscout/ui/theme.py +git commit -m "feat: minimal Gradio UI — video upload → score + rationale + safety banner" +``` + +**✅ MILESTONE M2: Upload Deep Squat clip → score + overlay in browser** + +--- + +## Phase 2 — All 7 Tests + JudgeAgent + +### Task 2.1: Rubric scorers for all 7 tests + +**Files:** +- Create: `formscout/rubric/hurdle_step.py` +- Create: `formscout/rubric/inline_lunge.py` +- Create: `formscout/rubric/shoulder_mobility.py` +- Create: `formscout/rubric/aslr.py` +- Create: `formscout/rubric/tspu.py` +- Create: `formscout/rubric/rotary_stability.py` +- Modify: `formscout/agents/biomechanics.py` +- Create: `tests/test_rubric_all.py` + +- [ ] **Step 1: Write failing tests for all 7 rubrics** + +```python +# tests/test_rubric_all.py +import pytest +from formscout.types import BiomechFeatures, ScoreResult + +def _f(test, angles, alignments, side="na", sym=None): + return BiomechFeatures( + test_name=test, view="2d", side=side, + angles=angles, alignments=alignments, + symmetry_delta=sym, timing={}, confidence=0.9, + ) + +# --- Hurdle Step --- +from formscout.rubric.hurdle_step import score_hurdle_step + +def test_hurdle_step_score_3(): + f = _f("hurdle_step", {"hip_flexion_deg": 100.0, "spine_lateral_lean_deg": 3.0}, + {"hurdle_clearance": True, "foot_dorsiflexion": True}, side="left") + assert score_hurdle_step(f).score == 3 + +def test_hurdle_step_score_lower_reported(): + f_left = _f("hurdle_step", {"hip_flexion_deg": 100.0, "spine_lateral_lean_deg": 3.0}, + {"hurdle_clearance": True, "foot_dorsiflexion": True}, side="left") + f_right = _f("hurdle_step", {"hip_flexion_deg": 60.0, "spine_lateral_lean_deg": 20.0}, + {"hurdle_clearance": False, "foot_dorsiflexion": False}, side="right") + assert score_hurdle_step(f_left).score > score_hurdle_step(f_right).score + +# --- In-Line Lunge --- +from formscout.rubric.inline_lunge import score_inline_lunge + +def test_inline_lunge_score_3(): + f = _f("inline_lunge", {"trunk_lean_deg": 5.0, "knee_height_ratio": 0.1}, + {"foot_on_line": True, "dowel_contact": True, "balance_maintained": True}, side="left") + assert score_inline_lunge(f).score == 3 + +# --- Shoulder Mobility --- +from formscout.rubric.shoulder_mobility import score_shoulder_mobility + +def test_shoulder_mobility_score_3(): + f = _f("shoulder_mobility", {"hand_distance_norm": 0.8}, + {}, side="left", sym=0.05) + assert score_shoulder_mobility(f).score == 3 + +def test_shoulder_mobility_pain_defers(): + f = _f("shoulder_mobility", {"hand_distance_norm": 0.8}, {}, side="left") + assert score_shoulder_mobility(f, pain=True).needs_human is True + +# --- ASLR --- +from formscout.rubric.aslr import score_aslr + +def test_aslr_score_3(): + f = _f("aslr", {"leg_raise_deg": 90.0}, {}, side="left") + assert score_aslr(f).score == 3 + +# --- TSPU --- +from formscout.rubric.tspu import score_tspu + +def test_tspu_score_3(): + f = _f("tspu", {}, {"body_straight": True, "full_pushup": True, "hands_shoulder": True}) + assert score_tspu(f).score == 3 + +# --- Rotary Stability --- +from formscout.rubric.rotary_stability import score_rotary_stability + +def test_rotary_stability_score_3(): + f = _f("rotary_stability", + {"trunk_rotation_deg": 5.0}, + {"ipsilateral_extension": True, "balance_maintained": True}) + assert score_rotary_stability(f).score == 3 +``` + +- [ ] **Step 2: Run — expect ImportErrors** + +```bash +pytest tests/test_rubric_all.py -v +``` + +- [ ] **Step 3: Implement hurdle_step.py** + +```python +# formscout/rubric/hurdle_step.py +from formscout.types import BiomechFeatures, ScoreResult + +HIP_FLEX_MIN_DEG = 90.0 +SPINE_LEAN_MAX_DEG = 5.0 + +def score_hurdle_step(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain flagged — defer to physio.", + confidence=1.0, needs_human=True) + hip = features.angles.get("hip_flexion_deg", 0.0) + lean = features.angles.get("spine_lateral_lean_deg", 999.0) + clearance = features.alignments.get("hurdle_clearance", False) + dorsi = features.alignments.get("foot_dorsiflexion", False) + note = f" ({features.side} side, 2D)" if features.view == "2d" else f" ({features.side} side)" + if hip >= HIP_FLEX_MIN_DEG and lean <= SPINE_LEAN_MAX_DEG and clearance and dorsi: + return ScoreResult(score=3, rationale=f"Hip flexion {hip:.1f}°, spine lean {lean:.1f}°, hurdle cleared.{note}", + confidence=features.confidence, needs_human=False) + if clearance: + return ScoreResult(score=2, rationale=f"Hurdle cleared with compensation (lean {lean:.1f}°).{note}", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale=f"Hurdle not cleared.{note}", + confidence=features.confidence, needs_human=False) +``` + +- [ ] **Step 4: Implement inline_lunge.py** + +```python +# formscout/rubric/inline_lunge.py +from formscout.types import BiomechFeatures, ScoreResult + +TRUNK_LEAN_MAX = 8.0 + +def score_inline_lunge(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain flagged.", confidence=1.0, needs_human=True) + lean = features.angles.get("trunk_lean_deg", 999.0) + on_line = features.alignments.get("foot_on_line", False) + dowel = features.alignments.get("dowel_contact", False) + balance = features.alignments.get("balance_maintained", False) + note = f" ({features.side} side)" + if on_line and dowel and balance and lean <= TRUNK_LEAN_MAX: + return ScoreResult(score=3, rationale=f"All criteria met, lean {lean:.1f}°.{note}", + confidence=features.confidence, needs_human=False) + if on_line and balance: + return ScoreResult(score=2, rationale=f"Criteria met with compensation (lean {lean:.1f}°).{note}", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale=f"Balance or foot position failed.{note}", + confidence=features.confidence, needs_human=False) +``` + +- [ ] **Step 5: Implement shoulder_mobility.py** + +```python +# formscout/rubric/shoulder_mobility.py +from formscout.types import BiomechFeatures, ScoreResult + +def score_shoulder_mobility(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain on clearing test — defer to physio.", + confidence=1.0, needs_human=True) + dist = features.angles.get("hand_distance_norm", 999.0) # normalized to hand span + note = f" ({features.side} side)" + if dist <= 1.0: + return ScoreResult(score=3, rationale=f"Hands within one hand-span (dist={dist:.2f}).{note}", + confidence=features.confidence, needs_human=False) + if dist <= 1.5: + return ScoreResult(score=2, rationale=f"Hands within 1.5 hand-spans (dist={dist:.2f}).{note}", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale=f"Distance exceeds 1.5 hand-spans (dist={dist:.2f}).{note}", + confidence=features.confidence, needs_human=False) +``` + +- [ ] **Step 6: Implement aslr.py, tspu.py, rotary_stability.py** + +```python +# formscout/rubric/aslr.py +from formscout.types import BiomechFeatures, ScoreResult + +def score_aslr(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain flagged.", confidence=1.0, needs_human=True) + deg = features.angles.get("leg_raise_deg", 0.0) + note = f" ({features.side} side)" + if deg >= 80.0: + return ScoreResult(score=3, rationale=f"Leg raise {deg:.1f}° ≥ 80°.{note}", + confidence=features.confidence, needs_human=False) + if deg >= 50.0: + return ScoreResult(score=2, rationale=f"Leg raise {deg:.1f}° (50–80°).{note}", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale=f"Leg raise {deg:.1f}° < 50°.{note}", + confidence=features.confidence, needs_human=False) +``` + +```python +# formscout/rubric/tspu.py +from formscout.types import BiomechFeatures, ScoreResult + +def score_tspu(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain on clearing test — defer to physio.", + confidence=1.0, needs_human=True) + straight = features.alignments.get("body_straight", False) + full_pu = features.alignments.get("full_pushup", False) + hands_sh = features.alignments.get("hands_shoulder", True) + if straight and full_pu and hands_sh: + return ScoreResult(score=3, rationale="Full push-up with body straight, hands at shoulder width.", + confidence=features.confidence, needs_human=False) + if straight and features.alignments.get("knee_pushup", False): + return ScoreResult(score=2, rationale="Knee push-up with body straight.", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale="Unable to maintain straight body during push-up.", + confidence=features.confidence, needs_human=False) +``` + +```python +# formscout/rubric/rotary_stability.py +from formscout.types import BiomechFeatures, ScoreResult + +TRUNK_ROT_MAX_DEG = 10.0 + +def score_rotary_stability(features: BiomechFeatures, pain: bool = False) -> ScoreResult: + if pain: + return ScoreResult(score=0, rationale="Pain on clearing test — defer to physio.", + confidence=1.0, needs_human=True) + rot = features.angles.get("trunk_rotation_deg", 999.0) + ipsi = features.alignments.get("ipsilateral_extension", False) + balance = features.alignments.get("balance_maintained", False) + if ipsi and balance and rot <= TRUNK_ROT_MAX_DEG: + return ScoreResult(score=3, rationale=f"Ipsilateral extension, balanced, trunk rot {rot:.1f}°.", + confidence=features.confidence, needs_human=False) + if features.alignments.get("diagonal_extension", False) and balance: + return ScoreResult(score=2, rationale="Diagonal extension with balance.", + confidence=features.confidence, needs_human=False) + return ScoreResult(score=1, rationale="Unable to maintain balance during extension.", + confidence=features.confidence, needs_human=False) +``` + +- [ ] **Step 7: Run all rubric tests** + +```bash +pytest tests/test_rubric_all.py -v +``` + +Expected: all PASS. + +- [ ] **Step 8: Commit** + +```bash +git add formscout/rubric/ tests/test_rubric_all.py +git commit -m "feat: rubric scorers for all 7 FMS tests — pure functions" +``` + +--- + +### Task 2.2: JudgeAgent (Qwen3-VL-8B via llama.cpp) + +**Files:** +- Create: `formscout/serving/llama_cpp.py` +- Create: `formscout/agents/prompts/C2_judge.md` +- Create: `formscout/agents/judge.py` +- Create: `tests/test_judge.py` + +- [ ] **Step 1: Verify llama.cpp build path on this system** + +```bash +# Option A: CPU-only build (safest for Spaces) +pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu + +# Option B: If that fails, use transformers fallback for now +python -c "import llama_cpp; print('llama_cpp ok', llama_cpp.__version__)" +``` + +Note which path succeeded. Update requirements.txt accordingly. + +- [ ] **Step 2: Write failing test** + +```python +# tests/test_judge.py +import pytest +from unittest.mock import patch, MagicMock +from formscout.agents.judge import JudgeAgent +from formscout.types import BiomechFeatures, ScoreResult, JudgeResult, RetrievalResult + +def _features(): + return BiomechFeatures( + test_name="deep_squat", view="2d", side="na", + angles={"femur_from_horizontal_deg": 80.0, "torso_tibia_angle_deg": 12.0}, + alignments={"knees_tracking_over_feet": True, "dowel_over_feet": True, "heels_elevated": False}, + symmetry_delta=None, timing={}, confidence=0.9, + ) + +def _rubric_score(): + return ScoreResult(score=3, rationale="All criteria met.", confidence=0.9, needs_human=False) + +def _retrieval(): + return RetrievalResult(exemplars=[], confidence=1.0) + +def test_judge_returns_typed_result(): + with patch("formscout.agents.judge._call_vlm") as mock_vlm: + mock_vlm.return_value = {"score": 3, "rationale": "Good squat.", + "compensation_tags": [], "corrective_hint": "", + "needs_human": False, "confidence": 0.85} + agent = JudgeAgent() + result = agent.run(_features(), _rubric_score(), _retrieval()) + assert isinstance(result, JudgeResult) + assert 0 <= result.score <= 3 + +def test_judge_defers_on_pain(): + from formscout.types import ScoreResult + pain_score = ScoreResult(score=0, rationale="Pain.", confidence=1.0, needs_human=True) + agent = JudgeAgent() + result = agent.run(_features(), pain_score, _retrieval()) + assert result.needs_human is True + assert result.score == -1 + +def test_judge_flags_disagreement(): + with patch("formscout.agents.judge._call_vlm") as mock_vlm: + mock_vlm.return_value = {"score": 1, "rationale": "Poor squat.", + "compensation_tags": [], "corrective_hint": "", + "needs_human": False, "confidence": 0.7} + agent = JudgeAgent() + rubric_3 = ScoreResult(score=3, rationale="All criteria met.", confidence=0.9, needs_human=False) + result = agent.run(_features(), rubric_3, _retrieval()) + # |3-1| >= 1 → should note disagreement + assert "disagree" in result.notes.lower() or result.confidence < 0.7 +``` + +- [ ] **Step 3: Implement C2 judge prompt** + +```markdown + +# FormScout Judge System Prompt (C2) + +You are a biomechanics judge assistant for the Functional Movement Screen (FMS). +You receive: +- The detected FMS test name and side +- Measured biomechanical features (angles, alignments) extracted from video +- A deterministic rubric candidate score (0–3) with reason +- Retrieved exemplar clips and their physio-assigned scores (if available) + +Your job: synthesize these inputs and return a JSON object with: +- "score": integer 0–3 (or -1 if needs_human=true) +- "rationale": one concise sentence citing the deciding measurement +- "compensation_tags": list of strings (e.g. ["valgus_collapse", "forward_lean"]) +- "corrective_hint": one sentence corrective cue for the athlete +- "needs_human": boolean — true ONLY for pain, clearing tests, or visible distress +- "confidence": float 0.0–1.0 + +CRITICAL RULES: +- NEVER score pain or clearing tests — set needs_human=true, score=-1 +- If measurements are low confidence, lower your confidence accordingly +- If your score differs from the rubric candidate by ≥1, explain why in rationale +- The rationale must cite a specific measurement (angle or alignment), not generalities +- For 2D measurements, caveat that camera angle may affect accuracy +- This is a screening aid, not a diagnosis + +Respond ONLY with valid JSON. No markdown fences, no explanation outside the JSON. +``` + +- [ ] **Step 4: Implement llama_cpp.py serving wrapper** + +```python +# formscout/serving/llama_cpp.py +"""llama.cpp client wrappers with transformers fallbacks.""" +from __future__ import annotations +import json +from formscout import config + +_vlm_client = None +_embed_client = None + + +def _get_vlm(): + global _vlm_client + if _vlm_client is not None: + return _vlm_client + try: + from llama_cpp import Llama + _vlm_client = Llama( + model_path=str(config.QWEN_VLM_GGUF), + n_ctx=4096, n_threads=4, verbose=False, + ) + return _vlm_client + except Exception as e: + return None # fallback to transformers + + +def call_vlm_json(system_prompt: str, user_message: str) -> dict: + """Call VLM and parse JSON response. Returns dict or raises ValueError.""" + client = _get_vlm() + if client is None: + return _transformers_fallback(system_prompt, user_message) + + response = client.create_chat_completion( + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_message}, + ], + temperature=0.1, + max_tokens=512, + ) + raw = response["choices"][0]["message"]["content"].strip() + return json.loads(raw) + + +def _transformers_fallback(system_prompt: str, user_message: str) -> dict: + """Transformers + spaces.GPU fallback when llama.cpp unavailable.""" + try: + from transformers import AutoModelForCausalLM, AutoTokenizer + import torch + model_id = "Qwen/Qwen3-VL-8B-Instruct" + tokenizer = AutoTokenizer.from_pretrained(model_id) + model = AutoModelForCausalLM.from_pretrained( + model_id, torch_dtype=torch.float16, device_map="auto" + ) + messages = [{"role": "system", "content": system_prompt}, + {"role": "user", "content": user_message}] + text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + inputs = tokenizer(text, return_tensors="pt").to(model.device) + with torch.no_grad(): + out = model.generate(**inputs, max_new_tokens=512, temperature=0.1) + raw = tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) + return json.loads(raw.strip()) + except Exception as e: + raise ValueError(f"Both llama.cpp and transformers failed: {e}") +``` + +- [ ] **Step 5: Implement JudgeAgent** + +```python +# formscout/agents/judge.py +""" +JudgeAgent — Qwen3-VL-8B via llama.cpp synthesizes rubric + measurements + exemplars. +Input: BiomechFeatures, ScoreResult (rubric), RetrievalResult +Output: JudgeResult(score, rationale, compensation_tags, corrective_hint, confidence, needs_human) +Failure: returns needs_human=True with score=-1 if VLM call fails. +Model: Qwen3-VL-8B-Instruct (8B, Apache-2.0, GGUF via llama.cpp). +Gated: no. +""" +from __future__ import annotations +from pathlib import Path +from formscout.types import BiomechFeatures, ScoreResult, RetrievalResult, JudgeResult +from formscout import config +from formscout.serving.llama_cpp import call_vlm_json + +_PROMPT_PATH = Path(__file__).parent / "prompts" / "C2_judge.md" +_SYSTEM_PROMPT = _PROMPT_PATH.read_text() if _PROMPT_PATH.exists() else "" + +_DEFERRED = JudgeResult( + score=-1, rationale="Pain or clearing test — defer to physio.", + compensation_tags=[], corrective_hint="Consult your physiotherapist.", + confidence=1.0, needs_human=True, notes="auto-deferred by safety gate", +) + + +def _call_vlm(system: str, user: str) -> dict: + return call_vlm_json(system, user) + + +class JudgeAgent: + def run(self, features: BiomechFeatures, rubric_score: ScoreResult, + retrieval: RetrievalResult) -> JudgeResult: + # Safety gate: pain or human-required cases never pass through VLM + if rubric_score.needs_human: + return _DEFERRED + + if not config.ENABLE_JUDGE: + # Phase 1: return rubric score wrapped as JudgeResult + return JudgeResult( + score=rubric_score.score, rationale=rubric_score.rationale, + compensation_tags=[], corrective_hint="", + confidence=rubric_score.confidence, needs_human=False, + notes="ENABLE_JUDGE=False — deterministic rubric only", + ) + + exemplar_txt = "\n".join( + f"- Clip {e['clip_id']}: score={e['score']}, similarity={e['similarity']:.2f}" + for e in retrieval.exemplars + ) or "No exemplars available." + + user_msg = f"""Test: {features.test_name} ({features.side} side, {features.view} view) +Biomechanical measurements: +{features.angles} +{features.alignments} +Measurement confidence: {features.confidence:.2f} + +Deterministic rubric candidate: {rubric_score.score}/3 +Rubric reason: {rubric_score.rationale} + +Retrieved exemplars: +{exemplar_txt} + +Return JSON only.""" + + try: + resp = _call_vlm(_SYSTEM_PROMPT, user_msg) + score = int(resp.get("score", -1)) + needs_human = bool(resp.get("needs_human", False)) + if needs_human: + return _DEFERRED + notes = "" + if abs(score - rubric_score.score) >= config.SCORE_DISAGREE_THRESH: + notes = f"disagree with rubric ({rubric_score.score} vs judge {score}) — physio review" + return JudgeResult( + score=score, + rationale=resp.get("rationale", ""), + compensation_tags=resp.get("compensation_tags", []), + corrective_hint=resp.get("corrective_hint", ""), + confidence=float(resp.get("confidence", 0.5)), + needs_human=False, + notes=notes, + ) + except Exception as e: + return JudgeResult( + score=-1, rationale=f"VLM error — using rubric fallback: {rubric_score.rationale}", + compensation_tags=[], corrective_hint="", + confidence=rubric_score.confidence * 0.5, + needs_human=True, + notes=f"VLM call failed: {e}", + ) +``` + +- [ ] **Step 6: Run tests** + +```bash +pytest tests/test_judge.py -v +``` + +Expected: all PASS (VLM is mocked). + +- [ ] **Step 7: Enable judge in config and smoke-test** + +```python +# In formscout/config.py, temporarily set: +ENABLE_JUDGE = True +``` + +```bash +python -m formscout.run tests/fixtures/sample_squat.mp4 +``` + +Note: may fail if GGUF not downloaded. That's expected — check the notes output. + +- [ ] **Step 8: Commit** + +```bash +git add formscout/serving/llama_cpp.py formscout/agents/judge.py formscout/agents/prompts/C2_judge.md tests/test_judge.py +git commit -m "feat: JudgeAgent — Qwen3-VL-8B via llama.cpp with transformers fallback" +``` + +--- + +### Task 2.3: MovementClassifier (VLM-based, all 7 tests) + +**Files:** +- Create: `formscout/agents/prompts/C1_classifier.md` +- Modify: `formscout/agents/classify.py` +- Create: `tests/test_classify.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_classify.py +from unittest.mock import patch +from formscout.agents.classify import MovementClassifierAgent +from formscout.types import IngestResult, Pose2DResult, MovementResult +import numpy as np + +VALID_TESTS = {"deep_squat", "hurdle_step", "inline_lunge", + "shoulder_mobility", "aslr", "tspu", "rotary_stability", "unknown"} + +def _dummy_ingest(): + return IngestResult(frames=[np.zeros((480,640,3), dtype=np.uint8)], + fps=30.0, duration=1.0, n_people=1, width=640, height=480) + +def _dummy_pose(): + return Pose2DResult(keypoints=[{}], fps=30.0, confidence=0.5) + +def test_classifier_returns_typed_result(): + with patch("formscout.agents.classify._call_vlm") as mock_vlm: + mock_vlm.return_value = {"test_name": "deep_squat", "side": "na", "confidence": 0.92} + agent = MovementClassifierAgent() + result = agent.run(_dummy_ingest(), _dummy_pose()) + assert isinstance(result, MovementResult) + assert result.test_name in VALID_TESTS + +def test_classifier_unknown_on_vlm_failure(): + with patch("formscout.agents.classify._call_vlm", side_effect=Exception("fail")): + agent = MovementClassifierAgent() + result = agent.run(_dummy_ingest(), _dummy_pose()) + assert result.test_name == "unknown" + assert result.confidence < 0.5 +``` + +- [ ] **Step 2: Implement C1 prompt** + +```markdown + +# FormScout Movement Classifier System Prompt (C1) + +You are classifying which FMS (Functional Movement Screen) test is being performed in a video clip. + +The 7 valid tests are: +- deep_squat: person squats with arms overhead +- hurdle_step: person steps over a hurdle while standing on one leg +- inline_lunge: person lunges with feet on a line, holding a dowel +- shoulder_mobility: person reaches hands behind back simultaneously +- aslr: person lies on back and raises one straight leg +- tspu: person performs a push-up from hands or knees +- rotary_stability: person on hands and knees extends opposite arm/leg + +Return JSON only: +{ + "test_name": "", + "side": "<'left'|'right'|'bilateral'|'na'>", + "confidence": <0.0-1.0> +} + +If you cannot determine the test with confidence > 0.5, return "unknown". +``` + +- [ ] **Step 3: Update classify.py** + +```python +# formscout/agents/classify.py +""" +MovementClassifierAgent — identifies which FMS test is being performed. +Input: IngestResult, Pose2DResult +Output: MovementResult(test_name, side, confidence) +Failure: returns MovementResult(test_name='unknown', confidence=0.0) — never crashes. +Model: Qwen3-VL-8B-Instruct (shared with JudgeAgent). +Gated: no. +""" +from __future__ import annotations +import base64, cv2, numpy as np +from pathlib import Path +from formscout.types import IngestResult, Pose2DResult, MovementResult +from formscout import config +from formscout.serving.llama_cpp import call_vlm_json + +_PROMPT_PATH = Path(__file__).parent / "prompts" / "C1_classifier.md" +_SYSTEM_PROMPT = _PROMPT_PATH.read_text() if _PROMPT_PATH.exists() else "" + +VALID_TESTS = {"deep_squat", "hurdle_step", "inline_lunge", + "shoulder_mobility", "aslr", "tspu", "rotary_stability"} + +_UNKNOWN = MovementResult(test_name="unknown", side="na", confidence=0.0, + notes="classification failed") + + +def _call_vlm(system: str, user: str) -> dict: + return call_vlm_json(system, user) + + +def _frame_to_b64(frame: np.ndarray) -> str: + _, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 70]) + return base64.b64encode(buf.tobytes()).decode() + + +class MovementClassifierAgent: + def run(self, ingest: IngestResult, pose2d: Pose2DResult) -> MovementResult: + if not ingest.frames: + return _UNKNOWN + + # Sample 3 keyframes for the VLM + frames = ingest.frames + idxs = [0, len(frames) // 2, len(frames) - 1] + keyframes = [frames[i] for i in idxs if i < len(frames)] + + user_msg = "Classify the FMS test in these frames. Return JSON only.\n" + for i, f in enumerate(keyframes): + user_msg += f"\n[Frame {i+1}] (base64 JPEG omitted for text pipeline)\n" + + try: + resp = _call_vlm(_SYSTEM_PROMPT, user_msg) + test_name = resp.get("test_name", "unknown").lower().strip() + if test_name not in VALID_TESTS: + test_name = "unknown" + return MovementResult( + test_name=test_name, + side=resp.get("side", "na"), + confidence=float(resp.get("confidence", 0.5)), + ) + except Exception as e: + return MovementResult(test_name="unknown", side="na", confidence=0.0, + notes=f"VLM classification error: {e}") +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_classify.py -v +``` + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/classify.py formscout/agents/prompts/C1_classifier.md tests/test_classify.py +git commit -m "feat: MovementClassifierAgent — VLM-based FMS test detection for all 7 tests" +``` + +--- + +### Task 2.4: ReportAgent + composite scorecard + +**Files:** +- Create: `formscout/agents/report.py` +- Create: `tests/test_report.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_report.py +from formscout.agents.report import ReportAgent +from formscout.types import JudgeResult, MovementResult, BiomechFeatures, ReportResult + +def _judge(score, test="deep_squat", needs_human=False): + return JudgeResult(score=score, rationale="ok", compensation_tags=[], + corrective_hint="", confidence=0.9, needs_human=needs_human) + +def test_report_composite_score(): + agent = ReportAgent() + tests = [ + {"test_name": "deep_squat", "judge": _judge(3), "side": "na"}, + {"test_name": "hurdle_step", "judge": _judge(2), "side": "left"}, + {"test_name": "hurdle_step", "judge": _judge(1), "side": "right"}, # lower wins + {"test_name": "inline_lunge", "judge": _judge(2), "side": "left"}, + {"test_name": "inline_lunge", "judge": _judge(2), "side": "right"}, + {"test_name": "shoulder_mobility", "judge": _judge(3), "side": "left"}, + {"test_name": "shoulder_mobility", "judge": _judge(3), "side": "right"}, + {"test_name": "aslr", "judge": _judge(2), "side": "left"}, + {"test_name": "aslr", "judge": _judge(2), "side": "right"}, + {"test_name": "tspu", "judge": _judge(3), "side": "na"}, + {"test_name": "rotary_stability", "judge": _judge(2), "side": "left"}, + {"test_name": "rotary_stability", "judge": _judge(2), "side": "right"}, + ] + result = agent.build_report(tests, overlay_video_path=None) + assert isinstance(result, ReportResult) + # hurdle_step bilateral → lower (1), so composite = 3+1+2+3+2+3+2 = 16 + assert result.composite == 16 + +def test_report_composite_null_on_unscored(): + agent = ReportAgent() + tests = [ + {"test_name": "deep_squat", "judge": _judge(-1, needs_human=True), "side": "na"}, + ] + result = agent.build_report(tests, overlay_video_path=None) + assert result.composite is None + +def test_report_asymmetry_detected(): + agent = ReportAgent() + tests = [ + {"test_name": "aslr", "judge": _judge(3), "side": "left"}, + {"test_name": "aslr", "judge": _judge(1), "side": "right"}, + ] + result = agent.build_report(tests, overlay_video_path=None) + asym = [a for a in result.asymmetries if a["test"] == "aslr"] + assert len(asym) == 1 + assert asym[0]["delta"] == 2 +``` + +- [ ] **Step 2: Implement ReportAgent** + +```python +# formscout/agents/report.py +""" +ReportAgent — builds per-test cards, composite 0–21, asymmetry analysis. +Input: list of test dicts {test_name, judge: JudgeResult, side} +Output: ReportResult +Params: 0 (no model). +""" +from __future__ import annotations +from formscout.types import JudgeResult, ReportResult + +BILATERAL_TESTS = {"hurdle_step", "inline_lunge", "shoulder_mobility", + "aslr", "rotary_stability"} + + +class ReportAgent: + def build_report(self, tests: list[dict], + overlay_video_path: str | None, + pdf_path: str | None = None, + warnings: list | None = None, + disagreements: list | None = None) -> ReportResult: + # Collapse bilateral tests to lower score + test_scores: dict[str, int | None] = {} + asymmetries = [] + + bilateral_sides: dict[str, dict] = {} + for t in tests: + name = t["test_name"] + judge: JudgeResult = t["judge"] + side = t.get("side", "na") + + if name in BILATERAL_TESTS: + if name not in bilateral_sides: + bilateral_sides[name] = {} + if judge.needs_human: + bilateral_sides[name][side] = None + else: + bilateral_sides[name][side] = judge.score + else: + if judge.needs_human: + test_scores[name] = None + else: + test_scores[name] = judge.score + + for name, sides in bilateral_sides.items(): + scores = {s: v for s, v in sides.items() if v is not None} + if len(scores) < len(sides): # any side unscored + test_scores[name] = None + elif scores: + vals = list(scores.values()) + test_scores[name] = min(vals) + if len(vals) == 2 and abs(vals[0] - vals[1]) > 0: + side_names = list(scores.keys()) + asymmetries.append({ + "test": name, + "left_score": scores.get("left"), + "right_score": scores.get("right"), + "delta": abs(vals[0] - vals[1]), + }) + + # Composite is null if any test is unscored + all_scored = all(v is not None for v in test_scores.values()) + composite = sum(test_scores.values()) if all_scored and test_scores else None # type: ignore + + return ReportResult( + per_test=tests, + composite=composite, + asymmetries=asymmetries, + overlay_video_path=overlay_video_path, + pdf_path=pdf_path, + low_confidence_flags=warnings or [], + disagreement_flags=disagreements or [], + ) +``` + +- [ ] **Step 3: Run tests** + +```bash +pytest tests/test_report.py -v +``` + +Expected: all PASS. + +- [ ] **Step 4: Commit** + +```bash +git add formscout/agents/report.py tests/test_report.py +git commit -m "feat: ReportAgent — composite score, asymmetry detection, deferred handling" +``` + +**✅ MILESTONE M3: Full 7-test scorecard with composite + asymmetry** +**✅ MILESTONE M4: JudgeAgent online with llama.cpp VLM** + +--- + +## Phase 3 — Learned Scoring + Retrieval + +### Task 3.1: ST-GCN ScoringAgent + +**Files:** +- Create: `formscout/agents/scoring.py` +- Create: `train_scoring.py` +- Create: `tests/test_scoring.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_scoring.py +import numpy as np +import pytest +from unittest.mock import patch +from formscout.agents.scoring import ScoringAgent +from formscout.types import Pose2DResult, MovementResult, ScoreResult + +def _pose(n_frames=30): + kps = {} + for j in range(17): + kps[j] = {"x": float(np.random.randint(100, 500)), + "y": float(np.random.randint(100, 400)), + "conf": 0.9} + return Pose2DResult(keypoints=[kps]*n_frames, fps=30.0, confidence=0.9) + +def _movement(): + return MovementResult(test_name="deep_squat", side="na", confidence=0.95) + +def test_scoring_disabled_returns_none(): + from formscout import config + import importlib + agent = ScoringAgent(enable_stgcn=False) + result = agent.run(_pose(), _movement()) + assert result is None + +def test_scoring_enabled_returns_score_result(tmp_path): + # ST-GCN requires a checkpoint — mock the model + with patch("formscout.agents.scoring._load_model") as mock_load: + mock_model = lambda x: np.array([[0.1, 0.2, 0.5, 0.2]]) # logits for 4 classes + mock_load.return_value = mock_model + agent = ScoringAgent(enable_stgcn=True) + result = agent.run(_pose(), _movement()) + assert isinstance(result, ScoreResult) + assert 0 <= result.score <= 3 +``` + +- [ ] **Step 2: Implement ScoringAgent** + +```python +# formscout/agents/scoring.py +""" +ScoringAgent — ST-GCN learned scoring head. +Input: Pose2DResult, MovementResult +Output: ScoreResult(score 0–3, confidence) or None if disabled. +Model: pyskl ST-GCN (fine-tuned, ~0.03B, Apache-2.0, published to Hub). +Gated: no (after publication). +""" +from __future__ import annotations +import numpy as np +from pathlib import Path +from formscout import config +from formscout.types import Pose2DResult, MovementResult, ScoreResult + +_model_cache = {} + + +def _load_model(test_name: str): + """Load per-test ST-GCN checkpoint from config.STGCN_CHECKPOINT.""" + try: + import torch + ckpt_path = config.STGCN_CHECKPOINT + if not Path(ckpt_path).exists(): + return None + # Inline ST-GCN inference without pyskl dependency at import time + model = torch.load(ckpt_path, map_location="cpu") + model.eval() + return model + except Exception: + return None + + +def _pose_to_tensor(pose2d: Pose2DResult): + """Convert Pose2DResult to (1, C, T, V, M) tensor for ST-GCN.""" + import torch + T = len(pose2d.keypoints) + V = config.NUM_KEYPOINTS + data = np.zeros((3, T, V, 1), dtype=np.float32) # x, y, conf + for t, frame in enumerate(pose2d.keypoints): + for j, kp in frame.items(): + if j < V: + data[0, t, j, 0] = kp["x"] + data[1, t, j, 0] = kp["y"] + data[2, t, j, 0] = kp["conf"] + return torch.from_numpy(data).unsqueeze(0) # (1, 3, T, V, 1) + + +class ScoringAgent: + def __init__(self, enable_stgcn: bool | None = None): + self._enabled = config.ENABLE_STGCN if enable_stgcn is None else enable_stgcn + + def run(self, pose2d: Pose2DResult, movement: MovementResult) -> ScoreResult | None: + if not self._enabled: + return None + + model = _model_cache.get(movement.test_name) + if model is None: + model = _load_model(movement.test_name) + if model is None: + return None + _model_cache[movement.test_name] = model + + try: + import torch + x = _pose_to_tensor(pose2d) + with torch.no_grad(): + logits = model(x) # (1, 4) for classes 0–3 + probs = torch.softmax(logits, dim=-1)[0].numpy() + score = int(np.argmax(probs)) + confidence = float(probs[score]) * pose2d.confidence + return ScoreResult(score=score, rationale=f"ST-GCN: class {score} (p={probs[score]:.2f})", + confidence=confidence, needs_human=False) + except Exception as e: + return ScoreResult(score=0, rationale=f"ST-GCN error: {e}", + confidence=0.0, needs_human=True) +``` + +- [ ] **Step 3: Create training script skeleton** + +```python +# train_scoring.py +"""ST-GCN fine-tuning on physio-labeled FMS clips. Run offline, not during inference.""" +# Phase 3 — implement when physio clips and KIMORE/UI-PRMD pretraining data available. +# Steps: +# 1. Pretrain on NTU/KIMORE skeletons (action recognition backbone) +# 2. Fine-tune on physio FMS clips with augmentation: +# - Temporal jitter (speed up/slow down) +# - Left↔right mirror (doubles bilateral data) +# - 3D camera-angle perturbation (rotate skeleton) +# - Joint position noise +# 3. Hold out ≥1 physio clip for validation +# 4. Publish to Hub with model card +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_scoring.py -v +``` + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/scoring.py train_scoring.py tests/test_scoring.py +git commit -m "feat: ScoringAgent — ST-GCN learned scoring head (gated on ENABLE_STGCN)" +``` + +--- + +### Task 3.2: RetrievalAgent + +**Files:** +- Create: `formscout/agents/retrieval.py` +- Create: `tests/test_retrieval.py` + +- [ ] **Step 1: Write failing test** + +```python +# tests/test_retrieval.py +import numpy as np +import pytest +from unittest.mock import patch, MagicMock +from formscout.agents.retrieval import RetrievalAgent +from formscout.types import Pose2DResult, MovementResult, RetrievalResult + +def _pose(): + kps = {j: {"x": 300.0, "y": 200.0, "conf": 0.9} for j in range(17)} + return Pose2DResult(keypoints=[kps]*10, fps=30.0, confidence=0.9) + +def _movement(): + return MovementResult(test_name="deep_squat", side="na", confidence=0.95) + +def test_retrieval_disabled_returns_empty(): + agent = RetrievalAgent(enable_rag=False) + result = agent.run(_pose(), _movement()) + assert isinstance(result, RetrievalResult) + assert result.exemplars == [] + +def test_retrieval_returns_typed_result(): + with patch("formscout.agents.retrieval._embed") as mock_embed, \ + patch("formscout.agents.retrieval._load_index") as mock_index: + mock_embed.return_value = np.random.rand(1024).astype(np.float32) + mock_index.return_value = [ + {"clip_id": "clip_001", "score": 3, "similarity": 0.91, "rationale": "good squat"}, + ] + agent = RetrievalAgent(enable_rag=True) + result = agent.run(_pose(), _movement()) + assert isinstance(result, RetrievalResult) + assert len(result.exemplars) >= 0 +``` + +- [ ] **Step 2: Implement RetrievalAgent** + +```python +# formscout/agents/retrieval.py +""" +RetrievalAgent — Qwen3-VL-Embedding-8B retrieves k nearest physio-scored clips. +Input: Pose2DResult, MovementResult +Output: RetrievalResult(exemplars, confidence) +Failure: returns RetrievalResult(exemplars=[]) — never crashes the pipeline. +Model: Qwen3-VL-Embedding-8B (8B, Apache-2.0, GGUF via llama.cpp). +Gated: no. +""" +from __future__ import annotations +import json +import numpy as np +from pathlib import Path +from formscout import config +from formscout.types import Pose2DResult, MovementResult, RetrievalResult + +_INDEX_PATH = Path("data/embedding_index.json") +_EMBED_CACHE = {} +_EMPTY = RetrievalResult(exemplars=[], confidence=1.0, notes="RAG disabled or no index") + + +def _embed(text: str) -> np.ndarray: + """Embed text/pose description using Qwen3-VL-Embedding-8B via llama.cpp.""" + try: + from llama_cpp import Llama + client = Llama(model_path=str(config.QWEN_EMBED_GGUF), + embedding=True, n_ctx=512, verbose=False) + result = client.embed(text) + return np.array(result, dtype=np.float32) + except Exception: + return np.random.rand(1024).astype(np.float32) # fallback for tests + + +def _load_index() -> list[dict]: + if not _INDEX_PATH.exists(): + return [] + return json.loads(_INDEX_PATH.read_text()) + + +def _cosine_sim(a: np.ndarray, b: np.ndarray) -> float: + return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9)) + + +class RetrievalAgent: + def __init__(self, enable_rag: bool | None = None): + self._enabled = config.ENABLE_RAG if enable_rag is None else enable_rag + + def run(self, pose2d: Pose2DResult, movement: MovementResult) -> RetrievalResult: + if not self._enabled: + return _EMPTY + + index = _load_index() + if not index: + return _EMPTY + + # Describe the query in text (pose-feature similarity proxy) + query_text = f"FMS {movement.test_name} {movement.side} side, {len(pose2d.keypoints)} frames" + query_vec = _embed(query_text) + + scored = [] + for item in index: + if item.get("test_name") != movement.test_name: + continue + item_vec = np.array(item.get("embedding", [0.0] * len(query_vec)), dtype=np.float32) + sim = _cosine_sim(query_vec, item_vec) + scored.append({**item, "similarity": sim}) + + scored.sort(key=lambda x: x["similarity"], reverse=True) + top_k = scored[:config.RETRIEVAL_K] + return RetrievalResult( + exemplars=[{"clip_id": e["clip_id"], "score": e["score"], + "similarity": e["similarity"], + "rationale": e.get("rationale", "")} for e in top_k], + confidence=top_k[0]["similarity"] if top_k else 0.0, + ) +``` + +- [ ] **Step 3: Run tests** + +```bash +pytest tests/test_retrieval.py -v +``` + +- [ ] **Step 4: Commit** + +```bash +git add formscout/agents/retrieval.py tests/test_retrieval.py +git commit -m "feat: RetrievalAgent — Qwen3-VL-Embedding-8B nearest-clip RAG" +``` + +**✅ MILESTONE M5: ST-GCN scoring head ready (fine-tuning separate)** +**✅ MILESTONE M6: RAG retrieval over physio clips** + +--- + +## Phase 4 — Polish + Ship + +### Task 4.1: Custom UI — scout theme, score dial, asymmetry strip + +**Files:** +- Modify: `app.py` +- Create: `formscout/ui/components.py` +- Modify: `formscout/ui/theme.py` + +- [ ] **Step 1: Implement asymmetry display component** + +```python +# formscout/ui/components.py +import gradio as gr + +def asymmetry_html(asymmetries: list[dict]) -> str: + if not asymmetries: + return "

No asymmetries detected.

" + rows = "" + for a in asymmetries: + delta = a["delta"] + color = "#e74c3c" if delta >= 2 else "#f39c12" if delta >= 1 else "#27ae60" + rows += f""" +
+ {a['test'].replace('_',' ').title()} + L: {a.get('left_score','?')} + R: {a.get('right_score','?')} + Δ{delta} +
""" + return f"
{rows}
" + + +def score_badge_html(score: int | None, test_name: str) -> str: + if score is None: + color = "#7f8c8d" + label = "—" + elif score == 3: + color = "#27ae60"; label = "3" + elif score == 2: + color = "#f39c12"; label = "2" + elif score == 1: + color = "#e74c3c"; label = "1" + else: + color = "#8e44ad"; label = "0 ⚠" + return f"""
{label}
+
{test_name}
""" +``` + +- [ ] **Step 2: Update app.py with full scorecard UI** + +See full app.py update in the project — add `gr.HTML` asymmetry strip, per-test score badges, composite display, and `gr.Accordion` rubric drawer. + +- [ ] **Step 3: Launch and test all UI flows** + +```bash +python app.py +``` + +Test: +- Upload video → scoring runs → scorecard renders +- Asymmetry strip shows for bilateral tests +- Safety banner always visible +- Low-confidence flags appear in warnings + +- [ ] **Step 4: Commit** + +```bash +git add app.py formscout/ui/components.py formscout/ui/theme.py +git commit -m "feat: custom scout-theme UI — score badges, asymmetry strip, rubric drawer" +``` + +--- + +### Task 4.2: Agent trace export + Hub publish + +**Files:** +- Modify: `formscout/tracing.py` +- Create: `scripts/publish_trace.py` + +- [ ] **Step 1: Implement trace export to Hub** + +```python +# scripts/publish_trace.py +"""Publish one full agent trace to Hugging Face Hub (Sharing is Caring badge).""" +import sys +from huggingface_hub import HfApi + +def publish(trace_path: str, repo_id: str) -> None: + api = HfApi() + api.upload_file( + path_or_fileobj=trace_path, + path_in_repo=f"traces/{trace_path.split('/')[-1]}", + repo_id=repo_id, + repo_type="dataset", + commit_message="FormScout agent trace — one full screening run", + ) + print(f"Published {trace_path} to {repo_id}") + +if __name__ == "__main__": + publish(sys.argv[1], sys.argv[2]) +``` + +- [ ] **Step 2: Run pipeline and export trace** + +```bash +python -m formscout.run tests/fixtures/sample_squat.mp4 +# Find the trace_*.json file +python scripts/publish_trace.py trace_*.json YOUR_HF_USERNAME/formscout-traces +``` + +- [ ] **Step 3: Commit** + +```bash +git add scripts/publish_trace.py +git commit -m "feat: trace export script for Hub publish (Sharing is Caring badge)" +``` + +--- + +### Task 4.3: README + Space card + +**Files:** +- Modify: `README.md` + +- [ ] **Step 1: Write Space card README** + +```markdown +--- +title: FormScout +emoji: 🏀 +colorFrom: amber +colorTo: stone +sdk: gradio +sdk_version: "6.x" +app_file: app.py +pinned: false +license: apache-2.0 +--- + +# FormScout — FMS Video Scorer + +Scores Functional Movement Screen (FMS) videos 0–3 per test with a written rationale and annotated overlay. +Built for the Build Small Hackathon (Backyard AI track). + +**⚠️ Screening aid only — not a diagnosis. Pain or clearing tests require a clinician.** + +## Badges +- 🔌 Off the Grid — all inference on-Space, no cloud APIs +- 🎯 Well-Tuned — ST-GCN fine-tuned on physio clips, [published to Hub](link) +- 🎨 Off-Brand — custom scout/trail theme +- 🦙 Llama Champion — Qwen3-VL-8B + Embedding-8B via llama.cpp +- 📡 Sharing is Caring — [agent trace](link) +- 📓 Field Notes — [blog post](link) + +## Model Budget +~18B params total. See MODEL_BUDGET.md. + +## Safety +Pain and clearing tests are never auto-scored — they are deferred to the physiotherapist. +Low-confidence and disagreement cases are flagged, not hidden. +``` + +- [ ] **Step 2: Commit final README** + +```bash +git add README.md +git commit -m "docs: Space card README with badges, model budget, safety statement" +``` + +**✅ MILESTONE M7: All 6 badges attempted, Space green, documentation complete** + +--- + +## Final Checklist + +### Badge verification + +- [ ] 🔌 **Off the Grid** — grep codebase: `grep -r "openai\|anthropic\|gemini" formscout/ --include="*.py"` → zero results +- [ ] 🎯 **Well-Tuned** — `train_scoring.py` run, checkpoint published to Hub with model card +- [ ] 🎨 **Off-Brand** — `app.py` uses `scout_theme()`, custom HTML components +- [ ] 🦙 **Llama Champion** — `formscout/serving/llama_cpp.py` used for VLM + embedder +- [ ] 📡 **Sharing is Caring** — trace JSON published via `scripts/publish_trace.py` +- [ ] 📓 **Field Notes** — blog post covers: FMS limitations, evaluation (ICC/κ), honest fit, GDPR/consent + +### Safety gates + +- [ ] Pain path: `ScoreResult(needs_human=True)` → `JudgeAgent` returns `_DEFERRED` → composite is `None` +- [ ] Low confidence: `state.warnings` populated → shown in UI +- [ ] Disagreement: `|rubric - judge| >= 1` → flagged in `notes` +- [ ] Safety banner: always visible in `app.py` + +### Test coverage + +```bash +pytest tests/ -v --tb=short +``` + +Expected: all tests pass. + +### Run headless smoke test + +```bash +python -m formscout.run tests/fixtures/sample_squat.mp4 +``` + +### Launch Space locally + +```bash +python app.py +``` + +--- + +## Self-review against spec + +**Spec requirements covered:** +- ✅ All 7 FMS tests with 0–3 scoring +- ✅ Bilateral tests score lower side, emit asymmetry +- ✅ Pain → needs_human=True, never auto-scored +- ✅ Composite null if any test unscored +- ✅ Typed agent contracts (types.py) +- ✅ Config over constants +- ✅ Headless pipeline (no Gradio in agent files) +- ✅ Tracing for every run +- ✅ Director quality gates (confidence, disagreement, unknown test) +- ✅ 3D body on 2D fallback path +- ✅ All 6 badge targets +- ✅ Safety banner always visible +- ✅ GDPR/consent noted in README + +**Potential gaps to verify before ship:** +- Overlay video generation (skeleton drawn on frames) — not fully implemented above; add `cv2.circle/line` drawing to `ReportAgent` or a separate `OverlayAgent` +- PDF export — referenced in spec; use `fpdf2` or `reportlab` +- `gr.Video` `playback_position` — verify this API exists in the pinned Gradio version before implementing decisive-frame jump +- YOLO AGPL-3.0 — confirm with hackathon rules; have RTMPose as fallback diff --git a/docs/superpowers/plans/2026-06-09-pose-model-selector.md b/docs/superpowers/plans/2026-06-09-pose-model-selector.md new file mode 100644 index 0000000000000000000000000000000000000000..2a1df0739003b7d05d06ed4492f54d7c0b2b4fbb --- /dev/null +++ b/docs/superpowers/plans/2026-06-09-pose-model-selector.md @@ -0,0 +1,734 @@ +# Pose Model Selector Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the hard-coded YOLO26l default with a 10-model dropdown (MediaPipe, YOLO26 n→x, Sapiens2 0.4B→5B) wired end-to-end from UI through the Director to `Pose2DAgent`. + +**Architecture:** Unified `POSE_MODELS` registry in `config.py` drives a `gr.Dropdown` in `app.py`; the selected key flows through `Director.run()` into `Pose2DAgent.run(model_key)`, which dispatches to one of three private sub-runners (`_run_yolo`, `_run_mediapipe`, `_run_sapiens2`), all producing the same COCO-17 `list[dict]` contract. + +**Tech Stack:** `ultralytics` (YOLO), `onnxruntime` + `huggingface_hub` (MediaPipe), `transformers` (Sapiens2), `gradio` (UI). + +--- + +## File map + +| File | Change | +|---|---| +| `formscout/config.py` | Replace `YOLO_POSE_MODELS` with `POSE_MODELS` dict + `DEFAULT_POSE_MODEL` | +| `formscout/agents/pose2d.py` | Add `_run_yolo`, `_run_mediapipe`, `_run_sapiens2`; update `run()` signature | +| `formscout/pipeline.py` | Change `pose_model_path` param to `model_key` | +| `app.py` | Add `pose_model_dropdown`, fix `_map_inputs` + `process_video` | +| `requirements.txt` | Add `onnxruntime>=1.18` | +| `tests/test_pose2d.py` | Add mocked tests for each backend | + +--- + +## Task 1: Add unified `POSE_MODELS` registry to `config.py` + +**Files:** +- Modify: `formscout/config.py` + +- [ ] **Step 1: Open `formscout/config.py` and replace the `YOLO_POSE_MODELS` block** + +Replace lines 12–20 (the `YOLO_POSE_MODELS` dict and `YOLO_POSE_MODEL` / `YOLO_POSE_MODEL_HQ` lines) with: + +```python +_YOLO_DIR = ROOT / "checkpoints" / "yolo26" + +POSE_MODELS: dict[str, dict] = { + # ── MediaPipe (Qualcomm HF, ONNX Runtime) ────────────────────────────── + "MediaPipe-Pose ⬇ ~16 MB, CPU-friendly": { + "backend": "mediapipe", + "hf_id": "qualcomm/MediaPipe-Pose-Estimation", + "params_m": 4.2, + }, + # ── YOLO26 (local checkpoints) ───────────────────────────────────────── + "YOLO26n — nano (0.7M, fastest)": { + "backend": "yolo", + "path": str(_YOLO_DIR / "yolo26n-pose.pt"), + "params_m": 0.7, + }, + "YOLO26s — small (3.5M)": { + "backend": "yolo", + "path": str(_YOLO_DIR / "yolo26s-pose.pt"), + "params_m": 3.5, + }, + "YOLO26m — medium (9M)": { + "backend": "yolo", + "path": str(_YOLO_DIR / "yolo26m-pose.pt"), + "params_m": 9.0, + }, + "YOLO26l — large (25.9M)": { + "backend": "yolo", + "path": str(_YOLO_DIR / "yolo26l-pose.pt"), + "params_m": 25.9, + }, + "YOLO26x — extra-large (57.6M)": { + "backend": "yolo", + "path": str(_YOLO_DIR / "yolo26x-pose.pt"), + "params_m": 57.6, + }, + # ── Sapiens2 (HF download, transformers) ─────────────────────────────── + "Sapiens2-0.4B ⬇ ~1.6 GB": { + "backend": "sapiens2", + "hf_id": "facebook/sapiens2-pose-0.4b", + "params_m": 400, + }, + "Sapiens2-0.8B ⬇ ~3.2 GB": { + "backend": "sapiens2", + "hf_id": "facebook/sapiens2-pose-0.8b", + "params_m": 800, + }, + "Sapiens2-1B ⬇ ~4 GB": { + "backend": "sapiens2", + "hf_id": "facebook/sapiens2-pose-1b", + "params_m": 1000, + }, + "Sapiens2-5B ⬇ ~20 GB, large GPU": { + "backend": "sapiens2", + "hf_id": "facebook/sapiens2-pose-5b", + "params_m": 5000, + }, +} + +DEFAULT_POSE_MODEL = "YOLO26n — nano (0.7M, fastest)" + +# Backward-compat aliases — kept for any direct references outside the agent +YOLO_POSE_MODEL = str(_YOLO_DIR / "yolo26l-pose.pt") +YOLO_POSE_MODEL_HQ = str(_YOLO_DIR / "yolo26x-pose.pt") +``` + +- [ ] **Step 2: Verify import is clean** + +```bash +python3 -c "from formscout import config; print(list(config.POSE_MODELS.keys()))" +``` + +Expected: list of 10 model labels, starting with `MediaPipe-Pose...` + +- [ ] **Step 3: Commit** + +```bash +git add formscout/config.py +git commit -m "feat: unified POSE_MODELS registry with MediaPipe, YOLO26 n-x, Sapiens2 0.4-5B" +git push +``` + +--- + +## Task 2: Refactor `Pose2DAgent` — YOLO sub-runner + new `run()` signature + +**Files:** +- Modify: `formscout/agents/pose2d.py` +- Modify: `tests/test_pose2d.py` + +- [ ] **Step 1: Write failing test for the new `model_key` signature** + +Add to `tests/test_pose2d.py`: + +```python +def test_run_accepts_model_key(pose2d_agent): + """run() must accept model_key kwarg, not model_path.""" + import inspect + sig = inspect.signature(pose2d_agent.run) + assert "model_key" in sig.parameters + assert "model_path" not in sig.parameters +``` + +- [ ] **Step 2: Run to confirm it fails** + +```bash +pytest tests/test_pose2d.py::TestPose2DAgent::test_run_accepts_model_key -v +``` + +Expected: FAIL — `model_path` still present in signature. + +- [ ] **Step 3: Rewrite `formscout/agents/pose2d.py`** + +Replace the entire file with: + +```python +""" +Pose2DAgent — 2D per-frame keypoint extraction. + +Backends: yolo (local ONNX), mediapipe (Qualcomm HF/ONNX Runtime), + sapiens2 (Meta HF/transformers). +All backends output COCO-17 keypoints: dict[int, {x, y, conf}] per frame. + +Input: IngestResult +Output: Pose2DResult(keypoints per frame, fps, confidence) +Failure: Pose2DResult(confidence=0.0, notes=) — never raises. +""" +from __future__ import annotations + +import logging +import numpy as np + +from formscout import config +from formscout.types import IngestResult, Pose2DResult + +logger = logging.getLogger(__name__) + +COCO_KEYPOINTS = [ + "nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", + "left_knee", "right_knee", "left_ankle", "right_ankle", +] + +# BlazePose-33 → COCO-17 index mapping +_BLAZEPOSE_TO_COCO: dict[int, int] = { + 0: 0, # nose + 1: 2, # left_eye (inner → left_eye) + 2: 1, # right_eye (inner → right_eye) — swapped: BlazePose 1=left_eye_inner + 3: 3, # left_ear + 4: 4, # right_ear + 5: 5, # left_shoulder → COCO left_shoulder... wait + # Correct BlazePose-33 COCO mapping (canonical): + # BlazePose idx : COCO idx + # 0 nose → COCO 0 + # 2 left_eye → COCO 1 + # 5 right_eye → COCO 2 + # 7 left_ear → COCO 3 + # 8 right_ear → COCO 4 + # 11 left_shoulder → COCO 5 + # 12 right_shoulder → COCO 6 + # 13 left_elbow → COCO 7 + # 14 right_elbow → COCO 8 + # 15 left_wrist → COCO 9 + # 16 right_wrist → COCO 10 + # 23 left_hip → COCO 11 + # 24 right_hip → COCO 12 + # 25 left_knee → COCO 13 + # 26 right_knee → COCO 14 + # 27 left_ankle → COCO 15 + # 28 right_ankle → COCO 16 +} + +# BlazePose source index → COCO target index (correct mapping, no duplicates) +_BP_SRC = [0, 2, 5, 7, 8, 11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28] +_BP_DST = list(range(17)) # COCO 0..16 + +_model_cache: dict[str, object] = {} + + +# ── YOLO backend ───────────────────────────────────────────────────────────── + +def _get_yolo(path: str) -> object: + if path not in _model_cache: + from ultralytics import YOLO + _model_cache[path] = YOLO(path) + return _model_cache[path] + + +def _run_yolo(frames: list, path: str) -> list[dict]: + model = _get_yolo(path) + out = [] + for frame in frames: + try: + results = model(frame, verbose=False) + kps: dict[int, dict] = {} + if results and results[0].keypoints is not None: + kp = results[0].keypoints + if kp.xy is not None and len(kp.xy) > 0: + xy = kp.xy[0].cpu().numpy() + conf = kp.conf[0].cpu().numpy() + for j in range(min(len(xy), 17)): + kps[j] = {"x": float(xy[j, 0]), "y": float(xy[j, 1]), "conf": float(conf[j])} + out.append(kps) + except Exception: + out.append({}) + return out + + +# ── MediaPipe backend ──────────────────────────────────────────────────────── + +def _get_mediapipe_sessions(hf_id: str): + """Return (detector_session, landmark_session) cached by hf_id.""" + cache_key = f"mp:{hf_id}" + if cache_key not in _model_cache: + from huggingface_hub import snapshot_download + import onnxruntime as ort + from pathlib import Path + + snap = Path(snapshot_download(hf_id)) + onnx_files = sorted(snap.glob("**/*.onnx"), key=lambda p: p.stat().st_size) + if len(onnx_files) < 2: + raise RuntimeError(f"Expected 2 ONNX files in {snap}, found {len(onnx_files)}") + # Smaller file = pose detector; larger = pose landmark detector + det_sess = ort.InferenceSession(str(onnx_files[0])) + lmk_sess = ort.InferenceSession(str(onnx_files[-1])) + _model_cache[cache_key] = (det_sess, lmk_sess) + return _model_cache[cache_key] + + +def _preprocess_mediapipe(frame: np.ndarray, size: int = 256) -> np.ndarray: + """Resize to size×size, normalize to [0,1], add batch dim → (1,3,H,W).""" + import cv2 + img = cv2.resize(frame, (size, size)).astype(np.float32) / 255.0 + return img.transpose(2, 0, 1)[None] # (1, 3, 256, 256) + + +def _run_mediapipe(frames: list, hf_id: str) -> list[dict]: + try: + det_sess, lmk_sess = _get_mediapipe_sessions(hf_id) + except Exception as e: + logger.warning("mediapipe load failed: %s", e) + return [{} for _ in frames] + + import cv2 + h_orig, w_orig = frames[0].shape[:2] if frames else (480, 640) + out = [] + + for frame in frames: + try: + h, w = frame.shape[:2] + inp = _preprocess_mediapipe(frame) + + # Run landmark detector directly on full frame (single-person FMS use-case) + lmk_input_name = lmk_sess.get_inputs()[0].name + lmk_out = lmk_sess.run(None, {lmk_input_name: inp}) + + # lmk_out[0] shape: (1, 33, 3) — [x, y, visibility] normalized 0..1 + landmarks = lmk_out[0][0] # (33, 3) + + kps: dict[int, dict] = {} + for coco_idx, bp_idx in zip(_BP_DST, _BP_SRC): + if bp_idx < len(landmarks): + lm = landmarks[bp_idx] + kps[coco_idx] = { + "x": float(lm[0] * w), + "y": float(lm[1] * h), + "conf": float(lm[2]), # visibility score + } + out.append(kps) + except Exception: + out.append({}) + + return out + + +# ── Sapiens2 backend ───────────────────────────────────────────────────────── + +# COCO-17 keypoint names in order (used to map Sapiens2 named output → COCO index) +_COCO_NAMES = [ + "nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", + "left_knee", "right_knee", "left_ankle", "right_ankle", +] + + +def _get_sapiens2(hf_id: str) -> object: + if hf_id not in _model_cache: + from transformers import pipeline as hf_pipeline + _model_cache[hf_id] = hf_pipeline("pose-estimation", model=hf_id) + return _model_cache[hf_id] + + +def _run_sapiens2(frames: list, hf_id: str) -> list[dict]: + try: + pipe = _get_sapiens2(hf_id) + except Exception as e: + logger.warning("sapiens2 load failed: %s", e) + return [{} for _ in frames] + + from PIL import Image + out = [] + + for frame in frames: + try: + pil_img = Image.fromarray(frame) + result = pipe(pil_img) + + # result is a list of person dicts; take the first (highest confidence) + if not result: + out.append({}) + continue + + person = result[0] + keypoints = person.get("keypoints", []) + scores = person.get("keypoint_scores", []) + + # Build name→(x,y,score) lookup from pipeline output + kp_lookup: dict[str, tuple] = {} + for i, kp in enumerate(keypoints): + name = kp.get("label", "") if isinstance(kp, dict) else "" + x = kp.get("x", 0.0) if isinstance(kp, dict) else float(kp[0]) + y = kp.get("y", 0.0) if isinstance(kp, dict) else float(kp[1]) + score = scores[i] if i < len(scores) else 0.0 + if name: + kp_lookup[name] = (x, y, float(score)) + + kps: dict[int, dict] = {} + for coco_idx, name in enumerate(_COCO_NAMES): + if name in kp_lookup: + x, y, s = kp_lookup[name] + kps[coco_idx] = {"x": x, "y": y, "conf": s} + + out.append(kps) + except Exception: + out.append({}) + + return out + + +# ── Agent ──────────────────────────────────────────────────────────────────── + +class Pose2DAgent: + """Extracts COCO-17 keypoints per frame; dispatches to YOLO, MediaPipe, or Sapiens2.""" + + def run(self, ingest: IngestResult, model_key: str | None = None) -> Pose2DResult: + if not ingest.frames: + return Pose2DResult(keypoints=[], fps=ingest.fps, confidence=0.0, notes="no frames in ingest") + + key = model_key or config.DEFAULT_POSE_MODEL + spec = config.POSE_MODELS.get(key) + if spec is None: + logger.warning("Unknown model_key %r — falling back to %s", key, config.DEFAULT_POSE_MODEL) + spec = config.POSE_MODELS[config.DEFAULT_POSE_MODEL] + + backend = spec["backend"] + try: + if backend == "yolo": + kps_per_frame = _run_yolo(ingest.frames, spec["path"]) + elif backend == "mediapipe": + kps_per_frame = _run_mediapipe(ingest.frames, spec["hf_id"]) + elif backend == "sapiens2": + kps_per_frame = _run_sapiens2(ingest.frames, spec["hf_id"]) + else: + return Pose2DResult( + keypoints=[{} for _ in ingest.frames], + fps=ingest.fps, confidence=0.0, + notes=f"unknown backend: {backend}", + ) + except Exception as e: + return Pose2DResult( + keypoints=[{} for _ in ingest.frames], + fps=ingest.fps, confidence=0.0, + notes=str(e), + ) + + n_detected = sum(1 for f in kps_per_frame if f) + total_conf = sum( + sum(kp["conf"] for kp in f.values()) / len(f) + for f in kps_per_frame if f + ) + overall_conf = (total_conf / n_detected) if n_detected > 0 else 0.0 + notes = "" if n_detected > 0 else "no person detected in any frame" + + return Pose2DResult( + keypoints=kps_per_frame, + fps=ingest.fps, + confidence=overall_conf, + notes=notes, + ) +``` + +- [ ] **Step 4: Run the new signature test** + +```bash +pytest tests/test_pose2d.py::TestPose2DAgent::test_run_accepts_model_key -v +``` + +Expected: PASS + +- [ ] **Step 5: Run full existing pose2d test suite** + +```bash +pytest tests/test_pose2d.py -v +``` + +Expected: all existing tests pass (they will skip if YOLO model unavailable in env — that's OK). + +- [ ] **Step 6: Commit and push** + +```bash +git add formscout/agents/pose2d.py tests/test_pose2d.py +git commit -m "feat: Pose2DAgent — three backends (yolo/mediapipe/sapiens2), model_key dispatch" +git push +``` + +--- + +## Task 3: Add `onnxruntime` to requirements + +**Files:** +- Modify: `requirements.txt` + +- [ ] **Step 1: Add onnxruntime** + +Open `requirements.txt` and add after the existing `transformers` line: + +``` +onnxruntime>=1.18 +``` + +- [ ] **Step 2: Verify it installs** + +```bash +pip install onnxruntime --quiet && python3 -c "import onnxruntime; print(onnxruntime.__version__)" +``` + +Expected: version string printed, no errors. + +- [ ] **Step 3: Commit and push** + +```bash +git add requirements.txt +git commit -m "chore: add onnxruntime for MediaPipe ONNX backend" +git push +``` + +--- + +## Task 4: Update `Director.run()` — `pose_model_path` → `model_key` + +**Files:** +- Modify: `formscout/pipeline.py` + +- [ ] **Step 1: Update the signature and the `pose2d` call** + +In `formscout/pipeline.py`, change `Director.run()`: + +```python +def run(self, video_path: str, test_name: str = "deep_squat", side: str = "na", model_key: str | None = None) -> PipelineState: + """ + Run the full pipeline on a single video. + test_name/side serve as manual override when provided (skips classifier). + model_key selects the pose backend (see config.POSE_MODELS). + """ + state = PipelineState(video_path=video_path) + + # ─── Ingest ─── + state.ingest = self._ingest.run(video_path) + if state.ingest.confidence < config.MIN_CONFIDENCE: + state.errors.append("ingest: low confidence — video may be corrupt") + return state + + # ─── Pose 2D ─── + state.pose2d = self._pose2d.run(state.ingest, model_key=model_key) + # ... rest of method unchanged +``` + +(Only the signature line and the `self._pose2d.run(...)` call change — everything else stays the same.) + +- [ ] **Step 2: Verify import is clean** + +```bash +python3 -c "from formscout.pipeline import Director; d = Director(); print('ok')" +``` + +Expected: `ok` (models load lazily so no crash here). + +- [ ] **Step 3: Commit and push** + +```bash +git add formscout/pipeline.py +git commit -m "feat: Director.run() accepts model_key, threads to Pose2DAgent" +git push +``` + +--- + +## Task 5: Wire the UI — pose model dropdown in `app.py` + +**Files:** +- Modify: `app.py` + +- [ ] **Step 1: Update `process_video` to use `model_key` and the unified registry** + +Replace the existing `process_video` function signature and the old `YOLO_POSE_MODELS.get()` lookup: + +```python +def process_video(video_path: str, test_name: str, side: str, model_key: str): + """Process an uploaded video through the FormScout pipeline.""" + if not video_path: + return ( + _render_empty_state(), + "Upload a video to begin analysis.", + "", + "", + ) + + director = Director() + state = director.run(video_path, test_name=test_name, side=side, model_key=model_key) +``` + +(Remove the `pose_model_path = config.YOLO_POSE_MODELS.get(...)` line entirely.) + +- [ ] **Step 2: Add the `pose_model_dropdown` in `build_app()`** + +Inside `build_app()`, after the `side_dropdown` block (around line 265) and before `submit_btn`, add: + +```python +pose_model_dropdown = gr.Dropdown( + choices=list(config.POSE_MODELS.keys()), + value=config.DEFAULT_POSE_MODEL, + label="Pose Model", +) +``` + +- [ ] **Step 3: Update `_map_inputs` to pass the model key** + +Replace the existing `_map_inputs` closure: + +```python +def _map_inputs(video, test_display_name, side_display, pose_model_key): + """Map UI display values to internal values.""" + test_map = {name: val for name, val in FMS_TESTS} + test_name = test_map.get(test_display_name, "deep_squat") + side = {"N/A": "na", "Left": "left", "Right": "right"}.get(side_display, "na") + return process_video(video, test_name, side, pose_model_key) +``` + +- [ ] **Step 4: Update `submit_btn.click` to include `pose_model_dropdown`** + +Replace the existing `.click(...)` call: + +```python +submit_btn.click( + fn=_map_inputs, + inputs=[video_input, test_dropdown, side_dropdown, pose_model_dropdown], + outputs=[score_html, pipeline_md, score_details, alerts_md], +) +``` + +- [ ] **Step 5: Smoke-test the app starts** + +```bash +python3 -c "from app import build_app; app = build_app(); print('app built ok')" +``` + +Expected: `app built ok` — no import or config errors. + +- [ ] **Step 6: Commit and push** + +```bash +git add app.py +git commit -m "feat: pose model dropdown in UI, wired through process_video → Director" +git push +``` + +--- + +## Task 6: Add mocked backend tests + +**Files:** +- Modify: `tests/test_pose2d.py` + +- [ ] **Step 1: Add mocked YOLO test** + +Append to `tests/test_pose2d.py`: + +```python +import unittest.mock as mock +import numpy as np +from formscout.types import IngestResult, Pose2DResult + + +def _blank_ingest_3(): + frames = [np.zeros((480, 640, 3), dtype=np.uint8) for _ in range(3)] + return IngestResult(frames=frames, fps=30.0, duration=0.1, n_people=1, width=640, height=480) + + +class TestPose2DBackendsMocked: + """Backend dispatch tests — no real model downloads.""" + + def test_yolo_backend_dispatches(self): + from formscout.agents.pose2d import Pose2DAgent, _run_yolo + fake_kps = [{0: {"x": 10.0, "y": 20.0, "conf": 0.9}} for _ in range(3)] + with mock.patch("formscout.agents.pose2d._run_yolo", return_value=fake_kps) as m: + agent = Pose2DAgent() + result = agent.run(_blank_ingest_3(), model_key="YOLO26n — nano (0.7M, fastest)") + m.assert_called_once() + assert isinstance(result, Pose2DResult) + assert len(result.keypoints) == 3 + assert result.confidence > 0.0 + + def test_mediapipe_backend_dispatches(self): + from formscout.agents.pose2d import Pose2DAgent + fake_kps = [{i: {"x": float(i), "y": float(i), "conf": 0.8} for i in range(17)} for _ in range(3)] + with mock.patch("formscout.agents.pose2d._run_mediapipe", return_value=fake_kps) as m: + agent = Pose2DAgent() + result = agent.run(_blank_ingest_3(), model_key="MediaPipe-Pose ⬇ ~16 MB, CPU-friendly") + m.assert_called_once() + assert isinstance(result, Pose2DResult) + assert len(result.keypoints) == 3 + assert all(len(f) == 17 for f in result.keypoints) + + def test_sapiens2_backend_dispatches(self): + from formscout.agents.pose2d import Pose2DAgent + fake_kps = [{i: {"x": float(i), "y": float(i), "conf": 0.85} for i in range(17)} for _ in range(3)] + with mock.patch("formscout.agents.pose2d._run_sapiens2", return_value=fake_kps) as m: + agent = Pose2DAgent() + result = agent.run(_blank_ingest_3(), model_key="Sapiens2-0.4B ⬇ ~1.6 GB") + m.assert_called_once() + assert isinstance(result, Pose2DResult) + assert len(result.keypoints) == 3 + + def test_unknown_model_key_falls_back(self): + from formscout.agents.pose2d import Pose2DAgent + fake_kps = [{0: {"x": 1.0, "y": 2.0, "conf": 0.7}} for _ in range(3)] + with mock.patch("formscout.agents.pose2d._run_yolo", return_value=fake_kps): + agent = Pose2DAgent() + result = agent.run(_blank_ingest_3(), model_key="nonexistent-model-xyz") + assert isinstance(result, Pose2DResult) # graceful fallback, no crash + + def test_confidence_zero_on_empty_keypoints(self): + from formscout.agents.pose2d import Pose2DAgent + with mock.patch("formscout.agents.pose2d._run_yolo", return_value=[{}, {}, {}]): + agent = Pose2DAgent() + result = agent.run(_blank_ingest_3(), model_key="YOLO26n — nano (0.7M, fastest)") + assert result.confidence == 0.0 + assert "no person" in result.notes.lower() +``` + +- [ ] **Step 2: Run the new tests** + +```bash +pytest tests/test_pose2d.py::TestPose2DBackendsMocked -v +``` + +Expected: all 5 tests PASS. + +- [ ] **Step 3: Run the full test suite to check for regressions** + +```bash +pytest tests/ -v --tb=short 2>&1 | tail -30 +``` + +Expected: same pass/fail ratio as before (45/46 known passing). The one known failure (`test_unimplemented_test_returns_low_confidence`) is pre-existing — ignore it. + +- [ ] **Step 4: Commit and push** + +```bash +git add tests/test_pose2d.py +git commit -m "test: mocked backend dispatch tests for YOLO, MediaPipe, Sapiens2" +git push +``` + +--- + +## Self-review + +**Spec coverage:** +- ✅ Unified `POSE_MODELS` registry (Task 1) +- ✅ `DEFAULT_POSE_MODEL = YOLO26n` (Task 1) +- ✅ Backward-compat `YOLO_POSE_MODEL` / `YOLO_POSE_MODEL_HQ` aliases (Task 1) +- ✅ `_run_yolo` sub-runner (Task 2) +- ✅ `_run_mediapipe` with ONNX Runtime + BlazePose→COCO-17 mapping (Task 2) +- ✅ `_run_sapiens2` with transformers pipeline + named-keypoint→COCO-17 mapping (Task 2) +- ✅ `Pose2DAgent.run(model_key)` dispatch + fallback on unknown key (Task 2) +- ✅ `onnxruntime` added to requirements (Task 3) +- ✅ `Director.run(model_key)` threads key to agent (Task 4) +- ✅ `pose_model_dropdown` in UI (Task 5) +- ✅ `_map_inputs` + `submit_btn.click` wired (Task 5) +- ✅ Error handling: unknown key → warning + fallback; download failure → confidence=0 (Task 2) +- ✅ Mocked tests for all three backends (Task 6) + +**Placeholder scan:** None found. + +**Type consistency:** `model_key: str | None` used consistently across `Pose2DAgent.run`, `Director.run`, `process_video`. `config.POSE_MODELS` and `config.DEFAULT_POSE_MODEL` referenced consistently. + +**Note on Sapiens2 keypoint format:** The `_run_sapiens2` implementation uses **named keypoint lookup** (by label string) rather than assuming fixed indices 0–16 = COCO. This is the safe approach — the transformers pipeline returns labeled keypoints and the code maps by name. If the pipeline returns unnamed keypoints (index-only), the `kp_lookup` will be empty and the frame will gracefully return `{}`. diff --git a/docs/superpowers/plans/2026-06-09-pose-visualizer.md b/docs/superpowers/plans/2026-06-09-pose-visualizer.md new file mode 100644 index 0000000000000000000000000000000000000000..9fa37bf7c094fb648dd20193fb9d9554286a1773 --- /dev/null +++ b/docs/superpowers/plans/2026-06-09-pose-visualizer.md @@ -0,0 +1,914 @@ +# Pose Overlay Visualizer Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a pose overlay video output to FormScout with skeleton, motion trails, and velocity arrows, plus a per-joint velocity summary table. + +**Architecture:** A new `formscout/agents/visualizer.py` runs after `director.run()` in `process_video()`; it uses Kalman-filtered per-joint velocity and OpenCV rendering. `app.py` gains a `gr.CheckboxGroup` for layer selection, a new `gr.Video` output tab, and a `gr.Markdown` velocity summary. + +**Tech Stack:** `opencv-python`, `numpy`, `colorsys` (stdlib), `gradio`. + +--- + +## File map + +| File | Change | +|---|---| +| `formscout/agents/visualizer.py` | Create — Kalman filter, velocity, PoseVisualizer, summary | +| `tests/test_visualizer.py` | Create — all visualizer tests | +| `app.py` | Modify — overlay_layers checkbox, new tab, wiring | + +--- + +## Task 1: `SimpleKalmanFilter` + `compute_joint_velocity` + +**Files:** +- Create: `formscout/agents/visualizer.py` +- Create: `tests/test_visualizer.py` + +- [ ] **Step 1: Write failing tests** + +Create `tests/test_visualizer.py`: + +```python +"""Tests for PoseVisualizer — no GPU, no model downloads.""" +import numpy as np +import pytest +from formscout.types import IngestResult, Pose2DResult + + +def _make_ingest(n=5, h=480, w=640, fps=30.0): + frames = [np.zeros((h, w, 3), dtype=np.uint8) for _ in range(n)] + return IngestResult(frames=frames, fps=fps, duration=n/fps, n_people=1, width=w, height=h) + + +def _make_pose(n=5, w=640, h=480): + """Synthetic Pose2DResult: 17 joints at fixed pixel positions, conf=0.9.""" + kps_per_frame = [] + for i in range(n): + frame_kps = {} + for j in range(17): + frame_kps[j] = { + "x": float(50 + j * 30 + i * 2), # slight movement each frame + "y": float(100 + j * 20), + "conf": 0.9, + } + kps_per_frame.append(frame_kps) + return Pose2DResult(keypoints=kps_per_frame, fps=30.0, confidence=0.9, notes="") + + +class TestComputeJointVelocity: + def test_returns_17_joints(self): + from formscout.agents.visualizer import compute_joint_velocity + pose = _make_pose(n=5) + result = compute_joint_velocity(pose.keypoints, fps=30.0) + assert len(result) == 17 + + def test_each_list_has_n_frames(self): + from formscout.agents.visualizer import compute_joint_velocity + pose = _make_pose(n=5) + result = compute_joint_velocity(pose.keypoints, fps=30.0) + for joint_idx, speeds in result.items(): + assert len(speeds) == 5, f"joint {joint_idx} has {len(speeds)} speeds, expected 5" + + def test_speeds_are_non_negative(self): + from formscout.agents.visualizer import compute_joint_velocity + pose = _make_pose(n=5) + result = compute_joint_velocity(pose.keypoints, fps=30.0) + for speeds in result.values(): + assert all(s >= 0.0 for s in speeds) + + def test_missing_keypoints_give_zero_speed(self): + from formscout.agents.visualizer import compute_joint_velocity + # All frames empty + empty_kps = [{} for _ in range(5)] + result = compute_joint_velocity(empty_kps, fps=30.0) + for speeds in result.values(): + assert all(s == 0.0 for s in speeds) +``` + +- [ ] **Step 2: Run to confirm failure** + +```bash +pytest tests/test_visualizer.py::TestComputeJointVelocity -v +``` + +Expected: `ERROR` — `ModuleNotFoundError: No module named 'formscout.agents.visualizer'` + +- [ ] **Step 3: Create `formscout/agents/visualizer.py` with Kalman + velocity** + +```python +""" +PoseVisualizer — annotated overlay video with skeleton, trails, velocity arrows. + +Input: IngestResult + Pose2DResult +Output: .mp4 path (or None on failure/empty layers) +Failure: returns None, never raises. +""" +from __future__ import annotations + +import colorsys +import logging +import math +import tempfile +from collections import deque + +import cv2 +import numpy as np + +logger = logging.getLogger(__name__) + +# ── COCO constants ──────────────────────────────────────────────────────────── + +COCO_KEYPOINTS = [ + "nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", + "left_knee", "right_knee", "left_ankle", "right_ankle", +] + +COCO_SKELETON = [ + (0, 1), (0, 2), (1, 3), (2, 4), # face + (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), # arms + (5, 11), (6, 12), (11, 12), # torso + (11, 13), (13, 15), (12, 14), (14, 16), # legs +] + +TRAIL_LENGTH = 10 +MAX_ARROW_PX = 40 +CONF_THRESHOLD = 0.3 + + +# ── Kalman filter ───────────────────────────────────────────────────────────── + +class SimpleKalmanFilter: + """4-state Kalman filter (x, y, vx, vy) for joint tracking.""" + + def __init__(self, process_noise: float = 0.01, measurement_noise: float = 0.1): + self.is_initialized = False + self.state = np.zeros(4) + self.cov = np.eye(4) * 0.1 + self.Q = np.eye(4) * process_noise + self.R = np.eye(2) * measurement_noise + self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=float) + + def predict(self, dt: float = 1.0): + F = np.array([[1, 0, dt, 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=float) + self.state = F @ self.state + self.cov = F @ self.cov @ F.T + self.Q + + def update(self, x: float, y: float): + z = np.array([x, y]) + if not self.is_initialized: + self.state[:2] = z + self.is_initialized = True + return + S = self.H @ self.cov @ self.H.T + self.R + K = self.cov @ self.H.T @ np.linalg.inv(S) + self.state = self.state + K @ (z - self.H @ self.state) + self.cov = (np.eye(4) - K @ self.H) @ self.cov + + def velocity_magnitude(self) -> float: + vx, vy = self.state[2], self.state[3] + return math.sqrt(vx * vx + vy * vy) + + def velocity_vector(self) -> tuple[float, float]: + return float(self.state[2]), float(self.state[3]) + + +# ── Velocity computation ────────────────────────────────────────────────────── + +def compute_joint_velocity( + keypoints_per_frame: list[dict], + fps: float, +) -> dict[int, list[float]]: + """ + Compute Kalman-filtered per-joint speed (px/s) for each frame. + + Returns dict[joint_idx, [speed_frame0, speed_frame1, ...]] for all 17 COCO joints. + Missing/low-confidence keypoints yield speed=0.0 for that frame. + """ + dt = 1.0 / fps if fps > 0 else 1.0 + filters: dict[int, SimpleKalmanFilter] = {j: SimpleKalmanFilter() for j in range(17)} + result: dict[int, list[float]] = {j: [] for j in range(17)} + + for frame_kps in keypoints_per_frame: + for j in range(17): + kf = filters[j] + kp = frame_kps.get(j) + kf.predict(dt) + if kp and kp.get("conf", 0.0) >= CONF_THRESHOLD: + kf.update(kp["x"], kp["y"]) + speed = kf.velocity_magnitude() + else: + speed = 0.0 + result[j].append(speed) + + return result +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_visualizer.py::TestComputeJointVelocity -v +``` + +Expected: 4 PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_visualizer.py +git commit -m "feat: SimpleKalmanFilter + compute_joint_velocity (4 tests pass)" +``` + +--- + +## Task 2: `PoseVisualizer._draw_skeleton` + +**Files:** +- Modify: `formscout/agents/visualizer.py` +- Modify: `tests/test_visualizer.py` + +- [ ] **Step 1: Write failing test** + +Append to `tests/test_visualizer.py`: + +```python +class TestDrawSkeleton: + def test_skeleton_draws_without_error(self): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + kps = {j: {"x": float(50 + j * 30), "y": float(100 + j * 20), "conf": 0.9} + for j in range(17)} + result = vis._draw_skeleton(frame.copy(), kps) + assert result.shape == frame.shape + # Frame must be modified (not all zeros after drawing) + assert not np.array_equal(result, frame) + + def test_low_confidence_keypoints_not_drawn(self): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + # All keypoints below threshold + kps = {j: {"x": float(50 + j * 30), "y": 100.0, "conf": 0.1} for j in range(17)} + result = vis._draw_skeleton(frame.copy(), kps) + # Nothing drawn — frame stays all zeros + assert np.array_equal(result, frame) +``` + +- [ ] **Step 2: Run to confirm failure** + +```bash +pytest tests/test_visualizer.py::TestDrawSkeleton -v +``` + +Expected: FAIL — `AttributeError: 'PoseVisualizer' object has no attribute '_draw_skeleton'` + +- [ ] **Step 3: Add `PoseVisualizer` class with `_draw_skeleton` to `visualizer.py`** + +Append after `compute_joint_velocity`: + +```python +# ── Helpers ─────────────────────────────────────────────────────────────────── + +def _conf_to_bgr(conf: float) -> tuple[int, int, int]: + """Map confidence 0→1 to BGR color red→green via HSV.""" + hue = conf * 120.0 / 360.0 + r, g, b = colorsys.hsv_to_rgb(hue, 1.0, 1.0) + return (int(b * 255), int(g * 255), int(r * 255)) + + +# ── PoseVisualizer ──────────────────────────────────────────────────────────── + +class PoseVisualizer: + """Renders skeleton, trails, and velocity arrows onto video frames.""" + + def __init__(self): + self.last_velocities: dict[int, list[float]] = {} + + # ── Skeleton ────────────────────────────────────────────────────────────── + + def _draw_skeleton(self, frame: np.ndarray, kps: dict) -> np.ndarray: + """Draw COCO-17 bones (white) and joints (confidence-colored) onto frame.""" + visible = {j: kp for j, kp in kps.items() if kp.get("conf", 0.0) >= CONF_THRESHOLD} + + # Bones + for j1, j2 in COCO_SKELETON: + if j1 in visible and j2 in visible: + p1 = (int(visible[j1]["x"]), int(visible[j1]["y"])) + p2 = (int(visible[j2]["x"]), int(visible[j2]["y"])) + cv2.line(frame, p1, p2, (255, 255, 255), 2) + + # Joints + for j, kp in visible.items(): + pt = (int(kp["x"]), int(kp["y"])) + color = _conf_to_bgr(kp["conf"]) + cv2.circle(frame, pt, 4, color, -1) + cv2.circle(frame, pt, 5, (255, 255, 255), 1) + + return frame +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_visualizer.py::TestDrawSkeleton -v +``` + +Expected: 2 PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_visualizer.py +git commit -m "feat: PoseVisualizer._draw_skeleton with confidence-colored joints" +``` + +--- + +## Task 3: `PoseVisualizer._draw_trails` + +**Files:** +- Modify: `formscout/agents/visualizer.py` +- Modify: `tests/test_visualizer.py` + +- [ ] **Step 1: Write failing test** + +Append to `tests/test_visualizer.py`: + +```python +class TestDrawTrails: + def test_trails_draw_without_error(self): + from formscout.agents.visualizer import PoseVisualizer, TRAIL_LENGTH + from collections import deque + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + # Build a trail history for joint 0 with 5 positions + trail_history = { + 0: deque([(100 + i * 5, 200 + i * 3) for i in range(5)], maxlen=TRAIL_LENGTH) + } + result = vis._draw_trails(frame.copy(), trail_history) + assert result.shape == frame.shape + # Trail should modify at least some pixels + assert not np.array_equal(result, frame) + + def test_short_trail_no_crash(self): + from formscout.agents.visualizer import PoseVisualizer, TRAIL_LENGTH + from collections import deque + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + # Only one point — no line possible + trail_history = {0: deque([(100, 200)], maxlen=TRAIL_LENGTH)} + result = vis._draw_trails(frame.copy(), trail_history) + # No crash, frame unchanged (single point = no segment) + assert np.array_equal(result, frame) +``` + +- [ ] **Step 2: Run to confirm failure** + +```bash +pytest tests/test_visualizer.py::TestDrawTrails -v +``` + +Expected: FAIL — `AttributeError: 'PoseVisualizer' object has no attribute '_draw_trails'` + +- [ ] **Step 3: Add `_draw_trails` to `PoseVisualizer`** + +Inside the `PoseVisualizer` class, after `_draw_skeleton`: + +```python + # ── Trails ─────────────────────────────────────────────────────────────── + + def _draw_trails(self, frame: np.ndarray, trail_history: dict) -> np.ndarray: + """Draw fading motion trails for each joint.""" + for joint_idx, trail in trail_history.items(): + pts = list(trail) + if len(pts) < 2: + continue + for i in range(1, len(pts)): + alpha = i / len(pts) + brightness = int(255 * alpha) + color = (brightness, brightness, brightness) + thickness = max(1, int(3 * alpha)) + p1 = (int(pts[i - 1][0]), int(pts[i - 1][1])) + p2 = (int(pts[i][0]), int(pts[i][1])) + cv2.line(frame, p1, p2, color, thickness) + return frame +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_visualizer.py::TestDrawTrails -v +``` + +Expected: 2 PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_visualizer.py +git commit -m "feat: PoseVisualizer._draw_trails with fading alpha" +``` + +--- + +## Task 4: `PoseVisualizer._draw_velocity_arrows` + +**Files:** +- Modify: `formscout/agents/visualizer.py` +- Modify: `tests/test_visualizer.py` + +- [ ] **Step 1: Write failing test** + +Append to `tests/test_visualizer.py`: + +```python +class TestDrawVelocityArrows: + def test_arrows_draw_without_error(self): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + kps = {j: {"x": float(50 + j * 30), "y": float(100 + j * 20), "conf": 0.9} + for j in range(17)} + prev_kps = {j: {"x": float(48 + j * 30), "y": float(98 + j * 20), "conf": 0.9} + for j in range(17)} + # velocities: joint 5 moving fast + velocities = {j: [0.0] * 5 for j in range(17)} + velocities[5] = [0.0, 10.0, 50.0, 80.0, 120.0] + result = vis._draw_velocity_arrows(frame.copy(), kps, prev_kps, velocities, frame_idx=4) + assert result.shape == frame.shape + + def test_no_prev_kps_no_crash(self): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + kps = {j: {"x": float(50 + j * 30), "y": 100.0, "conf": 0.9} for j in range(17)} + velocities = {j: [50.0] * 5 for j in range(17)} + # prev_kps is None — should skip without crash + result = vis._draw_velocity_arrows(frame.copy(), kps, None, velocities, frame_idx=0) + assert result.shape == frame.shape +``` + +- [ ] **Step 2: Run to confirm failure** + +```bash +pytest tests/test_visualizer.py::TestDrawVelocityArrows -v +``` + +Expected: FAIL — `AttributeError: 'PoseVisualizer' object has no attribute '_draw_velocity_arrows'` + +- [ ] **Step 3: Add `_draw_velocity_arrows` to `PoseVisualizer`** + +Inside the `PoseVisualizer` class, after `_draw_trails`: + +```python + # ── Velocity arrows ─────────────────────────────────────────────────────── + + def _draw_velocity_arrows( + self, + frame: np.ndarray, + kps: dict, + prev_kps: dict | None, + velocities: dict[int, list[float]], + frame_idx: int, + ) -> np.ndarray: + """Draw per-joint velocity arrows scaled by speed.""" + if prev_kps is None: + return frame + + all_speeds = [velocities[j][frame_idx] for j in range(17) if frame_idx < len(velocities.get(j, []))] + peak = max(all_speeds) if all_speeds else 1.0 + if peak == 0.0: + return frame + + for j in range(17): + kp = kps.get(j) + pk = prev_kps.get(j) + if not kp or not pk: + continue + if kp.get("conf", 0.0) < CONF_THRESHOLD: + continue + speeds = velocities.get(j, []) + if frame_idx >= len(speeds): + continue + speed = speeds[frame_idx] + if speed == 0.0: + continue + + dx = kp["x"] - pk["x"] + dy = kp["y"] - pk["y"] + mag = math.sqrt(dx * dx + dy * dy) + if mag < 1e-6: + continue + + # Normalize direction, scale to arrow length + length = min(speed / peak * MAX_ARROW_PX, MAX_ARROW_PX) + nx, ny = dx / mag, dy / mag + start = (int(kp["x"]), int(kp["y"])) + end = (int(kp["x"] + nx * length), int(kp["y"] + ny * length)) + + ratio = speed / peak + if ratio < 0.33: + color = (0, 200, 0) # green + elif ratio < 0.66: + color = (0, 140, 255) # orange + else: + color = (0, 0, 255) # red + + cv2.arrowedLine(frame, start, end, color, 2, tipLength=0.35) + + return frame +``` + +- [ ] **Step 4: Run tests** + +```bash +pytest tests/test_visualizer.py::TestDrawVelocityArrows -v +``` + +Expected: 2 PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_visualizer.py +git commit -m "feat: PoseVisualizer._draw_velocity_arrows speed-colored" +``` + +--- + +## Task 5: `render_video` + `build_velocity_summary` + +**Files:** +- Modify: `formscout/agents/visualizer.py` +- Modify: `tests/test_visualizer.py` + +- [ ] **Step 1: Write failing tests** + +Append to `tests/test_visualizer.py`: + +```python +class TestRenderVideo: + def test_creates_mp4_file(self, tmp_path): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + ingest = _make_ingest(n=5) + pose = _make_pose(n=5) + out = str(tmp_path / "out.mp4") + result = vis.render_video(ingest, pose, {"skeleton"}, out) + assert result is not None + import os + assert os.path.exists(result) + assert os.path.getsize(result) > 0 + + def test_empty_layers_returns_none(self, tmp_path): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + out = str(tmp_path / "out.mp4") + result = vis.render_video(_make_ingest(), _make_pose(), set(), out) + assert result is None + + def test_no_detections_returns_none(self, tmp_path): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + ingest = _make_ingest(n=5) + empty_pose = Pose2DResult( + keypoints=[{} for _ in range(5)], fps=30.0, confidence=0.0, notes="" + ) + out = str(tmp_path / "out.mp4") + result = vis.render_video(ingest, empty_pose, {"skeleton"}, out) + assert result is None + + def test_last_velocities_set_after_render(self, tmp_path): + from formscout.agents.visualizer import PoseVisualizer + vis = PoseVisualizer() + out = str(tmp_path / "out.mp4") + vis.render_video(_make_ingest(n=5), _make_pose(n=5), {"skeleton"}, out) + assert len(vis.last_velocities) == 17 + + +class TestBuildVelocitySummary: + def test_returns_markdown_table(self): + from formscout.agents.visualizer import build_velocity_summary, compute_joint_velocity + pose = _make_pose(n=10) + vels = compute_joint_velocity(pose.keypoints, fps=30.0) + result = build_velocity_summary(pose.keypoints, vels) + assert "|" in result + # At least one COCO joint name appears + assert any(name in result for name in ["knee", "shoulder", "hip", "ankle"]) + + def test_empty_keypoints_returns_empty_string(self): + from formscout.agents.visualizer import build_velocity_summary + empty_kps = [{} for _ in range(5)] + vels = {j: [0.0] * 5 for j in range(17)} + result = build_velocity_summary(empty_kps, vels) + assert result == "" +``` + +- [ ] **Step 2: Run to confirm failure** + +```bash +pytest tests/test_visualizer.py::TestRenderVideo tests/test_visualizer.py::TestBuildVelocitySummary -v +``` + +Expected: FAIL — `AttributeError: 'PoseVisualizer' object has no attribute 'render_video'` + +- [ ] **Step 3: Add `render_video` to `PoseVisualizer`** + +Inside the `PoseVisualizer` class, after `_draw_velocity_arrows`: + +```python + # ── Public ──────────────────────────────────────────────────────────────── + + def render_video( + self, + ingest, + pose2d, + layers: set[str], + output_path: str, + ) -> str | None: + """ + Render annotated video. Returns output_path on success, None otherwise. + layers: subset of {"skeleton", "trails", "velocity_arrows"} + """ + if not layers: + return None + + # Require at least one detected frame + if not any(pose2d.keypoints): + return None + + try: + velocities = compute_joint_velocity(pose2d.keypoints, ingest.fps) + self.last_velocities = velocities + + frames = ingest.frames + h, w = frames[0].shape[:2] + fps = ingest.fps or 30.0 + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + writer = cv2.VideoWriter(output_path, fourcc, fps, (w, h)) + if not writer.isOpened(): + logger.warning("VideoWriter failed to open: %s", output_path) + return None + + trail_history: dict[int, deque] = {j: deque(maxlen=TRAIL_LENGTH) for j in range(17)} + prev_kps: dict | None = None + + for frame_idx, (frame, kps) in enumerate(zip(frames, pose2d.keypoints)): + out_frame = frame.copy() + + if "trails" in layers: + # Update trail history before drawing + for j, kp in kps.items(): + if kp.get("conf", 0.0) >= CONF_THRESHOLD: + trail_history[j].append((kp["x"], kp["y"])) + out_frame = self._draw_trails(out_frame, trail_history) + + if "skeleton" in layers: + out_frame = self._draw_skeleton(out_frame, kps) + + if "velocity_arrows" in layers: + out_frame = self._draw_velocity_arrows( + out_frame, kps, prev_kps, velocities, frame_idx + ) + + writer.write(out_frame) + prev_kps = kps + + writer.release() + return output_path + + except Exception as e: + logger.warning("render_video failed: %s", e) + return None +``` + +- [ ] **Step 4: Add `build_velocity_summary` after the class** + +After the `PoseVisualizer` class definition, add: + +```python +# ── Velocity summary ────────────────────────────────────────────────────────── + +def build_velocity_summary( + keypoints_per_frame: list[dict], + velocities: dict[int, list[float]], +) -> str: + """Return markdown table of per-joint avg/peak velocity. Empty string if no valid joints.""" + n_frames = len(keypoints_per_frame) + if n_frames == 0: + return "" + + rows = [] + for j in range(17): + # Count frames where this joint is detected + detected = sum( + 1 for kps in keypoints_per_frame + if kps.get(j, {}).get("conf", 0.0) >= CONF_THRESHOLD + ) + if detected < n_frames * 0.5: + continue # skip joints present in <50% of frames + + speeds = velocities.get(j, []) + if not speeds: + continue + + avg_speed = sum(speeds) / len(speeds) + peak_speed = max(speeds) + rows.append((COCO_KEYPOINTS[j], avg_speed, peak_speed)) + + if not rows: + return "" + + rows.sort(key=lambda r: r[2], reverse=True) # sort by peak descending + lines = [ + "| Joint | Avg (px/s) | Peak (px/s) |", + "|---|---|---|", + ] + for name, avg, peak in rows: + lines.append(f"| {name} | {avg:.1f} | {peak:.1f} |") + return "\n".join(lines) +``` + +- [ ] **Step 5: Run all visualizer tests** + +```bash +pytest tests/test_visualizer.py -v +``` + +Expected: all tests PASS (4 + 2 + 2 + 2 + 4 + 2 = 16 total) + +- [ ] **Step 6: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_visualizer.py +git commit -m "feat: PoseVisualizer.render_video + build_velocity_summary (16 tests pass)" +``` + +--- + +## Task 6: Wire `app.py` + +**Files:** +- Modify: `app.py` + +- [ ] **Step 1: Add `import tempfile` if not present and import visualizer in `process_video`** + +Check the top of `app.py` for `import tempfile`. If missing, add it alongside the other stdlib imports. (Look at the existing import block and add `import tempfile` there.) + +- [ ] **Step 2: Update `process_video()` signature and body** + +Replace the existing `process_video` function (lines 46–83) with: + +```python +def process_video(video_path: str, test_name: str, side: str, model_key: str, layers: list[str]): + """Process an uploaded video through the FormScout pipeline.""" + if not video_path: + return ( + _render_empty_state(), + "Upload a video to begin analysis.", + "", + "", + None, + "", + ) + + director = Director() + state = director.run(video_path, test_name=test_name, side=side, model_key=model_key) + + # ─── Score card ─── + score_html = _render_empty_state() + score_details = "" + + if state.features: + result = score_test(state.features) + judge = state.judge + if judge and judge.score is not None: + score_html = _render_score_card(judge.score, judge.confidence, judge.needs_human) + score_details = _render_score_details_judge(judge, result, state.features) + elif judge and judge.needs_human: + score_html = _render_score_card(0, 0, True) + score_details = f"### Needs Clinician Review\n{judge.rationale}" + else: + score_html = _render_score_card(result.score, result.confidence, result.needs_human) + score_details = _render_score_details(result, state.features) + + # ─── Pipeline info ─── + pipeline_md = _render_pipeline_status(state) + + # ─── Warnings/errors ─── + alerts = _render_alerts(state) + + # ─── Overlay video ─── + overlay_path = None + vel_summary = "" + layer_set = {lbl.lower().replace(" ", "_") for lbl in (layers or [])} + if layer_set and state.ingest and state.pose2d: + try: + from formscout.agents.visualizer import PoseVisualizer, build_velocity_summary + vis = PoseVisualizer() + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + out_path = f.name + overlay_path = vis.render_video(state.ingest, state.pose2d, layer_set, out_path) + if overlay_path: + vel_summary = build_velocity_summary(state.pose2d.keypoints, vis.last_velocities) + except Exception as e: + alerts = (alerts or "") + f"\n⚠️ Visualizer error: {e}" + + return score_html, pipeline_md, score_details, alerts, overlay_path, vel_summary +``` + +- [ ] **Step 3: Add `overlay_layers` CheckboxGroup in `build_app()`** + +After the `pose_model_dropdown` block (around line 270), and before `submit_btn`: + +```python + overlay_layers = gr.CheckboxGroup( + choices=["Skeleton", "Trails", "Velocity arrows"], + value=["Skeleton", "Trails"], + label="Overlay Layers", + ) +``` + +- [ ] **Step 4: Add overlay tab in the results panel** + +Inside the `with gr.Tabs():` block (after the `⚠️ Alerts` tab): + +```python + with gr.TabItem("🎬 Overlay Video"): + overlay_video = gr.Video(label="Annotated Movement") + velocity_md = gr.Markdown("") +``` + +- [ ] **Step 5: Update `_map_inputs` and `submit_btn.click`** + +Replace the `_map_inputs` closure and `submit_btn.click` call: + +```python + def _map_inputs(video, test_display_name, side_display, pose_model_key, overlay_layers): + """Map UI display values to internal values.""" + test_map = {name: val for name, val in FMS_TESTS} + test_name = test_map.get(test_display_name, "deep_squat") + side = {"N/A": "na", "Left": "left", "Right": "right"}.get(side_display, "na") + return process_video(video, test_name, side, pose_model_key, overlay_layers) + + submit_btn.click( + fn=_map_inputs, + inputs=[video_input, test_dropdown, side_dropdown, pose_model_dropdown, overlay_layers], + outputs=[score_html, pipeline_md, score_details, alerts_md, overlay_video, velocity_md], + ) +``` + +- [ ] **Step 6: Smoke-test the app builds** + +```bash +python3 -c "from app import build_app; build_app(); print('ok')" +``` + +Expected: `ok` (Gradio UserWarning about theme is fine, not an error) + +- [ ] **Step 7: Run full test suite to check for regressions** + +```bash +pytest tests/ -v --tb=short 2>&1 | tail -15 +``` + +Expected: all previous tests still pass (62 passing, 1 pre-existing fail in biomechanics), plus 16 new visualizer tests = 78 passing. + +- [ ] **Step 8: Commit** + +```bash +git add app.py +git commit -m "feat: overlay video tab + velocity summary wired in Gradio UI" +``` + +--- + +## Self-review + +**Spec coverage:** +- ✅ `SimpleKalmanFilter` 4-state (Task 1) +- ✅ `compute_joint_velocity` Kalman-filtered px/s (Task 1) +- ✅ `_draw_skeleton` COCO bones, confidence-colored joints (Task 2) +- ✅ `_draw_trails` fading deque-based trails (Task 3) +- ✅ `_draw_velocity_arrows` speed-colored, direction from consecutive frames (Task 4) +- ✅ `render_video` layer dispatch, trail history, VideoWriter (Task 5) +- ✅ `build_velocity_summary` markdown table, >50% detection filter (Task 5) +- ✅ `overlay_layers` CheckboxGroup in UI (Task 6) +- ✅ New `🎬 Overlay Video` tab with `gr.Video` + `gr.Markdown` (Task 6) +- ✅ `process_video` wired with layers param (Task 6) +- ✅ `vis.last_velocities` stored on instance after `render_video` (Task 5) +- ✅ Error handling: empty layers → None, empty detections → None, exception → alerts (Task 5 + 6) +- ✅ All 5 spec test cases covered across Tasks 1–5 + +**Placeholder scan:** None found. All code blocks are complete. + +**Type consistency:** +- `compute_joint_velocity` returns `dict[int, list[float]]` — used identically in `render_video`, `_draw_velocity_arrows`, and `build_velocity_summary`. ✓ +- `layers: set[str]` in `render_video`; converted from `list[str]` in `process_video` via set comprehension. ✓ +- `vis.last_velocities` set in `render_video`, read in `process_video`. ✓ +- `_draw_velocity_arrows(frame, kps, prev_kps, velocities, frame_idx)` — signature matches call in `render_video`. ✓ diff --git a/docs/superpowers/plans/2026-06-13-full-fms-session-pdf.md b/docs/superpowers/plans/2026-06-13-full-fms-session-pdf.md new file mode 100644 index 0000000000000000000000000000000000000000..c7ee694fb5a9cb5379a8b120b321c456c38f5de9 --- /dev/null +++ b/docs/superpowers/plans/2026-06-13-full-fms-session-pdf.md @@ -0,0 +1,1209 @@ +# Full FMS Session + PDF Report — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Turn FormScout's one-clip scorer into a screening session that accumulates analyzed clips into a composite 0–21 report and exports a branded PDF with annotated worst-moment key-frame stills. + +**Architecture:** A new `formscout/session.py` accumulates typed `SessionEntry` objects (one per analyzed clip), persisting each to a temp session dir. `PoseVisualizer.render_frame()` captures the governing frame (already computed by `BiomechanicsAgent` and stored in `features.timing`) as an annotated PNG. On "Finish", the existing `ReportAgent` computes composite + asymmetries, and a new `PdfReportAgent` renders a ReportLab PDF. The UI (`app.py`) gains `gr.State` session accumulation with "Analyse new clip" / "Finish & generate PDF" buttons. + +**Tech Stack:** Python 3.13, ReportLab (new dep), OpenCV (existing), Gradio 5, pytest. No model downloads in tests. + +--- + +## File Structure + +- `requirements.txt` — add `reportlab`. +- `formscout/types.py` — add `SessionEntry` frozen dataclass. +- `formscout/agents/biomechanics.py` — add `max_sag_frame` to `trunk_stability_pushup` timing (rotary already has `peak_extension_frame`). +- `formscout/agents/visualizer.py` — add `PoseVisualizer.render_frame()`. +- `formscout/session.py` — **new**: session accumulator (new/add/finish + persistence + key-frame helpers). +- `formscout/agents/pdf_report.py` — **new**: `PdfReportAgent` (ReportLab). +- `app.py` — wire `gr.State`, two buttons, "Session so far" table, finish handler. +- `tests/test_session.py`, `tests/test_keyframe.py`, `tests/test_pdf_report.py` — **new**. + +--- + +## Task 1: Add ReportLab dependency + +**Files:** +- Modify: `requirements.txt` + +- [ ] **Step 1: Add the dependency** + +Add this line to `requirements.txt` (after `pillow>=10.3`): + +``` +reportlab>=4.0 +``` + +- [ ] **Step 2: Install it** + +Run: `pip install 'reportlab>=4.0'` +Expected: `Successfully installed reportlab-4.x.x` + +- [ ] **Step 3: Verify import** + +Run: `python3 -c "import reportlab; print(reportlab.Version)"` +Expected: prints a version like `4.x.x` + +- [ ] **Step 4: Commit** + +```bash +git add requirements.txt +git commit -m "build: add reportlab for PDF report generation" +``` + +--- + +## Task 2: Add `SessionEntry` dataclass + +**Files:** +- Modify: `formscout/types.py` (after `ReportResult`, before `PipelineState`) +- Test: `tests/test_session.py` + +- [ ] **Step 1: Write the failing test** + +Create `tests/test_session.py` with: + +```python +"""Tests for the FMS session accumulator — no GPU, no model downloads.""" +import numpy as np + +from formscout.types import ( + IngestResult, Pose2DResult, BiomechFeatures, ScoreResult, JudgeResult, + MovementResult, SessionEntry, +) + + +def test_session_entry_holds_typed_objects(): + movement = MovementResult(test_name="deep_squat", side="na", confidence=1.0) + features = BiomechFeatures( + test_name="deep_squat", view="2d", side="na", + angles={"left_knee_flexion_deg": 95.0}, alignments={"knees_tracking_over_feet": True}, + symmetry_delta=None, timing={"deepest_frame": 2}, confidence=0.9, + ) + rubric = ScoreResult(score=2, rationale="ok", confidence=0.8) + judge = JudgeResult(score=2, rationale="ok", compensation_tags=["heels elevated"], + corrective_hint="ankle mobility", confidence=0.85) + entry = SessionEntry( + test_name="deep_squat", side="na", score=2, needs_human=False, + rationale="ok", compensation_tags=["heels elevated"], corrective_hint="ankle mobility", + measurements={"left_knee_flexion_deg": 95.0}, confidence=0.85, view="2d", + keyframe_path=None, movement=movement, features=features, + rubric_score=rubric, judge=judge, + ) + assert entry.score == 2 + assert entry.movement.test_name == "deep_squat" + assert entry.rubric_score.score == 2 + assert entry.judge.compensation_tags == ["heels elevated"] +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/test_session.py::test_session_entry_holds_typed_objects -v` +Expected: FAIL with `ImportError: cannot import name 'SessionEntry'` + +- [ ] **Step 3: Add the dataclass** + +In `formscout/types.py`, insert after the `ReportResult` class (line ~142) and before `PipelineState`: + +```python +@dataclass(frozen=True) +class SessionEntry: + """One accumulated analysis in a screening session. + + Display fields (test_name…keyframe_path) feed the PDF/JSON/MD artifacts; + the trailing typed objects (movement…judge) feed ReportAgent.run(). + """ + test_name: str + side: str + score: int | None + needs_human: bool + rationale: str + compensation_tags: list + corrective_hint: str + measurements: dict + confidence: float + view: str + keyframe_path: str | None + movement: MovementResult + features: BiomechFeatures + rubric_score: ScoreResult + judge: JudgeResult | None +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/test_session.py::test_session_entry_holds_typed_objects -v` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/types.py tests/test_session.py +git commit -m "feat: add SessionEntry typed contract for screening sessions" +``` + +--- + +## Task 3: Add governing-frame index to push-up biomechanics + +**Files:** +- Modify: `formscout/agents/biomechanics.py:468-529` (`_trunk_stability_pushup`) +- Test: `tests/test_biomechanics.py` (append a test) + +The other six tests already store a governing frame index in `features.timing` +(`deepest_frame`, `peak_step_frame`, `deepest_lunge_frame`, `measure_frame`, +`peak_raise_frame`, `peak_extension_frame`). Only `trunk_stability_pushup` is missing one. + +- [ ] **Step 1: Write the failing test** + +Append to `tests/test_biomechanics.py`: + +```python +def test_pushup_timing_has_max_sag_frame(): + from formscout.agents.biomechanics import BiomechanicsAgent + from formscout.types import Pose2DResult, Body3DResult, MovementResult + + # 4 frames; frame 2 has the largest hip sag (hip far below shoulder/ankle midline) + def kps(hip_y): + base = { + 5: {"x": 200, "y": 200, "conf": 0.9}, # L shoulder + 6: {"x": 220, "y": 200, "conf": 0.9}, # R shoulder + 11: {"x": 300, "y": hip_y, "conf": 0.9}, # L hip + 12: {"x": 320, "y": hip_y, "conf": 0.9}, # R hip + 15: {"x": 400, "y": 200, "conf": 0.9}, # L ankle + 16: {"x": 420, "y": 200, "conf": 0.9}, # R ankle + } + return base + + frames = [kps(200), kps(210), kps(260), kps(205)] + pose = Pose2DResult(keypoints=frames, fps=30.0, confidence=0.9) + body3d = Body3DResult(used=False, joints_3d=[]) + movement = MovementResult(test_name="trunk_stability_pushup", side="na", confidence=1.0) + + feats = BiomechanicsAgent().run(pose, body3d, movement) + assert "max_sag_frame" in feats.timing + assert feats.timing["max_sag_frame"] == 2 +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/test_biomechanics.py::test_pushup_timing_has_max_sag_frame -v` +Expected: FAIL with `assert 'max_sag_frame' in {...}` (KeyError-style assertion failure) + +- [ ] **Step 3: Track the max-sag frame index** + +In `formscout/agents/biomechanics.py`, replace the body of `_trunk_stability_pushup` from the +`trunk_angles_over_time = []` loop through the `if trunk_angles_over_time:` block. Replace: + +```python + # Analyze multiple frames to detect sag/lag + trunk_angles_over_time = [] + for i, kps in enumerate(pose2d.keypoints): +``` + +…down to and including the `alignments["no_sag"] = max_sag < 30` line, with: + +```python + # Analyze multiple frames to detect sag/lag + trunk_sags: list[tuple[int, float]] = [] # (frame_idx, sag_px) + for i, kps in enumerate(pose2d.keypoints): + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + l_ankle = _get_joint(kps, L_ANKLE) + r_ankle = _get_joint(kps, R_ANKLE) + + if l_sh and r_sh and l_hip and r_hip and l_ankle and r_ankle: + sh_y = (l_sh[1] + r_sh[1]) / 2 + hip_y = (l_hip[1] + r_hip[1]) / 2 + ankle_y = (l_ankle[1] + r_ankle[1]) / 2 + expected_hip_y = (sh_y + ankle_y) / 2 + sag_px = hip_y - expected_hip_y + trunk_sags.append((i, sag_px)) + + max_sag_frame = 0 + if trunk_sags: + sags = [s for _, s in trunk_sags] + max_sag_frame = max(trunk_sags, key=lambda t: t[1])[0] + mean = sum(sags) / len(sags) + variance = (sum((x - mean) ** 2 for x in sags) / len(sags)) ** 0.5 + max_sag = max(sags) + angles["max_sag_px"] = max_sag + angles["trunk_variance_px"] = variance + alignments["body_rigid"] = max_sag < 30 and variance < 15 + alignments["no_sag"] = max_sag < 30 + else: + notes_parts.append("insufficient landmarks for trunk analysis") +``` + +Then update the `return BiomechFeatures(...)` `timing=` argument at the end of the method from: + +```python + timing={"n_frames_analyzed": len(trunk_angles_over_time)}, +``` + +to: + +```python + timing={"n_frames_analyzed": len(trunk_sags), "max_sag_frame": max_sag_frame}, +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/test_biomechanics.py::test_pushup_timing_has_max_sag_frame -v` +Expected: PASS + +- [ ] **Step 5: Run the full biomechanics suite (no regressions)** + +Run: `pytest tests/test_biomechanics.py -v` +Expected: all previously-passing tests still pass (the pre-existing `test_unimplemented_test_returns_low_confidence` known-failure may remain failing — that is unrelated and documented in CLAUDE.md). + +- [ ] **Step 6: Commit** + +```bash +git add formscout/agents/biomechanics.py tests/test_biomechanics.py +git commit -m "feat: track max-sag frame index in push-up biomechanics for key-frame capture" +``` + +--- + +## Task 4: Add `PoseVisualizer.render_frame()` + +**Files:** +- Modify: `formscout/agents/visualizer.py` (add method to `PoseVisualizer`, after `render_video`) +- Test: `tests/test_keyframe.py` + +- [ ] **Step 1: Write the failing test** + +Create `tests/test_keyframe.py`: + +```python +"""Tests for PoseVisualizer.render_frame — single annotated still.""" +import os +import numpy as np + +from formscout.types import IngestResult, Pose2DResult + + +def _ingest(n=5, h=480, w=640): + frames = [np.zeros((h, w, 3), dtype=np.uint8) for _ in range(n)] + return IngestResult(frames=frames, fps=30.0, duration=n / 30.0, n_people=1, width=w, height=h) + + +def _pose(n=5): + kps = [] + for i in range(n): + kps.append({j: {"x": float(50 + j * 25), "y": float(80 + j * 18), "conf": 0.9} + for j in range(17)}) + return Pose2DResult(keypoints=kps, fps=30.0, confidence=0.9) + + +def test_render_frame_writes_png(tmp_path): + from formscout.agents.visualizer import PoseVisualizer + out = str(tmp_path / "key.png") + path = PoseVisualizer().render_frame(_ingest(), _pose(), frame_idx=2, + layers={"skeleton"}, caption="Deep Squat — heels elevated", + out_png=out) + assert path == out + assert os.path.exists(out) + assert os.path.getsize(out) > 0 + + +def test_render_frame_bad_index_returns_none(tmp_path): + from formscout.agents.visualizer import PoseVisualizer + out = str(tmp_path / "key.png") + path = PoseVisualizer().render_frame(_ingest(n=3), _pose(n=3), frame_idx=99, + layers={"skeleton"}, caption="", out_png=out) + assert path is None +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/test_keyframe.py -v` +Expected: FAIL with `AttributeError: 'PoseVisualizer' object has no attribute 'render_frame'` + +- [ ] **Step 3: Add the method** + +In `formscout/agents/visualizer.py`, inside the `PoseVisualizer` class, add this method +immediately after `render_video` (before the closing of the class / the module-level +`build_velocity_summary`): + +```python + def render_frame( + self, + ingest, + pose2d, + frame_idx: int, + layers: set[str], + caption: str = "", + out_png: str | None = None, + ) -> str | None: + """Render a single annotated still (skeleton + optional trails + caption). + + frame_idx is typically the governing frame from BiomechFeatures.timing. + Returns the PNG path on success, None on any failure. Never raises. + """ + try: + if not (0 <= frame_idx < len(ingest.frames)) or frame_idx >= len(pose2d.keypoints): + return None + + frame = ingest.frames[frame_idx].copy() + kps = pose2d.keypoints[frame_idx] + + if "trails" in layers: + trail: dict[int, deque] = {j: deque(maxlen=TRAIL_LENGTH) for j in range(17)} + start = max(0, frame_idx - TRAIL_LENGTH) + for fi in range(start, frame_idx + 1): + for j, kp in pose2d.keypoints[fi].items(): + if kp.get("conf", 0.0) >= CONF_THRESHOLD: + trail[j].append((kp["x"], kp["y"])) + frame = self._draw_trails(frame, trail) + + if "skeleton" in layers: + frame = self._draw_skeleton(frame, kps) + + if caption: + cv2.rectangle(frame, (0, 0), (frame.shape[1], 28), (0, 0, 0), -1) + cv2.putText(frame, caption[:80], (8, 20), cv2.FONT_HERSHEY_SIMPLEX, + 0.55, (255, 255, 255), 1, cv2.LINE_AA) + + if out_png is None: + out_png = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name + + ok = cv2.imwrite(out_png, frame) + return out_png if ok else None + except Exception as e: + logger.warning("render_frame failed: %s", e) + return None +``` + +(`deque`, `cv2`, `tempfile`, `logger`, `TRAIL_LENGTH`, `CONF_THRESHOLD` are all already imported at the top of this file.) + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/test_keyframe.py -v` +Expected: both tests PASS + +- [ ] **Step 5: Commit** + +```bash +git add formscout/agents/visualizer.py tests/test_keyframe.py +git commit -m "feat: add PoseVisualizer.render_frame for annotated key-frame stills" +``` + +--- + +## Task 5: Create the session accumulator + +**Files:** +- Create: `formscout/session.py` +- Test: `tests/test_session.py` (append tests) + +- [ ] **Step 1: Write the failing tests** + +Append to `tests/test_session.py`: + +```python +def _ingest(n=5, h=480, w=640): + frames = [np.zeros((h, w, 3), dtype=np.uint8) for _ in range(n)] + return IngestResult(frames=frames, fps=30.0, duration=n / 30.0, n_people=1, width=w, height=h) + + +def _pose(n=5): + kps = [] + for i in range(n): + kps.append({j: {"x": float(50 + j * 25), "y": float(80 + j * 18), "conf": 0.9} + for j in range(17)}) + return Pose2DResult(keypoints=kps, fps=30.0, confidence=0.9) + + +def _features(test_name="deep_squat", side="na", frame_key="deepest_frame"): + return BiomechFeatures( + test_name=test_name, view="2d", side=side, + angles={"left_knee_flexion_deg": 95.0}, + alignments={"knees_tracking_over_feet": False}, + symmetry_delta=None, timing={frame_key: 2}, confidence=0.9, + ) + + +def _judge(score=2, needs_human=False): + return JudgeResult( + score=None if needs_human else score, rationale="r", + compensation_tags=["heels elevated"], corrective_hint="ankle mobility", + confidence=0.85, needs_human=needs_human, + ) + + +def test_add_analysis_appends_entry_and_writes_files(): + import os + from formscout import session as S + sess = S.new_session() + entry = S.add_analysis(sess, ingest=_ingest(), pose2d=_pose(), + features=_features(), judge=_judge(), test_name="deep_squat", side="na") + assert len(sess.entries) == 1 + assert entry.score == 2 + assert os.path.exists(os.path.join(sess.session_dir, "session.json")) + assert os.path.exists(os.path.join(sess.session_dir, "analysis.md")) + # key-frame still written (deepest_frame=2 is valid) + assert entry.keyframe_path and os.path.exists(entry.keyframe_path) + + +def test_finish_composite_null_when_needs_human(): + from formscout import session as S + sess = S.new_session() + S.add_analysis(sess, ingest=_ingest(), pose2d=_pose(), features=_features(), + judge=_judge(score=3), test_name="deep_squat", side="na") + S.add_analysis(sess, ingest=_ingest(), pose2d=_pose(), + features=_features("trunk_stability_pushup", frame_key="max_sag_frame"), + judge=_judge(needs_human=True), test_name="trunk_stability_pushup", side="na") + report, pdf_path = S.finish_session(sess) + assert report is not None + assert report.composite is None # one test needs_human + + +def test_finish_empty_session_returns_none(): + from formscout import session as S + sess = S.new_session() + report, pdf_path = S.finish_session(sess) + assert report is None and pdf_path is None +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `pytest tests/test_session.py -v` +Expected: the three new tests FAIL with `ModuleNotFoundError: No module named 'formscout.session'` + +- [ ] **Step 3: Create the module** + +Create `formscout/session.py`: + +```python +""" +Screening-session accumulator. + +Accumulates one SessionEntry per analyzed clip, persists each to a temp session +dir (session.json + analysis.md + key-frame PNGs), and on finish builds a +ReportResult (via ReportAgent) + a PDF (via PdfReportAgent). + +Pure orchestration — no Gradio imports. Disk writes tolerate failure with a +logged warning and never block scoring. +""" +from __future__ import annotations + +import json +import logging +import os +import tempfile +import uuid +from dataclasses import dataclass, replace + +from formscout.rubric import score_test +from formscout.types import MovementResult, ReportResult, SessionEntry + +logger = logging.getLogger(__name__) + +# Maps each test to the BiomechFeatures.timing key holding its governing frame. +TIMING_KEY = { + "deep_squat": "deepest_frame", + "hurdle_step": "peak_step_frame", + "inline_lunge": "deepest_lunge_frame", + "shoulder_mobility": "measure_frame", + "active_slr": "peak_raise_frame", + "trunk_stability_pushup": "max_sag_frame", + "rotary_stability": "peak_extension_frame", +} + + +@dataclass +class Session: + """Mutable session: an id, its temp dir, and accumulated entries.""" + session_id: str + session_dir: str + entries: list # list[SessionEntry] + + +def new_session() -> Session: + sid = uuid.uuid4().hex[:12] + base = os.path.join(tempfile.gettempdir(), "formscout_sessions", sid) + try: + os.makedirs(os.path.join(base, "keyframes"), exist_ok=True) + except Exception as e: + logger.warning("session dir create failed: %s", e) + return Session(session_id=sid, session_dir=base, entries=[]) + + +def governing_frame_index(features) -> int | None: + """Return the governing frame index for this test, or None.""" + key = TIMING_KEY.get(features.test_name) + if key is None: + return None + idx = features.timing.get(key) + return int(idx) if isinstance(idx, (int, float)) else None + + +def worst_compensation_caption(judge, features) -> str: + """Short caption naming the worst compensation for the key-frame still.""" + if judge and getattr(judge, "compensation_tags", None): + return ", ".join(judge.compensation_tags) + failed = [k.replace("_", " ") for k, v in features.alignments.items() if v is False] + return ("compensation: " + ", ".join(failed)) if failed else "key position" + + +def add_analysis(session, *, ingest, pose2d, features, judge, test_name, side, + draw_trails: bool = False) -> SessionEntry: + """Build a SessionEntry from a completed analysis, render its key-frame, + persist the session, append, and return the entry.""" + movement = MovementResult(test_name=test_name, side=side, confidence=1.0) + rubric = score_test(features) + + needs_human = bool((judge and judge.needs_human) or rubric.needs_human) + if needs_human: + score = None + elif judge and judge.score is not None: + score = judge.score + else: + score = rubric.score + + keyframe_path = None + idx = governing_frame_index(features) + if idx is not None and 0 <= idx < len(pose2d.keypoints): + from formscout.agents.visualizer import PoseVisualizer + caption = (f"{test_name.replace('_', ' ').title()} " + f"({side}) — {worst_compensation_caption(judge, features)}") + layers = {"skeleton", "trails"} if draw_trails else {"skeleton"} + out_png = os.path.join(session.session_dir, "keyframes", f"{test_name}_{side}.png") + try: + keyframe_path = PoseVisualizer().render_frame(ingest, pose2d, idx, layers, caption, out_png) + except Exception as e: + logger.warning("keyframe render failed: %s", e) + + measurements = {} + measurements.update(features.angles) + measurements.update(features.alignments) + + entry = SessionEntry( + test_name=test_name, side=side, score=score, needs_human=needs_human, + rationale=(judge.rationale if judge else rubric.rationale), + compensation_tags=list(judge.compensation_tags) if judge else [], + corrective_hint=(judge.corrective_hint if judge else ""), + measurements=measurements, + confidence=(judge.confidence if judge else rubric.confidence), + view=features.view, + keyframe_path=keyframe_path, + movement=movement, features=features, rubric_score=rubric, judge=judge, + ) + session.entries.append(entry) + _persist(session) + return entry + + +def finish_session(session) -> tuple[ReportResult | None, str | None]: + """Build the composite report + PDF. Returns (report, pdf_path). + Returns (None, None) for an empty session.""" + if not session.entries: + return None, None + + from formscout.agents.report import ReportAgent + report_inputs = [{ + "movement": e.movement, "features": e.features, + "rubric_score": e.rubric_score, "judge": e.judge, "side": e.side, + } for e in session.entries] + report = ReportAgent().run(report_inputs) + + pdf_path = None + try: + from formscout.agents.pdf_report import PdfReportAgent + pdf_path = PdfReportAgent().run(report, session.entries, session.session_dir) + except Exception as e: + logger.warning("pdf generation failed: %s", e) + + report = replace(report, pdf_path=pdf_path) + return report, pdf_path + + +# ── Persistence ─────────────────────────────────────────────────────────────── + +def _jsonable(d: dict) -> dict: + out = {} + for k, v in d.items(): + if isinstance(v, float): + out[k] = round(v, 2) + elif isinstance(v, (int, str, bool)) or v is None: + out[k] = v + else: + out[k] = str(v) + return out + + +def _entry_display(e: SessionEntry) -> dict: + return { + "test_name": e.test_name, "side": e.side, "score": e.score, + "needs_human": e.needs_human, "rationale": e.rationale, + "compensation_tags": list(e.compensation_tags), "corrective_hint": e.corrective_hint, + "measurements": _jsonable(e.measurements), "confidence": round(e.confidence, 2), + "view": e.view, "keyframe_path": e.keyframe_path, + } + + +def _render_markdown(session: Session) -> str: + lines = ["# FormScout — Session Log", ""] + for e in session.entries: + title = e.test_name.replace("_", " ").title() + if e.side in ("left", "right"): + title += f" ({e.side})" + score = "Clinician review required" if e.needs_human else f"{e.score}/3" + lines.append(f"## {title} — {score}") + lines.append(e.rationale or "") + if e.compensation_tags: + lines.append(f"- Compensations: {', '.join(e.compensation_tags)}") + if e.corrective_hint: + lines.append(f"- Corrective: {e.corrective_hint}") + if e.keyframe_path: + lines.append(f"- Key frame: `{e.keyframe_path}`") + lines.append("") + return "\n".join(lines) + + +def _persist(session: Session) -> None: + try: + with open(os.path.join(session.session_dir, "session.json"), "w") as f: + json.dump([_entry_display(e) for e in session.entries], f, indent=2) + with open(os.path.join(session.session_dir, "analysis.md"), "w") as f: + f.write(_render_markdown(session)) + except Exception as e: + logger.warning("session persist failed: %s", e) +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pytest tests/test_session.py -v` +Expected: all session tests PASS (Task 6 provides `PdfReportAgent`; `finish_session` tolerates its +absence via the try/except, so these pass now — `pdf_path` may be `None` until Task 6). + +- [ ] **Step 5: Commit** + +```bash +git add formscout/session.py tests/test_session.py +git commit -m "feat: add screening-session accumulator with key-frame capture and persistence" +``` + +--- + +## Task 6: Create `PdfReportAgent` + +**Files:** +- Create: `formscout/agents/pdf_report.py` +- Test: `tests/test_pdf_report.py` + +- [ ] **Step 1: Write the failing test** + +Create `tests/test_pdf_report.py`: + +```python +"""Tests for PdfReportAgent — no GPU, no model downloads.""" +import os + +from formscout.types import ( + ReportResult, SessionEntry, MovementResult, BiomechFeatures, ScoreResult, JudgeResult, +) + + +def _entry(test_name="deep_squat", score=2, needs_human=False): + movement = MovementResult(test_name=test_name, side="na", confidence=1.0) + features = BiomechFeatures( + test_name=test_name, view="2d", side="na", + angles={"left_knee_flexion_deg": 95.0}, alignments={"knees_tracking_over_feet": False}, + symmetry_delta=None, timing={"deepest_frame": 1}, confidence=0.9, + ) + rubric = ScoreResult(score=2, rationale="rubric ok", confidence=0.8) + judge = JudgeResult(score=None if needs_human else score, rationale="judge rationale", + compensation_tags=["heels elevated"], corrective_hint="ankle mobility", + confidence=0.85, needs_human=needs_human) + return SessionEntry( + test_name=test_name, side="na", score=None if needs_human else score, + needs_human=needs_human, rationale="judge rationale", + compensation_tags=["heels elevated"], corrective_hint="ankle mobility", + measurements={"left_knee_flexion_deg": 95.0, "knees_tracking_over_feet": False}, + confidence=0.85, view="2d", keyframe_path=None, + movement=movement, features=features, rubric_score=rubric, judge=judge, + ) + + +def _report(composite=2): + return ReportResult( + per_test=[], composite=composite, asymmetries=[], + overlay_video_path=None, pdf_path=None, + low_confidence_flags=[], disagreement_flags=[], + ) + + +def test_pdf_is_created(tmp_path): + from formscout.agents.pdf_report import PdfReportAgent + path = PdfReportAgent().run(_report(2), [_entry()], str(tmp_path)) + assert path is not None + assert os.path.exists(path) + assert os.path.getsize(path) > 1000 # a real PDF, not an empty file + with open(path, "rb") as f: + assert f.read(5) == b"%PDF-" + + +def test_pdf_handles_incomplete_composite(tmp_path): + from formscout.agents.pdf_report import PdfReportAgent + path = PdfReportAgent().run(_report(None), [_entry(needs_human=True)], str(tmp_path)) + assert path is not None and os.path.exists(path) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pytest tests/test_pdf_report.py -v` +Expected: FAIL with `ModuleNotFoundError: No module named 'formscout.agents.pdf_report'` + +- [ ] **Step 3: Create the agent** + +Create `formscout/agents/pdf_report.py`: + +```python +""" +PdfReportAgent — renders a ReportResult + session entries to a branded PDF. + +Input: ReportResult, list[SessionEntry], session_dir (str) +Output: path to the written PDF (str), or None on failure. +Failure: returns None, never raises. +Params: 0 (pure rendering — no model). +License: n/a. +Gated: no. +""" +from __future__ import annotations + +import logging +import os + +from formscout.types import ReportResult + +logger = logging.getLogger(__name__) + +DISCLAIMER = "Screening aid — not a diagnosis. Pain or clearing tests require a clinician." + + +class PdfReportAgent: + """Assembles the screening-session PDF via ReportLab.""" + + def run(self, report: ReportResult, entries: list, session_dir: str) -> str | None: + try: + from reportlab.lib import colors + from reportlab.lib.pagesizes import LETTER + from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet + from reportlab.lib.units import inch + from reportlab.platypus import ( + Image, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle, + ) + except Exception as e: + logger.warning("reportlab unavailable: %s", e) + return None + + out_path = os.path.join(session_dir, "formscout_report.pdf") + try: + styles = getSampleStyleSheet() + banner = ParagraphStyle( + "banner", parent=styles["Normal"], fontSize=9, textColor=colors.white, + backColor=colors.HexColor("#b45309"), alignment=1, borderPadding=6, spaceAfter=12, + ) + story = [] + story.append(Paragraph(f"⚠ {DISCLAIMER}", banner)) + story.append(Paragraph("FormScout — FMS Screening Report", styles["Title"])) + + if report.composite is not None: + comp = f"Composite: {report.composite} / 21" + else: + comp = f"Composite: Incomplete — {len(entries)}/7 tests scored" + story.append(Paragraph(comp, styles["Heading2"])) + story.append(Spacer(1, 0.2 * inch)) + + for e in entries: + title = e.test_name.replace("_", " ").title() + if e.side in ("left", "right"): + title += f" ({e.side})" + score_txt = "Clinician review required" if e.needs_human else f"Score: {e.score}/3" + story.append(Paragraph(f"{title} — {score_txt}", styles["Heading3"])) + if e.rationale: + story.append(Paragraph(e.rationale, styles["Normal"])) + if e.compensation_tags: + story.append(Paragraph("Compensations: " + ", ".join(e.compensation_tags), + styles["Normal"])) + if e.corrective_hint: + story.append(Paragraph("Corrective: " + e.corrective_hint, styles["Normal"])) + + items = list(e.measurements.items())[:6] + if items: + rows = [[k.replace("_", " "), + (f"{v:.1f}" if isinstance(v, float) else str(v))] for k, v in items] + tbl = Table(rows, colWidths=[3 * inch, 1.5 * inch]) + tbl.setStyle(TableStyle([ + ("FONTSIZE", (0, 0), (-1, -1), 8), + ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor("#334155")), + ])) + story.append(tbl) + + if e.keyframe_path and os.path.exists(e.keyframe_path): + try: + story.append(Image(e.keyframe_path, width=3.0 * inch, height=2.25 * inch)) + except Exception: + story.append(Paragraph("(key-frame image unavailable)", styles["Normal"])) + else: + story.append(Paragraph("(key-frame image unavailable)", styles["Normal"])) + + story.append(Spacer(1, 0.2 * inch)) + + if report.asymmetries: + story.append(Paragraph("Asymmetries", styles["Heading2"])) + for a in report.asymmetries: + story.append(Paragraph( + f"{a['test'].replace('_', ' ').title()}: " + f"L={a['left_score']} R={a['right_score']} (Δ {a['delta']})", + styles["Normal"])) + + flags = list(report.low_confidence_flags) + list(report.disagreement_flags) + if flags: + story.append(Paragraph("Flags", styles["Heading2"])) + for fl in flags: + story.append(Paragraph(fl, styles["Normal"])) + + story.append(Spacer(1, 0.3 * inch)) + story.append(Paragraph(f"⚠ {DISCLAIMER}", banner)) + + doc = SimpleDocTemplate(out_path, pagesize=LETTER, + topMargin=0.6 * inch, bottomMargin=0.6 * inch) + doc.build(story) + return out_path + except Exception as e: + logger.warning("pdf build failed: %s", e) + return None +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pytest tests/test_pdf_report.py -v` +Expected: both tests PASS + +- [ ] **Step 5: Re-run the session suite (pdf_path now populated)** + +Run: `pytest tests/test_session.py -v` +Expected: all PASS (now `finish_session` returns a real `pdf_path`). + +- [ ] **Step 6: Commit** + +```bash +git add formscout/agents/pdf_report.py tests/test_pdf_report.py +git commit -m "feat: add PdfReportAgent — branded ReportLab session PDF" +``` + +--- + +## Task 7: Wire the session UI in `app.py` + +**Files:** +- Modify: `app.py` (`process_video`, `build_app`, event wiring) + +This task is verified by running the app (Gradio event wiring is not unit-tested; the +orchestration it calls is already covered by `tests/test_session.py`). + +- [ ] **Step 1: Import the session module** + +In `app.py`, add to the imports block (after `from formscout.startup import ensure_checkpoints`): + +```python +from formscout import session as session_mod +``` + +- [ ] **Step 2: Refactor `process_video` to accumulate into a session** + +Replace the entire `process_video` function (lines ~51-105) with a version that takes and +returns the session, appends an entry on success, and builds the "Session so far" table. +Replace from `def process_video(` through its final `return ...` with: + +```python +def process_video(video_path: str, test_name: str, side: str, model_key: str, + layers: list[str], session_state): + """Analyse one clip and accumulate it into the screening session.""" + if not video_path: + return ( + session_state, _render_empty_state(), "Upload a video to begin analysis.", + "", "", None, "", _render_session_table(session_state), + gr.update(visible=False), gr.update(visible=False), + ) + + if session_state is None: + session_state = session_mod.new_session() + + director = Director() + state = director.run(video_path, test_name=test_name, side=side, model_key=model_key) + + score_html = _render_empty_state() + score_details = "" + + if state.features: + result = score_test(state.features) + judge = state.judge + if judge and judge.score is not None: + score_html = _render_score_card(judge.score, judge.confidence, judge.needs_human) + score_details = _render_score_details_judge(judge, result, state.features) + elif judge and judge.needs_human: + score_html = _render_score_card(0, 0, True) + score_details = f"### Needs Clinician Review\n{judge.rationale}" + else: + score_html = _render_score_card(result.score, result.confidence, result.needs_human) + score_details = _render_score_details(result, state.features) + + # Accumulate into the session (only when we have a real analysis) + if state.ingest and state.pose2d and state.judge: + draw_trails = "trails" in {lbl.lower().replace(" ", "_") for lbl in (layers or [])} + try: + session_mod.add_analysis( + session_state, ingest=state.ingest, pose2d=state.pose2d, + features=state.features, judge=state.judge, + test_name=test_name, side=side, draw_trails=draw_trails, + ) + except Exception as e: + state.warnings.append(f"session accumulation failed: {e}") + + pipeline_md = _render_pipeline_status(state) + alerts = _render_alerts(state) + + overlay_path = None + vel_summary = "" + layer_set = {lbl.lower().replace(" ", "_") for lbl in (layers or [])} + if layer_set and state.ingest and state.pose2d: + try: + from formscout.agents.visualizer import PoseVisualizer, build_velocity_summary + vis = PoseVisualizer() + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + out_path = f.name + overlay_path = vis.render_video(state.ingest, state.pose2d, layer_set, out_path) + if overlay_path: + vel_summary = build_velocity_summary(state.pose2d.keypoints, vis.last_velocities) + except Exception as e: + alerts = (alerts or "") + f"\n⚠️ Visualizer error: {e}" + + has_entries = bool(session_state and session_state.entries) + return ( + session_state, score_html, pipeline_md, score_details, alerts, + overlay_path, vel_summary, _render_session_table(session_state), + gr.update(visible=has_entries), gr.update(visible=has_entries), + ) +``` + +- [ ] **Step 3: Add the session-table renderer and finish handler** + +In `app.py`, add these two functions just before `def build_app()`: + +```python +def _render_session_table(session_state) -> str: + """Render the accumulated 'Session so far' table as markdown.""" + if not session_state or not session_state.entries: + return "*No clips analysed yet.*" + lines = ["| Test | Side | Score | Status |", "|---|---|---|---|"] + for e in session_state.entries: + test = e.test_name.replace("_", " ").title() + side = e.side if e.side in ("left", "right") else "—" + if e.needs_human: + score, status = "—", "⚠️ Clinician review" + else: + score, status = f"{e.score}/3", "✓ scored" + lines.append(f"| {test} | {side} | {score} | {status} |") + return "\n".join(lines) + + +def _finish_session(session_state): + """Build the composite report + PDF for the whole session.""" + if not session_state or not session_state.entries: + return ("⚠️ No clips analysed yet — analyse at least one clip first.", + None, None) + + report, pdf_path = session_mod.finish_session(session_state) + if report is None: + return ("⚠️ Nothing to report.", None, None) + + if report.composite is not None: + summary = [f"## Composite: {report.composite} / 21"] + else: + n = len(session_state.entries) + summary = [f"## Composite: Incomplete — {n}/7 tests scored", + "*(One or more tests need clinician review or were unscored.)*"] + + if report.asymmetries: + summary.append("\n### Asymmetries") + for a in report.asymmetries: + test = a["test"].replace("_", " ").title() + summary.append(f"- **{test}:** L={a['left_score']} R={a['right_score']} (Δ {a['delta']})") + + flags = list(report.low_confidence_flags) + list(report.disagreement_flags) + if flags: + summary.append("\n### Flags") + for fl in flags: + summary.append(f"- {fl}") + + md_path = os.path.join(session_state.session_dir, "analysis.md") + md_out = md_path if os.path.exists(md_path) else None + return "\n".join(summary), pdf_path, md_out +``` + +Also add `import os` to the top of `app.py` if not already present (it currently imports only +`tempfile` and `gradio`). Add after `import tempfile`: + +```python +import os +``` + +- [ ] **Step 4: Add the session state, buttons, and outputs to `build_app`** + +In `build_app`, inside the `with gr.Blocks(...) as app:` block, immediately after the line +`with gr.Blocks(title="FormScout — FMS Screening Aid") as app:` add: + +```python + session_state = gr.State(None) +``` + +Then, in the left input column, replace the single submit button block: + +```python + submit_btn = gr.Button( + "🎯 Score Movement", + variant="primary", + size="lg", + ) +``` + +with: + +```python + submit_btn = gr.Button( + "🎯 Score Movement", + variant="primary", + size="lg", + ) + with gr.Row(): + new_clip_btn = gr.Button("➕ Analyse new clip", visible=False) + finish_btn = gr.Button("✅ Finish & generate PDF", + variant="primary", visible=False) +``` + +In the right results column, add a "Session" tab and a finish-output area. Inside `with gr.Tabs():` +add a new tab after the "🎬 Overlay Video" tab: + +```python + with gr.TabItem("🗂️ Session"): + session_table = gr.Markdown("*No clips analysed yet.*") + finish_summary = gr.Markdown("") + pdf_file = gr.File(label="Screening Report (PDF)", visible=True) + md_file = gr.File(label="Analysis Log (Markdown)", visible=True) +``` + +- [ ] **Step 5: Update event wiring** + +Replace the `_map_inputs` function and `submit_btn.click(...)` block at the bottom of `build_app` +with: + +```python + def _map_inputs(video, test_display_name, side_display, pose_model_key, overlay_layers, sess): + """Map UI display values to internal values and accumulate into the session.""" + test_map = {name: val for name, val in FMS_TESTS} + test_name = test_map.get(test_display_name, "deep_squat") + side = {"N/A": "na", "Left": "left", "Right": "right"}.get(side_display, "na") + return process_video(video, test_name, side, pose_model_key, overlay_layers, sess) + + submit_btn.click( + fn=_map_inputs, + inputs=[video_input, test_dropdown, side_dropdown, pose_model_dropdown, + overlay_layers, session_state], + outputs=[session_state, score_html, pipeline_md, score_details, alerts_md, + overlay_video, velocity_md, session_table, new_clip_btn, finish_btn], + ) + + def _new_clip(): + """Clear inputs for the next clip; keep the session intact.""" + return None, _render_empty_state(), "" + + new_clip_btn.click( + fn=_new_clip, + inputs=[], + outputs=[video_input, score_html, score_details], + ) + + finish_btn.click( + fn=_finish_session, + inputs=[session_state], + outputs=[finish_summary, pdf_file, md_file], + ) +``` + +- [ ] **Step 6: Verify the full test suite still passes** + +Run: `pytest tests/ -q` +Expected: all tests pass except the single pre-existing known failure documented in CLAUDE.md +(`test_unimplemented_test_returns_low_confidence`). No new failures. + +- [ ] **Step 7: Manually verify the app** + +Run: `python3 app.py` +Then in the browser: +1. Upload a clip, pick a test, click **Score Movement** → score card appears; the **Session** tab + shows one row; the two new buttons appear. +2. Click **➕ Analyse new clip** → the video input clears, the session row persists. +3. Analyse a second test → a second row appears. +4. Click **✅ Finish & generate PDF** → the Session tab shows the composite summary and a + downloadable PDF (open it: disclaimer top + bottom, per-test blocks with key-frame images, + composite or "Incomplete"). The Markdown log is also downloadable. + +Expected: all four steps work; PDF opens and contains the disclaimer, composite, and per-test sections. + +- [ ] **Step 8: Commit** + +```bash +git add app.py +git commit -m "feat: accumulate FMS clips into a session with composite report + PDF export" +``` + +--- + +## Task 8: Update docs + +**Files:** +- Modify: `CLAUDE.md` (Build phases / status) +- Modify: `MODEL_BUDGET.md` (no param change — note PDF agent adds 0 params, for completeness) + +- [ ] **Step 1: Update the Phase 4 line in CLAUDE.md** + +In `CLAUDE.md`, in the "Build phases" section, update the Phase 4 line from: + +``` +4. **Phase 4 — Polish + ship:** Custom Svelte UI components, PDF export, agent trace to Hub, blog post. (Overlay video already done via `PoseVisualizer`.) +``` + +to: + +``` +4. **Phase 4 — Polish + ship:** Custom Svelte UI components, agent trace to Hub, blog post. (Overlay video done via `PoseVisualizer`; full 7-test session + PDF export done via `formscout/session.py` + `PdfReportAgent`.) +``` + +- [ ] **Step 2: Note the PDF agent in the architecture section** + +In `CLAUDE.md`, under "### Rubric scorers" or near the ReportAgent description, this is optional +context; no required change. Skip if no natural home. + +- [ ] **Step 3: Commit** + +```bash +git add CLAUDE.md +git commit -m "docs: mark full FMS session + PDF export complete in build phases" +``` + +--- + +## Self-Review Notes (already applied) + +- **Spec coverage:** session accumulation (Task 5), two-button UX (Task 7), on-disk MD/JSON/keyframes (Task 5), key-frame from `features.timing` (Tasks 3–5), ReportLab PDF top/bottom disclaimer + composite + per-test + asymmetry + flags (Task 6), `SessionEntry` type (Task 2), `ReportAgent` reuse (Task 5 `finish_session`), composite-null-on-needs-human (Task 5 test), error tolerance / never-raise (Tasks 4–6). All covered. +- **Type consistency:** `SessionEntry` field names are identical across Tasks 2, 5, 6, 7. `finish_session` returns `(ReportResult | None, str | None)` and is consumed that way in Task 7. `render_frame(ingest, pose2d, frame_idx, layers, caption, out_png)` signature matches its callers. +- **No placeholders:** every code step shows complete code; every run step states the exact command + expected outcome. diff --git a/docs/superpowers/specs/2026-06-09-pose-model-selector-design.md b/docs/superpowers/specs/2026-06-09-pose-model-selector-design.md new file mode 100644 index 0000000000000000000000000000000000000000..883b01b167fe811bcd4a4c87e47b0eb94e3dc27d --- /dev/null +++ b/docs/superpowers/specs/2026-06-09-pose-model-selector-design.md @@ -0,0 +1,171 @@ +# Pose Model Selector — Design Spec + +**Date:** 2026-06-09 +**Status:** Approved + +## Goal + +Expose all available pose estimation models as a selectable dropdown in the Gradio UI, replacing the hard-coded YOLO26l default. Supported families: MediaPipe (Qualcomm HF/ONNX), YOLO26 n→x (local), Sapiens2 0.4B→5B (HF/transformers). + +--- + +## Architecture + +### Unified model registry (`config.py`) + +Replace `YOLO_POSE_MODELS` with a single `POSE_MODELS` dict. Each entry: + +```python +{ + "backend": "yolo" | "mediapipe" | "sapiens2", + "path": str, # yolo only — absolute path to local .pt + "hf_id": str, # mediapipe + sapiens2 — HuggingFace repo id + "params_m": float, # millions of parameters +} +``` + +Ordered as displayed in the UI: + +| Label | backend | source | +|---|---|---| +| `MediaPipe-Pose ⬇ ~16 MB, CPU-friendly` | mediapipe | `qualcomm/MediaPipe-Pose-Estimation` | +| `YOLO26n — nano (0.7M, fastest)` ★ default | yolo | local checkpoint | +| `YOLO26s — small (3.5M)` | yolo | local checkpoint | +| `YOLO26m — medium (9M)` | yolo | local checkpoint | +| `YOLO26l — large (25.9M)` | yolo | local checkpoint | +| `YOLO26x — extra-large (57.6M)` | yolo | local checkpoint | +| `Sapiens2-0.4B ⬇ ~1.6 GB` | sapiens2 | `facebook/sapiens2-pose-0.4b` | +| `Sapiens2-0.8B ⬇ ~3.2 GB` | sapiens2 | `facebook/sapiens2-pose-0.8b` | +| `Sapiens2-1B ⬇ ~4 GB` | sapiens2 | `facebook/sapiens2-pose-1b` | +| `Sapiens2-5B ⬇ ~20 GB, large GPU` | sapiens2 | `facebook/sapiens2-pose-5b` | + +```python +DEFAULT_POSE_MODEL = "YOLO26n — nano (0.7M, fastest)" +``` + +Keep `YOLO_POSE_MODEL` and `YOLO_POSE_MODEL_HQ` as string aliases for backward compat with any direct references outside the agent. + +--- + +### Pose2DAgent (`formscout/agents/pose2d.py`) + +Three private sub-runners, all returning `list[dict[int, dict]]` (COCO 17 keypoints per frame, same format as today): + +#### `_run_yolo(frames, path) -> list[dict]` +Existing logic, lifted into a named function. Model cached in `_model_cache[path]`. + +#### `_run_mediapipe(frames, hf_id) -> list[dict]` +- Download repo snapshot via `huggingface_hub.snapshot_download(hf_id)` +- Locate the pose landmark `.onnx` file in the snapshot +- Load with `onnxruntime.InferenceSession` +- Preprocess each frame: resize to 256×256, normalize +- Run inference → 33 BlazePose landmarks +- Map BlazePose 33 → COCO 17 via fixed index table: + ``` + COCO 0=nose → BlazePose 0 + COCO 1=left_eye → BlazePose 2 + COCO 2=right_eye → BlazePose 5 + COCO 3=left_ear → BlazePose 7 + COCO 4=right_ear → BlazePose 8 + COCO 5=left_shld → BlazePose 11 + COCO 6=right_shld → BlazePose 12 + COCO 7=left_elbow → BlazePose 13 + COCO 8=right_elbow → BlazePose 14 + COCO 9=left_wrist → BlazePose 15 + COCO 10=right_wrist → BlazePose 16 + COCO 11=left_hip → BlazePose 23 + COCO 12=right_hip → BlazePose 24 + COCO 13=left_knee → BlazePose 25 + COCO 14=right_knee → BlazePose 26 + COCO 15=left_ankle → BlazePose 27 + COCO 16=right_ankle → BlazePose 28 + ``` +- Session cached in `_model_cache[hf_id]` + +#### `_run_sapiens2(frames, hf_id) -> list[dict]` +- Load via `transformers.pipeline("pose-estimation", model=hf_id)` +- Sapiens2 outputs 308 whole-body keypoints; map first 17 (indices 0–16) to COCO 17 — Sapiens2 preserves COCO ordering for the body subset +- Pipeline cached in `_model_cache[hf_id]` + +#### `Pose2DAgent.run(ingest, model_key)` +- `model_key: str` replaces `model_path: str` (old param) +- Looks up `config.POSE_MODELS[model_key]` (falls back to `DEFAULT_POSE_MODEL` if key missing) +- Dispatches to the appropriate sub-runner +- Returns `Pose2DResult` — identical contract as today + +--- + +### UI (`app.py`) + +Add `gr.Dropdown` for pose model in the input column, below the test/side row: + +```python +pose_model_dropdown = gr.Dropdown( + choices=list(config.POSE_MODELS.keys()), + value=config.DEFAULT_POSE_MODEL, + label="Pose Model", +) +``` + +Update `_map_inputs` to accept and forward `pose_model_key`: + +```python +def _map_inputs(video, test_display_name, side_display, pose_model_key): + ... + return process_video(video, test_name, side, pose_model_key) +``` + +Update `submit_btn.click` inputs to include `pose_model_dropdown`. + +`process_video(video_path, test_name, side, pose_model_key)` passes `pose_model_key` through to `director.run()`, which passes it to `Pose2DAgent.run()`. Remove the old `YOLO_POSE_MODELS.get()` lookup from `process_video`. + +--- + +## Data flow + +``` +UI dropdown (pose_model_key: str) + → process_video() + → Director.run(pose_model_key=...) + → Pose2DAgent.run(ingest, model_key=pose_model_key) + → config.POSE_MODELS[model_key] → {backend, path|hf_id} + → _run_yolo / _run_mediapipe / _run_sapiens2 + → list[dict[int, {x, y, conf}]] (COCO 17, same contract) + → Pose2DResult +``` + +--- + +## Error handling + +- Unknown `model_key`: log warning, fall back to `DEFAULT_POSE_MODEL` +- ONNX file not found in MediaPipe snapshot: `Pose2DResult(confidence=0.0, notes="mediapipe onnx not found")` +- Sapiens2 / MediaPipe download failure: `Pose2DResult(confidence=0.0, notes=str(e))` +- All failures are non-fatal; pipeline continues with 0-confidence result and surfaces alert in UI + +--- + +## Dependencies to add (`requirements.txt`) + +- `onnxruntime` — MediaPipe ONNX inference +- `huggingface_hub` — snapshot download for MediaPipe (already likely present via transformers) + +Sapiens2 uses `transformers`, already a dependency. + +--- + +## Testing + +Each new backend gets a pytest in `tests/test_pose2d.py` that: +- Mocks the model load (no actual HF download in CI) +- Passes a 3-frame synthetic IngestResult +- Asserts `Pose2DResult.keypoints` has 3 entries, each a dict with at most 17 int keys +- Asserts `confidence` is a float in [0, 1] + +--- + +## Out of scope + +- Sapiens2 / MediaPipe accuracy benchmarking +- Automatic backend selection based on hardware +- Downloading Sapiens2/MediaPipe checkpoints to local `checkpoints/` directory diff --git a/docs/superpowers/specs/2026-06-09-pose-visualizer-design.md b/docs/superpowers/specs/2026-06-09-pose-visualizer-design.md new file mode 100644 index 0000000000000000000000000000000000000000..340cc6ee26a49b16b348411298cf434f598a3d3e --- /dev/null +++ b/docs/superpowers/specs/2026-06-09-pose-visualizer-design.md @@ -0,0 +1,197 @@ +# Pose Overlay Visualizer — Design Spec + +**Date:** 2026-06-09 +**Status:** Approved + +## Goal + +Add an annotated overlay video output to the FormScout UI showing skeleton, motion trails, and velocity arrows on top of the original footage, alongside a per-joint velocity summary table. Overlay layers are user-selectable via checkboxes. Adapted from the Laban Movement Analysis project. + +--- + +## Architecture + +Three files change or are created. No changes to `pipeline.py`, `types.py`, or any existing agent. + +``` +formscout/agents/visualizer.py ← new +tests/test_visualizer.py ← new +app.py ← overlay_layers checkbox, new tab, wiring +``` + +The visualizer runs **after** `director.run()` returns in `process_video()` — it is a pure post-processing step, never on the critical scoring path. + +--- + +## Module: `formscout/agents/visualizer.py` + +### `compute_joint_velocity(keypoints_per_frame, fps) → dict[int, list[float]]` + +- Input: `list[dict[int, {x, y, conf}]]` (COCO-17 pixel coords per frame), `fps: float` +- Output: `dict[int, list[float]]` — per-joint per-frame speed in **px/s** +- Method: for each joint index, run a `SimpleKalmanFilter` (1D per axis, constant-velocity model, same structure as Laban's engine) over the (x, y) series. Speed = `sqrt(vx² + vy²)` from the filter's velocity state. +- Missing keypoints (conf < 0.3 or absent) → speed = 0.0 for that frame, filter state held. + +### `SimpleKalmanFilter` + +Minimal 4-state Kalman (x, y, vx, vy), identical in structure to the Laban `SimpleKalmanFilter`: +- Transition: constant-velocity model +- Measurement: position only (x, y) +- One instance per joint per video run + +### `PoseVisualizer` + +#### Constants +```python +COCO_SKELETON = [ + (0,1),(0,2),(1,3),(2,4), # face + (5,6),(5,7),(7,9),(6,8),(8,10), # arms + (5,11),(6,12),(11,12), # torso + (11,13),(13,15),(12,14),(14,16), # legs +] +TRAIL_LENGTH = 10 # frames of trail history +MAX_ARROW_PX = 40 # arrow scaled so peak velocity → 40px length +CONF_THRESHOLD = 0.3 # min confidence to draw a keypoint +``` + +#### Private methods + +**`_draw_skeleton(frame, kps)`** +- Draw each COCO bone as a line if both endpoints have conf > CONF_THRESHOLD +- Joint dots: color green→red by confidence using HSV (same as Laban `_confidence_to_color`) +- Bone color: white + +**`_draw_trails(frame, trail_history, frame_idx)`** +- `trail_history: dict[int, deque(maxlen=TRAIL_LENGTH)]` keyed by joint index +- Each deque holds `(x, y)` pixel positions from previous frames +- Draw fading line segments: alpha = segment_position / TRAIL_LENGTH, color white + +**`_draw_velocity_arrows(frame, kps, velocities, frame_idx)`** +- `velocities: dict[int, list[float]]` — speeds per joint per frame +- Direction vector from consecutive keypoint positions (x[t] - x[t-1], y[t] - y[t-1]) +- Arrow length = `speed / peak_speed * MAX_ARROW_PX` (clamped) +- Drawn only for joints with conf > CONF_THRESHOLD and speed > 0 +- Color: green=slow, orange=medium, red=fast (same thresholds as Laban intensity) + +#### Public method + +**`render_video(ingest, pose2d, layers: set[str], output_path: str) → str | None`** +- `layers`: subset of `{"skeleton", "trails", "velocity_arrows"}` +- If `layers` is empty → return `None` immediately +- Pre-computes `compute_joint_velocity(pose2d.keypoints, ingest.fps)` +- Iterates frames, updates `trail_history`, calls selected `_draw_*` methods +- Writes output via `cv2.VideoWriter` (codec: `mp4v`, same fps as ingest) +- Returns output path on success; `None` on any exception (logs warning) + +#### Velocity summary + +**`build_velocity_summary(keypoints_per_frame, velocities) → str`** +- For each joint with conf > 0.3 in >50% of frames: + - Compute avg and peak speed (px/s) +- Return markdown table sorted by peak speed descending: + ``` + | Joint | Avg (px/s) | Peak (px/s) | + |---------------|-----------|-------------| + | left_knee | 42.3 | 118.7 | + ``` +- Returns empty string if no valid joints + +--- + +## UI changes: `app.py` + +### Input column — overlay layer checkboxes + +Below `pose_model_dropdown`, add: + +```python +overlay_layers = gr.CheckboxGroup( + choices=["Skeleton", "Trails", "Velocity arrows"], + value=["Skeleton", "Trails"], + label="Overlay Layers", +) +``` + +### Results panel — new tab + +Inside the existing `gr.Tabs()` block, add a fourth tab: + +```python +with gr.TabItem("🎬 Overlay Video"): + overlay_video = gr.Video(label="Annotated Movement") + velocity_md = gr.Markdown("") +``` + +### `process_video()` signature + +```python +def process_video(video_path, test_name, side, model_key, layers: list[str]): +``` + +After `director.run()`: +```python +from formscout.agents.visualizer import PoseVisualizer, build_velocity_summary +layer_set = {l.lower().replace(" ", "_") for l in layers} +# map UI labels to internal names: +# "Skeleton" → "skeleton", "Trails" → "trails", "Velocity arrows" → "velocity_arrows" +overlay_path = None +vel_summary = "" +if layer_set and state.ingest and state.pose2d: + try: + vis = PoseVisualizer() + with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as f: + out_path = f.name + overlay_path = vis.render_video(state.ingest, state.pose2d, layer_set, out_path) + if overlay_path: + vel_summary = build_velocity_summary(state.pose2d.keypoints, vis.last_velocities) + except Exception as e: + alerts += f"\n⚠️ Visualizer error: {e}" +return score_html, pipeline_md, score_details, alerts, overlay_path, vel_summary +``` + +`vis.last_velocities` is stored on the instance after `render_video()` to avoid recomputing. + +### Event wiring + +```python +submit_btn.click( + fn=_map_inputs, + inputs=[video_input, test_dropdown, side_dropdown, pose_model_dropdown, overlay_layers], + outputs=[score_html, pipeline_md, score_details, alerts_md, overlay_video, velocity_md], +) +``` + +`_map_inputs` gains `overlay_layers` as fifth parameter. + +--- + +## Error handling + +| Failure | Behaviour | +|---|---| +| All frames have no detections | `render_video()` returns `None`, tab empty, no crash | +| `cv2.VideoWriter` fails | logs warning, returns `None` | +| Any exception in visualizer | caught in `process_video()`, appended to alerts, `overlay_path = None` | +| `layers` is empty | returns `None` immediately, no processing | + +The score is always returned regardless of visualizer outcome. + +--- + +## Testing: `tests/test_visualizer.py` + +- Synthetic `IngestResult`: 5 blank 480×640 BGR frames, fps=30 +- Synthetic `Pose2DResult`: 17 keypoints per frame at fixed positions with conf=0.9 +- `test_render_video_creates_file`: assert output `.mp4` exists and size > 0 +- `test_compute_joint_velocity_shape`: assert 17-key dict, each list length == 5 +- `test_empty_layers_returns_none`: assert `render_video(..., layers=set())` returns `None` +- `test_no_detections_returns_none`: all-empty keypoints → `None` +- `test_velocity_summary_markdown`: assert output contains `|` (table) and at least one joint name + +--- + +## Out of scope + +- Frame-by-frame metrics synced to video playback (Phase 4 / custom Svelte) +- Multi-person tracking +- Saving overlay video to Hugging Face Hub (tracing feature, Phase 4) diff --git a/docs/superpowers/specs/2026-06-13-full-fms-session-pdf-design.md b/docs/superpowers/specs/2026-06-13-full-fms-session-pdf-design.md new file mode 100644 index 0000000000000000000000000000000000000000..91076010b7c9a297e4a839aac50cc9c44af41f1b --- /dev/null +++ b/docs/superpowers/specs/2026-06-13-full-fms-session-pdf-design.md @@ -0,0 +1,154 @@ +# Full FMS Session + PDF Report — Design + +**Date:** 2026-06-13 +**Status:** Approved (brainstorming) — pending implementation plan +**Owner:** FormScout +**Related:** `formscout/agents/report.py`, `formscout/agents/visualizer.py`, `formscout/agents/biomechanics.py`, `app.py`, `formscout/types.py` + +## Problem + +FormScout today scores **one** FMS test per upload. A real Functional Movement Screen is **all 7 tests** producing a single **composite 0–21** with asymmetry flags. `ReportAgent` and `ReportResult.composite` already support a multi-test report, but the UI never accumulates more than one test, and `ReportResult.pdf_path` is a hardcoded `None` stub. + +This feature turns the one-clip scorer into a **screening session**: each analyzed clip accumulates; a "Finish" action produces the composite report plus a downloadable, brand-consistent **PDF**. Each clip's worst-moment frame is captured as an annotated still embedded in both an on-disk log and the PDF. + +## Goals + +- Accumulate multiple analyzed clips into one session, then emit a composite 0–21 report. +- Generate a clinician/client-facing **PDF** handout (ReportLab) with scores, rationale, asymmetries, key-frame images, and the safety disclaimer. +- Capture and annotate the **worst-moment frame** per test (the governing/peak frame already computed by `BiomechanicsAgent`). +- Persist each analysis incrementally to disk (`session.json`, `analysis.md`, key-frame PNGs) until "Finish" is clicked. + +## Non-goals (YAGNI) + +- No cross-restart session reload — the session lives in `gr.State` + a temp dir for the browser session. +- No PDF styling beyond a clean branded layout (no HTML/CSS engine; ReportLab only). +- No RAG / exemplar-clip citations (separate future spec). +- No changes to the scoring pipeline, rubric functions, or Director flow. + +## UX + +The current one-clip-at-a-time flow is preserved. Two new buttons appear after an analysis completes: + +- **➕ Analyse new clip** — clears the video/test inputs for the next upload; **keeps** the session. +- **✅ Finish & generate PDF** — runs the report + PDF over everything accumulated so far. + +After each analysis, a **"Session so far"** table updates: `test · side · score · status`. Finish renders an on-screen composite scorecard + asymmetry summary and exposes the PDF (and `analysis.md`) via `gr.File` for download. + +Guard: Finish with zero analyses → warning, no PDF. + +## Components + +### 1. Session state + on-disk store + +A per-session temp directory `/formscout_sessions//`: + +- `session.json` — structured list of entries; **source of truth** for the PDF. +- `analysis.md` — human-readable log, appended after each clip. +- `keyframes/_.png` — annotated worst-frame stills. + +Session identity lives in a `gr.State`. Each entry carries: + +- `test_name`, `side`, `score` (judge score, else rubric), `needs_human` +- `rationale`, `compensation_tags`, `corrective_hint` +- key measurements (selected `angles` / `alignments`) +- `confidence`, `view` (`"2d"`/`"3d"`) +- `keyframe_path` +- the `movement` / `features` / `rubric_score` / `judge` objects that `ReportAgent.run()` consumes + +Persistence lasts until Finish; files are kept afterward for download. Cross-restart cleanup is best-effort and out of scope. + +### 2. Key-frame capture + +New method on `PoseVisualizer`: + +```python +def render_frame(self, ingest, pose2d, frame_idx: int, + layers: set[str], caption: str, out_png: str) -> str | None +``` + +- `frame_idx` comes from `features.timing`, which already stores the governing frame per test: + `deep_squat → deepest_frame`, `hurdle_step → peak_step_frame`, + `inline_lunge → deepest_lunge_frame`, `shoulder_mobility → measure_frame`, + `active_slr → peak_raise_frame`. +- `trunk_stability_pushup` and `rotary_stability` currently store only counts in `timing`. Add the worst-sag-frame and peak-extension-frame index to their `timing` dicts (one-line change in each `BiomechanicsAgent` method). +- Reuses `_draw_skeleton` (+ optional `_draw_trails`) on the single frame, overlays a caption naming the worst compensation, writes a PNG. +- Returns `None` on any failure — never raises, never blocks the entry. + +The "worst compensation" caption is derived from `judge.compensation_tags` (preferred) or the failed `alignments` (fallback). + +### 3. PDF generator + +New module `formscout/agents/pdf_report.py`: + +```python +class PdfReportAgent: + def run(self, report_result: ReportResult, + entries: list[SessionEntry], session_dir: str) -> str | None +``` + +Uses **ReportLab** (pure-Python, no system deps — safe on HF Spaces/ZeroGPU). Layout: + +- Safety disclaimer banner at **top and bottom** (mirrors the UI invariant). +- Title/brand header + date. +- Composite **0–21** badge, or "Incomplete — N/7 tests scored" when `composite is None`. +- Per-test block: score, rationale, key measurements, compensation tags, corrective hint, the annotated key-frame image, asymmetry delta (bilateral). +- Flags section: low-confidence, rubric↔judge disagreement, needs-human. +- Populates `ReportResult.pdf_path`. + +Returns the PDF path, or `None` on failure (UI surfaces the error and keeps the session for retry). Image embedding tolerates a missing/`None` `keyframe_path` with a placeholder line. + +### 4. ReportAgent reuse + +At Finish, build the entry list and call the existing `ReportAgent.run()` for composite + asymmetries + flags. The bilateral lower-score + asymmetry-delta logic and the null-composite rule already exist and are not rewritten. A small adapter converts `SessionEntry` objects to the dict schema `ReportAgent.run()` expects (or `ReportAgent` gains overload tolerance — implementer's choice, keep it minimal). + +### 5. Types + +Add a `SessionEntry` frozen dataclass to `formscout/types.py` (consistent with the "every agent I/O is a typed dataclass" standard), including `keyframe_path: str | None`. Populate the existing `ReportResult.pdf_path` (and optionally `overlay_video_path`). No other type changes. + +### 6. UI (`app.py`) + +- Add a `gr.State` holding the session (id + entries). +- After each analysis: render the scorecard as today, append the entry, write `session.json`/`analysis.md`/keyframe PNG, refresh the "Session so far" table, and reveal the two buttons. +- **Analyse new clip**: reset the video/test/side inputs; keep session state. +- **Finish & generate PDF**: `ReportAgent.run` → `PdfReportAgent.run` → display composite + asymmetry summary + `gr.File` downloads (PDF + `analysis.md`). +- Guard: Finish with zero analyses → warning. + +## Data flow + +``` +upload → Director.run → score + → build SessionEntry (+ render_frame keyframe png) + → append to gr.State + write session.json / analysis.md / keyframe png + → refresh "Session so far" table + +Finish → ReportAgent.run(entries) → composite / asymmetries / flags + → PdfReportAgent.run(...) → pdf_path + → on-screen composite + gr.File (PDF, analysis.md) +``` + +## Error handling + +- Key-frame render fails → entry still saved; PDF shows an image placeholder. +- PDF generation fails → surface the error, keep the session intact for retry. +- `needs_human` entry → no numeric score; PDF shows "Clinician review required"; composite null. +- Composite is `None` whenever any test is unscored or needs human review (existing rule — never show a partial 0–21 as complete). +- All disk writes tolerate failure with a logged warning; a write failure degrades the artifact but never blocks scoring. + +## Testing (must run without model downloads) + +- `tests/test_pdf_report.py` — synthetic `ReportResult` + entries → PDF file created, non-zero size, contains the disclaimer text and composite line. +- `tests/test_session.py` — accumulation; composite math; bilateral lower-score + asymmetry delta; null composite when one entry `needs_human`. +- `tests/test_keyframe.py` — `render_frame` returns a real PNG path (file exists) for a synthetic frame; returns `None` gracefully on bad input. + +## Invariants preserved + +- Pipeline stays headless — no Gradio imports in agent files (`PdfReportAgent` is a pure agent; key-frame capture stays in `visualizer.py`, the existing UI-layer component). +- Safety disclaimer present top and bottom of the PDF, mirroring the UI. +- Pain / clearing / needs-human is never auto-scored; composite null when any test unscored. +- New code follows the engineering standards: one public entrypoint per agent, typed dataclass I/O, `confidence`/`notes` where applicable, module docstring stating purpose/inputs/outputs/failure/params/license/gated. + +## Open implementation choices (left to the plan) + +- Exact `SessionEntry` → `ReportAgent` dict adapter shape. +- Which measurements to surface per test in the PDF (a curated subset, not the full `angles` dump). +- PDF assertion strategy in tests (text extraction vs. size/smoke). diff --git a/formscout/__init__.py b/formscout/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/formscout/agents/__init__.py b/formscout/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/formscout/agents/biomechanics.py b/formscout/agents/biomechanics.py new file mode 100644 index 0000000000000000000000000000000000000000..510f3285777b74bf3871059d443ab357dddbb22d --- /dev/null +++ b/formscout/agents/biomechanics.py @@ -0,0 +1,608 @@ +""" +BiomechanicsAgent — extracts named, documented, unit-bearing measurements from pose data. + +Input: Pose2DResult (or Body3DResult if used), MovementResult +Output: BiomechFeatures(test_name, view, angles, alignments, ...) +Failure: returns BiomechFeatures with confidence=0.0 and notes. +Params: 0 (pure computation — no model). +License: n/a. +Gated: no. + +This module is MEASUREMENT ONLY — no scoring happens here. +Scoring is done by the rubric functions in formscout/rubric/. +""" +from __future__ import annotations + +import math +from typing import Any + +from formscout.types import ( + Pose2DResult, Body3DResult, MovementResult, BiomechFeatures, +) +from formscout import config + + +def _angle_between_points(a: tuple, b: tuple, c: tuple) -> float: + """ + Compute angle at point b formed by segments ba and bc. + Returns degrees. Returns NaN if any point is missing. + """ + try: + ba = (a[0] - b[0], a[1] - b[1]) + bc = (c[0] - b[0], c[1] - b[1]) + dot = ba[0] * bc[0] + ba[1] * bc[1] + mag_ba = math.sqrt(ba[0] ** 2 + ba[1] ** 2) + mag_bc = math.sqrt(bc[0] ** 2 + bc[1] ** 2) + if mag_ba == 0 or mag_bc == 0: + return float("nan") + cos_angle = max(-1.0, min(1.0, dot / (mag_ba * mag_bc))) + return math.degrees(math.acos(cos_angle)) + except (TypeError, IndexError, ZeroDivisionError): + return float("nan") + + +def _get_joint(keypoints: dict, joint_id: int) -> tuple | None: + """Extract (x, y) for a joint, or None if missing/low-confidence.""" + j = keypoints.get(joint_id) + if j is None: + return None + if j.get("conf", 0) < config.POSE_CONF_THRESHOLD: + return None + return (j["x"], j["y"]) + + +# COCO joint indices +NOSE, L_EYE, R_EYE, L_EAR, R_EAR = 0, 1, 2, 3, 4 +L_SHOULDER, R_SHOULDER = 5, 6 +L_ELBOW, R_ELBOW = 7, 8 +L_WRIST, R_WRIST = 9, 10 +L_HIP, R_HIP = 11, 12 +L_KNEE, R_KNEE = 13, 14 +L_ANKLE, R_ANKLE = 15, 16 + + +class BiomechanicsAgent: + """Pure-function biomechanics measurement — no model calls.""" + + def run( + self, + pose2d: Pose2DResult, + body3d: Body3DResult, + movement: MovementResult, + ) -> BiomechFeatures: + if not pose2d.keypoints: + return BiomechFeatures( + test_name=movement.test_name, + view="2d", + side=movement.side, + angles={}, alignments={}, + symmetry_delta=None, timing={}, + confidence=0.0, + notes="no keypoints available", + ) + + view = "3d" if body3d.used else "2d" + + dispatch = { + "deep_squat": self._deep_squat, + "hurdle_step": self._hurdle_step, + "inline_lunge": self._inline_lunge, + "shoulder_mobility": self._shoulder_mobility, + "active_slr": self._active_slr, + "trunk_stability_pushup": self._trunk_stability_pushup, + "rotary_stability": self._rotary_stability, + } + fn = dispatch.get(movement.test_name) + if fn is None: + return BiomechFeatures( + test_name=movement.test_name, view=view, side=movement.side, + angles={}, alignments={}, symmetry_delta=None, timing={}, + confidence=0.0, notes=f"unknown test: {movement.test_name}", + ) + return fn(pose2d, view, movement.side) + + def _deep_squat(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """Extract deep squat biomechanics from the deepest frame.""" + # Find the frame with lowest hip Y (deepest squat position) + best_frame_idx = 0 + lowest_hip_y = -1.0 + for i, kps in enumerate(pose2d.keypoints): + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + if l_hip and r_hip: + mid_hip_y = (l_hip[1] + r_hip[1]) / 2 + if mid_hip_y > lowest_hip_y: # higher Y = lower in image + lowest_hip_y = mid_hip_y + best_frame_idx = i + + kps = pose2d.keypoints[best_frame_idx] + notes_parts: list[str] = [] + + # Extract joints + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + l_knee = _get_joint(kps, L_KNEE) + r_knee = _get_joint(kps, R_KNEE) + l_ankle = _get_joint(kps, L_ANKLE) + r_ankle = _get_joint(kps, R_ANKLE) + l_shoulder = _get_joint(kps, L_SHOULDER) + r_shoulder = _get_joint(kps, R_SHOULDER) + + # Compute angles + angles: dict[str, float] = {} + + # Hip-knee-ankle angle (knee flexion) — average of both sides + l_knee_angle = _angle_between_points(l_hip, l_knee, l_ankle) if all([l_hip, l_knee, l_ankle]) else float("nan") + r_knee_angle = _angle_between_points(r_hip, r_knee, r_ankle) if all([r_hip, r_knee, r_ankle]) else float("nan") + + if not math.isnan(l_knee_angle): + angles["left_knee_flexion_deg"] = l_knee_angle + else: + notes_parts.append("left knee angle unavailable") + + if not math.isnan(r_knee_angle): + angles["right_knee_flexion_deg"] = r_knee_angle + else: + notes_parts.append("right knee angle unavailable") + + # Femur angle from horizontal + # Femur = hip to knee. Angle from horizontal = atan2(dy, dx) + if l_hip and l_knee: + dy = l_knee[1] - l_hip[1] + dx = l_knee[0] - l_hip[0] + angles["left_femur_from_horizontal_deg"] = abs(math.degrees(math.atan2(dy, dx))) + if r_hip and r_knee: + dy = r_knee[1] - r_hip[1] + dx = r_knee[0] - r_hip[0] + angles["right_femur_from_horizontal_deg"] = abs(math.degrees(math.atan2(dy, dx))) + + # Torso-tibia angle (torso parallel to tibia = score 3 criterion) + if l_shoulder and l_hip and l_knee and l_ankle: + torso_angle = math.degrees(math.atan2(l_hip[1] - l_shoulder[1], l_hip[0] - l_shoulder[0])) + tibia_angle = math.degrees(math.atan2(l_ankle[1] - l_knee[1], l_ankle[0] - l_knee[0])) + angles["torso_tibia_angle_deg"] = abs(torso_angle - tibia_angle) + + # Alignments + alignments: dict[str, Any] = {} + + # Knee valgus check: are knees inside the ankle line? + if l_knee and r_knee and l_ankle and r_ankle: + knee_width = abs(l_knee[0] - r_knee[0]) + ankle_width = abs(l_ankle[0] - r_ankle[0]) + alignments["knees_tracking_over_feet"] = knee_width >= (ankle_width - config.DEEP_SQUAT_KNEE_TRACKING_MARGIN_PX) + alignments["knee_valgus_deg"] = 0.0 # placeholder for actual valgus angle + + # Heels elevated detection (approximation: ankle Y relative to frame bottom) + # This is a rough heuristic — proper detection needs foot keypoints or depth + alignments["heels_elevated"] = False # default; refine with better detection + + # Dowel position (need wrist positions relative to feet) + if l_wrist := _get_joint(kps, L_WRIST): + if r_wrist := _get_joint(kps, R_WRIST): + if l_ankle and r_ankle: + mid_wrist_x = (l_wrist[0] + r_wrist[0]) / 2 + mid_ankle_x = (l_ankle[0] + r_ankle[0]) / 2 + alignments["dowel_over_feet"] = abs(mid_wrist_x - mid_ankle_x) < 50 + alignments["dowel_feet_offset_px"] = mid_wrist_x - mid_ankle_x + + # Confidence based on how many measurements we got + n_expected = 6 # main measurements + n_got = len(angles) + len([v for v in alignments.values() if v is not None]) + confidence = min(1.0, n_got / n_expected) * pose2d.confidence + + return BiomechFeatures( + test_name="deep_squat", + view=view, + side="na", + angles=angles, + alignments=alignments, + symmetry_delta=None, + timing={"deepest_frame": best_frame_idx}, + confidence=confidence, + notes="; ".join(notes_parts) if notes_parts else "", + ) + + # ─── Helper: find peak frame by joint Y ───────────────────────────────── + + def _find_peak_frame(self, pose2d: Pose2DResult, joint_id: int, maximize: bool = True) -> int: + """Find frame where a joint reaches its extreme Y position.""" + best_idx, best_val = 0, -1.0 if maximize else float("inf") + for i, kps in enumerate(pose2d.keypoints): + j = _get_joint(kps, joint_id) + if j: + if (maximize and j[1] > best_val) or (not maximize and j[1] < best_val): + best_val = j[1] + best_idx = i + return best_idx + + def _bilateral_features( + self, pose2d: Pose2DResult, view: str, side: str, test_name: str, + extractor, + ) -> BiomechFeatures: + """Run a bilateral test: compute both sides, report the specified side + symmetry_delta.""" + left = extractor(pose2d, "left") + right = extractor(pose2d, "right") + + # Pick the requested side as primary + primary = left if side == "left" else right if side == "right" else left + other = right if side == "left" else left if side == "right" else right + + # Merge angles with side prefix for the primary + angles = primary.get("angles", {}) + alignments = primary.get("alignments", {}) + timing = primary.get("timing", {}) + + # Compute symmetry delta from the main measurement + main_key = primary.get("main_measure_key") + sym_delta = None + if main_key and main_key in left.get("angles", {}) and main_key in right.get("angles", {}): + sym_delta = abs(left["angles"][main_key] - right["angles"][main_key]) + + n_got = len(angles) + len([v for v in alignments.values() if v is not None]) + confidence = min(1.0, n_got / max(primary.get("expected", 3), 1)) * pose2d.confidence + + return BiomechFeatures( + test_name=test_name, view=view, side=side, + angles=angles, alignments=alignments, + symmetry_delta=sym_delta, timing=timing, + confidence=confidence, + notes=primary.get("notes", ""), + ) + + # ─── Hurdle Step ───────────────────────────────────────────────────────── + + def _hurdle_step(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """Hurdle Step: hip/knee flexion of stepping leg, stance stability.""" + def extract(p2d: Pose2DResult, s: str) -> dict: + hip_id = L_HIP if s == "left" else R_HIP + knee_id = L_KNEE if s == "left" else R_KNEE + ankle_id = L_ANKLE if s == "left" else R_ANKLE + # Stance side is opposite + stance_hip = R_HIP if s == "left" else L_HIP + stance_knee = R_KNEE if s == "left" else L_KNEE + stance_ankle = R_ANKLE if s == "left" else L_ANKLE + + # Peak = frame where stepping knee is highest (lowest Y in image) + peak_idx = self._find_peak_frame(p2d, knee_id, maximize=False) + kps = p2d.keypoints[peak_idx] + + hip = _get_joint(kps, hip_id) + knee = _get_joint(kps, knee_id) + ankle = _get_joint(kps, ankle_id) + s_hip = _get_joint(kps, stance_hip) + s_knee = _get_joint(kps, stance_knee) + s_ankle = _get_joint(kps, stance_ankle) + + angles = {} + alignments = {} + notes_parts = [] + + # Hip flexion of stepping leg + if all([hip, knee, ankle]): + angles["step_knee_flexion_deg"] = _angle_between_points(hip, knee, ankle) + # Hip angle (torso-femur) + shoulder_id = L_SHOULDER if s == "left" else R_SHOULDER + shoulder = _get_joint(kps, shoulder_id) + if all([shoulder, hip, knee]): + angles["step_hip_flexion_deg"] = _angle_between_points(shoulder, hip, knee) + + # Stance knee should stay extended + if all([s_hip, s_knee, s_ankle]): + angles["stance_knee_angle_deg"] = _angle_between_points(s_hip, s_knee, s_ankle) + alignments["stance_knee_extended"] = angles["stance_knee_angle_deg"] > 160 + + # Lateral trunk lean: shoulders should be level + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + if l_sh and r_sh: + angles["shoulder_tilt_deg"] = abs(math.degrees( + math.atan2(r_sh[1] - l_sh[1], r_sh[0] - l_sh[0]) + )) + alignments["trunk_stable"] = angles["shoulder_tilt_deg"] < 10 + + return { + "angles": angles, "alignments": alignments, + "timing": {"peak_step_frame": peak_idx}, + "main_measure_key": "step_hip_flexion_deg", + "expected": 4, "notes": "; ".join(notes_parts), + } + + return self._bilateral_features(pose2d, view, side, "hurdle_step", extract) + + # ─── In-Line Lunge ─────────────────────────────────────────────────────── + + def _inline_lunge(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """In-Line Lunge: knee flexion depth, trunk upright, balance.""" + def extract(p2d: Pose2DResult, s: str) -> dict: + # Front leg is the assessed side + hip_id = L_HIP if s == "left" else R_HIP + knee_id = L_KNEE if s == "left" else R_KNEE + ankle_id = L_ANKLE if s == "left" else R_ANKLE + rear_knee_id = R_KNEE if s == "left" else L_KNEE + + # Deepest lunge = front knee lowest + peak_idx = self._find_peak_frame(p2d, knee_id, maximize=True) + kps = p2d.keypoints[peak_idx] + + hip = _get_joint(kps, hip_id) + knee = _get_joint(kps, knee_id) + ankle = _get_joint(kps, ankle_id) + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + + angles = {} + alignments = {} + + # Front knee flexion + if all([hip, knee, ankle]): + angles["front_knee_flexion_deg"] = _angle_between_points(hip, knee, ankle) + + # Trunk upright: midline shoulder-to-hip angle from vertical + if l_sh and r_sh and l_hip and r_hip: + mid_sh = ((l_sh[0] + r_sh[0]) / 2, (l_sh[1] + r_sh[1]) / 2) + mid_hip = ((l_hip[0] + r_hip[0]) / 2, (l_hip[1] + r_hip[1]) / 2) + trunk_from_vert = abs(math.degrees( + math.atan2(mid_hip[0] - mid_sh[0], mid_sh[1] - mid_hip[1]) + )) + angles["trunk_lean_from_vertical_deg"] = trunk_from_vert + alignments["trunk_upright"] = trunk_from_vert < 15 + + # Knee over ankle alignment + if knee and ankle: + alignments["knee_over_ankle"] = abs(knee[0] - ankle[0]) < 40 + + return { + "angles": angles, "alignments": alignments, + "timing": {"deepest_lunge_frame": peak_idx}, + "main_measure_key": "front_knee_flexion_deg", + "expected": 3, "notes": "", + } + + return self._bilateral_features(pose2d, view, side, "inline_lunge", extract) + + # ─── Shoulder Mobility ─────────────────────────────────────────────────── + + def _shoulder_mobility(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """Shoulder Mobility: inter-fist distance normalized to hand length.""" + def extract(p2d: Pose2DResult, s: str) -> dict: + # "side" = the hand reaching over (top hand) + top_wrist = L_WRIST if s == "left" else R_WRIST + bot_wrist = R_WRIST if s == "left" else L_WRIST + + # Use mid-sequence frame (static hold) + mid_idx = len(p2d.keypoints) // 2 + kps = p2d.keypoints[mid_idx] + + top_w = _get_joint(kps, top_wrist) + bot_w = _get_joint(kps, bot_wrist) + + angles = {} + alignments = {} + + if top_w and bot_w: + # Vertical distance between fists (normalized by torso length) + fist_dist_px = math.sqrt((top_w[0] - bot_w[0])**2 + (top_w[1] - bot_w[1])**2) + angles["inter_fist_distance_px"] = fist_dist_px + + # Normalize by torso length (shoulder to hip) + sh_id = L_SHOULDER if s == "left" else R_SHOULDER + hip_id = L_HIP if s == "left" else R_HIP + sh = _get_joint(kps, sh_id) + hip = _get_joint(kps, hip_id) + if sh and hip: + torso_len = math.sqrt((sh[0] - hip[0])**2 + (sh[1] - hip[1])**2) + if torso_len > 0: + norm_dist = fist_dist_px / torso_len + angles["inter_fist_normalized"] = norm_dist + # Score 3: fists within 1 hand-length (~0.3 torso) + # Score 2: within 1.5 hand-lengths + alignments["fists_within_one_hand"] = norm_dist < 0.35 + alignments["fists_within_1_5_hand"] = norm_dist < 0.55 + + return { + "angles": angles, "alignments": alignments, + "timing": {"measure_frame": mid_idx}, + "main_measure_key": "inter_fist_normalized", + "expected": 2, "notes": "", + } + + return self._bilateral_features(pose2d, view, side, "shoulder_mobility", extract) + + # ─── Active Straight-Leg Raise ─────────────────────────────────────────── + + def _active_slr(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """ASLR: hip flexion angle of raised leg; down-leg stays flat.""" + def extract(p2d: Pose2DResult, s: str) -> dict: + hip_id = L_HIP if s == "left" else R_HIP + knee_id = L_KNEE if s == "left" else R_KNEE + ankle_id = L_ANKLE if s == "left" else R_ANKLE + # Down leg + d_hip_id = R_HIP if s == "left" else L_HIP + d_knee_id = R_KNEE if s == "left" else L_KNEE + d_ankle_id = R_ANKLE if s == "left" else L_ANKLE + + # Peak = raised ankle at highest point (lowest Y) + peak_idx = self._find_peak_frame(p2d, ankle_id, maximize=False) + kps = p2d.keypoints[peak_idx] + + hip = _get_joint(kps, hip_id) + knee = _get_joint(kps, knee_id) + ankle = _get_joint(kps, ankle_id) + d_hip = _get_joint(kps, d_hip_id) + d_knee = _get_joint(kps, d_knee_id) + d_ankle = _get_joint(kps, d_ankle_id) + + angles = {} + alignments = {} + + # Raised leg hip flexion: angle of femur from horizontal + if hip and ankle: + dy = hip[1] - ankle[1] # positive = ankle above hip + dx = ankle[0] - hip[0] + hip_flex = math.degrees(math.atan2(dy, abs(dx) if abs(dx) > 1 else 1)) + angles["raised_leg_angle_deg"] = max(0, hip_flex) + # Score 3: malleolus past contralateral knee (>70°) + # Score 2: between contralateral knee and mid-thigh (45-70°) + alignments["past_contralateral_knee"] = hip_flex > 70 + alignments["past_mid_thigh"] = hip_flex > 45 + + # Down leg: should stay flat (knee angle ~180) + if all([d_hip, d_knee, d_ankle]): + down_knee_angle = _angle_between_points(d_hip, d_knee, d_ankle) + angles["down_leg_knee_angle_deg"] = down_knee_angle + alignments["down_leg_flat"] = down_knee_angle > 160 + + return { + "angles": angles, "alignments": alignments, + "timing": {"peak_raise_frame": peak_idx}, + "main_measure_key": "raised_leg_angle_deg", + "expected": 3, "notes": "", + } + + return self._bilateral_features(pose2d, view, side, "active_slr", extract) + + # ─── Trunk Stability Push-Up ───────────────────────────────────────────── + + def _trunk_stability_pushup(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """Trunk Stability Push-Up: body rigidity through the press.""" + angles = {} + alignments = {} + notes_parts = [] + + # Analyze multiple frames to detect sag/lag + trunk_sags: list[tuple[int, float]] = [] # (frame_idx, sag_px) + for i, kps in enumerate(pose2d.keypoints): + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + l_ankle = _get_joint(kps, L_ANKLE) + r_ankle = _get_joint(kps, R_ANKLE) + + if l_sh and r_sh and l_hip and r_hip and l_ankle and r_ankle: + # Sag = hip drops below shoulder-ankle line + sh_y = (l_sh[1] + r_sh[1]) / 2 + hip_y = (l_hip[1] + r_hip[1]) / 2 + ankle_y = (l_ankle[1] + r_ankle[1]) / 2 + # In image coords: sag = hip_y > midpoint of shoulder-ankle Y + expected_hip_y = (sh_y + ankle_y) / 2 + sag_px = hip_y - expected_hip_y + trunk_sags.append((i, sag_px)) + + max_sag_frame = 0 + if trunk_sags: + sags = [s for _, s in trunk_sags] + max_sag_frame = max(trunk_sags, key=lambda t: t[1])[0] + mean = sum(sags) / len(sags) + variance = (sum((x - mean) ** 2 for x in sags) / len(sags)) ** 0.5 + max_sag = max(sags) + angles["max_sag_px"] = max_sag + angles["trunk_variance_px"] = variance + alignments["body_rigid"] = max_sag < 30 and variance < 15 + alignments["no_sag"] = max_sag < 30 + else: + notes_parts.append("insufficient landmarks for trunk analysis") + + # Hand position (near head = harder = score 3 position) + if pose2d.keypoints: + mid_kps = pose2d.keypoints[0] + nose = _get_joint(mid_kps, NOSE) + l_w = _get_joint(mid_kps, L_WRIST) + r_w = _get_joint(mid_kps, R_WRIST) + if nose and l_w and r_w: + avg_wrist_y = (l_w[1] + r_w[1]) / 2 + # Hands near head = wrist Y close to nose Y + alignments["hands_at_forehead"] = abs(avg_wrist_y - nose[1]) < 50 + + n_got = len(angles) + len([v for v in alignments.values() if v is not None]) + confidence = min(1.0, n_got / 3) * pose2d.confidence + + return BiomechFeatures( + test_name="trunk_stability_pushup", view=view, side="na", + angles=angles, alignments=alignments, + symmetry_delta=None, + timing={"n_frames_analyzed": len(trunk_sags), "max_sag_frame": max_sag_frame}, + confidence=confidence, + notes="; ".join(notes_parts) if notes_parts else "", + ) + + # ─── Rotary Stability ──────────────────────────────────────────────────── + + def _rotary_stability(self, pose2d: Pose2DResult, view: str, side: str) -> BiomechFeatures: + """Rotary Stability: coordination of ipsilateral arm/leg extension.""" + angles = {} + alignments = {} + notes_parts = [] + + # Look for the frame with max arm+leg extension + # Quadruped: hands + knees on ground, extending one arm + one leg + best_ext_frame = 0 + best_ext_val = 0 + + for i, kps in enumerate(pose2d.keypoints): + l_w = _get_joint(kps, L_WRIST) + r_w = _get_joint(kps, R_WRIST) + l_a = _get_joint(kps, L_ANKLE) + r_a = _get_joint(kps, R_ANKLE) + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + + # Extension = distance of wrist from shoulder + ankle from hip + ext_val = 0 + if l_w and l_sh: + ext_val += abs(l_w[0] - l_sh[0]) + if r_w and r_sh: + ext_val += abs(r_w[0] - r_sh[0]) + if ext_val > best_ext_val: + best_ext_val = ext_val + best_ext_frame = i + + kps = pose2d.keypoints[best_ext_frame] if pose2d.keypoints else {} + + # Trunk stability: shoulders level, hips level + l_sh = _get_joint(kps, L_SHOULDER) + r_sh = _get_joint(kps, R_SHOULDER) + l_hip = _get_joint(kps, L_HIP) + r_hip = _get_joint(kps, R_HIP) + + if l_sh and r_sh: + sh_tilt = abs(l_sh[1] - r_sh[1]) + angles["shoulder_level_diff_px"] = sh_tilt + alignments["shoulders_level"] = sh_tilt < 20 + + if l_hip and r_hip: + hip_tilt = abs(l_hip[1] - r_hip[1]) + angles["hip_level_diff_px"] = hip_tilt + alignments["hips_level"] = hip_tilt < 20 + + # Check for trunk sag across frames (similar to pushup) + trunk_variance = [] + for kps_frame in pose2d.keypoints: + ls = _get_joint(kps_frame, L_SHOULDER) + rs = _get_joint(kps_frame, R_SHOULDER) + lh = _get_joint(kps_frame, L_HIP) + rh = _get_joint(kps_frame, R_HIP) + if ls and rs and lh and rh: + mid_sh_y = (ls[1] + rs[1]) / 2 + mid_hip_y = (lh[1] + rh[1]) / 2 + trunk_variance.append(mid_hip_y - mid_sh_y) + + if trunk_variance: + std = (sum((x - sum(trunk_variance) / len(trunk_variance))**2 + for x in trunk_variance) / len(trunk_variance)) ** 0.5 + angles["trunk_stability_std_px"] = std + alignments["trunk_stable"] = std < 15 + + n_got = len(angles) + len([v for v in alignments.values() if v is not None]) + confidence = min(1.0, n_got / 3) * pose2d.confidence + + return BiomechFeatures( + test_name="rotary_stability", view=view, side="na", + angles=angles, alignments=alignments, + symmetry_delta=None, + timing={"peak_extension_frame": best_ext_frame}, + confidence=confidence, + notes="; ".join(notes_parts) if notes_parts else "", + ) diff --git a/formscout/agents/body3d.py b/formscout/agents/body3d.py new file mode 100644 index 0000000000000000000000000000000000000000..f6097f996cd482ef6d2374517271b15cc9822f60 --- /dev/null +++ b/formscout/agents/body3d.py @@ -0,0 +1,221 @@ +""" +Body3DAgent — optional 3D mesh/joint angle recovery via SAM 3D Body. + +Input: Pose2DResult, list of athlete masks, list of frames (np.ndarray BGR) +Output: Body3DResult(used, joints_3d, confidence) +Failure: ALWAYS returns Body3DResult(used=False) when enable_3d=False or + checkpoint unavailable — this is a normal success path, not an error. +Model: facebook/sam-3d-body-dinov3 (840M params, SAM License, GATED). +Gated: YES — access GRANTED June 4, 2026. +Params: ~0.84B (DINOv3-H+ variant). + +API (verified from github.com/facebookresearch/sam-3d-body README, Jun 2026): + from notebook.utils import setup_sam_3d_body + estimator = setup_sam_3d_body(hf_repo_id="facebook/sam-3d-body-dinov3") + outputs = estimator.process_one_image(rgb_image) # single RGB np.ndarray + # outputs contains MHR joints, body mesh, etc. +""" +from __future__ import annotations + +import numpy as np + +from formscout.types import Pose2DResult, Body3DResult, IngestResult +from formscout import config + +_NOT_USED = Body3DResult( + used=False, joints_3d=[], confidence=0.0, + notes="3D disabled or checkpoint unavailable", +) + +# Subsample frames for 3D inference (expensive per-frame) +_MAX_3D_FRAMES = 30 + + +class Body3DAgent: + """ + Optional 3D body joint estimation via SAM 3D Body (MHR rig). + Falls back gracefully when unavailable — returning Body3DResult(used=False) + is the expected success path for the 2D-only pipeline. + """ + + def __init__(self, enable_3d: bool | None = None): + self._enabled = config.ENABLE_3D if enable_3d is None else enable_3d + self._estimator = None + if self._enabled: + self._estimator = self._try_load() + + def _try_load(self): + """ + Attempt to load SAM 3D Body from HuggingFace. + Returns the estimator object or None on any failure. + """ + try: + from notebook.utils import setup_sam_3d_body # noqa: F401 + estimator = setup_sam_3d_body( + hf_repo_id=config.SAM_3D_HF_REPO, + ) + return estimator + except ImportError: + return None + except Exception: + return None + + def run( + self, + pose2d: Pose2DResult, + masks: list, + frames: list | None = None, + ) -> Body3DResult: + """ + Run 3D body estimation on selected keyframes. + + Args: + pose2d: 2D pose results (used for confidence weighting) + masks: Per-frame athlete masks from SegmentationAgent + frames: Raw BGR frames from IngestResult.frames + + Returns: + Body3DResult with used=True and 3D joints if successful, + or Body3DResult(used=False) if disabled/unavailable (normal path). + """ + if not self._enabled or self._estimator is None: + return _NOT_USED + + if not frames: + return Body3DResult( + used=False, joints_3d=[], confidence=0.0, + notes="3D enabled but no frames provided", + ) + + try: + import cv2 + + # Subsample frames evenly for 3D (it's expensive per-image) + n_frames = len(frames) + step = max(1, n_frames // _MAX_3D_FRAMES) + selected_indices = list(range(0, n_frames, step))[:_MAX_3D_FRAMES] + + joints_3d_per_frame: list[dict] = [] + confidences: list[float] = [] + + for idx in selected_indices: + frame_bgr = frames[idx] + # SAM 3D Body expects RGB + frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) + + outputs = self._estimator.process_one_image(frame_rgb) + + # Extract MHR joint positions from outputs + # The model returns joints in the MHR (Momentum Human Rig) format + frame_joints = self._extract_joints(outputs, idx) + joints_3d_per_frame.append(frame_joints) + + # Confidence from detection quality + conf = self._estimate_confidence(outputs) + confidences.append(conf) + + # Apply light temporal smoothing to reduce jitter + joints_3d_smoothed = self._temporal_smooth(joints_3d_per_frame) + + overall_conf = float(np.mean(confidences)) if confidences else 0.0 + + return Body3DResult( + used=True, + joints_3d=joints_3d_smoothed, + confidence=overall_conf, + notes=f"3D mesh recovery on {len(selected_indices)}/{n_frames} frames", + ) + + except Exception as e: + return Body3DResult( + used=False, joints_3d=[], confidence=0.0, + notes=f"3D inference failed: {e}", + ) + + def _extract_joints(self, outputs: dict, frame_idx: int) -> dict: + """ + Extract 3D joint positions from SAM 3D Body outputs. + Maps MHR rig joints to a standardized dict format. + """ + joints: dict = {"frame_index": frame_idx} + + # SAM 3D Body outputs MHR model params including joint positions + # The exact key depends on the model output format + if hasattr(outputs, "joints_3d"): + joint_data = outputs.joints_3d + elif isinstance(outputs, dict) and "joints_3d" in outputs: + joint_data = outputs["joints_3d"] + elif isinstance(outputs, dict) and "pred_joints" in outputs: + joint_data = outputs["pred_joints"] + else: + # Fallback: extract from vertices/body model params + joint_data = None + + if joint_data is not None: + if hasattr(joint_data, "cpu"): + joint_data = joint_data.cpu().numpy() + if isinstance(joint_data, np.ndarray): + # Map to named joints (MHR has standard SMPL-like ordering) + joint_names = [ + "pelvis", "left_hip", "right_hip", "spine1", + "left_knee", "right_knee", "spine2", + "left_ankle", "right_ankle", "spine3", + "left_foot", "right_foot", "neck", + "left_collar", "right_collar", "head", + "left_shoulder", "right_shoulder", + "left_elbow", "right_elbow", + "left_wrist", "right_wrist", + ] + for i, name in enumerate(joint_names): + if i < len(joint_data): + pos = joint_data[i] + joints[name] = { + "x": float(pos[0]), + "y": float(pos[1]), + "z": float(pos[2]), + } + + return joints + + def _estimate_confidence(self, outputs) -> float: + """Estimate confidence from the SAM 3D Body output quality.""" + # If outputs have a confidence/score field, use it + if isinstance(outputs, dict): + if "confidence" in outputs: + return float(outputs["confidence"]) + if "score" in outputs: + return float(outputs["score"]) + # Default: assume reasonable confidence if we got outputs at all + return 0.75 + + def _temporal_smooth( + self, joints_3d: list[dict], alpha: float = 0.3 + ) -> list[dict]: + """ + Apply exponential moving average smoothing to 3D joint positions + to reduce per-frame jitter from single-image prediction. + """ + if len(joints_3d) <= 1: + return joints_3d + + smoothed = [joints_3d[0]] + for i in range(1, len(joints_3d)): + prev = smoothed[-1] + curr = joints_3d[i] + smooth_frame = {"frame_index": curr.get("frame_index", i)} + + for key in curr: + if key == "frame_index": + continue + if key in prev and isinstance(curr[key], dict) and isinstance(prev[key], dict): + smooth_frame[key] = { + "x": alpha * curr[key]["x"] + (1 - alpha) * prev[key]["x"], + "y": alpha * curr[key]["y"] + (1 - alpha) * prev[key]["y"], + "z": alpha * curr[key]["z"] + (1 - alpha) * prev[key]["z"], + } + else: + smooth_frame[key] = curr[key] + + smoothed.append(smooth_frame) + + return smoothed diff --git a/formscout/agents/classifier.py b/formscout/agents/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab5844049a5fbb933d86443808c35c72d20d809 --- /dev/null +++ b/formscout/agents/classifier.py @@ -0,0 +1,102 @@ +""" +MovementClassifierAgent — identifies which FMS test is in the clip. + +Input: IngestResult (keyframes), Pose2DResult (skeleton context) +Output: MovementResult(test_name, side, confidence) +Failure: returns MovementResult(test_name="unknown") — pipeline stops and asks for manual override. +Model: Qwen3-VL-8B-Instruct via llama.cpp (8B params, Apache-2.0). +Gated: No. +""" +from __future__ import annotations + +import logging +from pathlib import Path + +from formscout import config +from formscout.types import IngestResult, Pose2DResult, MovementResult +from formscout.serving.llama_cpp import LlamaCppClient + +logger = logging.getLogger(__name__) + +_PROMPT_PATH = Path(__file__).parent / "prompts" / "c1_classifier.md" + + +class MovementClassifierAgent: + """Classifies which FMS test is being performed via VLM or manual override.""" + + def __init__(self): + self._client = LlamaCppClient(port=config.LLAMA_CPP_PORT_VLM) + self._system_prompt = _PROMPT_PATH.read_text(encoding="utf-8") + + def run( + self, + ingest: IngestResult, + pose2d: Pose2DResult | None = None, + manual_override: str | None = None, + ) -> MovementResult: + """ + Classify the movement. If manual_override is provided, use it directly. + Otherwise, use VLM inference on keyframes. + """ + if manual_override and manual_override != "unknown": + return MovementResult( + test_name=manual_override, side="na", + confidence=1.0, notes="manual override", + ) + + if not self._client.available: + return MovementResult( + test_name="unknown", side="na", confidence=0.0, + notes="VLM server unavailable — use manual override", + ) + + # Select keyframes for classification (3 evenly spaced) + n = len(ingest.frames) + indices = [0, n // 2, n - 1] if n >= 3 else list(range(n)) + images = self._encode_frames(ingest.frames, indices) + + prompt = f"{self._system_prompt}\n\nClassify this movement from the keyframes shown." + result = self._client.complete(prompt, images=images, max_tokens=256, temperature=0.1) + + return self._parse_response(result) + + def _encode_frames(self, frames: list, indices: list[int]) -> list[str]: + """Encode selected frames as base64 JPEG for the VLM.""" + import cv2 + import base64 + + encoded = [] + for idx in indices: + if idx < len(frames): + _, buf = cv2.imencode(".jpg", frames[idx], [cv2.IMWRITE_JPEG_QUALITY, 80]) + encoded.append(base64.b64encode(buf.tobytes()).decode()) + return encoded + + def _parse_response(self, result: dict) -> MovementResult: + """Parse VLM JSON response into MovementResult.""" + if "error" in result: + return MovementResult( + test_name="unknown", side="na", confidence=0.0, + notes=f"VLM error: {result['error']}", + ) + + test = result.get("test", "unknown") + side = result.get("side", "na") + confidence = float(result.get("confidence", 0.0)) + reason = result.get("reason", "") + + valid_tests = { + "deep_squat", "hurdle_step", "inline_lunge", + "shoulder_mobility", "active_slr", + "trunk_stability_pushup", "rotary_stability", "unknown", + } + if test not in valid_tests: + test = "unknown" + + if side not in ("left", "right", "na"): + side = "na" + + return MovementResult( + test_name=test, side=side, + confidence=confidence, notes=reason, + ) diff --git a/formscout/agents/ingest.py b/formscout/agents/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..3337d44b0f4ac7a7075dd249579f063429d515b8 --- /dev/null +++ b/formscout/agents/ingest.py @@ -0,0 +1,91 @@ +""" +IngestAgent — decodes video, normalizes FPS, samples frames. + +Input: video file path (str) +Output: IngestResult(frames, fps, duration, n_people, width, height) +Failure: returns IngestResult with confidence=0.0 and notes explaining the error. +Params: 0 (no model — pure OpenCV). +License: n/a. +Gated: no. +""" +from __future__ import annotations + +import cv2 +from pathlib import Path + +from formscout.types import IngestResult +from formscout import config + + +class IngestAgent: + """Deterministic video ingestion — no model, just OpenCV decode + frame sampling.""" + + def run(self, video_path: str) -> IngestResult: + p = Path(video_path) + if not p.exists(): + return IngestResult( + frames=[], fps=0.0, duration=0.0, n_people=0, + width=0, height=0, confidence=0.0, + notes=f"video not found: {video_path}", + ) + + try: + cap = cv2.VideoCapture(str(p)) + except Exception as e: + return IngestResult( + frames=[], fps=0.0, duration=0.0, n_people=0, + width=0, height=0, confidence=0.0, + notes=f"failed to open video: {e}", + ) + + if not cap.isOpened(): + return IngestResult( + frames=[], fps=0.0, duration=0.0, n_people=0, + width=0, height=0, confidence=0.0, + notes=f"could not open video: {video_path}", + ) + + fps = cap.get(cv2.CAP_PROP_FPS) or config.TARGET_FPS + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + duration = total / fps if fps > 0 else 0.0 + + notes_parts: list[str] = [] + if duration > config.MAX_DURATION_SEC: + notes_parts.append( + f"video is {duration:.1f}s (>{config.MAX_DURATION_SEC}s) — capping frames" + ) + + # Sample frames evenly, capped at MAX_FRAMES + step = max(1, total // config.MAX_FRAMES) + frames: list = [] + idx = 0 + while True: + ret, frame = cap.read() + if not ret: + break + if idx % step == 0: + frames.append(frame) + idx += 1 + if len(frames) >= config.MAX_FRAMES: + break + cap.release() + + if not frames: + return IngestResult( + frames=[], fps=fps, duration=duration, n_people=0, + width=w, height=h, confidence=0.0, + notes="no frames decoded", + ) + + return IngestResult( + frames=frames, + fps=fps, + duration=duration, + n_people=-1, # unknown until segmentation/pose + width=w, + height=h, + confidence=1.0, + notes="; ".join(notes_parts) if notes_parts else "", + ) diff --git a/formscout/agents/judge.py b/formscout/agents/judge.py new file mode 100644 index 0000000000000000000000000000000000000000..23e18d461daf7cfc329a63df7b9baa031a40fd03 --- /dev/null +++ b/formscout/agents/judge.py @@ -0,0 +1,125 @@ +""" +JudgeAgent — VLM-based final scorer with rationale, compensation tags, pain detection. + +Input: BiomechFeatures, ScoreResult (rubric candidate), MovementResult, keyframes +Output: JudgeResult(score, rationale, compensation_tags, corrective_hint, needs_human) +Failure: returns JudgeResult(needs_human=True, score=None) when uncertain. +Model: Qwen3-VL-8B-Instruct via llama.cpp (8B params, Apache-2.0). +Gated: No. + +Safety: NEVER auto-scores pain. If any indication of pain/clearing test, + sets needs_human=True and score=None. +""" +from __future__ import annotations + +import json +import logging +from pathlib import Path + +from formscout import config +from formscout.types import ( + BiomechFeatures, ScoreResult, MovementResult, + IngestResult, JudgeResult, +) +from formscout.serving import get_vlm_client + +logger = logging.getLogger(__name__) + +_PROMPT_PATH = Path(__file__).parent / "prompts" / "c2_judge.md" + + +class JudgeAgent: + """VLM judge that produces the final FMS score with rationale.""" + + def __init__(self): + self._client = get_vlm_client() + self._system_prompt = _PROMPT_PATH.read_text(encoding="utf-8") + + def run( + self, + features: BiomechFeatures, + rubric_score: ScoreResult, + movement: MovementResult, + ingest: IngestResult | None = None, + ) -> JudgeResult: + """ + Produce final score. Falls back to rubric score if VLM unavailable. + """ + if not config.ENABLE_JUDGE: + return self._fallback_from_rubric(rubric_score, features) + + if not self._client.available: + logger.warning("JudgeAgent: VLM unavailable, using rubric score as final") + return self._fallback_from_rubric(rubric_score, features) + + # Build context for the judge + context = { + "test": features.test_name, + "side": features.side, + "view": features.view, + "features": {"angles": features.angles, "alignments": features.alignments}, + "candidate_score": rubric_score.score, + "candidate_confidence": rubric_score.confidence, + "exemplars": [], # Phase 3: populated by RetrievalAgent + } + + prompt = f"{self._system_prompt}\n\n{json.dumps(context, indent=2)}" + + # Optionally include keyframes + images = None + if ingest and ingest.frames: + images = self._encode_keyframes(ingest.frames) + + result = self._client.complete(prompt, images=images, max_tokens=512, temperature=0.1) + if result.get("fallback"): + # transformers backend couldn't load/run — use the deterministic rubric + return self._fallback_from_rubric(rubric_score, features) + return self._parse_response(result) + + def _encode_keyframes(self, frames: list) -> list[str]: + """Encode 3 keyframes for VLM context.""" + import cv2 + import base64 + + n = len(frames) + indices = [0, n // 2, n - 1] if n >= 3 else list(range(n)) + encoded = [] + for idx in indices: + _, buf = cv2.imencode(".jpg", frames[idx], [cv2.IMWRITE_JPEG_QUALITY, 70]) + encoded.append(base64.b64encode(buf.tobytes()).decode()) + return encoded + + def _parse_response(self, result: dict) -> JudgeResult: + """Parse VLM JSON response into JudgeResult.""" + if "error" in result: + return JudgeResult( + score=None, rationale=f"VLM error: {result['error']}", + compensation_tags=[], corrective_hint="", + confidence=0.0, needs_human=True, + ) + + needs_human = result.get("needs_human", False) + score = result.get("score") if not needs_human else None + if score is not None: + score = max(0, min(3, int(score))) + + return JudgeResult( + score=score, + rationale=result.get("rationale", ""), + compensation_tags=result.get("compensation_tags", []), + corrective_hint=result.get("corrective_hint", ""), + confidence=float(result.get("confidence", 0.5)), + needs_human=needs_human, + ) + + def _fallback_from_rubric(self, rubric: ScoreResult, features: BiomechFeatures) -> JudgeResult: + """When VLM is unavailable, promote the rubric score as the final score.""" + return JudgeResult( + score=rubric.score, + rationale=f"[rubric-only] {rubric.rationale}", + compensation_tags=[], + corrective_hint="", + confidence=rubric.confidence * 0.8, + needs_human=rubric.needs_human, + notes="VLM unavailable — rubric score used as final", + ) diff --git a/formscout/agents/pdf_report.py b/formscout/agents/pdf_report.py new file mode 100644 index 0000000000000000000000000000000000000000..33023877baaac616686e6a2d7fb718aa367fea70 --- /dev/null +++ b/formscout/agents/pdf_report.py @@ -0,0 +1,175 @@ +""" +PdfReportAgent — renders a ReportResult + session entries to a branded PDF. + +Input: ReportResult, list[SessionEntry], session_dir (str) +Output: path to the written PDF (str), or None on failure. +Failure: returns None, never raises. +Params: 0 (pure rendering — no model). +License: n/a. +Gated: no. +""" +from __future__ import annotations + +import logging +import os + +from formscout.types import ReportResult + +logger = logging.getLogger(__name__) + +DISCLAIMER = "Screening aid — not a diagnosis. Pain or clearing tests require a clinician." + + +class PdfReportAgent: + """Assembles the screening-session PDF via ReportLab.""" + + def run(self, report: ReportResult, entries: list, session_dir: str) -> str | None: + try: + from reportlab.lib import colors + from reportlab.lib.pagesizes import LETTER + from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet + from reportlab.lib.units import inch + from reportlab.platypus import ( + Image, PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle, + ) + except Exception as e: + logger.warning("reportlab unavailable: %s", e) + return None + + out_path = os.path.join(session_dir, "formscout_report.pdf") + try: + styles = getSampleStyleSheet() + banner = ParagraphStyle( + "banner", parent=styles["Normal"], fontSize=9, textColor=colors.white, + backColor=colors.HexColor("#cf922a"), alignment=1, borderPadding=6, spaceAfter=12, + ) + ink = colors.HexColor("#243a34") + + def _meas_table(pairs, col0=3.0, col1=1.6): + rows = [[str(k).replace("_", " "), + (f"{v:.2f}" if isinstance(v, float) else str(v))] for k, v in pairs] + tbl = Table(rows, colWidths=[col0 * inch, col1 * inch]) + tbl.setStyle(TableStyle([ + ("FONTSIZE", (0, 0), (-1, -1), 8), + ("TEXTCOLOR", (0, 0), (-1, -1), ink), + ("ROWBACKGROUNDS", (0, 0), (-1, -1), + [colors.HexColor("#f7eedd"), colors.white]), + ])) + return tbl + + def _img(path, w=3.0, h=2.25): + if path and os.path.exists(path): + try: + return Image(path, width=w * inch, height=h * inch) + except Exception: + return None + return None + story = [] + story.append(Paragraph(f"⚠ {DISCLAIMER}", banner)) + story.append(Paragraph("FormScout — FMS Screening Report", styles["Title"])) + + if report.composite is not None: + comp = f"Composite: {report.composite} / 21" + else: + comp = f"Composite: Incomplete — {len(entries)}/7 tests scored" + story.append(Paragraph(comp, styles["Heading2"])) + story.append(Spacer(1, 0.2 * inch)) + + for ei, e in enumerate(entries): + if ei > 0: + story.append(PageBreak()) + title = e.test_name.replace("_", " ").title() + if e.side in ("left", "right"): + title += f" ({e.side})" + score_txt = "Clinician review required" if e.needs_human else f"Score: {e.score}/3" + story.append(Paragraph(f"{title} — {score_txt}", styles["Heading3"])) + story.append(Paragraph(f"view: {e.view} · confidence: " + f"{e.confidence:.0%}", styles["Normal"])) + if e.rationale: + story.append(Paragraph(e.rationale, styles["Normal"])) + if e.compensation_tags: + story.append(Paragraph("Compensations: " + ", ".join(e.compensation_tags), + styles["Normal"])) + if e.corrective_hint: + story.append(Paragraph("Corrective: " + e.corrective_hint, styles["Normal"])) + + # Key frame + flexion chart side by side + kf, fb = _img(e.keyframe_path), _img((e.chart_paths or {}).get("flexion"), w=3.2, h=2.0) + if kf or fb: + cells = [c for c in (kf, fb) if c] or [Paragraph("(images unavailable)", + styles["Normal"])] + story.append(Table([cells], hAlign="LEFT")) + + # Relevant-joint flexion table + if e.flexion: + story.append(Paragraph("Relevant joint flexion (key frame)", styles["Normal"])) + story.append(_meas_table( + [(n, f"{v['deg']:.1f}° — {v['openness']}") for n, v in e.flexion.items()], + col0=2.6, col1=2.6)) + + # Laban Effort + radar + if e.laban: + eff, lab = e.laban.get("effort", {}), e.laban.get("labels", {}) + story.append(Spacer(1, 0.08 * inch)) + story.append(Paragraph("Laban Effort (kinematic estimate)", styles["Normal"])) + laban_tbl = _meas_table( + [(k.title(), f"{eff.get(k, 0):.2f} — {lab.get(k, '')}") + for k in ("space", "weight", "time", "flow")], col0=2.6, col1=2.6) + radar = _img((e.chart_paths or {}).get("radar"), w=2.6, h=2.6) + if radar: + story.append(Table([[laban_tbl, radar]], hAlign="LEFT")) + else: + story.append(laban_tbl) + if e.laban.get("body_emphasis"): + emph = ", ".join(f"{n}" for n, _ in e.laban["body_emphasis"]) + story.append(Paragraph(f"Body emphasis: {emph} · " + f"{e.laban.get('notes', '')}", styles["Normal"])) + + # Angle + velocity charts + for kind in ("angle", "velocity"): + chart = _img((e.chart_paths or {}).get(kind), w=5.0, h=2.5) + if chart: + story.append(chart) + + # Full measurement dump + if e.measurements: + story.append(Paragraph("All measurements", styles["Normal"])) + story.append(_meas_table(list(e.measurements.items()))) + + story.append(Spacer(1, 0.15 * inch)) + + if report.asymmetries: + story.append(PageBreak()) + story.append(Paragraph("Asymmetries", styles["Heading2"])) + for a in report.asymmetries: + story.append(Paragraph( + f"{a['test'].replace('_', ' ').title()}: " + f"L={a['left_score']} R={a['right_score']} (Δ {a['delta']})", + styles["Normal"])) + try: + from formscout.analysis.charts import symmetry_bars + os.makedirs(os.path.join(session_dir, "charts"), exist_ok=True) + sym_png = symmetry_bars(report.asymmetries, + os.path.join(session_dir, "charts", "symmetry.png")) + sym_img = _img(sym_png, w=5.5, h=2.75) + if sym_img: + story.append(sym_img) + except Exception: + pass + + flags = list(report.low_confidence_flags) + list(report.disagreement_flags) + if flags: + story.append(Paragraph("Flags", styles["Heading2"])) + for fl in flags: + story.append(Paragraph(fl, styles["Normal"])) + + story.append(Spacer(1, 0.3 * inch)) + story.append(Paragraph(f"⚠ {DISCLAIMER}", banner)) + + doc = SimpleDocTemplate(out_path, pagesize=LETTER, + topMargin=0.6 * inch, bottomMargin=0.6 * inch) + doc.build(story) + return out_path + except Exception as e: + logger.warning("pdf build failed: %s", e) + return None diff --git a/formscout/agents/pose2d.py b/formscout/agents/pose2d.py new file mode 100644 index 0000000000000000000000000000000000000000..739fe73564a5e5e838af20b394e9842ec1241ddf --- /dev/null +++ b/formscout/agents/pose2d.py @@ -0,0 +1,232 @@ +""" +Pose2DAgent — 2D per-frame keypoint extraction. + +Backends: yolo (local checkpoints, ultralytics), mediapipe (official Tasks API, + local .task checkpoint), sapiens2 (Meta HF/transformers). +All backends output COCO-17 keypoints: dict[int, {x, y, conf}] per frame. + +Input: IngestResult +Output: Pose2DResult(keypoints per frame, fps, confidence) +Failure: Pose2DResult(confidence=0.0, notes=) — never raises. +Gated: yolo=no; mediapipe=no (local checkpoint); sapiens2=yes (access accepted). +""" +from __future__ import annotations + +import logging +import numpy as np + +from formscout import config +from formscout.types import IngestResult, Pose2DResult + +logger = logging.getLogger(__name__) + +COCO_KEYPOINTS = [ + "nose", "left_eye", "right_eye", "left_ear", "right_ear", + "left_shoulder", "right_shoulder", "left_elbow", "right_elbow", + "left_wrist", "right_wrist", "left_hip", "right_hip", + "left_knee", "right_knee", "left_ankle", "right_ankle", +] + +# BlazePose-33 source indices → COCO-17 target indices +# BlazePose: 0=nose, 2=left_eye, 5=right_eye, 7=left_ear, 8=right_ear, +# 11=left_shoulder, 12=right_shoulder, 13=left_elbow, 14=right_elbow, +# 15=left_wrist, 16=right_wrist, 23=left_hip, 24=right_hip, +# 25=left_knee, 26=right_knee, 27=left_ankle, 28=right_ankle +_BP_SRC = [0, 2, 5, 7, 8, 11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28] +_BP_DST = list(range(17)) # COCO indices 0..16 + +_model_cache: dict[str, object] = {} + + +# ── YOLO backend ────────────────────────────────────────────────────────────── + +def _get_yolo(path: str) -> object: + if path not in _model_cache: + from ultralytics import YOLO + _model_cache[path] = YOLO(path) + return _model_cache[path] + + +def _run_yolo(frames: list, path: str) -> list[dict]: + model = _get_yolo(path) + out = [] + for frame in frames: + try: + results = model(frame, verbose=False) + kps: dict[int, dict] = {} + if results and results[0].keypoints is not None: + kp = results[0].keypoints + if kp.xy is not None and len(kp.xy) > 0: + xy = kp.xy[0].cpu().numpy() + conf = kp.conf[0].cpu().numpy() + for j in range(min(len(xy), 17)): + kps[j] = {"x": float(xy[j, 0]), "y": float(xy[j, 1]), "conf": float(conf[j])} + out.append(kps) + except Exception: + out.append({}) + return out + + +# ── MediaPipe backend (official Tasks API, local .task checkpoint) ──────────── + +def _get_mediapipe_landmarker(path: str) -> object: + """Return PoseLandmarker cached by model path.""" + cache_key = f"mp:{path}" + if cache_key not in _model_cache: + from mediapipe.tasks import python as mp_tasks + from mediapipe.tasks.python import vision + + options = vision.PoseLandmarkerOptions( + base_options=mp_tasks.BaseOptions(model_asset_path=path), + running_mode=vision.RunningMode.IMAGE, + num_poses=1, + min_pose_detection_confidence=0.4, + min_pose_presence_confidence=0.4, + min_tracking_confidence=0.4, + ) + _model_cache[cache_key] = vision.PoseLandmarker.create_from_options(options) + return _model_cache[cache_key] + + +def _run_mediapipe(frames: list, path: str) -> list[dict]: + import cv2 + import mediapipe as mp + + try: + landmarker = _get_mediapipe_landmarker(path) + except Exception as e: + logger.warning("mediapipe load failed: %s", e) + return [{} for _ in frames] + + out = [] + for frame in frames: + try: + h, w = frame.shape[:2] + rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb) + detection = landmarker.detect(mp_image) + + kps: dict[int, dict] = {} + if detection.pose_landmarks: + lms = detection.pose_landmarks[0] + for coco_idx, bp_idx in zip(_BP_DST, _BP_SRC): + if bp_idx < len(lms): + lm = lms[bp_idx] + kps[coco_idx] = { + "x": float(lm.x * w), + "y": float(lm.y * h), + "conf": float(lm.visibility), + } + out.append(kps) + except Exception: + out.append({}) + return out + + +# ── Sapiens2 backend (Meta HF, transformers) ────────────────────────────────── + +def _get_sapiens2(hf_id: str) -> object: + if hf_id not in _model_cache: + from transformers import pipeline as hf_pipeline + _model_cache[hf_id] = hf_pipeline("pose-estimation", model=hf_id) + return _model_cache[hf_id] + + +def _run_sapiens2(frames: list, hf_id: str) -> list[dict]: + try: + pipe = _get_sapiens2(hf_id) + except Exception as e: + logger.warning("sapiens2 load failed: %s", e) + return [{} for _ in frames] + + from PIL import Image + + out = [] + for frame in frames: + try: + pil_img = Image.fromarray(frame) + result = pipe(pil_img) + + if not result: + out.append({}) + continue + + # Take highest-confidence person (first result) + person = result[0] + keypoints = person.get("keypoints", []) + scores = person.get("keypoint_scores", []) + + # Build name→(x, y, score) lookup from pipeline output + kp_lookup: dict[str, tuple] = {} + for i, kp in enumerate(keypoints): + if isinstance(kp, dict): + name = kp.get("label", "") + x, y = kp.get("x", 0.0), kp.get("y", 0.0) + else: + name = "" + x, y = float(kp[0]), float(kp[1]) + score = float(scores[i]) if i < len(scores) else 0.0 + if name: + kp_lookup[name] = (x, y, score) + + kps: dict[int, dict] = {} + for coco_idx, name in enumerate(COCO_KEYPOINTS): + if name in kp_lookup: + x, y, s = kp_lookup[name] + kps[coco_idx] = {"x": x, "y": y, "conf": s} + out.append(kps) + except Exception: + out.append({}) + return out + + +# ── Agent ───────────────────────────────────────────────────────────────────── + +class Pose2DAgent: + """Extracts COCO-17 keypoints per frame; dispatches to YOLO, MediaPipe, or Sapiens2.""" + + def run(self, ingest: IngestResult, model_key: str | None = None) -> Pose2DResult: + if not ingest.frames: + return Pose2DResult(keypoints=[], fps=ingest.fps, confidence=0.0, notes="no frames in ingest") + + key = model_key or config.DEFAULT_POSE_MODEL + spec = config.POSE_MODELS.get(key) + if spec is None: + logger.warning("Unknown model_key %r — falling back to %s", key, config.DEFAULT_POSE_MODEL) + spec = config.POSE_MODELS[config.DEFAULT_POSE_MODEL] + + backend = spec["backend"] + try: + if backend == "yolo": + kps_per_frame = _run_yolo(ingest.frames, spec["path"]) + elif backend == "mediapipe": + kps_per_frame = _run_mediapipe(ingest.frames, spec["path"]) + elif backend == "sapiens2": + kps_per_frame = _run_sapiens2(ingest.frames, spec["hf_id"]) + else: + return Pose2DResult( + keypoints=[{} for _ in ingest.frames], + fps=ingest.fps, confidence=0.0, + notes=f"unknown backend: {backend}", + ) + except Exception as e: + return Pose2DResult( + keypoints=[{} for _ in ingest.frames], + fps=ingest.fps, confidence=0.0, + notes=str(e), + ) + + n_detected = sum(1 for f in kps_per_frame if f) + total_conf = sum( + sum(kp["conf"] for kp in f.values()) / len(f) + for f in kps_per_frame if f + ) + overall_conf = (total_conf / n_detected) if n_detected > 0 else 0.0 + notes = "" if n_detected > 0 else "no person detected in any frame" + + return Pose2DResult( + keypoints=kps_per_frame, + fps=ingest.fps, + confidence=overall_conf, + notes=notes, + ) diff --git a/formscout/agents/prompts/c1_classifier.md b/formscout/agents/prompts/c1_classifier.md new file mode 100644 index 0000000000000000000000000000000000000000..f01e868915142e51e66dfd9478e9279fa7db9710 --- /dev/null +++ b/formscout/agents/prompts/c1_classifier.md @@ -0,0 +1,17 @@ +You are an FMS movement classifier. You are shown a few keyframes and a skeleton montage from a single short clip of one person performing ONE Functional Movement Screen test. Identify which test it is and, for one-sided tests, which side is being assessed. + +The seven tests and their tells: +- deep_squat: feet shoulder-width, a dowel/bar held overhead with both arms, a deep two-legged squat. +- hurdle_step: stepping one leg over a low hurdle/cord while balancing on the other, dowel across shoulders. +- inline_lunge: feet in a narrow heel-to-toe line, a lunge down the line, dowel held vertically behind the back. +- shoulder_mobility: one hand reaching over the shoulder down the back, the other reaching up from below; fists measured. +- active_slr: lying supine, one leg raised straight up while the other stays flat on the ground. +- trunk_stability_pushup: prone push-up with hands high (near the head), body pressed up as one rigid unit. +- rotary_stability: quadruped (hands+knees), same-side or opposite arm and leg extended then drawn together. +- unknown: it does not clearly match any of the above, or the view is too poor to tell. + +Rules: +- Prefer "unknown" over a low-confidence guess. A wrong test makes the whole score meaningless. +- "side" is "left" or "right" for one-sided tests (hurdle_step, inline_lunge, shoulder_mobility, active_slr); use "na" for two-sided tests (deep_squat, trunk_stability_pushup, rotary_stability) and unknown. +- Output ONLY this JSON object, nothing else: +{"test": "", "side": "left|right|na", "confidence": <0.0-1.0>, "reason": ""} diff --git a/formscout/agents/prompts/c2_judge.md b/formscout/agents/prompts/c2_judge.md new file mode 100644 index 0000000000000000000000000000000000000000..73af3a426e4cf3b73e7e1dbcb34052cb68fb2213 --- /dev/null +++ b/formscout/agents/prompts/c2_judge.md @@ -0,0 +1,43 @@ +You are an assistant scoring ONE Functional Movement Screen test from objective measurements. You are a SCREENING AID, not a clinician. You never diagnose and you never predict injury. + +You are given, as JSON: +- test, side +- view: "3d" (reliable angles) or "2d" (angles are camera-angle dependent — caveat them) +- features: measured biomechanics for this test (angles in degrees, distances normalized) +- candidate_score: a model's provisional 0-3 (corroboration, may be absent) +- exemplars: physio-scored reference clips of the SAME test with their scores (anchors, may be empty) +- a few keyframes / skeleton overlay for context + +FMS scoring scale (apply per side; the test score is the LOWER side): +- 3: the movement is performed to criterion with no compensation. +- 2: the movement is completed but with compensation / poor mechanics (or only with the allowed regression, e.g. deep_squat heels elevated). +- 1: the person cannot perform the movement pattern even with the allowed regression. +- 0: PAIN. You CANNOT see pain. Never assign 0 yourself. + +Per-test criteria to weigh (use the features as primary evidence): +- deep_squat (3): femur below horizontal, torso roughly parallel to the tibia, knees tracking over the feet, dowel staying aligned over the feet, heels flat. (2): the same achieved only with heels elevated. (1): criteria unmet even with heels elevated. +- hurdle_step / inline_lunge: minimal sway/loss of balance, knee/hip/ankle alignment maintained, no contact with the hurdle, dowel/posture stable. Compensation -> 2; failure to complete -> 1. Report L/R asymmetry. +- shoulder_mobility: judge by the normalized inter-fist distance bands (per side). Report asymmetry. +- active_slr: judge the raised-leg hip-flexion angle relative to the standard band; the down leg stays flat. +- trunk_stability_pushup: the body must move as one rigid unit (low segment-angle variance through the press); sag/lag or needing the easier hand position -> 2. +- rotary_stability: smooth contralateral (or the allowed unilateral) coordination with a stable trunk; loss of coordination/balance -> lower. + +Hard safety rules: +- If there is any clearing-test context, visible pain, grimacing, or an aborted rep, set needs_human=true and score=null. Do not score it. +- If view=="2d" on a depth/angle-critical test (deep_squat, inline_lunge, active_slr), include an explicit one-clause caveat that the angle is a 2D estimate dependent on camera position. +- If the measurements and the candidate_score disagree by a point or more, lower your confidence and say so. +- When the features are insufficient to decide, prefer needs_human=true over a confident guess. + +Reason from the features first; use exemplars to calibrate borderline cases; treat candidate_score as a second opinion, not the answer. + +Output ONLY this JSON object, nothing else: +{ + "test": "