File size: 12,945 Bytes
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d00d7c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f489938
 
 
 
d00d7c6
f489938
 
 
d00d7c6
 
f489938
 
 
 
88dedfd
 
 
 
 
 
 
 
 
 
f489938
 
 
 
 
ee00e7c
f489938
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
 
 
f489938
ee00e7c
 
f489938
 
 
ee00e7c
f489938
 
ee00e7c
f489938
 
3361a9a
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
 
 
 
 
 
f489938
 
 
ee00e7c
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88dedfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f489938
ee00e7c
f489938
 
ee00e7c
b382650
 
 
f489938
ee00e7c
 
f489938
ee00e7c
f489938
 
 
 
 
 
 
 
d7e18fc
fbf6b81
 
f489938
ee00e7c
4fd96c2
f489938
813a5c6
d00d7c6
 
f489938
88dedfd
 
 
 
 
 
ee00e7c
 
88dedfd
ee00e7c
 
 
 
f489938
 
ee00e7c
 
 
 
 
 
88dedfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
88dedfd
 
ee00e7c
88dedfd
 
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
f489938
 
ee00e7c
b382650
 
 
f489938
ee00e7c
 
f489938
ee00e7c
f489938
 
 
 
 
 
 
 
 
 
d7e18fc
f489938
 
 
 
 
4fd96c2
f489938
813a5c6
88dedfd
 
 
 
 
 
813a5c6
f489938
 
 
 
ee00e7c
88dedfd
ee00e7c
 
f489938
ee00e7c
 
 
f489938
ee00e7c
 
 
f489938
88dedfd
 
 
 
 
 
 
 
 
 
 
b241f9d
88dedfd
b241f9d
 
88dedfd
 
 
b241f9d
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
f489938
 
ee00e7c
f489938
 
 
 
 
 
ee00e7c
 
f489938
 
 
 
 
 
 
 
 
 
ee00e7c
f489938
 
 
 
 
 
 
 
 
 
 
ee00e7c
f489938
ee00e7c
f489938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee00e7c
f489938
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import os
from datetime import datetime, timedelta
import tempfile

import gradio as gr
import hopsworks
import numpy as np
import pandas as pd
from xgboost import XGBRegressor

from functions.util import plot_air_quality_forecast


# -------------------------
# CONFIG
# -------------------------


SENSOR_CANONICAL = {
    # Whitehall Street
    "whitehall_street": "whitehall_street",
    "whitehall": "whitehall_street",

    # Meadowside
    "meadowside": "meadowside",

    # Lochee Road
    "lochee_road": "lochee_road",

    # Seagate
    "seagate": "seagate",

    # Broughty Ferry Road
    "broughty_ferry_road": "broughty_ferry_road",
    "ferry_road": "broughty_ferry_road",

    # Mains Loan (typo hell)
    "mains_loan": "mains_loan",
    "mains_laon": "mains_loan",   # typo
    "mains_loa": "mains_loan",    # typo
}

CITY_NAME = "Dundee"

# internal sensor names (as in Hopsworks) -> pretty labels for UI
SENSOR_LABELS = {
    "whitehall_street": "Whitehall Street",
    "meadowside": "Meadowside",
    "lochee_road": "Lochee Road",
    "seagate": "Seagate",
    "broughty_ferry_road": "Broughty Ferry Road",
    "mains_loan": "Mains Loan",
}

DISPLAY_TO_INTERNAL = {v: k for k, v in SENSOR_LABELS.items()}

feature_order = [
    "date", "pm10", "no2",
    "temperature_2m_mean", "precipitation_sum",
    "wind_speed_10m_max", "wind_direction_10m_dominant",
    "pm25_lag1", "pm25_lag2", "pm25_lag3",
    "sensor_broughty_ferry_road", "sensor_lochee_road",
    "sensor_mains_loan", "sensor_meadowside",
    "sensor_seagate", "sensor_whitehall_street"
]


# -------------------------
# HOPSWORKS + MODEL LOADING (LAZY)
# -------------------------

