File size: 15,239 Bytes
6963661
 
7bf5a7e
66d2e51
2756f0f
 
 
 
66d2e51
be69d1e
 
 
 
2756f0f
 
 
be69d1e
2756f0f
6963661
2756f0f
 
 
 
7a3215f
6963661
e980186
2756f0f
 
ae2c68f
be69d1e
7a3215f
be69d1e
a8788e5
be69d1e
2756f0f
 
be69d1e
2756f0f
 
 
 
 
 
 
be69d1e
 
2756f0f
 
 
 
 
 
 
 
 
 
 
6963661
2756f0f
 
 
7a3215f
 
 
 
 
 
 
 
 
 
6963661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf5a7e
6963661
 
 
2756f0f
be69d1e
 
2756f0f
 
 
be69d1e
 
 
 
 
 
 
2756f0f
be69d1e
 
 
6963661
be69d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e980186
be69d1e
 
 
 
 
 
 
 
 
 
 
 
6963661
f9655f6
 
66d2e51
19d2582
 
 
 
 
 
 
 
 
 
 
66d2e51
 
19d2582
 
 
 
 
 
 
 
 
 
 
 
6963661
be69d1e
2756f0f
 
 
 
 
6963661
 
2756f0f
6963661
2756f0f
6963661
 
 
 
 
 
2756f0f
 
 
 
 
6963661
 
66d2e51
 
2756f0f
 
ae2c68f
fe40b87
6c0b843
2756f0f
be69d1e
 
 
 
 
 
 
 
 
 
2756f0f
 
6963661
e980186
2756f0f
 
 
be69d1e
 
 
e980186
 
 
 
 
 
 
 
 
 
 
 
 
 
be69d1e
6963661
be69d1e
6963661
 
 
2756f0f
 
ae2c68f
be69d1e
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
"""H1: validate the ML payload, build the swing or pitch report with the ai_coach library and save both on the session.

Hitting sessions (mode "h") take swing contract 1.0/1.1; pitching sessions (mode "p") take pitch-1.1.
Pitch-1.1 coaching uses only structured ML evidence.

Revision rules: the same analysis_id and revision returns the stored report (no rebuild, no model call); a lower
revision is refused (STALE_REVISION); a higher one rebuilds and replaces; another analysis_id is refused
(ANALYSIS_MISMATCH). Only the first report of a session counts toward the plan.
An obsolete pitch-1.1 report is rebuilt from the same saved measurements to remove legacy visual coaching.

With queue=True (the endpoints' default) the same checks run in the request, but the build is left to the report
worker (queue.py): the
payload is stored on the session, the request returns at once and the owner is notified when the report is saved.
"""

import asyncio
import logging
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from uuid import UUID

from ai_coach.config import get_settings as get_coach_settings
from ai_coach.pitch_report import build_pitch_report, validate_pitch_payload
from ai_coach.swing_report import AthleteContext, InvalidPayload, PreviousSession, build_report, validate_payload
from sqlalchemy.ext.asyncio import AsyncSession

from app.common.consent import analysis_consent_blocked
from app.common.notify import notify
from app.core.config import get_settings
from app.core.errors import Conflict, Forbidden, NotFound, PlanLimitReached, ServiceUnavailable, Unprocessable
from app.integrations.pitching_reports import obsolete_pitch_coaching
from app.integrations.push import PushClient
from app.modules.accounts.models import Account
from app.modules.billing.entitlement import EntitlementService
from app.modules.sessions.models import SwingSession
from app.modules.swing_reports.repository import SwingReportRepository

LEVELS = ("youth", "high_school", "college", "adult")
HANDS = {"R": "right", "L": "left"}

ReportBuilder = Callable[..., dict]

log = logging.getLogger(__name__)


def athlete_context(snapshot: dict | None) -> AthleteContext:
    """Session athlete snapshot -> library context. Switch hitters (S) have no fixed side; the payload says which."""
    snapshot = snapshot or {}
    level = snapshot.get("level")
    height = snapshot.get("height_cm")
    try:
        height_cm = float(height) if height is not None else None
    except (TypeError, ValueError):
        height_cm = None
    return AthleteContext(batting_hand=HANDS.get(snapshot.get("bats")),  # type: ignore[arg-type]
                          throwing_hand=HANDS.get(snapshot.get("throws")),  # type: ignore[arg-type]
                          level=level if level in LEVELS else None, height_cm=height_cm)


def ensure_coach_configured() -> None:
    """The coaching text must come from Gemini: a missing key is a configuration error, never a silent fallback.

    Tests (ENV=test) are exempt so they never call the model.
    """
    if get_settings().env != "test" and not get_coach_settings().llm_enabled:
        raise ServiceUnavailable("The AI coach is not configured. Please try again later.",
                                 code="COACH_NOT_CONFIGURED")


