File size: 7,286 Bytes
b033899
36e3d98
 
b033899
36e3d98
 
b033899
df84bf4
2ba6522
b033899
 
 
 
36e3d98
b033899
 
 
 
 
 
 
 
 
36e3d98
 
b033899
fdb8446
 
 
 
2ba6522
 
fdb8446
2ba6522
 
fdb8446
 
 
 
2ba6522
fdb8446
24f2130
2ba6522
24f2130
b033899
 
 
 
36e3d98
b033899
 
36e3d98
b033899
 
36e3d98
b033899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ba6522
b033899
 
2ba6522
b033899
 
 
 
 
 
 
 
 
2ba6522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b033899
 
 
 
2ba6522
 
b033899
2ba6522
b033899
 
 
2ba6522
b033899
 
2ba6522
 
 
b033899
2ba6522
 
b033899
 
2ba6522
 
 
b033899
 
2ba6522
 
 
 
 
 
 
 
 
 
 
 
b033899
36e3d98
 
 
 
 
 
 
 
b033899
36e3d98
2ba6522
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b033899
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

import streamlit as st
import pandas as pd
import numpy as np
import joblib
from huggingface_hub import hf_hub_download
import json
import os
import plotly.graph_objects as go

# =============================================================================
# STREAMLIT CONFIG
# =============================================================================

st.set_page_config(
    page_title="Predictive Maintenance",
    layout="wide",
    page_icon="🛠️"
)

# =============================================================================
# LOAD MODEL
# =============================================================================

@st.cache_resource
def load_artifacts():
    try:
        repo_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, True

    except Exception as e:
        st.error(f"❌ Error loading model: {e}")
        return None, None, {}, False

model, scaler, metadata, MODEL_LOADED = load_artifacts()
MODEL_NAME = metadata.get("model_name", "Predictive Maintenance Model")

# =============================================================================
# FEATURE ENGINEERING
# =============================================================================

def engineer_features(df):
    df = df.copy()

    df["temp_pressure_ratio"] = df["coolant_temp"] / (df["coolant_pressure"] + 1e-6)
    df["oil_temp_pressure_ratio"] = df["lub_oil_temp"] / (df["lub_oil_pressure"] + 1e-6)

    df["pressure_diff_oil_coolant"] = df["lub_oil_pressure"] - df["coolant_pressure"]
    df["pressure_diff_fuel_oil"] = df["fuel_pressure"] - df["lub_oil_pressure"]

    df["temp_diff_oil_coolant"] = df["lub_oil_temp"] - df["coolant_temp"]

    df["avg_temp"] = (df["lub_oil_temp"] + df["coolant_temp"]) / 2
    df["avg_pressure"] = (
        df["lub_oil_pressure"] +
        df["fuel_pressure"] +
        df["coolant_pressure"]
    ) / 3

    df["high_rpm"] = (df["engine_rpm"] > 934).astype(int)
    df["high_temp"] = (df["coolant_temp"] > 82.9).astype(int)
    df["operating_stress"] = df["high_rpm"] * df["high_temp"]
    df["low_oil_pressure"] = (df["lub_oil_pressure"] < 2.52).astype(int)

    return df

# =============================================================================
# PREDICTION
# =============================================================================

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"):
        confidence = model.predict_proba(X_scaled)[0][pred]
    else:
        confidence = 0.85

    return 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 fig

def 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,
        "fuel_pressure": fuel_pressure,
        "coolant_pressure": coolant_pressure,
        "lub_oil_temp": lub_oil_temp,
        "coolant_temp": coolant_temp
    }])

    pred, 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
        )
    )