Aaron006/fuel_efficiency
0
1import gradio as gr2import pandas as pd3import xgboost as xgb4import os5 6os.environ["MPLCONFIGDIR"] = "/tmp" # Fix for fontconfig error7 8# Load XGBoost booster from JSON9booster = xgb.Booster()10booster.load_model("xgb_model.json")11 12# Define options13makes = ['FORD', 'TOYOTA', 'HONDA', 'BMW', 'AUDI']14transmissions = ['Automatic', 'Manual', 'CVT', 'Auto-Manual', 'Direct Drive']15fuels = ['Regular Gasoline', 'Premium Gasoline', 'Diesel', 'Electricity', 'E85', 'CNG']16classes = ['SUV', 'Compact Cars', 'Mid-size Cars', 'Large Cars', 'Pickup Trucks', 'Station Wagons']17 18# Preprocess input into DMatrix19def preprocess_input(year, cylinders, displ, make, trany, fuel, vclass):20 df = pd.DataFrame([{21 "year": year,22 "cylinders": cylinders,23 "displ": displ,24 "make": make,25 "trany": trany,26 "fuelType": fuel,27 "VClass": vclass28 }])29 return xgb.DMatrix(df)30 31# Predict MPG32def predict_mpg(year, cylinders, displ, make, trany, fuel, vclass):33 input_dmatrix = preprocess_input(year, cylinders, displ, make, trany, fuel, vclass)34 prediction = booster.predict(input_dmatrix)[0]35 return f"๐ Predicted Combined MPG: {prediction:.2f} MPG"36 37# Gradio UI38with gr.Blocks() as demo:39 gr.Markdown("## ๐ Vehicle MPG Predictor")40 gr.Markdown("Enter vehicle details to predict Combined MPG")41 with gr.Row():42 with gr.Column():43 year = gr.Slider(2000, 2025, value=2020, step=1, label="Year")44 cylinders = gr.Slider(2, 16, value=4, step=1, label="Cylinders")45 displ = gr.Slider(1.0, 8.0, value=2.0, step=0.1, label="Engine Displacement (L)")46 with gr.Column():47 make = gr.Dropdown(makes, label="Make")48 trany = gr.Dropdown(transmissions, label="Transmission")49 fuel = gr.Dropdown(fuels, label="Fuel Type")50 vclass = gr.Dropdown(classes, label="Vehicle Class")51 result = gr.Textbox(label="Prediction Result")52 predict_btn = gr.Button("๐ Predict MPG")53 predict_btn.click(fn=predict_mpg, inputs=[year, cylinders, displ, make, trany, fuel, vclass], outputs=result)54 55demo.launch()