File size: 28,111 Bytes
8c38d83
 
 
 
01e938d
 
 
 
4655d1b
 
 
 
8c38d83
 
01e938d
4655d1b
 
 
01e938d
 
8c38d83
 
01e938d
 
 
 
82d82cc
 
 
01e938d
8c38d83
 
 
01e938d
 
 
 
 
 
 
4655d1b
01e938d
 
 
82d82cc
8c38d83
01e938d
 
 
 
 
82d82cc
 
01e938d
 
 
 
 
 
 
 
82d82cc
01e938d
82d82cc
 
 
 
 
 
 
01e938d
 
 
 
 
 
 
 
 
 
 
 
82d82cc
01e938d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82d82cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c38d83
01e938d
8c38d83
01e938d
8c38d83
01e938d
 
 
 
 
 
8c38d83
82d82cc
 
 
 
01e938d
8c38d83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01e938d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c38d83
 
 
 
01e938d
 
 
8c38d83
 
 
 
01e938d
8c38d83
 
 
 
01e938d
8c38d83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01e938d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82d82cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01e938d
 
 
 
 
82d82cc
01e938d
82d82cc
 
01e938d
 
 
 
 
 
 
 
 
 
8c38d83
 
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
import streamlit as st
import cv2
import numpy as np
import os
import tempfile
import librosa
import librosa.display
import matplotlib.pyplot as plt
import tempfile
import librosa
import librosa.display
import matplotlib.pyplot as plt
from PIL import Image
import torch

# Import deforestation modules
from prediction_engine import load_onnx_model

# Import deforestation modules
from prediction_engine import load_onnx_model
from utils.helpers import calculate_deforestation_metrics, create_overlay

# Import audio classification modules
from utils.audio_processing import preprocess_audio
from utils.audio_model import load_audio_model, predict_audio, class_names

# Import YOLO detection modules
from utils.onnx_inference import YOLOv11

# Ensure torch classes path is initialized to avoid warnings
torch.classes.__path__ = []

# Set page config
st.set_page_config(
    page_title="Nature Nexus - Forest Surveillance",
    page_icon="🌳",
    layout="wide",
    initial_sidebar_state="expanded"
)


# Constants
DEFOREST_MODEL_INPUT_SIZE = 256
AUDIO_MODEL_PATH = "models/best_model.pth"
YOLO_MODEL_PATH = "models/best_model.onnx"

# Initialize session state for navigation
if 'current_service' not in st.session_state:
    st.session_state.current_service = 'deforestation'
if 'audio_input_method' not in st.session_state:
    st.session_state.audio_input_method = 'upload'
if 'detection_input_method' not in st.session_state:
    st.session_state.detection_input_method = 'image'

# Sidebar for navigation
with st.sidebar:
    st.title("Nature Nexus")
    st.subheader("Forest Surveillance System")
    
    selected_service = st.radio(
        "Select Service:",
        ["Deforestation Detection", "Forest Audio Surveillance", "Object Detection"]
    )
    
    if selected_service == "Deforestation Detection":
        st.session_state.current_service = 'deforestation'
    elif selected_service == "Forest Audio Surveillance":
        st.session_state.current_service = 'audio'
    else:
        st.session_state.current_service = 'detection'
    
    st.markdown("---")
    
    # Service-specific sidebar content
    if st.session_state.current_service == 'deforestation':
        st.info(
            """

            **Deforestation Detection**

            

            Upload satellite or aerial images to detect areas of deforestation.

            """
        )
    elif st.session_state.current_service == 'audio':
        st.info(
            """

            **Forest Audio Surveillance**

            

            Detect unusual human-related sounds in forested regions.

            """
        )
        
        # Audio service specific controls
        st.subheader("Audio Configuration")
        audio_input_method = st.radio(
            "Select Input Method:",
            ("Upload Audio", "Record Audio"),
            index=0 if st.session_state.audio_input_method == 'upload' else 1
        )
        st.session_state.audio_input_method = 'upload' if audio_input_method == "Upload Audio" else 'record'
        
        # Audio class information
        st.markdown("**Detection Classes:**")
        
        # Group classes by category
        human_sounds = ['footsteps', 'coughing', 'laughing', 'breathing', 
                       'drinking_sipping', 'snoring', 'sneezing']
        tool_sounds = ['chainsaw', 'hand_saw']
        vehicle_sounds = ['car_horn', 'engine', 'siren']
        other_sounds = ['crackling_fire', 'fireworks']
        
        st.markdown("πŸ‘€ **Human Sounds:** " + ", ".join([s.capitalize() for s in human_sounds]))
        st.markdown("πŸ”¨ **Tool Sounds:** " + ", ".join([s.capitalize() for s in tool_sounds]))
        st.markdown("πŸš— **Vehicle Sounds:** " + ", ".join([s.capitalize() for s in vehicle_sounds]))
        st.markdown("πŸ’₯ **Other Sounds:** " + ", ".join([s.capitalize() for s in other_sounds]))
    else:  # Object Detection
        st.info(
            """

            **Object Detection**

            

            Detect trespassers, vehicles, fires, and other objects in forest surveillance footage.

            """
        )
        
        # Detection service specific controls
        st.subheader("Detection Configuration")
        detection_input_method = st.radio(
            "Select Input Method:",
            ("Image", "Video", "Camera"),
            index=0 if st.session_state.detection_input_method == 'image' else 
                  (1 if st.session_state.detection_input_method == 'video' else 2)
        )
        
        if detection_input_method == "Image":
            st.session_state.detection_input_method = 'image'
        elif detection_input_method == "Video":
            st.session_state.detection_input_method = 'video'
        else:
            st.session_state.detection_input_method = 'camera'
            
        # Detection threshold controls
        st.subheader("Detection Settings")
        confidence = st.slider("Confidence Threshold", 0.0, 1.0, 0.5)
        iou_thres = st.slider("IoU Threshold", 0.0, 1.0, 0.5)
        
        # Detection class information
        st.markdown("**Detection Classes:**")
        st.markdown("🚴 **Bike/Bicycle**")
        st.markdown("🚚 **Bus/Truck**")
        st.markdown("πŸš— **Car**")
        st.markdown("πŸ”₯ **Fire**")
        st.markdown("πŸ‘€ **Human**")
        st.markdown("πŸ’¨ **Smoke**")

