File size: 8,452 Bytes
5bc66d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9798a6c
5bc66d8
64a44ca
d39b4fd
 
 
 
 
 
 
 
 
64a44ca
d39b4fd
 
 
64a44ca
d39b4fd
 
64a44ca
d39b4fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64a44ca
d39b4fd
5bc66d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import streamlit as st
import pandas as pd
import numpy as np
from huggingface_hub import hf_hub_download
import joblib
from datetime import datetime
import warnings
warnings.filterwarnings("ignore")

# ============================================
# PAGE CONFIGURATION
# ============================================
st.set_page_config(
    page_title="Engine Predictive Maintenance System",
    page_icon="πŸ”§",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ============================================
# LOAD MODEL FROM HUGGING FACE
# ============================================
@st.cache_resource
def load_model():
    """Load trained model from Hugging Face Hub"""
    try:
        model = hf_hub_download(
            repo_id="nilanjanadevc/engine-predictive-maintenance-model",
            filename="model.joblib"
        )
        return joblib.load(model)
    except Exception as e:
        st.error(f"Error loading model: {e}")
        return None

# ============================================
# FEATURE ENGINEERING FUNCTION
# ============================================
def engineer_features(df):
    """Apply feature engineering to match training pipeline exactly"""
    df_enhanced = df.copy()
    
    # STEP 1: Rename columns to match training convention (CAPITALS)
    rename_mapping = {
        "Lub oil pressure": "Lube Oil Pressure",
        "lub oil temp": "Lube Oil Temperature",
        "Coolant temp": "Coolant Temperature",
        "Engine rpm": "Engine RPM",
        "Fuel pressure": "Fuel Pressure",
        "Coolant pressure": "Coolant Pressure"
    }
    
    for old_name, new_name in rename_mapping.items():
        if old_name in df_enhanced.columns:
            df_enhanced.rename(columns={old_name: new_name}, inplace=True)
    
    # STEP 2: Get sensor columns (all columns except 'Engine Condition')
    sensor_columns = [col for col in df_enhanced.columns if col != 'Engine Condition']
    
    # STEP 3: Add ratio features
    if 'Lube Oil Pressure' in df_enhanced.columns and 'Coolant Pressure' in df_enhanced.columns:
        df_enhanced['Oil_Coolant_Pressure_Ratio'] = (
            df_enhanced['Lube Oil Pressure'] / (df_enhanced['Coolant Pressure'] + 1)
        )
    
    if 'Lube Oil Temperature' in df_enhanced.columns and 'Coolant Temperature' in df_enhanced.columns:
        df_enhanced['Oil_Coolant_Temp_Diff'] = (
            df_enhanced['Lube Oil Temperature'] - df_enhanced['Coolant Temperature']
        )
    
    # STEP 4: Add squared features for EACH sensor column
    for col in sensor_columns:
        if col in df_enhanced.columns:
            df_enhanced[f'{col}_Squared'] = df_enhanced[col] ** 2
    
    return df_enhanced

# ============================================
# MAIN APP
# ============================================
st.title("πŸ”§ Engine Predictive Maintenance System")
st.markdown("Real-time failure prediction using ML and physics-based features")

model = load_model()

if model is None:
    st.stop()

# ============================================
# SIDEBAR: INPUT METHOD
# ============================================
st.sidebar.header("βš™οΈ Input Configuration")
input_method = st.sidebar.radio(
    "Select input method:",
    ["πŸ“ Manual Input", "πŸ“€ Upload CSV", "πŸ”’ Batch Prediction"]
)

# ============================================
# MANUAL INPUT
# ============================================
if input_method == "πŸ“ Manual Input":
    st.header("Manual Engine Sensor Input")

    col1, col2, col3 = st.columns(3)

    with col1:
        engine_rpm = st.number_input("Engine RPM", min_value=0.0, max_value=3000.0, value=1000.0)
        lub_oil_pressure = st.number_input("Lub Oil Pressure (bar)", min_value=0.0, max_value=10.0, value=5.0)
        fuel_pressure = st.number_input("Fuel Pressure (bar)", min_value=0.0, max_value=10.0, value=3.5)

    with col2:
        coolant_pressure = st.number_input("Coolant Pressure (bar)", min_value=0.0, max_value=5.0, value=2.0)
        lub_oil_temp = st.number_input("Lub Oil Temp (Β°C)", min_value=0.0, max_value=150.0, value=80.0)
        coolant_temp = st.number_input("Coolant Temp (Β°C)", min_value=0.0, max_value=120.0, value=85.0)

    with col3:
        st.write("### Summary")
        st.info(f"βœ“ {6} sensor inputs ready")

    if st.button("πŸ” Predict Engine Condition", key="predict_manual"):
        # Create dataframe
        input_data = pd.DataFrame({
            'Engine rpm': [engine_rpm],
            'Lub oil pressure': [lub_oil_pressure],
            'Fuel pressure': [fuel_pressure],
            'Coolant pressure': [coolant_pressure],
            'lub oil temp': [lub_oil_temp],
            'Coolant temp': [coolant_temp]
        })

        # Engineer features
        input_enhanced = engineer_features(input_data)

        # Make prediction
        prediction = model.predict(input_enhanced)[0]
        probability = model.predict_proba(input_enhanced)[0]

        # Display results
        st.success("βœ“ Prediction completed!")

        col_pred, col_prob = st.columns(2)

        with col_pred:
            if prediction == 0:
                st.metric("Status", "🟒 HEALTHY", delta="Normal Operation")
            else:
                st.metric("Status", "πŸ”΄ FAULTY", delta="Maintenance Required")

        with col_prob:
            st.metric("Confidence", f"{probability[prediction]*100:.2f}%")

        # Risk assessment
        st.subheader("πŸ“Š Risk Assessment")
        failure_risk = probability[1] * 100

        if failure_risk < 30:
            risk_level = "🟒 Low Risk"
        elif failure_risk < 70:
            risk_level = "🟑 Medium Risk"
        else:
            risk_level = "πŸ”΄ High Risk"

        st.write(f"Failure Risk: {risk_level} ({failure_risk:.2f}%)")

        # Feature importance for manual input
        st.subheader("πŸ” Sensor Analysis")
        col1, col2, col3 = st.columns(3)
        with col1:
            st.write("**Oil System:**")
            st.write(f"β€’ Pressure: {lub_oil_pressure:.2f} bar")
            st.write(f"β€’ Temp: {lub_oil_temp:.2f}Β°C")
        with col2:
            st.write("**Cooling System:**")
            st.write(f"β€’ Pressure: {coolant_pressure:.2f} bar")
            st.write(f"β€’ Temp: {coolant_temp:.2f}Β°C")
        with col3:
            st.write("**Engine Load:**")
            st.write(f"β€’ RPM: {engine_rpm:.2f}")
            st.write(f"β€’ Fuel: {fuel_pressure:.2f} bar")

# ============================================
# CSV UPLOAD
# ============================================
elif input_method == "πŸ“€ Upload CSV":
    st.header("Batch CSV Prediction")

    uploaded_file = st.file_uploader("Choose a CSV file", type="csv")

    if uploaded_file is not None:
        df = pd.read_csv(uploaded_file)
        st.write("### Preview:")
        st.dataframe(df.head())

        if st.button("πŸ” Predict All Rows"):
            df_enhanced = engineer_features(df)
            predictions = model.predict(df_enhanced)
            probabilities = model.predict_proba(df_enhanced)

            results_df = df.copy()
            results_df['Prediction'] = predictions
            results_df['Failure_Risk_%'] = probabilities[:, 1] * 100
            results_df['Status'] = results_df['Prediction'].apply(
                lambda x: "🟒 HEALTHY" if x == 0 else "πŸ”΄ FAULTY"
            )

            st.success("βœ“ Predictions completed!")
            st.dataframe(results_df)

            # Download results
            csv = results_df.to_csv(index=False)
            st.download_button(
                label="πŸ“₯ Download Predictions",
                data=csv,
                file_name=f"predictions_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
                mime="text/csv"
            )

# ============================================
# INFO SECTION
# ============================================
st.sidebar.markdown("---")
st.sidebar.header("ℹ️ About This Model")
st.sidebar.info("""
**Physics-Aware Predictive Maintenance System**

- **Training Data**: 19,535 engine observations
- **Features**: 9 (6 raw + 3 engineered)
- **Target**: Binary classification (Healthy/Faulty)
- **Primary Metric**: F2-Score (recall-focused)
- **Calibration**: Brier Score optimized

**Key Features:**
- Lubrication Stress Index
- Thermal Efficiency
- Power Load Index
""")

st.sidebar.markdown("---")
st.sidebar.caption("Β© 2026 Predictive Maintenance System v1.0")