vbdnewmodel / app /api_server.py
neeraj-ceew's picture
Add 8-horizon dengue forecast API
9b8ddd4
Raw History Blame Contribute Delete
4.21 kB
"""
FastAPI server β€” 8-horizon dengue forecast API.
Endpoints
---------
GET / redirect to /docs
GET /health service status + loaded models
GET /districts list of valid district names
POST /predict produce 1..8 week-ahead predictions
Run locally:
uvicorn app.api_server:app --host 0.0.0.0 --port 7860 --reload
"""
from __future__ import annotations
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from app.schemas import (
HealthResponse,
HorizonPrediction,
PredictionRequest,
PredictionResponse,
)
from app.panel_loader import load_base_panel, get_districts, get_historical_range
from app.feature_builder import build_feature_panel_for_request
from app.inference import load_all_models, predict_all_horizons
# ── Lifespan: load models + historical panel once ─────────────────────────────
_state: dict = {}
@asynccontextmanager
async def lifespan(_app: FastAPI):
print("[startup] Loading bundled historical panel...")
_state["panel"] = load_base_panel(year_max=2025)
print(f"[startup] Historical panel rows: {len(_state['panel'])}")
print("[startup] Loading trained models...")
info = load_all_models()
_state["loaded_models"] = info["loaded"]
print(f"[startup] Loaded: {info['loaded']}")
_state["districts"] = get_districts(_state["panel"])
print(f"[startup] {len(_state['districts'])} districts available")
yield
_state.clear()
app = FastAPI(
title="EWS Dengue 8-Horizon Forecast API",
description=(
"Predicts dengue incidence rate and case counts for 1, 2, 3, 4, 5, 6, 7, "
"and 8 weeks ahead. Uses Tweedie V6 for h=1-4 directly, and "
"horizon-extension models (built on V6) for h=5-8."
),
version="1.0.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/docs")
@app.get("/health", response_model=HealthResponse)
async def health() -> HealthResponse:
if "panel" not in _state:
raise HTTPException(503, "Service not ready")
yr_min, yr_max = get_historical_range(_state["panel"])
return HealthResponse(
status="ok",
models_loaded=_state["loaded_models"],
n_districts=len(_state["districts"]),
historical_range=f"{yr_min}-{yr_max}",
)
@app.get("/districts")
async def list_districts() -> dict:
return {"districts": _state["districts"], "count": len(_state["districts"])}
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest) -> PredictionResponse:
if "panel" not in _state:
raise HTTPException(503, "Service not ready")
notes: list[str] = []
# 1) Build feature panel for this request
try:
panel, outcome_idx = build_feature_panel_for_request(
request, _state["panel"]
)
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
raise HTTPException(500, f"Feature build failed: {e}")
# 2) Run inference for all 8 horizons
try:
preds = predict_all_horizons(
panel, outcome_idx, request.population,
)
except Exception as e:
raise HTTPException(500, f"Inference failed: {e}")
# 3) Warnings / caveats
if not request.forecast_climate:
notes.append(
"No forecast_climate provided β€” week (present+1) uses district climatology. "
"Horizons 4-8 may be less accurate."
)
if 4 not in outcome_idx:
notes.append("Outcome row for h=4 could not be constructed β€” h=5-8 skipped.")
return PredictionResponse(
district=request.district,
present_year=request.present_year,
present_week=request.present_week,
population=request.population,
predictions=[HorizonPrediction(**p) for p in preds],
notes=notes or None,
)