Spaces:
Sleeping
Sleeping
File size: 6,861 Bytes
44a1e2b |
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
import os
import joblib
import pandas as pd
import numpy as np
import streamlit as st
from huggingface_hub import hf_hub_download, login
# Configuration
HF_TOKEN = os.getenv("HF_TOKEN") # optional if model is public
HF_MODEL_REPO = os.getenv("HF_MODEL_REPO", "dhani10/engine-condition-model")
MODEL_FILE = os.getenv("MODEL_FILE", "best_engine_model.joblib")
# Use a writable cache (esp. on Spaces)
os.environ.setdefault("HF_HOME", "/tmp/huggingface")
os.environ.setdefault("HF_HUB_CACHE", "/tmp/huggingface/hub")
os.makedirs(os.environ["HF_HUB_CACHE"], exist_ok=True)
if HF_TOKEN:
try:
login(HF_TOKEN)
except Exception:
pass
@st.cache_resource
def load_model():
p = hf_hub_download(
repo_id=HF_MODEL_REPO,
filename=MODEL_FILE,
repo_type="model",
token=HF_TOKEN,
cache_dir=os.environ["HF_HUB_CACHE"],
)
return joblib.load(p)
model = load_model()
# Engine sensor features
ENGINE_FEATURES = [
"Engine rpm",
"Lub oil pressure",
"Fuel pressure",
"Coolant pressure",
"lub oil temp",
"Coolant temp"
]
st.set_page_config(page_title="Engine Condition Monitor", layout="centered")
st.title("🏭 Engine Condition Monitoring System")
st.caption("Enter sensor readings to predict engine condition (Normal/Faulty)")
# Add information about the model
with st.expander("ℹ️ About this Model"):
st.write('''
This model predicts engine condition based on real-time sensor readings:
- **Normal (0)**: Engine operating within normal parameters
- **Faulty (1)**: Engine showing signs of potential failure
**Typical Operating Ranges:**
- Engine RPM: 600-2500
- Lub Oil Pressure: 2.0-4.0 bar
- Fuel Pressure: 8.0-15.0 bar
- Coolant Pressure: 1.5-4.0 bar
- Lub Oil Temp: 75-110°C
- Coolant Temp: 70-100°C
''')
# Sensor input form
with st.form("engine_predict_form"):
st.subheader("🔧 Sensor Readings")
col1, col2 = st.columns(2)
with col1:
engine_rpm = st.slider(
"Engine RPM",
min_value=0,
max_value=3000,
value=1800,
help="Engine rotations per minute"
)
lub_oil_pressure = st.slider(
"Lub Oil Pressure (bar)",
min_value=0.0,
max_value=6.0,
value=3.1,
step=0.1,
help="Lubricating oil pressure in bar"
)
fuel_pressure = st.slider(
"Fuel Pressure (bar)",
min_value=0.0,
max_value=20.0,
value=12.0,
step=0.1,
help="Fuel system pressure in bar"
)
with col2:
coolant_pressure = st.slider(
"Coolant Pressure (bar)",
min_value=0.0,
max_value=5.0,
value=2.9,
step=0.1,
help="Cooling system pressure in bar"
)
lub_oil_temp = st.slider(
"Lub Oil Temp (°C)",
min_value=0,
max_value=150,
value=92,
help="Lubricating oil temperature in °C"
)
coolant_temp = st.slider(
"Coolant Temp (°C)",
min_value=0,
max_value=150,
value=89,
help="Coolant temperature in °C"
)
submitted = st.form_submit_button("🔍 Predict Engine Condition")
if submitted:
# Build input data
ui_row = {
"Engine rpm": float(engine_rpm),
"Lub oil pressure": float(lub_oil_pressure),
"Fuel pressure": float(fuel_pressure),
"Coolant pressure": float(coolant_pressure),
"lub oil temp": float(lub_oil_temp),
"Coolant temp": float(coolant_temp)
}
# Create DataFrame with expected columns
row = pd.DataFrame([ui_row])
try:
# Make prediction
prediction = model.predict(row)[0]
probability = None
if hasattr(model, "predict_proba"):
probability = model.predict_proba(row)[0]
# Display results
st.subheader("🎯 Prediction Result")
if prediction == 1:
st.error("🚨 **FAULTY CONDITION DETECTED**")
st.warning("⚠️ Engine shows signs of potential failure. Immediate maintenance recommended.")
if probability is not None:
st.metric(
"Confidence Score",
f"{probability[1]:.1%}",
delta=f"Faulty probability",
delta_color="inverse"
)
else:
st.success("✅ **NORMAL OPERATION**")
st.info("🌡️ Engine operating within normal parameters.")
if probability is not None:
st.metric(
"Confidence Score",
f"{probability[0]:.1%}",
delta=f"Normal probability",
delta_color="normal"
)
# Display detailed probabilities
if probability is not None:
col1, col2 = st.columns(2)
with col1:
st.progress(probability[0], text=f"Normal: {probability[0]:.1%}")
with col2:
st.progress(probability[1], text=f"Faulty: {probability[1]:.1%}")
# Show input values
with st.expander("📊 Sensor Readings Used"):
st.dataframe(row.T.rename(columns={0: "Value"}))
# Add maintenance recommendations for faulty conditions
if prediction == 1:
st.subheader("🔧 Recommended Actions")
issues = []
if lub_oil_pressure < 2.5:
issues.append("Low lubricating oil pressure")
if fuel_pressure > 13.0:
issues.append("High fuel pressure")
if lub_oil_temp > 105:
issues.append("High lubricating oil temperature")
if coolant_temp > 95:
issues.append("High coolant temperature")
if issues:
st.write("Potential issues detected:")
for issue in issues:
st.write(f"• {issue}")
st.write('''
**Immediate Steps:**
1. Check oil levels and quality
2. Inspect cooling system
3. Verify fuel system components
4. Consult maintenance manual
''')
except Exception as e:
st.error(f"❌ Prediction failed: {e}")
st.write("Expected features:", ENGINE_FEATURES)
# Add footer
st.markdown("---")
st.caption('''
**Engine Condition Prediction System** |
Predictive Maintenance Model |
[View Model on Hugging Face](https://huggingface.co/dhani10/engine-condition-model)
''')
|