risunobushi commited on
Commit
aaa0ade
·
1 Parent(s): abce027

Implement NSFW filter using Hugging Face Transformers

Browse files

- Add NSFW content detection using Falconsai/nsfw_image_detection model
- Filter only product images for inappropriate content (porn/explicit)
- Add transformers and torch dependencies to requirements.txt
- Implement fail-safe design with comprehensive logging
- Block content with >70% confidence threshold
- Provide clear error messages to users

Files changed (2) hide show
  1. app.py +51 -0
  2. requirements.txt +3 -1
app.py CHANGED
@@ -18,6 +18,7 @@ import threading
18
 
19
  import gradio as gr
20
  from supabase import create_client, Client
 
21
 
22
  # -----------------------------------------------------------------------------
23
  # Environment & Supabase setup
@@ -76,6 +77,20 @@ except Exception as exc: # noqa: BLE001
76
  print(f"[startup] Bucket check/create raised {exc!r}. Continuing…")
77
 
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  # -----------------------------------------------------------------------------
80
  # Rate Limiting
81
  # -----------------------------------------------------------------------------
@@ -273,6 +288,37 @@ def _public_storage_url(path: str) -> str:
273
  return f"{SUPABASE_URL}/storage/v1/object/public/{path.lstrip('/')}"
274
 
275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  # -----------------------------------------------------------------------------
277
  # Main generate function
278
  # -----------------------------------------------------------------------------
@@ -292,6 +338,11 @@ def generate(
292
  if not check_rate_limit(client_ip):
293
  raise gr.Error("Rate limit exceeded. Please try again later (30 requests per hour limit).")
294
 
 
 
 
 
 
295
  # 1. Persist both images to Supabase storage
296
  job_id = str(uuid.uuid4())
297
  folder = f"user_uploads/gradio/{job_id}"
 
18
 
19
  import gradio as gr
20
  from supabase import create_client, Client
21
+ from transformers import pipeline
22
 
23
  # -----------------------------------------------------------------------------
24
  # Environment & Supabase setup
 
77
  print(f"[startup] Bucket check/create raised {exc!r}. Continuing…")
78
 
79
 
80
+ # -----------------------------------------------------------------------------
81
+ # NSFW Filter Setup
82
+ # -----------------------------------------------------------------------------
83
+
84
+ # Initialize NSFW classifier at startup
85
+ print("[startup] Loading NSFW classifier...")
86
+ try:
87
+ nsfw_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
88
+ print("[startup] NSFW classifier loaded successfully")
89
+ except Exception as exc:
90
+ print(f"[startup] Failed to load NSFW classifier: {exc!r}")
91
+ nsfw_classifier = None
92
+
93
+
94
  # -----------------------------------------------------------------------------
95
  # Rate Limiting
96
  # -----------------------------------------------------------------------------
 
288
  return f"{SUPABASE_URL}/storage/v1/object/public/{path.lstrip('/')}"
289
 
290
 
291
+ def is_nsfw_content(img: Image.Image) -> bool:
292
+ """Check if image contains NSFW content using Hugging Face transformer."""
293
+ if nsfw_classifier is None:
294
+ print("[NSFW] Classifier not available, skipping check")
295
+ return False
296
+
297
+ try:
298
+ # Run classification
299
+ results = nsfw_classifier(img)
300
+ print(f"[NSFW] Classification results: {results}")
301
+
302
+ # Check for explicit content
303
+ for result in results:
304
+ label = result['label'].lower()
305
+ score = result['score']
306
+ print(f"[NSFW] Label: {label}, Score: {score:.3f}")
307
+
308
+ # Flag as NSFW if "porn" or explicit content detected with high confidence
309
+ if label in ['porn', 'nsfw', 'explicit'] and score > 0.7:
310
+ print(f"[NSFW] BLOCKED - {label} detected with {score:.3f} confidence")
311
+ return True
312
+
313
+ print("[NSFW] Content approved")
314
+ return False
315
+
316
+ except Exception as exc:
317
+ print(f"[NSFW] Error during classification: {exc!r}")
318
+ # Fail open - don't block if classifier has issues
319
+ return False
320
+
321
+
322
  # -----------------------------------------------------------------------------
323
  # Main generate function
324
  # -----------------------------------------------------------------------------
 
338
  if not check_rate_limit(client_ip):
339
  raise gr.Error("Rate limit exceeded. Please try again later (30 requests per hour limit).")
340
 
341
+ # NSFW content filtering - only check product image
342
+ print(f"[NSFW] Checking product image for inappropriate content...")
343
+ if is_nsfw_content(garment_img):
344
+ raise gr.Error("Product image contains inappropriate content. Please use a different image.")
345
+
346
  # 1. Persist both images to Supabase storage
347
  job_id = str(uuid.uuid4())
348
  folder = f"user_uploads/gradio/{job_id}"
requirements.txt CHANGED
@@ -2,4 +2,6 @@ gradio>=4.29.0
2
  supabase>=2.0.0
3
  python-dotenv>=1.0.0
4
  requests>=2.31.0
5
- Pillow
 
 
 
2
  supabase>=2.0.0
3
  python-dotenv>=1.0.0
4
  requests>=2.31.0
5
+ Pillow
6
+ transformers>=4.30.0
7
+ torch>=2.0.0