File size: 8,007 Bytes
3d2a487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""Flash Flood Risk Inference API.



Start the server:

    uvicorn src.api.app:app --reload --port 8000



Endpoints:

    GET  /health                     β†’ liveness check

    GET  /predict?lat=18.96&lon=72.82

    POST /predict  { "lat": 18.96, "lon": 72.82 }



Example response:

    {

        "lat": 18.96,

        "lon": 72.82,

        "flood_probability": 0.823,

        "alert_level": "CRITICAL",

        "window_hours": 24,

        "latest_timestamp": "2026-03-01 11:00:00",

        "features_snapshot": {

            "Precipitation_mm": 42.3,

            "Soil_Moisture": 0.38,

            ...

        }

    }

"""
from __future__ import annotations

import sys
from pathlib import Path

# Ensure project root is on sys.path when running as `uvicorn src.api.app:app`
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(_PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(_PROJECT_ROOT))

from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, field_validator

from src.api.inference import predict
from src.api.inference_forecast import predict_24h

# ─────────────────────────────────────────────────────────────────────────────
# App
# ─────────────────────────────────────────────────────────────────────────────

app = FastAPI(
    title="Flash Flood Risk API",
    description=(
        "Given a geographic coordinate, fetches live hourly weather from Open-Meteo, "
        "engineers 13 hydrological features, and returns a flood risk probability "
        "from a trained LSTM model."
    ),
    version="1.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)


# ─────────────────────────────────────────────────────────────────────────────
# Schemas
# ─────────────────────────────────────────────────────────────────────────────

class PredictRequest(BaseModel):
    lat: float = Field(..., ge=-90,  le=90,  description="Latitude in decimal degrees")
    lon: float = Field(..., ge=-180, le=180, description="Longitude in decimal degrees")


class PredictResponse(BaseModel):
    lat:                float
    lon:                float
    flood_probability:  float = Field(..., description="LSTM sigmoid output in (0, 1) β€” raw float precision")
    alert_level:        str   = Field(..., description="LOW | MODERATE | HIGH | CRITICAL")
    window_hours:       int   = Field(..., description="Sliding window used (hours)")
    latest_timestamp:   str   = Field(..., description="UTC timestamp of most recent weather row")
    features_snapshot:  dict  = Field(..., description="13 engineered feature values at latest hour")


class ForecastResponse(BaseModel):
    lat:                      float
    lon:                      float
    flood_probability:        float = Field(..., description="Max flood probability across the next 24h")
    alert_level:              str   = Field(..., description="LOW | MODERATE | HIGH | CRITICAL")
    forecast_horizon_hours:   int   = Field(..., description="How many hours ahead this prediction covers")
    based_on_data_until:      str   = Field(..., description="Latest weather timestamp used as input")
    peak_flood_time:          str | None = Field(None, description="Timestamp when flood risk is highest in the next 24h")
    features_snapshot:        dict  = Field(..., description="13 engineered feature values at last forecast hour")
    threshold_used:           float = Field(..., description="F1-optimal decision threshold used to compute alert_level")


# ─────────────────────────────────────────────────────────────────────────────
# Routes
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/health", tags=["utility"])
def health() -> dict:
    """Liveness probe β€” confirms the API is running."""
    return {"status": "ok"}


@app.get(

    "/predict",

    response_model=PredictResponse,

    tags=["inference"],

    summary="Predict flood risk for a coordinate (GET)",

)
def predict_get(

    lat: float = Query(..., ge=-90,  le=90,  description="Latitude"),

    lon: float = Query(..., ge=-180, le=180, description="Longitude"),

) -> PredictResponse:
    """Fetch live weather and return flood risk probability for the given coordinate."""
    return _run_predict(lat, lon)


@app.post(

    "/predict",

    response_model=PredictResponse,

    tags=["inference"],

    summary="Predict flood risk for a coordinate (POST)",

)
def predict_post(body: PredictRequest) -> PredictResponse:
    """Same as GET /predict but accepts JSON body β€” convenient for batch clients."""
    return _run_predict(body.lat, body.lon)


# ─────────────────────────────────────────────────────────────────────────────
# Internal helper
# ─────────────────────────────────────────────────────────────────────────────

def _run_predict(lat: float, lon: float) -> PredictResponse:
    try:
        result = predict(lat, lon)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc
    except RuntimeError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Inference failed: {exc}") from exc
    return PredictResponse(**result)


@app.get(

    "/forecast",

    response_model=ForecastResponse,

    tags=["inference"],

    summary="Predict flood risk 24 hours from now (GET)",

)
def forecast_get(

    lat: float = Query(..., ge=-90,  le=90,  description="Latitude"),

    lon: float = Query(..., ge=-180, le=180, description="Longitude"),

) -> ForecastResponse:
    """Uses the last 24 h of observed weather to predict flood risk 24 h from now."""
    return _run_forecast(lat, lon)


@app.post(

    "/forecast",

    response_model=ForecastResponse,

    tags=["inference"],

    summary="Predict flood risk 24 hours from now (POST)",

)
def forecast_post(body: PredictRequest) -> ForecastResponse:
    """Same as GET /forecast but accepts JSON body."""
    return _run_forecast(body.lat, body.lon)


def _run_forecast(lat: float, lon: float) -> ForecastResponse:
    try:
        result = predict_24h(lat, lon)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc
    except RuntimeError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Forecast failed: {exc}") from exc
    return ForecastResponse(**result)