File size: 48,899 Bytes
e39a6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
"""Builds the public part of the luoke-search benchmark from the published datasets, reproducibly.

Most people never run this: they fetch the finished corpora with get_corpus.py. This is how those corpora, the
question sets in sets/ and the ID lists in ids/ were made, so anyone can check or redo it.

    python3 -I search/fetch.py download --raw <empty folder>      # the source files, at pinned revisions
    python3 -I search/fetch.py build --raw <that folder> --out <corpus folder>
    python3 -I search/fetch.py pack --out <corpus folder> --assets <folder for the .tar.gz>

Needs (not the standard library; install them in a virtual environment of your own):
huggingface_hub, pyarrow, pillow, python-docx, python-pptx, pypdf, numpy.

The downloaded files are data, never run: nothing here imports or executes anything from them. Every random choice
comes from one seed (SEED), so the same sources give the same picks, file names and files.
"""
from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import io
import json
import math
import os
import random
import re
import shutil
import sys
import tarfile
import zipfile
from collections import Counter, defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
SEED = 20261109

# The blocks, in the order they are built and run. "kind" is what the block mostly tests.
BLOCKS = {
    "xm3600-zh": {"lang": "zh", "kind": "image", "questions": 300},
    "mvision-zh": {"lang": "zh", "kind": "screenshot-pdf", "questions": 189},
    "vidore-en": {"lang": "en", "kind": "pdf", "questions": 150},
    "t2-zh": {"lang": "zh", "kind": "passage", "questions": 300},
    "miracl-zh": {"lang": "zh", "kind": "passage", "questions": 150},
    "miracl-en": {"lang": "en", "kind": "passage", "questions": 100},
}
NO_ANSWER_SHARE = 0.10

# Hugging Face datasets, pinned to the revisions the sets were built from (2026-11-09).
HF = {
    "mteb/XM3600T2IRetrieval": ("963e5fcdc6b2f222360cec3df3869cc9b8343cb0", [
        "zh-corpus/test-00000-of-00001.parquet", "zh-qrels/test-00000-of-00001.parquet",
        "zh-queries/test-00000-of-00001.parquet"]),
    "nvidia/miracl-vision": ("309e1696433408fbd555959cf1da968f3814f8b6", [
        "zh/corpus.parquet", "zh/images.parquet", "zh/qrels.parquet", "zh/queries.parquet"]),
    "vidore/vidore_v3_hr": ("0cdf0979f2c5a0fd3e335e6373b9da48a9fe3bc3", None),
    "vidore/vidore_v3_finance_en": ("7f432c176d82e27546501ad8064a713ac3071809", None),
    "vidore/vidore_v3_industrial": ("e26c864724f5dd71a3d7d739272d95637764cee9", None),
    "mteb/T2Retrieval": ("921dd3af6e78d1ae7ee0368aa8d7eaee02c8f08e", [
        "corpus/dev-00000-of-00001.parquet", "data/dev-00000-of-00001.parquet", "queries/dev-00000-of-00001.parquet"]),
    "THUIR/T2Ranking": ("2a369a430a70979223f1b9a41b1919774d46b432", ["data/qrels.dev.tsv"]),
    "mteb/MIRACLRetrievalHardNegatives": ("332a9acb49f5e83d5397683f79d23e588f685916", [
        f"{lang}-{part}/dev-00000-of-00001.parquet" for lang in ("zh", "en") for part in ("corpus", "qrels", "queries")]),
}
VIDORE = ["vidore/vidore_v3_hr", "vidore/vidore_v3_finance_en", "vidore/vidore_v3_industrial"]
VIDORE_FILES = ["queries/test-00000-of-00001.parquet", "qrels/test-00000-of-00001.parquet",
                "documents_metadata/test-00000-of-00001.parquet", "pdfs/metadata.csv"]
# Crossmodal-3600's own site: the captions with each image's locale, and each image's author and license.
XM3600_WEB = {
    "captions.zip": "https://google.github.io/crossmodal-3600/web-data/captions.zip",
    "image_attributions.csv": "https://google.github.io/crossmodal-3600/web-data/image_attributions.csv",
}

# ViDoRe documents left out after the first build (2026-11-09, the user's decisions, in this order): TO_36-1-191, a
# 371 MB scanned manual, then TO_35-1-18 (107 MB). Their questions are replaced by replace_dropped, the first
# document's before the second's (so each round's picks stay as they were); replacements never come from a PDF over
# 50 MB, and come from documents with a text layer before scanned ones.
DROPPED_ORDER = {"industrial": ["TO_36-1-191", "TO_35-1-18"]}
DROPPED_VIDORE = {short: set(docs) for short, docs in DROPPED_ORDER.items()}
REPLACEMENT_MAX_BYTES = 50_000_000

# Licenses a ViDoRe document may carry to be packed (its documents_metadata "license" field, matched by its start).
REDISTRIBUTABLE = ("cc-by-4.0", "Public Domain", "DISTRIBUTION STATEMENT A")


def say(*parts):
    print(*parts, flush=True)


def local(raw, repo):
    return os.path.join(raw, repo.replace("/", "__"))


# ---------------------------------------------------------------------------------------------------------- download

