"""HTTP upload/status/result API. Start with Uvicorn --factory --workers 1.""" from contextlib import asynccontextmanager import asyncio import hmac import json import os from pathlib import Path import shutil import threading from typing import Annotated from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile, Request from fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponse from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from pydantic import ValidationError from starlette.background import BackgroundTask from starlette.concurrency import run_in_threadpool from .api_contract import AnalysisInput from .api_jobs import ApiSettings, JobService, QueueFull from .load_timing_contract import LoadTimingPayload from .timing_evidence import TimingEvidencePayload from .storage import atomic_json, read_json, sha256_file from .swing_clips import SwingsManifest from .media import open_verified_media, media_response ALLOWED_VIDEO_SUFFIXES = {".mp4", ".mov", ".mkv", ".avi", ".webm"} BEARER = HTTPBearer(auto_error=False) class UploadGuard: """Authenticate before multipart parsing and limit its total streamed body.""" def __init__(self, app, settings, service): self.app, self.settings, self.service = app, settings, service self.upload_slots = asyncio.Semaphore(2) async def __call__(self, scope, receive, send): if scope["type"] != "http" or not scope["path"].startswith("/v1/"): return await self.app(scope, receive, send) headers = dict(scope["headers"]) authorization = headers.get(b"authorization", b"") supplied = authorization[7:] if authorization.lower().startswith(b"bearer ") else b"" if not hmac.compare_digest(supplied, self.settings.api_key.encode()): return await JSONResponse({"detail": "Invalid or missing API key"}, status_code=401, headers={"WWW-Authenticate": "Bearer"})(scope, receive, send) limit = (512 * 1024 if scope['path'].startswith('/v1/motion-analyses/') and scope['path'].endswith('/revisions') else 4 * 1024 * 1024 if scope['path']=='/v1/sam-batting/group-reviews' else self.settings.max_upload_bytes + 1024 * 1024) size = headers.get(b"content-length") if size: try: oversized = int(size) > limit or int(size) < 0 except ValueError: oversized = True if oversized: return await JSONResponse({"detail": "Request exceeds upload limit"}, status_code=413)(scope, receive, send) received = 0 async def limited_receive(): nonlocal received message = await receive() received += len(message.get("body", b"")) if received > limit: raise HTTPException(413, "Request exceeds upload limit") return message is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses','/v1/sam-batting/analyses','/v1/motion-analyses'} if is_upload: if not self.service.ready: return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send) if self.upload_slots.locked(): return await JSONResponse({"detail": "Too many concurrent uploads"}, status_code=429)(scope, receive, send) async with self.upload_slots: return await self.app(scope, limited_receive, send) return await self.app(scope, limited_receive, send) def create_app(settings=None, service=None): settings = settings or ApiSettings.from_env() service = service or JobService(settings) review_lock = threading.Lock() @asynccontextmanager async def lifespan(app): service.start() try: yield finally: service.stop() app = FastAPI(title="Baseball Motion Engine and Coach", version="1.21.7", lifespan=lifespan, description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.") app.state.service = service app.add_middleware(UploadGuard, settings=settings, service=service) def authenticated(credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(BEARER)]): # Documents Bearer authorization in OpenAPI; UploadGuard also checks before body parsing. if credentials is None or not hmac.compare_digest(credentials.credentials.encode(), settings.api_key.encode()): raise HTTPException(401, "Invalid or missing API key", headers={"WWW-Authenticate": "Bearer"}) def job_record(job_id): try: directory = service.job_directory(job_id) except ValueError: raise HTTPException(404, "Job not found") record = service.store.get(job_id) if not record: raise HTTPException(404, "Job not found") return directory, record def coaching_available(): import importlib.util return importlib.util.find_spec("ai_coach") is not None @app.get("/", response_class=HTMLResponse, include_in_schema=False) def home(): return HTMLResponse(Path(__file__).with_name("product.html").read_text(), headers={ "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' blob:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"}) @app.get("/healthz") def health(): return {"status": "alive", "gpu_ready": service.ready, "body_3d": False} @app.get("/readyz") def ready(): return JSONResponse({"ready": service.ready, "reason": service.readiness_reason, 'bat_ball_tracking_ready': service.tracking_ready, 'coaching_available': coaching_available(), 'visual_model_configured': bool(os.environ.get('GOOGLE_API_KEY')), 'visual_model_status': service.visual_model_status, "device": "cuda", "body_3d": False}, status_code=200 if service.ready else 503) @app.get("/v1/capabilities", dependencies=[Depends(authenticated)]) def capabilities(): tracking_configured = service.tracking_ready sam_record = os.environ.get("BASEBALL_SAM_WORKER_RECORD") sam_configured = False if sam_record and Path(sam_record).is_file(): try: record = read_json(sam_record) sam_configured = all(Path(record[key]).exists() for key in ("worker_python", "sam_repo", "sam_checkpoint", "sam_config", "mhr_path")) except (ValueError, KeyError, TypeError, OSError): pass return {"discipline": "hitting", "device": "cuda", "body_3d": True, "measurement_backends": {"2d": {"configured": True}, "rtmw3d": {"configured": (settings.model_root/"body_pose_3d/model.onnx").is_file()}, "sam3d": {"configured": sam_configured}}, "body_3d_scope": "experimental sparse contact/foot-plant windows; actual CUDA checked during inference", "body_points": 17, "foot_points": 6, "automatic_rep_splitting": True, "automatic_events": True, "swing_metrics": True, "estimated_only": True, "swing_clips": {"configured": True, "route": "/v1/analyses/{job_id}/swings", "content_type": "video/mp4", "codec": "h264", "audio": False, "max_dimension": 1280, "time_basis": "playback", "byte_ranges": True, "overlay": True, "overlay_style": "colab_swing_preview"}, "measurement_validation": "reference_validation_pending", "coaching": coaching_available(), "swing_coach": {"upload_route": "/v1/swing-coach/analyses", "product_route": "/v1/analyses/{job_id}/product", "visual_model_configured": bool(os.environ.get("GOOGLE_API_KEY")), "experimental_score_path": "visual_review.score", "visual_review_accuracy_validated": False}, "load_timing": {"schema_version": "3.0", 'evidence_schema_version': '3.1', "route": "/v1/analyses/{job_id}/load-timing", 'upload_route': '/v1/load-timing/analyses', "automatic_load_and_foot_timing": True, "automatic_ball_contact": tracking_configured, 'contact_scope': 'visual bat/ball interaction estimate; not independently validated', "automatic_bat_ball_tracking": tracking_configured, "early_late_estimate": tracking_configured, 'early_late_requirements': 'secondary_video, documented calibration/synchronization/position bounds and complete spatial paths', 'single_video_early_late': False}, "limits": {"upload_bytes": settings.max_upload_bytes, "duration_s": settings.max_duration_s, "frames": settings.max_frames, "pixels": settings.max_pixels}, "retention_hours": settings.retention_s / 3600} @app.get("/v1/input-schema", dependencies=[Depends(authenticated)]) def input_schema(): return AnalysisInput.model_json_schema() @app.get("/v1/output-schema", dependencies=[Depends(authenticated)]) def output_schema(): return read_json(Path(__file__).resolve().parents[1] / "docs/api-result.schema.json") @app.get("/v1/coach-payload-schema", dependencies=[Depends(authenticated)]) def coach_schema(): return read_json(Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json") @app.get("/v1/swings-schema", dependencies=[Depends(authenticated)]) def swings_schema(): return SwingsManifest.model_json_schema() @app.get("/v1/video-score-schema", dependencies=[Depends(authenticated)]) def video_score_schema(): if not coaching_available(): raise HTTPException(503, "Coach is not installed") from ai_coach.visual_scoring import VideoScore return VideoScore.model_json_schema() @app.get("/v1/load-timing-schema", dependencies=[Depends(authenticated)]) def timing_schema(include_evidence: bool = False): if include_evidence: return TimingEvidencePayload.model_json_schema() return read_json(Path(__file__).resolve().parents[1] / "docs/load-timing.schema.json") @app.post("/v1/analyses", status_code=202, dependencies=[Depends(authenticated)]) @app.post("/v1/swing-coach/analyses", status_code=202, dependencies=[Depends(authenticated)], summary="One video to measurements, coaching and optional experimental visual feedback") @app.post('/v1/load-timing/analyses', status_code=202, dependencies=[Depends(authenticated)], summary='Upload for load/timing; reject missing recording settings before inference') async def create_analysis(request: Request, video: Annotated[UploadFile, File(description="Original recording")], options: Annotated[str, Form(description="One JSON text field. For timing: view=face_on, handedness, pitcher_direction and documented timing are required.")] = "{}", secondary_video: Annotated[UploadFile | None, File(description='Optional synchronized second view; requires stereo_tracking calibration in options')] = None): identifier = None try: if not service.ready: raise HTTPException(503, "GPU worker is not ready; check /readyz") if len(options.encode()) > 512 * 1024: raise HTTPException(413, "Options exceed size limit") try: parsed = AnalysisInput.model_validate_json(options) except ValidationError as error: # No echo of arbitrary client inputs in error responses. details = [{"loc": list(item["loc"]), "type": item["type"], "msg": item["msg"]} for item in error.errors(include_url=False, include_input=False)] raise HTTPException(422, details) if request.url.path == '/v1/swing-coach/analyses' and 'coaching_mode' not in parsed.model_fields_set: parsed.coaching_mode = 'poc_video' if parsed.coaching_mode != 'disabled' and not coaching_available(): raise HTTPException(503, {'code': 'coach_not_installed', 'message': 'Install requirements-coach.txt and AI-coach-agent, or use the unified Docker image.'}) missing = [] if parsed.view != 'face_on': missing.append('view') if parsed.handedness is None: missing.append('handedness') if parsed.pitcher_direction is None: missing.append('pitcher_direction') if parsed.timing.kind == 'unknown': missing.append('timing') if request.url.path == '/v1/load-timing/analyses' and missing: raise HTTPException(422, {'code': 'timing_settings_required', 'fields': missing, 'message': 'Supply these recording facts in the options JSON. The engine cannot infer original capture time or verify your camera view.'}) if request.url.path == '/v1/load-timing/analyses': if parsed.measurement_backend != '2d': raise HTTPException(422, {'code': 'timing_uses_2d_body', 'message': 'Use measurement_backend=2d for this route. Bat/ball geometry is independent of SAM body reconstruction.'}) if not service.tracking_ready: raise HTTPException(503, {'code': 'tracking_models_unavailable', 'message': 'Bat and ball models must pass CUDA preflight. Rebuild the tracking-enabled GPU image.'}) if (secondary_video is not None) != (parsed.stereo_tracking is not None): raise HTTPException(422, {'code': 'stereo_input_incomplete', 'message': 'Supply both secondary_video and stereo_tracking calibration, or neither.'}) suffix = Path(video.filename or "").suffix.lower() if suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, "Unsupported video extension") if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes: raise HTTPException(507, "Insufficient storage") try: identifier = service.store.create(settings.max_active_jobs) except QueueFull: raise HTTPException(429, "GPU queue is full", headers={"Retry-After": "30"}) directory = service.job_directory(identifier) directory.mkdir() size = 0 with (directory / ("input" + suffix)).open("wb") as destination: while block := await video.read(1024 * 1024): size += len(block) if size > settings.max_upload_bytes: raise HTTPException(413, "Video exceeds upload limit") if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes + len(block): raise HTTPException(507, "Insufficient storage") destination.write(block) if size == 0: raise HTTPException(422, "Video is empty") if secondary_video is not None: second_suffix = Path(secondary_video.filename or '').suffix.lower() if second_suffix not in ALLOWED_VIDEO_SUFFIXES: raise HTTPException(415, 'Unsupported secondary video extension') second_size = 0 with (directory/('secondary'+second_suffix)).open('wb') as destination: while block := await secondary_video.read(1024*1024): size += len(block); second_size += len(block) if size > settings.max_upload_bytes: raise HTTPException(413, 'Combined videos exceed upload limit') if shutil.disk_usage(settings.data_root).free < settings.minimum_free_bytes+len(block): raise HTTPException(507, 'Insufficient storage') destination.write(block) if second_size == 0: raise HTTPException(422, 'Secondary video is empty') atomic_json(directory / "request.json", parsed.model_dump(exclude_none=True)) service.store.update(identifier, "queued") service.wakeup.set() return {"job_id": identifier, "status": "queued", "status_url": f"/v1/analyses/{identifier}", "result_url": f"/v1/analyses/{identifier}/result", "load_timing_url": f"/v1/analyses/{identifier}/load-timing", 'load_timing_evidence_url': f'/v1/analyses/{identifier}/load-timing?include_evidence=true', 'product_url': f'/v1/analyses/{identifier}/product' if parsed.coaching_mode != 'disabled' else None, 'swings_url': f'/v1/analyses/{identifier}/swings', 'coaching_url': f'/v1/analyses/{identifier}/coaching' if parsed.coaching_mode != 'disabled' else None, 'warnings': ([{'code': 'timing_settings_missing', 'fields': missing, 'message': 'Timing measurements may be unavailable. Supply recording facts in options.'}] if missing else []) + ([{'code': 'camera_stability_unverified', 'message': 'Foot landing timing needs a verified fixed camera.'}] if parsed.camera_stability != 'fixed_verified' else []), "coach_payload_url": f"/v1/analyses/{identifier}/coach-payload"} except BaseException: if identifier: service.store.forget(identifier) shutil.rmtree(service.job_directory(identifier), ignore_errors=True) raise finally: await video.close() if secondary_video is not None: await secondary_video.close() @app.get("/v1/analyses/{job_id}", dependencies=[Depends(authenticated)]) def status(job_id: str): with service.mutation_lock: directory, record = job_record(job_id) progress = read_json(directory / "progress.json") if (directory / "progress.json").is_file() else None return {"job_id": job_id, "status": record["status"], "created_at": record["created"], "updated_at": record["updated"], "progress": progress, "error": record["error"], "result_url": f"/v1/analyses/{job_id}/result" if record["status"] == "completed" else None, "load_timing_url": f"/v1/analyses/{job_id}/load-timing" if record["status"] == "completed" and record.get("load_timing_sha256") else None, 'load_timing_evidence_url': f'/v1/analyses/{job_id}/load-timing?include_evidence=true' if record['status'] == 'completed' and record.get('timing_evidence_sha256') else None, "coach_payload_url": f"/v1/analyses/{job_id}/coach-payload" if record["status"] == "completed" else None, "product_url": f"/v1/analyses/{job_id}/product" if record["status"] == "completed" and record.get("product_sha256") else None, "swings_url": f"/v1/analyses/{job_id}/swings" if record["status"] == "completed" and record.get("swings_sha256") else None, "coaching_url": f"/v1/analyses/{job_id}/coaching" if record["status"] == "completed" and record.get("product_sha256") else None} def stored_product(job_id): directory, record = job_record(job_id) if record['status'] != 'completed' or not record.get('product_sha256'): raise HTTPException(409, 'No completed coaching product; submit with coaching enabled') path = directory/'product.json' if not path.is_file() or sha256_file(path) != record['product_sha256']: raise HTTPException(500, 'Stored product failed its integrity check') return directory, read_json(path) @app.get('/v1/analyses/{job_id}/product', dependencies=[Depends(authenticated)]) def get_product(job_id: str): with service.mutation_lock: _, payload = stored_product(job_id) return JSONResponse(payload, headers={'Cache-Control': 'no-store'}) @app.get('/v1/analyses/{job_id}/coaching', dependencies=[Depends(authenticated)]) def get_coaching(job_id: str): with service.mutation_lock: _, payload = stored_product(job_id) return JSONResponse(payload['coaching'], headers={'Cache-Control': 'no-store'}) @app.post('/v1/analyses/{job_id}/video-review', dependencies=[Depends(authenticated)]) def retry_review(job_id: str): if not review_lock.acquire(blocking=False): raise HTTPException(429, 'A video review is already running; try again later', headers={'Retry-After': '30'}) try: with service.mutation_lock: directory, payload = stored_product(job_id) from ai_coach.video_review import review_is_current if review_is_current(payload['visual_review']): return JSONResponse(payload, headers={'Cache-Control': 'no-store'}) if not payload['evidence']['frames']: raise HTTPException(409, 'No retained video frames; upload again with video feedback enabled') options = AnalysisInput.model_validate(read_json(directory/'request.json')) previous_hash = service.store.get(job_id)['product_sha256'] from .product import retry_video_review try: updated = retry_video_review(directory, payload, options) except ValueError: raise HTTPException(500, 'Stored review frames failed their integrity check') from None with service.mutation_lock: _, current = stored_product(job_id) if service.store.get(job_id)['product_sha256'] != previous_hash: raise HTTPException(409, 'Product changed while review was running; reload its result') atomic_json(directory/'product.json', updated) try: service.store.update_product(job_id, sha256_file(directory/'product.json')) except Exception: atomic_json(directory/'product.json', current) raise HTTPException(500, 'Could not save video feedback; the previous result was kept') from None return JSONResponse(updated, headers={'Cache-Control': 'no-store'}) finally: review_lock.release() @app.get('/v1/analyses/{job_id}/frames/{frame_id}', dependencies=[Depends(authenticated)]) def get_frame(job_id: str, frame_id: int): with service.mutation_lock: directory, payload = stored_product(job_id) frame = next((f for f in payload['evidence']['frames'] if f['frame'] == frame_id), None) if frame is None: raise HTTPException(404, 'Frame not found') path = directory/'review-frames'/f'{frame_id}.jpg' if not path.is_file() or sha256_file(path) != frame['sha256']: raise HTTPException(500, 'Stored frame failed its integrity check') return Response(path.read_bytes(), media_type='image/jpeg', headers={ 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'}) def stored_swings(job_id): directory, record = job_record(job_id) if record['status'] != 'completed': raise HTTPException(409, 'Job has no completed result; check job status') if not record.get('swings_sha256'): raise HTTPException(409, 'This older job has no swing clips; submit the video again') path = directory/'swings.json' if not path.is_file() or sha256_file(path) != record['swings_sha256']: raise HTTPException(500, 'Stored swing manifest failed its integrity check') try: payload = SwingsManifest.model_validate(read_json(path)) except (ValidationError, ValueError): raise HTTPException(500, 'Stored swing manifest has invalid structure') from None return directory, payload @app.get('/v1/analyses/{job_id}/swings', response_model=SwingsManifest, dependencies=[Depends(authenticated)], summary='List every detected swing and its playable clip') def get_swings(job_id: str): with service.mutation_lock: _, payload = stored_swings(job_id) return JSONResponse(payload.model_dump(mode='json'), headers={'Cache-Control': 'no-store'}) @app.get('/v1/analyses/{job_id}/swings/{rep}/clip', dependencies=[Depends(authenticated)], response_class=StreamingResponse, responses={200: {'content': {'video/mp4': {}}}, 206: {'description': 'Requested byte range', 'content': {'video/mp4': {}}}, 416: {'description': 'Unsatisfiable byte range'}}, summary='Play or download a swing MP4') @app.head('/v1/analyses/{job_id}/swings/{rep}/clip', dependencies=[Depends(authenticated)], include_in_schema=False) def get_swing_clip(job_id: str, rep: int, request: Request): with service.mutation_lock: directory, payload = stored_swings(job_id) swing = next((s for s in payload.swings if s.rep == rep), None) if swing is None: raise HTTPException(404, 'Swing not found') if swing.clip.status != 'available': raise HTTPException(409, {'code': swing.clip.reason_code, 'message': 'Swing clip is unavailable'}) handle, size = open_verified_media(directory/'swing-clips'/f'{rep}.mp4', swing.clip.sha256, swing.clip.size_bytes) return media_response(request, handle, size, swing.clip.sha256) @app.get("/v1/analyses/{job_id}/coach-payload", dependencies=[Depends(authenticated)]) def get_coach_payload(job_id: str): with service.mutation_lock: directory, record = job_record(job_id) if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status") path = directory / "coach-payload.json" if record.get("coach_payload_sha256") is None: raise HTTPException(409, "This older job has no coach payload; submit the video again") if not path.is_file() or sha256_file(path) != record["coach_payload_sha256"]: raise HTTPException(500, "Stored coach payload failed its integrity check") payload = read_json(path) return JSONResponse(payload, headers={"Cache-Control": "no-store"}) @app.get("/v1/analyses/{job_id}/load-timing", response_model=LoadTimingPayload | TimingEvidencePayload, dependencies=[Depends(authenticated)], summary="Get four load and swing timing measurements", description="Capture milliseconds per swing. Default 3.0; include_evidence=true returns 3.1 with events, reason codes, context and sensitivity. Physical miss/shift requires supported two-view geometry.") def get_load_timing(job_id: str, include_evidence: bool = False): with service.mutation_lock: directory, record = job_record(job_id) if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status") path = directory / ('load-timing-evidence.json' if include_evidence else 'load-timing.json') hash_key = 'timing_evidence_sha256' if include_evidence else 'load_timing_sha256' if record.get(hash_key) is None: raise HTTPException(409, "This older job has no load/timing payload; submit the video again") if not path.is_file() or sha256_file(path) != record[hash_key]: raise HTTPException(500, "Stored load/timing payload failed its integrity check") try: model = TimingEvidencePayload if include_evidence else LoadTimingPayload payload = model.model_validate(read_json(path)) except (ValidationError, ValueError): raise HTTPException(500, "Stored load/timing payload has invalid structure") from None return JSONResponse(payload.model_dump(mode="json"), headers={"Cache-Control": "no-store"}) @app.get("/v1/analyses/{job_id}/result", dependencies=[Depends(authenticated)]) def result(job_id: str): with service.mutation_lock: directory, record = job_record(job_id) if record["status"] != "completed": raise HTTPException(409, "Job has no completed result; check job status") path = directory / "result.json" if not path.is_file() or sha256_file(path) != record["result_sha256"]: raise HTTPException(500, "Stored result failed its integrity check") # An open descriptor stays usable when DELETE/retention removes the path. handle = path.open("rb") size = path.stat().st_size async def stream(): try: while block := await run_in_threadpool(handle.read, 64 * 1024): yield block finally: handle.close() return StreamingResponse(stream(), media_type="application/json", headers={"Cache-Control": "no-store", "Content-Length": str(size)}, background=BackgroundTask(handle.close)) @app.delete("/v1/analyses/{job_id}", status_code=202, dependencies=[Depends(authenticated)]) def delete(job_id: str): job_record(job_id) status = service.delete(job_id) return {"job_id": job_id, "status": status} from .sam_api import register register(app,service,authenticated) from .motion_api import register as register_motion register_motion(app,service,authenticated) return app