-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsafeVisionScreenGuard.py
More file actions
1305 lines (1182 loc) · 54.3 KB
/
Copy pathsafeVisionScreenGuard.py
File metadata and controls
1305 lines (1182 loc) · 54.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
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 Screen Guard
Real-time local screen protection. Captures the current monitor with mss,
runs SafeVision detection, and draws a transparent topmost overlay that blocks
or outlines detected unsafe screen regions. No frames are recorded or saved.
"""
import argparse
import ctypes
import os
import queue
import sys
import threading
import time
import tkinter as tk
from pathlib import Path
import cv2
import numpy as np
try:
import mss
except ImportError:
mss = None
try:
from PIL import Image, ImageDraw, ImageTk
except ImportError:
Image = None
ImageDraw = None
ImageTk = None
from safevision_utils import label_group, label_matches_filter, parse_provider_list
from video import NudeDetector
APP_DIR = Path(__file__).resolve().parent
TRANSPARENT_COLOR = "#010203"
DEFAULT_BLOCK_COLOR = "0,0,0"
DEFAULT_LABEL_BG = "#111111"
GWL_EXSTYLE = -20
WS_EX_LAYERED = 0x00080000
WS_EX_TRANSPARENT = 0x00000020
WS_EX_TOOLWINDOW = 0x00000080
LWA_COLORKEY = 0x00000001
WDA_NONE = 0x00000000
WDA_EXCLUDEFROMCAPTURE = 0x00000011
SW_HIDE = 0
SW_SHOWNA = 8
SRCCOPY = 0x00CC0020
DIB_RGB_COLORS = 0
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", ctypes.c_uint32),
("biWidth", ctypes.c_long),
("biHeight", ctypes.c_long),
("biPlanes", ctypes.c_uint16),
("biBitCount", ctypes.c_uint16),
("biCompression", ctypes.c_uint32),
("biSizeImage", ctypes.c_uint32),
("biXPelsPerMeter", ctypes.c_long),
("biYPelsPerMeter", ctypes.c_long),
("biClrUsed", ctypes.c_uint32),
("biClrImportant", ctypes.c_uint32),
]
class BITMAPINFO(ctypes.Structure):
_fields_ = [
("bmiHeader", BITMAPINFOHEADER),
("bmiColors", ctypes.c_uint32 * 3),
]
def set_dpi_awareness():
if os.name != "nt":
return
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2)
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
def hex_to_colorref(value):
value = value.lstrip("#")
if len(value) != 6:
value = "010203"
red = int(value[0:2], 16)
green = int(value[2:4], 16)
blue = int(value[4:6], 16)
return red | (green << 8) | (blue << 16)
def configure_transparent_window(window, click_through=True, exclude_from_capture=True):
if os.name != "nt":
return
try:
window.update_idletasks()
hwnd = window.winfo_id()
user32 = ctypes.windll.user32
ex_style = user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
ex_style |= WS_EX_LAYERED | WS_EX_TOOLWINDOW
if click_through:
ex_style |= WS_EX_TRANSPARENT
else:
ex_style &= ~WS_EX_TRANSPARENT
user32.SetWindowLongW(hwnd, GWL_EXSTYLE, ex_style)
user32.SetLayeredWindowAttributes(hwnd, hex_to_colorref(TRANSPARENT_COLOR), 0, LWA_COLORKEY)
affinity = WDA_EXCLUDEFROMCAPTURE if exclude_from_capture else WDA_NONE
try:
user32.SetWindowDisplayAffinity(hwnd, affinity)
except Exception:
pass
except Exception:
pass
def bgr_to_hex(value):
parts = [part.strip() for part in str(value).split(",")]
if len(parts) != 3:
parts = DEFAULT_BLOCK_COLOR.split(",")
try:
b, g, r = [max(0, min(255, int(part))) for part in parts]
except ValueError:
b, g, r = 0, 0, 0
return f"#{r:02x}{g:02x}{b:02x}"
def normalize_color(value, default):
value = str(value or "").strip()
if value.startswith("#") and len(value) == 7:
return value
if "," in value:
return bgr_to_hex(value)
return default
def normalize_args(args):
if args.show_boxes is None:
args.show_boxes = args.mode in {"box", "both", "block"}
if args.block_enabled is None:
args.block_enabled = args.mode in {"block", "both"}
if args.blur_enabled is None:
args.blur_enabled = args.mode == "blur"
if args.privacy_on_detection is None:
args.privacy_on_detection = args.mode == "privacy"
args.line_width = max(1, int(args.line_width))
args.box_padding = max(0, int(args.box_padding))
args.min_box_area = max(0, int(args.min_box_area))
args.blur_strength = max(3, int(args.blur_strength))
args.hold_ms = max(0, int(args.hold_ms))
args.track_hold_ms = max(0, int(args.track_hold_ms))
args.fps = max(0.2, float(args.fps))
args.overlay_fps = max(1.0, float(args.overlay_fps))
args.threshold = max(0.0, min(1.0, float(args.threshold)))
args.smooth_iou = max(0.05, min(0.95, float(args.smooth_iou)))
args.smooth_alpha = max(0.05, min(1.0, float(args.smooth_alpha)))
args.stable_score_alpha = max(0.0, min(1.0, float(args.stable_score_alpha)))
args.merge_overlap = max(0.05, min(1.0, float(args.merge_overlap)))
args.merge_distance = max(0, int(args.merge_distance))
args.feedback_delta = max(0.0, float(args.feedback_delta))
args.capture_hide_ms = max(0, int(args.capture_hide_ms))
args.stale_region_delta = max(0.0, float(args.stale_region_delta))
args.screen_change_delta = max(0.0, float(args.screen_change_delta))
args.label_filter = str(args.label_filter or "exposed").lower()
return args
def list_monitors():
if mss is None:
print("mss is not installed. Install requirements.txt first.")
return 2
with mss.mss() as sct:
for index, monitor in enumerate(sct.monitors[1:], start=1):
print(
f"{index}: {monitor['width']}x{monitor['height']} "
f"at ({monitor['left']}, {monitor['top']})"
)
class MssCaptureBackend:
def __init__(self, monitor):
self.monitor = monitor
self.sct = None
def __enter__(self):
self.sct = mss.mss()
return self
def __exit__(self, _exc_type, _exc, _tb):
if self.sct is not None:
self.sct.close()
self.sct = None
def grab_bgr(self):
screenshot = self.sct.grab(self.monitor)
frame = np.array(screenshot)
return cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
class WindowsGdiCaptureBackend:
def __init__(self, monitor):
if os.name != "nt":
raise RuntimeError("Windows GDI capture is only available on Windows.")
self.monitor = monitor
self.width = int(monitor["width"])
self.height = int(monitor["height"])
self.left = int(monitor["left"])
self.top = int(monitor["top"])
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
self.gdi32 = ctypes.WinDLL("gdi32", use_last_error=True)
self.user32.GetDC.argtypes = [ctypes.c_void_p]
self.user32.GetDC.restype = ctypes.c_void_p
self.user32.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.user32.ReleaseDC.restype = ctypes.c_int
self.gdi32.CreateCompatibleDC.argtypes = [ctypes.c_void_p]
self.gdi32.CreateCompatibleDC.restype = ctypes.c_void_p
self.gdi32.CreateCompatibleBitmap.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
self.gdi32.CreateCompatibleBitmap.restype = ctypes.c_void_p
self.gdi32.CreateDIBSection.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.POINTER(ctypes.c_void_p),
ctypes.c_void_p,
ctypes.c_uint32,
]
self.gdi32.CreateDIBSection.restype = ctypes.c_void_p
self.gdi32.SelectObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.gdi32.SelectObject.restype = ctypes.c_void_p
self.gdi32.DeleteObject.argtypes = [ctypes.c_void_p]
self.gdi32.DeleteObject.restype = ctypes.c_int
self.gdi32.DeleteDC.argtypes = [ctypes.c_void_p]
self.gdi32.DeleteDC.restype = ctypes.c_int
self.gdi32.BitBlt.argtypes = [
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_uint32,
]
self.gdi32.BitBlt.restype = ctypes.c_int
self.gdi32.GetDIBits.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
]
self.gdi32.GetDIBits.restype = ctypes.c_int
self.screen_dc = None
self.memory_dc = None
self.bitmap = None
self.old_bitmap = None
self.bits = ctypes.c_void_p()
self.bitmap_info = BITMAPINFO()
self.bitmap_info.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
self.bitmap_info.bmiHeader.biWidth = self.width
self.bitmap_info.bmiHeader.biHeight = -self.height
self.bitmap_info.bmiHeader.biPlanes = 1
self.bitmap_info.bmiHeader.biBitCount = 32
self.bitmap_info.bmiHeader.biCompression = 0
def __enter__(self):
self.screen_dc = self.user32.GetDC(0)
if not self.screen_dc:
raise RuntimeError("Could not get Windows screen DC.")
self.memory_dc = self.gdi32.CreateCompatibleDC(self.screen_dc)
self.bitmap = self.gdi32.CreateDIBSection(
self.screen_dc,
ctypes.byref(self.bitmap_info),
DIB_RGB_COLORS,
ctypes.byref(self.bits),
None,
0,
)
if not self.memory_dc or not self.bitmap:
raise RuntimeError("Could not create Windows GDI capture objects.")
self.old_bitmap = self.gdi32.SelectObject(self.memory_dc, self.bitmap)
return self
def __exit__(self, _exc_type, _exc, _tb):
if self.memory_dc and self.old_bitmap:
self.gdi32.SelectObject(self.memory_dc, self.old_bitmap)
if self.bitmap:
self.gdi32.DeleteObject(self.bitmap)
if self.memory_dc:
self.gdi32.DeleteDC(self.memory_dc)
if self.screen_dc:
self.user32.ReleaseDC(0, self.screen_dc)
self.screen_dc = None
self.memory_dc = None
self.bitmap = None
self.old_bitmap = None
def grab_bgr(self):
ok = self.gdi32.BitBlt(
self.memory_dc,
0,
0,
self.width,
self.height,
self.screen_dc,
self.left,
self.top,
SRCCOPY,
)
if not ok:
error = ctypes.get_last_error()
raise RuntimeError(f"Windows GDI BitBlt capture failed (error {error}).")
if not self.bits:
raise RuntimeError("Windows GDI capture did not return a DIB buffer.")
size = self.width * self.height * 4
array_type = ctypes.c_ubyte * size
bgra = np.ctypeslib.as_array(array_type.from_address(self.bits.value)).reshape((self.height, self.width, 4))
return bgra[:, :, :3].copy()
class AutoCaptureBackend:
def __init__(self, monitor):
self.monitor = monitor
self.backend = None
self.backend_name = None
def __enter__(self):
if os.name == "nt":
try:
self.backend = WindowsGdiCaptureBackend(self.monitor)
self.backend.__enter__()
self.backend_name = "gdi"
return self
except Exception as exc:
print(f"Windows GDI capture unavailable ({exc}). Falling back to mss.")
try:
if self.backend is not None:
self.backend.__exit__(None, None, None)
except Exception:
pass
self.backend = MssCaptureBackend(self.monitor)
self.backend.__enter__()
self.backend_name = "mss"
return self
def __exit__(self, exc_type, exc, tb):
if self.backend is not None:
self.backend.__exit__(exc_type, exc, tb)
self.backend = None
def switch_to_mss(self, reason):
print(f"Capture backend {self.backend_name} failed ({reason}). Falling back to mss.")
try:
if self.backend is not None:
self.backend.__exit__(None, None, None)
except Exception:
pass
self.backend = MssCaptureBackend(self.monitor)
self.backend.__enter__()
self.backend_name = "mss"
def grab_bgr(self):
try:
return self.backend.grab_bgr()
except Exception as exc:
if self.backend_name != "mss":
self.switch_to_mss(exc)
return self.backend.grab_bgr()
raise
def create_capture_backend(args, monitor):
backend = args.capture_backend
if backend == "auto":
return AutoCaptureBackend(monitor)
if backend == "gdi":
return WindowsGdiCaptureBackend(monitor)
return MssCaptureBackend(monitor)
class ScreenGuard:
def __init__(self, args):
if mss is None:
raise RuntimeError("mss is not installed. Run: pip install -r requirements.txt")
self.args = args
self.running = threading.Event()
self.running.set()
self.result_queue = queue.Queue(maxsize=1)
self.latest_detections = []
self.latest_frame = None
self.latest_frame_signature = None
self.last_detection_time = 0.0
self.last_positive_time = 0.0
self.last_positive_screen_hash = None
self.previous_smoothed_detections = []
self.overlay_visible = True
self.block_color = bgr_to_hex(args.block_color)
self.outline_color = normalize_color(args.outline_color, "#ff3333")
self.safe_outline_color = normalize_color(args.safe_outline_color, "#3388ff")
self.rule_skipped_outline_color = normalize_color(args.rule_skipped_outline_color, "#aaaaaa")
self.label_bg = normalize_color(args.label_bg, DEFAULT_LABEL_BG)
self.label_color = args.label_color or "white"
self._tk_images = []
self._blur_cache = {}
self._last_draw_signature = None
self._last_status_draw = 0.0
self.stats = {
"frames": 0,
"detections": 0,
"last_fps_time": time.time(),
"fps": 0.0,
}
if args.blur_enabled and (Image is None or ImageTk is None):
raise RuntimeError("Pillow is required for screen blur mode. Run: pip install pillow")
with mss.mss() as sct:
if args.monitor < 1 or args.monitor >= len(sct.monitors):
raise ValueError(f"Monitor {args.monitor} is not available. Use --list-monitors.")
self.monitor = dict(sct.monitors[args.monitor])
self.detector = NudeDetector(providers=parse_provider_list(args.providers))
self.detector.load_exception_rules(args.rules)
set_dpi_awareness()
self.root = tk.Tk()
self.root.title("SafeVision Screen Guard")
self.root.overrideredirect(True)
self.root.attributes("-topmost", True)
self.root.configure(bg=TRANSPARENT_COLOR)
try:
self.root.attributes("-transparentcolor", TRANSPARENT_COLOR)
except tk.TclError:
pass
self.root.update_idletasks()
self.hwnd = self.root.winfo_id()
geometry = (
f"{self.monitor['width']}x{self.monitor['height']}"
f"+{self.monitor['left']}+{self.monitor['top']}"
)
self.root.geometry(geometry)
self.canvas = tk.Canvas(
self.root,
width=self.monitor["width"],
height=self.monitor["height"],
highlightthickness=0,
bg=TRANSPARENT_COLOR,
)
self.canvas.pack(fill="both", expand=True)
self.root.after(
50,
lambda: configure_transparent_window(
self.root,
args.click_through,
args.exclude_overlay_capture,
),
)
self.root.after(150, self.hide_overlay)
if not args.click_through:
self.root.bind("<Escape>", lambda _event: self.stop())
self.root.protocol("WM_DELETE_WINDOW", self.stop)
def stop(self):
self.running.clear()
try:
self.root.destroy()
except tk.TclError:
pass
def hide_overlay(self):
if not self.overlay_visible:
return
try:
self.root.withdraw()
self.overlay_visible = False
except tk.TclError:
pass
def show_overlay(self):
if self.overlay_visible:
return
try:
self.root.deiconify()
self.root.lift()
self.root.attributes("-topmost", True)
configure_transparent_window(
self.root,
self.args.click_through,
self.args.exclude_overlay_capture,
)
self.overlay_visible = True
except tk.TclError:
pass
def hide_window_for_capture(self):
if (
os.name != "nt"
or not self.args.feedback_safe_capture
or not self.overlay_visible
or not self.hwnd
):
return False
try:
ctypes.windll.user32.ShowWindow(self.hwnd, SW_HIDE)
if self.args.capture_hide_ms:
time.sleep(self.args.capture_hide_ms / 1000.0)
return True
except Exception:
return False
def restore_window_after_capture(self, was_hidden):
if not was_hidden or os.name != "nt" or not self.hwnd:
return
try:
ctypes.windll.user32.ShowWindow(self.hwnd, SW_SHOWNA)
except Exception:
pass
def capture_loop(self):
interval = 1.0 / max(1, self.args.fps)
with create_capture_backend(self.args, self.monitor) as capture:
while self.running.is_set():
start = time.time()
try:
hidden_for_capture = self.hide_window_for_capture()
frame = capture.grab_bgr()
self.restore_window_after_capture(hidden_for_capture)
screen_hash = self.screen_hash(frame)
detections = self.detector.detect_frame(frame)
detections = self.filter_detections(detections, frame, screen_hash)
frame_signature = self.attach_region_signatures(frame, detections)
self.publish_detections(
detections,
frame if self.args.blur_enabled else None,
frame_signature,
)
self.update_stats(detections)
except Exception as exc:
self.restore_window_after_capture(locals().get("hidden_for_capture", False))
print(f"Screen guard detection error: {exc}")
time.sleep(1.0)
elapsed = time.time() - start
if elapsed < interval:
time.sleep(interval - elapsed)
def filter_detections(self, detections, frame=None, screen_hash=None):
filtered = []
for detection in detections:
label = detection["class"]
score = detection["score"]
if score < self.args.threshold:
continue
if not label_matches_filter(label, self.args.label_filter):
continue
rule_allowed = self.detector.should_apply_blur(label)
if self.args.respect_rules and not rule_allowed:
continue
x, y, w, h = detection["box"]
padding = self.args.box_padding
x1 = max(0, min(self.monitor["width"], x - padding))
y1 = max(0, min(self.monitor["height"], y - padding))
x2 = max(0, min(self.monitor["width"], x + w + padding))
y2 = max(0, min(self.monitor["height"], y + h + padding))
if x2 <= x1 or y2 <= y1:
continue
if (x2 - x1) * (y2 - y1) < self.args.min_box_area:
continue
cleaned = dict(detection)
cleaned["box"] = [x1, y1, x2 - x1, y2 - y1]
cleaned["rule_allowed"] = rule_allowed
cleaned["label_group"] = label_group(label)
filtered.append(cleaned)
if self.args.smooth_overlay:
filtered = self.smooth_detections(filtered, frame, screen_hash)
elif self.args.blur_enabled:
for detection in filtered:
self.attach_blur_source(detection, frame)
return filtered
@staticmethod
def detection_iou(first, second):
ax, ay, aw, ah = first["box"]
bx, by, bw, bh = second["box"]
ax2 = ax + aw
ay2 = ay + ah
bx2 = bx + bw
by2 = by + bh
ix1 = max(ax, bx)
iy1 = max(ay, by)
ix2 = min(ax2, bx2)
iy2 = min(ay2, by2)
if ix2 <= ix1 or iy2 <= iy1:
return 0.0
intersection = (ix2 - ix1) * (iy2 - iy1)
union = aw * ah + bw * bh - intersection
if union <= 0:
return 0.0
return intersection / union
@staticmethod
def union_box(first_box, second_box):
ax, ay, aw, ah = first_box
bx, by, bw, bh = second_box
x1 = min(ax, bx)
y1 = min(ay, by)
x2 = max(ax + aw, bx + bw)
y2 = max(ay + ah, by + bh)
return [x1, y1, x2 - x1, y2 - y1]
@staticmethod
def intersection_area(first_box, second_box):
ax, ay, aw, ah = first_box
bx, by, bw, bh = second_box
ix1 = max(ax, bx)
iy1 = max(ay, by)
ix2 = min(ax + aw, bx + bw)
iy2 = min(ay + ah, by + bh)
if ix2 <= ix1 or iy2 <= iy1:
return 0
return (ix2 - ix1) * (iy2 - iy1)
def expanded_intersects(self, first_box, second_box):
distance = self.args.merge_distance
if distance <= 0:
return False
ax, ay, aw, ah = first_box
bx, by, bw, bh = second_box
ax1 = ax - distance
ay1 = ay - distance
ax2 = ax + aw + distance
ay2 = ay + ah + distance
bx1 = bx - distance
by1 = by - distance
bx2 = bx + bw + distance
by2 = by + bh + distance
return ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1
def should_merge_detections(self, first, second):
if self.detection_iou(first, second) >= self.args.smooth_iou:
return True
intersection = self.intersection_area(first["box"], second["box"])
if intersection > 0:
first_area = max(1, first["box"][2] * first["box"][3])
second_area = max(1, second["box"][2] * second["box"][3])
if intersection / min(first_area, second_area) >= self.args.merge_overlap:
return True
if self.args.merge_nearby and self.expanded_intersects(first["box"], second["box"]):
return True
if self.args.merge_nearby and self.same_visual_target(first["box"], second["box"]):
return True
return False
@staticmethod
def box_center(box):
x, y, w, h = box
return x + w / 2.0, y + h / 2.0
def same_visual_target(self, first_box, second_box):
ax, ay = self.box_center(first_box)
bx, by = self.box_center(second_box)
distance = ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
first_size = max(first_box[2], first_box[3])
second_size = max(second_box[2], second_box[3])
dynamic_distance = max(self.args.merge_distance, int(max(first_size, second_size) * 0.9))
return distance <= dynamic_distance
def merge_overlapping_detections(self, detections):
merged = []
for detection in sorted(detections, key=lambda item: item["score"], reverse=True):
target = None
for existing in merged:
if self.should_merge_detections(existing, detection):
target = existing
break
if target is None:
copy = dict(detection)
copy["merged_labels"] = [detection["class"]]
merged.append(copy)
continue
target["box"] = self.union_box(target["box"], detection["box"])
if detection["score"] > target["score"]:
target["class"] = detection["class"]
target["score"] = detection["score"]
target["label_group"] = detection.get("label_group", target.get("label_group"))
target["rule_allowed"] = target.get("rule_allowed", True) and detection.get("rule_allowed", True)
labels = target.setdefault("merged_labels", [target["class"]])
if detection["class"] not in labels:
labels.append(detection["class"])
return merged
def interpolate_box(self, previous_box, current_box):
alpha = self.args.smooth_alpha
return [
int(round(previous_box[index] + (current_box[index] - previous_box[index]) * alpha))
for index in range(4)
]
def stabilize_detection_metadata(self, detection, previous, feedback_only=False):
if previous is None:
detection["stable_score"] = float(detection.get("score", 0.0))
return detection
if feedback_only:
detection["class"] = previous.get("class", detection.get("class"))
detection["score"] = previous.get("score", detection.get("score", 0.0))
detection["stable_score"] = previous.get("stable_score", detection.get("score", 0.0))
detection["label_group"] = previous.get("label_group", detection.get("label_group"))
detection["merged_labels"] = previous.get("merged_labels", detection.get("merged_labels", []))
return detection
previous_score = float(previous.get("stable_score", previous.get("score", detection.get("score", 0.0))))
current_score = float(detection.get("score", 0.0))
alpha = self.args.stable_score_alpha
stable_score = previous_score + (current_score - previous_score) * alpha
detection["stable_score"] = stable_score
detection["score"] = stable_score
if previous.get("label_group") == detection.get("label_group") and current_score <= previous_score + 0.08:
detection["class"] = previous.get("class", detection.get("class"))
return detection
def screen_changed_since_positive(self, screen_hash):
if not self.args.drop_stale_on_screen_change:
return False
delta = self.region_delta(self.last_positive_screen_hash, screen_hash)
return delta is not None and delta > self.args.screen_change_delta
def smooth_detections(self, detections, frame=None, screen_hash=None):
now = time.time()
merged = self.merge_overlapping_detections(detections)
if not merged:
if self.screen_changed_since_positive(screen_hash):
self.previous_smoothed_detections = []
return []
if (
self.previous_smoothed_detections
and now - self.last_positive_time <= self.args.track_hold_ms / 1000.0
):
held = []
for detection in self.previous_smoothed_detections:
copy = dict(detection)
if not self.held_detection_is_still_valid(copy, frame):
continue
copy["held"] = True
held.append(copy)
if not held:
self.previous_smoothed_detections = []
return held
self.previous_smoothed_detections = []
return []
smoothed = []
real_detection_seen = False
for detection in merged:
best_previous = None
best_iou = 0.0
for previous in self.previous_smoothed_detections:
overlap = self.detection_iou(previous, detection)
if overlap > best_iou or self.should_merge_detections(previous, detection):
best_iou = overlap
best_previous = previous
copy = dict(detection)
feedback_only = self.detection_looks_like_overlay_feedback(copy, frame, best_previous)
if feedback_only and self.screen_changed_since_positive(screen_hash):
continue
if feedback_only:
copy["box"] = list(best_previous["box"])
copy["feedback_only"] = True
elif best_previous is not None and (best_iou >= self.args.smooth_iou or self.should_merge_detections(best_previous, detection)):
copy["box"] = self.interpolate_box(best_previous["box"], detection["box"])
if not feedback_only:
real_detection_seen = True
self.stabilize_detection_metadata(copy, best_previous, feedback_only)
if self.args.blur_enabled:
self.attach_blur_source(copy, frame, best_previous, use_previous=feedback_only)
smoothed.append(copy)
if not smoothed:
self.previous_smoothed_detections = []
return []
self.previous_smoothed_detections = [dict(detection) for detection in smoothed]
self.last_positive_time = now
if real_detection_seen:
self.last_positive_screen_hash = screen_hash
return smoothed
def hash_region_array(self, region):
if region is None or region.size == 0:
return None
sample = cv2.resize(region, (8, 8), interpolation=cv2.INTER_AREA)
return sample.tobytes()
def extract_region(self, frame, box, inset=0):
if frame is None:
return None
x, y, w, h = [int(value) for value in box]
inset = max(0, int(inset))
x1 = max(0, x + inset)
y1 = max(0, y + inset)
x2 = min(frame.shape[1], x + w - inset)
y2 = min(frame.shape[0], y + h - inset)
if x2 <= x1 or y2 <= y1:
return None
return frame[y1:y2, x1:x2]
def region_hash(self, frame, box, inset=0):
return self.hash_region_array(self.extract_region(frame, box, inset=inset))
def process_censor_region(self, region):
if region is None or region.size == 0:
return None
if self.args.blur_style == "pixelate":
scale = max(4, min(40, self.args.blur_strength))
small_w = max(1, region.shape[1] // scale)
small_h = max(1, region.shape[0] // scale)
processed = cv2.resize(region, (small_w, small_h), interpolation=cv2.INTER_LINEAR)
return cv2.resize(processed, (region.shape[1], region.shape[0]), interpolation=cv2.INTER_NEAREST)
kernel = self.args.blur_strength
if kernel % 2 == 0:
kernel += 1
return cv2.GaussianBlur(region, (kernel, kernel), 0)
def attach_blur_source(self, detection, frame, previous=None, use_previous=False):
if use_previous and previous is not None and previous.get("source_patch") is not None:
detection["source_patch"] = previous.get("source_patch")
detection["source_hash"] = previous.get("source_hash")
detection["censor_hash"] = previous.get("censor_hash")
detection["region_hash"] = previous.get("source_hash")
return
region = self.extract_region(frame, detection["box"])
if region is None or region.size == 0:
if previous is not None and previous.get("source_patch") is not None:
self.attach_blur_source(detection, frame, previous, use_previous=True)
return
source_patch = region.copy()
censored_patch = self.process_censor_region(source_patch)
detection["source_patch"] = source_patch
detection["source_hash"] = self.hash_region_array(source_patch)
detection["censor_hash"] = self.hash_region_array(censored_patch)
detection["region_hash"] = detection["source_hash"]
def detection_looks_like_overlay_feedback(self, detection, frame, previous):
if previous is None or frame is None or not self.args.blur_enabled:
return False
if previous.get("censor_hash") is None:
return False
if self.detection_iou(previous, detection) < 0.15 and not self.should_merge_detections(previous, detection):
return False
inset = max(self.args.line_width + 2, 4)
current_hash = self.region_hash(frame, detection["box"], inset=inset)
delta = self.region_delta(previous.get("censor_hash"), current_hash)
return delta is not None and delta <= self.args.feedback_delta
@staticmethod
def screen_hash(frame):
if frame is None:
return None
sample = cv2.resize(frame, (24, 14), interpolation=cv2.INTER_AREA)
return sample.tobytes()
@staticmethod
def region_delta(first_hash, second_hash):
if not first_hash or not second_hash or len(first_hash) != len(second_hash):
return None
first = np.frombuffer(first_hash, dtype=np.uint8).astype(np.int16)
second = np.frombuffer(second_hash, dtype=np.uint8).astype(np.int16)
return float(np.mean(np.abs(first - second)))
def held_detection_is_still_valid(self, detection, frame):
if not self.args.drop_stale_on_screen_change:
return True
if frame is None:
return True
if self.region_looks_like_censor_feedback(detection, frame):
return True
previous_hash = detection.get("source_hash") or detection.get("region_hash")
current_hash = self.region_hash(frame, detection["box"])
delta = self.region_delta(previous_hash, current_hash)
if delta is None:
return False
if delta > self.args.stale_region_delta:
return False
detection["region_hash"] = current_hash
return True
def region_looks_like_censor_feedback(self, detection, frame):
if frame is None or not self.args.blur_enabled or detection.get("censor_hash") is None:
return False
inset = max(self.args.line_width + 2, 4)
current_hash = self.region_hash(frame, detection["box"], inset=inset)
delta = self.region_delta(detection.get("censor_hash"), current_hash)
return delta is not None and delta <= self.args.feedback_delta
def attach_region_signatures(self, frame, detections):
if not detections or not self.args.blur_enabled:
return None
signatures = []
for detection in detections:
signature = detection.get("source_hash") if self.args.smooth_overlay else self.region_hash(frame, detection["box"])
detection["region_hash"] = signature
signatures.append(signature)
return tuple(signatures)
def publish_detections(self, detections, frame=None, frame_signature=None):
if self.result_queue.full():
try:
self.result_queue.get_nowait()
except queue.Empty:
pass
self.result_queue.put_nowait((time.time(), detections, frame, frame_signature))
def update_stats(self, detections):
self.stats["frames"] += 1
self.stats["detections"] += len(detections)
now = time.time()
delta = now - self.stats["last_fps_time"]
if delta >= 1.0:
self.stats["fps"] = self.stats["frames"] / delta
self.stats["frames"] = 0
self.stats["last_fps_time"] = now
def draw_loop(self):
try:
while True:
(
self.last_detection_time,
self.latest_detections,
self.latest_frame,
self.latest_frame_signature,
) = self.result_queue.get_nowait()
except queue.Empty:
pass
detections = self.latest_detections
frame = self.latest_frame
frame_signature = self.latest_frame_signature
draw_signature = self.overlay_signature(detections, frame_signature)
status_due = self.args.show_status and time.time() - self._last_status_draw >= 0.5
if not self.args.smooth_overlay or draw_signature != self._last_draw_signature or status_due:
self.draw_overlay(detections, frame)
self._last_draw_signature = draw_signature
if self.args.show_status:
self._last_status_draw = time.time()
if self.running.is_set():
self.root.after(max(15, int(1000 / max(1, self.args.overlay_fps))), self.draw_loop)
def overlay_signature(self, detections, frame_signature=None):
if not detections:
return ("empty", bool(self.args.show_status))
detection_parts = []
for detection in detections:
x, y, w, h = detection["box"]
detection_parts.append(
(
detection.get("class"),
round(float(detection.get("score", 0)), 2),
int(x) // 3,
int(y) // 3,
int(w) // 3,
int(h) // 3,
detection.get("label_group"),
detection.get("rule_allowed", True),
)
)
return (
tuple(detection_parts),
frame_signature if self.args.blur_enabled else None,
self.args.show_boxes,
self.args.show_labels,
self.args.block_enabled,
self.args.blur_enabled,
self.args.privacy_on_detection,
)
def detection_outline_color(self, detection):
if not detection.get("rule_allowed", True):
return self.rule_skipped_outline_color
if detection.get("label_group") != "exposed":