File size: 4,212 Bytes
9b8ddd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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,
    )