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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Importing required Library
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os, pickle
|
| 6 |
+
#from sklearn.tree import DecisionTreeRegressor
|
| 7 |
+
from sklearn import preprocessing
|
| 8 |
+
from PIL import Image
|
| 9 |
+
#import threadpoolctl
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Setting up page configuration and directory path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
st.set_page_config(page_title="Sales Forecasting App", page_icon="🐞", layout="centered")
|
| 17 |
+
DIRPATH = os.path.dirname(os.path.realpath(__file__))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Setting background image
|
| 21 |
+
|
| 22 |
+
page_bg_img = '''
|
| 23 |
+
<style>
|
| 24 |
+
[data-testid="stAppViewContainer"] {
|
| 25 |
+
background-color:black;
|
| 26 |
+
background-image:
|
| 27 |
+
radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 40px),
|
| 28 |
+
radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 30px),
|
| 29 |
+
radial-gradient(white, rgba(255,255,255,.1) 2px, transparent 40px),
|
| 30 |
+
radial-gradient(rgba(255,255,255,.4), rgba(255,255,255,.1) 2px, transparent 30px);
|
| 31 |
+
background-size: 550px 550px, 350px 350px, 250px 250px, 150px 150px;
|
| 32 |
+
background-position: 0 0, 40px 60px, 130px 270px, 70px 100px;
|
| 33 |
+
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
</style>
|
| 37 |
+
'''
|
| 38 |
+
st.markdown(page_bg_img,unsafe_allow_html=True)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Setting up logo
|
| 43 |
+
left1, left2, mid,right1, right2 = st.columns(5)
|
| 44 |
+
with left1:
|
| 45 |
+
#image1= Image.open(r"C:\\Users\\USER\Desktop\\lo.jpg")
|
| 46 |
+
st.image('https://th.bing.com/th/id/R.0fbe9296bcb3eccfd1da47a17b0f8c4c?rik=9gof%2bvdKHPQyYw&pid=ImgRaw&r=0', width=400,caption=None, use_column_width=None, clamp=100, channels="RGB", output_format='JPEG')
|
| 47 |
+
with right1:
|
| 48 |
+
#image= Image.open(r"C:\\Users\\USER\Desktop\\loi.jpg")
|
| 49 |
+
st.image('https://th.bing.com/th/id/OIP.hOpxwsP1OFM5ebfOnHq_kQAAAA?pid=ImgDet&rs=1',caption=None, use_column_width=None, clamp=100, channels="RGB", output_format='JPEG', width=317,)
|
| 50 |
+
|
| 51 |
+
# Setting up Sidebar
|
| 52 |
+
social_acc = ['Data Field Description', 'EDA', 'About App']
|
| 53 |
+
social_acc_nav = st.sidebar.radio('**INFORMATION SECTION**', social_acc)
|
| 54 |
+
|
| 55 |
+
if social_acc_nav == 'Data Field Description':
|
| 56 |
+
st.sidebar.markdown("<h2 style='text-align: center;'> Data Field Description </h2> ", unsafe_allow_html=True)
|
| 57 |
+
st.sidebar.markdown("**Date:** The date you want to predict sales for")
|
| 58 |
+
st.sidebar.markdown("**Family:** identifies the type of product sold")
|
| 59 |
+
st.sidebar.markdown("**Onpromotion:** gives the total number of items in a product family that are being promoted at a store at a given date")
|
| 60 |
+
st.sidebar.markdown("**Store Number:** identifies the store at which the products are sold")
|
| 61 |
+
st.sidebar.markdown("**Holiday Locale:** provide information about the locale where holiday is celebrated")
|
| 62 |
+
|
| 63 |
+
elif social_acc_nav == 'EDA':
|
| 64 |
+
st.sidebar.markdown("<h2 style='text-align: center;'> Exploratory Data Analysis </h2> ", unsafe_allow_html=True)
|
| 65 |
+
st.sidebar.markdown('''---''')
|
| 66 |
+
st.sidebar.markdown('''The exploratory data analysis of this project can be find in a Jupyter notebook from the linl below''')
|
| 67 |
+
st.sidebar.markdown("[Open Notebook](https://github.com/Kyei-frank/Regression-Project-Store-Sales--Time-Series-Forecasting/blob/main/project_workflow.ipynb)")
|
| 68 |
+
|
| 69 |
+
elif social_acc_nav == 'About App':
|
| 70 |
+
st.sidebar.markdown("<h2 style='text-align: center;'> Sales Forecasting App </h2> ", unsafe_allow_html=True)
|
| 71 |
+
st.sidebar.markdown('''---''')
|
| 72 |
+
st.sidebar.markdown("This App predicts the sales for product families sold at Favorita stores using regression model.")
|
| 73 |
+
st.sidebar.markdown("")
|
| 74 |
+
st.sidebar.markdown("[ Visit Github Repository for more information](https://github.com/Kyei-frank/Regression-Project-Store-Sales--Time-Series-Forecasting)")
|
| 75 |
+
st.sidebar.markdown("For mom❄️ and Delp❄️.")
|
| 76 |
+
st.sidebar.markdown("")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@st.cache(allow_output_mutation=True)
|
| 81 |
+
def Load_ml_items(relative_path):
|
| 82 |
+
"Load ML items to reuse them"
|
| 83 |
+
with open(relative_path, 'rb') as file:
|
| 84 |
+
loaded_object = pickle.load(file)
|
| 85 |
+
return loaded_object
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
loaded_object = Load_ml_items('ML_items')
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
#return loaded_object
|
| 92 |
+
Loaded_object = Load_ml_items('ML_items')
|
| 93 |
+
model, encoder, train_data, stores, holidays_event = Loaded_object['model'], Loaded_object['encoder'], Loaded_object['train_data'], Loaded_object['stores'], Loaded_object['holidays_event']
|
| 94 |
+
|
| 95 |
+
# Setting Function for extracting Calendar features
|
| 96 |
+
@st.cache(allow_output_mutation=True)
|
| 97 |
+
|
| 98 |
+
def getDateFeatures(df, date ):
|
| 99 |
+
df['date'] = pd.to_datetime(df[date])
|
| 100 |
+
df['month'] = df.date.dt.month
|
| 101 |
+
df['day_of_month'] = df.date.dt.day
|
| 102 |
+
df['day_of_year'] = df.date.dt.dayofyear
|
| 103 |
+
df['week_of_year'] = df.date.dt.isocalendar().week
|
| 104 |
+
df['day_of_week'] = df.date.dt.dayofweek
|
| 105 |
+
df['year'] = df.date.dt.year
|
| 106 |
+
df['is_weekend']= np.where(df['day_of_week'] > 4, 1, 0)
|
| 107 |
+
df['is_month_start']= df.date.dt.is_month_start.astype(int)
|
| 108 |
+
df['is_month_end']= df.date.dt.is_month_end.astype(int)
|
| 109 |
+
df['quarter']= df.date.dt.quarter
|
| 110 |
+
df['is_quarter_start']= df.date.dt.is_quarter_start.astype(int)
|
| 111 |
+
df['is_quarter_end']= df.date.dt.is_quarter_end.astype(int)
|
| 112 |
+
df['is_year_start']= df.date.dt.is_year_start.astype(int)
|
| 113 |
+
|
| 114 |
+
return df
|
| 115 |
+
|
| 116 |
+
# Setting up variables for input data
|
| 117 |
+
@st.cache()
|
| 118 |
+
def setup(tmp_df_file):
|
| 119 |
+
"Setup the required elements like files, models, global variables, etc"
|
| 120 |
+
pd.DataFrame(
|
| 121 |
+
dict(
|
| 122 |
+
date=[],
|
| 123 |
+
store_nbr=[],
|
| 124 |
+
family=[],
|
| 125 |
+
onpromotion=[],
|
| 126 |
+
city=[],
|
| 127 |
+
state=[],
|
| 128 |
+
store_type=[],
|
| 129 |
+
cluster=[],
|
| 130 |
+
day_type=[],
|
| 131 |
+
locale=[],
|
| 132 |
+
locale_name=[],
|
| 133 |
+
)
|
| 134 |
+
).to_csv(tmp_df_file, index=False)
|
| 135 |
+
|
| 136 |
+
# Setting up a file to save our input data
|
| 137 |
+
tmp_df_file = os.path.join(DIRPATH, "tmp", "data.csv")
|
| 138 |
+
setup(tmp_df_file)
|
| 139 |
+
|
| 140 |
+
# setting Title for forms
|
| 141 |
+
st.markdown("<h2 style='text-align: center;'> Sales Prediction </h2> ", unsafe_allow_html=True)
|
| 142 |
+
st.markdown("<h7 style='text-align: center;'> Fill in the details below and click on SUBMIT button to make a prediction for a specific date and item </h7> ", unsafe_allow_html=True)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# Creating columns for for input data(forms)
|
| 146 |
+
left_col, mid_col, right_col = st.columns(3)
|
| 147 |
+
|
| 148 |
+
# Developing forms to collect input data
|
| 149 |
+
with st.form(key="information", clear_on_submit=True):
|
| 150 |
+
|
| 151 |
+
# Setting up input data for 1st column
|
| 152 |
+
left_col.markdown("**PRODUCT DATA**")
|
| 153 |
+
date = left_col.date_input('Select a date:',min_value= train_data['date'].min())
|
| 154 |
+
family = left_col.selectbox("Item family:", options= list(train_data["family"].unique()))
|
| 155 |
+
onpromotion = left_col.selectbox("Onpromotion code:", options= set(train_data["onpromotion"].unique()))
|
| 156 |
+
store_nbr = left_col.selectbox("Store Number:", options= set(stores["store_nbr"].unique()))
|
| 157 |
+
|
| 158 |
+
# Setting up input data for 2nd column
|
| 159 |
+
mid_col.markdown("**STORE DATA**")
|
| 160 |
+
city = mid_col.selectbox("City:", options= set(stores["city"].unique()))
|
| 161 |
+
state = mid_col.selectbox("State:", options= list(stores["state"].unique()))
|
| 162 |
+
cluster = mid_col.selectbox("Store Cluster:", options= list(stores["cluster"].unique()))
|
| 163 |
+
store_type = mid_col.radio("Store Type:", options= sorted(set(stores["store_type"].unique())), horizontal = True)
|
| 164 |
+
|
| 165 |
+
# Setting up input data for 3rd column
|
| 166 |
+
right_col.markdown("**ADDITIONAL DATA**")
|
| 167 |
+
check= right_col.checkbox("Is it a Holiday or weekend?")
|
| 168 |
+
if check:
|
| 169 |
+
right_col.write('Fill the following information on Day Type')
|
| 170 |
+
day_type = right_col.selectbox("Holiday:", options= ('Holiday','Special Day:Transfered/Additional Holiday','No Work/Weekend'))
|
| 171 |
+
locale= right_col.selectbox("Holiday Locale:", options= list(holidays_event["locale"].unique()))
|
| 172 |
+
locale_name= right_col.selectbox("Locale Name:", options= list(holidays_event["locale_name"].unique()))
|
| 173 |
+
else:
|
| 174 |
+
day_type = 'Workday'
|
| 175 |
+
locale = 'National'
|
| 176 |
+
locale_name= 'Ecuador'
|
| 177 |
+
|
| 178 |
+
submitted = st.form_submit_button(label="Submit")
|
| 179 |
+
|
| 180 |
+
# Setting up background operations after submitting forms
|
| 181 |
+
if submitted:
|
| 182 |
+
# Saving input data as csv after submission
|
| 183 |
+
pd.read_csv(tmp_df_file).append(
|
| 184 |
+
dict(
|
| 185 |
+
date = date,
|
| 186 |
+
store_nbr = store_nbr,
|
| 187 |
+
family=family,
|
| 188 |
+
onpromotion= onpromotion,
|
| 189 |
+
city=city,
|
| 190 |
+
state=state,
|
| 191 |
+
store_type=store_type,
|
| 192 |
+
cluster=cluster,
|
| 193 |
+
day_type=day_type,
|
| 194 |
+
locale=locale,
|
| 195 |
+
locale_name=locale_name
|
| 196 |
+
),
|
| 197 |
+
ignore_index=True,
|
| 198 |
+
).to_csv(tmp_df_file, index=False)
|
| 199 |
+
st.balloons()
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
df = pd.read_csv(tmp_df_file)
|
| 203 |
+
df= df.copy()
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# Getting date Features
|
| 207 |
+
processed_data= getDateFeatures(df, 'date')
|
| 208 |
+
processed_data= processed_data.drop(columns=['date'])
|
| 209 |
+
|
| 210 |
+
# Encoding Categorical Variables
|
| 211 |
+
encoder = preprocessing.LabelEncoder()
|
| 212 |
+
cols = ['family', 'city', 'state', 'store_type', 'locale', 'locale_name', 'day_type']
|
| 213 |
+
for col in cols:
|
| 214 |
+
processed_data[col] = encoder.fit_transform(processed_data[col])
|
| 215 |
+
|
| 216 |
+
# Making Predictions
|
| 217 |
+
def predict(X, model= Loaded_object['model']):
|
| 218 |
+
results = model.predict(X)
|
| 219 |
+
return results
|
| 220 |
+
|
| 221 |
+
prediction = predict(processed_data, model= Loaded_object['model'])
|
| 222 |
+
df['Sales']= prediction
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# Displaying prediction results
|
| 226 |
+
st.markdown('''---''')
|
| 227 |
+
st.markdown("<h4 style='text-align: center;'> Prediction Results </h4> ", unsafe_allow_html=True)
|
| 228 |
+
st.success(f"Predicted Sales: {prediction[-1]}")
|
| 229 |
+
st.markdown('''---''')
|
| 230 |
+
|
| 231 |
+
# Making expander to view all records
|
| 232 |
+
expander = st.expander("See all records")
|
| 233 |
+
with expander:
|
| 234 |
+
df = pd.read_csv(tmp_df_file)
|
| 235 |
+
df['Sales']= prediction
|
| 236 |
+
st.dataframe(df)
|