File size: 26,798 Bytes
20da4cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
#!/usr/bin/env python3
"""
Create a HuggingFace dataset from PopSign data.

This script reads PopSign game and non-game subsets, extracts frames from videos
at signing segments, and creates a HuggingFace-compatible dataset with images.
"""

import argparse
import csv
import io
import json
import os
import pickle
import shutil
import tarfile
from functools import partial
from multiprocessing import Pool, cpu_count
from pathlib import Path

import cv2
import pympi
from datasets import Dataset, DatasetDict, Features, Image, Sequence, Value
from PIL import Image as PILImage
from tqdm import tqdm

from pose_utils import get_signing_time_range_from_pose

# Path to the README template
README_TEMPLATE_PATH = Path(__file__).parent / "popsign-images" / "README.md"


def get_video_duration(video_path: str) -> float:
    """Get the duration of a video in seconds."""
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    cap.release()

    if fps <= 0:
        raise ValueError(f"Invalid FPS for video: {video_path}")

    return frame_count / fps


def get_video_fps(video_path: str) -> float:
    """Get the FPS of a video."""
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    cap.release()
    return fps


def get_sign_time_range_from_eaf(eaf_path: str) -> tuple[float, float] | None:
    """
    Get the time range of the largest sign segment from an EAF file.

    Returns:
        Tuple of (start_time, end_time) in seconds, or None if no segments found.
    """
    try:
        eaf = pympi.Elan.Eaf(file_path=eaf_path)

        if 'SIGN' not in eaf.get_tier_names():
            return None

        sign_annotations = eaf.get_annotation_data_for_tier('SIGN')

        if not sign_annotations:
            return None

        # Find the largest segment
        largest_segment = max(sign_annotations, key=lambda s: s[1] - s[0])
        start_time = largest_segment[0] / 1000  # Convert ms to seconds
        end_time = largest_segment[1] / 1000

        return start_time, end_time
    except Exception:
        return None


