File size: 48,644 Bytes
2f92e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
#!/usr/bin/env python3
"""Rebuild OpenEmbed training shards from released records (text sets, and image sets via pinned source pointers).

Each dataset folder ``<category>/<name>/`` holds set.json, records.parquet (every stored field of every training
record; images as pointers into a pinned public source, with the sha256 and length of our training bytes),
filters.parquet and shards.parquet (md5 / crc32c per shard). This script re-creates every record (tf.train.Example,
RecordV2 schema of the training code), writes the TFRecord shards and checks each record's sha256 and each shard's
md5 and crc32c. Text sets need nothing else, except a few released without their texts (set.json "text_source"),
whose texts are fetched from the pinned public source; image sets fetch their source files from the pinned revision. The few
images that no public source reproduces ship in the set's own folder (a ``local_tar_member`` pointer with
``"base": "set"`` names a tar file relative to that folder) and are read from there.

    pip install pyarrow huggingface_hub crc32c Pillow==12.3.0
    python tools/openembed_data/rebuild_shards.py --out shards/ --sets text/allnli
    python tools/openembed_data/rebuild_shards.py --no-write --set-dir text/allnli

Provenance. Each record names the shard and record of the earlier conversion it came from. Our training shards carry
our internal storage location in that string; the release writes ``openembed://...`` instead, so a rebuild equals our
training shards in every other byte and is checked against the ``*_public`` values. Given the internal prefixes
(OPENEMBED_PROVENANCE_MAP, a JSON list of [public prefix, internal prefix] pairs, with ``--check train``) the
rebuild is byte-identical to the training shards.
"""
from __future__ import annotations

import argparse
import base64
import collections
import concurrent.futures as cf
import hashlib
import io
import json
import os
import shutil
import struct
import sys
import tempfile
import time

FIELDS = (
    ("record_key", "int", "scalar"), ("dataset_id", "str", "scalar"), ("wemm_type", "str", "scalar"),
    ("task_subtype", "str", "scalar"), ("modality_sig", "str", "scalar"), ("query_image", "bytes", "scalar"),
    ("query_text", "str", "scalar"), ("instruction", "str", "scalar"), ("target_image", "bytes", "scalar"),
    ("target_text", "str", "scalar"), ("neg_texts", "str", "list"), ("neg_images", "bytes", "list"),
    ("neg_scores", "float", "list"), ("pos_score", "float", "scalar"), ("pos_rank", "int", "scalar"),
    ("graded_score", "float", "scalar"), ("target_key", "int", "scalar"), ("group_key", "int", "scalar"),
    ("license", "str", "scalar"), ("provenance", "str", "scalar"),
)
PILLOW_FOR_REENCODING = "12.3.0"     # the version that reproduces our converters' JPEG bytes
SCALARS = ("record_key", "dataset_id", "wemm_type", "task_subtype", "modality_sig", "query_text", "instruction",
           "target_text", "pos_score", "pos_rank", "graded_score", "target_key", "group_key", "license")


# ----------------------------------------------------------------------------------------------- CRC-32C, framing
def _crc32c_backend():
    try:
        import crc32c as _c
        return lambda data, value=0: _c.crc32c(data, value), "crc32c"
    except ImportError:
        pass
    try:
        import google_crc32c as _g
        return lambda data, value=0: _g.extend(value, data), "google-crc32c"
    except ImportError:
        pass
    table = []
    for i in range(256):
        c = i
        for _ in range(8):
            c = (c >> 1) ^ 0x82F63B78 if c & 1 else c >> 1
        table.append(c)

    def slow(data, value=0):
        c = value ^ 0xFFFFFFFF
        for b in bytes(data):
            c = table[(c ^ b) & 0xFF] ^ (c >> 8)
        return c ^ 0xFFFFFFFF
    return slow, "pure-python (slow)"


CRC32C, CRC32C_BACKEND = _crc32c_backend()


def masked_crc32c(data: bytes) -> int:
    c = CRC32C(data)
    return (((c >> 15) | (c << 17)) + 0xA282EAD8) & 0xFFFFFFFF


def frame_record(payload: bytes) -> bytes:
    ln = struct.pack("<Q", len(payload))
    return ln + struct.pack("<I", masked_crc32c(ln)) + payload + struct.pack("<I", masked_crc32c(payload))


def _varint(n: int) -> bytes:
    if n < 0:
        n += 1 << 64
    out = bytearray()
    while True:
        b = n & 0x7F
        n >>= 7
        if n:
            out.append(b | 0x80)
        else:
            out.append(b)
            return bytes(out)


def _ld(field: int, payload: bytes) -> bytes:
    return _varint((field << 3) | 2) + _varint(len(payload)) + payload


def _feature(kind: str, values: list) -> bytes:
    if kind in ("str", "bytes"):
        return _ld(1, b"".join(_ld(1, v.encode("utf-8") if isinstance(v, str) else bytes(v)) for v in values))
    if kind == "float":
        return _ld(2, _ld(1, struct.pack(f"<{len(values)}f", *values)) if values else b"")
    if kind == "int":
        return _ld(3, _ld(1, b"".join(_varint(int(v)) for v in values)) if values else b"")
    raise ValueError(kind)


def encode_record(rec: dict) -> bytes:
    """RecordV2 field mapping -> serialized tf.train.Example (features sorted by name, packed numeric lists)."""
    entries = []
    for name, kind, card in sorted(FIELDS):
        v = rec[name]
        entries.append(_ld(1, _ld(1, name.encode("utf-8")) + _ld(2, _feature(kind, [v] if card == "scalar" else list(v)))))
    return _ld(1, b"".join(entries))


