Spaces:
Running on T4
Running on T4
Download backend/app/modules/sessions/service.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/sessions/service.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/sessions/service.py
-
curl -L -o service.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/sessions/service.py
11.6 kB
| """Sessions (D2 to D5): create with mark validation, plan and media checks; read with access rules; list; delete.""" | |
| import logging | |
| import math | |
| from datetime import UTC, datetime, timedelta | |
| from uuid import UUID | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.common.academy_access import can_see_player, sessions_shared, staff_context | |
| from app.common.consent import analysis_consent_blocked | |
| from app.common.media import media_ref | |
| from app.common.schemas import Page | |
| from app.core.config import get_settings | |
| from app.core.errors import Forbidden, NotFound, Unprocessable, ValidationFailed | |
| from app.core.pagination import PageParams, paginate | |
| from app.integrations.pitching_reports import report_for_read | |
| from app.integrations.storage import StorageClient | |
| from app.modules.accounts.models import Account | |
| from app.modules.billing.entitlement import EntitlementService | |
| from app.modules.reviews.schemas import ReviewOut | |
| from app.modules.sessions.models import SwingSession | |
| from app.modules.sessions.repository import SessionRepository, SessionUploadRepository | |
| from app.modules.sessions.schemas import MediaOut, PitchMarksIn, PreviousOut, SessionIn, SessionOut | |
| from app.modules.sessions.summary import SessionSummary, load_summaries | |
| from app.modules.uploads.models import Upload | |
| MIN_DIRECTION_LENGTH = 0.08 | |
| def _num(value) -> float | None: | |
| return float(value) if value is not None else None | |
| def validate_marks(body: SessionIn) -> None: | |
| """Field errors for the cross-field rules that the request model cannot express.""" | |
| settings = get_settings() | |
| errors: dict[str, str] = {} | |
| if body.duration_sec > settings.max_video_seconds: | |
| errors["duration_sec"] = f"Clips can be at most {settings.max_video_seconds:g} seconds." | |
| last_frame = (body.frame_count or round(body.duration_sec * body.fps)) - 1 | |
| marks = body.marks | |
| pitching = isinstance(marks, PitchMarksIn) | |
| names = (("leg_lift_frame", "foot_strike_frame", "release_frame") if pitching | |
| else ("stride_start_frame", "stride_end_frame", "contact_frame")) | |
| present = [(name, getattr(marks, name)) for name in names if getattr(marks, name) is not None] | |
| for name, value in present: | |
| if value > last_frame: | |
| errors[f"marks.{name}"] = f"Must be within 0..{last_frame}." | |
| for (previous, a), (name, b) in zip(present, present[1:], strict=False): | |
| if a >= b: | |
| errors.setdefault(f"marks.{name}", f"Must be after {previous}.") | |
| direction = None if pitching else marks.pitcher_direction | |
| if direction is not None and math.dist(direction.from_, direction.to) < MIN_DIRECTION_LENGTH: | |
| errors["marks.pitcher_direction"] = "The arrow must be at least 8% of the frame long." | |
| if body.is_self and body.athlete is not None: | |
| errors["athlete"] = "Must be null for your own rep." | |
| if not body.is_self and body.athlete is None: | |
| errors["athlete"] = "Required for someone else's rep." | |
| if errors: | |
| raise ValidationFailed(fields=errors) | |
| def profile_snapshot(account: Account) -> dict: | |
| return {"name": account.name, "age": account.age, "height_cm": _num(account.height_cm), | |
| "weight_kg": _num(account.weight_kg), "bats": account.bats, "throws": account.throws, | |
| "level": account.level} | |
| log = logging.getLogger(__name__) | |
| BODY_DATA_KEYS = ("age", "height_cm", "weight_kg") | |
| def _without_body_data(athlete: dict) -> dict: | |
| """Coaches see scores and targets, never the athlete's body data.""" | |
| return {k: v for k, v in athlete.items() if k not in BODY_DATA_KEYS} | |
| VIDEO_BOX_TYPES = (b"ftyp", b"moov", b"wide", b"mdat", b"free", b"skip") # first box of an MP4 / QuickTime file | |
| def _looks_like(kind: str, head: bytes) -> bool: | |
| """Cheap content check: the file must start like the type it claims to be.""" | |
| if kind == "thumbnail": | |
| return head.startswith(b"\xff\xd8\xff") | |
| return head[4:8] in VIDEO_BOX_TYPES | |
| class SessionService: | |
| def __init__(self, db: AsyncSession, storage: StorageClient): | |
| self.db = db | |
| self.sessions = SessionRepository(db) | |
| self.uploads = SessionUploadRepository(db) | |
| self.storage = storage | |
| # D2 | |
| async def create(self, account: Account, body: SessionIn) -> SessionOut: | |
| validate_marks(body) | |
| 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") | |
| await EntitlementService(self.db).ensure_can_analyze(account.id) | |
| video = await self._claimable(account, body.video_upload_id, "video", "video_upload_id") | |
| thumb = None | |
| if body.thumbnail_upload_id: | |
| thumb = await self._claimable(account, body.thumbnail_upload_id, "thumbnail", "thumbnail_upload_id") | |
| for upload in (video, thumb): | |
| if upload: | |
| await self._verify_object(upload) | |
| now = datetime.now(UTC) | |
| for upload in (video, thumb): | |
| if upload: | |
| await self.uploads.update(upload, attached_at=now) | |
| athlete = profile_snapshot(account) if body.is_self else body.athlete.model_dump() | |
| session = await self.sessions.create( | |
| owner_id=account.id, is_self=body.is_self, athlete=athlete, mode=body.mode, | |
| video_upload_id=video.id, thumbnail_upload_id=thumb.id if thumb else None, | |
| duration_sec=body.duration_sec, fps=body.fps, marks=body.marks.model_dump(mode="json", by_alias=True)) | |
| return await self._out(session) | |
| async def _claimable(self, account: Account, upload_id: UUID, kind: str, field: str) -> Upload: | |
| upload = await self.uploads.get(upload_id) | |
| if upload is None or upload.owner_id != account.id or upload.kind != kind: | |
| raise ValidationFailed(fields={field: f"Not one of your {kind} uploads."}) | |
| if upload.attached_at is not None: | |
| raise ValidationFailed(fields={field: "This upload is already used by a session."}) | |
| return upload | |
| async def _verify_object(self, upload: Upload) -> None: | |
| info = await self.storage.head(upload.object_key) | |
| if info is None: | |
| raise Unprocessable("The upload has not finished. Please try again.", code="UPLOAD_MISSING") | |
| settings = get_settings() | |
| limit = settings.max_video_bytes if upload.kind == "video" else settings.max_thumbnail_bytes | |
| if (info.size_bytes > limit or info.content_type != upload.content_type | |
| or not _looks_like(upload.kind, await self.storage.read_prefix(upload.object_key, 16))): | |
| await self.storage.delete_many([upload.object_key]) | |
| raise Unprocessable("The uploaded file is not valid. Please record again.", code="UPLOAD_INVALID") | |
| if info.size_bytes != upload.size_bytes: | |
| await self.uploads.update(upload, size_bytes=info.size_bytes) | |
| # D3 | |
| async def get(self, viewer: Account, session_id: UUID) -> SessionOut: | |
| session = await self.sessions.get_live(session_id) | |
| if session is None: | |
| raise NotFound() | |
| is_owner = session.owner_id == viewer.id | |
| if not is_owner: | |
| # Staff who can see the player see their own analysed reps, unless the player hid sessions from | |
| # coaches (coach_can_see_sessions); private_videos does not block the coach. | |
| staff = await staff_context(self.db, viewer) if session.is_self and session.analyzed_at else None | |
| allowed = (staff is not None and await can_see_player(self.db, staff, session.owner_id) | |
| and await sessions_shared(self.db, session.owner_id)) | |
| if not allowed: | |
| raise Forbidden() | |
| return await self._out(session, include_body_data=is_owner) | |
| async def _out(self, s: SwingSession, *, include_body_data: bool = True) -> SessionOut: | |
| keys = await self.uploads.object_keys(s.video_upload_id, s.thumbnail_upload_id) | |
| review_row = await self.sessions.review_with_coach_name(s.id) | |
| review = None | |
| if review_row: | |
| r, coach_name = review_row | |
| voice_note = None | |
| if r.voice_upload_id is not None: | |
| voice_keys = await self.uploads.object_keys(r.voice_upload_id) | |
| if r.voice_upload_id in voice_keys: | |
| voice_note = media_ref(self.storage, r.voice_upload_id, voice_keys[r.voice_upload_id], | |
| float(r.voice_seconds) if r.voice_seconds is not None else None) | |
| review = ReviewOut(coach_id=r.coach_id, coach_name=coach_name, cue=r.cue, drill_id=r.drill_id, | |
| verdicts=r.verdicts, at=r.updated_at, voice_note=voice_note) | |
| previous = await self.sessions.previous(s) | |
| previous_report = (report_for_read(previous.mode, previous.report, previous.measurement_payload) | |
| if previous else None) | |
| previous_score = previous.overall_score if previous and previous_report is previous.report else None | |
| thumb_key = keys.get(s.thumbnail_upload_id) if s.thumbnail_upload_id else None | |
| return SessionOut( | |
| id=s.id, owner_id=s.owner_id, is_self=s.is_self, mode=s.mode, status=s.status, | |
| created_at=s.created_at, analyzed_at=s.analyzed_at, | |
| athlete=s.athlete if include_body_data else _without_body_data(s.athlete), | |
| duration_sec=float(s.duration_sec), fps=s.fps, marks=s.marks, | |
| report=report_for_read(s.mode, s.report, s.measurement_payload), report_error=s.report_error, | |
| review=review, | |
| media=MediaOut( | |
| video_url=self.storage.presign_get(keys[s.video_upload_id]), | |
| thumbnail_url=self.storage.presign_get(thumb_key) if thumb_key else None, | |
| expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl)), | |
| previous=PreviousOut(id=previous.id, overall_score=previous_score, | |
| created_at=previous.created_at) if previous else None, | |
| ordinal=await self.sessions.ordinal(s), | |
| ) | |
| # D4 | |
| async def list(self, owner: Account, paging: PageParams, *, mode: str | None, is_self: bool | None, | |
| athlete_name: str | None, since: datetime | None) -> Page[SessionSummary]: | |
| if since and since.tzinfo is None: | |
| since = since.replace(tzinfo=UTC) | |
| query = self.sessions.summaries_query(owner.id, mode=mode, is_self=is_self, athlete_name=athlete_name, | |
| since=since, cursor=paging.cursor, limit=paging.limit + 1) | |
| items = await load_summaries(self.db, self.storage, query) | |
| items, next_cursor = paginate(items, paging.limit) | |
| return Page[SessionSummary](items=items, next_cursor=next_cursor) | |
| # D5 | |
| async def delete(self, owner: Account, session_id: UUID) -> None: | |
| session = await self.sessions.get_live(session_id) | |
| if session is None: | |
| raise NotFound() | |
| if session.owner_id != owner.id: | |
| raise Forbidden() | |
| await self.sessions.update(session, deleted_at=datetime.now(UTC)) | |
| # The media goes now; the cleanup job removes the rows later (and retries if this delete fails). | |
| keys = await self.uploads.object_keys(session.video_upload_id, session.thumbnail_upload_id) | |
| try: | |
| await self.storage.delete_many(list(keys.values())) | |
| except Exception: | |
| log.exception("media delete failed for session %s; cleanup will retry", session.id) | |