vlordier commited on
Commit
3c6d4e5
·
verified ·
1 Parent(s): 600d133

Upload hf_job_sam3d.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hf_job_sam3d.py +183 -0
hf_job_sam3d.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SAM 3D Body Inference Job - Extract 3D pose and keypoints
4
+ Outputs: Vertices, keypoints 2D/3D, camera params, bboxes
5
+ """
6
+ import argparse
7
+ import os
8
+ from pathlib import Path
9
+ import warnings
10
+ warnings.filterwarnings('ignore')
11
+ import logging
12
+ import sys
13
+
14
+ logging.basicConfig(
15
+ level=logging.INFO,
16
+ format='[%(asctime)s] %(levelname)s: %(message)s',
17
+ datefmt='%Y-%m-%d %H:%M:%S',
18
+ stream=sys.stdout,
19
+ force=True
20
+ )
21
+ logger = logging.getLogger(__name__)
22
+
23
+ import numpy as np
24
+ import torch
25
+ from datasets import load_dataset, Dataset as HFDataset, Features, Value
26
+ from PIL import Image
27
+ import cv2
28
+ import json
29
+ import time
30
+
31
+ # SAM 3D Body imports
32
+ sam_repo = Path(__file__).parent.parent / "sam-3d-body"
33
+ if str(sam_repo) not in sys.path:
34
+ sys.path.insert(0, str(sam_repo))
35
+ from sam_3d_body import load_sam_3d_body, SAM3DBodyEstimator
36
+
37
+ os.environ['PYOPENGL_PLATFORM'] = 'osmesa'
38
+
39
+
40
+ def process_batch(batch):
41
+ """Process batch of images with SAM 3D Body"""
42
+ images = batch['image']
43
+ image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))])
44
+
45
+ results_list = []
46
+
47
+ for idx, image_pil in enumerate(images):
48
+ image_id = Path(image_paths[idx]).stem if image_paths[idx] else f'img_{idx:06d}'
49
+ img_width, img_height = image_pil.size
50
+
51
+ # Convert to BGR
52
+ image_rgb = np.array(image_pil.convert('RGB'))
53
+ image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
54
+
55
+ # Process with SAM 3D Body
56
+ with torch.inference_mode():
57
+ outputs = teacher.process_one_image(image_bgr)
58
+
59
+ if not outputs:
60
+ results_list.append({
61
+ 'image_id': image_id,
62
+ 'num_humans': 0,
63
+ 'data': None
64
+ })
65
+ continue
66
+
67
+ # Collect all humans data
68
+ humans_data = []
69
+ for human_idx, pred in enumerate(outputs):
70
+ human_data = {
71
+ 'vertices': pred.get('pred_vertices').astype(np.float32).tolist() if pred.get('pred_vertices') is not None else None,
72
+ 'cam_t': pred.get('pred_cam_t').astype(np.float32).tolist() if pred.get('pred_cam_t') is not None else None,
73
+ 'focal_length': float(pred.get('focal_length')) if pred.get('focal_length') is not None else None,
74
+ 'keypoints_2d': pred.get('pred_keypoints_2d').astype(np.float32).tolist() if pred.get('pred_keypoints_2d') is not None else None,
75
+ 'keypoints_3d': pred.get('pred_keypoints_3d').astype(np.float32).tolist() if pred.get('pred_keypoints_3d') is not None else None,
76
+ 'bbox': pred.get('bbox').tolist() if pred.get('bbox') is not None else None
77
+ }
78
+ humans_data.append(human_data)
79
+
80
+ results_list.append({
81
+ 'image_id': image_id,
82
+ 'num_humans': len(humans_data),
83
+ 'data': json.dumps(humans_data)
84
+ })
85
+
86
+ return {
87
+ 'image_id': [r['image_id'] for r in results_list],
88
+ 'num_humans': [r['num_humans'] for r in results_list],
89
+ 'sam3d_data': [r['data'] for r in results_list]
90
+ }
91
+
92
+
93
+ def main():
94
+ global teacher
95
+
96
+ logger.info("="*60)
97
+ logger.info("SAM 3D Body Inference")
98
+ logger.info("="*60)
99
+
100
+ ap = argparse.ArgumentParser()
101
+ ap.add_argument('--input-dataset', type=str, required=True)
102
+ ap.add_argument('--output-dataset', type=str, required=True)
103
+ ap.add_argument('--split', type=str, default='train')
104
+ ap.add_argument('--checkpoint', type=str, default='checkpoints/sam-3d-body-dinov3/model.ckpt')
105
+ ap.add_argument('--mhr-path', type=str, default='checkpoints/sam-3d-body-dinov3/assets/mhr_model.pt')
106
+ ap.add_argument('--batch-size', type=int, default=4)
107
+ ap.add_argument('--shard-index', type=int, default=0)
108
+ ap.add_argument('--num-shards', type=int, default=1)
109
+ args = ap.parse_args()
110
+
111
+ logger.info(f"Arguments: {vars(args)}")
112
+
113
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
114
+ logger.info(f"Using device: {device}")
115
+
116
+ # Load model
117
+ logger.info("Loading SAM 3D Body...")
118
+ model, model_cfg = load_sam_3d_body(args.checkpoint, device=device, mhr_path=args.mhr_path)
119
+ model.eval()
120
+
121
+ teacher = SAM3DBodyEstimator(
122
+ sam_3d_body_model=model,
123
+ model_cfg=model_cfg,
124
+ human_detector=None,
125
+ human_segmentor=None,
126
+ fov_estimator=None,
127
+ )
128
+ logger.info("✓ Model loaded")
129
+
130
+ # Load dataset
131
+ logger.info(f"Loading dataset {args.input_dataset}...")
132
+ ds = load_dataset(args.input_dataset, split=args.split, streaming=True)
133
+
134
+ if args.num_shards > 1:
135
+ ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
136
+ logger.info(f"Using shard {args.shard_index+1}/{args.num_shards}")
137
+
138
+ # Process
139
+ logger.info(f"Processing with batch_size={args.batch_size}")
140
+
141
+ processed_ds = ds.map(
142
+ process_batch,
143
+ batched=True,
144
+ batch_size=args.batch_size,
145
+ remove_columns=ds.column_names
146
+ )
147
+
148
+ # Collect results
149
+ results = []
150
+ for batch_idx, item in enumerate(processed_ds):
151
+ results.append(item)
152
+
153
+ if (batch_idx + 1) % 50 == 0:
154
+ logger.info(f"Processed {batch_idx + 1} images")
155
+
156
+ logger.info(f"✓ Processed {len(results)} images")
157
+
158
+ # Create output dataset
159
+ features = Features({
160
+ 'image_id': Value('string'),
161
+ 'num_humans': Value('int32'),
162
+ 'sam3d_data': Value('string')
163
+ })
164
+
165
+ output_ds = HFDataset.from_dict({
166
+ 'image_id': [r['image_id'] for r in results],
167
+ 'num_humans': [r['num_humans'] for r in results],
168
+ 'sam3d_data': [r['sam3d_data'] for r in results]
169
+ }, features=features)
170
+
171
+ # Upload
172
+ logger.info(f"Uploading to {args.output_dataset}...")
173
+ output_ds.push_to_hub(
174
+ args.output_dataset,
175
+ split=args.split,
176
+ token=os.environ.get('HF_TOKEN'),
177
+ private=True
178
+ )
179
+ logger.info("✓ Upload complete")
180
+
181
+
182
+ if __name__ == '__main__':
183
+ main()