Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files5 unmodified lines6789101115 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636428 unmodified lines939495969798991003 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351365 unmodified lines1421431441451461471481491505 unmodified linesfrom huggingface_hub import hf_hub_downloadimport jsonimport os# =============================================================================# STREAMLIT CONFIG15 unmodified linesrepo_id = "SharleyK/predictive-maintenance-model"token = os.getenv("HF_TOKEN")model_path = hf_hub_download(repo_id=repo_id,filename="best_model.pkl",token=token)model = joblib.load(model_path)scaler_path = hf_hub_download(repo_id=repo_id,filename="scaler.pkl",token=token)scaler = joblib.load(scaler_path)metadata_path = hf_hub_download(repo_id=repo_id,filename="metadata.json",token=token)with open(metadata_path, "r") as f:metadata = json.load(f)return model, scaler, metadata, Trueexcept Exception as e:st.error(f"❌ Error loading model artifacts: {e}")return None, None, {}, Falsemodel, scaler, metadata, MODEL_LOADED = load_artifacts()MODEL_NAME = metadata.get("model_name", "Predictive Maintenance Model")# =============================================================================# FEATURE ENGINEERING# =============================================================================28 unmodified lines# =============================================================================def predict(df):df_eng = engineer_features(df)X_scaled = scaler.transform(df_eng)pred = model.predict(X_scaled)[0]if hasattr(model, "predict_proba"):3 unmodified linesreturn pred, confidence# =============================================================================# UI# =============================================================================st.title("🛠️ Predictive Maintenance – Engine Failure Prediction")st.caption("AI-powered real-time engine health assessment")st.markdown(f"""**Model:** {MODEL_NAME}**Accuracy:** 66.68% | **Recall:** 87.13%""")st.divider()col1, col2 = st.columns(2)with col1:engine_rpm = st.slider("Engine RPM", 50, 2500, 800, step=10)lub_oil_pressure = st.slider("Lub Oil Pressure", 0.0, 8.0, 3.3)fuel_pressure = st.slider("Fuel Pressure", 0.0, 22.0, 6.5)with col2:coolant_pressure = st.slider("Coolant Pressure", 0.0, 8.0, 2.3)lub_oil_temp = st.slider("Lub Oil Temp (°C)", 70.0, 95.0, 77.0)coolant_temp = st.slider("Coolant Temp (°C)", 60.0, 200.0, 78.0)if st.button("Predict Engine Condition"):df = pd.DataFrame([{"engine_rpm": engine_rpm,"lub_oil_pressure": lub_oil_pressure,5 unmodified linespred, conf = predict(df)if pred == 1:st.error("🚨 FAULTY ENGINE DETECTED")else:st.success("✅ ENGINE OPERATING NORMALLY")st.metric("Confidence", f"{conf*100:.1f}%")5 unmodified lines678910111215 unmodified lines28293031323334353637383940414243444546474828 unmodified lines777879808182838485863 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172185 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632645 unmodified linesfrom huggingface_hub import hf_hub_downloadimport jsonimport osimport plotly.graph_objects as go# =============================================================================# STREAMLIT CONFIG15 unmodified linesrepo_id = "SharleyK/predictive-maintenance-model"token = os.getenv("HF_TOKEN")model = joblib.load(hf_hub_download(repo_id, "best_model.pkl", token=token))scaler = joblib.load(hf_hub_download(repo_id, "scaler.pkl", token=token))metadata_path = hf_hub_download(repo_id, "metadata.json", token=token)metadata = json.load(open(metadata_path))return model, scaler, metadata, Trueexcept Exception as e:st.error(f"❌ Error loading model: {e}")return None, None, {}, Falsemodel, scaler, metadata, MODEL_LOADED = load_artifacts()MODEL_NAME = metadata.get("model_name", "Predictive Maintenance Model")# =============================================================================# FEATURE ENGINEERING# =============================================================================28 unmodified lines# =============================================================================def predict(df):df_eng = engineer_features(df)X_scaled = scaler.transform(df_eng)pred = model.predict(X_scaled)[0]if hasattr(model, "predict_proba"):3 unmodified linesreturn pred, confidence# =============================================================================# VISUALS# =============================================================================def gauge_chart(confidence):fig = go.Figure(go.Indicator(mode="gauge+number",value=confidence * 100,title={'text': "Confidence %"},gauge={'axis': {'range': [0, 100]},'steps': [{'range': [0, 50], 'color': 'lightgreen'},{'range': [50, 70], 'color': 'yellow'},{'range': [70, 85], 'color': 'orange'},{'range': [85, 100], 'color': 'red'}],}))fig.update_layout(height=300)return figdef radar_chart(params):categories = ['RPM','Oil Pressure','Fuel Pressure','Coolant Pressure','Oil Temp','Coolant Temp']values = [params["engine_rpm"]/25,params["lub_oil_pressure"]/0.08,params["fuel_pressure"]/0.22,params["coolant_pressure"]/0.08,params["lub_oil_temp"],params["coolant_temp"]/2]fig = go.Figure()fig.add_trace(go.Scatterpolar(r=values,theta=categories,fill='toself'))return fig# =============================================================================# RECOMMENDATIONS# =============================================================================def recommendations(pred, rpm, oil_p, fuel_p, coolant_p, oil_t, coolant_t):rec = []if pred == 1:rec.append("### 🚨 Maintenance Recommended")if oil_p < 2.5:rec.append("• Check oil pump / leaks")if coolant_t > 85:rec.append("• Cooling system inspection needed")if rpm < 600:rec.append("• Engine load or fuel intake check")if fuel_p > 8:rec.append("• Possible fuel regulator issue")else:rec.append("### ✅ Engine Healthy")rec.append("• Continue routine maintenance")rec.append("• Monitor coolant weekly")return "\n".join(rec)# =============================================================================# UI# =============================================================================st.title("🛠️ Predictive Maintenance Dashboard")st.caption("Real-time AI Engine Health Monitoring")st.info(f"Model: {MODEL_NAME}")st.divider()col1, col2, col3 = st.columns(3)with col1:engine_rpm = st.slider("Engine RPM", 50, 2500, 800)with col2:lub_oil_pressure = st.slider("Lub Oil Pressure", 0.0, 8.0, 3.3)with col3:fuel_pressure = st.slider("Fuel Pressure", 0.0, 22.0, 6.5)col4, col5, col6 = st.columns(3)with col4:coolant_pressure = st.slider("Coolant Pressure", 0.0, 8.0, 2.3)with col5:lub_oil_temp = st.slider("Lub Oil Temp", 70.0, 95.0, 77.0)with col6:coolant_temp = st.slider("Coolant Temp", 60.0, 200.0, 78.0)# =============================================================================# PREDICT BUTTON# =============================================================================if st.button("🔮 Predict Engine Condition"):df = pd.DataFrame([{"engine_rpm": engine_rpm,"lub_oil_pressure": lub_oil_pressure,5 unmodified linespred, conf = predict(df)colA, colB = st.columns(2)with colA:if pred == 1:st.error("🚨 Faulty Engine Detected")else:st.success("✅ Engine Healthy")st.metric("Confidence", f"{conf*100:.2f}%")with colB:st.plotly_chart(gauge_chart(conf), use_container_width=True)st.divider()st.subheader("📊 Engine Parameter Profile")st.plotly_chart(radar_chart(df.iloc[0]),use_container_width=True)st.divider()st.subheader("💡 Recommendations")st.markdown(recommendations(pred,engine_rpm,lub_oil_pressure,fuel_pressure,coolant_pressure,lub_oil_temp,coolant_temp))
app.py+154-40