# Load deforestation model
@st.cache_resource
def load_cached_deforestation_model():
    model_path = "models/deforestation_model.onnx"
    return load_onnx_model(model_path, input_size=DEFOREST_MODEL_INPUT_SIZE)

# Load audio model
@st.cache_resource
def load_cached_audio_model():
    return load_audio_model(AUDIO_MODEL_PATH)

@st.cache_resource
def load_cached_yolo_model():
    return YOLOv11(YOLO_MODEL_PATH)

# Process image for deforestation detection
def process_image(model, image):
    """Process a single image and return results"""
    # Save original image dimensions for display
    orig_height, orig_width = image.shape[:2]

    # Make prediction
    mask = model.predict(image)

    # Resize mask back to original dimensions for display
    display_mask = cv2.resize(mask, (orig_width, orig_height))

    # Create binary mask for visualization
    binary_mask = (display_mask > 0.5).astype(np.uint8) * 255

    # Create colored overlay
    overlay = create_overlay(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), display_mask)

    # Calculate metrics
    metrics = calculate_deforestation_metrics(mask)

    return binary_mask, overlay, metrics

# Visualize audio for audio classification
def visualize_audio(audio_path):
    y, sr = librosa.load(audio_path, sr=16000)
    duration = len(y) / sr
    
    fig, ax = plt.subplots(2, 1, figsize=(10, 6))
    
    # Waveform plot
    librosa.display.waveshow(y, sr=sr, ax=ax[0])
    ax[0].set_title('Audio Waveform')
    ax[0].set_xlabel('Time (s)')
    ax[0].set_ylabel('Amplitude')
    
    # Spectrogram plot
    S = librosa.feature.melspectrogram(y=y, sr=sr)
    S_db = librosa.power_to_db(S, ref=np.max)
    img = librosa.display.specshow(S_db, sr=sr, x_axis='time', y_axis='mel', ax=ax[1])
    fig.colorbar(img, ax=ax[1], format='%+2.0f dB')
    ax[1].set_title('Mel Spectrogram')
    
    plt.tight_layout()
    st.pyplot(fig)
    
    return y, sr, duration