def extract_frames_from_video(
    video_path: str,
    start_time: float,
    end_time: float,
    target_fps: float = 5,
    frame_size: int = 256
) -> list[PILImage.Image]:
    """
    Extract frames from a video between start and end times.

    Args:
        video_path: Path to the video file
        start_time: Start time in seconds
        end_time: End time in seconds
        target_fps: Target frames per second to extract
        frame_size: Size to resize frames to (square)

    Returns:
        List of PIL Images
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    if fps <= 0:
        cap.release()
        raise ValueError(f"Invalid FPS for video: {video_path}")

    duration = end_time - start_time
    num_frames = max(2, int(duration * target_fps))

    # Calculate frame indices to extract
    start_frame = int(start_time * fps)
    end_frame = int(end_time * fps)
    duration_frames = end_frame - start_frame

    if duration_frames <= 0:
        cap.release()
        return []

    # Sample frames evenly across the duration
    if num_frames >= duration_frames:
        frame_indices = list(range(start_frame, end_frame + 1))
    else:
        frame_indices = [
            start_frame + int(i * duration_frames / (num_frames - 1))
            for i in range(num_frames - 1)
        ]
        frame_indices.append(end_frame)

    frames = []
    for frame_num in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
        ret, frame = cap.read()
        if ret:
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = PILImage.fromarray(frame_rgb)
            # Resize if needed (videos should already be 256x256)
            if img.size != (frame_size, frame_size):
                img = img.resize((frame_size, frame_size), PILImage.Resampling.LANCZOS)
            frames.append(img)

    cap.release()
    return frames


def process_csv_row(
    row: dict,
    videos_dir: str,
    eaf_dir: str,
    pose_dir: str,
    target_fps: float = 5
) -> dict | None:
    """
    Process a single CSV row and return a dataset entry.

    Uses a cascading approach for segmentation:
    1. First try pose-based segmentation (wrist above elbow heuristic)
    2. If pose covers entire file, fall back to EAF segmentation
    3. If neither works, use full video duration

    Args:
        row: CSV row dictionary
        videos_dir: Directory containing 256x256 videos
        eaf_dir: Directory containing EAF files
        pose_dir: Directory containing pose files
        target_fps: Target FPS for frame extraction

    Returns:
        Dictionary with dataset entry or None if processing failed
    """
    md5 = row['md5']
    video_path = os.path.join(videos_dir, f"{md5}.mp4")
    pose_path = os.path.join(pose_dir, f"{md5}.pose")
    eaf_path = os.path.join(eaf_dir, f"{md5}.eaf")

    # Check if video exists
    if not os.path.exists(video_path):
        return None

    # Cascading segmentation approach:
    # 1. Try pose-based segmentation first
    time_range = None
    if os.path.exists(pose_path):
        time_range = get_signing_time_range_from_pose(pose_path)

    # 2. If pose covers entire file (returns None), try EAF
    if time_range is None and os.path.exists(eaf_path):
        time_range = get_sign_time_range_from_eaf(eaf_path)

    # 3. Fall back to full video duration
    if time_range is not None:
        start_time, end_time = time_range
    else:
        try:
            start_time = 0.0
            end_time = get_video_duration(video_path)
        except Exception:
            return None

    # Validate time range
    if end_time <= start_time:
        return None

    # Extract frames
    try:
        frames = extract_frames_from_video(
            video_path, start_time, end_time, target_fps=target_fps
        )
    except Exception:
        return None

    if not frames:
        return None

    return {
        'file': row['file'],
        'start': round(start_time, 3),
        'end': round(end_time, 3),
        'text': row['text'],
        'images': frames
    }


def load_csv_data(csv_path: str) -> dict[str, list[dict]]:
    """
    Load CSV data and group by split.

    Returns:
        Dictionary mapping split names to lists of row dictionaries
    """
    splits = {'train': [], 'validation': [], 'test': []}

    with open(csv_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            split = row['split']
            if split in splits:
                splits[split].append(row)

    return splits


def _process_row_wrapper(args: tuple) -> dict | None:
    """Wrapper for process_csv_row to work with multiprocessing."""
    row, videos_dir, eaf_dir, pose_dir, target_fps = args
    return process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)


def create_subset_dataset(
    csv_path: str,
    videos_dir: str,
    eaf_dir: str,
    pose_dir: str,
    target_fps: float = 5,
    limit: int | None = None,
    num_workers: int | None = None
) -> DatasetDict:
    """
    Create a DatasetDict for a single subset (game or non-game).

    Args:
        csv_path: Path to the index.csv file
        videos_dir: Directory containing 256x256 videos
        eaf_dir: Directory containing EAF files
        pose_dir: Directory containing pose files
        target_fps: Target FPS for frame extraction
        limit: Optional limit on number of samples per split (for testing)
        num_workers: Number of parallel workers (default: CPU count)

    Returns:
        DatasetDict with train, validation, test splits
    """
    splits_data = load_csv_data(csv_path)

    if num_workers is None:
        num_workers = cpu_count()

    features = Features({
        'file': Value('string'),
        'start': Value('float32'),
        'end': Value('float32'),
        'text': Value('string'),
        'images': Sequence(Image())
    })

    dataset_splits = {}

    for split_name, rows in splits_data.items():
        if not rows:
            continue

        if limit is not None:
            rows = rows[:limit]

        # Prepare arguments for parallel processing
        args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in rows]

        processed_data = []

        if num_workers > 1:
            with Pool(num_workers) as pool:
                results = list(tqdm(
                    pool.imap(_process_row_wrapper, args_list, chunksize=100),
                    total=len(args_list),
                    desc=f"Processing {split_name}",
                    unit="sample"
                ))
            processed_data = [r for r in results if r is not None]
        else:
            for row in tqdm(rows, desc=f"Processing {split_name}", unit="sample"):
                result = process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)
                if result is not None:
                    processed_data.append(result)

        if processed_data:
            dataset_splits[split_name] = Dataset.from_list(
                processed_data,
                features=features
            )

    return DatasetDict(dataset_splits)


def create_popsign_dataset(
    popsign_dir: str,
    videos_dir: str,
    eaf_dir: str,
    pose_dir: str,
    output_dir: str,
    target_fps: float = 5,
    limit: int | None = None,
    num_workers: int | None = None
):
    """
    Create the complete PopSign HuggingFace dataset with game and non-game subsets.

    Args:
        popsign_dir: Root directory containing game/ and non-game/ subdirectories
        videos_dir: Directory containing 256x256 videos
        eaf_dir: Directory containing EAF files
        pose_dir: Directory containing pose files
        output_dir: Output directory for the dataset
        target_fps: Target FPS for frame extraction
        limit: Optional limit on samples per split (for testing)
        num_workers: Number of parallel workers
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    subsets = ['game', 'non-game']

    for subset in subsets:
        csv_path = os.path.join(popsign_dir, subset, 'index.csv')

        if not os.path.exists(csv_path):
            print(f"Warning: {csv_path} not found, skipping {subset}")
            continue

        print(f"\nProcessing {subset} subset...")

        dataset_dict = create_subset_dataset(
            csv_path=csv_path,
            videos_dir=videos_dir,
            eaf_dir=eaf_dir,
            pose_dir=pose_dir,
            target_fps=target_fps,
            limit=limit,
            num_workers=num_workers
        )

        # Save the subset
        subset_path = output_path / subset
        dataset_dict.save_to_disk(str(subset_path))
        print(f"Saved {subset} to {subset_path}")

    print(f"\nDataset saved to {output_dir}")


