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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import plotly.express as px
|
5 |
+
from datetime import datetime, timedelta
|
6 |
+
import holidays
|
7 |
+
from sklearn.ensemble import GradientBoostingRegressor
|
8 |
+
import xgboost as xgb
|
9 |
+
from sklearn.ensemble import AdaBoostRegressor
|
10 |
+
from catboost import CatBoostRegressor
|
11 |
+
from sklearn.ensemble import VotingRegressor
|
12 |
+
from sklearn.model_selection import train_test_split
|
13 |
+
import random
|
14 |
+
|
15 |
+
|
16 |
+
st.set_page_config(
|
17 |
+
page_title="Inventory Management System",
|
18 |
+
page_icon="💮",
|
19 |
+
layout="wide",
|
20 |
+
initial_sidebar_state="expanded",
|
21 |
+
)
|
22 |
+
|
23 |
+
st.markdown(
|
24 |
+
"""
|
25 |
+
<style>
|
26 |
+
[data-testid="stSidebar"][aria-expanded="true"] > div:first-child {
|
27 |
+
width: 200px;
|
28 |
+
}
|
29 |
+
[data-testid="stSidebar"][aria-expanded="flase"] > div:first-child {
|
30 |
+
width: 50px;
|
31 |
+
margin-left: -100px;
|
32 |
+
}
|
33 |
+
</style>
|
34 |
+
""",
|
35 |
+
unsafe_allow_html=True,
|
36 |
+
)
|
37 |
+
var = 0
|
38 |
+
with open("ATIF_SHAIK.pdf", "rb") as pdf_file:
|
39 |
+
PDFbyte = pdf_file.read()
|
40 |
+
|
41 |
+
with st.sidebar:
|
42 |
+
err = 0
|
43 |
+
data = st.file_uploader('Upload Stores Data')
|
44 |
+
if data:
|
45 |
+
# st.write(data.type)
|
46 |
+
if data.type != 'text/csv':
|
47 |
+
err = 1
|
48 |
+
st.info('Please Upload a CSV File format Only...')
|
49 |
+
|
50 |
+
st.download_button(
|
51 |
+
label="Download My Model Report as PDF",
|
52 |
+
data=PDFbyte,
|
53 |
+
key="download_button",
|
54 |
+
on_click=None, # You can specify a function to be called when the button is clicked
|
55 |
+
args=None, # Arguments to pass to the on_click function if specified
|
56 |
+
file_name='inventory_management_report.pdf',
|
57 |
+
mime='application/pdf' # Use 'application/pdf' for PDF files
|
58 |
+
)
|
59 |
+
|
60 |
+
st.markdown("<h1 style='color: blue;'>INVENTORY MANAGEMENT SYSTEM</h1>", unsafe_allow_html=True)
|
61 |
+
with st.expander('Introduction'):
|
62 |
+
st.write('Welcome to Invento - Your Smart Inventory Management Solution! Our app leverages the power of artificial intelligence and data analytics to revolutionize inventory management for businesses of all sizes. Say goodbye to overstocked shelves and stockouts. With Invento, you can predict product demand, optimize stock levels, and boost profitability. Explore our intuitive interface, harness the magic of machine learning, and stay ahead of the competition. Get ready to experience inventory management reimagined!')
|
63 |
+
|
64 |
+
|
65 |
+
st.warning('Click on Forecast Button after every chnages you make...')
|
66 |
+
st.warning("If any error displayed on screen don't worry just follow steps and it'll vanish")
|
67 |
+
|
68 |
+
def create_holiday_flags(date_series, country='TH'):
|
69 |
+
holiday_dict = holidays.CountryHoliday(country)
|
70 |
+
|
71 |
+
# Create a list to store binary holiday flags
|
72 |
+
holiday_flags = []
|
73 |
+
|
74 |
+
# Iterate through the date_series
|
75 |
+
for date in date_series:
|
76 |
+
date_obj = datetime.strptime(date, '%m/%d/%Y')
|
77 |
+
if date_obj in holiday_dict:
|
78 |
+
holiday_flags.append(1)
|
79 |
+
else:
|
80 |
+
holiday_flags.append(0)
|
81 |
+
|
82 |
+
return holiday_flags
|
83 |
+
|
84 |
+
|
85 |
+
def gender_encode(text):
|
86 |
+
if text == 'Male':
|
87 |
+
return 1;
|
88 |
+
else:
|
89 |
+
return 0
|
90 |
+
|
91 |
+
|
92 |
+
@st.cache_data
|
93 |
+
def train(dat):
|
94 |
+
store = pd.read_csv(dat)
|
95 |
+
store = store.sort_values(by='Date')
|
96 |
+
encoded_payment_mode = pd.get_dummies(store['Payment'], prefix='payment')
|
97 |
+
store = store.drop('Payment', axis=1)
|
98 |
+
store = pd.concat([store, encoded_payment_mode], axis=1)
|
99 |
+
|
100 |
+
|
101 |
+
store['Gender'] = store['Gender'].apply(gender_encode)
|
102 |
+
|
103 |
+
store['is_holiday'] = create_holiday_flags(store['Date'])
|
104 |
+
|
105 |
+
store['Date'] = pd.to_datetime(store['Date'])
|
106 |
+
|
107 |
+
store['year'] = store['Date'].dt.year
|
108 |
+
store['day'] = store['Date'].dt.day
|
109 |
+
store['month'] = store['Date'].dt.month
|
110 |
+
|
111 |
+
try:
|
112 |
+
store = store.drop(['Invoice ID', 'Branch', 'City', 'Customer type', 'Tax 5%', 'gross margin percentage', 'gross income', 'Rating'], axis=1)
|
113 |
+
except Exception:
|
114 |
+
pass
|
115 |
+
|
116 |
+
store = store.drop(['Date'], axis=1)
|
117 |
+
|
118 |
+
try:
|
119 |
+
store = store.drop(['Total', 'Time'], axis=1)
|
120 |
+
except Exception:
|
121 |
+
pass
|
122 |
+
|
123 |
+
import category_encoders as ce
|
124 |
+
tenc=ce.TargetEncoder()
|
125 |
+
df_city=tenc.fit_transform(store['Product line'],store['Quantity'])
|
126 |
+
|
127 |
+
d = {}
|
128 |
+
for i,j in zip(list(store['Product line']), list(df_city['Product line'])):
|
129 |
+
if i not in d:
|
130 |
+
d[i] = j
|
131 |
+
|
132 |
+
store['Product line'] = df_city
|
133 |
+
|
134 |
+
store = store.reset_index()
|
135 |
+
|
136 |
+
try:
|
137 |
+
store = store.drop(['index'], axis=1)
|
138 |
+
except Exception:
|
139 |
+
pass
|
140 |
+
|
141 |
+
model4 = CatBoostRegressor()
|
142 |
+
model1 = GradientBoostingRegressor()
|
143 |
+
model2 = xgb.XGBRegressor()
|
144 |
+
model3 = AdaBoostRegressor()
|
145 |
+
|
146 |
+
y = store['Quantity']
|
147 |
+
y = y.values
|
148 |
+
X = store.drop(['Quantity'], axis=1)
|
149 |
+
X = X.drop(['payment_Cash'],axis=1)
|
150 |
+
# st.dataframe(X)
|
151 |
+
X = X.values
|
152 |
+
|
153 |
+
ensemble_EC1 = VotingRegressor(estimators=[('gb', model1), ('xgb', model2), ('ada', model3), ('cat', model4)])
|
154 |
+
ensemble_EC1.fit(X, y)
|
155 |
+
|
156 |
+
return d, ensemble_EC1
|
157 |
+
|
158 |
+
|
159 |
+
with st.spinner("Model is getting trained..."):
|
160 |
+
if data:
|
161 |
+
di, model = train(data)
|
162 |
+
|
163 |
+
if data and err==0:
|
164 |
+
st.toast('Just one click and manage your Goods stock', icon='😍')
|
165 |
+
forecast = st.button('Forecast Inventory')
|
166 |
+
|
167 |
+
|
168 |
+
def func(daa):
|
169 |
+
store2 = pd.read_csv(daa)
|
170 |
+
store2['Date'] = pd.to_datetime(store2['Date'])
|
171 |
+
store2['year'] = store2['Date'].dt.year
|
172 |
+
store2['day'] = store2['Date'].dt.day
|
173 |
+
store2['month'] = store2['Date'].dt.month
|
174 |
+
|
175 |
+
|
176 |
+
yy = store2.iloc[store2.shape[1]-1].year
|
177 |
+
dd = store2.iloc[store2.shape[1]-1].day
|
178 |
+
mm = store2.iloc[store2.shape[1]-1].month
|
179 |
+
|
180 |
+
return yy, dd, mm
|
181 |
+
|
182 |
+
try:
|
183 |
+
yy, dd, mm = func(data)
|
184 |
+
except Exception as e:
|
185 |
+
pass
|
186 |
+
|
187 |
+
col1, col2 = st.columns(2)
|
188 |
+
col3, col4 = st.columns(2)
|
189 |
+
col5, col6 = st.columns(2)
|
190 |
+
|
191 |
+
with col1:
|
192 |
+
gender = st.radio("Select Gender for Forecasting", ('Male', 'Female'))
|
193 |
+
|
194 |
+
with col2:
|
195 |
+
payment_method = st.radio("Select Payment Method for Forecasting", ('Cash', 'Credit Card', 'E-Wallet'))
|
196 |
+
|
197 |
+
with col3:
|
198 |
+
uni_price = st.number_input("Insert Min Price of Individual Unit Price")
|
199 |
+
|
200 |
+
with col4:
|
201 |
+
uni_max = st.number_input("Insert Max Price of Individual Unit Price")
|
202 |
+
|
203 |
+
with col5:
|
204 |
+
cog_price = st.number_input("Insert Min Price of COGS")
|
205 |
+
|
206 |
+
with col6:
|
207 |
+
cog_max = st.number_input("Insert Max Price of COGS")
|
208 |
+
|
209 |
+
|
210 |
+
try:
|
211 |
+
prods = st.selectbox('Choose a Product for Forecast', di.keys())
|
212 |
+
except Exception as e:
|
213 |
+
pass
|
214 |
+
|
215 |
+
|
216 |
+
start_date = st.slider(
|
217 |
+
"When to start?",
|
218 |
+
value=datetime(yy, mm, dd),
|
219 |
+
format="DD/MM/YY")
|
220 |
+
|
221 |
+
# input_date = datetime(yy, mm, dd)
|
222 |
+
st.write("Forecast from : ", start_date.date())
|
223 |
+
|
224 |
+
# result_date = input_date + timedelta(days=60)
|
225 |
+
|
226 |
+
end_date = st.slider("How many days to forecast?",1, 60)
|
227 |
+
|
228 |
+
st.write('Days to Forecast : ', end_date)
|
229 |
+
|
230 |
+
range_date = start_date+timedelta(days=end_date-1)
|
231 |
+
|
232 |
+
col7, col8, col9 = st.columns(3)
|
233 |
+
with col8:
|
234 |
+
st.write(f'{start_date.date()} : {range_date.date()}')
|
235 |
+
|
236 |
+
gender = [] #d
|
237 |
+
uni_pr = [] #d
|
238 |
+
cogs = [] #d
|
239 |
+
cred = [] #d
|
240 |
+
e_wallet = [] #d
|
241 |
+
date_list = [] #d
|
242 |
+
prod = [] #d
|
243 |
+
is_hol = [] #d
|
244 |
+
|
245 |
+
|
246 |
+
current_date = start_date.date()
|
247 |
+
while current_date <= range_date.date():
|
248 |
+
date_list.append(current_date)
|
249 |
+
current_date += timedelta(days=1)
|
250 |
+
|
251 |
+
# st.dataframe(pd.DataFrame(date_list))
|
252 |
+
|
253 |
+
years = [i.year for i in date_list]
|
254 |
+
months = [i.month for i in date_list]
|
255 |
+
days = [i.day for i in date_list]
|
256 |
+
|
257 |
+
for i in range(len(date_list)):
|
258 |
+
if gender == "Male":
|
259 |
+
gender.append(1)
|
260 |
+
else:
|
261 |
+
gender.append(0)
|
262 |
+
|
263 |
+
|
264 |
+
for i in range(len(date_list)):
|
265 |
+
random_value = random.uniform(uni_price, uni_max)
|
266 |
+
uni_pr.append(random_value)
|
267 |
+
|
268 |
+
|
269 |
+
for i in range(len(date_list)):
|
270 |
+
random_vaue = random.uniform(cog_price, cog_max)
|
271 |
+
cogs.append(random_vaue)
|
272 |
+
|
273 |
+
if payment_method == "Cash":
|
274 |
+
cred = [0 for i in range(len(date_list))]
|
275 |
+
e_wallet = [0 for i in range(len(date_list))]
|
276 |
+
|
277 |
+
elif payment_method == "Credit Card":
|
278 |
+
cred = [1 for i in range(len(date_list))]
|
279 |
+
e_wallet = [0 for i in range(len(date_list))]
|
280 |
+
|
281 |
+
elif payment_method == "E-Wallet":
|
282 |
+
cred = [0 for i in range(len(date_list))]
|
283 |
+
e_wallet = [1 for i in range(len(date_list))]
|
284 |
+
|
285 |
+
|
286 |
+
for i in range(len(date_list)):
|
287 |
+
prod.append(di[prods])
|
288 |
+
|
289 |
+
date_strings = [date.strftime('%m/%d/%Y') for date in date_list]
|
290 |
+
is_hol = create_holiday_flags(date_strings)
|
291 |
+
|
292 |
+
|
293 |
+
forecast_data = pd.DataFrame({"Gender":gender, "Product line":prod, "Unit price":uni_pr, "cogs":cogs, "payment_Credit card":cred, "payment_Ewallet":e_wallet,
|
294 |
+
"is_holiday":is_hol, "year":years, "day":days, "month":months})
|
295 |
+
|
296 |
+
# st.dataframe(forecast_data)
|
297 |
+
forecast_data = forecast_data.values
|
298 |
+
|
299 |
+
# y_pred = int(np.round(model.predict(forecast_data)))
|
300 |
+
y_pred = [int(np.round(pred)) for pred in model.predict(forecast_data)]
|
301 |
+
|
302 |
+
line = px.line(x=date_list, y=y_pred, title="Quantity Sale forecast")
|
303 |
+
box = px.box(y=y_pred, title='To Identify Bursts or Lower Quantity Sale')
|
304 |
+
hist = px.histogram(x=y_pred, title = 'Sales Display in Area')
|
305 |
+
col11, col22 = st.columns(2)
|
306 |
+
col33, col44 = st.columns(2)
|
307 |
+
|
308 |
+
with col11:
|
309 |
+
st.plotly_chart(line, use_container_width=True)
|
310 |
+
|
311 |
+
with col22:
|
312 |
+
st.plotly_chart(box, use_container_width=True)
|
313 |
+
|
314 |
+
with col33:
|
315 |
+
st.write(f"AVG SALE FORECAST : {np.average(np.array(y_pred)).round(2)} QUANTITIES")
|
316 |
+
|
317 |
+
with col44:
|
318 |
+
st.plotly_chart(hist, use_container_width=True)
|