# Process audio for classification
def process_audio(audio_file):
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
        tmp_file.write(audio_file.read() if hasattr(audio_file, 'read') else audio_file)
        audio_path = tmp_file.name
    
    try:
        # Load audio model
        audio_model = load_cached_audio_model()
        
        # Visualize audio
        with st.spinner('Analyzing audio...'):
            y, sr, duration = visualize_audio(audio_path)
            st.caption(f"Audio duration: {duration:.2f} seconds")
        
        # Make prediction
        with st.spinner('Making prediction...'):
            class_name, confidence = predict_audio(audio_path, audio_model)
        
        # Display results
        st.subheader("Detection Results")
        
        col1, col2 = st.columns(2)
        with col1:
            st.metric("Detected Sound", class_name.replace('_', ' ').title())
        with col2:
            st.metric("Confidence", f"{confidence*100:.2f}%")
        
        # Show alerts based on class
        human_sounds = ['footsteps', 'coughing', 'laughing', 'breathing', 
                      'drinking_sipping', 'snoring', 'sneezing']
        tool_sounds = ['chainsaw', 'hand_saw']
        
        if class_name in human_sounds:
            st.warning("""

            ⚠️ **Human Activity Detected!**

            Potential human presence in the monitored area.

            """)
        elif class_name in tool_sounds:
            st.error("""

            🚨 **ALERT: Human Tool Detected!**

            Potential illegal logging or activity detected. Consider immediate verification.

            """)
        elif class_name in ['car_horn', 'engine', 'siren']:
            st.warning("""

            ⚠️ **Vehicle Detected!**

            Vehicle sounds detected in the monitored area.

            """)
        elif class_name == 'fireworks':
            st.error("""

            🚨 **ALERT: Fireworks Detected!**

            Potential fire hazard and disturbance to wildlife. Immediate verification required.

            """)
        elif class_name == 'crackling_fire':
            st.error("""

            🚨 **ALERT: Fire Detected!**

            Potential wildfire detected. Immediate verification required.

            """)
        else:
            st.success("βœ… Environmental sound detected - no immediate threat")
            
    except Exception as e:
        st.error(f"Error processing audio: {str(e)}")
        st.exception(e)
    finally:
        # Clean up temp file
        try:
            os.unlink(audio_path)
        except:
            pass

# Deforestation detection UI
def show_deforestation_detection():
    # App title and description
    st.title("🌳 Deforestation Detection")
    st.markdown(
        """

        This service detects areas of deforestation in satellite or aerial images of forests.

        Upload an image to get started!

        """
    )

    # Model info
    st.info(
        f"βš™οΈ Model optimized for {DEFOREST_MODEL_INPUT_SIZE}x{DEFOREST_MODEL_INPUT_SIZE} pixel images using ONNX runtime"
    )

    # Load model
    try:
        model = load_cached_deforestation_model()
    except Exception as e:
        st.error(f"Error loading model: {e}")
        st.info(
            "Make sure you have converted your PyTorch model to ONNX format using the utils/onnx_converter.py script."
        )
        st.code(
            "python -m utils.onnx_converter models/best_model_100.pth models/deforestation_model.onnx"
        )
        return

    # File uploader for images
    uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])

    if uploaded_file is not None:
        # Load image
        file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
        image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)

        # Display original image
        st.subheader("Original Image")
        st.image(
            cv2.cvtColor(image, cv2.COLOR_BGR2RGB),
            caption="Uploaded Image",
            use_container_width=True,
        )

        # Add a spinner while processing
        with st.spinner("Processing..."):
            try:
                # Process image
                binary_mask, overlay, metrics = process_image(model, image)

                # Display results in columns
                col1, col2 = st.columns(2)

                with col1:
                    st.subheader("Segmentation Result")
                    st.image(
                        binary_mask,
                        caption="Forest Areas (White)",
                        use_container_width=True,
                    )

                with col2:
                    st.subheader("Overlay Visualization")
                    st.image(
                        overlay,
                        caption="Green: Forest, Brown: Deforested",
                        use_container_width=True,
                    )

                # Display metrics
                st.subheader("Deforestation Analysis")

                # Create metrics cards
                metrics_col1, metrics_col2, metrics_col3 = st.columns(3)

                with metrics_col1:
                    st.metric(
                        label="Forest Coverage",
                        value=f"{metrics['forest_percentage']:.1f}%",
                    )

                with metrics_col2:
                    st.metric(
                        label="Deforested Area",
                        value=f"{metrics['deforested_percentage']:.1f}%",
                    )

                with metrics_col3:
                    st.metric(
                        label="Deforestation Level",
                        value=metrics["deforestation_level"],
                    )

            except Exception as e:
                st.error(f"Error during processing: {e}")