def _save_shard(shard_data: list, shard_idx: int, num_shards: int, split_name: str, subset_data_path: Path, features: Features) -> int:
    """Save a shard to parquet and return the number of samples saved."""
    if not shard_data:
        return 0
    dataset = Dataset.from_list(shard_data, features=features)
    parquet_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.parquet"
    dataset.to_parquet(str(parquet_path))
    count = len(shard_data)
    print(f"\n  Saved shard {shard_idx} ({count} samples) -> {parquet_path.name}", flush=True)
    del dataset
    return count


def save_as_parquet(
    popsign_dir: str,
    videos_dir: str,
    eaf_dir: str,
    pose_dir: str,
    output_dir: str,
    target_fps: float = 5,
    limit: int | None = None,
    shard_size: int = 10000,
    num_workers: int | None = None
):
    """
    Create the PopSign dataset and save in Parquet format for HuggingFace Hub upload.

    Saves shards incrementally to minimize RAM usage by processing in small batches.

    Directory structure:
    output_dir/
    ├── README.md
    └── data/
        ├── game/
        │   ├── train-00000-of-NNNNN.parquet
        │   └── ...
        └── non-game/
            └── ...

    Args:
        pose_dir: Directory containing pose files
        shard_size: Number of samples per parquet shard (default: 10000)
        num_workers: Number of parallel workers
    """
    output_path = Path(output_dir)
    data_path = output_path / "data"
    data_path.mkdir(parents=True, exist_ok=True)

    # Copy README.md to output directory (if not already there)
    readme_dest = output_path / "README.md"
    if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
        shutil.copy(README_TEMPLATE_PATH, readme_dest)
        print(f"Copied README.md to {readme_dest}")

    if num_workers is None:
        num_workers = cpu_count()

    # Process in small batches to limit memory - each batch is processed in parallel,
    # then results are accumulated until we have enough for a shard
    batch_size = min(1000, shard_size)  # Small batches to limit memory
    print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)

    features = Features({
        'file': Value('string'),
        'start': Value('float32'),
        'end': Value('float32'),
        'text': Value('string'),
        'images': Sequence(Image())
    })

    subsets = ['game', 'non-game']

    for subset in subsets:
        csv_path = os.path.join(popsign_dir, subset, 'index.csv')

        if not os.path.exists(csv_path):
            print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
            continue

        print(f"\nProcessing {subset} subset...", flush=True)

        splits_data = load_csv_data(csv_path)
        subset_data_path = data_path / subset
        subset_data_path.mkdir(parents=True, exist_ok=True)

        for split_name, rows in splits_data.items():
            if not rows:
                continue

            if limit is not None:
                rows = rows[:limit]

            total_rows = len(rows)
            num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
            print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)

            shard_data = []
            shard_idx = 0
            total_saved = 0
            total_processed = 0

            # Process in small batches to control memory
            pbar = tqdm(total=total_rows, desc=f"  {split_name}", unit="row")

            for batch_start in range(0, total_rows, batch_size):
                batch_end = min(batch_start + batch_size, total_rows)
                batch_rows = rows[batch_start:batch_end]

                # Process this batch
                if num_workers > 1:
                    args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
                    with Pool(num_workers) as pool:
                        results = pool.map(_process_row_wrapper, args_list)
                else:
                    results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]

                # Accumulate successful results
                for result in results:
                    if result is not None:
                        shard_data.append(result)

                        # Save shard when full
                        if len(shard_data) >= shard_size:
                            total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
                            shard_data = []
                            shard_idx += 1

                # Free batch memory
                del results
                total_processed += len(batch_rows)
                pbar.update(len(batch_rows))

            pbar.close()

            # Save any remaining data
            if shard_data:
                total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
                shard_idx += 1

            print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)

    print(f"\nDataset saved to {output_dir}", flush=True)
    print("\nTo upload to HuggingFace Hub:")
    print(f"  huggingface-cli upload sign/popsign-images {output_dir} .")


