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

Upload hf_job_face_embedding.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hf_job_face_embedding.py +246 -0
hf_job_face_embedding.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Face Embedding Job - Extract ArcFace embeddings from detected faces
4
+ Requires: SAM 3D Body outputs for face bboxes
5
+ Outputs: 512-dim face embeddings with detection confidence
6
+ """
7
+ import argparse
8
+ import os
9
+ from pathlib import Path
10
+ import warnings
11
+ warnings.filterwarnings('ignore')
12
+ import logging
13
+ import sys
14
+ import subprocess
15
+
16
+ logging.basicConfig(
17
+ level=logging.INFO,
18
+ format='[%(asctime)s] %(levelname)s: %(message)s',
19
+ datefmt='%Y-%m-%d %H:%M:%S',
20
+ stream=sys.stdout,
21
+ force=True
22
+ )
23
+ logger = logging.getLogger(__name__)
24
+
25
+ import numpy as np
26
+ import torch
27
+ from datasets import load_dataset, Dataset as HFDataset, Features, Value
28
+ from PIL import Image
29
+ import cv2
30
+ import json
31
+
32
+
33
+ def init_face_embedder(device='cuda'):
34
+ """Initialize InsightFace ArcFace model"""
35
+ logger.info("Installing InsightFace...")
36
+ try:
37
+ subprocess.run(
38
+ ['pip', 'install', '-q', 'insightface', 'onnxruntime-gpu' if device.type == 'cuda' else 'onnxruntime'],
39
+ check=True,
40
+ capture_output=True
41
+ )
42
+ logger.info("✓ InsightFace installed")
43
+ except Exception as e:
44
+ logger.warning(f"InsightFace installation failed: {e}")
45
+
46
+ logger.info("Loading InsightFace ArcFace...")
47
+ import insightface
48
+ from insightface.app import FaceAnalysis
49
+
50
+ app = FaceAnalysis(
51
+ name='buffalo_l',
52
+ providers=['CUDAExecutionProvider'] if device.type == 'cuda' else ['CPUExecutionProvider']
53
+ )
54
+ app.prepare(ctx_id=0 if device.type == 'cuda' else -1, det_size=(640, 640))
55
+ logger.info("✓ ArcFace loaded")
56
+
57
+ return app
58
+
59
+
60
+ def extract_embedding(app, image_bgr, bbox):
61
+ """Extract face embedding from bbox region"""
62
+ try:
63
+ x1, y1, x2, y2 = map(int, bbox)
64
+ pad = 20
65
+ h, w = image_bgr.shape[:2]
66
+ x1 = max(0, x1 - pad)
67
+ y1 = max(0, y1 - pad)
68
+ x2 = min(w, x2 + pad)
69
+ y2 = min(h, y2 + pad)
70
+ crop = image_bgr[y1:y2, x1:x2]
71
+
72
+ faces = app.get(crop)
73
+ if len(faces) == 0:
74
+ return None
75
+
76
+ face = max(faces, key=lambda x: x.det_score)
77
+ embedding = face.embedding
78
+ embedding_norm = embedding / np.linalg.norm(embedding)
79
+
80
+ return {
81
+ 'embedding': embedding_norm.astype(np.float32).tolist(),
82
+ 'det_score': float(face.det_score),
83
+ 'embedding_dim': len(embedding)
84
+ }
85
+ except Exception as e:
86
+ logger.error(f"Embedding extraction failed: {e}")
87
+ return None
88
+
89
+
90
+ def process_batch(batch, sam3d_dataset):
91
+ """Process batch of images - join with SAM3D results to get bboxes"""
92
+ images = batch['image']
93
+ image_paths = batch.get('image_path', [f'img_{i:06d}' for i in range(len(images))])
94
+
95
+ results_list = []
96
+
97
+ for idx, image_pil in enumerate(images):
98
+ image_id = Path(image_paths[idx]).stem if image_paths[idx] else f'img_{idx:06d}'
99
+
100
+ # Find corresponding SAM3D data
101
+ sam3d_row = sam3d_dataset.filter(lambda x: x['image_id'] == image_id).take(1)
102
+ sam3d_row = list(sam3d_row)
103
+
104
+ if not sam3d_row or not sam3d_row[0]['sam3d_data']:
105
+ results_list.append({
106
+ 'image_id': image_id,
107
+ 'embeddings': None
108
+ })
109
+ continue
110
+
111
+ humans_data = json.loads(sam3d_row[0]['sam3d_data'])
112
+
113
+ # Convert to BGR
114
+ image_rgb = np.array(image_pil.convert('RGB'))
115
+ image_bgr = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR)
116
+
117
+ # Extract embeddings for each human with valid face
118
+ embeddings = []
119
+ for human_idx, human in enumerate(humans_data):
120
+ bbox = human.get('bbox')
121
+ kpts2d = human.get('keypoints_2d')
122
+ kpts3d = human.get('keypoints_3d')
123
+
124
+ # Check if face is valid
125
+ if bbox is None or kpts2d is None or kpts3d is None:
126
+ embeddings.append(None)
127
+ continue
128
+
129
+ kpts2d_arr = np.array(kpts2d)
130
+ kpts3d_arr = np.array(kpts3d)
131
+
132
+ if len(kpts2d_arr) < 3 or len(kpts3d_arr) < 3:
133
+ embeddings.append(None)
134
+ continue
135
+
136
+ # Check face keypoints valid
137
+ nose_3d = kpts3d_arr[0]
138
+ left_eye_3d = kpts3d_arr[1]
139
+ right_eye_3d = kpts3d_arr[2]
140
+
141
+ if (np.linalg.norm(nose_3d) < 1e-6 or
142
+ np.linalg.norm(left_eye_3d) < 1e-6 or
143
+ np.linalg.norm(right_eye_3d) < 1e-6):
144
+ embeddings.append(None)
145
+ continue
146
+
147
+ # Extract embedding
148
+ embedding = extract_embedding(face_app, image_bgr, bbox)
149
+ embeddings.append(embedding)
150
+
151
+ results_list.append({
152
+ 'image_id': image_id,
153
+ 'embeddings': json.dumps(embeddings) if any(e is not None for e in embeddings) else None
154
+ })
155
+
156
+ return {
157
+ 'image_id': [r['image_id'] for r in results_list],
158
+ 'face_embeddings': [r['embeddings'] for r in results_list]
159
+ }
160
+
161
+
162
+ def main():
163
+ global face_app
164
+
165
+ logger.info("="*60)
166
+ logger.info("Face Embedding Extraction (ArcFace)")
167
+ logger.info("="*60)
168
+
169
+ ap = argparse.ArgumentParser()
170
+ ap.add_argument('--input-dataset', type=str, required=True, help='Original images')
171
+ ap.add_argument('--sam3d-dataset', type=str, required=True, help='SAM3D outputs with bboxes')
172
+ ap.add_argument('--output-dataset', type=str, required=True)
173
+ ap.add_argument('--split', type=str, default='train')
174
+ ap.add_argument('--batch-size', type=int, default=4)
175
+ ap.add_argument('--shard-index', type=int, default=0)
176
+ ap.add_argument('--num-shards', type=int, default=1)
177
+ args = ap.parse_args()
178
+
179
+ logger.info(f"Arguments: {vars(args)}")
180
+
181
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
182
+ logger.info(f"Using device: {device}")
183
+
184
+ # Load face embedder
185
+ face_app = init_face_embedder(device)
186
+
187
+ # Load SAM3D results
188
+ logger.info(f"Loading SAM3D results from {args.sam3d_dataset}...")
189
+ sam3d_ds = load_dataset(args.sam3d_dataset, split=args.split, streaming=True)
190
+
191
+ # Load images dataset
192
+ logger.info(f"Loading images from {args.input_dataset}...")
193
+ ds = load_dataset(args.input_dataset, split=args.split, streaming=True)
194
+
195
+ if args.num_shards > 1:
196
+ ds = ds.shard(num_shards=args.num_shards, index=args.shard_index)
197
+ sam3d_ds = sam3d_ds.shard(num_shards=args.num_shards, index=args.shard_index)
198
+ logger.info(f"Using shard {args.shard_index+1}/{args.num_shards}")
199
+
200
+ # Process
201
+ logger.info(f"Processing with batch_size={args.batch_size}")
202
+
203
+ from functools import partial
204
+ process_fn = partial(process_batch, sam3d_dataset=sam3d_ds)
205
+
206
+ processed_ds = ds.map(
207
+ process_fn,
208
+ batched=True,
209
+ batch_size=args.batch_size,
210
+ remove_columns=ds.column_names
211
+ )
212
+
213
+ # Collect results
214
+ results = []
215
+ for batch_idx, item in enumerate(processed_ds):
216
+ results.append(item)
217
+
218
+ if (batch_idx + 1) % 50 == 0:
219
+ logger.info(f"Processed {batch_idx + 1} images")
220
+
221
+ logger.info(f"✓ Processed {len(results)} images")
222
+
223
+ # Create output dataset
224
+ features = Features({
225
+ 'image_id': Value('string'),
226
+ 'face_embeddings': Value('string')
227
+ })
228
+
229
+ output_ds = HFDataset.from_dict({
230
+ 'image_id': [r['image_id'] for r in results],
231
+ 'face_embeddings': [r['face_embeddings'] for r in results]
232
+ }, features=features)
233
+
234
+ # Upload
235
+ logger.info(f"Uploading to {args.output_dataset}...")
236
+ output_ds.push_to_hub(
237
+ args.output_dataset,
238
+ split=args.split,
239
+ token=os.environ.get('HF_TOKEN'),
240
+ private=True
241
+ )
242
+ logger.info("✓ Upload complete")
243
+
244
+
245
+ if __name__ == '__main__':
246
+ main()