-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathlive_streamer.py
More file actions
1342 lines (1094 loc) · 50.1 KB
/
Copy pathlive_streamer.py
File metadata and controls
1342 lines (1094 loc) · 50.1 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
#!/usr/bin/env python3
"""
SafeVision Live Streamer Edition
Real-time nudity detection and censoring for streamers with OBS integration.
Supports camera input, screen capture, and virtual camera output.
"""
import cv2
import numpy as np
import sys
import os
import time
import threading
import queue
import argparse
import traceback
import math
import urllib.request
from pathlib import Path
import json
import socket
import subprocess
import platform
from collections import defaultdict
from datetime import datetime
from safevision_utils import create_onnx_session
# Try to import OBS WebSocket for integration
try:
import obsws_python as obs
OBS_AVAILABLE = True
print("OBS WebSocket support available")
except ImportError:
OBS_AVAILABLE = False
print("Warning: obsws_python not available. Install with: pip install obsws-python")
# Try to import screen capture libraries
try:
import mss
MSS_AVAILABLE = True
print("Screen capture support available")
except ImportError:
MSS_AVAILABLE = False
print("Warning: mss not available. Install with: pip install mss")
# Try to import virtual camera support
try:
import pyvirtualcam
PYVIRTUALCAM_AVAILABLE = True
print("Virtual camera support available")
except ImportError:
PYVIRTUALCAM_AVAILABLE = False
print("Warning: pyvirtualcam not available. Install with: pip install pyvirtualcam")
# Global variables for ONNX Runtime components
onnxruntime = None
onnx = None
version_converter = None
_import_attempted = False
_import_successful = False
def _safe_import_onnx(force_retry=False):
"""Safely import ONNX Runtime with comprehensive error handling."""
global onnxruntime, onnx, version_converter, _import_attempted, _import_successful
if _import_attempted and not force_retry:
return _import_successful
_import_attempted = True
try:
import onnxruntime as ort
import onnx as onnx_module
from onnx import version_converter as vc
# Test basic functionality
providers = ort.get_available_providers()
if not providers:
raise RuntimeError("No ONNX providers available")
onnxruntime = ort
onnx = onnx_module
version_converter = vc
_import_successful = True
print(f"ONNX Runtime imported successfully, version: {ort.__version__}")
return True
except ImportError as e:
print(f"ONNX Runtime not installed: {e}")
_import_successful = False
return False
except Exception as e:
print(f"Error during ONNX import: {type(e).__name__}: {e}")
_import_successful = False
return False
def _get_onnx_status():
"""Get current ONNX Runtime status."""
if not _import_attempted:
_safe_import_onnx()
if _import_successful and onnxruntime is not None:
try:
providers = onnxruntime.get_available_providers()
return True, f"Available providers: {providers}"
except Exception as e:
return False, f"Error getting providers: {e}"
else:
return False, "ONNX Runtime not available"
# Try initial import
_safe_import_onnx()
# Try to import PIL for image processing
try:
from PIL import Image
PIL_AVAILABLE = True
except ImportError:
print("Warning: PIL not available, some features may not work")
PIL_AVAILABLE = False
Image = None
# Streamer-optimized configuration
STREAMER_CONFIG = {
# Performance settings for streaming
'TARGET_FPS': 60, # High FPS for smooth streaming
'PROCESSING_FPS': 30, # AI processing FPS (can be lower)
'RESOLUTION': (1920, 1080), # Default streaming resolution
'QUALITY': 'HIGH', # HIGH, MEDIUM, LOW
# Detection thresholds - matching live.py for accuracy
'DETECTION_THRESHOLD': 0.25, # Base threshold from live.py
'EXPOSED_THRESHOLD': 0.4, # Higher bar for exposed content
'GENITALIA_THRESHOLD': 0.6, # High confidence for explicit content
'FACE_THRESHOLD': 0.7, # Avoid false face positives
# Blur settings - matching live.py
'BLUR_STRENGTH': 25, # Default blur kernel from live.py
'BLUR_STRENGTH_CRITICAL': 35, # Max blur for critical content
'SOLID_COLOR_MASK': False, # Use blur by default
'MASK_COLOR': (0, 0, 0), # Black color for masking
'ADAPTIVE_BLUR': True, # Adjust blur based on content
'MOTION_BLUR_REDUCTION': True, # Reduce blur artifacts during motion
# OBS Integration
'OBS_HOST': 'localhost',
'OBS_PORT': 4455,
'OBS_PASSWORD': '', # Set your OBS WebSocket password
'AUTO_SCENE_SWITCH': False, # Auto switch to safe scene when needed
'SAFE_SCENE_NAME': 'BRB Screen', # Scene to switch to when content detected
'MAIN_SCENE_NAME': 'Main Stream', # Normal streaming scene
# Virtual Camera
'VIRTUAL_CAM_ENABLED': True,
'VIRTUAL_CAM_NAME': 'SafeVision Cam',
'VIRTUAL_CAM_FPS': 30,
# Input Sources
'INPUT_MODE': 'CAMERA', # CAMERA, SCREEN, WINDOW, OBS_SOURCE
'CAMERA_ID': 0,
'SCREEN_CAPTURE_MONITOR': 1, # Monitor number for screen capture
'WINDOW_TITLE': '', # Specific window to capture
'OBS_SOURCE_NAME': '', # OBS source to monitor
# Alert System for Streamers
'INSTANT_BLUR': True, # Immediate blur without delay
'ALERT_WEBHOOK': '', # Discord/Slack webhook for alerts
'AUTO_PAUSE_STREAM': False, # Auto pause stream on detection
'SAFE_MODE_TIMEOUT': 10, # Seconds in safe mode after detection
# UI for Streamers
'OVERLAY_ENABLED': True, # Show detection overlay
'STREAM_SAFE_OVERLAY': True, # Show "Stream Safe" indicator
'PERFORMANCE_OVERLAY': True, # Show FPS and performance info
'DETECTION_COUNTER': True, # Show detection count
# Privacy and Safety
'PRIVACY_MODE': False, # Hide sensitive UI elements
'LOG_DETECTIONS': True, # Log all detections for review
'SAVE_DETECTION_FRAMES': False, # Save frames with detections
'DETECTION_LOG_PATH': 'detection_log.json',
# Performance Optimization
'GPU_ACCELERATION': True,
'MULTI_THREADING': True,
'FRAME_SKIP_ON_LOAD': True, # Skip frames when system is loaded
'DYNAMIC_QUALITY': True, # Lower quality when performance drops
}
# Content labels with streaming safety levels
STREAMING_LABELS = [
"FEMALE_GENITALIA_COVERED", # Stream Safe
"FACE_FEMALE", # Stream Safe
"BUTTOCKS_EXPOSED", # Stream Unsafe - Blur
"FEMALE_BREAST_EXPOSED", # Stream Unsafe - Strong Blur
"FEMALE_GENITALIA_EXPOSED", # Stream Banned - Immediate Action
"MALE_BREAST_EXPOSED", # Stream Safe (usually)
"ANUS_EXPOSED", # Stream Banned - Immediate Action
"FEET_EXPOSED", # Stream Safe
"BELLY_COVERED", # Stream Safe
"FEET_COVERED", # Stream Safe
"ARMPITS_COVERED", # Stream Safe
"ARMPITS_EXPOSED", # Stream Safe
"FACE_MALE", # Stream Safe
"BELLY_EXPOSED", # Stream Safe (context dependent)
"MALE_GENITALIA_EXPOSED", # Stream Banned - Immediate Action
"ANUS_COVERED", # Stream Safe
"FEMALE_BREAST_COVERED", # Stream Safe
"BUTTOCKS_COVERED", # Stream Safe
]
# Streaming safety classification - matching live.py severity system
STREAMING_SAFETY = {
'CRITICAL': [
'FEMALE_GENITALIA_EXPOSED', 'MALE_GENITALIA_EXPOSED'
],
'HIGH': [
'FEMALE_BREAST_EXPOSED', 'ANUS_EXPOSED'
],
'MODERATE': [
'BUTTOCKS_EXPOSED'
],
'LOW': [
'MALE_BREAST_EXPOSED', 'BELLY_EXPOSED', 'ARMPITS_EXPOSED', 'FEET_EXPOSED'
],
'SAFE': [
'FACE_FEMALE', 'FACE_MALE', 'FEMALE_GENITALIA_COVERED',
'BELLY_COVERED', 'FEET_COVERED', 'ARMPITS_COVERED', 'ANUS_COVERED',
'FEMALE_BREAST_COVERED', 'BUTTOCKS_COVERED'
]
}
def get_streaming_safety(label):
"""Get severity level for detected content (matching live.py)."""
for severity, labels in STREAMING_SAFETY.items():
if label in labels:
return severity
return 'UNKNOWN'
def get_streaming_threshold(label):
"""Get confidence threshold matching live.py implementation."""
severity = get_streaming_safety(label)
if severity == 'CRITICAL':
return STREAMER_CONFIG['GENITALIA_THRESHOLD']
elif label in ['FACE_FEMALE', 'FACE_MALE']:
return STREAMER_CONFIG['FACE_THRESHOLD']
elif severity in ['HIGH', 'MODERATE']:
return STREAMER_CONFIG['EXPOSED_THRESHOLD']
else:
return STREAMER_CONFIG['DETECTION_THRESHOLD']
class DetectionTracker:
"""Tracks detections across frames to maintain consistent blur."""
def __init__(self, max_age=30, iou_threshold=0.3, confidence_decay=0.95):
self.max_age = max_age # Maximum frames to keep a track alive
self.iou_threshold = iou_threshold # IoU threshold for matching detections
self.confidence_decay = confidence_decay # How much confidence decays per frame
self.tracks = [] # List of active tracks
self.next_id = 0 # Next track ID
def calculate_iou(self, box1, box2):
"""Calculate Intersection over Union of two bounding boxes."""
x1_1, y1_1, w1, h1 = box1
x1_2, y1_2, w2, h2 = box2
x2_1, y2_1 = x1_1 + w1, y1_1 + h1
x2_2, y2_2 = x1_2 + w2, y1_2 + h2
# Calculate intersection
xi1 = max(x1_1, x1_2)
yi1 = max(y1_1, y1_2)
xi2 = min(x2_1, x2_2)
yi2 = min(y2_1, y2_2)
if xi2 <= xi1 or yi2 <= yi1:
return 0.0
inter_area = (xi2 - xi1) * (yi2 - yi1)
# Calculate union
box1_area = w1 * h1
box2_area = w2 * h2
union_area = box1_area + box2_area - inter_area
if union_area <= 0:
return 0.0
return inter_area / union_area
def update(self, detections):
"""Update tracks with new detections."""
# Age existing tracks
for track in self.tracks:
track['age'] += 1
track['confidence'] *= self.confidence_decay
# Remove old tracks
self.tracks = [track for track in self.tracks if track['age'] < self.max_age]
# Match new detections to existing tracks
matched_tracks = set()
matched_detections = set()
for i, detection in enumerate(detections):
best_iou = 0
best_track_idx = -1
for j, track in enumerate(self.tracks):
if j in matched_tracks:
continue
iou = self.calculate_iou(detection['box'], track['box'])
if iou > best_iou and iou > self.iou_threshold:
best_iou = iou
best_track_idx = j
if best_track_idx >= 0:
# Update existing track
track = self.tracks[best_track_idx]
track['box'] = detection['box']
track['confidence'] = max(track['confidence'], detection['score'])
track['severity'] = detection['severity']
track['class'] = detection['class']
track['age'] = 0 # Reset age
track['last_seen'] = time.time()
matched_tracks.add(best_track_idx)
matched_detections.add(i)
# Create new tracks for unmatched detections
for i, detection in enumerate(detections):
if i not in matched_detections:
new_track = {
'id': self.next_id,
'box': detection['box'],
'confidence': detection['score'],
'severity': detection['severity'],
'class': detection['class'],
'age': 0,
'created': time.time(),
'last_seen': time.time()
}
self.tracks.append(new_track)
self.next_id += 1
return self.get_active_tracks()
def get_active_tracks(self):
"""Get all active tracks that should be blurred."""
active_tracks = []
for track in self.tracks:
# Only include tracks with sufficient confidence or critical severity
if (track['confidence'] > 0.1 or
track['severity'] in ['CRITICAL', 'HIGH'] or
track['age'] < 5): # Keep recent tracks visible
active_tracks.append({
'id': track['id'],
'box': track['box'],
'confidence': track['confidence'],
'severity': track['severity'],
'class': track['class'],
'age': track['age']
})
return active_tracks
def clear(self):
"""Clear all tracks."""
self.tracks = []
class OBSIntegration:
"""OBS WebSocket integration for streamers."""
def __init__(self, host='localhost', port=4455, password=''):
self.host = host
self.port = port
self.password = password
self.client = None
self.connected = False
if OBS_AVAILABLE:
self.connect()
else:
print("OBS integration disabled - obsws_python not available")
def connect(self):
"""Connect to OBS WebSocket."""
try:
self.client = obs.ReqClient(host=self.host, port=self.port, password=self.password)
self.connected = True
print(f"Connected to OBS at {self.host}:{self.port}")
# Get OBS version info
version_info = self.client.get_version()
print(f"OBS Version: {version_info.obs_version}")
except Exception as e:
print(f"Failed to connect to OBS: {e}")
self.connected = False
def switch_scene(self, scene_name):
"""Switch to a specific scene."""
if not self.connected:
return False
try:
self.client.set_current_program_scene(scene_name)
print(f"Switched to scene: {scene_name}")
return True
except Exception as e:
print(f"Failed to switch scene: {e}")
return False
def get_current_scene(self):
"""Get current active scene."""
if not self.connected:
return None
try:
response = self.client.get_current_program_scene()
return response.current_program_scene_name
except Exception as e:
print(f"Failed to get current scene: {e}")
return None
def start_stop_streaming(self, start=True):
"""Start or stop streaming."""
if not self.connected:
return False
try:
if start:
self.client.start_stream()
print("Started streaming")
else:
self.client.stop_stream()
print("Stopped streaming")
return True
except Exception as e:
print(f"Failed to {'start' if start else 'stop'} streaming: {e}")
return False
def get_streaming_status(self):
"""Get current streaming status."""
if not self.connected:
return False
try:
response = self.client.get_stream_status()
return response.output_active
except Exception as e:
print(f"Failed to get streaming status: {e}")
return False
def send_chat_message(self, message):
"""Send a message to chat (if supported)."""
# This would need additional OBS plugins
print(f"Chat message: {message}")
class ScreenCapture:
"""Screen capture for streaming."""
def __init__(self, monitor=1):
self.monitor = monitor
self.sct = None
if MSS_AVAILABLE:
self.sct = mss.mss()
self.monitors = self.sct.monitors
print(f"Available monitors: {len(self.monitors) - 1}")
for i, monitor in enumerate(self.monitors[1:], 1):
print(f"Monitor {i}: {monitor['width']}x{monitor['height']} at ({monitor['left']}, {monitor['top']})")
else:
print("Screen capture disabled - mss not available")
def capture_screen(self, monitor_num=None):
"""Capture screen or specific monitor."""
if not MSS_AVAILABLE or not self.sct:
return None
try:
if monitor_num is None:
monitor_num = self.monitor
if monitor_num >= len(self.monitors):
monitor_num = 1
monitor = self.monitors[monitor_num]
screenshot = self.sct.grab(monitor)
# Convert to OpenCV format
frame = np.array(screenshot)
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
return frame
except Exception as e:
print(f"Screen capture error: {e}")
return None
def capture_window(self, window_title):
"""Capture specific window by title."""
# This would need platform-specific implementation
print(f"Window capture not implemented for: {window_title}")
return None
class VirtualCamera:
"""Virtual camera output for OBS."""
def __init__(self, width=1920, height=1080, fps=30):
self.width = width
self.height = height
self.fps = fps
self.cam = None
self.enabled = False
if PYVIRTUALCAM_AVAILABLE:
try:
self.cam = pyvirtualcam.Camera(width=width, height=height, fps=fps)
self.enabled = True
print(f"Virtual camera initialized: {width}x{height} @ {fps}FPS")
except Exception as e:
print(f"Failed to initialize virtual camera: {e}")
else:
print("Virtual camera disabled - pyvirtualcam not available")
def send_frame(self, frame):
"""Send frame to virtual camera."""
if not self.enabled or not self.cam:
return False
try:
# Ensure frame is the right size
if frame.shape[:2] != (self.height, self.width):
frame = cv2.resize(frame, (self.width, self.height))
# Convert BGR to RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Send to virtual camera
self.cam.send(frame_rgb)
return True
except Exception as e:
print(f"Virtual camera error: {e}")
return False
def close(self):
"""Close virtual camera."""
if self.cam:
self.cam.close()
self.enabled = False
class StreamerDetector:
"""Optimized detector for streaming."""
def __init__(self):
print("Initializing Streamer Detector...")
# Import ONNX Runtime
if not _safe_import_onnx(force_retry=True):
print("ONNX Runtime not available - detector disabled")
self.onnx_session = None
return
# Get script directory
if getattr(sys, 'frozen', False):
script_dir = os.path.dirname(sys.executable)
else:
script_dir = os.path.dirname(os.path.abspath(__file__))
# Model setup
model_dir = os.path.join(script_dir, "Models")
model_path = os.path.join(model_dir, "best.onnx")
if not os.path.exists(model_path):
print(f"Model not found at: {model_path}")
print("Please ensure the model file exists")
self.onnx_session = None
return
try:
provider_override = None if STREAMER_CONFIG['GPU_ACCELERATION'] else ['CPUExecutionProvider']
# Session options for performance
sess_options = onnxruntime.SessionOptions()
sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
if STREAMER_CONFIG['MULTI_THREADING']:
sess_options.intra_op_num_threads = 0 # Use all available threads
sess_options.inter_op_num_threads = 0
self.onnx_session = create_onnx_session(
model_path,
providers=provider_override,
sess_options=sess_options,
)
# Get model info
inp = self.onnx_session.get_inputs()[0]
self.input_name = inp.name
self.input_size = inp.shape[2] # Assuming square input
print(f"Streamer Detector initialized successfully!")
print(f"Model input: {self.input_name}, size: {self.input_size}")
except Exception as e:
print(f"Error initializing detector: {e}")
traceback.print_exc()
self.onnx_session = None
def preprocess_frame(self, frame, target_size=320):
"""Optimized preprocessing for streaming."""
img_height, img_width = frame.shape[:2]
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Calculate aspect ratio
aspect = img_width / img_height
if img_height > img_width:
new_height = target_size
new_width = int(round(target_size * aspect))
else:
new_width = target_size
new_height = int(round(target_size / aspect))
# Resize
img = cv2.resize(img, (new_width, new_height))
# Padding
pad_x = target_size - new_width
pad_y = target_size - new_height
pad_top, pad_bottom = [int(i) for i in np.floor([pad_y, pad_y]) / 2]
pad_left, pad_right = [int(i) for i in np.floor([pad_x, pad_x]) / 2]
img = cv2.copyMakeBorder(
img, pad_top, pad_bottom, pad_left, pad_right,
cv2.BORDER_CONSTANT, value=[0, 0, 0]
)
img = cv2.resize(img, (target_size, target_size))
# Normalize and format for model
image_data = img.astype("float32") / 255.0
image_data = np.transpose(image_data, (2, 0, 1))
image_data = np.expand_dims(image_data, axis=0)
# Calculate resize factor for postprocessing
resize_factor = math.sqrt(
(img_width**2 + img_height**2) / (new_width**2 + new_height**2)
)
return image_data, resize_factor, pad_left, pad_top
def postprocess_detections(self, outputs, resize_factor, pad_left, pad_top):
"""Process model outputs with live.py compatible filtering."""
outputs = np.transpose(np.squeeze(outputs[0]))
rows = outputs.shape[0]
boxes = []
scores = []
class_ids = []
for i in range(rows):
classes_scores = outputs[i][4:]
max_score = np.amax(classes_scores)
class_id = np.argmax(classes_scores)
if class_id < len(STREAMING_LABELS):
label = STREAMING_LABELS[class_id]
required_threshold = get_streaming_threshold(label)
# Only accept detections that meet the severity-specific threshold
if max_score >= required_threshold:
x, y, w, h = outputs[i][0], outputs[i][1], outputs[i][2], outputs[i][3]
# Scale back to original coordinates (matching live.py format)
left = int(round((x - w * 0.5 - pad_left) * resize_factor))
top = int(round((y - h * 0.5 - pad_top) * resize_factor))
width = int(round(w * resize_factor))
height = int(round(h * resize_factor))
# Additional validation for critical content
severity = get_streaming_safety(label)
if severity == 'CRITICAL':
# Extra strict validation for genitalia detection
min_box_area = 500 # Minimum area to avoid tiny false positives
box_area = width * height
if max_score >= 0.7 and box_area >= min_box_area:
class_ids.append(class_id)
scores.append(max_score)
boxes.append([left, top, width, height])
elif severity == 'HIGH':
# Strict validation for high-severity content
if max_score >= 0.5:
class_ids.append(class_id)
scores.append(max_score)
boxes.append([left, top, width, height])
else:
# Standard validation for other content
class_ids.append(class_id)
scores.append(max_score)
boxes.append([left, top, width, height])
# Use stricter NMS parameters matching live.py for better filtering
indices = cv2.dnn.NMSBoxes(boxes, scores, 0.3, 0.4)
detections = []
if len(indices) > 0:
for i in indices:
box = boxes[i]
score = scores[i]
class_id = class_ids[i]
label = STREAMING_LABELS[class_id]
severity = get_streaming_safety(label)
detections.append({
"class": label,
"score": float(score),
"box": box,
"severity": severity
})
return detections
def detect_frame(self, frame):
"""Detect content in frame optimized for streaming."""
if self.onnx_session is None:
return []
try:
# Preprocess
input_data, resize_factor, pad_left, pad_top = self.preprocess_frame(
frame, self.input_size
)
# Run inference
outputs = self.onnx_session.run(None, {self.input_name: input_data})
# Postprocess
detections = self.postprocess_detections(outputs, resize_factor, pad_left, pad_top)
return detections
except Exception as e:
print(f"Detection error: {e}")
return []
class StreamProcessor:
"""Main streaming processor with all integrations."""
def __init__(self, config=None):
# Load configuration
self.config = config or STREAMER_CONFIG.copy()
# Initialize components
self.detector = StreamerDetector()
self.obs = None
self.screen_capture = None
self.virtual_camera = None
self.camera = None
# Initialize detection tracker for stable blur
self.tracker = DetectionTracker(
max_age=45, # Keep tracks for 45 frames (1.5 seconds at 30fps)
iou_threshold=0.3, # IoU threshold for matching
confidence_decay=0.98 # Slow confidence decay for stability
)
# State tracking
self.running = False
self.input_mode = self.config['INPUT_MODE']
self.frame_count = 0
self.detection_count = 0
self.last_detections = []
self.stable_tracks = [] # Tracks from previous frame
self.safe_mode = False
self.safe_mode_start = 0
# Performance tracking
self.fps_counter = 0
self.fps_start = time.time()
self.actual_fps = 0
self.processing_fps = 0
# Detection logging
self.detection_log = []
# Initialize integrations
self.init_integrations()
def init_integrations(self):
"""Initialize OBS, virtual camera, and input sources."""
# OBS Integration
if OBS_AVAILABLE:
self.obs = OBSIntegration(
host=self.config['OBS_HOST'],
port=self.config['OBS_PORT'],
password=self.config['OBS_PASSWORD']
)
# Virtual Camera
if PYVIRTUALCAM_AVAILABLE and self.config['VIRTUAL_CAM_ENABLED']:
width, height = self.config['RESOLUTION']
self.virtual_camera = VirtualCamera(
width=width,
height=height,
fps=self.config['VIRTUAL_CAM_FPS']
)
# Screen Capture
if MSS_AVAILABLE:
self.screen_capture = ScreenCapture(
monitor=self.config['SCREEN_CAPTURE_MONITOR']
)
# Camera Input
if self.input_mode == 'CAMERA':
self.init_camera()
def init_camera(self):
"""Initialize camera input."""
try:
self.camera = cv2.VideoCapture(self.config['CAMERA_ID'])
if not self.camera.isOpened():
raise RuntimeError(f"Cannot open camera {self.config['CAMERA_ID']}")
# Set camera properties
width, height = self.config['RESOLUTION']
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
self.camera.set(cv2.CAP_PROP_FPS, self.config['TARGET_FPS'])
# Get actual properties
actual_width = int(self.camera.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_height = int(self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
actual_fps = self.camera.get(cv2.CAP_PROP_FPS)
print(f"Camera initialized: {actual_width}x{actual_height} @ {actual_fps}FPS")
except Exception as e:
print(f"Camera initialization failed: {e}")
self.camera = None
def get_frame(self):
"""Get frame from current input source."""
frame = None
if self.input_mode == 'CAMERA' and self.camera:
ret, frame = self.camera.read()
if not ret:
frame = None
elif self.input_mode == 'SCREEN' and self.screen_capture:
frame = self.screen_capture.capture_screen()
elif self.input_mode == 'WINDOW' and self.screen_capture:
frame = self.screen_capture.capture_window(self.config['WINDOW_TITLE'])
# Resize frame to target resolution if needed
if frame is not None:
target_width, target_height = self.config['RESOLUTION']
if frame.shape[:2] != (target_height, target_width):
frame = cv2.resize(frame, (target_width, target_height))
return frame
def process_frame(self, frame):
"""Process frame with AI detection and apply safety measures with tracking."""
if frame is None:
return frame
processed_frame = frame.copy()
# Skip AI processing on some frames for performance
should_process_ai = (self.frame_count % max(1, self.config['TARGET_FPS'] // self.config['PROCESSING_FPS']) == 0)
raw_detections = []
if should_process_ai and self.detector.onnx_session is not None:
raw_detections = self.detector.detect_frame(frame)
# Update tracker with new detections
if raw_detections or should_process_ai:
# Update tracker even with empty detections to age existing tracks
self.stable_tracks = self.tracker.update(raw_detections)
# Use stable tracks for consistent blur
if self.stable_tracks:
self.last_detections = self.stable_tracks
self.detection_count += len([t for t in self.stable_tracks if t['age'] == 0]) # Only count new detections
# Log detections
if self.config['LOG_DETECTIONS'] and raw_detections:
self.log_detections(raw_detections)
# Apply safety measures using stable tracks
processed_frame = self.apply_safety_measures(processed_frame, self.stable_tracks)
# Handle streaming actions
self.handle_streaming_actions(self.stable_tracks)
# Apply overlays
if self.config['OVERLAY_ENABLED']:
processed_frame = self.apply_overlays(processed_frame, self.stable_tracks)
# Check safe mode timeout
if self.safe_mode and time.time() - self.safe_mode_start > self.config['SAFE_MODE_TIMEOUT']:
self.exit_safe_mode()
return processed_frame
def apply_safety_measures(self, frame, tracks):
"""Apply real-time censoring to tracked regions with stable blur."""
censored_frame = frame.copy()
font = cv2.FONT_HERSHEY_SIMPLEX
# Define severity colors for visual feedback
severity_colors = {
'CRITICAL': (0, 0, 255), # Red for critical content
'HIGH': (0, 165, 255), # Orange for high severity
'MODERATE': (0, 255, 255), # Yellow for moderate
'LOW': (0, 255, 0), # Green for low severity
'SAFE': (255, 255, 255) # White for safe content
}
for track in tracks:
box = track["box"]
x, y, w, h = box[0], box[1], box[2], box[3]
label = track["class"]
score = track["confidence"] # Use tracked confidence
severity = track.get("severity", "MODERATE")
track_id = track["id"]
age = track["age"]
# Check bounds
if x < 0 or y < 0 or x + w > frame.shape[1] or y + h > frame.shape[0]:
continue
# Determine if censoring should be applied based on severity
should_censor = False
# Apply severity-based logic with age consideration
if severity == 'CRITICAL':
should_censor = True
elif severity == 'HIGH':
should_censor = True
elif severity == 'MODERATE' and score >= 0.4:
should_censor = True
elif severity == 'LOW' and score >= 0.6:
should_censor = True
# For older tracks, keep censoring but potentially reduce strength
if age > 0 and should_censor:
# Keep censoring for tracked objects to prevent flickering
should_censor = True
# Apply censoring if needed
if should_censor:
roi = censored_frame[y:y + h, x:x + w]
if self.config.get('SOLID_COLOR_MASK', False):
# Solid color mask
censored_frame[y:y + h, x:x + w] = np.full(
(h, w, 3), self.config['MASK_COLOR'], dtype=np.uint8
)
else:
# Apply blur based on severity with age consideration
if severity == 'CRITICAL':
blur_strength = self.config['BLUR_STRENGTH_CRITICAL']
elif severity == 'HIGH':
blur_strength = int(self.config['BLUR_STRENGTH'] * 1.5) # Stronger blur
elif severity == 'MODERATE':
blur_strength = self.config['BLUR_STRENGTH']
else:
blur_strength = int(self.config['BLUR_STRENGTH'] * 0.7) # Lighter blur
# For older tracks, slightly reduce blur but keep consistency
if age > 10:
fade_factor = min(0.3, age / 100.0) # Max 30% reduction over time
blur_strength = int(blur_strength * (1.0 - fade_factor))
# OpenCV needs odd numbers for blur kernels
if blur_strength % 2 == 0:
blur_strength += 1
blurred_roi = cv2.GaussianBlur(roi, (blur_strength, blur_strength), 0)
censored_frame[y:y + h, x:x + w] = blurred_roi
# Draw detection box and label with severity-based colors
if self.config.get('SHOW_DETECTION_BOXES', True):
box_color = severity_colors.get(severity, (0, 255, 255))
text_color = box_color
# Adjust box thickness based on age (newer tracks get thicker boxes)
thickness = 3 if age == 0 else 2 if age < 10 else 1