Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,144 +1,144 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import matplotlib.pyplot as plt
|
| 6 |
-
from model import GDPPredictor
|
| 7 |
-
|
| 8 |
-
# Initialize the predictor
|
| 9 |
-
predictor = GDPPredictor()
|
| 10 |
-
|
| 11 |
-
# Check if we have models saved
|
| 12 |
-
model_file = 'gdp_models.pkl'
|
| 13 |
-
data_file = 'Consolidated.csv'
|
| 14 |
-
|
| 15 |
-
# Initialize and train models if needed
|
| 16 |
-
if os.path.exists(model_file):
|
| 17 |
-
print("Loading pre-trained models...")
|
| 18 |
-
predictor.load_models(model_file)
|
| 19 |
-
predictor.load_data(data_file)
|
| 20 |
-
else:
|
| 21 |
-
print("Training new models...")
|
| 22 |
-
predictor.load_data(data_file)
|
| 23 |
-
predictor.train_models()
|
| 24 |
-
predictor.save_models(model_file)
|
| 25 |
-
|
| 26 |
-
# Get latest GDP for reference
|
| 27 |
-
latest_year, latest_gdp = predictor.get_latest_gdp()
|
| 28 |
-
|
| 29 |
-
# Create a dictionary of all features and their default values (current values)
|
| 30 |
-
feature_info = predictor.get_feature_info()
|
| 31 |
-
|
| 32 |
-
# Create sliders for each feature, organized by category
|
| 33 |
-
def create_feature_inputs():
|
| 34 |
-
inputs = []
|
| 35 |
-
|
| 36 |
-
# For each category
|
| 37 |
-
for category, features in feature_info.items():
|
| 38 |
-
# Add a label for the category
|
| 39 |
-
inputs.append(gr.Markdown(f"## {category}"))
|
| 40 |
-
|
| 41 |
-
# Add sliders for each feature in this category
|
| 42 |
-
for feature_name, (min_val, max_val, mean_val, current_val) in features.items():
|
| 43 |
-
# Adjust slider range to be a bit wider than historical data
|
| 44 |
-
slider_min = min_val * 0.9
|
| 45 |
-
slider_max = max_val * 1.1
|
| 46 |
-
|
| 47 |
-
# Create a slider for this feature
|
| 48 |
-
slider = gr.Slider(
|
| 49 |
-
minimum=slider_min,
|
| 50 |
-
maximum=slider_max,
|
| 51 |
-
value=current_val, # Default to current value
|
| 52 |
-
step=(slider_max - slider_min) / 100, # 100 steps across range
|
| 53 |
-
label=feature_name
|
| 54 |
-
)
|
| 55 |
-
inputs.append(slider)
|
| 56 |
-
|
| 57 |
-
return inputs
|
| 58 |
-
|
| 59 |
-
def predict(*feature_values):
|
| 60 |
-
# Get all input features as flat list
|
| 61 |
-
flat_inputs = list(feature_values)
|
| 62 |
-
|
| 63 |
-
# Map features to values
|
| 64 |
-
feature_names = []
|
| 65 |
-
for category, features in feature_info.items():
|
| 66 |
-
for feature_name in features:
|
| 67 |
-
feature_names.append(feature_name)
|
| 68 |
-
|
| 69 |
-
# Create input dictionary
|
| 70 |
-
input_dict = {feature_names[i]: flat_inputs[i] for i in range(len(feature_names))}
|
| 71 |
-
|
| 72 |
-
# Make prediction
|
| 73 |
-
try:
|
| 74 |
-
predictions = predictor.predict_gdp(input_dict)
|
| 75 |
-
|
| 76 |
-
# Get ensemble prediction and calculate change
|
| 77 |
-
ensemble_pred = predictions['Ensemble']
|
| 78 |
-
change = ensemble_pred - latest_gdp
|
| 79 |
-
pct_change = (change / latest_gdp) * 100
|
| 80 |
-
|
| 81 |
-
# Format results
|
| 82 |
-
result_text = f"# GDP Prediction Results\n\n"
|
| 83 |
-
result_text += f"## Primary Prediction\n"
|
| 84 |
-
result_text += f"**Ensemble Model:** {ensemble_pred:.2f} USD billion\n\n"
|
| 85 |
-
result_text += f"## Comparison with {latest_year} GDP ({latest_gdp:.2f} USD billion)\n"
|
| 86 |
-
result_text += f"**Change:** {change:.2f} USD billion ({pct_change:.2f}%)\n\n"
|
| 87 |
-
result_text += f"## All Model Predictions\n"
|
| 88 |
-
|
| 89 |
-
# Add all individual model predictions
|
| 90 |
-
for name, pred in sorted(predictions.items(), key=lambda x: x[1], reverse=True):
|
| 91 |
-
if name != 'Ensemble':
|
| 92 |
-
result_text += f"- **{name}:** {pred:.2f} USD billion\n"
|
| 93 |
-
|
| 94 |
-
# Create visualization
|
| 95 |
-
fig, ax = plt.subplots(figsize=(10, 6))
|
| 96 |
-
|
| 97 |
-
# Get last 10 years data
|
| 98 |
-
df = predictor.cleaned_df
|
| 99 |
-
last_years = df.sort_values('Year').tail(10)
|
| 100 |
-
ax.plot(last_years['Year'], last_years[predictor.target], 'o-', linewidth=2, label='Historical GDP')
|
| 101 |
-
|
| 102 |
-
# Add prediction point
|
| 103 |
-
pred_year = latest_year + 1
|
| 104 |
-
ax.scatter([pred_year], [predictions['Ensemble']], color='green', s=150, label='Prediction')
|
| 105 |
-
|
| 106 |
-
# Format plot
|
| 107 |
-
ax.set_title('GDP Prediction', fontsize=14)
|
| 108 |
-
ax.set_xlabel('Year', fontsize=12)
|
| 109 |
-
ax.set_ylabel('Real GDP (USD billion)', fontsize=12)
|
| 110 |
-
ax.grid(True, alpha=0.3)
|
| 111 |
-
ax.legend()
|
| 112 |
-
|
| 113 |
-
return result_text, fig
|
| 114 |
-
|
| 115 |
-
except Exception as e:
|
| 116 |
-
return f"Error making prediction: {str(e)}", None
|
| 117 |
-
|
| 118 |
-
# Create the interface
|
| 119 |
-
with gr.Blocks(title="GDP Predictor") as demo:
|
| 120 |
-
gr.Markdown("# GDP Prediction Model")
|
| 121 |
-
gr.Markdown(f"""
|
| 122 |
-
This application predicts GDP based on various economic indicators. The current dataset contains data up to the year {latest_year}.
|
| 123 |
-
|
| 124 |
-
Adjust the sliders below to see how changes in different economic indicators might affect GDP.
|
| 125 |
-
The default values are set to the most recent values from the dataset.
|
| 126 |
-
""")
|
| 127 |
-
|
| 128 |
-
with gr.Row():
|
| 129 |
-
with gr.Column(scale=2):
|
| 130 |
-
# Create input sliders from feature info
|
| 131 |
-
inputs = create_feature_inputs()
|
| 132 |
-
|
| 133 |
-
with gr.Column(scale=3):
|
| 134 |
-
# Output components
|
| 135 |
-
prediction_text = gr.Markdown("Adjust sliders and click 'Predict' to see results")
|
| 136 |
-
prediction_plot = gr.Plot(label="GDP Prediction Visualization")
|
| 137 |
-
|
| 138 |
-
# Predict button
|
| 139 |
-
predict_btn = gr.Button("Predict GDP")
|
| 140 |
-
predict_btn.click(fn=predict, inputs=inputs, outputs=[prediction_text, prediction_plot])
|
| 141 |
-
|
| 142 |
-
# Launch the app
|
| 143 |
-
if __name__ == "__main__":
|
| 144 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from model import GDPPredictor
|
| 7 |
+
|
| 8 |
+
# Initialize the predictor
|
| 9 |
+
predictor = GDPPredictor()
|
| 10 |
+
|
| 11 |
+
# Check if we have models saved
|
| 12 |
+
model_file = 'gdp_models.pkl'
|
| 13 |
+
data_file = 'Consolidated.csv'
|
| 14 |
+
|
| 15 |
+
# Initialize and train models if needed
|
| 16 |
+
if os.path.exists(model_file):
|
| 17 |
+
print("Loading pre-trained models...")
|
| 18 |
+
predictor.load_models(model_file)
|
| 19 |
+
predictor.load_data(data_file)
|
| 20 |
+
else:
|
| 21 |
+
print("Training new models...")
|
| 22 |
+
predictor.load_data(data_file)
|
| 23 |
+
predictor.train_models()
|
| 24 |
+
predictor.save_models(model_file)
|
| 25 |
+
|
| 26 |
+
# Get latest GDP for reference
|
| 27 |
+
latest_year, latest_gdp = predictor.get_latest_gdp()
|
| 28 |
+
|
| 29 |
+
# Create a dictionary of all features and their default values (current values)
|
| 30 |
+
feature_info = predictor.get_feature_info()
|
| 31 |
+
|
| 32 |
+
# Create sliders for each feature, organized by category
|
| 33 |
+
def create_feature_inputs():
|
| 34 |
+
inputs = []
|
| 35 |
+
|
| 36 |
+
# For each category
|
| 37 |
+
for category, features in feature_info.items():
|
| 38 |
+
# Add a label for the category
|
| 39 |
+
inputs.append(gr.Markdown(f"## {category}"))
|
| 40 |
+
|
| 41 |
+
# Add sliders for each feature in this category
|
| 42 |
+
for feature_name, (min_val, max_val, mean_val, current_val) in features.items():
|
| 43 |
+
# Adjust slider range to be a bit wider than historical data
|
| 44 |
+
slider_min = min_val * 0.9
|
| 45 |
+
slider_max = max_val * 1.1
|
| 46 |
+
|
| 47 |
+
# Create a slider for this feature
|
| 48 |
+
slider = gr.Slider(
|
| 49 |
+
minimum=slider_min,
|
| 50 |
+
maximum=slider_max,
|
| 51 |
+
value=current_val, # Default to current value
|
| 52 |
+
step=(slider_max - slider_min) / 100, # 100 steps across range
|
| 53 |
+
label=feature_name
|
| 54 |
+
)
|
| 55 |
+
inputs.append(slider)
|
| 56 |
+
|
| 57 |
+
return inputs
|
| 58 |
+
|
| 59 |
+
def predict(*feature_values):
|
| 60 |
+
# Get all input features as flat list
|
| 61 |
+
flat_inputs = list(feature_values)
|
| 62 |
+
|
| 63 |
+
# Map features to values
|
| 64 |
+
feature_names = []
|
| 65 |
+
for category, features in feature_info.items():
|
| 66 |
+
for feature_name in features:
|
| 67 |
+
feature_names.append(feature_name)
|
| 68 |
+
|
| 69 |
+
# Create input dictionary
|
| 70 |
+
input_dict = {feature_names[i]: flat_inputs[i] for i in range(len(feature_names))}
|
| 71 |
+
|
| 72 |
+
# Make prediction
|
| 73 |
+
try:
|
| 74 |
+
predictions = predictor.predict_gdp(input_dict)
|
| 75 |
+
|
| 76 |
+
# Get ensemble prediction and calculate change
|
| 77 |
+
ensemble_pred = predictions['Ensemble']
|
| 78 |
+
change = ensemble_pred - latest_gdp
|
| 79 |
+
pct_change = (change / latest_gdp) * 100
|
| 80 |
+
|
| 81 |
+
# Format results
|
| 82 |
+
result_text = f"# GDP Prediction Results\n\n"
|
| 83 |
+
result_text += f"## Primary Prediction\n"
|
| 84 |
+
result_text += f"**Ensemble Model:** {ensemble_pred:.2f} USD billion\n\n"
|
| 85 |
+
result_text += f"## Comparison with {latest_year} GDP ({latest_gdp:.2f} USD billion)\n"
|
| 86 |
+
result_text += f"**Change:** {change:.2f} USD billion ({pct_change:.2f}%)\n\n"
|
| 87 |
+
result_text += f"## All Model Predictions\n"
|
| 88 |
+
|
| 89 |
+
# Add all individual model predictions
|
| 90 |
+
for name, pred in sorted(predictions.items(), key=lambda x: x[1], reverse=True):
|
| 91 |
+
if name != 'Ensemble':
|
| 92 |
+
result_text += f"- **{name}:** {pred:.2f} USD billion\n"
|
| 93 |
+
|
| 94 |
+
# Create visualization
|
| 95 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 96 |
+
|
| 97 |
+
# Get last 10 years data
|
| 98 |
+
df = predictor.cleaned_df
|
| 99 |
+
last_years = df.sort_values('Year').tail(10)
|
| 100 |
+
ax.plot(last_years['Year'], last_years[predictor.target], 'o-', linewidth=2, label='Historical GDP')
|
| 101 |
+
|
| 102 |
+
# Add prediction point
|
| 103 |
+
pred_year = latest_year + 1
|
| 104 |
+
ax.scatter([pred_year], [predictions['Ensemble']], color='green', s=150, label='Prediction')
|
| 105 |
+
|
| 106 |
+
# Format plot
|
| 107 |
+
ax.set_title('GDP Prediction', fontsize=14)
|
| 108 |
+
ax.set_xlabel('Year', fontsize=12)
|
| 109 |
+
ax.set_ylabel('Real GDP (USD billion)', fontsize=12)
|
| 110 |
+
ax.grid(True, alpha=0.3)
|
| 111 |
+
ax.legend()
|
| 112 |
+
|
| 113 |
+
return result_text, fig
|
| 114 |
+
|
| 115 |
+
except Exception as e:
|
| 116 |
+
return f"Error making prediction: {str(e)}", None
|
| 117 |
+
|
| 118 |
+
# Create the interface
|
| 119 |
+
with gr.Blocks(title="GDP Predictor") as demo:
|
| 120 |
+
gr.Markdown("# GDP Prediction Model")
|
| 121 |
+
gr.Markdown(f"""
|
| 122 |
+
This application predicts GDP based on various economic indicators. The current dataset contains data up to the year {latest_year}.
|
| 123 |
+
|
| 124 |
+
Adjust the sliders below to see how changes in different economic indicators might affect GDP.
|
| 125 |
+
The default values are set to the most recent values from the dataset.
|
| 126 |
+
""")
|
| 127 |
+
|
| 128 |
+
with gr.Row():
|
| 129 |
+
with gr.Column(scale=2):
|
| 130 |
+
# Create input sliders from feature info
|
| 131 |
+
inputs = create_feature_inputs()
|
| 132 |
+
|
| 133 |
+
with gr.Column(scale=3):
|
| 134 |
+
# Output components
|
| 135 |
+
prediction_text = gr.Markdown("Adjust sliders and click 'Predict' to see results")
|
| 136 |
+
prediction_plot = gr.Plot(label="GDP Prediction Visualization")
|
| 137 |
+
|
| 138 |
+
# Predict button
|
| 139 |
+
predict_btn = gr.Button("Predict GDP")
|
| 140 |
+
predict_btn.click(fn=predict, inputs=inputs, outputs=[prediction_text, prediction_plot])
|
| 141 |
+
|
| 142 |
+
# Launch the app
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
demo.launch()
|