Aditya Das Gupta commited on
Commit
8df3106
·
verified ·
1 Parent(s): 522da5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -40
app.py CHANGED
@@ -8,14 +8,12 @@ model = joblib.load('lgbm_model.pkl')
8
  scaler = joblib.load('scaler.pkl')
9
 
10
  # --- Step 2: Create a Prediction Function ---
11
- # The function now accepts a single 'product_type' argument.
12
  def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear, product_type):
13
- # Convert the product_type ('L', 'M', 'H') into the one-hot encoded
14
- # format that the model was trained on. 'H' is the baseline.
15
  type_l_val = 1 if product_type == 'L' else 0
16
  type_m_val = 1 if product_type == 'M' else 0
17
 
18
- # Create a dictionary from the inputs
19
  input_data = {
20
  'Air temperature [K]': air_temp,
21
  'Process temperature [K]': process_temp,
@@ -25,16 +23,14 @@ def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear,
25
  'Type_L': type_l_val,
26
  'Type_M': type_m_val
27
  }
28
-
29
- # Create a DataFrame from the dictionary
30
  input_df = pd.DataFrame([input_data])
31
 
32
- # --- Feature Engineering (must be identical to training) ---
33
  input_df['TempDiff_K'] = input_df['Process temperature [K]'] - input_df['Air temperature [K]']
34
  input_df['Power_W'] = input_df['Torque [Nm]'] * input_df['Rotational speed [rpm]'] * (2 * 3.14159 / 60)
35
  input_df['ToolWear_Torque'] = input_df['Tool wear [min]'] * input_df['Torque [Nm]']
36
 
37
- # --- Scaling (using the loaded scaler) ---
38
  final_cols = scaler.get_feature_names_out()
39
  input_df_reordered = input_df[final_cols]
40
  input_scaled = scaler.transform(input_df_reordered)
@@ -44,18 +40,27 @@ def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear,
44
  failure_probability = prediction_proba[0][1]
45
  no_failure_probability = 1 - failure_probability
46
 
47
- # Prepare data for the BarPlot
 
48
  plot_data = pd.DataFrame({
49
  'Category': ['Failure', 'No Failure'],
50
  'Probability': [failure_probability, no_failure_probability]
51
  })
52
 
53
- return plot_data
 
 
 
 
 
 
 
 
54
 
