File size: 28,346 Bytes
44a7ed3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
import argparse
import glob
import math
import os
import re
from collections.abc import Sized
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple

import pyarrow.parquet as pq
from datasets import (
    Audio as HFAudio,
    Dataset,
    DatasetDict,
    Features,
    Image as HFImage,
    Video as HFVideo,
    load_dataset,
)
from tqdm import tqdm


_MEDIA_FEATURES = Features(
    {
        "image": HFImage(),
        "video": HFVideo(),
        "audio": HFAudio(),
    }
)
MEDIA_TYPE_COLUMNS = ("image", "video", "audio")
MEDIA_ROLES = ("media", "query", "candidate")
DEFAULT_ROW_GROUP_SIZE = 100
DEFAULT_MEDIA_ROWS_PER_SHARD = 5000
KNOWN_DATA_SPLITS = ("train", "test", "validation", "valid", "dev")


def resolve_split_output_dir(output_root, split_name: str, subset_name: str) -> Path:
    """Resolve the output dir for one subset of a split.

    Default layout mirrors the Hub repos: ``{output_root}/MVEB-{split}/{subset}``.
    Override the split root with env ``MVEB_TRAIN_DIR`` / ``MVEB_TEST_DIR``
    (e.g. point them at locally downloaded MVEB-train / MVEB-test repos).
    """
    override = os.environ.get(f"MVEB_{split_name.upper()}_DIR")
    base = Path(override) if override else Path(output_root) / f"MVEB-{split_name}"
    return base / subset_name


def _infer_collection_name(dir_path: str) -> str:
    """Infer collection label from path basename (e.g. ``test`` / ``train`` for Hub repo name)."""
    return os.path.basename(os.path.normpath(dir_path))


def _infer_data_split(path_like: str, default: str = "train") -> str:
    """Infer split name from path components, fallback to ``default``."""
    parts = [p.lower() for p in os.path.normpath(path_like).split(os.sep) if p]
    for part in reversed(parts):
        if part in KNOWN_DATA_SPLITS:
            return part
    return default


def infer_media_type(media_row: dict) -> Optional[str]:
    """Return which media column is set (``image`` / ``video`` / ``audio``)."""
    for column in MEDIA_TYPE_COLUMNS:
        if media_row.get(column) is not None:
            return column
    return None


def get_media_payload(media_row: dict):
    """Return the non-null media payload; raises if the row is empty."""
    media_type = infer_media_type(media_row)
    if media_type is None:
        raise ValueError("media row has no populated image/video/audio column")
    return media_row[media_type]


def _make_media_row(
    *,
    image=None,
    video=None,
    audio=None,
) -> dict:
    populated = [
        name
        for name, value in (("image", image), ("video", video), ("audio", audio))
        if value is not None
    ]
    if len(populated) != 1:
        raise ValueError(f"exactly one media column must be set, got {populated}")
    return {"image": image, "video": video, "audio": audio}


def _read_media_bytes(media_path: str) -> bytes:
    with open(media_path, "rb") as f:
        return f.read()


def _parse_size(size: str) -> int:
    size = size.strip().upper()
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([KMGT]?B)", size)
    if not m:
        raise ValueError(f"Invalid size string: {size!r}, e.g. 500MB or 1GB")
    value = float(m.group(1))
    unit = m.group(2)
    scale = {"B": 1, "KB": 1024, "MB": 1024**2, "GB": 1024**3, "TB": 1024**4}
    return int(value * scale[unit])


def _resolve_image_path(image_path: str, image_dir: str) -> str:
    if not image_path:
        raise ValueError("empty image_path")
    if os.path.isabs(image_path) and os.path.exists(image_path):
        return image_path
    candidate = os.path.join(image_dir, image_path)
    if os.path.exists(candidate):
        return candidate
    raise FileNotFoundError(
        f"Image not found: {image_path!r} (image_dir={image_dir!r})"
    )


