scripts / hf_job_face_embedding.py
vlordier's picture
Upload hf_job_face_embedding.py with huggingface_hub
fc35e87 verified
#!/usr/bin/env python3
"""
Face Embedding Job - Extract ArcFace embeddings from detected faces
Requires: SAM 3D Body outputs for face bboxes
Outputs: 512-dim face embeddings with detection confidence
"""
import argparse
import os
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')
import logging
import sys
import subprocess
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
def init_face_embedder(device='cuda'):
"""Initialize InsightFace ArcFace model"""
logger.info("Installing InsightFace...")
try:
subprocess.run(
['pip', 'install', '-q', 'insightface', 'onnxruntime-gpu' if device.type == 'cuda' else 'onnxruntime'],
check=True,
capture_output=True
)
logger.info("✓ InsightFace installed")
except Exception as e:
logger.warning(f"InsightFace installation failed: {e}")
logger.info("Loading InsightFace ArcFace...")
import insightface
from insightface.app import FaceAnalysis
app = FaceAnalysis(
name='buffalo_l',
providers=['CUDAExecutionProvider'] if device.type == 'cuda' else ['CPUExecutionProvider']
)
app.prepare(ctx_id=0 if device.type == 'cuda' else -1, det_size=(640, 640))
logger.info("✓ ArcFace loaded")
return app
def make_square_bbox_with_padding(bbox, img_width, img_height, padding=0.2):
"""Convert bbox to square with padding for face detection"""
x1, y1, x2, y2 = bbox
w = x2 - x1
h = y2 - y1
# Make square
size = max(w, h)
cx = (x1 + x2) / 2
cy = (y1 + y2) / 2
# Add padding
size = size * (1 + padding)
# Get square bbox
x1_sq = max(0, int(cx - size / 2))
y1_sq = max(0, int(cy - size / 2))
x2_sq = min(img_width, int(cx + size / 2))
y2_sq = min(img_height, int(cy + size / 2))
return [x1_sq, y1_sq, x2_sq, y2_sq]
def has_valid_face(keypoints_2d, keypoints_3d, img_width, img_height):
"""Check if human has a valid, visible face"""
if keypoints_2d is None or keypoints_3d is None:
return False
kpts2d_arr = np.array(keypoints_2d)
kpts3d_arr = np.array(keypoints_3d)
if len(kpts2d_arr) < 3 or len(kpts3d_arr) < 3:
return False
# Check face keypoints (nose, left eye, right eye)
nose_2d = kpts2d_arr[0]
left_eye_2d = kpts2d_arr[1]
right_eye_2d = kpts2d_arr[2]
nose_3d = kpts3d_arr[0]
left_eye_3d = kpts3d_arr[1]
right_eye_3d = kpts3d_arr[2]
# Check 3D keypoints are valid (not at origin)
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)
if not keypoints_valid_3d:
return False
# Check 2D keypoints are within image bounds
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):
return False
return True
def extract_embedding(app, image_bgr, bbox, img_width, img_height):
"""Extract face embedding from bbox region with proper cropping and padding"""
try:
# Make square bbox with padding for better face detection
square_bbox = make_square_bbox_with_padding(bbox, img_width, img_height, padding=0.2)
x1, y1, x2, y2 = square_bbox
# Crop to square region
crop = image_bgr[y1:y2, x1:x2]
if crop.size == 0:
return None
# Resize to optimal size for InsightFace (640x640 max)
crop_h, crop_w = crop.shape[:2]
if max(crop_h, crop_w) > 640:
scale = 640 / max(crop_h, crop_w)
new_h = int(crop_h * scale)
new_w = int(crop_w * scale)
crop = cv2.resize(crop, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
# Detect faces
faces = app.get(crop)
if len(faces) == 0:
return None
# Use the most confident face
face = max(faces, key=lambda x: x.det_score)
embedding = face.embedding
embedding_norm = embedding / np.linalg.norm(embedding)
return {
'embedding': embedding_norm.astype(np.float32).tolist(),
'det_score': float(face.det_score),
'embedding_dim': len(embedding)
}
except Exception as e:
logger.error(f"Embedding extraction failed: {e}")
return None
def process_batch(batch, sam3d_dataset):
"""Process batch of images - join with SAM3D results to get bboxes"""
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
# Find corresponding SAM3D data
sam3d_row = sam3d_dataset.filter(lambda x: x['image_id'] == image_id).take(1)
sam3d_row = list(sam3d_row)
if not sam3d_row or not sam3d_row[0]['sam3d_data']:
results_list.append({
'image_id': image_id,
'embeddings': None
})
continue
humans_data = json.loads(sam3d_row[0]['sam3d_data'])
# Convert to BGR
image_rgb = np.array(image_pil.convert('RGB'))
image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
# Extract embeddings for each human with valid face
embeddings = []
for human_idx, human in enumerate(humans_data):
bbox = human.get('bbox')
kpts2d = human.get('keypoints_2d')
kpts3d = human.get('keypoints_3d')
# Check if this human has a valid, visible face
if not has_valid_face(kpts2d, kpts3d, img_width, img_height):
embeddings.append(None)
continue
if bbox is None:
embeddings.append(None)
continue
# Extract embedding from face region
embedding = extract_embedding(face_app, image_bgr, bbox, img_width, img_height)
embeddings.append(embedding)
results_list.append({
'image_id': image_id,
'embeddings': json.dumps(embeddings) if any(e is not None for e in embeddings) else None
})
return {
'image_id': [r['image_id'] for r in results_list],
'face_embeddings': [r['embeddings'] for r in results_list]
}
def main():
global face_app
logger.info("="*60)
logger.info("Face Embedding Extraction (ArcFace)")
logger.info("="*60)
ap = argparse.ArgumentParser()
ap.add_argument('--input-dataset', type=str, required=True, help='Original images')
ap.add_argument('--sam3d-dataset', type=str, required=True, help='SAM3D outputs with bboxes')
ap.add_argument('--output-dataset', type=str, required=True)
ap.add_argument('--split', type=str, default='train')
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}")
# Load face embedder
face_app = init_face_embedder(device)
# Load SAM3D results
logger.info(f"Loading SAM3D results from {args.sam3d_dataset}...")
sam3d_ds = load_dataset(args.sam3d_dataset, split=args.split, streaming=True)
# Load images dataset
logger.info(f"Loading images from {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)
sam3d_ds = sam3d_ds.shard(num_shards=args.num_shards, index=args.shard_index)
logger.info(f"Using shard {args.shard_index+1}/{args.num_shards}")
# Process
logger.info(f"Processing with batch_size={args.batch_size}")
from functools import partial
process_fn = partial(process_batch, sam3d_dataset=sam3d_ds)
processed_ds = ds.map(
process_fn,
batched=True,
batch_size=args.batch_size,
remove_columns=ds.column_names
)
# Collect results
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")
# Create output dataset
features = Features({
'image_id': Value('string'),
'face_embeddings': Value('string')
})
output_ds = HFDataset.from_dict({
'image_id': [r['image_id'] for r in results],
'face_embeddings': [r['face_embeddings'] for r in results]
}, features=features)
# Upload
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()