import gradio as gr
import pandas as pd
import joblib
from gradio.themes.base import Base
import numpy as np
import matplotlib.pyplot as plt
# --- Step 1: Load the Pre-Trained Model and Scaler ---
model = joblib.load('lgbm_model.pkl')
scaler = joblib.load('scaler.pkl')
# --- Step 2: Create a Prediction Function ---
# The function now returns both the plot data and a color-coded status message with percentages.
def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear, product_type):
# Convert the product_type ('L', 'M', 'H') into the one-hot encoded format.
type_l_val = 1 if product_type == 'L' else 0
type_m_val = 1 if product_type == 'M' else 0
input_data = {
'Air temperature [K]': air_temp,
'Process temperature [K]': process_temp,
'Rotational speed [rpm]': rotational_speed,
'Torque [Nm]': torque,
'Tool wear [min]': tool_wear,
'Type_L': type_l_val,
'Type_M': type_m_val
}
input_df = pd.DataFrame([input_data])
# --- Feature Engineering ---
input_df['TempDiff_K'] = input_df['Process temperature [K]'] - input_df['Air temperature [K]']
input_df['Power_W'] = input_df['Torque [Nm]'] * input_df['Rotational speed [rpm]'] * (2 * 3.14159 / 60)
input_df['ToolWear_Torque'] = input_df['Tool wear [min]'] * input_df['Torque [Nm]']
# --- Scaling ---
final_cols = scaler.get_feature_names_out()
input_df_reordered = input_df[final_cols]
input_scaled = scaler.transform(input_df_reordered)
# --- Prediction ---
prediction_proba = model.predict_proba(input_scaled)
failure_probability = prediction_proba[0][1]
no_failure_probability = 1 - failure_probability
# --- Prepare Outputs ---
# Data for the Bar Plot
plot_data = pd.DataFrame({
'Category': ['Failure', 'No Failure'],
'Probability': [failure_probability, no_failure_probability],
'Percentage': [f"{failure_probability:.1%}", f"{no_failure_probability:.1%}"]
})
# Color-coded status message based on risk, now with percentage
failure_percent = failure_probability * 100
if failure_probability > 0.5:
status_text = f"
Status: High Risk of Failure ({failure_percent:.1f}%)
"
elif failure_probability > 0.2:
status_text = f"Status: Caution - Maintenance Recommended ({failure_percent:.1f}%)
"
else:
status_text = f"Status: Normal Operation ({failure_percent:.1f}%)
"
return plot_data, status_text
# --- Step 3: Define Custom Theme and CSS for a more professional look ---
theme = Base(
primary_hue="sky",
secondary_hue="blue",
font=gr.themes.GoogleFont("Inter"),
).set(
body_background_fill="#f0f4f9",
block_background_fill="white",
block_border_width="1px",
block_shadow="*shadow_drop_lg",
block_radius="*radius_xl",
button_primary_background_fill="*primary_500",
button_primary_background_fill_hover="*primary_600",
button_secondary_background_fill="*neutral_200",
button_secondary_background_fill_hover="*neutral_300",
)
custom_css = """
.gradio-container { max-width: 90% !important; margin: auto; }
#main_title { text-align: center; font-size: 2.5em; color: #1e3a8a; font-weight: 600; padding-top: 20px; }
#input_header, #output_header { text-align: center; color: #374151; font-weight: 500; }
"""
# --- Step 4: Define a Reset Function ---
def reset_all():
# Returns default values for all inputs and clears outputs
return 298.1, 308.6, 1551, 42.8, 10, 'M', None, ""
# --- Step 5: Build the Interface with gr.Blocks ---
with gr.Blocks(theme=theme, css=custom_css) as demo:
gr.Markdown("Advanced Predictive Maintenance Dashboard
", elem_id="main_title")
with gr.Row(variant='panel'):
with gr.Column(scale=2):
gr.Markdown("", elem_id="input_header")
air_temp = gr.Slider(295, 305, step=0.1, value=298.1, label="Air temperature [K]")
process_temp = gr.Slider(305, 315, step=0.1, value=308.6, label="Process temperature [K]")
rotational_speed = gr.Slider(1100, 2900, step=1, value=1551, label="Rotational speed [rpm]")
torque = gr.Slider(3, 80, step=0.1, value=42.8, label="Torque [Nm]")
tool_wear = gr.Slider(0, 260, step=1, value=10, label="Tool wear [min]")
product_type = gr.Radio(['L', 'M', 'H'], value='M', label="Product Quality Type", info="L: Low, M: Medium, H: High")
with gr.Row():
reset_btn = gr.Button("Clear / Reset")
submit_btn = gr.Button("Predict Failure", variant="primary")
with gr.Column(scale=1):
gr.Markdown("", elem_id="output_header")
status_display = gr.Markdown(label="System Status")
output_plot = gr.BarPlot(
x="Category", y="Probability", y_lim=[0, 1], color="Category",
vertical=False, title="Prediction Confidence", tooltip=['Category', 'Percentage']
)
gr.Examples(
examples=[
[298.1, 308.6, 1551, 42.8, 0, 'M'],
[303.4, 312.8, 1333, 65.7, 191, 'L'],
[301.7, 310.9, 1439, 49.1, 20, 'H'],
[302.3, 311.5, 1422, 41.5, 108, 'M']
],
inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
outputs=[output_plot, status_display],
fn=predict_failure,
cache_examples=True
)
with gr.Accordion("About the Model & App", open=False):
gr.Markdown("""
### 🤖 About the Model
This interface uses a **LightGBM (Light Gradient Boosting Machine)** model to predict machine failure based on real-time sensor data. The model was trained on the "AI4I 2020 Predictive Maintenance Dataset" from UCI.
### 📈 Key Features
The model's prediction relies on several engineered features, including temperature differences, calculated power consumption, and the interaction between tool wear and torque.
### 💻 About the App
This Gradio application provides an interactive dashboard to explore the model's predictions. It is designed to be responsive and easy to use across different devices.
""")
# Define button actions
submit_btn.click(
fn=predict_failure,
inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
outputs=[output_plot, status_display]
)
reset_btn.click(
fn=reset_all,
inputs=None,
outputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type, output_plot, status_display]
)
# --- Step 6: Launch the Demo ---
demo.launch()