File size: 15,480 Bytes
81f23e0 | 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | """Fast Gradio dashboard for the wine-production forecast Space.
This version is optimized for Hugging Face Spaces: it loads the interface
quickly and only evaluates/trains the forecasting models after the user clicks
the forecast button. That avoids long startup times on free CPU spaces.
"""
from __future__ import annotations
from functools import lru_cache
import gradio as gr
import pandas as pd
from future_forecast import evaluate_forecasters, forecast_2026, load_history
def fmt(value: float | int, decimals: int = 0) -> str:
if pd.isna(value):
return ""
return f"{value:,.{decimals}f}"
def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
view = data.copy()
for column in [
"vineyard_area_ha",
"predicted_production_hl",
"lower_90_hl",
"upper_90_hl",
]:
if column in view.columns:
view[column] = view[column].map(lambda value: fmt(value))
return view.rename(
columns={
"region": "Region",
"year_start": "Campaign year",
"vineyard_area_ha": "Area (ha)",
"selected_model": "Selected model",
"predicted_production_hl": "Predicted production (hl)",
"lower_90_hl": "Lower empirical 90% (hl)",
"upper_90_hl": "Upper empirical 90% (hl)",
}
)
def format_metrics_table(data: pd.DataFrame) -> pd.DataFrame:
view = data[["model", "MAE", "RMSE", "R2"]].copy()
view["MAE"] = view["MAE"].map(lambda value: fmt(value))
view["RMSE"] = view["RMSE"].map(lambda value: fmt(value))
view["R2"] = view["R2"].map(lambda value: f"{value:.3f}")
return view.rename(
columns={
"model": "Model",
"MAE": "MAE (hl)",
"RMSE": "RMSE (hl)",
"R2": "R2",
}
)
@lru_cache(maxsize=1)
def get_evaluation():
"""Compute model evaluation once, then reuse it for later clicks."""
return evaluate_forecasters()
history = load_history()
latest_area = (
history.sort_values(["region", "year_start"])
.groupby("region", as_index=False)
.tail(1)[["region", "vineyard_area_ha"]]
)
region_choices = sorted(history["region"].astype(str).unique().tolist())
default_region = region_choices[0]
area_map = dict(zip(latest_area["region"].astype(str), latest_area["vineyard_area_ha"]))
def update_area(region: str):
return gr.update(value=round(float(area_map.get(region, 0.0)), 2))
def welcome_card() -> str:
return """
<section class="result-card empty">
<div class="eyebrow">Ready to forecast</div>
<h2>Select a region</h2>
<p class="note">
Click <b>Forecast 2026/27</b> to run the model. The first forecast
may take a little longer because the Space evaluates and caches the
forecasting models.
</p>
</section>
"""
def simulate(region: str, vineyard_area_ha: float):
if not region:
raise gr.Error("Please choose a region.")
if vineyard_area_ha is None or vineyard_area_ha <= 0:
raise gr.Error("Vineyard area must be greater than 0.")
evaluation = get_evaluation()
forecast = forecast_2026(
evaluation=evaluation,
area_overrides={region: float(vineyard_area_ha)},
)
selected = forecast[forecast["region"] == region].copy().reset_index(drop=True)
if selected.empty:
raise gr.Error(f"No forecast returned for region: {region}")
row = selected.iloc[0]
validation_metrics = (
evaluation.metrics.query("split == 'rolling_validation_2018_2022'")
.sort_values("MAE")
.reset_index(drop=True)
)
test_metrics = (
evaluation.metrics.query("split == 'test_2023_2025'")
.sort_values("MAE")
.reset_index(drop=True)
)
summary = f"""
<section class="result-card">
<div class="eyebrow">Forecast result - 2026/27</div>
<h2>{row["region"]}</h2>
<div class="result-grid">
<div class="result-main">
<span>Predicted production</span>
<strong>{fmt(row["predicted_production_hl"])} hl</strong>
</div>
<div class="result-mini">
<span>Empirical 90% interval</span>
<strong>{fmt(row["lower_90_hl"])} to {fmt(row["upper_90_hl"])} hl</strong>
</div>
<div class="result-mini">
<span>Area scenario</span>
<strong>{fmt(row["vineyard_area_ha"], 2)} ha</strong>
</div>
<div class="result-mini">
<span>Selected model</span>
<strong>{row["selected_model"]}</strong>
</div>
</div>
<p class="note">
This is a scenario forecast. Changing vineyard area in the interface
does not demonstrate a causal effect.
</p>
</section>
"""
model_badge = f"""
<div class="metric-row">
<div class="metric-card">
<span>Selected model</span>
<strong>{evaluation.selected_model}</strong>
</div>
<div class="metric-card">
<span>Empirical interval</span>
<strong>+/- {fmt(evaluation.interval_half_width)} hl</strong>
</div>
<div class="metric-card">
<span>Regions covered</span>
<strong>{len(region_choices)}</strong>
</div>
</div>
"""
return (
model_badge,
summary,
format_forecast_table(selected),
format_metrics_table(validation_metrics),
format_metrics_table(test_metrics),
format_forecast_table(forecast),
)
custom_css = """
:root {
--wine-900: #2b0715;
--wine-800: #4c0d25;
--wine-700: #74133a;
--wine-500: #9b2850;
--cream: #fff8f2;
--paper: #ffffff;
--gold: #c79a45;
--gold-soft: #f3dfb8;
--ink: #21161a;
--muted: #75666b;
}
body {
background: #fbf4ee !important;
}
.gradio-container {
max-width: 1220px !important;
margin: 0 auto !important;
padding: 28px 34px !important;
background:
radial-gradient(circle at 8% 0%, rgba(199, 154, 69, 0.22), transparent 25%),
radial-gradient(circle at 95% 10%, rgba(116, 19, 58, 0.18), transparent 25%),
linear-gradient(180deg, #fffaf7 0%, #f8eee8 100%) !important;
}
.hero {
position: relative;
overflow: hidden;
border-radius: 30px;
padding: 42px 44px;
margin-bottom: 22px;
color: white;
background:
radial-gradient(circle at 86% 24%, rgba(199, 154, 69, 0.50), transparent 24%),
linear-gradient(135deg, var(--wine-900) 0%, var(--wine-800) 48%, var(--wine-700) 100%);
box-shadow: 0 26px 60px rgba(43, 7, 21, 0.28);
}
.hero,
.hero * {
color: #ffffff !important;
}
.hero::after {
content: "";
position: absolute;
inset: auto -90px -120px auto;
width: 310px;
height: 310px;
border-radius: 50%;
border: 38px solid rgba(255, 255, 255, 0.08);
}
.kicker {
display: inline-flex;
border: 1px solid rgba(255, 255, 255, 0.28);
border-radius: 999px;
padding: 7px 13px;
color: #ffe9bc !important;
background: rgba(255, 255, 255, 0.10);
font-size: 0.82rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hero h1 {
margin: 18px 0 10px;
max-width: 760px;
font-size: clamp(2.2rem, 5vw, 4.15rem);
line-height: 0.98;
letter-spacing: -0.045em;
color: #ffffff !important;
}
.hero p {
max-width: 780px;
margin: 0;
color: rgba(255, 255, 255, 0.84);
font-size: 1.08rem;
color: rgba(255, 255, 255, 0.90) !important;
}
.hero-pills {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 24px;
}
.hero-pills span {
padding: 9px 13px;
border-radius: 999px;
color: #fff7e9;
background: rgba(255, 255, 255, 0.13);
border: 1px solid rgba(255, 255, 255, 0.18);
color: #fff7e9 !important;
}
.metric-row {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px;
margin-bottom: 18px;
}
.metric-card {
padding: 18px 20px;
border-radius: 22px;
background: rgba(255, 255, 255, 0.82);
border: 1px solid rgba(116, 19, 58, 0.11);
box-shadow: 0 16px 38px rgba(43, 7, 21, 0.08);
}
.metric-card span {
display: block;
color: var(--muted);
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric-card strong {
display: block;
margin-top: 7px;
color: var(--wine-800);
font-size: 1.25rem;
}
.interpretation {
margin-bottom: 22px;
padding: 16px 18px;
border-radius: 18px;
color: var(--ink);
background: linear-gradient(90deg, rgba(243, 223, 184, 0.88), rgba(255, 255, 255, 0.72));
border: 1px solid rgba(199, 154, 69, 0.34);
}
.panel-card {
padding: 20px !important;
border-radius: 24px !important;
background: rgba(255, 255, 255, 0.86) !important;
border: 1px solid rgba(116, 19, 58, 0.11) !important;
box-shadow: 0 18px 42px rgba(43, 7, 21, 0.08) !important;
}
.section-title {
color: var(--wine-900);
}
.result-card {
min-height: 260px;
padding: 28px;
border-radius: 26px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(255, 245, 246, 0.98));
border: 1px solid rgba(116, 19, 58, 0.13);
box-shadow: 0 18px 44px rgba(43, 7, 21, 0.12);
}
.result-card.empty {
display: flex;
flex-direction: column;
justify-content: center;
}
.eyebrow {
color: var(--gold);
font-weight: 800;
font-size: 0.78rem;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.result-card h2 {
margin: 5px 0 20px;
color: var(--wine-900);
font-size: 2.15rem;
}
.result-grid {
display: grid;
grid-template-columns: 1.2fr 1fr;
gap: 14px;
}
.result-main,
.result-mini {
border-radius: 18px;
padding: 16px;
background: var(--paper);
border: 1px solid rgba(116, 19, 58, 0.08);
}
.result-main {
background: linear-gradient(135deg, var(--wine-800), var(--wine-500));
color: white;
}
.result-main,
.result-main * {
color: #ffffff !important;
}
.result-main span,
.result-mini span {
display: block;
color: var(--muted);
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.result-main span {
color: rgba(255, 255, 255, 0.78);
color: rgba(255, 255, 255, 0.82) !important;
}
.result-main strong,
.result-mini strong {
display: block;
margin-top: 6px;
color: var(--wine-700);
font-size: 1.08rem;
}
.result-main strong {
color: white;
font-size: 1.65rem;
color: #ffffff !important;
}
.note {
margin: 18px 0 0;
color: var(--muted);
font-size: 0.93rem;
}
button.primary {
background: linear-gradient(135deg, var(--wine-800), var(--wine-500)) !important;
border: none !important;
color: white !important;
box-shadow: 0 14px 28px rgba(116, 19, 58, 0.24) !important;
}
@media (max-width: 860px) {
.metric-row,
.result-grid {
grid-template-columns: 1fr;
}
.hero {
padding: 30px 24px;
}
}
"""
theme = gr.themes.Soft(
primary_hue="rose",
secondary_hue="orange",
neutral_hue="stone",
)
empty_metrics = pd.DataFrame(columns=["Model", "MAE (hl)", "RMSE (hl)", "R2"])
empty_forecast = pd.DataFrame(
columns=[
"Region",
"Campaign year",
"Area (ha)",
"Selected model",
"Predicted production (hl)",
"Lower empirical 90% (hl)",
"Upper empirical 90% (hl)",
]
)
with gr.Blocks(
title="Wine Production Dashboard",
theme=theme,
css=custom_css,
) as demo:
gr.HTML(
"""
<section class="hero">
<span class="kicker">Professional dashboard - 2026/27 forecast</span>
<h1>Wine Production Dashboard</h1>
<p>
Explore experimental wine-production forecasts for Portuguese
viticultural regions using lagged production, vineyard-area
scenarios, and rolling-origin validation.
</p>
<div class="hero-pills">
<span>IVV official data</span>
<span>One-step-ahead forecast</span>
<span>Scenario simulator</span>
</div>
</section>
"""
)
model_badge = gr.HTML(
f"""
<div class="metric-row">
<div class="metric-card">
<span>Status</span>
<strong>Ready</strong>
</div>
<div class="metric-card">
<span>Model</span>
<strong>Computed on click</strong>
</div>
<div class="metric-card">
<span>Regions covered</span>
<strong>{len(region_choices)}</strong>
</div>
</div>
"""
)
gr.HTML(
"""
<div class="interpretation">
<b>Important interpretation.</b> Vineyard area is a scenario input,
not a causal estimate. The 90% interval is empirical and based on
validation errors, not a formal confidence interval.
</div>
"""
)
with gr.Row():
with gr.Column(scale=1, elem_classes=["panel-card"]):
gr.Markdown("### Simulation inputs", elem_classes=["section-title"])
region = gr.Dropdown(
choices=region_choices,
value=default_region,
label="Region",
info="Choose a Portuguese wine region.",
)
area = gr.Number(
value=round(float(area_map.get(default_region, 0.0)), 2),
label="Vineyard area (ha)",
precision=2,
info="Scenario input only; not a causal effect estimate.",
)
run_button = gr.Button("Forecast 2026/27", variant="primary")
with gr.Column(scale=2, elem_classes=["panel-card"]):
gr.Markdown("### Prediction result", elem_classes=["section-title"])
summary = gr.HTML(value=welcome_card())
result_table = gr.Dataframe(
value=empty_forecast,
label="Forecast result",
interactive=False,
)
with gr.Accordion("Validation metrics", open=False):
validation_table = gr.Dataframe(
value=empty_metrics,
label="Rolling validation 2018-2022",
interactive=False,
)
with gr.Accordion("Final one-step-ahead test metrics", open=False):
test_table = gr.Dataframe(
value=empty_metrics,
label="Test years 2023-2025",
interactive=False,
)
with gr.Accordion("Forecast table for all regions", open=False):
all_forecasts_table = gr.Dataframe(
value=empty_forecast,
label="Default 2026/27 forecasts for all regions",
interactive=False,
)
region.change(fn=update_area, inputs=region, outputs=area)
run_button.click(
fn=simulate,
inputs=[region, area],
outputs=[
model_badge,
summary,
result_table,
validation_table,
test_table,
all_forecasts_table,
],
)
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|