# Audio classification UI
def show_audio_classification():
    # App title and description
    st.title("🎧 Forest Audio Surveillance")
    st.markdown("""

    Detect unusual human-related sounds in forested regions to prevent illegal activities.

    Supported sounds: {}

    """.format(", ".join(class_names)))
    
    if st.session_state.audio_input_method == 'upload':
        st.header("Upload Audio File")
        
        sample_col, upload_col = st.columns(2)
        with sample_col:
            st.info("Upload a WAV, MP3 or OGG file with forest sounds")
            st.markdown("""

            **Tips for best results:**

            - Use audio with minimal background noise

            - Ensure the sound of interest is clear

            - 2-3 second clips work best

            """)
        
        with upload_col:
            audio_file = st.file_uploader(
                "Choose an audio file",
                type=["wav", "mp3", "ogg"],
                help="Supported formats: WAV, MP3, OGG"
            )
            
        if audio_file:
            st.success("File uploaded successfully!")
            with st.expander("Audio Preview", expanded=True):
                st.audio(audio_file)
            process_audio(audio_file)

    else:  # Record mode
        st.header("Record Live Audio")
        
        st.info("""

        Click the microphone button below to record a sound for analysis.  

        **Note:** Please ensure your browser has permission to access your microphone.  

        When prompted, click "Allow" to enable recording.

        """)
        
        recorded_audio = st.audio_input(
            label="Record a sound",
            key="audio_recorder",
            help="Click to record forest sounds for analysis",
            label_visibility="visible"
        )
        
        if recorded_audio:
            st.success("Audio recorded successfully!")
            with st.expander("Recorded Audio", expanded=True):
                st.audio(recorded_audio)
            process_audio(recorded_audio)
        else:
            st.write("Waiting for recording...")

