-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
470 lines (388 loc) · 14.3 KB
/
Copy pathapp.py
File metadata and controls
470 lines (388 loc) · 14.3 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
"""
AI-Driven Home Security Target Detection System
Main Streamlit Application
"""
import streamlit as st
import cv2
import time
import numpy as np
from datetime import datetime
from typing import Optional, List
import threading
import queue
from video_source import VideoSource
from detection_engine import DetectionEngine
from mqtt_publisher import MQTTPublisher
from utils import (
annotate_frame,
crop_detection,
encode_image_base64,
resize_frame,
draw_fps,
format_detection_log,
adjust_brightness
)
# Page configuration
st.set_page_config(
page_title="AI Home Security Detection",
page_icon="🔒",
layout="wide",
initial_sidebar_state="expanded"
)
def initialize_session_state():
"""Initialize Streamlit session state variables"""
if 'running' not in st.session_state:
st.session_state.running = False
if 'video_source' not in st.session_state:
st.session_state.video_source = None
if 'detection_engine' not in st.session_state:
st.session_state.detection_engine = None
if 'mqtt_publisher' not in st.session_state:
st.session_state.mqtt_publisher = None
if 'detection_logs' not in st.session_state:
st.session_state.detection_logs = []
if 'last_detection' not in st.session_state:
st.session_state.last_detection = None
if 'last_detection_image' not in st.session_state:
st.session_state.last_detection_image = None
if 'stats' not in st.session_state:
st.session_state.stats = {'total_detections': 0, 'target_detections': 0, 'frames_processed': 0}
def sidebar_controls():
"""Render sidebar controls"""
st.sidebar.title("🔒 Security Detection System")
st.sidebar.markdown("---")
# Video Source Configuration
st.sidebar.subheader("📹 Video Source")
source_type = st.sidebar.selectbox(
"Source Type",
["Webcam", "RTSP Stream", "Video File"],
key="source_type"
)
if source_type == "Webcam":
source_input = st.sidebar.number_input(
"Camera Index",
min_value=0,
max_value=10,
value=0,
key="webcam_index"
)
source_type_key = "webcam"
elif source_type == "RTSP Stream":
source_input = st.sidebar.text_input(
"RTSP URL",
value="rtsp://example.com/stream",
key="rtsp_url"
)
source_type_key = "rtsp"
else: # Video File
source_input = st.sidebar.text_input(
"File Path",
value="/path/to/video.mp4",
key="file_path"
)
source_type_key = "file"
st.sidebar.markdown("---")
# YOLO Model Configuration
st.sidebar.subheader("🤖 Detection Model")
model_option = st.sidebar.selectbox(
"YOLO Model",
["yolov8n.pt", "yolov8s.pt", "yolov8m.pt", "yolov8l.pt", "Custom"],
index=1,
key="model_option"
)
if model_option == "Custom":
model_path = st.sidebar.text_input(
"Custom Model Path",
value="path/to/custom_model.pt",
key="custom_model_path"
)
else:
model_path = model_option
st.sidebar.markdown("---")
# Detection Configuration
st.sidebar.subheader("🎯 Target Configuration")
# Load model to get available classes
if st.sidebar.button("Load Model & Get Classes"):
with st.spinner("Loading model..."):
temp_engine = DetectionEngine(model_path)
if temp_engine.load_model():
st.session_state.available_classes = temp_engine.get_class_names()
st.success(f"Model loaded! {len(st.session_state.available_classes)} classes available")
else:
st.error("Failed to load model")
# Target class selection
if 'available_classes' in st.session_state:
target_class = st.sidebar.selectbox(
"Target Class",
st.session_state.available_classes,
key="target_class"
)
else:
target_class = st.sidebar.text_input(
"Target Class (load model first for list)",
value="person",
key="target_class_manual"
)
confidence_threshold = st.sidebar.slider(
"Confidence Threshold",
min_value=0.0,
max_value=1.0,
value=0.5,
step=0.05,
key="confidence_threshold"
)
st.sidebar.markdown("---")
# Display Options
st.sidebar.subheader("🎨 Display Options")
auto_brightness = st.sidebar.checkbox(
"Auto-adjust brightness (for dark cameras)",
value=True,
key="auto_brightness"
)
st.sidebar.markdown("---")
# MQTT Configuration
st.sidebar.subheader("📡 MQTT Configuration")
mqtt_broker = st.sidebar.text_input(
"Broker Address",
value="localhost",
key="mqtt_broker"
)
mqtt_port = st.sidebar.number_input(
"Port",
min_value=1,
max_value=65535,
value=1883,
key="mqtt_port"
)
mqtt_topic = st.sidebar.text_input(
"Topic",
value="irvine/home/bedroom/item",
key="mqtt_topic"
)
mqtt_username = st.sidebar.text_input(
"Username (optional)",
value="",
key="mqtt_username"
)
mqtt_password = st.sidebar.text_input(
"Password (optional)",
value="",
type="password",
key="mqtt_password"
)
include_image = st.sidebar.checkbox(
"Include image in MQTT payload",
value=False,
key="include_image"
)
st.sidebar.markdown("---")
return {
'source_input': source_input,
'source_type': source_type_key,
'model_path': model_path,
'target_class': target_class,
'confidence_threshold': confidence_threshold,
'auto_brightness': auto_brightness,
'mqtt_broker': mqtt_broker,
'mqtt_port': mqtt_port,
'mqtt_topic': mqtt_topic,
'mqtt_username': mqtt_username if mqtt_username else None,
'mqtt_password': mqtt_password if mqtt_password else None,
'include_image': include_image
}
def main():
"""Main application"""
initialize_session_state()
# Title
st.title("🔒 AI-Driven Home Security Detection System")
st.markdown("Real-time object detection with MQTT notifications")
# Get configuration from sidebar
config = sidebar_controls()
# Control buttons
col1, col2, col3 = st.columns([1, 1, 3])
with col1:
if st.button("▶️ Start Detection", disabled=st.session_state.running):
# Ensure clean state before starting
st.session_state.video_source = None
st.session_state.detection_engine = None
st.session_state.mqtt_publisher = None
st.session_state.detection_logs = []
st.session_state.last_detection = None
st.session_state.last_detection_image = None
st.session_state.stats = {'total_detections': 0, 'target_detections': 0, 'frames_processed': 0}
st.session_state.running = True
st.rerun()
with col2:
if st.button("⏹️ Stop Detection", disabled=not st.session_state.running):
st.session_state.running = False
# Cleanup resources
if st.session_state.video_source:
st.session_state.video_source.close()
st.session_state.video_source = None
if st.session_state.mqtt_publisher:
st.session_state.mqtt_publisher.disconnect()
st.session_state.mqtt_publisher = None
if st.session_state.detection_engine:
st.session_state.detection_engine = None
# Reset session state data
st.session_state.detection_logs = []
st.session_state.last_detection = None
st.session_state.last_detection_image = None
st.session_state.stats = {'total_detections': 0, 'target_detections': 0, 'frames_processed': 0}
st.rerun()
st.markdown("---")
# Main content area
if st.session_state.running:
# Initialize components if needed
if st.session_state.video_source is None:
st.session_state.video_source = VideoSource()
if not st.session_state.video_source.open(config['source_input'], config['source_type']):
st.error("Failed to open video source!")
st.session_state.running = False
st.rerun()
if st.session_state.detection_engine is None:
st.session_state.detection_engine = DetectionEngine(
config['model_path'],
config['confidence_threshold']
)
if not st.session_state.detection_engine.load_model():
st.error("Failed to load detection model!")
st.session_state.running = False
st.rerun()
if st.session_state.mqtt_publisher is None:
st.session_state.mqtt_publisher = MQTTPublisher(
config['mqtt_broker'],
config['mqtt_port'],
config['mqtt_username'],
config['mqtt_password']
)
if st.session_state.mqtt_publisher.connect():
st.success("Connected to MQTT broker")
else:
st.warning("Failed to connect to MQTT broker. Will queue messages.")
# Run detection loop
run_detection_loop(config)
else:
# Show placeholder when not running
st.info("👆 Configure settings in the sidebar and click 'Start Detection' to begin")
# Show stats and last detection even when stopped
if st.session_state.stats['frames_processed'] > 0:
display_stats()
if st.session_state.last_detection:
display_last_detection()
def run_detection_loop(config):
"""Run the main detection loop"""
# Create layout
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("📹 Live Feed")
video_placeholder = st.empty()
with col2:
st.subheader("📊 Statistics")
stats_placeholder = st.empty()
st.subheader("📝 Detection Log")
log_placeholder = st.empty()
# Detection loop
fps_counter = []
frame_count = 0
max_frames = 1000 # Process frames continuously
video_source = st.session_state.video_source
detection_engine = st.session_state.detection_engine
mqtt_publisher = st.session_state.mqtt_publisher
for _ in range(max_frames):
if not st.session_state.running:
break
loop_start = time.time()
# Read frame
ret, frame = video_source.read()
if not ret:
st.error("Failed to read from video source")
break
frame_count += 1
st.session_state.stats['frames_processed'] = frame_count
# Apply brightness adjustment if enabled
if config['auto_brightness']:
frame = adjust_brightness(frame)
# Run detection
detections = detection_engine.detect(frame, target_classes=[config['target_class']])
# Process detections
for detection in detections:
# Add timestamp
detection['timestamp'] = datetime.now().isoformat()
# Optionally include image
if config['include_image']:
cropped = crop_detection(frame, detection['bbox'])
if cropped is not None:
detection['image'] = encode_image_base64(cropped)
# Publish to MQTT
mqtt_publisher.publish_detection(detection, config['mqtt_topic'])
# Update logs
st.session_state.detection_logs.insert(0, detection)
if len(st.session_state.detection_logs) > 50:
st.session_state.detection_logs.pop()
# Save last detection
st.session_state.last_detection = detection
st.session_state.last_detection_image = crop_detection(frame, detection['bbox'])
# Update stats
st.session_state.stats.update(detection_engine.get_stats())
# Annotate frame
annotated = annotate_frame(frame, detections, [config['target_class']])
# Calculate and draw FPS
fps_counter.append(time.time() - loop_start)
if len(fps_counter) > 30:
fps_counter.pop(0)
fps = 1.0 / (sum(fps_counter) / len(fps_counter))
annotated = draw_fps(annotated, fps)
# Resize for display
display_frame = resize_frame(annotated, max_width=800)
# Convert BGR to RGB for Streamlit
display_frame = cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB)
# Update displays
video_placeholder.image(display_frame, channels="RGB", width="stretch")
# Update stats
with stats_placeholder.container():
display_stats()
# Update logs
with log_placeholder.container():
display_logs()
# Small delay to prevent overwhelming the UI
time.sleep(0.01)
# After loop ends
if st.session_state.running:
st.session_state.running = False
st.info("Detection loop ended")
st.rerun()
def display_stats():
"""Display detection statistics"""
stats = st.session_state.stats
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Frames Processed", stats['frames_processed'])
with col2:
st.metric("Total Detections", stats['total_detections'])
with col3:
st.metric("Target Detections", stats['target_detections'])
def display_logs():
"""Display detection logs"""
if st.session_state.detection_logs:
logs_text = "\n".join([
format_detection_log(log)
for log in st.session_state.detection_logs[:10]
])
st.text_area("Recent Detections", logs_text, height=300, disabled=True)
else:
st.info("No detections yet")
def display_last_detection():
"""Display last detection details"""
st.subheader("🎯 Last Detection")
detection = st.session_state.last_detection
image = st.session_state.last_detection_image
col1, col2 = st.columns(2)
with col1:
if image is not None:
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
st.image(image_rgb, caption="Detection Crop", width="stretch")
with col2:
st.json(detection)
if __name__ == "__main__":
main()