| |
| """ |
| SAM 3D Body Inference Job - Extract 3D pose and keypoints |
| Outputs: Vertices, keypoints 2D/3D, camera params, bboxes |
| """ |
| import argparse |
| import os |
| from pathlib import Path |
| import warnings |
| warnings.filterwarnings('ignore') |
| import logging |
| import sys |
|
|
| 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__) |
|
|
| import numpy as np |
| import torch |
| from datasets import load_dataset, Dataset as HFDataset, Features, Value |
| from PIL import Image |
| import cv2 |
| import json |
| import time |
|
|
| |
| 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 |
|
|
| os.environ['PYOPENGL_PLATFORM'] = 'osmesa' |
|
|
|
|
| def process_batch(batch): |
| """Process batch of images with SAM 3D Body""" |
| images = batch['image'] |
| image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))]) |
| |
| results_list = [] |
| |
| for idx, image_pil in enumerate(images): |
| image_id = Path(image_paths[idx]).stem if image_paths[idx] else f'img_{idx:06d}' |
| img_width, img_height = image_pil.size |
| |
| |
| image_rgb = np.array(image_pil.convert('RGB')) |
| image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) |
| |
| |
| with torch.inference_mode(): |
| outputs = teacher.process_one_image(image_bgr) |
| |
| if not outputs: |
| results_list.append({ |
| 'image_id': image_id, |
| 'num_humans': 0, |
| 'data': None |
| }) |
| continue |
| |
| |
| humans_data = [] |
| for human_idx, pred in enumerate(outputs): |
| human_data = { |
| 'vertices': pred.get('pred_vertices').astype(np.float32).tolist() if pred.get('pred_vertices') is not None else None, |
| 'cam_t': pred.get('pred_cam_t').astype(np.float32).tolist() if pred.get('pred_cam_t') is not None else None, |
| 'focal_length': float(pred.get('focal_length')) if pred.get('focal_length') is not None else None, |
| 'keypoints_2d': pred.get('pred_keypoints_2d').astype(np.float32).tolist() if pred.get('pred_keypoints_2d') is not None else None, |
| 'keypoints_3d': pred.get('pred_keypoints_3d').astype(np.float32).tolist() if pred.get('pred_keypoints_3d') is not None else None, |
| 'bbox': pred.get('bbox').tolist() if pred.get('bbox') is not None else None |
| } |
| humans_data.append(human_data) |
| |
| results_list.append({ |
| 'image_id': image_id, |
| 'num_humans': len(humans_data), |
| 'data': json.dumps(humans_data) |
| }) |
| |
| return { |
| 'image_id': [r['image_id'] for r in results_list], |
| 'num_humans': [r['num_humans'] for r in results_list], |
| 'sam3d_data': [r['data'] for r in results_list] |
| } |
|
|
|
|
| def main(): |
| global teacher |
| |
| logger.info("="*60) |
| logger.info("SAM 3D Body Inference") |
| logger.info("="*60) |
| |
| 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('--batch-size', type=int, default=4) |
| 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)}") |
| |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| logger.info(f"Using device: {device}") |
| |
| |
| logger.info("Loading SAM 3D Body...") |
| 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("✓ Model loaded") |
| |
| |
| logger.info(f"Loading dataset {args.input_dataset}...") |
| 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}") |
| |
| |
| logger.info(f"Processing with batch_size={args.batch_size}") |
| |
| processed_ds = ds.map( |
| process_batch, |
| batched=True, |
| batch_size=args.batch_size, |
| remove_columns=ds.column_names |
| ) |
| |
| |
| results = [] |
| for batch_idx, item in enumerate(processed_ds): |
| results.append(item) |
| |
| if (batch_idx + 1) % 50 == 0: |
| logger.info(f"Processed {batch_idx + 1} images") |
| |
| logger.info(f"✓ Processed {len(results)} images") |
| |
| |
| features = Features({ |
| 'image_id': Value('string'), |
| 'num_humans': Value('int32'), |
| 'sam3d_data': Value('string') |
| }) |
| |
| output_ds = HFDataset.from_dict({ |
| 'image_id': [r['image_id'] for r in results], |
| 'num_humans': [r['num_humans'] for r in results], |
| 'sam3d_data': [r['sam3d_data'] for r in results] |
| }, features=features) |
| |
| |
| logger.info(f"Uploading to {args.output_dataset}...") |
| output_ds.push_to_hub( |
| args.output_dataset, |
| split=args.split, |
| token=os.environ.get('HF_TOKEN'), |
| private=True |
| ) |
| logger.info("✓ Upload complete") |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|