Spaces:
Sleeping
Sleeping
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import torch | |
| from api.services.dino_service import GroundingDinoService | |
| from api.routers.analysis import router as analysis_router | |
| # Define the lifespan context manager for startup and shutdown events | |
| async def lifespan(app: FastAPI): | |
| # Initialize the Grounding DINO Service (downloads model if not cached and loads onto device) | |
| dino_service = GroundingDinoService() | |
| app.state.dino_service = dino_service | |
| yield | |
| # Clean up and free device memory | |
| if hasattr(app.state, "dino_service"): | |
| del app.state.dino_service | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| # Create FastAPI application instance | |
| app = FastAPI( | |
| title="Emergency Incident Detector & Analyzer API", | |
| description="A REST API wrapper around Grounding DINO for real-time disaster and accident scene analysis.", | |
| version="1.0.0", | |
| lifespan=lifespan | |
| ) | |
| # Set up CORS middleware to support local testing and front-end integration | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Include incident routers | |
| app.include_router(analysis_router) | |
| # Basic health-check endpoint | |
| def health_check(): | |
| return { | |
| "status": "healthy", | |
| "model_loaded": hasattr(app.state, "dino_service") and app.state.dino_service is not None | |
| } | |
| def read_root(): | |
| return { | |
| "message": "Welcome to the Emergency Incident Detection API. Go to /docs for the interactive Swagger API documentation." | |
| } | |