File size: 32,261 Bytes
e75ff1d
f10e9c0
 
 
 
 
 
 
 
f1fc825
f10e9c0
 
 
0d7f610
f10e9c0
 
 
 
 
 
 
e75ff1d
0d7f610
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
 
 
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
 
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
 
 
 
 
 
 
 
 
 
 
 
 
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75ff1d
 
f10e9c0
 
 
e75ff1d
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f2b56e
0d7f610
 
 
1f2b56e
0d7f610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f2b56e
0d7f610
 
 
 
 
 
 
 
 
 
1f2b56e
 
0d7f610
 
1f2b56e
 
 
0d7f610
 
 
 
 
1f2b56e
0d7f610
 
1f2b56e
 
 
 
 
 
 
 
0d7f610
1f2b56e
 
 
 
0d7f610
1f2b56e
 
0d7f610
 
1f2b56e
 
 
 
 
 
 
f10e9c0
 
 
 
 
 
 
 
 
 
e75ff1d
f10e9c0
 
 
e75ff1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f10e9c0
 
250504d
f10e9c0
250504d
f10e9c0
 
 
 
250504d
f10e9c0
 
 
250504d
f10e9c0
 
 
 
 
e75ff1d
 
250504d
e75ff1d
 
250504d
e75ff1d
 
 
250504d
e75ff1d
 
f10e9c0
 
 
250504d
e75ff1d
 
250504d
e75ff1d
 
 
 
250504d
e75ff1d
 
 
250504d
e75ff1d
 
 
 
250504d
f10e9c0
e75ff1d
 
 
 
250504d
f10e9c0
250504d
e75ff1d
250504d
 
 
 
 
 
0dbacdd
250504d
 
 
 
 
 
0dbacdd
250504d
 
 
 
 
0dbacdd
 
 
 
250504d
 
0dbacdd
250504d
 
0dbacdd
 
250504d
 
e75ff1d
 
 
250504d
 
 
 
 
 
 
 
e75ff1d
 
250504d
e75ff1d
 
 
250504d
e75ff1d
 
 
250504d
e75ff1d
250504d
e75ff1d
250504d
e75ff1d
 
 
250504d
e75ff1d
250504d
e75ff1d
250504d
e75ff1d
 
 
 
 
 
 
 
250504d
f9d8a61
250504d
f9d8a61
 
250504d
f10e9c0
 
250504d
e75ff1d
f10e9c0
e75ff1d
 
f10e9c0
 
250504d
0dbacdd
f10e9c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9008e80
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
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
import base64
import streamlit as st
import cv2
import numpy as np
import time
import tempfile
from PIL import Image
import io
import os
import imageio
import sys
import threading
from datetime import datetime
import av
import requests
import google.generativeai as genai
import folium
from streamlit_folium import folium_static
import geocoder
from twilio.rest import Client
from inference_sdk import InferenceHTTPClient
from inference_sdk import InferenceHTTPClient, InferenceConfiguration
# from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, RTCConfiguration

# Page configuration
st.set_page_config(
    page_title="Crash Detection System",
    page_icon="🚨",
    layout="wide"
)

# App title and description
st.markdown("<h1 style='text-align: center; color: #FF4B4B;'>Vehicle Crash Detection System</h1>", unsafe_allow_html=True)
st.markdown("""
    <p style='text-align: center; font-size: 1.2em;'>Real-time vehicle crash detection and severity assessment</p>
    """, unsafe_allow_html=True)

# Sidebar for API key and Twilio configuration
with st.sidebar.expander("API Configuration", expanded=False):
    api_key = st.text_input("Google Gemini API Key", type="password",value="AIzaSyCcf3s3GS7_925D7t2fgODc5WIKOMZSOzc")
    roboflow_api_key = st.text_input("Roboflow API Key", value="fWfYhVuhRbuPSffMaLMr", type="password")
    if api_key:
        genai.configure(api_key=api_key)
        st.success("Google API key configured!")
    if roboflow_api_key:
        st.success("Roboflow API key configured!")

