File size: 12,744 Bytes
70b0f71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import torch
import os
import warnings
from typing import Dict
from dataclasses import dataclass

warnings.filterwarnings('ignore')

try:
    from ultralytics import YOLO
    from transformers import pipeline
    from PIL import Image
except ImportError as e:
    print(f"Missing dependency: {e}")


@dataclass
class DetectionResult:
    """Simple detection result"""
    nude_count: int = 0
    gun_count: int = 0
    knife_count: int = 0
    fight_count: int = 0
    is_safe: bool = True

    def to_dict(self):
        return {
            'nude': self.nude_count,
            'gun': self.gun_count,
            'knife': self.knife_count,
            'fight': self.fight_count,
            'is_safe': self.is_safe
        }


class SmartSequentialModerator:
    """

    Smart Sequential Pipeline with balanced thresholds:

    1. NSFW Check with BALANCED threshold

    2. Only if NSFW is clean β†’ Check Weapons/Fights

    """

    def __init__(self):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'

        # Models
        self.nsfw_classifier = None
        self.weapon_model = None

        # BALANCED Thresholds
        self.nsfw_threshold = 0.75  # Balanced: not too high, not too low
        self.nsfw_safe_threshold = 0.25  # If below this, definitely safe
        self.gun_threshold = 0.7
        self.knife_threshold = 0.65
        self.fight_threshold = 0.25

        print(f"πŸš€ Smart Sequential Moderator initialized on {self.device}")
        print(f"πŸ“‹ Pipeline: NSFW (0.75) β†’ Weapons/Fights")

        self._setup_models()

    def _setup_models(self):
        """Initialize models"""
        try:
            if torch.cuda.is_available():
                torch.cuda.empty_cache()

            # 1. NSFW Classifier (PRIORITY)
            self._setup_nsfw()

            # 2. Weapon/Fight Model
            self._setup_weapons()

            print("βœ… All models ready!")

        except Exception as e:
            print(f"❌ Setup error: {e}")

    def _setup_nsfw(self):
        """Setup NSFW classifier"""
        try:
            print("πŸ”ž Loading NSFW classifier...")

            device_id = 0 if self.device == 'cuda' else -1

            # Use the NSFW detection model
            self.nsfw_classifier = pipeline(
                "image-classification",
                model="Falconsai/nsfw_image_detection",
                device=device_id
            )
            print("βœ… NSFW classifier loaded")

        except Exception as e:
            print(f"⚠️ NSFW failed: {e}")
            self.nsfw_classifier = None

    def _setup_weapons(self):
        """Setup weapon/fight model"""
        try:
            print("πŸ”« Loading weapon/fight model...")

            # Custom model path
            custom_path = "models/best_ft4.pt"
            if os.path.exists(custom_path):
                self.weapon_model = YOLO(custom_path)
                print(f"βœ… Custom model loaded")

                # Show available classes
                if hasattr(self.weapon_model, 'names'):
                    classes = list(self.weapon_model.names.values())
                    print(f"   Classes: {classes}")
            else:
                # Fallback
                self.weapon_model = YOLO('yolo11n.pt')
                print("βœ… General model loaded")

        except Exception as e:
            print(f"⚠️ Weapon model failed: {e}")
            self.weapon_model = None

    def process_image(self, image) -> DetectionResult:
        """

        STRICT SEQUENTIAL:

        1. NSFW first (balanced threshold)

        2. If NSFW detected β†’ STOP

        3. If clean β†’ check weapons/fights

        """

        result = DetectionResult()

        try:
            # Load image
            if isinstance(image, str):
                image = cv2.imread(image)
                if image is None:
                    return result

            print(f"\n{'=' * 40}")
            print(f"πŸ“Έ Processing: {image.shape}")

            # ========== STAGE 1: NSFW ==========
            print("\nπŸ”ž Stage 1: NSFW Check")

            nsfw_score = self._check_nsfw(image)

            if nsfw_score > self.nsfw_threshold:
                print(f"   🚨 NSFW DETECTED: {nsfw_score:.3f}")
                print(f"   β›” STOPPING - Returning NSFW only")

                result.nude_count = 1
                result.is_safe = False
                return result  # STOP HERE

            elif nsfw_score < self.nsfw_safe_threshold:
                print(f"   βœ… Definitely safe: {nsfw_score:.3f}")
            else:
                print(f"   ⚠️ Borderline safe: {nsfw_score:.3f} - Continuing checks")

            # ========== STAGE 2: WEAPONS/FIGHTS ==========
            print("\nπŸ”« Stage 2: Weapons & Fights")

            if self.weapon_model:
                detections = self._detect_threats(image)
                result.gun_count = detections['guns']
                result.knife_count = detections['knives']
                result.fight_count = detections['fights']

                if detections['total'] > 0:
                    print(f"   Found: G:{detections['guns']} K:{detections['knives']} F:{detections['fights']}")

            # Final safety
            total = result.nude_count + result.gun_count + result.knife_count + result.fight_count
            result.is_safe = (total == 0)

            print(
                f"\nπŸ“Š Result: N:{result.nude_count} G:{result.gun_count} K:{result.knife_count} F:{result.fight_count} Safe:{result.is_safe}")
            print(f"{'=' * 40}\n")

            return result

        except Exception as e:
            print(f"❌ Error: {e}")
            return result

    def _check_nsfw(self, image) -> float:
        """

        Check NSFW with proper scoring

        Returns confidence score (0-1)

        """
        try:
            if not self.nsfw_classifier:
                return 0.0

            # Convert to RGB
            rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(rgb_image)

            # Run classifier
            results = self.nsfw_classifier(pil_image)

            # Get NSFW score
            nsfw_score = 0.0
            for result in results:
                label = result['label'].lower()
                score = result['score']

                # Check for NSFW label
                if 'nsfw' in label or 'unsafe' in label or 'explicit' in label:
                    nsfw_score = max(nsfw_score, score)
                    print(f"   {label}: {score:.3f}")

            return nsfw_score

        except Exception as e:
            print(f"   ⚠️ NSFW error: {e}")
            return 0.0

    def _detect_threats(self, image) -> Dict[str, int]:
        """Detect weapons and fights"""
        counts = {
            'guns': 0,
            'knives': 0,
            'fights': 0,
            'total': 0
        }

        try:
            # Run detection with low base threshold
            results = self.weapon_model(
                image,
                conf=0.4,  # Low base threshold
                device=self.device,
                verbose=False
            )

            for result in results:
                if result.boxes is None:
                    continue

                for box in result.boxes:
                    class_id = int(box.cls[0])
                    confidence = float(box.conf[0])

                    if hasattr(result, 'names'):
                        class_name = result.names[class_id].lower()
                    else:
                        continue

                    # Check each category with proper threshold
                    if self._is_gun(class_name) and confidence > self.gun_threshold:
                        counts['guns'] += 1

                    elif self._is_knife(class_name) and confidence > self.knife_threshold:
                        counts['knives'] += 1

                    elif self._is_fight(class_name) and confidence > self.fight_threshold:
                        counts['fights'] += 1

            counts['total'] = counts['guns'] + counts['knives'] + counts['fights']
            return counts

        except Exception as e:
            print(f"   ⚠️ Detection error: {e}")
            return counts

    def _is_gun(self, name: str) -> bool:
        gun_words = ['gun', 'pistol', 'rifle', 'firearm', 'sΓΊng']
        return any(w in name for w in gun_words)

    def _is_knife(self, name: str) -> bool:
        knife_words = ['knife', 'dao', 'blade', 'sword']
        return any(w in name for w in knife_words)

    def _is_fight(self, name: str) -> bool:
        fight_words = ['fight', 'fighting', 'combat', 'violence']
        return any(w in name for w in fight_words)

    def process_video(self, video_path: str) -> Dict:
        """

        Process video with SMART frame skipping

        Auto-adjusts based on video duration

        """

        total = DetectionResult()

        try:
            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                return total.to_dict()

            # Get video info
            fps = cap.get(cv2.CAP_PROP_FPS)
            total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            duration = total_frames / fps if fps > 0 else 0

            # SMART frame skip based on duration
            if duration <= 10:  # Short video
                frame_skip = 5  # Check every 5th frame
                max_frames = 100
            elif duration <= 30:
                frame_skip = 10  # Check every 10th frame
                max_frames = 150
            elif duration <= 60:
                frame_skip = 15
                max_frames = 200
            else:  # Long video
                frame_skip = 30
                max_frames = 300

            print(f"\nπŸ“Ή Video: {duration:.1f}s, {total_frames} frames")
            print(f"   Auto settings: skip={frame_skip}, max={max_frames}")

            frame_count = 0
            processed = 0
            nsfw_strikes = 0  # Count NSFW detections

            while True:
                ret, frame = cap.read()
                if not ret:
                    break

                frame_count += 1

                # Skip frames
                if frame_count % frame_skip != 0:
                    continue

                # Max frame limit
                if processed >= max_frames:
                    break

                processed += 1

                # Process frame
                result = self.process_image(frame)

                # Accumulate
                total.nude_count += result.nude_count
                total.gun_count += result.gun_count
                total.knife_count += result.knife_count
                total.fight_count += result.fight_count

                # Early stop on multiple NSFW
                if result.nude_count > 0:
                    nsfw_strikes += 1
                    if nsfw_strikes >= 3:  # Stop after 3 NSFW frames
                        print(f"β›” Early stop: {nsfw_strikes} NSFW frames")
                        break

                # Progress
                if processed % 50 == 0:
                    print(f"   Processed {processed} frames...")

            cap.release()

            # Final safety
            total_threats = total.nude_count + total.gun_count + total.knife_count + total.fight_count
            total.is_safe = (total_threats == 0)

            print(f"\nπŸ“Š Video complete: {processed} frames analyzed")
            print(f"   Total: N:{total.nude_count} G:{total.gun_count} K:{total.knife_count} F:{total.fight_count}")

            return total.to_dict()

        except Exception as e:
            print(f"❌ Video error: {e}")
            return total.to_dict()


def main():
    """Test the moderator"""

    moderator = SmartSequentialModerator()

    print("\n" + "=" * 50)
    print("🎯 SMART SEQUENTIAL MODERATOR")
    print("=" * 50)
    print("β€’ Balanced NSFW threshold: 0.75")
    print("β€’ Auto frame skipping for videos")
    print("β€’ Simple output: counts + boolean")
    print("=" * 50)

    # Test
    test_image = "test.jpg"
    if os.path.exists(test_image):
        result = moderator.process_image(test_image)
        print(f"\nResult: {result.to_dict()}")


if __name__ == "__main__":
    main()