_resources = None


def _login_hopsworks():
    api_key = os.environ.get("HOPSWORKS_API_KEY")
    if not api_key:
        raise RuntimeError(
            "HOPSWORKS_API_KEY is not set. "
            "Add it as a secret in your HuggingFace Space settings."
        )
    project = hopsworks.login(api_key_value=api_key)
    return project


def load_resources():
    """
    Connect to Hopsworks and load model + feature view + weather FG.

    This is our SINGLE lag-aware model setup.
    """
    project = _login_hopsworks()
    fs = project.get_feature_store()

    fv = fs.get_feature_view("dundee_fv", version=3)  # lag-feature FeatureView
    fv.init_batch_scoring(1)

    weather_fg = fs.get_feature_group("dundee_weather_fg", version=1)

    mr = project.get_model_registry()
    model_obj = mr.get_model("dundee_pm25_xgboost", version=2)
    model_dir = model_obj.download()

    model = XGBRegressor()
    model.load_model(model_dir + "/model.json")

    return {
        "project": project,
        "fs": fs,
        "fv": fv,
        "weather_fg": weather_fg,
        "model": model,
    }


def get_resources():
    """Lazy loader for the single model configuration."""
    global _resources
    if _resources is None:
        _resources = load_resources()
    return _resources


# -------------------------
# HELPER: AQI CATEGORY (optional, not yet used in UI)
# -------------------------

def pm25_to_aqi_category(pm25: float) -> str:
    """Rough AQI-style category from PM2.5 (µg/m3)."""
    if pm25 <= 12:
        return "Good 😊"
    if pm25 <= 35.4:
        return "Moderate 🙂"
    if pm25 <= 55.4:
        return "Unhealthy for Sensitive Groups 😐"
    if pm25 <= 150.4:
        return "Unhealthy 😷"
    if pm25 <= 250.4:
        return "Very Unhealthy 🤢"
    return "Hazardous ☠️"


def sensor_one_hot(sensor_internal: str):
    cols = {
        "sensor_broughty_ferry_road": 0,
        "sensor_lochee_road": 0,
        "sensor_mains_loan": 0,
        "sensor_meadowside": 0,
        "sensor_seagate": 0,
        "sensor_whitehall_street": 0,
    }
    col_name = f"sensor_{sensor_internal}"
    if col_name in cols:
        cols[col_name] = 1
    return cols


# -------------------------
# FORECAST LOGIC (lag-aware model)
# -------------------------

