DataWizard9742's picture
Update app.py
3443224 verified
import gradio as gr
import pandas as pd
import numpy as np
import pickle
import os
# Path to your saved model artifact
MODEL_PATH = 'car_price_model.pkl'
# --- Load model from pickle --- #
if not os.path.exists(MODEL_PATH):
print(f"Error: Model file not found at {MODEL_PATH}. Please ensure 'car_price_model.pkl' is in the same directory.")
# In a real deployment, you might want to handle this more robustly, e.g., by exiting or raising an error.
exit(1)
with open(MODEL_PATH, 'rb') as f:
artifact = pickle.load(f)
pipeline = artifact['pipeline']
brand_list = sorted(artifact['brand_list'])
fuel_list = sorted(artifact['fuel_list'])
owner_list = ['First Owner', 'Second Owner', 'Third Owner', 'Fourth & Above Owner', 'Test Drive Car']
def predict_price(
brand, km_driven, fuel, seller_type, transmission,
owner, mileage, engine, max_power, seats, car_age
):
try:
input_df = pd.DataFrame([{ # Ensure correct feature names as expected by the pipeline
'km_driven' : float(km_driven),
'fuel' : fuel,
'seller_type' : seller_type,
'transmission': transmission,
'owner' : owner,
'mileage' : float(mileage),
'engine' : float(engine),
'max_power' : float(max_power),
'seats' : int(seats),
'car_age' : int(car_age),
'brand' : brand,
}])
log_pred = pipeline.predict(input_df)[0]
price = np.expm1(log_pred)
# Confidence band Β±12% (as per original notebook)
low = price * 0.88
high = price * 1.12
result = (
f"πŸš— Estimated Selling Price\n"
f"{'─' * 35}\n"
f" πŸ’° Predicted : β‚Ή {price:>12,.0f}\n"
f" πŸ“‰ Low Range : β‚Ή {low:>12,.0f}\n"
f" πŸ“ˆ High Range : β‚Ή {high:>12,.0f}\n"
f"{'─' * 35}\n"
f" Model : {artifact['model_name']}\n"
f" RΒ² : {artifact['test_r2']:.4f}"
)
return result
except Exception as e:
return f'⚠️ Error: {str(e)}'
# ── Gradio UI ──────────────────────────────────────────────
with gr.Blocks(
title='πŸš— Car Price Predictor',
theme=gr.themes.Soft(primary_hue='blue')
) as demo:
gr.Markdown("""
# πŸš— Used Car Price Predictor
### Powered by Machine Learning Β· Dataset: Car Details v3
Fill in the car details below and click **Predict Price** to get an instant estimate.
""")
with gr.Row():
# ── Left Column: Car Identity
with gr.Column(scale=1):
gr.Markdown('### πŸ”– Car Identity')
brand = gr.Dropdown(brand_list, label='Brand', value='Maruti')
fuel = gr.Radio(fuel_list, label='Fuel Type', value='Petrol')
transmission = gr.Radio(['Manual', 'Automatic'], label='Transmission', value='Manual')
seller_type = gr.Radio(['Individual', 'Dealer', 'Trustmark Dealer'],
label='Seller Type', value='Individual')
owner = gr.Dropdown(owner_list, label='Owner', value='First Owner')
# ── Right Column: Specs
with gr.Column(scale=1):
gr.Markdown('### βš™οΈ Car Specifications')
car_age = gr.Slider(1, 40, value=5, step=1, label='Car Age (years)')
km_driven = gr.Number(value=50000, label='KM Driven')
mileage = gr.Slider(5.0, 35.0, value=18.0, step=0.1, label='Mileage (kmpl)')
engine = gr.Slider(500, 5000, value=1200, step=50, label='Engine (CC)')
max_power = gr.Slider(30, 400, value=80, step=1, label='Max Power (bhp)')
seats = gr.Slider(2, 10, value=5, step=1, label='Seats')
with gr.Row():
predict_btn = gr.Button('πŸš€ Predict Price', variant='primary', scale=2)
clear_btn = gr.Button('πŸ”„ Reset', scale=1)
output = gr.Textbox(label='Prediction Result', lines=9, )
# Examples
gr.Examples(
examples=[
['Maruti', 50000, 'Petrol', 'Individual', 'Manual', 'First Owner', 22.0, 1200, 82, 5, 5],
['Honda', 30000, 'Petrol', 'Individual', 'Automatic', 'Second Owner', 17.0, 1500, 118, 5, 3],
['Toyota', 80000, 'Diesel', 'Dealer', 'Manual', 'First Owner', 21.0, 2000, 150, 7, 7],
['BMW', 40000, 'Petrol', 'Trustmark Dealer','Automatic', 'Second Owner', 12.0, 2000, 190, 5, 4],
['Mahindra', 120000, 'Diesel', 'Individual', 'Manual', 'Third Owner', 16.0, 2200, 130, 7, 10],
],
inputs=[brand, km_driven, fuel, seller_type, transmission,
owner, mileage, engine, max_power, seats, car_age],
label='πŸ“‹ Example Cars β€” Click to Auto-Fill'
)
gr.Markdown(f"""
---
**Model Info:** {artifact['model_name']} Β· Test RΒ² = {artifact['test_r2']:.4f} Β· MAE β‰ˆ β‚Ή{artifact['test_mae']:,.0f}
""")
predict_btn.click(
fn=predict_price,
inputs=[brand, km_driven, fuel, seller_type, transmission,
owner, mileage, engine, max_power, seats, car_age],
outputs=output
)
clear_btn.click(fn=lambda: None, outputs=output)
if __name__ == '__main__':
demo.launch(share=False, show_error=True)