def _discover_subsets(split_dir: str) -> List[str]:
    subsets: List[str] = []
    for name in sorted(os.listdir(split_dir)):
        if name == "images":
            continue
        sub_path = os.path.join(split_dir, name)
        if not os.path.isdir(sub_path):
            continue
        query_path = os.path.join(sub_path, "query.parquet")
        candidate_path = os.path.join(sub_path, "candidate.parquet")
        if os.path.exists(query_path) and os.path.exists(candidate_path):
            subsets.append(name)
    return subsets


def _collect_unique_paths(
    query_rows: Sequence[dict],
    candidate_rows: Sequence[dict],
) -> Tuple[List[str], Dict[str, int]]:
    path_to_index: Dict[str, int] = {}
    ordered_paths: List[str] = []

    def add_path(path: Optional[str]) -> None:
        if not path:
            return
        if path not in path_to_index:
            path_to_index[path] = len(ordered_paths)
            ordered_paths.append(path)

    for row in query_rows:
        add_path(row.get("image_path"))
    for row in candidate_rows:
        add_path(row.get("image_path"))

    return ordered_paths, path_to_index


def _rows_with_media_index(
    rows: Sequence[dict],
    path_to_index: Dict[str, int],
) -> List[dict]:
    converted: List[dict] = []
    for row in rows:
        new_row = {
            k: v
            for k, v in row.items()
            if k not in ("image_path", "media_type")
        }
        image_path = row.get("image_path")
        if image_path:
            new_row["media_index"] = path_to_index[image_path]
        elif "media_index" not in new_row:
            raise ValueError(f"row id={row.get('id')}: missing image_path and media_index")
        converted.append(new_row)
    return converted


def _load_media_rows(
    ordered_paths: Sequence[str],
    image_dir: str,
    desc: str = "load images",
    show_progress: bool = True,
) -> List[dict]:
    iterator = ordered_paths
    if show_progress:
        iterator = tqdm(ordered_paths, desc=desc)
    media_rows: List[dict] = []
    for rel_path in iterator:
        abs_path = _resolve_image_path(rel_path, image_dir)
        media_rows.append(
            _make_media_row(image={"bytes": _read_media_bytes(abs_path), "path": None})
        )
    return media_rows


def _estimate_num_shards_by_rows(
    media_items: Sized,
    media_rows_per_shard: int,
) -> int:
    """Shard count for ``media_items`` (media rows or their source paths)."""
    if media_rows_per_shard < 1:
        raise ValueError(
            f"media_rows_per_shard must be >= 1, got {media_rows_per_shard}"
        )
    num_items = len(media_items)
    if num_items == 0:
        return 1
    return max(1, math.ceil(num_items / media_rows_per_shard))


def _write_parquet(
    rows_or_ds: Sequence[dict] | Dataset,
    path: str,
    row_group_size: int,
    *,
    features: Optional[Features] = None,
) -> None:
    """Write parquet with explicit row groups (HF ``batch_size`` = rows per group)."""
    if row_group_size < 1:
        raise ValueError(f"row_group_size must be >= 1, got {row_group_size}")
    if isinstance(rows_or_ds, Dataset):
        ds = rows_or_ds
    elif features is not None:
        ds = Dataset.from_list(list(rows_or_ds), features=features)
    else:
        ds = Dataset.from_list(list(rows_or_ds))
    ds.to_parquet(path, batch_size=row_group_size)


def _media_shard_path(output_dir: str, shard_idx: int, num_shards: int) -> str:
    return os.path.join(
        output_dir,
        f"media-{shard_idx:05d}-of-{num_shards:05d}.parquet",
    )


def _write_one_media_shard(
    shard_idx: int,
    num_shards: int,
    shard_paths: Sequence[str],
    image_dir: str,
    output_dir: str,
    row_group_size: int,
) -> Tuple[int, int, str]:
    shard_rows = _load_media_rows(
        shard_paths,
        image_dir,
        show_progress=False,
    )
    shard = Dataset.from_list(shard_rows, features=_MEDIA_FEATURES)
    out_path = _media_shard_path(output_dir, shard_idx, num_shards)
    _write_parquet(shard, out_path, row_group_size)
    return shard_idx, len(shard_rows), out_path


