File size: 9,217 Bytes
a9c13c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30d0d6a
a9c13c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355529f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from datetime import datetime, timedelta
import holidays
from sklearn.ensemble import GradientBoostingRegressor
import xgboost as xgb
from sklearn.ensemble import AdaBoostRegressor
from catboost import CatBoostRegressor
from sklearn.ensemble import VotingRegressor
from sklearn.model_selection import train_test_split
import random


st.set_page_config(
    page_title="Inventory Management System",
    page_icon="๐Ÿ’ฎ",
    layout="wide",
    initial_sidebar_state="expanded",
)

st.markdown(
    """
    <style>
    [data-testid="stSidebar"][aria-expanded="true"] > div:first-child {
        width: 200px;
    }
    [data-testid="stSidebar"][aria-expanded="flase"] > div:first-child {
        width: 50px;
        margin-left: -100px;
    }
    </style>
    """,
    unsafe_allow_html=True,
)
var = 0
with open("ATIF_SHAIK.pdf", "rb") as pdf_file:
    PDFbyte = pdf_file.read()

with st.sidebar:
    err = 0
    data = st.file_uploader("Upload Stores Data (please use the same data uder 'files' section)")
    if data:
        # st.write(data.type)
        if data.type != 'text/csv':
            err = 1
            st.info('Please Upload a CSV File format Only...')

    st.download_button(
        label="Download My Model Report as PDF",
        data=PDFbyte,
        key="download_button",
        on_click=None,  # You can specify a function to be called when the button is clicked
        args=None,  # Arguments to pass to the on_click function if specified
        file_name='inventory_management_report.pdf',
        mime='application/pdf'  # Use 'application/pdf' for PDF files
        )

st.markdown("<h1 style='color: blue;'>INVENTORY MANAGEMENT SYSTEM</h1>", unsafe_allow_html=True)
with st.expander('Introduction'):
    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!')


st.warning('Click on Forecast Button after every chnages you make...')
st.warning("If any error displayed on screen don't worry just follow steps and it'll vanish")

def create_holiday_flags(date_series, country='TH'):
    holiday_dict = holidays.CountryHoliday(country)

    # Create a list to store binary holiday flags
    holiday_flags = []

    # Iterate through the date_series
    for date in date_series:
        date_obj = datetime.strptime(date, '%m/%d/%Y')
        if date_obj in holiday_dict:
            holiday_flags.append(1)
        else:
            holiday_flags.append(0)

    return holiday_flags


def gender_encode(text):
    if text == 'Male':
        return 1;
    else:
        return 0


@st.cache_data
def train(dat):
    store = pd.read_csv(dat)
    store = store.sort_values(by='Date')
    encoded_payment_mode = pd.get_dummies(store['Payment'], prefix='payment')
    store = store.drop('Payment', axis=1)
    store = pd.concat([store, encoded_payment_mode], axis=1)


    store['Gender'] = store['Gender'].apply(gender_encode)

    store['is_holiday'] = create_holiday_flags(store['Date'])

    store['Date'] = pd.to_datetime(store['Date'])

    store['year'] = store['Date'].dt.year
    store['day'] = store['Date'].dt.day
    store['month'] = store['Date'].dt.month

    try:
        store = store.drop(['Invoice ID', 'Branch', 'City', 'Customer type', 'Tax 5%', 'gross margin percentage', 'gross income', 'Rating'], axis=1)
    except Exception:
        pass

    store = store.drop(['Date'], axis=1)

    try:
        store = store.drop(['Total', 'Time'], axis=1)
    except Exception:
        pass

    import category_encoders as ce
    tenc=ce.TargetEncoder()
    df_city=tenc.fit_transform(store['Product line'],store['Quantity'])

    d = {}
    for i,j in zip(list(store['Product line']), list(df_city['Product line'])):
        if i not in d:
            d[i] = j

    store['Product line'] = df_city

    store = store.reset_index()

    try:
        store = store.drop(['index'], axis=1)
    except Exception:
        pass

    model4 = CatBoostRegressor()
    model1 = GradientBoostingRegressor()
    model2 = xgb.XGBRegressor()
    model3 = AdaBoostRegressor()

    y = store['Quantity']
    y = y.values
    X = store.drop(['Quantity'], axis=1)
    X = X.drop(['payment_Cash'],axis=1)
    # st.dataframe(X)
    X = X.values

    ensemble_EC1 = VotingRegressor(estimators=[('gb', model1), ('xgb', model2), ('ada', model3), ('cat', model4)])
    ensemble_EC1.fit(X, y)

    return d, ensemble_EC1


with st.spinner("Model is getting trained..."):
    if data:
        di, model = train(data)

