-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
632 lines (548 loc) ยท 30.6 KB
/
Copy pathdashboard.py
File metadata and controls
632 lines (548 loc) ยท 30.6 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import time
import pandas as pd
import streamlit as st
import plotly.express as px
import requests
from datetime import datetime, timedelta, timezone
import streamlit.components.v1 as components
# ---------------------------------------------------------
# 1. PAGE CONFIG & THEME SETUP
# ---------------------------------------------------------
st.set_page_config(page_title="AR Diagnostic Dashboard", layout="wide", page_icon="ARVIS2.png", initial_sidebar_state="expanded")
# Custom CSS for a sleek dark theme feel
st.markdown("""
<style>
.reportview-container { background: #0e1117; }
.sidebar .sidebar-content { background: #262730; }
h1, h2, h3 { color: #00ffcc !important; }
.stMetric label { color: #a1a1a1 !important; }
</style>
""", unsafe_allow_html=True)
FIREBASE_DB_URL = "https://arapp-feb0f-default-rtdb.firebaseio.com/"
@st.cache_resource
def get_http_session():
""" ๐ข FIX: Global HTTP Session to prevent recreating TLS handshakes every 1.5 seconds.
This massively speeds up Render free-tier fetching! """
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10)
session.mount('https://', adapter)
return session
# ---------------------------------------------------------
# 2. HELPER FUNCTIONS
# ---------------------------------------------------------
def add_breaks_for_gaps(df, threshold_seconds=5):
""" Prevents Plotly from drawing straight lines across missing data periods """
if df.empty: return df
df = df.sort_values("timestamp")
df['time_diff'] = df['timestamp'].diff().dt.total_seconds()
gap_mask = df['time_diff'] > threshold_seconds
gap_rows = []
for idx, row in df[gap_mask].iterrows():
gap_row = row.copy()
for col in df.columns:
if col not in ['timestamp', 'time_diff', 'device_id']:
gap_row[col] = None
gap_row['timestamp'] = row['timestamp'] - timedelta(seconds=1)
gap_rows.append(gap_row)
if gap_rows:
df_gaps = pd.DataFrame(gap_rows)
df_final = pd.concat([df, df_gaps], ignore_index=True).sort_values("timestamp")
return df_final.drop(columns=['time_diff'])
return df.drop(columns=['time_diff'])
def format_offline_duration(seconds):
if seconds < 0: seconds = 0
m, s = divmod(int(seconds), 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
mo, d = divmod(d, 30)
y, mo = divmod(mo, 12)
parts = []
if y > 0: parts.append(f"{y} year{'s' if y != 1 else ''}")
if mo > 0: parts.append(f"{mo} month{'s' if mo != 1 else ''}")
if d > 0: parts.append(f"{d} day{'s' if d != 1 else ''}")
if h > 0: parts.append(f"{h} hour{'s' if h != 1 else ''}")
if m > 0: parts.append(f"{m} minute{'s' if m != 1 else ''}")
if s > 0 or len(parts) == 0: parts.append(f"{s} second{'s' if s != 1 else ''}")
return ", ".join(parts)
@st.cache_data(ttl=3)
def get_devices():
try:
res = get_http_session().get(f"{FIREBASE_DB_URL}live.json?shallow=true", timeout=3.0)
if res.status_code == 200 and res.json():
return list(res.json().keys())
except: pass
return []
def get_live_data(device_id):
try:
# ๐ข FIX: Use pooled session for lightning-fast fetching
res = get_http_session().get(f"{FIREBASE_DB_URL}live/{device_id}.json", timeout=1.5)
if res.status_code == 200: return res.json()
except: pass
return None
def get_recent_history_data(device_id):
try:
# ๐ข BULK INCREMENTAL FETCH (BACKWARD COMPATIBLE)
# Because your Render backend hasn't been updated to the Append-Only architecture,
# we CANNOT use `startAt` (it skips packets that Render inserts into the past).
# Instead, we brute-force pull the newest 800 packets (approx 6.5 minutes of cache)
# every cycle. This effortlessly absorbs the 1-minute disconnects you are testing!
url = f"{FIREBASE_DB_URL}history/{device_id}.json?orderBy=\"$key\"&limitToLast=800"
res = get_http_session().get(url, timeout=3.0)
if res.status_code == 200 and res.json():
data = res.json()
records = list(data.values())
df = pd.DataFrame(records)
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
except: pass
return pd.DataFrame()
def get_full_history_data(device_id):
""" Only called ONCE when the dashboard first loads to build the initial 3-hour cache """
try:
res = get_http_session().get(f"{FIREBASE_DB_URL}history/{device_id}.json?orderBy=\"$key\"&limitToLast=6000", timeout=10.0)
if res.status_code == 200 and res.json():
data = res.json()
records = list(data.values())
df = pd.DataFrame(records)
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
except: pass
return pd.DataFrame()
# ---------------------------------------------------------
# 3. SIDEBAR (FILLED WITH CONTEXT)
# ---------------------------------------------------------
with st.sidebar:
# ๐ข FIX: Use columns to perfectly center the new transparent logo and make it larger!
c1, c2, c3 = st.columns([1, 3, 1])
with c2:
st.image("ARVIS2.png")
st.title("Vehicle Profile")
devices = get_devices()
device_id = st.selectbox("Active Device", devices) if devices else None
# ๐ข NEW: Clear Device History Button
if device_id:
with st.expander("๐๏ธ Clear Device History"):
st.error(f"โ ๏ธ **WARNING:** This will permanently delete ALL data for **{device_id}**! This action cannot be undone.")
if st.button("Confirm Delete", use_container_width=True, type="primary"):
try:
get_http_session().delete(f"{FIREBASE_DB_URL}history/{device_id}.json")
get_http_session().delete(f"{FIREBASE_DB_URL}live/{device_id}.json")
if "full_history_df" in st.session_state:
del st.session_state.full_history_df
st.toast(f"โ
History for {device_id} cleared successfully!")
st.rerun()
except Exception as e:
st.error("Failed to clear history")
st.divider()
st.markdown("### ๐ Suzuki Alto 800")
st.markdown("- **Engine:** F8D (796cc 3-Cylinder)")
st.markdown("- **System:** Speed-Density (MAP)")
st.markdown("- **Protocol:** CAN 500kbps 11-bit")
st.divider()
st.markdown("### ๐ค ML Architecture")
st.markdown("- **Model:** Predictive Diagnostic Net v1")
st.markdown("- **Target Classes:** 9 Subsystems")
st.markdown("- **Update Rate:** 2Hz (500ms)")
# ---------------------------------------------------------
# 4. DATA FETCHING & STATUS LOGIC
# ---------------------------------------------------------
st.title("๐ ARVIS Dashboard")
if device_id:
# 1. FETCH FULL HISTORY ONCE
if "full_history_df" not in st.session_state:
df = get_full_history_data(device_id)
st.session_state.full_history_df = df.copy()
# 2. FETCH INCREMENTAL CACHE (BULK COMPATIBILITY MODE)
recent_df = get_recent_history_data(device_id)
# 3. STACK AND TRIM
if not recent_df.empty:
combined = pd.concat([st.session_state.full_history_df, recent_df])
combined = combined.drop_duplicates(subset=['timestamp']).sort_values('timestamp')
two_hours_ago = combined['timestamp'].max() - timedelta(hours=3)
st.session_state.full_history_df = combined[combined['timestamp'] >= two_hours_ago]
df = st.session_state.get("full_history_df", pd.DataFrame())
# 2. FETCH LIVE
latest_raw = get_live_data(device_id)
latest = latest_raw if latest_raw else {}
# 3. CROSS-REFERENCE AND CALCULATE STRICT OBD AGE
try:
current_packet_time = latest.get("timestamp", "")
# Override with history if it's fresher (bypasses broken Live nodes instantly)
if not df.empty:
freshest_history_time = str(df['timestamp'].max())
if freshest_history_time > current_packet_time:
latest = df.iloc[-1].to_dict()
current_packet_time = str(latest.get("timestamp", ""))
# ๐ข STRICT OBD PACKET AGE
# We no longer trust the server arrival time. We calculate exactly how old the
# data is based purely on when it was generated by the car.
packet_utc = pd.to_datetime(current_packet_time) - timedelta(hours=5)
absolute_seconds_ago = (datetime.now(timezone.utc).replace(tzinfo=None) - packet_utc).total_seconds()
# Prevent negative seconds if phone clock is a fraction of a second fast
seconds_ago = max(0.0, absolute_seconds_ago)
# ๐ข USER REQUIREMENT: "if data is 4 seconds old maximum, it should not be considered live"
is_online = seconds_ago <= 15
is_display_fresh = seconds_ago <= 6.0
is_actually_live = seconds_ago <= 4.0
except Exception as e:
is_online = False
is_display_fresh = False
is_actually_live = False
seconds_ago = 9999
# Ensure ALL columns exist to prevent crashes
expected_cols = ["RPM", "Speed", "CoolantTemp", "EngineLoad", "Voltage",
"IntakeTemp", "MAF", "ThrottlePos", "OilTemp", "MAP",
"FuelLevel", "STFT", "LTFT", "O2Voltage",
"ml_status", "ml_alert"]
if not df.empty:
for col in expected_cols:
if col not in df.columns:
df[col] = "Healthy" if col == "ml_status" else "None" if col == "ml_alert" else 0.0
if not latest:
is_online = False
is_display_fresh = False
is_actually_live = False
latest = None
seconds_ago = 9999
else:
is_online = False
is_display_fresh = False
is_actually_live = False
latest = None
df = pd.DataFrame()
seconds_ago = 9999
# Status Banner
if is_online:
if is_actually_live:
st.success("๐ข **SYSTEM ONLINE** โ Live Data Streaming Active")
else:
st.warning(f"๐ก **DATA DELAYED** โ Last packet received {int(seconds_ago)}s ago. Waiting for live sync...")
else:
if latest:
offline_text = format_offline_duration(seconds_ago)
st.error(f"๐ด **SYSTEM OFFLINE** โ Connection lost for {offline_text}")
else:
st.error("๐ด **SYSTEM OFFLINE** โ No vehicle connected.")
# ---------------------------------------------------------
# 5. PRE-CALCULATE ALERTS FOR TAB NOTIFICATIONS
# ---------------------------------------------------------
confirmed_alerts = []
if not df.empty and "ml_prediction" in df.columns:
try:
df_alerts = df.copy()
df_alerts['ml_prediction'] = df_alerts['ml_prediction'].astype(str).str.split(',')
df_alerts = df_alerts.explode('ml_prediction')
df_alerts['ml_prediction'] = df_alerts['ml_prediction'].str.strip()
df_faults = df_alerts[~df_alerts['ml_prediction'].str.contains("Healthy", na=False, case=False)].copy()
if not df_faults.empty:
for alert_type, alert_group in df_faults.groupby('ml_prediction'):
alert_group = alert_group.sort_values('timestamp')
alert_group['time_diff'] = alert_group['timestamp'].diff().dt.total_seconds()
alert_group['Block'] = (alert_group['time_diff'] > 15).cumsum()
for block_id, group in alert_group.groupby('Block'):
if len(group) >= 3:
start_time = group['timestamp'].iloc[0]
end_time = group['timestamp'].iloc[-1]
clean_alert_name = alert_type.replace("_", " ")
t_start = pd.to_datetime(start_time)
t_end = pd.to_datetime(end_time)
exact_seconds = (t_end - t_start).total_seconds()
if exact_seconds < 1: exact_seconds = len(group) * 1.5
max_db_time = pd.to_datetime(df['timestamp'].max())
# ๐ข FIX: Handle OBD Disconnection during active alert!
is_active = False
was_disconnected = False
if (max_db_time - t_end).total_seconds() <= 5:
if is_online:
is_active = True
else:
was_disconnected = True
confirmed_alerts.append({
"Start": start_time,
"End": end_time,
"Alert": clean_alert_name,
"DurationSeconds": exact_seconds,
"IsActive": is_active,
"WasDisconnected": was_disconnected
})
confirmed_alerts.sort(key=lambda x: x['End'], reverse=True)
except Exception as e:
pass
# ๐ข FIX: We CANNOT dynamically change Tab Names in Streamlit!
# If the tab name changes from "Alerts (1)" to "Alerts (0)", Streamlit destroys the tab
# and violently kicks the user back to Tab 1.
# To fix the jumping bug, the tab names MUST remain static!
active_alerts_count = sum(1 for a in confirmed_alerts if a['IsActive'])
alert_badge = f"{active_alerts_count}" if active_alerts_count <= 9 else "9+"
future_rul_status = latest.get("ml_future_status", "Healthy") if latest else "Healthy"
future_alerts_count = 1 if future_rul_status == "Degrading" else 0
future_badge = f"{future_alerts_count}" if future_alerts_count <= 9 else "9+"
# ๐ข NEW: GLOBAL FLOATING ALERTS (TOP RIGHT)
has_floats = False
floating_html = "<div style='position: fixed; top: 60px; right: 20px; z-index: 999999; display: flex; flex-direction: column; gap: 10px;'>"
# We must collect the JS code separately so Streamlit doesn't strip it!
js_scripts = ""
for alert in confirmed_alerts:
if alert['IsActive'] and alert['DurationSeconds'] <= 25.0:
has_floats = True
raw_id = f"{alert['Alert']}_{str(alert['Start'])}"
safe_id = raw_id.replace(' ', '_').replace('-', '_').replace(':', '_').replace('.', '_')
# ๐ข FIX: Remove all indentation so Streamlit does NOT render this as a raw <pre> code block!
floating_html += f"""
<div id="float_{safe_id}" style="background: linear-gradient(135deg, #ff4b4b 0%, #b30000 100%); color: white; padding: 15px; border-radius: 10px; box-shadow: 0px 8px 16px rgba(0,0,0,0.5); border: 2px solid white; width: 300px; display: block;">
<div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.4); padding-bottom: 8px; margin-bottom: 8px;">
<span style="font-weight: bold; font-size: 12px; letter-spacing: 1px;">โ ๏ธ ENGINE FAULT DETECTED</span>
<span id="close_{safe_id}" style="cursor: pointer; font-size: 14px; background: rgba(0,0,0,0.3); padding: 4px 8px; border-radius: 5px;">โ</span>
</div>
<div style="font-size: 16px; font-weight: bold;">{alert['Alert']}</div>
</div>
"""
# ๐ข FIX: Break out of the components iframe to access the parent Streamlit DOM!
js_scripts += f"""
// Hide immediately if already dismissed
if (session.getItem('dismiss_{safe_id}') === 'true') {{
const el = parent.getElementById('float_{safe_id}');
if (el) el.style.display = 'none';
}}
// Bind click event natively
const btn = parent.getElementById('close_{safe_id}');
if (btn) {{
btn.onclick = function() {{
session.setItem('dismiss_{safe_id}', 'true');
parent.getElementById('float_{safe_id}').style.display = 'none';
}};
}}
"""
floating_html += "</div>"
# ---------------------------------------------------------
# 6. TABBED INTERFACE
# ---------------------------------------------------------
tab1, tab2, tab3, tab4, tab5 = st.tabs(["๐ Live Metrics", "๐ Graphs", "๐ Raw Historical Data", "๐จ Alerts", "๐ฎ Future Alerts"])
# ================= TAB 1: LIVE METRICS =================
with tab1:
st.subheader("Real-Time Engine Status")
if latest and is_online and is_display_fresh:
c1, c2, c3, c4 = st.columns(4)
c1.metric("RPM", int(latest.get("RPM", 0)))
c2.metric("Speed", f"{int(latest.get('Speed', 0))} km/h")
c3.metric("Engine Load", f"{float(latest.get('EngineLoad', 0))} %")
c4.metric("Throttle", f"{float(latest.get('ThrottlePos', 0))} %")
c5, c6, c7, c8 = st.columns(4)
c5.metric("Coolant Temp", f"{float(latest.get('CoolantTemp', 0))} ยฐC")
c6.metric("Oil Temp", f"{float(latest.get('OilTemp', 0))} ยฐC")
c7.metric("Intake Temp", f"{float(latest.get('IntakeTemp', 0))} ยฐC")
c8.metric("Voltage", f"{float(latest.get('Voltage', 0))} V")
c9, c10, c11, c12 = st.columns(4)
c9.metric("MAP Pressure", f"{float(latest.get('MAP', 0))} kPa")
c10.metric("MAF Airflow", f"{float(latest.get('MAF', 0))} g/s")
c11.metric("STFT / LTFT", f"{float(latest.get('STFT', 0))}% / {float(latest.get('LTFT', 0))}%")
c12.metric("O2 Sensor", f"{float(latest.get('O2Voltage', 0))} V")
else:
# Show stale indicators when the feed pauses > 4 seconds
c1, c2, c3, c4 = st.columns(4)
c1.metric("RPM", "--"); c2.metric("Speed", "-- km/h"); c3.metric("Engine Load", "-- %"); c4.metric("Throttle", "-- %")
c5, c6, c7, c8 = st.columns(4)
c5.metric("Coolant Temp", "-- ยฐC"); c6.metric("Oil Temp", "-- ยฐC"); c7.metric("Intake Temp", "-- ยฐC"); c8.metric("Voltage", "-- V")
c9, c10, c11, c12 = st.columns(4)
c9.metric("MAP Pressure", "-- kPa"); c10.metric("MAF Airflow", "-- g/s"); c11.metric("STFT / LTFT", "--% / --%"); c12.metric("O2 Sensor", "-- V")
# ================= TAB 2: GRAPHS (LAST 5 MINS) =================
with tab2:
if not df.empty:
# STRICT 5-MINUTE WINDOW CUTOFF
five_mins_ago = df["timestamp"].max() - timedelta(minutes=5)
df_graphs = df[df["timestamp"] >= five_mins_ago].copy()
df_plot = add_breaks_for_gaps(df_graphs, threshold_seconds=5)
# ๐ข FIX: Drastic Performance Optimization
# We completely removed Plotly (which is extremely heavy for the server)
# and replaced it with Streamlit's native Altair line_charts.
# This shifts the rendering load to the browser, making it run lightning-fast!
g1, g2, g3 = st.columns(3)
with g1:
st.markdown("###### Engine RPM")
st.line_chart(df_plot, x="timestamp", y="RPM", color="#FF4B4B", height=200, width='stretch')
st.markdown("###### Coolant Temp (ยฐC)")
st.line_chart(df_plot, x="timestamp", y="CoolantTemp", color="#FFA500", height=200, width='stretch')
st.markdown("###### MAP Pressure (kPa)")
st.line_chart(df_plot, x="timestamp", y="MAP", color="#AB63FA", height=200, width='stretch')
st.markdown("###### Short Term Fuel Trim (%)")
st.line_chart(df_plot, x="timestamp", y="STFT", color="#E2D9F3", height=200, width='stretch')
with g2:
st.markdown("###### Vehicle Speed (km/h)")
st.line_chart(df_plot, x="timestamp", y="Speed", color="#00CC96", height=200, width='stretch')
st.markdown("###### Oil Temp (ยฐC)")
st.line_chart(df_plot, x="timestamp", y="OilTemp", color="#F4D03F", height=200, width='stretch')
st.markdown("###### Intake Temp (ยฐC)")
st.line_chart(df_plot, x="timestamp", y="IntakeTemp", color="#58D68D", height=200, width='stretch')
st.markdown("###### Long Term Fuel Trim (%)")
st.line_chart(df_plot, x="timestamp", y="LTFT", color="#A569BD", height=200, width='stretch')
with g3:
st.markdown("###### Engine Load (%)")
st.line_chart(df_plot, x="timestamp", y="EngineLoad", color="#636EFA", height=200, width='stretch')
st.markdown("###### Throttle Position (%)")
st.line_chart(df_plot, x="timestamp", y="ThrottlePos", color="#1ABC9C", height=200, width='stretch')
st.markdown("###### Battery Voltage (V)")
st.line_chart(df_plot, x="timestamp", y="Voltage", color="#F39C12", height=200, width='stretch')
st.markdown("###### O2 Sensor (V)")
st.line_chart(df_plot, x="timestamp", y="O2Voltage", color="#E74C3C", height=200, width='stretch')
else:
st.info("No historical data available yet. Start the engine to generate graphs!")
# ================= TAB 3: TABULAR DATA =================
with tab3:
st.subheader("Historical Telemetry Log")
if not df.empty:
df_table = df.copy()
# Clean up the format so it's not messy!
# The timestamp is already in Local Time from the phone
df_table['Date'] = df_table['timestamp'].dt.strftime('%Y-%m-%d')
df_table['Time (Local)'] = df_table['timestamp'].dt.strftime('%H:%M:%S')
# Reorder columns to put Date and Time first, drop the raw timestamp
cols = ['Date', 'Time (Local)'] + [c for c in df_table.columns if c not in ['Date', 'Time (Local)', 'timestamp']]
df_table = df_table[cols]
st.caption("Displaying the full 3-hour history seamlessly from the local memory cache.")
# Display perfectly sorted, most recent first, without the ugly index column
st.dataframe(df_table.sort_values(["Date", "Time (Local)"], ascending=[False, False]), hide_index=True, width='stretch')
else:
st.info("Database is entirely blank. No historical logs exist.")
# ๐ข NEW: Helper to map ML predictions to physical AR Targets or locations
def get_component_location(problem_name):
p = problem_name.lower()
# 1. Map to the 9 Tracked AR Components
if "battery" in p:
return "๐ AR Target: Battery"
elif "head gasket" in p or "misfire" in p or "vacuum leak" in p:
return "โ๏ธ AR Target: Main Engine"
elif "air filter" in p:
return "๐จ AR Target: Air Filter"
elif "overheat" in p or "coolant" in p or "radiator" in p:
return "๐ก๏ธ AR Target: Radiator / Coolant"
# 2. Map untracked components to physical engine bay locations
elif "alternator" in p:
return "๐ Location: Lower-left side of the main engine block, driven by the serpentine belt."
elif "water pump" in p:
return "๐ Location: Front-left side of the engine block, attached to the belt system."
elif "fuel pump" in p:
return "๐ Location: Underneath the rear passenger seat / top of the fuel tank at the back of the car."
elif "catalytic converter" in p:
return "๐ Location: Underneath the car, attached to the exhaust pipe right below the front of the engine."
elif "oxygen sensor" in p or "o2" in p:
return "๐ Location: Screwed into the exhaust manifold, clearly visible at the front/bottom of the engine block."
else:
return "๐ Location: Check Main Engine compartment."
# ================= TAB 4: ALERTS =================
with tab4:
# ๐ข NEW: Display the alert count safely INSIDE the tab to prevent jumping
if active_alerts_count > 0:
st.markdown(f"<h3 style='color: #ff4b4b;'>๐จ {active_alerts_count} Active Alerts Happening Now</h3>", unsafe_allow_html=True)
else:
st.subheader("Historical ML Alerts (Last 7 Days)")
st.markdown("Automated AI Diagnostic engine scanning telemetry history to isolate confirmed component failures.")
if not df.empty and "ml_prediction" in df.columns:
if len(confirmed_alerts) == 0:
st.success("โ
**No confirmed alerts.** (Some minor sensor edges were detected but discarded as noise).")
else:
for alert in confirmed_alerts:
icon = "๐ฅ" if "Overheating" in alert["Alert"] else "โก" if "Alternator" in alert["Alert"] else "๐จ"
duration_text = format_offline_duration(alert['DurationSeconds'])
# Dynamic Styling based on Active vs Resolved state
if alert['IsActive']:
status_badge = "<span style='background-color: #ff4b4b; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: bold; margin-left: 10px; border: 1px solid white;'>๐ด HAPPENING NOW</span>"
time_text = f"<b>Started:</b> {alert['Start']} (Ongoing for {duration_text})"
border_color = "#ff4b4b"
bg_color = "#631313"
elif alert.get('WasDisconnected', False):
# ๐ข FIX: Explicitly indicate if the OBD disconnected during the fault
status_badge = "<span style='background-color: #f39c12; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; margin-left: 10px;'>๐ RESOLVED (OBD DISCONNECTED)</span>"
time_text = f"<b>Time:</b> {alert['Start']} to {alert['End']}<br><b>Total Duration:</b> {duration_text} before signal loss"
border_color = "#f39c12"
bg_color = "#333"
else:
status_badge = "<span style='background-color: #555; color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; margin-left: 10px;'>โ
RESOLVED</span>"
time_text = f"<b>Time:</b> {alert['Start']} to {alert['End']}<br><b>Total Duration:</b> {duration_text}"
border_color = "#555"
bg_color = "#333"
st.markdown(f"""
<div style="background-color: {bg_color}; padding: 15px; border-radius: 10px; margin-bottom: 10px; border-left: 5px solid {border_color};">
<h4 style="margin: 0; color: white;">{icon} {alert['Alert']} {status_badge}</h4>
<p style="margin: 5px 0 0 0; color: #d1d1d1; font-size: 14px;">
<b>Component Affected:</b> {get_component_location(alert['Alert'])}<br>
{time_text}
</p>
</div>
""", unsafe_allow_html=True)
else:
st.info("Waiting for data to run diagnostics...")
# ================= TAB 5: FUTURE ALERTS (PREDICTIVE MAINTENANCE) =================
with tab5:
if future_alerts_count > 0:
st.markdown(f"<h3 style='color: #f39c12;'>๐ฎ {future_alerts_count} Predictive Alerts</h3>", unsafe_allow_html=True)
else:
st.subheader("๐ฎ Predictive Maintenance (Remaining Useful Life)")
st.markdown("Advanced ML Regression Engine actively monitoring long-term sensor degradation slopes to predict failures BEFORE they happen.")
# ๐ข FUTURE PROOFING: This tab is structurally ready to accept the JSON probability arrays
# from the new ML model once training is approved and complete!
if latest and is_online:
# Example of how the future banner will appear based on the upcoming ML regression model
future_rul_status = latest.get("ml_future_status", "Healthy")
future_rul_component = latest.get("ml_future_component", "None")
future_rul_hours = latest.get("ml_future_hours", 0)
if future_rul_status == "Degrading":
components_list = future_rul_component.split(",")
for comp in components_list:
# 1. Format the Component Name gracefully
friendly_name = comp.strip().replace("_", " ")
if "Filter" in friendly_name:
future_problem = "Severe Air Filter Clogging"
elif "Alternator" in friendly_name:
future_problem = "Complete Alternator Failure"
elif "Pump" in friendly_name:
future_problem = "Water Pump Seizure (Engine Overheating)"
else:
future_problem = friendly_name + " Failure"
# 2. Calculate Days
try:
hours_float = float(future_rul_hours)
days_left = round(hours_float / 24.0, 1)
time_estimate = f"{days_left} Days ({hours_float} Hours)"
except:
time_estimate = f"{future_rul_hours} Hours"
st.markdown(f"""
<div style="background-color: #3b2a0c; padding: 15px; border-radius: 10px; margin-bottom: 10px; border-left: 5px solid #f39c12;">
<h4 style="margin: 0; color: #ffb74d;">โณ PREDICTIVE WARNING: {future_problem}</h4>
<p style="margin: 5px 0 0 0; color: #d1d1d1; font-size: 14px;">
<b>Component Affected:</b> {get_component_location(friendly_name)}<br>
<b>Analysis:</b> The ML Regression model has detected a slow, continuous drift in sensor data indicating the <b>{friendly_name}</b> is actively wearing out.<br>
<b>Time to Failure:</b> {time_estimate} left of safe driving.<br>
<b>Action Required:</b> Schedule a replacement for the {friendly_name} before the estimated timeframe to avoid a roadside breakdown.
</p>
</div>
""", unsafe_allow_html=True)
else:
st.success("โ
**No Future Faults Predicted** โ All component degradation slopes are within factory tolerances.")
else:
st.info("Awaiting live telemetry to calculate degradation slopes...")
# ---------------------------------------------------------
# 7. INJECT GLOBAL FLOATING UI ELEMENTS (BOTTOM OF DOM)
# ---------------------------------------------------------
# ๐ข FIX: Moved the floating UI rendering to the absolute bottom of the Streamlit DOM!
# Injecting UI elements above the tabs dynamically shifts the entire Streamlit component tree,
# which causes the tab jumping bug and pushes the entire interface down!
st.markdown(floating_html if has_floats else "<div style='display:none;'></div>", unsafe_allow_html=True)
components.html(f"""
<script>
const parent = window.parent.document;
const session = window.parent.sessionStorage;
{js_scripts}
</script>
""" if has_floats else "<script></script>", height=0)
# ---------------------------------------------------------
# 8. AUTO-REFRESH LOGIC
# ---------------------------------------------------------
# ๐ข FIX: Optimized Refresh Rates for Continuous Flow
if is_online:
# ๐ข FIX: Streamlit's internal execution and network roundtrip takes ~0.5s to 1.0s.
# To achieve a TRUE 1.5s update interval on the screen, we sleep for exactly 0.5s!
time.sleep(0.5)
st.rerun()
else:
time.sleep(1.5) # Faster offline recovery polling
st.rerun()