def _write_media_shards(
    ordered_paths: Sequence[str],
    image_dir: str,
    output_dir: str,
    media_rows_per_shard: int,
    row_group_size: int,
    num_workers: int,
    *,
    desc: str = "media",
    show_progress: bool = True,
) -> int:
    os.makedirs(output_dir, exist_ok=True)
    num_shards = _estimate_num_shards_by_rows(ordered_paths, media_rows_per_shard)
    for old_path in glob.glob(os.path.join(output_dir, "media-*.parquet")):
        os.remove(old_path)

    shard_specs = []
    for shard_idx in range(num_shards):
        start = shard_idx * media_rows_per_shard
        end = min(start + media_rows_per_shard, len(ordered_paths))
        shard_specs.append((shard_idx, ordered_paths[start:end]))

    if num_workers < 1:
        raise ValueError(f"num_workers must be >= 1, got {num_workers}")

    if num_workers == 1 or num_shards == 1:
        for shard_idx, shard_paths in shard_specs:
            shard_rows = _load_media_rows(
                shard_paths,
                image_dir,
                desc=f"{desc} shard {shard_idx + 1}/{num_shards}",
                show_progress=show_progress,
            )
            shard = Dataset.from_list(shard_rows, features=_MEDIA_FEATURES)
            out_path = _media_shard_path(output_dir, shard_idx, num_shards)
            _write_parquet(shard, out_path, row_group_size)
        return num_shards

    workers = min(num_workers, num_shards)
    with ProcessPoolExecutor(max_workers=workers) as executor:
        futures = [
            executor.submit(
                _write_one_media_shard,
                shard_idx,
                num_shards,
                shard_paths,
                image_dir,
                output_dir,
                row_group_size,
            )
            for shard_idx, shard_paths in shard_specs
        ]
        iterator = as_completed(futures)
        if show_progress:
            iterator = tqdm(
                iterator,
                total=len(futures),
                desc=f"{desc} shards",
            )
        for future in iterator:
            future.result()

    return num_shards


def _write_readme(
    output_dir: str,
    dataset_name: str,
    data_split: str,
    num_media: int,
    num_query: int,
    num_candidate: int,
    query_feature_names: Sequence[str],
    candidate_feature_names: Sequence[str],
) -> None:
    readme = _render_subset_readme_yaml(
        config_name=dataset_name,
        path_prefix="",
        data_split=data_split,
        num_media=num_media,
        num_query=num_query,
        num_candidate=num_candidate,
        query_feature_names=query_feature_names,
        candidate_feature_names=candidate_feature_names,
        pretty_name=dataset_name,
    )
    with open(os.path.join(output_dir, "README.md"), "w", encoding="utf-8") as f:
        f.write(readme)


def _discover_packed_subsets(output_dir: str) -> List[str]:
    """Find packed subset folders under a split output root."""
    subsets: List[str] = []
    for name in sorted(os.listdir(output_dir)):
        sub_path = os.path.join(output_dir, name)
        if not os.path.isdir(sub_path):
            continue
        if not os.path.exists(os.path.join(sub_path, "query.parquet")):
            continue
        if not glob.glob(os.path.join(sub_path, "media-*.parquet")):
            continue
        subsets.append(name)
    return subsets


def _parquet_num_rows(parquet_path: str) -> int:
    return pq.read_metadata(parquet_path).num_rows


def _parquet_column_names(parquet_path: str) -> List[str]:
    return pq.read_schema(parquet_path).names


def _media_num_rows(subset_dir: str) -> int:
    media_files = sorted(glob.glob(os.path.join(subset_dir, "media-*.parquet")))
    if not media_files:
        raise FileNotFoundError(f"No media shards under {subset_dir}")
    return sum(_parquet_num_rows(path) for path in media_files)


