Spaces:
Running
Running
Amol Kaushik commited on
Commit ·
18cd4f7
1
Parent(s): 67c486c
a16
Browse files- .github/workflows/push_to_hf_space.yml +1 -1
- A12/service/ui.py +1 -1
- A15/__init__.py +0 -0
- A15/inference.py +124 -0
- A16/A16_Report.ipynb +3 -0
- A16/MANUAL_TEST_CHECKLIST.md +147 -0
- A16/__init__.py +0 -0
- A16/service/__init__.py +1 -0
- A16/service/endpoint.py +274 -0
- A16/service/ui.py +127 -0
- A16/tests/__init__.py +0 -0
- A16/tests/test_endpoint.py +199 -0
- app.py +4 -0
- pytest.ini +1 -1
.github/workflows/push_to_hf_space.yml
CHANGED
|
@@ -61,7 +61,7 @@ jobs:
|
|
| 61 |
# -------------------------
|
| 62 |
- name: Run unit tests
|
| 63 |
run: |
|
| 64 |
-
pytest A4/ -v --tb=short
|
| 65 |
|
| 66 |
# -------------------------
|
| 67 |
# 7. Push to HuggingFace
|
|
|
|
| 61 |
# -------------------------
|
| 62 |
- name: Run unit tests
|
| 63 |
run: |
|
| 64 |
+
pytest A4/ A16/ -v --tb=short
|
| 65 |
|
| 66 |
# -------------------------
|
| 67 |
# 7. Push to HuggingFace
|
A12/service/ui.py
CHANGED
|
@@ -37,4 +37,4 @@ Outputs:
|
|
| 37 |
)
|
| 38 |
|
| 39 |
except Exception as e:
|
| 40 |
-
return None, None,
|
|
|
|
| 37 |
)
|
| 38 |
|
| 39 |
except Exception as e:
|
| 40 |
+
return None, None, {"error": str(e)}, f"### Error\n{e}"
|
A15/__init__.py
ADDED
|
File without changes
|
A15/inference.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A15 scoring — reusable inference helpers.
|
| 2 |
+
|
| 3 |
+
Extracted from ``app.py`` so that other endpoints (notably A16) can reuse the
|
| 4 |
+
deployed 0–4 regression scorer without importing the Gradio app module.
|
| 5 |
+
|
| 6 |
+
The deployed champion architecture (Dense_medium) and scaling are described in
|
| 7 |
+
``A15_results/training_summary.json``. Models live in ``<repo_root>/models/``:
|
| 8 |
+
|
| 9 |
+
- ``scoring_model.keras`` — Dense regressor (input: 390 = 10×13×3)
|
| 10 |
+
- ``scoring_scaler.pkl`` — StandardScaler fitted on flattened frames
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Tuple
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
# 13-joint Kinect ordering used during A15 training.
|
| 21 |
+
A15_JOINTS = [
|
| 22 |
+
'head', 'left_shoulder', 'left_elbow', 'right_shoulder', 'right_elbow',
|
| 23 |
+
'left_hand', 'right_hand', 'left_hip', 'right_hip',
|
| 24 |
+
'left_knee', 'right_knee', 'left_foot', 'right_foot',
|
| 25 |
+
]
|
| 26 |
+
A15_C = 10 # frames per clip the scorer was trained on
|
| 27 |
+
|
| 28 |
+
_REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 29 |
+
_MODEL_PATH = _REPO_ROOT / 'models' / 'scoring_model.keras'
|
| 30 |
+
_SCALER_PATH = _REPO_ROOT / 'models' / 'scoring_scaler.pkl'
|
| 31 |
+
|
| 32 |
+
_MODEL = None
|
| 33 |
+
_SCALER = None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_a15_scorer():
|
| 37 |
+
"""Lazy-load the deployed A15 regression scorer.
|
| 38 |
+
|
| 39 |
+
Returns
|
| 40 |
+
-------
|
| 41 |
+
(model, scaler) : tuple
|
| 42 |
+
Keras model and fitted StandardScaler. Cached after first call.
|
| 43 |
+
"""
|
| 44 |
+
global _MODEL, _SCALER
|
| 45 |
+
if _MODEL is not None and _SCALER is not None:
|
| 46 |
+
return _MODEL, _SCALER
|
| 47 |
+
|
| 48 |
+
import joblib # local import keeps app startup light
|
| 49 |
+
from tensorflow import keras
|
| 50 |
+
from tensorflow.keras import layers
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
_MODEL = keras.models.load_model(str(_MODEL_PATH))
|
| 54 |
+
except (TypeError, ValueError):
|
| 55 |
+
# Saved with a newer Keras (extra ``quantization_config`` kwarg);
|
| 56 |
+
# rebuild Dense_medium and load weights only. Architecture matches
|
| 57 |
+
# ``A15_results/training_summary.json``'s deployed champion.
|
| 58 |
+
inp = keras.Input(shape=(390,))
|
| 59 |
+
x = layers.Dense(64, activation='relu')(inp)
|
| 60 |
+
x = layers.Dropout(0.2)(x)
|
| 61 |
+
out = layers.Dense(1, activation='linear')(x)
|
| 62 |
+
_MODEL = keras.Model(inp, out, name='Dense')
|
| 63 |
+
_MODEL.load_weights(str(_MODEL_PATH))
|
| 64 |
+
|
| 65 |
+
_SCALER = joblib.load(str(_SCALER_PATH))
|
| 66 |
+
return _MODEL, _SCALER
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def sample_frames(df) -> np.ndarray:
|
| 70 |
+
"""Sample ``A15_C`` equally-spaced frames from a cut 3D dataframe.
|
| 71 |
+
|
| 72 |
+
Returns array of shape ``(A15_C, len(A15_JOINTS), 3)``.
|
| 73 |
+
"""
|
| 74 |
+
df = df.copy()
|
| 75 |
+
df.columns = df.columns.str.strip()
|
| 76 |
+
idx = np.linspace(0, len(df) - 1, A15_C).astype(int)
|
| 77 |
+
sub = df.iloc[idx]
|
| 78 |
+
frames = []
|
| 79 |
+
for _, row in sub.iterrows():
|
| 80 |
+
frames.append([
|
| 81 |
+
[row[f'{j}_x'], row[f'{j}_y'], row[f'{j}_z']]
|
| 82 |
+
for j in A15_JOINTS
|
| 83 |
+
])
|
| 84 |
+
return np.array(frames, dtype=np.float32)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def score_band(score: float) -> str:
|
| 88 |
+
"""Map a 0–4 score onto a traffic-light band."""
|
| 89 |
+
if score < 1.0:
|
| 90 |
+
return "GREEN — acceptable form (0-1)"
|
| 91 |
+
if score < 2.0:
|
| 92 |
+
return "AMBER — borderline (1-2)"
|
| 93 |
+
return "RED — poor form (2-4)"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def predict_score(df) -> Tuple[float, str, float]:
|
| 97 |
+
"""End-to-end scoring: cut 3D dataframe → (clipped score, band, NN ms).
|
| 98 |
+
|
| 99 |
+
Parameters
|
| 100 |
+
----------
|
| 101 |
+
df : pandas.DataFrame
|
| 102 |
+
Cut 3D dataframe with columns ``<joint>_x/y/z`` for the 13 A15 joints.
|
| 103 |
+
|
| 104 |
+
Returns
|
| 105 |
+
-------
|
| 106 |
+
(score, band, nn_ms) : tuple
|
| 107 |
+
``score`` is clipped to ``[0, 4]``. ``nn_ms`` is the wall-clock time
|
| 108 |
+
spent inside ``model.predict`` only (excludes sampling / scaling).
|
| 109 |
+
"""
|
| 110 |
+
import time
|
| 111 |
+
|
| 112 |
+
model, scaler = load_a15_scorer()
|
| 113 |
+
frames = sample_frames(df)
|
| 114 |
+
flat = frames.reshape(1, -1)
|
| 115 |
+
scaled = scaler.transform(flat).astype(np.float32)
|
| 116 |
+
if len(model.input_shape) == 3:
|
| 117 |
+
scaled = scaled.reshape(1, A15_C, len(A15_JOINTS) * 3)
|
| 118 |
+
|
| 119 |
+
t0 = time.perf_counter()
|
| 120 |
+
raw = float(model.predict(scaled, verbose=0).flatten()[0])
|
| 121 |
+
nn_ms = (time.perf_counter() - t0) * 1000.0
|
| 122 |
+
|
| 123 |
+
score = float(np.clip(raw, 0.0, 4.0))
|
| 124 |
+
return score, score_band(score), nn_ms
|
A16/A16_Report.ipynb
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4c1c557bbb157bbc918fea0c355c38d55cf8ae6951c7317608e8b1a57131dcb3
|
| 3 |
+
size 12468
|
A16/MANUAL_TEST_CHECKLIST.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A16 Final Endpoint — Manual Test Checklist
|
| 2 |
+
|
| 3 |
+
Use this list to verify the A16 tab end-to-end before the presentation.
|
| 4 |
+
Tick each box. If a step fails, capture what you saw and let the dev know
|
| 5 |
+
(do not hallucinate fixes).
|
| 6 |
+
|
| 7 |
+
**Scope:** UI behaviour, response shape, and integration. Model accuracy
|
| 8 |
+
is out of scope for this checklist (covered by A10/A11/A13/A15 reports).
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## 0. Pre-flight
|
| 13 |
+
|
| 14 |
+
- [ ] `python -m pytest A4/ A16/ -v` passes locally. Expect **11 A16 tests + the A4 tests** all green.
|
| 15 |
+
- [ ] Model artefacts present in `models/`:
|
| 16 |
+
- [ ] `week16_result.h5`
|
| 17 |
+
- [ ] `week15_2d_to_3d.h5`
|
| 18 |
+
- [ ] `week17_start_and_stop.h5`
|
| 19 |
+
- [ ] `week17_start_and_stop.pkl`
|
| 20 |
+
- [ ] `A_CNN.keras`
|
| 21 |
+
- [ ] `scoring_model.keras`
|
| 22 |
+
- [ ] `scoring_scaler.pkl`
|
| 23 |
+
- [ ] `week16_scaler_X.pkl`, `week16_scaler_y.pkl`
|
| 24 |
+
- [ ] MediaPipe model present: `A14/pose_landmarker_lite.task`.
|
| 25 |
+
- [ ] `python app.py` launches without traceback. Console shows the existing
|
| 26 |
+
`Initialising Exercise Pipeline` banner only **when** a tab triggers it
|
| 27 |
+
(lazy load), **not** at startup.
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
## 1. Tab presence & layout
|
| 32 |
+
|
| 33 |
+
Open `http://127.0.0.1:7860` (local) or the HF Space URL (deployed).
|
| 34 |
+
|
| 35 |
+
- [ ] A new tab labelled **"A16 Final Endpoint"** is visible to the right
|
| 36 |
+
of `Exercise Scoring (A15)`.
|
| 37 |
+
- [ ] The tab contains, top to bottom on each column:
|
| 38 |
+
- **Left column:** intro markdown, a `Video` upload, a `Recording quality
|
| 39 |
+
threshold` slider (default 0.6, range 0.1–0.9), a primary `Run A16
|
| 40 |
+
endpoint` button.
|
| 41 |
+
- **Right column:** `Status` textbox (read-only), a Markdown panel, a
|
| 42 |
+
`3D skeleton animation` video output, a `Full response (A16 schema)`
|
| 43 |
+
JSON viewer.
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## 2. Happy path (good recording)
|
| 48 |
+
|
| 49 |
+
Use any good-quality exercise clip you have used for A14 / A15 demos.
|
| 50 |
+
|
| 51 |
+
- [ ] Upload the video, leave threshold at `0.6`, click **Run A16 endpoint**.
|
| 52 |
+
- [ ] During processing the console prints the existing
|
| 53 |
+
`[1] Loading MediaPipe …` banner once.
|
| 54 |
+
- [ ] When it finishes:
|
| 55 |
+
- [ ] **Status** textbox starts with `OK — score <number> (<BAND>...)`.
|
| 56 |
+
- [ ] **Summary** Markdown shows non-`None` values for Recording, Segment,
|
| 57 |
+
Classification, Score and Timing sections.
|
| 58 |
+
- [ ] **3D skeleton animation** plays (it is the same `<stem>_skeleton.mp4`
|
| 59 |
+
you'd get from A14).
|
| 60 |
+
- [ ] **Full response JSON** has:
|
| 61 |
+
- `endpoint == "A16"`, `variant == "3D"`, `schema_version == "1.0.0"`
|
| 62 |
+
- `status == "OK"`
|
| 63 |
+
- `score.value` is a number in `[0, 4]`
|
| 64 |
+
- `score.band` matches the threshold: `<1` GREEN, `1–2` AMBER, `≥2` RED
|
| 65 |
+
- `timing_ms.upstream_ms` > 0 and `timing_ms.total_ms` ≥ `upstream_ms`
|
| 66 |
+
- `artefacts.cut_3d_csv` and `artefacts.full_3d_csv` are non-null paths
|
| 67 |
+
- `warnings` is an empty list
|
| 68 |
+
|
| 69 |
+
> If the score is `null` but everything else looks fine, check the
|
| 70 |
+
> `status` field — `ERROR_SCORER` or `ERROR_TOO_SHORT_AFTER_CUT` is the
|
| 71 |
+
> expected failure mode and should already show a clear message.
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## 3. Ugly recording path
|
| 76 |
+
|
| 77 |
+
Use a deliberately bad clip (occluded body, very dark, partial frame).
|
| 78 |
+
If you don't have one, raise the threshold to `0.9` on any normal clip.
|
| 79 |
+
|
| 80 |
+
- [ ] Click **Run A16 endpoint**.
|
| 81 |
+
- [ ] **Status** textbox starts with `REJECTED — ugly recording (conf <n>)`.
|
| 82 |
+
- [ ] **Full response JSON**:
|
| 83 |
+
- `status == "REJECTED_UGLY_RECORDING"`
|
| 84 |
+
- `recording.quality_label == "UGLY"`
|
| 85 |
+
- `recording.quality_confidence` < `recording.threshold`
|
| 86 |
+
- `score.value` is `null`
|
| 87 |
+
- `classification.label` is `null`
|
| 88 |
+
- `segment.start_frame` is `null`
|
| 89 |
+
- `timing_ms.scorer_nn_ms == 0.0`
|
| 90 |
+
|
| 91 |
+
---
|
| 92 |
+
|
| 93 |
+
## 4. No-video path
|
| 94 |
+
|
| 95 |
+
- [ ] Click **Run A16 endpoint** without uploading anything.
|
| 96 |
+
- [ ] **Status** shows `ERROR_NO_VIDEO — No video provided.`
|
| 97 |
+
- [ ] **Full response JSON** `status == "ERROR_NO_VIDEO"`, all sections present but null.
|
| 98 |
+
- [ ] **No traceback** appears in the console.
|
| 99 |
+
|
| 100 |
+
---
|
| 101 |
+
|
| 102 |
+
## 5. Existing tabs still work (regression check)
|
| 103 |
+
|
| 104 |
+
Quickly verify nothing regressed in the other tabs:
|
| 105 |
+
|
| 106 |
+
- [ ] `📸 Image Processing` — still renders an annotated image.
|
| 107 |
+
- [ ] `🎥 Video Processing` — still renders an annotated video.
|
| 108 |
+
- [ ] `🧪 Video Pipeline` (A12) — still runs end-to-end.
|
| 109 |
+
- [ ] `Exercise Analysis (A14)` — still runs end-to-end.
|
| 110 |
+
- [ ] `Exercise Scoring (A15)` — still returns a score.
|
| 111 |
+
|
| 112 |
+
---
|
| 113 |
+
|
| 114 |
+
## 6. Deployment
|
| 115 |
+
|
| 116 |
+
After pushing to `main`:
|
| 117 |
+
|
| 118 |
+
- [ ] GitHub Actions run `Sync to Hugging Face hub` is green:
|
| 119 |
+
- [ ] `Lint .py files` passes
|
| 120 |
+
- [ ] `Lint notebooks` passes
|
| 121 |
+
- [ ] `Run unit tests` passes (now runs `pytest A4/ A16/`)
|
| 122 |
+
- [ ] `Push to hub` succeeds
|
| 123 |
+
- [ ] The HF Space rebuilds and the **A16 Final Endpoint** tab appears live.
|
| 124 |
+
|
| 125 |
+
---
|
| 126 |
+
|
| 127 |
+
## 7. What to capture for the presentation
|
| 128 |
+
|
| 129 |
+
- [ ] Screenshot of the A16 tab on a happy-path run (status + summary + JSON).
|
| 130 |
+
- [ ] Screenshot of the ugly rejection path (status + JSON).
|
| 131 |
+
- [ ] Mermaid architecture diagram from `A16_Report.ipynb` §1.
|
| 132 |
+
- [ ] One-line timing numbers from the happy-path JSON (`upstream_ms`,
|
| 133 |
+
`scorer_nn_ms`, `total_ms`).
|
| 134 |
+
|
| 135 |
+
---
|
| 136 |
+
|
| 137 |
+
## 8. If something looks wrong
|
| 138 |
+
|
| 139 |
+
Do **not** guess. Note exactly:
|
| 140 |
+
|
| 141 |
+
1. Which step failed (section + checkbox text).
|
| 142 |
+
2. What the `status` and `message` fields said.
|
| 143 |
+
3. The first 5 lines of the console output around the failure.
|
| 144 |
+
4. Whether the same clip works in the A14 or A15 tab.
|
| 145 |
+
|
| 146 |
+
Then ping the dev with that info — most failures map directly to a
|
| 147 |
+
known model-loading issue documented in `A16_Report.ipynb` §8.
|
A16/__init__.py
ADDED
|
File without changes
|
A16/service/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""A16 final-week capstone endpoint package."""
|
A16/service/endpoint.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A16 — Final unified server endpoint (capstone, week 22 deliverable).
|
| 2 |
+
|
| 3 |
+
Single entry point that runs the full chain in one call:
|
| 4 |
+
|
| 5 |
+
video → MediaPipe pose → PoseNet→Kinect 2D → 2D→3D
|
| 6 |
+
→ start/stop cut → recording-quality (ugly) gate
|
| 7 |
+
→ good/bad classifier → 0–4 score (A15)
|
| 8 |
+
|
| 9 |
+
Two alternatives are scaffolded; only the **3D** variant is wired today. The
|
| 10 |
+
2D-only fast path is reserved as the named stretch alternative (see
|
| 11 |
+
``run_pipeline_2d``) so the public surface is stable when it lands.
|
| 12 |
+
|
| 13 |
+
Design notes
|
| 14 |
+
------------
|
| 15 |
+
- Heavy lifting is **delegated** to the existing :class:`ExercisePipeline`
|
| 16 |
+
(``exercise_pipeline.py``). A16 only adds: (1) A15 scoring on top of the cut
|
| 17 |
+
3D CSV, (2) a unified response schema, (3) per-stage timing instrumentation,
|
| 18 |
+
(4) a stable JSON contract that the UI / future REST clients can rely on.
|
| 19 |
+
- Models that fail to load are reported in the response (``warnings``) instead
|
| 20 |
+
of crashing the endpoint — the wider service must stay demo-able even when
|
| 21 |
+
individual deep-learning artefacts are out of sync with the installed Keras.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import time
|
| 27 |
+
import traceback
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any, Dict, Optional
|
| 30 |
+
|
| 31 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 32 |
+
OUTPUTS_DIR = REPO_ROOT / "outputs"
|
| 33 |
+
|
| 34 |
+
# Stable response schema — bump on breaking changes.
|
| 35 |
+
A16_RESPONSE_VERSION = "1.0.0"
|
| 36 |
+
|
| 37 |
+
# Status enum kept narrow on purpose; UI / tests pattern-match on these.
|
| 38 |
+
STATUS_OK = "OK"
|
| 39 |
+
STATUS_REJECTED_UGLY = "REJECTED_UGLY_RECORDING"
|
| 40 |
+
STATUS_ERROR_NO_VIDEO = "ERROR_NO_VIDEO"
|
| 41 |
+
STATUS_ERROR_PIPELINE = "ERROR_PIPELINE"
|
| 42 |
+
STATUS_ERROR_SCORER = "ERROR_SCORER"
|
| 43 |
+
STATUS_ERROR_TOO_SHORT = "ERROR_TOO_SHORT_AFTER_CUT"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _empty_timing() -> Dict[str, float]:
|
| 47 |
+
return {
|
| 48 |
+
"upstream_ms": 0.0,
|
| 49 |
+
"scorer_nn_ms": 0.0,
|
| 50 |
+
"scorer_total_ms": 0.0,
|
| 51 |
+
"total_ms": 0.0,
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _base_response(
|
| 56 |
+
status: str,
|
| 57 |
+
*,
|
| 58 |
+
variant: str = "3D",
|
| 59 |
+
message: str = "",
|
| 60 |
+
) -> Dict[str, Any]:
|
| 61 |
+
"""Skeleton response — every endpoint return goes through this."""
|
| 62 |
+
return {
|
| 63 |
+
"schema_version": A16_RESPONSE_VERSION,
|
| 64 |
+
"endpoint": "A16",
|
| 65 |
+
"variant": variant,
|
| 66 |
+
"status": status,
|
| 67 |
+
"message": message,
|
| 68 |
+
"recording": {
|
| 69 |
+
"quality_label": None,
|
| 70 |
+
"quality_confidence": None,
|
| 71 |
+
"threshold": None,
|
| 72 |
+
},
|
| 73 |
+
"segment": {
|
| 74 |
+
"start_frame": None,
|
| 75 |
+
"stop_frame": None,
|
| 76 |
+
"duration_frames": None,
|
| 77 |
+
"duration_sec": None,
|
| 78 |
+
"total_frames": None,
|
| 79 |
+
},
|
| 80 |
+
"classification": {
|
| 81 |
+
"label": None,
|
| 82 |
+
"confidence": None,
|
| 83 |
+
},
|
| 84 |
+
"score": {
|
| 85 |
+
"value": None,
|
| 86 |
+
"band": None,
|
| 87 |
+
"scale": "0=best, 4=worst",
|
| 88 |
+
},
|
| 89 |
+
"artefacts": {
|
| 90 |
+
"full_3d_csv": None,
|
| 91 |
+
"cut_3d_csv": None,
|
| 92 |
+
"skeleton_mp4": None,
|
| 93 |
+
},
|
| 94 |
+
"timing_ms": _empty_timing(),
|
| 95 |
+
"warnings": [],
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _attach_upstream_fields(resp: Dict[str, Any], upstream: Dict[str, Any]) -> None:
|
| 100 |
+
"""Copy the relevant slice of the ``ExercisePipeline`` result into resp."""
|
| 101 |
+
resp["recording"]["quality_label"] = upstream.get("recording_quality")
|
| 102 |
+
resp["recording"]["quality_confidence"] = upstream.get("recording_confidence")
|
| 103 |
+
resp["recording"]["threshold"] = upstream.get("recording_threshold")
|
| 104 |
+
|
| 105 |
+
resp["segment"]["start_frame"] = upstream.get("start_frame")
|
| 106 |
+
resp["segment"]["stop_frame"] = upstream.get("stop_frame")
|
| 107 |
+
resp["segment"]["duration_frames"] = upstream.get("exercise_frames")
|
| 108 |
+
resp["segment"]["duration_sec"] = upstream.get("exercise_duration_sec")
|
| 109 |
+
resp["segment"]["total_frames"] = upstream.get("total_frames")
|
| 110 |
+
|
| 111 |
+
resp["classification"]["label"] = upstream.get("quality_label")
|
| 112 |
+
resp["classification"]["confidence"] = upstream.get("quality_confidence")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _resolve_artefacts(resp: Dict[str, Any], video_path: str) -> Optional[Path]:
|
| 116 |
+
"""Populate artefact paths from the upstream stage. Returns cut CSV path."""
|
| 117 |
+
stem = Path(video_path).stem
|
| 118 |
+
full_csv = OUTPUTS_DIR / f"{stem}_3d_points.csv"
|
| 119 |
+
cut_csv = OUTPUTS_DIR / f"{stem}_cut_3d_points.csv"
|
| 120 |
+
skel_mp4 = OUTPUTS_DIR / f"{stem}_skeleton.mp4"
|
| 121 |
+
|
| 122 |
+
resp["artefacts"]["full_3d_csv"] = str(full_csv) if full_csv.exists() else None
|
| 123 |
+
resp["artefacts"]["cut_3d_csv"] = str(cut_csv) if cut_csv.exists() else None
|
| 124 |
+
resp["artefacts"]["skeleton_mp4"] = str(skel_mp4) if skel_mp4.exists() else None
|
| 125 |
+
return cut_csv if cut_csv.exists() else None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def run_pipeline_3d(
|
| 129 |
+
video_path: Optional[str],
|
| 130 |
+
quality_threshold: float = 0.6,
|
| 131 |
+
) -> Dict[str, Any]:
|
| 132 |
+
"""Run the full 3D A16 pipeline on one video.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
video_path : str or None
|
| 137 |
+
Path to the input video. ``None`` returns a structured error.
|
| 138 |
+
quality_threshold : float
|
| 139 |
+
Recording-quality threshold forwarded to :class:`ExercisePipeline`.
|
| 140 |
+
|
| 141 |
+
Returns
|
| 142 |
+
-------
|
| 143 |
+
dict
|
| 144 |
+
A response dictionary matching the schema in :data:`A16_RESPONSE_VERSION`.
|
| 145 |
+
Errors are reported via ``status`` + ``message`` rather than raised.
|
| 146 |
+
"""
|
| 147 |
+
t_total = time.perf_counter()
|
| 148 |
+
resp = _base_response(STATUS_OK, variant="3D")
|
| 149 |
+
|
| 150 |
+
if not video_path:
|
| 151 |
+
resp["status"] = STATUS_ERROR_NO_VIDEO
|
| 152 |
+
resp["message"] = "No video provided."
|
| 153 |
+
resp["timing_ms"]["total_ms"] = (time.perf_counter() - t_total) * 1000.0
|
| 154 |
+
return resp
|
| 155 |
+
|
| 156 |
+
# ---- Stage 1-5: upstream pipeline (pose → 3D → cut → ugly/good-bad) ----
|
| 157 |
+
t_up = time.perf_counter()
|
| 158 |
+
try:
|
| 159 |
+
# Local import keeps test-time mocking easy and avoids importing
|
| 160 |
+
# TensorFlow when this module is merely inspected.
|
| 161 |
+
from exercise_pipeline import ExercisePipeline
|
| 162 |
+
|
| 163 |
+
pipeline = ExercisePipeline(quality_threshold=quality_threshold)
|
| 164 |
+
try:
|
| 165 |
+
upstream = pipeline.process_video(video_path)
|
| 166 |
+
finally:
|
| 167 |
+
pipeline.close()
|
| 168 |
+
except Exception as exc: # pragma: no cover — surfaced via response
|
| 169 |
+
resp["status"] = STATUS_ERROR_PIPELINE
|
| 170 |
+
resp["message"] = f"{type(exc).__name__}: {exc}"
|
| 171 |
+
resp["warnings"].append(traceback.format_exc(limit=3))
|
| 172 |
+
resp["timing_ms"]["upstream_ms"] = (time.perf_counter() - t_up) * 1000.0
|
| 173 |
+
resp["timing_ms"]["total_ms"] = (time.perf_counter() - t_total) * 1000.0
|
| 174 |
+
return resp
|
| 175 |
+
resp["timing_ms"]["upstream_ms"] = (time.perf_counter() - t_up) * 1000.0
|
| 176 |
+
|
| 177 |
+
if not upstream:
|
| 178 |
+
resp["status"] = STATUS_ERROR_PIPELINE
|
| 179 |
+
resp["message"] = "Upstream pipeline returned no result."
|
| 180 |
+
resp["timing_ms"]["total_ms"] = (time.perf_counter() - t_total) * 1000.0
|
| 181 |
+
return resp
|
| 182 |
+
|
| 183 |
+
_attach_upstream_fields(resp, upstream)
|
| 184 |
+
cut_csv = _resolve_artefacts(resp, video_path)
|
| 185 |
+
|
| 186 |
+
# Ugly recording → early return, no scoring.
|
| 187 |
+
if upstream.get("pipeline_stopped") or upstream.get("recording_quality") == "UGLY":
|
| 188 |
+
resp["status"] = STATUS_REJECTED_UGLY
|
| 189 |
+
resp["message"] = upstream.get(
|
| 190 |
+
"reason", "Recording rejected by quality gate."
|
| 191 |
+
)
|
| 192 |
+
resp["timing_ms"]["total_ms"] = (time.perf_counter() - t_total) * 1000.0
|
| 193 |
+
return resp
|
| 194 |
+
|
| 195 |
+
# ---- Stage 6: A15 scoring on the cut 3D CSV ----
|
| 196 |
+
if cut_csv is None:
|
| 197 |
+
resp["status"] = STATUS_ERROR_PIPELINE
|
| 198 |
+
resp["message"] = "Cut 3D CSV not produced by the upstream stage."
|
| 199 |
+
resp["timing_ms"]["total_ms"] = (time.perf_counter() - t_total) * 1000.0
|
| 200 |
+
return resp
|
| 201 |
+
|
| 202 |
+
t_score = time.perf_counter()
|
| 203 |
+
try:
|
| 204 |
+
import pandas as pd
|
| 205 |
+
from A15.inference import A15_C, predict_score
|
| 206 |
+
|
| 207 |
+
df = pd.read_csv(cut_csv)
|
| 208 |
+
if len(df) < A15_C:
|
| 209 |
+
resp["status"] = STATUS_ERROR_TOO_SHORT
|
| 210 |
+
resp["message"] = (
|
| 211 |
+
f"Only {len(df)} cut frames available; scorer needs {A15_C}."
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
score, band, nn_ms = predict_score(df)
|
| 215 |
+
resp["score"]["value"] = round(score, 4)
|
| 216 |
+
resp["score"]["band"] = band
|
| 217 |
+
resp["timing_ms"]["scorer_nn_ms"] = round(nn_ms, 2)
|
| 218 |
+
except Exception as exc:
|
| 219 |
+
resp["status"] = STATUS_ERROR_SCORER
|
| 220 |
+
resp["message"] = f"Scorer failed: {type(exc).__name__}: {exc}"
|
| 221 |
+
resp["warnings"].append(traceback.format_exc(limit=3))
|
| 222 |
+
resp["timing_ms"]["scorer_total_ms"] = round(
|
| 223 |
+
(time.perf_counter() - t_score) * 1000.0, 2
|
| 224 |
+
)
|
| 225 |
+
resp["timing_ms"]["upstream_ms"] = round(resp["timing_ms"]["upstream_ms"], 2)
|
| 226 |
+
resp["timing_ms"]["total_ms"] = round(
|
| 227 |
+
(time.perf_counter() - t_total) * 1000.0, 2
|
| 228 |
+
)
|
| 229 |
+
return resp
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def run_pipeline_2d(
|
| 233 |
+
video_path: Optional[str],
|
| 234 |
+
quality_threshold: float = 0.6,
|
| 235 |
+
) -> Dict[str, Any]:
|
| 236 |
+
"""Reserved 2D-only alternative endpoint.
|
| 237 |
+
|
| 238 |
+
Not implemented yet — kept as a named slot so the UI / clients can probe
|
| 239 |
+
its existence and the schema stays stable when the 2D path lands. Returns
|
| 240 |
+
a well-formed response with ``status = ERROR_PIPELINE`` and an explanatory
|
| 241 |
+
message.
|
| 242 |
+
"""
|
| 243 |
+
resp = _base_response(
|
| 244 |
+
STATUS_ERROR_PIPELINE,
|
| 245 |
+
variant="2D",
|
| 246 |
+
message="2D alternative not implemented yet — see A16_Report.ipynb.",
|
| 247 |
+
)
|
| 248 |
+
return resp
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def run_pipeline(
|
| 252 |
+
video_path: Optional[str],
|
| 253 |
+
quality_threshold: float = 0.6,
|
| 254 |
+
variant: str = "3D",
|
| 255 |
+
) -> Dict[str, Any]:
|
| 256 |
+
"""Dispatcher — pick the 2D or 3D alternative."""
|
| 257 |
+
variant = (variant or "3D").upper()
|
| 258 |
+
if variant == "2D":
|
| 259 |
+
return run_pipeline_2d(video_path, quality_threshold=quality_threshold)
|
| 260 |
+
return run_pipeline_3d(video_path, quality_threshold=quality_threshold)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
__all__ = [
|
| 264 |
+
"A16_RESPONSE_VERSION",
|
| 265 |
+
"STATUS_OK",
|
| 266 |
+
"STATUS_REJECTED_UGLY",
|
| 267 |
+
"STATUS_ERROR_NO_VIDEO",
|
| 268 |
+
"STATUS_ERROR_PIPELINE",
|
| 269 |
+
"STATUS_ERROR_SCORER",
|
| 270 |
+
"STATUS_ERROR_TOO_SHORT",
|
| 271 |
+
"run_pipeline",
|
| 272 |
+
"run_pipeline_3d",
|
| 273 |
+
"run_pipeline_2d",
|
| 274 |
+
]
|
A16/service/ui.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio UI tab for the A16 final unified endpoint."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Any, Dict, Tuple
|
| 6 |
+
|
| 7 |
+
from A16.service.endpoint import (
|
| 8 |
+
STATUS_OK,
|
| 9 |
+
STATUS_REJECTED_UGLY,
|
| 10 |
+
run_pipeline_3d,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _format_summary(resp: Dict[str, Any]) -> str:
|
| 15 |
+
"""Render the response as a human-readable Markdown block."""
|
| 16 |
+
rec = resp["recording"]
|
| 17 |
+
seg = resp["segment"]
|
| 18 |
+
cls = resp["classification"]
|
| 19 |
+
sc = resp["score"]
|
| 20 |
+
t = resp["timing_ms"]
|
| 21 |
+
|
| 22 |
+
lines = [
|
| 23 |
+
f"### A16 Final Endpoint — {resp['variant']} variant",
|
| 24 |
+
f"**Status:** `{resp['status']}`",
|
| 25 |
+
]
|
| 26 |
+
if resp.get("message"):
|
| 27 |
+
lines.append(f"**Message:** {resp['message']}")
|
| 28 |
+
|
| 29 |
+
lines += [
|
| 30 |
+
"",
|
| 31 |
+
"#### Recording quality (ugly gate)",
|
| 32 |
+
f"- Label: **{rec['quality_label']}**",
|
| 33 |
+
f"- Confidence: **{rec['quality_confidence']}** "
|
| 34 |
+
f"(threshold {rec['threshold']})",
|
| 35 |
+
"",
|
| 36 |
+
"#### Exercise segment (start/stop cut)",
|
| 37 |
+
f"- Frames: **{seg['start_frame']} → {seg['stop_frame']}** "
|
| 38 |
+
f"of {seg['total_frames']}",
|
| 39 |
+
f"- Duration: **{seg['duration_frames']} frames "
|
| 40 |
+
f"≈ {seg['duration_sec']} s**",
|
| 41 |
+
"",
|
| 42 |
+
"#### Good / Bad classification",
|
| 43 |
+
f"- Label: **{cls['label']}**",
|
| 44 |
+
f"- Confidence: **{cls['confidence']}**",
|
| 45 |
+
"",
|
| 46 |
+
"#### Score (0–4, lower is better)",
|
| 47 |
+
f"- Score: **{sc['value']}**",
|
| 48 |
+
f"- Band: **{sc['band']}**",
|
| 49 |
+
"",
|
| 50 |
+
"#### Timing (ms)",
|
| 51 |
+
f"- Upstream (pose + 3D + cut + ugly/good-bad): **{t['upstream_ms']}**",
|
| 52 |
+
f"- Scorer total: **{t['scorer_total_ms']}** "
|
| 53 |
+
f"(NN only: **{t['scorer_nn_ms']}**)",
|
| 54 |
+
f"- End-to-end total: **{t['total_ms']}**",
|
| 55 |
+
]
|
| 56 |
+
if resp.get("warnings"):
|
| 57 |
+
lines += ["", "#### Warnings"]
|
| 58 |
+
for w in resp["warnings"]:
|
| 59 |
+
lines.append(f"- {w.splitlines()[0] if w else ''}")
|
| 60 |
+
return "\n".join(lines)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _status_badge(resp: Dict[str, Any]) -> str:
|
| 64 |
+
"""Compact one-line status string for the textbox."""
|
| 65 |
+
if resp["status"] == STATUS_OK:
|
| 66 |
+
return f"OK — score {resp['score']['value']} ({resp['score']['band']})"
|
| 67 |
+
if resp["status"] == STATUS_REJECTED_UGLY:
|
| 68 |
+
return (
|
| 69 |
+
f"REJECTED — ugly recording "
|
| 70 |
+
f"(conf {resp['recording']['quality_confidence']})"
|
| 71 |
+
)
|
| 72 |
+
return f"{resp['status']} — {resp.get('message', '')}"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def run_a16_tab(
|
| 76 |
+
video_path: str,
|
| 77 |
+
quality_threshold: float,
|
| 78 |
+
) -> Tuple[str, str, Any, Dict[str, Any]]:
|
| 79 |
+
"""Gradio callback for the A16 tab.
|
| 80 |
+
|
| 81 |
+
Returns ``(status_text, summary_markdown, skeleton_video, full_json)``.
|
| 82 |
+
"""
|
| 83 |
+
resp = run_pipeline_3d(video_path, quality_threshold=quality_threshold)
|
| 84 |
+
skeleton_video = resp["artefacts"].get("skeleton_mp4")
|
| 85 |
+
return _status_badge(resp), _format_summary(resp), skeleton_video, resp
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def build_a16_tab(gr):
|
| 89 |
+
"""Build the A16 Gradio tab. ``gr`` is the imported ``gradio`` module.
|
| 90 |
+
|
| 91 |
+
Kept as a builder so [app.py](../../app.py) can import and mount the tab
|
| 92 |
+
without re-implementing the layout.
|
| 93 |
+
"""
|
| 94 |
+
with gr.TabItem("A16 Final Endpoint"):
|
| 95 |
+
gr.Markdown(
|
| 96 |
+
"""
|
| 97 |
+
## A16 — Final unified endpoint (3D alternative)
|
| 98 |
+
|
| 99 |
+
Single video upload runs the full Part-II chain:
|
| 100 |
+
**pose → PoseNet→Kinect 2D → 2D→3D → start/stop cut →
|
| 101 |
+
ugly/good-bad → 0–4 score**.
|
| 102 |
+
|
| 103 |
+
A 2D-only alternative is reserved on the same response schema
|
| 104 |
+
(see `A16.service.endpoint.run_pipeline_2d`).
|
| 105 |
+
"""
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
with gr.Row():
|
| 109 |
+
with gr.Column():
|
| 110 |
+
a16_video = gr.Video(label="Upload exercise video")
|
| 111 |
+
a16_threshold = gr.Slider(
|
| 112 |
+
minimum=0.1, maximum=0.9, value=0.6, step=0.05,
|
| 113 |
+
label="Recording quality threshold",
|
| 114 |
+
)
|
| 115 |
+
a16_run = gr.Button("Run A16 endpoint", variant="primary")
|
| 116 |
+
|
| 117 |
+
with gr.Column():
|
| 118 |
+
a16_status = gr.Textbox(label="Status", interactive=False)
|
| 119 |
+
a16_summary = gr.Markdown()
|
| 120 |
+
a16_video_out = gr.Video(label="3D skeleton animation")
|
| 121 |
+
a16_json = gr.JSON(label="Full response (A16 schema)")
|
| 122 |
+
|
| 123 |
+
a16_run.click(
|
| 124 |
+
fn=run_a16_tab,
|
| 125 |
+
inputs=[a16_video, a16_threshold],
|
| 126 |
+
outputs=[a16_status, a16_summary, a16_video_out, a16_json],
|
| 127 |
+
)
|
A16/tests/__init__.py
ADDED
|
File without changes
|
A16/tests/test_endpoint.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for the A16 unified endpoint.
|
| 2 |
+
|
| 3 |
+
These tests are intentionally **model-free**: the upstream
|
| 4 |
+
``ExercisePipeline`` and the A15 scorer are monkey-patched so CI does not
|
| 5 |
+
need GPU / large model artefacts. They lock in the public response schema
|
| 6 |
+
and the error/ugly branches.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 17 |
+
if str(REPO_ROOT) not in sys.path:
|
| 18 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 19 |
+
|
| 20 |
+
from A16.service import endpoint as ep # noqa: E402
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ---------- helpers ----------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
class _FakePipeline:
|
| 26 |
+
"""Stand-in for :class:`ExercisePipeline` — returns a canned result."""
|
| 27 |
+
|
| 28 |
+
def __init__(self, result, *args, **kwargs):
|
| 29 |
+
self._result = result
|
| 30 |
+
|
| 31 |
+
def process_video(self, video_path): # noqa: D401 — signature match
|
| 32 |
+
return self._result
|
| 33 |
+
|
| 34 |
+
def close(self):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _install_fake_pipeline(monkeypatch, result):
|
| 39 |
+
"""Replace the upstream pipeline with a fake returning ``result``."""
|
| 40 |
+
import types
|
| 41 |
+
|
| 42 |
+
fake_module = types.ModuleType("exercise_pipeline")
|
| 43 |
+
|
| 44 |
+
class _Factory(_FakePipeline):
|
| 45 |
+
def __init__(self, *args, **kwargs):
|
| 46 |
+
super().__init__(result)
|
| 47 |
+
|
| 48 |
+
fake_module.ExercisePipeline = _Factory
|
| 49 |
+
monkeypatch.setitem(sys.modules, "exercise_pipeline", fake_module)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ---------- schema -----------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
REQUIRED_TOP_LEVEL_KEYS = {
|
| 55 |
+
"schema_version",
|
| 56 |
+
"endpoint",
|
| 57 |
+
"variant",
|
| 58 |
+
"status",
|
| 59 |
+
"message",
|
| 60 |
+
"recording",
|
| 61 |
+
"segment",
|
| 62 |
+
"classification",
|
| 63 |
+
"score",
|
| 64 |
+
"artefacts",
|
| 65 |
+
"timing_ms",
|
| 66 |
+
"warnings",
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
REQUIRED_TIMING_KEYS = {
|
| 70 |
+
"upstream_ms", "scorer_nn_ms", "scorer_total_ms", "total_ms",
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _assert_schema(resp):
|
| 75 |
+
assert isinstance(resp, dict)
|
| 76 |
+
missing = REQUIRED_TOP_LEVEL_KEYS - set(resp.keys())
|
| 77 |
+
assert not missing, f"missing top-level keys: {missing}"
|
| 78 |
+
assert resp["endpoint"] == "A16"
|
| 79 |
+
assert resp["schema_version"] == ep.A16_RESPONSE_VERSION
|
| 80 |
+
assert resp["variant"] in {"2D", "3D"}
|
| 81 |
+
assert REQUIRED_TIMING_KEYS <= set(resp["timing_ms"].keys())
|
| 82 |
+
for section in ("recording", "segment", "classification", "score", "artefacts"):
|
| 83 |
+
assert isinstance(resp[section], dict)
|
| 84 |
+
assert isinstance(resp["warnings"], list)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ---------- tests ------------------------------------------------------------
|
| 88 |
+
|
| 89 |
+
class TestSchema:
|
| 90 |
+
|
| 91 |
+
def test_no_video_returns_well_formed_error(self):
|
| 92 |
+
resp = ep.run_pipeline_3d(None)
|
| 93 |
+
_assert_schema(resp)
|
| 94 |
+
assert resp["status"] == ep.STATUS_ERROR_NO_VIDEO
|
| 95 |
+
|
| 96 |
+
def test_2d_alternative_returns_well_formed_placeholder(self):
|
| 97 |
+
resp = ep.run_pipeline_2d("dummy.mp4")
|
| 98 |
+
_assert_schema(resp)
|
| 99 |
+
assert resp["variant"] == "2D"
|
| 100 |
+
# 2D not implemented yet — must surface as structured error, not raise.
|
| 101 |
+
assert resp["status"] == ep.STATUS_ERROR_PIPELINE
|
| 102 |
+
|
| 103 |
+
def test_dispatcher_routes_variant(self):
|
| 104 |
+
assert ep.run_pipeline(None, variant="2D")["variant"] == "2D"
|
| 105 |
+
assert ep.run_pipeline(None, variant="3D")["variant"] == "3D"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class TestUglyPath:
|
| 109 |
+
|
| 110 |
+
def test_ugly_recording_short_circuits(self, monkeypatch):
|
| 111 |
+
ugly_upstream = {
|
| 112 |
+
"video": "x.mp4",
|
| 113 |
+
"total_frames": 30,
|
| 114 |
+
"recording_quality": "UGLY",
|
| 115 |
+
"recording_confidence": 0.31,
|
| 116 |
+
"recording_threshold": 0.6,
|
| 117 |
+
"pipeline_stopped": True,
|
| 118 |
+
"reason": "Poor recording quality.",
|
| 119 |
+
}
|
| 120 |
+
_install_fake_pipeline(monkeypatch, ugly_upstream)
|
| 121 |
+
resp = ep.run_pipeline_3d("does-not-need-to-exist.mp4")
|
| 122 |
+
_assert_schema(resp)
|
| 123 |
+
assert resp["status"] == ep.STATUS_REJECTED_UGLY
|
| 124 |
+
assert resp["recording"]["quality_label"] == "UGLY"
|
| 125 |
+
assert resp["recording"]["quality_confidence"] == 0.31
|
| 126 |
+
# No score should have been computed on the ugly branch.
|
| 127 |
+
assert resp["score"]["value"] is None
|
| 128 |
+
assert resp["timing_ms"]["scorer_nn_ms"] == 0.0
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TestHappyPath:
|
| 132 |
+
|
| 133 |
+
def test_full_pipeline_with_mocked_scorer(self, monkeypatch, tmp_path):
|
| 134 |
+
# Fake cut CSV with 10 frames and the expected 13-joint xyz columns.
|
| 135 |
+
import pandas as pd
|
| 136 |
+
from A15.inference import A15_JOINTS, A15_C
|
| 137 |
+
|
| 138 |
+
cols = [f"{j}_{ax}" for j in A15_JOINTS for ax in ("x", "y", "z")]
|
| 139 |
+
df = pd.DataFrame(
|
| 140 |
+
[[0.0] * len(cols) for _ in range(A15_C)],
|
| 141 |
+
columns=cols,
|
| 142 |
+
)
|
| 143 |
+
cut_csv = tmp_path / "demo_cut_3d_points.csv"
|
| 144 |
+
df.to_csv(cut_csv, index=False)
|
| 145 |
+
|
| 146 |
+
# Point the endpoint's artefact resolution at our tmp dir.
|
| 147 |
+
monkeypatch.setattr(ep, "OUTPUTS_DIR", tmp_path)
|
| 148 |
+
|
| 149 |
+
good_upstream = {
|
| 150 |
+
"video": "demo.mp4",
|
| 151 |
+
"total_frames": 90,
|
| 152 |
+
"start_frame": 10,
|
| 153 |
+
"stop_frame": 70,
|
| 154 |
+
"exercise_frames": 61,
|
| 155 |
+
"exercise_duration_sec": 2.03,
|
| 156 |
+
"quality_label": "GOOD",
|
| 157 |
+
"quality_confidence": 0.87,
|
| 158 |
+
"recording_quality": "GOOD",
|
| 159 |
+
"recording_confidence": 0.78,
|
| 160 |
+
"recording_threshold": 0.6,
|
| 161 |
+
}
|
| 162 |
+
_install_fake_pipeline(monkeypatch, good_upstream)
|
| 163 |
+
|
| 164 |
+
# Mock the A15 scorer so we don't load Keras / joblib in CI.
|
| 165 |
+
import A15.inference as inf
|
| 166 |
+
monkeypatch.setattr(
|
| 167 |
+
inf, "predict_score", lambda d: (0.42, "GREEN — acceptable form (0-1)", 1.5)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# `_resolve_artefacts` uses the video stem; mirror it in tmp.
|
| 171 |
+
video_path = str(tmp_path / "demo.mp4")
|
| 172 |
+
# Need the upstream stem-prefixed CSV to exist where _resolve_artefacts looks.
|
| 173 |
+
(tmp_path / "demo_cut_3d_points.csv").write_text(cut_csv.read_text())
|
| 174 |
+
|
| 175 |
+
resp = ep.run_pipeline_3d(video_path)
|
| 176 |
+
_assert_schema(resp)
|
| 177 |
+
assert resp["status"] == ep.STATUS_OK
|
| 178 |
+
assert resp["classification"]["label"] == "GOOD"
|
| 179 |
+
assert resp["segment"]["start_frame"] == 10
|
| 180 |
+
assert resp["segment"]["stop_frame"] == 70
|
| 181 |
+
assert resp["score"]["value"] == pytest.approx(0.42)
|
| 182 |
+
assert "GREEN" in resp["score"]["band"]
|
| 183 |
+
assert resp["timing_ms"]["scorer_nn_ms"] == 1.5
|
| 184 |
+
assert resp["timing_ms"]["total_ms"] >= 0
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class TestBandMapping:
|
| 188 |
+
|
| 189 |
+
@pytest.mark.parametrize("score,prefix", [
|
| 190 |
+
(0.0, "GREEN"),
|
| 191 |
+
(0.99, "GREEN"),
|
| 192 |
+
(1.0, "AMBER"),
|
| 193 |
+
(1.99, "AMBER"),
|
| 194 |
+
(2.0, "RED"),
|
| 195 |
+
(4.0, "RED"),
|
| 196 |
+
])
|
| 197 |
+
def test_score_band_boundaries(self, score, prefix):
|
| 198 |
+
from A15.inference import score_band
|
| 199 |
+
assert score_band(score).startswith(prefix)
|
app.py
CHANGED
|
@@ -4,6 +4,7 @@ from A8.pose_estimator import MoveNetPoseEstimator
|
|
| 4 |
from A12.pose_interpolator import smooth_pose_sequence
|
| 5 |
#http://127.0.0.1:7860from A12.service.ui import run_a12_tab
|
| 6 |
from A12.service.ui import run_a12_video_tab
|
|
|
|
| 7 |
from exercise_pipeline import ExercisePipeline
|
| 8 |
import json
|
| 9 |
import csv
|
|
@@ -751,6 +752,9 @@ with gr.Blocks(title="MoveNet Pose Estimation") as demo:
|
|
| 751 |
outputs=[a15_band, a15_score, a15_timing, a15_json],
|
| 752 |
)
|
| 753 |
|
|
|
|
|
|
|
|
|
|
| 754 |
|
| 755 |
# Example section
|
| 756 |
with gr.Accordion("ℹ️ Information", open=False):
|
|
|
|
| 4 |
from A12.pose_interpolator import smooth_pose_sequence
|
| 5 |
#http://127.0.0.1:7860from A12.service.ui import run_a12_tab
|
| 6 |
from A12.service.ui import run_a12_video_tab
|
| 7 |
+
from A16.service.ui import build_a16_tab
|
| 8 |
from exercise_pipeline import ExercisePipeline
|
| 9 |
import json
|
| 10 |
import csv
|
|
|
|
| 752 |
outputs=[a15_band, a15_score, a15_timing, a15_json],
|
| 753 |
)
|
| 754 |
|
| 755 |
+
# A16 Final unified endpoint (capstone)
|
| 756 |
+
build_a16_tab(gr)
|
| 757 |
+
|
| 758 |
|
| 759 |
# Example section
|
| 760 |
with gr.Accordion("ℹ️ Information", open=False):
|
pytest.ini
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
[pytest]
|
| 2 |
-
testpaths = A4
|
| 3 |
|
| 4 |
python_files = test_*.py
|
| 5 |
python_classes = Test*
|
|
|
|
| 1 |
[pytest]
|
| 2 |
+
testpaths = A4 A16
|
| 3 |
|
| 4 |
python_files = test_*.py
|
| 5 |
python_classes = Test*
|