krupal02 commited on
Commit
f45c73e
·
verified ·
1 Parent(s): 0b128b7

Upload streamlit_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. streamlit_app.py +628 -0
streamlit_app.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ from ultralytics import YOLO
5
+ import requests
6
+ import math
7
+ import time
8
+ import os
9
+ from tempfile import NamedTemporaryFile
10
+ import folium
11
+ from streamlit_folium import st_folium
12
+
13
+ # ============================================================
14
+ # CONFIGURATION
15
+ # ============================================================
16
+ MODEL_PATH = "model/best.pt"
17
+ CLASS_NAMES = {0: "Accident", 1: "Non-accident", 2: "Fire"}
18
+ ALERT_CLASSES = {"Accident", "Fire"}
19
+ DEFAULT_CONFIDENCE = 0.3
20
+ HOSPITAL_RADIUS_M = 5000
21
+
22
+ # ============================================================
23
+ # PAGE CONFIG
24
+ # ============================================================
25
+ st.set_page_config(
26
+ page_title="AccidentAI — Real-Time Detection & Alert",
27
+ page_icon="🚨",
28
+ layout="wide",
29
+ initial_sidebar_state="expanded",
30
+ )
31
+
32
+ # ============================================================
33
+ # CUSTOM CSS
34
+ # ============================================================
35
+ st.markdown("""
36
+ <style>
37
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap');
38
+
39
+ html, body, .stApp {
40
+ font-family: 'Inter', sans-serif !important;
41
+ }
42
+
43
+ /* Hero */
44
+ .hero-wrap {
45
+ text-align: center;
46
+ padding: 2.5rem 1rem 1.5rem;
47
+ }
48
+ .hero-wrap h1 {
49
+ font-size: 2.8rem;
50
+ font-weight: 900;
51
+ background: linear-gradient(135deg, #ff3b30, #ff9500, #ff3b30);
52
+ background-size: 200% 200%;
53
+ -webkit-background-clip: text;
54
+ -webkit-text-fill-color: transparent;
55
+ animation: grad 4s ease infinite;
56
+ margin-bottom: 0.25rem;
57
+ }
58
+ @keyframes grad {
59
+ 0% { background-position: 0% 50%; }
60
+ 50% { background-position: 100% 50%; }
61
+ 100% { background-position: 0% 50%; }
62
+ }
63
+ .hero-wrap .subtitle {
64
+ font-size: 1.1rem;
65
+ color: #aaa;
66
+ font-weight: 400;
67
+ }
68
+ .hero-wrap .pills {
69
+ margin-top: 0.75rem;
70
+ display: flex;
71
+ gap: 0.5rem;
72
+ justify-content: center;
73
+ flex-wrap: wrap;
74
+ }
75
+ .hero-wrap .pill {
76
+ background: rgba(255,59,48,0.12);
77
+ border: 1px solid rgba(255,59,48,0.25);
78
+ color: #ff6b5e;
79
+ padding: 0.3rem 0.85rem;
80
+ border-radius: 999px;
81
+ font-size: 0.78rem;
82
+ font-weight: 500;
83
+ }
84
+
85
+ /* Glass card */
86
+ .glass {
87
+ background: rgba(255,255,255,0.04);
88
+ border: 1px solid rgba(255,255,255,0.08);
89
+ border-radius: 16px;
90
+ padding: 1.5rem;
91
+ backdrop-filter: blur(12px);
92
+ margin-bottom: 1rem;
93
+ }
94
+
95
+ /* Stat box */
96
+ .stat-row {
97
+ display: flex;
98
+ gap: 1rem;
99
+ flex-wrap: wrap;
100
+ margin: 0.5rem 0;
101
+ }
102
+ .stat-box {
103
+ flex: 1;
104
+ min-width: 120px;
105
+ text-align: center;
106
+ background: rgba(255,255,255,0.04);
107
+ border: 1px solid rgba(255,255,255,0.08);
108
+ border-radius: 12px;
109
+ padding: 1rem 0.75rem;
110
+ }
111
+ .stat-box .num {
112
+ font-size: 1.8rem;
113
+ font-weight: 700;
114
+ }
115
+ .stat-box .lbl {
116
+ font-size: 0.75rem;
117
+ color: #888;
118
+ text-transform: uppercase;
119
+ letter-spacing: 0.05em;
120
+ }
121
+
122
+ /* Alert banner */
123
+ @keyframes pulse-border {
124
+ 0%, 100% { border-color: rgba(255,59,48,0.25); }
125
+ 50% { border-color: rgba(255,59,48,0.65); }
126
+ }
127
+ .alert-banner {
128
+ background: linear-gradient(135deg, rgba(255,59,48,0.10), rgba(255,149,0,0.06));
129
+ border: 2px solid rgba(255,59,48,0.35);
130
+ border-radius: 14px;
131
+ padding: 1.25rem 1.5rem;
132
+ animation: pulse-border 2s ease infinite;
133
+ margin-bottom: 1rem;
134
+ }
135
+ .alert-banner h3 {
136
+ margin: 0 0 0.25rem;
137
+ color: #ff5e57;
138
+ }
139
+ .alert-banner p {
140
+ margin: 0;
141
+ color: #ccc;
142
+ font-size: 0.92rem;
143
+ }
144
+
145
+ /* Hospital card */
146
+ .hosp-card {
147
+ background: rgba(255,255,255,0.04);
148
+ border: 1px solid rgba(255,255,255,0.09);
149
+ border-radius: 12px;
150
+ padding: 1rem 1.25rem;
151
+ margin-bottom: 0.65rem;
152
+ transition: border-color 0.25s;
153
+ }
154
+ .hosp-card:hover {
155
+ border-color: rgba(52,199,89,0.45);
156
+ }
157
+ .hosp-card .name {
158
+ font-weight: 600;
159
+ font-size: 1rem;
160
+ color: #e0e0e0;
161
+ }
162
+ .hosp-card .meta {
163
+ font-size: 0.82rem;
164
+ color: #999;
165
+ margin-top: 0.25rem;
166
+ }
167
+
168
+ /* Notification log entry */
169
+ .notif-entry {
170
+ display: flex;
171
+ align-items: center;
172
+ gap: 0.6rem;
173
+ padding: 0.6rem 1rem;
174
+ border-radius: 10px;
175
+ margin-bottom: 0.4rem;
176
+ font-size: 0.88rem;
177
+ }
178
+ .notif-ok {
179
+ background: rgba(52,199,89,0.10);
180
+ border: 1px solid rgba(52,199,89,0.20);
181
+ color: #34c759;
182
+ }
183
+
184
+ /* Hide default header & footer */
185
+ #MainMenu, header, footer { visibility: hidden; }
186
+
187
+ /* Folium map container */
188
+ iframe { border-radius: 14px !important; }
189
+ </style>
190
+ """, unsafe_allow_html=True)
191
+
192
+
193
+ # ============================================================
194
+ # MODEL LOADING
195
+ # ============================================================
196
+ @st.cache_resource
197
+ def load_model():
198
+ if not os.path.exists(MODEL_PATH):
199
+ st.error(f"Model file not found at `{MODEL_PATH}`.")
200
+ st.stop()
201
+ return YOLO(MODEL_PATH)
202
+
203
+
204
+ model = load_model()
205
+
206
+
207
+ # ============================================================
208
+ # UTILITY FUNCTIONS
209
+ # ============================================================
210
+ def haversine_km(lat1, lon1, lat2, lon2):
211
+ """Return distance in km between two lat/lon points."""
212
+ R = 6371
213
+ dlat = math.radians(lat2 - lat1)
214
+ dlon = math.radians(lon2 - lon1)
215
+ a = (
216
+ math.sin(dlat / 2) ** 2
217
+ + math.cos(math.radians(lat1))
218
+ * math.cos(math.radians(lat2))
219
+ * math.sin(dlon / 2) ** 2
220
+ )
221
+ return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
222
+
223
+
224
+ # ============================================================
225
+ # DETECTION FUNCTIONS
226
+ # ============================================================
227
+ def detect_in_image(image_array, conf):
228
+ """Run YOLO on a single image. Returns (detections, annotated_rgb)."""
229
+ results = model.predict(image_array, conf=conf, verbose=False)
230
+ detections = []
231
+ for result in results:
232
+ for box in result.boxes:
233
+ cls_id = int(box.cls[0])
234
+ detections.append(
235
+ {
236
+ "label": CLASS_NAMES.get(cls_id, "Unknown"),
237
+ "confidence": float(box.conf[0]),
238
+ }
239
+ )
240
+ annotated_bgr = results[0].plot()
241
+ annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
242
+ return detections, annotated_rgb
243
+
244
+
245
+ def detect_in_video(video_path, conf, frame_skip=4, progress_cb=None):
246
+ """Run YOLO on video frames. Returns (detections, best_annotated_rgb)."""
247
+ cap = cv2.VideoCapture(video_path)
248
+ total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1
249
+ detections = []
250
+ best_frame = None
251
+ best_conf = 0
252
+ idx = 0
253
+
254
+ while cap.isOpened():
255
+ ret, frame = cap.read()
256
+ if not ret:
257
+ break
258
+ if idx % frame_skip == 0:
259
+ results = model.predict(frame, conf=conf, verbose=False)
260
+ for result in results:
261
+ for box in result.boxes:
262
+ cls_id = int(box.cls[0])
263
+ c = float(box.conf[0])
264
+ label = CLASS_NAMES.get(cls_id, "Unknown")
265
+ if label in ALERT_CLASSES:
266
+ detections.append(
267
+ {"label": label, "confidence": c, "frame": idx}
268
+ )
269
+ if c > best_conf:
270
+ best_conf = c
271
+ best_frame = results[0].plot()
272
+ idx += 1
273
+ if progress_cb:
274
+ progress_cb(min(idx / total, 1.0))
275
+
276
+ cap.release()
277
+ if best_frame is not None:
278
+ best_frame = cv2.cvtColor(best_frame, cv2.COLOR_BGR2RGB)
279
+ return detections, best_frame
280
+
281
+
282
+ # ============================================================
283
+ # LOCATION & HOSPITAL FUNCTIONS
284
+ # ============================================================
285
+ def get_ip_location():
286
+ """Free IP-based geolocation (no API key required)."""
287
+ try:
288
+ r = requests.get("http://ip-api.com/json/", timeout=5)
289
+ d = r.json()
290
+ if d.get("status") == "success":
291
+ return {
292
+ "lat": d["lat"],
293
+ "lon": d["lon"],
294
+ "city": d.get("city", ""),
295
+ "region": d.get("regionName", ""),
296
+ "country": d.get("country", ""),
297
+ }
298
+ except Exception:
299
+ pass
300
+ return None
301
+
302
+
303
+ def fetch_hospitals(lat, lon, radius_m=5000):
304
+ """Query OpenStreetMap Overpass API for hospitals within radius."""
305
+ query = f"""
306
+ [out:json][timeout:10];
307
+ (
308
+ node["amenity"="hospital"](around:{radius_m},{lat},{lon});
309
+ way["amenity"="hospital"](around:{radius_m},{lat},{lon});
310
+ relation["amenity"="hospital"](around:{radius_m},{lat},{lon});
311
+ );
312
+ out center body;
313
+ """
314
+ try:
315
+ r = requests.post(
316
+ "https://overpass-api.de/api/interpreter",
317
+ data={"data": query},
318
+ timeout=15,
319
+ )
320
+ elements = r.json().get("elements", [])
321
+ except Exception:
322
+ return []
323
+
324
+ hospitals = []
325
+ for el in elements:
326
+ tags = el.get("tags", {})
327
+ if el["type"] == "node":
328
+ h_lat, h_lon = el["lat"], el["lon"]
329
+ else:
330
+ c = el.get("center", {})
331
+ h_lat = c.get("lat", lat)
332
+ h_lon = c.get("lon", lon)
333
+ dist = haversine_km(lat, lon, h_lat, h_lon)
334
+ hospitals.append(
335
+ {
336
+ "name": tags.get("name", "Unnamed Hospital"),
337
+ "lat": h_lat,
338
+ "lon": h_lon,
339
+ "distance_km": round(dist, 2),
340
+ "phone": tags.get("phone", tags.get("contact:phone", "—")),
341
+ "beds": tags.get("beds", "—"),
342
+ "emergency": tags.get("emergency", "unknown"),
343
+ }
344
+ )
345
+ hospitals.sort(key=lambda h: h["distance_km"])
346
+ return hospitals
347
+
348
+
349
+ def build_map(lat, lon, hospitals, radius_m=5000):
350
+ """Create a folium map with accident marker, radius circle, and hospitals."""
351
+ m = folium.Map(location=[lat, lon], zoom_start=14, tiles="CartoDB dark_matter")
352
+ # Accident location
353
+ folium.Marker(
354
+ [lat, lon],
355
+ popup="🚨 Accident",
356
+ icon=folium.Icon(color="red", icon="exclamation-triangle", prefix="fa"),
357
+ ).add_to(m)
358
+ # Radius
359
+ folium.Circle(
360
+ [lat, lon],
361
+ radius=radius_m,
362
+ color="#ff3b30",
363
+ fill=True,
364
+ fill_opacity=0.06,
365
+ weight=2,
366
+ dash_array="6 4",
367
+ ).add_to(m)
368
+ # Hospitals
369
+ for h in hospitals:
370
+ folium.Marker(
371
+ [h["lat"], h["lon"]],
372
+ popup=f"🏥 {h['name']} — {h['distance_km']} km",
373
+ icon=folium.Icon(color="green", icon="plus-square", prefix="fa"),
374
+ ).add_to(m)
375
+ return m
376
+
377
+
378
+ # ============================================================
379
+ # SIDEBAR
380
+ # ============================================================
381
+ with st.sidebar:
382
+ st.markdown("## ⚙️ Detection Settings")
383
+ confidence = st.slider(
384
+ "Confidence threshold", 0.10, 0.90, DEFAULT_CONFIDENCE, 0.05
385
+ )
386
+
387
+ st.markdown("---")
388
+ st.markdown("## 📍 Location")
389
+ st.caption(
390
+ "Location is auto-detected via IP. On cloud deployments this returns "
391
+ "the server location — use manual override for accurate testing."
392
+ )
393
+ use_manual = st.checkbox("Use manual coordinates")
394
+ if use_manual:
395
+ manual_lat = st.number_input("Latitude", value=28.6139, format="%.4f")
396
+ manual_lon = st.number_input("Longitude", value=77.2090, format="%.4f")
397
+ else:
398
+ manual_lat, manual_lon = None, None
399
+
400
+ st.markdown("---")
401
+ st.markdown("## ℹ️ About")
402
+ st.markdown(
403
+ "**AccidentAI** uses a custom-trained **YOLOv8** model to detect "
404
+ "accidents and fires in CCTV footage, then automatically locates "
405
+ "nearby hospitals and sends simulated emergency alerts."
406
+ )
407
+ st.markdown(
408
+ "Built with Ultralytics, Streamlit, OpenStreetMap Overpass API, and Folium."
409
+ )
410
+
411
+
412
+ # ============================================================
413
+ # HERO
414
+ # ============================================================
415
+ st.markdown(
416
+ """
417
+ <div class="hero-wrap">
418
+ <h1>🚨 AccidentAI</h1>
419
+ <p class="subtitle">Real-Time Accident Detection &amp; Emergency Alert System</p>
420
+ <div class="pills">
421
+ <span class="pill">YOLOv8</span>
422
+ <span class="pill">CCTV Analysis</span>
423
+ <span class="pill">Hospital Alerts</span>
424
+ <span class="pill">Live Map</span>
425
+ </div>
426
+ </div>
427
+ """,
428
+ unsafe_allow_html=True,
429
+ )
430
+
431
+
432
+ # ============================================================
433
+ # FILE UPLOAD
434
+ # ============================================================
435
+ uploaded = st.file_uploader(
436
+ "Upload CCTV footage or image",
437
+ type=["jpg", "jpeg", "png", "mp4", "avi", "mov"],
438
+ help="Supported formats: JPG, PNG images and MP4, AVI, MOV videos",
439
+ )
440
+
441
+ if not uploaded:
442
+ st.info("👆 Upload an image or video to start detection.")
443
+ st.stop()
444
+
445
+ # ============================================================
446
+ # RUN DETECTION
447
+ # ============================================================
448
+ is_video = uploaded.name.lower().endswith((".mp4", ".avi", ".mov"))
449
+
450
+ if is_video:
451
+ with NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
452
+ tmp.write(uploaded.read())
453
+ tmp_path = tmp.name
454
+ st.markdown("### 🎬 Analyzing video frames…")
455
+ pbar = st.progress(0)
456
+ detections, annotated = detect_in_video(
457
+ tmp_path, confidence, progress_cb=pbar.progress
458
+ )
459
+ pbar.empty()
460
+ try:
461
+ os.unlink(tmp_path)
462
+ except OSError:
463
+ pass
464
+ else:
465
+ raw = np.asarray(bytearray(uploaded.read()), dtype=np.uint8)
466
+ image = cv2.imdecode(raw, cv2.IMREAD_COLOR)
467
+ detections, annotated = detect_in_image(image, confidence)
468
+
469
+ alert_dets = [d for d in detections if d["label"] in ALERT_CLASSES]
470
+
471
+ # ============================================================
472
+ # RESULTS
473
+ # ============================================================
474
+ st.markdown("---")
475
+ col_img, col_stats = st.columns([2, 1], gap="large")
476
+
477
+ with col_img:
478
+ st.markdown("### 🔍 Detection Output")
479
+ if annotated is not None:
480
+ st.image(annotated, use_container_width=True)
481
+ elif is_video:
482
+ st.info("No hazard frames captured — video appears safe.")
483
+
484
+ with col_stats:
485
+ st.markdown("### 📊 Analysis")
486
+ n_acc = sum(1 for d in alert_dets if d["label"] == "Accident")
487
+ n_fire = sum(1 for d in alert_dets if d["label"] == "Fire")
488
+ total = len(detections)
489
+
490
+ st.markdown(
491
+ f"""
492
+ <div class="stat-row">
493
+ <div class="stat-box">
494
+ <div class="num" style="color:#ff5e57">{n_acc}</div>
495
+ <div class="lbl">Accidents</div>
496
+ </div>
497
+ <div class="stat-box">
498
+ <div class="num" style="color:#ff9500">{n_fire}</div>
499
+ <div class="lbl">Fires</div>
500
+ </div>
501
+ <div class="stat-box">
502
+ <div class="num" style="color:#34c759">{total}</div>
503
+ <div class="lbl">Total Detections</div>
504
+ </div>
505
+ </div>
506
+ """,
507
+ unsafe_allow_html=True,
508
+ )
509
+
510
+ if alert_dets:
511
+ peak = max(d["confidence"] for d in alert_dets)
512
+ avg = sum(d["confidence"] for d in alert_dets) / len(alert_dets)
513
+ st.metric("Peak Confidence", f"{peak:.1%}")
514
+ st.metric("Avg Confidence", f"{avg:.1%}")
515
+ if is_video:
516
+ frames_hit = len(set(d.get("frame", 0) for d in alert_dets))
517
+ st.metric("Frames with Hazards", frames_hit)
518
+ else:
519
+ st.success("✅ No hazards detected in the uploaded media.")
520
+
521
+
522
+ # ============================================================
523
+ # EMERGENCY ALERT SYSTEM
524
+ # ============================================================
525
+ if not alert_dets:
526
+ st.stop()
527
+
528
+ st.markdown("---")
529
+
530
+ # Alert banner
531
+ top_label = "Accident" if n_acc else "Fire"
532
+ st.markdown(
533
+ f"""
534
+ <div class="alert-banner">
535
+ <h3>🚨 EMERGENCY — {top_label} Detected</h3>
536
+ <p>Initiating automated alert protocol • Searching hospitals within 5 km radius</p>
537
+ </div>
538
+ """,
539
+ unsafe_allow_html=True,
540
+ )
541
+
542
+ # -- Get location --
543
+ if use_manual and manual_lat is not None:
544
+ loc = {
545
+ "lat": manual_lat,
546
+ "lon": manual_lon,
547
+ "city": "Manual",
548
+ "region": "",
549
+ "country": "",
550
+ }
551
+ else:
552
+ with st.spinner("📍 Detecting location…"):
553
+ loc = get_ip_location()
554
+
555
+ if loc is None:
556
+ st.warning(
557
+ "Could not detect location automatically. "
558
+ "Enable **manual coordinates** in the sidebar."
559
+ )
560
+ st.stop()
561
+
562
+ loc_str = ", ".join(filter(None, [loc["city"], loc["region"], loc["country"]]))
563
+ st.markdown(
564
+ f"**📍 Incident Location:** {loc_str} &nbsp;|&nbsp; "
565
+ f"`{loc['lat']:.4f}, {loc['lon']:.4f}`"
566
+ )
567
+
568
+ # -- Fetch hospitals --
569
+ with st.spinner("🏥 Querying OpenStreetMap for nearby hospitals…"):
570
+ hospitals = fetch_hospitals(loc["lat"], loc["lon"], HOSPITAL_RADIUS_M)
571
+
572
+ if not hospitals:
573
+ st.warning(
574
+ "No hospitals found within 5 km. Try different coordinates or increase radius."
575
+ )
576
+ st.stop()
577
+
578
+ st.markdown(f"**Found {len(hospitals)} hospital(s) within 5 km**")
579
+
580
+ # -- Map & hospital list side by side --
581
+ col_map, col_list = st.columns([1, 1], gap="large")
582
+
583
+ with col_map:
584
+ st.markdown("### 🗺️ Incident Map")
585
+ m = build_map(loc["lat"], loc["lon"], hospitals)
586
+ st_folium(m, height=420, use_container_width=True)
587
+
588
+ with col_list:
589
+ st.markdown("### 🏥 Nearby Hospitals")
590
+ for i, h in enumerate(hospitals):
591
+ emoji = "🥇" if i == 0 else "🥈" if i == 1 else "🥉" if i == 2 else "🏥"
592
+ st.markdown(
593
+ f"""<div class="hosp-card">
594
+ <div class="name">{emoji} {h['name']}</div>
595
+ <div class="meta">
596
+ 📏 {h['distance_km']} km &nbsp;|&nbsp;
597
+ 📞 {h['phone']} &nbsp;|&nbsp;
598
+ 🛏️ Beds: {h['beds']}
599
+ </div>
600
+ </div>""",
601
+ unsafe_allow_html=True,
602
+ )
603
+ if len(hospitals) > 8:
604
+ st.caption(f"Showing all {len(hospitals)} results")
605
+
606
+ # ============================================================
607
+ # SIMULATED NOTIFICATIONS
608
+ # ============================================================
609
+ st.markdown("---")
610
+ st.markdown("### 📨 Alert Dispatch Log")
611
+ st.caption("Sending automated emergency alerts to the nearest hospitals…")
612
+
613
+ notify_count = min(len(hospitals), 3)
614
+ log_container = st.container()
615
+ for i in range(notify_count):
616
+ h = hospitals[i]
617
+ time.sleep(0.7)
618
+ log_container.markdown(
619
+ f"""<div class="notif-entry notif-ok">
620
+ ✅ &nbsp; Alert dispatched to <b>{h['name']}</b> — {h['distance_km']} km away
621
+ </div>""",
622
+ unsafe_allow_html=True,
623
+ )
624
+
625
+ st.success(
626
+ f"✅ Emergency alerts sent to **{notify_count}** hospital(s). "
627
+ f"Nearest: **{hospitals[0]['name']}** ({hospitals[0]['distance_km']} km)"
628
+ )