def download(raw):
    os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
    from huggingface_hub import HfApi, hf_hub_download
    import pyarrow.parquet as pq
    from huggingface_hub import HfFileSystem

    os.makedirs(raw, exist_ok=True)
    api = HfApi()
    for repo, (revision, files) in HF.items():
        if files is None:
            listed = api.list_repo_files(repo, repo_type="dataset", revision=revision)
            files = VIDORE_FILES + sorted(f for f in listed if f.startswith("pdfs/") and f.endswith(".pdf"))
        for name in files:
            say("download", repo, name)
            hf_hub_download(repo, name, repo_type="dataset", revision=revision, local_dir=local(raw, repo))
    # ViDoRe's corpus files hold each page's picture too (GBs): only the columns that say which document and page
    # a corpus id is, and the page's text (for BM25), are read, over HTTP ranges.
    fs = HfFileSystem()
    for repo in VIDORE:
        revision = HF[repo][0]
        out = os.path.join(local(raw, repo), "corpus_pages.jsonl")
        if os.path.exists(out):
            continue
        rows = []
        for path in sorted(fs.glob(f"datasets/{repo}@{revision}/corpus/*.parquet")):
            with fs.open(path) as handle:
                parquet = pq.ParquetFile(handle)
                columns = [c for c in parquet.schema_arrow.names if c != "image"]
                rows += parquet.read(columns=columns).to_pylist()
        with open(out + ".part", "w") as handle:
            for row in rows:
                handle.write(json.dumps(row, ensure_ascii=False) + "\n")
        os.replace(out + ".part", out)
        say("corpus pages", repo, len(rows))
    import urllib.request
    folder = os.path.join(raw, "xm3600-official")
    os.makedirs(folder, exist_ok=True)
    for name, url in XM3600_WEB.items():
        target = os.path.join(folder, name)
        if not os.path.exists(target):
            say("download", url)
            with urllib.request.urlopen(url, timeout=120) as response, open(target + ".part", "wb") as handle:
                shutil.copyfileobj(response, handle)
            os.replace(target + ".part", target)
    say("done")



# ------------------------------------------------------------------------------------------------------------- tools

def read_parquet(path, columns=None):
    import pyarrow.parquet as pq
    return pq.read_table(path, columns=columns).to_pylist()


CJK = re.compile(r"[㐀-鿿豈-﫿]+")
WORD = re.compile(r"[A-Za-z0-9]+")
EN_STOP = set("""a an the of to in on for and or is are was were be been by with as at from that this these those it its
what which who whom when where why how do does did can could should would will shall may might has have had not no
than then there their they them he she his her you your we our i me my about into over under between""".split())


def tokens(text, lang):
    """Words for BM25: for Chinese each character and each pair of neighbouring characters, for Latin script the
    lower-cased words (English stop words dropped)."""
    out = []
    for word in WORD.findall(text):
        word = word.lower()
        if lang == "en" and word in EN_STOP:
            continue
        out.append(word)
    if lang == "zh":
        for run in CJK.findall(text):
            out.extend(run)
            out.extend(run[i:i + 2] for i in range(len(run) - 1))
    return out


class BM25:
    """Okapi BM25 (k1 0.9, b 0.4, Anserini's defaults) over a list of texts, with postings in numpy arrays."""

    def __init__(self, texts, lang, k1=0.9, b=0.4):
        import numpy as np
        from array import array
        self.np, self.lang, self.k1, self.b = np, lang, k1, b
        self.vocab = {}
        terms, docs, freqs = array("i"), array("i"), array("i")
        lengths = array("i")
        for number, text in enumerate(texts):
            counts = Counter(tokens(text, lang))
            lengths.append(sum(counts.values()))
            for term, count in counts.items():
                terms.append(self.vocab.setdefault(term, len(self.vocab)))
                docs.append(number)
                freqs.append(count)
        terms, docs, freqs = np.frombuffer(terms, np.int32), np.frombuffer(docs, np.int32), np.frombuffer(freqs, np.int32)
        order = np.argsort(terms, kind="stable")
        self.docs, self.freqs = docs[order], freqs[order].astype(np.float32)
        self.pointers = np.zeros(len(self.vocab) + 1, np.int64)
        np.add.at(self.pointers, terms[order] + 1, 1)
        self.pointers = np.cumsum(self.pointers)
        self.lengths = np.frombuffer(lengths, np.int32).astype(np.float32)
        self.n = len(self.lengths)
        frequency = np.diff(self.pointers).astype(np.float32)
        self.idf = np.log(1 + (self.n - frequency + 0.5) / (frequency + 0.5))
        self.norm = k1 * (1 - b + b * self.lengths / max(float(self.lengths.mean()), 1.0))

    def top(self, query, k=10):
        np = self.np
        scores = np.zeros(self.n, np.float32)
        for term in set(tokens(query, self.lang)):
            index = self.vocab.get(term)
            if index is None:
                continue
            start, end = self.pointers[index], self.pointers[index + 1]
            docs, tf = self.docs[start:end], self.freqs[start:end]
            scores[docs] += self.idf[index] * tf * (self.k1 + 1) / (tf + self.norm[docs])
        k = min(k, self.n)
        best = np.argpartition(-scores, k - 1)[:k]
        best = best[np.argsort(-scores[best], kind="stable")]
        return [int(i) for i in best if scores[i] > 0]


def allocate(total, sizes):
    """Splits `total` over groups in proportion to their sizes (largest remainder), never more than a group has."""
    sizes = {key: size for key, size in sizes.items() if size > 0}
    whole = sum(sizes.values())
    share = {key: total * size / whole for key, size in sizes.items()}
    out = {key: min(int(value), sizes[key]) for key, value in share.items()}
    while sum(out.values()) < min(total, whole):
        open_ = [key for key in sizes if out[key] < sizes[key]]
        key = max(open_, key=lambda k: (share[k] - out[k], k))
        out[key] += 1
    return out


def stratified(rng, items, total, domain, hard):
    """`total` items, spread over domains in proportion, and within each domain half hard and half easy (as far as
    there are enough of each). `domain(item)` and `hard(item)` say which."""
    groups = defaultdict(list)
    for item in items:
        groups[domain(item)].append(item)
    picked = []
    for key, count in sorted(allocate(total, {k: len(v) for k, v in groups.items()}).items()):
        members = sorted(groups[key], key=lambda item: str(item["id"]))
        rng.shuffle(members)
        tough = [m for m in members if hard(m)]
        easy = [m for m in members if not hard(m)]
        want_hard = count // 2 + (count % 2 if len(tough) > len(easy) else 0)
        want_hard = max(min(want_hard, len(tough)), count - len(easy))
        picked += tough[:want_hard] + easy[:count - want_hard]
    return picked


class Names:
    """File names that say nothing about what's inside: templates and numbers drawn from the seed."""

    def __init__(self, rng):
        self.rng, self.used = rng, set()

    def make(self, template, low=1000, high=9999):
        while True:
            name = template.format(n=self.rng.randint(low, high), d=self.date(), t=self.time())
            if name not in self.used:
                self.used.add(name)
                return name

    def date(self):
        return f"2026-{self.rng.randint(1, 10):02d}-{self.rng.randint(1, 28):02d}"

    def time(self):
        return f"{self.rng.randint(1, 12)}.{self.rng.randint(0, 59):02d}.{self.rng.randint(0, 59):02d}"


