File size: 3,837 Bytes
35e80ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""Regenerate docs/examples/responses/*.json: real API responses (v2.0) for every screen state, for the frontend engineer.

They are produced by the real code from the sessions in examples/inputs (rule-based text, so no API key and no cost; the model's
sentences read a little more varied but have the same shape). request_id, latency and prompt_version are fixed so the files
only change when the response itself changes. `tests/test_response_examples.py` fails if they are out of date.

    python tools/build_response_examples.py
"""

import json
from pathlib import Path

from ai_coach.config import Settings
from ai_coach.service import CoachService

ROOT = Path(__file__).resolve().parents[1]
INPUTS = ROOT / "examples" / "inputs"
OUT = ROOT / "docs" / "examples" / "responses"


def load(name: str) -> dict:
    return json.loads((INPUTS / f"{name}.json").read_text(encoding="utf-8"))


def timing(reps: list[dict], fps: float | None = 240.0) -> dict:
    return {
        "schema_version": "3.1",
        "discipline": "hitting",
        "capture": {"capture_fps": fps, "time_source": "original_pts"},
        "reps": reps,
    }


def tmetrics(load_ms: float, foot_ms: float) -> list[dict]:
    est = {"unit": "ms", "status": "estimated", "confidence": "est"}
    return [
        {"key": "load_to_swing_ms", "value": load_ms, **est},
        {"key": "foot_down_to_swing_ms", "value": foot_ms, **est, "order_resolved": True},
        {
            "key": "swing_duration_ms",
            "value": None,
            "unit": "ms",
            "status": "unclear",
            "reason_codes": ["actual_end_unavailable"],
        },
        {"key": "early_late_shift_ms", "value": None, "unit": "ms", "status": "unclear", "reason_codes": ["outcome_unknown"]},
    ]


def tee_swings(loads: list[int]) -> list[dict]:
    return [
        {
            "rep": i + 1,
            "outcome": "unknown",
            "stepped": True,
            "context": {"practice_type": "tee"},
            "frame_interval_ms": {"median": 4.17},
            "metrics": tmetrics(v, 60 + 5 * i),
        }
        for i, v in enumerate(loads)
    ]


def scenarios() -> dict[str, dict]:
    hitting_with_timing = load("hitting_stride_and_lunging_240fps")
    hitting_with_timing.update(session_id="sess_001", timing=timing(tee_swings([310, 340, 295, 330, 300, 325])))
    pitching = load("pitching_short_stride_hs_rough_range_240fps")
    pitching["arm_care"] = {
        "known": True,
        "pitch_count_today": 42,
        "daily_max": 95,
        "next_eligible_date": "2026-10-13",
        "alerts": [],
    }
    record_again = load("hitting_ok_240fps")
    record_again["capture"] = {"ok": False, "reasons": ["too_dark"]}
    return {
        "hitting_with_timing": hitting_with_timing,
        "hitting_clean": load("hitting_ok_240fps"),
        "pitching_arm_care": pitching,
        "record_again": record_again,
        "score_withheld_low_fps": load("hitting_30fps_geometry_only"),
        "timing_only": timing(tee_swings([310])[:1], fps=None) | {"time_basis": "capture"},
    }


def build() -> dict[str, str]:
    service = CoachService(Settings(_env_file=None, google_api_key=None, cache_enabled=False, log_to_console=False))
    out = {}
    for name, session in scenarios().items():
        data = service.respond(session).model_dump(mode="json")
        data["request_id"] = "req_example"
        data["meta"].update(latency_ms=None, prompt_version="example")
        out[f"{name}.json"] = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
    return out


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    for filename, text in build().items():
        (OUT / filename).write_text(text, encoding="utf-8")
    print(f"{len(build())} response examples written to {OUT}")


if __name__ == "__main__":
    main()