Subelinha commited on
Commit
c9ccff3
·
verified ·
1 Parent(s): 38336dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -39
app.py CHANGED
@@ -19,6 +19,13 @@ except ModuleNotFoundError:
19
  from src.future_forecast import evaluate_forecasters, forecast_2026, load_history
20
 
21
 
 
 
 
 
 
 
 
22
  def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
23
  """Return a human-readable forecast table for display in Gradio."""
24
  view = data.copy()
@@ -30,9 +37,7 @@ def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
30
  ]
31
  for column in numeric_columns:
32
  if column in view.columns:
33
- view[column] = view[column].map(
34
- lambda value: f"{value:,.0f}" if pd.notna(value) else ""
35
- )
36
 
37
  return view.rename(
38
  columns={
@@ -47,6 +52,22 @@ def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
47
  )
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  history = load_history()
51
  evaluation = evaluate_forecasters()
52
  base_forecast = forecast_2026(evaluation=evaluation)
@@ -95,64 +116,266 @@ def simulate(region: str, area_ha: float):
95
 
96
  row = selected.iloc[0]
97
  summary = f"""
98
- <div class="summary-card">
99
- <h3>Forecast summary</h3>
100
- <p><b>Region:</b> {row['region']}</p>
101
- <p><b>Campaign:</b> 2026/27</p>
102
- <p><b>Selected model:</b> {row['selected_model']}</p>
103
- <p><b>Vineyard area scenario:</b> {row['vineyard_area_ha']:,.2f} ha</p>
104
- <p><b>Predicted production:</b> {row['predicted_production_hl']:,.0f} hl</p>
105
- <p><b>Empirical 90% interval:</b> {row['lower_90_hl']:,.0f}
106
- to {row['upper_90_hl']:,.0f} hl</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  </div>
108
  """
109
  return summary, format_forecast_table(selected)
110
 
111
 
112
  custom_css = """
 
 
 
 
 
 
 
 
 
 
113
  .gradio-container {
114
- max-width: 1120px !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
- .summary-card {
117
- border: 1px solid #ead7d7;
118
- border-radius: 14px;
119
- padding: 18px;
120
- background: #fff8f8;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  }
122
  """
123
 
124
- theme = gr.themes.Soft(primary_hue="rose", secondary_hue="orange")
125
 
126
  with gr.Blocks(
127
  title="Wine Production Predictor",
128
  theme=theme,
129
  css=custom_css,
130
  ) as demo:
131
- gr.Markdown(
132
  """
133
- # Wine Production Predictor
134
-
135
- Experimental 2026/27 wine-production forecast by Portuguese
136
- viticultural region.
137
-
138
- **Important interpretation:** the vineyard-area input creates a
139
- scenario, not a causal estimate. The empirical 90% interval is based on
140
- observed validation errors and should not be read as a formal
141
- statistical confidence interval.
142
  """
143
  )
144
 
145
- gr.Markdown(
146
  f"""
147
- **Selected one-step-ahead model:** `{evaluation.selected_model}`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- **Empirical 90% interval half-width:** `{evaluation.interval_half_width:,.0f} hl`
 
 
 
 
 
 
 
150
  """
151
  )
152
 
153
  with gr.Row():
154
- with gr.Column(scale=1):
155
- gr.Markdown("### Simulation inputs")
156
  region = gr.Dropdown(
157
  choices=region_choices,
158
  value=default_region,
@@ -170,23 +393,29 @@ with gr.Blocks(
170
  )
171
  run_button = gr.Button("Forecast 2026/27", variant="primary")
172
 
173
- with gr.Column(scale=2):
174
- gr.Markdown("### Prediction result")
175
  summary = gr.HTML()
176
- result_table = gr.Dataframe(label="Forecast result", interactive=False)
 
 
 
 
177
 
178
  with gr.Accordion("Validation metrics", open=False):
179
  gr.Dataframe(
180
- value=validation_metrics[["model", "MAE", "RMSE", "R2"]],
181
  label="Rolling validation 2018-2022",
182
  interactive=False,
 
183
  )
184
 
185
  with gr.Accordion("Final one-step-ahead test metrics", open=False):
186
  gr.Dataframe(
187
- value=test_metrics[["model", "MAE", "RMSE", "R2"]],
188
  label="Test years 2023-2025",
189
  interactive=False,
 
190
  )
191
 
192
  with gr.Accordion("Forecast table for all regions", open=False):
@@ -194,6 +423,7 @@ with gr.Blocks(
194
  value=format_forecast_table(base_forecast),
195
  label="Default 2026/27 forecasts for all regions",
196
  interactive=False,
 
197
  )
198
 
199
  region.change(fn=update_area, inputs=region, outputs=area)
 
19
  from src.future_forecast import evaluate_forecasters, forecast_2026, load_history
20
 
21
 
22
+ def number(value: float | int, decimals: int = 0) -> str:
23
+ """Format numbers for cards and tables."""
24
+ if pd.isna(value):
25
+ return ""
26
+ return f"{value:,.{decimals}f}"
27
+
28
+
29
  def format_forecast_table(data: pd.DataFrame) -> pd.DataFrame:
30
  """Return a human-readable forecast table for display in Gradio."""
31
  view = data.copy()
 
37
  ]
38
  for column in numeric_columns:
39
  if column in view.columns:
40
+ view[column] = view[column].map(lambda value: number(value))
 
 
41
 
42
  return view.rename(
43
  columns={
 
52
  )
53
 
54
 
55
+ def format_metrics_table(data: pd.DataFrame) -> pd.DataFrame:
56
+ """Round and rename metric columns for a cleaner dashboard table."""
57
+ view = data[["model", "MAE", "RMSE", "R2"]].copy()
58
+ view["MAE"] = view["MAE"].map(lambda value: number(value))
59
+ view["RMSE"] = view["RMSE"].map(lambda value: number(value))
60
+ view["R2"] = view["R2"].map(lambda value: f"{value:.3f}")
61
+ return view.rename(
62
+ columns={
63
+ "model": "Model",
64
+ "MAE": "MAE (hl)",
65
+ "RMSE": "RMSE (hl)",
66
+ "R2": "R²",
67
+ }
68
+ )
69
+
70
+
71
  history = load_history()
72
  evaluation = evaluate_forecasters()
73
  base_forecast = forecast_2026(evaluation=evaluation)
 
116
 
117
  row = selected.iloc[0]
118
  summary = f"""
119
+ <div class="forecast-card">
120
+ <div class="forecast-eyebrow">2026/27 forecast</div>
121
+ <div class="forecast-title">{row['region']}</div>
122
+ <div class="forecast-grid">
123
+ <div class="big-stat">
124
+ <span>Predicted production</span>
125
+ <strong>{number(row['predicted_production_hl'])} hl</strong>
126
+ </div>
127
+ <div class="big-stat">
128
+ <span>Empirical 90% interval</span>
129
+ <strong>{number(row['lower_90_hl'])} – {number(row['upper_90_hl'])} hl</strong>
130
+ </div>
131
+ <div class="big-stat">
132
+ <span>Vineyard-area scenario</span>
133
+ <strong>{number(row['vineyard_area_ha'], 2)} ha</strong>
134
+ </div>
135
+ <div class="big-stat">
136
+ <span>Selected model</span>
137
+ <strong>{row['selected_model']}</strong>
138
+ </div>
139
+ </div>
140
+ <p class="card-note">
141
+ Scenario output only: changing vineyard area does not prove causality.
142
+ </p>
143
  </div>
144
  """
145
  return summary, format_forecast_table(selected)
146
 
147
 
148
  custom_css = """
149
+ :root {
150
+ --wine: #6f1232;
151
+ --wine-dark: #3d071a;
152
+ --rose: #fff4f6;
153
+ --rose-2: #fbe7eb;
154
+ --gold: #c29348;
155
+ --ink: #24151a;
156
+ --muted: #76676b;
157
+ }
158
+
159
  .gradio-container {
160
+ max-width: 1180px !important;
161
+ margin: 0 auto !important;
162
+ background:
163
+ radial-gradient(circle at 10% 0%, rgba(194, 147, 72, 0.18), transparent 26%),
164
+ radial-gradient(circle at 95% 8%, rgba(111, 18, 50, 0.16), transparent 24%),
165
+ linear-gradient(180deg, #fffafa 0%, #fbf5f1 100%) !important;
166
+ }
167
+
168
+ .hero {
169
+ border-radius: 28px;
170
+ padding: 34px 38px;
171
+ margin: 8px 0 22px;
172
+ color: white;
173
+ background:
174
+ linear-gradient(135deg, rgba(61, 7, 26, 0.98), rgba(111, 18, 50, 0.94)),
175
+ radial-gradient(circle at 85% 20%, rgba(194, 147, 72, 0.45), transparent 28%);
176
+ box-shadow: 0 22px 55px rgba(61, 7, 26, 0.22);
177
+ }
178
+
179
+ .hero-kicker {
180
+ display: inline-block;
181
+ padding: 6px 12px;
182
+ border: 1px solid rgba(255, 255, 255, 0.28);
183
+ border-radius: 999px;
184
+ color: #ffe6b8;
185
+ font-size: 0.84rem;
186
+ letter-spacing: 0.08em;
187
+ text-transform: uppercase;
188
+ }
189
+
190
+ .hero h1 {
191
+ margin: 14px 0 8px;
192
+ font-size: clamp(2rem, 4vw, 3.5rem);
193
+ line-height: 1.02;
194
+ }
195
+
196
+ .hero p {
197
+ max-width: 780px;
198
+ color: rgba(255, 255, 255, 0.86);
199
+ font-size: 1.04rem;
200
+ }
201
+
202
+ .metric-row {
203
+ display: grid;
204
+ grid-template-columns: repeat(3, minmax(0, 1fr));
205
+ gap: 14px;
206
+ margin: 0 0 20px;
207
+ }
208
+
209
+ .metric-card {
210
+ border: 1px solid rgba(111, 18, 50, 0.10);
211
+ border-radius: 20px;
212
+ padding: 18px 20px;
213
+ background: rgba(255, 255, 255, 0.78);
214
+ box-shadow: 0 12px 34px rgba(61, 7, 26, 0.08);
215
+ }
216
+
217
+ .metric-card span {
218
+ display: block;
219
+ color: var(--muted);
220
+ font-size: 0.83rem;
221
+ text-transform: uppercase;
222
+ letter-spacing: 0.06em;
223
+ }
224
+
225
+ .metric-card strong {
226
+ display: block;
227
+ margin-top: 6px;
228
+ color: var(--wine-dark);
229
+ font-size: 1.25rem;
230
+ }
231
+
232
+ .interpretation {
233
+ border-left: 5px solid var(--gold);
234
+ border-radius: 18px;
235
+ padding: 16px 18px;
236
+ margin-bottom: 22px;
237
+ background: rgba(255, 250, 239, 0.86);
238
+ color: var(--ink);
239
  }
240
+
241
+ .panel-card {
242
+ border: 1px solid rgba(111, 18, 50, 0.11) !important;
243
+ border-radius: 24px !important;
244
+ padding: 18px !important;
245
+ background: rgba(255, 255, 255, 0.84) !important;
246
+ box-shadow: 0 16px 38px rgba(61, 7, 26, 0.07) !important;
247
+ }
248
+
249
+ .section-title {
250
+ color: var(--wine-dark);
251
+ margin-bottom: 6px;
252
+ }
253
+
254
+ .forecast-card {
255
+ border: 1px solid rgba(111, 18, 50, 0.14);
256
+ border-radius: 26px;
257
+ padding: 26px;
258
+ background:
259
+ linear-gradient(180deg, rgba(255, 255, 255, 0.96), rgba(255, 244, 246, 0.98));
260
+ box-shadow: 0 18px 46px rgba(61, 7, 26, 0.12);
261
+ }
262
+
263
+ .forecast-eyebrow {
264
+ color: var(--gold);
265
+ font-weight: 700;
266
+ text-transform: uppercase;
267
+ letter-spacing: 0.08em;
268
+ font-size: 0.78rem;
269
+ }
270
+
271
+ .forecast-title {
272
+ margin-top: 4px;
273
+ color: var(--wine-dark);
274
+ font-size: 2rem;
275
+ font-weight: 800;
276
+ }
277
+
278
+ .forecast-grid {
279
+ display: grid;
280
+ grid-template-columns: repeat(2, minmax(0, 1fr));
281
+ gap: 14px;
282
+ margin-top: 20px;
283
+ }
284
+
285
+ .big-stat {
286
+ border-radius: 18px;
287
+ padding: 15px 16px;
288
+ background: white;
289
+ border: 1px solid rgba(111, 18, 50, 0.08);
290
+ }
291
+
292
+ .big-stat span {
293
+ display: block;
294
+ color: var(--muted);
295
+ font-size: 0.82rem;
296
+ }
297
+
298
+ .big-stat strong {
299
+ display: block;
300
+ margin-top: 4px;
301
+ color: var(--wine);
302
+ font-size: 1.12rem;
303
+ }
304
+
305
+ .card-note {
306
+ margin: 18px 0 0;
307
+ color: var(--muted);
308
+ font-size: 0.92rem;
309
+ }
310
+
311
+ button.primary {
312
+ background: linear-gradient(135deg, var(--wine), #e64267) !important;
313
+ border: none !important;
314
+ box-shadow: 0 12px 24px rgba(111, 18, 50, 0.24) !important;
315
+ }
316
+
317
+ @media (max-width: 850px) {
318
+ .metric-row,
319
+ .forecast-grid {
320
+ grid-template-columns: 1fr;
321
+ }
322
  }
323
  """
324
 
325
+ theme = gr.themes.Soft(primary_hue="rose", secondary_hue="orange", neutral_hue="stone")
326
 
327
  with gr.Blocks(
328
  title="Wine Production Predictor",
329
  theme=theme,
330
  css=custom_css,
331
  ) as demo:
332
+ gr.HTML(
333
  """
334
+ <section class="hero">
335
+ <span class="hero-kicker">Experimental forecast prototype</span>
336
+ <h1>Wine Production Predictor</h1>
337
+ <p>
338
+ Forecast 2026/27 wine production for Portuguese viticultural
339
+ regions using lagged production, vineyard area scenarios, and
340
+ rolling-origin model validation.
341
+ </p>
342
+ </section>
343
  """
344
  )
345
 
346
+ gr.HTML(
347
  f"""
348
+ <div class="metric-row">
349
+ <div class="metric-card">
350
+ <span>Selected model</span>
351
+ <strong>{evaluation.selected_model}</strong>
352
+ </div>
353
+ <div class="metric-card">
354
+ <span>Empirical interval</span>
355
+ <strong>± {number(evaluation.interval_half_width)} hl</strong>
356
+ </div>
357
+ <div class="metric-card">
358
+ <span>Regions covered</span>
359
+ <strong>{len(region_choices)}</strong>
360
+ </div>
361
+ </div>
362
+ """
363
+ )
364
 
365
+ gr.HTML(
366
+ """
367
+ <div class="interpretation">
368
+ <b>Important interpretation.</b> The vineyard-area input creates a
369
+ scenario, not a causal estimate. The 90% interval is empirical,
370
+ based on validation errors, and should not be read as a formal
371
+ statistical confidence interval.
372
+ </div>
373
  """
374
  )
375
 
376
  with gr.Row():
377
+ with gr.Column(scale=1, elem_classes=["panel-card"]):
378
+ gr.Markdown("### Simulation inputs", elem_classes=["section-title"])
379
  region = gr.Dropdown(
380
  choices=region_choices,
381
  value=default_region,
 
393
  )
394
  run_button = gr.Button("Forecast 2026/27", variant="primary")
395
 
396
+ with gr.Column(scale=2, elem_classes=["panel-card"]):
397
+ gr.Markdown("### Prediction result", elem_classes=["section-title"])
398
  summary = gr.HTML()
399
+ result_table = gr.Dataframe(
400
+ label="Forecast result",
401
+ interactive=False,
402
+ wrap=True,
403
+ )
404
 
405
  with gr.Accordion("Validation metrics", open=False):
406
  gr.Dataframe(
407
+ value=format_metrics_table(validation_metrics),
408
  label="Rolling validation 2018-2022",
409
  interactive=False,
410
+ wrap=True,
411
  )
412
 
413
  with gr.Accordion("Final one-step-ahead test metrics", open=False):
414
  gr.Dataframe(
415
+ value=format_metrics_table(test_metrics),
416
  label="Test years 2023-2025",
417
  interactive=False,
418
+ wrap=True,
419
  )
420
 
421
  with gr.Accordion("Forecast table for all regions", open=False):
 
423
  value=format_forecast_table(base_forecast),
424
  label="Default 2026/27 forecasts for all regions",
425
  interactive=False,
426
+ wrap=True,
427
  )
428
 
429
  region.change(fn=update_area, inputs=region, outputs=area)