Update app.py
Browse files
app.py
CHANGED
|
@@ -1,712 +1,743 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import cv2
|
| 3 |
-
import numpy as np
|
| 4 |
-
import time
|
| 5 |
-
import tempfile
|
| 6 |
-
from PIL import Image
|
| 7 |
-
import io
|
| 8 |
-
import os
|
| 9 |
-
import sys
|
| 10 |
-
import threading
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
import requests
|
| 13 |
-
import google.generativeai as genai
|
| 14 |
-
|
| 15 |
-
import
|
| 16 |
-
|
| 17 |
-
import
|
| 18 |
-
from
|
| 19 |
-
|
| 20 |
-
# Page configuration
|
| 21 |
-
st.set_page_config(
|
| 22 |
-
page_title="Crash Detection System",
|
| 23 |
-
page_icon="🚨",
|
| 24 |
-
layout="wide"
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
# App title and description
|
| 28 |
-
st.markdown("<h1 style='text-align: center; color: #FF4B4B;'>Vehicle Crash Detection System</h1>", unsafe_allow_html=True)
|
| 29 |
-
st.markdown("""
|
| 30 |
-
<p style='text-align: center; font-size: 1.2em;'>Real-time vehicle crash detection and severity assessment</p>
|
| 31 |
-
""", unsafe_allow_html=True)
|
| 32 |
-
|
| 33 |
-
# Sidebar for API key and Twilio configuration
|
| 34 |
-
with st.sidebar.expander("API Configuration", expanded=False):
|
| 35 |
-
api_key = st.text_input("Google Gemini API Key", type="password")
|
| 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 |
-
except Exception as e:
|
| 212 |
-
return
|
| 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 |
-
<div style="padding: 10px; border-radius: 5px; background-color: #
|
| 485 |
-
<
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
<div style="padding: 10px; border-radius: 5px; background-color:
|
| 494 |
-
<h4>
|
| 495 |
-
<p>{
|
| 496 |
-
</div>
|
| 497 |
-
""", unsafe_allow_html=True)
|
| 498 |
-
|
| 499 |
-
# Update
|
| 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 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 712 |
""", unsafe_allow_html=True)
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import time
|
| 5 |
+
import tempfile
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
import requests
|
| 13 |
+
import google.generativeai as genai
|
| 14 |
+
import folium
|
| 15 |
+
from streamlit_folium import folium_static
|
| 16 |
+
import geocoder
|
| 17 |
+
from twilio.rest import Client
|
| 18 |
+
from inference_sdk import InferenceHTTPClient
|
| 19 |
+
|
| 20 |
+
# Page configuration
|
| 21 |
+
st.set_page_config(
|
| 22 |
+
page_title="Crash Detection System",
|
| 23 |
+
page_icon="🚨",
|
| 24 |
+
layout="wide"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# App title and description
|
| 28 |
+
st.markdown("<h1 style='text-align: center; color: #FF4B4B;'>Vehicle Crash Detection System</h1>", unsafe_allow_html=True)
|
| 29 |
+
st.markdown("""
|
| 30 |
+
<p style='text-align: center; font-size: 1.2em;'>Real-time vehicle crash detection and severity assessment</p>
|
| 31 |
+
""", unsafe_allow_html=True)
|
| 32 |
+
|
| 33 |
+
# Sidebar for API key and Twilio configuration
|
| 34 |
+
with st.sidebar.expander("API Configuration", expanded=False):
|
| 35 |
+
api_key = st.text_input("Google Gemini API Key", type="password",value="AIzaSyCcf3s3GS7_925D7t2fgODc5WIKOMZSOzc")
|
| 36 |
+
roboflow_api_key = st.text_input("Roboflow API Key", value="7pg4aR4pI1rxRJ4BTQo8", type="password")
|
| 37 |
+
if api_key:
|
| 38 |
+
genai.configure(api_key=api_key)
|
| 39 |
+
st.success("Google API key configured!")
|
| 40 |
+
if roboflow_api_key:
|
| 41 |
+
st.success("Roboflow API key configured!")
|
| 42 |
+
|
| 43 |
+
with st.sidebar.expander("Twilio Configuration", expanded=False):
|
| 44 |
+
twilio_account_sid = st.text_input("Twilio Account SID", type="password")
|
| 45 |
+
twilio_auth_token = st.text_input("Twilio Auth Token", type="password")
|
| 46 |
+
twilio_from_number = st.text_input("Twilio From Number")
|
| 47 |
+
recipient_number = st.text_input("Recipient Phone Number")
|
| 48 |
+
|
| 49 |
+
# BACKEND IMPLEMENTATION
|
| 50 |
+
@st.cache_resource
|
| 51 |
+
def initialize_roboflow_client():
|
| 52 |
+
"""Initialize the Roboflow client with caching"""
|
| 53 |
+
return InferenceHTTPClient(
|
| 54 |
+
api_url="https://detect.roboflow.com",
|
| 55 |
+
api_key=roboflow_api_key
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Get the client
|
| 59 |
+
CLIENT = initialize_roboflow_client()
|
| 60 |
+
|
| 61 |
+
def detect_crash(image):
|
| 62 |
+
"""
|
| 63 |
+
Detects crashes in an image using Roboflow YOLO model
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
image: PIL Image or numpy array
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
Dictionary with crash detection results, annotated image, and crash details
|
| 70 |
+
"""
|
| 71 |
+
try:
|
| 72 |
+
# Convert to PIL Image if it's a numpy array
|
| 73 |
+
if isinstance(image, np.ndarray):
|
| 74 |
+
# Convert BGR (OpenCV) to RGB (PIL)
|
| 75 |
+
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 76 |
+
pil_image = Image.fromarray(image_rgb)
|
| 77 |
+
else:
|
| 78 |
+
pil_image = image
|
| 79 |
+
|
| 80 |
+
# Save image temporarily with reduced quality for faster upload
|
| 81 |
+
temp_img_path = "temp_detection_image.jpg"
|
| 82 |
+
pil_image.save(temp_img_path, "JPEG", quality=70)
|
| 83 |
+
|
| 84 |
+
# Send to Roboflow for inference
|
| 85 |
+
result = CLIENT.infer(temp_img_path, model_id="accident-yqljb/1")
|
| 86 |
+
|
| 87 |
+
# Clean up temp file
|
| 88 |
+
if os.path.exists(temp_img_path):
|
| 89 |
+
os.remove(temp_img_path)
|
| 90 |
+
|
| 91 |
+
# Initialize default response
|
| 92 |
+
crash_detected = False
|
| 93 |
+
severity = "None"
|
| 94 |
+
annotated_image = None
|
| 95 |
+
|
| 96 |
+
# Create annotated image (with bounding boxes)
|
| 97 |
+
if isinstance(image, np.ndarray):
|
| 98 |
+
annotated_image = image.copy()
|
| 99 |
+
else:
|
| 100 |
+
annotated_image = np.array(pil_image)
|
| 101 |
+
# Convert back to BGR for OpenCV operations
|
| 102 |
+
annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)
|
| 103 |
+
|
| 104 |
+
# Process predictions if available
|
| 105 |
+
if "predictions" in result and result["predictions"]:
|
| 106 |
+
for pred in result["predictions"]:
|
| 107 |
+
crash_detected = True
|
| 108 |
+
|
| 109 |
+
# Extract severity based on class_id
|
| 110 |
+
class_id = pred.get("class_id", 0)
|
| 111 |
+
if class_id == 1:
|
| 112 |
+
severity = "Minor"
|
| 113 |
+
elif class_id == 2:
|
| 114 |
+
severity = "Moderate"
|
| 115 |
+
elif class_id == 3:
|
| 116 |
+
severity = "Severe"
|
| 117 |
+
else:
|
| 118 |
+
severity = "Unknown"
|
| 119 |
+
|
| 120 |
+
# Draw bounding box on the image
|
| 121 |
+
x, y = pred.get("x", 0), pred.get("y", 0)
|
| 122 |
+
width, height = pred.get("width", 0), pred.get("height", 0)
|
| 123 |
+
confidence = pred.get("confidence", 0)
|
| 124 |
+
|
| 125 |
+
# Calculate coordinates for rectangle
|
| 126 |
+
x1 = int(x - width/2)
|
| 127 |
+
y1 = int(y - height/2)
|
| 128 |
+
x2 = int(x + width/2)
|
| 129 |
+
y2 = int(y + height/2)
|
| 130 |
+
|
| 131 |
+
# Ensure coordinates are within image bounds
|
| 132 |
+
img_height, img_width = annotated_image.shape[:2]
|
| 133 |
+
x1 = max(0, min(x1, img_width-1))
|
| 134 |
+
y1 = max(0, min(y1, img_height-1))
|
| 135 |
+
x2 = max(0, min(x2, img_width-1))
|
| 136 |
+
y2 = max(0, min(y2, img_height-1))
|
| 137 |
+
|
| 138 |
+
# Set color based on severity
|
| 139 |
+
if severity == "Minor":
|
| 140 |
+
color = (0, 255, 255) # Yellow
|
| 141 |
+
elif severity == "Moderate":
|
| 142 |
+
color = (0, 165, 255) # Orange
|
| 143 |
+
else:
|
| 144 |
+
color = (0, 0, 255) # Red
|
| 145 |
+
|
| 146 |
+
# Draw rectangle and label
|
| 147 |
+
cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
|
| 148 |
+
label = f"{severity} crash: {confidence:.2f}"
|
| 149 |
+
cv2.putText(annotated_image, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
|
| 150 |
+
|
| 151 |
+
return {
|
| 152 |
+
"crash_detected": crash_detected,
|
| 153 |
+
"severity": severity,
|
| 154 |
+
"annotated_image": annotated_image,
|
| 155 |
+
"raw_result": result
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
st.error(f"Error in crash detection: {str(e)}")
|
| 160 |
+
# Return original image if error occurs
|
| 161 |
+
if isinstance(image, np.ndarray):
|
| 162 |
+
return {"crash_detected": False, "severity": "Error", "annotated_image": image, "raw_result": {}}
|
| 163 |
+
else:
|
| 164 |
+
return {"crash_detected": False, "severity": "Error", "annotated_image": np.array(pil_image), "raw_result": {}}
|
| 165 |
+
|
| 166 |
+
def assess_crash_severity(image, crash_info):
|
| 167 |
+
"""
|
| 168 |
+
Uses Google Gemini AI to assess crash severity in an image.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
image: PIL Image or numpy array
|
| 172 |
+
crash_info: Dictionary with crash detection results
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
Detailed analysis as a string
|
| 176 |
+
"""
|
| 177 |
+
if not api_key:
|
| 178 |
+
return "API key not configured for detailed analysis"
|
| 179 |
+
|
| 180 |
+
if not crash_info["crash_detected"]:
|
| 181 |
+
return "No crash detected in this image"
|
| 182 |
+
|
| 183 |
+
try:
|
| 184 |
+
# Convert to PIL Image if it's a numpy array
|
| 185 |
+
if isinstance(image, np.ndarray):
|
| 186 |
+
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
| 187 |
+
else:
|
| 188 |
+
image_pil = image
|
| 189 |
+
|
| 190 |
+
# Use Gemini to assess severity
|
| 191 |
+
model_gemini = genai.GenerativeModel("gemini-1.5-flash")
|
| 192 |
+
prompt = f"""
|
| 193 |
+
Analyze this vehicle crash image.
|
| 194 |
+
Detected crash severity: {crash_info['severity']}
|
| 195 |
+
Raw detection data: {crash_info['raw_result']}
|
| 196 |
+
|
| 197 |
+
Give a short, 2-line analysis of the crash. Focus on:
|
| 198 |
+
1. Apparent damage level and potential injuries
|
| 199 |
+
2. Possible cause or contributing factors
|
| 200 |
+
|
| 201 |
+
Keep your response concise and direct.
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
response = model_gemini.generate_content([prompt, image_pil])
|
| 205 |
+
|
| 206 |
+
if response and hasattr(response, "text"):
|
| 207 |
+
return response.text.strip()
|
| 208 |
+
else:
|
| 209 |
+
return "Unable to generate detailed analysis"
|
| 210 |
+
|
| 211 |
+
except Exception as e:
|
| 212 |
+
return f"Error in analysis: {str(e)}"
|
| 213 |
+
|
| 214 |
+
def get_current_location():
|
| 215 |
+
"""
|
| 216 |
+
Get the current geolocation.
|
| 217 |
+
Returns approximate location as a dictionary with lat, lng, address
|
| 218 |
+
"""
|
| 219 |
+
try:
|
| 220 |
+
g = geocoder.ip('me')
|
| 221 |
+
return {
|
| 222 |
+
"lat": g.lat,
|
| 223 |
+
"lng": g.lng,
|
| 224 |
+
"address": g.address
|
| 225 |
+
}
|
| 226 |
+
except Exception as e:
|
| 227 |
+
return {
|
| 228 |
+
"lat": 0,
|
| 229 |
+
"lng": 0,
|
| 230 |
+
"address": "Location unavailable"
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
def send_crash_alert_twilio(crash_data):
|
| 234 |
+
"""
|
| 235 |
+
Send a text message alert using Twilio
|
| 236 |
+
|
| 237 |
+
Args:
|
| 238 |
+
crash_data: Dictionary with crash details
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
Boolean indicating success and message
|
| 242 |
+
"""
|
| 243 |
+
messaging_service_sid = "MGf47912734231e47b941784b93376839d"
|
| 244 |
+
if not twilio_account_sid or not twilio_auth_token or not messaging_service_sid or not recipient_number:
|
| 245 |
+
return False, "Twilio configuration incomplete"
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
# Initialize Twilio client
|
| 249 |
+
client = Client(twilio_account_sid, twilio_auth_token)
|
| 250 |
+
|
| 251 |
+
# Create message content
|
| 252 |
+
message_body = f"""
|
| 253 |
+
🚨 CRASH ALERT 🚨
|
| 254 |
+
Time: {crash_data['timestamp']}
|
| 255 |
+
Severity: {crash_data['severity']}
|
| 256 |
+
Location: {crash_data['location']['address']}
|
| 257 |
+
|
| 258 |
+
Analysis: {crash_data['analysis']}
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
# Send message using MessagingServiceSid
|
| 262 |
+
message = client.messages.create(
|
| 263 |
+
body=message_body,
|
| 264 |
+
from_=twilio_from_number,
|
| 265 |
+
messaging_service_sid=messaging_service_sid,
|
| 266 |
+
to=recipient_number
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
return True, f"Message sent with SID: {message.sid}"
|
| 270 |
+
|
| 271 |
+
except Exception as e:
|
| 272 |
+
return False, f"Failed to send alert: {str(e)}"
|
| 273 |
+
|
| 274 |
+
# FRONTEND IMPLEMENTATION
|
| 275 |
+
# Create sidebar for controls
|
| 276 |
+
st.sidebar.title("Controls")
|
| 277 |
+
|
| 278 |
+
# Detection settings
|
| 279 |
+
confidence_threshold = st.sidebar.slider(
|
| 280 |
+
"Detection Confidence",
|
| 281 |
+
min_value=0.0,
|
| 282 |
+
max_value=1.0,
|
| 283 |
+
value=0.45
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# Input method selection
|
| 287 |
+
input_method = st.sidebar.radio(
|
| 288 |
+
"Input Source",
|
| 289 |
+
["Webcam", "Upload Image", "Upload Video"]
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
# Global variables for tracking detections
|
| 293 |
+
last_crash_time = None
|
| 294 |
+
crash_detected = False
|
| 295 |
+
crash_severity = "None"
|
| 296 |
+
crash_analysis = "None"
|
| 297 |
+
crash_alert_duration = 10 # seconds to show alert after crash detection
|
| 298 |
+
latest_crash_image = None
|
| 299 |
+
alert_sent_for_crash = False
|
| 300 |
+
|
| 301 |
+
# Statistics
|
| 302 |
+
if 'total_detections' not in st.session_state:
|
| 303 |
+
st.session_state.total_detections = 0
|
| 304 |
+
if 'total_crashes' not in st.session_state:
|
| 305 |
+
st.session_state.total_crashes = 0
|
| 306 |
+
if 'severe_crashes' not in st.session_state:
|
| 307 |
+
st.session_state.severe_crashes = 0
|
| 308 |
+
if 'alerts_sent' not in st.session_state:
|
| 309 |
+
st.session_state.alerts_sent = 0
|
| 310 |
+
|
| 311 |
+
# Create columns for the main display area
|
| 312 |
+
col1, col2 = st.columns([2, 1])
|
| 313 |
+
|
| 314 |
+
# Create a single map placeholder that will be populated only once
|
| 315 |
+
map_container = st.container()
|
| 316 |
+
|
| 317 |
+
# Image display area in column 1
|
| 318 |
+
with col1:
|
| 319 |
+
frame_placeholder = st.empty()
|
| 320 |
+
# Initial image
|
| 321 |
+
sample_img = np.zeros((480, 640, 3), dtype=np.uint8)
|
| 322 |
+
frame_placeholder.image(sample_img, channels="BGR", use_column_width=True)
|
| 323 |
+
|
| 324 |
+
# Info area in column 2
|
| 325 |
+
with col2:
|
| 326 |
+
status_placeholder = st.empty()
|
| 327 |
+
severity_placeholder = st.empty()
|
| 328 |
+
analysis_placeholder = st.empty()
|
| 329 |
+
timestamp_placeholder = st.empty()
|
| 330 |
+
location_placeholder = st.empty()
|
| 331 |
+
alert_status_placeholder = st.empty()
|
| 332 |
+
|
| 333 |
+
# Initialize displays
|
| 334 |
+
status_placeholder.markdown("""
|
| 335 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 336 |
+
<h3>Status: Monitoring</h3>
|
| 337 |
+
</div>
|
| 338 |
+
""", unsafe_allow_html=True)
|
| 339 |
+
|
| 340 |
+
severity_placeholder.markdown("""
|
| 341 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 342 |
+
<h4>Crash Severity:</h4>
|
| 343 |
+
<p>None</p>
|
| 344 |
+
</div>
|
| 345 |
+
""", unsafe_allow_html=True)
|
| 346 |
+
|
| 347 |
+
analysis_placeholder.markdown("""
|
| 348 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 349 |
+
<h4>Crash Analysis:</h4>
|
| 350 |
+
<p>None</p>
|
| 351 |
+
</div>
|
| 352 |
+
""", unsafe_allow_html=True)
|
| 353 |
+
|
| 354 |
+
timestamp_placeholder.markdown("""
|
| 355 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 356 |
+
<h4>Timestamp:</h4>
|
| 357 |
+
<p>N/A</p>
|
| 358 |
+
</div>
|
| 359 |
+
""", unsafe_allow_html=True)
|
| 360 |
+
|
| 361 |
+
location_placeholder.markdown("""
|
| 362 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 363 |
+
<h4>Location:</h4>
|
| 364 |
+
<p>N/A</p>
|
| 365 |
+
</div>
|
| 366 |
+
""", unsafe_allow_html=True)
|
| 367 |
+
|
| 368 |
+
# Add a placeholder for the map in the map container
|
| 369 |
+
with map_container:
|
| 370 |
+
map_placeholder = st.empty()
|
| 371 |
+
|
| 372 |
+
# Initialize the map only once
|
| 373 |
+
initial_location = get_current_location()
|
| 374 |
+
m = folium.Map(location=[initial_location["lat"], initial_location["lng"]], zoom_start=15)
|
| 375 |
+
folium.Marker(
|
| 376 |
+
[initial_location["lat"], initial_location["lng"]],
|
| 377 |
+
popup="Current Location",
|
| 378 |
+
tooltip="Current Location"
|
| 379 |
+
).add_to(m)
|
| 380 |
+
map_placeholder.empty() # Clear initially, will be populated when needed
|
| 381 |
+
|
| 382 |
+
def handle_crash_detection(image, is_video=False, is_webcam=False):
|
| 383 |
+
"""
|
| 384 |
+
Unified function to handle crash detection and all subsequent actions
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
image: The image/frame to process
|
| 388 |
+
is_video: Whether this is from a video source
|
| 389 |
+
is_webcam: Whether this is from a webcam
|
| 390 |
+
|
| 391 |
+
Returns:
|
| 392 |
+
Dictionary with results and whether to stop processing
|
| 393 |
+
"""
|
| 394 |
+
global crash_detected, crash_severity, crash_analysis, last_crash_time, latest_crash_image, alert_sent_for_crash
|
| 395 |
+
|
| 396 |
+
# Increment total detections
|
| 397 |
+
st.session_state.total_detections += 1
|
| 398 |
+
|
| 399 |
+
# Detect crash
|
| 400 |
+
detection_result = detect_crash(image)
|
| 401 |
+
|
| 402 |
+
# Update image with annotations
|
| 403 |
+
annotated_image = detection_result["annotated_image"]
|
| 404 |
+
frame_placeholder.image(annotated_image, channels="BGR", use_column_width=True)
|
| 405 |
+
|
| 406 |
+
# If crash detected
|
| 407 |
+
if detection_result["crash_detected"]:
|
| 408 |
+
# Set global variables
|
| 409 |
+
crash_detected = True
|
| 410 |
+
crash_severity = detection_result["severity"]
|
| 411 |
+
last_crash_time = time.time()
|
| 412 |
+
latest_crash_image = annotated_image.copy()
|
| 413 |
+
alert_sent_for_crash = False
|
| 414 |
+
|
| 415 |
+
# Get detailed analysis from Gemini
|
| 416 |
+
crash_analysis = assess_crash_severity(image, detection_result)
|
| 417 |
+
|
| 418 |
+
# Update crash statistics
|
| 419 |
+
st.session_state.total_crashes += 1
|
| 420 |
+
if crash_severity.lower() == "severe":
|
| 421 |
+
st.session_state.severe_crashes += 1
|
| 422 |
+
|
| 423 |
+
# Update info display
|
| 424 |
+
update_info_display()
|
| 425 |
+
|
| 426 |
+
# Get current location
|
| 427 |
+
location = get_current_location()
|
| 428 |
+
|
| 429 |
+
# Prepare crash data
|
| 430 |
+
crash_data = {
|
| 431 |
+
"timestamp": datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S'),
|
| 432 |
+
"severity": crash_severity,
|
| 433 |
+
"analysis": crash_analysis,
|
| 434 |
+
"location": location,
|
| 435 |
+
"raw_detection": detection_result["raw_result"]
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
# Send alert
|
| 439 |
+
success, message = send_crash_alert_twilio(crash_data)
|
| 440 |
+
|
| 441 |
+
if success:
|
| 442 |
+
alert_sent_for_crash = True
|
| 443 |
+
st.session_state.alerts_sent += 1
|
| 444 |
+
alert_status_placeholder.success(f"Alert sent: {message}")
|
| 445 |
+
else:
|
| 446 |
+
alert_status_placeholder.error(f"Alert failed: {message}")
|
| 447 |
+
|
| 448 |
+
# Return result indicating whether to stop processing
|
| 449 |
+
return {
|
| 450 |
+
"crash_detected": True,
|
| 451 |
+
"should_stop": is_video and not is_webcam # Stop if video but not webcam
|
| 452 |
+
}
|
| 453 |
+
else:
|
| 454 |
+
# Update info display for monitoring state
|
| 455 |
+
status_placeholder.markdown("""
|
| 456 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #4CAF50; color: white;">
|
| 457 |
+
<h3>Status: Monitoring</h3>
|
| 458 |
+
</div>
|
| 459 |
+
""", unsafe_allow_html=True)
|
| 460 |
+
|
| 461 |
+
return {
|
| 462 |
+
"crash_detected": False,
|
| 463 |
+
"should_stop": False
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
def update_info_display():
|
| 467 |
+
"""Update the information display"""
|
| 468 |
+
global crash_detected, crash_severity, crash_analysis, last_crash_time
|
| 469 |
+
|
| 470 |
+
# Check if crash alert should be active
|
| 471 |
+
current_time = time.time()
|
| 472 |
+
if last_crash_time and (current_time - last_crash_time > crash_alert_duration):
|
| 473 |
+
crash_detected = False
|
| 474 |
+
|
| 475 |
+
# Update status
|
| 476 |
+
if crash_detected:
|
| 477 |
+
status_placeholder.markdown(f"""
|
| 478 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #FF4B4B; color: white;">
|
| 479 |
+
<h3>Status: CRASH DETECTED! 🚨</h3>
|
| 480 |
+
</div>
|
| 481 |
+
""", unsafe_allow_html=True)
|
| 482 |
+
else:
|
| 483 |
+
status_placeholder.markdown("""
|
| 484 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #4CAF50; color: white;">
|
| 485 |
+
<h3>Status: Monitoring</h3>
|
| 486 |
+
</div>
|
| 487 |
+
""", unsafe_allow_html=True)
|
| 488 |
+
|
| 489 |
+
# Update severity
|
| 490 |
+
if crash_detected:
|
| 491 |
+
severity_color = "#FF4B4B" if crash_severity.lower() == "severe" else "#FFA500"
|
| 492 |
+
severity_placeholder.markdown(f"""
|
| 493 |
+
<div style="padding: 10px; border-radius: 5px; background-color: {severity_color}; color: white;">
|
| 494 |
+
<h4>Crash Severity:</h4>
|
| 495 |
+
<p>{crash_severity}</p>
|
| 496 |
+
</div>
|
| 497 |
+
""", unsafe_allow_html=True)
|
| 498 |
+
|
| 499 |
+
# Update analysis
|
| 500 |
+
analysis_placeholder.markdown(f"""
|
| 501 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 502 |
+
<h4>Crash Analysis:</h4>
|
| 503 |
+
<p>{crash_analysis}</p>
|
| 504 |
+
</div>
|
| 505 |
+
""", unsafe_allow_html=True)
|
| 506 |
+
else:
|
| 507 |
+
severity_placeholder.markdown("""
|
| 508 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 509 |
+
<h4>Crash Severity:</h4>
|
| 510 |
+
<p>None</p>
|
| 511 |
+
</div>
|
| 512 |
+
""", unsafe_allow_html=True)
|
| 513 |
+
|
| 514 |
+
analysis_placeholder.markdown("""
|
| 515 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 516 |
+
<h4>Crash Analysis:</h4>
|
| 517 |
+
<p>None</p>
|
| 518 |
+
</div>
|
| 519 |
+
""", unsafe_allow_html=True)
|
| 520 |
+
|
| 521 |
+
# Update timestamp
|
| 522 |
+
if last_crash_time:
|
| 523 |
+
crash_time = datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S')
|
| 524 |
+
timestamp_placeholder.markdown(f"""
|
| 525 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 526 |
+
<h4>Last Crash Detected:</h4>
|
| 527 |
+
<p>{crash_time}</p>
|
| 528 |
+
</div>
|
| 529 |
+
""", unsafe_allow_html=True)
|
| 530 |
+
|
| 531 |
+
# Update location
|
| 532 |
+
location = get_current_location()
|
| 533 |
+
location_placeholder.markdown(f"""
|
| 534 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 535 |
+
<h4>Location:</h4>
|
| 536 |
+
<p>{location['address']}</p>
|
| 537 |
+
</div>
|
| 538 |
+
""", unsafe_allow_html=True)
|
| 539 |
+
|
| 540 |
+
# Update map with crash location
|
| 541 |
+
m = folium.Map(location=[location["lat"], location["lng"]], zoom_start=15)
|
| 542 |
+
folium.Marker(
|
| 543 |
+
[location["lat"], location["lng"]],
|
| 544 |
+
popup=f"Crash Location<br>Severity: {crash_severity}<br>Time: {crash_time}",
|
| 545 |
+
tooltip="Crash Location",
|
| 546 |
+
icon=folium.Icon(color='red', icon='warning-sign')
|
| 547 |
+
).add_to(m)
|
| 548 |
+
|
| 549 |
+
# Only update the map once in the map container
|
| 550 |
+
with map_container:
|
| 551 |
+
folium_static(m)
|
| 552 |
+
else:
|
| 553 |
+
timestamp_placeholder.markdown("""
|
| 554 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 555 |
+
<h4>Timestamp:</h4>
|
| 556 |
+
<p>N/A</p>
|
| 557 |
+
</div>
|
| 558 |
+
""", unsafe_allow_html=True)
|
| 559 |
+
|
| 560 |
+
location_placeholder.markdown("""
|
| 561 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
|
| 562 |
+
<h4>Location:</h4>
|
| 563 |
+
<p>N/A</p>
|
| 564 |
+
</div>
|
| 565 |
+
""", unsafe_allow_html=True)
|
| 566 |
+
|
| 567 |
+
# Handle different input methods
|
| 568 |
+
if input_method == "Webcam":
|
| 569 |
+
# Add webcam selection
|
| 570 |
+
webcam_source = st.sidebar.selectbox(
|
| 571 |
+
"Select Camera",
|
| 572 |
+
["0", "1", "2", "3"],
|
| 573 |
+
index=0
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
start_button = st.sidebar.button("Start Detection")
|
| 577 |
+
stop_button = st.sidebar.button("Stop Detection")
|
| 578 |
+
|
| 579 |
+
if start_button:
|
| 580 |
+
try:
|
| 581 |
+
cap = cv2.VideoCapture(int(webcam_source))
|
| 582 |
+
if not cap.isOpened():
|
| 583 |
+
st.error(f"Cannot open webcam {webcam_source}")
|
| 584 |
+
else:
|
| 585 |
+
st.session_state.webcam_running = True
|
| 586 |
+
|
| 587 |
+
while st.session_state.webcam_running and not stop_button:
|
| 588 |
+
ret, frame = cap.read()
|
| 589 |
+
if not ret:
|
| 590 |
+
st.error("Failed to capture frame from webcam")
|
| 591 |
+
break
|
| 592 |
+
|
| 593 |
+
# Process frame with unified handler
|
| 594 |
+
result = handle_crash_detection(frame, is_video=True, is_webcam=True)
|
| 595 |
+
|
| 596 |
+
# Rerun to check for stop button
|
| 597 |
+
time.sleep(0.1)
|
| 598 |
+
|
| 599 |
+
# Release resources
|
| 600 |
+
cap.release()
|
| 601 |
+
st.session_state.webcam_running = False
|
| 602 |
+
|
| 603 |
+
except Exception as e:
|
| 604 |
+
st.error(f"Error accessing webcam: {e}")
|
| 605 |
+
|
| 606 |
+
if stop_button and 'webcam_running' in st.session_state:
|
| 607 |
+
st.session_state.webcam_running = False
|
| 608 |
+
st.success("Detection stopped")
|
| 609 |
+
|
| 610 |
+
elif input_method == "Upload Image":
|
| 611 |
+
uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
|
| 612 |
+
|
| 613 |
+
if uploaded_file is not None:
|
| 614 |
+
# Read image
|
| 615 |
+
image_bytes = uploaded_file.read()
|
| 616 |
+
image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
|
| 617 |
+
|
| 618 |
+
# Display original image
|
| 619 |
+
frame_placeholder.image(image, channels="BGR", caption="Uploaded Image", use_column_width=True)
|
| 620 |
+
|
| 621 |
+
# Process button
|
| 622 |
+
if st.sidebar.button("Process Image"):
|
| 623 |
+
# Process the image with unified handler
|
| 624 |
+
handle_crash_detection(image)
|
| 625 |
+
|
| 626 |
+
elif input_method == "Upload Video":
|
| 627 |
+
uploaded_file = st.sidebar.file_uploader("Choose a video...", type=["mp4", "avi", "mov"])
|
| 628 |
+
|
| 629 |
+
if uploaded_file is not None:
|
| 630 |
+
# Save to temporary file
|
| 631 |
+
tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
|
| 632 |
+
tfile.write(uploaded_file.read())
|
| 633 |
+
tfile_path = tfile.name
|
| 634 |
+
tfile.close()
|
| 635 |
+
|
| 636 |
+
# Process button
|
| 637 |
+
if st.sidebar.button("Process Video"):
|
| 638 |
+
stop_processing = st.sidebar.button("Stop Processing")
|
| 639 |
+
|
| 640 |
+
try:
|
| 641 |
+
cap = cv2.VideoCapture(tfile_path)
|
| 642 |
+
|
| 643 |
+
if not cap.isOpened():
|
| 644 |
+
st.error("Cannot open video file")
|
| 645 |
+
else:
|
| 646 |
+
# Get video info
|
| 647 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 648 |
+
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 649 |
+
|
| 650 |
+
# Add progress bar
|
| 651 |
+
progress_bar = st.sidebar.progress(0)
|
| 652 |
+
frame_number = 0
|
| 653 |
+
|
| 654 |
+
# Process video
|
| 655 |
+
st.session_state.video_running = True
|
| 656 |
+
should_stop = False
|
| 657 |
+
|
| 658 |
+
while st.session_state.video_running and not stop_processing and not should_stop:
|
| 659 |
+
ret, frame = cap.read()
|
| 660 |
+
if not ret:
|
| 661 |
+
break
|
| 662 |
+
|
| 663 |
+
# Process frame with unified handler
|
| 664 |
+
result = handle_crash_detection(frame, is_video=True, is_webcam=False)
|
| 665 |
+
should_stop = result["should_stop"]
|
| 666 |
+
|
| 667 |
+
# If crash detected and it's a video, stop processing
|
| 668 |
+
if should_stop:
|
| 669 |
+
st.success("Crash detected! Video processing stopped.")
|
| 670 |
+
break
|
| 671 |
+
|
| 672 |
+
# Update progress
|
| 673 |
+
frame_number += 1
|
| 674 |
+
progress_bar.progress(min(frame_number / frame_count, 1.0))
|
| 675 |
+
|
| 676 |
+
# Process frames faster than real-time
|
| 677 |
+
time.sleep(0.05)
|
| 678 |
+
|
| 679 |
+
# Release resources
|
| 680 |
+
cap.release()
|
| 681 |
+
|
| 682 |
+
# Clean up
|
| 683 |
+
os.unlink(tfile_path)
|
| 684 |
+
st.session_state.video_running = False
|
| 685 |
+
|
| 686 |
+
# If video finished without crash detection
|
| 687 |
+
if not should_stop and frame_number >= frame_count:
|
| 688 |
+
st.info("Video processed. No crashes detected.")
|
| 689 |
+
|
| 690 |
+
except Exception as e:
|
| 691 |
+
st.error(f"Error processing video: {e}")
|
| 692 |
+
try:
|
| 693 |
+
os.unlink(tfile_path)
|
| 694 |
+
except:
|
| 695 |
+
pass
|
| 696 |
+
|
| 697 |
+
# Stop button
|
| 698 |
+
if st.sidebar.button("Stop", key="stop_video") and 'video_running' in st.session_state:
|
| 699 |
+
st.session_state.video_running = False
|
| 700 |
+
st.success("Processing stopped")
|
| 701 |
+
|
| 702 |
+
# Add metrics/statistics section at the bottom
|
| 703 |
+
st.markdown("---")
|
| 704 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 705 |
+
|
| 706 |
+
with col1:
|
| 707 |
+
st.markdown(f"""
|
| 708 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
|
| 709 |
+
<h4>Total Detections</h4>
|
| 710 |
+
<h2>{st.session_state.total_detections}</h2>
|
| 711 |
+
</div>
|
| 712 |
+
""", unsafe_allow_html=True)
|
| 713 |
+
|
| 714 |
+
with col2:
|
| 715 |
+
st.markdown(f"""
|
| 716 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
|
| 717 |
+
<h4>Total Crashes</h4>
|
| 718 |
+
<h2>{st.session_state.total_crashes}</h2>
|
| 719 |
+
</div>
|
| 720 |
+
""", unsafe_allow_html=True)
|
| 721 |
+
|
| 722 |
+
with col3:
|
| 723 |
+
st.markdown(f"""
|
| 724 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
|
| 725 |
+
<h4>Severe Crashes</h4>
|
| 726 |
+
<h2>{st.session_state.severe_crashes}</h2>
|
| 727 |
+
</div>
|
| 728 |
+
""", unsafe_allow_html=True)
|
| 729 |
+
|
| 730 |
+
with col4:
|
| 731 |
+
st.markdown(f"""
|
| 732 |
+
<div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
|
| 733 |
+
<h4>SMS Alerts Sent</h4>
|
| 734 |
+
<h2>{st.session_state.alerts_sent}</h2>
|
| 735 |
+
</div>
|
| 736 |
+
""", unsafe_allow_html=True)
|
| 737 |
+
|
| 738 |
+
# Footer
|
| 739 |
+
st.markdown("---")
|
| 740 |
+
st.markdown("""
|
| 741 |
+
<p style='text-align: center;'>Vehicle Crash Detection and Severity Assessment System</p>
|
| 742 |
+
<p style='text-align: center;'>© 2025</p>
|
| 743 |
""", unsafe_allow_html=True)
|