TEXT_TEMPLATES = {
    "zh": {"txt": ["笔记/笔记 {n}.txt", "下载/新建文本文档 ({n}).txt", "资料/摘录 {n}.txt"],
           "md": ["笔记/备忘 {n}.md", "资料/整理 {n}.md"],
           "docx": ["资料/文档{n}.docx", "下载/资料 {n}.docx"],
           "pptx": ["资料/演示文稿{n}.pptx", "下载/汇报 {n}.pptx"]},
    "en": {"txt": ["Notes/note {n}.txt", "Downloads/Untitled {n}.txt", "Documents/clip {n}.txt"],
           "md": ["Notes/notes {n}.md", "Documents/draft {n}.md"],
           "docx": ["Documents/Document{n}.docx", "Downloads/file {n}.docx"],
           "pptx": ["Documents/Presentation{n}.pptx", "Downloads/slides {n}.pptx"]},
}


def text_formats(rng, count):
    """For `count` text files: 80% plain (txt 50, md 30), 20% converted (docx 10, pptx 10), in a seeded order."""
    formats = (["txt"] * 50 + ["md"] * 30 + ["docx"] * 10 + ["pptx"] * 10)
    out = [formats[i % 100] for i in range(count)]
    rng.shuffle(out)
    return out


def write_text_file(path, fmt, title, body):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    if fmt == "txt":
        with open(path, "w", encoding="utf-8") as handle:
            handle.write((title + "\n\n" if title else "") + body + "\n")
    elif fmt == "md":
        with open(path, "w", encoding="utf-8") as handle:
            handle.write(("# " + title + "\n\n" if title else "") + body + "\n")
    elif fmt == "docx":
        import docx
        document = docx.Document()
        if title:
            document.add_heading(title, level=1)
        document.add_paragraph(body)
        properties = document.core_properties
        properties.author = properties.last_modified_by = properties.title = properties.comments = ""
        document.save(path)
    elif fmt == "pptx":
        import pptx
        from pptx.util import Pt
        deck = pptx.Presentation()
        slide = deck.slides.add_slide(deck.slide_layouts[1])
        slide.shapes.title.text = title or body[:24]
        frame = slide.placeholders[1].text_frame
        frame.text = body
        for paragraph in frame.paragraphs:
            for run in paragraph.runs:
                run.font.size = Pt(12)
        properties = deck.core_properties
        properties.author = properties.last_modified_by = properties.title = ""
        deck.save(path)
    else:
        raise ValueError(fmt)


def save_picture(data, path, fmt):
    """Re-encodes a picture with no metadata at all (EXIF, descriptions, XMP): only the pixels and the colour profile."""
    from PIL import Image, ImageOps
    with Image.open(io.BytesIO(data)) as image:
        image = ImageOps.exif_transpose(image)
        profile = image.info.get("icc_profile")
        if fmt == "JPEG":
            image = image.convert("RGB")
            kwargs = {"quality": 90}
        else:
            image = image.convert("RGBA" if image.mode in ("RGBA", "LA", "P") else "RGB")
            kwargs = {"optimize": True}
        os.makedirs(os.path.dirname(path), exist_ok=True)
        clean = Image.new(image.mode, image.size)
        clean.paste(image)
        if profile:
            kwargs["icc_profile"] = profile
        clean.save(path, fmt, **kwargs)


def image_bytes(value):
    """A picture from a parquet row: {"bytes": …} as the datasets library stores it, or the bytes themselves."""
    if isinstance(value, dict):
        return value.get("bytes")
    return value


class Block:
    """One block's corpus and questions while it is built."""

    def __init__(self, name, out):
        self.name = name
        self.lang = BLOCKS[name]["lang"]
        self.root = os.path.join(out, name)
        if os.path.exists(self.root):
            shutil.rmtree(self.root)
        os.makedirs(self.root)
        self.rng = random.Random(f"{SEED}-{name}")
        self.names = Names(random.Random(f"{SEED}-{name}-names"))
        self.answerable, self.unanswerable = [], []
        self.qrels = []          # (query id, document key, grade)
        self.files = {}          # source id -> {"file": …, "page": …}
        self.extra = {}

    def question(self, qid, text, expect, tag, **more):
        entry = {"id": str(qid), "q": text, "expect": expect, "tag": tag}
        entry.update(more)
        (self.answerable if expect else self.unanswerable).append(entry)

    def write(self, source):
        sets = os.path.join(HERE, "sets")
        os.makedirs(sets, exist_ok=True)
        base = "~/DigUpTestbed/" + self.name
        for suffix, queries in (("", self.answerable), ("-noanswer", self.unanswerable)):
            with open(os.path.join(sets, f"{self.name}{suffix}.json"), "w", encoding="utf-8") as handle:
                json.dump({"base": base, "lang": self.lang, "kind": BLOCKS[self.name]["kind"], "queries": queries},
                          handle, ensure_ascii=False, indent=1)
                handle.write("\n")
        with open(os.path.join(sets, f"{self.name}.qrels.tsv"), "w", encoding="utf-8") as handle:
            handle.write("query_id\tdocument\tgrade\n")
            for qid, doc, grade in sorted(set(self.qrels), key=lambda r: (r[0], r[1])):
                handle.write(f"{qid}\t{doc}\t{grade}\n")
        corpus = []
        for folder, _, files in os.walk(self.root):
            for name in files:
                corpus.append(os.path.relpath(os.path.join(folder, name), self.root))
        ids = {"block": self.name, "seed": SEED, "source": source, "corpus_files": len(corpus),
               "questions": [q["id"] for q in self.answerable], "no_answer": [q["id"] for q in self.unanswerable],
               "files": dict(sorted(self.files.items()))}
        ids.update(self.extra)
        os.makedirs(os.path.join(HERE, "ids"), exist_ok=True)
        with open(os.path.join(HERE, "ids", f"{self.name}.json"), "w", encoding="utf-8") as handle:
            json.dump(ids, handle, ensure_ascii=False, indent=1)
            handle.write("\n")
        say(f"{self.name}: {len(self.answerable)} questions + {len(self.unanswerable)} without an answer, "
            f"{len(corpus)} files")


