File size: 5,773 Bytes
7f288fa 3bdd127 294e01f 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 294e01f 7f288fa 294e01f 7f288fa 294e01f 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 7f288fa 3bdd127 | 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 | import pandas as pd
import numpy as np
import joblib
import gradio as gr
from sklearn.multiclass import OneVsRestClassifier
from xgboost import XGBClassifier
import traceback
# ==============================================================================
# --- Main Application Logic ---
# ==============================================================================
# --- 1. Load the trained model ---
# The model file will be in the same directory on Hugging Face Spaces
try:
loaded_model = joblib.load('champion_model.pkl')
print("Model loaded successfully.")
except FileNotFoundError:
# This provides a clear error message if the model file is missing
print("Error: 'champion_model.pkl' not found. Please upload the model file to your Hugging Face Space.")
loaded_model = None
# --- 2. Define the prediction function ---
def predict_failure(type_L_M_H, air_temp, process_temp, rotational_speed, torque, tool_wear):
"""
Predicts machine failure probabilities using the loaded model.
"""
if loaded_model is None:
return pd.DataFrame(), "ERROR: Model is not loaded. Check logs."
try:
type_mapping = {'L (Low)': 0, 'M (Medium)': 1, 'H (High)': 2}
type_numeric = int(type_mapping.get(type_L_M_H, 0))
input_data = pd.DataFrame({
'type': [type_numeric],
'airtemperaturek': [float(air_temp)],
'processtemperaturek': [float(process_temp)],
'rotationalspeedrpm': [int(rotational_speed)],
'torquenm': [float(torque)],
'toolwearmin': [int(tool_wear)]
})
labels = ['Normal', 'TWF', 'HDF', 'PWF', 'OSF', 'RNF']
output_dict = {}
for i, label in enumerate(labels):
estimator = loaded_model.estimators_[i]
prob_for_label = estimator.predict_proba(input_data)
output_dict[label] = round(prob_for_label[0, 1], 4)
barplot_df = pd.DataFrame(list(output_dict.items()), columns=['Failure Mode', 'Probability'])
failure_probs = {k: v for k, v in output_dict.items() if k != 'Normal'}
if not failure_probs or max(failure_probs.values()) < 0.1:
highest_failure = "None (Machine is likely Normal)"
interpretation = f"✅ Status: {highest_failure}"
else:
highest_failure = max(failure_probs, key=failure_probs.get)
interpretation = f"⚠️ Highest Predicted Failure Mode: {highest_failure}"
return barplot_df, interpretation
except Exception as e:
error_message = f"An error occurred: {str(e)}"
traceback.print_exc()
empty_df = pd.DataFrame({'Failure Mode': [], 'Probability': []})
return empty_df, error_message
# --- 3. Create the Gradio interface ---
# Custom CSS for a more polished look
css = """
#title {
text-align: center;
font-family: 'Garamond', serif; /* Elegant serif font */
font-size: 3.5em; /* Large size for main title */
color: #4A90E2; /* Professional blue color */
padding-bottom: 10px;
}
#subtitle {
text-align: center;
font-family: 'Garamond', serif;
font-size: 2em;
color: #333333;
padding-bottom: 20px;
}
"""
with gr.Blocks(theme=gr.themes.Glass(), css=css) as demo:
gr.Markdown(
"""
# 🔧 **Advanced Machine Failure Prediction**
### _Detect machine failure from given information_
Enter the machine details — including attributes such as **temperature**, **torque**, **rotational speed**, and **tool wear** — and this AI model will predict the **probability of potential failure** in real time.
""",
elem_id="title"
)
with gr.Row():
with gr.Column(scale=1):
with gr.Group():
gr.Markdown("### Input Parameters")
type_input = gr.Radio(['L (Low)', 'M (Medium)', 'H (High)'], label="Product Type", value='M (Medium)')
air_temp_input = gr.Slider(295, 305, value=300.1, label="Air Temperature [K]")
process_temp_input = gr.Slider(305, 315, value=310.1, label="Process Temperature [K]")
rotational_speed_input = gr.Slider(1100, 2900, value=1500, label="Rotational Speed [rpm]")
torque_input = gr.Slider(3, 80, value=45, label="Torque [Nm]")
tool_wear_input = gr.Slider(0, 260, value=100, label="Tool Wear [min]")
submit_btn = gr.Button("Predict Failure", variant="primary")
with gr.Column(scale=2):
with gr.Group():
gr.Markdown("### Prediction Results")
interpretation_output = gr.Textbox(label="Status Interpretation", interactive=False)
barplot_output = gr.BarPlot(x="Failure Mode", y="Probability", title="Failure Mode Probabilities", vertical=False, y_lim=[0, 1])
gr.Markdown("### Example Scenarios")
gr.Examples(
examples=[
['L (Low)', 302.6, 311.8, 1333, 65.2, 191],
['M (Medium)', 300.5, 309.8, 1360, 38.6, 210],
['H (High)', 303.4, 312.8, 1310, 55.3, 50],
['L (Low)', 300.1, 310.1, 1500, 45.0, 10]
],
examples_per_page=4,
label="Click an example to run a scenario:",
inputs=[type_input, air_temp_input, process_temp_input, rotational_speed_input, torque_input, tool_wear_input]
)
all_inputs = [type_input, air_temp_input, process_temp_input, rotational_speed_input, torque_input, tool_wear_input]
submit_btn.click(fn=predict_failure, inputs=all_inputs, outputs=[barplot_output, interpretation_output])
# --- 4. Launch the app ---
# This command is used to run the app on Hugging Face Spaces
demo.launch()
|