def generate_forecast(sensor_internal: str, days: int) -> str | None:
    print("DEBUG: Sensor internal =", sensor_internal)
    print("DEBUG: Canonical =", SENSOR_CANONICAL.get(sensor_internal, sensor_internal))

    """
    Generate forecast PNG path for given sensor.
    Returns path to saved PNG or None if no data.
    """
    resources = get_resources()
    model = resources["model"]
    weather_fg = resources["weather_fg"]
    project = resources["project"]

    today = datetime.utcnow().date()

    # Future weather (city-level, same for all sensors)
    df_future = weather_fg.read().sort_values("date")
    df_future["date"] = pd.to_datetime(df_future["date"], unit="ms").dt.date
    print("DEBUG: WEATHER FUTURE DATES:", df_future["date"].tail(15).tolist())
    print("DEBUG: Today:", today)

    # PM2.5 history for this sensor
    aq_fg = project.get_feature_store().get_feature_group("dundee_air_quality", version=1)
    aq_df = aq_fg.read()
    aq_df["date"] = pd.to_datetime(aq_df["date"], unit="ms").dt.date
    canonical = SENSOR_CANONICAL.get(sensor_internal, sensor_internal)
    aq_df = aq_df[aq_df["sensor"] == canonical].sort_values("date")

    pm25_history = list(aq_df["pm25"].values[-3:])
    pm10_history = list(aq_df["pm10"].values[-3:])
    no2_history  = list(aq_df["no2"].values[-3:])
    print("DEBUG: AQ DF HEAD\n", aq_df.head())
    print("DEBUG: AQ DF UNIQUE SENSORS:", aq_df["sensor"].unique())

    if aq_df.empty:
        return None
    
    if len(pm25_history) < 3:
        # Not enough history, bail gracefully
        return None

    preds = []

    for offset in range(1, days + 1):
        target_date = today + timedelta(days=offset)
        row = df_future[df_future["date"] == target_date]
        if len(row) == 0:
            continue

        weather = row.iloc[0]

        # Build sensor one-hot
        sensor_flags = sensor_one_hot(sensor_internal)

        # Build X row *exactly matching model training*
        X = {
            "date": target_date.toordinal(),  # model saw date as integer-ish
            "pm10": pm10_history[-1],
            "no2": no2_history[-1],
            "temperature_2m_mean": weather["temperature_2m_mean"],
            "precipitation_sum": weather["precipitation_sum"],
            "wind_speed_10m_max": weather["wind_speed_10m_max"],
            "wind_direction_10m_dominant": weather["wind_direction_10m_dominant"],
            "pm25_lag1": pm25_history[-1],
            "pm25_lag2": pm25_history[-2],
            "pm25_lag3": pm25_history[-3],
            **sensor_flags
        }

        # Convert to DataFrame
        X_df = pd.DataFrame([X])
        X_df = X_df[feature_order]

        pred = float(model.predict(X_df)[0])
        preds.append({"date": target_date, "predicted_pm25": pred})

        # update histories
        pm25_history.append(pred)
        pm10_history.append(pm10_history[-1])  # no future pm10 → hold last known
        no2_history.append(no2_history[-1])

    if not preds:
        return None

    df_preds = pd.DataFrame(preds)

    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    sensor_label = SENSOR_LABELS[sensor_internal]

    plot_air_quality_forecast(
        CITY_NAME,
        sensor_label,
        df_preds,
        tmp_path,
        hindcast=False,
    )

    return tmp_path


# -------------------------
# HINDCAST LOGIC (lag-aware model)
# -------------------------

def generate_hindcast(sensor_internal: str, days: int) -> str | None:
    print("DEBUG: Sensor internal =", sensor_internal)
    print("DEBUG: Canonical =", SENSOR_CANONICAL.get(sensor_internal, sensor_internal))

    """
    Generate hindcast PNG path for given sensor.
    Returns path to saved PNG or None if no data.
    """
    resources = get_resources()
    model = resources["model"]
    weather_fg = resources["weather_fg"]
    project = resources["project"]

    today = datetime.utcnow().date()
    start_date = today - timedelta(days=days + 3)  # extra for lags
    end_date = today

    # Weather history
    weather_df = weather_fg.read()
    weather_df["date"] = pd.to_datetime(weather_df["date"], unit="ms").dt.date
    weather_df = weather_df[
        (weather_df["date"] >= start_date) & (weather_df["date"] <= end_date)
    ].sort_values("date")

    # PM2.5 history per sensor
    aq_fg = project.get_feature_store().get_feature_group("dundee_air_quality", version=1)
    aq_df = aq_fg.read()
    aq_df["date"] = pd.to_datetime(aq_df["date"], unit="ms").dt.date
    canonical = SENSOR_CANONICAL.get(sensor_internal, sensor_internal)
    aq_df = aq_df[aq_df["sensor"] == canonical].sort_values("date")

    pm25_history = list(aq_df["pm25"].values[-3:])
    pm10_history = list(aq_df["pm10"].values[-3:])
    no2_history  = list(aq_df["no2"].values[-3:])


    if aq_df.empty:
        return None

    # Merge weather + actual pm25
    df = pd.merge(weather_df, aq_df[["date", "pm25", "pm10", "no2"]], on="date")
    if df.empty:
        return None

    df["pm25_lag1"] = df["pm25"].shift(1)
    df["pm25_lag2"] = df["pm25"].shift(2)
    df["pm25_lag3"] = df["pm25"].shift(3)

    df = df.dropna().tail(days)
    if df.empty:
        return None

    # Build sensor one-hot flags
    sensor_flags = sensor_one_hot(sensor_internal)

    df["sensor_broughty_ferry_road"] = sensor_flags["sensor_broughty_ferry_road"]
    df["sensor_lochee_road"]         = sensor_flags["sensor_lochee_road"]
    df["sensor_mains_loan"]          = sensor_flags["sensor_mains_loan"]
    df["sensor_meadowside"]          = sensor_flags["sensor_meadowside"]
    df["sensor_seagate"]             = sensor_flags["sensor_seagate"]
    df["sensor_whitehall_street"]    = sensor_flags["sensor_whitehall_street"]

    # Convert date to ordinal (model expects numeric date)
    df["date_ordinal"] = df["date"].apply(lambda d: d.toordinal())

    # Build X with correct order using the ordinal date
    X_df = df.assign(date=df["date_ordinal"])[feature_order]

    # Predict hindcast
    df["predicted_pm25"] = model.predict(X_df)
    df_hind = df  # df still has real dates!

    tmp_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    sensor_label = SENSOR_LABELS[sensor_internal]

    plot_air_quality_forecast(
        CITY_NAME,
        sensor_label,
        df_hind,
        tmp_path,
        hindcast=True,
    )

    return tmp_path


