File size: 34,990 Bytes
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43f4332
cf992fe
 
2adf024
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf992fe
c144739
cf992fe
c144739
 
cf992fe
 
 
c144739
 
 
 
 
cf992fe
 
 
 
c144739
cf992fe
 
 
 
c144739
cf992fe
 
 
 
 
 
 
 
 
 
c144739
cf992fe
 
 
 
c144739
 
 
 
cf992fe
 
 
 
 
 
 
 
 
 
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf992fe
c144739
 
 
 
cf992fe
c144739
 
 
 
 
 
 
 
 
 
cf992fe
 
 
 
 
 
 
c144739
cf992fe
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43f4332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793169b
cf992fe
 
43f4332
 
 
 
793169b
43f4332
cf992fe
 
 
 
43f4332
cf992fe
 
43f4332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf992fe
43f4332
 
 
 
 
 
cf992fe
43f4332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793169b
 
 
 
 
43f4332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
793169b
 
 
 
 
 
 
43f4332
 
 
c144739
43f4332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c144739
43f4332
c144739
 
43f4332
 
 
c144739
43f4332
c144739
43f4332
c144739
43f4332
c144739
43f4332
c144739
43f4332
 
 
 
c144739
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
HuggingFace Jobs script: Collect teacher outputs with metadata tracking.

