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go
|
| 5 |
import numpy as np
|
| 6 |
-
|
| 7 |
# Function to train the model and generate forecast
|
| 8 |
def predict_sales(time_frame):
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
#fetch all sell data
|
| 23 |
-
per_page=-1
|
| 24 |
-
url=f"https://livesystem.hisabkarlay.com/connector/api/sell?per_page={per_page}"
|
| 25 |
-
headers={
|
| 26 |
-
'Authorization':f'Bearer {access_token}'
|
| 27 |
-
}
|
| 28 |
-
response=requests.get(url,headers=headers)
|
| 29 |
-
data=response.json()['data']
|
| 30 |
-
date=[]
|
| 31 |
-
amount=[]
|
| 32 |
-
for item in data:
|
| 33 |
-
date.append(item.get('transaction_date'))
|
| 34 |
-
amount.append(float(item.get('final_total')))
|
| 35 |
-
data_dict={
|
| 36 |
-
'date':date,
|
| 37 |
-
'amount':amount
|
| 38 |
-
}
|
| 39 |
-
data_frame=pd.DataFrame(data_dict)
|
| 40 |
-
# Convert 'date' column to datetime format
|
| 41 |
-
data_frame['date'] = pd.to_datetime(data_frame['date'])
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
|
| 46 |
-
#
|
| 47 |
-
|
|
|
|
|
|
|
| 48 |
|
| 49 |
# Prepare the DataFrame for Prophet
|
| 50 |
df = pd.DataFrame({
|
|
@@ -139,7 +271,7 @@ def run_gradio():
|
|
| 139 |
outputs=[
|
| 140 |
gr.components.Dataframe(label="Forecasted Sales Table"), # Forecasted data in tabular form
|
| 141 |
gr.components.Dataframe(label="Weekend Forecasted Sales Table"), # Weekend forecast data
|
| 142 |
-
gr.components.Plot(label="Sales Forecast Plot"
|
| 143 |
],
|
| 144 |
title="Sales Forecasting with Prophet",
|
| 145 |
description="Select a time range for the forecast and click on the button to train the model and see the results."
|
|
|
|
| 1 |
+
# import pandas as pd
|
| 2 |
+
# from prophet import Prophet
|
| 3 |
+
# import gradio as gr
|
| 4 |
+
# import plotly.graph_objs as go
|
| 5 |
+
# import numpy as np
|
| 6 |
+
# import requests
|
| 7 |
+
# # Function to train the model and generate forecast
|
| 8 |
+
# def predict_sales(time_frame):
|
| 9 |
+
# #login
|
| 10 |
+
# url="https://livesystem.hisabkarlay.com/auth/login"
|
| 11 |
+
# payload={
|
| 12 |
+
# 'username':'testuser',
|
| 13 |
+
# 'password':'testuser',
|
| 14 |
+
# 'client_secret':'3udPXhYSfCpktnls1C3TSzI96JLypqUGwJR05RHf',
|
| 15 |
+
# 'client_id':'4',
|
| 16 |
+
# 'grant_type':'password'
|
| 17 |
+
# }
|
| 18 |
+
# response=requests.post(url,data=payload)
|
| 19 |
+
# print(response.text)
|
| 20 |
+
# access_token=response.json()['access_token']
|
| 21 |
+
# print(access_token)
|
| 22 |
+
# #fetch all sell data
|
| 23 |
+
# per_page=-1
|
| 24 |
+
# url=f"https://livesystem.hisabkarlay.com/connector/api/sell?per_page={per_page}"
|
| 25 |
+
# headers={
|
| 26 |
+
# 'Authorization':f'Bearer {access_token}'
|
| 27 |
+
# }
|
| 28 |
+
# response=requests.get(url,headers=headers)
|
| 29 |
+
# data=response.json()['data']
|
| 30 |
+
# date=[]
|
| 31 |
+
# amount=[]
|
| 32 |
+
# for item in data:
|
| 33 |
+
# date.append(item.get('transaction_date'))
|
| 34 |
+
# amount.append(float(item.get('final_total')))
|
| 35 |
+
# data_dict={
|
| 36 |
+
# 'date':date,
|
| 37 |
+
# 'amount':amount
|
| 38 |
+
# }
|
| 39 |
+
# data_frame=pd.DataFrame(data_dict)
|
| 40 |
+
# # Convert 'date' column to datetime format
|
| 41 |
+
# data_frame['date'] = pd.to_datetime(data_frame['date'])
|
| 42 |
+
|
| 43 |
+
# # Extract only the date part
|
| 44 |
+
# data_frame['date_only'] = data_frame['date'].dt.date
|
| 45 |
+
|
| 46 |
+
# # Group by date and calculate total sales
|
| 47 |
+
# daily_sales = data_frame.groupby('date_only').agg(total_sales=('amount', 'sum')).reset_index()
|
| 48 |
+
|
| 49 |
+
# # Prepare the DataFrame for Prophet
|
| 50 |
+
# df = pd.DataFrame({
|
| 51 |
+
# 'Date': daily_sales['date_only'],
|
| 52 |
+
# 'Total paid': daily_sales['total_sales']
|
| 53 |
+
# })
|
| 54 |
+
|
| 55 |
+
# # Apply log transformation
|
| 56 |
+
# df['y'] = np.log1p(df['Total paid']) # Using log1p to avoid log(0)
|
| 57 |
+
|
| 58 |
+
# # Prepare Prophet model
|
| 59 |
+
# model = Prophet(weekly_seasonality=True) # Enable weekly seasonality
|
| 60 |
+
# df['ds'] = df['Date']
|
| 61 |
+
# model.fit(df[['ds', 'y']])
|
| 62 |
+
|
| 63 |
+
# # Future forecast based on the time frame
|
| 64 |
+
# future_periods = {
|
| 65 |
+
# 'Next Day': 1,
|
| 66 |
+
# '7 days': 7,
|
| 67 |
+
# '10 days': 10,
|
| 68 |
+
# '15 days': 15,
|
| 69 |
+
# '1 month': 30
|
| 70 |
+
# }
|
| 71 |
+
|
| 72 |
+
# # Get the last historical date and calculate the start date for the forecast
|
| 73 |
+
# last_date_value = df['Date'].iloc[-1]
|
| 74 |
+
# forecast_start_date = pd.Timestamp(last_date_value) + pd.Timedelta(days=1) # Start the forecast from the next day
|
| 75 |
+
|
| 76 |
+
# # Generate the future time DataFrame starting from the day after the last date
|
| 77 |
+
# future_time = model.make_future_dataframe(periods=future_periods[time_frame], freq='D')
|
| 78 |
+
|
| 79 |
+
# # Filter future_time to include only future dates starting from forecast_start_date
|
| 80 |
+
# future_only = future_time[future_time['ds'] >= forecast_start_date]
|
| 81 |
+
# forecast = model.predict(future_only)
|
| 82 |
+
|
| 83 |
+
# # Exponentiate the forecast to revert back to the original scale
|
| 84 |
+
# forecast['yhat'] = np.expm1(forecast['yhat']) # Use expm1 to handle the log transformation
|
| 85 |
+
# forecast['yhat_lower'] = np.expm1(forecast['yhat_lower']) # Exponentiate lower bound
|
| 86 |
+
# forecast['yhat_upper'] = np.expm1(forecast['yhat_upper']) # Exponentiate upper bound
|
| 87 |
+
|
| 88 |
+
# # Create a DataFrame for weekends only
|
| 89 |
+
# forecast['day_of_week'] = forecast['ds'].dt.day_name() # Get the day name from the date
|
| 90 |
+
# weekends = forecast[forecast['day_of_week'].isin(['Saturday', 'Sunday'])] # Filter for weekends
|
| 91 |
+
|
| 92 |
+
# # Display the forecasted data for the specified period
|
| 93 |
+
# forecast_table = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head(future_periods[time_frame])
|
| 94 |
+
# weekend_forecast_table = weekends[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] # Weekend forecast
|
| 95 |
+
|
| 96 |
+
# # Create a Plotly graph
|
| 97 |
+
# fig = go.Figure()
|
| 98 |
+
# fig.add_trace(go.Scatter(
|
| 99 |
+
# x=forecast['ds'], y=forecast['yhat'],
|
| 100 |
+
# mode='lines+markers',
|
| 101 |
+
# name='Forecasted Sales',
|
| 102 |
+
# line=dict(color='orange'),
|
| 103 |
+
# marker=dict(size=6),
|
| 104 |
+
# hovertemplate='Date: %{x}<br>Forecasted Sales: %{y}<extra></extra>'
|
| 105 |
+
# ))
|
| 106 |
+
|
| 107 |
+
# # Add lines for yhat_lower and yhat_upper
|
| 108 |
+
# fig.add_trace(go.Scatter(
|
| 109 |
+
# x=forecast['ds'], y=forecast['yhat_lower'],
|
| 110 |
+
# mode='lines',
|
| 111 |
+
# name='Lower Bound',
|
| 112 |
+
# line=dict(color='red', dash='dash')
|
| 113 |
+
# ))
|
| 114 |
+
|
| 115 |
+
# fig.add_trace(go.Scatter(
|
| 116 |
+
# x=forecast['ds'], y=forecast['yhat_upper'],
|
| 117 |
+
# mode='lines',
|
| 118 |
+
# name='Upper Bound',
|
| 119 |
+
# line=dict(color='green', dash='dash')
|
| 120 |
+
# ))
|
| 121 |
+
|
| 122 |
+
# fig.update_layout(
|
| 123 |
+
# title='Sales Forecast using Prophet',
|
| 124 |
+
# xaxis_title='Date',
|
| 125 |
+
# yaxis_title='Sales Price',
|
| 126 |
+
# xaxis=dict(tickformat="%Y-%m-%d"),
|
| 127 |
+
# yaxis=dict(autorange=True)
|
| 128 |
+
# )
|
| 129 |
+
|
| 130 |
+
# return forecast_table, weekend_forecast_table, fig # Return the forecast table, weekend forecast, and plot
|
| 131 |
+
|
| 132 |
+
# # Gradio interface
|
| 133 |
+
# def run_gradio():
|
| 134 |
+
# # Create the Gradio Interface
|
| 135 |
+
# time_options = ['Next Day', '7 days', '10 days', '15 days', '1 month']
|
| 136 |
+
# gr.Interface(
|
| 137 |
+
# fn=predict_sales, # Function to be called
|
| 138 |
+
# inputs=gr.components.Dropdown(time_options, label="Select Forecast Time Range"), # User input
|
| 139 |
+
# outputs=[
|
| 140 |
+
# gr.components.Dataframe(label="Forecasted Sales Table"), # Forecasted data in tabular form
|
| 141 |
+
# gr.components.Dataframe(label="Weekend Forecasted Sales Table"), # Weekend forecast data
|
| 142 |
+
# gr.components.Plot(label="Sales Forecast Plot",min_width=500,scale=2) # Plotly graph output
|
| 143 |
+
# ],
|
| 144 |
+
# title="Sales Forecasting with Prophet",
|
| 145 |
+
# description="Select a time range for the forecast and click on the button to train the model and see the results."
|
| 146 |
+
# ).launch(debug=True)
|
| 147 |
+
|
| 148 |
+
# # Run the Gradio interface
|
| 149 |
+
# if __name__ == '__main__':
|
| 150 |
+
# run_gradio()
|
| 151 |
import pandas as pd
|
| 152 |
from prophet import Prophet
|
| 153 |
import gradio as gr
|
| 154 |
import plotly.graph_objs as go
|
| 155 |
import numpy as np
|
| 156 |
+
|
| 157 |
# Function to train the model and generate forecast
|
| 158 |
def predict_sales(time_frame):
|
| 159 |
+
all_sales_data = pd.read_csv('All sales - House of Pizza.csv')
|
| 160 |
+
|
| 161 |
+
# Clean up the 'Total paid' column by splitting based on '₨' symbol and converting to float
|
| 162 |
+
def clean_total_paid(val):
|
| 163 |
+
if isinstance(val, str): # Only process if the value is a string
|
| 164 |
+
amounts = [float(x.replace(',', '').strip()) for x in val.split('₨') if x.strip()]
|
| 165 |
+
return sum(amounts) # Sum if multiple values exist
|
| 166 |
+
elif pd.isna(val): # Handle NaN values
|
| 167 |
+
return 0.0
|
| 168 |
+
return val # If it's already a float, return it as-is
|
| 169 |
+
|
| 170 |
+
# Apply the cleaning function to the 'Total paid' column
|
| 171 |
+
all_sales_data['Total paid'] = all_sales_data['Total paid'].apply(clean_total_paid)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
# Convert the 'Date' column to datetime, coercing errors
|
| 174 |
+
all_sales_data['Date'] = pd.to_datetime(all_sales_data['Date'], format='%m/%d/%Y %H:%M', errors='coerce')
|
| 175 |
|
| 176 |
+
# Drop rows with invalid dates
|
| 177 |
+
all_sales_data = all_sales_data.dropna(subset=['Date'])
|
| 178 |
+
all_sales_data['date_only'] = all_sales_data['Date'].dt.date
|
| 179 |
+
daily_sales = all_sales_data.groupby('date_only').agg(total_sales=('Total paid', 'sum')).reset_index()
|
| 180 |
|
| 181 |
# Prepare the DataFrame for Prophet
|
| 182 |
df = pd.DataFrame({
|
|
|
|
| 271 |
outputs=[
|
| 272 |
gr.components.Dataframe(label="Forecasted Sales Table"), # Forecasted data in tabular form
|
| 273 |
gr.components.Dataframe(label="Weekend Forecasted Sales Table"), # Weekend forecast data
|
| 274 |
+
gr.components.Plot(label="Sales Forecast Plot") # Plotly graph output
|
| 275 |
],
|
| 276 |
title="Sales Forecasting with Prophet",
|
| 277 |
description="Select a time range for the forecast and click on the button to train the model and see the results."
|