liberatoratif's picture
Update app.py
30d0d6a
raw
history blame
9.22 kB
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)