Spaces:
Running on T4
Running on T4
Download backend/app/modules/threads/service.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/threads/service.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/threads/service.py
-
curl -L -o service.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/threads/service.py
17.3 kB
| """Conversations between a player and their coaches (N10-N15). | |
| Access: the player of a thread, or staff of the thread's academy who can see its player (CurrentStaff rules, so | |
| paused or removed members lose access). Only the thread's own coach moves the coach read watermark. Anything else | |
| is a 404. Read state is one watermark per side on Message.seq; | |
| Thread.last_seq is the counter, incremented under a row lock. | |
| Every change is also announced to connected sockets after commit (live.py): new messages automatically, read marks | |
| and new threads through live.announce. | |
| """ | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from uuid import UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.common.academy_access import ( | |
| Staff, | |
| can_see_player, | |
| require_player, | |
| sessions_shared, | |
| staff_context, | |
| visible_players_query, | |
| ) | |
| from app.common.labels import drill_catalog, tone | |
| from app.common.media import upload_ref | |
| from app.common.notify import notify | |
| from app.common.schemas import MediaRef, Page | |
| from app.common.uploads import UploadErrors, claim_upload | |
| from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable | |
| from app.core.pagination import PageParams, paginate | |
| from app.integrations.push import PushClient | |
| from app.integrations.storage import StorageClient | |
| from app.modules.accounts.models import Account | |
| from app.modules.reviews.models import Review | |
| from app.modules.sessions.models import SwingSession | |
| from app.modules.threads import live | |
| from app.modules.threads.models import Message, Thread | |
| from app.modules.threads.repository import ThreadRepository | |
| from app.modules.threads.schemas import ( | |
| EnsureThreadIn, | |
| Finding, | |
| ImageMessageOut, | |
| MessageIn, | |
| ReviewMessageOut, | |
| SendResult, | |
| SessionMessageOut, | |
| TextMessageOut, | |
| ThreadOut, | |
| VideoMessageOut, | |
| VoiceMessageOut, | |
| ) | |
| from app.modules.uploads.models import Upload | |
| LIST_MESSAGES = 20 # messages included per thread in the list | |
| # message kind -> (upload kind it must reference, notification preview) | |
| MEDIA_KINDS = {"voice": ("audio", "Sent a voice message."), "image": ("image", "Sent a photo."), | |
| "video": ("video", "Sent a video.")} | |
| _SESSION_WORD = {"h": "Swing", "p": "Pitch"} | |
| class Access: | |
| thread: Thread | |
| side: str # player | coach | |
| staff: Staff | None | |
| class ThreadService: | |
| def __init__(self, db: AsyncSession, storage: StorageClient, push: PushClient | None = None): | |
| self.db = db | |
| self.repo = ThreadRepository(db) | |
| self.storage = storage | |
| self.push = push | |
| # ---------- access ---------- | |
| async def _access(self, account: Account, thread: Thread | None) -> Access: | |
| if thread is None: | |
| raise NotFound() | |
| if thread.player_id == account.id: | |
| return Access(thread, "player", None) | |
| staff = await staff_context(self.db, account) | |
| if (staff is not None and staff.team_id is not None and thread.team_id == staff.team_id | |
| and await can_see_player(self.db, staff, thread.player_id)): | |
| return Access(thread, "coach", staff) | |
| raise NotFound() | |
| async def _load(self, account: Account, thread_id: UUID, *, lock: bool = False) -> Access: | |
| thread = await (self.repo.locked(thread_id) if lock else self.repo.get(thread_id)) | |
| return await self._access(account, thread) | |
| async def can_access(self, account: Account, thread: Thread) -> bool: | |
| try: | |
| await self._access(account, thread) | |
| except NotFound: | |
| return False | |
| return True | |
| async def live_event(self, kind: str, thread: Thread, message_id: UUID | None) -> dict: | |
| """The data of one socket event, in the same shapes the reads return.""" | |
| if kind == "thread.new": | |
| return {"thread": (await self._render([thread], LIST_MESSAGES))[0]} | |
| data: dict = {"thread_id": thread.id, "thread_status": thread.status, "updated_at": thread.updated_at, | |
| "unread_for_player": thread.last_seq > thread.player_read_seq, | |
| "unread_for_coach": thread.last_seq > thread.coach_read_seq} | |
| message = await self.repo.message(message_id) if message_id else None | |
| if message is not None: | |
| data["message"] = (await self._render_messages(thread, [message]))[0] | |
| return data | |
| # ---------- reads ---------- | |
| async def list_threads(self, account: Account, paging: PageParams, *, mode: str | None, player_id: UUID | None, | |
| unread: bool | None) -> Page[ThreadOut]: | |
| staff = await staff_context(self.db, account) | |
| if staff is None and player_id is not None and player_id != account.id: | |
| player_id = None # a player cannot widen their scope | |
| scoped = staff if staff is not None and staff.team_id is not None else None | |
| visible = visible_players_query(scoped) if scoped else None | |
| cursor = paging.cursor | |
| rows = await self.repo.run(self.repo.list_query( | |
| player_id=account.id, staff_id=scoped.id if scoped else None, | |
| team_id=scoped.team_id if scoped else None, visible=visible, mode=mode, | |
| filter_player_id=player_id, unread=unread, cursor_at=cursor.created_at if cursor else None, | |
| cursor_id=cursor.id if cursor else None, limit=paging.limit + 1)) | |
| page, next_cursor = paginate(rows, paging.limit, lambda t: (t.updated_at, t.id)) | |
| out = await self._render(page, LIST_MESSAGES) | |
| return Page[ThreadOut](items=out, next_cursor=next_cursor) | |
| async def get(self, account: Account, thread_id: UUID, cursor: str | None, limit: int) -> ThreadOut: | |
| access = await self._load(account, thread_id) | |
| return (await self._render([access.thread], limit, before_seq=_seq(cursor)))[0] | |
| async def for_session(self, account: Account, session_id: UUID) -> ThreadOut: | |
| session = await self.repo.session_row(session_id) | |
| try: | |
| if session is None or session.deleted_at is not None: | |
| raise NotFound() | |
| access = await self._access(account, await self.repo.for_session(session_id)) | |
| except NotFound: | |
| raise NotFound("No conversation for this session.", code="THREAD_NOT_FOUND") from None | |
| return (await self._render([access.thread], LIST_MESSAGES))[0] | |
| # ---------- writes ---------- | |
| async def mark_read(self, account: Account, thread_id: UUID, last_message_id: UUID | None) -> None: | |
| access = await self._load(account, thread_id) | |
| if last_message_id is None: | |
| return | |
| if access.side == "coach" and account.id != access.thread.coach_id: | |
| return # the watermark belongs to the thread's own coach | |
| message = await self.repo.message(last_message_id) | |
| if message is None or message.thread_id != thread_id: | |
| raise Unprocessable("That message is not in this conversation.", code="MESSAGE_NOT_IN_THREAD") | |
| await self.repo.advance_read(thread_id, access.side, message.seq) | |
| live.announce(self.db, "thread.read", thread_id) | |
| async def send(self, account: Account, thread_id: UUID, body: MessageIn) -> SendResult: | |
| access = await self._load(account, thread_id, lock=True) | |
| thread = access.thread | |
| if access.staff is not None: | |
| access.staff.require("review") | |
| values: dict = {"kind": body.kind} | |
| preview = "" | |
| if body.kind == "text": | |
| values["text"] = body.text | |
| preview = body.text | |
| elif body.kind in MEDIA_KINDS: | |
| upload_kind, preview = MEDIA_KINDS[body.kind] | |
| await self._claim_media(account, body.upload_id, upload_kind) | |
| values.update(upload_id=body.upload_id, seconds=getattr(body, "seconds", None)) | |
| else: | |
| await self._check_session(access, body.session_id) | |
| values["session_id"] = body.session_id | |
| preview = "Shared a session." | |
| now = datetime.now(UTC) | |
| seq = thread.last_seq + 1 | |
| message = await self.repo.add_message(thread_id=thread.id, seq=seq, author_id=account.id, created_at=now, | |
| **values) | |
| read = {"player_read_seq": seq} if access.side == "player" else ( | |
| {"coach_read_seq": seq} if account.id == thread.coach_id else {}) | |
| await self.repo.update(thread, last_seq=seq, updated_at=now, **read, | |
| status="waiting_for_coach" if access.side == "player" else "reviewed") | |
| recipient = thread.coach_id if access.side == "player" else thread.player_id | |
| if recipient is not None: | |
| await notify(self.db, self.push, recipient, kind="review", | |
| title=f"{account.name or 'Someone'} sent a message", body=preview, | |
| target={"thread_id": thread.id}, event_key=f"message:{message.id}") | |
| out = (await self._render_messages(thread, [message]))[0] | |
| return SendResult(message=out, thread_status=thread.status, updated_at=thread.updated_at) | |
| async def ensure_general(self, staff: Staff, player_id: UUID, body: EnsureThreadIn) -> tuple[ThreadOut, bool]: | |
| staff.require("review") | |
| player = await require_player(self.db, staff, player_id) | |
| thread = await self.repo.general(player.id, staff.id, body.mode) | |
| created = thread is None | |
| if thread is None: | |
| thread = await self.repo.create_general(team_id=staff.team_id, player_id=player.id, coach_id=staff.id, | |
| mode=body.mode, status="reviewed") | |
| if thread is None: # lost a race with a concurrent create | |
| thread = await self.repo.general(player.id, staff.id, body.mode) | |
| created = False | |
| else: | |
| live.announce(self.db, "thread.new", thread.id) | |
| return (await self._render([thread], LIST_MESSAGES))[0], created | |
| async def _claim_media(self, account: Account, upload_id: UUID, kind: str) -> None: | |
| await claim_upload( | |
| self.db, self.storage, upload_id, owner_id=account.id, kind=kind, | |
| errors=UploadErrors( | |
| invalid=Unprocessable(f"Not a valid {kind} upload.", code="INVALID_UPLOAD"), | |
| used=Unprocessable(f"This {kind} was already used.", code="UPLOAD_ALREADY_USED"), | |
| not_ready=Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY")), | |
| in_use=lambda: self.repo.upload_in_use(upload_id)) | |
| async def _check_session(self, access: Access, session_id: UUID) -> None: | |
| session = await self.repo.session_row(session_id) | |
| if session is None or session.deleted_at is not None or session.owner_id != access.thread.player_id: | |
| raise NotFound() | |
| if session.mode != access.thread.mode: | |
| raise Unprocessable("This session is for the other mode.", code="MODE_MISMATCH") | |
| if access.side == "coach" and not await sessions_shared(self.db, session.owner_id): | |
| raise Forbidden("This player does not share sessions with coaches.") | |
| # ---------- rendering ---------- | |
| async def _render(self, threads: list[Thread], per_thread: int, before_seq: int | None = None) -> list[ThreadOut]: | |
| if not threads: | |
| return [] | |
| grouped = await self.repo.latest_messages([t.id for t in threads], per_thread + 1, before_seq) | |
| cursors: dict[UUID, str | None] = {} | |
| for thread in threads: | |
| messages = grouped[thread.id] | |
| cursors[thread.id] = None | |
| if len(messages) > per_thread: | |
| messages = messages[1:] | |
| cursors[thread.id] = str(messages[0].seq) | |
| grouped[thread.id] = messages | |
| flat = [m for t in threads for m in grouped[t.id]] | |
| ctx = await self._context(threads, flat) | |
| out = [] | |
| for thread in threads: | |
| session, ordinal = ctx.sessions.get(thread.session_id, (None, 0)) if thread.session_id else (None, 0) | |
| score = session.overall_score if session else None | |
| label = _label(session, ordinal) if session else "Latest session" | |
| out.append(ThreadOut( # a deleted session renders as a tombstone: session_id null | |
| id=thread.id, mode=thread.mode, session_id=session.id if session else None, session_label=label, | |
| score=score, tone=tone(score), coach_id=thread.coach_id, | |
| coach_name=ctx.names.get(thread.coach_id, "") if thread.coach_id else "", | |
| player_id=thread.player_id, player_name=ctx.names.get(thread.player_id, ""), status=thread.status, | |
| unread_for_player=thread.last_seq > thread.player_read_seq, | |
| unread_for_coach=thread.last_seq > thread.coach_read_seq, updated_at=thread.updated_at, | |
| messages=[self._message(thread, m, ctx) for m in grouped[thread.id]], | |
| next_message_cursor=cursors[thread.id])) | |
| return out | |
| async def _render_messages(self, thread: Thread, messages: list[Message]): | |
| ctx = await self._context([thread], messages) | |
| return [self._message(thread, m, ctx) for m in messages] | |
| async def _context(self, threads: list[Thread], messages: list[Message]) -> "_Context": | |
| session_ids = {t.session_id for t in threads if t.session_id} | {m.session_id for m in messages if m.session_id} | |
| reviews = await self.repo.reviews({t.session_id for t in threads if t.session_id and any( | |
| m.thread_id == t.id and m.kind == "review" for m in messages)}) | |
| upload_ids = {m.upload_id for m in messages if m.upload_id} | { | |
| r.voice_upload_id for r in reviews.values() if r.voice_upload_id} | |
| return _Context( | |
| names=await self.repo.names({t.coach_id for t in threads if t.coach_id} | {t.player_id for t in threads}), | |
| sessions=await self.repo.session_infos(session_ids), reviews=reviews, | |
| uploads=await self.repo.uploads(upload_ids), storage=self.storage) | |
| def _message(self, thread: Thread, m: Message, ctx: "_Context"): | |
| common = {"id": m.id, "author_id": m.author_id, "from": "player" if m.author_id == thread.player_id | |
| else "coach", "at": m.created_at} | |
| if m.kind == "text": | |
| return TextMessageOut(**common, text=m.text or "") | |
| if m.kind == "voice": | |
| return VoiceMessageOut(**common, seconds=float(m.seconds or 0), | |
| audio=ctx.media(m.upload_id, float(m.seconds) if m.seconds else None)) | |
| if m.kind == "image": | |
| return ImageMessageOut(**common, media=ctx.media(m.upload_id, None)) | |
| if m.kind == "video": | |
| seconds = float(m.seconds or 0) | |
| return VideoMessageOut(**common, seconds=seconds, media=ctx.media(m.upload_id, seconds or None)) | |
| if m.kind == "session": | |
| session, ordinal = ctx.sessions.get(m.session_id, (None, 0)) | |
| return SessionMessageOut(**common, session_id=session.id if session else None, | |
| label=_label(session, ordinal) if session else None, | |
| score=session.overall_score if session else None) | |
| review = ctx.reviews.get(thread.session_id) | |
| session = ctx.sessions.get(thread.session_id, (None, 0))[0] | |
| if review is None: | |
| return ReviewMessageOut(**common, cue="", voice_seconds=None, audio=None, findings=[], drill_id=None, | |
| drill_name=None) | |
| common["at"] = review.updated_at | |
| seconds = float(review.voice_seconds) if review.voice_seconds is not None else None | |
| return ReviewMessageOut( | |
| **common, cue=review.cue, voice_seconds=seconds, audio=ctx.media(review.voice_upload_id, seconds), | |
| findings=_findings(review, session), drill_id=review.drill_id, | |
| drill_name=drill_catalog().get(review.drill_id, {}).get("name")) | |
| class _Context: | |
| names: dict[UUID, str] | |
| sessions: dict[UUID, tuple[SwingSession, int]] | |
| reviews: dict[UUID, Review] | |
| uploads: dict[UUID, Upload] | |
| storage: StorageClient | |
| def media(self, upload_id: UUID | None, seconds: float | None) -> MediaRef | None: | |
| upload = self.uploads.get(upload_id) if upload_id else None | |
| return upload_ref(self.storage, upload, seconds) | |
| def _label(session: SwingSession, ordinal: int) -> str: | |
| return f"{_SESSION_WORD.get(session.mode, 'Swing')} {ordinal}" | |
| def _findings(review: Review, session: SwingSession | None) -> list[Finding]: | |
| names = {m.get("metric_id"): m.get("display_name") or m.get("name") | |
| for m in ((session.report if session else None) or {}).get("measurements", [])} | |
| return [Finding(metric_id=k, name=names.get(k) or k.replace("_", " ").title(), verdict=v) | |
| for k, v in review.verdicts.items()] | |
| def _seq(cursor: str | None) -> int | None: | |
| if cursor is None: | |
| return None | |
| try: | |
| return int(cursor) | |
| except ValueError: | |
| from app.core.errors import ValidationFailed | |
| raise ValidationFailed(fields={"message_cursor": "Invalid cursor."}) from None | |