# Object Detection UI
def show_object_detection():
    # App title and description
    st.title("πŸ” Forest Object Detection")
    st.markdown(
        """

        Detect trespassers, vehicles, fires, and other objects in forest surveillance footage.

        Choose an input method to begin detection.

        """
    )

    # Model info
    st.info("βš™οΈ Object detection model optimized with ONNX runtime for faster inference")

    # Load model
    try:
        model = load_cached_yolo_model()
        # Update model confidence and IoU thresholds from sidebar
        confidence = st.session_state.get('confidence', 0.5)
        iou_thres = st.session_state.get('iou_thres', 0.5)
        model.conf_thres = confidence
        model.iou_thres = iou_thres
    except Exception as e:
        st.error(f"Error loading model: {e}")
        st.info(
            "Make sure you have the YOLO ONNX model file available at models/best_model.onnx"
        )
        return

    # Input method based selection
    if st.session_state.detection_input_method == 'image':
        # Image upload
        img_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
        if img_file is not None:
            # Load image
            file_bytes = np.asarray(bytearray(img_file.read()), dtype=np.uint8)
            image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
            if image is not None:
                # Display original image
                st.subheader("Original Image")
                st.image(
                    cv2.cvtColor(image, cv2.COLOR_BGR2RGB),
                    caption="Uploaded Image",
                    use_container_width=True,
                )
                
                # Process with detection model
                with st.spinner("Processing image..."):
                    try:
                        detections = model.detect(image)
                        result_image = model.draw_detections(image.copy(), detections)
                        
                        # Display results
                        st.subheader("Detection Results")
                        st.image(
                            cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB),
                            caption="Detected Objects",
                            use_container_width=True,
                        )
                        
                        # Display detection statistics
                        st.subheader("Detection Statistics")
                        
                        # Count detections by class
                        class_counts = {}
                        for det in detections:
                            class_name = det['class']
                            if class_name in class_counts:
                                class_counts[class_name] += 1
                            else:
                                class_counts[class_name] = 1
                        
                        # Display counts with emojis
                        cols = st.columns(3)
                        col_idx = 0
                        
                        for class_name, count in class_counts.items():
                            emoji = "πŸ‘€" if class_name == "human" else (
                                   "πŸ”₯" if class_name == "fire" else (
                                   "πŸ’¨" if class_name == "smoke" else (
                                   "πŸš—" if class_name == "car" else (
                                   "🚴" if class_name == "bike-bicycle" else "🚚"))))
                            
                            with cols[col_idx % 3]:
                                st.metric(f"{emoji} {class_name.capitalize()}", count)
                            col_idx += 1
                        
                        # Check for priority threats
                        if "fire" in class_counts or "smoke" in class_counts:
                            st.error("🚨 **ALERT: Fire Detected!** Potential forest fire detected. Immediate action required.")
                        
                        if "human" in class_counts or "car" in class_counts or "bike-bicycle" in class_counts or "bus-truck" in class_counts:
                            st.warning("⚠️ **Trespassers Detected!** Unauthorized entry detected in monitored area.")
                            
                    except Exception as e:
                        st.error(f"Error during detection: {e}")
                        st.exception(e)
    
    elif st.session_state.detection_input_method == 'video':
        # Video upload
        video_file = st.file_uploader("Upload Video", type=["mp4", "avi", "mov"])
        if video_file is not None:
            # Save uploaded video to temp file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tfile:
                tfile.write(video_file.read())
                temp_video_path = tfile.name
            
            # Display video upload success
            st.success("Video uploaded successfully!")
            
            # Process video button
            if st.button("Process Video"):
                with st.spinner("Processing video... This may take a while."):
                    try:
                        # Open video file
                        cap = cv2.VideoCapture(temp_video_path)
                        
                        # Create video writer for output
                        output_path = "output_video.mp4"
                        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
                        fps = cap.get(cv2.CAP_PROP_FPS)
                        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
                        
                        # Create placeholder for video frames
                        video_placeholder = st.empty()
                        status_text = st.empty()
                        
                        # Process frames
                        frame_count = 0
                        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
                        
                        while cap.isOpened():
                            ret, frame = cap.read()
                            if not ret:
                                break
                                
                            # Process every 5th frame for speed
                            if frame_count % 5 == 0:
                                detections = model.detect(frame)
                                result_frame = model.draw_detections(frame.copy(), detections)
                                
                                # Update preview
                                if frame_count % 15 == 0:  # Update display less frequently
                                    video_placeholder.image(
                                        cv2.cvtColor(result_frame, cv2.COLOR_BGR2RGB),
                                        caption="Processing Video",
                                        use_container_width=True
                                    )
                                    progress = min(100, int((frame_count / total_frames) * 100))
                                    status_text.text(f"Processing: {progress}% complete")
                            else:
                                result_frame = frame  # Skip detection on some frames
                                
                            # Write frame to output video
                            out.write(result_frame)
                            frame_count += 1
                            
                        # Release resources
                        cap.release()
                        out.release()
                        
                        # Display completion message
                        st.success("Video processing complete!")
                        
                        # Provide download button for processed video
                        with open(output_path, "rb") as file:
                            st.download_button(
                                label="Download Processed Video",
                                data=file,
                                file_name="forest_surveillance_results.mp4",
                                mime="video/mp4"
                            )
                            
                    except Exception as e:
                        st.error(f"Error processing video: {e}")
                        st.exception(e)
                    finally:
                        # Clean up temp file
                        try:
                            os.unlink(temp_video_path)
                        except:
                            pass
    
    else:  # Camera mode
        # Live camera feed
        st.subheader("Live Camera Detection")
        st.info("Use your webcam to detect objects in real-time")
        
        cam = st.camera_input("Camera Feed")
        
        if cam:
            # Process camera input
            with st.spinner("Processing image..."):
                try:
                    # Convert image
                    image = cv2.imdecode(np.frombuffer(cam.getvalue(), np.uint8), cv2.IMREAD_COLOR)
                    
                    # Run detection
                    detections = model.detect(image)
                    result_image = model.draw_detections(image.copy(), detections)
                    
                    # Display results
                    st.image(
                        cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB),
                        caption="Detection Results",
                        use_container_width=True
                    )
                    
                    # Show detection summary
                    if detections:
                        # Count detections by class
                        class_counts = {}
                        for det in detections:
                            class_name = det['class']
                            if class_name in class_counts:
                                class_counts[class_name] += 1
                            else:
                                class_counts[class_name] = 1
                        
                        # Display as metrics
                        st.subheader("Detection Summary")
                        cols = st.columns(3)
                        for i, (class_name, count) in enumerate(class_counts.items()):
                            with cols[i % 3]:
                                st.metric(class_name.capitalize(), count)
                        
                        # Check for priority threats
                        if "fire" in class_counts or "smoke" in class_counts:
                            st.error("🚨 **ALERT: Fire Detected!** Potential forest fire detected.")
                        
                        if "human" in class_counts:
                            st.warning("⚠️ **Trespasser Detected!** Human presence detected.")
                    else:
                        st.info("No objects detected in frame")
                        
                except Exception as e:
                    st.error(f"Error processing camera feed: {e}")

# Main function
def main():
    # Check which service is selected and render appropriate UI
    if st.session_state.current_service == 'deforestation':
        show_deforestation_detection()
    elif st.session_state.current_service == 'audio':
        show_audio_classification()
    else:  # 'detection'
        show_object_detection()
    
    # Footer
    st.markdown("---")
    st.markdown("""

    <div style="text-align: center; padding: 10px;">

        <p>Nature Nexus - Forest Surveillance System | 🌳 Protect Natural Ecosystems</p>

        <p><small>Built with Streamlit and PyTorch</small></p>

    </div>

    """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()