def split_no_answer(rng, picked, conflicts):
    """About 10% of the picked questions become questions without an answer: their right answers leave the corpus.
    `conflicts(a, b)`: removing a's answers would take one of b's. Those whose removal would hurt another picked
    question are passed over."""
    want = round(len(picked) * NO_ANSWER_SHARE)
    order = list(picked)
    rng.shuffle(order)
    gone = []
    for item in order:
        if len(gone) == want:
            break
        if any(conflicts(item, other) for other in picked if other is not item and other not in gone):
            continue
        gone.append(item)
    return gone


# ------------------------------------------------------------------------------------------------------------ blocks

def build_xm3600(raw, out):
    """Chinese captions of Crossmodal-3600 asking for a photo: 300 questions (one caption each), 1,500 photos."""
    block = Block("xm3600-zh", out)
    repo = local(raw, "mteb/XM3600T2IRetrieval")
    queries = read_parquet(os.path.join(repo, "zh-queries/test-00000-of-00001.parquet"), ["id", "text"])
    qrels = read_parquet(os.path.join(repo, "zh-qrels/test-00000-of-00001.parquet"))
    image_of = {r["query-id"]: r["corpus-id"] for r in qrels if str(r["score"]) != "0"}
    locale = {}
    with zipfile.ZipFile(os.path.join(raw, "xm3600-official", "captions.zip")) as archive:
        with archive.open("captions.jsonl") as handle:
            for line in handle:
                row = json.loads(line)
                locale["corpus-" + row["image/key"]] = row["image/locale"]
    captions = defaultdict(list)
    for query in queries:
        if query["id"] in image_of and query["text"].strip():
            captions[image_of[query["id"]]].append(query)
    candidates = []
    for image in sorted(captions):
        options = sorted(captions[image], key=lambda q: q["id"])
        chosen = block.rng.choice(options)
        candidates.append({"id": chosen["id"], "image": image, "text": chosen["text"].strip(),
                           "locale": locale.get(image, "-")})
    picked = stratified(block.rng, candidates, BLOCKS[block.name]["questions"], lambda c: c["locale"], lambda c: False)
    gone = split_no_answer(block.rng, picked, lambda a, b: a["image"] == b["image"])
    gone_images = {c["image"] for c in gone}
    keep = [c for c in picked if c not in gone]
    wanted = {c["image"] for c in keep}
    others = sorted(i for i in locale if i not in wanted and i not in gone_images and i not in {c["image"] for c in picked})
    block.rng.shuffle(others)
    corpus_images = sorted(wanted | set(others[:1500 - len(wanted)]))
    # Names as an iPhone's DCIM export: two folders of IMG_4xxx (1,500 photos don't fit in one IMG_4000–4999 range).
    order = list(corpus_images)
    block.rng.shuffle(order)
    path_of = {}
    for number, image in enumerate(order):
        folder = "DCIM/100APPLE" if number % 2 == 0 else "DCIM/101APPLE"
        while True:
            name = f"{folder}/IMG_{block.names.rng.randint(4000, 4999)}.jpg"
            if name not in block.names.used:
                block.names.used.add(name)
                break
        path_of[image] = name
    import pyarrow.parquet as pq
    parquet = pq.ParquetFile(os.path.join(repo, "zh-corpus/test-00000-of-00001.parquet"))
    for group in range(parquet.num_row_groups):
        for row in parquet.read_row_group(group, columns=["id", "image"]).to_pylist():
            if row["id"] in path_of:
                save_picture(image_bytes(row["image"]), os.path.join(block.root, path_of[row["id"]]), "JPEG")
                block.files[row["id"].removeprefix("corpus-")] = {"file": path_of[row["id"]]}
    missing = [i for i in path_of if i.removeprefix("corpus-") not in block.files]
    if missing:
        sys.exit(f"xm3600: {len(missing)} pictures missing from the corpus file")
    for c in keep:
        block.question(c["id"], c["text"], [path_of[c["image"]]], "image", domain=c["locale"])
        block.qrels.append((c["id"], path_of[c["image"]], 1))
    for c in gone:
        block.question(c["id"], c["text"], [], "none-near", domain=c["locale"])
    attributions = {}
    with open(os.path.join(raw, "xm3600-official", "image_attributions.csv"), newline="", encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            key = row["ImageID"]
            if key in block.files:
                attributions[key] = {"author": row["Author"], "license": row["License"],
                                     "source": row["OriginalLandingURL"]}
    block.extra["attribution"] = dict(sorted(attributions.items()))
    block.extra["licenses"] = dict(Counter(a["license"] for a in attributions.values()))
    block.write({"captions": f"mteb/XM3600T2IRetrieval@{HF['mteb/XM3600T2IRetrieval'][0]} (zh)",
                 "locales and attributions": "google.github.io/crossmodal-3600/web-data"})


def build_mvision(raw, out):
    """MIRACL-VISION zh: questions about Wikipedia pages as screenshots. Each source page is one article's first
    screen; half are kept as screenshots (PNG, read by screenshot OCR), half bound a few at a time into PDFs without a
    text layer (read by PDF OCR)."""
    block = Block("mvision-zh", out)
    repo = os.path.join(local(raw, "nvidia/miracl-vision"), "zh")
    corpus = read_parquet(os.path.join(repo, "corpus.parquet"), ["_id", "title", "text", "image_id"])
    queries = read_parquet(os.path.join(repo, "queries.parquet"))
    qrels = read_parquet(os.path.join(repo, "qrels.parquet"))
    position = {row["_id"]: n for n, row in enumerate(corpus)}
    positives = defaultdict(set)
    for r in qrels:
        if int(r["score"]) > 0 and str(r["corpus-id"]) in position:
            positives[str(r["query-id"])].add(str(r["corpus-id"]))
    say("mvision: BM25 over", len(corpus), "pages")
    bm25 = BM25([row["title"] + "\n" + row["text"] for row in corpus], "zh")
    candidates = []
    for q in queries:
        if not positives[str(q["_id"])]:
            continue
        ranked = [corpus[i]["_id"] for i in bm25.top(q["text"], 60)]
        candidates.append({"id": q["_id"], "text": q["text"], "pos": positives[q["_id"]], "ranked": ranked,
                           "hard": not (set(ranked[:10]) & positives[q["_id"]])})
    picked = stratified(block.rng, candidates, BLOCKS[block.name]["questions"], lambda c: "all", lambda c: c["hard"])
    gone = split_no_answer(block.rng, picked, lambda a, b: bool(a["pos"] & b["pos"]))
    keep = [c for c in picked if c not in gone]
    removed = set().union(*(c["pos"] for c in gone)) if gone else set()
    pages = set().union(*(c["pos"] for c in keep))
    target = 2000
    depth = 0
    while len(pages) < target and depth < 60:
        for c in picked:
            if depth < len(c["ranked"]) and c["ranked"][depth] not in removed:
                pages.add(c["ranked"][depth])
                if len(pages) >= target:
                    break
        depth += 1
    pages = sorted(pages, key=lambda p: position[p])
    order = list(pages)
    block.rng.shuffle(order)
    as_png = set(order[: len(order) // 2])
    pdf_pages = [p for p in order if p not in as_png]
    # PDFs of 3–8 pages each, in the shuffled order.
    bundles, start = [], 0
    while start < len(pdf_pages):
        size = block.rng.randint(3, 8)
        bundles.append(pdf_pages[start:start + size])
        start += size
    where = {}
    for page in sorted(as_png, key=lambda p: position[p]):
        where[page] = (block.names.make("截图/截屏{d} 下午{t}.png"), None)
    for bundle in bundles:
        name = block.names.make(block.rng.choice(["扫描/扫描件_{n}.pdf", "下载/文档 {n}.pdf", "扫描/Scan {d} {n}.pdf"]))
        for number, page in enumerate(bundle, 1):
            where[page] = (name, number)
    image_id = {row["_id"]: row["image_id"] for row in corpus}
    wanted = {image_id[p]: p for p in where}
    pictures = {}
    import pyarrow.parquet as pq
    parquet = pq.ParquetFile(os.path.join(repo, "images.parquet"))
    for group in range(parquet.num_row_groups):
        for row in parquet.read_row_group(group).to_pylist():
            page = wanted.get(row["file_name"])
            if page is None:
                continue
            data = image_bytes(row["image"])
            name, number = where[page]
            if number is None:
                save_picture(data, os.path.join(block.root, name), "PNG")
            else:
                pictures[page] = data
    from PIL import Image
    for bundle in bundles:
        name = where[bundle[0]][0]
        images = [Image.open(io.BytesIO(pictures[p])).convert("RGB") for p in bundle]
        os.makedirs(os.path.dirname(os.path.join(block.root, name)), exist_ok=True)
        images[0].save(os.path.join(block.root, name), "PDF", resolution=144.0, save_all=True, append_images=images[1:],
                       title="", author="", producer="", creator="")
    for page, (name, number) in where.items():
        block.files[page] = {"file": name, **({"page": number} if number else {})}

    def key(page):
        name, number = where[page]
        return f"{name}@{number}-{number}" if number else name

    for c in keep:
        expect = sorted(key(p) for p in c["pos"])
        kinds = {"pdf" if where[p][1] else "png" for p in c["pos"]}
        block.question(c["id"], c["text"], expect, ("+".join(sorted(kinds))) + ("/bm25-miss" if c["hard"] else "/bm25-top10"))
        for p in c["pos"]:
            block.qrels.append((c["id"], key(p).rsplit("-", 1)[0] if where[p][1] else key(p), 1))
    for c in gone:
        block.question(c["id"], c["text"], [], "none-near")
    block.extra["pdf_pages"] = {where[b[0]][0]: len(b) for b in bundles}
    block.write({"pages": f"nvidia/miracl-vision@{HF['nvidia/miracl-vision'][0]} (zh)"})


def write_passages(block, passages, chosen):
    """One file per passage: 80% .txt/.md, 20% made into .docx/.pptx. `passages`: id -> (title, text)."""
    templates = TEXT_TEMPLATES[block.lang]
    ids = sorted(chosen)
    formats = text_formats(block.rng, len(ids))
    for pid, fmt in zip(ids, formats):
        name = block.names.make(block.rng.choice(templates[fmt]))
        title, text = passages[pid]
        write_text_file(os.path.join(block.root, name), fmt, title, text)
        block.files[pid] = {"file": name}
    block.extra["formats"] = dict(Counter(formats))


def passage_block(block, passages, questions, target, judged_negatives, hard_per_query, same_group=None):
    """The passage blocks (T2, MIRACL). `questions`: picked questions with "pos" (ids answering it), "judged" (id ->
    grade, every judged passage) and "ranked" (BM25 order over the source corpus). Without-answer questions lose every
    passage judged relevant to them (and, with `same_group`, every passage of the same article)."""
    gone = split_no_answer(block.rng, questions,
                           lambda a, b: bool(a["pos"] & b["pos"]) or bool(
                               same_group and {same_group(p) for p in a["pos"]} & {same_group(p) for p in b["pos"]}))
    keep = [q for q in questions if q not in gone]
    removed = set()
    for q in gone:
        removed |= q["pos"]
        removed |= {p for p, grade in q["judged"].items() if grade > 0}
    gone_groups = {same_group(p) for p in removed} if same_group else set()

    def allowed(p):
        return p in passages and p not in removed and not (same_group and same_group(p) in gone_groups)

    chosen = set()
    for q in keep:
        chosen |= {p for p in q["judged"] if q["judged"][p] > 0 and allowed(p)}
    for q in questions:
        negatives = sorted((p for p, g in q["judged"].items() if g == 0 and allowed(p)))
        block.rng.shuffle(negatives)
        chosen |= set(negatives[:judged_negatives])
    for q in questions:
        added = 0
        for p in q["ranked"]:
            if added >= hard_per_query or len(chosen) >= target:
                break
            if allowed(p) and p not in chosen:
                chosen.add(p)
                added += 1
    pool = sorted(p for p in passages if allowed(p) and p not in chosen)
    block.rng.shuffle(pool)
    random_count = max(0, target - len(chosen))
    chosen |= set(pool[:random_count])
    block.extra["composition"] = {"judged_relevant_and_negatives_and_bm25": len(chosen) - random_count,
                                  "random": random_count}
    write_passages(block, passages, chosen)
    for q in keep:
        expect = sorted(block.files[p]["file"] for p in q["pos"] if p in chosen)
        block.question(q["id"], q["text"], expect, q["tag"])
        for p, grade in q["judged"].items():
            if p in chosen:
                block.qrels.append((q["id"], block.files[p]["file"], grade))
    for q in gone:
        block.question(q["id"], q["text"], [], "none-near")


def build_t2(raw, out):
    """T2Retrieval (T2Ranking dev): 300 questions in strata of their best grade (3 or 2) and BM25 difficulty;
    about 5,000 passages. Relevant = grade 2 or 3 (as T2Ranking counts it); the grades 0–3 go to the qrels."""
    block = Block("t2-zh", out)
    repo = local(raw, "mteb/T2Retrieval")
    rows = read_parquet(os.path.join(repo, "corpus/dev-00000-of-00001.parquet"))
    passages = {str(r["_id"]): ((r.get("title") or "").strip(), r["text"].strip()) for r in rows}
    queries = {str(r["_id"]): r["text"] for r in read_parquet(os.path.join(repo, "queries/dev-00000-of-00001.parquet"))}
    judged = defaultdict(dict)
    with open(os.path.join(local(raw, "THUIR/T2Ranking"), "data/qrels.dev.tsv"), encoding="utf-8") as handle:
        next(handle)
        for line in handle:
            qid, _, pid, grade = line.rstrip("\n").split("\t")
            if qid in queries and pid in passages:
                judged[qid][pid] = int(grade)
    candidates = [q for q in sorted(judged, key=int) if any(g >= 2 for g in judged[q].values())]
    block.rng.shuffle(candidates)
    pool = candidates[:1500]
    ids = sorted(passages)
    say("t2: BM25 over", len(ids), "passages for", len(pool), "candidate questions")
    bm25 = BM25([passages[p][0] + " " + passages[p][1] for p in ids], "zh")
    items = []
    for qid in pool:
        pos = {p for p, g in judged[qid].items() if g >= 2}
        ranked = [ids[i] for i in bm25.top(queries[qid], 30)]
        hard = not (set(ranked[:10]) & pos)
        best = max(judged[qid].values())
        items.append({"id": qid, "text": queries[qid], "pos": pos, "judged": judged[qid], "ranked": ranked,
                      "hard": hard, "best": best, "tag": f"grade{best}/" + ("bm25-miss" if hard else "bm25-top10")})
    picked = stratified(block.rng, items, BLOCKS[block.name]["questions"], lambda q: q["best"], lambda q: q["hard"])
    passage_block(block, passages, picked, 5000, judged_negatives=2, hard_per_query=4)
    block.write({"passages and questions": f"mteb/T2Retrieval@{HF['mteb/T2Retrieval'][0]}",
                 "graded judgments": f"THUIR/T2Ranking@{HF['THUIR/T2Ranking'][0]} data/qrels.dev.tsv"})


def build_miracl(raw, out, lang):
    """MIRACL dev (the hard-negatives subset MTEB publishes): Wikipedia passages; 150 (zh) or 100 (en) questions."""
    block = Block(f"miracl-{lang}", out)
    repo = local(raw, "mteb/MIRACLRetrievalHardNegatives")
    rows = read_parquet(os.path.join(repo, f"{lang}-corpus/dev-00000-of-00001.parquet"))
    passages = {str(r.get("_id", r.get("id"))): ((r.get("title") or "").strip(), r["text"].strip()) for r in rows}
    queries = {str(r["id"]): r["text"] for r in read_parquet(os.path.join(repo, f"{lang}-queries/dev-00000-of-00001.parquet"))}
    judged = defaultdict(dict)
    for r in read_parquet(os.path.join(repo, f"{lang}-qrels/dev-00000-of-00001.parquet")):
        if str(r["corpus-id"]) in passages:
            judged[str(r["query-id"])][str(r["corpus-id"])] = int(r["score"])
    ids = sorted(passages)
    say(f"miracl-{lang}: BM25 over", len(ids), "passages")
    bm25 = BM25([passages[p][0] + " " + passages[p][1] for p in ids], lang)
    items = []
    for qid in sorted(judged):
        pos = {p for p, g in judged[qid].items() if g > 0}
        if not pos or qid not in queries:
            continue
        ranked = [ids[i] for i in bm25.top(queries[qid], 30)]
        hard = not (set(ranked[:10]) & pos)
        items.append({"id": qid, "text": queries[qid], "pos": pos, "judged": judged[qid], "ranked": ranked,
                      "hard": hard, "tag": "bm25-miss" if hard else "bm25-top10"})
    picked = stratified(block.rng, items, BLOCKS[block.name]["questions"], lambda q: "all", lambda q: q["hard"])
    passage_block(block, passages, picked, 2500 if lang == "zh" else 2000, judged_negatives=3, hard_per_query=4,
                  same_group=lambda p: p.split("#")[0])
    block.write({"passages and questions": f"mteb/MIRACLRetrievalHardNegatives@{HF['mteb/MIRACLRetrievalHardNegatives'][0]} ({lang} dev)"})


def has_text_layer(path, sample=5):
    """Whether a PDF has text to extract on a few pages spread through it (a scan has none)."""
    from pypdf import PdfReader
    reader = PdfReader(path)
    count = len(reader.pages)
    picks = sorted({int(i * (count - 1) / max(sample - 1, 1)) for i in range(sample)}) if count else []
    return sum(len((reader.pages[i].extract_text() or "").strip()) for i in picks) > 200


def replace_dropped(short, folder, allowed_docs, items, picked, keep, gone, cut):
    """Takes out the questions that need a dropped document (DROPPED_VIDORE) and puts in as many others from the same
    dataset, each of the same type and difficulty as one taken out if there is one (then the same difficulty, then
    any), in an order drawn from the seed. Only questions whose pages are all in documents of at most
    REPLACEMENT_MAX_BYTES, kept, and not cut for a question without an answer; those with a text layer first."""
    dropped = DROPPED_VIDORE.get(short, set())
    if not dropped:
        return keep
    if any(doc in dropped for q in gone for doc, _ in q["pos"]):
        sys.exit(f"vidore {short}: a question without an answer uses a dropped document")
    out = [q for q in keep if not any(doc in dropped for doc, _ in q["pos"])]
    order = DROPPED_ORDER[short]

    def round_of(q):
        return min(order.index(doc) for doc, _ in q["pos"] if doc in dropped)

    removed = sorted((q for q in keep if q not in out), key=lambda q: (round_of(q), q["id"]))
    size = {doc: os.path.getsize(os.path.join(folder, "pdfs", allowed_docs[doc]["file_name"])) for doc in allowed_docs}
    text = {}
    taken = {id(q) for q in picked}

    def usable(q):
        return (id(q) not in taken and all(doc not in dropped and size[doc] <= REPLACEMENT_MAX_BYTES
                                           and page not in cut[doc] for doc, page in q["pos"]))

    candidates = sorted((q for q in items if usable(q)), key=lambda q: q["id"])
    random.Random(f"{SEED}-vidore-replace-{short}").shuffle(candidates)

    def texty(q):
        for doc in {doc for doc, _ in q["pos"]}:
            if doc not in text:
                text[doc] = has_text_layer(os.path.join(folder, "pdfs", allowed_docs[doc]["file_name"]))
            if not text[doc]:
                return False
        return True

    chosen = []
    for old in removed:
        for test in (lambda q: q["kind"] == old["kind"] and q["hard"] == old["hard"],
                     lambda q: q["hard"] == old["hard"], lambda q: True):
            match = next((q for need_text in (True, False) for q in candidates
                          if q not in chosen and test(q) and texty(q) == need_text), None)
            if match:
                break
        if match is None:
            sys.exit(f"vidore {short}: not enough questions to replace {old['id']}")
        chosen.append(match)
        say(f"vidore {short}: {old['id']} ({old['kind']}, {'hard' if old['hard'] else 'easy'}) -> "
            f"{match['id']} ({match['kind']}, {'hard' if match['hard'] else 'easy'})")
    return out + chosen


def build_vidore(raw, out):
    """ViDoRe v3 (hr, finance_en, industrial), English questions only: 50 per dataset, the whole PDFs. The pages that
    answer a without-answer question are taken out of their PDF (pypdf), and the page numbers after them shift."""
    from pypdf import PdfReader, PdfWriter
    block = Block("vidore-en", out)
    names = Names(random.Random(f"{SEED}-vidore-en-names"))
    for repo in VIDORE:
        short = repo.split("_v3_")[1]
        folder = local(raw, repo)
        meta = read_parquet(os.path.join(folder, "documents_metadata/test-00000-of-00001.parquet"))
        allowed_docs = {m["doc_id"]: m for m in meta if m["license"].startswith(REDISTRIBUTABLE)
                        and os.path.exists(os.path.join(folder, "pdfs", m["file_name"]))}
        skipped = sorted(m["doc_id"] for m in meta if m["doc_id"] not in allowed_docs)
        pages = {}
        with open(os.path.join(folder, "corpus_pages.jsonl"), encoding="utf-8") as handle:
            for line in handle:
                row = json.loads(line)
                pages[int(row["corpus_id"])] = row
        base = min(int(r["page_number_in_doc"]) for r in pages.values())   # 0 or 1, made 1-based below
        queries = [q for q in read_parquet(os.path.join(folder, "queries/test-00000-of-00001.parquet"))
                   if q["language"] == "english"]
        grades = defaultdict(dict)
        for r in read_parquet(os.path.join(folder, "qrels/test-00000-of-00001.parquet")):
            row = pages.get(int(r["corpus_id"]))
            if row and int(r["score"]) > 0:
                grades[str(r["query_id"])][(row["doc_id"], int(row["page_number_in_doc"]) - base + 1)] = int(r["score"])
        ids = sorted(pages)
        say(f"vidore {short}: BM25 over", len(ids), "pages")
        bm25 = BM25([pages[i]["markdown"] or "" for i in ids], "en")
        items = []
        for q in queries:
            judged = grades.get(str(q["query_id"]))
            if not judged or any(doc not in allowed_docs for doc, _ in judged):
                continue
            top = {(pages[ids[i]]["doc_id"], int(pages[ids[i]]["page_number_in_doc"]) - base + 1)
                   for i in bm25.top(q["query"], 10)}
            hard = not (top & set(judged))
            types = q["query_types"]
            types = list(types) if isinstance(types, (list, tuple)) else re.findall(r"[a-z-]+", types or "")
            kind = (types or ["-"])[0]
            items.append({"id": f"{short}-{q['query_id']}", "text": q["query"].strip(), "pos": set(judged),
                          "judged": judged, "hard": hard, "kind": kind,
                          "tag": f"{short}/" + ("bm25-miss" if hard else "bm25-top10")})
        picked = stratified(block.rng, items, 50, lambda q: q["kind"], lambda q: q["hard"])
        small = [q for q in picked if len(q["pos"]) <= 3]
        gone = []
        # Only questions with at most three answer pages may lose them, and none of those pages may answer another
        # picked question.
        want = round(50 * NO_ANSWER_SHARE)
        order = list(small)
        block.rng.shuffle(order)
        for q in order:
            if len(gone) == want:
                break
            if any(q["pos"] & other["pos"] for other in picked if other is not q and other not in gone):
                continue
            gone.append(q)
        keep = [q for q in picked if q not in gone]
        cut = defaultdict(set)
        for q in gone:
            for doc, page in q["pos"]:
                cut[doc].add(page)
        keep = replace_dropped(short, folder, allowed_docs, items, picked, keep, gone, cut)
        new_page = {}
        for doc in sorted(allowed_docs):
            meta_row = allowed_docs[doc]
            name = names.make(block.rng.choice(["Documents/report {n}.pdf", "Downloads/document ({n}).pdf",
                                                "Documents/scan_{n}.pdf"]))
            if doc in DROPPED_VIDORE.get(short, ()):
                continue   # its name is still drawn, so every other document keeps the name it had
            reader = PdfReader(os.path.join(folder, "pdfs", meta_row["file_name"]))
            total = len(reader.pages)
            target = os.path.join(block.root, name)
            os.makedirs(os.path.dirname(target), exist_ok=True)
            if cut[doc]:
                writer = PdfWriter()
                for number, page in enumerate(reader.pages, 1):
                    if number not in cut[doc]:
                        writer.add_page(page)
                writer.add_metadata({"/Title": "", "/Author": "", "/Subject": "", "/Keywords": ""})
                with open(target, "wb") as handle:
                    writer.write(handle)
            else:
                shutil.copyfile(os.path.join(folder, "pdfs", meta_row["file_name"]), target)
            kept = 0
            for number in range(1, total + 1):
                if number in cut[doc]:
                    continue
                kept += 1
                new_page[(doc, number)] = (name, kept)
            block.files[f"{short}/{doc}"] = {"file": name, "pages": kept, "source_pages": total,
                                             "removed_pages": sorted(cut[doc]), "license": meta_row["license"],
                                             "url": meta_row["url"]}
        for q in keep:
            expect, rels = [], []
            for (doc, page), grade in sorted(q["judged"].items()):
                if (doc, page) not in new_page:
                    continue
                name, number = new_page[(doc, page)]
                expect.append(f"{name}@{number}-{number}")
                rels.append((q["id"], f"{name}@{number}", grade))
            if not expect:
                continue
            block.question(q["id"], q["text"], expect, q["tag"], domain=short, type=q["kind"])
            block.qrels.extend(rels)
        for q in gone:
            block.question(q["id"], q["text"], [], "none-near", domain=short, type=q["kind"])
        block.extra.setdefault("skipped_documents", {})[short] = skipped + sorted(DROPPED_VIDORE.get(short, ()))
    block.names = names
    block.write({repo: f"{repo}@{HF[repo][0]}" for repo in VIDORE})


# -------------------------------------------------------------------------------------------------------------- pack

FILE_TIME = 1780272000   # 2026-06-01 00:00 UTC: every packed file gets this time, so packing twice gives the same tar


def pack(out, assets, only=None):
    """One <block>.tar.gz per block (files in sorted order, fixed times and owners), and corpus.sha256 here."""
    os.makedirs(assets, exist_ok=True)
    lines = {}
    manifest = os.path.join(HERE, "corpus.sha256")
    if os.path.exists(manifest):
        for line in open(manifest, encoding="utf-8"):
            if line.strip():
                digest, name = line.split()
                lines[name] = digest
    for name in BLOCKS:
        if only and name not in only:
            continue
        root = os.path.join(out, name)
        if not os.path.isdir(root):
            say("not built:", name)
            continue
        target = os.path.join(assets, f"{name}.tar.gz")
        entries = []
        for folder, subfolders, files in os.walk(root):
            subfolders.sort()
            for entry in [folder] + [os.path.join(folder, f) for f in sorted(files)]:
                entries.append(entry)
        with open(target + ".part", "wb") as raw_handle:
            with gzip.GzipFile(filename="", mode="wb", fileobj=raw_handle, mtime=0, compresslevel=6) as zipped:
                with tarfile.open(fileobj=zipped, mode="w", format=tarfile.PAX_FORMAT) as tar:
                    for entry in sorted(set(entries)):
                        if os.path.basename(entry).startswith("."):
                            continue
                        info = tar.gettarinfo(entry, arcname=os.path.join(name, os.path.relpath(entry, root)).rstrip("/."))
                        info.mtime, info.uid, info.gid, info.uname, info.gname = FILE_TIME, 0, 0, "", ""
                        info.mode = 0o755 if info.isdir() else 0o644
                        info.pax_headers = {}
                        if info.isfile():
                            with open(entry, "rb") as handle:
                                tar.addfile(info, handle)
                        else:
                            tar.addfile(info)
        os.replace(target + ".part", target)
        digest = hashlib.sha256()
        with open(target, "rb") as handle:
            for chunk in iter(lambda: handle.read(1 << 20), b""):
                digest.update(chunk)
        lines[f"{name}.tar.gz"] = digest.hexdigest()
        say(f"{name}.tar.gz  {os.path.getsize(target) / 1e6:.1f} MB")
    with open(manifest, "w", encoding="utf-8") as handle:
        for name in sorted(lines):
            handle.write(f"{lines[name]}  {name}\n")


BUILDERS = {
    "xm3600-zh": build_xm3600,
    "mvision-zh": build_mvision,
    "vidore-en": build_vidore,
    "t2-zh": build_t2,
    "miracl-zh": lambda raw, out: build_miracl(raw, out, "zh"),
    "miracl-en": lambda raw, out: build_miracl(raw, out, "en"),
}


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    sub = parser.add_subparsers(dest="command", required=True)
    one = sub.add_parser("download", help="the source files, at the pinned revisions")
    one.add_argument("--raw", required=True)
    two = sub.add_parser("build", help="corpora, sets/ and ids/ from the source files")
    two.add_argument("--raw", required=True)
    two.add_argument("--out", required=True)
    two.add_argument("--block", action="append", choices=sorted(BLOCKS))
    three = sub.add_parser("pack", help="one .tar.gz per block, and corpus.sha256")
    three.add_argument("--out", required=True)
    three.add_argument("--assets", required=True)
    three.add_argument("--block", action="append", choices=sorted(BLOCKS))
    args = parser.parse_args()
    if args.command == "download":
        download(os.path.abspath(args.raw))
    elif args.command == "build":
        for name in BLOCKS:
            if not args.block or name in args.block:
                BUILDERS[name](os.path.abspath(args.raw), os.path.abspath(args.out))
    else:
        pack(os.path.abspath(args.out), os.path.abspath(args.assets), args.block)


if __name__ == "__main__":
    main()