File size: 1,736 Bytes
8e6f164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
@asynccontextmanager
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
@app.get("/health", tags=["Health"])
def health_check():
    return {
        "status": "healthy",
        "model_loaded": hasattr(app.state, "dino_service") and app.state.dino_service is not None
    }

@app.get("/", tags=["Root"])
def read_root():
    return {
        "message": "Welcome to the Emergency Incident Detection API. Go to /docs for the interactive Swagger API documentation."
    }