IvanStudent commited on
Commit
05f3172
1 Parent(s): 7f437a0

Guardar mis cambios locales

Browse files
Files changed (1) hide show
  1. app.py +73 -31
app.py CHANGED
@@ -1,35 +1,77 @@
1
- import gradio as gr
2
  import pandas as pd
3
- import joblib
 
 
4
 
5
- # Cargar el modelo entrenado
6
- model = joblib.load("arima_sales_model.pkl")
7
 
8
- # Funci贸n para hacer predicciones con el modelo
9
- def predict(file):
 
 
 
10
  # Leer el archivo CSV
11
- data = pd.read_csv(file.name)
12
-
13
- # Aseg煤rate de que el archivo tenga las columnas necesarias
14
- if 'Date' not in data.columns or 'Sales' not in data.columns:
15
- return "El archivo debe contener las columnas 'Date' y 'Sales'."
16
-
17
- # Aqu铆 puedes agregar tu l贸gica de predicci贸n con el modelo
18
- # Por ejemplo, model.predict(data['Sales'])
19
- prediction = model.predict(data['Sales'].values.reshape(-1, 1)) # Suponiendo que es una serie temporal
20
-
21
- return f"Predicci贸n de ventas: {prediction}"
22
-
23
- # Crear la interfaz interactiva en Gradio
24
- iface = gr.Interface(
25
- fn=predict,
26
- inputs=gr.File(label="Sube los datos de tu tienda (debe contener Date y Sales)", file_count="single", file_types=[".csv"]),
27
- outputs="text",
28
- title="MLCast v1.1",
29
- description="Un sistema inteligente de pron贸stico de ventas. Suba los datos de su tienda para proceder (debe contener al menos Date y Sales).",
30
- theme="huggingface",
31
- allow_flagging="never"
32
- )
33
-
34
- # Ejecutar la interfaz
35
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
  import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from statsmodels.tsa.arima.model import ARIMA
5
+ import pickle
6
 
7
+ # T铆tulo de la interfaz
8
+ st.title("MLCast v1.1 - Intelligent Sales Forecasting System")
9
 
10
+ # Subir archivo CSV
11
+ uploaded_file = st.file_uploader("Upload your store data here (must contain Date and Sales)", type="csv")
12
+
13
+ # Verificar si se subi贸 un archivo
14
+ if uploaded_file is not None:
15
  # Leer el archivo CSV
16
+ df = pd.read_csv(uploaded_file)
17
+
18
+ # Verificar si las columnas necesarias est谩n presentes
19
+ if 'Date' in df.columns and 'Sale' in df.columns:
20
+ st.success("File uploaded successfully!")
21
+
22
+ # Mostrar una vista previa de los primeros datos
23
+ st.write(df.head())
24
+
25
+ # Convertir la columna 'Date' en tipo datetime
26
+ df['Date'] = pd.to_datetime(df['Date'])
27
+
28
+ # Renombrar las columnas para ARIMA
29
+ df_arima = df.rename(columns={'Date': 'ds', 'Sale': 'y'})
30
+
31
+ # Cargar el modelo ARIMA desde el archivo
32
+ with open('arima_sales_model.pkl', 'rb') as f:
33
+ arima_model = pickle.load(f)
34
+
35
+ # Realizar la predicci贸n para los pr贸ximos 30 d铆as (ajustable)
36
+ forecast_period = 30
37
+ forecast = arima_model.get_forecast(steps=forecast_period)
38
+ forecast_index = pd.date_range(df['Date'].max(), periods=forecast_period + 1, freq='D')[1:]
39
+
40
+ # Crear un DataFrame con las predicciones
41
+ forecast_df = pd.DataFrame({
42
+ 'Date': forecast_index,
43
+ 'Sales Forecast': forecast.predicted_mean
44
+ })
45
+
46
+ # Graficar los resultados
47
+ fig, ax = plt.subplots(figsize=(10, 6))
48
+ ax.plot(df['Date'], df['Sale'], label='Historical Sales', color='blue')
49
+ ax.plot(forecast_df['Date'], forecast_df['Sales Forecast'], label='Sales Forecast', color='red', linestyle='--')
50
+ ax.set_xlabel('Date')
51
+ ax.set_ylabel('Sales')
52
+ ax.set_title('Sales Forecasting with ARIMA')
53
+ ax.legend()
54
+
55
+ # Mostrar la gr谩fica
56
+ st.pyplot(fig)
57
+
58
+ # Opcional: Ajuste del rango de fechas para el pron贸stico
59
+ st.sidebar.title("Adjust Forecast Range")
60
+ start_date = st.sidebar.date_input('Start Date', df['Date'].min())
61
+ end_date = st.sidebar.date_input('End Date', df['Date'].max())
62
+
63
+ # Filtrar los datos seg煤n el rango seleccionado
64
+ filtered_df = df[(df['Date'] >= pd.to_datetime(start_date)) & (df['Date'] <= pd.to_datetime(end_date))]
65
+
66
+ # Graficar el rango ajustado
67
+ st.subheader(f"Sales Data from {start_date} to {end_date}")
68
+ fig_filtered, ax_filtered = plt.subplots(figsize=(10, 6))
69
+ ax_filtered.plot(filtered_df['Date'], filtered_df['Sale'], label=f'Sales from {start_date} to {end_date}')
70
+ ax_filtered.set_xlabel('Date')
71
+ ax_filtered.set_ylabel('Sale')
72
+ ax_filtered.set_title(f'Sales Forecasting from {start_date} to {end_date}')
73
+ ax_filtered.legend()
74
+ st.pyplot(fig_filtered)
75
+
76
+ else:
77
+ st.error("The uploaded file must contain at least 'Date' and 'Sales' columns.")