# ----------------------------------------------------------------------------------------------- image sources
class Sources:
    """Fetches image bytes from pinned sources; each source file is downloaded once per process."""

    def __init__(self, cache_dir: str, set_dir: str | None = None):
        self.cache_dir = cache_dir
        self.set_dir = set_dir                  # the dataset's folder, for images shipped in it ("base": "set")
        self.files: dict[tuple, str] = {}
        self.parquet: dict[str, object] = {}
        self.zips: dict[str, object] = {}
        self.tars: dict[str, dict] = {}
        self.columns: "collections.OrderedDict" = collections.OrderedDict()   # (file, row group, column) -> cells
        self.downloaded = 0

    def path(self, src: dict) -> str:
        key = (src.get("repo"), src.get("revision"), src.get("file"), src.get("url"), src.get("base"))
        p = self.files.get(key)
        if p is None:
            if src["type"].startswith("hf_"):
                local = os.path.join(self.cache_dir, src["repo"].replace("/", "__"), src["file"])
                if os.path.isfile(local):                 # already in the cache folder (downloaded or copied)
                    p = local
                else:
                    from huggingface_hub import hf_hub_download
                    p = hf_hub_download(src["repo"], src["file"], repo_type="dataset", revision=src["revision"],
                                        local_dir=os.path.join(self.cache_dir, src["repo"].replace("/", "__")))
                    self.downloaded += os.path.getsize(p)
            elif src["type"] == "local_tar_member" and src.get("base") == "set":   # shipped in the set's folder
                if not self.set_dir:
                    raise ValueError(f"{src['file']}: the pointer names a file in the dataset's folder; none given")
                p = os.path.join(self.set_dir, src["file"])
                if not os.path.exists(p):
                    raise FileNotFoundError(f"{p}: this file is part of the dataset's folder; download the whole folder")
            elif src["type"] in ("local_tar_member", "archive_member"):
                p = os.path.join(self.cache_dir, src["file"])
                if not os.path.exists(p):
                    raise FileNotFoundError(f"{p}: put the official file {src['file']} here ({src.get('url', '')})")
            else:
                raise ValueError(f"unknown source type {src['type']}")
            self.files[key] = p
        return p

    def raw(self, src: dict) -> bytes:
        t = src["type"]
        if t == "hf_zip_member":
            import zipfile
            p = self.path(src)
            z = self.zips.get(p) or self.zips.setdefault(p, zipfile.ZipFile(p))
            return z.read(src["member"])
        if t == "hf_parquet_cell":
            import bisect
            import pyarrow.parquet as pq
            p = self.path(src)
            ent = self.parquet.get(p)
            if ent is None:
                pf = pq.ParquetFile(p)
                starts, n = [], 0
                for i in range(pf.metadata.num_row_groups):
                    starts.append(n)
                    n += pf.metadata.row_group(i).num_rows
                ent = self.parquet[p] = {"pf": pf, "starts": starts}
            rg = bisect.bisect_right(ent["starts"], src["row"]) - 1        # row: index in the file
            key = (p, rg, src["column"])
            col = self.columns.get(key)
            if col is None:                # a row group's column can be the whole file (one row group of ~1 GB);
                while len(self.columns) >= 1:          # fetches come sorted by file and row, so one at a time is enough
                    self.columns.popitem(last=False)
                col = self.columns[key] = ent["pf"].read_row_group(rg, columns=[src["column"]]).column(0)
            else:
                self.columns.move_to_end(key)
            cell = col[src["row"] - ent["starts"][rg]].as_py()
            for k in src.get("path", []):
                cell = cell[k]
            return cell if isinstance(cell, bytes) else bytes(cell)
        if t == "archive_member":
            return self.archive_member(src)
        if t == "hf_arrow_cell":                            # a datasets save_to_disk file (Arrow IPC stream)
            import pyarrow as pa
            p = self.path(src)
            ent = self.parquet.get(p)
            if ent is None:
                if len(self.parquet) > 4:
                    self.parquet.clear()
                ent = self.parquet[p] = {"table": pa.ipc.open_stream(pa.memory_map(p)).read_all()}
            cell = ent["table"].column(src["column"])[src["row"]].as_py()
            for k in src.get("path", []):
                cell = cell[k]
            return cell if isinstance(cell, bytes) else bytes(cell)
        if t == "local_tar_member":
            return self.tar_member(self.path(src), src["member"], src.get("offset"), src.get("size"))
        raise ValueError(f"unknown source type {t}")

    def archive_member(self, src: dict) -> bytes:
        """A member of a published archive: read from the archive in the cache folder (zip, or uncompressed tar), or
        from its extracted copy (<cache>/<member> or <cache>/<archive name without extension>/<member>)."""
        name, member = src["archive"], src["member"]
        p = os.path.join(self.cache_dir, name)
        if os.path.isfile(p):
            if name.endswith(".zip"):
                import zipfile
                z = self.zips.get(p) or self.zips.setdefault(p, zipfile.ZipFile(p))
                return z.read(member)
            if name.endswith(".tar"):
                return self.tar_member(p, member, None, None)
        stem = name
        for ext in (".tar.gz", ".tgz", ".tar", ".zip"):
            if stem.endswith(ext):
                stem = stem[: -len(ext)]
                break
        for q in (os.path.join(self.cache_dir, member), os.path.join(self.cache_dir, stem, member)):
            if os.path.isfile(q):
                with open(q, "rb") as fh:
                    return fh.read()
        raise FileNotFoundError(f"{member}: put {name} in {self.cache_dir} (a zip or an uncompressed tar is read as "
                                f"is; extract a compressed tar there): {src.get('how', '')}")

    def tar_member(self, p: str, member: str, off, size) -> bytes:
        """A tar member: at its recorded data offset when the header there names it, else by a name index."""
        ent = self.tars.get(p)
        if ent is None:
            ent = self.tars[p] = {"fh": open(p, "rb"), "index": None}
        fh = ent["fh"]
        if off is not None and size is not None and off >= 512:
            fh.seek(off - 512)                     # the member's header block precedes its data
            hdr = fh.read(512)
            name = hdr[:100].split(b"\0", 1)[0].decode("utf-8", "replace")
            prefix = hdr[345:500].split(b"\0", 1)[0].decode("utf-8", "replace") if hdr[257:263] == b"ustar\x00" else ""
            if (prefix + "/" + name if prefix else name) == member:
                return fh.read(size)
        if ent["index"] is None:                   # another copy of the archive: find the member by name
            import tarfile
            with tarfile.open(p) as tf:
                ent["index"] = {m.name: (m.offset_data, m.size) for m in tf if m.isfile()}
        off, size = ent["index"][member]
        fh.seek(off)
        return fh.read(size)

    def video_frames(self, src: dict, tr: dict) -> list:
        """The k frames our uCO3D converter took from one video (PyAV decode at the centres of k equal segments,
        RGB, LANCZOS downscale to at most max_pixels, JPEG); the last video's frames are kept."""
        key = (src.get("repo"), src.get("file"), src.get("member"), tr["k"], tr["max_pixels"])
        if getattr(self, "_video", (None,))[0] == key:
            return self._video[1]
        import av
        from PIL import Image
        data, k, images = self.raw(src), int(tr["k"]), []
        with av.open(io.BytesIO(data)) as container:
            stream = container.streams.video[0]
            tb = float(stream.time_base) if stream.time_base else 0.0
            duration = float(stream.duration * stream.time_base) if stream.duration and tb else \
                (container.duration / 1e6 if container.duration else 0.0)
            if duration > 0 and tb > 0:
                for j in range(k):
                    t = (j + 0.5) * duration / k
                    container.seek(int(t / tb), stream=stream, backward=True, any_frame=False)
                    for f in container.decode(stream):
                        if f.pts is None or f.pts * tb >= t - 1e-3:
                            images.append(f.to_image())
                            break
        if not images:                                       # no usable timing: decode in order
            with av.open(io.BytesIO(data)) as container:
                frames = list(container.decode(container.streams.video[0]))
            picks = sorted({min(len(frames) - 1, int((j + 0.5) * len(frames) / k)) for j in range(k)}) if frames else []
            images = [frames[q].to_image() for q in picks]
        out = []
        for im in images:
            im = im.convert("RGB")
            w, h = im.size
            if w * h > tr["max_pixels"]:
                f = (tr["max_pixels"] / (w * h)) ** 0.5
                im = im.resize((max(2, int(w * f)), max(2, int(h * f))), Image.LANCZOS)
            buf = io.BytesIO()
            im.save(buf, format="JPEG", **tr.get("jpeg", {}))
            out.append(buf.getvalue())
        self._video = (key, out)
        return out

    def image(self, src: dict) -> bytes:
        tr = src.get("transform") or {"op": "none"}
        if tr["op"] == "video_frame":
            return self.video_frames(src, tr)[int(tr["index"])]
        b = self.raw(src)
        if tr["op"] == "none":
            return b
        if tr["op"] == "pil_jpeg":
            import PIL
            from PIL import Image
            if PIL.__version__ != PILLOW_FOR_REENCODING and not getattr(Sources, "_warned", False):
                Sources._warned = True
                print(f"warning: images are re-encoded with Pillow {PIL.__version__}; the recorded bytes were made with "
                      f"Pillow {PILLOW_FOR_REENCODING} (pip install Pillow=={PILLOW_FOR_REENCODING}), other versions can "
                      f"give other bytes and fail the sha256 check", file=sys.stderr, flush=True)
            im = Image.open(io.BytesIO(b))
            if tr.get("exif_transpose") and im.getexif().get(0x0112) is not None:
                from PIL import ImageOps                     # as the datasets library decodes images: EXIF
                im.load()                                    # orientation applied when the tag is present
                im = ImageOps.exif_transpose(im)
            if tr.get("mode"):
                im = im.convert(tr["mode"])
            if tr.get("crop"):                               # (x0, y0, x1, y1), after the mode conversion
                im = im.crop(tuple(int(v) for v in tr["crop"]))
            out = io.BytesIO()
            im.save(out, format="JPEG", **tr.get("save", {}))
            return out.getvalue()
        if tr["op"] == "pil_rgba_on_white_png":           # MapQA: RGBA composited on white, saved as PNG
            from PIL import Image
            with Image.open(io.BytesIO(b)) as im:
                im = im.convert("RGBA")
                rgb = Image.new("RGB", im.size, tuple(tr.get("background", (255, 255, 255))))
                rgb.paste(im, mask=im.split()[3])
            out = io.BytesIO()
            rgb.save(out, format="PNG")
            return out.getvalue()
        raise ValueError(f"unknown transform {tr['op']}")


