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)