def _hub_feature_yaml_lines(name: str, indent: str = "  ") -> str:
    inner = indent + "  "
    if name in ("pos_ids", "neg_ids", "pool_ids"):
        return f"{inner}- name: {name}\n{inner}  sequence: string"
    if name == "scores":
        return f"{inner}- name: {name}\n{inner}  sequence: float64"
    if name == "media_index":
        return f"{inner}- name: {name}\n{inner}  dtype: int64"
    return f"{inner}- name: {name}\n{inner}  dtype: string"


def _features_yaml_block(feature_names: Sequence[str], indent: str = "  ") -> str:
    return "\n".join(_hub_feature_yaml_lines(name, indent) for name in feature_names)


def _media_features_yaml() -> str:
    inner = "  "
    return (
        f"{inner}- name: image\n{inner}  dtype: image\n"
        f"{inner}- name: video\n{inner}  dtype: video\n"
        f"{inner}- name: audio\n{inner}  dtype: audio"
    )


def _role_config_name(subset_name: str, role: str) -> str:
    if role not in MEDIA_ROLES:
        raise ValueError(f"role must be one of {MEDIA_ROLES}, got {role!r}")
    return f"{subset_name}_{role}"


def _render_subset_readme_yaml(
    *,
    config_name: str,
    path_prefix: str,
    data_split: str,
    num_media: int,
    num_query: int,
    num_candidate: int,
    query_feature_names: Sequence[str],
    candidate_feature_names: Sequence[str],
    pretty_name: Optional[str] = None,
) -> str:
    media_path = f"{path_prefix}media-*.parquet" if path_prefix else "media-*.parquet"
    query_path = f"{path_prefix}query.parquet" if path_prefix else "query.parquet"
    candidate_path = f"{path_prefix}candidate.parquet" if path_prefix else "candidate.parquet"
    title_line = f"pretty_name: {pretty_name}\n" if pretty_name else ""
    media_config = _role_config_name(config_name, "media")
    query_config = _role_config_name(config_name, "query")
    candidate_config = _role_config_name(config_name, "candidate")
    return (
        "---\n"
        f"{title_line}"
        "configs:\n"
        f"- config_name: {media_config}\n"
        "  data_files:\n"
        f"  - split: {data_split}\n"
        f"    path: {media_path}\n"
        f"- config_name: {query_config}\n"
        "  data_files:\n"
        f"  - split: {data_split}\n"
        f"    path: {query_path}\n"
        f"- config_name: {candidate_config}\n"
        "  data_files:\n"
        f"  - split: {data_split}\n"
        f"    path: {candidate_path}\n"
        "---\n"
    )


def _collect_subset_hub_metadata(
    subset_name: str,
    subset_dir: str,
) -> dict:
    """Build hub README metadata for one subset config (splits: media/query/candidate)."""
    query_path = os.path.join(subset_dir, "query.parquet")
    candidate_path = os.path.join(subset_dir, "candidate.parquet")
    return {
        "config_name": subset_name,
        "num_media": _media_num_rows(subset_dir),
        "num_query": _parquet_num_rows(query_path),
        "num_candidate": _parquet_num_rows(candidate_path),
        "query_feature_names": _parquet_column_names(query_path),
        "candidate_feature_names": _parquet_column_names(candidate_path),
    }


def build_hub_readme(
    output_dir: str,
    *,
    data_split: Optional[str] = None,
    dataset_title: Optional[str] = None,
    subsets: Optional[Sequence[str]] = None,
) -> str:
    """
    Write a top-level HuggingFace Hub README for all packed subsets under ``output_dir``.

    One config per subset; HF splits are ``media`` / ``query`` / ``candidate``.
    Use separate repos or directories (e.g. ``.../test``, ``.../train``) for collections.
    """
    output_dir = os.path.abspath(output_dir)
    subset_names = list(subsets) if subsets else _discover_packed_subsets(output_dir)
    if not subset_names:
        raise ValueError(f"No packed subsets found under {output_dir}")

    title = dataset_title or _infer_collection_name(output_dir)
    split_name = data_split or _infer_data_split(output_dir)
    config_blocks: List[str] = []
    for subset_name in subset_names:
        _ = _collect_subset_hub_metadata(subset_name, os.path.join(output_dir, subset_name))
        config_blocks.append(
            f"- config_name: {_role_config_name(subset_name, 'media')}\n"
            "  data_files:\n"
            f"  - split: {split_name}\n"
            f"    path: {subset_name}/media-*.parquet\n"
            f"- config_name: {_role_config_name(subset_name, 'query')}\n"
            "  data_files:\n"
            f"  - split: {split_name}\n"
            f"    path: {subset_name}/query.parquet\n"
            f"- config_name: {_role_config_name(subset_name, 'candidate')}\n"
            "  data_files:\n"
            f"  - split: {split_name}\n"
            f"    path: {subset_name}/candidate.parquet"
        )

    readme = (
        "---\n"
        f"pretty_name: {title}\n"
        "configs:\n"
        + "\n".join(config_blocks)
        + "\n---\n"
    )
    readme_path = os.path.join(output_dir, "README.md")
    with open(readme_path, "w", encoding="utf-8") as f:
        f.write(readme)
    return readme_path


