Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,224 +1,53 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
-
import joblib
|
| 5 |
-
|
| 6 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 7 |
|
| 8 |
-
# ---------------------------
|
| 9 |
-
#
|
| 10 |
-
# ---------------------------
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
st.set_page_config(
|
| 15 |
-
page_title="Predictive Maintenance - Engine Failure Risk",
|
| 16 |
-
page_icon="🛠️",
|
| 17 |
-
layout="wide"
|
| 18 |
)
|
|
|
|
| 19 |
|
| 20 |
-
# ---------------------------
|
| 21 |
-
#
|
| 22 |
-
# ---------------------------
|
| 23 |
-
|
| 24 |
-
def load_model():
|
| 25 |
-
"""
|
| 26 |
-
Downloads the model from Hugging Face Hub and loads it once per session.
|
| 27 |
-
If your repo is private, set HF_TOKEN as a Space secret/environment variable.
|
| 28 |
-
"""
|
| 29 |
-
token = st.secrets.get("HF_TOKEN", None) if hasattr(st, "secrets") else None
|
| 30 |
-
|
| 31 |
-
model_path = hf_hub_download(
|
| 32 |
-
repo_id=MODEL_REPO_ID,
|
| 33 |
-
filename=MODEL_FILENAME,
|
| 34 |
-
token=token # works for private repos; ignored for public
|
| 35 |
-
)
|
| 36 |
-
return joblib.load(model_path)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def get_feature_names_from_pipeline(pipeline):
|
| 40 |
-
"""
|
| 41 |
-
Your saved object is a sklearn Pipeline:
|
| 42 |
-
[columntransformer -> xgbclassifier]
|
| 43 |
-
We fetch the numeric feature names from the fitted ColumnTransformer.
|
| 44 |
-
"""
|
| 45 |
-
# Step name from make_pipeline(make_column_transformer(...), xgb_model)
|
| 46 |
-
# usually becomes: 'columntransformer' and 'xgbclassifier'
|
| 47 |
-
if "columntransformer" not in pipeline.named_steps:
|
| 48 |
-
raise ValueError("Could not find 'columntransformer' inside the saved pipeline.")
|
| 49 |
-
|
| 50 |
-
ct = pipeline.named_steps["columntransformer"]
|
| 51 |
-
|
| 52 |
-
# make_column_transformer creates transformers like:
|
| 53 |
-
# [('standardscaler', StandardScaler(), ['col1','col2',...])]
|
| 54 |
-
# Sometimes it may appear under different auto-names, so scan.
|
| 55 |
-
for name, transformer, cols in ct.transformers_:
|
| 56 |
-
if isinstance(cols, (list, tuple)) and len(cols) > 0:
|
| 57 |
-
return list(cols)
|
| 58 |
-
|
| 59 |
-
raise ValueError("Could not extract feature columns from the ColumnTransformer.")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def coerce_numeric(df, feature_cols):
|
| 63 |
-
"""
|
| 64 |
-
Ensures all feature columns exist and are numeric.
|
| 65 |
-
"""
|
| 66 |
-
missing = [c for c in feature_cols if c not in df.columns]
|
| 67 |
-
if missing:
|
| 68 |
-
raise ValueError(f"Missing required columns: {missing}")
|
| 69 |
-
|
| 70 |
-
out = df.copy()
|
| 71 |
-
for c in feature_cols:
|
| 72 |
-
out[c] = pd.to_numeric(out[c], errors="coerce")
|
| 73 |
-
|
| 74 |
-
if out[feature_cols].isna().any().any():
|
| 75 |
-
bad_cols = out[feature_cols].columns[out[feature_cols].isna().any()].tolist()
|
| 76 |
-
raise ValueError(
|
| 77 |
-
f"Some values could not be parsed as numbers (NaN found). Problem columns: {bad_cols}. "
|
| 78 |
-
f"Fix your inputs / CSV and try again."
|
| 79 |
-
)
|
| 80 |
-
return out
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def predict_proba(pipeline, X):
|
| 84 |
-
"""
|
| 85 |
-
Returns probability of class 1 (failure/risk).
|
| 86 |
-
"""
|
| 87 |
-
proba = pipeline.predict_proba(X)[:, 1]
|
| 88 |
-
return proba
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
# -----------------------------
|
| 92 |
-
# Load model + features
|
| 93 |
-
# -----------------------------
|
| 94 |
-
with st.spinner("Loading model from Hugging Face Hub..."):
|
| 95 |
-
model = load_model()
|
| 96 |
-
|
| 97 |
-
try:
|
| 98 |
-
feature_cols = get_feature_names_from_pipeline(model)
|
| 99 |
-
except Exception as e:
|
| 100 |
-
st.error(f"Failed to read feature names from the model pipeline: {e}")
|
| 101 |
-
st.stop()
|
| 102 |
-
|
| 103 |
-
# -----------------------------
|
| 104 |
-
# UI
|
| 105 |
-
# -----------------------------
|
| 106 |
-
st.title("🛠️ Predictive Maintenance – Engine Failure Risk Predictor")
|
| 107 |
st.write(
|
| 108 |
-
"
|
| 109 |
-
"probability of **engine failure (class = 1)** based on numeric sensor inputs."
|
| 110 |
)
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
st.
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
#
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
for i, feat in enumerate(feature_cols):
|
| 144 |
-
target_col = c1 if i % 2 == 0 else c2
|
| 145 |
-
with target_col:
|
| 146 |
-
inputs[feat] = st.number_input(
|
| 147 |
-
label=f"{feat}",
|
| 148 |
-
value=0.0,
|
| 149 |
-
step=0.1,
|
| 150 |
-
format="%.6f"
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
submitted = st.form_submit_button("Predict")
|
| 154 |
-
|
| 155 |
-
if submitted:
|
| 156 |
-
input_df = pd.DataFrame([inputs], columns=feature_cols)
|
| 157 |
-
|
| 158 |
-
try:
|
| 159 |
-
input_df = coerce_numeric(input_df, feature_cols)
|
| 160 |
-
proba = float(predict_proba(model, input_df)[0])
|
| 161 |
-
pred = 1 if proba >= threshold else 0
|
| 162 |
-
|
| 163 |
-
st.success("Prediction complete ✅")
|
| 164 |
-
st.metric("Failure probability (class=1)", f"{proba:.4f}")
|
| 165 |
-
|
| 166 |
-
if pred == 1:
|
| 167 |
-
st.error(f"⚠️ Predicted: **FAILURE (1)** at threshold {threshold:.2f}")
|
| 168 |
-
else:
|
| 169 |
-
st.info(f"✅ Predicted: **NO FAILURE (0)** at threshold {threshold:.2f}")
|
| 170 |
-
|
| 171 |
-
except Exception as e:
|
| 172 |
-
st.error(str(e))
|
| 173 |
-
|
| 174 |
-
# -----------------------------
|
| 175 |
-
# Batch prediction via CSV
|
| 176 |
-
# -----------------------------
|
| 177 |
-
with col_right:
|
| 178 |
-
st.subheader("Batch prediction (CSV upload)")
|
| 179 |
-
st.caption("Upload a CSV containing the same feature columns used in training.")
|
| 180 |
-
|
| 181 |
-
uploaded = st.file_uploader("Upload CSV", type=["csv"])
|
| 182 |
-
|
| 183 |
-
threshold_batch = st.slider(
|
| 184 |
-
"Batch threshold (>= threshold → Failure = 1)",
|
| 185 |
-
min_value=0.0,
|
| 186 |
-
max_value=1.0,
|
| 187 |
-
value=0.50,
|
| 188 |
-
step=0.01,
|
| 189 |
-
key="threshold_batch"
|
| 190 |
-
)
|
| 191 |
-
|
| 192 |
-
if uploaded is not None:
|
| 193 |
-
try:
|
| 194 |
-
df = pd.read_csv(uploaded)
|
| 195 |
-
st.write("Preview:")
|
| 196 |
-
st.dataframe(df.head(10))
|
| 197 |
-
|
| 198 |
-
df_fixed = coerce_numeric(df, feature_cols)
|
| 199 |
-
proba = predict_proba(model, df_fixed[feature_cols])
|
| 200 |
-
pred = (proba >= threshold_batch).astype(int)
|
| 201 |
-
|
| 202 |
-
out = df.copy()
|
| 203 |
-
out["failure_probability"] = proba
|
| 204 |
-
out["failure_prediction"] = pred
|
| 205 |
-
|
| 206 |
-
st.success("Batch prediction complete ✅")
|
| 207 |
-
st.write("Results preview:")
|
| 208 |
-
st.dataframe(out.head(20))
|
| 209 |
-
|
| 210 |
-
csv_bytes = out.to_csv(index=False).encode("utf-8")
|
| 211 |
-
st.download_button(
|
| 212 |
-
"Download results CSV",
|
| 213 |
-
data=csv_bytes,
|
| 214 |
-
file_name="predictive_maintenance_predictions.csv",
|
| 215 |
-
mime="text/csv"
|
| 216 |
-
)
|
| 217 |
-
|
| 218 |
-
except Exception as e:
|
| 219 |
-
st.error(str(e))
|
| 220 |
-
|
| 221 |
-
st.divider()
|
| 222 |
-
st.caption(
|
| 223 |
-
"Tip: If your model repo is private, add `HF_TOKEN` in your Hugging Face Space **Secrets**."
|
| 224 |
-
)
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
| 3 |
from huggingface_hub import hf_hub_download
|
| 4 |
+
import joblib
|
| 5 |
|
| 6 |
+
# ---------------------------
|
| 7 |
+
# Download + load model (PUBLIC repo, so no token needed)
|
| 8 |
+
# ---------------------------
|
| 9 |
+
model_path = hf_hub_download(
|
| 10 |
+
repo_id="vinodcwanted/Predictive-Maintenance",
|
| 11 |
+
filename="best_engine_xgb_model.joblib"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
)
|
| 13 |
+
model = joblib.load(model_path)
|
| 14 |
|
| 15 |
+
# ---------------------------
|
| 16 |
+
# Streamlit UI
|
| 17 |
+
# ---------------------------
|
| 18 |
+
st.title("Predictive Maintenance - Engine Condition Prediction")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
st.write(
|
| 20 |
+
"Enter the engine sensor values below. The model will predict **Engine Condition** (0/1)."
|
|
|
|
| 21 |
)
|
| 22 |
|
| 23 |
+
# ---------------------------
|
| 24 |
+
# Collect user input (6 parameters)
|
| 25 |
+
# ---------------------------
|
| 26 |
+
engine_rpm = st.number_input("Engine rpm", min_value=0.0, value=700.0, step=1.0)
|
| 27 |
+
lub_oil_pressure = st.number_input("Lub oil pressure", min_value=0.0, value=2.5, step=0.01)
|
| 28 |
+
fuel_pressure = st.number_input("Fuel pressure", min_value=0.0, value=12.0, step=0.01)
|
| 29 |
+
coolant_pressure = st.number_input("Coolant pressure", min_value=0.0, value=3.0, step=0.01)
|
| 30 |
+
lub_oil_temp = st.number_input("lub oil temp", min_value=0.0, value=80.0, step=0.1)
|
| 31 |
+
coolant_temp = st.number_input("Coolant temp", min_value=0.0, value=82.0, step=0.1)
|
| 32 |
+
|
| 33 |
+
# Build input DataFrame (MUST match training column names exactly)
|
| 34 |
+
input_data = pd.DataFrame([{
|
| 35 |
+
"Engine rpm": engine_rpm,
|
| 36 |
+
"Lub oil pressure": lub_oil_pressure,
|
| 37 |
+
"Fuel pressure": fuel_pressure,
|
| 38 |
+
"Coolant pressure": coolant_pressure,
|
| 39 |
+
"lub oil temp": lub_oil_temp,
|
| 40 |
+
"Coolant temp": coolant_temp
|
| 41 |
+
}])
|
| 42 |
+
|
| 43 |
+
# ---------------------------
|
| 44 |
+
# Prediction
|
| 45 |
+
# ---------------------------
|
| 46 |
+
classification_threshold = 0.50
|
| 47 |
+
|
| 48 |
+
if st.button("Predict"):
|
| 49 |
+
prediction_proba = model.predict_proba(input_data)[0, 1]
|
| 50 |
+
prediction = int(prediction_proba >= classification_threshold)
|
| 51 |
+
|
| 52 |
+
st.write(f"**Predicted probability (Engine Condition = 1):** {prediction_proba:.4f}")
|
| 53 |
+
st.write(f"✅ **Engine Condition (Predicted): {prediction}**")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|