File size: 6,946 Bytes
098c97f
 
 
1434fea
5c4cb43
b559fa9
098c97f
 
 
 
 
 
b559fa9
522da5b
8df3106
522da5b
 
 
098c97f
 
 
 
 
 
522da5b
 
098c97f
 
 
8df3106
098c97f
 
 
 
8df3106
098c97f
 
 
 
 
 
 
1434fea
098c97f
8df3106
 
1434fea
 
8fa7f88
 
1434fea
657fef2
8fa7f88
 
8df3106
8fa7f88
8df3106
8fa7f88
8df3106
8fa7f88
8df3106
b559fa9
657fef2
8df3106
1434fea
8df3106
 
1434fea
657fef2
1434fea
 
 
 
 
8df3106
 
 
 
657fef2
 
 
1434fea
8df3106
 
657fef2
098c97f
8df3106
 
 
b559fa9
8df3106
 
1434fea
 
 
 
 
 
 
 
 
 
 
8df3106
1434fea
8df3106
 
 
1434fea
 
 
8df3106
1434fea
8df3106
8fa7f88
1434fea
 
 
 
522da5b
 
 
 
1434fea
522da5b
b559fa9
1434fea
 
 
 
 
 
 
 
 
 
 
 
 
8df3106
 
1434fea
 
522da5b
b559fa9
8df3106
 
 
 
b559fa9
1434fea
 
8df3106
522da5b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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"<h3 style='color: #ef4444; text-align: center;'>Status: High Risk of Failure ({failure_percent:.1f}%)</h3>"
    elif failure_probability > 0.2:
        status_text = f"<h3 style='color: #f59e0b; text-align: center;'>Status: Caution - Maintenance Recommended ({failure_percent:.1f}%)</h3>"
    else:
        status_text = f"<h3 style='color: #22c55e; text-align: center;'>Status: Normal Operation ({failure_percent:.1f}%)</h3>"

    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("<h1 id='main_title'>Advanced Predictive Maintenance Dashboard</h1>", elem_id="main_title")

    with gr.Row(variant='panel'):
        with gr.Column(scale=2):
            gr.Markdown("<h2 id='input_header'>⚙️ Input Parameters</h2>", 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("<h2 id='output_header'>📊 Prediction Results</h2>", 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()