carmodel / app.py
kariukireuben's picture
Upload app.py with huggingface_hub
b3384bd verified
import streamlit as st
import pandas as pd
import joblib
import numpy as np
from datetime import datetime
# -------------------------------
# Load the trained model safely
# -------------------------------
@st.cache_resource #is a Streamlit decorator used to cache expensive resources β€” things that take time to load or initialize
def load_model():
# Use the path where the model was saved in the notebook
saved_model_path = "deployment_files/car_prediction_model_v1_0.joblib"
try:
model = joblib.load(saved_model_path)
return model
except FileNotFoundError:
st.error(f"Model file not found at {saved_model_path}. Please ensure the model is saved correctly.")
return None
except Exception as e:
st.error(f"An error occurred while loading the model: {e}")
return None
model = load_model()
# -------------------------------
# Main Streamlit App
# -------------------------------
def main():
st.set_page_config(page_title="Car Pricing Predictor", page_icon="πŸš—", layout="centered")
st.title("πŸš— Car Pricing Prediction Solution")
st.write("Enter your car details below to predict its resale price in **USD**.")
# -------------------------------
# Sidebar Instructions
# -------------------------------
st.sidebar.header("Instructions")
st.sidebar.info("""
- **Year:** Year the car was manufactured (e.g., 2016)
- **Kms Driven:** Total kilometers driven
- **Owner:** Number of previous owners (0 = first owner)
- **Fuel Type:** Diesel, Petrol, or CNG
- **Seller Type:** Individual or Dealer
- **Transmission:** Manual or Automatic
""")
# -------------------------------
# User Inputs
# -------------------------------
manufacture_year_input = st.number_input(
"Year of Manufacture",
min_value=1990, max_value=datetime.now().year, value=2015,
help="Enter the year the car was made"
)
kms_driven_input = st.number_input(
"Total Kilometers Driven",
min_value=0, value=50000, step=1000,
help="Enter total kilometers driven"
)
owner_input = st.number_input(
"Number of Previous Owners",
min_value=0, max_value=10, value=0, step=1,
help="Enter the number of previous owners"
)
fuel_type_input = st.selectbox(
"Fuel Type",
["Petrol", "Diesel", "CNG"],
help="Select the fuel type"
)
seller_type_input = st.selectbox(
"Seller Type",
["Dealer", "Individual"],
help="Select the seller type"
)
transmission_input = st.selectbox(
"Transmission Type",
["Manual", "Automatic"],
help="Select the transmission type"
)
# -------------------------------
# Prediction Logic
# -------------------------------
if st.button("Predict Selling Price"):
if model is not None:
# Create a DataFrame from user inputs
# Ensure column order matches the training data used for the model
# The model was trained on: ['Year', 'Kms_Driven', 'Owner', 'Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
# Calculate Car Age
current_year = datetime.now().year
car_age = current_year - manufacture_year_input
input_data = pd.DataFrame({
'Year': [car_age], # Use calculated car age
'Kms_Driven': [kms_driven_input],
'Owner': [owner_input],
# One-hot encode Fuel_Type
'Fuel_Type_Diesel': [1 if fuel_type_input == 'Diesel' else 0],
'Fuel_Type_Petrol': [1 if fuel_type_input == 'Petrol' else 0],
# One-hot encode Seller_Type
'Seller_Type_Individual': [1 if seller_type_input == 'Individual' else 0],
# One-hot encode Transmission
'Transmission_Manual': [1 if transmission_input == 'Manual' else 0]
})
# Ensure numerical columns have correct types and check for NaNs
numerical_cols = ['Year', 'Kms_Driven', 'Owner']
for col in numerical_cols:
input_data[col] = pd.to_numeric(input_data[col], errors='coerce')
if input_data[numerical_cols].isnull().any().any():
st.error("Invalid input detected for numerical fields. Please check your values.")
return # Stop execution if invalid input is found
# Ensure one-hot encoded columns have correct types (int)
encoded_cols = ['Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
for col in encoded_cols:
input_data[col] = input_data[col].astype(int)
try:
# Make prediction
predicted_price = model.predict(input_data)[0]
# Display prediction
st.success(f"Predicted Selling Price: **${predicted_price:,.2f}**")
except Exception as e:
st.error(f"An error occurred during prediction: {e}")
st.write("Please check your input values and ensure the model is loaded correctly.")
else:
st.warning("Model not loaded. Please check the model file path and try again.")