""" Pushup Counter API — FastAPI + asyncio + ProcessPoolExecutor Auto-detects GPU (CUDA / Apple MPS) or falls back to CPU. Handles concurrent video uploads with YOLO11 pose estimation. """ import asyncio import os import shutil import tempfile import uuid import time import logging from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor from contextlib import asynccontextmanager, contextmanager from pathlib import Path from typing import Optional, Generator import cv2 import torch import uvicorn from fastapi import FastAPI, File, Form, HTTPException, UploadFile, BackgroundTasks from fastapi.responses import FileResponse from pydantic import BaseModel # ── Logging ─────────────────────────────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s", ) log = logging.getLogger("pushup_api") # ── GPU / CPU auto-detection ────────────────────────────────────────────────── def _detect_device() -> str: """ Priority: CUDA GPU → Apple Silicon MPS → CPU Logs what was found so the operator always knows which device is active. """ if torch.cuda.is_available(): gpu_name = torch.cuda.get_device_name(0) log.info("🟢 GPU detected: %s — inference will use CUDA", gpu_name) return "cuda" if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): log.info("🟢 Apple Silicon GPU detected — inference will use MPS") return "mps" log.info("🟡 No GPU found — inference will use CPU") return "cpu" DEVICE = _detect_device() MAX_WORKERS = int(os.getenv("MAX_WORKERS", 4)) MAX_FILE_SIZE_MB = int(os.getenv("MAX_FILE_SIZE_MB", 200)) SKIP_FRAMES = int(os.getenv("SKIP_FRAMES", 2)) RESIZE_W = int(os.getenv("RESIZE_W", 640)) RESIZE_H = int(os.getenv("RESIZE_H", 360)) MODEL_NAME = os.getenv("YOLO_MODEL", "yolo11n-pose.pt") TEMP_DIR = Path(tempfile.gettempdir()) / "pushup_api" TEMP_DIR.mkdir(parents=True, exist_ok=True) # ── Schemas ─────────────────────────────────────────────────────────────────── class PersonResult(BaseModel): person_id: int reps: int class PushupResponse(BaseModel): job_id: str status: str total_reps: int per_person: list[PersonResult] frames_processed: int processing_time_sec: float device_used: str output_video_path: Optional[str] = None kpts: list[int] class ErrorResponse(BaseModel): job_id: str status: str = "error" detail: str class HealthResponse(BaseModel): status: str device: str gpu_name: Optional[str] workers: int model: str # ── Core processing (runs in isolated worker process) ───────────────────────── def _process_video( video_path: str, kpts: list[int], save_output: bool, output_path: str, device: str, ) -> dict: """ Runs in a separate process — no GIL, no blocking the event loop. The detected device string is passed in so YOLO uses GPU when available. """ from ultralytics import solutions cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise RuntimeError(f"Cannot open video: {video_path}") fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 writer = None if save_output: writer = cv2.VideoWriter( output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (RESIZE_W, RESIZE_H), ) gym = solutions.AIGym( show=False, kpts=kpts, model=MODEL_NAME, line_width=1, device=device, # ← GPU or CPU injected at runtime ) frame_count = 0 processed = 0 last_results = None t_start = time.perf_counter() while cap.isOpened(): success, frame = cap.read() if not success: break frame_count += 1 if frame_count % SKIP_FRAMES != 0: continue frame = cv2.resize(frame, (RESIZE_W, RESIZE_H)) results = gym(frame) last_results = results processed += 1 if save_output and writer: writer.write(results.plot_im) cap.release() if writer: writer.release() elapsed = time.perf_counter() - t_start per_person: list[dict] = [] total_reps = 0 if last_results and hasattr(last_results, "workout_count"): counts = last_results.workout_count if isinstance(counts, list): for i, reps in enumerate(counts): per_person.append({"person_id": i + 1, "reps": int(reps)}) total_reps = int(sum(counts)) else: total_reps = int(counts) per_person.append({"person_id": 1, "reps": total_reps}) return { "total_reps": total_reps, "per_person": per_person, "frames_processed": processed, "processing_time_sec": round(elapsed, 3), "device_used": device, } # ── App lifespan ────────────────────────────────────────────────────────────── @asynccontextmanager async def lifespan(app: FastAPI): # ✅ Startup: Clean old temp files and create temp directory log.info("🧹 Cleaning old temporary files (>24 hours)…") _cleanup_old_temp_files(max_age_hours=24) log.info("🚀 Pushup API ready — device=%s workers=%d model=%s", DEVICE, MAX_WORKERS, MODEL_NAME) app.state.process_pool = ProcessPoolExecutor(max_workers=MAX_WORKERS) app.state.thread_pool = ThreadPoolExecutor(max_workers=MAX_WORKERS * 2) yield # ✅ Shutdown: Clean all temp files log.info("🛑 Shutting down — cleaning all temp files…") _cleanup_old_temp_files(max_age_hours=0) # Remove ALL temp files app.state.process_pool.shutdown(wait=False) app.state.thread_pool.shutdown(wait=False) # ── FastAPI app ─────────────────────────────────────────────────────────────── app = FastAPI( title="💪 Pushup Counter API", description=( "Upload a workout video and receive per-person push-up rep counts " "powered by YOLO11 pose estimation.\n\n" "**Auto-detects**: CUDA GPU → Apple MPS → CPU" ), version="2.0.0", lifespan=lifespan, ) # ── Helpers ─────────────────────────────────────────────────────────────────── def _cleanup(paths: list[str]): """Remove files with error suppression.""" for p in paths: try: Path(p).unlink(missing_ok=True) except Exception: pass @contextmanager def temp_file( suffix: str = "", prefix: str = "tmp_", dir_path: Optional[Path] = None, ) -> Generator[Path, None, None]: """ Context manager for guaranteed temporary file cleanup. **Usage:** ```python with temp_file(suffix=".avi") as tmp_path: # Use tmp_path # Automatically deleted on exit, even if exception occurs ``` Args: suffix: File extension (e.g. ".avi", ".mp4") prefix: File name prefix (default "tmp_") dir_path: Directory to store temp file (default system temp) Yields: Path object to temporary file """ target_dir = dir_path or Path(tempfile.gettempdir()) temp_path = target_dir / f"{prefix}{uuid.uuid4().hex[:8]}{suffix}" try: yield temp_path finally: # Guaranteed cleanup on exit (even on exception) try: if temp_path.exists(): if temp_path.is_dir(): shutil.rmtree(temp_path, ignore_errors=True) else: temp_path.unlink(missing_ok=True) log.debug("🗑️ Deleted temp file: %s", temp_path) except Exception as e: log.warning("⚠️ Failed to cleanup temp file %s: %s", temp_path, e) async def _save_upload(upload: UploadFile, dest: Path) -> int: """Stream large file upload with size limit enforcement.""" size = 0 loop = asyncio.get_event_loop() with dest.open("wb") as f: while chunk := await upload.read(1 << 16): # 64 KB chunks size += len(chunk) if size > MAX_FILE_SIZE_MB * 1024 * 1024: raise HTTPException(413, f"File exceeds {MAX_FILE_SIZE_MB} MB limit") await loop.run_in_executor(app.state.thread_pool, f.write, chunk) return size def _cleanup_old_temp_files(max_age_hours: float = 24): """ Remove temp files older than max_age_hours. Called on startup to prevent disk space bloat. """ import time now = time.time() max_age_sec = max_age_hours * 3600 try: for temp_file in TEMP_DIR.glob("*_input*") | TEMP_DIR.glob("*_output*"): if not temp_file.is_file(): continue file_age = now - temp_file.stat().st_mtime if file_age > max_age_sec: temp_file.unlink(missing_ok=True) log.debug("🗑️ Cleaned old temp file: %s (%.1f hours old)", temp_file, file_age / 3600) except Exception as e: log.warning("⚠️ Error during temp cleanup: %s", e) # ── Routes ──────────────────────────────────────────────────────────────────── @app.get( "/health", response_model=HealthResponse, tags=["Meta"], summary="Health check + hardware info", ) async def health(): """Returns API liveness status, active compute device, GPU name, worker count, and model.""" gpu_name = None if DEVICE == "cuda": gpu_name = torch.cuda.get_device_name(0) elif DEVICE == "mps": gpu_name = "Apple Silicon (MPS)" return HealthResponse( status="ok", device=DEVICE, gpu_name=gpu_name, workers=MAX_WORKERS, model=MODEL_NAME, ) @app.post( "/pushup", response_model=PushupResponse, responses={ 400: {"model": ErrorResponse, "description": "Invalid file type or keypoints"}, 413: {"model": ErrorResponse, "description": "File too large (>200 MB)"}, 500: {"model": ErrorResponse, "description": "Processing error"}, }, tags=["Workout"], summary="Count push-ups in an uploaded video", ) async def pushup( background_tasks: BackgroundTasks, video: UploadFile = File( ..., description="Video file — mp4, avi, mov, mkv, webm. Max 200 MB.", ), kpts: str = Form( default="6,8,10", description=( "Comma-separated COCO keypoint indices (minimum 3). " "Default `6,8,10` = left shoulder, elbow, wrist. Range 0–16." ), ), save_output: bool = Form( default=False, description="Generate annotated output video. Download via GET /pushup/output/{job_id}.", ), ): """ ## Count Push-ups Upload a workout video → receive per-person repetition counts. Inference runs on **GPU if available**, automatically falls back to CPU. ### COCO Keypoint Index Reference | idx | joint | idx | joint | |-----|----------------|-----|---------------| | 0 | nose | 9 | right wrist | | 5 | right shoulder | 10 | left wrist | | 6 | left shoulder | 11 | right hip | | 7 | right elbow | 13 | right knee | | 8 | left elbow | 15 | right ankle | """ job_id = str(uuid.uuid4())[:8] log.info("[%s] New job — file=%s device=%s", job_id, video.filename, DEVICE) # Validate keypoints try: kpts_list = [int(k.strip()) for k in kpts.split(",")] if len(kpts_list) < 3: raise ValueError("Need at least 3 keypoints") if any(k < 0 or k > 16 for k in kpts_list): raise ValueError("Index out of range 0–16") except ValueError as e: raise HTTPException(400, f"Invalid kpts: {e}") # Validate file type allowed_ext = {".mp4", ".avi", ".mov", ".mkv", ".webm"} ext = Path(video.filename or "video.mp4").suffix.lower() if ext not in allowed_ext: raise HTTPException(400, f"Unsupported type '{ext}'. Use: {sorted(allowed_ext)}") # Write upload to temp file tmp_in = TEMP_DIR / f"{job_id}_input{ext}" tmp_out = TEMP_DIR / f"{job_id}_output.avi" cleanup_paths = [str(tmp_in), str(tmp_out)] try: size_bytes = await _save_upload(video, tmp_in) log.info("[%s] Saved %.1f MB → %s", job_id, size_bytes / 1e6, tmp_in) except HTTPException: _cleanup(cleanup_paths) raise except Exception as exc: _cleanup(cleanup_paths) log.exception("[%s] Upload failed", job_id) raise HTTPException(500, f"Upload error: {exc}") # Run inference in process pool (non-blocking) loop = asyncio.get_event_loop() try: result: dict = await loop.run_in_executor( app.state.process_pool, _process_video, str(tmp_in), kpts_list, save_output, str(tmp_out), DEVICE, ) except Exception as exc: background_tasks.add_task(_cleanup, cleanup_paths) log.exception("[%s] Processing failed", job_id) raise HTTPException(500, f"Processing error: {exc}") # Schedule temp file cleanup after response remove_paths = [str(tmp_in)] if not save_output: remove_paths.append(str(tmp_out)) background_tasks.add_task(_cleanup, remove_paths) log.info( "[%s] ✅ reps=%d frames=%d %.2fs device=%s", job_id, result["total_reps"], result["frames_processed"], result["processing_time_sec"], result["device_used"], ) return PushupResponse( job_id=job_id, status="success", total_reps=result["total_reps"], per_person=[PersonResult(**p) for p in result["per_person"]], frames_processed=result["frames_processed"], processing_time_sec=result["processing_time_sec"], device_used=result["device_used"], output_video_path=str(tmp_out) if save_output else None, kpts=kpts_list, ) @app.get( "/pushup/output/{job_id}", tags=["Workout"], summary="Download annotated output video", responses={404: {"description": "Video not found or already cleaned up"}}, ) async def download_output(job_id: str): """ Download the annotated output video for a completed job. Only available if the original POST used `save_output=true`. """ path = TEMP_DIR / f"{job_id}_output.avi" if not path.exists(): raise HTTPException(404, "Video not found or already cleaned up.") return FileResponse(str(path), media_type="video/x-msvideo", filename=f"pushup_{job_id}.avi") @app.get( "/temp-demo", tags=["Meta"], summary="Demo: Temporary file handling with guaranteed cleanup", ) async def temp_file_demo(): """ **Demo endpoint showing the temp_file context manager.** This demonstrates guaranteed cleanup even if errors occur: - File is created automatically - File is deleted on exit (even on exception) - No cleanup code needed — handled by context manager **Example usage pattern:** ```python with temp_file(suffix=".txt") as tmp_path: # Write data tmp_path.write_text("Hello World") # Use file... # File automatically deleted on exit ``` """ results = [] # ✅ Demo 1: Normal case — file is auto-deleted on exit try: with temp_file(suffix=".txt", prefix="demo_") as tmp_path: tmp_path.write_text("Test data 1") results.append({"status": "created", "path": str(tmp_path), "exists": tmp_path.exists()}) results.append({"status": "after_exit", "existed": not tmp_path.exists()}) except Exception as e: results.append({"error": str(e)}) # ✅ Demo 2: Exception case — file is STILL auto-deleted try: with temp_file(suffix=".bin", prefix="demo_") as tmp_path: tmp_path.write_bytes(b"Binary data") results.append({"status": "exception_demo", "path": str(tmp_path)}) # Simulate error (file still gets cleaned up!) raise ValueError("Intentional error to test cleanup") except ValueError: results.append({"status": "exception_caught", "file_deleted": not tmp_path.exists()}) return { "message": "✅ All temp files cleaned up — see details below", "demo_results": results, "temp_dir": str(TEMP_DIR), } # ── Entry point ─────────────────────────────────────────────────────────────── if __name__ == "__main__": uvicorn.run( "app:app", host="0.0.0.0", port=8000, workers=1, # 1 uvicorn process; concurrency lives in the pool loop="asyncio", # fastest async event loop http="h11", # fastest HTTP parser log_level="info", access_log=True, timeout_keep_alive=30, )