Aditya Das Gupta commited on
Commit
7f288fa
·
verified ·
1 Parent(s): 210f365

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import joblib
4
+ import gradio as gr
5
+ from sklearn.multiclass import OneVsRestClassifier
6
+ from xgboost import XGBClassifier
7
+ import traceback
8
+
9
+ # ==============================================================================
10
+ # --- Main Application Logic ---
11
+ # ==============================================================================
12
+
13
+ # --- 1. Load the trained model ---
14
+ # The model file will be in the same directory on Hugging Face Spaces
15
+ try:
16
+ loaded_model = joblib.load('champion_model.pkl')
17
+ print("Model loaded successfully.")
18
+ except FileNotFoundError:
19
+ # This provides a clear error message if the model file is missing
20
+ print("Error: 'champion_model.pkl' not found. Please upload the model file to your Hugging Face Space.")
21
+ loaded_model = None
22
+
23
+ # --- 2. Define the prediction function ---
24
+ def predict_failure(type_L_M_H, air_temp, process_temp, rotational_speed, torque, tool_wear):
25
+ """
26
+ Predicts machine failure probabilities using the loaded model.
27
+ """
28
+ if loaded_model is None:
29
+ return pd.DataFrame(), "ERROR: Model is not loaded. Check logs."
30
+
31
+ try:
32
+ type_mapping = {'L (Low)': 0, 'M (Medium)': 1, 'H (High)': 2}
33
+ type_numeric = int(type_mapping.get(type_L_M_H, 0))
34
+
35
+ input_data = pd.DataFrame({
36
+ 'type': [type_numeric],
37
+ 'airtemperaturek': [float(air_temp)],
38
+ 'processtemperaturek': [float(process_temp)],
39
+ 'rotationalspeedrpm': [int(rotational_speed)],
40
+ 'torquenm': [float(torque)],
41
+ 'toolwearmin': [int(tool_wear)]
42
+ })
43
+
44
+ labels = ['Normal', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']
45
+ output_dict = {}
46
+
47
+ for i, label in enumerate(labels):
48
+ estimator = loaded_model.estimators_[i]
49
+ prob_for_label = estimator.predict_proba(input_data)
50
+ output_dict[label] = round(prob_for_label[0, 1], 4)
51
+
52
+ barplot_df = pd.DataFrame(list(output_dict.items()), columns=['Failure Mode', 'Probability'])
53
+
54
+ failure_probs = {k: v for k, v in output_dict.items() if k != 'Normal'}
55
+ if not failure_probs or max(failure_probs.values()) < 0.1:
56
+ highest_failure = "None (Machine is likely Normal)"
57
+ interpretation = f"✅ Status: {highest_failure}"
58
+ else:
59
+ highest_failure = max(failure_probs, key=failure_probs.get)
60
+ interpretation = f"⚠️ Highest Predicted Failure Mode: {highest_failure}"
61
+
62
+ return barplot_df, interpretation
63
+
64
+ except Exception as e:
65
+ error_message = f"An error occurred: {str(e)}"
66
+ traceback.print_exc()
67
+ empty_df = pd.DataFrame({'Failure Mode': [], 'Probability': []})
68
+ return empty_df, error_message
69
+
70
+ # --- 3. Create the Gradio interface ---
71
+ css = """
72
+ #title { text-align: center; font-family: 'Garamond', serif; font-size: 3em; color: #4A90E2; padding-bottom: 10px; }
73
+ """
74
+
75
+ with gr.Blocks(theme=gr.themes.Glass(), css=css) as demo:
76
+ gr.Markdown("Advanced Machine Failure Prediction", elem_id="title")
77
+ gr.Markdown("An interactive demo of the XGBoost model trained on the AI4I 2020 dataset. Adjust the sliders or select an example to see real-time predictions.")
78
+
79
+ with gr.Row():
80
+ with gr.Column(scale=1):
81
+ with gr.Group():
82
+ gr.Markdown("### Input Parameters")
83
+ type_input = gr.Radio(['L (Low)', 'M (Medium)', 'H (High)'], label="Product Type", value='M (Medium)')
84
+ air_temp_input = gr.Slider(295, 305, value=300.1, label="Air Temperature [K]")
85
+ process_temp_input = gr.Slider(305, 315, value=310.1, label="Process Temperature [K]")
86
+ rotational_speed_input = gr.Slider(1100, 2900, value=1500, label="Rotational Speed [rpm]")
87
+ torque_input = gr.Slider(3, 80, value=45, label="Torque [Nm]")
88
+ tool_wear_input = gr.Slider(0, 260, value=100, label="Tool Wear [min]")
89
+ submit_btn = gr.Button("Predict Failure", variant="primary")
90
+
91
+ with gr.Column(scale=2):
92
+ with gr.Group():
93
+ gr.Markdown("### Prediction Results")
94
+ interpretation_output = gr.Textbox(label="Status Interpretation", interactive=False)
95
+ barplot_output = gr.BarPlot(x="Failure Mode", y="Probability", title="Failure Mode Probabilities", vertical=False, y_lim=[0, 1])
96
+
97
+ gr.Markdown("### Example Scenarios")
98
+ gr.Examples(
99
+ examples=[
100
+ ['L (Low)', 302.6, 311.8, 1333, 65.2, 191],
101
+ ['M (Medium)', 300.5, 309.8, 1360, 38.6, 210],
102
+ ['H (High)', 303.4, 312.8, 1310, 55.3, 50],
103
+ ['L (Low)', 300.1, 310.1, 1500, 45.0, 10]
104
+ ],
105
+ examples_per_page=4,
106
+ label="Click an example to run a scenario:",
107
+ inputs=[type_input, air_temp_input, process_temp_input, rotational_speed_input, torque_input, tool_wear_input]
108
+ )
109
+
110
+ all_inputs = [type_input, air_temp_input, process_temp_input, rotational_speed_input, torque_input, tool_wear_input]
111
+ submit_btn.click(fn=predict_failure, inputs=all_inputs, outputs=[barplot_output, interpretation_output])
112
+
113
+ # --- 4. Launch the app ---
114
+ # This command is used to run the app on Hugging Face Spaces
115
+ demo.launch()