# ----------------------------------------------------------------------------------------------- rebuild
def _b64(b: bytes) -> str:
    return base64.b64encode(b).decode()


def to_train(p: str, pmap: list) -> str:
    """Public provenance -> training provenance: every occurrence of each public prefix, longest prefix first."""
    for public, internal in sorted(pmap, key=lambda x: -len(x[0])):
        p = p.replace(public, internal)
    return p


def order_key(srcs: "Sources", src_json: str) -> tuple:
    """Fetch order: by source file, then by position in it (zip entry offset, parquet column and row, member)."""
    try:
        src = json.loads(src_json)
        pos = src.get("row", src.get("offset", 0))
        if src["type"] in ("hf_zip_member",) or (src["type"] == "archive_member" and src["archive"].endswith(".zip")):
            p = srcs.path(src) if src["type"] == "hf_zip_member" else os.path.join(srcs.cache_dir, src["archive"])
            if os.path.isfile(p):
                import zipfile
                z = srcs.zips.get(p) or srcs.zips.setdefault(p, zipfile.ZipFile(p))
                pos = z.getinfo(src["member"]).header_offset
        return (src.get("repo") or "", src.get("file") or src.get("archive") or "", src.get("column") or "",
                pos if isinstance(pos, int) else 0, src.get("member") or "", int((src.get("transform") or {}).get("index", 0)))
    except Exception:  # noqa: BLE001 - an unusual pointer is fetched last; image() reports its problem
        return ("~", "", "", 0, "", 0)


