import pandas as pd from prophet import Prophet import gradio as gr import plotly.graph_objs as go # Function to train the model and generate forecast def predict_sales(time_frame): all_sales_data = pd.read_csv('/content/All sales - House of Pizza.csv') # Clean up the 'Total paid' column amount = all_sales_data['Total paid'].str.replace('₨', '', regex=False) amount = amount.str.replace(',', '', regex=False) amount = amount.str.strip() amount = amount.astype(float) # Convert the 'Date' column to datetime, coercing errors all_sales_data['Date'] = pd.to_datetime(all_sales_data['Date'], format='%m/%d/%Y %H:%M', errors='coerce') # Drop rows with invalid dates all_sales_data = all_sales_data.dropna(subset=['Date']) # Prepare the DataFrame df = pd.DataFrame({ 'Date': all_sales_data['Date'], 'Total paid': amount }) # Prepare Prophet model model = Prophet() df['ds'] = df['Date'] df['y'] = df['Total paid'] model.fit(df[['ds', 'y']]) last_date_value = df['Date'].iloc[-2] # Future forecast based on the time frame future_periods = { '7 days': 7 * 24 * 60, '10 days': 10 * 24 * 60, '15 days': 15 * 24 * 60, '1 month': 30 * 24 * 60 } # Get the future time based on the selected time frame future_time = model.make_future_dataframe(periods=future_periods[time_frame], freq='T') current_time = pd.Timestamp.now() # Set the last historical date in the format 'MM/DD/YYYY HH:MM' last_historical_date = pd.to_datetime(last_date_value, format='%m/%d/%Y %H:%M') # Filter future_time to include rows from the current time and onwards, including future hours and minutes future_only = future_time[(future_time['ds'] >= current_time) & (future_time['ds'] > last_historical_date)] forecast = model.predict(future_only) # Display the forecasted data forecast_table = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(future_periods[time_frame]) # Create a Plotly graph fig = go.Figure() fig.add_trace(go.Scatter( x=forecast['ds'], y=forecast['yhat'], mode='lines+markers', name='Forecasted Sales', line=dict(color='orange'), marker=dict(size=6), hovertemplate='Date: %{x}
Forecasted Sales: %{y}' )) fig.update_layout( title='Sales Forecast using Prophet', xaxis_title='Date and Time', yaxis_title='Sales Price', xaxis=dict(tickformat="%Y-%m-%d %H:%M"), yaxis=dict(autorange=True) ) return forecast_table, fig # Gradio interface def run_gradio(): # Create the Gradio Interface time_options = ['7 days', '10 days', '15 days', '1 month'] gr.Interface( fn=predict_sales, # Function to be called inputs=gr.components.Dropdown(time_options, label="Select Forecast Time Range"), # User input outputs=[ gr.components.Dataframe(label="Forecasted Sales Table"), # Forecasted data in tabular form gr.components.Plot(label="Sales Forecast Plot") # Plotly graph output ], title="Sales Forecasting with Prophet", description="Select a time range for the forecast and click on the button to train the model and see the results." ).launch(debug=True) # Run the Gradio interface if __name__ == '__main__': run_gradio()