def load_hub_subset(
    repo_or_path: str,
    subset_name: str,
    role: str,
    data_split: Optional[str] = None,
) -> Dataset:
    """Load one role dataset for a subset (config: ``{subset}_{role}``, split inferred from path)."""
    if role not in MEDIA_ROLES:
        raise ValueError(f"role must be one of {MEDIA_ROLES}, got {role!r}")
    config_name = _role_config_name(subset_name, role)
    split_name = data_split or _infer_data_split(repo_or_path)
    return load_dataset(repo_or_path, config_name, split=split_name)


def load_hub_subset_dict(
    repo_or_path: str,
    subset_name: str,
    data_split: Optional[str] = None,
) -> DatasetDict:
    """Load media / query / candidate datasets for one subset."""
    return DatasetDict(
        {
            "media": load_hub_subset(repo_or_path, subset_name, "media", data_split=data_split),
            "query": load_hub_subset(repo_or_path, subset_name, "query", data_split=data_split),
            "candidate": load_hub_subset(
                repo_or_path, subset_name, "candidate", data_split=data_split
            ),
        }
    )


def pack_dataset_with_media(
    query_annotations: Sequence[dict],
    candidate_annotations: Sequence[dict],
    image_dir: str,
    output_dir: str,
    *,
    max_shard_size: str = "500MB",
    media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD,
    num_workers: int = 1,
    row_group_size: int = DEFAULT_ROW_GROUP_SIZE,
    dataset_name: Optional[str] = None,
    data_split: str = "train",
    write_subset_readme: bool = True,
    show_progress: bool = True,
) -> Dict[str, int]:
    query_rows = list(query_annotations)
    candidate_rows = list(candidate_annotations)

    if not query_rows and not candidate_rows:
        raise ValueError("query_annotations and candidate_annotations are both empty")

    ordered_paths, path_to_index = _collect_unique_paths(query_rows, candidate_rows)
    if not ordered_paths:
        raise ValueError("No image_path found in query/candidate annotations")

    name = dataset_name or os.path.basename(os.path.normpath(output_dir))
    # Deprecated in favor of fixed rows-per-shard; kept for CLI compatibility.
    _ = max_shard_size

    os.makedirs(output_dir, exist_ok=True)
    num_shards = _write_media_shards(
        ordered_paths,
        image_dir,
        output_dir,
        media_rows_per_shard,
        row_group_size,
        num_workers,
        desc=f"{name} images",
        show_progress=show_progress,
    )

    query_out = _rows_with_media_index(query_rows, path_to_index)
    candidate_out = _rows_with_media_index(candidate_rows, path_to_index)

    _write_parquet(query_out, os.path.join(output_dir, "query.parquet"), row_group_size)
    _write_parquet(
        candidate_out, os.path.join(output_dir, "candidate.parquet"), row_group_size
    )

    if write_subset_readme:
        _write_readme(
            output_dir=output_dir,
            dataset_name=name,
            data_split=data_split,
            num_media=len(ordered_paths),
            num_query=len(query_out),
            num_candidate=len(candidate_out),
            query_feature_names=list(query_out[0].keys()) if query_out else [],
            candidate_feature_names=list(candidate_out[0].keys()) if candidate_out else [],
        )

    return {
        "num_media": len(ordered_paths),
        "num_query": len(query_out),
        "num_candidate": len(candidate_out),
        "num_shards": num_shards,
    }


