vlordier commited on
Commit
db65255
·
verified ·
1 Parent(s): 5259419

Upload hf_job_nsfw.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hf_job_nsfw.py +121 -41
hf_job_nsfw.py CHANGED
@@ -1,7 +1,8 @@
1
  #!/usr/bin/env python3
2
  """
3
- NSFW Classification Job - Process images with EraX YOLO
4
- Outputs: Per-image NSFW detections with bboxes and confidence scores
 
5
  """
6
  import argparse
7
  import os
@@ -22,34 +23,91 @@ logger = logging.getLogger(__name__)
22
 
23
  import numpy as np
24
  import torch
25
- from datasets import load_dataset, Dataset as HFDataset, Features, Value, Sequence
26
  from PIL import Image
27
  import json
28
  from huggingface_hub import snapshot_download
29
  from ultralytics import YOLO
30
 
31
 
32
- def process_batch(batch):
33
- """Process batch of images with NSFW detection"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  images = batch['image']
35
  image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))])
36
 
37
  results_list = []
38
 
39
- # Convert all images to numpy arrays
40
  crops = []
41
- for image_pil in images:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  image_rgb = np.array(image_pil.convert('RGB'))
43
- crops.append(image_rgb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # Batch inference
46
  if crops:
47
  try:
48
  yolo_results = model(crops, conf=0.2, iou=0.3, verbose=False)
49
 
50
- for idx, result in enumerate(yolo_results):
51
- image_id = Path(image_paths[idx]).stem if image_paths[idx] else f'img_{idx:06d}'
52
- img_width, img_height = images[idx].size
53
 
54
  detections = []
55
  if result.boxes:
@@ -59,38 +117,53 @@ def process_batch(batch):
59
  class_names = ['anus', 'make_love', 'nipple', 'penis', 'vagina']
60
  class_name = class_names[class_id] if class_id < len(class_names) else f'class_{class_id}'
61
 
62
- x1, y1, x2, y2 = box.xyxy[0].tolist()
 
 
 
 
 
63
 
64
  detections.append({
65
  'class': class_name,
66
  'confidence': confidence,
67
- 'bbox': [x1, y1, x2, y2]
68
  })
69
 
70
  if not detections:
71
- detections = [{'class': 'safe', 'confidence': 1.0, 'bbox': [0, 0, img_width, img_height]}]
72
 
73
- results_list.append({
74
- 'image_id': image_id,
75
- 'detections': detections,
76
- 'num_detections': len(detections)
77
- })
78
  except Exception as e:
79
  logger.error(f"NSFW batch failed: {e}")
80
- # Fallback: mark all as safe
81
- for idx, image_path in enumerate(image_paths):
82
- image_id = Path(image_path).stem if image_path else f'img_{idx:06d}'
83
- img_width, img_height = images[idx].size
84
- results_list.append({
85
- 'image_id': image_id,
86
- 'detections': [{'class': 'safe', 'confidence': 1.0, 'bbox': [0, 0, img_width, img_height]}],
87
- 'num_detections': 1
88
- })
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  return {
91
  'image_id': [r['image_id'] for r in results_list],
92
- 'detections_json': [json.dumps(r['detections']) for r in results_list],
93
- 'num_detections': [r['num_detections'] for r in results_list]
94
  }
95
 
96
 
@@ -98,14 +171,15 @@ def main():
98
  global model
99
 
100
  logger.info("="*60)
101
- logger.info("NSFW Classification with EraX YOLO")
102
  logger.info("="*60)
103
 
104
  ap = argparse.ArgumentParser()
105
- ap.add_argument('--input-dataset', type=str, required=True)
 
106
  ap.add_argument('--output-dataset', type=str, required=True)
107
  ap.add_argument('--split', type=str, default='train')
108
- ap.add_argument('--batch-size', type=int, default=8)
109
  ap.add_argument('--shard-index', type=int, default=0)
110
  ap.add_argument('--num-shards', type=int, default=1)
111
  args = ap.parse_args()
@@ -123,19 +197,27 @@ def main():
123
  model = YOLO('erax_nsfw_yolo11m.pt')
124
  logger.info("✓ Model loaded")
125
 
126
- # Load dataset
127
- logger.info(f"Loading dataset {args.input_dataset}...")
 
 
 
 
128
  ds = load_dataset(args.input_dataset, split=args.split, streaming=True)
129
 
130
  if args.num_shards > 1:
131
  ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
 
132
  logger.info(f"Using shard {args.shard_index+1}/{args.num_shards}")
133
 
134
  # Process with batching
135
  logger.info(f"Processing with batch_size={args.batch_size}")
136
 
 
 
 
137
  processed_ds = ds.map(
138
- process_batch,
139
  batched=True,
140
  batch_size=args.batch_size,
141
  remove_columns=ds.column_names
@@ -154,14 +236,12 @@ def main():
154
  # Create output dataset
155
  features = Features({
156
  'image_id': Value('string'),
157
- 'detections_json': Value('string'),
158
- 'num_detections': Value('int32')
159
  })
160
 
161
  output_ds = HFDataset.from_dict({
162
  'image_id': [r['image_id'] for r in results],
163
- 'detections_json': [r['detections_json'] for r in results],
164
- 'num_detections': [r['num_detections'] for r in results]
165
  }, features=features)
166
 
167
  # Upload
 
1
  #!/usr/bin/env python3
2
  """
