nilanjanadevc commited on
Commit
5bc66d8
Β·
verified Β·
1 Parent(s): 73baadf

Update Streamlit app

Browse files
Files changed (1) hide show
  1. app.py +215 -0
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from huggingface_hub import hf_hub_download
5
+ import joblib
6
+ from datetime import datetime
7
+ import warnings
8
+ warnings.filterwarnings("ignore")
9
+
10
+ # ============================================
11
+ # PAGE CONFIGURATION
12
+ # ============================================
13
+ st.set_page_config(
14
+ page_title="Engine Predictive Maintenance System",
15
+ page_icon="πŸ”§",
16
+ layout="wide",
17
+ initial_sidebar_state="expanded"
18
+ )
19
+
20
+ # ============================================
21
+ # LOAD MODEL FROM HUGGING FACE
22
+ # ============================================
23
+ @st.cache_resource
24
+ def load_model():
25
+ """Load trained model from Hugging Face Hub"""
26
+ try:
27
+ model = hf_hub_download(
28
+ repo_id="nilanjanadevc/engine-predictive-maintenance-model",
29
+ filename="model.joblib"
30
+ )
31
+ return joblib.load(model)
32
+ except Exception as e:
33
+ st.error(f"Error loading model: {e}")
34
+ return None
35
+
36
+ # ============================================
37
+ # FEATURE ENGINEERING FUNCTION
38
+ # ============================================
39
+ def engineer_features(df):
40
+ """Apply physics-based feature engineering"""
41
+ df_enhanced = df.copy()
42
+
43
+ # Lubrication Stress Index
44
+ df_enhanced['Lub_Stress_Index'] = df_enhanced['Lub oil pressure'] * df_enhanced['lub oil temp']
45
+
46
+ # Thermal Efficiency
47
+ df_enhanced['Thermal_Efficiency'] = df_enhanced['Coolant pressure'] / (df_enhanced['Coolant temp'] + 1e-5)
48
+
49
+ # Power Load Index
50
+ df_enhanced['Power_Load_Index'] = df_enhanced['Engine rpm'] * df_enhanced['Fuel pressure']
51
+
52
+ return df_enhanced
53
+
54
+ # ============================================
55
+ # MAIN APP
56
+ # ============================================
57
+ st.title("πŸ”§ Engine Predictive Maintenance System")
58
+ st.markdown("Real-time failure prediction using ML and physics-based features")
59
+
60
+ model = load_model()
61
+
62
+ if model is None:
63
+ st.stop()
64
+
65
+ # ============================================
66
+ # SIDEBAR: INPUT METHOD
67
+ # ============================================
68
+ st.sidebar.header("βš™οΈ Input Configuration")
69
+ input_method = st.sidebar.radio(
70
+ "Select input method:",
71
+ ["πŸ“ Manual Input", "πŸ“€ Upload CSV", "πŸ”’ Batch Prediction"]
72
+ )
73
+
74
+ # ============================================
75
+ # MANUAL INPUT
76
+ # ============================================
77
+ if input_method == "πŸ“ Manual Input":
78
+ st.header("Manual Engine Sensor Input")
79
+
80
+ col1, col2, col3 = st.columns(3)
81
+
82
+ with col1:
83
+ engine_rpm = st.number_input("Engine RPM", min_value=0.0, max_value=3000.0, value=1000.0)
84
+ lub_oil_pressure = st.number_input("Lub Oil Pressure (bar)", min_value=0.0, max_value=10.0, value=5.0)
85
+ fuel_pressure = st.number_input("Fuel Pressure (bar)", min_value=0.0, max_value=10.0, value=3.5)
86
+
87
+ with col2:
88
+ coolant_pressure = st.number_input("Coolant Pressure (bar)", min_value=0.0, max_value=5.0, value=2.0)
89
+ lub_oil_temp = st.number_input("Lub Oil Temp (Β°C)", min_value=0.0, max_value=150.0, value=80.0)
90
+ coolant_temp = st.number_input("Coolant Temp (Β°C)", min_value=0.0, max_value=120.0, value=85.0)
91
+
92
+ with col3:
93
+ st.write("### Summary")
94
+ st.info(f"βœ“ {6} sensor inputs ready")
95
+
96
+ if st.button("πŸ” Predict Engine Condition", key="predict_manual"):
97
+ # Create dataframe
98
+ input_data = pd.DataFrame({
99
+ 'Engine rpm': [engine_rpm],
100
+ 'Lub oil pressure': [lub_oil_pressure],
101
+ 'Fuel pressure': [fuel_pressure],
102
+ 'Coolant pressure': [coolant_pressure],
103
+ 'lub oil temp': [lub_oil_temp],
104
+ 'Coolant temp': [coolant_temp]
105
+ })
106
+
107
+ # Engineer features
108
+ input_enhanced = engineer_features(input_data)
109
+
110
+ # Make prediction
111
+ prediction = model.predict(input_enhanced)[0]
112
+ probability = model.predict_proba(input_enhanced)[0]
113
+
114
+ # Display results
115
+ st.success("βœ“ Prediction completed!")
116
+
117
+ col_pred, col_prob = st.columns(2)
118
+
119
+ with col_pred:
120
+ if prediction == 0:
121
+ st.metric("Status", "🟒 HEALTHY", delta="Normal Operation")
122
+ else:
123
+ st.metric("Status", "πŸ”΄ FAULTY", delta="Maintenance Required")
124
+
125
+ with col_prob:
126
+ st.metric("Confidence", f"{probability[prediction]*100:.2f}%")
127
+
128
+ # Risk assessment
129
+ st.subheader("πŸ“Š Risk Assessment")
130
+ failure_risk = probability[1] * 100
131
+
132
+ if failure_risk < 30:
133
+ risk_level = "🟒 Low Risk"
134
+ elif failure_risk < 70:
135
+ risk_level = "🟑 Medium Risk"
136
+ else:
137
+ risk_level = "πŸ”΄ High Risk"
138
+
139
+ st.write(f"Failure Risk: {risk_level} ({failure_risk:.2f}%)")
140
+
141
+ # Feature importance for manual input
142
+ st.subheader("πŸ” Sensor Analysis")
143
+ col1, col2, col3 = st.columns(3)
144
+ with col1:
145
+ st.write("**Oil System:**")
146
+ st.write(f"β€’ Pressure: {lub_oil_pressure:.2f} bar")
147
+ st.write(f"β€’ Temp: {lub_oil_temp:.2f}Β°C")
148
+ with col2:
149
+ st.write("**Cooling System:**")
150
+ st.write(f"β€’ Pressure: {coolant_pressure:.2f} bar")
151
+ st.write(f"β€’ Temp: {coolant_temp:.2f}Β°C")
152
+ with col3:
153
+ st.write("**Engine Load:**")
154
+ st.write(f"β€’ RPM: {engine_rpm:.2f}")
155
+ st.write(f"β€’ Fuel: {fuel_pressure:.2f} bar")
156
+
157
+ # ============================================
158
+ # CSV UPLOAD
159
+ # ============================================
160
+ elif input_method == "πŸ“€ Upload CSV":
161
+ st.header("Batch CSV Prediction")
162
+
163
+ uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
164
+
165
+ if uploaded_file is not None:
166
+ df = pd.read_csv(uploaded_file)
167
+ st.write("### Preview:")
168
+ st.dataframe(df.head())
169
+
170
+ if st.button("πŸ” Predict All Rows"):
171
+ df_enhanced = engineer_features(df)
172
+ predictions = model.predict(df_enhanced)
173
+ probabilities = model.predict_proba(df_enhanced)
174
+
175
+ results_df = df.copy()
176
+ results_df['Prediction'] = predictions
177
+ results_df['Failure_Risk_%'] = probabilities[:, 1] * 100
178
+ results_df['Status'] = results_df['Prediction'].apply(
179
+ lambda x: "🟒 HEALTHY" if x == 0 else "πŸ”΄ FAULTY"
180
+ )
181
+
182
+ st.success("βœ“ Predictions completed!")
183
+ st.dataframe(results_df)
184
+
185
+ # Download results
186
+ csv = results_df.to_csv(index=False)
187
+ st.download_button(
188
+ label="πŸ“₯ Download Predictions",
189
+ data=csv,
190
+ file_name=f"predictions_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
191
+ mime="text/csv"
192
+ )
193
+
194
+ # ============================================
195
+ # INFO SECTION
196
+ # ============================================
197
+ st.sidebar.markdown("---")
198
+ st.sidebar.header("ℹ️ About This Model")
199
+ st.sidebar.info("""
200
+ **Physics-Aware Predictive Maintenance System**
201
+
202
+ - **Training Data**: 19,535 engine observations
203
+ - **Features**: 9 (6 raw + 3 engineered)
204
+ - **Target**: Binary classification (Healthy/Faulty)
205
+ - **Primary Metric**: F2-Score (recall-focused)
206
+ - **Calibration**: Brier Score optimized
207
+
208
+ **Key Features:**
209
+ - Lubrication Stress Index
210
+ - Thermal Efficiency
211
+ - Power Load Index
212
+ """)
213
+
214
+ st.sidebar.markdown("---")
215
+ st.sidebar.caption("Β© 2026 Predictive Maintenance System v1.0")