def _save_webdataset_shard(
    shard_data: list,
    shard_idx: int,
    num_shards: int,
    split_name: str,
    subset_data_path: Path,
    sample_id_offset: int,
    jpeg_quality: int
) -> int:
    """Save a shard to tar and return the number of samples saved."""
    if not shard_data:
        return 0

    tar_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.tar"

    with tarfile.open(tar_path, 'w') as tar:
        for i, sample in enumerate(shard_data):
            sample_id = f"{sample_id_offset + i:06d}"

            # Write metadata JSON
            metadata = {
                'file': sample['file'],
                'start': sample['start'],
                'end': sample['end'],
                'text': sample['text'],
                'num_frames': len(sample['images'])
            }
            json_data = json.dumps(metadata).encode('utf-8')
            json_info = tarfile.TarInfo(name=f"{sample_id}.json")
            json_info.size = len(json_data)
            tar.addfile(json_info, io.BytesIO(json_data))

            # Write all frames as JPEG bytes in a single pickle file
            frames_data = []
            for img in sample['images']:
                jpg_buffer = io.BytesIO()
                img.save(jpg_buffer, format='JPEG', quality=jpeg_quality)
                frames_data.append(jpg_buffer.getvalue())

            pyd_data = pickle.dumps(frames_data)
            pyd_info = tarfile.TarInfo(name=f"{sample_id}.pyd")
            pyd_info.size = len(pyd_data)
            tar.addfile(pyd_info, io.BytesIO(pyd_data))

    count = len(shard_data)
    print(f"\n  Saved shard {shard_idx} ({count} samples) -> {tar_path.name}", flush=True)
    return count


def save_as_webdataset(
    popsign_dir: str,
    videos_dir: str,
    eaf_dir: str,
    pose_dir: str,
    output_dir: str,
    target_fps: float = 5,
    limit: int | None = None,
    shard_size: int = 1000,
    num_workers: int | None = None,
    jpeg_quality: int = 90
):
    """
    Create the PopSign dataset and save in WebDataset format for HuggingFace Hub upload.

    Saves shards incrementally to minimize RAM usage.

    Directory structure:
    output_dir/
    ├── README.md
    └── data/
        ├── game/
        │   ├── train-00000-of-NNNNN.tar
        │   └── ...
        └── non-game/
            └── ...

    Each tar contains:
    - {sample_id:06d}.json  (metadata: file, start, end, text, num_frames)
    - {sample_id:06d}.pyd   (pickled list of JPEG bytes)

    Args:
        pose_dir: Directory containing pose files
        shard_size: Number of samples per tar shard (default: 1000)
        num_workers: Number of parallel workers
        jpeg_quality: JPEG quality for saved images (default: 90)
    """
    output_path = Path(output_dir)
    data_path = output_path / "data"
    data_path.mkdir(parents=True, exist_ok=True)

    # Copy README.md to output directory (if not already there)
    readme_dest = output_path / "README.md"
    if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
        shutil.copy(README_TEMPLATE_PATH, readme_dest)
        print(f"Copied README.md to {readme_dest}")

    if num_workers is None:
        num_workers = cpu_count()

    # Process in small batches to limit memory
    batch_size = min(1000, shard_size)
    print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)

    subsets = ['game', 'non-game']

    for subset in subsets:
        csv_path = os.path.join(popsign_dir, subset, 'index.csv')

        if not os.path.exists(csv_path):
            print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
            continue

        print(f"\nProcessing {subset} subset...", flush=True)

        splits_data = load_csv_data(csv_path)
        subset_data_path = data_path / subset
        subset_data_path.mkdir(parents=True, exist_ok=True)

        for split_name, rows in splits_data.items():
            if not rows:
                continue

            if limit is not None:
                rows = rows[:limit]

            total_rows = len(rows)
            num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
            print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)

            shard_data = []
            shard_idx = 0
            total_saved = 0
            sample_id_offset = 0

            # Process in small batches to control memory
            pbar = tqdm(total=total_rows, desc=f"  {split_name}", unit="row")

            for batch_start in range(0, total_rows, batch_size):
                batch_end = min(batch_start + batch_size, total_rows)
                batch_rows = rows[batch_start:batch_end]

                # Process this batch
                if num_workers > 1:
                    args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
                    with Pool(num_workers) as pool:
                        results = pool.map(_process_row_wrapper, args_list)
                else:
                    results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]

                # Accumulate successful results
                for result in results:
                    if result is not None:
                        shard_data.append(result)

                        # Save shard when full
                        if len(shard_data) >= shard_size:
                            total_saved += _save_webdataset_shard(
                                shard_data, shard_idx, num_shards, split_name,
                                subset_data_path, sample_id_offset, jpeg_quality
                            )
                            sample_id_offset += len(shard_data)
                            shard_data = []
                            shard_idx += 1

                # Free batch memory
                del results
                pbar.update(len(batch_rows))

            pbar.close()

            # Save any remaining data
            if shard_data:
                total_saved += _save_webdataset_shard(
                    shard_data, shard_idx, num_shards, split_name,
                    subset_data_path, sample_id_offset, jpeg_quality
                )
                shard_idx += 1

            print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)

    print(f"\nDataset saved to {output_dir}", flush=True)
    print("\nTo upload to HuggingFace Hub:")
    print(f"  huggingface-cli upload sign/popsign-images {output_dir} .")