def pack_subset_dir(
    subset_input_dir: str,
    subset_output_dir: str,
    image_dir: str,
    *,
    subset_name: Optional[str] = None,
    max_shard_size: str = "500MB",
    media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD,
    num_workers: int = 1,
    row_group_size: int = DEFAULT_ROW_GROUP_SIZE,
    data_split: str = "train",
    write_subset_readme: bool = True,
    show_progress: bool = True,
) -> Dict[str, int]:
    query_path = os.path.join(subset_input_dir, "query.parquet")
    candidate_path = os.path.join(subset_input_dir, "candidate.parquet")
    if not os.path.exists(query_path):
        raise FileNotFoundError(f"Missing {query_path}")
    if not os.path.exists(candidate_path):
        raise FileNotFoundError(f"Missing {candidate_path}")

    query_rows = pq.read_table(query_path).to_pylist()
    candidate_rows = pq.read_table(candidate_path).to_pylist()

    return pack_dataset_with_media(
        query_rows,
        candidate_rows,
        image_dir=image_dir,
        output_dir=subset_output_dir,
        max_shard_size=max_shard_size,
        media_rows_per_shard=media_rows_per_shard,
        num_workers=num_workers,
        row_group_size=row_group_size,
        dataset_name=subset_name or os.path.basename(subset_input_dir),
        data_split=data_split,
        write_subset_readme=write_subset_readme,
        show_progress=show_progress,
    )


def pack_split_dir(
    input_dir: str,
    output_dir: str,
    *,
    image_dir: Optional[str] = None,
    max_shard_size: str = "500MB",
    media_rows_per_shard: int = DEFAULT_MEDIA_ROWS_PER_SHARD,
    num_workers: int = 1,
    row_group_size: int = DEFAULT_ROW_GROUP_SIZE,
    subsets: Optional[Sequence[str]] = None,
    write_subset_readme: bool = True,
    write_hub_readme: bool = True,
    hub_dataset_title: Optional[str] = None,
    show_progress: bool = True,
) -> Dict[str, Dict[str, int]]:
    """
    Iterate all subsets under a split directory and pack each to
    ``{output_dir}/{subset_name}/``.
    """
    input_dir = os.path.abspath(input_dir)
    output_dir = os.path.abspath(output_dir)
    image_root = os.path.abspath(image_dir or input_dir)
    split_name = _infer_data_split(input_dir)

    subset_names = list(subsets) if subsets else _discover_subsets(input_dir)
    if not subset_names:
        raise ValueError(f"No subsets with query/candidate parquet found under {input_dir}")

    os.makedirs(output_dir, exist_ok=True)
    all_stats: Dict[str, Dict[str, int]] = {}

    subset_iter = subset_names
    if show_progress:
        subset_iter = tqdm(subset_names, desc="subsets")

    for subset_name in subset_iter:
        subset_input = os.path.join(input_dir, subset_name)
        subset_output = os.path.join(output_dir, subset_name)
        stats = pack_subset_dir(
            subset_input,
            subset_output,
            image_dir=image_root,
            subset_name=subset_name,
            max_shard_size=max_shard_size,
            media_rows_per_shard=media_rows_per_shard,
            num_workers=num_workers,
            row_group_size=row_group_size,
            data_split=split_name,
            write_subset_readme=write_subset_readme,
            show_progress=show_progress,
        )
        all_stats[subset_name] = stats
        if show_progress and not isinstance(subset_iter, tqdm):
            print(
                f"[{subset_name}] media={stats['num_media']} "
                f"({stats['num_shards']} shards), "
                f"query={stats['num_query']}, candidate={stats['num_candidate']}"
            )

    if write_hub_readme and all_stats:
        hub_path = build_hub_readme(
            output_dir,
            data_split=split_name,
            dataset_title=hub_dataset_title,
            subsets=list(all_stats.keys()),
        )
        if show_progress:
            print(f"Hub README: {hub_path}")
    return all_stats


