import os from fastapi import FastAPI from fastapi.responses import FileResponse, JSONResponse from scripts.extract_frames import extract_frames from contextlib import asynccontextmanager FRAMES_DIR = "frames" VIDEO_DIR = "videos" @asynccontextmanager async def lifespan(app: FastAPI): os.makedirs(FRAMES_DIR, exist_ok=True) # Step 1: Extract frames from each video for video_file in os.listdir(VIDEO_DIR): if video_file.lower().endswith(('.mp4', '.avi', '.mov')): video_path = os.path.join(VIDEO_DIR, video_file) extract_frames(video_path, FRAMES_DIR) print("✅ Frame extraction complete.") yield app = FastAPI(lifespan=lifespan) # Endpoint to list all available frames @app.get("/frames") def list_frames(): try: frames = [f for f in os.listdir(FRAMES_DIR) if f.lower().endswith(('.png', '.jpg', '.jpeg'))] return JSONResponse(content={"frames": frames}) except Exception as e: return JSONResponse(content={"error": str(e)}, status_code=500) # Endpoint to download a specific frame @app.get("/frames/{filename}") def get_frame(filename: str): file_path = os.path.join(FRAMES_DIR, filename) if os.path.exists(file_path): return FileResponse(file_path, filename=filename) return JSONResponse(content={"error": "File not found"}, status_code=404)