BackpackPricePrediction / src /streamlit_app.py
handex's picture
Update src/streamlit_app.py
ab65519 verified
Raw
History Blame Contribute Delete
3.56 kB
import streamlit as st
import pandas as pd
import joblib
import numpy as np
# Load Model
@st.cache_resource
def load_artifacts():
try:
return joblib.load('src/backpack_model.joblib')
except FileNotFoundError:
st.error("Model file 'backpack_model.joblib' not found. Please upload it to the Files section.")
return None
artifacts = load_artifacts()
if artifacts:
model = artifacts['model']
encoders = artifacts['encoders']
size_mapping = artifacts['size_mapping']
medians = artifacts.get('medians', {})
# Page Configuration
st.set_page_config(
page_title="Backpack Price Predictor",
page_icon="πŸŽ’",
layout="centered")
st.title("πŸŽ’ Backpack Price Prediction AI")
st.markdown("""
This AI tool predicts the price of a backpack based on its features.
\n**Adjust the values below and click 'Predict Price'.**
""")
# Input
if artifacts:
with st.form("prediction_form"):
st.subheader("1. Backpack Features")
col1, col2 = st.columns(2)
with col1:
brand = st.selectbox("Brand", options=encoders['Brand'].classes_)
material = st.selectbox("Material", options=encoders['Material'].classes_)
style = st.selectbox("Style", options=encoders['Style'].classes_)
color = st.selectbox("Color", options=encoders['Color'].classes_)
with col2:
size = st.selectbox("Size", options=['Small', 'Medium', 'Large', 'Unknown'])
compartments = st.number_input("Number of Compartments", min_value=0, max_value=20, value=5, step=1)
weight_capacity = st.number_input("Weight Capacity (kg)", min_value=0.0, max_value=100.0, value=10.0, step=0.5)
st.subheader("2. Extra Features")
col3, col4 = st.columns(2)
with col3:
laptop = st.selectbox("Laptop Compartment?", options=['Yes', 'No'])
with col4:
waterproof = st.selectbox("Waterproof?", options=['Yes', 'No'])
submit_btn = st.form_submit_button("Predict Price πŸš€", type="primary")
# Prediction
if submit_btn:
input_data = {
'Brand': brand,
'Material': material,
'Style': style,
'Color': color,
'Laptop Compartment': laptop,
'Waterproof': waterproof,
'Size': size,
'Compartments': compartments,
'Weight Capacity (kg)': weight_capacity}
df_input = pd.DataFrame([input_data])
try:
df_input['Size_Encoded'] = df_input['Size'].map(size_mapping).fillna(-1)
encode_cols = ['Brand', 'Material', 'Style', 'Color', 'Laptop Compartment', 'Waterproof']
for col in encode_cols:
df_input[f'{col}_Encoded'] = encoders[col].transform([input_data[col]])
model_features = model.get_booster().feature_names
X_pred = df_input[model_features]
prediction = model.predict(X_pred)[0]
st.success(f"πŸ’° Estimated Price: **${prediction:.2f}**")
st.progress(min(int(prediction), 300) / 300)
except Exception as e:
st.error(f"An error occurred during prediction: {e}")
st.warning("Technical Detail: Ensure the input categories match the training data.")
else:
st.warning("Please upload the 'backpack_model.joblib' file to the app files.")