-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathvideo.py
More file actions
1703 lines (1446 loc) · 78.2 KB
/
Copy pathvideo.py
File metadata and controls
1703 lines (1446 loc) · 78.2 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
import os
import math
import cv2
import numpy as np
import onnx
from onnx import version_converter
import onnxruntime
import argparse
import time
from tqdm import tqdm
import subprocess
import shutil
import sys
import platform
import zipfile
import urllib.request
import tempfile
from pathlib import Path
from safevision_utils import (
apply_region_censor as shared_apply_region_censor,
cv2_imwrite,
create_onnx_session,
detection_is_censorable,
load_blur_exception_rules,
make_blur_kernel,
normalize_mask_shape,
open_video_capture,
parse_provider_list,
parse_detector_selection,
)
from object_detector import DEFAULT_OBJECT_LABELS, DEFAULT_OBJECT_MODEL, ObjectContentDetector
from marker_export import (
detection_events_from_frame,
export_marker_files,
write_detection_reports,
)
# Configuration variables - adjust these for different visual effects
CONFIG = {
# Blur settings
'BLUR_STRENGTH_NORMAL': (23, 23, 30), # (kernel_size_x, kernel_size_y, sigma)
'BLUR_STRENGTH_HIGH': (31, 31, 50), # Stronger blur for more sensitive content
'FULL_BLUR_STRENGTH': (99, 99, 75), # Very strong blur for full frame blurring
'ENHANCED_BLUR': False, # When True, applies stronger blur that completely obscures content
# Box colors (BGR format)
'BOX_COLOR_NORMAL': (0, 255, 0), # Green for normal content
'BOX_COLOR_EXPOSED': (0, 0, 255), # Red for exposed content
# Text settings
'FONT_SCALE': 0.5,
'FONT_THICKNESS': 1,
'TEXT_COLOR_NORMAL': (0, 255, 0), # Green for normal text
'TEXT_COLOR_EXPOSED': (0, 0, 255), # Red for exposed text
# Detection threshold
'DETECTION_THRESHOLD': 0.2, # Minimum confidence score for detection
# Monitoring settings
'MONITOR_THRESHOLD_PERCENT': 10.0, # Default percentage threshold for monitoring (overridden by -r)
'MONITOR_THRESHOLD_COUNT': 5, # Default count threshold for monitoring (overridden by -r)
# Full blur trigger
'FULL_BLUR_LABELS': 2, # Number of exposed labels to trigger full blur (overridden by -fbr)
'FULL_BLUR_FRAMES': 10, # Minimum frames with exposed content to trigger full blur
# Solid color mask (alternative to blur)
'USE_SOLID_COLOR': False, # When True, uses solid color instead of blur
'SOLID_COLOR': (0, 0, 0), # BGR color for masking (black by default)
'MASK_SHAPE': 'rectangle', # Region mask shape: rectangle or ellipse
# Output naming
'OUTPUT_VIDEO_SUFFIX': '_processed.mp4',
'OUTPUT_VIDEO_BOXES_SUFFIX': '_with_boxes.mp4',
'OUTPUT_VIDEO_AUDIO_SUFFIX': '_with_audio.mp4',
'OUTPUT_VIDEO_BOXES_AUDIO_SUFFIX': '_with_boxes_audio.mp4',
}
# Try to import ffmpeg, but don't fail if it's not available
try:
import ffmpeg
except ImportError:
ffmpeg = None
__labels = [
"FEMALE_GENITALIA_COVERED",
"FACE_FEMALE",
"BUTTOCKS_EXPOSED",
"FEMALE_BREAST_EXPOSED",
"FEMALE_GENITALIA_EXPOSED",
"MALE_BREAST_EXPOSED",
"ANUS_EXPOSED",
"FEET_EXPOSED",
"BELLY_COVERED",
"FEET_COVERED",
"ARMPITS_COVERED",
"ARMPITS_EXPOSED",
"FACE_MALE",
"BELLY_EXPOSED",
"MALE_GENITALIA_EXPOSED",
"ANUS_COVERED",
"FEMALE_BREAST_COVERED",
"BUTTOCKS_COVERED",
]
def process_frames(video_path, detector, output_folder):
"""
Read a video, run the detector on each frame,
censor/save each frame to output_folder.
"""
import os
output_folder = output_folder or "output_frames"
cap = open_video_capture(video_path)
if not cap.isOpened():
raise FileNotFoundError(f"Could not open video: {video_path}")
os.makedirs(output_folder, exist_ok=True)
frame_idx = 0
while True:
ret, frame = cap.read()
if not ret:
break
frame_idx += 1
# detect + censor
dets = detector.detect_frame(frame)
out_path = os.path.join(output_folder, f"frame_{frame_idx:04d}.jpg")
detector.censor_frame(frame, dets, out_path)
cap.release()
def _read_frame(frame, target_size=320):
img_height, img_width = frame.shape[:2]
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
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_factor = math.sqrt(
(img_width**2 + img_height**2) / (new_width**2 + new_height**2)
)
img = cv2.resize(img, (new_width, new_height))
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))
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)
return image_data, resize_factor, pad_left, pad_top
def _postprocess(output, resize_factor, pad_left, pad_top):
outputs = np.transpose(np.squeeze(output[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)
if max_score >= 0.2:
class_id = np.argmax(classes_scores)
x, y, w, h = outputs[i][0], outputs[i][1], outputs[i][2], outputs[i][3]
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))
class_ids.append(class_id)
scores.append(max_score)
boxes.append([left, top, width, height])
indices = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45)
detections = []
for i in indices:
box = boxes[i]
score = scores[i]
class_id = class_ids[i]
label = __labels[class_id]
detections.append(
{
"class": label,
"score": float(score),
"box": box,
"category": "exposed" if "EXPOSED" in label else ("covered" if "COVERED" in label else "face" if label.startswith("FACE_") else "other"),
"source": "nude",
"model": "safevision_nude",
"censor": "EXPOSED" in label,
}
)
return detections
def _ensure_opset15(original_path: str) -> str:
"""
Load the original ONNX model, convert it to opset 15 if needed,
and save to a new file. Returns the path to the opset-15 model.
"""
base, ext = os.path.splitext(original_path)
conv_path = f"{base}_opset15{ext}"
if not os.path.exists(conv_path):
model = onnx.load(original_path)
converted = version_converter.convert_version(model, 15)
onnx.save(converted, conv_path)
return conv_path
# Function to create a video writer with fallback codecs
def create_safe_video_writer(output_path, width, height, fps, codec_preference=None):
"""
Create a VideoWriter with fallback options if the preferred codec fails
"""
# Try the specified codec first
if codec_preference:
try:
fourcc = cv2.VideoWriter_fourcc(*codec_preference)
writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
if writer.isOpened():
print(f"Using codec: {codec_preference}")
return writer
except Exception as e:
print(f"Failed with preferred codec {codec_preference}: {str(e)}")
# Try a list of codecs in order
codecs = ["mp4v", "XVID", "MJPG", "DIVX"]
for codec in codecs:
if codec == codec_preference:
continue # Skip if we already tried it
try:
fourcc = cv2.VideoWriter_fourcc(*codec)
writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
if writer.isOpened():
print(f"Using codec: {codec}")
return writer
except Exception as e:
print(f"Failed with codec {codec}: {str(e)}")
# If all else fails, try with default codec
print("All codecs failed, trying with default codec (0)")
writer = cv2.VideoWriter(output_path, 0, fps, (width, height))
if not writer.isOpened():
print("ERROR: Could not create video writer with any codec.")
return writer
def download_model(url, save_path):
"""Download the ONNX model from the provided URL and save it to the specified path."""
import urllib.request
print(f"Downloading model from {url}...")
try:
# Create the directory if it doesn't exist
os.makedirs(os.path.dirname(save_path), exist_ok=True)
# Download the file
urllib.request.urlretrieve(url, save_path)
print(f"Model downloaded successfully to {save_path}")
return True
except Exception as e:
print(f"Error downloading model: {str(e)}")
return False
class NudeDetector:
def __init__(self, providers=None):
# 1) locate the shipped model
model_dir = os.path.join(os.path.dirname(__file__), "Models")
model_orig = os.path.join(model_dir, "best.onnx")
# Check if model exists, if not download it
if not os.path.exists(model_orig):
print("Model file not found. Creating Models directory and downloading model...")
model_url = "https://github.com/im-syn/SafeVision/raw/refs/heads/main/Models/best.onnx"
success = download_model(model_url, model_orig)
if not success:
raise FileNotFoundError(f"Could not download model from {model_url}. Please download manually and place in {model_dir}")
# 2) convert/downgrade to opset15 on first run
model_to_load = _ensure_opset15(model_orig)
# 3) now load the compatible model
self.onnx_session = create_onnx_session(model_to_load, providers=providers)
# 4) pull out input shape & name as before
inp = self.onnx_session.get_inputs()[0]
self.input_name = inp.name
self.input_width = inp.shape[2] # 320
self.input_height = inp.shape[3] # 320
# Initialize exception rules to None
self.blur_exception_rules = None
def load_exception_rules(self, rule_file_path):
if not rule_file_path:
rule_file_path = "BlurException.rule"
self.blur_exception_rules = load_blur_exception_rules(rule_file_path, labels=globals()["__labels"])
print(f"Loaded {len(self.blur_exception_rules)} exception rules from {rule_file_path}")
def should_apply_blur(self, label):
return self.blur_exception_rules.get(label, True)
def detect_frame(self, frame):
preprocessed_image, resize_factor, pad_left, pad_top = _read_frame(
frame, self.input_width
)
outputs = self.onnx_session.run(None, {self.input_name: preprocessed_image})
detections = _postprocess(outputs, resize_factor, pad_left, pad_top)
return detections
def apply_region_censor(self, image, x, y, w, h, blur_kernel):
return shared_apply_region_censor(
image,
x,
y,
w,
h,
blur_kernel=blur_kernel,
use_solid_color=CONFIG['USE_SOLID_COLOR'],
solid_color=CONFIG['SOLID_COLOR'],
mask_shape=CONFIG.get('MASK_SHAPE', 'rectangle'),
)
def censor_frame(self, frame, detections, output_path, nsfw_percentage=None, force_full_blur=False, save_frame=True):
img_boxes = frame.copy()
img_combined = frame.copy()
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = CONFIG['FONT_SCALE']
font_thickness = CONFIG['FONT_THICKNESS']
# Check if we need to apply full frame blur based on the force_full_blur flag
if force_full_blur:
# Check if we should use solid color or blur
if CONFIG['USE_SOLID_COLOR']:
# Apply a solid color to the entire frame
height, width = img_combined.shape[:2]
img_combined = np.full((height, width, 3), CONFIG['SOLID_COLOR'], dtype=np.uint8)
# Also update the original frame for video output
frame[:] = np.full((height, width, 3), CONFIG['SOLID_COLOR'], dtype=np.uint8)
else:
# Apply a strong blur to the entire frame to fully conceal all content
img_combined = cv2.GaussianBlur(img_combined,
(CONFIG['FULL_BLUR_STRENGTH'][0], CONFIG['FULL_BLUR_STRENGTH'][1]),
CONFIG['FULL_BLUR_STRENGTH'][2])
# Also update the original frame for video output
frame[:] = cv2.GaussianBlur(frame,
(CONFIG['FULL_BLUR_STRENGTH'][0], CONFIG['FULL_BLUR_STRENGTH'][1]),
CONFIG['FULL_BLUR_STRENGTH'][2])
# Add a warning text overlay
warning_text = "Content Filtered - Excessive NSFW Content"
text_size = cv2.getTextSize(warning_text, font, 1.0, 2)[0]
text_x = (img_combined.shape[1] - text_size[0]) // 2
text_y = (img_combined.shape[0] + text_size[1]) // 2
cv2.putText(img_combined, warning_text, (text_x, text_y), font, 1.0, (0, 0, 255), 2, cv2.LINE_AA)
# Also add warning text to the original frame
cv2.putText(frame, warning_text, (text_x, text_y), font, 1.0, (0, 0, 255), 2, cv2.LINE_AA)
# Still draw boxes on the box image for reference
for detection in detections:
box = detection["box"]
x, y, w, h = box[0], box[1], box[2], box[3]
label = detection["class"]
is_censorable = detection_is_censorable(detection)
box_color = CONFIG['BOX_COLOR_EXPOSED'] if is_censorable else CONFIG['BOX_COLOR_NORMAL']
cv2.rectangle(img_boxes, (x, y), (x + w, y + h), box_color, 2)
else:
# Normal processing for individual detections
for detection in detections:
box = detection["box"]
x, y, w, h = box[0], box[1], box[2], box[3]
label = detection["class"]
is_censorable = detection_is_censorable(detection)
label_text = label if not is_censorable else "Unsafe, " + label
# Select colors based on content type (exposed or normal)
box_color = CONFIG['BOX_COLOR_EXPOSED'] if is_censorable else CONFIG['BOX_COLOR_NORMAL']
text_color = CONFIG['TEXT_COLOR_EXPOSED'] if is_censorable else CONFIG['TEXT_COLOR_NORMAL']
# Select blur strength based on content sensitivity and enhanced blur setting
if CONFIG['ENHANCED_BLUR'] and is_censorable:
blur_kernel = CONFIG['FULL_BLUR_STRENGTH'] # Use the strongest blur for enhanced mode
else:
blur_kernel = CONFIG['BLUR_STRENGTH_HIGH'] if is_censorable else CONFIG['BLUR_STRENGTH_NORMAL']
x1 = max(0, x)
y1 = max(0, y)
x2 = min(frame.shape[1], x + w)
y2 = min(frame.shape[0], y + h)
if x2 > x1 and y2 > y1:
if is_censorable and self.should_apply_blur(label):
self.apply_region_censor(img_combined, x, y, w, h, blur_kernel)
self.apply_region_censor(frame, x, y, w, h, blur_kernel)
else:
cv2.rectangle(img_boxes, (x1, y1), (x2, y2), box_color, 2)
cv2.putText(img_boxes, label_text, (x1, max(0, y1 - 5)), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
else:
cv2.rectangle(img_boxes, (x, y), (x + w, y + h), box_color, 2)
cv2.putText(img_boxes, label_text, (x, y - 5), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
# Always draw boxes and labels on combined image
if x2 > x1 and y2 > y1:
cv2.rectangle(img_combined, (x1, y1), (x2, y2), box_color, 2)
cv2.putText(img_combined, label_text, (x1, max(0, y1 - 5)), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
if save_frame and output_path:
cv2_imwrite(output_path, img_combined)
cv2_imwrite(f"{output_path}_boxes.jpg", img_boxes)
# print(f"Processed frame {output_path}")
def blur_all_frames(self, frame_list, nsfw_percentage=None):
exposed_frame_count = 0
for _, detections, _ in frame_list:
exposed_count = self.check_exposed_count(detections)
if exposed_count >= 2:
exposed_frame_count += 1
total_frames = len(frame_list)
exposed_percentage = (exposed_frame_count / total_frames) * 100
for frame, detections, output_path in frame_list:
if exposed_percentage >= nsfw_percentage:
# Apply full blur to the whole image if the condition is met
self.censor_frame(frame, detections, output_path, nsfw_percentage=100, save_frame=False)
else:
# Blur individual frames based on the NSFW content
self.censor_frame(frame, detections, output_path, nsfw_percentage=nsfw_percentage, save_frame=False)
print(f"Exposure percentage: {exposed_percentage}%")
def check_exposed_count(self, detections):
exposed_labels = [detection["class"] for detection in detections if detection_is_censorable(detection)]
exposed_count = len(exposed_labels)
return exposed_count
class NudeVideoProcessor:
def __init__(
self,
video_path,
output_folder,
task="video",
providers=None,
video_output_folder="video_output",
blur_rule=0.5,
detectors="nude",
object_model=None,
object_labels=None,
object_threshold=0.25,
):
self.task = task.lower()
self.video_path = video_path
self.cap = open_video_capture(video_path)
if not self.cap.isOpened():
raise FileNotFoundError(f"Could not open video: {video_path}")
self.frame_width = int(self.cap.get(3))
self.frame_height = int(self.cap.get(4))
# Extract the input filename without extension for output naming
self.input_filename = os.path.splitext(os.path.basename(video_path))[0]
print(f"Processing input file: {self.input_filename}")
# Get the original frame rate
self.original_fps = self.cap.get(cv2.CAP_PROP_FPS)
if self.original_fps <= 0:
self.original_fps = 30.0 # Default to 30 fps if unable to determine
print(f"Original video FPS: {self.original_fps}")
self.enabled_detectors = parse_detector_selection(detectors)
self.detector = None
self.object_detector = None
self.blur_exception_rules = load_blur_exception_rules("BlurException.rule")
if "nude" in self.enabled_detectors:
self.detector = NudeDetector(providers)
self.detector.load_exception_rules("BlurException.rule")
if "objects" in self.enabled_detectors:
self.object_detector = ObjectContentDetector(
model_path=object_model or DEFAULT_OBJECT_MODEL,
labels_path=object_labels or DEFAULT_OBJECT_LABELS,
providers=providers,
threshold=object_threshold,
)
if not self.detector and not self.object_detector:
raise ValueError("No detectors enabled. Use --detectors nude, --detectors objects, or --detectors both.")
print(f"Enabled detectors: {', '.join(self.enabled_detectors)}")
self.output_folder = output_folder or "output_frames"
self.video_output_folder = video_output_folder
os.makedirs(self.output_folder, exist_ok=True)
os.makedirs(self.video_output_folder, exist_ok=True)
self.blur_rule = blur_rule
# Store command line arguments for access within class methods
global args
def detect_frame(self, frame):
detections = []
if self.detector:
detections.extend(self.detector.detect_frame(frame))
if self.object_detector:
detections.extend(self.object_detector.detect_frame(frame))
return detections
def should_apply_blur(self, label):
return self.blur_exception_rules.get(label, True)
def apply_region_censor(self, image, x, y, w, h, blur_kernel):
return shared_apply_region_censor(
image,
x,
y,
w,
h,
blur_kernel=blur_kernel,
use_solid_color=CONFIG['USE_SOLID_COLOR'],
solid_color=CONFIG['SOLID_COLOR'],
mask_shape=CONFIG.get('MASK_SHAPE', 'rectangle'),
)
def censor_frame(self, frame, detections, output_path, nsfw_percentage=None, force_full_blur=False, save_frame=True):
img_boxes = frame.copy()
img_combined = frame.copy()
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = CONFIG['FONT_SCALE']
font_thickness = CONFIG['FONT_THICKNESS']
if force_full_blur:
if CONFIG['USE_SOLID_COLOR']:
height, width = img_combined.shape[:2]
img_combined = np.full((height, width, 3), CONFIG['SOLID_COLOR'], dtype=np.uint8)
frame[:] = np.full((height, width, 3), CONFIG['SOLID_COLOR'], dtype=np.uint8)
else:
img_combined = cv2.GaussianBlur(
img_combined,
(CONFIG['FULL_BLUR_STRENGTH'][0], CONFIG['FULL_BLUR_STRENGTH'][1]),
CONFIG['FULL_BLUR_STRENGTH'][2],
)
frame[:] = cv2.GaussianBlur(
frame,
(CONFIG['FULL_BLUR_STRENGTH'][0], CONFIG['FULL_BLUR_STRENGTH'][1]),
CONFIG['FULL_BLUR_STRENGTH'][2],
)
warning_text = "Content Filtered - Excessive Unsafe Content"
text_size = cv2.getTextSize(warning_text, font, 1.0, 2)[0]
text_x = (img_combined.shape[1] - text_size[0]) // 2
text_y = (img_combined.shape[0] + text_size[1]) // 2
cv2.putText(img_combined, warning_text, (text_x, text_y), font, 1.0, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(frame, warning_text, (text_x, text_y), font, 1.0, (0, 0, 255), 2, cv2.LINE_AA)
else:
frame_height, frame_width = frame.shape[:2]
for detection in detections:
x, y, w, h = [int(value) for value in detection.get("box", [0, 0, 0, 0])]
x1 = max(0, x)
y1 = max(0, y)
x2 = min(frame_width, x + w)
y2 = min(frame_height, y + h)
if x2 <= x1 or y2 <= y1:
continue
label = detection.get("class", "UNKNOWN")
is_censorable = detection_is_censorable(detection)
label_text = label if not is_censorable else "Unsafe, " + label
box_color = CONFIG['BOX_COLOR_EXPOSED'] if is_censorable else CONFIG['BOX_COLOR_NORMAL']
text_color = CONFIG['TEXT_COLOR_EXPOSED'] if is_censorable else CONFIG['TEXT_COLOR_NORMAL']
if CONFIG['ENHANCED_BLUR'] and is_censorable:
blur_kernel = CONFIG['FULL_BLUR_STRENGTH']
else:
blur_kernel = CONFIG['BLUR_STRENGTH_HIGH'] if is_censorable else CONFIG['BLUR_STRENGTH_NORMAL']
if is_censorable and self.should_apply_blur(label):
self.apply_region_censor(img_combined, x1, y1, x2 - x1, y2 - y1, blur_kernel)
self.apply_region_censor(frame, x1, y1, x2 - x1, y2 - y1, blur_kernel)
cv2.rectangle(img_boxes, (x1, y1), (x2, y2), box_color, 2)
cv2.putText(img_boxes, label_text, (x1, max(0, y1 - 5)), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
cv2.rectangle(img_combined, (x1, y1), (x2, y2), box_color, 2)
cv2.putText(img_combined, label_text, (x1, max(0, y1 - 5)), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
if save_frame and output_path:
cv2_imwrite(output_path, img_combined)
cv2_imwrite(f"{output_path}_boxes.jpg", img_boxes)
def process_video(self):
self.original_video_path = self.video_path
if self.task == "frames":
self._process_frames_task()
return
if args and getattr(args, 'analyze_only', False):
self._process_analysis_stream()
elif args and hasattr(args, 'boxes') and args.boxes:
self._process_boxes_video_stream(include_blur=hasattr(args, 'blur') and args.blur)
else:
self._process_video_stream()
def _frame_output_path(self, frame_count):
return os.path.join(self.output_folder, f"frame_{frame_count}.jpg")
def _empty_video_stats(self):
return {
"total_frames": 0,
"total_exposed_boxes": 0,
"frames_with_exposed": 0,
"frames_with_required_labels": 0,
}
def _update_video_stats(self, stats, detections):
exposed_count = self.check_exposed_count(detections)
stats["total_frames"] += 1
stats["total_exposed_boxes"] += exposed_count
if exposed_count > 0:
stats["frames_with_exposed"] += 1
if exposed_count >= CONFIG['FULL_BLUR_LABELS']:
stats["frames_with_required_labels"] += 1
return exposed_count
def _metadata(self, total_frames=None, width=None, height=None):
return {
"source_path": os.path.abspath(self.video_path),
"source_name": os.path.basename(self.video_path),
"input_name": self.input_filename,
"fps": float(self.original_fps or 30.0),
"total_frames": int(total_frames or 0),
"duration_seconds": round((total_frames or 0) / float(self.original_fps or 30.0), 6),
"width": int(width or self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0),
"height": int(height or self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0),
}
def _record_detection_events(self, events, detections, frame_count):
events.extend(detection_events_from_frame(detections, frame_count, float(self.original_fps or 30.0)))
def _analysis_stats(self, stats):
result = dict(stats)
total_frames = result.get("total_frames", 0)
frames_with_exposed = result.get("frames_with_exposed", 0)
result["frames_with_exposed_percentage"] = round(
(frames_with_exposed / total_frames * 100) if total_frames else 0.0,
4,
)
return result
def _write_detection_outputs(self, events, stats, total_frames, width, height, force_report=False):
metadata = self._metadata(total_frames=total_frames, width=width, height=height)
written = []
should_write_report = force_report or bool(args and getattr(args, "save_report", False))
if should_write_report:
report_formats = getattr(args, "report_formats", "json,csv") if args else "json,csv"
written.extend(
write_detection_reports(
self.video_output_folder,
self.input_filename,
events,
metadata=metadata,
stats=self._analysis_stats(stats),
formats=report_formats,
)
)
marker_formats = getattr(args, "export_markers", "") if args else ""
if marker_formats:
marker_gap = getattr(args, "marker_gap", 1.0) if args else 1.0
written.extend(
export_marker_files(
self.video_output_folder,
self.input_filename,
events,
metadata=metadata,
formats=marker_formats,
gap_seconds=marker_gap,
)
)
for path in written:
print(f"Analysis output saved at: {path}")
return written
def _process_analysis_stream(self):
total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
stats = self._empty_video_stats()
events = []
frame_count = 0
width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
try:
with tqdm(total=total_frames if total_frames > 0 else None, desc="Analyzing Video", unit="frames", ncols=100, mininterval=0.5) as pbar:
while True:
ret, frame = self.cap.read()
if not ret:
break
frame_count += 1
if not width or not height:
height, width = frame.shape[:2]
detections = self.detect_frame(frame)
self._update_video_stats(stats, detections)
self._record_detection_events(events, detections, frame_count)
pbar.update(1)
finally:
self.cap.release()
if frame_count == 0:
print("No frames were read from the input video.")
return
self._write_detection_outputs(events, stats, frame_count, width, height, force_report=True)
summary = self._analysis_stats(stats)
print(
f"\nAnalysis complete: {len(events)} detections across "
f"{summary['frames_with_exposed']} exposed frames "
f"({summary['frames_with_exposed_percentage']:.2f}%)."
)
def _should_apply_full_blur_from_stats(self, stats):
total_frames = stats["total_frames"]
if total_frames <= 0:
return False, "", 0
frames_with_exposed = stats["frames_with_exposed"]
nsfw_percentage = frames_with_exposed / total_frames * 100
blur_rule_percentage, blur_rule_count = self.blur_rule
threshold_percentage = blur_rule_percentage if blur_rule_percentage > 0 else CONFIG['MONITOR_THRESHOLD_PERCENT']
threshold_count = blur_rule_count if blur_rule_count > 0 else CONFIG['MONITOR_THRESHOLD_COUNT']
print(f"\nFull blur analysis: {stats['frames_with_required_labels']} frames with {CONFIG['FULL_BLUR_LABELS']}+ exposed labels")
print(f"Full blur threshold: {CONFIG['FULL_BLUR_FRAMES']} frames")
if nsfw_percentage >= threshold_percentage:
return True, f"NSFW content ({nsfw_percentage:.1f}%) exceeds threshold ({threshold_percentage}%)", nsfw_percentage
if frames_with_exposed >= threshold_count:
return True, f"Frames with exposed content ({frames_with_exposed}) exceeds threshold ({threshold_count})", nsfw_percentage
if stats["frames_with_required_labels"] >= CONFIG['FULL_BLUR_FRAMES']:
return True, (
f"{stats['frames_with_required_labels']} frames with {CONFIG['FULL_BLUR_LABELS']}+ exposed labels "
f"(threshold: {CONFIG['FULL_BLUR_FRAMES']} frames)"
), nsfw_percentage
if CONFIG['FULL_BLUR_FRAMES'] == 1 and stats["frames_with_required_labels"] > 0:
return True, f"Found {stats['frames_with_required_labels']} frames with {CONFIG['FULL_BLUR_LABELS']}+ exposed labels", nsfw_percentage
return False, "", nsfw_percentage
def _process_frames_task(self):
frame_count = 0
total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
try:
with tqdm(total=total_frames if total_frames > 0 else None, desc="Processing Frames", unit="frames", ncols=100, mininterval=0.5) as pbar:
while True:
ret, frame = self.cap.read()
if not ret:
break
frame_count += 1
detections = self.detect_frame(frame)
self.censor_frame(frame, detections, self._frame_output_path(frame_count), save_frame=True)
pbar.update(1)
finally:
self.cap.release()
def _process_video_stream(self):
codec_preference = args.codec if args and hasattr(args, 'codec') else "mp4v"
output_filename = f"{self.input_filename}{CONFIG['OUTPUT_VIDEO_SUFFIX']}"
output_path = os.path.join(self.video_output_folder, output_filename)
total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
stats = self._empty_video_stats()
events = []
frame_count = 0
out = None
width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
try:
with tqdm(total=total_frames if total_frames > 0 else None, desc="Processing Video", unit="frames", ncols=100, mininterval=0.5) as pbar:
while True:
ret, frame = self.cap.read()
if not ret:
break
frame_count += 1
if out is None:
height, width = frame.shape[:2]
out = create_safe_video_writer(output_path, width, height, self.original_fps, codec_preference)
if not out.isOpened():
print("Failed to create video writer. Check your codec installation.")
return
detections = self.detect_frame(frame)
frame_exposed_count = self._update_video_stats(stats, detections)
self._record_detection_events(events, detections, frame_count)
if frame_count % 50 == 0:
if frame_exposed_count > 0:
exposed_labels = [d["class"] for d in detections if detection_is_censorable(d)]
print(f"Frame {frame_count}: {frame_exposed_count} censorable regions - {', '.join(exposed_labels)}")
if frame_exposed_count >= CONFIG['FULL_BLUR_LABELS']:
print(f"Frame {frame_count}: Has {frame_exposed_count} censorable labels (trigger threshold: {CONFIG['FULL_BLUR_LABELS']})")
frame_to_process = frame.copy()
self.censor_frame(frame_to_process, detections, None, save_frame=False)
out.write(frame_to_process)
pbar.update(1)
finally:
if out is not None:
out.release()
self.cap.release()
if frame_count == 0:
print("No frames were read from the input video.")
return
apply_full_blur, blur_reason, nsfw_percentage = self._should_apply_full_blur_from_stats(stats)
if apply_full_blur:
print(f"\nWARNING: {blur_reason}")
print("Applying full video blur as per monitoring rules")
blurred_filename = f"{self.input_filename}_fully_blurred.mp4"
blurred_output_path = os.path.join(self.video_output_folder, blurred_filename)
if self._create_full_blur_video_stream(blurred_output_path, nsfw_percentage):
print(f"Fully blurred video saved to: {blurred_output_path}")
if args and hasattr(args, 'with_audio') and args.with_audio and os.path.exists(self.video_path):
blurred_audio_filename = f"{self.input_filename}_fully_blurred_with_audio.mp4"
blurred_with_audio = os.path.join(self.video_output_folder, blurred_audio_filename)
success = self.add_audio_to_video(blurred_output_path, self.video_path, blurred_with_audio)
if success:
print(f"Fully blurred video with audio saved to: {blurred_with_audio}")
if args and hasattr(args, 'with_audio') and args.with_audio and os.path.exists(self.video_path):
audio_filename = f"{self.input_filename}{CONFIG['OUTPUT_VIDEO_AUDIO_SUFFIX']}"
output_with_audio = os.path.join(self.video_output_folder, audio_filename)
success = self.add_audio_to_video(output_path, self.video_path, output_with_audio)
if success:
print(f"\nVideo with audio saved at: {output_with_audio}")
else:
print(f"\nFailed to add audio. Video saved at: {output_path}")
else:
print(f"\nVideo saved at: {output_path}")
self._write_detection_outputs(events, stats, frame_count, width, height)
if args and hasattr(args, 'delete_frames') and args.delete_frames:
print("No intermediate frame images were written in video mode.")
def _create_full_blur_video_stream(self, output_path, nsfw_percentage):
source = open_video_capture(self.video_path)
if not source.isOpened():
print(f"Could not reopen video for full blur pass: {self.video_path}")
return False
codec_preference = args.codec if args and hasattr(args, 'codec') else "mp4v"
total_frames = int(source.get(cv2.CAP_PROP_FRAME_COUNT))
out = None
try:
with tqdm(total=total_frames if total_frames > 0 else None, desc="Applying Full Video Blur", unit="frames", ncols=100, mininterval=0.5) as pbar:
while True:
ret, frame = source.read()
if not ret:
break
if out is None:
height, width = frame.shape[:2]
out = create_safe_video_writer(output_path, width, height, self.original_fps, codec_preference)
if not out.isOpened():
print("Failed to create blurred video writer. Continuing with regular output.")
return False
blurred_frame = frame.copy()
self.censor_frame(
blurred_frame,
[],
None,
nsfw_percentage=nsfw_percentage,
force_full_blur=True,
save_frame=False,
)
out.write(blurred_frame)
pbar.update(1)
finally:
if out is not None:
out.release()
source.release()
return True
def _render_boxed_frame(self, frame, detections, include_blur=False):
boxed_frame = frame.copy()
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = CONFIG['FONT_SCALE']
font_thickness = CONFIG['FONT_THICKNESS']
height, width = frame.shape[:2]
for detection in detections:
x, y, w, h = detection["box"]
label = detection["class"]
is_censorable = detection_is_censorable(detection)
label_text = label if not is_censorable else "Unsafe, " + label
box_color = CONFIG['BOX_COLOR_EXPOSED'] if is_censorable else CONFIG['BOX_COLOR_NORMAL']
text_color = CONFIG['TEXT_COLOR_EXPOSED'] if is_censorable else CONFIG['TEXT_COLOR_NORMAL']
blur_kernel = CONFIG['BLUR_STRENGTH_HIGH'] if is_censorable else CONFIG['BLUR_STRENGTH_NORMAL']
x1 = max(0, x)
y1 = max(0, y)
x2 = min(width, x + w)
y2 = min(height, y + h)
if x2 <= x1 or y2 <= y1:
continue
if include_blur and is_censorable and self.should_apply_blur(label):
self.apply_region_censor(boxed_frame, x, y, w, h, blur_kernel)
cv2.rectangle(boxed_frame, (x1, y1), (x2, y2), box_color, 2)
cv2.putText(boxed_frame, label_text, (x1, max(0, y1 - 5)), font, font_scale, text_color, font_thickness, cv2.LINE_AA)
return boxed_frame
def _process_boxes_video_stream(self, include_blur=False):
codec_preference = args.codec if args and hasattr(args, 'codec') else "mp4v"
boxes_filename = f"{self.input_filename}{CONFIG['OUTPUT_VIDEO_BOXES_SUFFIX']}"
video_output_path = os.path.join(self.video_output_folder, boxes_filename)
total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
stats = self._empty_video_stats()
events = []
frame_count = 0
out = None
width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
try:
with tqdm(total=total_frames if total_frames > 0 else None, desc="Generating Video with Boxes", unit="frames", ncols=100, mininterval=0.5) as pbar:
while True:
ret, frame = self.cap.read()
if not ret:
break
frame_count += 1
if out is None:
height, width = frame.shape[:2]
out = create_safe_video_writer(video_output_path, width, height, self.original_fps, codec_preference)
if not out.isOpened():
print("Failed to create video writer. Check your codec installation.")
return
detections = self.detect_frame(frame)
self._update_video_stats(stats, detections)
self._record_detection_events(events, detections, frame_count)
out.write(self._render_boxed_frame(frame, detections, include_blur=include_blur))
pbar.update(1)
finally:
if out is not None:
out.release()
self.cap.release()
if frame_count == 0:
print("No frames were read from the input video.")
return
if args and hasattr(args, 'with_audio') and args.with_audio and os.path.exists(self.video_path):
boxes_audio_filename = f"{self.input_filename}{CONFIG['OUTPUT_VIDEO_BOXES_AUDIO_SUFFIX']}"
output_with_audio = os.path.join(self.video_output_folder, boxes_audio_filename)
success = self.add_audio_to_video(video_output_path, self.video_path, output_with_audio)
if success:
print(f"\nVideo with boxes and audio saved at: {output_with_audio}")
else:
print(f"\nFailed to add audio. Video with boxes saved at: {video_output_path}")
else:
print(f"\nVideo with boxes saved at: {video_output_path}")