# ----------------------------------------------------------------------------------------------- shared-source pre-pass
# Records are spread over the shards in random order, so in a hard-negative page set every shard touches most row groups
# of the source parquet files (colpali_pdf_hn: 255 of 1,235 row groups per shard, 937 GB read for a 55 GB source), and
# the 4 frames of a uCO3D video sit in 4 shards (each video read and decoded 4 times). For such sets a pre-pass fetches
# every pointer once in source order (one task per parquet row group, one per zip file: each row group or video is read
# once) and keeps the image bytes in a temporary folder; the shard pass then takes them from there. Every image is still
# checked against its recorded sha256 in the shard pass, and a pointer the pre-pass could not fetch is fetched there.
PREPASS_TYPES = ("hf_parquet_cell", "hf_zip_member")


def _ptr_key(src_json: str) -> str:
    return hashlib.sha1(src_json.encode("utf-8")).hexdigest()


def image_pointers(r: dict):
    for col in ("query_image_source", "target_image_source"):
        if r.get(col):
            yield r[col]
    yield from (s for s in (r.get("neg_images_source") or []) if s)


def _source_path(job) -> tuple:
    """(local path or None, bytes downloaded) of one pointer's source file (downloaded into the cache if missing)."""
    cache_dir, src = job
    s = Sources(cache_dir)
    try:
        return s.path(src), s.downloaded
    except Exception:  # noqa: BLE001 - the shard pass fetches it again and reports the problem
        return None, 0


def plan_prepass(by_shard: dict, cache_dir: str, mode: str, procs: int) -> tuple[list, float, int]:
    """Pointers worth fetching in the pre-pass, grouped into tasks (one per parquet row group and column, one per zip
    file), the re-read factor (source units the shard pass would read, counted once per shard that touches them, over
    the distinct units) and the bytes downloaded while planning (missing source files, fetched in parallel)."""
    if mode == "never":
        return [], 1.0, 0
    import bisect
    parsed, files = [], {}
    for shard, rows in by_shard.items():
        for r in rows:
            for sj in image_pointers(r):
                try:
                    src = json.loads(sj)
                except ValueError:
                    continue
                if src.get("type") in PREPASS_TYPES:
                    fk = (src.get("repo"), src.get("revision"), src.get("file"), src.get("url"))
                    files.setdefault(fk, src)
                    parsed.append((shard, sj, src, fk))
    if not parsed:
        return [], 1.0, 0
    with cf.ThreadPoolExecutor(max_workers=max(1, min(8, procs, len(files)))) as tp:
        got = dict(zip(files, tp.map(_source_path, [(cache_dir, s) for s in files.values()])))
    downloaded = sum(n for _, n in got.values())
    starts = {}
    unit_shards = collections.defaultdict(set)
    unit_ptrs = collections.defaultdict(set)
    for shard, sj, src, fk in parsed:
        p = got[fk][0]
        if p is None:
            continue
        try:
            if src["type"] == "hf_parquet_cell":
                if p not in starts:
                    import pyarrow.parquet as pq
                    md = pq.ParquetFile(p).metadata
                    acc, n = [], 0
                    for i in range(md.num_row_groups):
                        acc.append(n)
                        n += md.row_group(i).num_rows
                    starts[p] = acc
                unit = (p, src.get("column"), bisect.bisect_right(starts[p], src["row"]) - 1)
                task = unit                                   # one task per row group and column
            else:
                unit, task = (p, src["member"]), (p,)         # one task per zip file (its videos in entry order)
        except Exception:  # noqa: BLE001 - left to the shard pass, which reports it
            continue
        unit_shards[unit].add(shard)
        unit_ptrs[task].add(sj)
    if not unit_shards:
        return [], 1.0, downloaded
    factor = sum(len(v) for v in unit_shards.values()) / len(unit_shards)
    if mode == "auto" and factor < 1.5:
        return [], factor, downloaded
    srcs = Sources(cache_dir)
    tasks = [sorted(v, key=lambda sj: order_key(srcs, sj)) for v in unit_ptrs.values()]
    return sorted(tasks, key=len, reverse=True), factor, downloaded


def prepass_file(job) -> tuple[dict, int]:
    """Fetch one source file's pointers in order and append the image bytes to out_path; {pointer key: (offset, len)}."""
    pointers, cache_dir, out_path = job
    srcs = Sources(cache_dir)
    index, off = {}, 0
    with open(out_path, "wb") as fh:
        for sj in pointers:
            try:
                b = srcs.image(json.loads(sj))
            except Exception:  # noqa: BLE001 - fetched again (and reported) by the shard pass
                continue
            fh.write(b)
            index[_ptr_key(sj)] = (off, len(b))
            off += len(b)
    return index, srcs.downloaded


