Commit
·
9f65c7c
1
Parent(s):
2ac50b5
Guardar mis cambios locales
Browse files
app.py
CHANGED
@@ -2,6 +2,8 @@ import pandas as pd
|
|
2 |
import matplotlib.pyplot as plt
|
3 |
import joblib
|
4 |
import gradio as gr
|
|
|
|
|
5 |
|
6 |
def load_model():
|
7 |
try:
|
@@ -10,39 +12,47 @@ def load_model():
|
|
10 |
except Exception as e:
|
11 |
return None, f"Failed to load model: {str(e)}"
|
12 |
|
13 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
if uploaded_file is None:
|
15 |
-
return "No file uploaded.", None
|
16 |
|
17 |
try:
|
18 |
df = pd.read_csv(uploaded_file)
|
19 |
if 'Date' not in df.columns or 'Sale' not in df.columns:
|
20 |
-
return "The uploaded file must contain 'Date' and 'Sale' columns.",
|
21 |
except Exception as e:
|
22 |
-
return f"Failed to read the uploaded CSV file: {str(e)}",
|
23 |
|
24 |
df['Date'] = pd.to_datetime(df['Date'])
|
25 |
df = df.rename(columns={'Date': 'ds', 'Sale': 'y'})
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
end = pd.to_datetime(end_date)
|
31 |
-
except ValueError:
|
32 |
-
return "Please enter valid dates in YYYY-MM-DD format.", None
|
33 |
|
34 |
-
df_filtered = df[(df['ds'] >=
|
35 |
|
36 |
arima_model, error = load_model()
|
37 |
if arima_model is None:
|
38 |
-
return error,
|
39 |
|
40 |
try:
|
41 |
-
forecast_index = pd.date_range(start=end, periods=forecast_period + 1, freq='D')[1:]
|
42 |
forecast = arima_model.get_forecast(steps=forecast_period)
|
|
|
43 |
forecast_df = pd.DataFrame({'Date': forecast_index, 'Sales Forecast': forecast.predicted_mean})
|
44 |
except Exception as e:
|
45 |
-
return f"Failed during forecasting: {str(e)}",
|
46 |
|
47 |
try:
|
48 |
fig, ax = plt.subplots(figsize=(10, 6))
|
@@ -52,23 +62,23 @@ def forecast_sales(uploaded_file, start_date, end_date, forecast_period=30):
|
|
52 |
ax.set_ylabel('Sales')
|
53 |
ax.set_title('Sales Forecasting with ARIMA')
|
54 |
ax.legend()
|
55 |
-
return None,
|
56 |
except Exception as e:
|
57 |
-
return f"Failed to generate plot: {str(e)}",
|
58 |
|
59 |
def setup_interface():
|
60 |
with gr.Blocks() as demo:
|
61 |
gr.Markdown("## MLCast v1.1 - Intelligent Sales Forecasting System")
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
output_text = gr.Textbox(visible=True)
|
67 |
output_plot = gr.Plot()
|
|
|
68 |
forecast_button.click(
|
69 |
-
forecast_sales,
|
70 |
-
inputs=[file_input,
|
71 |
-
outputs=[
|
72 |
)
|
73 |
return demo
|
74 |
|
|
|
2 |
import matplotlib.pyplot as plt
|
3 |
import joblib
|
4 |
import gradio as gr
|
5 |
+
from dateutil.relativedelta import relativedelta
|
6 |
+
import calendar
|
7 |
|
8 |
def load_model():
|
9 |
try:
|
|
|
12 |
except Exception as e:
|
13 |
return None, f"Failed to load model: {str(e)}"
|
14 |
|
15 |
+
def parse_date(date_str):
|
16 |
+
"""Parse the custom date format 'Month-Year' and return the start and end of the month."""
|
17 |
+
try:
|
18 |
+
date = pd.to_datetime(date_str, format="%B-%Y")
|
19 |
+
_, last_day = calendar.monthrange(date.year, date.month)
|
20 |
+
start_date = date.replace(day=1)
|
21 |
+
end_date = date.replace(day=last_day)
|
22 |
+
return start_date, end_date, None
|
23 |
+
except ValueError:
|
24 |
+
return None, None, "Date format should be 'Month-Year', e.g., 'January-2024'."
|
25 |
+
|
26 |
+
def forecast_sales(uploaded_file, date_str, forecast_period=30):
|
27 |
if uploaded_file is None:
|
28 |
+
return "No file uploaded.", None, "Please upload a file."
|
29 |
|
30 |
try:
|
31 |
df = pd.read_csv(uploaded_file)
|
32 |
if 'Date' not in df.columns or 'Sale' not in df.columns:
|
33 |
+
return None, "The uploaded file must contain 'Date' and 'Sale' columns.", "File does not have required columns."
|
34 |
except Exception as e:
|
35 |
+
return None, f"Failed to read the uploaded CSV file: {str(e)}", "Error reading file."
|
36 |
|
37 |
df['Date'] = pd.to_datetime(df['Date'])
|
38 |
df = df.rename(columns={'Date': 'ds', 'Sale': 'y'})
|
39 |
|
40 |
+
start_date, end_date, error = parse_date(date_str)
|
41 |
+
if error:
|
42 |
+
return None, error, "Invalid date format."
|
|
|
|
|
|
|
43 |
|
44 |
+
df_filtered = df[(df['ds'] >= start_date) & (df['ds'] <= end_date)]
|
45 |
|
46 |
arima_model, error = load_model()
|
47 |
if arima_model is None:
|
48 |
+
return None, error, "Failed to load ARIMA model."
|
49 |
|
50 |
try:
|
|
|
51 |
forecast = arima_model.get_forecast(steps=forecast_period)
|
52 |
+
forecast_index = pd.date_range(start=end_date, periods=forecast_period + 1, freq='D')[1:]
|
53 |
forecast_df = pd.DataFrame({'Date': forecast_index, 'Sales Forecast': forecast.predicted_mean})
|
54 |
except Exception as e:
|
55 |
+
return None, f"Failed during forecasting: {str(e)}", "Forecasting failed."
|
56 |
|
57 |
try:
|
58 |
fig, ax = plt.subplots(figsize=(10, 6))
|
|
|
62 |
ax.set_ylabel('Sales')
|
63 |
ax.set_title('Sales Forecasting with ARIMA')
|
64 |
ax.legend()
|
65 |
+
return fig, None, "File loaded and processed successfully."
|
66 |
except Exception as e:
|
67 |
+
return None, f"Failed to generate plot: {str(e)}", "Plotting failed."
|
68 |
|
69 |
def setup_interface():
|
70 |
with gr.Blocks() as demo:
|
71 |
gr.Markdown("## MLCast v1.1 - Intelligent Sales Forecasting System")
|
72 |
+
with gr.Row():
|
73 |
+
file_input = gr.File(label="Upload your store data here (must contain Date and Sales)")
|
74 |
+
date_input = gr.Textbox(label="Enter Month and Year (e.g., January-2024)")
|
75 |
+
forecast_button = gr.Button("Forecast Sales")
|
|
|
76 |
output_plot = gr.Plot()
|
77 |
+
output_message = gr.Textbox(label="System Messages", visible=True)
|
78 |
forecast_button.click(
|
79 |
+
forecast_sales,
|
80 |
+
inputs=[file_input, date_input],
|
81 |
+
outputs=[output_plot, output_message]
|
82 |
)
|
83 |
return demo
|
84 |
|