Subelinha commited on
Commit
66c4e71
·
verified ·
1 Parent(s): 620569c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -97
app.py CHANGED
@@ -1,100 +1,42 @@
1
- """Interactive Gradio app for the experimental wine-production forecast.
2
 
3
- Run from the repository root with:
4
- python src/app.py
5
 
6
- The app is intentionally a visual prototype. It uses the same forecasting logic
7
- as ``src/future_forecast.py`` and does not make causal claims about vineyard
8
- area changes.
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import pandas as pd
14
- import gradio as gr
15
-
16
- try:
17
- from future_forecast import evaluate_forecasters, forecast_2026, load_history
18
- except ModuleNotFoundError:
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()
32
- numeric_columns = [
33
- "vineyard_area_ha",
34
- "predicted_production_hl",
35
- "lower_90_hl",
36
- "upper_90_hl",
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={
44
- "region": "Region",
45
- "year_start": "Year",
46
- "vineyard_area_ha": "Area (ha)",
47
- "selected_model": "Selected model",
48
- "predicted_production_hl": "Predicted production (hl)",
49
- "lower_90_hl": "Lower empirical 90% (hl)",
50
- "upper_90_hl": "Upper empirical 90% (hl)",
51
- }
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)
74
-
75
- latest_area = (
76
- history.sort_values(["region", "year_start"])
77
- .groupby("region", as_index=False)
78
- .tail(1)[["region", "vineyard_area_ha"]]
79
- )
80
-
81
- region_choices = sorted(base_forecast["region"].astype(str).unique().tolist())
82
- default_region = region_choices[0]
83
- area_map = dict(zip(latest_area["region"].astype(str), latest_area["vineyard_area_ha"]))
84
-
85
- validation_metrics = (
86
- evaluation.metrics.query("split == 'rolling_validation_2018_2022'")
87
- .sort_values("MAE")
88
- .reset_index(drop=True)
89
- )
90
- test_metrics = (
91
- evaluation.metrics.query("split == 'test_2023_2025'")
92
- .sort_values("MAE")
93
- .reset_index(drop=True)
94
- )
95
-
96
-
97
- def update_area(region: str):
98
- """Reset the area input to the latest observed area for the chosen region."""
99
- return gr.update(value=round(float(area_map.get(region, 0.0)), 2))
100
 
 
 
1
 
 
 
2
 
3
+ with gr.Column(scale=2, elem_classes=["panel-card"]):
4
+ gr.Markdown("### Prediction result", elem_classes=["section-title"])
5
+ summary = gr.HTML()
6
+ result_table = gr.Dataframe(
7
+ label="Forecast result",
8
+ interactive=False,
9
+ wrap=True,
10
+ )
11
+
12
+ with gr.Accordion("Validation metrics", open=False):
13
+ gr.Dataframe(
14
+ value=format_metrics_table(validation_metrics),
15
+ label="Rolling validation 2018-2022",
16
+ interactive=False,
17
+ wrap=True,
18
+ )
19
+
20
+ with gr.Accordion("Final one-step-ahead test metrics", open=False):
21
+ gr.Dataframe(
22
+ value=format_metrics_table(test_metrics),
23
+ label="Test years 2023-2025",
24
+ interactive=False,
25
+ wrap=True,
26
+ )
27
+
28
+ with gr.Accordion("Forecast table for all regions", open=False):
29
+ gr.Dataframe(
30
+ value=format_forecast_table(base_forecast),
31
+ label="Default 2026/27 forecasts for all regions",
32
+ interactive=False,
33
+ wrap=True,
34
+ )
35
+
36
+ region.change(fn=update_area, inputs=region, outputs=area)
37
+ run_button.click(fn=simulate, inputs=[region, area], outputs=[summary, result_table])
38
+ demo.load(fn=simulate, inputs=[region, area], outputs=[summary, result_table])
39
+
40
+
41
+ demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42