# -------------------------
# GRADIO UI (MAX VIBES, SINGLE MODEL)
# -------------------------

def run_dashboard(sensor_display: str, forecast_days: int, hindcast_days: int):
    try:
        sensor_internal = DISPLAY_TO_INTERNAL[sensor_display]
    except KeyError:
        return None, None, f"Unknown sensor: {sensor_display}"

    try:
        forecast_path = generate_forecast(sensor_internal, forecast_days)
        hindcast_path = generate_hindcast(sensor_internal, hindcast_days)
    except Exception as e:
        # Don't explode the UI; show error text and empty images
        return None, None, f"⚠️ Something went wrong: {str(e)}"

    if forecast_path is None and hindcast_path is None:
        return None, None, "No data available for this sensor/time range yet."

    summary_text = ""
    if forecast_path is not None:
        summary_text = (
            f"✅ Forecast generated for **{sensor_display}** using the lag-aware Dundee PM2.5 model.\n\n"
            f"City: **{CITY_NAME}**  \n"
            f"Last updated: **{datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}**"
        )

    return forecast_path, hindcast_path, summary_text


with gr.Blocks(theme="soft") as demo:
    gr.Markdown(
        """
        # 🌤️ Dundee Air Quality Dashboard  
        Lag-aware PM2.5 forecasts and hindcasts for Dundee’s air quality sensors.

        Select a **sensor**, set your horizons, and hit **Update**.
        """
    )

    with gr.Row():
        sensor_dropdown = gr.Dropdown(
            choices=list(DISPLAY_TO_INTERNAL.keys()),
            value="Meadowside",
            label="Sensor",
            info="Choose which sensor in Dundee to analyze.",
        )

    with gr.Row():
        forecast_days_slider = gr.Slider(
            minimum=3,
            maximum=10,
            value=7,
            step=1,
            label="Forecast days (future)",
        )
        hindcast_days_slider = gr.Slider(
            minimum=3,
            maximum=10,
            value=7,
            step=1,
            label="Hindcast days (past)",
        )

    update_btn = gr.Button("🚀 Update dashboard", variant="primary")

    with gr.Row():
        forecast_img = gr.Image(label="Forecast (PM2.5)", show_label=True)
        hindcast_img = gr.Image(label="Hindcast (PM2.5)", show_label=True)

    summary_box = gr.Markdown()

    update_btn.click(
        fn=run_dashboard,
        inputs=[sensor_dropdown, forecast_days_slider, hindcast_days_slider],
        outputs=[forecast_img, hindcast_img, summary_box],
    )


if __name__ == "__main__":
    demo.launch()