"""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 """
Ready to forecast
Select a region
Click Forecast 2026/27 to run the model. The first forecast
may take a little longer because the Space evaluates and caches the
forecasting models.
"""
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"""
Forecast result - 2026/27
{row["region"]}
Predicted production
{fmt(row["predicted_production_hl"])} hl
Empirical 90% interval
{fmt(row["lower_90_hl"])} to {fmt(row["upper_90_hl"])} hl
Area scenario
{fmt(row["vineyard_area_ha"], 2)} ha
Selected model
{row["selected_model"]}
This is a scenario forecast. Changing vineyard area in the interface
does not demonstrate a causal effect.
"""
model_badge = f"""
Selected model
{evaluation.selected_model}
Empirical interval
+/- {fmt(evaluation.interval_half_width)} hl
Regions covered
{len(region_choices)}
"""
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(
"""
Professional dashboard - 2026/27 forecast
Wine Production Dashboard
Explore experimental wine-production forecasts for Portuguese
viticultural regions using lagged production, vineyard-area
scenarios, and rolling-origin validation.
IVV official data
One-step-ahead forecast
Scenario simulator
"""
)
model_badge = gr.HTML(
f"""
Status
Ready
Model
Computed on click
Regions covered
{len(region_choices)}
"""
)
gr.HTML(
"""
Important interpretation. 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.
"""
)
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)