def swing_marks(events: Any) -> dict:
    """Hitting events -> the session marks the app draws on the clip."""
    marks: dict = {}
    for event_name, mark_name in (("stride_start", "stride_start_frame"),
                                  ("front_foot_down", "stride_end_frame"), ("contact", "contact_frame")):
        event = getattr(events, event_name)
        if event.status != "unavailable" and event.source_frame_index is not None:
            marks[mark_name] = event.source_frame_index
            if event_name == "contact":
                marks["contact_offset"] = 0
                marks["contact_source"] = "manual" if event.source == "manual_review" else "detected"
    return marks


def pitch_marks(events: Any) -> dict:
    """Pitching events -> session marks (peak_knee_height_frame, foot_plant_frame, ball_release_frame)."""
    marks: dict = {}
    if hasattr(events, "release"):
        # Null overwrites an earlier mark when a reviewed revision removes it.
        return {f"{name}_frame": getattr(events, name).source_frame_index
                for name in ("leg_lift", "foot_strike", "release")}
    for event_name in ("peak_knee_height", "foot_plant", "ball_release"):
        event = getattr(events, event_name)
        if event is not None and event.status != "unavailable" and event.source_frame_index is not None:
            marks[f"{event_name}_frame"] = event.source_frame_index
    return marks


@dataclass(frozen=True)
class ReportKind:
    mode: str  # session mode this report is for
    validate: Callable[[Any], tuple[Any, dict[str, str]]]
    contract: str  # named in the INVALID_PAYLOAD message
    mode_message: str
    marks: Callable[[Any], dict]


SWING = ReportKind(mode="h", validate=validate_payload, contract="swing analysis contract 1.0 or 1.1",
                   mode_message="Swing reports are for hitting sessions.", marks=swing_marks)
PITCH = ReportKind(mode="p", validate=validate_pitch_payload, contract="pitch analysis contract pitch-1.1",
                   mode_message="Pitch reports are for pitching sessions.", marks=pitch_marks)


