Spaces:
Running on T4
Running on T4
Download AI-coach-agent/tests/helpers.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 6.86 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/tests/helpers.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/AI-coach-agent/tests/helpers.py
-
curl -L -o helpers.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/tests/helpers.py
6.86 kB
| """Test helpers: example loading, input/note factories, measurement builders and a scripted fake generator.""" | |
| from __future__ import annotations | |
| import json | |
| from collections import deque | |
| from pathlib import Path | |
| from ai_coach.chain import GenerationError, GenerationResult | |
| from ai_coach.fallback import build_fallback_note | |
| from ai_coach.input_builder import build_coach_input | |
| from ai_coach.schemas import ( | |
| CaptureInput, | |
| CoachInput, | |
| CoachNote, | |
| DrillInput, | |
| MetricInput, | |
| ProblemInput, | |
| SolidItem, | |
| Usage, | |
| WorkOnItem, | |
| ) | |
| EXAMPLES = Path(__file__).resolve().parents[1] / "examples" / "inputs" | |
| def example_names() -> list[str]: | |
| return sorted(p.stem for p in EXAMPLES.glob("*.json")) | |
| def load_example(name: str) -> dict: | |
| return json.loads((EXAMPLES / f"{name}.json").read_text(encoding="utf-8")) | |
| def measurements(discipline="hitting", fps=240.0, level="hs_varsity", series=None, capture=None, **extra) -> dict: | |
| """A measurements-only session. `series` maps metric key -> (unit, confidence, [value per rep]).""" | |
| series = series or {} | |
| n = max((len(v[2]) for v in series.values()), default=0) | |
| reps = [ | |
| { | |
| "rep": i + 1, | |
| "metrics": [ | |
| { | |
| "key": key, | |
| "value": vals[i], | |
| "unit": unit, | |
| "confidence": conf, | |
| **({"note": "n/a"} if vals[i] is None else {}), | |
| } | |
| for key, (unit, conf, vals) in series.items() | |
| ], | |
| } | |
| for i in range(n) | |
| ] | |
| return { | |
| "schema_version": "2.0", | |
| "discipline": discipline, | |
| "view": "face_on" if discipline == "hitting" else "open_side", | |
| "fps": fps, | |
| "level": level, | |
| "capture": capture or {"ok": True, "reasons": []}, | |
| "reps": reps, | |
| **extra, | |
| } | |
| def make_input(**overrides) -> CoachInput: | |
| """A small valid hitting input: one supported problem (over_stride), one in-range metric, one estimate.""" | |
| base = dict( | |
| discipline="hitting", | |
| level="hs_varsity", | |
| fps=240.0, | |
| fps_class="high_speed", | |
| reps_analyzed=8, | |
| capture=CaptureInput(ok=True), | |
| metrics=[ | |
| MetricInput( | |
| key="stride_pct_height", | |
| label="Stride length", | |
| value=58.2, | |
| unit="%", | |
| confidence="high", | |
| band=(43.0, 51.0), | |
| zone="outside_typical_range", | |
| n_reps=8, | |
| per_rep=[57.0, 58.0, 59.0, 58.5, 57.5, 58.8, 59.1, 58.2], | |
| range_status="unverified", | |
| ), | |
| MetricInput( | |
| key="head_movement_pct_height", | |
| label="Head movement", | |
| value=2.1, | |
| unit="%", | |
| confidence="high", | |
| band=(0.0, 5.0), | |
| zone="in_range", | |
| n_reps=8, | |
| per_rep=[2.0, 2.2, 2.1, 2.0, 2.3, 2.1, 1.9, 2.1], | |
| range_status="unverified", | |
| ), | |
| MetricInput( | |
| key="hip_shoulder_separation_foot_plant_deg", | |
| label="Hip and shoulder separation", | |
| value=41.0, | |
| unit="deg", | |
| confidence="est", | |
| band=(-23.0, -3.0), | |
| zone="reference_only", | |
| n_reps=8, | |
| per_rep=[41.0] * 8, | |
| range_status="unverified", | |
| ), | |
| ], | |
| problems=[ | |
| ProblemInput( | |
| key="over_stride", | |
| label="Front foot lands too far out", | |
| what="Your front foot lands too far out.", | |
| why="A long step pulls your weight forward.", | |
| cue="Take a short, quiet step.", | |
| severity="major", | |
| frequency=0.75, | |
| reps_showing=6, | |
| reps_evaluated=8, | |
| median_excess=1.2, | |
| evidence=["stride_pct_height"], | |
| baseline_rank=1, | |
| drills=[ | |
| DrillInput(name="Short Step Tee", rep_scheme="3x8", cue="Short step, stay tall."), | |
| DrillInput(name="No-Stride Tee", rep_scheme="3x8", cue="Turn, don't reach."), | |
| ], | |
| ), | |
| ], | |
| ) | |
| base.update(overrides) | |
| return CoachInput(**base) | |
| def second_problem() -> ProblemInput: | |
| return ProblemInput( | |
| key="head_drift", | |
| label="Head moves during the swing", | |
| what="Your head moves during the swing.", | |
| why="Moving eyes make the ball harder to track.", | |
| cue="Keep your eyes quiet.", | |
| severity="minor", | |
| frequency=0.5, | |
| reps_showing=4, | |
| reps_evaluated=8, | |
| median_excess=0.3, | |
| evidence=["head_movement_pct_height"], | |
| baseline_rank=2, | |
| drills=[DrillInput(name="Quiet Head Tee", rep_scheme="3x8", cue="Eyes on the spot.")], | |
| ) | |
| def good_note(**overrides) -> CoachNote: | |
| """A note that passes every guardrail for make_input().""" | |
| data = dict( | |
| headline="Your head stays quiet. One step change can help.", | |
| looks_solid=[SolidItem(metric_key="head_movement_pct_height", text="Your head stays quiet during the swing.")], | |
| work_on=[ | |
| WorkOnItem( | |
| fault_key="over_stride", | |
| evidence=["stride_pct_height"], | |
| text="Your stride is longer than the typical range in 75% of swings. A long step pulls your weight forward.", | |
| ) | |
| ], | |
| cue="Take a short, quiet step.", | |
| drill={"name": "Short Step Tee", "how": "Do 3x8 swings with a quiet step."}, | |
| caveats=["The typical ranges are drafts that your coach should confirm."], | |
| ) | |
| data.update(overrides) | |
| return CoachNote(**data) | |
| class FakeGenerator: | |
| """Scripted stand-in for GeminiGenerator. Each script item is a CoachNote, a GenerationError or a callable.""" | |
| def __init__(self, script): | |
| self.script = deque(script) | |
| self.calls: list[dict] = [] | |
| def generate(self, session_json: str, *, model: str, repair_hint: str | None = None, run_metadata=None) -> GenerationResult: | |
| self.calls.append( | |
| {"model": model, "repair_hint": repair_hint, "session_json": session_json, "run_metadata": run_metadata} | |
| ) | |
| item = self.script.popleft() | |
| if isinstance(item, GenerationError): | |
| raise item | |
| note = item() if callable(item) else item | |
| return GenerationResult(note=note, usage=Usage(input_tokens=1000, output_tokens=300), latency_ms=5) | |
| def example_note(name): | |
| """A guardrail-clean note for a real example (the rule-based note is valid by construction).""" | |
| return build_fallback_note(build_coach_input(load_example(name))) | |