-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyolov8_live_rtmp_stream_detection.py
executable file
·1551 lines (1350 loc) · 70.8 KB
/
yolov8_live_rtmp_stream_detection.py
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
# yolov8_live_rtmp_stream_detection.py
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# https://github.com/FlyingFathead/dvr-yolov8-detection
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# get the version number
import version # Import the version module
version_number = version.version_number
import av
import cv2
import torch
import logging
import numpy as np
from utils import hz_line
# Time and timezone related
import time
from datetime import datetime
import pytz
from collections import deque, defaultdict
import pyttsx3
import os
from ultralytics import YOLO
import threading
from threading import Thread, Event, Lock
from queue import Queue, Empty, Full
import configparser
import argparse
import signal
import sys
# Import web server functions
from web_server import start_web_server, set_output_frame
# Import the remote sync module
import remote_sync
# Import sending alerts on Telegram
import telegram_alerts
hz_line()
print(f"::: dvr-yolov8-detection v{version_number} | https://github.com/FlyingFathead/dvr-yolov8-detection/")
hz_line()
# Shared data structures
detections_list = deque(maxlen=100) # Store up to 100 latest detections on web UI
logs_list = deque(maxlen=100) # Store up to 100 latest logs on web UI
detection_timestamps = deque(maxlen=10000) # Store up to 10,000 timestamps
# Global variable to store masked regions
masked_regions = [] # each entry: { "name": str, "confidence_threshold": float, "x1": int, "y1": int, "x2": int, "y2": int }
# Locks for thread safety
timestamps_lock = threading.Lock()
detections_lock = threading.Lock()
logs_lock = threading.Lock()
# Load configuration from `config.ini` file with case-sensitive keys
def load_config(config_path=None):
try:
if config_path is None:
script_dir = os.path.dirname(os.path.abspath(__file__))
print(f"Script directory resolved to: {script_dir}", flush=True)
config_path = os.path.join(script_dir, 'config.ini')
print(f"Attempting to load config from: {config_path}", flush=True)
config = configparser.ConfigParser()
# config.optionxform = str # Make keys case-sensitive
read_files = config.read(config_path)
if not read_files:
print(f"Warning: Config file {config_path} not found or is empty. Using default settings.", flush=True)
else:
print(f"Config file {config_path} loaded successfully.", flush=True)
return config
except Exception as e:
print(f"Error loading config: {e}", flush=True)
raise
# Shared data structure to hold image filenames associated with detection counts
detection_images = defaultdict(list)
detection_images_lock = threading.Lock()
# Load configuration
print("Starting configuration loading...", flush=True)
config = load_config()
print("Configuration loading completed.", flush=True)
# Assign configurations to variables
HEADLESS = config.getboolean('detection', 'headless', fallback=False)
DEFAULT_CONF_THRESHOLD = config.getfloat('general', 'default_conf_threshold')
DEFAULT_MODEL_VARIANT = config.get('general', 'default_model_variant')
USE_WEBCAM = config.getboolean('input', 'use_webcam', fallback=False)
WEBCAM_INDEX = config.getint('input', 'webcam_index', fallback=0)
STREAM_URL = config.get('stream', 'stream_url')
DRAW_RECTANGLES = config.getboolean('detection', 'draw_rectangles')
SAVE_FULL_FRAMES = config.getboolean('detection', 'save_full_frames', fallback=True)
FULL_FRAME_IMAGE_FORMAT = config.get('detection', 'full_frame_image_format', fallback='jpg')
DETECTION_AREA_IMAGE_FORMAT = config.get('detection', 'detection_area_image_format', fallback='jpg')
IMAGE_QUALITY = config.getint('detection', 'image_quality', fallback=100)
PNG_COMPRESSION_LEVEL = config.getint('detection', 'png_compression_level', fallback=3)
WEBP_LOSSLESS = config.getboolean('detection', 'webp_lossless', fallback=False)
SAVE_DETECTION_AREAS = config.getboolean('detection', 'save_detection_areas', fallback=False)
DETECTION_AREA_MARGIN = config.getint('detection', 'detection_area_margin', fallback=0)
IMAGE_SAVE_QUEUE_MAXSIZE = config.getint('performance', 'IMAGE_SAVE_QUEUE_MAXSIZE', fallback=1000)
USE_ENV_SAVE_DIR = config.getboolean('detection', 'use_env_save_dir', fallback=False)
ENV_SAVE_DIR_VAR = config.get('detection', 'env_save_dir_var', fallback='YOLO_SAVE_DIR')
# Extract SAVE_DIR_BASE from config.ini or set a default value
SAVE_DIR_BASE = config.get('detection', 'save_dir_base', fallback='./yolo_detections')
DEFAULT_SAVE_DIR = config.get('detection', 'default_save_dir')
FALLBACK_SAVE_DIR = config.get('detection', 'fallback_save_dir')
RETRY_DELAY = config.getint('detection', 'retry_delay')
MAX_RETRIES = config.getint('detection', 'max_retries')
RESCALE_INPUT = config.getboolean('detection', 'rescale_input')
TARGET_HEIGHT = config.getint('detection', 'target_height')
DENOISE = config.getboolean('detection', 'denoise')
USE_PROCESS_FPS = config.getboolean('detection', 'use_process_fps')
PROCESS_FPS = config.getint('detection', 'process_fps')
TIMEOUT = config.getint('detection', 'timeout')
TTS_COOLDOWN = config.getint('detection', 'tts_cooldown')
# Logging options
ENABLE_DETECTION_LOGGING_TO_FILE = config.getboolean('logging', 'enable_detection_logging_to_file')
LOG_DIRECTORY = config.get('logging', 'log_directory')
LOG_FILE = config.get('logging', 'log_file')
DETECTION_LOG_FILE = config.get('logging', 'detection_log_file')
# New configuration for creating date-based subdirectories
CREATE_DATE_SUBDIRS = config.getboolean('detection', 'create_date_subdirs', fallback=False)
# Web server configuration
ENABLE_WEBSERVER = config.getboolean('webserver', 'enable_webserver', fallback=False)
WEBSERVER_HOST = config.get('webserver', 'webserver_host', fallback='0.0.0.0')
WEBSERVER_PORT = config.getint('webserver', 'webserver_port', fallback=5000)
# Read AGGREGATED_DETECTIONS_FILE from config for remote sync
ENABLE_PERSISTENT_AGGREGATED_DETECTIONS = config.getboolean('aggregation', 'enable_persistent_aggregated_detections', fallback=False)
AGGREGATED_DETECTIONS_FILE = config.get('aggregation', 'aggregated_detections_file', fallback='./logs/aggregated_detections.json')
# max number of aggregation entries to show on webUI
webui_max_aggregation_entries = 100
# Initialize the image save queue and stop event
# image_save_queue = Queue()
image_save_queue = Queue(maxsize=IMAGE_SAVE_QUEUE_MAXSIZE)
image_saving_stop_event = threading.Event()
# load masked regions if enabled
def load_masked_regions(config, main_logger):
"""
If 'enable_masked_regions' is True, attempt to load the JSON
from 'output_json'. Store in global 'masked_regions'.
"""
global masked_regions
enable_masked_regions = config.getboolean('region_masker', 'enable_masked_regions', fallback=False)
if not enable_masked_regions:
main_logger.info("Masked regions are disabled in config. Proceeding without any region masking.")
return
# If enabled, read the JSON file path
masked_json_path = config.get('region_masker', 'output_json', fallback='./ignore_zones.json')
main_logger.info(f"Masked regions are ENABLED. Attempting to load from: {masked_json_path}")
if not os.path.exists(masked_json_path):
main_logger.warning(f"Masked regions file '{masked_json_path}' not found. No masked regions will be used.")
return
try:
import json
with open(masked_json_path, 'r') as f:
data = json.load(f)
loaded_zones = data.get("ignore_zones", [])
masked_regions = loaded_zones # store globally
if loaded_zones:
main_logger.info(f"Loaded {len(loaded_zones)} masked region(s) from '{masked_json_path}':")
for i, zone in enumerate(loaded_zones, 1):
zname = zone.get("name", f"Zone_{i}")
cthr = zone.get("confidence_threshold", 0.0)
x1 = zone.get("x1", 0)
y1 = zone.get("y1", 0)
x2 = zone.get("x2", 0)
y2 = zone.get("y2", 0)
main_logger.info(f" -> {zname} (threshold={cthr}), coords=({x1},{y1}) to ({x2},{y2})")
else:
main_logger.info(f"File '{masked_json_path}' loaded but no zones found. Proceeding with no masked regions.")
except Exception as e:
main_logger.error(f"Failed to parse masked regions JSON '{masked_json_path}': {e}")
main_logger.info("Continuing with no masked regions loaded.")
# masked regions
def apply_masked_regions(x1, y1, x2, y2, confidence, masked_regions):
"""
Example logic: if detection box intersects a masked region,
then either ignore it or require a higher confidence threshold.
This is TOTALLY up to you how you interpret it.
Returns (keep_detection_bool, skip_info_dict|None).
skip_info_dict has keys like {"zone_name": str, "required_conf": float} if skipping.
"""
for zone in masked_regions:
zx1 = zone.get("x1", 0)
zy1 = zone.get("y1", 0)
zx2 = zone.get("x2", 0)
zy2 = zone.get("y2", 0)
if boxes_intersect(x1, y1, x2, y2, zx1, zy1, zx2, zy2):
zone_name = zone.get("name", "UnknownZone")
required_conf = zone.get("confidence_threshold", 1.0)
# If detection's conf < the zone's threshold => skip
if confidence < required_conf:
return (False, {
"zone_name": zone_name,
"required_conf": required_conf
})
return (True, None)
# for zone in masked_regions:
# # Parse region coords
# zx1 = zone.get("x1", 0)
# zy1 = zone.get("y1", 0)
# zx2 = zone.get("x2", 0)
# zy2 = zone.get("y2", 0)
# # Could do fancy polygon intersection, but let's do simple AABB
# if boxes_intersect(x1, y1, x2, y2, zx1, zy1, zx2, zy2):
# # Let’s say zone.confidence_threshold acts as "ignore unless conf >= that threshold"
# required_conf = zone.get("confidence_threshold", 1.0)
# if confidence < required_conf:
# return False # means "skip this detection"
# return True
def boxes_intersect(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2):
# quick axis-aligned overlap check
# assume (x1 < x2) and (y1 < y2)
if ax2 < bx1 or bx2 < ax1:
return False # no horizontal overlap
if ay2 < by1 or by2 < ay1:
return False # no vertical overlap
return True
# List handler for webUI logging
class ListHandler(logging.Handler):
def __init__(self, logs_list, logs_lock):
super().__init__()
self.logs_list = logs_list
self.logs_lock = logs_lock
def emit(self, record):
log_entry = self.format(record)
with self.logs_lock:
self.logs_list.append(log_entry)
# Centralized Logging Configuration
def setup_logging():
# Create a root logger with StreamHandler
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# Prevent root logger from propagating to higher loggers (if any)
root_logger.propagate = False
# Define and configure the logger for remote_sync
remote_sync_logger = logging.getLogger("remote_sync")
remote_sync_logger.setLevel(logging.INFO)
remote_sync_logger.propagate = False
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
# Create and add StreamHandler to root logger
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
root_logger.addHandler(stream_handler)
# Define the main logger
main_logger = logging.getLogger('main')
main_logger.setLevel(logging.INFO)
main_logger.propagate = False # Prevent propagation to root
# Add ListHandler to main_logger to capture WARNING and ERROR logs
list_handler = ListHandler(logs_list, logs_lock)
list_handler.setLevel(logging.WARNING) # Capture WARNING and ERROR logs
list_handler.setFormatter(formatter)
main_logger.addHandler(list_handler)
# **Add StreamHandler to main_logger for INFO level logs**
stream_handler_main = logging.StreamHandler(sys.stdout)
stream_handler_main.setLevel(logging.INFO)
stream_handler_main.setFormatter(formatter)
main_logger.addHandler(stream_handler_main)
# Define detection logger
detection_logger = logging.getLogger('detection')
detection_logger.setLevel(logging.INFO)
detection_logger.propagate = False # Prevent propagation to root
# **Configure 'remote_sync' logger to propagate to root logger**
remote_sync_logger = logging.getLogger("remote_sync")
remote_sync_logger.setLevel(logging.INFO)
remote_sync_logger.propagate = True # Allow propagation to root logger
# Initialize detection_log_path
detection_log_path = None
# Add FileHandler to detection_logger if enabled
if ENABLE_DETECTION_LOGGING_TO_FILE:
if not os.path.exists(LOG_DIRECTORY):
os.makedirs(LOG_DIRECTORY)
detection_log_path = os.path.join(LOG_DIRECTORY, DETECTION_LOG_FILE)
detection_file_handler = logging.FileHandler(detection_log_path)
detection_file_handler.setLevel(logging.INFO)
detection_file_handler.setFormatter(formatter)
detection_logger.addHandler(detection_file_handler)
main_logger.info(f"Detection logging to file is enabled. Logging to: {detection_log_path}")
else:
main_logger.info("Detection logging to file is disabled.")
# Define web_server logger
web_server_logger = logging.getLogger('web_server')
web_server_logger.setLevel(logging.INFO)
web_server_logger.propagate = False # Prevent propagation to root
# Add StreamHandler to web_server_logger if not already present
if not web_server_logger.hasHandlers():
web_stream_handler = logging.StreamHandler(sys.stdout)
web_stream_handler.setLevel(logging.INFO)
web_stream_handler.setFormatter(formatter)
web_server_logger.addHandler(web_stream_handler)
return main_logger, detection_logger, web_server_logger, detection_log_path
# Initialize logging
main_logger, detection_logger, web_server_logger, detection_log_path = setup_logging()
# Load masked regions if enabled
load_masked_regions(config, main_logger)
# Timekeeping and frame counting
last_log_time = time.time()
# Initialize TTS engine
tts_engine = pyttsx3.init()
tts_lock = Lock()
last_tts_time = 0
tts_thread = None
tts_stop_event = Event()
# Check if Telegram alerts are enabled
if telegram_alerts.bot is None:
main_logger.warning("Telegram alerts are disabled.")
else:
main_logger.info("Telegram alerts are enabled.")
# Initialize remote sync (if enabled)
remote_sync_obj = remote_sync.RemoteSync(config, main_logger, SAVE_DIR_BASE, AGGREGATED_DETECTIONS_FILE)
remote_sync_obj.start()
# Specify supported image formats
SUPPORTED_IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp']
# Load the YOLOv8 model
def load_model(model_variant=DEFAULT_MODEL_VARIANT):
"""Loads the YOLO model and puts it onto the configured CUDA device (or CPU)."""
try:
model = YOLO(model_variant)
# 1) Read from config
cuda_device_id = config.getint('hardware', 'cuda_device_id', fallback=0)
cuda_fallback_if_unavailable = config.getboolean('hardware', 'cuda_fallback_if_unavailable', fallback=True)
if torch.cuda.is_available():
# 2) Check how many devices we have
num_gpus = torch.cuda.device_count()
if cuda_device_id < num_gpus:
try:
# Attempt to put the model on the user-specified device
device_str = f"cuda:{cuda_device_id}"
model.to(device_str)
main_logger.info(f"Using CUDA device {cuda_device_id} for model inference.")
except Exception as e:
main_logger.error(f"Failed to load model on cuda:{cuda_device_id}: {e}")
if cuda_fallback_if_unavailable and num_gpus > 0:
# Attempt fallback on the first available GPU (usually cuda:0)
main_logger.warning("Falling back to cuda:0")
model.to("cuda:0")
else:
main_logger.warning("No fallback GPU or fallback disabled. Using CPU instead.")
model.to('cpu')
else:
# The user-specified device doesn't exist
main_logger.warning(f"Requested cuda:{cuda_device_id}, but only {num_gpus} GPU(s) found.")
if cuda_fallback_if_unavailable and num_gpus > 0:
main_logger.warning("Falling back to cuda:0")
model.to("cuda:0")
else:
main_logger.warning("No fallback GPU or fallback disabled. Using CPU instead.")
model.to('cpu')
else:
# No GPU present at all
main_logger.warning("CUDA not available, using CPU for model inference.")
model.to('cpu')
return model
except Exception as e:
logging.error(f"Error loading model {model_variant}: {e}")
raise
# Initialize model
model = load_model(DEFAULT_MODEL_VARIANT)
# Get available CUDA GPU and its details
def log_cuda_info():
if not torch.cuda.is_available():
logging.warning("No CUDA devices detected. Running on CPU.")
return
num_gpus = torch.cuda.device_count()
logging.info(f"Number of CUDA devices detected: {num_gpus}")
for i in range(num_gpus):
gpu_name = torch.cuda.get_device_name(i)
gpu_capability = torch.cuda.get_device_capability(i)
gpu_memory = torch.cuda.get_device_properties(i).total_memory / 1e9 # Convert bytes to GB
logging.info(f"CUDA Device {i}: {gpu_name}")
logging.info(f" Compute Capability: {gpu_capability[0]}.{gpu_capability[1]}")
logging.info(f" Total Memory: {gpu_memory:.2f} GB")
# // not in use after 0.1614.3, preferred CUDA device is now set in `config.ini`
# Log the current device being used
# current_device = torch.cuda.current_device()
# current_gpu_name = torch.cuda.get_device_name(current_device)
# logging.info(f"Using CUDA Device {current_device}: {current_gpu_name}")
# Function to get the base save directory (without date subdirs)
def get_base_save_dir():
base_save_dir = None
# 1. Use environment-specified directory
if USE_ENV_SAVE_DIR:
env_dir = os.getenv(ENV_SAVE_DIR_VAR)
if env_dir and os.path.exists(env_dir) and os.access(env_dir, os.W_OK):
main_logger.info(f"Using environment-specified save directory: {env_dir}")
base_save_dir = env_dir # Set base_save_dir here
else:
main_logger.warning(
f"Environment variable {ENV_SAVE_DIR_VAR} is set but the directory does not exist or is not writable. Checked path: {env_dir}"
)
# 2. Use save_dir_base from config or default
if not base_save_dir:
SAVE_DIR_BASE = config.get('detection', 'save_dir_base', fallback='./yolo_detections')
if os.path.exists(SAVE_DIR_BASE) and os.access(SAVE_DIR_BASE, os.W_OK):
main_logger.info(f"Using save_dir_base from config: {SAVE_DIR_BASE}")
base_save_dir = SAVE_DIR_BASE
else:
main_logger.warning(f"save_dir_base {SAVE_DIR_BASE} does not exist or is not writable. Attempting to create it.")
try:
os.makedirs(SAVE_DIR_BASE, exist_ok=True)
if os.access(SAVE_DIR_BASE, os.W_OK):
main_logger.info(f"Created and using save_dir_base: {SAVE_DIR_BASE}")
base_save_dir = SAVE_DIR_BASE
else:
main_logger.warning(f"save_dir_base {SAVE_DIR_BASE} is not writable after creation.")
except Exception as e:
main_logger.error(f"Failed to create save_dir_base: {SAVE_DIR_BASE}. Error: {e}")
# 3. Fallback to fallback_save_dir
if not base_save_dir and FALLBACK_SAVE_DIR:
if os.path.exists(FALLBACK_SAVE_DIR) and os.access(FALLBACK_SAVE_DIR, os.W_OK):
main_logger.info(f"Using fallback save directory: {FALLBACK_SAVE_DIR}")
base_save_dir = FALLBACK_SAVE_DIR
else:
main_logger.warning(f"Fallback save directory {FALLBACK_SAVE_DIR} does not exist or is not writable. Attempting to create it.")
try:
os.makedirs(FALLBACK_SAVE_DIR, exist_ok=True)
if os.access(FALLBACK_SAVE_DIR, os.W_OK):
main_logger.info(f"Created and using fallback save directory: {FALLBACK_SAVE_DIR}")
base_save_dir = FALLBACK_SAVE_DIR
else:
main_logger.warning(f"Fallback save directory {FALLBACK_SAVE_DIR} is not writable after creation.")
except Exception as e:
main_logger.error(f"Failed to create fallback save directory: {FALLBACK_SAVE_DIR}. Error: {e}")
# 4. Use default_save_dir
if not base_save_dir and DEFAULT_SAVE_DIR:
if os.path.exists(DEFAULT_SAVE_DIR) and os.access(DEFAULT_SAVE_DIR, os.W_OK):
main_logger.info(f"Using default save directory: {DEFAULT_SAVE_DIR}")
base_save_dir = DEFAULT_SAVE_DIR
else:
main_logger.warning(f"Default save directory {DEFAULT_SAVE_DIR} does not exist or is not writable. Attempting to create it.")
try:
os.makedirs(DEFAULT_SAVE_DIR, exist_ok=True)
if os.access(DEFAULT_SAVE_DIR, os.W_OK):
main_logger.info(f"Created and using default save directory: {DEFAULT_SAVE_DIR}")
base_save_dir = DEFAULT_SAVE_DIR
else:
main_logger.warning(f"Default save directory {DEFAULT_SAVE_DIR} is not writable after creation.")
except Exception as e:
main_logger.error(f"Failed to create default save directory: {DEFAULT_SAVE_DIR}. Error: {e}")
# 5. Final fallback to a hardcoded directory (optional)
if not base_save_dir:
final_fallback_dir = os.path.join(os.path.dirname(__file__), 'final_fallback_detections')
if os.path.exists(final_fallback_dir) and os.access(final_fallback_dir, os.W_OK):
main_logger.info(f"Using final hardcoded fallback save directory: {final_fallback_dir}")
base_save_dir = final_fallback_dir
else:
try:
os.makedirs(final_fallback_dir, exist_ok=True)
if os.access(final_fallback_dir, os.W_OK):
main_logger.info(f"Created and using final hardcoded fallback save directory: {final_fallback_dir}")
base_save_dir = final_fallback_dir
else:
main_logger.warning(f"Final fallback save directory {final_fallback_dir} is not writable after creation.")
except Exception as e:
main_logger.error(f"Failed to create final hardcoded fallback save directory: {final_fallback_dir}. Error: {e}")
# Raise error if no writable directory is found
if not base_save_dir:
raise RuntimeError("No writable save directory available.")
return base_save_dir
# Initialize SAVE_DIR and CURRENT_DATE
# Initialize SAVE_DIR_BASE using the updated get_base_save_dir function
SAVE_DIR_BASE = get_base_save_dir()
main_logger.info(f"SAVE_DIR_BASE is set to: {SAVE_DIR_BASE}")
CURRENT_DATE = datetime.now().date()
# Function to get the current save directory with date-based subdirectories
def get_current_save_dir():
global CURRENT_DATE, SAVE_DIR_BASE
if CREATE_DATE_SUBDIRS:
new_date = datetime.now().date()
if new_date != CURRENT_DATE:
CURRENT_DATE = new_date
# Update SAVE_DIR with new date-based subdirectories
year = CURRENT_DATE.strftime("%Y")
month = CURRENT_DATE.strftime("%m")
day = CURRENT_DATE.strftime("%d")
date_subdir = os.path.join(SAVE_DIR_BASE, year, month, day)
try:
os.makedirs(date_subdir, exist_ok=True)
main_logger.info(f"Date changed. Created/navigated to new date-based subdirectory: {date_subdir}")
return date_subdir
except Exception as e:
main_logger.error(f"Failed to create new date-based subdirectory {date_subdir}: {e}")
# Fallback to base_save_dir if subdirectory creation fails
return SAVE_DIR_BASE
else:
# Ensure the date-based subdirectory exists
year = CURRENT_DATE.strftime("%Y")
month = CURRENT_DATE.strftime("%m")
day = CURRENT_DATE.strftime("%d")
date_subdir = os.path.join(SAVE_DIR_BASE, year, month, day)
if not os.path.exists(date_subdir):
try:
os.makedirs(date_subdir, exist_ok=True)
main_logger.info(f"Created date-based subdirectory: {date_subdir}")
except Exception as e:
main_logger.error(f"Failed to create date-based subdirectory {date_subdir}: {e}")
return date_subdir
else:
return SAVE_DIR_BASE
# Initialize the initial SAVE_DIR
SAVE_DIR = get_current_save_dir()
# Function to log detection details
def log_detection_details(detections, frame_count, timestamp):
if ENABLE_DETECTION_LOGGING_TO_FILE:
for detection in detections:
x1, y1, x2, y2, confidence, class_idx = detection
detection_logger.info(f"Detection: Frame {frame_count}, Timestamp {timestamp}, Coordinates: ({x1}, {y1}), ({x2}, {y2}), Confidence: {confidence:.2f}")
# Function to resize while maintaining aspect ratio
def resize_frame(frame, target_height):
"""Resize the frame to the target height while maintaining the aspect ratio."""
height, width = frame.shape[:2]
aspect_ratio = width / height
new_width = int(target_height * aspect_ratio)
resized_frame = cv2.resize(frame, (new_width, target_height))
return resized_frame
# Function to announce detection using a separate thread
def announce_detection():
global last_tts_time
while not tts_stop_event.is_set():
current_time = time.time()
if current_time - last_tts_time >= TTS_COOLDOWN:
with tts_lock:
tts_engine.say("Human detected!")
tts_engine.runAndWait()
last_tts_time = current_time
time.sleep(1)
# # Function to save detection image with date check
# def save_detection_image(frame, detection_count):
# global SAVE_DIR
# main_logger.info(f"Current SAVE_DIR is: {SAVE_DIR}")
# main_logger.info("Attempting to save detection image.")
# try:
# # Update SAVE_DIR based on current date
# SAVE_DIR = get_current_save_dir()
# timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") # Format timestamp as YYYYMMDD-HHMMSS
# filename = os.path.join(SAVE_DIR, f"{timestamp}_{detection_count}.{IMAGE_FORMAT}") # Ensure SAVE_DIR already includes date subdirs
# if not cv2.imwrite(filename, frame):
# main_logger.error(f"Failed to save detection image: {filename}")
# else:
# main_logger.info(f"Saved detection image: {filename}")
# except Exception as e:
# main_logger.error(f"Error saving detection image: {e}")
# Check if the CUDA denoising function is available
def cuda_denoising_available():
try:
_ = cv2.cuda.createFastNlMeansDenoisingColored
main_logger.info("CUDA denoising is available.")
return True
except AttributeError:
main_logger.warning("CUDA denoising is not available.")
return False
# Frame capture thread
def frame_capture_thread(stream_url, use_webcam, webcam_index, frame_queue, stop_event):
retries = 0
cap = None
if use_webcam:
main_logger.info(f"Using webcam with index {webcam_index}")
cap = cv2.VideoCapture(webcam_index)
if not cap.isOpened():
main_logger.error(f"Unable to open webcam with index {webcam_index}")
return
while not stop_event.is_set():
ret, frame = cap.read()
if not ret:
main_logger.warning("Failed to read frame from webcam.")
time.sleep(1)
continue
frame_queue.put(frame)
cap.release()
main_logger.info("Webcam video source closed.")
else:
while retries < MAX_RETRIES and not stop_event.is_set():
try:
main_logger.info(f"Attempting to open video stream: {stream_url}")
container = av.open(stream_url)
main_logger.info("Successfully opened video stream.")
for frame in container.decode(video=0):
if stop_event.is_set():
break
image = frame.to_ndarray(format='bgr24')
frame_queue.put(image)
# If the stream ends, break out of the loop
break
except av.AVError as e:
main_logger.error(f"Error reading video stream: {e}")
retries += 1
time.sleep(RETRY_DELAY)
main_logger.info(f"Retrying... ({retries}/{MAX_RETRIES})")
except Exception as e:
main_logger.error(f"Unexpected error: {e}")
retries += 1
time.sleep(RETRY_DELAY)
main_logger.info(f"Retrying... ({retries}/{MAX_RETRIES})")
if retries >= MAX_RETRIES:
main_logger.error(f"Failed to open video source after {MAX_RETRIES} retries.")
return
main_logger.info("RTMP video source closed.")
# Frame processing thread
def frame_processing_thread(
frame_queue, stop_event,
conf_threshold, draw_rectangles, denoise,
process_fps, use_process_fps,
detection_ongoing, headless
):
global last_tts_time, tts_thread, tts_stop_event
model = load_model(DEFAULT_MODEL_VARIANT)
use_cuda_denoising = cuda_denoising_available()
detection_count = 0
last_log_time = time.time()
total_frames = 0
detecting_human = False
if not headless:
cv2.namedWindow('Real-time Human Detection', cv2.WINDOW_NORMAL)
try:
while not stop_event.is_set() or not frame_queue.empty():
if frame_queue.empty():
# If queue has no frames, just sleep briefly
time.sleep(0.01)
continue
frame = frame_queue.get()
start_time = time.time()
# 1) Optional resize
if RESCALE_INPUT:
resized_frame = resize_frame(frame, TARGET_HEIGHT)
else:
resized_frame = frame
# 2) Optional denoising
if denoise:
try:
if use_cuda_denoising:
gpu_frame = cv2.cuda_GpuMat()
gpu_frame.upload(resized_frame)
denoised_gpu = cv2.cuda.createFastNlMeansDenoisingColored(
gpu_frame, None, 3, 3, 7
)
denoised_frame = denoised_gpu.download()
else:
denoised_frame = cv2.fastNlMeansDenoisingColored(
resized_frame, None, 3, 3, 7, 21
)
except cv2.error as e:
main_logger.error(f"Error applying denoising: {e}")
denoised_frame = resized_frame
else:
denoised_frame = resized_frame
# 3) Run YOLO inference (only detecting person=class0 here)
results = model.predict(
source=denoised_frame,
conf=conf_threshold,
classes=[0],
verbose=False
)
detections = results[0].boxes.data.cpu().numpy()
# 4) If we have any raw YOLO detections:
if detections.size > 0:
# If previously not detecting, set flags
if not detecting_human:
detecting_human = True
detection_ongoing.set()
detection_count += 1
main_logger.info(f"Detections found: {detections}")
# We track if at least one detection is “kept”
any_kept_detection = False
full_frame_filename = None
# 4A) We *do not* immediately queue a full-frame
# We'll only do so if at least one detection is kept.
# (So we don't waste a full-frame if they're all masked.)
# 5) Per-detection
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
SAVE_DIR = get_current_save_dir() # update date-based subdir
kept_detections_list = [] # For logging, if you like
for det_idx, det in enumerate(detections):
x1, y1, x2, y2, confidence, class_idx = det
# 5A) Check masked regions logic:
# If in a masked region with threshold > this detection's confidence => skip
if masked_regions:
# Unpack both values from apply_masked_regions
keep_detection, skip_info = apply_masked_regions(
int(x1), int(y1), int(x2), int(y2),
float(confidence),
masked_regions
)
if not keep_detection:
# Now skip_info is available
zone_name = skip_info.get("zone_name", "UnknownZone")
required_conf = skip_info.get("required_conf", 1.0)
main_logger.info(
f"Skipping detection in masked region '{zone_name}': "
f"needed≥{required_conf:.2f}, got={confidence:.2f}, "
f"coords=({x1:.0f},{y1:.0f})-({x2:.0f},{y2:.0f})"
)
# do NOT save or alert
continue
# If we’re here => detection is *kept*
any_kept_detection = True
# 5B) If we haven't queued the full-frame yet, do so once
if SAVE_FULL_FRAMES and (full_frame_filename is None):
full_frame_filename = generate_full_frame_filename(detection_count)
try:
image_save_queue.put(
(denoised_frame.copy(), full_frame_filename, 'full_frame'),
block=False
)
main_logger.info("Queued full-frame image for saving.")
except Full:
main_logger.warning("Image save queue is full. Dropping full-frame image.")
full_frame_filename = None
# 5C) Prepare detection-area image if desired
detection_area_filename = None
if SAVE_DETECTION_AREAS:
main_logger.info("Queuing detection area image for saving.")
margin = DETECTION_AREA_MARGIN
x1_m = max(0, int(x1) - margin)
y1_m = max(0, int(y1) - margin)
x2_m = min(denoised_frame.shape[1], int(x2) + margin)
y2_m = min(denoised_frame.shape[0], int(y2) + margin)
detection_area = denoised_frame[y1_m:y2_m, x1_m:x2_m]
detection_area_filename = generate_detection_area_filename(detection_count, det_idx)
try:
image_save_queue.put(
(detection_area.copy(), detection_area_filename, 'detection_area'),
block=False
)
except Full:
main_logger.warning("Image save queue is full. Dropping detection area image.")
detection_area_filename = None
# 5D) Build detection_info
image_filenames = {}
if full_frame_filename:
image_filenames['full_frame'] = os.path.relpath(
os.path.join(SAVE_DIR, full_frame_filename),
SAVE_DIR_BASE
)
if detection_area_filename:
image_filenames['detection_area'] = os.path.relpath(
os.path.join(SAVE_DIR, detection_area_filename),
SAVE_DIR_BASE
)
detection_info = {
'detection_count': detection_count,
'frame_count': int(total_frames),
'timestamp': timestamp,
'coordinates': (int(x1), int(y1), int(x2), int(y2)),
'confidence': float(confidence),
'image_filenames': image_filenames
}
with detections_lock:
detections_list.appendleft(detection_info)
# 5E) Enqueue Telegram alert
alert_message = {
"detection_count": detection_info['detection_count'],
"frame_count": detection_info['frame_count'],
"timestamp": detection_info['timestamp'],
"coordinates": detection_info['coordinates'],
"confidence": detection_info['confidence']
}
telegram_alerts.queue_alert(alert_message)
# 5F) If draw_rectangles => draw
if draw_rectangles:
ix1 = max(0, int(x1))
iy1 = max(0, int(y1))
ix2 = min(denoised_frame.shape[1], int(x2))
iy2 = min(denoised_frame.shape[0], int(y2))
if not headless:
cv2.rectangle(
denoised_frame,
(ix1, iy1), (ix2, iy2),
(0, 255, 0), 2
)
label = f'Person: {confidence:.2f}'
cv2.putText(
denoised_frame, label,
(ix1, max(iy1 - 10, 0)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 255, 0), 2
)
main_logger.info(
f"Rectangle drawn: {ix1},{iy1},{ix2},{iy2}"
f" with conf {confidence:.2f}"
)
# 6) If we had at least one valid detection, log details
if any_kept_detection:
log_detection_details(detections, total_frames, timestamp)
# Start TTS in a separate thread if not running
if tts_thread is None or not tts_thread.is_alive():
tts_stop_event.clear()
tts_thread = threading.Thread(target=announce_detection)
tts_thread.start()
else:
# Means all detections were masked/skipped
main_logger.info(
"All detections in this batch were masked or below threshold; "
"no saving/alerts triggered."
)
else:
# 7) No detections => reset flags if previously detecting
if detecting_human:
detecting_human = False
detection_ongoing.clear()
tts_stop_event.set() # Stop TTS if no humans now
# 8) Send to web server or local display
if ENABLE_WEBSERVER:
set_output_frame(denoised_frame)
elif not headless:
cv2.imshow('Real-time Human Detection', denoised_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
stop_event.set()
break
# 9) FPS logging
total_frames += 1
if time.time() - last_log_time >= 1:
fps = total_frames / (time.time() - last_log_time)
main_logger.info(f'Processed {total_frames} frames at {fps:.2f} FPS')
last_log_time = time.time()
total_frames = 0
# 10) Throttle if needed
if use_process_fps:
frame_time = time.time() - start_time
frame_interval = 1.0 / process_fps
time_to_wait = frame_interval - frame_time
if time_to_wait > 0:
time.sleep(time_to_wait)
except Exception as e:
main_logger.error(f"Error in frame_processing_thread: {e}", exc_info=True)
finally:
tts_stop_event.set()
if not headless:
cv2.destroyAllWindows()
# # // old logic; changed and obsoleted on Jan 4th, 2025 w/ v0.1615
# # // to be cleaned up ...
#
# def frame_processing_thread(frame_queue, stop_event, conf_threshold, draw_rectangles, denoise, process_fps, use_process_fps, detection_ongoing, headless):
# global last_tts_time, tts_thread, tts_stop_event
# model = load_model(DEFAULT_MODEL_VARIANT)
# use_cuda_denoising = cuda_denoising_available()
# detection_count = 0
# last_log_time = time.time()
# total_frames = 0
# detecting_human = False
# # Initialize an empty list to store image filenames
# image_filenames = []
# if not headless:
# # Create a named window with the ability to resize
# cv2.namedWindow('Real-time Human Detection', cv2.WINDOW_NORMAL)
# try:
# while not stop_event.is_set() or not frame_queue.empty():
# if not frame_queue.empty():
# frame = frame_queue.get()
# start_time = time.time()
# if RESCALE_INPUT:
# resized_frame = resize_frame(frame, TARGET_HEIGHT)
# else:
# resized_frame = frame
# if denoise:
# try:
# if use_cuda_denoising:
# gpu_frame = cv2.cuda_GpuMat()
# gpu_frame.upload(resized_frame)
# denoised_gpu = cv2.cuda.createFastNlMeansDenoisingColored(gpu_frame, None, 3, 3, 7)
# denoised_frame = denoised_gpu.download()
# else:
# denoised_frame = cv2.fastNlMeansDenoisingColored(resized_frame, None, 3, 3, 7, 21)
# except cv2.error as e:
# main_logger.error(f"Error applying denoising: {e}")
# denoised_frame = resized_frame
# else:
# denoised_frame = resized_frame
# results = model.predict(source=denoised_frame, conf=conf_threshold, classes=[0], verbose=False)
# detections = results[0].boxes.data.cpu().numpy()
# if detections.size > 0:
# if not detecting_human:
# detecting_human = True
# detection_ongoing.set()
# detection_count += 1
# main_logger.info(f"Detections found: {detections}")
# image_filenames = []
# # Initialize full_frame_filename outside the loop
# full_frame_filename = None
# # reset the logic for any kept detections
# any_kept_detection = False
# # Queue full-frame image for saving