Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse files
dt_app.py
CHANGED
|
@@ -5,116 +5,135 @@ import joblib
|
|
| 5 |
from huggingface_hub import hf_hub_download
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
# --- Constants ---
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
HF_MODEL_FILENAME = "optimized_dt_predictor.pkl"
|
|
|
|
| 11 |
|
| 12 |
# --- Function to Load Model from Hugging Face ---
|
| 13 |
@st.cache_resource
|
| 14 |
def load_model():
|
| 15 |
"""Downloads the model artifact from the Hugging Face Hub and loads it."""
|
| 16 |
try:
|
|
|
|
| 17 |
model_path = hf_hub_download(
|
| 18 |
repo_id=HF_MODEL_REPO_ID,
|
| 19 |
filename=HF_MODEL_FILENAME,
|
| 20 |
-
repo_type="model",
|
| 21 |
local_dir=".",
|
| 22 |
local_dir_use_symlinks=False
|
| 23 |
)
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
-
st.error(f"
|
| 27 |
-
st.stop()
|
| 28 |
|
| 29 |
# --- Streamlit Application Layout ---
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# Load the trained model
|
| 33 |
model = load_model()
|
| 34 |
|
| 35 |
-
#
|
|
|
|
| 36 |
INPUT_COLUMNS = [
|
| 37 |
'Engine rpm', 'Lub oil pressure', 'Fuel pressure',
|
| 38 |
'Coolant pressure', 'lub oil temp', 'Coolant temp'
|
| 39 |
]
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
st.
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
| 46 |
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
-
st.subheader("Pressure Readings")
|
| 50 |
-
input_data['Lub oil pressure'] = st.slider("Lub Oil Pressure (bar)", 0.0, 8.0, 3.30, 0.01)
|
| 51 |
-
input_data['Fuel pressure'] = st.slider("Fuel Pressure (bar)", 0.0, 25.0, 6.60, 0.01)
|
| 52 |
-
input_data['Coolant pressure'] = st.slider("Coolant Pressure (bar)", 0.0, 8.0, 2.30, 0.01)
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
if
|
| 68 |
-
# 1.
|
| 69 |
input_df = pd.DataFrame([input_data])
|
| 70 |
|
| 71 |
-
# 2.
|
| 72 |
input_df = input_df[INPUT_COLUMNS]
|
| 73 |
|
| 74 |
-
# 3.
|
| 75 |
-
rename_map = {
|
| 76 |
-
'Engine rpm': 'Engine_RPM',
|
| 77 |
-
'Lub oil pressure': 'Lub_Oil_Pressure',
|
| 78 |
-
'Fuel pressure': 'Fuel_Pressure',
|
| 79 |
-
'Coolant pressure': 'Coolant_Pressure',
|
| 80 |
-
'lub oil temp': 'Lub_Oil_Temperature',
|
| 81 |
-
'Coolant temp': 'Coolant_Temperature'
|
| 82 |
-
}
|
| 83 |
-
input_df.rename(columns=rename_map, inplace=True)
|
| 84 |
-
|
| 85 |
-
# 4. Make Prediction
|
| 86 |
try:
|
|
|
|
| 87 |
prediction_proba = model.predict_proba(input_df)[0]
|
|
|
|
| 88 |
prediction = model.predict(input_df)[0]
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
st.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if prediction == 1:
|
| 107 |
-
st.metric(label="Failure Probability", value=f"{prediction_proba[1]*100:.2f}%", delta="High Risk", delta_color="inverse")
|
| 108 |
-
else:
|
| 109 |
-
st.metric(label="Health Score", value=f"{prediction_proba[0]*100:.2f}%", delta="Stable")
|
| 110 |
-
|
| 111 |
-
# Expandable section for raw data
|
| 112 |
-
with st.expander("View Processed Sensor Telemetry"):
|
| 113 |
-
st.dataframe(input_df, hide_index=True, use_container_width=True)
|
| 114 |
|
| 115 |
except Exception as e:
|
| 116 |
-
st.error(f"An error occurred during prediction
|
| 117 |
-
|
| 118 |
-
st.info("👈 Please configure sensors in the sidebar and click 'Run Diagnostics' to begin.")
|
| 119 |
else:
|
| 120 |
-
st.warning("
|
|
|
|
| 5 |
from huggingface_hub import hf_hub_download
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# --- Constants: MODIFIED FOR DECISION TREE MODEL (CODE 4) ---
|
| 9 |
+
# Use the exact repository ID from Code 4
|
| 10 |
+
HF_MODEL_REPO_ID = "ShaksML/dt-model-predictive-maintenance"
|
| 11 |
+
# The model file was saved and uploaded as 'optimized_dt_predictor.pkl' in Code 4
|
| 12 |
HF_MODEL_FILENAME = "optimized_dt_predictor.pkl"
|
| 13 |
+
# Note: Since Code 4 trained a scikit-learn Pipeline (Scaler + DT), the pipeline handles preprocessing.
|
| 14 |
|
| 15 |
# --- Function to Load Model from Hugging Face ---
|
| 16 |
@st.cache_resource
|
| 17 |
def load_model():
|
| 18 |
"""Downloads the model artifact from the Hugging Face Hub and loads it."""
|
| 19 |
try:
|
| 20 |
+
# Download the model file from the Hugging Face repository
|
| 21 |
model_path = hf_hub_download(
|
| 22 |
repo_id=HF_MODEL_REPO_ID,
|
| 23 |
filename=HF_MODEL_FILENAME,
|
| 24 |
+
repo_type="model", # Explicitly set repo_type to 'model'
|
| 25 |
local_dir=".",
|
| 26 |
local_dir_use_symlinks=False
|
| 27 |
)
|
| 28 |
+
st.success(f"Model '{HF_MODEL_FILENAME}' successfully loaded from {HF_MODEL_REPO_ID}!")
|
| 29 |
+
# Load the model using joblib (which is the format used by Code 4)
|
| 30 |
+
model = joblib.load(model_path)
|
| 31 |
+
return model
|
| 32 |
except Exception as e:
|
| 33 |
+
st.error(f"Error loading model from Hugging Face Hub. Please check repo ID and filename: {e}")
|
| 34 |
+
st.stop() # Stop execution if the model cannot be loaded
|
| 35 |
|
| 36 |
# --- Streamlit Application Layout ---
|
| 37 |
+
|
| 38 |
+
st.set_page_config(
|
| 39 |
+
page_title="DT Predictive Maintenance App",
|
| 40 |
+
layout="wide"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
st.title("Decision Tree Engine Maintenance Dashboard")
|
| 44 |
+
st.subheader("Forecast potential engine failures using real-time sensor data.")
|
| 45 |
|
| 46 |
# Load the trained model
|
| 47 |
model = load_model()
|
| 48 |
|
| 49 |
+
# Define the columns exactly as expected by the model (using the names from the original data)
|
| 50 |
+
# Assuming the column names are:
|
| 51 |
INPUT_COLUMNS = [
|
| 52 |
'Engine rpm', 'Lub oil pressure', 'Fuel pressure',
|
| 53 |
'Coolant pressure', 'lub oil temp', 'Coolant temp'
|
| 54 |
]
|
| 55 |
|
| 56 |
+
if model is not None:
|
| 57 |
+
# --- Input Form for Sensor Readings ---
|
| 58 |
+
st.markdown("---")
|
| 59 |
+
st.header("Enter Engine Sensor Readings")
|
| 60 |
|
| 61 |
+
# Dictionary to hold the user inputs
|
| 62 |
+
input_data = {}
|
| 63 |
|
| 64 |
+
# Define the input columns in a three-column layout
|
| 65 |
+
col1, col2, col3 = st.columns(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
with col1:
|
| 68 |
+
# Engine rpm (int)
|
| 69 |
+
input_data['Engine rpm'] = st.number_input(
|
| 70 |
+
"Engine RPM (Revolutions per Minute)",
|
| 71 |
+
min_value=400, max_value=2000, value=790, step=10, key='rpm'
|
| 72 |
+
)
|
| 73 |
+
# Lub oil pressure (float)
|
| 74 |
+
input_data['Lub oil pressure'] = st.number_input(
|
| 75 |
+
"Lub Oil Pressure (bar)",
|
| 76 |
+
min_value=0.0, max_value=8.0, value=3.30, step=0.1, format="%.2f", key='lop'
|
| 77 |
+
)
|
| 78 |
|
| 79 |
+
with col2:
|
| 80 |
+
# Fuel pressure (float)
|
| 81 |
+
input_data['Fuel pressure'] = st.number_input(
|
| 82 |
+
"Fuel Pressure (bar)",
|
| 83 |
+
min_value=0.0, max_value=25.0, value=6.60, step=0.1, format="%.2f", key='fp'
|
| 84 |
+
)
|
| 85 |
+
# Coolant pressure (float)
|
| 86 |
+
input_data['Coolant pressure'] = st.number_input(
|
| 87 |
+
"Coolant Pressure (bar)",
|
| 88 |
+
min_value=0.0, max_value=8.0, value=2.30, step=0.1, format="%.2f", key='cp'
|
| 89 |
+
)
|
| 90 |
|
| 91 |
+
with col3:
|
| 92 |
+
# lub oil temp (float)
|
| 93 |
+
input_data['lub oil temp'] = st.number_input(
|
| 94 |
+
"Lub Oil Temperature (°C)",
|
| 95 |
+
min_value=70.0, max_value=100.0, value=78.0, step=0.1, format="%.2f", key='lot'
|
| 96 |
+
)
|
| 97 |
+
# Coolant temp (float)
|
| 98 |
+
input_data['Coolant temp'] = st.number_input(
|
| 99 |
+
"Coolant Temperature (°C)",
|
| 100 |
+
min_value=70.0, max_value=110.0, value=78.0, step=0.1, format="%.2f", key='ct'
|
| 101 |
+
)
|
| 102 |
|
| 103 |
+
# --- Prediction Logic ---
|
| 104 |
+
if st.button("Predict Engine Condition", type="primary"):
|
| 105 |
+
# 1. Get the inputs and save them into a dataframe
|
| 106 |
input_df = pd.DataFrame([input_data])
|
| 107 |
|
| 108 |
+
# 2. Ensure the order of columns matches the training data (CRITICAL)
|
| 109 |
input_df = input_df[INPUT_COLUMNS]
|
| 110 |
|
| 111 |
+
# 3. Make Prediction
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
try:
|
| 113 |
+
# Predict probability for both classes (0 and 1)
|
| 114 |
prediction_proba = model.predict_proba(input_df)[0]
|
| 115 |
+
# Prediction is the class index (0 or 1)
|
| 116 |
prediction = model.predict(input_df)[0]
|
| 117 |
|
| 118 |
+
# 4. Display Result
|
| 119 |
+
st.markdown("---")
|
| 120 |
+
st.header("Prediction Result")
|
| 121 |
+
|
| 122 |
+
if prediction == 1:
|
| 123 |
+
st.error("🚨 FAULT PREDICTED (Requires Maintenance)")
|
| 124 |
+
st.markdown(f"**Probability of Failure (Class 1):** `{prediction_proba[1]*100:.2f}%`")
|
| 125 |
+
st.markdown("Immediate inspection and preventive maintenance are **strongly recommended** to avoid unexpected breakdown and costly repairs.")
|
| 126 |
+
else:
|
| 127 |
+
st.success("✅ NORMAL OPERATION")
|
| 128 |
+
st.markdown(f"**Probability of Normal Operation (Class 0):** `{prediction_proba[0]*100:.2f}%`")
|
| 129 |
+
st.markdown("The engine is operating within normal parameters. Continue with scheduled monitoring.")
|
| 130 |
+
|
| 131 |
+
st.markdown("---")
|
| 132 |
+
st.caption("Input Data Used for Prediction:")
|
| 133 |
+
st.dataframe(input_df, hide_index=True) # Show the data that was fed to the model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
+
st.error(f"An error occurred during prediction. Please check input values. Full error: {e}")
|
| 137 |
+
|
|
|
|
| 138 |
else:
|
| 139 |
+
st.warning("Cannot proceed without a successfully loaded model. Please ensure the Decision Tree model exists in the Hugging Face repo.")
|