"""The agent's own reference data: typical ranges, problem definitions, drills, metric labels, plausibility bounds. Everything the agent is allowed to know about baseball mechanics lives in knowledge/*.yaml, so coaches and the product team can improve it without touching code or the pose pipeline. """ from __future__ import annotations import math from collections.abc import Mapping from dataclasses import dataclass from functools import cache from pathlib import Path from typing import Any import yaml from .config import PACKAGE_DIR KNOWLEDGE_DIR = PACKAGE_DIR / "knowledge" LEVELS = ("hs_jv", "hs_varsity", "college") DEFAULT_LEVEL = "hs_varsity" @cache def _load(name: str) -> dict: return yaml.safe_load(Path(KNOWLEDGE_DIR, name).read_text(encoding="utf-8")) @dataclass(frozen=True) class RangeInfo: """A typical range for one metric and level. `source` is "library" or "override" (a coach or org target).""" low: float high: float comparable: bool placeholder: bool status: str # calibrated | confirmed | adjusted | unverified source: str = "library" confidence: str = "low" # high | medium | low: how well this range is established for this level n_athletes: int | None = None # athletes behind a calibrated range @property def width(self) -> float: return self.high - self.low def normalise_level(level: str | None) -> tuple[str, bool]: """(level to use, whether it was assumed). A missing or unknown level falls back to hs_varsity.""" if level in LEVELS: return level, False return DEFAULT_LEVEL, True def _check_override(key: str, value: Any) -> tuple[float, float]: """A coach/org target must be two finite numbers with low < high, otherwise it would flip or zero the tolerance.""" try: low, high = (float(value[0]), float(value[1])) except (TypeError, ValueError, IndexError) as exc: raise ValueError(f"override for {key!r} must be (low, high) numbers") from exc if not (math.isfinite(low) and math.isfinite(high) and low < high): raise ValueError(f"override for {key!r} needs finite numbers with low < high, got ({value[0]}, {value[1]})") return low, high def metric_range( discipline: str, key: str, level: str, overrides: Mapping[str, tuple[float, float]] | None = None ) -> RangeInfo | None: """Typical range for a metric at a level, or None when there is no default (a coach/org must supply one).""" if overrides and key in overrides: low, high = _check_override(key, overrides[key]) return RangeInfo(low, high, comparable=True, placeholder=False, status="confirmed", source="override", confidence="high") entry = _load("ranges.yaml").get(discipline, {}).get(key) if not entry or not entry.get("levels"): return None band = entry["levels"].get(level) if not band: return None scope = "college" if level == "college" else "hs" confidence = (entry.get("confidence") or {}).get(level, "low") n_athletes = (entry.get("n_athletes") or {}).get(level) judged = entry.get("use", "judge") == "judge" and bool(entry.get("comparable", True)) return RangeInfo( float(band[0]), float(band[1]), judged, bool(entry.get("placeholder", False)), entry["status"][scope], confidence=confidence, n_athletes=n_athletes, ) def metric_info(discipline: str, metric_key: str) -> dict: """{"label","solid"} for a metric. Unknown keys get a readable label and no praise line.""" info = _load("metrics.yaml").get(discipline, {}).get(metric_key) if info is None: return {"label": metric_key.replace("_", " ").capitalize(), "solid": None} return info def metric_unit(discipline: str, key: str) -> str: """The unit of a metric, from the agent's own data (never taken from the session).""" entry = _load("ranges.yaml").get(discipline, {}).get(key) or {} return str(entry.get("unit", "")) def metric_keys(discipline: str) -> list[str]: return list(_load("metrics.yaml").get(discipline, {})) def problems(discipline: str) -> dict[str, dict[str, Any]]: """All problems the agent may name for a discipline: label, tier, rules, what, why, cue.""" return {k: v for k, v in _load("problems.yaml").get(discipline, {}).items()} def problem_info(discipline: str, key: str) -> dict[str, Any] | None: return problems(discipline).get(key) def problem_keys(discipline: str) -> list[str]: return list(problems(discipline)) def thresholds() -> dict[str, float]: return _load("problems.yaml")["thresholds"] def tier_weights() -> dict[str, float]: return _load("problems.yaml")["tier_weights"] def range_confidence_tolerance() -> dict[str, float]: return _load("problems.yaml")["range_confidence_tolerance"] def range_confidence_weights() -> dict[str, float]: return _load("problems.yaml")["range_confidence_weights"] def confidence_weights() -> dict[str, float]: return _load("problems.yaml")["confidence_weights"] def all_drills() -> list[dict[str, Any]]: return _load("drills.yaml")["drills"] def drills_for(discipline: str, problem_key: str) -> list[dict[str, Any]]: """Library drills for a problem, in library order.""" return [d for d in all_drills() if d["discipline"] == discipline and problem_key in d["faults"]]