class SwingReportService:
    def __init__(self, db: AsyncSession, builder: ReportBuilder | None = None,
                 pitch_builder: ReportBuilder | None = None):
        self.db = db
        self.sessions = SwingReportRepository(db)
        self.entitlements = EntitlementService(db)
        self.builder = builder or build_report
        self.pitch_builder = pitch_builder or build_pitch_report

    async def create(self, account: Account, session_id: UUID, payload: Any, request_id: str | None,
                     *, queue: bool = False) -> dict | None:
        """The report, or None when it was queued (queue=True and a build is needed)."""
        return await self._create(SWING, self.builder, account, session_id, payload, request_id, queue)

    async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None,
                           *, queue: bool = False) -> dict | None:
        return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id, queue)

    async def build_next_queued(self, push: PushClient | None) -> bool:
        """Worker step: build the oldest queued report, save it and tell the owner. False when nothing is queued.

        The row stays locked for the whole build, so a crash leaves the session queued for the next worker.
        """
        session = await self.sessions.next_queued()
        if session is None:
            return False
        kind, builder = (PITCH, self.pitch_builder) if session.mode == "p" else (SWING, self.builder)
        payload, noun = session.queued_payload, "pitch" if session.mode == "p" else "swing"
        try:
            parsed, problems = kind.validate(payload)
            if parsed is None:
                raise InvalidPayload(problems)
            report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete),
                                             request_id=f"queue-{session.id}", **await self._history(session, payload))
        except Exception:
            # Failed builds leave the queue, so one bad payload cannot block it; the app posts again to retry.
            log.exception("queued report for session %s failed", session.id)
            await self.sessions.update(session, queued_payload=None, report_error="REPORT_FAILED")
            outcome, title, body = "failed", f"We couldn't finish your {noun} report", "Open the app to try again."
        else:
            await self._save(session, kind, parsed, payload, report)
            outcome, title, body = "ready", f"Your {noun} report is ready", "Tap to see your score and focus."
        await notify(self.db, push, session.owner_id, kind="result", title=title, body=body,
                     target={"session_id": session.id, "mode": session.mode, "outcome": outcome},
                     event_key=f"report:{session.id}:{(payload or {}).get('analysis_revision')}:{outcome}")
        return True

    async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None,
                                   *, refresh: bool = False) -> dict:
        """Retry unavailable/obsolete text without rerunning ML or consuming another analysis."""
        session = await self.sessions.get_for_update(session_id)
        if session is None:
            raise NotFound("We couldn't find that session.")
        if session.owner_id != account.id:
            raise Forbidden()
        if session.mode != "p":
            raise Unprocessable("Pitch coaching is for pitching sessions.", code="MODE_NOT_SUPPORTED")
        if not session.report or not session.measurement_payload:
            raise Conflict("Complete the motion analysis first.", code="REPORT_NOT_READY")
        if session.measurement_payload.get("schema_version") != "pitch-1.1":
            raise Unprocessable("This saved report does not support coaching retry.", code="MODE_NOT_SUPPORTED")
        if ((session.report.get("coaching") or {}).get("status") == "generated"
                and not refresh and not obsolete_pitch_coaching(session.report)):
            return session.report
        if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
            raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
        ensure_coach_configured()
        try:
            report = await asyncio.to_thread(self.pitch_builder, session.measurement_payload,
                                             athlete_context(session.athlete), request_id=request_id)
        except InvalidPayload as exc:
            raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc
        await self.sessions.update(session, report=report)
        return report

    async def _create(self, kind: ReportKind, builder: ReportBuilder, account: Account, session_id: UUID,
                      payload: Any, request_id: str | None, queue: bool = False) -> dict | None:
        session = await self.sessions.get_for_update(session_id)
        if session is None:
            raise NotFound("We couldn't find that session.")
        if session.owner_id != account.id:
            raise Forbidden()
        if session.mode != kind.mode:
            raise Unprocessable(kind.mode_message, code="MODE_NOT_SUPPORTED")
        # Validation is cheap and runs first, so a broken payload never reaches the plan check or the model.
        parsed, problems = kind.validate(payload)
        if parsed is None:
            raise Unprocessable(f"The payload does not follow {kind.contract}.", code="INVALID_PAYLOAD",
                                fields=problems)

        evidence_pitch = kind.mode == "p" and parsed.schema_version == "pitch-1.1"
        if evidence_pitch and parsed.pitch_id != str(session_id):
            raise Unprocessable("The pitch ID must match this session.", code="PITCH_ID_MISMATCH")

        if session.report is not None:
            if session.analysis_id != parsed.analysis_id:
                raise Conflict("This session already has a report for a different analysis.", code="ANALYSIS_MISMATCH")
            if parsed.analysis_revision == session.analysis_revision:
                if evidence_pitch and session.measurement_payload != payload:
                    raise Conflict("This revision already has a different payload.", code="REVISION_PAYLOAD_MISMATCH")
                if not evidence_pitch or not obsolete_pitch_coaching(session.report):
                    return session.report
            if parsed.analysis_revision < (session.analysis_revision or 0):
                raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION")
        if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
            raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
        ensure_coach_configured()
        if session.analyzed_at is None:
            entitlement = await self.entitlements.get(account.id)
            # Queued first reports have not been counted yet, so they are reserved here.
            # shortcut: two posts for different sessions at the same instant can each take the last analysis;
            # lock the account row here if the limit must be exact.
            waiting = await self.sessions.queued_first_reports(account.id, session.id) if queue else 0
            if entitlement.left is not None and entitlement.left - waiting <= 0:
                raise PlanLimitReached()
        if queue:
            await self.sessions.update(session, queued_payload=payload, report_error=None)
            return None

        try:
            report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete),
                                             request_id=request_id, **await self._history(session, payload))
        except InvalidPayload as exc:  # defensive: the builder re-validates
            raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc

        await self._save(session, kind, parsed, payload, report)
        return report

    async def _history(self, session: SwingSession, payload: Any) -> dict:
        """Builder arguments for "since last time" wording: the player's previous hitting report for the same drill.

        Only for the account's own reps: a rep recorded for someone else does not say reliably who the athlete is.
        """
        if session.mode != "h" or not session.is_self:
            return {}
        practice_type = ((payload or {}).get("context") or {}).get("practice_type")
        previous = await self.sessions.previous_report(session, practice_type)
        if previous is None:
            return {}
        return {"previous": PreviousSession(report=previous.report,
                                            days_ago=(session.created_at - previous.created_at).days)}

    async def _save(self, session: SwingSession, kind: ReportKind, parsed: Any, payload: Any, report: dict) -> None:
        marks = {**(session.marks or {}), **kind.marks(parsed.events)}
        if kind.mode == "p" and parsed.schema_version == "pitch-1.1":
            for key in ("contact_frame", "contact_offset", "contact_source", "stride_start_frame", "stride_end_frame",
                        "peak_knee_height_frame", "foot_plant_frame", "ball_release_frame"):
                marks.pop(key, None)
        await self.sessions.update(
            session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id,
            analysis_revision=parsed.analysis_revision, marks=marks,
            analyzed_at=session.analyzed_at or datetime.now(UTC), queued_payload=None, report_error=None)