if data and err==0:
    st.toast('Just one click and manage your Goods stock', icon='๐Ÿ˜')
    forecast = st.button('Forecast Inventory')


def func(daa):
    store2 = pd.read_csv(daa)
    store2['Date'] = pd.to_datetime(store2['Date'])
    store2['year'] = store2['Date'].dt.year
    store2['day'] = store2['Date'].dt.day
    store2['month'] = store2['Date'].dt.month


    yy = store2.iloc[store2.shape[1]-1].year
    dd = store2.iloc[store2.shape[1]-1].day
    mm = store2.iloc[store2.shape[1]-1].month

    return yy, dd, mm

try:
    yy, dd, mm = func(data)
except Exception as e:
    pass

col1, col2 = st.columns(2)
col3, col4 = st.columns(2)
col5, col6 = st.columns(2)

with col1:
    gender = st.radio("Select Gender for Forecasting", ('Male', 'Female'))

with col2:
    payment_method = st.radio("Select Payment Method for Forecasting", ('Cash', 'Credit Card', 'E-Wallet'))

with col3:
    uni_price = st.number_input("Insert Min Price of Individual Unit Price")

with col4:
    uni_max = st.number_input("Insert Max Price of Individual Unit Price")

with col5:
    cog_price = st.number_input("Insert Min Price of COGS")

with col6:
    cog_max = st.number_input("Insert Max Price of COGS")


try:
    prods = st.selectbox('Choose a Product for Forecast', di.keys())    
except Exception as e:
    pass


start_date = st.slider(
                        "When to start?",
                        value=datetime(yy, mm, dd),
                        format="DD/MM/YY")

# input_date = datetime(yy, mm, dd)
st.write("Forecast from : ", start_date.date())

# result_date = input_date + timedelta(days=60)

end_date = st.slider("How many days to forecast?",1, 60)

st.write('Days to Forecast : ', end_date)

range_date = start_date+timedelta(days=end_date-1)

col7, col8, col9 = st.columns(3)
with col8:
    st.write(f'{start_date.date()} : {range_date.date()}')

gender = [] #d
uni_pr = [] #d
cogs = []   #d
cred = []   #d
e_wallet = []   #d
date_list = []  #d
prod = []   #d
is_hol = [] #d


current_date = start_date.date()
while current_date <= range_date.date():
    date_list.append(current_date)
    current_date += timedelta(days=1)

# st.dataframe(pd.DataFrame(date_list))

years = [i.year for i in date_list]
months = [i.month for i in date_list]
days = [i.day for i in date_list]

for i in range(len(date_list)):
    if gender == "Male":
        gender.append(1)
    else:
        gender.append(0)


for i in range(len(date_list)):
    random_value = random.uniform(uni_price, uni_max)
    uni_pr.append(random_value)


for i in range(len(date_list)):
    random_vaue = random.uniform(cog_price, cog_max)
    cogs.append(random_vaue)

if payment_method == "Cash":
    cred = [0 for i in range(len(date_list))]
    e_wallet = [0 for i in range(len(date_list))]

elif payment_method == "Credit Card":
    cred = [1 for i in range(len(date_list))]
    e_wallet = [0 for i in range(len(date_list))]

elif payment_method == "E-Wallet":
    cred = [0 for i in range(len(date_list))]
    e_wallet = [1 for i in range(len(date_list))]


for i in range(len(date_list)):
    prod.append(di[prods])

date_strings = [date.strftime('%m/%d/%Y') for date in date_list]
is_hol = create_holiday_flags(date_strings)


forecast_data = pd.DataFrame({"Gender":gender, "Product line":prod, "Unit price":uni_pr, "cogs":cogs, "payment_Credit card":cred, "payment_Ewallet":e_wallet,
                              "is_holiday":is_hol, "year":years, "day":days, "month":months})

# st.dataframe(forecast_data)
forecast_data = forecast_data.values

# y_pred = int(np.round(model.predict(forecast_data)))
y_pred = [int(np.round(pred)) for pred in model.predict(forecast_data)]

line = px.line(x=date_list, y=y_pred, title="Quantity Sale forecast")
box = px.box(y=y_pred, title='To Identify Bursts or Lower Quantity Sale')
hist = px.histogram(x=y_pred, title = 'Sales Display in Area')
col11, col22 = st.columns(2)
col33, col44 = st.columns(2)

with col11:
    st.plotly_chart(line, use_container_width=True)

with col22:
    st.plotly_chart(box, use_container_width=True)

with col33:
    st.write(f"AVG SALE FORECAST : {np.average(np.array(y_pred)).round(2)} QUANTITIES")

with col44:
    st.plotly_chart(hist, use_container_width=True)