Aditya Das Gupta commited on
Commit
1434fea
·
verified ·
1 Parent(s): 657fef2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -65
app.py CHANGED
@@ -1,17 +1,15 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import joblib
4
- import gradio.themes as gr_themes # Import the themes module
5
 
6
  # --- Step 1: Load the Pre-Trained Model and Scaler ---
7
- # These files must be in the same repository on Hugging Face Spaces.
8
  model = joblib.load('lgbm_model.pkl')
9
  scaler = joblib.load('scaler.pkl')
10
 
11
  # --- Step 2: Create a Prediction Function ---
12
- # This function is unchanged.
13
  def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear, type_l, type_m):
14
-
15
  # Create a dictionary from the inputs
16
  input_data = {
17
  'Air temperature [K]': air_temp,
@@ -39,75 +37,102 @@ def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear,
39
  # --- Prediction ---
40
  prediction_proba = model.predict_proba(input_scaled)
41
  failure_probability = prediction_proba[0][1]
 
42
 
43
- # Return the probability in a nice format
44
- return {
45
- "No Failure Probability": 1 - failure_probability,
46
- "Failure Probability": failure_probability
47
- }
48
-
49
 
50
- # --- Step 3: Define the Interface Components ---
51
- # We can add default values to guide the user.
52
- inputs = [
53
- gr.Slider(295, 305, step=0.1, value=298.1, label="Air temperature [K]"),
54
- gr.Slider(305, 315, step=0.1, value=308.6, label="Process temperature [K]"),
55
- gr.Slider(1100, 2900, step=1, value=1551, label="Rotational speed [rpm]"),
56
- gr.Slider(3, 80, step=0.1, value=42.8, label="Torque [Nm]"),
57
- gr.Slider(0, 260, step=1, value=10, label="Tool wear [min]"),
58
- gr.Checkbox(label="Type L (Low quality variant)"),
59
- gr.Checkbox(label="Type M (Medium quality variant)", value=True)
60
- ]
61
-
62
- outputs = gr.Label(num_top_classes=2, label="Prediction Confidence")
63
-
64
- # --- Step 4: Add Examples for Users ---
65
- # This makes the app much more user-friendly and professional.
66
- examples = [
67
- [298.1, 308.6, 1551, 42.8, 0, False, True],
68
- [303.4, 312.8, 1333, 65.7, 191, True, False],
69
- [302.3, 311.5, 1422, 41.5, 108, False, True]
70
- ]
71
-
72
- # --- Step 5: Add an Article/Explanation ---
73
- # This section provides context and adds a professional touch.
74
- article = """
75
- <div style='text-align: center; font-family: "Garamond", serif;'>
76
- <h2>About the Model</h2>
77
- <p>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.</p>
78
- <p>The key features used for prediction include temperature differences, power consumption (calculated from torque and speed), and the interaction between tool wear and torque.</p>
79
- </div>
80
- """
81
 
82
- # --- Step 6: Define a Custom Theme and CSS ---
83
- # Here's where the magic happens!
84
- theme = gr_themes.Soft(
85
  primary_hue="blue",
86
  secondary_hue="sky",
 
87
  ).set(
88
- body_background_fill='linear-gradient(to right, #f0f8ff, #d6eaff)',
 
 
 
 
 
 
89
  )
90
 
91
  custom_css = """
92
- .gradio-container .title {
93
- font-size: 2.5em !important;
94
- font-family: 'Garamond', serif !important;
95
- color: #1e3a8a !important;
96
- text-shadow: 2px 2px 4px #ccc;
97
- }
98
  """
99
 
100
- # --- Step 7: Launch the Interface with the New Look ---
101
- interface = gr.Interface(
102
- fn=predict_failure,
103
- inputs=inputs,
104
- outputs=outputs,
105
- examples=examples,
106
- article=article,
107
- theme=theme,
108
- css=custom_css,
109
- title="Advanced Predictive Maintenance Dashboard",
110
- description="Enter the machine's sensor readings to predict the probability of failure. Based on a LightGBM model trained on the AI4I 2020 dataset."
111
- )
112
-
113
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import joblib
4
+ from gradio.themes.base import Base
5
 
6
  # --- Step 1: Load the Pre-Trained Model and Scaler ---
 
7
  model = joblib.load('lgbm_model.pkl')
8
  scaler = joblib.load('scaler.pkl')
9
 
10
  # --- Step 2: Create a Prediction Function ---
11
+ # This function is updated to return data formatted for the new BarPlot component.
12
  def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear, type_l, type_m):
 
13
  # Create a dictionary from the inputs
