refactor: remove sample_pose_cache module and streamline pose processing in pipeline
Browse filesFiles changed (12)
- .gitignore+3-1
- src/pozify/ml/exercise_router_inference.py+12-10
- src/pozify/pipeline.py+4-14
- src/pozify/sample_pose_cache.pyDeleted-229
- src/pozify/steps/exercise_classifier.py+199-3
- src/pozify/steps/pose_landmarker.py+11-27
- src/pozify/steps/video_qc.py+9-6
- tests/test_exercise_classifier.py+160-18
- tests/test_pipeline_contracts.py+10-110
- tests/test_pose_steps.py+6-7
- tests/test_sample_pose_cache.pyDeleted-128
- tests/test_video_qc.py+14
5 unmodified lines67895 unmodified linesruns/models/.envtests/fixtures5 unmodified lines678910115 unmodified linesruns/models/.envtests/fixtures.DS_Store
7 unmodified lines891011121378 unmodified lines929394959697128 unmodified lines22622722822923023123223323426 unmodified lines26126226326426526626724 unmodified lines29229329429529629729829930039 unmodified lines3403413423433443453461 unmodified line34834935035135235335418 unmodified lines3733743753763773783797 unmodified linesimport numpy as npfrom pozify.hf_spaces import router_torch_devicefrom pozify.ml.exercise_router_features import (FEATURE_SCHEMA,78 unmodified linesrepo_id: str | None = None,revision: str | None = None,) -> RouterModelBundle | None:if _env_truthy(os.getenv(HF_DISABLE_ENV)):return None128 unmodified lineslabels = _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:26 unmodified linesend_sec=window.end_sec,label=label,confidence=round(confidence, 4),scores={key: round(max(0.0, min(1.0, scores.get(key, 0.0))), 6) for key in ROUTER_LABELS},))return predictions24 unmodified lineswinning_agreement = (sum(1 for prediction in predictions if prediction.label == winning_label) / window_count)winning_confidences = [prediction.scores.get(winning_label, 0.0) for prediction in predictions]confidence = min(winning_score, sum(winning_confidences) / len(winning_confidences))score_margin = winning_score - second_scorefallback_required = (39 unmodified linesif not selection_path.exists():return Noneselection = json.loads(selection_path.read_text(encoding="utf-8"))selected_artifact = selection.get("selected_artifact")if not isinstance(selected_artifact, str) or not selected_artifact:return Nonereturn model_dir / selected_artifact1 unmodified linedef _selected_artifact_name(selection_path: Path) -> str | None:selection = json.loads(selection_path.read_text(encoding="utf-8"))selected_artifact = selection.get("selected_artifact")if not isinstance(selected_artifact, str) or not selected_artifact:return Nonereturn selected_artifact18 unmodified linestry:from huggingface_hub import hf_hub_downloadexcept ImportError as exc: # pragma: no cover - dependency is declaredraise RuntimeError("huggingface_hub is required to load router artifacts from the Hub") from excreturn Path(hf_hub_download(7 unmodified lines89101112131478 unmodified lines93949596979899128 unmodified lines22822923023123223323426 unmodified lines26126226326426526626726826924 unmodified lines29429529629729829930039 unmodified lines3403413423433443453461 unmodified line34834935035135235335418 unmodified lines3733743753763773783793803817 unmodified linesimport numpy as npfrom pozify.env import load_local_envfrom pozify.hf_spaces import router_torch_devicefrom pozify.ml.exercise_router_features import (FEATURE_SCHEMA,78 unmodified linesrepo_id: str | None = None,revision: str | None = None,) -> RouterModelBundle | None:load_local_env()if _env_truthy(os.getenv(HF_DISABLE_ENV)):return None128 unmodified lineslabels = _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:26 unmodified linesend_sec=window.end_sec,label=label,confidence=round(confidence, 4),scores={key: round(max(0.0, min(1.0, scores.get(key, 0.0))), 6) for key in ROUTER_LABELS},))return predictions24 unmodified lineswinning_agreement = (sum(1 for prediction in predictions if prediction.label == winning_label) / window_count)winning_confidences = [prediction.scores.get(winning_label, 0.0) for prediction in predictions]confidence = min(winning_score, sum(winning_confidences) / len(winning_confidences))score_margin = winning_score - second_scorefallback_required = (39 unmodified linesif not selection_path.exists():return Noneselection = json.loads(selection_path.read_text(encoding="utf-8"))selected_artifact = selection.get("selected_artifact") or selection.get("selected_model")if not isinstance(selected_artifact, str) or not selected_artifact:return Nonereturn model_dir / selected_artifact1 unmodified linedef _selected_artifact_name(selection_path: Path) -> str | None:selection = json.loads(selection_path.read_text(encoding="utf-8"))selected_artifact = selection.get("selected_artifact") or selection.get("selected_model")if not isinstance(selected_artifact, str) or not selected_artifact:return Nonereturn selected_artifact18 unmodified linestry:from huggingface_hub import hf_hub_downloadexcept ImportError as exc: # pragma: no cover - dependency is declaredraise RuntimeError("huggingface_hub is required to load router artifacts from the Hub") from excreturn Path(hf_hub_download(
5 unmodified lines678910111255 unmodified lines68697071727374757654 unmodified lines1311321331341351361371381391401411427 unmodified lines1501511521531541551561571581591601611625 unmodified linesfrom typing import Any, Callablefrom uuid import uuid4from pozify import sample_pose_cachefrom pozify.artifacts import write_jsonfrom pozify.contracts import UserProfile, Verification, to_dictfrom pozify.env import env_truthy, load_local_env55 unmodified linesmock_mode = _env_mock_mode(video_path) if mock is None else mockbypass_verifier_enabled = _bypass_verifier_enabled(bypass_verifier)run_id = (f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}-{uuid4().hex[:8]}")run_dir = RUNS_DIR / run_idartifact_index: list[dict[str, str]] = []54 unmodified lines"active","Now I am mapping your posture and tracking the key body landmarks.",)cached_pose_sequence = None if mock_mode else sample_pose_cache.load(manifest)if cached_pose_sequence is None:pose_sequence = pose_landmarker.run(manifest, mock=mock_mode)cleaned_pose_sequence = pose_cleaning.run(pose_sequence)else:cleaned_pose_sequence = cached_pose_sequencewrite_artifact("pose_sequence.json", cleaned_pose_sequence)pose_source = (cleaned_pose_sequence.frames[0].pose_quality.get("source")7 unmodified linesframe_count=len(cleaned_pose_sequence.frames),pose_source=pose_source,pose_valid_ratio=cleaned_pose_sequence.pose_valid_ratio,pose_cache_hit=cached_pose_sequence is not None,)emit("exercise", "active", "Let me figure out which exercise you are doing.")classification = exercise_classifier.run(cleaned_pose_sequence, profile, mock=mock_mode)write_artifact("exercise_classification.json", classification)emit("exercise",5 unmodified lines6789101155 unmodified lines6768697071727354 unmodified lines1281291301311321331341357 unmodified lines1431441451461471481491501511525 unmodified linesfrom typing import Any, Callablefrom uuid import uuid4from pozify.artifacts import write_jsonfrom pozify.contracts import UserProfile, Verification, to_dictfrom pozify.env import env_truthy, load_local_env55 unmodified linesmock_mode = _env_mock_mode(video_path) if mock is None else mockbypass_verifier_enabled = _bypass_verifier_enabled(bypass_verifier)run_id = f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}-{uuid4().hex[:8]}"run_dir = RUNS_DIR / run_idartifact_index: list[dict[str, str]] = []54 unmodified lines"active","Now I am mapping your posture and tracking the key body landmarks.",)pose_sequence = pose_landmarker.run(manifest, mock=mock_mode)cleaned_pose_sequence = pose_cleaning.run(pose_sequence)write_artifact("pose_sequence.json", cleaned_pose_sequence)pose_source = (cleaned_pose_sequence.frames[0].pose_quality.get("source")7 unmodified linesframe_count=len(cleaned_pose_sequence.frames),pose_source=pose_source,pose_valid_ratio=cleaned_pose_sequence.pose_valid_ratio,)emit("exercise", "active", "Let me figure out which exercise you are doing.")classification = exercise_classifier.run(cleaned_pose_sequence, profile, mock=mock_mode)write_artifact("exercise_classification.json", classification)emit("exercise",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229from __future__ import annotations
import hashlibimport jsonimport osfrom pathlib import Pathfrom typing import Any
from pozify.contracts import ( ContractValidationError, PoseFrame, PoseSequence, VideoManifest, validate_contract,)
ROOT_DIR = Path(__file__).resolve().parents[2]SAMPLE_POSE_CACHE_PATH_ENV = "POZIFY_SAMPLE_POSE_CACHE_PATH"SAMPLE_POSE_RUNS_DIR_ENV = "POZIFY_SAMPLE_POSE_RUNS_DIR"SAMPLE_VIDEO_SHA256_ENV = "POZIFY_SAMPLE_VIDEO_SHA256"
SAMPLE_VIDEO_NAMES = { "sample.mp4", "sample.mov", "sample_converted.mp4",}KNOWN_SAMPLE_VIDEO_SHA256 = { "77e17441c273da24647028f20b5573d03710e0f9b32dc43ff1dc3cc72aaa77f4",}KNOWN_SAMPLE_VIDEO_SIZES = { 9_797_579,}
def _env_values(name: str) -> list[str]: raw_value = os.getenv(name, "") return [value.strip() for value in raw_value.split(os.pathsep) if value.strip()]
def _sha256(path: Path) -> str | None: try: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() except OSError: return None
def _known_sample_hashes() -> set[str]: hashes = set(KNOWN_SAMPLE_VIDEO_SHA256) hashes.update(_env_values(SAMPLE_VIDEO_SHA256_ENV))
fixture_path = ROOT_DIR / "tests" / "fixtures" / "sample.mp4" if fixture_path.is_file(): fixture_hash = _sha256(fixture_path) if fixture_hash is not None: hashes.add(fixture_hash)
return hashes
def _looks_like_sample_name(path: Path) -> bool: name = path.name.lower() stem = path.stem.lower() return ( name in SAMPLE_VIDEO_NAMES or stem == "sample" or stem.startswith("pozify-sample-") )
def _is_known_sample_video(manifest: VideoManifest) -> bool: if not manifest.analysis_allowed or manifest.video_path is None: return False
video_path = Path(manifest.video_path) if not video_path.is_file(): return False
try: file_size = video_path.stat().st_size except OSError: return False
should_hash = _looks_like_sample_name(video_path) or file_size in KNOWN_SAMPLE_VIDEO_SIZES if not should_hash: return False
video_hash = _sha256(video_path) return video_hash in _known_sample_hashes() if video_hash is not None else False
def _manifest_matches(manifest: VideoManifest, payload: dict[str, Any]) -> bool: try: return ( int(payload["total_frames"]) == manifest.total_frames and int(payload["width"]) == manifest.width and int(payload["height"]) == manifest.height and round(float(payload["fps"]), 3) == round(manifest.fps, 3) and round(float(payload["duration_sec"]), 3) == round(manifest.duration_sec, 3) ) except (KeyError, TypeError, ValueError): return False
def _manifest_path_looks_like_sample(payload: dict[str, Any]) -> bool: video_path = payload.get("video_path") return isinstance(video_path, str) and _looks_like_sample_name(Path(video_path))
def _runs_cache_paths(manifest: VideoManifest) -> list[Path]: runs_dir_values = _env_values(SAMPLE_POSE_RUNS_DIR_ENV) runs_dir = Path(runs_dir_values[0]) if runs_dir_values else ROOT_DIR / "runs" if not runs_dir.is_dir(): return []
candidates: list[Path] = [] for manifest_path in runs_dir.glob("*/video_manifest.json"): try: payload = json.loads(manifest_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): continue
if not isinstance(payload, dict): continue if not _manifest_path_looks_like_sample(payload): continue if not _manifest_matches(manifest, payload): continue
pose_path = manifest_path.parent / "pose_sequence.json" if pose_path.is_file(): candidates.append(pose_path)
return sorted(candidates, key=lambda path: path.stat().st_mtime, reverse=True)
def _cache_paths(manifest: VideoManifest) -> list[Path]: paths = [Path(value) for value in _env_values(SAMPLE_POSE_CACHE_PATH_ENV)]
default_cache = ROOT_DIR / "demo" / "precomputed" / "sample_pose_sequence.json" if default_cache.is_file(): paths.append(default_cache)
paths.extend(_runs_cache_paths(manifest)) return paths
def _pose_payload_matches_manifest(payload: dict[str, Any], manifest: VideoManifest) -> bool: frames = payload.get("frames") if not isinstance(frames, list) or not frames: return False if manifest.total_frames > 0 and len(frames) != manifest.total_frames: return False if payload.get("normalized") is not True: return False
first_frame = frames[0] if not isinstance(first_frame, dict): return False first_quality = first_frame.get("pose_quality", {}) if not isinstance(first_quality, dict): return False if first_quality.get("source") in {"mock_pose", "none"}: return False if first_quality.get("landmark_schema") != "coco17": return False
last_frame = frames[-1] if not isinstance(last_frame, dict): return False try: return int(last_frame["frame_index"]) <= max(manifest.total_frames - 1, 0) except (KeyError, TypeError, ValueError): return False
def _pose_sequence_from_payload(payload: dict[str, Any]) -> PoseSequence: return PoseSequence( frames=[ PoseFrame( frame_index=int(frame["frame_index"]), timestamp_sec=float(frame["timestamp_sec"]), landmarks=frame["landmarks"], world_landmarks=frame["world_landmarks"], pose_quality=frame["pose_quality"], ) for frame in payload["frames"] ], normalized=bool(payload["normalized"]), smoothing_method=str(payload["smoothing_method"]), pose_valid_ratio=float(payload["pose_valid_ratio"]), )
def _load_pose_sequence(path: Path, manifest: VideoManifest) -> PoseSequence | None: try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return None
if not isinstance(payload, dict): return None
try: validate_contract("pose_sequence.json", payload) except ContractValidationError: return None
if not _pose_payload_matches_manifest(payload, manifest): return None
return _pose_sequence_from_payload(payload)
def load(manifest: VideoManifest) -> PoseSequence | None: if not _is_known_sample_video(manifest): return None
for cache_path in _cache_paths(manifest): cached_sequence = _load_pose_sequence(cache_path, manifest) if cached_sequence is not None: return cached_sequence
return None123456786 unmodified lines15161718192067 unmodified lines88899091929341 unmodified lines135136137138139140141142143from __future__ import annotationsfrom pathlib import Pathfrom pozify.contracts import ExerciseClassification, PoseSequence, UserProfilefrom pozify.exercise_catalog import DEFAULT_AUTO_EXERCISEfrom pozify.hf_spaces import default_spaces_gpu_duration, spaces_gpufrom pozify.ml.exercise_router_features import RouterWindow, extract_router_windows6 unmodified linespredict_window_probabilities,window_predictions_from_scores,)def _sample_prediction_frames(sequence: PoseSequence, count: int = 4) -> list[object]:67 unmodified lines)def _gpu_duration(*_args: object, **_kwargs: object) -> int:return default_spaces_gpu_duration()41 unmodified linesstr(model_dir or Path("models/exercise_router/active")),)if not score_rows:return _unknown_fallback()except Exception:return _unknown_fallback()predictions = window_predictions_from_scores(windows, score_rows)window_payload = contract_window_predictions(predictions)1234567896 unmodified lines161718192021222324252667 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828941 unmodified lines331332333334335336337338339from __future__ import annotationsfrom collections.abc import Iterablefrom pathlib import Pathfrom pozify.contracts import ExerciseClassification, PoseFrame, PoseSequence, UserProfilefrom pozify.exercise_catalog import DEFAULT_AUTO_EXERCISEfrom pozify.hf_spaces import default_spaces_gpu_duration, spaces_gpufrom pozify.ml.exercise_router_features import RouterWindow, extract_router_windows6 unmodified linespredict_window_probabilities,window_predictions_from_scores,)from pozify.steps.rep_signals import angle_deg, smooth_signalMIN_HEURISTIC_CONFIDENCE = 0.58MIN_HEURISTIC_MARGIN = 0.14def _sample_prediction_frames(sequence: PoseSequence, count: int = 4) -> list[object]:67 unmodified lines)def _clip01(value: float) -> float:return max(0.0, min(1.0, value))def _usable(values: Iterable[float | None]) -> list[float]:return [float(value) for value in values if value is not None]def _range(values: Iterable[float | None]) -> float:usable_values = _usable(smooth_signal(list(values)))if not usable_values:return 0.0return max(usable_values) - min(usable_values)def _raw_axis(frame: PoseFrame, name: str, axis: str) -> float | None:values = frame.landmarks.get(name) or frame.world_landmarks.get(name)if values is None:return Nonevalue = values.get(f"smoothed_{axis}",values.get(axis, values.get(f"normalized_{axis}")),)return None if value is None else float(value)def _mean_raw_axis(frame: PoseFrame, names: tuple[str, ...], axis: str) -> float | None:values = _usable(_raw_axis(frame, name, axis) for name in names)if not values:return Nonereturn sum(values) / len(values)def _mean_abs_y_gap(frames: list[PoseFrame],first: tuple[str, ...],second: tuple[str, ...],) -> float:gaps: list[float] = []for frame in frames:first_y = _mean_raw_axis(frame, first, "y")second_y = _mean_raw_axis(frame, second, "y")if first_y is None or second_y is None:continuegaps.append(abs(first_y - second_y))return sum(gaps) / len(gaps) if gaps else 0.0def _joint_bend_deg(frame: PoseFrame, triples: tuple[tuple[str, str, str], ...]) -> float | None:values: list[float] = []for first, middle, last in triples:angle = angle_deg(frame, first, middle, last)if angle is not None:values.append(max(0.0, 180.0 - angle))return sum(values) / len(values) if values else Nonedef _heuristic_score_rows(sequence: PoseSequence) -> dict[str, float]:frames = [frame for frame in sequence.frames if frame.landmarks or frame.world_landmarks]if len(frames) < 9:return {"squat": 0.0, "push_up": 0.0, "shoulder_press": 0.0}shoulder_y = [_mean_raw_axis(frame, ("left_shoulder", "right_shoulder"), "y") for frame in frames]hip_y = [_mean_raw_axis(frame, ("left_hip", "right_hip"), "y") for frame in frames]wrist_y = [_mean_raw_axis(frame, ("left_wrist", "right_wrist"), "y") for frame in frames]knee_bend = [_joint_bend_deg(frame,(("left_hip", "left_knee", "left_ankle"),("right_hip", "right_knee", "right_ankle"),),)for frame in frames]hip_bend = [_joint_bend_deg(frame,(("left_shoulder", "left_hip", "left_knee"),("right_shoulder", "right_hip", "right_knee"),),)for frame in frames]elbow_bend = [_joint_bend_deg(frame,(("left_shoulder", "left_elbow", "left_wrist"),("right_shoulder", "right_elbow", "right_wrist"),),)for frame in frames]shoulder_range = _range(shoulder_y)hip_range = _range(hip_y)wrist_range = _range(wrist_y)chest_range = (shoulder_range + hip_range) / 2.0knee_bend_range = _range(knee_bend)hip_bend_range = _range(hip_bend)elbow_bend_range = _range(elbow_bend)shoulder_hip_gap = _mean_abs_y_gap(frames,("left_shoulder", "right_shoulder"),("left_hip", "right_hip"),)hip_ankle_gap = _mean_abs_y_gap(frames,("left_hip", "right_hip"),("left_ankle", "right_ankle"),)standing_score = _clip01((shoulder_hip_gap + hip_ankle_gap) / 0.45)plank_score = (_clip01((0.28 - shoulder_hip_gap) / 0.28) + _clip01((0.24 - hip_ankle_gap) / 0.24)) / 2.0wrist_not_dominant = _clip01(1.0 - wrist_range / max(hip_range + 0.05, 0.05))wrist_stable_for_push = _clip01(1.0 - wrist_range / max(chest_range + 0.04, 0.04))body_still_for_press = _clip01(1.0 - max(shoulder_range, hip_range) / max(wrist_range, 0.05))lower_body_bend = max(_clip01(knee_bend_range / 45.0), _clip01(hip_bend_range / 45.0))push_up_geometry = 0.55 + 0.45 * plank_scorepress_lower_body_gate = 1.0 - 0.55 * lower_body_bendsquat_score = standing_score * (0.42 * _clip01(knee_bend_range / 45.0)+ 0.24 * _clip01(hip_bend_range / 45.0)+ 0.22 * _clip01(hip_range / 0.10)+ 0.12 * wrist_not_dominant)push_up_score = (0.45 * _clip01(elbow_bend_range / 55.0)+ 0.25 * _clip01(chest_range / 0.08)+ 0.20 * plank_score+ 0.10 * wrist_stable_for_push) * push_up_geometryshoulder_press_score = press_lower_body_gate * (0.40 * _clip01(wrist_range / 0.16)+ 0.25 * _clip01(elbow_bend_range / 55.0)+ 0.20 * body_still_for_press+ 0.15 * standing_score)return {"squat": round(_clip01(squat_score), 4),"push_up": round(_clip01(push_up_score), 4),"shoulder_press": round(_clip01(shoulder_press_score), 4),}def _heuristic_classification(sequence: PoseSequence,windows: list[RouterWindow],) -> ExerciseClassification:scores = _heuristic_score_rows(sequence)ranked = sorted(scores, key=lambda label: scores[label], reverse=True)winning_label = ranked[0]score_margin = scores[winning_label] - scores[ranked[1]]if scores[winning_label] < MIN_HEURISTIC_CONFIDENCE or score_margin < MIN_HEURISTIC_MARGIN:return _unknown_fallback(confidence=scores[winning_label])confidence = round(min(0.88, 0.55 + scores[winning_label] * 0.25 + min(score_margin, 0.4) * 0.20),4,)if not windows:return _fixed_classification(sequence,exercise=winning_label,confidence=confidence,fallback_required=False,)return ExerciseClassification(exercise=winning_label, # type: ignore[arg-type]confidence=confidence,window_predictions=[{"start_sec": window.start_sec,"end_sec": window.end_sec,"label": winning_label,"confidence": confidence,}for window in windows],fallback_required=False,)def _gpu_duration(*_args: object, **_kwargs: object) -> int:return default_spaces_gpu_duration()41 unmodified linesstr(model_dir or Path("models/exercise_router/active")),)if not score_rows:return _heuristic_classification(sequence, windows)except Exception:return _heuristic_classification(sequence, windows)predictions = window_predictions_from_scores(windows, score_rows)window_payload = contract_window_predictions(predictions)
14 unmodified lines1516171819202126 unmodified lines48495051525324 unmodified lines787980818283848586878889909192939495969798991001011021031041051061078 unmodified lines11611711811912012112212312439 unmodified lines16416516616716816917017117232 unmodified lines20520620720820921021121221321421521621721821922014 unmodified linesPoseBackendUnavailableError,create_pose_backend,)from pozify.steps.video_qc import sample_frame_indicesCRITICAL_LANDMARKS = {26 unmodified linestry:if not capture.isOpened():returnif sample_count is None:for frame_index in range(manifest.total_frames):ok, frame = capture.read()24 unmodified lines"pose_warning": "pose_not_detected",}visibility_values = [landmark.get("visibility", 0.0) for landmark in landmarks.values()]critical_values = [landmarks[name].get("visibility", 0.0)for name in CRITICAL_LANDMARKSif name in landmarks]full_body_values = [landmarks[name].get("visibility", 0.0)for name in FULL_BODY_LANDMARKSif name in landmarks]critical_visible = (len(critical_values) == len(CRITICAL_LANDMARKS)and min(critical_values, default=0.0) >= 0.5)return {"mean_visibility": round(sum(visibility_values) / len(visibility_values), 4),"critical_landmarks_visible": critical_visible,"full_body_visibility_proxy": (round(sum(full_body_values) / len(full_body_values), 4)if full_body_valueselse 0.0),"landmark_count": len(landmarks),}8 unmodified linesdef _empty_sequence() -> PoseSequence:return PoseSequence(frames=[], normalized=False, smoothing_method="none", pose_valid_ratio=0.0)def _unavailable_sequence(reason: str) -> PoseSequence:39 unmodified linesframes.append(PoseFrame(frame_index=frame_index,timestamp_sec=(round(frame_index / manifest.fps, 3) if manifest.fps else 0.0),landmarks=detection.landmarks,world_landmarks=detection.world_landmarks,pose_quality={32 unmodified linesdef _run_mock(manifest: VideoManifest) -> PoseSequence:frames: list[PoseFrame] = []backend = MockPoseBackend()for frame_index in sample_frame_indices(manifest.total_frames, DEFAULT_POSE_SAMPLE_COUNT):detection = backend.detect(None, frame_index=frame_index)frames.append(PoseFrame(frame_index=frame_index,timestamp_sec=(round(frame_index / manifest.fps, 3) if manifest.fps else 0.0),landmarks=detection.landmarks,world_landmarks=detection.world_landmarks,pose_quality={14 unmodified lines1516171819202126 unmodified lines4849505152535424 unmodified lines7980818283848586878889909192939495969798998 unmodified lines10810911011111211311439 unmodified lines15415515615715815916032 unmodified lines19319419519619719819920020120220320414 unmodified linesPoseBackendUnavailableError,create_pose_backend,)from pozify.steps.video_qc import enable_capture_orientation, sample_frame_indicesCRITICAL_LANDMARKS = {26 unmodified linestry:if not capture.isOpened():returnenable_capture_orientation(capture)if sample_count is None:for frame_index in range(manifest.total_frames):ok, frame = capture.read()24 unmodified lines"pose_warning": "pose_not_detected",}visibility_values = [landmark.get("visibility", 0.0) for landmark in landmarks.values()]critical_values = [landmarks[name].get("visibility", 0.0) for name in CRITICAL_LANDMARKS if name in landmarks]full_body_values = [landmarks[name].get("visibility", 0.0) for name in FULL_BODY_LANDMARKS if name in landmarks]critical_visible = (len(critical_values) == len(CRITICAL_LANDMARKS) and min(critical_values, default=0.0) >= 0.5)return {"mean_visibility": round(sum(visibility_values) / len(visibility_values), 4),"critical_landmarks_visible": critical_visible,"full_body_visibility_proxy": (round(sum(full_body_values) / len(full_body_values), 4) if full_body_values else 0.0),"landmark_count": len(landmarks),}8 unmodified linesdef _empty_sequence() -> PoseSequence:return PoseSequence(frames=[], normalized=False, smoothing_method="none", pose_valid_ratio=0.0)def _unavailable_sequence(reason: str) -> PoseSequence:39 unmodified linesframes.append(PoseFrame(frame_index=frame_index,timestamp_sec=(round(frame_index / manifest.fps, 3) if manifest.fps else 0.0),landmarks=detection.landmarks,world_landmarks=detection.world_landmarks,pose_quality={32 unmodified linesdef _run_mock(manifest: VideoManifest) -> PoseSequence:frames: list[PoseFrame] = []backend = MockPoseBackend()for frame_index in sample_frame_indices(manifest.total_frames, DEFAULT_POSE_SAMPLE_COUNT):detection = backend.detect(None, frame_index=frame_index)frames.append(PoseFrame(frame_index=frame_index,timestamp_sec=(round(frame_index / manifest.fps, 3) if manifest.fps else 0.0),landmarks=detection.landmarks,world_landmarks=detection.world_landmarks,pose_quality={
19 unmodified lines20212223242517 unmodified lines4344454647484950515253545 unmodified lines60616263646538 unmodified lines10410510610710810919 unmodified linesHARD_FAILURE_WARNINGS = {"video_decode_failed"}def _decode_fourcc(value: float) -> str | None:code = int(value)if code <= 0:17 unmodified linesreturn list(range(total_frames))last_index = total_frames - 1return sorted({round(index * last_index / (sample_count - 1))for index in range(sample_count)})def sample_video_frames(5 unmodified linesif not capture.isOpened():returntotal_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)for frame_index in sample_frame_indices(total_frames, sample_count):capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)38 unmodified linesif not capture.isOpened():return _empty_manifest(video_path, ["video_decode_failed"])fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)total_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)19 unmodified lines20212223242526272829303117 unmodified lines495051525354555 unmodified lines6162636465666738 unmodified lines10610710810911011111219 unmodified linesHARD_FAILURE_WARNINGS = {"video_decode_failed"}def enable_capture_orientation(capture: cv2.VideoCapture) -> None:orientation_auto = getattr(cv2, "CAP_PROP_ORIENTATION_AUTO", None)if orientation_auto is not None:capture.set(orientation_auto, 1)def _decode_fourcc(value: float) -> str | None:code = int(value)if code <= 0:17 unmodified linesreturn list(range(total_frames))last_index = total_frames - 1return sorted({round(index * last_index / (sample_count - 1)) for index in range(sample_count)})def sample_video_frames(5 unmodified linesif not capture.isOpened():returnenable_capture_orientation(capture)total_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)for frame_index in sample_frame_indices(total_frames, sample_count):capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index)38 unmodified linesif not capture.isOpened():return _empty_manifest(video_path, ["video_decode_failed"])enable_capture_orientation(capture)fps = float(capture.get(cv2.CAP_PROP_FPS) or 0.0)total_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT) or 0)width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
14 unmodified lines1516171819202161 unmodified lines8384858687888928 unmodified lines11811912012112212312412 unmodified lines13713813914014114252 unmodified lines19519619719819920020120220320420516 unmodified lines2222232242252262272282294 unmodified lines23423523623723823924024124224324424524628 unmodified lines2752762772782792808 unmodified lines28929029129229329429520 unmodified lines3163173183193203213229 unmodified lines33233333433533633724 unmodified lines3623633643653663673683 unmodified lines37237337437537637714 unmodified linessys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from 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,61 unmodified lines)def _landmarks_for_exercise(exercise: str, phase: float, visibility: float) -> dict[str, dict[str, float]]:landmarks = _base_landmarks(visibility)wave = (1.0 - math.cos(2.0 * math.pi * phase)) / 2.0if exercise == "squat":28 unmodified linesreturn landmarksdef _sequence(exercise: str = "push_up", frame_count: int = 45, visibility: float = 0.95) -> PoseSequence:frames = [PoseFrame(frame_index=index,12 unmodified lines)class _FakePushUpModel:classes_ = np.asarray(ROUTER_LABELS)52 unmodified linesframe.frame_index,frame.timestamp_sec,{name: {key: valuefor key, value in landmark.items()if key != "visibility"}for name, landmark in frame.landmarks.items()},frame.world_landmarks,16 unmodified linesclass ExerciseRouterAggregationTests(unittest.TestCase):def test_aggregates_confident_windows(self) -> None:predictions = [WindowRouterPrediction(0.0, 1.0, "push_up", 0.91, {"squat": 0.03, "push_up": 0.91, "shoulder_press": 0.02, "unknown": 0.04}),WindowRouterPrediction(0.5, 1.5, "push_up", 0.88, {"squat": 0.05, "push_up": 0.88, "shoulder_press": 0.02, "unknown": 0.05}),]aggregated = aggregate_window_predictions(predictions)4 unmodified linesdef test_low_confidence_and_inconsistent_windows_fallback_to_unknown(self) -> None:low_confidence = [WindowRouterPrediction(0.0, 1.0, "push_up", 0.45, {"squat": 0.25, "push_up": 0.45, "shoulder_press": 0.15, "unknown": 0.15}),WindowRouterPrediction(0.5, 1.5, "push_up", 0.48, {"squat": 0.22, "push_up": 0.48, "shoulder_press": 0.15, "unknown": 0.15}),]inconsistent = [WindowRouterPrediction(0.0, 1.0, "push_up", 0.8, {"squat": 0.05, "push_up": 0.8, "shoulder_press": 0.1, "unknown": 0.05}),WindowRouterPrediction(0.5, 1.5, "squat", 0.8, {"squat": 0.8, "push_up": 0.05, "shoulder_press": 0.1, "unknown": 0.05}),WindowRouterPrediction(1.0, 2.0, "shoulder_press", 0.8, {"squat": 0.1, "push_up": 0.05, "shoulder_press": 0.8, "unknown": 0.05}),]self.assertTrue(aggregate_window_predictions(low_confidence).fallback_required)28 unmodified linesself.assertEqual(result.exercise, "push_up")self.assertFalse(result.fallback_required)def test_hf_loader_honors_selection_file(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:model_dir = Path(temp_dir)8 unmodified linesdef fake_download(*, repo_id: str, filename: str, revision: str | None) -> Path:self.assertEqual(repo_id, "owner/pozify-router")self.assertEqual(revision, "main")return {"router_selection.json": selection_path, "router.joblib": artifact_path}[filename]with patch("pozify.ml.exercise_router_inference._hf_hub_download",20 unmodified linesdef fake_download(*, repo_id: str, filename: str, revision: str | None) -> Path:self.assertEqual(repo_id, DEFAULT_HF_REPO_ID)self.assertIsNone(revision)return {"router_selection.json": selection_path, "router.joblib": artifact_path}[filename]with (patch.dict(os.environ, {}, clear=True),9 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)24 unmodified linesself.assertEqual(result.confidence, 0.98)validate_contract("exercise_classification.json", result)def test_missing_model_falls_back_to_unknown(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:with patch.dict(os.environ, {HF_DISABLE_ENV: "1"}):result = exercise_classifier.run(3 unmodified linesmodel_dir=Path(temp_dir),)self.assertEqual(result.exercise, "unknown")self.assertTrue(result.fallback_required)validate_contract("exercise_classification.json", result)14 unmodified lines1516171819202122232461 unmodified lines86878889909192939428 unmodified lines12312412512612712812913013112 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716852 unmodified lines22122222322422522622716 unmodified lines2442452462472482492502512522532542552562572582592602612622634 unmodified lines26826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931028 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603618 unmodified lines37037137237337437537637737820 unmodified lines3994004014024034044054064079 unmodified lines41741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346424 unmodified lines4894904914924934944953 unmodified lines49950050150250350450550650750850951051151251351451551651751851914 unmodified linessys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from pozify.contracts import PoseFrame, PoseSequence, UserProfile, validate_contractfrom pozify.ml.exercise_router_evaluation import (evaluate_router_predictions,select_router_candidate,)from pozify.ml.exercise_router_features import (FEATURE_SCHEMA,ROUTER_LABELS,61 unmodified lines)def _landmarks_for_exercise(exercise: str, phase: float, visibility: float) -> dict[str, dict[str, float]]:landmarks = _base_landmarks(visibility)wave = (1.0 - math.cos(2.0 * math.pi * phase)) / 2.0if exercise == "squat":28 unmodified linesreturn landmarksdef _sequence(exercise: str = "push_up", frame_count: int = 45, visibility: float = 0.95) -> PoseSequence:frames = [PoseFrame(frame_index=index,12 unmodified lines)def _static_sequence(frame_count: int = 45, visibility: float = 0.95) -> PoseSequence:frames = [PoseFrame(frame_index=index,timestamp_sec=round(index / 30.0, 3),landmarks=_landmarks_for_exercise("push_up", 0.0, visibility),world_landmarks={},pose_quality={"mean_visibility": visibility, "normalized": True},)for index in range(frame_count)]return PoseSequence(frames=frames,normalized=True,smoothing_method="exponential_smoothing",pose_valid_ratio=1.0 if visibility >= 0.2 else 0.4,)class _FakePushUpModel:classes_ = np.asarray(ROUTER_LABELS)52 unmodified linesframe.frame_index,frame.timestamp_sec,{name: {key: value for key, value in landmark.items() if key != "visibility"}for name, landmark in frame.landmarks.items()},frame.world_landmarks,16 unmodified linesclass ExerciseRouterAggregationTests(unittest.TestCase):def test_aggregates_confident_windows(self) -> None:predictions = [WindowRouterPrediction(0.0,1.0,"push_up",0.91,{"squat": 0.03, "push_up": 0.91, "shoulder_press": 0.02, "unknown": 0.04},),WindowRouterPrediction(0.5,1.5,"push_up",0.88,{"squat": 0.05, "push_up": 0.88, "shoulder_press": 0.02, "unknown": 0.05},),]aggregated = aggregate_window_predictions(predictions)4 unmodified linesdef test_low_confidence_and_inconsistent_windows_fallback_to_unknown(self) -> None:low_confidence = [WindowRouterPrediction(0.0,1.0,"push_up",0.45,{"squat": 0.25, "push_up": 0.45, "shoulder_press": 0.15, "unknown": 0.15},),WindowRouterPrediction(0.5,1.5,"push_up",0.48,{"squat": 0.22, "push_up": 0.48, "shoulder_press": 0.15, "unknown": 0.15},),]inconsistent = [WindowRouterPrediction(0.0,1.0,"push_up",0.8,{"squat": 0.05, "push_up": 0.8, "shoulder_press": 0.1, "unknown": 0.05},),WindowRouterPrediction(0.5,1.5,"squat",0.8,{"squat": 0.8, "push_up": 0.05, "shoulder_press": 0.1, "unknown": 0.05},),WindowRouterPrediction(1.0,2.0,"shoulder_press",0.8,{"squat": 0.1, "push_up": 0.05, "shoulder_press": 0.8, "unknown": 0.05},),]self.assertTrue(aggregate_window_predictions(low_confidence).fallback_required)28 unmodified linesself.assertEqual(result.exercise, "push_up")self.assertFalse(result.fallback_required)def test_selection_file_accepts_legacy_selected_model_field(self) -> None:with 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_model": artifact_path.name}),encoding="utf-8",)with patch.dict(os.environ, {HF_DISABLE_ENV: "1"}):bundle = load_router_model(model_dir)self.assertIsNotNone(bundle)assert bundle is not Noneself.assertEqual(bundle.labels, tuple(ROUTER_LABELS))def test_hf_loader_honors_selection_file(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:model_dir = Path(temp_dir)8 unmodified linesdef fake_download(*, repo_id: str, filename: str, revision: str | None) -> Path:self.assertEqual(repo_id, "owner/pozify-router")self.assertEqual(revision, "main")return {"router_selection.json": selection_path, "router.joblib": artifact_path}[filename]with patch("pozify.ml.exercise_router_inference._hf_hub_download",20 unmodified linesdef fake_download(*, repo_id: str, filename: str, revision: str | None) -> Path:self.assertEqual(repo_id, DEFAULT_HF_REPO_ID)self.assertIsNone(revision)return {"router_selection.json": selection_path, "router.joblib": artifact_path}[filename]with (patch.dict(os.environ, {}, clear=True),9 unmodified linesself.assertEqual(bundle.model_kind, "baseline")self.assertEqual(bundle.labels, tuple(ROUTER_LABELS))def test_hf_loader_reads_local_env_before_selecting_repo(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:root = Path(temp_dir)model_dir = root / "model"model_dir.mkdir()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",)(root / ".env").write_text("POZIFY_ROUTER_HF_REPO_ID=owner/env-router\n",encoding="utf-8",)original_cwd = Path.cwd()def fake_download(*, repo_id: str, filename: str, revision: str | None) -> Path:self.assertEqual(repo_id, "owner/env-router")self.assertIsNone(revision)return {"router_selection.json": selection_path, "router.joblib": artifact_path}[filename]try:os.chdir(root)with (patch.dict(os.environ, {}, clear=True),patch("pozify.ml.exercise_router_inference._hf_hub_download",side_effect=fake_download,),):bundle = load_router_model_from_hf()finally:os.chdir(original_cwd)self.assertIsNotNone(bundle)assert bundle is not Noneself.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)24 unmodified linesself.assertEqual(result.confidence, 0.98)validate_contract("exercise_classification.json", result)def test_missing_model_uses_pose_heuristic_for_clear_motion(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:with patch.dict(os.environ, {HF_DISABLE_ENV: "1"}):result = exercise_classifier.run(3 unmodified linesmodel_dir=Path(temp_dir),)self.assertEqual(result.exercise, "push_up")self.assertFalse(result.fallback_required)self.assertGreaterEqual(result.confidence, 0.65)validate_contract("exercise_classification.json", result)def test_missing_model_keeps_static_motion_unknown(self) -> None:with tempfile.TemporaryDirectory() as temp_dir:with patch.dict(os.environ, {HF_DISABLE_ENV: "1"}):result = exercise_classifier.run(_static_sequence(),_profile("auto"),mock=False,model_dir=Path(temp_dir),)self.assertEqual(result.exercise, "unknown")self.assertTrue(result.fallback_required)validate_contract("exercise_classification.json", result)
16 unmodified lines17181920212223242526121 unmodified lines14814915015115215315415515617 unmodified lines17417517617717817918018118218318418518618718818919019119216 unmodified lines20921021121221321421521621721821922022122222322410 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631714 unmodified lines33233333433533633733833934025 unmodified lines36636736836937037137237337411 unmodified lines38638738838939039139239339459 unmodified lines45445545645745845946046146216 unmodified linesfrom pozify.contracts import (CoachSummary,ContractValidationError,PoseFrame,PoseSequence,UserProfile,VideoManifest,validate_contract,)from pozify.exercise_catalog import USER_SELECTABLE_EXERCISES121 unmodified linesfor frame_index in range(int(fps * duration_sec)):frame = np.full((height, width, 3), 130, dtype=np.uint8)offset = frame_index % 120cv2.rectangle(frame, (40 + offset, 80), (260 + offset, 300), (245, 245, 245), -1)cv2.line(frame,(0, frame_index % height),17 unmodified linesself.assertEqual(sorted(payload.keys()), keys, artifact_name)if artifact_name == "final_report.json":self.assertIn("issue_thumbnail_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["issue_thumbnail_paths"], list)self.assertIn("issue_clip_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["issue_clip_paths"], list)self.assertIn("knowledge_card_pack_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["knowledge_card_pack_paths"], list)self.assertIn("knowledge_external_cards_loaded", payload["artifacts"])self.assertIn("knowledge_external_cards_retrieved", payload["artifacts"])manifest = json.loads(manifest_path.read_text(encoding="utf-8"))self.assertTrue(manifest["mock_mode"])16 unmodified lines)def test_pipeline_runs_end_to_end_without_video(self) -> None:result = pipeline.run_pipeline(video_path=None, profile_input=PROFILE_INPUT, mock=True)self._assert_pipeline_artifacts(result)report = result["final_report"]self.assertEqual(report["exercise"]["exercise"], "squat")self.assertEqual(report["video_manifest"]["quality_warnings"], ["video_decode_failed"])self.assertFalse(report["video_manifest"]["analysis_allowed"])def test_pipeline_runs_end_to_end_with_fixture_video_path(self) -> None:10 unmodified linesself.assertEqual(report["video_manifest"]["width"], 640)self.assertEqual(report["video_manifest"]["height"], 480)def test_pipeline_uses_cached_sample_pose_sequence_when_available(self) -> None:fixture = self._write_video("sample.mp4", duration_sec=1 / 30)manifest = VideoManifest(video_path=str(fixture),fps=30.0,duration_sec=0.033,total_frames=1,sampled_frames=1,width=640,height=480,codec="mp4v",container="mp4",brightness_mean=120.0,blur_laplacian_var=80.0,quality_warnings=[],analysis_allowed=True,)cached_sequence = PoseSequence(frames=[PoseFrame(frame_index=0,timestamp_sec=0.0,landmarks={"left_hip": {"x": 0.4,"y": 0.5,"z": 0.0,"visibility": 0.9,}},world_landmarks={},pose_quality={"source": "mediapipe_pose","mean_visibility": 0.9,"landmark_schema": "coco17",},)],normalized=True,smoothing_method="exponential_smoothing",pose_valid_ratio=1.0,)events: list[dict[str, object]] = []with (patch("pozify.pipeline.video_qc.run", return_value=manifest),patch("pozify.pipeline.sample_pose_cache.load",return_value=cached_sequence,) as load_cache,patch("pozify.pipeline.pose_landmarker.run") as run_landmarker,patch("pozify.pipeline.pose_cleaning.run") as run_cleaning,):result = pipeline.run_pipeline(video_path=str(fixture),profile_input={**PROFILE_INPUT, "intended_exercise": "unknown"},mock=False,progress=events.append,)load_cache.assert_called_once_with(manifest)run_landmarker.assert_not_called()run_cleaning.assert_not_called()run_dir = Path(str(result["run_dir"]))pose_payload = json.loads((run_dir / "pose_sequence.json").read_text())self.assertEqual(pose_payload["frames"][0]["pose_quality"]["source"],"mediapipe_pose",)pose_done = next(eventfor event in eventsif event.get("step") == "pose" and event.get("status") == "done")self.assertTrue(pose_done["payload"]["pose_cache_hit"]) # type: ignore[index]def test_pipeline_emits_progress_after_steps(self) -> None:events: list[dict[str, object]] = []14 unmodified lines[event["step"] for event in done_events],["quality", "pose", "exercise", "reps", "issues", "render", "coach"],)payload_by_step = {str(event["step"]): event.get("payload", {}) for event in done_events}self.assertEqual(payload_by_step["exercise"]["exercise"], "squat")self.assertEqual(payload_by_step["reps"]["rep_count"], 0)self.assertEqual(payload_by_step["issues"]["issue_count"], 0)25 unmodified lines"pozify.pipeline.verifier.run",) as verifier_run,):result = pipeline.run_pipeline(video_path=None, profile_input=PROFILE_INPUT, mock=True)self._assert_pipeline_artifacts(result)report = result["final_report"]11 unmodified linesreport["verification"]["notes"],["Coach summary verifier is disabled for this run."],)self.assertTrue(report["artifacts"]["coach_summary_verifier_bypass_requested"])verifier_run.assert_not_called()def test_contract_validation_rejects_missing_required_field(self) -> None:59 unmodified linesself.assertEqual(report["exercise"]["exercise"], "unknown")self.assertFalse(report["exercise"]["fallback_required"])self.assertEqual(report["reps"]["reps"], [])self.assertEqual(report["reps"]["partial_reps"], [{"reason": "unknown_exercise"}])def test_mock_mode_defaults_to_real_when_video_path_is_present(self) -> None:with patch.dict(os.environ, {}, clear=True):16 unmodified lines17181920212223121 unmodified lines14514614714814915015117 unmodified lines16917017117217317417517617717817918018116 unmodified lines19819920020120220320420520620720820910 unmodified lines22022122222322422514 unmodified lines24024124224324424524625 unmodified lines27227327427527627727811 unmodified lines29029129229329429529659 unmodified lines35635735835936036136216 unmodified linesfrom pozify.contracts import (CoachSummary,ContractValidationError,UserProfile,validate_contract,)from pozify.exercise_catalog import USER_SELECTABLE_EXERCISES121 unmodified linesfor frame_index in range(int(fps * duration_sec)):frame = np.full((height, width, 3), 130, dtype=np.uint8)offset = frame_index % 120cv2.rectangle(frame, (40 + offset, 80), (260 + offset, 300), (245, 245, 245), -1)cv2.line(frame,(0, frame_index % height),17 unmodified linesself.assertEqual(sorted(payload.keys()), keys, artifact_name)if artifact_name == "final_report.json":self.assertIn("issue_thumbnail_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["issue_thumbnail_paths"], list)self.assertIn("issue_clip_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["issue_clip_paths"], list)self.assertIn("knowledge_card_pack_paths", payload["artifacts"])self.assertIsInstance(payload["artifacts"]["knowledge_card_pack_paths"], list)self.assertIn("knowledge_external_cards_loaded", payload["artifacts"])self.assertIn("knowledge_external_cards_retrieved", payload["artifacts"])manifest = json.loads(manifest_path.read_text(encoding="utf-8"))self.assertTrue(manifest["mock_mode"])16 unmodified lines)def test_pipeline_runs_end_to_end_without_video(self) -> None:result = pipeline.run_pipeline(video_path=None, profile_input=PROFILE_INPUT, mock=True)self._assert_pipeline_artifacts(result)report = result["final_report"]self.assertEqual(report["exercise"]["exercise"], "squat")self.assertEqual(report["video_manifest"]["quality_warnings"], ["video_decode_failed"])self.assertFalse(report["video_manifest"]["analysis_allowed"])def test_pipeline_runs_end_to_end_with_fixture_video_path(self) -> None:10 unmodified linesself.assertEqual(report["video_manifest"]["width"], 640)self.assertEqual(report["video_manifest"]["height"], 480)def test_pipeline_emits_progress_after_steps(self) -> None:events: list[dict[str, object]] = []14 unmodified lines[event["step"] for event in done_events],["quality", "pose", "exercise", "reps", "issues", "render", "coach"],)payload_by_step = {str(event["step"]): event.get("payload", {}) for event in done_events}self.assertEqual(payload_by_step["exercise"]["exercise"], "squat")self.assertEqual(payload_by_step["reps"]["rep_count"], 0)self.assertEqual(payload_by_step["issues"]["issue_count"], 0)25 unmodified lines"pozify.pipeline.verifier.run",) as verifier_run,):result = pipeline.run_pipeline(video_path=None, profile_input=PROFILE_INPUT, mock=True)self._assert_pipeline_artifacts(result)report = result["final_report"]11 unmodified linesreport["verification"]["notes"],["Coach summary verifier is disabled for this run."],)self.assertTrue(report["artifacts"]["coach_summary_verifier_bypass_requested"])verifier_run.assert_not_called()def test_contract_validation_rejects_missing_required_field(self) -> None:59 unmodified linesself.assertEqual(report["exercise"]["exercise"], "unknown")self.assertFalse(report["exercise"]["fallback_required"])self.assertEqual(report["reps"]["reps"], [])self.assertEqual(report["reps"]["partial_reps"], [{"reason": "unknown_exercise"}])def test_mock_mode_defaults_to_real_when_video_path_is_present(self) -> None:with patch.dict(os.environ, {}, clear=True):
26 unmodified lines27282930313233343539 unmodified lines757677787980818283129 unmodified lines21321421521621721821926 unmodified linesfrom pozify.steps.pose_backends.mediapipe import MediaPipePoseBackend, _MediaPipeTasksPoseAdapterdef _landmark(x: float, y: float, z: float = 0.0, visibility: float = 0.9) -> SimpleNamespace:return SimpleNamespace(x=x, y=y, z=z, visibility=visibility)39 unmodified linesdef _write_video(self, frame_count: int = 4) -> Path:path = Path(self.temp_dir.name) / "pose.mp4"writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 30.0, (640, 480))self.assertTrue(writer.isOpened())for frame_index in range(frame_count):frame = np.full((480, 640, 3), 120 + frame_index, dtype=np.uint8)129 unmodified linesframes = list(pose_landmarker._iter_video_frames(manifest, sample_count=None))self.assertEqual([frame_index for frame_index, _ in frames], [0, 1, 2])self.assertEqual(capture.set_calls, [])def test_pose_cleaning_interpolates_smooths_and_adds_normalized_fields(self,26 unmodified lines2728293031323339 unmodified lines73747576777879129 unmodified lines20921021121221321421521621721826 unmodified linesfrom pozify.steps.pose_backends.mediapipe import MediaPipePoseBackend, _MediaPipeTasksPoseAdapterdef _landmark(x: float, y: float, z: float = 0.0, visibility: float = 0.9) -> SimpleNamespace:return SimpleNamespace(x=x, y=y, z=z, visibility=visibility)39 unmodified linesdef _write_video(self, frame_count: int = 4) -> Path:path = Path(self.temp_dir.name) / "pose.mp4"writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 30.0, (640, 480))self.assertTrue(writer.isOpened())for frame_index in range(frame_count):frame = np.full((480, 640, 3), 120 + frame_index, dtype=np.uint8)129 unmodified linesframes = list(pose_landmarker._iter_video_frames(manifest, sample_count=None))self.assertEqual([frame_index for frame_index, _ in frames], [0, 1, 2])seek_calls = [call for call in capture.set_calls if call[0] == cv2.CAP_PROP_POS_FRAMES]self.assertEqual(seek_calls, [])if hasattr(cv2, "CAP_PROP_ORIENTATION_AUTO"):self.assertIn((cv2.CAP_PROP_ORIENTATION_AUTO, 1), capture.set_calls)def test_pose_cleaning_interpolates_smooths_and_adds_normalized_fields(self,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from __future__ import annotations
import hashlibimport jsonimport osimport sysimport tempfileimport unittestfrom pathlib import Pathfrom unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from pozify import sample_pose_cachefrom pozify.contracts import PoseFrame, PoseSequence, VideoManifest, to_dict
def _manifest(video_path: Path) -> VideoManifest: return VideoManifest( video_path=str(video_path), fps=30.0, duration_sec=0.067, total_frames=2, sampled_frames=2, width=640, height=480, codec="mp4v", container="mp4", brightness_mean=120.0, blur_laplacian_var=80.0, quality_warnings=[], analysis_allowed=True, )
def _cached_pose_sequence() -> PoseSequence: frames = [ PoseFrame( frame_index=0, timestamp_sec=0.0, landmarks={"left_hip": {"x": 0.4, "y": 0.5, "z": 0.0, "visibility": 0.9}}, world_landmarks={}, pose_quality={ "source": "mediapipe_pose", "mean_visibility": 0.9, "landmark_schema": "coco17", }, ), PoseFrame( frame_index=1, timestamp_sec=0.033, landmarks={"left_hip": {"x": 0.42, "y": 0.52, "z": 0.0, "visibility": 0.9}}, world_landmarks={}, pose_quality={ "source": "mediapipe_pose", "mean_visibility": 0.9, "landmark_schema": "coco17", }, ), ] return PoseSequence( frames=frames, normalized=True, smoothing_method="exponential_smoothing", pose_valid_ratio=1.0, )
class SamplePoseCacheTests(unittest.TestCase): def test_load_returns_cached_sequence_for_known_sample_hash(self) -> None: with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) video_path = root / "sample.mp4" video_bytes = b"sample-video" video_path.write_bytes(video_bytes)
cache_path = root / "pose_sequence.json" cache_path.write_text( json.dumps(to_dict(_cached_pose_sequence())), encoding="utf-8", )
with patch.dict( os.environ, { sample_pose_cache.SAMPLE_VIDEO_SHA256_ENV: hashlib.sha256( video_bytes ).hexdigest(), sample_pose_cache.SAMPLE_POSE_CACHE_PATH_ENV: str(cache_path), }, ): cached = sample_pose_cache.load(_manifest(video_path))
self.assertIsNotNone(cached) assert cached is not None self.assertEqual(len(cached.frames), 2) self.assertEqual(cached.frames[0].pose_quality["source"], "mediapipe_pose")
def test_load_ignores_non_sample_video(self) -> None: with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) video_path = root / "workout.mp4" video_bytes = b"sample-video" video_path.write_bytes(video_bytes)
cache_path = root / "pose_sequence.json" cache_path.write_text( json.dumps(to_dict(_cached_pose_sequence())), encoding="utf-8", )
with patch.dict( os.environ, { sample_pose_cache.SAMPLE_VIDEO_SHA256_ENV: hashlib.sha256( video_bytes ).hexdigest(), sample_pose_cache.SAMPLE_POSE_CACHE_PATH_ENV: str(cache_path), }, ): cached = sample_pose_cache.load(_manifest(video_path))
self.assertIsNone(cached)
if __name__ == "__main__": unittest.main()13 unmodified lines14151617181962 unmodified lines82838485868713 unmodified linesfrom pozify.steps import video_qcclass VideoQCTests(unittest.TestCase):def setUp(self) -> None:self.temp_dir = tempfile.TemporaryDirectory()62 unmodified linesself.assertIsNotNone(manifest.brightness_mean)self.assertIsNotNone(manifest.blur_laplacian_var)def test_invalid_video_sets_decode_failure_and_blocks_analysis(self) -> None:manifest = video_qc.run(str(Path(self.temp_dir.name) / "missing.mp4"))13 unmodified lines14151617181920212262 unmodified lines85868788899091929394959697989910010113 unmodified linesfrom pozify.steps import video_qcFIXTURES_DIR = Path(__file__).resolve().parent / "fixtures"class VideoQCTests(unittest.TestCase):def setUp(self) -> None:self.temp_dir = tempfile.TemporaryDirectory()62 unmodified linesself.assertIsNotNone(manifest.brightness_mean)self.assertIsNotNone(manifest.blur_laplacian_var)def test_rotated_mov_reports_display_dimensions(self) -> None:path = FIXTURES_DIR / "IMG_2296.MOV"self.assertTrue(path.exists(), path)manifest = video_qc.run(str(path))self.assertTrue(manifest.analysis_allowed)self.assertEqual(manifest.width, 1080)self.assertEqual(manifest.height, 1920)self.assertEqual(manifest.quality_warnings, [])def test_invalid_video_sets_decode_failure_and_blocks_analysis(self) -> None:manifest = video_qc.run(str(Path(self.temp_dir.name) / "missing.mp4"))
.gitignore+3-1
src/pozify/ml/exercise_router_inference.py+12-10
src/pozify/pipeline.py+4-14
src/pozify/sample_pose_cache.pyDeleted-229
src/pozify/steps/exercise_classifier.py+199-3
src/pozify/steps/pose_landmarker.py+11-27
src/pozify/steps/video_qc.py+9-6
tests/test_exercise_classifier.py+160-18
tests/test_pipeline_contracts.py+10-110
tests/test_pose_steps.py+6-7
tests/test_sample_pose_cache.pyDeleted-128
tests/test_video_qc.py+14