def rebuild_shard(job) -> dict:
    """Rebuild one shard. A record goes into the written shard only when every image was fetched with the recorded
    sha256 and length and the record re-serializes to its recorded sha256; any other record is left out and listed in
    res["problems"] (shard, ordinal, field, pointer, reason), and the shard is then written as <shard>.incomplete."""
    shard, rows, pmap, check, out, cache_dir = job[:6]
    spill = job[6] if len(job) > 6 else {}          # pointer key -> (pre-pass file, offset, length)
    set_dir = job[7] if len(job) > 7 else None
    rows = sorted(rows, key=lambda r: r["ordinal"])
    res = {"shard": shard, "records": len(rows), "record_ok": 0, "record_bad": 0, "image_missing": 0, "image_bad": 0,
           "ordinals_contiguous": [r["ordinal"] for r in rows] == list(range(len(rows))), "examples": [], "problems": [],
           "written": 0}
    srcs = Sources(cache_dir, set_dir)
    spill_fh = {}

    def problem(r, field, pointer, reason):
        res["problems"].append({"shard": shard, "ordinal": r["ordinal"], "field": field, "pointer": pointer,
                                "reason": reason})

    def from_spill(src_json):
        ent = spill.get(_ptr_key(src_json))
        if ent is None:
            return None
        p, off, n = ent
        fh_s = spill_fh.get(p) or spill_fh.setdefault(p, open(p, "rb"))
        fh_s.seek(off)
        return fh_s.read(n)
    modes = ["train", "public"] if check == "both" else [check]    # both: one pass, images fetched once
    sums = {m: [hashlib.md5(), 0, 0] for m in modes}
    fh = None
    if out is not None:
        path = os.path.join(out, shard)
        os.makedirs(os.path.dirname(path), exist_ok=True)
        fh = open(path + ".partial", "wb")

    def image(src_json, sha, ln):
        """(bytes, None) or (None, reason)."""
        if not ln:
            return b"", None
        try:
            b = from_spill(src_json) if spill else None
            if b is None:
                b = srcs.image(json.loads(src_json))
        except Exception as e:  # noqa: BLE001
            res["image_missing"] += 1
            return None, f"not fetched: {type(e).__name__}: {str(e)[:200]}"
        if len(b) != ln or hashlib.sha256(b).hexdigest() != sha:
            res["image_bad"] += 1
            return None, f"differs from the training image (length {len(b)}, expected {ln}; sha256 differs)"
        return b, None

    def build(r, got, bad):
        if r.get("_problem"):                        # e.g. its texts were not found in the source
            problem(r, r["_problem"][0], r["_problem"][1], r["_problem"][2])
            bad = True
        if bad:
            res["record_bad"] += 1
            if len(res["examples"]) < 3:
                res["examples"].append(r["ordinal"])
            return
        rec = {k: r[k] for k in SCALARS}
        rec["neg_texts"] = list(r["neg_texts"] or [])
        rec["neg_scores"] = list(r["neg_scores"] or [])
        rec["query_image"] = got.get("query_image", b"")
        rec["target_image"] = got.get("target_image", b"")
        rec["neg_images"] = [got.get(("neg", j), b"") for j in range(len(r.get("neg_images_source") or []))]
        frames, ok = {}, True
        for m in modes:
            rec["provenance"] = to_train(r["provenance"], pmap) if m == "train" else r["provenance"]
            rec["license"] = r.get("_license_train", r["license"]) if m == "train" else r["license"]
            payload = encode_record(rec)
            want = r["record_sha256"] if m == "train" else r["record_sha256_public"]
            if hashlib.sha256(payload).hexdigest() != want:
                ok = False
                problem(r, "record", None, f"the rebuilt record differs from record_sha256{'' if m == 'train' else '_public'}")
            frames[m] = frame_record(payload)
        if not ok:
            res["record_bad"] += 1
            if len(res["examples"]) < 3:
                res["examples"].append(r["ordinal"])
            return
        for m, frame in frames.items():
            h = sums[m]
            h[0].update(frame)
            h[1] = CRC32C(frame, h[1])
            h[2] += len(frame)
        if fh is not None:
            fh.write(frames[modes[-1]])
            res["written"] += 1
        res["record_ok"] += 1

    fields = [("query_image", "query_image_source", "query_image_sha256", "query_image_len"),
              ("target_image", "target_image_source", "target_image_sha256", "target_image_len")]
    CHUNK = 8192                       # records whose images are fetched together, in source order (a typical
                                       # shard at once, so each source file or row group is read once per shard)
    for start in range(0, len(rows), CHUNK):
        chunk = rows[start:start + CHUNK]
        jobs = []
        for i, r in enumerate(chunk):
            for f, sk, hk, lk in fields:
                if r.get(lk):
                    jobs.append((r.get(sk), i, f, r.get(hk), r.get(lk)))
            for j, (sj, h, n) in enumerate(zip(r.get("neg_images_source") or [], r.get("neg_images_sha256") or [],
                                               r.get("neg_images_len") or [])):
                if n:
                    jobs.append((sj, i, ("neg", j), h, n))
        got, bad = collections.defaultdict(dict), set()
        for sj, i, f, h, n in sorted(jobs, key=lambda x: order_key(srcs, x[0]) if x[0] else ("~", "", "", 0, "", 0)):
            b, why = image(sj, h, n)
            if why is not None:
                bad.add(i)
                problem(chunk[i], f if isinstance(f, str) else f"neg_images[{f[1]}]", sj, why)
            else:
                got[i][f] = b
        for i, r in enumerate(chunk):
            build(r, got[i], i in bad)
    for f_s in spill_fh.values():
        f_s.close()
    if fh is not None:
        fh.close()
        final = path if res["record_ok"] == len(rows) else path + ".incomplete"
        os.replace(path + ".partial", final)
        res["written_as"] = os.path.basename(final)
    for m, (h, c, n) in sums.items():
        res[m] = {"md5": _b64(h.digest()), "crc32c": _b64(c.to_bytes(4, "big")), "bytes": n}
    res.update(res[modes[-1]])
    res["downloaded"] = srcs.downloaded
    return res