14
  input_data = {
15
  'Air temperature [K]': air_temp,
 
37
  # --- Prediction ---
38
  prediction_proba = model.predict_proba(input_scaled)
39
  failure_probability = prediction_proba[0][1]
40
+ no_failure_probability = 1 - failure_probability
41
 
42
+ # Prepare data for the BarPlot
43
+ plot_data = pd.DataFrame({
44
+ 'Category': ['Failure', 'No Failure'],
45
+ 'Probability': [failure_probability, no_failure_probability]
46
+ })
 
47
 
48
+ return plot_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # --- Step 3: Define Custom Theme and CSS ---
51
+ # A clean, professional theme with custom CSS for a polished look.
52
+ theme = Base(
53
  primary_hue="blue",
54
  secondary_hue="sky",
55
+ font=gr.themes.GoogleFont("Inter"),
56
  ).set(
57
+ body_background_fill="#f0f4f9",
58
+ block_background_fill="white",
59
+ block_border_width="1px",
60
+ block_shadow="*shadow_drop_lg",
61
+ block_radius="*radius_xl",
62
+ button_primary_background_fill="*primary_600",
63
+ button_primary_background_fill_hover="*primary_700",
64
  )
65
 
66
  custom_css = """
67
+ .gradio-container { max-width: 90% !important; margin: auto; }
68
+ #main_title { text-align: center; font-size: 2.5em; color: #1e3a8a; font-weight: 600; }
69
+ #input_header, #output_header { text-align: center; color: #374151; }
 
 
 
70
  """
71
 
72
+ # --- Step 4: Build the Interface with gr.Blocks for a Compact Layout ---
73
+ with gr.Blocks(theme=theme, css=custom_css) as demo:
74
+ gr.Markdown("<h1 id='main_title'>Advanced Predictive Maintenance Dashboard</h1>", elem_id="main_title")
75
+
76
+ # Main layout with two responsive columns
77
+ with gr.Row(variant='panel'):
78
+ # Left column for all input controls
79
+ with gr.Column(scale=2):
80
+ gr.Markdown("<h2 id='input_header'>��️ Input Parameters</h2>", elem_id="input_header")
81
+ air_temp = gr.Slider(295, 305, step=0.1, value=298.1, label="Air temperature [K]")
82
+ process_temp = gr.Slider(305, 315, step=0.1, value=308.6, label="Process temperature [K]")
83
+ rotational_speed = gr.Slider(1100, 2900, step=1, value=1551, label="Rotational speed [rpm]")
84
+ torque = gr.Slider(3, 80, step=0.1, value=42.8, label="Torque [Nm]")
85
+ tool_wear = gr.Slider(0, 260, step=1, value=10, label="Tool wear [min]")
86
+
87
+ with gr.Row():
88
+ type_l = gr.Checkbox(label="Type L (Low quality)")
89
+ type_m = gr.Checkbox(label="Type M (Medium quality)", value=True)
90
+
91
+ submit_btn = gr.Button("Predict Failure", variant="primary")
92
+
93
+ # Right column for the prediction output
94
+ with gr.Column(scale=1):
95
+ gr.Markdown("<h2 id='output_header'>📊 Prediction Results</h2>", elem_id="output_header")
96
+ output_plot = gr.BarPlot(
97
+ x="Category",
98
+ y="Probability",
99
+ y_lim=[0, 1],
100
+ color="Category",
101
+ vertical=False,
102
+ title="Prediction Confidence",
103
+ tooltip=['Category', 'Probability']
104
+ )
105
+
106
+ # Examples section to guide the user
107
+ gr.Examples(
108
+ examples=[
109
+ [298.1, 308.6, 1551, 42.8, 0, False, True],
110
+ [303.4, 312.8, 1333, 65.7, 191, True, False],
111
+ [302.3, 311.5, 1422, 41.5, 108, False, True]
112
+ ],
113
+ inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, type_l, type_m],
114
+ outputs=output_plot,
115
+ fn=predict_failure,
116
+ cache_examples=True
117
+ )
118
+
119
+ # Accordion for the "About" section to keep the interface clean
120
+ with gr.Accordion("About the Model & App", open=False):
121
+ gr.Markdown("""
122
+ ### 🤖 About the Model
123
+ 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.
124
+ ### 📈 Key Features
125
+ The model's prediction relies on several engineered features, including temperature differences, calculated power consumption, and the interaction between tool wear and torque.
126
+ ### 💻 About the App
127
+ 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.
128
+ """)
129
+
130
+ # Link the submit button to the prediction function
131
+ submit_btn.click(
132
+ fn=predict_failure,
133
+ inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, type_l, type_m],
134
+ outputs=output_plot
135
+ )
136
+
137
+ # --- Step 5: Launch the Demo ---
138
+ demo.launch()