AmitMY commited on
Commit
20da4cb
·
verified ·
1 Parent(s): b999c2e

Create create_dataset.py

Browse files
Files changed (1) hide show
  1. create_dataset.py +832 -0
create_dataset.py ADDED
@@ -0,0 +1,832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Create a HuggingFace dataset from PopSign data.
4
+
5
+ This script reads PopSign game and non-game subsets, extracts frames from videos
6
+ at signing segments, and creates a HuggingFace-compatible dataset with images.
7
+ """
8
+
9
+ import argparse
10
+ import csv
11
+ import io
12
+ import json
13
+ import os
14
+ import pickle
15
+ import shutil
16
+ import tarfile
17
+ from functools import partial
18
+ from multiprocessing import Pool, cpu_count
19
+ from pathlib import Path
20
+
21
+ import cv2
22
+ import pympi
23
+ from datasets import Dataset, DatasetDict, Features, Image, Sequence, Value
24
+ from PIL import Image as PILImage
25
+ from tqdm import tqdm
26
+
27
+ from pose_utils import get_signing_time_range_from_pose
28
+
29
+ # Path to the README template
30
+ README_TEMPLATE_PATH = Path(__file__).parent / "popsign-images" / "README.md"
31
+
32
+
33
+ def get_video_duration(video_path: str) -> float:
34
+ """Get the duration of a video in seconds."""
35
+ cap = cv2.VideoCapture(video_path)
36
+ if not cap.isOpened():
37
+ raise ValueError(f"Could not open video: {video_path}")
38
+
39
+ fps = cap.get(cv2.CAP_PROP_FPS)
40
+ frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
41
+ cap.release()
42
+
43
+ if fps <= 0:
44
+ raise ValueError(f"Invalid FPS for video: {video_path}")
45
+
46
+ return frame_count / fps
47
+
48
+
49
+ def get_video_fps(video_path: str) -> float:
50
+ """Get the FPS of a video."""
51
+ cap = cv2.VideoCapture(video_path)
52
+ if not cap.isOpened():
53
+ raise ValueError(f"Could not open video: {video_path}")
54
+
55
+ fps = cap.get(cv2.CAP_PROP_FPS)
56
+ cap.release()
57
+ return fps
58
+
59
+
60
+ def get_sign_time_range_from_eaf(eaf_path: str) -> tuple[float, float] | None:
61
+ """
62
+ Get the time range of the largest sign segment from an EAF file.
63
+
64
+ Returns:
65
+ Tuple of (start_time, end_time) in seconds, or None if no segments found.
66
+ """
67
+ try:
68
+ eaf = pympi.Elan.Eaf(file_path=eaf_path)
69
+
70
+ if 'SIGN' not in eaf.get_tier_names():
71
+ return None
72
+
73
+ sign_annotations = eaf.get_annotation_data_for_tier('SIGN')
74
+
75
+ if not sign_annotations:
76
+ return None
77
+
78
+ # Find the largest segment
79
+ largest_segment = max(sign_annotations, key=lambda s: s[1] - s[0])
80
+ start_time = largest_segment[0] / 1000 # Convert ms to seconds
81
+ end_time = largest_segment[1] / 1000
82
+
83
+ return start_time, end_time
84
+ except Exception:
85
+ return None
86
+
87
+
88
+ def extract_frames_from_video(
89
+ video_path: str,
90
+ start_time: float,
91
+ end_time: float,
92
+ target_fps: float = 5,
93
+ frame_size: int = 256
94
+ ) -> list[PILImage.Image]:
95
+ """
96
+ Extract frames from a video between start and end times.
97
+
98
+ Args:
99
+ video_path: Path to the video file
100
+ start_time: Start time in seconds
101
+ end_time: End time in seconds
102
+ target_fps: Target frames per second to extract
103
+ frame_size: Size to resize frames to (square)
104
+
105
+ Returns:
106
+ List of PIL Images
107
+ """
108
+ cap = cv2.VideoCapture(video_path)
109
+ if not cap.isOpened():
110
+ raise ValueError(f"Could not open video: {video_path}")
111
+
112
+ fps = cap.get(cv2.CAP_PROP_FPS)
113
+ if fps <= 0:
114
+ cap.release()
115
+ raise ValueError(f"Invalid FPS for video: {video_path}")
116
+
117
+ duration = end_time - start_time
118
+ num_frames = max(2, int(duration * target_fps))
119
+
120
+ # Calculate frame indices to extract
121
+ start_frame = int(start_time * fps)
122
+ end_frame = int(end_time * fps)
123
+ duration_frames = end_frame - start_frame
124
+
125
+ if duration_frames <= 0:
126
+ cap.release()
127
+ return []
128
+
129
+ # Sample frames evenly across the duration
130
+ if num_frames >= duration_frames:
131
+ frame_indices = list(range(start_frame, end_frame + 1))
132
+ else:
133
+ frame_indices = [
134
+ start_frame + int(i * duration_frames / (num_frames - 1))
135
+ for i in range(num_frames - 1)
136
+ ]
137
+ frame_indices.append(end_frame)
138
+
139
+ frames = []
140
+ for frame_num in frame_indices:
141
+ cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
142
+ ret, frame = cap.read()
143
+ if ret:
144
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
145
+ img = PILImage.fromarray(frame_rgb)
146
+ # Resize if needed (videos should already be 256x256)
147
+ if img.size != (frame_size, frame_size):
148
+ img = img.resize((frame_size, frame_size), PILImage.Resampling.LANCZOS)
149
+ frames.append(img)
150
+
151
+ cap.release()
152
+ return frames
153
+
154
+
155
+ def process_csv_row(
156
+ row: dict,
157
+ videos_dir: str,
158
+ eaf_dir: str,
159
+ pose_dir: str,
160
+ target_fps: float = 5
161
+ ) -> dict | None:
162
+ """
163
+ Process a single CSV row and return a dataset entry.
164
+
165
+ Uses a cascading approach for segmentation:
166
+ 1. First try pose-based segmentation (wrist above elbow heuristic)
167
+ 2. If pose covers entire file, fall back to EAF segmentation
168
+ 3. If neither works, use full video duration
169
+
170
+ Args:
171
+ row: CSV row dictionary
172
+ videos_dir: Directory containing 256x256 videos
173
+ eaf_dir: Directory containing EAF files
174
+ pose_dir: Directory containing pose files
175
+ target_fps: Target FPS for frame extraction
176
+
177
+ Returns:
178
+ Dictionary with dataset entry or None if processing failed
179
+ """
180
+ md5 = row['md5']
181
+ video_path = os.path.join(videos_dir, f"{md5}.mp4")
182
+ pose_path = os.path.join(pose_dir, f"{md5}.pose")
183
+ eaf_path = os.path.join(eaf_dir, f"{md5}.eaf")
184
+
185
+ # Check if video exists
186
+ if not os.path.exists(video_path):
187
+ return None
188
+
189
+ # Cascading segmentation approach:
190
+ # 1. Try pose-based segmentation first
191
+ time_range = None
192
+ if os.path.exists(pose_path):
193
+ time_range = get_signing_time_range_from_pose(pose_path)
194
+
195
+ # 2. If pose covers entire file (returns None), try EAF
196
+ if time_range is None and os.path.exists(eaf_path):
197
+ time_range = get_sign_time_range_from_eaf(eaf_path)
198
+
199
+ # 3. Fall back to full video duration
200
+ if time_range is not None:
201
+ start_time, end_time = time_range
202
+ else:
203
+ try:
204
+ start_time = 0.0
205
+ end_time = get_video_duration(video_path)
206
+ except Exception:
207
+ return None
208
+
209
+ # Validate time range
210
+ if end_time <= start_time:
211
+ return None
212
+
213
+ # Extract frames
214
+ try:
215
+ frames = extract_frames_from_video(
216
+ video_path, start_time, end_time, target_fps=target_fps
217
+ )
218
+ except Exception:
219
+ return None
220
+
221
+ if not frames:
222
+ return None
223
+
224
+ return {
225
+ 'file': row['file'],
226
+ 'start': round(start_time, 3),
227
+ 'end': round(end_time, 3),
228
+ 'text': row['text'],
229
+ 'images': frames
230
+ }
231
+
232
+
233
+ def load_csv_data(csv_path: str) -> dict[str, list[dict]]:
234
+ """
235
+ Load CSV data and group by split.
236
+
237
+ Returns:
238
+ Dictionary mapping split names to lists of row dictionaries
239
+ """
240
+ splits = {'train': [], 'validation': [], 'test': []}
241
+
242
+ with open(csv_path, 'r', encoding='utf-8') as f:
243
+ reader = csv.DictReader(f)
244
+ for row in reader:
245
+ split = row['split']
246
+ if split in splits:
247
+ splits[split].append(row)
248
+
249
+ return splits
250
+
251
+
252
+ def _process_row_wrapper(args: tuple) -> dict | None:
253
+ """Wrapper for process_csv_row to work with multiprocessing."""
254
+ row, videos_dir, eaf_dir, pose_dir, target_fps = args
255
+ return process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)
256
+
257
+
258
+ def create_subset_dataset(
259
+ csv_path: str,
260
+ videos_dir: str,
261
+ eaf_dir: str,
262
+ pose_dir: str,
263
+ target_fps: float = 5,
264
+ limit: int | None = None,
265
+ num_workers: int | None = None
266
+ ) -> DatasetDict:
267
+ """
268
+ Create a DatasetDict for a single subset (game or non-game).
269
+
270
+ Args:
271
+ csv_path: Path to the index.csv file
272
+ videos_dir: Directory containing 256x256 videos
273
+ eaf_dir: Directory containing EAF files
274
+ pose_dir: Directory containing pose files
275
+ target_fps: Target FPS for frame extraction
276
+ limit: Optional limit on number of samples per split (for testing)
277
+ num_workers: Number of parallel workers (default: CPU count)
278
+
279
+ Returns:
280
+ DatasetDict with train, validation, test splits
281
+ """
282
+ splits_data = load_csv_data(csv_path)
283
+
284
+ if num_workers is None:
285
+ num_workers = cpu_count()
286
+
287
+ features = Features({
288
+ 'file': Value('string'),
289
+ 'start': Value('float32'),
290
+ 'end': Value('float32'),
291
+ 'text': Value('string'),
292
+ 'images': Sequence(Image())
293
+ })
294
+
295
+ dataset_splits = {}
296
+
297
+ for split_name, rows in splits_data.items():
298
+ if not rows:
299
+ continue
300
+
301
+ if limit is not None:
302
+ rows = rows[:limit]
303
+
304
+ # Prepare arguments for parallel processing
305
+ args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in rows]
306
+
307
+ processed_data = []
308
+
309
+ if num_workers > 1:
310
+ with Pool(num_workers) as pool:
311
+ results = list(tqdm(
312
+ pool.imap(_process_row_wrapper, args_list, chunksize=100),
313
+ total=len(args_list),
314
+ desc=f"Processing {split_name}",
315
+ unit="sample"
316
+ ))
317
+ processed_data = [r for r in results if r is not None]
318
+ else:
319
+ for row in tqdm(rows, desc=f"Processing {split_name}", unit="sample"):
320
+ result = process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)
321
+ if result is not None:
322
+ processed_data.append(result)
323
+
324
+ if processed_data:
325
+ dataset_splits[split_name] = Dataset.from_list(
326
+ processed_data,
327
+ features=features
328
+ )
329
+
330
+ return DatasetDict(dataset_splits)
331
+
332
+
333
+ def create_popsign_dataset(
334
+ popsign_dir: str,
335
+ videos_dir: str,
336
+ eaf_dir: str,
337
+ pose_dir: str,
338
+ output_dir: str,
339
+ target_fps: float = 5,
340
+ limit: int | None = None,
341
+ num_workers: int | None = None
342
+ ):
343
+ """
344
+ Create the complete PopSign HuggingFace dataset with game and non-game subsets.
345
+
346
+ Args:
347
+ popsign_dir: Root directory containing game/ and non-game/ subdirectories
348
+ videos_dir: Directory containing 256x256 videos
349
+ eaf_dir: Directory containing EAF files
350
+ pose_dir: Directory containing pose files
351
+ output_dir: Output directory for the dataset
352
+ target_fps: Target FPS for frame extraction
353
+ limit: Optional limit on samples per split (for testing)
354
+ num_workers: Number of parallel workers
355
+ """
356
+ output_path = Path(output_dir)
357
+ output_path.mkdir(parents=True, exist_ok=True)
358
+
359
+ subsets = ['game', 'non-game']
360
+
361
+ for subset in subsets:
362
+ csv_path = os.path.join(popsign_dir, subset, 'index.csv')
363
+
364
+ if not os.path.exists(csv_path):
365
+ print(f"Warning: {csv_path} not found, skipping {subset}")
366
+ continue
367
+
368
+ print(f"\nProcessing {subset} subset...")
369
+
370
+ dataset_dict = create_subset_dataset(
371
+ csv_path=csv_path,
372
+ videos_dir=videos_dir,
373
+ eaf_dir=eaf_dir,
374
+ pose_dir=pose_dir,
375
+ target_fps=target_fps,
376
+ limit=limit,
377
+ num_workers=num_workers
378
+ )
379
+
380
+ # Save the subset
381
+ subset_path = output_path / subset
382
+ dataset_dict.save_to_disk(str(subset_path))
383
+ print(f"Saved {subset} to {subset_path}")
384
+
385
+ print(f"\nDataset saved to {output_dir}")
386
+
387
+
388
+ def _save_shard(shard_data: list, shard_idx: int, num_shards: int, split_name: str, subset_data_path: Path, features: Features) -> int:
389
+ """Save a shard to parquet and return the number of samples saved."""
390
+ if not shard_data:
391
+ return 0
392
+ dataset = Dataset.from_list(shard_data, features=features)
393
+ parquet_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.parquet"
394
+ dataset.to_parquet(str(parquet_path))
395
+ count = len(shard_data)
396
+ print(f"\n Saved shard {shard_idx} ({count} samples) -> {parquet_path.name}", flush=True)
397
+ del dataset
398
+ return count
399
+
400
+
401
+ def save_as_parquet(
402
+ popsign_dir: str,
403
+ videos_dir: str,
404
+ eaf_dir: str,
405
+ pose_dir: str,
406
+ output_dir: str,
407
+ target_fps: float = 5,
408
+ limit: int | None = None,
409
+ shard_size: int = 10000,
410
+ num_workers: int | None = None
411
+ ):
412
+ """
413
+ Create the PopSign dataset and save in Parquet format for HuggingFace Hub upload.
414
+
415
+ Saves shards incrementally to minimize RAM usage by processing in small batches.
416
+
417
+ Directory structure:
418
+ output_dir/
419
+ ├── README.md
420
+ └── data/
421
+ ├── game/
422
+ │ ├── train-00000-of-NNNNN.parquet
423
+ │ └── ...
424
+ └── non-game/
425
+ └── ...
426
+
427
+ Args:
428
+ pose_dir: Directory containing pose files
429
+ shard_size: Number of samples per parquet shard (default: 10000)
430
+ num_workers: Number of parallel workers
431
+ """
432
+ output_path = Path(output_dir)
433
+ data_path = output_path / "data"
434
+ data_path.mkdir(parents=True, exist_ok=True)
435
+
436
+ # Copy README.md to output directory (if not already there)
437
+ readme_dest = output_path / "README.md"
438
+ if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
439
+ shutil.copy(README_TEMPLATE_PATH, readme_dest)
440
+ print(f"Copied README.md to {readme_dest}")
441
+
442
+ if num_workers is None:
443
+ num_workers = cpu_count()
444
+
445
+ # Process in small batches to limit memory - each batch is processed in parallel,
446
+ # then results are accumulated until we have enough for a shard
447
+ batch_size = min(1000, shard_size) # Small batches to limit memory
448
+ print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)
449
+
450
+ features = Features({
451
+ 'file': Value('string'),
452
+ 'start': Value('float32'),
453
+ 'end': Value('float32'),
454
+ 'text': Value('string'),
455
+ 'images': Sequence(Image())
456
+ })
457
+
458
+ subsets = ['game', 'non-game']
459
+
460
+ for subset in subsets:
461
+ csv_path = os.path.join(popsign_dir, subset, 'index.csv')
462
+
463
+ if not os.path.exists(csv_path):
464
+ print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
465
+ continue
466
+
467
+ print(f"\nProcessing {subset} subset...", flush=True)
468
+
469
+ splits_data = load_csv_data(csv_path)
470
+ subset_data_path = data_path / subset
471
+ subset_data_path.mkdir(parents=True, exist_ok=True)
472
+
473
+ for split_name, rows in splits_data.items():
474
+ if not rows:
475
+ continue
476
+
477
+ if limit is not None:
478
+ rows = rows[:limit]
479
+
480
+ total_rows = len(rows)
481
+ num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
482
+ print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)
483
+
484
+ shard_data = []
485
+ shard_idx = 0
486
+ total_saved = 0
487
+ total_processed = 0
488
+
489
+ # Process in small batches to control memory
490
+ pbar = tqdm(total=total_rows, desc=f" {split_name}", unit="row")
491
+
492
+ for batch_start in range(0, total_rows, batch_size):
493
+ batch_end = min(batch_start + batch_size, total_rows)
494
+ batch_rows = rows[batch_start:batch_end]
495
+
496
+ # Process this batch
497
+ if num_workers > 1:
498
+ args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
499
+ with Pool(num_workers) as pool:
500
+ results = pool.map(_process_row_wrapper, args_list)
501
+ else:
502
+ results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
503
+
504
+ # Accumulate successful results
505
+ for result in results:
506
+ if result is not None:
507
+ shard_data.append(result)
508
+
509
+ # Save shard when full
510
+ if len(shard_data) >= shard_size:
511
+ total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
512
+ shard_data = []
513
+ shard_idx += 1
514
+
515
+ # Free batch memory
516
+ del results
517
+ total_processed += len(batch_rows)
518
+ pbar.update(len(batch_rows))
519
+
520
+ pbar.close()
521
+
522
+ # Save any remaining data
523
+ if shard_data:
524
+ total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
525
+ shard_idx += 1
526
+
527
+ print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)
528
+
529
+ print(f"\nDataset saved to {output_dir}", flush=True)
530
+ print("\nTo upload to HuggingFace Hub:")
531
+ print(f" huggingface-cli upload sign/popsign-images {output_dir} .")
532
+
533
+
534
+ def _save_webdataset_shard(
535
+ shard_data: list,
536
+ shard_idx: int,
537
+ num_shards: int,
538
+ split_name: str,
539
+ subset_data_path: Path,
540
+ sample_id_offset: int,
541
+ jpeg_quality: int
542
+ ) -> int:
543
+ """Save a shard to tar and return the number of samples saved."""
544
+ if not shard_data:
545
+ return 0
546
+
547
+ tar_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.tar"
548
+
549
+ with tarfile.open(tar_path, 'w') as tar:
550
+ for i, sample in enumerate(shard_data):
551
+ sample_id = f"{sample_id_offset + i:06d}"
552
+
553
+ # Write metadata JSON
554
+ metadata = {
555
+ 'file': sample['file'],
556
+ 'start': sample['start'],
557
+ 'end': sample['end'],
558
+ 'text': sample['text'],
559
+ 'num_frames': len(sample['images'])
560
+ }
561
+ json_data = json.dumps(metadata).encode('utf-8')
562
+ json_info = tarfile.TarInfo(name=f"{sample_id}.json")
563
+ json_info.size = len(json_data)
564
+ tar.addfile(json_info, io.BytesIO(json_data))
565
+
566
+ # Write all frames as JPEG bytes in a single pickle file
567
+ frames_data = []
568
+ for img in sample['images']:
569
+ jpg_buffer = io.BytesIO()
570
+ img.save(jpg_buffer, format='JPEG', quality=jpeg_quality)
571
+ frames_data.append(jpg_buffer.getvalue())
572
+
573
+ pyd_data = pickle.dumps(frames_data)
574
+ pyd_info = tarfile.TarInfo(name=f"{sample_id}.pyd")
575
+ pyd_info.size = len(pyd_data)
576
+ tar.addfile(pyd_info, io.BytesIO(pyd_data))
577
+
578
+ count = len(shard_data)
579
+ print(f"\n Saved shard {shard_idx} ({count} samples) -> {tar_path.name}", flush=True)
580
+ return count
581
+
582
+
583
+ def save_as_webdataset(
584
+ popsign_dir: str,
585
+ videos_dir: str,
586
+ eaf_dir: str,
587
+ pose_dir: str,
588
+ output_dir: str,
589
+ target_fps: float = 5,
590
+ limit: int | None = None,
591
+ shard_size: int = 1000,
592
+ num_workers: int | None = None,
593
+ jpeg_quality: int = 90
594
+ ):
595
+ """
596
+ Create the PopSign dataset and save in WebDataset format for HuggingFace Hub upload.
597
+
598
+ Saves shards incrementally to minimize RAM usage.
599
+
600
+ Directory structure:
601
+ output_dir/
602
+ ├── README.md
603
+ └── data/
604
+ ├── game/
605
+ │ ├── train-00000-of-NNNNN.tar
606
+ │ └── ...
607
+ └── non-game/
608
+ └── ...
609
+
610
+ Each tar contains:
611
+ - {sample_id:06d}.json (metadata: file, start, end, text, num_frames)
612
+ - {sample_id:06d}.pyd (pickled list of JPEG bytes)
613
+
614
+ Args:
615
+ pose_dir: Directory containing pose files
616
+ shard_size: Number of samples per tar shard (default: 1000)
617
+ num_workers: Number of parallel workers
618
+ jpeg_quality: JPEG quality for saved images (default: 90)
619
+ """
620
+ output_path = Path(output_dir)
621
+ data_path = output_path / "data"
622
+ data_path.mkdir(parents=True, exist_ok=True)
623
+
624
+ # Copy README.md to output directory (if not already there)
625
+ readme_dest = output_path / "README.md"
626
+ if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
627
+ shutil.copy(README_TEMPLATE_PATH, readme_dest)
628
+ print(f"Copied README.md to {readme_dest}")
629
+
630
+ if num_workers is None:
631
+ num_workers = cpu_count()
632
+
633
+ # Process in small batches to limit memory
634
+ batch_size = min(1000, shard_size)
635
+ print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)
636
+
637
+ subsets = ['game', 'non-game']
638
+
639
+ for subset in subsets:
640
+ csv_path = os.path.join(popsign_dir, subset, 'index.csv')
641
+
642
+ if not os.path.exists(csv_path):
643
+ print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
644
+ continue
645
+
646
+ print(f"\nProcessing {subset} subset...", flush=True)
647
+
648
+ splits_data = load_csv_data(csv_path)
649
+ subset_data_path = data_path / subset
650
+ subset_data_path.mkdir(parents=True, exist_ok=True)
651
+
652
+ for split_name, rows in splits_data.items():
653
+ if not rows:
654
+ continue
655
+
656
+ if limit is not None:
657
+ rows = rows[:limit]
658
+
659
+ total_rows = len(rows)
660
+ num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
661
+ print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)
662
+
663
+ shard_data = []
664
+ shard_idx = 0
665
+ total_saved = 0
666
+ sample_id_offset = 0
667
+
668
+ # Process in small batches to control memory
669
+ pbar = tqdm(total=total_rows, desc=f" {split_name}", unit="row")
670
+
671
+ for batch_start in range(0, total_rows, batch_size):
672
+ batch_end = min(batch_start + batch_size, total_rows)
673
+ batch_rows = rows[batch_start:batch_end]
674
+
675
+ # Process this batch
676
+ if num_workers > 1:
677
+ args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
678
+ with Pool(num_workers) as pool:
679
+ results = pool.map(_process_row_wrapper, args_list)
680
+ else:
681
+ results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
682
+
683
+ # Accumulate successful results
684
+ for result in results:
685
+ if result is not None:
686
+ shard_data.append(result)
687
+
688
+ # Save shard when full
689
+ if len(shard_data) >= shard_size:
690
+ total_saved += _save_webdataset_shard(
691
+ shard_data, shard_idx, num_shards, split_name,
692
+ subset_data_path, sample_id_offset, jpeg_quality
693
+ )
694
+ sample_id_offset += len(shard_data)
695
+ shard_data = []
696
+ shard_idx += 1
697
+
698
+ # Free batch memory
699
+ del results
700
+ pbar.update(len(batch_rows))
701
+
702
+ pbar.close()
703
+
704
+ # Save any remaining data
705
+ if shard_data:
706
+ total_saved += _save_webdataset_shard(
707
+ shard_data, shard_idx, num_shards, split_name,
708
+ subset_data_path, sample_id_offset, jpeg_quality
709
+ )
710
+ shard_idx += 1
711
+
712
+ print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)
713
+
714
+ print(f"\nDataset saved to {output_dir}", flush=True)
715
+ print("\nTo upload to HuggingFace Hub:")
716
+ print(f" huggingface-cli upload sign/popsign-images {output_dir} .")
717
+
718
+
719
+ def main():
720
+ parser = argparse.ArgumentParser(
721
+ description='Create PopSign HuggingFace dataset with images'
722
+ )
723
+ parser.add_argument(
724
+ '--popsign-dir',
725
+ type=str,
726
+ default='some-path-to/popsign/v1',
727
+ help='Root directory containing game/ and non-game/ subdirectories'
728
+ )
729
+ parser.add_argument(
730
+ '--videos-dir',
731
+ type=str,
732
+ default='some-path-to-videos/256x256',
733
+ help='Directory containing 256x256 videos named by MD5 hash'
734
+ )
735
+ parser.add_argument(
736
+ '--eaf-dir',
737
+ type=str,
738
+ default='some-path-to-segments',
739
+ help='Directory containing EAF segmentation files'
740
+ )
741
+ parser.add_argument(
742
+ '--pose-dir',
743
+ type=str,
744
+ default='some-path-to-poses',
745
+ help='Directory containing pose files for signing boundary detection'
746
+ )
747
+ parser.add_argument(
748
+ '--output-dir',
749
+ type=str,
750
+ default='/shared/popsign-images',
751
+ help='Output directory for the HuggingFace dataset'
752
+ )
753
+ parser.add_argument(
754
+ '--fps',
755
+ type=float,
756
+ default=5,
757
+ help='Target frames per second for frame extraction (default: 5)'
758
+ )
759
+ parser.add_argument(
760
+ '--limit',
761
+ type=int,
762
+ default=None,
763
+ help='Limit number of samples per split (for testing)'
764
+ )
765
+ parser.add_argument(
766
+ '--format',
767
+ type=str,
768
+ choices=['webdataset', 'parquet', 'arrow'],
769
+ default='parquet',
770
+ help='Output format: webdataset (JPEG compressed), parquet, or arrow (for local use)'
771
+ )
772
+ parser.add_argument(
773
+ '--shard-size',
774
+ type=int,
775
+ default=1000,
776
+ help='Number of samples per shard (default: 1000)'
777
+ )
778
+ parser.add_argument(
779
+ '--jpeg-quality',
780
+ type=int,
781
+ default=90,
782
+ help='JPEG quality for WebDataset format (default: 90)'
783
+ )
784
+ parser.add_argument(
785
+ '--workers',
786
+ type=int,
787
+ default=None,
788
+ help='Number of parallel workers (default: CPU count)'
789
+ )
790
+
791
+ args = parser.parse_args()
792
+
793
+ if args.format == 'webdataset':
794
+ save_as_webdataset(
795
+ popsign_dir=args.popsign_dir,
796
+ videos_dir=args.videos_dir,
797
+ eaf_dir=args.eaf_dir,
798
+ pose_dir=args.pose_dir,
799
+ output_dir=args.output_dir,
800
+ target_fps=args.fps,
801
+ limit=args.limit,
802
+ shard_size=args.shard_size,
803
+ num_workers=args.workers,
804
+ jpeg_quality=args.jpeg_quality
805
+ )
806
+ elif args.format == 'parquet':
807
+ save_as_parquet(
808
+ popsign_dir=args.popsign_dir,
809
+ videos_dir=args.videos_dir,
810
+ eaf_dir=args.eaf_dir,
811
+ pose_dir=args.pose_dir,
812
+ output_dir=args.output_dir,
813
+ target_fps=args.fps,
814
+ limit=args.limit,
815
+ shard_size=args.shard_size,
816
+ num_workers=args.workers
817
+ )
818
+ else:
819
+ create_popsign_dataset(
820
+ popsign_dir=args.popsign_dir,
821
+ videos_dir=args.videos_dir,
822
+ eaf_dir=args.eaf_dir,
823
+ pose_dir=args.pose_dir,
824
+ output_dir=args.output_dir,
825
+ target_fps=args.fps,
826
+ limit=args.limit,
827
+ num_workers=args.workers
828
+ )
829
+
830
+
831
+ if __name__ == '__main__':
832
+ main()