Saves for each image:
- Full SAM 3D Body outputs (.npz)
- Metadata: num_humans, image_width, image_height, processing_time
"""
import argparse
import os
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
import logging
import sys

# Configure logging to stdout (so HF Jobs can capture it)
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    stream=sys.stdout,
    force=True
)
logger = logging.getLogger(__name__)

# Also flush stdout immediately
sys.stdout.reconfigure(line_buffering=True) if hasattr(sys.stdout, 'reconfigure') else None

import numpy as np
import torch
from datasets import load_dataset, Dataset as HFDataset, Features, Value
from PIL import Image
import cv2
from typing import List, Dict, Optional
import time
import functools
import json
from collections import defaultdict
import subprocess

# SAM 3D Body imports
import sys
sam_repo = Path(__file__).parent.parent / "sam-3d-body"
if str(sam_repo) not in sys.path:
    sys.path.insert(0, str(sam_repo))
from sam_3d_body import load_sam_3d_body, SAM3DBodyEstimator

# Set environment variable
os.environ['PYOPENGL_PLATFORM'] = 'osmesa'


class GazeEstimator:
    """Gaze estimation using L2CS-Net"""
    
    def __init__(self, device='cuda'):
        self.device = device
        logger.info("Installing L2CS-Net...")
        # Install L2CS-Net package
        try:
            subprocess.run(
                ['pip', 'install', '-q', 'git+https://github.com/edavalosanaya/L2CS-Net.git@main'],
                check=True,
                capture_output=True
            )
            logger.info("✓ L2CS-Net installed")
        except Exception as e:
            print(f"Warning: L2CS-Net installation failed: {e}")
        
        print("Loading L2CS-Net gaze estimator...")
        try:
            from l2cs import Pipeline
            # Use Gaze360 pretrained weights (better for unconstrained images)
            self.pipeline = Pipeline(
                weights='L2CSNet_gaze360.pkl',  # Will download automatically
                arch='ResNet50',
                device=device
            )
            self.enabled = True
            print("✓ L2CS-Net gaze estimator loaded")
        except Exception as e:
            print(f"Warning: Could not load L2CS-Net: {e}")
            print("Gaze estimation will be disabled")
            self.enabled = False
    
    def estimate_gaze(self, bbox, detections=None, image_bgr=None):
        """
        Estimate gaze direction for a bbox using optional precomputed detections.
        
        Args:
            bbox: [x1, y1, x2, y2]
            detections: cached L2CS pipeline outputs for the full image
            image_bgr: optional BGR image (used only when detections missing)
        """
        if not self.enabled:
            return None
        
        try:
            if detections is None and image_bgr is not None:
                detections = self.pipeline.step(image_bgr)
            if not detections:
                return None
            
            x1, y1, x2, y2 = bbox
            bbox_center = np.array([(x1 + x2) / 2, (y1 + y2) / 2])
            best_result = None
            min_dist = float('inf')
            
            for result in detections:
                face_bbox = result.get('bbox')
                if face_bbox is None:
                    continue
                fx1, fy1, fx2, fy2 = face_bbox
                face_center = np.array([(fx1 + fx2) / 2, (fy1 + fy2) / 2])
                dist = np.linalg.norm(bbox_center - face_center)
                if dist < min_dist:
                    min_dist = dist
                    best_result = result
            
            if best_result is not None:
                pitch = float(best_result.get('pitch', 0))
                yaw = float(best_result.get('yaw', 0))
                return {'pitch': pitch, 'yaw': yaw}
            return None
        except Exception as e:
            print(f"Gaze estimation error: {e}")
            return None
    
    def run_pipeline(self, image_bgr):
        """Run L2CS pipeline once per image and reuse detections."""
        if not self.enabled:
            return None
        try:
            return self.pipeline.step(image_bgr)
        except Exception as e:
            print(f"Warning: L2CS pipeline failed: {e}")
            return None


class FaceEmbedder:
    """Face embedding extraction using InsightFace ArcFace (ResNet100-IR)"""
    
    def __init__(self, device='cuda'):
        self.device = device
        print("Installing InsightFace...")
        # Install InsightFace package
        try:
            subprocess.run(
                ['pip', 'install', '-q', 'insightface', 'onnxruntime-gpu' if device.type == 'cuda' else 'onnxruntime'],
                check=True,
                capture_output=True
            )
            print("✓ InsightFace installed")
        except Exception as e:
            print(f"Warning: InsightFace installation failed: {e}")
        
        print("Loading InsightFace ArcFace (ResNet100-IR)...")
        try:
            import insightface
            from insightface.app import FaceAnalysis
            
            # Initialize with ArcFace ResNet100 model
            # det_size=(640, 640) for better detection
            self.app = FaceAnalysis(
                name='buffalo_l',  # Uses ResNet100 backbone
                providers=['CUDAExecutionProvider'] if device.type == 'cuda' else ['CPUExecutionProvider']
            )
            self.app.prepare(ctx_id=0 if device.type == 'cuda' else -1, det_size=(640, 640))
            self.enabled = True
            print("✓ InsightFace ArcFace loaded (ResNet100-IR)")
            print("  Model: buffalo_l (ResNet100 + ArcFace head)")
            print("  Robust to: occlusion, lighting, blur, pose variations, aging")
        except Exception as e:
            print(f"Warning: Could not load InsightFace: {e}")
            print("Face embeddings will be disabled")
            self.enabled = False
    
    def extract_embedding(self, image, bbox=None, keypoints_2d=None):
        """
        Extract 512-dimensional ArcFace embedding from face.
        
        Args:
            image: PIL Image or BGR numpy array
            bbox: [x1, y1, x2, y2] in pixel coordinates (optional, for cropping)
            keypoints_2d: Face keypoints for alignment (optional)
            
        Returns:
            dict with 'embedding' (512-dim vector), 'det_score' (confidence), or None if failed
        """
        if not self.enabled:
            return None
        
        try:
            # Convert to numpy BGR (InsightFace expects BGR)
            if isinstance(image, Image.Image):
                image_np = np.array(image)
                if image_np.shape[2] == 3:
                    image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
                else:
                    image_bgr = image_np
            else:
                image_bgr = image
            
            # Optionally crop to bbox region for efficiency
            if bbox is not None:
                x1, y1, x2, y2 = map(int, bbox)
                # Add padding for better detection
                pad = 20
                h, w = image_bgr.shape[:2]
                x1 = max(0, x1 - pad)
                y1 = max(0, y1 - pad)
                x2 = min(w, x2 + pad)
                y2 = min(h, y2 + pad)
                image_bgr = image_bgr[y1:y2, x1:x2]
            
            # Detect and extract faces
            faces = self.app.get(image_bgr)
            
            if len(faces) == 0:
                return None
            
            # Use the largest/most confident face
            face = max(faces, key=lambda x: x.det_score)
            
            # Extract embedding (512-dim ArcFace feature)
            embedding = face.embedding  # numpy array, shape (512,)
            det_score = float(face.det_score)
            
            # Normalize embedding (L2 norm = 1)
            embedding_norm = embedding / np.linalg.norm(embedding)
            
            return {
                'embedding': embedding_norm.astype(np.float32).tolist(),
                'det_score': det_score,
                'embedding_dim': len(embedding)
            }
            
        except Exception as e:
            print(f"Face embedding extraction error: {e}")
            return None


class NSFWClassifier:
    """NSFW classification using EraX-NSFW-V1.0 YOLO model"""
    
    def __init__(self, device='cuda'):
        self.device = device
        print("Loading EraX-NSFW YOLO model...")
        try:
            # Download the model if not already downloaded
            from huggingface_hub import snapshot_download
            snapshot_download(repo_id="erax-ai/EraX-NSFW-V1.0", local_dir="./", force_download=False)
            
            from ultralytics import YOLO
            # Use the m model for better accuracy
            self.model = YOLO('erax_nsfw_yolo11m.pt')
            self.enabled = True
            print("✓ EraX-NSFW classifier loaded (YOLO11m)")
        except Exception as e:
            print(f"Warning: Could not load EraX-NSFW: {e}")
            print("NSFW classification will be disabled")
            self.enabled = False
    
    def classify_crop(self, image_pil, bbox):
        """
        Classify NSFW content in a crop defined by bbox.
        
        Args:
            image_pil: PIL Image
            bbox: [x1, y1, x2, y2] in pixel coordinates
            
        Returns:
            dict with class scores, or None if failed
        """
        if not self.enabled:
            return None
        
        try:
            # Convert bbox to ultralytics format [x1, y1, x2, y2]
            x1, y1, x2, y2 = bbox
            
            # Crop the image
            crop = image_pil.crop((x1, y1, x2, y2))
            
            # Convert PIL to numpy for ultralytics
            crop_np = np.array(crop)
            
            # Run inference with confidence and IoU thresholds
            results = self.model(crop_np, conf=0.2, iou=0.3, verbose=False)
            
            detections = []
            if len(results) > 0 and len(results[0].boxes) > 0:
                boxes = results[0].boxes
                for box in boxes:
                    class_id = int(box.cls.item())
                    confidence = box.conf.item()
                    
                    # Model classes: ['anus', 'make_love', 'nipple', 'penis', 'vagina']
                    class_names = ['anus', 'make_love', 'nipple', 'penis', 'vagina']
                    class_name = class_names[class_id] if class_id < len(class_names) else f'class_{class_id}'
                    
                    # Get bbox relative to crop and convert to absolute coordinates
                    dx1, dy1, dx2, dy2 = box.xyxy[0].tolist()
                    abs_bbox = [x1 + dx1, y1 + dy1, x1 + dx2, y1 + dy2]
                    
                    detections.append({
                        'class': class_name,
                        'confidence': confidence,
                        'bbox': abs_bbox
                    })
            
            if detections:
                return detections
            else:
                # No detections - consider safe
                return [{'class': 'safe', 'confidence': 1.0, 'bbox': [x1, y1, x2, y2]}]
                
        except Exception as e:
            print(f"! NSFW classification failed: {e}")
            return None


def compute_face_orientation(vertices, keypoints_3d):
    """
    Compute face orientation vector from 3D mesh vertices and keypoints.
    Uses nose→head_top vector as face direction.
    
    Args:
        vertices: (N, 3) array of 3D vertices
        keypoints_3d: (70, 3) array of 3D keypoints (MHR70 format)
        
    Returns:
        (3,) normalized face orientation vector [x, y, z] or None
    """
    if vertices is None or keypoints_3d is None:
        return None
    
    try:
        # MHR70 keypoint indices (from sam-3d-body/sam_3d_body/metadata/mhr70.py)
        # 0: nose, 1: left-eye, 2: right-eye
        # Check if face keypoints are valid (not all zeros)
        nose_3d = keypoints_3d[0]
        left_eye_3d = keypoints_3d[1]
        right_eye_3d = keypoints_3d[2]
        
        # Verify face keypoints are valid (not at origin)
        if (np.linalg.norm(nose_3d) < 1e-6 or 
            np.linalg.norm(left_eye_3d) < 1e-6 or 
            np.linalg.norm(right_eye_3d) < 1e-6):
            return None  # Face keypoints not detected
        
        # Find topmost vertex as head top (highest Y coordinate in body frame)
        head_top_idx = np.argmax(vertices[:, 1])  # Y is up in SMPL convention
        head_top_3d = vertices[head_top_idx]
        
        # Face orientation = nose → head_top (points upward/forward from face)
        face_orientation = head_top_3d - nose_3d
        
        # Normalize
        norm = np.linalg.norm(face_orientation)
        if norm > 1e-6:
            face_orientation = face_orientation / norm
            return face_orientation.astype(np.float32)
        
        return None
        
    except Exception as e:
        print(f"Face orientation computation failed: {e}")
        return None


def compute_bbox_from_keypoints(keypoints_2d, indices):
    """
    Compute bounding box from a set of 2D keypoints.
    
    Args:
        keypoints_2d: (70, 2) array of 2D keypoints
        indices: list of keypoint indices to include
        
    Returns:
        [x1, y1, x2, y2] or None if no valid keypoints
    """
    if keypoints_2d is None or len(keypoints_2d) < max(indices) + 1:
        return None
    
    valid_points = []
    for idx in indices:
        kp = keypoints_2d[idx]
        if kp[0] >= 0 and kp[1] >= 0:  # Check if keypoint is valid (not -1, -1)
            valid_points.append(kp)
    
    if len(valid_points) < 2:  # Need at least 2 points for a bbox
        return None
    
    points = np.array(valid_points)
    x1, y1 = points.min(axis=0)
    x2, y2 = points.max(axis=0)
    
    # Add some padding (10% of bbox size)
    width = x2 - x1
    height = y2 - y1
    padding_x = width * 0.1
    padding_y = height * 0.1
    
    x1 = max(0, x1 - padding_x)
    y1 = max(0, y1 - padding_y)
    x2 = x2 + padding_x
    y2 = y2 + padding_y
    
    return [float(x1), float(y1), float(x2), float(y2)]


def process_batch(batch, teacher, nsfw_classifier, gaze_estimator, face_embedder, faces, out_dir):
    """
    Process a batch of samples using dataset.map() with batched NSFW inference
    
    Args:
        batch: dict with 'image' list and optional 'image_path' list
        ... (other args)
        
    Returns:
        dict with 'metadata' list
    """
    images = batch['image']
    image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))])
    
    # First pass: process images and collect humans data (without NSFW)
    humans_data_list = []
    outputs_list = []
    image_rgbs = []  # cache RGB numpy arrays for later crops
    image_bgrs = []  # cache BGR arrays for gaze/face embedding
    gaze_detections = []
    
    for img_idx, image_pil in enumerate(images):
        img_width, img_height = image_pil.size
        image_rgb = np.array(image_pil.convert('RGB'))
        image_rgbs.append(image_rgb)
        image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
        image_bgrs.append(image_bgr)
        
        detections = gaze_estimator.run_pipeline(image_bgr) if gaze_estimator is not None else None
        gaze_detections.append(detections)
        
        with torch.inference_mode():
            outputs = teacher.process_one_image(image_bgr)
        outputs_list.append(outputs)
        
        if not outputs:
            humans_data_list.append([])
            continue
        
        humans_data = []
        for human_idx, pred in enumerate(outputs):
            vertices = pred.get('pred_vertices')
            cam_t = pred.get('pred_cam_t')
            focal_length = pred.get('focal_length')
            kpts2d = pred.get('pred_keypoints_2d')
            kpts3d = pred.get('pred_keypoints_3d')
            bbox = pred.get('bbox', None)
            
            # Check face
            has_face = False
            if kpts2d is not None and kpts3d is not None and len(kpts2d) >= 3 and len(kpts3d) >= 3:
                nose_2d = kpts2d[0]
                left_eye_2d = kpts2d[1]
                right_eye_2d = kpts2d[2]
                nose_3d = kpts3d[0]
                left_eye_3d = kpts3d[1]
                right_eye_3d = kpts3d[2]
                
                keypoints_valid_3d = (np.linalg.norm(nose_3d) > 1e-6 and 
                                     np.linalg.norm(left_eye_3d) > 1e-6 and 
                                     np.linalg.norm(right_eye_3d) > 1e-6)
                
                keypoints_in_image = True
                if keypoints_valid_3d:
                    for kp in [nose_2d, left_eye_2d, right_eye_2d]:
                        if (kp[0] < 0 or kp[0] >= img_width or 
                            kp[1] < 0 or kp[1] >= img_height):
                            keypoints_in_image = False
                            break
                
                has_face = keypoints_valid_3d and keypoints_in_image
            
            face_orientation = None
            if has_face:
                face_orientation = compute_face_orientation(vertices, kpts3d)
            
            gaze_direction = None
            if has_face and bbox is not None and gaze_estimator is not None:
                try:
                    gaze_direction = gaze_estimator.estimate_gaze(bbox, detections=gaze_detections[img_idx])
                except Exception as e:
                    gaze_direction = None
            
            face_embedding = None
            if has_face and bbox is not None and face_embedder is not None:
                try:
                    face_embedding = face_embedder.extract_embedding(image_bgrs[img_idx], bbox, kpts2d)
                except Exception as e:
                    face_embedding = None
            
            # Compute bboxes
            left_hand_bbox = None
            right_hand_bbox = None
            left_foot_bbox = None
            right_foot_bbox = None
            
            if kpts2d is not None:
                left_hand_indices = list(range(42, 62))
                left_hand_bbox = compute_bbox_from_keypoints(kpts2d, left_hand_indices)
                
                right_hand_indices = list(range(21, 41))
                right_hand_bbox = compute_bbox_from_keypoints(kpts2d, right_hand_indices)
                
                left_foot_indices = [15, 16, 17]
                left_foot_bbox = compute_bbox_from_keypoints(kpts2d, left_foot_indices)
                
                right_foot_indices = [18, 19, 20]
                right_foot_bbox = compute_bbox_from_keypoints(kpts2d, right_foot_indices)
            
            humans_data.append({
                'human_idx': human_idx,
                'bbox': bbox.tolist() if bbox is not None else None,
                'left_hand_bbox': left_hand_bbox,
                'right_hand_bbox': right_hand_bbox,
                'left_foot_bbox': left_foot_bbox,
                'right_foot_bbox': right_foot_bbox,
                'has_face': has_face,
                'face_orientation': face_orientation.tolist() if face_orientation is not None else None,
                'gaze_direction': gaze_direction,
                'face_embedding': face_embedding,
                'has_mesh': vertices is not None,
                'nsfw_scores': None  # Will fill later
            })
        
        humans_data_list.append(humans_data)
    
    # Batch NSFW classification
    crops = []
    crop_info = []  # (img_idx, human_idx)
    
    for img_idx, humans_data in enumerate(humans_data_list):
        image_pil = images[img_idx]
        for human_idx, human in enumerate(humans_data):
            bbox = human['bbox']
            if bbox is not None:
                x1, y1, x2, y2 = bbox
                ix1, iy1, ix2, iy2 = map(lambda v: max(0, int(round(v))), [x1, y1, x2, y2])
                ix1, iy1 = min(ix1, image_rgbs[img_idx].shape[1]-1), min(iy1, image_rgbs[img_idx].shape[0]-1)
                ix2, iy2 = max(ix1+1, min(ix2, image_rgbs[img_idx].shape[1])), max(iy1+1, min(iy2, image_rgbs[img_idx].shape[0]))
                crop_np = np.ascontiguousarray(image_rgbs[img_idx][iy1:iy2, ix1:ix2])
                crops.append(crop_np)
                crop_info.append((img_idx, human_idx))
    
    if crops and nsfw_classifier is not None and nsfw_classifier.enabled:
        try:
            results = nsfw_classifier.model(crops, conf=0.2, iou=0.3, verbose=False)
            
            for crop_idx, result in enumerate(results):
                img_idx, human_idx = crop_info[crop_idx]
                bbox = humans_data_list[img_idx][human_idx]['bbox']
                x1, y1, x2, y2 = bbox
                
                detections = []
                if result.boxes:
                    for box in result.boxes:
                        class_id = int(box.cls.item())
                        confidence = box.conf.item()
                        class_names = ['anus', 'make_love', 'nipple', 'penis', 'vagina']
                        class_name = class_names[class_id] if class_id < len(class_names) else f'class_{class_id}'
                        
                        dx1, dy1, dx2, dy2 = box.xyxy[0].tolist()
                        abs_bbox = [x1 + dx1, y1 + dy1, x1 + dx2, y1 + dy2]
                        
                        detections.append({
                            'class': class_name,
                            'confidence': confidence,
                            'bbox': abs_bbox
                        })
                
                if detections:
                    humans_data_list[img_idx][human_idx]['nsfw_scores'] = detections
                else:
                    humans_data_list[img_idx][human_idx]['nsfw_scores'] = [{'class': 'safe', 'confidence': 1.0, 'bbox': [x1, y1, x2, y2]}]
        except Exception as e:
            print(f"! Batched NSFW failed: {e}")
            # Fallback: set safe for all
            for img_idx, humans_data in enumerate(humans_data_list):
                for human in humans_data:
                    if human['bbox'] is not None:
                        x1, y1, x2, y2 = human['bbox']
                        human['nsfw_scores'] = [{'class': 'safe', 'confidence': 1.0, 'bbox': [x1, y1, x2, y2]}]
    
    # Save NPZ files and create metadata
    metadatas = []
    for img_idx, (humans_data, image_path) in enumerate(zip(humans_data_list, image_paths)):
        image_pil = images[img_idx]
        image_id = Path(image_path).stem if image_path else f'img_{img_idx:06d}'
        img_width, img_height = image_pil.size
        
        out_path = out_dir / f"{image_id}.npz"
        if out_path.exists():
            metadatas.append(None)
            continue
        
        if not humans_data:
            metadata = {
                'image_id': image_id,
                'num_humans': 0,
                'image_width': img_width,
                'image_height': img_height,
                'processing_time_ms': 0,  # Not tracked in batch
                'status': 'no_detection',
                'humans': []
            }
        else:
            num_humans = len(humans_data)
            
            # Save first human's mesh
            pred = outputs_list[img_idx][0]
            vertices = pred.get('pred_vertices')
            cam_t = pred.get('pred_cam_t')
            focal_length = pred.get('focal_length')
            kpts2d = pred.get('pred_keypoints_2d')
            kpts3d = pred.get('pred_keypoints_3d')
            bbox_0 = pred.get('bbox', None)
            
            np.savez_compressed(
                out_path,
                vertices=vertices.astype(np.float32) if vertices is not None else None,
                faces=faces.astype(np.int32),
                cam_t=cam_t.astype(np.float32) if cam_t is not None else None,
                focal_length=np.array([focal_length], dtype=np.float32) if focal_length is not None else None,
                keypoints_2d=kpts2d.astype(np.float32) if kpts2d is not None else None,
                keypoints_3d=kpts3d.astype(np.float32) if kpts3d is not None else None,
                bbox=np.array(bbox_0, dtype=np.float32) if bbox_0 is not None else None,
                image_id=image_id,
                num_humans=num_humans,
                image_width=img_width,
                image_height=img_height,
                humans_metadata=json.dumps(humans_data)
            )
            
            metadata = {
                'image_id': image_id,
                'num_humans': num_humans,
                'image_width': img_width,
                'image_height': img_height,
                'processing_time_ms': 0,  # Not tracked
                'status': 'success',
                'npz_size_bytes': out_path.stat().st_size,
                'humans': humans_data
            }
        
        metadatas.append(metadata)
    
    return {'metadata': metadatas}


def main():
    logger.info("="*60)
    logger.info("SAM 3D Body Metadata Collection with Face Features")
    logger.info("="*60)
    sys.stdout.flush()
    
    ap = argparse.ArgumentParser()
    ap.add_argument('--input-dataset', type=str, required=True)
    ap.add_argument('--output-dataset', type=str, required=True)
    ap.add_argument('--split', type=str, default='train')
    ap.add_argument('--checkpoint', type=str, default='checkpoints/sam-3d-body-dinov3/model.ckpt')
    ap.add_argument('--mhr-path', type=str, default='checkpoints/sam-3d-body-dinov3/assets/mhr_model.pt')
    ap.add_argument('--limit', type=int, default=0)
    ap.add_argument('--shard-index', type=int, default=0)
    ap.add_argument('--num-shards', type=int, default=1)
    args = ap.parse_args()

    logger.info(f"Arguments: {vars(args)}")
    sys.stdout.flush()

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    logger.info(f"Using device: {device}")
    if torch.cuda.is_available():
        logger.info(f"  GPU: {torch.cuda.get_device_name(0)}")
        logger.info(f"  CUDA version: {torch.version.cuda}")
    sys.stdout.flush()

    # Load gaze estimator
    logger.info("Loading gaze estimator...")
    sys.stdout.flush()
    gaze_estimator = GazeEstimator(device=device)
    
    # Load face embedder (InsightFace ArcFace)
    logger.info("Loading face embedder (InsightFace ArcFace)...")
    sys.stdout.flush()
    face_embedder = FaceEmbedder(device=device)
    
    # Load NSFW classifier
    logger.info("Loading NSFW classifier...")
    sys.stdout.flush()
    nsfw_classifier = NSFWClassifier(device=device)

    # Load teacher
    logger.info("Loading SAM 3D Body teacher...")
    sys.stdout.flush()
    start_load = time.time()
    model, model_cfg = load_sam_3d_body(args.checkpoint, device=device, mhr_path=args.mhr_path)
    model.eval()
    
    teacher = SAM3DBodyEstimator(
        sam_3d_body_model=model,
        model_cfg=model_cfg,
        human_detector=None,
        human_segmentor=None,
        fov_estimator=None,
    )
    logger.info(f"✓ Model loaded in {time.time() - start_load:.1f}s")
    sys.stdout.flush()

    # Load dataset
    logger.info(f"Loading dataset {args.input_dataset}...")
    sys.stdout.flush()
    start_ds = time.time()
    ds = load_dataset(args.input_dataset, split=args.split, streaming=True)
    
    if args.num_shards > 1:
        ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
        logger.info(f"Using shard {args.shard_index+1}/{args.num_shards} (~{100/args.num_shards:.1f}% of dataset)")
    
    if args.limit and args.limit > 0:
        ds = ds.take(args.limit)
    logger.info(f"✓ Dataset ready in {time.time() - start_ds:.1f}s")
    sys.stdout.flush()

    # Prepare output directory and shared mesh topology
    out_dir = Path('teacher_labels')
    out_dir.mkdir(exist_ok=True)
    faces = teacher.faces
    logger.info(f"Mesh topology: {faces.shape[0]} faces")
    sys.stdout.flush()

    # Process using dataset.map() for efficient batching
    batch_size = 4  # Adjust based on GPU memory (higher = more efficient)
    logger.info(f"Processing with batch_size={batch_size} using dataset.map()")
    sys.stdout.flush()
    
    process_batch_partial = functools.partial(
        process_batch,
        teacher=teacher,
        nsfw_classifier=nsfw_classifier,
        gaze_estimator=gaze_estimator,
        face_embedder=face_embedder,
        faces=faces,
        out_dir=out_dir
    )
    
    processed_ds = ds.map(
        process_batch_partial,
        batched=True,
        batch_size=batch_size,
        remove_columns=ds.column_names  # Remove original columns, keep only metadata
    )
    
    # Collect metadata from processed dataset
    metadata_records = []
    batch_count = 0
    start_process = time.time()
    
    for batch_result in processed_ds:
        metadata_records.extend(batch_result['metadata'])
        batch_count += 1
        
        if batch_count % 10 == 0:
            elapsed = time.time() - start_process
            processed = sum(1 for m in metadata_records if m and m['status'] == 'success')
            speed = processed / elapsed if elapsed > 0 else 0
            logger.info(f"[{batch_count} batches] success={processed}, speed={speed:.2f} img/s")
            sys.stdout.flush()
    
    total_time = time.time() - start_process
    processed = sum(1 for m in metadata_records if m and m['status'] == 'success')
    no_detection = sum(1 for m in metadata_records if m and m['status'] == 'no_detection')
    failed = sum(1 for m in metadata_records if m and m['status'] == 'error')
    
    logger.info("="*60)
    logger.info(f"✓ Processing complete!")
    logger.info(f"  Processed: {processed} images in {total_time:.1f}s ({processed/total_time:.2f} img/s)")
    logger.info(f"  No detection: {no_detection}, Failed: {failed}")
    logger.info("="*60)
    sys.stdout.flush()
    
    # Compute metadata statistics
    if metadata_records:
        successful = [m for m in metadata_records if m['status'] == 'success']
        if successful:
            total_humans = sum(m['num_humans'] for m in successful)
            avg_humans = total_humans / len(successful)
            avg_width = sum(m['image_width'] for m in successful) / len(successful)
            avg_height = sum(m['image_height'] for m in successful) / len(successful)
            avg_time = sum(m['processing_time_ms'] for m in successful) / len(successful)
            
            # NSFW statistics
            nsfw_stats = defaultdict(list)
            for m in successful:
                for human in m.get('humans', []):
                    nsfw_list = human.get('nsfw_scores', [])
                    for detection in nsfw_list:
                        label = detection['class']
                        score = detection['confidence']
                        nsfw_stats[label].append(score)
            
            print(f"\nMetadata Statistics:")
            print(f"  Total humans detected: {total_humans}")
            print(f"  Avg humans per image: {avg_humans:.2f}")
            print(f"  Avg image size: {avg_width:.0f}x{avg_height:.0f}")
            print(f"  Avg processing time: {avg_time:.0f}ms")
            
            if nsfw_stats:
                print(f"\nNSFW Classification Statistics:")
                for label, scores in nsfw_stats.items():
                    avg_score = sum(scores) / len(scores)
                    max_score = max(scores)
                    print(f"  {label}: avg={avg_score:.3f}, max={max_score:.3f}, n={len(scores)}")
            
            # Face orientation and gaze statistics
            face_orientation_count = sum(1 for m in successful for h in m.get('humans', []) if h.get('face_orientation'))
            gaze_count = sum(1 for m in successful for h in m.get('humans', []) if h.get('gaze_direction'))
            face_embedding_count = sum(1 for m in successful for h in m.get('humans', []) if h.get('face_embedding'))
            print(f"\nFace Orientation & Gaze Statistics:")
            print(f"  Face orientations computed: {face_orientation_count}/{total_humans}")
            print(f"  Gaze directions estimated: {gaze_count}/{total_humans}")
            print(f"  Face embeddings extracted: {face_embedding_count}/{total_humans}")
            
            # Face embedding quality statistics
            if face_embedding_count > 0:
                det_scores = [h['face_embedding']['det_score'] for m in successful 
                             for h in m.get('humans', []) if h.get('face_embedding')]
                avg_det_score = sum(det_scores) / len(det_scores)
                min_det_score = min(det_scores)
                print(f"\nFace Embedding Quality (InsightFace ArcFace):")
                print(f"  Model: ResNet100-IR + ArcFace head (512-dim)")
                print(f"  Avg detection confidence: {avg_det_score:.3f}")
                print(f"  Min detection confidence: {min_det_score:.3f}")

    
    # Save metadata JSON locally
    metadata_path = Path('metadata.json')
    with open(metadata_path, 'w') as f:
        json.dump(metadata_records, f, indent=2)
    print(f"Saved metadata to {metadata_path}")
    
    # Upload labels
    print(f"\nUploading labels to {args.output_dataset}...")
    
    label_files = sorted(out_dir.glob('*.npz'))
    data = {'image_id': [], 'label_data': []}
    
    for npz_path in label_files:
        data['image_id'].append(npz_path.stem)
        with open(npz_path, 'rb') as f:
            data['label_data'].append(f.read())
    
    features = Features({
        'image_id': Value('string'),
        'label_data': Value('binary'),
    })
    
    label_ds = HFDataset.from_dict(data, features=features)
    label_ds.push_to_hub(
        args.output_dataset,
        split=args.split,
        token=os.environ.get('HF_TOKEN'),
        private=True,
    )
    logger.info(f"✓ Uploaded {len(label_files)} labels to {args.output_dataset}")
    sys.stdout.flush()
    
    # Upload metadata JSON
    from huggingface_hub import HfApi
    api = HfApi(token=os.environ.get('HF_TOKEN'))
    api.upload_file(
        path_or_fileobj=str(metadata_path),
        path_in_repo=f'metadata_shard{args.shard_index}.json',
        repo_id=args.output_dataset,
        repo_type='dataset'
    )
    logger.info(f"✓ Uploaded metadata to {args.output_dataset}/metadata_shard{args.shard_index}.json")
    sys.stdout.flush()


if __name__ == '__main__':
    main()