from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import JSONResponse import shutil import os import uuid from backend.pipelines.video_processor import VideoProcessor app = FastAPI(title="Pothole & Road Sign Detection API") # Initialize Processor (Loading models takes time, do it on startup) # In production, use lifespan events or dependency injection print("Initializing Video Processor...") try: processor = VideoProcessor() except Exception as e: print(f"Warning: Could not initialize processor (Check model paths). Error: {e}") processor = None UPLOAD_DIR = "uploads" os.makedirs(UPLOAD_DIR, exist_ok=True) @app.get("/") def health_check(): return {"status": "running", "models_loaded": processor is not None} @app.post("/detect/video") async def detect_video(file: UploadFile = File(...)): if processor is None: raise HTTPException(status_code=503, detail="Models not accepted or loaded.") # Save uploaded file file_id = str(uuid.uuid4()) file_location = os.path.join(UPLOAD_DIR, f"{file_id}_{file.filename}") with open(file_location, "wb") as buffer: shutil.copyfileobj(file.file, buffer) try: # Run processing start_time = os.times().elapsed results = processor.process_video(file_location) # Cleanup os.remove(file_location) return { "video_id": file_id, "processed": True, "unique_objects": results } except Exception as e: # Cleanup on error if os.path.exists(file_location): os.remove(file_location) raise HTTPException(status_code=500, detail=str(e)) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)