55
- # --- Step 3: Define Custom Theme and CSS ---
56
  theme = Base(
57
- primary_hue="blue",
58
- secondary_hue="sky",
59
  font=gr.themes.GoogleFont("Inter"),
60
  ).set(
61
  body_background_fill="#f0f4f9",
@@ -63,17 +68,24 @@ theme = Base(
63
  block_border_width="1px",
64
  block_shadow="*shadow_drop_lg",
65
  block_radius="*radius_xl",
66
- button_primary_background_fill="*primary_600",
67
- button_primary_background_fill_hover="*primary_700",
 
 
68
  )
69
 
70
  custom_css = """
71
  .gradio-container { max-width: 90% !important; margin: auto; }
72
- #main_title { text-align: center; font-size: 2.5em; color: #1e3a8a; font-weight: 600; }
73
- #input_header, #output_header { text-align: center; color: #374151; }
74
  """
75
 
76
- # --- Step 4: Build the Interface with gr.Blocks for a Compact Layout ---
 
 
 
 
 
77
  with gr.Blocks(theme=theme, css=custom_css) as demo:
78
  gr.Markdown("<h1 id='main_title'>Advanced Predictive Maintenance Dashboard</h1>", elem_id="main_title")
79
 
@@ -85,30 +97,20 @@ with gr.Blocks(theme=theme, css=custom_css) as demo:
85
  rotational_speed = gr.Slider(1100, 2900, step=1, value=1551, label="Rotational speed [rpm]")
86
  torque = gr.Slider(3, 80, step=0.1, value=42.8, label="Torque [Nm]")
87
  tool_wear = gr.Slider(0, 260, step=1, value=10, label="Tool wear [min]")
88
-
89
- # Replaced checkboxes with a more intuitive Radio group
90
- product_type = gr.Radio(
91
- ['L', 'M', 'H'],
92
- value='M',
93
- label="Product Quality Type",
94
- info="L: Low, M: Medium, H: High"
95
- )
96
 
97
- submit_btn = gr.Button("Predict Failure", variant="primary")
 
 
98
 
99
  with gr.Column(scale=1):
100
  gr.Markdown("<h2 id='output_header'>📊 Prediction Results</h2>", elem_id="output_header")
 
101
  output_plot = gr.BarPlot(
102
- x="Category",
103
- y="Probability",
104
- y_lim=[0, 1],
105
- color="Category",
106
- vertical=False,
107
- title="Prediction Confidence",
108
- tooltip=['Category', 'Probability']
109
  )
110
 
111
- # Updated examples to include the new product_type input
112
  gr.Examples(
113
  examples=[
114
  [298.1, 308.6, 1551, 42.8, 0, 'M'],
@@ -117,7 +119,7 @@ with gr.Blocks(theme=theme, css=custom_css) as demo:
117
  [302.3, 311.5, 1422, 41.5, 108, 'M']
118
  ],
119
  inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
120
- outputs=output_plot,
121
  fn=predict_failure,
122
  cache_examples=True
123
  )
@@ -131,13 +133,18 @@ with gr.Blocks(theme=theme, css=custom_css) as demo:
131
  ### 💻 About the App
132
  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.
133
  """)
134
-
135
- # Updated the click function to pass the new product_type input
136
  submit_btn.click(
137
  fn=predict_failure,
138
  inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
139
- outputs=output_plot
 
 
 
 
 
140
  )
141
 
142
- # --- Step 5: Launch the Demo ---
143
  demo.launch()
 
8
  scaler = joblib.load('scaler.pkl')
9
 
10
  # --- Step 2: Create a Prediction Function ---
11
+ # The function now returns both the plot data and a color-coded status message.
12
  def predict_failure(air_temp, process_temp, rotational_speed, torque, tool_wear, product_type):
13
+ # Convert the product_type ('L', 'M', 'H') into the one-hot encoded format.
 
14
  type_l_val = 1 if product_type == 'L' else 0
15
  type_m_val = 1 if product_type == 'M' else 0
16
 
 
17
  input_data = {
18
  'Air temperature [K]': air_temp,
19
  'Process temperature [K]': process_temp,
 
23
  'Type_L': type_l_val,
24
  'Type_M': type_m_val
25
  }
 
 
26
  input_df = pd.DataFrame([input_data])
27
 
28
+ # --- Feature Engineering ---
29
  input_df['TempDiff_K'] = input_df['Process temperature [K]'] - input_df['Air temperature [K]']
30
  input_df['Power_W'] = input_df['Torque [Nm]'] * input_df['Rotational speed [rpm]'] * (2 * 3.14159 / 60)
31
  input_df['ToolWear_Torque'] = input_df['Tool wear [min]'] * input_df['Torque [Nm]']
32
 
33
+ # --- Scaling ---
34
  final_cols = scaler.get_feature_names_out()
35
  input_df_reordered = input_df[final_cols]
36
  input_scaled = scaler.transform(input_df_reordered)
 
40
  failure_probability = prediction_proba[0][1]
41
  no_failure_probability = 1 - failure_probability
42
 
43
+ # --- Prepare Outputs ---
44
+ # Data for the Bar Plot
45
  plot_data = pd.DataFrame({
46
  'Category': ['Failure', 'No Failure'],
47
  'Probability': [failure_probability, no_failure_probability]
48
  })
49
 
50
+ # Color-coded status message based on risk
51
+ if failure_probability > 0.5:
52
+ status_text = "<h3 style='color: #ef4444; text-align: center;'>Status: High Risk of Failure</h3>"
53
+ elif failure_probability > 0.2:
54
+ status_text = "<h3 style='color: #f59e0b; text-align: center;'>Status: Caution - Maintenance Recommended</h3>"
55
+ else:
56
+ status_text = "<h3 style='color: #22c55e; text-align: center;'>Status: Normal Operation</h3>"
57
+
58
+ return plot_data, status_text
59
 
60
+ # --- Step 3: Define Custom Theme and CSS for a more professional look ---
61
  theme = Base(
62
+ primary_hue="sky",
63
+ secondary_hue="blue",
64
  font=gr.themes.GoogleFont("Inter"),
65
  ).set(
66
  body_background_fill="#f0f4f9",
 
68
  block_border_width="1px",
69
  block_shadow="*shadow_drop_lg",
70
  block_radius="*radius_xl",
71
+ button_primary_background_fill="*primary_500",
72
+ button_primary_background_fill_hover="*primary_600",
73
+ button_secondary_background_fill="*neutral_200",
74
+ button_secondary_background_fill_hover="*neutral_300",
75
  )
76
 
77
  custom_css = """
78
  .gradio-container { max-width: 90% !important; margin: auto; }
79
+ #main_title { text-align: center; font-size: 2.5em; color: #1e3a8a; font-weight: 600; padding-top: 20px; }
80
+ #input_header, #output_header { text-align: center; color: #374151; font-weight: 500; }
81
  """
82
 
83
+ # --- Step 4: Define a Reset Function ---
84
+ def reset_all():
85
+ # Returns default values for all inputs and clears outputs
86
+ return 298.1, 308.6, 1551, 42.8, 10, 'M', None, ""
87
+
88
+ # --- Step 5: Build the Interface with gr.Blocks ---
89
  with gr.Blocks(theme=theme, css=custom_css) as demo:
90
  gr.Markdown("<h1 id='main_title'>Advanced Predictive Maintenance Dashboard</h1>", elem_id="main_title")
91
 
 
97
  rotational_speed = gr.Slider(1100, 2900, step=1, value=1551, label="Rotational speed [rpm]")
98
  torque = gr.Slider(3, 80, step=0.1, value=42.8, label="Torque [Nm]")
99
  tool_wear = gr.Slider(0, 260, step=1, value=10, label="Tool wear [min]")
100
+ product_type = gr.Radio(['L', 'M', 'H'], value='M', label="Product Quality Type", info="L: Low, M: Medium, H: High")
 
 
 
 
 
 
 
101
 
102
+ with gr.Row():
103
+ reset_btn = gr.Button("Clear / Reset")
104
+ submit_btn = gr.Button("Predict Failure", variant="primary")
105
 
106
  with gr.Column(scale=1):
107
  gr.Markdown("<h2 id='output_header'>📊 Prediction Results</h2>", elem_id="output_header")
108
+ status_display = gr.Markdown(label="System Status")
109
  output_plot = gr.BarPlot(
110
+ x="Category", y="Probability", y_lim=[0, 1], color="Category",
111
+ vertical=False, title="Prediction Confidence", tooltip=['Category', 'Probability']
 
 
 
 
 
112
  )
113
 
 
114
  gr.Examples(
115
  examples=[
116
  [298.1, 308.6, 1551, 42.8, 0, 'M'],
 
119
  [302.3, 311.5, 1422, 41.5, 108, 'M']
120
  ],
121
  inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
122
+ outputs=[output_plot, status_display],
123
  fn=predict_failure,
124
  cache_examples=True
125
  )
 
133
  ### 💻 About the App
134
  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.
135
  """)
136
+
137
+ # Define button actions
138
  submit_btn.click(
139
  fn=predict_failure,
140
  inputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type],
141
+ outputs=[output_plot, status_display]
142
+ )
143
+ reset_btn.click(
144
+ fn=reset_all,
145
+ inputs=None,
146
+ outputs=[air_temp, process_temp, rotational_speed, torque, tool_wear, product_type, output_plot, status_display]
147
  )
148
 
149
+ # --- Step 6: Launch the Demo ---
150
  demo.launch()