def _build_argparser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="Pack all subsets under a split dir into media_index format.",
    )
    parser.add_argument(
        "--input-dir",
        help="Split directory, e.g. data/preprocess/Identity/test",
    )
    parser.add_argument(
        "--output-dir",
        required=True,
        help="Output root; each subset is written to {output_dir}/{subset_name}/",
    )
    parser.add_argument(
        "--image-dir",
        default=None,
        help="Root for relative image_path values (defaults to input-dir)",
    )
    parser.add_argument(
        "--max-shard-size",
        default="500MB",
        help=(
            "Deprecated. Previously used for byte-based media shard sizing; "
            "kept for compatibility."
        ),
    )
    parser.add_argument(
        "--media-rows-per-shard",
        type=int,
        default=DEFAULT_MEDIA_ROWS_PER_SHARD,
        help=f"Fixed number of media rows per shard (default: {DEFAULT_MEDIA_ROWS_PER_SHARD})",
    )
    parser.add_argument(
        "--num-workers",
        type=int,
        default=4,
        help="Number of worker processes for media shard writing (default: 1)",
    )
    parser.add_argument(
        "--row-group-size",
        type=int,
        default=DEFAULT_ROW_GROUP_SIZE,
        help=(
            "Rows per parquet row group for media/query/candidate "
            f"(default: {DEFAULT_ROW_GROUP_SIZE}, same as colpali_train_set)"
        ),
    )
    parser.add_argument(
        "--no-subset-readme",
        action="store_true",
        help="Do not write per-subset README.md (Hub root README only)",
    )
    parser.add_argument(
        "--no-hub-readme",
        action="store_true",
        help="Do not write top-level Hub README.md under output-dir",
    )
    parser.add_argument(
        "--hub-readme-only",
        action="store_true",
        help="Only (re)generate top-level Hub README from existing packed subsets",
    )
    parser.add_argument(
        "--hub-dataset-title",
        default=None,
        help="pretty_name for top-level Hub README (default: output-dir basename)",
    )
    parser.add_argument(
        "--subsets",
        nargs="*",
        default=None,
        help="Process only these subset names (default: all under input-dir)",
    )
    parser.add_argument(
        "--no-progress",
        action="store_true",
        help="Disable progress bars",
    )
    return parser


def main() -> None:
    args = _build_argparser().parse_args()
    if args.hub_readme_only:
        if not args.output_dir:
            raise SystemExit("--output-dir is required with --hub-readme-only")
        hub_path = build_hub_readme(
            args.output_dir,
            data_split=_infer_data_split(args.output_dir),
            dataset_title=args.hub_dataset_title,
            subsets=args.subsets,
        )
        print(f"Hub README written: {hub_path}")
        return

    if not args.input_dir:
        raise SystemExit("--input-dir is required unless --hub-readme-only is set")
    if not args.output_dir:
        raise SystemExit("--output-dir is required")
    all_stats = pack_split_dir(
        input_dir=args.input_dir,
        output_dir=args.output_dir,
        image_dir=args.image_dir,
        max_shard_size=args.max_shard_size,
        media_rows_per_shard=args.media_rows_per_shard,
        num_workers=args.num_workers,
        row_group_size=args.row_group_size,
        subsets=args.subsets,
        write_subset_readme=not args.no_subset_readme,
        write_hub_readme=not args.no_hub_readme,
        hub_dataset_title=args.hub_dataset_title,
        show_progress=not args.no_progress,
    )
    print(f"Done: {len(all_stats)} subsets -> {args.output_dir}")
    for subset_name, stats in all_stats.items():
        print(
            f"  {subset_name}: media={stats['num_media']} "
            f"({stats['num_shards']} shards), "
            f"query={stats['num_query']}, candidate={stats['num_candidate']}"
        )


if __name__ == "__main__":
    main()