Spaces:
Sleeping
Sleeping
File size: 18,639 Bytes
f45c73e | 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 | import streamlit as st
import cv2
import numpy as np
from ultralytics import YOLO
import requests
import math
import time
import os
from tempfile import NamedTemporaryFile
import folium
from streamlit_folium import st_folium
# ============================================================
# CONFIGURATION
# ============================================================
MODEL_PATH = "model/best.pt"
CLASS_NAMES = {0: "Accident", 1: "Non-accident", 2: "Fire"}
ALERT_CLASSES = {"Accident", "Fire"}
DEFAULT_CONFIDENCE = 0.3
HOSPITAL_RADIUS_M = 5000
# ============================================================
# PAGE CONFIG
# ============================================================
st.set_page_config(
page_title="AccidentAI β Real-Time Detection & Alert",
page_icon="π¨",
layout="wide",
initial_sidebar_state="expanded",
)
# ============================================================
# CUSTOM CSS
# ============================================================
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap');
html, body, .stApp {
font-family: 'Inter', sans-serif !important;
}
/* Hero */
.hero-wrap {
text-align: center;
padding: 2.5rem 1rem 1.5rem;
}
.hero-wrap h1 {
font-size: 2.8rem;
font-weight: 900;
background: linear-gradient(135deg, #ff3b30, #ff9500, #ff3b30);
background-size: 200% 200%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: grad 4s ease infinite;
margin-bottom: 0.25rem;
}
@keyframes grad {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
.hero-wrap .subtitle {
font-size: 1.1rem;
color: #aaa;
font-weight: 400;
}
.hero-wrap .pills {
margin-top: 0.75rem;
display: flex;
gap: 0.5rem;
justify-content: center;
flex-wrap: wrap;
}
.hero-wrap .pill {
background: rgba(255,59,48,0.12);
border: 1px solid rgba(255,59,48,0.25);
color: #ff6b5e;
padding: 0.3rem 0.85rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 500;
}
/* Glass card */
.glass {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 16px;
padding: 1.5rem;
backdrop-filter: blur(12px);
margin-bottom: 1rem;
}
/* Stat box */
.stat-row {
display: flex;
gap: 1rem;
flex-wrap: wrap;
margin: 0.5rem 0;
}
.stat-box {
flex: 1;
min-width: 120px;
text-align: center;
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 12px;
padding: 1rem 0.75rem;
}
.stat-box .num {
font-size: 1.8rem;
font-weight: 700;
}
.stat-box .lbl {
font-size: 0.75rem;
color: #888;
text-transform: uppercase;
letter-spacing: 0.05em;
}
/* Alert banner */
@keyframes pulse-border {
0%, 100% { border-color: rgba(255,59,48,0.25); }
50% { border-color: rgba(255,59,48,0.65); }
}
.alert-banner {
background: linear-gradient(135deg, rgba(255,59,48,0.10), rgba(255,149,0,0.06));
border: 2px solid rgba(255,59,48,0.35);
border-radius: 14px;
padding: 1.25rem 1.5rem;
animation: pulse-border 2s ease infinite;
margin-bottom: 1rem;
}
.alert-banner h3 {
margin: 0 0 0.25rem;
color: #ff5e57;
}
.alert-banner p {
margin: 0;
color: #ccc;
font-size: 0.92rem;
}
/* Hospital card */
.hosp-card {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.09);
border-radius: 12px;
padding: 1rem 1.25rem;
margin-bottom: 0.65rem;
transition: border-color 0.25s;
}
.hosp-card:hover {
border-color: rgba(52,199,89,0.45);
}
.hosp-card .name {
font-weight: 600;
font-size: 1rem;
color: #e0e0e0;
}
.hosp-card .meta {
font-size: 0.82rem;
color: #999;
margin-top: 0.25rem;
}
/* Notification log entry */
.notif-entry {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 1rem;
border-radius: 10px;
margin-bottom: 0.4rem;
font-size: 0.88rem;
}
.notif-ok {
background: rgba(52,199,89,0.10);
border: 1px solid rgba(52,199,89,0.20);
color: #34c759;
}
/* Hide default header & footer */
#MainMenu, header, footer { visibility: hidden; }
/* Folium map container */
iframe { border-radius: 14px !important; }
</style>
""", unsafe_allow_html=True)
# ============================================================
# MODEL LOADING
# ============================================================
@st.cache_resource
def load_model():
if not os.path.exists(MODEL_PATH):
st.error(f"Model file not found at `{MODEL_PATH}`.")
st.stop()
return YOLO(MODEL_PATH)
model = load_model()
# ============================================================
# UTILITY FUNCTIONS
# ============================================================
def haversine_km(lat1, lon1, lat2, lon2):
"""Return distance in km between two lat/lon points."""
R = 6371
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (
math.sin(dlat / 2) ** 2
+ math.cos(math.radians(lat1))
* math.cos(math.radians(lat2))
* math.sin(dlon / 2) ** 2
)
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# ============================================================
# DETECTION FUNCTIONS
# ============================================================
def detect_in_image(image_array, conf):
"""Run YOLO on a single image. Returns (detections, annotated_rgb)."""
results = model.predict(image_array, conf=conf, verbose=False)
detections = []
for result in results:
for box in result.boxes:
cls_id = int(box.cls[0])
detections.append(
{
"label": CLASS_NAMES.get(cls_id, "Unknown"),
"confidence": float(box.conf[0]),
}
)
annotated_bgr = results[0].plot()
annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
return detections, annotated_rgb
def detect_in_video(video_path, conf, frame_skip=4, progress_cb=None):
"""Run YOLO on video frames. Returns (detections, best_annotated_rgb)."""
cap = cv2.VideoCapture(video_path)
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1
detections = []
best_frame = None
best_conf = 0
idx = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if idx % frame_skip == 0:
results = model.predict(frame, conf=conf, verbose=False)
for result in results:
for box in result.boxes:
cls_id = int(box.cls[0])
c = float(box.conf[0])
label = CLASS_NAMES.get(cls_id, "Unknown")
if label in ALERT_CLASSES:
detections.append(
{"label": label, "confidence": c, "frame": idx}
)
if c > best_conf:
best_conf = c
best_frame = results[0].plot()
idx += 1
if progress_cb:
progress_cb(min(idx / total, 1.0))
cap.release()
if best_frame is not None:
best_frame = cv2.cvtColor(best_frame, cv2.COLOR_BGR2RGB)
return detections, best_frame
# ============================================================
# LOCATION & HOSPITAL FUNCTIONS
# ============================================================
def get_ip_location():
"""Free IP-based geolocation (no API key required)."""
try:
r = requests.get("http://ip-api.com/json/", timeout=5)
d = r.json()
if d.get("status") == "success":
return {
"lat": d["lat"],
"lon": d["lon"],
"city": d.get("city", ""),
"region": d.get("regionName", ""),
"country": d.get("country", ""),
}
except Exception:
pass
return None
def fetch_hospitals(lat, lon, radius_m=5000):
"""Query OpenStreetMap Overpass API for hospitals within radius."""
query = f"""
[out:json][timeout:10];
(
node["amenity"="hospital"](around:{radius_m},{lat},{lon});
way["amenity"="hospital"](around:{radius_m},{lat},{lon});
relation["amenity"="hospital"](around:{radius_m},{lat},{lon});
);
out center body;
"""
try:
r = requests.post(
"https://overpass-api.de/api/interpreter",
data={"data": query},
timeout=15,
)
elements = r.json().get("elements", [])
except Exception:
return []
hospitals = []
for el in elements:
tags = el.get("tags", {})
if el["type"] == "node":
h_lat, h_lon = el["lat"], el["lon"]
else:
c = el.get("center", {})
h_lat = c.get("lat", lat)
h_lon = c.get("lon", lon)
dist = haversine_km(lat, lon, h_lat, h_lon)
hospitals.append(
{
"name": tags.get("name", "Unnamed Hospital"),
"lat": h_lat,
"lon": h_lon,
"distance_km": round(dist, 2),
"phone": tags.get("phone", tags.get("contact:phone", "β")),
"beds": tags.get("beds", "β"),
"emergency": tags.get("emergency", "unknown"),
}
)
hospitals.sort(key=lambda h: h["distance_km"])
return hospitals
def build_map(lat, lon, hospitals, radius_m=5000):
"""Create a folium map with accident marker, radius circle, and hospitals."""
m = folium.Map(location=[lat, lon], zoom_start=14, tiles="CartoDB dark_matter")
# Accident location
folium.Marker(
[lat, lon],
popup="π¨ Accident",
icon=folium.Icon(color="red", icon="exclamation-triangle", prefix="fa"),
).add_to(m)
# Radius
folium.Circle(
[lat, lon],
radius=radius_m,
color="#ff3b30",
fill=True,
fill_opacity=0.06,
weight=2,
dash_array="6 4",
).add_to(m)
# Hospitals
for h in hospitals:
folium.Marker(
[h["lat"], h["lon"]],
popup=f"π₯ {h['name']} β {h['distance_km']} km",
icon=folium.Icon(color="green", icon="plus-square", prefix="fa"),
).add_to(m)
return m
# ============================================================
# SIDEBAR
# ============================================================
with st.sidebar:
st.markdown("## βοΈ Detection Settings")
confidence = st.slider(
"Confidence threshold", 0.10, 0.90, DEFAULT_CONFIDENCE, 0.05
)
st.markdown("---")
st.markdown("## π Location")
st.caption(
"Location is auto-detected via IP. On cloud deployments this returns "
"the server location β use manual override for accurate testing."
)
use_manual = st.checkbox("Use manual coordinates")
if use_manual:
manual_lat = st.number_input("Latitude", value=28.6139, format="%.4f")
manual_lon = st.number_input("Longitude", value=77.2090, format="%.4f")
else:
manual_lat, manual_lon = None, None
st.markdown("---")
st.markdown("## βΉοΈ About")
st.markdown(
"**AccidentAI** uses a custom-trained **YOLOv8** model to detect "
"accidents and fires in CCTV footage, then automatically locates "
"nearby hospitals and sends simulated emergency alerts."
)
st.markdown(
"Built with Ultralytics, Streamlit, OpenStreetMap Overpass API, and Folium."
)
# ============================================================
# HERO
# ============================================================
st.markdown(
"""
<div class="hero-wrap">
<h1>π¨ AccidentAI</h1>
<p class="subtitle">Real-Time Accident Detection & Emergency Alert System</p>
<div class="pills">
<span class="pill">YOLOv8</span>
<span class="pill">CCTV Analysis</span>
<span class="pill">Hospital Alerts</span>
<span class="pill">Live Map</span>
</div>
</div>
""",
unsafe_allow_html=True,
)
# ============================================================
# FILE UPLOAD
# ============================================================
uploaded = st.file_uploader(
"Upload CCTV footage or image",
type=["jpg", "jpeg", "png", "mp4", "avi", "mov"],
help="Supported formats: JPG, PNG images and MP4, AVI, MOV videos",
)
if not uploaded:
st.info("π Upload an image or video to start detection.")
st.stop()
# ============================================================
# RUN DETECTION
# ============================================================
is_video = uploaded.name.lower().endswith((".mp4", ".avi", ".mov"))
if is_video:
with NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
tmp.write(uploaded.read())
tmp_path = tmp.name
st.markdown("### π¬ Analyzing video framesβ¦")
pbar = st.progress(0)
detections, annotated = detect_in_video(
tmp_path, confidence, progress_cb=pbar.progress
)
pbar.empty()
try:
os.unlink(tmp_path)
except OSError:
pass
else:
raw = np.asarray(bytearray(uploaded.read()), dtype=np.uint8)
image = cv2.imdecode(raw, cv2.IMREAD_COLOR)
detections, annotated = detect_in_image(image, confidence)
alert_dets = [d for d in detections if d["label"] in ALERT_CLASSES]
# ============================================================
# RESULTS
# ============================================================
st.markdown("---")
col_img, col_stats = st.columns([2, 1], gap="large")
with col_img:
st.markdown("### π Detection Output")
if annotated is not None:
st.image(annotated, use_container_width=True)
elif is_video:
st.info("No hazard frames captured β video appears safe.")
with col_stats:
st.markdown("### π Analysis")
n_acc = sum(1 for d in alert_dets if d["label"] == "Accident")
n_fire = sum(1 for d in alert_dets if d["label"] == "Fire")
total = len(detections)
st.markdown(
f"""
<div class="stat-row">
<div class="stat-box">
<div class="num" style="color:#ff5e57">{n_acc}</div>
<div class="lbl">Accidents</div>
</div>
<div class="stat-box">
<div class="num" style="color:#ff9500">{n_fire}</div>
<div class="lbl">Fires</div>
</div>
<div class="stat-box">
<div class="num" style="color:#34c759">{total}</div>
<div class="lbl">Total Detections</div>
</div>
</div>
""",
unsafe_allow_html=True,
)
if alert_dets:
peak = max(d["confidence"] for d in alert_dets)
avg = sum(d["confidence"] for d in alert_dets) / len(alert_dets)
st.metric("Peak Confidence", f"{peak:.1%}")
st.metric("Avg Confidence", f"{avg:.1%}")
if is_video:
frames_hit = len(set(d.get("frame", 0) for d in alert_dets))
st.metric("Frames with Hazards", frames_hit)
else:
st.success("β
No hazards detected in the uploaded media.")
# ============================================================
# EMERGENCY ALERT SYSTEM
# ============================================================
if not alert_dets:
st.stop()
st.markdown("---")
# Alert banner
top_label = "Accident" if n_acc else "Fire"
st.markdown(
f"""
<div class="alert-banner">
<h3>π¨ EMERGENCY β {top_label} Detected</h3>
<p>Initiating automated alert protocol β’ Searching hospitals within 5 km radius</p>
</div>
""",
unsafe_allow_html=True,
)
# -- Get location --
if use_manual and manual_lat is not None:
loc = {
"lat": manual_lat,
"lon": manual_lon,
"city": "Manual",
"region": "",
"country": "",
}
else:
with st.spinner("π Detecting locationβ¦"):
loc = get_ip_location()
if loc is None:
st.warning(
"Could not detect location automatically. "
"Enable **manual coordinates** in the sidebar."
)
st.stop()
loc_str = ", ".join(filter(None, [loc["city"], loc["region"], loc["country"]]))
st.markdown(
f"**π Incident Location:** {loc_str} | "
f"`{loc['lat']:.4f}, {loc['lon']:.4f}`"
)
# -- Fetch hospitals --
with st.spinner("π₯ Querying OpenStreetMap for nearby hospitalsβ¦"):
hospitals = fetch_hospitals(loc["lat"], loc["lon"], HOSPITAL_RADIUS_M)
if not hospitals:
st.warning(
"No hospitals found within 5 km. Try different coordinates or increase radius."
)
st.stop()
st.markdown(f"**Found {len(hospitals)} hospital(s) within 5 km**")
# -- Map & hospital list side by side --
col_map, col_list = st.columns([1, 1], gap="large")
with col_map:
st.markdown("### πΊοΈ Incident Map")
m = build_map(loc["lat"], loc["lon"], hospitals)
st_folium(m, height=420, use_container_width=True)
with col_list:
st.markdown("### π₯ Nearby Hospitals")
for i, h in enumerate(hospitals):
emoji = "π₯" if i == 0 else "π₯" if i == 1 else "π₯" if i == 2 else "π₯"
st.markdown(
f"""<div class="hosp-card">
<div class="name">{emoji} {h['name']}</div>
<div class="meta">
π {h['distance_km']} km |
π {h['phone']} |
ποΈ Beds: {h['beds']}
</div>
</div>""",
unsafe_allow_html=True,
)
if len(hospitals) > 8:
st.caption(f"Showing all {len(hospitals)} results")
# ============================================================
# SIMULATED NOTIFICATIONS
# ============================================================
st.markdown("---")
st.markdown("### π¨ Alert Dispatch Log")
st.caption("Sending automated emergency alerts to the nearest hospitalsβ¦")
notify_count = min(len(hospitals), 3)
log_container = st.container()
for i in range(notify_count):
h = hospitals[i]
time.sleep(0.7)
log_container.markdown(
f"""<div class="notif-entry notif-ok">
β
Alert dispatched to <b>{h['name']}</b> β {h['distance_km']} km away
</div>""",
unsafe_allow_html=True,
)
st.success(
f"β
Emergency alerts sent to **{notify_count}** hospital(s). "
f"Nearest: **{hospitals[0]['name']}** ({hospitals[0]['distance_km']} km)"
)
|