with st.sidebar.expander("Twilio Configuration", expanded=False):
    twilio_account_sid = st.text_input("Twilio Account SID", type="password")
    twilio_auth_token = st.text_input("Twilio Auth Token", type="password")
    twilio_from_number = st.text_input("Twilio From Number")
    recipient_number = st.text_input("Recipient Phone Number")

@st.cache_resource
def initialize_roboflow_client():
    """Initialize the Roboflow client with caching"""
    return InferenceHTTPClient(
        api_url="https://serverless.roboflow.com",
        api_key=roboflow_api_key
    )

# Get the client
CLIENT = initialize_roboflow_client()

def detect_crash(image):
    """
    Detects crashes in an image using Roboflow YOLO model
    
    Args:
        image: PIL Image or numpy array
    
    Returns:
        Dictionary with crash detection results, annotated image, and crash details
    """
    try:
        # Convert to PIL Image if it's a numpy array
        if isinstance(image, np.ndarray):
            # Convert BGR (OpenCV) to RGB (PIL)
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(image_rgb)
        else:
            pil_image = image
            
        # Save image temporarily with reduced quality for faster upload
        temp_img_path = "temp_detection_image.jpg"
        pil_image.save(temp_img_path, "JPEG", quality=70)
        
        # Send to Roboflow for inference
        custom_configuration = InferenceConfiguration(confidence_threshold=0.85, iou_threshold=0.6)
        with CLIENT.use_configuration(custom_configuration):
            result = CLIENT.infer(temp_img_path, model_id="accident-detection-cwbvs/2")
        
        # Clean up temp file
        if os.path.exists(temp_img_path):
            os.remove(temp_img_path)
        
        # Initialize default response
        crash_detected = False
        severity = "None"
        annotated_image = None
        
        # Create annotated image (with bounding boxes)
        if isinstance(image, np.ndarray):
            annotated_image = image.copy()
        else:
            annotated_image = np.array(pil_image)
            # Convert back to BGR for OpenCV operations
            annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)
        
        # Process predictions if available
        if "predictions" in result and result["predictions"]:
            for pred in result["predictions"]:
                crash_detected = True
                
                # Extract severity based on class_id
                class_id = pred.get("class_id", 0)
                if class_id == 1:
                    severity = "Minor"
                elif class_id == 2:
                    severity = "Moderate"
                elif class_id == 3:
                    severity = "Severe"
                else:
                    # Default to Moderate for unclassified crashes
                    severity = "Moderate"
                
                # Draw bounding box on the image
                x, y = pred.get("x", 0), pred.get("y", 0)
                width, height = pred.get("width", 0), pred.get("height", 0)
                confidence = pred.get("confidence", 0)
                
                # Calculate coordinates for rectangle
                x1 = int(x - width/2)
                y1 = int(y - height/2)
                x2 = int(x + width/2)
                y2 = int(y + height/2)
                
                # Ensure coordinates are within image bounds
                img_height, img_width = annotated_image.shape[:2]
                x1 = max(0, min(x1, img_width-1))
                y1 = max(0, min(y1, img_height-1))
                x2 = max(0, min(x2, img_width-1))
                y2 = max(0, min(y2, img_height-1))
                
                # Set color based on severity
                if severity == "Minor":
                    color = (0, 255, 255)  # Yellow
                elif severity == "Moderate":
                    color = (0, 165, 255)  # Orange
                else:
                    color = (0, 0, 255)    # Red
                
                # Draw rectangle and label
                cv2.rectangle(annotated_image, (x1, y1), (x2, y2), color, 2)
                label = f"{severity} crash: {confidence:.2f}"
                cv2.putText(annotated_image, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
        
        return {
            "crash_detected": crash_detected,
            "severity": severity,
            "annotated_image": annotated_image,
            "raw_result": result
        }
    
    except Exception as e:
        st.error(f"Error in crash detection: {str(e)}")
        # Return original image if error occurs
        if isinstance(image, np.ndarray):
            return {"crash_detected": False, "severity": "Error", "annotated_image": image, "raw_result": {}}
        else:
            return {"crash_detected": False, "severity": "Error", "annotated_image": np.array(pil_image), "raw_result": {}}

def assess_crash_severity(image, crash_info):
    """
    Uses Google Gemini AI to assess crash severity in an image.
    
    Args:
        image: PIL Image or numpy array
        crash_info: Dictionary with crash detection results
    
    Returns:
        Detailed analysis as a string
    """
    if not api_key:
        return "API key not configured for detailed analysis"
    
    if not crash_info["crash_detected"]:
        return "No crash detected in this image"
    
    try:
        # Convert to PIL Image if it's a numpy array
        if isinstance(image, np.ndarray):
            image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
        else:
            image_pil = image
            
        # Use Gemini to assess severity
        model_gemini = genai.GenerativeModel("gemini-1.5-flash")
        prompt = f"""
        Analyze this vehicle crash image.
        Detected crash severity: {crash_info['severity']}
        Raw detection data: {crash_info['raw_result']}
        
        Give a short, 2-line analysis of the crash. Focus on:
        1. Apparent damage level and potential injuries
        2. Possible cause or contributing factors
        
        Keep your response concise and direct.
        """
        
        response = model_gemini.generate_content([prompt, image_pil])
        
        if response and hasattr(response, "text"):
            return response.text.strip()
        else:
            return "Unable to generate detailed analysis"
            
    except Exception as e:
        return f"Error in analysis: {str(e)}"

def get_current_location():
    """
    Get the current geolocation.
    Returns approximate location as a dictionary with lat, lng, address
    """
    try:
        g = geocoder.ip('me')
        return {
            "lat": g.lat,
            "lng": g.lng,
            "address": g.address
        }
    except Exception as e:
        return {
            "lat": 40.7128,  # Default to NYC coordinates
            "lng": -74.0060,
            "address": "Location unavailable"
        }

def send_crash_alert_twilio(crash_data):
    """
    Send a text message alert using Twilio

    Args:
        crash_data: Dictionary with crash details

    Returns:
        Boolean indicating success and message
    """
    messaging_service_sid = "MGf47912734231e47b941784b93376839d"
    if not twilio_account_sid or not twilio_auth_token or not recipient_number:
        return False, "Twilio configuration incomplete"

    try:
        # Initialize Twilio client
        client = Client(twilio_account_sid, twilio_auth_token)

        # Create message content
        message_body = f"""
        🚨 CRASH ALERT 🚨
        Time: {crash_data['timestamp']}
        Severity: {crash_data['severity']}
        """

        # Send message
        if twilio_from_number:
            message = client.messages.create(
                body=message_body,
                from_=twilio_from_number,
                to=recipient_number
            )
        else:
            message = client.messages.create(
                body=message_body,
                messaging_service_sid=messaging_service_sid,
                to=recipient_number
            )

        return True, f"Message sent with SID: {message.sid}"

    except Exception as e:
        return False, f"Failed to send alert: {str(e)}"

# FRONTEND IMPLEMENTATION
# Create sidebar for controls
st.sidebar.title("Controls")

# Detection settings
confidence_threshold = st.sidebar.slider(
    "Detection Confidence", 
    min_value=0.0, 
    max_value=1.0, 
    value=0.45
)

# Input method selection
input_method = st.sidebar.radio(
    "Input Source",
    ["Webcam", "Upload Image", "Upload Video"]
)

# Global variables for tracking detections
last_crash_time = None
crash_detected = False
crash_severity = "None"
crash_analysis = "None"
latest_crash_image = None
alert_sent = False

# Statistics
if 'total_detections' not in st.session_state:
    st.session_state.total_detections = 0
if 'total_crashes' not in st.session_state:
    st.session_state.total_crashes = 0
if 'severe_crashes' not in st.session_state:
    st.session_state.severe_crashes = 0
if 'alerts_sent' not in st.session_state:
    st.session_state.alerts_sent = 0

# Create columns for the main display area
col1, col2 = st.columns([2, 1])

# Create a single map placeholder that will be populated only once
map_container = st.container()

# Image display area in column 1
with col1:
    frame_placeholder = st.empty()
    # Initial image
    sample_img = np.zeros((480, 640, 3), dtype=np.uint8)
    frame_placeholder.image(sample_img, channels="BGR")

# Info area in column 2
with col2:
    status_placeholder = st.empty()
    severity_placeholder = st.empty()
    analysis_placeholder = st.empty()
    timestamp_placeholder = st.empty()
    location_placeholder = st.empty()
    alert_status_placeholder = st.empty()
    
    # Initialize displays
    status_placeholder.markdown("""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
            <h3>Status: Monitoring</h3>
        </div>
    """, unsafe_allow_html=True)
    
    severity_placeholder.markdown("""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
            <h4>Crash Severity:</h4>
            <p>None</p>
        </div>
    """, unsafe_allow_html=True)
    
    analysis_placeholder.markdown("""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
            <h4>Crash Analysis:</h4>
            <p>None</p>
        </div>
    """, unsafe_allow_html=True)
    
    timestamp_placeholder.markdown("""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
            <h4>Timestamp:</h4>
            <p>N/A</p>
        </div>
    """, unsafe_allow_html=True)
    
    location_placeholder.markdown("""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
            <h4>Location:</h4>
            <p>N/A</p>
        </div>
    """, unsafe_allow_html=True)

# Add a placeholder for the map in the map container
with map_container:
    map_placeholder = st.empty()
    
    # Initialize the map only once
    initial_location = get_current_location()
    m = folium.Map(location=[initial_location["lat"], initial_location["lng"]], zoom_start=15)
    folium.Marker(
        [initial_location["lat"], initial_location["lng"]],
        popup="Current Location",
        tooltip="Current Location"
    ).add_to(m)
    map_placeholder.empty()  # Clear initially, will be populated when needed

def update_info_display(custom_analysis=None):
    """Update the information display"""
    global crash_detected, crash_severity, crash_analysis, last_crash_time
    
    # Update status
    if crash_detected:
        status_placeholder.markdown(f"""
            <div style="padding: 10px; border-radius: 5px; background-color: #FF4B4B; color: white;">
                <h3>Status: CRASH DETECTED! 🚨</h3>
            </div>
        """, unsafe_allow_html=True)
    else:
        status_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #4CAF50; color: white;">
                <h3>Status: Monitoring</h3>
            </div>
        """, unsafe_allow_html=True)
    
    # Update severity
    if crash_detected:
        severity_color = "#FF4B4B" if crash_severity.lower() == "severe" else "#FFA500"
        severity_placeholder.markdown(f"""
            <div style="padding: 10px; border-radius: 5px; background-color: {severity_color}; color: white;">
                <h4>Crash Severity:</h4>
                <p>{crash_severity}</p>
            </div>
        """, unsafe_allow_html=True)
        
        # Update analysis - use custom if provided
        display_analysis = custom_analysis if custom_analysis else crash_analysis
        analysis_placeholder.markdown(f"""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Crash Analysis:</h4>
                <p>{display_analysis}</p>
            </div>
        """, unsafe_allow_html=True)
    else:
        severity_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Crash Severity:</h4>
                <p>None</p>
            </div>
        """, unsafe_allow_html=True)
        
        analysis_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Crash Analysis:</h4>
                <p>None</p>
            </div>
        """, unsafe_allow_html=True)
    
    # Update timestamp
    if last_crash_time:
        crash_time = datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S')
        timestamp_placeholder.markdown(f"""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Last Crash Detected:</h4>
                <p>{crash_time}</p>
            </div>
        """, unsafe_allow_html=True)
        
        # Update location
        location = get_current_location()
        location_placeholder.markdown(f"""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Location:</h4>
                <p>{location['address']}</p>
            </div>
        """, unsafe_allow_html=True)
        
        # Update map with crash location
        m = folium.Map(location=[location["lat"], location["lng"]], zoom_start=15)
        folium.Marker(
            [location["lat"], location["lng"]],
            popup=f"Crash Location<br>Severity: {crash_severity}<br>Time: {crash_time}",
            tooltip="Crash Location",
            icon=folium.Icon(color='red', icon='warning-sign')
        ).add_to(m)
        
        # Only update the map once in the map container
        with map_container:
            folium_static(m)
    else:
        timestamp_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Timestamp:</h4>
                <p>N/A</p>
            </div>
        """, unsafe_allow_html=True)
        
        location_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0;">
                <h4>Location:</h4>
                <p>N/A</p>
            </div>
        """, unsafe_allow_html=True)


# Display status message
# status_placeholder.info("Starting camera... Please accept camera permissions when prompted.")
from camera_input_live import camera_input_live

# WebRTC streamer component
if input_method == "Webcam":
    # No need for webcam selection as camera_input_live handles that
    
    # Add start/stop buttons in sidebar
    col1, col2 = st.sidebar.columns(2)
    start_button = col1.button("Start Detection")
    stop_button = col2.button("Stop Detection")
    
    if start_button:
        st.session_state.webcam_running = True
    
    if stop_button:
        st.session_state.webcam_running = False
        st.success("Detection stopped")
    
    # Display status initially
    if not st.session_state.get("webcam_running", False):
        status_placeholder.markdown("""
            <div style="padding: 10px; border-radius: 5px; background-color: #858585; color: white;">
                <h3>Status: Idle</h3>
            </div>
        """, unsafe_allow_html=True)
    
    # Only show camera when running
    if st.session_state.get("webcam_running", False):
        # Get image from camera_input_live
        frame = camera_input_live()
        
        # Process frame if available
        if frame is not None:
            # Convert camera_input_live output to OpenCV format
            st.image(frame)
            bytes_data = frame.getvalue()
            cv2_frame = cv2.imdecode(np.frombuffer(bytes_data, np.uint8), cv2.IMREAD_COLOR)
            
            # Process frame for detection
            st.session_state.total_detections += 1
            detection_result = detect_crash(cv2_frame)
            
            # Update image with annotations
            # annotated_image = detection_result["annotated_image"] 
            # frame_placeholder.image(annotated_image, channels="BGR")
            
            # If crash detected, process further
            if detection_result["crash_detected"] and not alert_sent:
                # Set crash data
                crash_detected = True
                crash_severity = detection_result["severity"]
                last_crash_time = time.time()
                
                # Update statistics
                st.session_state.total_crashes += 1
                if crash_severity.lower() == "severe":
                    st.session_state.severe_crashes += 1
                
                # Get analysis from Gemini
                crash_analysis = assess_crash_severity(cv2_frame, detection_result)
                
                # Update info display
                update_info_display()
                
                # Send alert only once
                location = get_current_location()
                crash_data = {
                    "timestamp": datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S'),
                    "severity": crash_severity,
                    "analysis": crash_analysis,
                    "location": location,
                    "raw_detection": detection_result["raw_result"]
                }
                
                success, message = send_crash_alert_twilio(crash_data)
                if success:
                    st.session_state.alerts_sent += 1
                    alert_status_placeholder.success(f"Alert sent: {message}")
                    alert_sent = True
                else:
                    alert_status_placeholder.error(f"Alert failed: {message}")
            
            # Status update if no crash
            if not detection_result["crash_detected"]:
                status_placeholder.markdown("""
                    <div style="padding: 10px; border-radius: 5px; background-color: #4CAF50; color: white;">
                        <h3>Status: Monitoring</h3>
                    </div>
                """, unsafe_allow_html=True)


elif input_method == "Upload Image":
    uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
    
    if uploaded_file is not None:
        # Read image
        image_bytes = uploaded_file.read()
        image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR)
        
        # Display original image
        frame_placeholder.image(image, channels="BGR", caption="Uploaded Image")
        
        # Process button
        if st.sidebar.button("Process Image"):
            # Increment counter
            st.session_state.total_detections += 1
            
            # Process the image
            with st.spinner("Processing image..."):
                detection_result = detect_crash(image)
                
                # Display annotated image
                annotated_image = detection_result["annotated_image"]
                frame_placeholder.image(annotated_image, channels="BGR", caption="Processed Image")
                
                # If crash detected
                if detection_result["crash_detected"]:
                    # Set crash data
                    crash_detected = True
                    crash_severity = detection_result["severity"]
                    last_crash_time = time.time()
                    
                    # Update statistics
                    st.session_state.total_crashes += 1
                    if crash_severity.lower() == "severe":
                        st.session_state.severe_crashes += 1
                    
                    # Get analysis from Gemini
                    crash_analysis = assess_crash_severity(image, detection_result)
                    
                    # Update info display
                    update_info_display()
                    
                    # Send alert
                    location = get_current_location()
                    crash_data = {
                        "timestamp": datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S'),
                        "severity": crash_severity,
                        "analysis": crash_analysis,
                        "location": location,
                        "raw_detection": detection_result["raw_result"]
                    }
                    
                    success, message = send_crash_alert_twilio(crash_data)
                    if success:
                        st.session_state.alerts_sent += 1
                        alert_status_placeholder.success(f"Alert sent: {message}")
                    else:
                        alert_status_placeholder.error(f"Alert failed: {message}")
                else:
                    st.info("No crash detected in this image.")
                    
                    # Update monitoring status
                    status_placeholder.markdown("""
                        <div style="padding: 10px; border-radius: 5px; background-color: #4CAF50; color: white;">
                            <h3>Status: Monitoring</h3>
                        </div>
                    """, unsafe_allow_html=True)


elif input_method == "Upload Video":
    uploaded_file = st.sidebar.file_uploader("Choose a video...", type=["mp4", "avi", "mov"])

    if uploaded_file is not None:
        # Save uploaded file temporarily
        tfile = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
        tfile.write(uploaded_file.read())
        tfile_path = tfile.name
        tfile.close()

        if st.sidebar.button("Process Video"):
            try:
                cap = cv2.VideoCapture(tfile_path)

                if not cap.isOpened():
                    st.error("Cannot open video file")
                else:
                    fps = cap.get(cv2.CAP_PROP_FPS)
                    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

                    processed_frames = []
                    crash_frames = []

                    progress_bar = st.progress(0)
                    status_text = st.empty()
                    status_text.text(f"Analyzing video... (0/{frame_count} frames)")

                    frame_number = 0
                    while True:
                        ret, frame = cap.read()
                        if not ret:
                            break

                        st.session_state.total_detections += 1
                        detection_result = detect_crash(frame)

                        processed_frames.append({
                            "frame": detection_result["annotated_image"],
                            "result": detection_result
                        })

                        if detection_result["crash_detected"]:
                            crash_frames.append({
                                "frame_number": frame_number,
                                "frame": frame.copy(),
                                "detection_result": detection_result,
                                "timestamp": time.time(),
                                "severity": detection_result["severity"]
                            })

                        frame_number += 1
                        if frame_number % 5 == 0 or frame_number == frame_count:
                            progress_value = min(frame_number / frame_count, 1.0)
                            progress_bar.progress(progress_value)
                            status_text.text(f"Analyzing video... ({frame_number}/{frame_count} frames)")

                    cap.release()

                    status_text.text("Creating processed video...")
                    output_video_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name

                    if processed_frames:
                        first_frame = processed_frames[0]["frame"]
                        h, w = first_frame.shape[:2]

                        fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Use 'mp4v' for compatibility
                        out = cv2.VideoWriter(output_video_path, fourcc, fps, (w, h))

                        for frame_data in processed_frames:
                            out.write(frame_data["frame"])

                        out.release()
                        time.sleep(0.5)  # Ensure the file is fully flushed

                        try:
                            with open(output_video_path, 'rb') as video_file:
                                video_bytes = video_file.read()

                            # Generate download link
                            b64 = base64.b64encode(video_bytes).decode()
                            href = f'<a href="data:video/mp4;base64,{b64}" download="processed_video.mp4">📥 Click here to download the processed video</a>'

                            status_text.empty()
                            progress_bar.empty()
                            st.markdown(href, unsafe_allow_html=True)

                        except Exception as e:
                            st.error(f"Error preparing video download: {e}")

                    st.success(f"Video analysis complete. {len(processed_frames)} frames processed, {len(crash_frames)} crashes detected.")

                    if crash_frames:
                        crash_frames.sort(key=lambda x: x["frame_number"])
                        last_crash = crash_frames[-1]

                        frame_placeholder.image(
                            last_crash["detection_result"]["annotated_image"],
                            channels="BGR",
                            caption=f"Last Detected Crash (Frame {last_crash['frame_number']})",
                            use_column_width=True
                        )

                        with st.spinner("Analyzing crash severity..."):
                            crash_analysis = assess_crash_severity(last_crash["frame"], last_crash["detection_result"])

                        crash_detected = True
                        crash_severity = last_crash["severity"]
                        last_crash_time = last_crash["timestamp"]

                        st.session_state.total_crashes += len(crash_frames)
                        severe_count = sum(1 for crash in crash_frames if crash["severity"].lower() == "severe")
                        st.session_state.severe_crashes += severe_count

                        update_info_display(custom_analysis=crash_analysis)

                        location = get_current_location()

                        crash_data = {
                            "timestamp": datetime.fromtimestamp(last_crash_time).strftime('%Y-%m-%d %H:%M:%S'),
                            "severity": crash_severity,
                            "analysis": crash_analysis,
                            "location": location,
                            "raw_detection": last_crash["detection_result"]["raw_result"]
                        }

                        success, message = send_crash_alert_twilio(crash_data)
                        if success:
                            st.session_state.alerts_sent += 1
                            alert_status_placeholder.success(f"Alert sent: {message}")
                        else:
                            alert_status_placeholder.error(f"Alert failed: {message}")
                    else:
                        st.info("No crashes detected in this video.")

                    try:
                        os.remove(output_video_path)
                    except:
                        pass

            except Exception as e:
                st.error(f"Error processing video: {e}")
                st.exception(e)
            finally:
                try:
                    if os.path.exists(tfile_path):
                        os.remove(tfile_path)
                except:
                    pass


st.markdown("---")
col1, col2, col3, col4 = st.columns(4)

with col1:
    st.markdown(f"""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
            <h4>Total Detections</h4>
            <h2>{st.session_state.total_detections}</h2>
        </div>
    """, unsafe_allow_html=True)

with col2:
    st.markdown(f"""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
            <h4>Total Crashes</h4>
            <h2>{st.session_state.total_crashes}</h2>
        </div>
    """, unsafe_allow_html=True)

with col3:
    st.markdown(f"""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
            <h4>Severe Crashes</h4>
            <h2>{st.session_state.severe_crashes}</h2>
        </div>
    """, unsafe_allow_html=True)

with col4:
    st.markdown(f"""
        <div style="padding: 10px; border-radius: 5px; background-color: #f0f0f0; text-align: center;">
            <h4>SMS Alerts Sent</h4>
            <h2>{st.session_state.alerts_sent}</h2>
        </div>
    """, unsafe_allow_html=True)

# Footer
st.markdown("---")
st.markdown("""
    <p style='text-align: center;'>Vehicle Crash Detection and Severity Assessment System</p>
    <p style='text-align: center;'>© 2025</p>
""", unsafe_allow_html=True)