feat(pose)!: use coco17 3d router features
Browse filesBREAKING CHANGE: exercise router artifacts must be regenerated with the coco17_3d_v1 feature schema.
Files changed (18)
- README.md+11-2
- docs/huggingface-router-release.md+14
- docs/implementation-plan.md+1-1
- docs/pozify-project-documentation.md+9-9
- scripts/exercise_router_modal.py+276-31
- scripts/upload_exercise_router_to_hf.py+4
- src/pozify/exercises/shared/analyzer.py+9-8
- src/pozify/ml/exercise_router_features.py+29-17
- src/pozify/ml/exercise_router_inference.py+52-7
- src/pozify/steps/pose_backends/__init__.py+7-1
- src/pozify/steps/pose_backends/landmarks.py+25-16
- src/pozify/steps/pose_cleaning.py+96-33
- src/pozify/steps/pose_landmarker.py+15
- src/pozify/steps/rep_signals.py+52-10
- tests/test_exercise_classifier.py+43-24
- tests/test_pose_steps.py+11-7
- tests/test_rep_counter.py+16
- web/app.js+1-1
94 unmodified lines9596979899100101146 unmodified lines24824925025125225311 unmodified lines26526626726826927027194 unmodified lines```textuser profile + input video-> video QC-> 33-point pose landmarker-> pose cleaning and normalization-> exercise classifier-> exercise-specific rep counter146 unmodified linesuv run modal run scripts/exercise_router_modal.py --stage evaluate```The latest training metrics and selected-artifact result are recorded in[docs/exercise-router-training-report.md](docs/exercise-router-training-report.md).Custom data collection is documented in11 unmodified lines`temporal_metrics.json`. Its default hyperparameters follow the Riccio exercise-classification paper:73 hidden units, 0.2174 dropout, 0.0004 learning rate, batch size 54, and 73 epochs(https://arxiv.org/abs/2411.11548). Evaluation scores every available trained artifact, writesper-model metrics into `evaluation.json`, and records the active artifact in `router_selection.json`.The current selection policy prefers the BiLSTM temporal model when it is available; the baseline iskept as a fallback/reference artifact.94 unmodified lines9596979899100101146 unmodified lines24824925025125225325425525625725825926026111 unmodified lines27327427527627727827928094 unmodified lines```textuser profile + input video-> video QC-> 17-point 3D pose landmarker-> pose cleaning and normalization-> exercise classifier-> exercise-specific rep counter146 unmodified linesuv run modal run scripts/exercise_router_modal.py --stage evaluate```The `evaluate` and `all` stages automatically publish the selected router artifacts to Hugging Faceafter evaluation. Set `POZIFY_ROUTER_HF_REPO_ID` and `HF_TOKEN` in `.env` or pass a repo explicitly:```bashuv run modal run scripts/exercise_router_modal.py --stage all --repo-id owner/pozify-exercise-routeruv run modal run scripts/exercise_router_modal.py --stage publish --repo-id owner/pozify-exercise-router```The latest training metrics and selected-artifact result are recorded in[docs/exercise-router-training-report.md](docs/exercise-router-training-report.md).Custom data collection is documented in11 unmodified lines`temporal_metrics.json`. Its default hyperparameters follow the Riccio exercise-classification paper:73 hidden units, 0.2174 dropout, 0.0004 learning rate, batch size 54, and 73 epochs(https://arxiv.org/abs/2411.11548). Evaluation scores every available trained artifact, writesper-model metrics into `evaluation.json`, records the active artifact in `router_selection.json`,and publishes artifacts to Hugging Face when the `evaluate` or `all` stage completes.The current selection policy prefers the BiLSTM temporal model when it is available; the baseline iskept as a fallback/reference artifact.
58 unmodified lines5960616263641 unmodified line66676869707158 unmodified linesOmit `--private` if the model repository should be public.The upload script creates the repository if needed and uploads:- `README.md` model card1 unmodified line- `router_selection.json`- `temporal.pt`- `training_report.md`## Runtime Configuration58 unmodified lines59606162636465666768697071727374751 unmodified line77787980818283848558 unmodified linesOmit `--private` if the model repository should be public.The Modal training script can also publish directly from the `pozify-router-models` volume afterevaluation. It reads `HF_TOKEN`, `POZIFY_ROUTER_HF_REPO_ID`, and optional`POZIFY_ROUTER_HF_PRIVATE=1` from `.env` via `modal.Secret.from_dotenv()`:```bashuv run modal run scripts/exercise_router_modal.py --stage alluv run modal run scripts/exercise_router_modal.py --stage publish --repo-id build-small-hackathon/pozify-exercise-router````stage evaluate` and `stage all` publish automatically after writing `router_selection.json`.The upload script creates the repository if needed and uploads:- `README.md` model card1 unmodified line- `router_selection.json`- `temporal.pt`- `training_report.md`- `evaluation.json`- `baseline_metrics.json`- `temporal_metrics.json`## Runtime Configuration
27 unmodified lines2829303132333427 unmodified lines## Phase 3: Pose Extraction And CleaningGoal: convert videos into a clean 33-point pose sequence.Deliverables:27 unmodified lines2829303132333427 unmodified lines## Phase 3: Pose Extraction And CleaningGoal: convert videos into a clean 17-point 3D pose sequence.Deliverables:
32 unmodified lines3334353637383939 unmodified lines7980818283848512 unmodified lines9899100101102103104297 unmodified lines4024034044054064074086 unmodified lines4154164174184194204214228 unmodified lines431432433434435436437438276 unmodified lines71571671771871972072132 unmodified lines- Upload or record short workout videos.- User profile and training intent form.- Video quality check.- 33-point pose extraction.- Pose cleaning and normalization.- Exercise classifier for `squat`, `push_up`, `shoulder_press`, and `unknown`.- Exercise-specific rep counter.39 unmodified lines```textuser profile + input video-> video QC-> 33-point pose landmarker-> pose cleaning and normalization-> exercise classifier-> exercise-specific rep counter12 unmodified linesflowchart TDA["User uploads or records workout video"] --> B["Video QC"]U["User profile and training intent"] --> G["Grounded coach summary"]B --> C["33-point Pose Landmarker"]C --> D["Pose cleaning and normalization"]D --> E["Exercise classifier"]E --> F{"Exercise type"}297 unmodified lines- Returns mocked video metadata and warnings.### Step 2: 33-Point Pose LandmarkerGoal:6 unmodified linesReasons:- Works on decoded video frames.- Outputs 33 pose landmarks.- Provides image coordinates and optional world coordinates.- Practical for a Gradio Space.Fine-tuning:8 unmodified linesFuture implementation:- Run MediaPipe on sampled frames.- Store all 33 landmarks.- Store visibility and pose quality per frame.### Step 3: Pose Cleaning And Normalization276 unmodified linesRole:- Extract 33 landmarks per valid frame.Fine-tuning:32 unmodified lines3334353637383939 unmodified lines7980818283848512 unmodified lines9899100101102103104297 unmodified lines4024034044054064074086 unmodified lines4154164174184194204214228 unmodified lines431432433434435436437438276 unmodified lines71571671771871972072132 unmodified lines- Upload or record short workout videos.- User profile and training intent form.- Video quality check.- 17-point 3D pose extraction.- Pose cleaning and normalization.- Exercise classifier for `squat`, `push_up`, `shoulder_press`, and `unknown`.- Exercise-specific rep counter.39 unmodified lines```textuser profile + input video-> video QC-> 17-point 3D pose landmarker-> pose cleaning and normalization-> exercise classifier-> exercise-specific rep counter12 unmodified linesflowchart TDA["User uploads or records workout video"] --> B["Video QC"]U["User profile and training intent"] --> G["Grounded coach summary"]B --> C["17-point 3D Pose Landmarker"]C --> D["Pose cleaning and normalization"]D --> E["Exercise classifier"]E --> F{"Exercise type"}297 unmodified lines- Returns mocked video metadata and warnings.### Step 2: 17-Point 3D Pose LandmarkerGoal:6 unmodified linesReasons:- Works on decoded video frames.- Outputs COCO-17 body landmarks.- Provides image coordinates for rendering and world coordinates for 3D exercise metrics.- Practical for a Gradio Space.Fine-tuning:8 unmodified linesFuture implementation:- Run MediaPipe on sampled frames.- Store all 17 COCO body landmarks.- Store visibility, pose quality, and 3D world coordinates per frame.### Step 3: Pose Cleaning And Normalization276 unmodified linesRole:- Extract 17 COCO body landmarks per valid frame, with 3D world coordinates when available.Fine-tuning:
1234565 unmodified lines12131415161718195 unmodified lines2526272829309 unmodified lines404142434445464748495019 unmodified lines70717273747576777879808182838485861 unmodified line8889909192939429 unmodified lines1241251261271281291301311321331341351361371381391407 unmodified lines14814915015115215315415515615715815916025 unmodified lines18618718818919019119210 unmodified lines2032042052062072081 unmodified line2102112122132142154 unmodified lines2202212222232242256 unmodified lines2322332342352362372382392402412422432442452461 unmodified line2482492502512522536 unmodified lines2602612622632642652663 unmodified lines27027127227327427527627727827928035 unmodified lines3163173183193203213 unmodified lines3253263273283293303311 unmodified line33333433533633733833911 unmodified lines3513523533543553563573583593603613623639 unmodified lines3733743753763773783798 unmodified lines38838939039139239339413 unmodified lines4084094104114124134142 unmodified lines41741841942042142248 unmodified lines47147247347447547647741 unmodified lines51952052152252352452510 unmodified lines5365375385395405415429 unmodified lines55255355455555655755812 unmodified lines57157257357457557657757857958058158258358458511 unmodified lines597598599600601602603604605606607608609610611612613from __future__ import annotationsimport jsonfrom pathlib import Pathimport shutilimport sys5 unmodified linesAPP_NAME = "pozify-exercise-router"DATASET_ID = "RickyRiccio/Real_Time_Exercise_Recognition_Dataset"DATA_ROOT = Path("/data")MODEL_ROOT = Path("/models")RAW_ROOT = DATA_ROOT / "raw"RICCIO_ROOT = RAW_ROOT / "riccio"CUSTOM_UNKNOWN_ROOT = RAW_ROOT / "custom_unknown"5 unmodified lines"final_kaggle_with_additional_video","my_test_video_1",)image = (modal.Image.debian_slim(python_version="3.10")9 unmodified lines"torch==2.11.0",).add_local_dir("src", "/root/src", copy=True))app = modal.App(APP_NAME, image=image)data_volume = modal.Volume.from_name("pozify-router-data", create_if_missing=True, version=2)model_volume = modal.Volume.from_name("pozify-router-models", create_if_missing=True, version=2)def _write_json(path: Path, payload: Any) -> None:19 unmodified lines]def _video_files(root: Path) -> list[Path]:if not root.exists():return []return sorted(path for path in root.rglob("*") if path.suffix.lower() in VIDEO_SUFFIXES)def _riccio_video_files(root: Path) -> list[Path]:files: list[Path] = []dataset_roots = [root / "Real-Time Exercise Recognition Dataset",root / "Real-Time Exercise Recognition Dataset" / "Real-Time Exercise Recognition Dataset",root,]for collection_name in RICCIO_VIDEO_COLLECTIONS:1 unmodified linecollection_root = dataset_root / collection_nameif not collection_root.exists():continuefor class_dir in sorted(path for path in collection_root.iterdir() if path.is_dir()):files.extend(_video_files(class_dir))if files:return sorted(files)29 unmodified lineslabel = normalize_router_label(part)if label != "unknown":return labelif any(token in part.lower() for token in ("unknown", "curl", "idle", "walk", "stretch")):return "unknown"return "unknown"def _example_id(path: Path) -> str:safe = "_".join(path.relative_to(RAW_ROOT).parts)return "".join(char if char.isalnum() or char in {"_", "-", "."} else "_" for char in safe)@app.function(volumes={str(DATA_ROOT): data_volume}, timeout=60 * 60)def ingest() -> dict[str, Any]:from huggingface_hub import snapshot_download7 unmodified linesextracted_archives = _extract_archives(RICCIO_ROOT)examples: list[dict[str, Any]] = []for video_path in [*_riccio_video_files(RICCIO_ROOT), *_video_files(CUSTOM_UNKNOWN_ROOT)]:source = "custom_unknown" if CUSTOM_UNKNOWN_ROOT in video_path.parents else "riccio"examples.append({"id": _example_id(video_path),"video_path": str(video_path),"label": "unknown" if source == "custom_unknown" else _label_from_path(video_path),"source": source,})25 unmodified linesimport numpy as npfrom pozify.ml.exercise_router_features import extract_router_windowsfrom pozify.steps import pose_cleaning, pose_landmarker, video_qcvideo_path = Path(example["video_path"])10 unmodified linesvectors=np.stack([window.vector for window in windows]),tensors=np.stack([window.tensor for window in windows]),label=example["label"],)else:np.savez_compressed(1 unmodified linevectors=np.empty((0, 0), dtype=np.float32),tensors=np.empty((0, 0, 0), dtype=np.float32),label=example["label"],)data_volume.commit()4 unmodified lines"feature_path": str(feature_path),"window_count": len(windows),"pose_valid_ratio": sequence.pose_valid_ratio,}6 unmodified lines"example_count": len(rows),"window_count": sum(int(row.get("window_count", 0)) for row in rows),"failed_count": sum(1 for row in rows if not row.get("ok", True)),},)data_volume.commit()return {"feature_manifest_path": str(FEATURE_MANIFEST_PATH), "example_count": len(rows)}def _load_feature_arrays() -> tuple[Any, Any, Any]:import numpy as npvectors: list[np.ndarray] = []tensors: list[np.ndarray] = []labels: list[str] = []1 unmodified lineif not row.get("ok", True) or int(row.get("window_count", 0)) <= 0:continuedata = np.load(row["feature_path"], allow_pickle=False)row_vectors = data["vectors"]row_tensors = data["tensors"]label = str(data["label"])6 unmodified linesreturn np.stack(vectors), np.stack(tensors), labels@app.function(volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume}, timeout=30 * 60)def train_baseline() -> dict[str, Any]:import joblibfrom sklearn.ensemble import HistGradientBoostingClassifier3 unmodified linesfrom sklearn.preprocessing import StandardScalersys.path.insert(0, "/root/src")from pozify.ml.exercise_router_features import window_vector_feature_namesvectors, _tensors, labels = _load_feature_arrays()if vectors is None or len(set(labels)) < 2:result = {"ok": False, "error": "At least two labels with extracted windows are required"}_write_json(MODEL_ROOT / "baseline_metrics.json", result)model_volume.commit()return result35 unmodified lines"labels": [str(label) for label in model.classes_],"model_kind": "baseline","feature_names": window_vector_feature_names(),"metrics": metrics,},MODEL_ROOT / "baseline.joblib",3 unmodified linesreturn metrics@app.function(gpu="A10", volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume}, timeout=60 * 60)def train_temporal(epochs: int = 73) -> dict[str, Any]:import torchfrom torch import nn1 unmodified linefrom sklearn.model_selection import train_test_splitsys.path.insert(0, "/root/src")from pozify.ml.exercise_router_features import ROUTER_LABELSfrom pozify.ml.exercise_router_evaluation import (evaluation_to_dict,evaluate_router_predictions,11 unmodified lines_vectors, tensors, labels = _load_feature_arrays()if tensors is None or len(set(labels)) < 2:result = {"ok": False, "error": "At least two labels with extracted windows are required"}_write_json(MODEL_ROOT / "temporal_metrics.json", result)model_volume.commit()return resultlabel_to_index = {label: index for index, label in enumerate(ROUTER_LABELS)}label_indices = [label_to_index.get(label, label_to_index["unknown"]) for label in labels]label_counts = {label: labels.count(label) for label in sorted(set(labels))}stratify = labels if min(label_counts.values()) >= 2 else Nonetrain_x, valid_x, train_y, valid_y, _train_labels, valid_labels = train_test_split(9 unmodified linestorch.tensor(train_y, dtype=torch.long),)generator = torch.Generator().manual_seed(42)loader = DataLoader(train_dataset, batch_size=TEMPORAL_BATCH_SIZE, shuffle=True, generator=generator)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")torch.manual_seed(42)8 unmodified linesdropout_rate=TEMPORAL_DROPOUT_RATE,)model = build_temporal_router_model(config).to(device)optimizer = torch.optim.AdamW(model.parameters(), lr=TEMPORAL_LEARNING_RATE, weight_decay=1e-4)loss_fn = nn.CrossEntropyLoss()model.train()last_loss = 0.013 unmodified lineslabels=ROUTER_LABELS,device=device,)validation = evaluation_to_dict(evaluate_router_predictions(list(valid_labels), valid_predictions))torch.save({2 unmodified lines"state_dict": model.cpu().state_dict(),"labels": list(ROUTER_LABELS),"input_size": int(tensors.shape[-1]),"hidden_size": TEMPORAL_HIDDEN_SIZE,"num_layers": TEMPORAL_NUM_LAYERS,"bidirectional": True,48 unmodified linesimport torchsys.path.insert(0, "/root/src")from pozify.ml.exercise_router_temporal import TemporalRouterConfig, build_temporal_router_modelcheckpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)labels = tuple(str(label) for label in checkpoint["labels"])41 unmodified linesif baseline_path.exists():artifact = joblib.load(baseline_path)predictions = list(artifact["model"].predict(vectors))baseline_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))model_results["baseline"] = {"ok": True,"artifact": "baseline.joblib",10 unmodified linesif temporal_path.exists():predictions = _evaluate_temporal_checkpoint(temporal_path, tensors)temporal_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))model_results["temporal"] = {"ok": True,"artifact": "temporal.pt",9 unmodified lines)if not candidates:result = {"ok": False, "error": "At least one trained router artifact is required"}_write_json(MODEL_ROOT / "evaluation.json", result)model_volume.commit()return result12 unmodified lines"selected_model": selection["selected_model"],"selected_artifact": selection["selected_artifact"],"models": model_results,**{key: selected[key] for key in ("accuracy", "precision", "recall", "unknown_rejection_rate", "confusion_matrix")},}_write_json(MODEL_ROOT / "evaluation.json", result)model_volume.commit()return result@app.local_entrypoint()def main(stage: str = "evaluate", limit: int | None = None, epochs: int = 73) -> None:if stage == "ingest":print(ingest.remote())elif stage == "features":11 unmodified linesprint(train_temporal.remote(epochs=epochs))elif stage == "evaluate":print(evaluate.remote())elif stage == "all":print(ingest.remote())examples = load_feature_examples.remote(limit)rows = []for result in extract_example_features.map(examples, return_exceptions=True):rows.append({"ok": False, "error": repr(result)} if isinstance(result, Exception) else {"ok": True, **result})print(write_feature_manifest.remote(rows))print(train_baseline.remote())print(train_temporal.remote(epochs=epochs))print(evaluate.remote())else:raise ValueError("stage must be one of: ingest, features, train-baseline, train-temporal, evaluate, all")12345675 unmodified lines1314151617181920212223245 unmodified lines30313233343536373839404142439 unmodified lines5354555657585960616263646566676869707172737475767719 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211 unmodified line12312412512612712812913013129 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861877 unmodified lines19519619719819920020120220320420520620720820921021121221321421521625 unmodified lines24224324424524624724824925025125225325410 unmodified lines2652662672682692702712722732741 unmodified line2762772782792802812822832842854 unmodified lines2902912922932942952962976 unmodified lines3043053063073083093103113123133143153163173183193203213223233243253263273283291 unmodified line3313323333343353363373383393403413423433443456 unmodified lines3523533543553563573583593603613 unmodified lines36536636736836937037137237337437537637737837938038138235 unmodified lines4184194204214224234244254263 unmodified lines4304314324334344354364374384394401 unmodified line44244344444544644744844945045145245311 unmodified lines4654664674684694704714724734744754764774784794804814829 unmodified lines4924934944954964974984995008 unmodified lines50951051151251351451551651713 unmodified lines5315325335345355365375385392 unmodified lines54254354454554654754854955048 unmodified lines59960060160260360460560660760841 unmodified lines65065165265365465565665765810 unmodified lines6696706716726736746756766779 unmodified lines68768868969069169269369469569612 unmodified lines70971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182211 unmodified lines834835836837838839840841842843844845846847848849850851852853854855856857858from __future__ import annotationsimport jsonimport osfrom pathlib import Pathimport shutilimport sys5 unmodified linesAPP_NAME = "pozify-exercise-router"DATASET_ID = "RickyRiccio/Real_Time_Exercise_Recognition_Dataset"DEFAULT_HF_REPO_ID = "build-small-hackathon/pozify-exercise-router"HF_REPO_ID_ENV = "POZIFY_ROUTER_HF_REPO_ID"HF_PRIVATE_ENV = "POZIFY_ROUTER_HF_PRIVATE"DATA_ROOT = Path("/data")MODEL_ROOT = Path("/models")DOCS_ROOT = Path("/root/docs")RAW_ROOT = DATA_ROOT / "raw"RICCIO_ROOT = RAW_ROOT / "riccio"CUSTOM_UNKNOWN_ROOT = RAW_ROOT / "custom_unknown"5 unmodified lines"final_kaggle_with_additional_video","my_test_video_1",)HF_ARTIFACT_FILENAMES = ("router.joblib","router_selection.json","temporal.pt","evaluation.json","baseline_metrics.json","temporal_metrics.json",)image = (modal.Image.debian_slim(python_version="3.10")9 unmodified lines"torch==2.11.0",).add_local_dir("src", "/root/src", copy=True).add_local_file("docs/huggingface-router-model-card.md","/root/docs/huggingface-router-model-card.md",copy=True,).add_local_file("docs/exercise-router-training-report.md","/root/docs/exercise-router-training-report.md",copy=True,))app = modal.App(APP_NAME, image=image)data_volume = modal.Volume.from_name("pozify-router-data", create_if_missing=True, version=2)model_volume = modal.Volume.from_name("pozify-router-models", create_if_missing=True, version=2)def _write_json(path: Path, payload: Any) -> None:19 unmodified lines]def _env_truthy(value: str | None) -> bool:return value is not None and value.strip().lower() in {"1", "true", "yes", "on"}def _video_files(root: Path) -> list[Path]:if not root.exists():return []return sorted(path for path in root.rglob("*") if path.suffix.lower() in VIDEO_SUFFIXES)def _riccio_video_files(root: Path) -> list[Path]:files: list[Path] = []dataset_roots = [root / "Real-Time Exercise Recognition Dataset",root/ "Real-Time Exercise Recognition Dataset"/ "Real-Time Exercise Recognition Dataset",root,]for collection_name in RICCIO_VIDEO_COLLECTIONS:1 unmodified linecollection_root = dataset_root / collection_nameif not collection_root.exists():continuefor class_dir in sorted(path for path in collection_root.iterdir() if path.is_dir()):files.extend(_video_files(class_dir))if files:return sorted(files)29 unmodified lineslabel = normalize_router_label(part)if label != "unknown":return labelif any(token in part.lower()for token in ("unknown", "curl", "idle", "walk", "stretch")):return "unknown"return "unknown"def _example_id(path: Path) -> str:safe = "_".join(path.relative_to(RAW_ROOT).parts)return "".join(char if char.isalnum() or char in {"_", "-", "."} else "_" for char in safe)@app.function(volumes={str(DATA_ROOT): data_volume},timeout=60 * 60,secrets=[modal.Secret.from_name("huggingface-secret")],gpu="any",)def ingest() -> dict[str, Any]:from huggingface_hub import snapshot_download7 unmodified linesextracted_archives = _extract_archives(RICCIO_ROOT)examples: list[dict[str, Any]] = []for video_path in [*_riccio_video_files(RICCIO_ROOT),*_video_files(CUSTOM_UNKNOWN_ROOT),]:source = ("custom_unknown" if CUSTOM_UNKNOWN_ROOT in video_path.parents else "riccio")examples.append({"id": _example_id(video_path),"video_path": str(video_path),"label": ("unknown"if source == "custom_unknown"else _label_from_path(video_path)),"source": source,})25 unmodified linesimport numpy as npfrom pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LANDMARK_SCHEMA,extract_router_windows,window_tensor_feature_names,window_vector_feature_names,)from pozify.steps import pose_cleaning, pose_landmarker, video_qcvideo_path = Path(example["video_path"])10 unmodified linesvectors=np.stack([window.vector for window in windows]),tensors=np.stack([window.tensor for window in windows]),label=example["label"],feature_schema=FEATURE_SCHEMA,landmark_schema=ROUTER_LANDMARK_SCHEMA,vector_feature_names=np.asarray(window_vector_feature_names()),tensor_feature_names=np.asarray(window_tensor_feature_names()),)else:np.savez_compressed(1 unmodified linevectors=np.empty((0, 0), dtype=np.float32),tensors=np.empty((0, 0, 0), dtype=np.float32),label=example["label"],feature_schema=FEATURE_SCHEMA,landmark_schema=ROUTER_LANDMARK_SCHEMA,vector_feature_names=np.asarray(window_vector_feature_names()),tensor_feature_names=np.asarray(window_tensor_feature_names()),)data_volume.commit()4 unmodified lines"feature_path": str(feature_path),"window_count": len(windows),"pose_valid_ratio": sequence.pose_valid_ratio,"feature_schema": FEATURE_SCHEMA,"landmark_schema": ROUTER_LANDMARK_SCHEMA,}6 unmodified lines"example_count": len(rows),"window_count": sum(int(row.get("window_count", 0)) for row in rows),"failed_count": sum(1 for row in rows if not row.get("ok", True)),"feature_schema": rows[0].get("feature_schema") if rows else None,"landmark_schema": rows[0].get("landmark_schema") if rows else None,},)data_volume.commit()return {"feature_manifest_path": str(FEATURE_MANIFEST_PATH),"example_count": len(rows),}def _load_feature_arrays() -> tuple[Any, Any, Any]:import numpy as npsys.path.insert(0, "/root/src")from pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LANDMARK_SCHEMA,)vectors: list[np.ndarray] = []tensors: list[np.ndarray] = []labels: list[str] = []1 unmodified lineif not row.get("ok", True) or int(row.get("window_count", 0)) <= 0:continuedata = np.load(row["feature_path"], allow_pickle=False)feature_schema = str(data["feature_schema"]) if "feature_schema" in data else ""landmark_schema = (str(data["landmark_schema"]) if "landmark_schema" in data else "")if (feature_schema != FEATURE_SCHEMAor landmark_schema != ROUTER_LANDMARK_SCHEMA):continuerow_vectors = data["vectors"]row_tensors = data["tensors"]label = str(data["label"])6 unmodified linesreturn np.stack(vectors), np.stack(tensors), labels@app.function(volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume},timeout=30 * 60,)def train_baseline() -> dict[str, Any]:import joblibfrom sklearn.ensemble import HistGradientBoostingClassifier3 unmodified linesfrom sklearn.preprocessing import StandardScalersys.path.insert(0, "/root/src")from pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LANDMARK_SCHEMA,window_vector_feature_names,)vectors, _tensors, labels = _load_feature_arrays()if vectors is None or len(set(labels)) < 2:result = {"ok": False,"error": "At least two labels with extracted windows are required",}_write_json(MODEL_ROOT / "baseline_metrics.json", result)model_volume.commit()return result35 unmodified lines"labels": [str(label) for label in model.classes_],"model_kind": "baseline","feature_names": window_vector_feature_names(),"feature_schema": FEATURE_SCHEMA,"landmark_schema": ROUTER_LANDMARK_SCHEMA,"input_size": int(vectors.shape[-1]),"metrics": metrics,},MODEL_ROOT / "baseline.joblib",3 unmodified linesreturn metrics@app.function(gpu="A10",volumes={str(DATA_ROOT): data_volume, str(MODEL_ROOT): model_volume},timeout=60 * 60,)def train_temporal(epochs: int = 73) -> dict[str, Any]:import torchfrom torch import nn1 unmodified linefrom sklearn.model_selection import train_test_splitsys.path.insert(0, "/root/src")from pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LABELS,ROUTER_LANDMARK_SCHEMA,window_tensor_feature_names,)from pozify.ml.exercise_router_evaluation import (evaluation_to_dict,evaluate_router_predictions,11 unmodified lines_vectors, tensors, labels = _load_feature_arrays()if tensors is None or len(set(labels)) < 2:result = {"ok": False,"error": "At least two labels with extracted windows are required",}_write_json(MODEL_ROOT / "temporal_metrics.json", result)model_volume.commit()return resultlabel_to_index = {label: index for index, label in enumerate(ROUTER_LABELS)}label_indices = [label_to_index.get(label, label_to_index["unknown"]) for label in labels]label_counts = {label: labels.count(label) for label in sorted(set(labels))}stratify = labels if min(label_counts.values()) >= 2 else Nonetrain_x, valid_x, train_y, valid_y, _train_labels, valid_labels = train_test_split(9 unmodified linestorch.tensor(train_y, dtype=torch.long),)generator = torch.Generator().manual_seed(42)loader = DataLoader(train_dataset, batch_size=TEMPORAL_BATCH_SIZE, shuffle=True, generator=generator)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")torch.manual_seed(42)8 unmodified linesdropout_rate=TEMPORAL_DROPOUT_RATE,)model = build_temporal_router_model(config).to(device)optimizer = torch.optim.AdamW(model.parameters(), lr=TEMPORAL_LEARNING_RATE, weight_decay=1e-4)loss_fn = nn.CrossEntropyLoss()model.train()last_loss = 0.013 unmodified lineslabels=ROUTER_LABELS,device=device,)validation = evaluation_to_dict(evaluate_router_predictions(list(valid_labels), valid_predictions))torch.save({2 unmodified lines"state_dict": model.cpu().state_dict(),"labels": list(ROUTER_LABELS),"input_size": int(tensors.shape[-1]),"feature_names": window_tensor_feature_names(),"feature_schema": FEATURE_SCHEMA,"landmark_schema": ROUTER_LANDMARK_SCHEMA,"hidden_size": TEMPORAL_HIDDEN_SIZE,"num_layers": TEMPORAL_NUM_LAYERS,"bidirectional": True,48 unmodified linesimport torchsys.path.insert(0, "/root/src")from pozify.ml.exercise_router_temporal import (TemporalRouterConfig,build_temporal_router_model,)checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)labels = tuple(str(label) for label in checkpoint["labels"])41 unmodified linesif baseline_path.exists():artifact = joblib.load(baseline_path)predictions = list(artifact["model"].predict(vectors))baseline_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))model_results["baseline"] = {"ok": True,"artifact": "baseline.joblib",10 unmodified linesif temporal_path.exists():predictions = _evaluate_temporal_checkpoint(temporal_path, tensors)temporal_evaluation = evaluation_to_dict(evaluate_router_predictions(labels, predictions))model_results["temporal"] = {"ok": True,"artifact": "temporal.pt",9 unmodified lines)if not candidates:result = {"ok": False,"error": "At least one trained router artifact is required",}_write_json(MODEL_ROOT / "evaluation.json", result)model_volume.commit()return result12 unmodified lines"selected_model": selection["selected_model"],"selected_artifact": selection["selected_artifact"],"models": model_results,**{key: selected[key]for key in ("accuracy","precision","recall","unknown_rejection_rate","confusion_matrix",)},}_write_json(MODEL_ROOT / "evaluation.json", result)model_volume.commit()return resultdef _upload_hf_file(api: Any,*,repo_id: str,local_path: Path,path_in_repo: str,) -> dict[str, Any]:if not local_path.exists():return {"path": str(local_path),"path_in_repo": path_in_repo,"uploaded": False,"reason": "missing",}api.upload_file(repo_id=repo_id,repo_type="model",path_or_fileobj=str(local_path),path_in_repo=path_in_repo,)return {"path": str(local_path),"path_in_repo": path_in_repo,"uploaded": True,}@app.function(volumes={str(MODEL_ROOT): model_volume},secrets=[modal.Secret.from_name("huggingface-secret")],timeout=20 * 60,)def publish_to_hf(repo_id: str | None = None,private: bool | None = None,) -> dict[str, Any]:from huggingface_hub import HfApirepo_id = repo_id or os.getenv(HF_REPO_ID_ENV) or DEFAULT_HF_REPO_IDprivate = _env_truthy(os.getenv(HF_PRIVATE_ENV)) if private is None else privateif not os.getenv("HF_TOKEN"):return {"ok": False,"error": "HF_TOKEN is required in the Modal environment or local .env","repo_id": repo_id,}api = HfApi()api.create_repo(repo_id=repo_id, repo_type="model", private=private, exist_ok=True)uploads = [_upload_hf_file(api,repo_id=repo_id,local_path=DOCS_ROOT / "huggingface-router-model-card.md",path_in_repo="README.md",),_upload_hf_file(api,repo_id=repo_id,local_path=DOCS_ROOT / "exercise-router-training-report.md",path_in_repo="training_report.md",),]uploads.extend(_upload_hf_file(api,repo_id=repo_id,local_path=MODEL_ROOT / filename,path_in_repo=filename,)for filename in HF_ARTIFACT_FILENAMES)result = {"ok": any(item["uploaded"] for item in uploads),"repo_id": repo_id,"private": private,"uploads": uploads,}_write_json(MODEL_ROOT / "hf_upload.json", result)model_volume.commit()return result@app.local_entrypoint()def main(stage: str = "evaluate",limit: int | None = None,epochs: int = 73,repo_id: str | None = None,private: bool | None = None,) -> None:if stage == "ingest":print(ingest.remote())elif stage == "features":11 unmodified linesprint(train_temporal.remote(epochs=epochs))elif stage == "evaluate":print(evaluate.remote())print(publish_to_hf.remote(repo_id=repo_id, private=private))elif stage == "publish":print(publish_to_hf.remote(repo_id=repo_id, private=private))elif stage == "all":print(ingest.remote())examples = load_feature_examples.remote(limit)rows = []for result in extract_example_features.map(examples, return_exceptions=True):rows.append({"ok": False, "error": repr(result)}if isinstance(result, Exception)else {"ok": True, **result})print(write_feature_manifest.remote(rows))print(train_baseline.remote())print(train_temporal.remote(epochs=epochs))print(evaluate.remote())print(publish_to_hf.remote(repo_id=repo_id, private=private))else:raise ValueError("stage must be one of: ingest, features, train-baseline, train-temporal, evaluate, publish, all")
12 unmodified lines13141516171812 unmodified lines"router.joblib","router_selection.json","temporal.pt",)12 unmodified lines1314151617181920212212 unmodified lines"router.joblib","router_selection.json","temporal.pt","evaluation.json","baseline_metrics.json","temporal_metrics.json","hf_upload.json",)
3 unmodified lines4567891057 unmodified lines686970717273747576777820 unmodified lines991001011021031041051061071081093 unmodified linesfrom typing import Any, Callable, Protocolfrom pozify.contracts import PoseFramefrom pozify.steps.rep_signals import angle_deg, average_axis, landmark_axisNumberGetter = Callable[[PoseFrame], float | None]57 unmodified linesdef width(frame: PoseFrame, left: str, right: str) -> float | None:left_x = landmark_axis(frame, left, "x")right_x = landmark_axis(frame, right, "x")if left_x is None or right_x is None:return Nonereturn abs(right_x - left_x)def mean_pair(20 unmodified linesdef torso_lean_deg(frame: PoseFrame, side: str) -> float | None:shoulder_x = landmark_axis(frame, f"{side}_shoulder", "x")shoulder_y = landmark_axis(frame, f"{side}_shoulder", "y")hip_x = landmark_axis(frame, f"{side}_hip", "x")hip_y = landmark_axis(frame, f"{side}_hip", "y")if None in {shoulder_x, shoulder_y, hip_x, hip_y}:return Nonehorizontal_offset = abs(float(shoulder_x) - float(hip_x))vertical_offset = abs(float(shoulder_y) - float(hip_y))if vertical_offset <= 1e-6:return None3 unmodified lines4567891057 unmodified lines6869707172737420 unmodified lines95969798991001011021031041051061071081091103 unmodified linesfrom typing import Any, Callable, Protocolfrom pozify.contracts import PoseFramefrom pozify.steps.rep_signals import angle_deg, average_axis, distance, landmark_axisNumberGetter = Callable[[PoseFrame], float | None]57 unmodified linesdef width(frame: PoseFrame, left: str, right: str) -> float | None:return distance(frame, left, right)def mean_pair(20 unmodified linesdef torso_lean_deg(frame: PoseFrame, side: str) -> float | None:shoulder_x = landmark_axis(frame, f"{side}_shoulder", "x")shoulder_y = landmark_axis(frame, f"{side}_shoulder", "y")shoulder_z = landmark_axis(frame, f"{side}_shoulder", "z")hip_x = landmark_axis(frame, f"{side}_hip", "x")hip_y = landmark_axis(frame, f"{side}_hip", "y")hip_z = landmark_axis(frame, f"{side}_hip", "z")if None in {shoulder_x, shoulder_y, shoulder_z, hip_x, hip_y, hip_z}:return Nonehorizontal_offset = ((float(shoulder_x) - float(hip_x)) ** 2+ (float(shoulder_z) - float(hip_z)) ** 2) ** 0.5vertical_offset = abs(float(shoulder_y) - float(hip_y))if vertical_offset <= 1e-6:return None
5 unmodified lines678910111264 unmodified lines77787980818283848537 unmodified lines1231241251261271281291301311321331341351361 unmodified line13813914014114214314411 unmodified lines1561571581591601611621631641651661676 unmodified lines17417517617717817918018118218318418583 unmodified lines2692702712725 unmodified linesimport numpy as npfrom pozify.contracts import PoseFrame, PoseSequencefrom pozify.steps.pose_backends.landmarks import LANDMARK_NAMESROUTER_LABELS = ("squat", "push_up", "shoulder_press", "unknown")64 unmodified linesfor landmark in LANDMARK_NAMES:base_names.extend([f"{landmark}_normalized_x",f"{landmark}_normalized_y",f"{landmark}_normalized_z",f"{landmark}_visibility",])37 unmodified linesdef _visibility(frame: PoseFrame, values: dict[str, float] | None) -> float:if values is not None and "visibility" in values:return max(0.0, min(1.0, float(values["visibility"])))return max(0.0, min(1.0, float(frame.pose_quality.get("mean_visibility", 0.0))))def _point(frame: PoseFrame, name: str) -> tuple[float, float] | None:values = frame.landmarks.get(name)if values is None:return Nonereturn _axis(values, "x"), _axis(values, "y")def _distance(frame: PoseFrame, first: str, second: str) -> float | None:1 unmodified linesecond_point = _point(frame, second)if first_point is None or second_point is None:return Nonereturn math.hypot(first_point[0] - second_point[0], first_point[1] - second_point[1])def _safe_ratio(numerator: float | None, denominator: float | None) -> float:11 unmodified linesabx = first_point[0] - middle_point[0]aby = first_point[1] - middle_point[1]cbx = last_point[0] - middle_point[0]cby = last_point[1] - middle_point[1]denom = math.hypot(abx, aby) * math.hypot(cbx, cby)if denom <= 1e-6:return 0.0cosine = max(-1.0, min(1.0, (abx * cbx + aby * cby) / denom))return math.degrees(math.acos(cosine))6 unmodified linesdef frame_feature_vector(frame: PoseFrame) -> np.ndarray:values: list[float] = []for landmark in LANDMARK_NAMES:landmark_values = frame.landmarks.get(landmark)values.extend([_axis(landmark_values, "x"),_axis(landmark_values, "y"),_axis(landmark_values, "z"),_visibility(frame, landmark_values),])83 unmodified lines))return windows5 unmodified lines678910111213141516171864 unmodified lines83848586878889909137 unmodified lines1291301311321331341351361371381391401411421431441 unmodified line14614714814915015115211 unmodified lines1641651661671681691701711721731741751761771781796 unmodified lines18618718818919019119219319419519619719883 unmodified lines2822832845 unmodified linesimport numpy as npfrom pozify.contracts import PoseFrame, PoseSequencefrom pozify.steps.pose_backends.landmarks import LANDMARK_NAMES, LANDMARK_SCHEMAfrom pozify.steps.rep_signals import landmark_axisFEATURE_SCHEMA = "coco17_3d_v1"ROUTER_LANDMARK_SCHEMA = LANDMARK_SCHEMAROUTER_INPUT_SIZE = 3 * (len(LANDMARK_NAMES) * 4 + 8 + 3)ROUTER_LABELS = ("squat", "push_up", "shoulder_press", "unknown")64 unmodified linesfor landmark in LANDMARK_NAMES:base_names.extend([f"{landmark}_pose3d_x",f"{landmark}_pose3d_y",f"{landmark}_pose3d_z",f"{landmark}_visibility",])37 unmodified linesdef _visibility(frame: PoseFrame, values: dict[str, float] | None) -> float:if values is not None and "visibility" in values:return max(0.0, min(1.0, float(values["visibility"])))return 0.0def _point(frame: PoseFrame, name: str) -> tuple[float, float, float] | None:x = landmark_axis(frame, name, "x")y = landmark_axis(frame, name, "y")z = landmark_axis(frame, name, "z")if None in {x, y, z}:return Nonereturn float(x), float(y), float(z)def _distance(frame: PoseFrame, first: str, second: str) -> float | None:1 unmodified linesecond_point = _point(frame, second)if first_point is None or second_point is None:return Nonereturn math.sqrt(sum((first_point[index] - second_point[index]) ** 2 for index in range(3)))def _safe_ratio(numerator: float | None, denominator: float | None) -> float:11 unmodified linesabx = first_point[0] - middle_point[0]aby = first_point[1] - middle_point[1]abz = first_point[2] - middle_point[2]cbx = last_point[0] - middle_point[0]cby = last_point[1] - middle_point[1]cbz = last_point[2] - middle_point[2]denom = math.sqrt(abx * abx + aby * aby + abz * abz) * math.sqrt(cbx * cbx + cby * cby + cbz * cbz)if denom <= 1e-6:return 0.0cosine = max(-1.0, min(1.0, (abx * cbx + aby * cby + abz * cbz) / denom))return math.degrees(math.acos(cosine))6 unmodified linesdef frame_feature_vector(frame: PoseFrame) -> np.ndarray:values: list[float] = []for landmark in LANDMARK_NAMES:landmark_values = frame.world_landmarks.get(landmark) or frame.landmarks.get(landmark)point = _point(frame, landmark)values.extend([point[0] if point is not None else 0.0,point[1] if point is not None else 0.0,point[2] if point is not None else 0.0,_visibility(frame, landmark_values),])83 unmodified lines))return windows
8 unmodified lines910111213141523 unmodified lines39404142434492 unmodified lines1371381391401411422 unmodified lines1451461471481491501511521531541551561574 unmodified lines1621631641651661675 unmodified lines1731741751761771781791801812 unmodified lines1841851861871881898 unmodified linesimport numpy as npfrom pozify.hf_spaces import router_torch_devicefrom pozify.ml.exercise_router_features import ROUTER_LABELS, RouterWindowfrom pozify.ml.exercise_router_temporal import TorchTemporalRouter23 unmodified lineslabels: tuple[str, ...] = ROUTER_LABELSscaler: Any | None = Nonemodel_kind: str = "baseline"@dataclass(frozen=True)92 unmodified linesmodel = artifact.get("model")if model is None:raise ValueError(f"Router artifact {path} is missing a 'model' entry")label_source = getattr(model, "classes_", None)if label_source is None:label_source = artifact.get("labels") or artifact.get("classes")2 unmodified linesmodel=model,labels=labels,scaler=artifact.get("scaler"),model_kind=str(artifact.get("model_kind", artifact.get("kind", "baseline"))),)return RouterModelBundle(model=artifact,labels=_labels_from_artifact(None, artifact),scaler=None,model_kind="baseline",)4 unmodified linesraise RuntimeError("torch is required to load temporal exercise router artifacts") from exccheckpoint = torch.load(path, map_location="cpu", weights_only=False)labels = _labels_from_artifact(checkpoint.get("labels"), checkpoint)model = TorchTemporalRouter(checkpoint=checkpoint,5 unmodified lineslabels=labels,scaler=None,model_kind=str(checkpoint.get("model_kind", "temporal")),)def predict_window_probabilities(bundle: RouterModelBundle,windows: list[RouterWindow],2 unmodified linesreturn []labels = _labels_from_artifact(bundle.labels, bundle.model)if bundle.model_kind == "temporal":inputs = np.stack([window.tensor for window in windows]).astype(np.float32)else:8 unmodified lines91011121314151617181920212223 unmodified lines464748495051525392 unmodified lines1461471481491501511521532 unmodified lines1561571581591601611621631641651661674 unmodified lines1721731741751761771785 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222 unmodified lines2252262272282292302312322332348 unmodified linesimport numpy as npfrom pozify.hf_spaces import router_torch_devicefrom pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LABELS,ROUTER_LANDMARK_SCHEMA,window_tensor_feature_names,window_vector_feature_names,RouterWindow,)from pozify.ml.exercise_router_temporal import TorchTemporalRouter23 unmodified lineslabels: tuple[str, ...] = ROUTER_LABELSscaler: Any | None = Nonemodel_kind: str = "baseline"feature_schema: str = FEATURE_SCHEMAlandmark_schema: str = ROUTER_LANDMARK_SCHEMA@dataclass(frozen=True)92 unmodified linesmodel = artifact.get("model")if model is None:raise ValueError(f"Router artifact {path} is missing a 'model' entry")model_kind = str(artifact.get("model_kind", artifact.get("kind", "baseline")))_validate_router_artifact_metadata(artifact, model_kind=model_kind, path=path)label_source = getattr(model, "classes_", None)if label_source is None:label_source = artifact.get("labels") or artifact.get("classes")2 unmodified linesmodel=model,labels=labels,scaler=artifact.get("scaler"),model_kind=model_kind,feature_schema=str(artifact.get("feature_schema", "")),landmark_schema=str(artifact.get("landmark_schema", "")),)raise ValueError(f"Router artifact {path} is missing required schema metadata for {FEATURE_SCHEMA}")4 unmodified linesraise RuntimeError("torch is required to load temporal exercise router artifacts") from exccheckpoint = torch.load(path, map_location="cpu", weights_only=False)_validate_router_artifact_metadata(checkpoint, model_kind="temporal", path=path)labels = _labels_from_artifact(checkpoint.get("labels"), checkpoint)model = TorchTemporalRouter(checkpoint=checkpoint,5 unmodified lineslabels=labels,scaler=None,model_kind=str(checkpoint.get("model_kind", "temporal")),feature_schema=str(checkpoint.get("feature_schema", "")),landmark_schema=str(checkpoint.get("landmark_schema", "")),)def _validate_router_artifact_metadata(artifact: dict[str, Any],*,model_kind: str,path: Path,) -> None:feature_schema = artifact.get("feature_schema")landmark_schema = artifact.get("landmark_schema")if feature_schema != FEATURE_SCHEMA or landmark_schema != ROUTER_LANDMARK_SCHEMA:raise ValueError(f"Router artifact {path} uses incompatible schema: "f"feature_schema={feature_schema!r}, landmark_schema={landmark_schema!r}")input_size = artifact.get("input_size")if input_size is None:returnexpected_size = (len(window_tensor_feature_names())if model_kind == "temporal"else len(window_vector_feature_names()))if int(input_size) != expected_size:raise ValueError(f"Router artifact {path} input_size={input_size} does not match {expected_size}")def predict_window_probabilities(bundle: RouterModelBundle,windows: list[RouterWindow],2 unmodified linesreturn []labels = _labels_from_artifact(bundle.labels, bundle.model)if bundle.feature_schema != FEATURE_SCHEMA or bundle.landmark_schema != ROUTER_LANDMARK_SCHEMA:raise ValueError("Router model schema does not match current pose feature schema")if bundle.model_kind == "temporal":inputs = np.stack([window.tensor for window in windows]).astype(np.float32)else:
12345672 unmodified lines101112131415from __future__ import annotationsfrom pozify.steps.pose_backends.base import PoseBackend, PoseDetectionfrom pozify.steps.pose_backends.landmarks import LANDMARK_NAMES, landmark_list_to_dict, landmark_to_dictfrom pozify.steps.pose_backends.mediapipe import MediaPipePoseBackendfrom pozify.steps.pose_backends.mmpose import MMPoseBackendfrom pozify.steps.pose_backends.mock import MockPoseBackend2 unmodified lines__all__ = ["LANDMARK_NAMES","MMPoseBackend","MediaPipePoseBackend","MockPoseBackend",1234567891011122 unmodified lines15161718192021from __future__ import annotationsfrom pozify.steps.pose_backends.base import PoseBackend, PoseDetectionfrom pozify.steps.pose_backends.landmarks import (LANDMARK_NAMES,LANDMARK_SCHEMA,landmark_list_to_dict,landmark_to_dict,)from pozify.steps.pose_backends.mediapipe import MediaPipePoseBackendfrom pozify.steps.pose_backends.mmpose import MMPoseBackendfrom pozify.steps.pose_backends.mock import MockPoseBackend2 unmodified lines__all__ = ["LANDMARK_NAMES","LANDMARK_SCHEMA","MMPoseBackend","MediaPipePoseBackend","MockPoseBackend",
2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414214 unmodified lines5758596061622 unmodified linesfrom typing import AnyLANDMARK_NAMES = ["nose","left_eye_inner","left_eye","left_eye_outer","right_eye_inner","right_eye","right_eye_outer","left_ear","right_ear","mouth_left","mouth_right","left_shoulder","right_shoulder","left_elbow","right_elbow","left_wrist","right_wrist","left_pinky","right_pinky","left_index","right_index","left_thumb","right_thumb","left_hip","right_hip","left_knee","right_knee","left_ankle","right_ankle","left_heel","right_heel","left_foot_index","right_foot_index",]14 unmodified linesif landmarks is None:return {}landmark_values = landmarks.landmark if hasattr(landmarks, "landmark") else landmarksreturn {name: landmark_to_dict(landmark)for name, landmark in zip(LANDMARK_NAMES, landmark_values, strict=False)2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474814 unmodified lines6364656667686970712 unmodified linesfrom typing import AnyLANDMARK_SCHEMA = "coco17"LANDMARK_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",]MEDIAPIPE_COCO17_INDICES = [0, # nose2, # left_eye5, # right_eye7, # left_ear8, # right_ear11, # left_shoulder12, # right_shoulder13, # left_elbow14, # right_elbow15, # left_wrist16, # right_wrist23, # left_hip24, # right_hip25, # left_knee26, # right_knee27, # left_ankle28, # right_ankle]14 unmodified linesif landmarks is None:return {}landmark_values = landmarks.landmark if hasattr(landmarks, "landmark") else landmarkslandmark_values = list(landmark_values)if len(landmark_values) >= 33:landmark_values = [landmark_values[index] for index in MEDIAPIPE_COCO17_INDICES]return {name: landmark_to_dict(landmark)for name, landmark in zip(LANDMARK_NAMES, landmark_values, strict=False)
13 unmodified lines14151617181920212223242552 unmodified lines78798081828384858687884 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417513 unmodified linesreturn {name: dict(values) for name, values in landmarks.items()}def _copy_frame(frame: PoseFrame, landmarks: dict[str, dict[str, float]] | None = None) -> PoseFrame:return PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=_copy_landmarks(landmarks if landmarks is not None else frame.landmarks),world_landmarks=_copy_landmarks(frame.world_landmarks),pose_quality=dict(frame.pose_quality),)52 unmodified linescleaned[next_index].landmarks,fraction,)cleaned[frame_index] = PoseFrame(frame_index=cleaned[frame_index].frame_index,timestamp_sec=cleaned[frame_index].timestamp_sec,landmarks=landmarks,world_landmarks=cleaned[frame_index].world_landmarks,pose_quality={**cleaned[frame_index].pose_quality,"interpolated": bool(landmarks),4 unmodified linesdef _add_smoothed_fields(frames: list[PoseFrame]) -> list[PoseFrame]:previous: dict[str, dict[str, float]] = {}smoothed_frames: list[PoseFrame] = []for frame in frames:landmarks = _copy_landmarks(frame.landmarks)for name, values in landmarks.items():previous_values = previous.get(name, {})current_smoothed: dict[str, float] = {}for field in SMOOTHED_FIELDS:if field not in values:continueprevious_value = previous_values.get(f"smoothed_{field}", values[field])smoothed = previous_value * (1.0 - SMOOTHING_ALPHA) + values[field] * SMOOTHING_ALPHAvalues[f"smoothed_{field}"] = round(smoothed, 6)current_smoothed[f"smoothed_{field}"] = values[f"smoothed_{field}"]previous[name] = current_smoothedsmoothed_frames.append(PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=landmarks,world_landmarks=frame.world_landmarks,pose_quality=frame.pose_quality,))return smoothed_framesdef _normalization_origin_and_scale(landmarks: dict[str, dict[str, float]],) -> tuple[float, float, float, bool]:required = ("left_hip", "right_hip", "left_shoulder", "right_shoulder")if not all(name in landmarks for name in required):return 0.0, 0.0, 1.0, Falseleft_hip = landmarks["left_hip"]right_hip = landmarks["right_hip"]1 unmodified lineright_shoulder = landmarks["right_shoulder"]origin_x = (left_hip["x"] + right_hip["x"]) / 2.0origin_y = (left_hip["y"] + right_hip["y"]) / 2.0mid_shoulder_x = (left_shoulder["x"] + right_shoulder["x"]) / 2.0mid_shoulder_y = (left_shoulder["y"] + right_shoulder["y"]) / 2.0torso_length = ((mid_shoulder_x - origin_x) ** 2 + (mid_shoulder_y - origin_y) ** 2) ** 0.5if torso_length <= 1e-6:return origin_x, origin_y, 1.0, Falsereturn origin_x, origin_y, torso_length, Truedef _add_normalized_fields(frames: list[PoseFrame]) -> list[PoseFrame]:normalized_frames: list[PoseFrame] = []for frame in frames:landmarks = _copy_landmarks(frame.landmarks)origin_x, origin_y, scale, normalized = _normalization_origin_and_scale(landmarks)for values in landmarks.values():source_x = values.get("smoothed_x", values.get("x"))source_y = values.get("smoothed_y", values.get("y"))source_z = values.get("smoothed_z", values.get("z"))if source_x is None or source_y is None or source_z is None:continuevalues["normalized_x"] = round((source_x - origin_x) / scale, 6)values["normalized_y"] = round((source_y - origin_y) / scale, 6)values["normalized_z"] = round(source_z / scale, 6)normalized_frames.append(PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=landmarks,world_landmarks=frame.world_landmarks,pose_quality={**frame.pose_quality,"cleaned": True,"normalized": normalized,"normalization_origin": "mid_hip","normalization_scale": "mid_shoulder_to_mid_hip",},))13 unmodified lines14151617181920212223242526272829303152 unmodified lines848586878889909192939495969798994 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541 unmodified line15615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723813 unmodified linesreturn {name: dict(values) for name, values in landmarks.items()}def _copy_frame(frame: PoseFrame,landmarks: dict[str, dict[str, float]] | None = None,world_landmarks: dict[str, dict[str, float]] | None = None,) -> PoseFrame:return PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=_copy_landmarks(landmarks if landmarks is not None else frame.landmarks),world_landmarks=_copy_landmarks(world_landmarks if world_landmarks is not None else frame.world_landmarks),pose_quality=dict(frame.pose_quality),)52 unmodified linescleaned[next_index].landmarks,fraction,)world_landmarks = _interpolate_landmarks(cleaned[previous_index].world_landmarks,cleaned[next_index].world_landmarks,fraction,)cleaned[frame_index] = PoseFrame(frame_index=cleaned[frame_index].frame_index,timestamp_sec=cleaned[frame_index].timestamp_sec,landmarks=landmarks,world_landmarks=world_landmarks,pose_quality={**cleaned[frame_index].pose_quality,"interpolated": bool(landmarks),4 unmodified linesdef _add_smoothed_fields(frames: list[PoseFrame]) -> list[PoseFrame]:previous_landmarks: dict[str, dict[str, float]] = {}previous_world_landmarks: dict[str, dict[str, float]] = {}smoothed_frames: list[PoseFrame] = []for frame in frames:landmarks = _copy_landmarks(frame.landmarks)world_landmarks = _copy_landmarks(frame.world_landmarks)_smooth_landmarks(landmarks, previous_landmarks)_smooth_landmarks(world_landmarks, previous_world_landmarks)smoothed_frames.append(PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=landmarks,world_landmarks=world_landmarks,pose_quality=frame.pose_quality,))return smoothed_framesdef _smooth_landmarks(landmarks: dict[str, dict[str, float]],previous: dict[str, dict[str, float]],) -> None:for name, values in landmarks.items():previous_values = previous.get(name, {})current_smoothed: dict[str, float] = {}for field in SMOOTHED_FIELDS:if field not in values:continueprevious_value = previous_values.get(f"smoothed_{field}", values[field])smoothed = previous_value * (1.0 - SMOOTHING_ALPHA) + values[field] * SMOOTHING_ALPHAvalues[f"smoothed_{field}"] = round(smoothed, 6)current_smoothed[f"smoothed_{field}"] = values[f"smoothed_{field}"]previous[name] = current_smootheddef _normalization_origin_and_scale(landmarks: dict[str, dict[str, float]],) -> tuple[float, float, float, float, bool]:required = ("left_hip", "right_hip", "left_shoulder", "right_shoulder")if not all(name in landmarks for name in required):return 0.0, 0.0, 0.0, 1.0, Falseleft_hip = landmarks["left_hip"]right_hip = landmarks["right_hip"]1 unmodified lineright_shoulder = landmarks["right_shoulder"]origin_x = (left_hip["x"] + right_hip["x"]) / 2.0origin_y = (left_hip["y"] + right_hip["y"]) / 2.0origin_z = (left_hip.get("z", 0.0) + right_hip.get("z", 0.0)) / 2.0mid_shoulder_x = (left_shoulder["x"] + right_shoulder["x"]) / 2.0mid_shoulder_y = (left_shoulder["y"] + right_shoulder["y"]) / 2.0mid_shoulder_z = (left_shoulder.get("z", 0.0) + right_shoulder.get("z", 0.0)) / 2.0torso_length = ((mid_shoulder_x - origin_x) ** 2+ (mid_shoulder_y - origin_y) ** 2+ (mid_shoulder_z - origin_z) ** 2) ** 0.5if torso_length <= 1e-6:return origin_x, origin_y, origin_z, 1.0, Falsereturn origin_x, origin_y, origin_z, torso_length, Truedef _vertical_sign(frames: list[PoseFrame], *, use_world_landmarks: bool) -> float:for frame in frames:landmarks = frame.world_landmarks if use_world_landmarks else frame.landmarksrequired = ("left_hip", "right_hip", "left_shoulder", "right_shoulder")if not all(name in landmarks for name in required):continueorigin_y = (landmarks["left_hip"]["y"] + landmarks["right_hip"]["y"]) / 2.0shoulder_y = (landmarks["left_shoulder"]["y"] + landmarks["right_shoulder"]["y"]) / 2.0return -1.0 if shoulder_y > origin_y else 1.0return 1.0def _add_normalized_landmarks(landmarks: dict[str, dict[str, float]],*,vertical_sign: float,) -> tuple[dict[str, dict[str, float]], bool]:normalized_landmarks = _copy_landmarks(landmarks)origin_x, origin_y, origin_z, scale, normalized = _normalization_origin_and_scale(normalized_landmarks)for values in normalized_landmarks.values():source_x = values.get("smoothed_x", values.get("x"))source_y = values.get("smoothed_y", values.get("y"))source_z = values.get("smoothed_z", values.get("z"))if source_x is None or source_y is None or source_z is None:continuevalues["normalized_x"] = round((source_x - origin_x) / scale, 6)values["normalized_y"] = round(((source_y - origin_y) * vertical_sign) / scale, 6)values["normalized_z"] = round((source_z - origin_z) / scale, 6)return normalized_landmarks, normalizeddef _add_normalized_fields(frames: list[PoseFrame]) -> list[PoseFrame]:normalized_frames: list[PoseFrame] = []landmark_vertical_sign = _vertical_sign(frames, use_world_landmarks=False)world_vertical_sign = _vertical_sign(frames, use_world_landmarks=True)for frame in frames:landmarks, landmarks_normalized = _add_normalized_landmarks(frame.landmarks,vertical_sign=landmark_vertical_sign,)world_landmarks, world_normalized = _add_normalized_landmarks(frame.world_landmarks,vertical_sign=world_vertical_sign,)normalized = world_normalized if world_landmarks else landmarks_normalizednormalized_frames.append(PoseFrame(frame_index=frame.frame_index,timestamp_sec=frame.timestamp_sec,landmarks=landmarks,world_landmarks=world_landmarks,pose_quality={**frame.pose_quality,"cleaned": True,"normalized": normalized,"normalization_origin": "mid_hip","normalization_scale": "mid_shoulder_to_mid_hip","world_landmarks_normalized": world_normalized,},))
7 unmodified lines891011121390 unmodified lines10410510610710810924 unmodified lines13413513613713813926 unmodified lines1661671681691701717 unmodified linesfrom pozify.contracts import PoseFrame, PoseSequence, VideoManifestfrom pozify.steps.pose_backends import (MockPoseBackend,PoseBackend,create_pose_backend,90 unmodified lines}def _empty_sequence() -> PoseSequence:return PoseSequence(frames=[], normalized=False, smoothing_method="none", pose_valid_ratio=0.024 unmodified linespose_quality={**_pose_quality(detection.landmarks),"source": detection.source,},))26 unmodified lines**_pose_quality(detection.landmarks),"source": detection.source,"mock": True,},))7 unmodified lines89101112131490 unmodified lines10510610710810911011111211311411511611711824 unmodified lines14314414514614714814915015115226 unmodified lines1791801811821831841851867 unmodified linesfrom pozify.contracts import PoseFrame, PoseSequence, VideoManifestfrom pozify.steps.pose_backends import (LANDMARK_SCHEMA,MockPoseBackend,PoseBackend,create_pose_backend,90 unmodified lines}def _coordinate_source(detection_source: str, world_landmarks: dict[str, dict[str, float]]) -> str:if not world_landmarks:return "image_landmarks"if detection_source.startswith("mediapipe"):return "mediapipe_world_landmarks"return "world_landmarks"def _empty_sequence() -> PoseSequence:return PoseSequence(frames=[], normalized=False, smoothing_method="none", pose_valid_ratio=0.024 unmodified linespose_quality={**_pose_quality(detection.landmarks),"source": detection.source,"landmark_schema": LANDMARK_SCHEMA,"coordinate_source": _coordinate_source(detection.source, detection.world_landmarks),},))26 unmodified lines**_pose_quality(detection.landmarks),"source": detection.source,"mock": True,"landmark_schema": LANDMARK_SCHEMA,"coordinate_source": "mock_landmarks",},))
13 unmodified lines14151617181920212223242526277 unmodified lines3536373839404142434445464748495051525354555657585960616263646513 unmodified linesdef _landmark_values(frame: PoseFrame, name: str) -> dict[str, float] | None:return frame.landmarks.get(name)def landmark_axis(frame: PoseFrame, name: str, axis: str) -> float | None:values = _landmark_values(frame, name)if values is None:return Nonereturn values.get(f"smoothed_{axis}", values.get(axis))def average_axis(frame: PoseFrame, names: tuple[str, ...], axis: str) -> float | None:7 unmodified linesdef angle_deg(frame: PoseFrame, first: str, middle: str, last: str) -> float | None:ax = landmark_axis(frame, first, "x")ay = landmark_axis(frame, first, "y")bx = landmark_axis(frame, middle, "x")by = landmark_axis(frame, middle, "y")cx = landmark_axis(frame, last, "x")cy = landmark_axis(frame, last, "y")if None in {ax, ay, bx, by, cx, cy}:return Noneabx = ax - bxaby = ay - bycbx = cx - bxcby = cy - bydenom = math.hypot(abx, aby) * math.hypot(cbx, cby)if denom <= 1e-6:return Nonecosine = max(-1.0, min(1.0, (abx * cbx + aby * cby) / denom))return math.degrees(math.acos(cosine))def body_line_score(frame: PoseFrame) -> float | None:shoulder_y = average_axis(frame, ("left_shoulder", "right_shoulder"), "y")hip_y = average_axis(frame, ("left_hip", "right_hip"), "y")ankle_y = average_axis(frame, ("left_ankle", "right_ankle"), "y")if None in {shoulder_y, hip_y, ankle_y}:return Nonereturn 1.0 - abs((shoulder_y + ankle_y) / 2.0 - hip_y)def smooth_signal(values: list[float | None], window_radius: int = 2) -> list[float | None]:13 unmodified lines1415161718192021222324252627282930317 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610713 unmodified linesdef _landmark_values(frame: PoseFrame, name: str) -> dict[str, float] | None:return frame.world_landmarks.get(name) or frame.landmarks.get(name)def landmark_axis(frame: PoseFrame, name: str, axis: str) -> float | None:values = _landmark_values(frame, name)if values is None:return Nonefallback = 0.0 if axis == "z" else Nonereturn values.get(f"normalized_{axis}",values.get(f"smoothed_{axis}", values.get(axis, fallback)),)def average_axis(frame: PoseFrame, names: tuple[str, ...], axis: str) -> float | None:7 unmodified linesdef angle_deg(frame: PoseFrame, first: str, middle: str, last: str) -> float | None:ax = landmark_axis(frame, first, "x")ay = landmark_axis(frame, first, "y")az = landmark_axis(frame, first, "z")bx = landmark_axis(frame, middle, "x")by = landmark_axis(frame, middle, "y")bz = landmark_axis(frame, middle, "z")cx = landmark_axis(frame, last, "x")cy = landmark_axis(frame, last, "y")cz = landmark_axis(frame, last, "z")if None in {ax, ay, az, bx, by, bz, cx, cy, cz}:return Noneabx = ax - bxaby = ay - byabz = az - bzcbx = cx - bxcby = cy - bycbz = cz - bzab_length = math.sqrt(abx * abx + aby * aby + abz * abz)cb_length = math.sqrt(cbx * cbx + cby * cby + cbz * cbz)denom = ab_length * cb_lengthif denom <= 1e-6:return Nonecosine = max(-1.0, min(1.0, (abx * cbx + aby * cby + abz * cbz) / denom))return math.degrees(math.acos(cosine))def body_line_score(frame: PoseFrame) -> float | None:shoulder = average_point(frame, ("left_shoulder", "right_shoulder"))hip = average_point(frame, ("left_hip", "right_hip"))ankle = average_point(frame, ("left_ankle", "right_ankle"))if shoulder is None or hip is None or ankle is None:return Nonemidline = tuple((shoulder[index] + ankle[index]) / 2.0 for index in range(3))deviation = math.sqrt(sum((midline[index] - hip[index]) ** 2 for index in range(3)))return 1.0 - deviationdef average_point(frame: PoseFrame, names: tuple[str, ...]) -> tuple[float, float, float] | None:points: list[tuple[float, float, float]] = []for name in names:x = landmark_axis(frame, name, "x")y = landmark_axis(frame, name, "y")z = landmark_axis(frame, name, "z")if None in {x, y, z}:continuepoints.append((float(x), float(y), float(z)))if not points:return Nonecount = len(points)return (sum(point[0] for point in points) / count,sum(point[1] for point in points) / count,sum(point[2] for point in points) / count,)def distance(frame: PoseFrame, first: str, second: str) -> float | None:first_point = average_point(frame, (first,))second_point = average_point(frame, (second,))if first_point is None or second_point is None:return Nonereturn math.sqrt(sum((first_point[index] - second_point[index]) ** 2 for index in range(3)))def smooth_signal(values: list[float | None], window_radius: int = 2) -> list[float | None]:
16 unmodified lines17181920212223118 unmodified lines14214314414514614716 unmodified lines16416516616716816930 unmodified lines20020120220320420520620720820921021121221319 unmodified lines23323423523623723823924024124224324424524620 unmodified lines26726826927027127227327427527627727827928018 unmodified lines29930030130230330416 unmodified linesfrom pozify.contracts import PoseFrame, PoseSequence, UserProfile, validate_contractfrom pozify.ml.exercise_router_evaluation import evaluate_router_predictions, select_router_candidatefrom pozify.ml.exercise_router_features import (ROUTER_LABELS,extract_router_windows,window_tensor_feature_names,window_vector_feature_names,118 unmodified linesreturn np.tile(np.asarray([[0.03, 0.91, 0.02, 0.04]]), (values.shape[0], 1))class ExerciseRouterFeatureTests(unittest.TestCase):def test_extracts_windows_for_supported_exercise_motion(self) -> None:for exercise in ("squat", "push_up", "shoulder_press"):16 unmodified linesself.assertEqual(extract_router_windows(empty), [])self.assertEqual(extract_router_windows(_sequence(visibility=0.05)), [])class ExerciseRouterAggregationTests(unittest.TestCase):def test_aggregates_confident_windows(self) -> None:30 unmodified lineswith tempfile.TemporaryDirectory() as temp_dir:model_dir = Path(temp_dir)artifact_path = model_dir / "selected.joblib"joblib.dump({"model": _FakePushUpModel(),"labels": ["unknown", "squat", "push_up", "shoulder_press"],"model_kind": "baseline",},artifact_path,)(model_dir / "router_selection.json").write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",19 unmodified linesmodel_dir = Path(temp_dir)artifact_path = model_dir / "router.joblib"selection_path = model_dir / "router_selection.json"joblib.dump({"model": _FakePushUpModel(),"labels": list(ROUTER_LABELS),"model_kind": "baseline",},artifact_path,)selection_path.write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",20 unmodified linesmodel_dir = Path(temp_dir)artifact_path = model_dir / "router.joblib"selection_path = model_dir / "router_selection.json"joblib.dump({"model": _FakePushUpModel(),"labels": list(ROUTER_LABELS),"model_kind": "baseline",},artifact_path,)selection_path.write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",18 unmodified linesself.assertEqual(bundle.model_kind, "baseline")self.assertEqual(bundle.labels, tuple(ROUTER_LABELS))class ExerciseClassifierStepTests(unittest.TestCase):def test_manual_override_bypasses_model_and_validates_contract(self) -> None:16 unmodified lines171819202122232425118 unmodified lines14414514614714814915015115215315415515615715815916016 unmodified lines17717817918018118218318418518618718818919019119219330 unmodified lines22422522622722822923019 unmodified lines25025125225325425525620 unmodified lines27727827928028128228318 unmodified lines30230330430530630730830931031131231331431531631731831932032132232316 unmodified linesfrom pozify.contracts import PoseFrame, PoseSequence, UserProfile, validate_contractfrom pozify.ml.exercise_router_evaluation import evaluate_router_predictions, select_router_candidatefrom pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LABELS,ROUTER_LANDMARK_SCHEMA,extract_router_windows,window_tensor_feature_names,window_vector_feature_names,118 unmodified linesreturn np.tile(np.asarray([[0.03, 0.91, 0.02, 0.04]]), (values.shape[0], 1))def _fake_router_artifact() -> dict[str, object]:return {"model": _FakePushUpModel(),"labels": list(ROUTER_LABELS),"model_kind": "baseline","feature_schema": FEATURE_SCHEMA,"landmark_schema": ROUTER_LANDMARK_SCHEMA,"input_size": len(window_vector_feature_names()),}class ExerciseRouterFeatureTests(unittest.TestCase):def test_extracts_windows_for_supported_exercise_motion(self) -> None:for exercise in ("squat", "push_up", "shoulder_press"):16 unmodified linesself.assertEqual(extract_router_windows(empty), [])self.assertEqual(extract_router_windows(_sequence(visibility=0.05)), [])def test_missing_landmark_visibility_is_zero(self) -> None:sequence = _sequence("push_up")frame = sequence.frames[0]frame.landmarks.pop("nose")windows = extract_router_windows(sequence, min_mean_visibility=0.0)self.assertGreater(len(windows), 0)nose_visibility_index = window_tensor_feature_names().index("nose_visibility")self.assertEqual(windows[0].tensor[0, nose_visibility_index], 0.0)class ExerciseRouterAggregationTests(unittest.TestCase):def test_aggregates_confident_windows(self) -> None:30 unmodified lineswith tempfile.TemporaryDirectory() as temp_dir:model_dir = Path(temp_dir)artifact_path = model_dir / "selected.joblib"joblib.dump(_fake_router_artifact(), artifact_path)(model_dir / "router_selection.json").write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",19 unmodified linesmodel_dir = Path(temp_dir)artifact_path = model_dir / "router.joblib"selection_path = model_dir / "router_selection.json"joblib.dump(_fake_router_artifact(), artifact_path)selection_path.write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",20 unmodified linesmodel_dir = Path(temp_dir)artifact_path = model_dir / "router.joblib"selection_path = model_dir / "router_selection.json"joblib.dump(_fake_router_artifact(), artifact_path)selection_path.write_text(json.dumps({"selected_artifact": artifact_path.name}),encoding="utf-8",18 unmodified linesself.assertEqual(bundle.model_kind, "baseline")self.assertEqual(bundle.labels, tuple(ROUTER_LABELS))def test_old_router_artifact_without_schema_is_rejected(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:model_dir = Path(temp_dir)joblib.dump({"model": _FakePushUpModel(),"labels": list(ROUTER_LABELS),"model_kind": "baseline",},model_dir / "router.joblib",)with patch.dict(os.environ, {HF_DISABLE_ENV: "1"}):with self.assertRaises(ValueError):load_router_model(model_dir)class ExerciseClassifierStepTests(unittest.TestCase):def test_manual_override_bypasses_model_and_validates_contract(self) -> None:
80 unmodified lines8182838485868713 unmodified lines10110210310410510610710810911073 unmodified lines18418518618718818919019119211 unmodified lines20420520620720820912 unmodified lines22222322422522622722880 unmodified lineswriter.release()return pathdef test_pose_landmarker_keeps_all_33_landmarks_and_quality(self) -> None:path = self._write_video()manifest = VideoManifest(video_path=str(path),13 unmodified linessequence = pose_landmarker.run(manifest, backend=_FakePose())self.assertEqual(len(sequence.frames), 4)self.assertEqual(len(sequence.frames[0].landmarks), 33)self.assertIn("left_foot_index", sequence.frames[0].landmarks)self.assertEqual(len(sequence.frames[0].world_landmarks), 33)self.assertEqual(sequence.frames[0].pose_quality["source"], "fake_pose")self.assertGreater(sequence.frames[0].pose_quality["mean_visibility"], 0.9)self.assertTrue(sequence.frames[0].pose_quality["critical_landmarks_visible"])self.assertEqual(sequence.pose_valid_ratio, 1.0)73 unmodified lineslast = landmark_list_to_dict(last_landmarks)sequence = PoseSequence(frames=[PoseFrame(0, 0.0, first, {}, {"mean_visibility": 0.9}),PoseFrame(1, 0.033, {}, {}, {"mean_visibility": 0.0}),PoseFrame(2, 0.067, last, {}, {"mean_visibility": 0.9}),],normalized=False,smoothing_method="none",11 unmodified linesself.assertIn("smoothed_x", shoulder)self.assertIn("normalized_x", shoulder)self.assertTrue(cleaned.frames[1].pose_quality["normalized"])@unittest.skipUnless(os.getenv("POZIFY_RUN_REAL_POSE_TESTS") == "1",12 unmodified linesself.assertTrue(manifest.analysis_allowed)self.assertGreater(len(sequence.frames), 0)self.assertGreater(sequence.pose_valid_ratio, 0.0)self.assertEqual(len(sequence.frames[0].landmarks), 33)self.assertEqual(sequence.frames[0].pose_quality["source"], "mediapipe_pose")self.assertTrue(cleaned.normalized)80 unmodified lines8182838485868713 unmodified lines10110210310410510610710810911011111273 unmodified lines18618718818919019119219319411 unmodified lines20620720820921021121221312 unmodified lines22622722822923023123280 unmodified lineswriter.release()return pathdef test_pose_landmarker_maps_to_coco17_landmarks_and_quality(self) -> None:path = self._write_video()manifest = VideoManifest(video_path=str(path),13 unmodified linessequence = pose_landmarker.run(manifest, backend=_FakePose())self.assertEqual(len(sequence.frames), 4)self.assertEqual(len(sequence.frames[0].landmarks), 17)self.assertIn("left_ankle", sequence.frames[0].landmarks)self.assertNotIn("left_foot_index", sequence.frames[0].landmarks)self.assertEqual(len(sequence.frames[0].world_landmarks), 17)self.assertEqual(sequence.frames[0].pose_quality["source"], "fake_pose")self.assertEqual(sequence.frames[0].pose_quality["landmark_schema"], "coco17")self.assertGreater(sequence.frames[0].pose_quality["mean_visibility"], 0.9)self.assertTrue(sequence.frames[0].pose_quality["critical_landmarks_visible"])self.assertEqual(sequence.pose_valid_ratio, 1.0)73 unmodified lineslast = landmark_list_to_dict(last_landmarks)sequence = PoseSequence(frames=[PoseFrame(0, 0.0, first, first, {"mean_visibility": 0.9}),PoseFrame(1, 0.033, {}, {}, {"mean_visibility": 0.0}),PoseFrame(2, 0.067, last, last, {"mean_visibility": 0.9}),],normalized=False,smoothing_method="none",11 unmodified linesself.assertIn("smoothed_x", shoulder)self.assertIn("normalized_x", shoulder)self.assertTrue(cleaned.frames[1].pose_quality["normalized"])self.assertIn("smoothed_x", cleaned.frames[1].world_landmarks["left_shoulder"])self.assertIn("normalized_z", cleaned.frames[1].world_landmarks["left_shoulder"])@unittest.skipUnless(os.getenv("POZIFY_RUN_REAL_POSE_TESTS") == "1",12 unmodified linesself.assertTrue(manifest.analysis_allowed)self.assertGreater(len(sequence.frames), 0)self.assertGreater(sequence.pose_valid_ratio, 0.0)self.assertEqual(len(sequence.frames[0].landmarks), 17)self.assertEqual(sequence.frames[0].pose_quality["source"], "mediapipe_pose")self.assertTrue(cleaned.normalized)
11 unmodified lines121314151617127 unmodified lines14514614714814915011 unmodified linesfrom pozify.exercises.push_up import PushUpExercisefrom pozify.exercises.shoulder_press import ShoulderPressExercisefrom pozify.exercises.squat import SquatExercisedef _frame(frame_index: int, landmarks: dict[str, dict[str, float]]) -> PoseFrame:127 unmodified linesclass RepCounterTests(unittest.TestCase):def test_segments_squat_reps(self) -> None:sequence = _sequence_for_exercise("squat", 3)reps, debug = _exercise_strategy("squat", sequence).count()11 unmodified lines12131415161718127 unmodified lines14614714814915015115215315415515615715815916016116216316416516611 unmodified linesfrom pozify.exercises.push_up import PushUpExercisefrom pozify.exercises.shoulder_press import ShoulderPressExercisefrom pozify.exercises.squat import SquatExercisefrom pozify.steps.rep_signals import angle_degdef _frame(frame_index: int, landmarks: dict[str, dict[str, float]]) -> PoseFrame:127 unmodified linesclass RepCounterTests(unittest.TestCase):def test_angle_deg_uses_3d_world_landmarks(self) -> None:frame = PoseFrame(frame_index=0,timestamp_sec=0.0,landmarks={},world_landmarks={"left_shoulder": {"x": 1.0, "y": 0.0, "z": 0.0},"left_elbow": {"x": 0.0, "y": 0.0, "z": 0.0},"left_wrist": {"x": 0.0, "y": 0.0, "z": 1.0},},pose_quality={"mean_visibility": 1.0},)self.assertEqual(round(angle_deg(frame, "left_shoulder", "left_elbow", "left_wrist") or 0.0), 90)def test_segments_squat_reps(self) -> None:sequence = _sequence_for_exercise("squat", 3)reps, debug = _exercise_strategy("squat", sequence).count()
911 unmodified lines912913914915916917918911 unmodified linesh("div",{ className: "metric" },h("strong", null, "33"),h("span", null, "pose landmarks"),),h(911 unmodified lines912913914915916917918911 unmodified linesh("div",{ className: "metric" },h("strong", null, "17"),h("span", null, "pose landmarks"),),h(
README.md+11-2
docs/huggingface-router-release.md+14
docs/implementation-plan.md+1-1
docs/pozify-project-documentation.md+9-9
scripts/exercise_router_modal.py+276-31
scripts/upload_exercise_router_to_hf.py+4
src/pozify/exercises/shared/analyzer.py+9-8
src/pozify/ml/exercise_router_features.py+29-17
src/pozify/ml/exercise_router_inference.py+52-7
src/pozify/steps/pose_backends/__init__.py+7-1
src/pozify/steps/pose_backends/landmarks.py+25-16
src/pozify/steps/pose_cleaning.py+96-33
src/pozify/steps/pose_landmarker.py+15
src/pozify/steps/rep_signals.py+52-10
tests/test_exercise_classifier.py+43-24
tests/test_pose_steps.py+11-7
tests/test_rep_counter.py+16
web/app.js+1-1