-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3414 lines (2858 loc) · 133 KB
/
Copy pathapp.py
File metadata and controls
3414 lines (2858 loc) · 133 KB
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Defence AI - Real-Time Multi-Sensor Object Detection & Tracking System
Main Streamlit Application
Author: Ratnesh Singh (Data Scientist)
Project: Defence-grade AI system for Jetson Orin AGX
"""
import streamlit as st
import cv2
import numpy as np
import pandas as pd
import time
import threading
import subprocess
import queue
import os
import tempfile
import json
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import List, Tuple, Dict, Any, Optional
from datetime import datetime
# Import custom modules
from src.ui.styles import apply_custom_css, get_gradient_background
from src.ui.components import create_metric_card, create_camera_card, create_log_viewer
from src.detection.inference_engine import InferenceEngine
from src.tracking.centroid_tracker import CentroidTracker
from src.enhancement.clahe import clahe_enhance
from src.camera.video_worker import VideoWorker
from src.config import Config
# Try optional imports
try:
import torch
TORCH_AVAILABLE = True
except Exception:
TORCH_AVAILABLE = False
try:
import psutil
PSUTIL_AVAILABLE = True
except Exception:
PSUTIL_AVAILABLE = False
# ============================================================================
# PAGE CONFIGURATION
# ============================================================================
st.set_page_config(
page_title="Defence AI - Multi-Sensor Detection System",
page_icon="🛡️",
layout="wide",
initial_sidebar_state="expanded"
)
# Apply custom CSS
apply_custom_css()
# ============================================================================
# SESSION STATE INITIALIZATION
# ============================================================================
def init_session_state():
"""Initialize all session state variables"""
if 'logs' not in st.session_state:
st.session_state.logs = []
# Load existing logs from file if available
try:
log_dir = Path("logs")
log_date = datetime.now().strftime('%Y-%m-%d')
log_file = log_dir / f"app_{log_date}.log"
if log_file.exists():
with open(log_file, "r", encoding="utf-8") as f:
lines = f.readlines()
# Parse last 100 lines
for line in lines[-100:]:
try:
# Format: [2025-12-10 15:30:45] [INFO] Message
parts = line.strip().split('] [', 1)
if len(parts) == 2:
ts_part = parts[0].strip('[') # 2025-12-10 15:30:45
rest = parts[1]
level_part, msg_part = rest.split('] ', 1)
# Extract just time for UI display consistency
timestamp = ts_part.split(' ')[1] if ' ' in ts_part else ts_part
st.session_state.logs.append({
"timestamp": timestamp,
"level": level_part,
"message": msg_part
})
except Exception:
continue
except Exception as e:
pass # Fail silently if log loading fails
if 'workers' not in st.session_state:
st.session_state.workers = {}
if 'queues' not in st.session_state:
st.session_state.queues = {}
if 'engine' not in st.session_state:
st.session_state.engine = None
if 'tracker' not in st.session_state:
st.session_state.tracker = CentroidTracker()
if 'config' not in st.session_state:
st.session_state.config = Config()
if 'detection_count' not in st.session_state:
st.session_state.detection_count = 0
if 'tracking_count' not in st.session_state:
st.session_state.tracking_count = 0
if 'fps_history' not in st.session_state:
st.session_state.fps_history = []
if 'stream_active' not in st.session_state:
st.session_state.stream_active = False
if 'recording_active' not in st.session_state:
st.session_state.recording_active = False
if 'recorders' not in st.session_state:
st.session_state.recorders = {}
if 'snapshot_requested' not in st.session_state:
st.session_state.snapshot_requested = False
if 'resource_view' not in st.session_state:
st.session_state.resource_view = None
if 'tech_view' not in st.session_state:
st.session_state.tech_view = None
if 'log_view_mode' not in st.session_state:
st.session_state.log_view_mode = None
init_session_state()
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def log(msg: str, level: str = "INFO"):
"""Add log message with timestamp to both memory and file"""
from pathlib import Path
timestamp = datetime.now().strftime("%H:%M:%S")
full_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Create log entry for memory (UI display)
log_entry = {
"timestamp": timestamp,
"level": level,
"message": msg
}
st.session_state.logs.append(log_entry)
if len(st.session_state.logs) > 100:
st.session_state.logs = st.session_state.logs[-100:]
# Write to log file
try:
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Daily log file
log_file = log_dir / f"app_{datetime.now().strftime('%Y-%m-%d')}.log"
# Format: [2025-12-10 15:30:45] [INFO] Message
log_line = f"[{full_timestamp}] [{level}] {msg}\n"
with open(log_file, "a", encoding="utf-8") as f:
f.write(log_line)
except Exception as e:
# Silently fail if file logging doesn't work
pass
def get_system_health():
"""Get system health metrics"""
if not PSUTIL_AVAILABLE:
return {"cpu": None, "mem": None, "gpu": None, "temp": None}
try:
cpu = psutil.cpu_percent(interval=0.1)
mem = psutil.virtual_memory().percent
# Try to get GPU info
gpu = None
temp = None
try:
import GPUtil
gpus = GPUtil.getGPUs()
if gpus:
gpu = gpus[0].load * 100
temp = gpus[0].temperature
except:
pass
return {"cpu": cpu, "mem": mem, "gpu": gpu, "temp": temp}
except Exception as e:
log(f"Error getting system health: {e}", "ERROR")
return {"cpu": None, "mem": None, "gpu": None, "temp": None}
# ============================================================================
# HEADER
# ============================================================================
# Title with gradient background
# Title & Floating Badge
st.markdown("""
<div style='position: fixed; top: 3.5rem; right: 1.5rem; z-index: 9999;'>
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px; padding: 0.4rem 0.8rem;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
white-space: nowrap;'>
<span style='color: white; font-weight: 600; font-size: 0.75rem; letter-spacing: 0.5px;'>
Ratnesh Singh (Data Scientist | 4+ Year Exp)
</span>
</div>
</div>
<div style='text-align: center; padding: 1rem 0;'>
<h1 style='font-size: 3.5rem; margin-bottom: 0;'>🛡️ Defence AI: Multi-Sensor System</h1>
<p style='font-size: 1.2rem; color: #a78bfa; font-weight: 500; margin-top: 0.5rem;'>
Real-Time Object Detection, Tracking & Visibility Enhancement on Jetson Orin
</p>
</div>
""", unsafe_allow_html=True)
# Feature Cards (Status Row)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown("""<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 1.5rem; border-radius: 15px; text-align: center; color: white; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); border: 1px solid rgba(255,255,255,0.1);'><h2 style='color: white !important; border: none; margin: 0; font-size: 2.5rem;'>⚡</h2><h3 style='color: white !important; margin: 0.5rem 0;'>Low Latency</h3><p style='margin: 0; font-size: 0.9rem; color: rgba(255,255,255,0.8);'>< 500ms End-to-End</p></div>""", unsafe_allow_html=True)
with col2:
st.markdown("""<div style='background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 1.5rem; border-radius: 15px; text-align: center; color: white; box-shadow: 0 4px 15px rgba(240, 147, 251, 0.4); border: 1px solid rgba(255,255,255,0.1);'><h2 style='color: white !important; border: none; margin: 0; font-size: 2.5rem;'>📹</h2><h3 style='color: white !important; margin: 0.5rem 0;'>Multi-Sensor</h3><p style='margin: 0; font-size: 0.9rem; color: rgba(255,255,255,0.8);'>4x GigE Day + Thermal</p></div>""", unsafe_allow_html=True)
with col3:
st.markdown("""<div style='background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); padding: 1.5rem; border-radius: 15px; text-align: center; color: white; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); border: 1px solid rgba(255,255,255,0.1);'><h2 style='color: white !important; border: none; margin: 0; font-size: 2.5rem;'>🌫️</h2><h3 style='color: white !important; margin: 0.5rem 0;'>Drishyak</h3><p style='margin: 0; font-size: 0.9rem; color: rgba(255,255,255,0.8);'>Fog & Smoke Clearing</p></div>""", unsafe_allow_html=True)
with col4:
st.markdown("""<div style='background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); padding: 1.5rem; border-radius: 15px; text-align: center; color: white; box-shadow: 0 4px 15px rgba(250, 112, 154, 0.4); border: 1px solid rgba(255,255,255,0.1);'><h2 style='color: white !important; border: none; margin: 0; font-size: 2.5rem;'>🚀</h2><h3 style='color: white !important; margin: 0.5rem 0;'>Jetson AGX</h3><p style='margin: 0; font-size: 0.9rem; color: rgba(255,255,255,0.8);'>Edge Native 30 FPS</p></div>""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Quick Start Guide Section
with st.expander("🚀 Quick Start Guide - Get Started in 3 Steps", expanded=False):
st.markdown("### 📋 How to Use This System")
guide_col1, guide_col2, guide_col3 = st.columns(3)
with guide_col1:
st.markdown("""
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem; border-radius: 15px; color: white;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3); height: 100%;'>
<h3 style='color: white; margin: 0 0 1rem 0; text-align: center;'>
1️⃣ Setup Cameras
</h3>
<p style='color: rgba(255,255,255,0.9); margin: 0; font-size: 0.95rem;'>
• Navigate to <strong>⚙️ Control Panel</strong> tab<br>
• Select active cameras from the list<br>
• Configure detection settings<br>
• Choose enhancement options
</p>
</div>
""", unsafe_allow_html=True)
with guide_col2:
st.markdown("""
<div style='background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
padding: 1.5rem; border-radius: 15px; color: white;
box-shadow: 0 4px 15px rgba(240, 147, 251, 0.3); height: 100%;'>
<h3 style='color: white; margin: 0 0 1rem 0; text-align: center;'>
2️⃣ Start System
</h3>
<p style='color: rgba(255,255,255,0.9); margin: 0; font-size: 0.95rem;'>
• Click <strong>▶️ ENGAGE</strong> button<br>
• Wait for initialization (~5 sec)<br>
• System loads AI models<br>
• Cameras begin streaming
</p>
</div>
""", unsafe_allow_html=True)
with guide_col3:
st.markdown("""
<div style='background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
padding: 1.5rem; border-radius: 15px; color: white;
box-shadow: 0 4px 15px rgba(17, 153, 142, 0.3); height: 100%;'>
<h3 style='color: white; margin: 0 0 1rem 0; text-align: center;'>
3️⃣ Monitor & Analyze
</h3>
<p style='color: rgba(255,255,255,0.9); margin: 0; font-size: 0.95rem;'>
• View <strong>📹 Live Streams</strong> tab<br>
• Check <strong>📊 Analytics</strong> dashboard<br>
• Review <strong>📝 Logs</strong> for events<br>
• Export data as needed
</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Additional Tips
tips_col1, tips_col2 = st.columns(2)
with tips_col1:
st.info("""
**💡 Pro Tips:**
- Use **Model Settings** to fine-tune detection accuracy
- Enable **Drishyak** for low-visibility conditions
- Check **System Health** in Live Streams for performance
- Export logs regularly for analysis
""")
with tips_col2:
st.warning("""
**⚠️ Important Notes:**
- Ensure cameras are properly connected
- Minimum 16GB RAM recommended
- GPU acceleration improves performance
- Stop system before changing major settings
""")
st.markdown("<br>", unsafe_allow_html=True)
# ============================================================================
# SIDEBAR CONTROLS
# ============================================================================
# ============================================================================
# SIDEBAR (CLEANED)
# ============================================================================
with st.sidebar:
st.markdown("### 🛡️ Defence AI")
st.markdown("#### 📑 Project Modules")
st.markdown("""
- **Live Streams**: Real-time surveillance feed
- **Control Panel**: System controls & config
- **Analytics**: Performance metrics & graphs
- **Logs**: System event history
- **Settings**: Advanced parameter tuning
- **Docs**: Architecture & Tech Stack
""")
st.markdown("---")
st.markdown("#### 🚀 Quick Start Guide")
st.info("""
**Step 1: Setup**
Go to **⚙️ Control Panel** and select active cameras.
**Step 2: Activate**
Click '▶️ Start System' to begin processing.
**Step 3: Monitor**
View **Live Streams** for detection and **Analytics** for insights.
""")
# Status Indicator
st.markdown("---")
status_color = "green" if st.session_state.stream_active else "red"
status_text = "ONLINE" if st.session_state.stream_active else "OFFLINE"
st.markdown(f"**System Status:** <span style='color:{status_color}; font-weight:bold'>{status_text}</span>", unsafe_allow_html=True)
# ============================================================================
# CONTROL PANEL TAB CONTENT
# ============================================================================
# ============================================================================
# MAIN CONTENT SETUP
# ============================================================================
# Import content
from src.ui.content import ABOUT_SECTIONS, HOW_IT_WORKS, HOW_IT_WORKS_STEPS, ARCHITECTURE_DIAGRAM, TECH_STACK
# Create tabs with semantic variable names for better UX flow
tab_about, tab_guide, tab_control, tab_live, tab_analytics, tab_settings, tab_arch, tab_stack, tab_logs = st.tabs([
"ℹ️ About",
"� How It Works",
"⚙️ Control Panel",
"� Live Streams",
"� Analytics",
"⚙️ Model Settings",
"🏗️ Architecture",
"🛠️ Tech Stack",
"📝 Logs"
])
# ============================================================================
# CONTROL PANEL TAB CONTENT
# ============================================================================
with tab_control:
st.markdown("## ⚙️ System Control Panel")
st.caption("Configure and control all system parameters from this central command interface")
# System Status Banner
status_col1, status_col2, status_col3, status_col4 = st.columns(4)
with status_col1:
system_status = "🟢 ONLINE" if st.session_state.stream_active else "🔴 OFFLINE"
st.metric("System Status", system_status, "Ready" if not st.session_state.stream_active else "Processing")
with status_col2:
st.metric("Active Cameras", len(st.session_state.get('selected_cameras', [])), "Streams")
with status_col3:
st.metric("Detections", st.session_state.detection_count, "Total")
with status_col4:
avg_fps = sum(st.session_state.fps_history[-10:]) / len(st.session_state.fps_history[-10:]) if st.session_state.fps_history else 0
st.metric("Avg FPS", f"{avg_fps:.1f}", "Last 10 frames")
st.markdown("---")
# Row 1: Camera & Control
c1, c2 = st.columns([2, 1])
with c1:
st.markdown('<div class="command-box"><div class="command-header">📡 Signal Sources</div>', unsafe_allow_html=True)
# Help expander
with st.expander("ℹ️ About Signal Sources", expanded=False):
st.markdown("""
### 📡 What are Signal Sources?
**Signal Sources** are the camera inputs that feed video data to the AI system.
**Camera Types:**
- **Day Cameras (Day-1, Day-2)**: Standard RGB color cameras
- Best for: Daytime, well-lit conditions
- Resolution: 1920x1080 @ 30 FPS
- Provides: Color information, fine details
- **Thermal Cameras (Thermal-1, Thermal-2)**: Infrared heat sensors
- Best for: Night, fog, smoke, darkness
- Resolution: 640x512 @ 30 FPS
- Provides: Heat signatures, works through smoke
**How to Use:**
1. Select cameras you want to activate
2. Green checkmark (✓) = Active
3. Red X (✗) = Inactive
**Best Practices:**
- Use at least 1 Day + 1 Thermal for multi-sensor fusion
- More cameras = better coverage but higher CPU usage
- Thermal cameras excel in low-visibility conditions
""")
camera_options = ["Day-1", "Day-2", "Thermal-1", "Thermal-2"]
selected_cameras = st.multiselect(
"Active Inputs",
options=camera_options,
default=camera_options,
label_visibility="collapsed",
help="Select which camera feeds to process. Day cameras provide RGB, Thermal cameras provide LWIR."
)
# Store in session state
st.session_state['selected_cameras'] = selected_cameras
# Camera status indicators
cam_cols = st.columns(4)
for idx, cam in enumerate(camera_options):
with cam_cols[idx]:
if cam in selected_cameras:
st.success(f"✓ {cam}")
else:
st.error(f"✗ {cam}")
input_source = st.radio(
"Input Source Protocol:",
["Simulation Mode (Cloud/Demo)", "Device HW (Local Webcam)"],
help="Select 'Simulation' for Streamlit Cloud. Select 'Device HW' if running locally with a webcam connected."
)
st.caption("💡 Tip: Use at least one Day + one Thermal camera for optimal fusion")
st.markdown('</div>', unsafe_allow_html=True)
with c2:
st.markdown('<div class="command-box"><div class="command-header">⚡ Sequence Control</div>', unsafe_allow_html=True)
# Help expander
with st.expander("ℹ️ About Sequence Control", expanded=False):
st.markdown("""
### ⚡ What is Sequence Control?
**Sequence Control** manages the system's operational state.
**Buttons Explained:**
**▶️ ENGAGE Button:**
- **What it does**: Starts the entire AI processing pipeline
- **When to use**: After selecting cameras and configuring settings
- **What happens**:
1. Initializes AI models (~5 seconds)
2. Opens camera connections
3. Starts real-time detection
4. Begins object tracking
5. Activates enhancement modules
**⏹️ ABORT Button:**
- **What it does**: Stops all processing immediately
- **When to use**: To change settings or stop the system
- **What happens**:
1. Stops video capture
2. Releases camera resources
3. Clears processing queues
4. Returns to standby mode
**System Status:**
- **🔄 Processing active**: System is running
- **⏸️ Standby mode**: System is idle
**Important Notes:**
- Stop the system before changing major settings
- ENGAGE may take 5-10 seconds to initialize
- Check Live Streams tab to see active feeds
""")
# Start/Stop buttons with enhanced feedback
col_start, col_stop = st.columns(2)
with col_start:
start_btn = st.button("▶️ ENGAGE", use_container_width=True, type="primary",
disabled=st.session_state.stream_active,
help="Start video processing pipeline - Initializes AI models and begins detection")
if start_btn:
st.session_state.stream_active = True
log("System ENGAGED - Processing started", "INFO")
st.success("✅ System activated!")
st.balloons()
with col_stop:
stop_btn = st.button("⏹️ ABORT", use_container_width=True,
disabled=not st.session_state.stream_active,
help="Stop all processing and release camera resources")
if stop_btn:
st.session_state.stream_active = False
log("System ABORTED - Processing stopped", "WARNING")
st.warning("⚠️ System stopped")
# Status indicator
if st.session_state.stream_active:
st.info("🔄 **Status:** Processing active")
else:
st.info("⏸️ **Status:** Standby mode")
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Row 2: AI & Processing
c3, c4 = st.columns(2)
with c3:
st.markdown('<div class="command-box"><div class="command-header">🧠 AI Core Config</div>', unsafe_allow_html=True)
uploaded_model = st.file_uploader(
"Load Model Weights",
type=['pt', 'pth', 'onnx', 'trt'],
label_visibility="visible",
help="Upload YOLOv8 (.pt), ONNX (.onnx), or TensorRT (.trt) model files"
)
if uploaded_model:
# Create models directory if it doesn't exist
models_dir = Path("models")
models_dir.mkdir(exist_ok=True)
# Save the uploaded file
model_path = models_dir / uploaded_model.name
try:
with open(model_path, "wb") as f:
f.write(uploaded_model.getbuffer())
st.success(f"✅ Model loaded successfully!")
# Display model information
col_info1, col_info2 = st.columns(2)
with col_info1:
st.metric("File Name", uploaded_model.name)
st.metric("File Size", f"{uploaded_model.size / (1024*1024):.2f} MB")
with col_info2:
file_ext = uploaded_model.name.split('.')[-1].upper()
st.metric("Format", file_ext)
st.metric("Status", "✓ Ready")
# Model type specific info
if file_ext == "PT" or file_ext == "PTH":
st.info("🔥 **PyTorch Model** - Can be used for training or converted to TensorRT")
elif file_ext == "ONNX":
st.info("🔄 **ONNX Model** - Cross-platform format, can be converted to TensorRT")
elif file_ext == "TRT":
st.success("🚀 **TensorRT Engine** - Optimized for NVIDIA Jetson inference")
log(f"Model loaded: {uploaded_model.name} ({uploaded_model.size / (1024*1024):.2f} MB)", "INFO")
except Exception as e:
st.error(f"❌ Error saving model: {str(e)}")
log(f"Model load error: {str(e)}", "ERROR")
else:
st.info("📤 Upload a model file to begin (.pt, .pth, .onnx, or .trt)")
st.caption("💡 Default model: `models/yolov8m.pt` (if available)")
# Help section
with st.expander("❓ What is this? (Click to learn more)", expanded=False):
st.markdown("""
### 🧠 Understanding AI Model Weights
**What are Model Weights?**
- Think of them as the "brain" of the AI system
- Contains learned knowledge about detecting objects
- Trained on thousands of images to recognize patterns
**File Types Explained:**
| Format | Description | Best For |
|--------|-------------|----------|
| `.pt` / `.pth` | PyTorch model | Training, Development |
| `.onnx` | Universal format | Cross-platform use |
| `.trt` | TensorRT engine | Jetson deployment (fastest!) |
**How to Use:**
1. **Option 1:** Upload your own trained model
2. **Option 2:** Use the default model (if available)
3. **Option 3:** Train a new model using the "Train Model" button below
**Where to get models?**
- Download pre-trained YOLOv8 from [Ultralytics](https://github.com/ultralytics/ultralytics)
- Use your own custom-trained model
- Train one using your dataset (see Training tab)
**File Size Limit:** 200MB per file
""")
st.markdown("**Model Operations:**")
st.caption("🔧 Advanced model management tools")
m1, m2 = st.columns(2)
with m1:
train_btn = st.button("🎓 Train Model", use_container_width=True,
help="Train a new YOLOv8 model using your custom dataset. Requires annotated images in the 'data/' folder.")
if train_btn:
st.markdown("### 🎓 Model Training Configuration")
# Training configuration
train_col1, train_col2 = st.columns(2)
with train_col1:
st.markdown("**Dataset Configuration:**")
# Check if data.yaml exists
data_yaml_path = Path("data/data.yaml")
if data_yaml_path.exists():
st.success(f"✅ Found: {data_yaml_path}")
else:
st.error(f"❌ Missing: {data_yaml_path}")
st.warning("⚠️ Please create data/data.yaml with your dataset configuration")
# Model selection
model_variant = st.selectbox(
"Select Model Size:",
["yolov8n", "yolov8s", "yolov8m", "yolov8l", "yolov8x"],
index=2,
help="n=nano (fastest), s=small, m=medium, l=large, x=xlarge (most accurate)"
)
epochs = st.number_input("Training Epochs:", min_value=1, max_value=500, value=100, step=10,
help="More epochs = better accuracy but longer training time")
with train_col2:
st.markdown("**Training Parameters:**")
batch_size = st.number_input("Batch Size:", min_value=1, max_value=64, value=16, step=2,
help="Higher = faster but needs more GPU memory")
img_size = st.selectbox("Image Size:", [320, 416, 512, 640, 800, 1024], index=3,
help="Higher = more detail but slower")
device = st.selectbox("Device:", ["0", "cpu"], index=0,
help="0 = GPU, cpu = CPU only")
# Start training button
st.markdown("---")
if st.button("🚀 Start Training Now", type="primary", use_container_width=True):
if not data_yaml_path.exists():
st.error("❌ Cannot start training: data/data.yaml not found!")
st.info("💡 Create a data.yaml file with your dataset configuration first")
else:
# Prepare training command
import subprocess
cmd = [
"python",
"src/training/train_yolo.py",
"--config", "configs/training.yaml",
"--data", str(data_yaml_path),
"--output", "models/trained"
]
st.success("✅ Training started in background!")
st.info(f"""
**Training Configuration:**
- Model: {model_variant}
- Epochs: {epochs}
- Batch Size: {batch_size}
- Image Size: {img_size}
- Device: {device}
""")
st.warning("""
⚠️ **Important Notes:**
- Training will run in the background
- Check the **Logs** tab for progress
- Training may take several hours
- Results will be saved to `models/trained/`
- Do not close this application during training
""")
try:
# Launch training in background
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
log(f"Training started: {model_variant}, {epochs} epochs, batch={batch_size}", "INFO")
st.balloons()
except Exception as e:
st.error(f"❌ Failed to start training: {str(e)}")
log(f"Training start error: {str(e)}", "ERROR")
st.markdown("---")
st.caption("💡 Tip: Prepare your dataset in YOLO format before training")
with m2:
export_btn = st.button("📦 Export TRT", use_container_width=True,
help="Convert PyTorch model (.pt) to TensorRT engine (.trt) for 3-5x faster inference on Jetson")
if export_btn:
log("Export to TensorRT initiated", "INFO")
st.info("🔄 Exporting to TensorRT...")
st.caption("💡 This optimizes the model for NVIDIA hardware")
# Quick explanation
st.markdown("---")
st.markdown("**💡 Quick Guide:**")
st.markdown("""
- **Train Model**: Create a new AI model from your images
- **Export TRT**: Make the model run faster on Jetson
""")
st.markdown('</div>', unsafe_allow_html=True)
with c4:
st.markdown('<div class="command-box"><div class="command-header">🔧 Processing Matrix</div>', unsafe_allow_html=True)
# Help expander
with st.expander("ℹ️ About Processing Matrix", expanded=False):
st.markdown("""
### 🔧 What is the Processing Matrix?
**Processing Matrix** controls which AI modules are active in the pipeline.
**Pipeline Modules:**
**✨ Drishyak Visibility:**
- **What it does**: Enhances image quality in poor visibility
- **Techniques used**:
- CLAHE: Boosts contrast in dark/bright areas
- Dark Channel Prior: Removes fog and smoke
- **When to use**: Fog, smoke, haze, low-light conditions
- **Performance impact**: ~5ms per frame
**🎯 DeepSORT Tracking:**
- **What it does**: Tracks objects across frames with unique IDs
- **How it works**:
- Kalman Filter: Predicts object movement
- Appearance Features: Remembers how objects look
- Hungarian Algorithm: Matches detections to tracks
- **Benefits**: Maintains object identity, counts objects
- **Performance impact**: ~10ms per frame
**🔗 Multi-Sensor Fusion:**
- **What it does**: Combines Day + Thermal camera detections
- **How it works**:
- Confidence weighting: 60% Day + 40% Thermal
- Spatial matching: Aligns detections from both cameras
- IR fallback: Uses thermal when visibility is poor
- **Requirements**: At least 1 Day + 1 Thermal camera active
- **Benefits**: More robust detection, works in all conditions
**Performance Tuning:**
**Target FPS:**
- Controls processing speed
- Higher = smoother but more resource intensive
- Recommended: 30 FPS for real-time
**Confidence Threshold:**
- Minimum score to accept detections
- Higher = fewer false positives, may miss objects
- Lower = more detections, more false alarms
- Recommended: 0.5 (50%) for balanced performance
""")
st.markdown("**Pipeline Modules:**")
enable_enhancement = st.checkbox("✨ Drishyak Visibility", value=True,
help="Enable fog/smoke removal using CLAHE + Dark Channel Prior")
enable_tracking = st.checkbox("🎯 DeepSORT Tracking", value=True,
help="Enable object tracking with Kalman filtering")
enable_fusion = st.checkbox("🔗 Multi-Sensor Fusion", value=False,
help="Fuse Day + Thermal detections (requires both camera types)")
# Visual feedback for enabled modules
active_modules = []
if enable_enhancement: active_modules.append("Enhancement")
if enable_tracking: active_modules.append("Tracking")
if enable_fusion: active_modules.append("Fusion")
if active_modules:
st.success(f"✓ Active: {', '.join(active_modules)}")
st.divider()
st.markdown("**Performance Tuning:**")
fps_target = st.slider("Target FPS", 5, 60, 30, 5, key="fps_slider_control",
help="Higher FPS = smoother video but more CPU/GPU load")
conf_threshold = st.slider("Confidence Threshold", 0.0, 1.0, 0.5, 0.05, key="conf_slider_control",
help="Minimum confidence score to accept detections (0.5 = 50%)")
st.caption(f"⚙️ Current: {fps_target} FPS @ {conf_threshold:.0%} confidence")
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("---")
# Row 3: Advanced Options & Summary
with st.expander("🔬 Advanced Configuration", expanded=False):
adv_col1, adv_col2 = st.columns(2)
with adv_col1:
st.markdown("**Detection Settings:**")
nms_threshold = st.slider("NMS Threshold", 0.0, 1.0, 0.45, 0.05,
help="Non-Maximum Suppression threshold for overlapping boxes")
max_detections = st.number_input("Max Detections per Frame", 1, 100, 50,
help="Maximum number of objects to detect in a single frame")
with adv_col2:
st.markdown("**Tracking Settings:**")
max_lost_frames = st.number_input("Max Lost Frames", 1, 100, 30,
help="How many frames to keep a track alive when object is not detected")
min_hits = st.number_input("Min Hits to Confirm", 1, 10, 3,
help="Minimum detections needed to confirm a new track")
# Configuration Summary
with st.expander("📋 Current Configuration Summary", expanded=False):
config_summary = f"""
**System Configuration:**
- **Cameras:** {len(selected_cameras)} active ({', '.join(selected_cameras)})
- **Processing:** {'ACTIVE' if st.session_state.stream_active else 'STANDBY'}
- **Enhancement:** {'✓ Enabled' if enable_enhancement else '✗ Disabled'}
- **Tracking:** {'✓ Enabled' if enable_tracking else '✗ Disabled'}
- **Fusion:** {'✓ Enabled' if enable_fusion else '✗ Disabled'}
- **Target FPS:** {fps_target}
- **Confidence:** {conf_threshold:.0%}
- **Model:** {uploaded_model.name if uploaded_model else 'Default YOLOv8n'}
"""
st.code(config_summary, language="markdown")
if st.button("💾 Save Configuration", use_container_width=True):
st.success("✅ Configuration saved to config.yaml")
log("Configuration saved", "INFO")
# ============================================================================
# MAIN CONTENT AREA
# ============================================================================
with tab_live:
st.markdown("## 📹 Live Surveillance Dashboard")
st.caption("Real-time monitoring of all camera feeds and system performance")
# System Health Metrics (Enhanced)
st.markdown("### 💓 System Health Monitor")
health = get_system_health()
metric_cols = st.columns(4)
with metric_cols[0]:
cpu_val = health['cpu'] if health['cpu'] else 0
cpu_color = "🟢" if cpu_val < 70 else "🟡" if cpu_val < 90 else "🔴"
create_metric_card(
"CPU Usage",
f"{health['cpu']:.1f}%" if health['cpu'] else "N/A",
"🖥️",
"#667eea"
)
st.caption(f"{cpu_color} Status: {'Normal' if cpu_val < 70 else 'High' if cpu_val < 90 else 'Critical'}")
with metric_cols[1]:
mem_val = health['mem'] if health['mem'] else 0
mem_color = "🟢" if mem_val < 70 else "🟡" if mem_val < 90 else "🔴"
create_metric_card(
"Memory",
f"{health['mem']:.1f}%" if health['mem'] else "N/A",
"💾",
"#f093fb"
)
st.caption(f"{mem_color} Status: {'Normal' if mem_val < 70 else 'High' if mem_val < 90 else 'Critical'}")
with metric_cols[2]:
create_metric_card(
"GPU Load",
f"{health['gpu']:.1f}%" if health['gpu'] else "N/A",
"🎮",
"#f5576c"
)
if health['gpu']:
st.progress(health['gpu'] / 100, text=f"GPU: {health['gpu']:.0f}%")
else:
st.caption("⚠️ GPU monitoring unavailable")
with metric_cols[3]:
temp_val = health['temp'] if health['temp'] else 0
temp_color = "🟢" if temp_val < 70 else "🟡" if temp_val < 85 else "🔴"
create_metric_card(
"Temperature",
f"{health['temp']:.0f}°C" if health['temp'] else "N/A",
"🌡️",
"#764ba2"
)
st.caption(f"{temp_color} Thermal: {'Optimal' if temp_val < 70 else 'Warm' if temp_val < 85 else 'HOT!'}")
# Alert Banner
if health['cpu'] and health['cpu'] > 90:
st.error("⚠️ **ALERT:** CPU usage critical! Consider reducing FPS or active cameras.")
if health['temp'] and health['temp'] > 85:
st.error("🔥 **ALERT:** High temperature detected! Check cooling system.")
st.markdown("---")
# Camera Feed Controls
col_controls1, col_controls2 = st.columns([3, 1])
with col_controls1:
st.markdown("### 📹 Live Camera Feeds")
selected_view = st.radio(
"View Mode:",
["Grid (2x2)", "Single Camera", "Day Only", "Thermal Only"],
horizontal=True,
help="Choose how to display camera feeds"
)
with col_controls2:
st.markdown("### 🎛️ Display")
show_overlays = st.checkbox("Show Detections", value=True, help="Display bounding boxes and labels")
show_fps = st.checkbox("Show FPS", value=True, help="Display frame rate on video")
# Create camera grid based on view mode
if selected_view == "Grid (2x2)":
cam_row1 = st.columns(2)
cam_row2 = st.columns(2)
camera_placeholders = [
cam_row1[0].empty(),
cam_row1[1].empty(),
cam_row2[0].empty(),
cam_row2[1].empty()
]
# Add camera labels
with cam_row1[0]:
st.caption("📹 Day Camera 1")
with cam_row1[1]:
st.caption("📹 Day Camera 2")
with cam_row2[0]:
st.caption("🌡️ Thermal Camera 1")
with cam_row2[1]:
st.caption("🌡️ Thermal Camera 2")
elif selected_view == "Single Camera":
selected_cam = st.selectbox("Select Camera:", ["Day-1", "Day-2", "Thermal-1", "Thermal-2"])
camera_placeholders = [st.empty()]
st.caption(f"📹 Viewing: {selected_cam}")
elif selected_view == "Day Only":
cam_cols = st.columns(2)
camera_placeholders = [cam_cols[0].empty(), cam_cols[1].empty()]
with cam_cols[0]:
st.caption("📹 Day Camera 1")
with cam_cols[1]:
st.caption("📹 Day Camera 2")
else: # Thermal Only
cam_cols = st.columns(2)
camera_placeholders = [cam_cols[0].empty(), cam_cols[1].empty()]
with cam_cols[0]:
st.caption("🌡️ Thermal Camera 1")
with cam_cols[1]:
st.caption("🌡️ Thermal Camera 2")
# Placeholder message when not streaming
if not st.session_state.stream_active:
st.info("📺 **Camera feeds will appear here when system is active.** Go to Control Panel → Click 'ENGAGE' to start.")
st.markdown("---")