geethargrao's picture
Update app.py
122fd87 verified
Raw History Blame Contribute Delete
10.6 kB
import gradio as gr
import gradio as gr
import pandas as pd
import numpy as np
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_absolute_percentage_error
import plotly.graph_objects as go
# =====================================================
# LOAD COLUMN NAMES
# =====================================================
def load_columns(file):
try:
if file.name.endswith(".csv"):
df = pd.read_csv(file.name)
else:
df = pd.read_excel(file.name)
columns = df.columns.tolist()
return (
gr.update(choices=columns),
gr.update(choices=columns),
)
except Exception as e:
return (
gr.update(choices=[]),
gr.update(choices=[]),
)
# =====================================================
# FORECAST FUNCTION
# =====================================================
def run_forecast(
file,
date_col,
value_col,
model_name,
forecast_periods,
holiday1_start,
holiday1_end,
holiday2_start,
holiday2_end,
):
try:
# ============================================
# READ FILE
# ============================================
if file.name.endswith(".csv"):
df = pd.read_csv(file.name)
else:
df = pd.read_excel(file.name)
# ============================================
# DATA PREP
# ============================================
df[date_col] = pd.to_datetime(df[date_col])
df[value_col] = pd.to_numeric(
df[value_col],
errors="coerce"
)
df = df[[date_col, value_col]].dropna()
df = df.sort_values(date_col)
# ============================================
# TRAIN TEST SPLIT
# ============================================
test_size = max(7, int(len(df) * 0.2))
train_df = df.iloc[:-test_size]
# ============================================
# HOLT-WINTERS MODEL
# ============================================
if model_name == "Holt-Winters":
train_series = train_df[value_col].values
model = ExponentialSmoothing(
train_series,
trend="add",
seasonal=None,
).fit()
# Historical Prediction
hist_values = model.predict(
start=0,
end=len(df)-1,
)
# Future Forecast
forecast_values = model.forecast(
forecast_periods
)
# ============================================
# ARIMA MODEL
# ============================================
else:
train_series = train_df[value_col].values
model = ARIMA(
train_series,
order=(5, 1, 0)
).fit()
# Historical Prediction
hist_values = model.predict(
start=0,
end=len(df)-1,
)
# Future Forecast
forecast_values = model.forecast(
steps=forecast_periods
)
# ============================================
# COMPARISON DATAFRAME
# ============================================
comparison_df = pd.DataFrame({
"Date": df[date_col].values,
"Actual": df[value_col].values,
"Forecast": hist_values
})
eval_df = comparison_df.tail(test_size)
# ============================================
# FUTURE FORECAST
# ============================================
future_dates = pd.date_range(
start=df[date_col].max(),
periods=forecast_periods + 1,
freq="D",
)[1:]
future_forecast = pd.DataFrame({
"Date": future_dates,
"Forecast": forecast_values,
"Lower Range": forecast_values * 0.90,
"Upper Range": forecast_values * 1.10,
})
# ============================================
# ACCURACY
# ============================================
mape = mean_absolute_percentage_error(
eval_df["Actual"],
eval_df["Forecast"],
) * 100
accuracy = max(0, 100 - mape)
accuracy_text = f"""
MAPE : {mape:.2f} %
Approx Accuracy : {accuracy:.2f} %
"""
# ============================================
# ACTUAL VS FORECAST PLOT
# ============================================
fig_actual = go.Figure()
fig_actual.add_trace(
go.Scatter(
x=eval_df["Date"],
y=eval_df["Actual"],
mode="lines",
name="Actual"
)
)
fig_actual.add_trace(
go.Scatter(
x=eval_df["Date"],
y=eval_df["Forecast"],
mode="lines",
name="Forecast"
)
)
fig_actual.update_layout(
title="Past Period : Actual vs Forecast",
xaxis_title="Date",
yaxis_title="Value",
height=500
)
# ============================================
# FUTURE FORECAST PLOT
# ============================================
fig_forecast = go.Figure()
fig_forecast.add_trace(
go.Scatter(
x=future_forecast["Date"],
y=future_forecast["Forecast"],
mode="lines",
name="Forecast"
)
)
fig_forecast.add_trace(
go.Scatter(
x=future_forecast["Date"],
y=future_forecast["Upper Range"],
mode="lines",
line=dict(dash="dash"),
name="Upper Range"
)
)
fig_forecast.add_trace(
go.Scatter(
x=future_forecast["Date"],
y=future_forecast["Lower Range"],
mode="lines",
fill="tonexty",
line=dict(dash="dash"),
name="Lower Range"
)
)
fig_forecast.update_layout(
title="Future Forecast",
xaxis_title="Date",
yaxis_title="Forecast",
height=550
)
return (
accuracy_text,
fig_actual,
fig_forecast,
future_forecast,
)
except Exception as e:
return (
f"Error : {str(e)}",
None,
None,
None,
)
# =====================================================
# GRADIO UI
# =====================================================
with gr.Blocks() as demo:
gr.Markdown("""
# 📈 Open Source Forecast Utility
Train open-source forecasting models using historical data.
### Features
- Upload CSV or Excel
- Dynamic column selection
- Holt-Winters forecasting
- ARIMA forecasting
- Holiday/event slots
- Forecast lower & upper range
- Actual vs Forecast validation
- Downloadable output
""")
# ============================================
# FILE INPUT
# ============================================
file_input = gr.File(
label="Upload CSV or Excel File"
)
# ============================================
# COLUMN SELECTION
# ============================================
with gr.Row():
date_col = gr.Dropdown(
label="Select Date Column",
choices=[]
)
value_col = gr.Dropdown(
label="Select Value Column",
choices=[]
)
file_input.change(
fn=load_columns,
inputs=file_input,
outputs=[date_col, value_col]
)
# ============================================
# MODEL SETTINGS
# ============================================
with gr.Row():
model_name = gr.Dropdown(
label="Forecast Model",
choices=[
"Holt-Winters",
"ARIMA"
],
value="Holt-Winters"
)
forecast_periods = gr.Slider(
minimum=7,
maximum=365,
value=30,
step=1,
label="Forecast Horizon"
)
# ============================================
# HOLIDAY SLOTS
# ============================================
gr.Markdown("## Holiday / Event Time Slots")
with gr.Row():
holiday1_start = gr.Textbox(
label="Holiday Slot 1 Start",
value="2025-12-20"
)
holiday1_end = gr.Textbox(
label="Holiday Slot 1 End",
value="2025-12-31"
)
with gr.Row():
holiday2_start = gr.Textbox(
label="Holiday Slot 2 Start",
value="2026-03-25"
)
holiday2_end = gr.Textbox(
label="Holiday Slot 2 End",
value="2026-04-05"
)
# ============================================
# BUTTON
# ============================================
run_btn = gr.Button(
"Generate Forecast"
)
# ============================================
# OUTPUTS
# ============================================
accuracy_output = gr.Textbox(
label="Forecast Accuracy"
)
actual_plot = gr.Plot(
label="Actual vs Forecast"
)
forecast_plot = gr.Plot(
label="Future Forecast"
)
forecast_table = gr.Dataframe(
label="Forecast Output"
)
# ============================================
# BUTTON ACTION
# ============================================
run_btn.click(
fn=run_forecast,
inputs=[
file_input,
date_col,
value_col,
model_name,
forecast_periods,
holiday1_start,
holiday1_end,
holiday2_start,
holiday2_end,
],
outputs=[
accuracy_output,
actual_plot,
forecast_plot,
forecast_table,
],
)
# =====================================================
# LAUNCH
# =====================================================
demo.launch()