# ------------------------------------------------------------- texts fetched from their public source (2026-11-12)
# Some text sets are released without their texts (the publishers' terms): each record names its query, positive and
# negative items in the source at a pinned revision (records.parquet column "text_source"; set.json "text_source"
# describes the source), and the texts are re-made here as our builders made them, then cleaned as the training
# adapter did. Every record is still checked against its sha256 afterwards.
MEDIA_PLACEHOLDERS = ("<|image_1|>", "<image>", "<|image_pad|>", "<|IMAGE|>", "<|video_pad|>", "<|VIDEO|>", "<video>")


def clean_text(s: str) -> str:
    """The training adapter's text cleaning: media placeholders out, surrounding blanks off."""
    if "<" in s:
        for tok in MEDIA_PLACEHOLDERS:
            s = s.replace(tok, "")
    return s.strip()


def normalize_text(s: str) -> str:
    """The training code's text key: NFKC, casefold, all whitespace collapsed to single spaces, stripped."""
    import unicodedata
    return " ".join(unicodedata.normalize("NFKC", s).casefold().split())


def adapter_negs(raw: list, target: str) -> list:
    """Negatives as the adapter kept them: joined by \\x1f by our builders, split, cleaned; then a blank one, one
    equal to the positive and a repeated one (normalize_text) dropped, the first of repeats kept."""
    s = "\x1f".join(raw)
    negs = [c for c in (clean_text(x) for x in s.split("\x1f")) if c] if s else []
    pos = normalize_text(target) if target.strip() else None
    kept, seen = [], set()
    for t in negs:
        n = normalize_text(t)
        if not n or n == pos or n in seen:
            continue
        seen.add(n)
        kept.append(t)
    return kept


def _hf_file(spec: dict, filename: str, cache: str) -> str:
    from huggingface_hub import hf_hub_download
    return hf_hub_download(spec["repo"], filename, repo_type="dataset", revision=spec["revision"],
                           cache_dir=os.path.join(cache, "hf"))


def _tevatron_passage(p: dict) -> str:
    title, text = (p.get("title") or "").strip(), (p.get("text") or "").strip()
    return (f"{title}. {text}" if title else text).strip()


def fill_texts(table: list, spec: dict, cache: str) -> tuple[int, list]:
    """Set query_text, target_text and neg_texts of every record from the source named by set.json "text_source".
    Returns (records whose items were not found, the first few of them)."""
    kind = spec["kind"]
    want = collections.defaultdict(list)            # source unit -> [(record index, pointer)]
    for i, r in enumerate(table):
        p = json.loads(r["text_source"])
        key = p["row"] if kind == "parquet_rows" else p["line"] if kind == "tevatron_jsonl" else (p["file"], p["row"])
        want[key].append((i, p))
    done = set()

    def put(i, q, t, negs):
        table[i]["query_text"], table[i]["target_text"], table[i]["neg_texts"] = q, t, negs
        done.add(i)
    if kind == "parquet_rows":                       # one source row per record (sentence-transformers triplets)
        import pyarrow.parquet as pq
        n0 = 0
        for f in spec["files"]:
            pf = pq.ParquetFile(_hf_file(spec, f, cache))
            for rg in range(pf.num_row_groups):
                t = pf.read_row_group(rg, columns=spec["columns"])
                cols = [t.column(c).to_pylist() for c in spec["columns"]]
                for j in range(t.num_rows):
                    for i, p in want.get(n0 + j, ()):
                        q, pos, *negs = ((c[j] or "").strip() for c in cols)
                        t_ = clean_text(pos)
                        put(i, clean_text(q), t_, adapter_negs(negs, t_))
                n0 += t.num_rows
    elif kind == "tevatron_jsonl":                   # Tevatron/msmarco-passage: a query row with its passages
        import gzip
        for f in spec["files"]:
            with gzip.open(_hf_file(spec, f, cache), "rt", encoding="utf-8") as fh:
                for line_no, line in enumerate(fh):
                    if line_no not in want:
                        continue
                    row = json.loads(line)
                    by_id = {str(x.get("docid")): x for x in (row.get("positive_passages") or []) + (row.get("negative_passages") or [])}
                    for i, p in want[line_no]:
                        if str(row.get("query_id")) != str(p["query_id"]) or p["pos"] not in by_id or any(d not in by_id for d in p["negs"]):
                            continue
                        t_ = clean_text(_tevatron_passage(by_id[p["pos"]]))
                        put(i, clean_text((row.get("query") or "").strip()), t_,
                            adapter_negs([_tevatron_passage(by_id[d]) for d in p["negs"]], t_))
    elif kind == "ms_marco_v21":                     # microsoft/ms_marco v2.1: a query row with its ten passages
        import pyarrow.parquet as pq
        cut = spec["max_chars"]
        for fi, f in enumerate(spec["files"]):
            if not any(k[0] == fi for k in want):
                continue
            pf = pq.ParquetFile(_hf_file(spec, f, cache))
            n0 = 0
            for rg in range(pf.num_row_groups):
                t = pf.read_row_group(rg, columns=["query_id", "query", "passages"])
                for j in range(t.num_rows):
                    hits = want.get((fi, n0 + j))
                    if not hits:
                        continue
                    row = {c: t.column(c)[j].as_py() for c in ("query_id", "query", "passages")}
                    texts = (row["passages"] or {}).get("passage_text") or []
                    for i, p in hits:
                        if str(row["query_id"]) != str(p["query_id"]) or max([p["pos"], *p["negs"]]) >= len(texts):
                            continue
                        t_ = clean_text((texts[p["pos"]] or "").strip()[:cut])
                        put(i, clean_text((row["query"] or "").strip()), t_,
                            adapter_negs([(texts[k] or "").strip()[:cut] for k in p["negs"]], t_))
                n0 += t.num_rows
    else:
        raise SystemExit(f"unknown text source kind {kind!r}; this loader is older than the set")
    missing = [i for i in range(len(table)) if i not in done]
    for i in missing:
        table[i]["query_text"] = table[i]["target_text"] = ""
        table[i]["neg_texts"] = []
        table[i]["_problem"] = ("texts", table[i]["text_source"], "the texts were not found in the source")
    return len(missing), [table[i]["ordinal"] for i in missing[:5]]


