aracfiyattahmin / app.py
berkemert's picture
Update app.py
c162a62 verified
Raw
History Blame Contribute Delete
7.92 kB
import pandas as pd
import joblib
import gradio as gr
# Load the pkl model
try:
pipe = joblib.load('car_price_model.pkl')
except FileNotFoundError:
print("ERROR: 'car_price_model.pkl' file not found. Please ensure the file is in the correct path.")
pipe = None
except Exception as e:
print(f"An error occurred while loading the model: {e}")
pipe = None
# Load data
try:
df = pd.read_excel('cars.xls')
# Get unique and non-NaN values for Gradio dropdowns, then sort them
make_options = sorted(df['Make'].dropna().unique().tolist())
cylinder_options = sorted(df['Cylinder'].dropna().unique().tolist())
doors_options = sorted(df['Doors'].dropna().unique().tolist())
except FileNotFoundError:
print("ERROR: 'cars.xls' file not found. Please ensure the file is in the correct path.")
# Create a sample or empty DataFrame to prevent the application from crashing
df = pd.DataFrame({
'Make': [], 'Model': [], 'Trim': [], 'Type': [],
'Cylinder': [], 'Doors': []
})
make_options = []
cylinder_options = []
doors_options = []
except Exception as e:
print(f"An error occurred while loading the data: {e}")
df = pd.DataFrame({
'Make': [], 'Model': [], 'Trim': [], 'Type': [],
'Cylinder': [], 'Doors': []
})
make_options = []
cylinder_options = []
doors_options = []
def predict_price(make, model, trim, mileage, car_type, cylinder, liter, doors, cruise, sound, leather):
if pipe is None:
return "ERROR: Model could not be loaded, prediction cannot be made."
try:
# Convert user input data to DataFrame
input_data = pd.DataFrame({
'Make': [make],
'Model': [model],
'Trim': [trim],
'Mileage': [mileage],
'Type': [car_type],
'Cylinder': [cylinder],
'Liter': [liter],
'Doors': [doors],
'Cruise': [cruise],
'Sound': [sound],
'Leather': [leather]
})
prediction = pipe.predict(input_data)[0]
return f"Estimated Price: ${int(prediction):,}" # Format the number
except Exception as e:
return f"An error occurred during prediction: {e}"
# Function to dynamically update model options
def update_models(selected_make):
if pd.isna(selected_make) or not selected_make:
return gr.Dropdown(choices=[], label="Model", interactive=True, value=None)
models = sorted(df[df['Make'] == selected_make]['Model'].dropna().unique().tolist())
return gr.Dropdown(choices=models, label="Model", interactive=True, value=None if not models else models[0])
# Function to dynamically update trim options
def update_trims(selected_make, selected_model):
if pd.isna(selected_make) or not selected_make or pd.isna(selected_model) or not selected_model:
return gr.Dropdown(choices=[], label="Trim", interactive=True, value=None)
trims = sorted(df[(df['Make'] == selected_make) & (df['Model'] == selected_model)]['Trim'].dropna().unique().tolist())
return gr.Dropdown(choices=trims, label="Trim", interactive=True, value=None if not trims else trims[0])
# Function to dynamically update car type options
def update_types(selected_make, selected_model, selected_trim):
if pd.isna(selected_make) or not selected_make or \
pd.isna(selected_model) or not selected_model or \
pd.isna(selected_trim) or not selected_trim:
return gr.Dropdown(choices=[], label="Car Type", interactive=True, value=None)
types = sorted(df[(df['Make'] == selected_make) &
(df['Model'] == selected_model) &
(df['Trim'] == selected_trim)]['Type'].dropna().unique().tolist())
return gr.Dropdown(choices=types, label="Car Type", interactive=True, value=None if not types else types[0])
# Gradio Interface
with gr.Blocks(theme=gr.themes.Monochrome(), title="Car Price Predictor") as demo:
gr.Markdown("""
# 🚗 **Luxurious Car Price Predictor**
### *Predict the market value of your dream car with advanced AI!*
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## 📋 Car Specifications")
make_dd = gr.Dropdown(choices=make_options, label="Make", interactive=True, info="Select the car's manufacturer.")
model_dd = gr.Dropdown(choices=[], label="Model", interactive=True, info="Choose the specific model.")
trim_dd = gr.Dropdown(choices=[], label="Trim", interactive=True, info="Specify the car's trim level.")
type_dd = gr.Dropdown(choices=[], label="Car Type", interactive=True, info="What type of car is it (e.g., Sedan, SUV)?")
with gr.Column(scale=1):
gr.Markdown("## ⚙️ Performance & Features")
mileage_num = gr.Slider(label="Mileage (km)", minimum=0, maximum=600000, step=1000, value=50000, info="Enter the total kilometers driven.")
cylinder_dd = gr.Dropdown(choices=cylinder_options, label="Cylinders", interactive=True, info="Number of engine cylinders.")
liter_num = gr.Slider(label="Engine Volume (Liters)", minimum=0.8, maximum=8.0, step=0.1, value=2.0, info="Engine displacement in liters.")
doors_dd = gr.Dropdown(choices=doors_options, label="Number of Doors", interactive=True, info="How many doors does the car have?")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## ✨ Comfort & Technology")
cruise_rb = gr.Radio(choices=[True, False], label="Cruise Control", value=True, type="value", info="Does the car have cruise control?")
sound_rb = gr.Radio(choices=[True, False], label="Premium Sound System", value=True, type="value", info="Is there an upgraded sound system?")
leather_rb = gr.Radio(choices=[True, False], label="Leather Seats", value=False, type="value", info="Are the seats upholstered in leather?")
with gr.Row():
predict_button = gr.Button("💰 **Get Estimated Price** 💰", size="lg", variant="primary")
with gr.Row():
output_text = gr.Textbox(label="Prediction Result", interactive=False, show_copy_button=True)
# Event listeners for dynamic dropdown updates
make_dd.change(fn=update_models, inputs=make_dd, outputs=model_dd)
make_dd.change(fn=lambda: (gr.Dropdown(choices=[], value=None), gr.Dropdown(choices=[], value=None)), outputs=[trim_dd, type_dd])
model_dd.change(fn=update_trims, inputs=[make_dd, model_dd], outputs=trim_dd)
model_dd.change(fn=lambda: gr.Dropdown(choices=[], value=None), outputs=type_dd)
trim_dd.change(fn=update_types, inputs=[make_dd, model_dd, trim_dd], outputs=type_dd)
predict_button.click(
fn=predict_price,
inputs=[make_dd, model_dd, trim_dd, mileage_num, type_dd, cylinder_dd, liter_num, doors_dd, cruise_rb, sound_rb, leather_rb],
outputs=output_text
)
gr.Markdown("---")
gr.Markdown("""
### 💡 **Usage Notes:**
* Please fill in all fields accurately for the best prediction.
* **Make** selection updates **Model** options.
* **Model** selection updates **Trim** options.
* **Make**, **Model**, and **Trim** selections update **Car Type** options.
* For 'Cruise Control', 'Premium Sound System', and 'Leather Seats', select 'True' (Yes) or 'False' (No).
* This predictor uses an AI model trained on specific car data. Predictions are estimates and may vary from actual market prices.
""")
gr.Markdown("---")
gr.Markdown("<p style='text-align: center;'>Developed with ❤️ by @drmurataltun</p>")
if __name__ == '__main__':
if pipe is None or df.empty:
print("Gradio interface cannot be launched because the model or data could not be loaded.")
print("Please check the existence and integrity of 'car_price_model.pkl' and 'cars.xls' files.")
else:
demo.launch()