3
+ NSFW Classification Job - Process human crops from SAM3D bboxes with EraX YOLO
4
+ Requires: SAM 3D Body outputs for human bboxes
5
+ Outputs: Per-human NSFW detections with bboxes and confidence scores
6
  """
7
  import argparse
8
  import os
 
23
 
24
  import numpy as np
25
  import torch
26
+ from datasets import load_dataset, Dataset as HFDataset, Features, Value
27
  from PIL import Image
28
  import json
29
  from huggingface_hub import snapshot_download
30
  from ultralytics import YOLO
31
 
32
 
33
+ def make_square_bbox_with_padding(bbox, img_width, img_height, padding=0.1):
34
+ """Convert bbox to square with padding"""
35
+ x1, y1, x2, y2 = bbox
36
+ w = x2 - x1
37
+ h = y2 - y1
38
+
39
+ # Make square
40
+ size = max(w, h)
41
+ cx = (x1 + x2) / 2
42
+ cy = (y1 + y2) / 2
43
+
44
+ # Add padding
45
+ size = size * (1 + padding)
46
+
47
+ # Get square bbox
48
+ x1_sq = max(0, cx - size / 2)
49
+ y1_sq = max(0, cy - size / 2)
50
+ x2_sq = min(img_width, cx + size / 2)
51
+ y2_sq = min(img_height, cy + size / 2)
52
+
53
+ return [x1_sq, y1_sq, x2_sq, y2_sq]
54
+
55
+
56
+ def process_batch(batch, sam3d_dataset):
57
+ """Process batch of images - join with SAM3D results to get human bboxes"""
58
  images = batch['image']
59
  image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))])
60
 
61
  results_list = []
62
 
63
+ # Collect all crops for batch inference
64
  crops = []
65
+ crop_info = [] # (image_idx, human_idx, original_bbox)
66
+
67
+ for idx, image_pil in enumerate(images):
68
+ image_id = Path(image_paths[idx]).stem if image_paths[idx] else f'img_{idx:06d}'
69
+
70
+ # Find corresponding SAM3D data
71
+ sam3d_row = sam3d_dataset.filter(lambda x: x['image_id'] == image_id).take(1)
72
+ sam3d_row = list(sam3d_row)
73
+
74
+ if not sam3d_row or not sam3d_row[0]['sam3d_data']:
75
+ results_list.append({
76
+ 'image_id': image_id,
77
+ 'human_detections': None
78
+ })
79
+ continue
80
+
81
+ humans_data = json.loads(sam3d_row[0]['sam3d_data'])
82
  image_rgb = np.array(image_pil.convert('RGB'))
83
+ img_width, img_height = image_pil.size
84
+
85
+ # Collect crops for each human
86
+ for human_idx, human in enumerate(humans_data):
87
+ bbox = human.get('bbox')
88
+ if bbox is None:
89
+ continue
90
+
91
+ # Make square bbox with padding
92
+ square_bbox = make_square_bbox_with_padding(bbox, img_width, img_height, padding=0.15)
93
+ x1, y1, x2, y2 = map(int, square_bbox)
94
+
95
+ # Crop and resize to standard size for YOLO
96
+ crop = image_rgb[y1:y2, x1:x2]
97
+ if crop.size > 0:
98
+ crops.append(crop)
99
+ crop_info.append((idx, human_idx, square_bbox, bbox))
100
+
101
+ # Batch NSFW inference on all crops
102
+ human_results = {} # {image_idx: {human_idx: detections}}
103
 
 
104
  if crops:
105
  try:
106
  yolo_results = model(crops, conf=0.2, iou=0.3, verbose=False)
107
 
108
+ for crop_idx, result in enumerate(yolo_results):
109
+ img_idx, human_idx, square_bbox, orig_bbox = crop_info[crop_idx]
110
+ x1_sq, y1_sq, x2_sq, y2_sq = square_bbox
111
 
112
  detections = []
113
  if result.boxes:
 
117
  class_names = ['anus', 'make_love', 'nipple', 'penis', 'vagina']
118
  class_name = class_names[class_id] if class_id < len(class_names) else f'class_{class_id}'
119
 
120
+ # Convert crop coordinates to image coordinates
121
+ dx1, dy1, dx2, dy2 = box.xyxy[0].tolist()
122
+ abs_x1 = x1_sq + dx1
123
+ abs_y1 = y1_sq + dy1
124
+ abs_x2 = x1_sq + dx2
125
+ abs_y2 = y1_sq + dy2
126
 
127
  detections.append({
128
  'class': class_name,
129
  'confidence': confidence,
130
+ 'bbox': [abs_x1, abs_y1, abs_x2, abs_y2]
131
  })
132
 
133
  if not detections:
134
+ detections = [{'class': 'safe', 'confidence': 1.0, 'bbox': orig_bbox}]
135
 
136
+ if img_idx not in human_results:
137
+ human_results[img_idx] = {}
138
+ human_results[img_idx][human_idx] = detections
139
+
 
140
  except Exception as e:
141
  logger.error(f"NSFW batch failed: {e}")
142
+
143
+ # Organize results by image
144
+ for idx, image_path in enumerate(image_paths):
145
+ image_id = Path(image_path).stem if image_path else f'img_{idx:06d}'
146
+
147
+ if idx in human_results:
148
+ # Convert dict to list ordered by human_idx
149
+ max_human_idx = max(human_results[idx].keys())
150
+ detections_list = []
151
+ for h_idx in range(max_human_idx + 1):
152
+ detections_list.append(human_results[idx].get(h_idx, [{'class': 'safe', 'confidence': 1.0}]))
153
+
154
+ results_list.append({
155
+ 'image_id': image_id,
156
+ 'human_detections': json.dumps(detections_list)
157
+ })
158
+ else:
159
+ results_list.append({
160
+ 'image_id': image_id,
161
+ 'human_detections': None
162
+ })
163
 
164
  return {
165
  'image_id': [r['image_id'] for r in results_list],
166
+ 'nsfw_detections': [r['human_detections'] for r in results_list]
 
167
  }
168
 
169
 
 
171
  global model
172
 
173
  logger.info("="*60)
174
+ logger.info("NSFW Classification with EraX YOLO (Per-Human)")
175
  logger.info("="*60)
176
 
177
  ap = argparse.ArgumentParser()
178
+ ap.add_argument('--input-dataset', type=str, required=True, help='Original images')
179
+ ap.add_argument('--sam3d-dataset', type=str, required=True, help='SAM3D outputs with bboxes')
180
  ap.add_argument('--output-dataset', type=str, required=True)
181
  ap.add_argument('--split', type=str, default='train')
182
+ ap.add_argument('--batch-size', type=int, default=4)
183
  ap.add_argument('--shard-index', type=int, default=0)
184
  ap.add_argument('--num-shards', type=int, default=1)
185
  args = ap.parse_args()
 
197
  model = YOLO('erax_nsfw_yolo11m.pt')
198
  logger.info("✓ Model loaded")
199
 
200
+ # Load SAM3D results
201
+ logger.info(f"Loading SAM3D results from {args.sam3d_dataset}...")
202
+ sam3d_ds = load_dataset(args.sam3d_dataset, split=args.split, streaming=True)
203
+
204
+ # Load images dataset
205
+ logger.info(f"Loading images from {args.input_dataset}...")
206
  ds = load_dataset(args.input_dataset, split=args.split, streaming=True)
207
 
208
  if args.num_shards > 1:
209
  ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
210
+ sam3d_ds = sam3d_ds.shard(num_shards=args.num_shards, index=args.shard_index)
211
  logger.info(f"Using shard {args.shard_index+1}/{args.num_shards}")
212
 
213
  # Process with batching
214
  logger.info(f"Processing with batch_size={args.batch_size}")
215
 
216
+ from functools import partial
217
+ process_fn = partial(process_batch, sam3d_dataset=sam3d_ds)
218
+
219
  processed_ds = ds.map(
220
+ process_fn,
221
  batched=True,
222
  batch_size=args.batch_size,
223
  remove_columns=ds.column_names
 
236
  # Create output dataset
237
  features = Features({
238
  'image_id': Value('string'),
239
+ 'nsfw_detections': Value('string')
 
240
  })
241
 
242
  output_ds = HFDataset.from_dict({
243
  'image_id': [r['image_id'] for r in results],
244
+ 'nsfw_detections': [r['nsfw_detections'] for r in results]
 
245
  }, features=features)
246
 
247
  # Upload