def find_set_dirs(root: str) -> list[str]:
    out = []
    for cat in sorted(os.listdir(root)):
        d = os.path.join(root, cat)
        if os.path.isdir(d) and not cat.startswith(".") and cat != "tools":
            out += [os.path.join(d, n) for n in sorted(os.listdir(d)) if os.path.exists(os.path.join(d, n, "set.json"))]
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--root", default=os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")))
    ap.add_argument("--set-dir", action="append", default=[])
    ap.add_argument("--sets", default="", help="comma-separated dataset ids or folder names (default: all)")
    ap.add_argument("--out", default=None)
    ap.add_argument("--no-write", action="store_true")
    ap.add_argument("--cache", default="openembed_sources", help="download cache for image source files")
    ap.add_argument("--prepass", choices=("auto", "always", "never"), default="auto",
                    help="fetch the images of sets whose shards share source row groups or videos in one pre-pass "
                         "(auto: when the shards would read each source unit 1.5 times or more)")
    ap.add_argument("--prepass-dir", default=None, help="temporary folder for the pre-pass images (default: inside "
                    "--cache; needs about the size of the set's images, removed afterwards)")
    ap.add_argument("--check", choices=("public", "train", "both"), default="public",
                    help="public: against the *_public values; train / both need OPENEMBED_PROVENANCE_MAP")
    ap.add_argument("--procs", type=int, default=os.cpu_count() or 4)
    ap.add_argument("--report", default=None)
    ap.add_argument("--shards", default="", help="only these shards of one dataset (file names as in shards.parquet, "
                    "comma-separated): rebuild and check just them, e.g. with only the image tars they use (2026-11-18)")
    ap.add_argument("--problems", default=None, help="JSON lines, one per image, text or record that could not be "
                    "rebuilt (default: next to --report, else in --out, else ./rebuild_problems.jsonl)")
    args = ap.parse_args()
    problems_path = args.problems or (os.path.splitext(args.report)[0] + ".problems.jsonl" if args.report else
                                      os.path.join(args.out, "rebuild_problems.jsonl") if args.out else
                                      "rebuild_problems.jsonl")
    os.makedirs(os.path.dirname(os.path.abspath(problems_path)), exist_ok=True)
    open(problems_path, "w").close()
    if not args.no_write and not args.out:
        ap.error("--out is required unless --no-write")
    pmap = json.loads(os.environ.get("OPENEMBED_PROVENANCE_MAP", "[]")) if args.check in ("train", "both") else []
    if args.check in ("train", "both") and not pmap:
        ap.error("--check train needs OPENEMBED_PROVENANCE_MAP (the internal prefixes are not part of the release)")
    import pyarrow.parquet as pq
    want = {x for x in args.sets.split(",") if x}
    chosen, found = [], set()
    for d in (args.set_dir or find_set_dirs(args.root)):
        info = json.load(open(os.path.join(d, "set.json")))
        rel = os.path.relpath(os.path.normpath(d), args.root).replace(os.sep, "/")
        names = {info["dataset_id"], rel, os.path.basename(os.path.normpath(d))}
        if not want or names & want:
            chosen.append((d, info))
            found |= names & want
    if want - found or not chosen:
        print(f"error: no dataset folder for {sorted(want - found) or 'any set'} under {args.root}", file=sys.stderr)
        return 2
    only = [x for x in args.shards.split(",") if x]
    if only and len(chosen) != 1:
        print("error: --shards names shards of one dataset: give exactly one in --sets", file=sys.stderr)
        return 2
    print(f"CRC-32C backend: {CRC32C_BACKEND}; checking against the {args.check} checksums; {len(chosen)} set(s)", flush=True)
    report = {"check": args.check, "sets": {}, "bytes_downloaded": 0}
    for set_dir, info in chosen:
        t0 = time.time()
        ds = info["dataset_id"]
        if not info.get("rebuildable", True):
            print(f"{ds}: identifiers only (records not distributed), nothing to rebuild", flush=True)
            continue
        if info.get("pyav"):
            try:
                import av
                found = av.__version__
            except ImportError:
                found = "none"
            if found != info["pyav"]:
                print(f"{ds}: needs PyAV {info['pyav']} (pip install av=={info['pyav']}) to decode its video frames "
                      f"exactly as our converter did (found {found}); skipped", file=sys.stderr, flush=True)
                report["sets"][ds] = {"pass": False, "error": f"PyAV {info['pyav']} required"}
                continue
        if info.get("pillow_min"):
            import PIL
            ver = lambda v: tuple(int(x) for x in v.split(".")[:3] if x.isdigit())  # noqa: E731
            if ver(PIL.__version__) < ver(info["pillow_min"]):
                print(f"{ds}: needs Pillow >= {info['pillow_min']} to re-create its images byte for byte (found "
                      f"{PIL.__version__}); skipped", file=sys.stderr, flush=True)
                report["sets"][ds] = {"pass": False, "error": f"Pillow >= {info['pillow_min']} required"}
                continue
        table = pq.read_table(os.path.join(set_dir, "records.parquet")).to_pylist()
        text_missing, text_missing_examples = 0, []
        if info.get("text_source"):
            t1 = time.time()
            text_missing, text_missing_examples = fill_texts(table, info["text_source"], os.path.abspath(args.cache))
            print(f"{ds}: texts fetched from {info['text_source']['repo']} at {info['text_source']['revision'][:8]} for "
                  f"{len(table) - text_missing}/{len(table)} records, {time.time() - t1:.0f}s", flush=True)
        if info.get("license_training"):           # the label the training records carry (corrected in the release)
            for r in table:
                r["_license_train"] = info["license_training"]
        shards = {s["shard"]: s for s in pq.read_table(os.path.join(set_dir, "shards.parquet")).to_pylist()}
        by_shard = collections.defaultdict(list)
        for r in table:
            by_shard[r["shard"]].append(r)
        if only:
            names = {s_: s_ for s_ in by_shard} | {os.path.basename(s_): s_ for s_ in by_shard}
            unknown = sorted(x for x in only if x not in names)
            if unknown:
                print(f"error: {ds}: no shard named {unknown[:3]} (see shards.parquet)", file=sys.stderr)
                return 2
            keep = {names[x] for x in only}
            by_shard = collections.defaultdict(list, {s_: by_shard[s_] for s_ in keep})
            print(f"{ds}: only {len(keep)} of {len(shards)} shards (--shards)", flush=True)
        cache = os.path.abspath(args.cache)
        tasks, factor, pre_downloaded = plan_prepass(by_shard, cache, args.prepass, args.procs)
        spill_dir, spill = None, {}
        try:
            if tasks:
                base = os.path.abspath(args.prepass_dir or cache)
                os.makedirs(base, exist_ok=True)
                spill_dir = tempfile.mkdtemp(prefix=".prepass-", dir=base)
                t1 = time.time()
                pre_jobs = [(t, cache, os.path.join(spill_dir, f"{i:05d}.bin")) for i, t in enumerate(tasks)]
                with cf.ProcessPoolExecutor(max_workers=max(1, min(args.procs, len(pre_jobs)))) as pool:
                    for (_, _, p), (index, dl) in zip(pre_jobs, pool.map(prepass_file, pre_jobs)):
                        for k, (off, n) in index.items():
                            spill[k] = (p, off, n)
                        pre_downloaded += dl
                print(f"{ds}: pre-pass read {len(tasks)} source units once each (re-read factor {factor:.1f}) and kept "
                      f"{len(spill)} images, {time.time() - t1:.0f}s", flush=True)
            jobs = []
            for s, rows in sorted(by_shard.items()):
                sub = {k: spill[k] for k in (_ptr_key(sj) for r in rows for sj in image_pointers(r)) if k in spill}
                jobs.append((s, rows, pmap, args.check, None if args.no_write else args.out, cache, sub,
                             os.path.abspath(set_dir)))
            with cf.ProcessPoolExecutor(max_workers=max(1, min(args.procs, len(jobs)))) as pool:
                results = list(pool.map(rebuild_shard, jobs))
        finally:
            if spill_dir:
                shutil.rmtree(spill_dir, ignore_errors=True)
        keys = {"public": {"md5": "md5_public", "crc32c": "crc32c_public", "bytes": "bytes_public"},
                "train": {"md5": "md5", "crc32c": "crc32c", "bytes": "bytes"}}
        modes = ["train", "public"] if args.check == "both" else [args.check]
        shard_ok = sum(1 for r in results if all(r[m][k] == shards[r["shard"]][v] for m in modes for k, v in keys[m].items()))
        out = {"records": sum(r["records"] for r in results), "record_ok": sum(r["record_ok"] for r in results),
               "record_bad": sum(r["record_bad"] for r in results), "image_missing": sum(r["image_missing"] for r in results),
               "image_bad": sum(r["image_bad"] for r in results), "shards": len(results), "shards_expected": len(by_shard) if only else len(shards),
               "shards_ok": shard_ok, "ordinals_contiguous": all(r["ordinals_contiguous"] for r in results),
               "bytes_downloaded": pre_downloaded + sum(r["downloaded"] for r in results), "seconds": round(time.time() - t0, 1),
               "prepass": {"tasks": len(tasks), "images": len(spill), "reread_factor": round(factor, 2)},
               "text_missing": text_missing, "text_missing_examples": text_missing_examples,
               "problems": sum(len(r["problems"]) for r in results),
               "incomplete_shards": [r.get("written_as") for r in results if (r.get("written_as") or "").endswith(".incomplete")],
               "bad_examples": [(r["shard"], r["examples"]) for r in results if r["examples"]][:5]}
        if only:
            out["only_shards"] = sorted(by_shard)
        expected_records = sum(len(v) for v in by_shard.values()) if only else info["records"]
        out["pass"] = (out["record_ok"] == out["records"] == expected_records and out["shards_ok"] == out["shards_expected"]
                       and not out["image_missing"] and not out["image_bad"] and out["ordinals_contiguous"]
                       and not out["text_missing"] and not out["problems"])
        with open(problems_path, "a") as fh_p:
            for r in results:
                for pr in r["problems"]:
                    fh_p.write(json.dumps({"dataset": ds, **pr}) + "\n")
        report["sets"][ds] = out
        report["bytes_downloaded"] += out["bytes_downloaded"]
        print(f"{ds}: {out['record_ok']}/{out['records']} records, {out['shards_ok']}/{out['shards_expected']} shards, "
              f"images missing {out['image_missing']} bad {out['image_bad']}, {out['seconds']}s -> "
              f"{'PASS' if out['pass'] else 'FAIL (incomplete: ' + str(out['problems']) + ' problems listed in ' + problems_path + ')'}",
              flush=True)
    if args.report:
        json.dump(report, open(args.report, "w"), indent=1)
    n_pass = sum(v["pass"] for v in report["sets"].values())
    if os.path.getsize(problems_path) == 0:
        os.remove(problems_path)
    print(f"{n_pass}/{len(report['sets'])} sets pass" + ("" if n_pass == len(report["sets"]) else
          f"; the others are incomplete (problems listed in {problems_path})"))
    return 0 if n_pass == len(report["sets"]) else 1


if __name__ == "__main__":
    sys.exit(main())