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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Smart Content Moderation - Frame-Based Video Processing (V2)
|
| 3 |
+
Extract frames → Process → Combine → Output
|
| 4 |
+
FAST FIX - WITHOUT DELETING OLD FILES
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import os
|
| 9 |
+
import logging
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
import tempfile
|
| 13 |
+
import shutil
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from detectors.yolov8_face import YOLOv8Face
|
| 19 |
+
from detectors.text_detector import TextDetector
|
| 20 |
+
from detectors.nsfw_detector import NSFWDetector
|
| 21 |
+
from modules.face_blur_p import FaceBlurrer
|
| 22 |
+
from modules.text_blur_p import TextBlurrer
|
| 23 |
+
from modules.nsfw_blur import NSFWBlurrer
|
| 24 |
+
except ImportError as e:
|
| 25 |
+
logger.warning(f"Import warning: {e}")
|
| 26 |
+
|
| 27 |
+
def validate_blur_strength(blur_strength):
|
| 28 |
+
blur_strength = int(blur_strength)
|
| 29 |
+
return blur_strength if blur_strength % 2 == 1 else blur_strength + 1
|
| 30 |
+
|
| 31 |
+
def get_file_type(file_path):
|
| 32 |
+
"""Detect file type"""
|
| 33 |
+
file_lower = str(file_path).lower()
|
| 34 |
+
if file_lower.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff')):
|
| 35 |
+
return 'image'
|
| 36 |
+
elif file_lower.endswith(('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm', '.m4v')):
|
| 37 |
+
return 'video'
|
| 38 |
+
return 'unknown'
|
| 39 |
+
|
| 40 |
+
def process_frame(frame, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold):
|
| 41 |
+
"""Process single frame with all 3 detections"""
|
| 42 |
+
if frame is None or frame.size == 0:
|
| 43 |
+
return frame
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
try:
|
| 47 |
+
face_blurrer = FaceBlurrer(method="gaussian", blur_strength=blur_strength, adaptive=True)
|
| 48 |
+
frame = face_blurrer.blur_faces(frame, confidence_threshold=confidence)
|
| 49 |
+
except:
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
if blur_text:
|
| 53 |
+
try:
|
| 54 |
+
text_detector = TextDetector(languages=['en'], gpu=False)
|
| 55 |
+
text_regions = text_detector.detect_text(frame, confidence_threshold=0.5)
|
| 56 |
+
if text_regions:
|
| 57 |
+
text_blurrer = TextBlurrer(kernel_size=(blur_strength, blur_strength))
|
| 58 |
+
frame = text_blurrer.blur_hate_text(frame)
|
| 59 |
+
except:
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
if nsfw_blur:
|
| 63 |
+
try:
|
| 64 |
+
nsfw_blurrer = NSFWBlurrer(method=nsfw_blur_type, blood_threshold=blood_threshold)
|
| 65 |
+
frame = nsfw_blurrer.blur_nsfw(frame)
|
| 66 |
+
except:
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
return frame
|
| 70 |
+
except:
|
| 71 |
+
return frame
|
| 72 |
+
|
| 73 |
+
def process_image(input_path, blur_strength=51, confidence=0.5, blur_text=True, nsfw_blur=True, nsfw_blur_type="gaussian", blood_threshold=0.3):
|
| 74 |
+
"""Process image file - handles video routing"""
|
| 75 |
+
|
| 76 |
+
file_lower = str(input_path).lower()
|
| 77 |
+
if file_lower.endswith(('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm', '.m4v')):
|
| 78 |
+
logger.info(f"VIDEO detected - routing to process_video()")
|
| 79 |
+
return process_video(input_path, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold)
|
| 80 |
+
|
| 81 |
+
logger.info(f"Processing IMAGE: {Path(input_path).name}")
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
image = cv2.imread(input_path)
|
| 85 |
+
if image is None:
|
| 86 |
+
raise ValueError(f"Cannot read: {input_path}")
|
| 87 |
+
|
| 88 |
+
processed = process_frame(image, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold)
|
| 89 |
+
|
| 90 |
+
output_dir = Path("social_moderation/data/output/images")
|
| 91 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 92 |
+
|
| 93 |
+
filename = Path(input_path).stem
|
| 94 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 95 |
+
output_path = output_dir / f"{filename}_{timestamp}.jpg"
|
| 96 |
+
|
| 97 |
+
cv2.imwrite(str(output_path), processed)
|
| 98 |
+
logger.info(f"✓ Image saved: {output_path}")
|
| 99 |
+
return str(output_path)
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Image error: {e}")
|
| 103 |
+
raise
|
| 104 |
+
|
| 105 |
+
def process_video(input_path, blur_strength=51, confidence=0.5, blur_text=True, nsfw_blur=True, nsfw_blur_type="gaussian", blood_threshold=0.3):
|
| 106 |
+
"""Process video using frame extraction"""
|
| 107 |
+
logger.info(f"Processing VIDEO: {Path(input_path).name}")
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
logger.info("Step 1: Extracting frames...")
|
| 111 |
+
|
| 112 |
+
cap = cv2.VideoCapture(input_path)
|
| 113 |
+
if not cap.isOpened():
|
| 114 |
+
raise ValueError(f"Cannot open: {input_path}")
|
| 115 |
+
|
| 116 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 117 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 118 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 119 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 120 |
+
|
| 121 |
+
logger.info(f"Video: {width}x{height} @ {fps} FPS, {total_frames} frames")
|
| 122 |
+
|
| 123 |
+
temp_dir = tempfile.mkdtemp(prefix="video_frames_")
|
| 124 |
+
|
| 125 |
+
frame_num = 0
|
| 126 |
+
saved_frames = []
|
| 127 |
+
|
| 128 |
+
while True:
|
| 129 |
+
ret, frame = cap.read()
|
| 130 |
+
if not ret:
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
frame_num += 1
|
| 134 |
+
frame_path = os.path.join(temp_dir, f"frame_{frame_num:06d}.jpg")
|
| 135 |
+
cv2.imwrite(frame_path, frame)
|
| 136 |
+
saved_frames.append(frame_path)
|
| 137 |
+
|
| 138 |
+
if frame_num % 50 == 0:
|
| 139 |
+
logger.info(f"Extracted: {frame_num}/{total_frames}")
|
| 140 |
+
|
| 141 |
+
cap.release()
|
| 142 |
+
logger.info(f"✓ Extracted {len(saved_frames)} frames")
|
| 143 |
+
|
| 144 |
+
logger.info("Step 2: Processing frames...")
|
| 145 |
+
|
| 146 |
+
processed_frames = []
|
| 147 |
+
for i, frame_path in enumerate(saved_frames):
|
| 148 |
+
try:
|
| 149 |
+
frame = cv2.imread(frame_path)
|
| 150 |
+
if frame is None:
|
| 151 |
+
processed_frames.append(frame_path)
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
processed = process_frame(frame, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold)
|
| 155 |
+
|
| 156 |
+
output_frame_path = frame_path.replace("frame_", "processed_")
|
| 157 |
+
cv2.imwrite(output_frame_path, processed)
|
| 158 |
+
processed_frames.append(output_frame_path)
|
| 159 |
+
|
| 160 |
+
if (i + 1) % 50 == 0:
|
| 161 |
+
logger.info(f"Processed: {i + 1}/{len(saved_frames)}")
|
| 162 |
+
except Exception as e:
|
| 163 |
+
logger.warning(f"Frame {i} error: {e}")
|
| 164 |
+
processed_frames.append(frame_path)
|
| 165 |
+
|
| 166 |
+
logger.info(f"✓ Processed {len(processed_frames)} frames")
|
| 167 |
+
|
| 168 |
+
logger.info("Step 3: Combining frames...")
|
| 169 |
+
|
| 170 |
+
output_dir = Path("social_moderation/data/output/videos")
|
| 171 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
|
| 173 |
+
filename = Path(input_path).stem
|
| 174 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 175 |
+
output_path = output_dir / f"{filename}_{timestamp}.mp4"
|
| 176 |
+
|
| 177 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 178 |
+
out = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
|
| 179 |
+
|
| 180 |
+
for i, frame_path in enumerate(processed_frames):
|
| 181 |
+
try:
|
| 182 |
+
frame = cv2.imread(frame_path)
|
| 183 |
+
if frame is not None:
|
| 184 |
+
out.write(frame)
|
| 185 |
+
|
| 186 |
+
if (i + 1) % 50 == 0:
|
| 187 |
+
logger.info(f"Written: {i + 1}/{len(processed_frames)}")
|
| 188 |
+
except:
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
out.release()
|
| 192 |
+
logger.info(f"✓ Video saved: {output_path}")
|
| 193 |
+
|
| 194 |
+
logger.info("Step 4: Cleanup...")
|
| 195 |
+
shutil.rmtree(temp_dir)
|
| 196 |
+
logger.info("✓ Done")
|
| 197 |
+
|
| 198 |
+
return str(output_path)
|
| 199 |
+
|
| 200 |
+
except Exception as e:
|
| 201 |
+
logger.error(f"Video error: {e}")
|
| 202 |
+
raise
|
| 203 |
+
|
| 204 |
+
def process_media_file(input_path, blur_strength=51, confidence=0.5, blur_text=True, nsfw_blur=True, nsfw_blur_type="gaussian", blood_threshold=0.3):
|
| 205 |
+
"""Main entry point"""
|
| 206 |
+
blur_strength = validate_blur_strength(blur_strength)
|
| 207 |
+
file_type = get_file_type(input_path)
|
| 208 |
+
|
| 209 |
+
logger.info(f"Detected: {file_type}")
|
| 210 |
+
|
| 211 |
+
if file_type == 'video':
|
| 212 |
+
return process_video(input_path, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold)
|
| 213 |
+
elif file_type == 'image':
|
| 214 |
+
return process_image(input_path, blur_strength, confidence, blur_text, nsfw_blur, nsfw_blur_type, blood_threshold)
|
| 215 |
+
else:
|
| 216 |
+
raise ValueError(f"Unsupported: {input_path}")
|