def main():
    parser = argparse.ArgumentParser(
        description='Create PopSign HuggingFace dataset with images'
    )
    parser.add_argument(
        '--popsign-dir',
        type=str,
        default='some-path-to/popsign/v1',
        help='Root directory containing game/ and non-game/ subdirectories'
    )
    parser.add_argument(
        '--videos-dir',
        type=str,
        default='some-path-to-videos/256x256',
        help='Directory containing 256x256 videos named by MD5 hash'
    )
    parser.add_argument(
        '--eaf-dir',
        type=str,
        default='some-path-to-segments',
        help='Directory containing EAF segmentation files'
    )
    parser.add_argument(
        '--pose-dir',
        type=str,
        default='some-path-to-poses',
        help='Directory containing pose files for signing boundary detection'
    )
    parser.add_argument(
        '--output-dir',
        type=str,
        default='/shared/popsign-images',
        help='Output directory for the HuggingFace dataset'
    )
    parser.add_argument(
        '--fps',
        type=float,
        default=5,
        help='Target frames per second for frame extraction (default: 5)'
    )
    parser.add_argument(
        '--limit',
        type=int,
        default=None,
        help='Limit number of samples per split (for testing)'
    )
    parser.add_argument(
        '--format',
        type=str,
        choices=['webdataset', 'parquet', 'arrow'],
        default='parquet',
        help='Output format: webdataset (JPEG compressed), parquet, or arrow (for local use)'
    )
    parser.add_argument(
        '--shard-size',
        type=int,
        default=1000,
        help='Number of samples per shard (default: 1000)'
    )
    parser.add_argument(
        '--jpeg-quality',
        type=int,
        default=90,
        help='JPEG quality for WebDataset format (default: 90)'
    )
    parser.add_argument(
        '--workers',
        type=int,
        default=None,
        help='Number of parallel workers (default: CPU count)'
    )

    args = parser.parse_args()

    if args.format == 'webdataset':
        save_as_webdataset(
            popsign_dir=args.popsign_dir,
            videos_dir=args.videos_dir,
            eaf_dir=args.eaf_dir,
            pose_dir=args.pose_dir,
            output_dir=args.output_dir,
            target_fps=args.fps,
            limit=args.limit,
            shard_size=args.shard_size,
            num_workers=args.workers,
            jpeg_quality=args.jpeg_quality
        )
    elif args.format == 'parquet':
        save_as_parquet(
            popsign_dir=args.popsign_dir,
            videos_dir=args.videos_dir,
            eaf_dir=args.eaf_dir,
            pose_dir=args.pose_dir,
            output_dir=args.output_dir,
            target_fps=args.fps,
            limit=args.limit,
            shard_size=args.shard_size,
            num_workers=args.workers
        )
    else:
        create_popsign_dataset(
            popsign_dir=args.popsign_dir,
            videos_dir=args.videos_dir,
            eaf_dir=args.eaf_dir,
            pose_dir=args.pose_dir,
            output_dir=args.output_dir,
            target_fps=args.fps,
            limit=args.limit,
            num_workers=args.workers
        )


if __name__ == '__main__':
    main()