File size: 28,065 Bytes
35a8678
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download a set of sources, verify every file, and write the manifests.



usage: python data/fetch.py [--set phase1|phase3|phase3-check|bench] [--root DIR] [--only NAME ...] [--jobs N]



The sets: phase1, the training data and the first evaluation sets (into DIR/<name>);

phase3, phase 3's on top of it;

phase3-check, the sets of phase 3 whose license is still to be confirmed (DocBank); bench, the

other benchmarks (into DIR/bench/<name>). DIR defaults to carbon-data next

to the repository, outside it, so `git clean` can never touch it. Each source gets

data/manifests/<set>/<name>.json: where every file came from, its size and SHA-256, the

checksum the source publishes (Hugging Face LFS SHA-256 or git blob id, Zenodo and PMC

MD5), and whether the two agree. A Hugging Face source is fetched at one commit, its

pinned `revision` or else the head when the fetch starts, and the manifest records it:

benchmark scores compare only at the same revision. A rerun resumes: files already

complete are only re-hashed.



Sources and slices are declared in sources.py.

"""
import argparse
import concurrent.futures as cf
import fnmatch
import hashlib
import http.client
import json
import random
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path

from sources import SETS

HERE = Path(__file__).resolve().parent
REPO = HERE.parent
DEFAULT_ROOT = REPO.parent / "carbon-data"
MANIFESTS = HERE / "manifests"
# where each set's data goes under the root
SUBDIR = {"phase1": "", "phase3": "", "phase3-check": "", "bench": "bench"}
UA = "Carbon-OCR data fetch (https://github.com/karanvora2599/Carbon-OCR)"
CHUNK = 8 * 1024 * 1024
_print_lock = threading.Lock()


def log(name, msg):
    with _print_lock:
        print(f"[{datetime.now():%H:%M:%S}] {name}: {msg}", flush=True)


def human(n):
    for u in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024:
            return f"{n:.1f} {u}"
        n /= 1024
    return f"{n:.1f} PB"


def file_hash(path, algo="sha256"):
    h = hashlib.new(algo)
    with open(path, "rb") as f:
        while block := f.read(CHUNK):
            h.update(block)
    return h.hexdigest()


def git_blob_id(path):
    """The id git gives a file's content: what Hugging Face reports for files not in LFS."""
    data = Path(path).read_bytes()
    return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()


def request(url, headers=None, timeout=120, tries=6):
    """GET with retries on transient errors and on 429/503, honouring Retry-After."""
    for k in range(tries):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": UA, **(headers or {})})
            return urllib.request.urlopen(req, timeout=timeout)
        except urllib.error.HTTPError as e:
            if e.code in (429, 500, 502, 503, 504) and k < tries - 1:
                time.sleep(float(e.headers.get("Retry-After") or 10 * (k + 1)))
                continue
            raise
        except (urllib.error.URLError, TimeoutError, ConnectionError):
            if k == tries - 1:
                raise
            time.sleep(10 * (k + 1))


def http_download(url, dest, expected=None, tries=6):
    """Resumable download. Returns bytes on disk; fails if a known size disagrees. A stream that

    ends short, or breaks partway (a read timeout, a reset connection), is opened again from the

    byte it reached (Range) and appended to, up to `tries` times with a longer wait each time,

    each resume logged: an unattended fetch of hundreds of GB goes on past a dropped connection

    (v2's GT4HistOCR ended at 1.19 of 4.03 GB, its pmc-oa timed out after an hour). When the

    tries are spent it fails, and the .part file stays for a rerun to resume."""
    dest.parent.mkdir(parents=True, exist_ok=True)
    part = dest.with_name(dest.name + ".part")
    if dest.exists() and (expected is None or dest.stat().st_size == expected):
        return dest.stat().st_size
    for k in range(tries):
        have = part.stat().st_size if part.exists() else 0
        headers = {"Range": f"bytes={have}-"} if have else {}
        total, broke = None, None
        try:
            with request(url, headers, timeout=300) as r:
                if have and r.status != 206:  # the server ignored the range: start over
                    have = 0
                total = int(r.headers.get("Content-Length", 0)) + have if r.headers.get("Content-Length") else None
                with open(part, "ab" if have else "wb") as f:
                    while block := r.read(CHUNK):
                        f.write(block)
        except urllib.error.HTTPError:
            raise  # an answer, not a dropped connection: request() has retried what retrying helps
        except (TimeoutError, urllib.error.URLError, ConnectionError, http.client.IncompleteRead) as e:
            broke = f"{type(e).__name__}: {e}"
        size = part.stat().st_size if part.exists() else 0
        want = expected or total
        if broke is None:
            if want is None or size == want:
                part.replace(dest)
                return size
            if size > want:
                raise IOError(f"{url}: got {size} bytes, expected {want}")
            broke = f"got {size} bytes, expected {want}"
        if k == tries - 1:
            raise IOError(f"{url}: {broke}, after {tries} tries ({part.name} kept: a rerun resumes it)")
        log(dest.name, f"{broke}: resuming at byte {size:,} in {10 * (k + 1)} s (try {k + 2} of {tries})")
        time.sleep(10 * (k + 1))


# ------------------------------------------------------------------ fetchers

def _git_head(dest):
    """A clone's commit, or a RuntimeError carrying git's own words."""
    try:
        return subprocess.run(["git", "-C", str(dest), "rev-parse", "HEAD"], check=True, capture_output=True,
                              text=True).stdout.strip()
    except subprocess.CalledProcessError as e:
        detail = (e.stderr or e.stdout or "").strip()
        raise RuntimeError(f"git rev-parse in {dest} failed (exit {e.returncode}): {detail[-2000:]}") from e


def fetch_git(src, dest):
    """A repository at its head, shallow. A clone that fails is reported with git's own error (its

    exit status alone says nothing) and removed, so a rerun clones again rather than finding a

    .git that git cannot read; a clone an earlier run left unreadable is cloned again, once."""
    def clone():
        fresh = not dest.exists() or not any(dest.iterdir())  # never remove what the clone did not make
        try:
            subprocess.run(["git", "-c", "core.longpaths=true", "clone", "--depth", "1", "--single-branch",
                            src["url"], str(dest)], check=True, capture_output=True, text=True)
        except subprocess.CalledProcessError as e:
            if fresh:
                shutil.rmtree(dest, ignore_errors=True)
            detail = (e.stderr or e.stdout or "").strip()
            raise RuntimeError(f"git clone {src['url']} failed (exit {e.returncode}): {detail[-2000:]}") from e

    if not (dest / ".git").exists():
        clone()
    try:
        commit = _git_head(dest)
    except RuntimeError as e:
        log(src.get("name", dest.name), f"{e}: cloning again")
        shutil.rmtree(dest, ignore_errors=True)
        clone()
        commit = _git_head(dest)
    n, size = 0, 0
    for p in dest.rglob("*"):
        if p.is_file() and ".git" not in p.relative_to(dest).parts:
            n += 1
            size += p.stat().st_size
    # git checks every object it receives, so the commit id stands for the whole tree
    return [dict(path=".", url=src["url"], commit=commit, files=n, bytes=size, verified=True,
                 check="git object ids")]


def hf_head(repo):
    """The commit a dataset's main branch is at now."""
    from huggingface_hub import HfApi
    for k in range(6):
        try:
            return HfApi().dataset_info(repo).sha
        except Exception:  # noqa: BLE001  (rate limits on the Hub API)
            if k == 5:
                raise
            time.sleep(30 * (k + 1))


def hf_listing(repo, prefix=None, revision=None):
    from huggingface_hub import HfApi
    api = HfApi()
    for k in range(6):
        try:
            return [f for f in api.list_repo_tree(repo, repo_type="dataset", path_in_repo=prefix, recursive=True,
                                                  expand=True, revision=revision)
                    if getattr(f, "size", None) is not None]
        except Exception as e:  # noqa: BLE001  (rate limits on the Hub API)
            if k == 5:
                raise
            time.sleep(30 * (k + 1))


def hf_pattern(path):
    """A repo path as an allow pattern. The Hub matches with fnmatch, which reads [ * ? as

    wildcards, and file names have them (OmniDocBench: book_en_[...][HTML5 Canvas]...png)."""
    return re.sub(r"([\[*?])", r"[\1]", path)


def hf_snapshot(src, dest, files):
    from huggingface_hub import snapshot_download
    for k in range(6):
        try:
            snapshot_download(src["repo"], repo_type="dataset", local_dir=str(dest), revision=src.get("revision"),
                              allow_patterns=[hf_pattern(f.path) for f in files], max_workers=8)
            return
        except Exception as e:  # noqa: BLE001
            if k == 5:
                raise
            log(src["name"], f"retrying after {type(e).__name__}: {str(e)[:120]}")
            time.sleep(30 * (k + 1))


def hf_check(src, dest, f):
    p = dest / f.path
    rec = dict(path=f.path, url=f"https://huggingface.co/datasets/{src['repo']}/resolve/{src.get('revision', 'main')}/{f.path}",
               bytes=p.stat().st_size)
    if getattr(f, "lfs", None):
        rec["sha256"] = file_hash(p)
        rec["upstream"] = {"sha256": f.lfs.sha256}
        rec["verified"] = rec["sha256"] == f.lfs.sha256 and rec["bytes"] == f.size
    else:
        rec["git_blob_id"] = git_blob_id(p)
        rec["sha256"] = file_hash(p)
        rec["upstream"] = {"git_blob_id": f.blob_id}
        rec["verified"] = rec["git_blob_id"] == f.blob_id
    return rec


def hf_download(src, dest, files):
    """Download the given RepoFile entries, then check each against the Hub's checksum.

    A file that fails is deleted and downloaded once more."""
    hf_snapshot(src, dest, files)
    records = {f.path: hf_check(src, dest, f) for f in files}
    bad = [f for f in files if not records[f.path]["verified"]]
    if bad:
        log(src["name"], f"{len(bad)} files failed their checksum; downloading them again")
        for f in bad:
            (dest / f.path).unlink()
            # the local-dir cache would otherwise call the file up to date
            (dest / ".cache" / "huggingface" / "download" / (f.path + ".metadata")).unlink(missing_ok=True)
        hf_snapshot(src, dest, bad)
        records.update({f.path: hf_check(src, dest, f) for f in bad})
    return [records[f.path] for f in files]


def fetch_hf(src, dest):
    listing = hf_listing(src["repo"], revision=src.get("revision"))
    if src.get("files"):
        want = set(src["files"])
        files = [f for f in listing if f.path in want]
        missing = want - {f.path for f in files}
        assert not missing, f"not in {src['repo']}: {sorted(missing)}"
    elif src.get("patterns"):  # a slice by glob, such as one split
        files = [f for f in listing if any(fnmatch.fnmatchcase(f.path, p) for p in src["patterns"])]
        assert files, f"nothing in {src['repo']} matches {src['patterns']}"
    else:
        files = [f for f in listing if not f.path.endswith(".gitattributes")]
    log(src["name"], f"{len(files)} files, {human(sum(f.size for f in files))}")
    return hf_download(src, dest, files)


def fetch_hf_budget(src, dest):
    """The first files under each prefix (in name order, or with order "hash" in their names'

    hashes' order, so a collection's titles and years mix) up to the byte budget; with

    skip_bytes, after the files another set took by the same rule (phase 3's NVIDIA shards,

    past phase 1's); with a companion {prefix, pattern, replace}, each file taken brings the

    file its name maps to (a newspaper page's ALTO with its PDF), outside the budget."""
    import hashlib
    import re

    files = []
    for prefix in src["prefixes"]:
        listing = sorted(hf_listing(src["repo"], prefix.rstrip("/"), src.get("revision")), key=lambda f: f.path)
        if src.get("order") == "hash":
            listing.sort(key=lambda f: hashlib.sha256(f.path.encode()).hexdigest())
        start, skipped = 0, 0
        for f in listing:
            if skipped + f.size > src.get("skip_bytes", 0):
                break
            skipped += f.size
            start += 1
        picked, total = [], 0
        for f in listing[start:]:
            if total + f.size > src["budget_bytes"]:
                break
            picked.append(f)
            total += f.size
        log(src["name"], f"{prefix}: {len(picked)} files, {human(total)}")
        files += picked
        if src.get("companion"):
            c = src["companion"]
            others = {f.path: f for f in hf_listing(src["repo"], c["prefix"].rstrip("/"), src.get("revision"))}
            with_them = [others[n] for n in (re.sub(c["pattern"], c["replace"], f.path) for f in picked) if n in others]
            log(src["name"], f"{c['prefix']}: {len(with_them)} companions, {human(sum(f.size for f in with_them))}")
            files += with_them
    return hf_download(src, dest, files)


def fetch_hf_rowgroups(src, dest):
    """The first row groups of each Parquet file, up to the byte budget, read with

    HTTP range requests (the files are 4.5 GB each; a slice is all phase 1 needs)."""
    import pyarrow.parquet as pq
    from huggingface_hub import HfFileSystem
    fs = HfFileSystem()
    records = []
    for path in src["files"]:
        out = dest / (path.replace("/", "__"))
        if not out.exists():
            with fs.open(f"datasets/{src['repo']}/{path}", "rb", block_size=16 * 1024 * 1024) as fh:
                pf = pq.ParquetFile(fh)
                cols = [c for c in src["columns"] if c in pf.schema_arrow.names]
                groups, size = [], 0
                for i in range(pf.metadata.num_row_groups):
                    rg = pf.metadata.row_group(i)
                    if groups and size + rg.total_byte_size > src["budget_bytes"]:
                        break
                    groups.append(i)
                    size += rg.total_byte_size
                table = pf.read_row_groups(groups, columns=cols)
            out.parent.mkdir(parents=True, exist_ok=True)
            tmp = out.with_name(out.name + ".part")
            pq.write_table(table, tmp, compression="zstd")
            tmp.replace(out)
            (out.with_suffix(".slice.json")).write_text(json.dumps(
                {"upstream": path, "row_groups": groups, "rows": table.num_rows, "columns": cols}), encoding="utf-8")
        meta = json.loads(out.with_suffix(".slice.json").read_text(encoding="utf-8"))
        records.append(dict(path=out.name, url=f"https://huggingface.co/datasets/{src['repo']}/resolve/main/{path}",
                            bytes=out.stat().st_size, sha256=file_hash(out), slice=meta, verified=None,
                            check="a re-encoded slice of the upstream file: no upstream checksum applies"))
        log(src["name"], f"{path}: {meta['rows']} rows from {len(meta['row_groups'])} row groups")
    return records


def fetch_http(src, dest):
    records = []
    for url in src["urls"]:
        name = url.rsplit("/", 1)[-1]
        with request(url, timeout=60) as r:  # HEAD-like: the size, then close
            expected = int(r.headers["Content-Length"]) if r.headers.get("Content-Length") else None
        size = http_download(url, dest / name, expected)
        records.append(dict(path=name, url=url, bytes=size, sha256=file_hash(dest / name),
                            upstream={"content_length": expected}, verified=expected == size,
                            check="size against Content-Length (no published checksum)"))
        log(src["name"], f"{name}: {human(size)}")
    return records


def fetch_govinfo(src, dest):
    """A govinfo collection's package PDFs (GOVPUB: agency publications, most of them tagged)

    from its year sitemaps, which need no API key: the packages in a fixed order (their ids'

    hashes, so years and agencies mix) up to the byte budget, each file's size checked

    against the server's Content-Length (govinfo publishes no checksums). A package without

    a PDF is passed over."""
    import concurrent.futures
    import hashlib
    import re
    import urllib.error

    ids = []
    for year in src["years"]:
        url = f"https://www.govinfo.gov/sitemap/{src['collection']}_{year}_sitemap.xml"
        with request(url, timeout=120) as r:
            ids += re.findall(r"/app/details/([^<\s]+)</loc>", r.read().decode("utf-8", "replace"))
    ids = sorted(set(ids), key=lambda i: hashlib.sha256(i.encode()).hexdigest())
    log(src["name"], f"{len(ids)} packages in {src['collection']} {src['years'][0]}-{src['years'][-1]}")

    def one(pkg):
        url = f"https://www.govinfo.gov/content/pkg/{pkg}/pdf/{pkg}.pdf"
        try:
            with request(url, timeout=60) as r:
                expected = int(r.headers["Content-Length"]) if r.headers.get("Content-Length") else None
            size = http_download(url, dest / f"{pkg}.pdf", expected)
        except (urllib.error.HTTPError, IOError) as e:
            return None, f"{pkg}: {e}"
        return dict(path=f"{pkg}.pdf", url=url, bytes=size, sha256=file_hash(dest / f"{pkg}.pdf"),
                    upstream={"content_length": expected}, verified=expected == size,
                    check="size against Content-Length (no published checksum)"), None

    records, total, missing = [], 0, 0
    with concurrent.futures.ThreadPoolExecutor(8) as pool:
        for k in range(0, len(ids), 16):  # in batches, so the budget stops it close to its mark
            for rec, err in pool.map(one, ids[k:k + 16]):
                if rec is None:
                    missing += 1
                    continue
                records.append(rec)
                total += rec["bytes"]
            log(src["name"], f"{len(records)} PDFs, {human(total)}; {missing} packages without one")
            if total >= src["budget_bytes"]:
                break
    return records


def fetch_zenodo(src, dest):
    with request(f"https://zenodo.org/api/records/{src['record']}") as r:
        rec = json.load(r)
    records = []
    for f in rec["files"]:
        algo, digest = f["checksum"].split(":", 1)
        size = http_download(f["links"]["self"], dest / f["key"], f["size"])
        got = file_hash(dest / f["key"], algo)
        records.append(dict(path=f["key"], url=f["links"]["self"], bytes=size, sha256=file_hash(dest / f["key"]),
                            upstream={algo: digest}, verified=got == digest))
        log(src["name"], f"{f['key']}: {human(size)}, {algo} {'ok' if got == digest else 'MISMATCH'}")
    return records


S3_PMC = "https://pmc-oa-opendata.s3.amazonaws.com"


def s3_keys(prefix, start_after, n):
    url = f"{S3_PMC}/?list-type=2&prefix={prefix}&start-after={start_after}&max-keys={n}"
    with request(url) as r:
        return re.findall(r"<Key>([^<]+)</Key>", r.read().decode())


def fetch_pmc(src, dest):
    """Born-digital PMC articles under the allowed licenses, sampled across the

    whole PMC id range, up to the byte budget. Historical OCR scans are skipped:

    their text layer is OCR, not the publisher's."""
    rng = random.Random(1344132)
    starts = sorted(rng.sample(range(1_000_000, 12_500_000), 60))
    keys = []
    for s in starts:
        keys += s3_keys("metadata/", f"metadata/PMC{s}", 250)
    log(src["name"], f"{len(keys)} article records to screen")

    def meta(key):
        with request(f"{S3_PMC}/{key}") as r:
            return json.load(r)

    with cf.ThreadPoolExecutor(16) as pool:
        metas = list(pool.map(meta, keys))
    allowed = set(src["licenses"])
    licenses = {}
    for m in metas:
        licenses[m.get("license_code")] = licenses.get(m.get("license_code"), 0) + 1
    keep = [m for m in metas if m.get("license_code") in allowed and m.get("pdf_url")
            and not m.get("is_historical_ocr") and not m.get("is_retracted")]
    rng.shuffle(keep)
    log(src["name"], f"licenses seen: {licenses}; {len(keep)} eligible")

    records, total, lock = [], 0, threading.Lock()
    (dest / "metadata").mkdir(parents=True, exist_ok=True)

    def one(m):
        nonlocal total
        with lock:
            if total >= src["budget_bytes"]:
                return None
        s3 = m["pdf_url"]
        key, md5 = re.match(r"s3://pmc-oa-opendata/([^?]+)\?md5=([0-9a-f]+)", s3).groups()
        out = dest / "pdf" / Path(key).name
        size = http_download(f"{S3_PMC}/{key}", out)
        ok = file_hash(out, "md5") == md5
        (dest / "metadata" / f"{m['pmcid']}.{m['version']}.json").write_text(json.dumps(m), encoding="utf-8")
        with lock:
            total += size
        return dict(path=f"pdf/{out.name}", url=f"{S3_PMC}/{key}", bytes=size, sha256=file_hash(out),
                    upstream={"md5": md5}, verified=ok, license=m["license_code"], pmcid=m["pmcid"])

    with cf.ThreadPoolExecutor(12) as pool:
        for r in pool.map(one, keep):
            if r:
                records.append(r)
    log(src["name"], f"{len(records)} PDFs, {human(total)}")
    return records


OAI = "https://oaipmh.arxiv.org/oai"
NS = {"o": "http://www.openarchives.org/OAI/2.0/", "a": "http://arxiv.org/OAI/arXiv/"}


def fetch_arxiv(src, dest):
    """CC-licensed papers from one OAI set, PDFs fetched one request every 3 s

    (arXiv's rate for scripted access outside the bulk S3 bucket)."""
    picked, token = [], None
    allowed = set(src["licenses"])
    while len(picked) < src["count"]:
        q = f"verb=ListRecords&resumptionToken={token}" if token else \
            f"verb=ListRecords&metadataPrefix=arXiv&set={src['oai_set']}&from={src['oai_from']}"
        with request(f"{OAI}?{q}", timeout=300) as r:
            root = ET.fromstring(r.read())
        for rec in root.iter(f"{{{NS['o']}}}record"):
            md = rec.find(".//a:arXiv", NS)
            if md is None:
                continue
            lic = (md.findtext("a:license", default="", namespaces=NS) or "").strip()
            if lic in allowed:
                picked.append(dict(id=md.findtext("a:id", namespaces=NS), license=lic,
                                   categories=md.findtext("a:categories", namespaces=NS),
                                   title=" ".join((md.findtext("a:title", namespaces=NS) or "").split())))
        t = root.find(".//o:resumptionToken", NS)
        token = t.text if t is not None and t.text else None
        if not token:
            break
        time.sleep(3)
    picked = picked[:src["count"]]
    log(src["name"], f"{len(picked)} papers with an allowed license")
    (dest / "pdf").mkdir(parents=True, exist_ok=True)
    (dest / "papers.jsonl").write_text("\n".join(json.dumps(p) for p in picked), encoding="utf-8")
    records = []
    for i, p in enumerate(picked):
        out = dest / "pdf" / (p["id"].replace("/", "_") + ".pdf")
        if not out.exists():
            try:
                http_download(f"https://export.arxiv.org/pdf/{p['id']}", out)
            except Exception as e:  # noqa: BLE001  (a withdrawn paper, a timeout)
                log(src["name"], f"{p['id']}: {type(e).__name__}")
                continue
            time.sleep(3)
        head = out.read_bytes()[:5]
        records.append(dict(path=f"pdf/{out.name}", url=f"https://arxiv.org/pdf/{p['id']}", bytes=out.stat().st_size,
                            sha256=file_hash(out), verified=head == b"%PDF-", check="PDF header (no published checksum)",
                            license=p["license"], arxiv_id=p["id"]))
        if i % 100 == 99:
            log(src["name"], f"{i + 1}/{len(picked)} PDFs")
    return records


FETCHERS = dict(git=fetch_git, hf=fetch_hf, hf_budget=fetch_hf_budget, hf_rowgroups=fetch_hf_rowgroups,
                http=fetch_http, zenodo=fetch_zenodo, pmc=fetch_pmc, arxiv=fetch_arxiv, govinfo=fetch_govinfo)


def run(src, root, set_name):
    dest = root / SUBDIR[set_name] / src["name"]
    dest.mkdir(parents=True, exist_ok=True)
    t0 = time.time()
    log(src["name"], f"start ({src['kind']}) -> {dest}")
    try:
        if src["kind"] in ("hf", "hf_budget") and not src.get("revision"):
            src = dict(src, revision=hf_head(src["repo"]))  # one commit for the listing and the download
        files = FETCHERS[src["kind"]](src, dest)
        error = None
    except Exception as e:  # noqa: BLE001  (record it; the other sources go on)
        files, error = [], f"{type(e).__name__}: {e}"
        log(src["name"], f"FAILED {error}")
    total = sum(f["bytes"] for f in files)
    bad = [f["path"] for f in files if f.get("verified") is False]
    manifest = {k: v for k, v in src.items()}
    manifest.update(fetched_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
                    seconds=round(time.time() - t0), bytes=total, file_count=len(files),
                    verified_files=sum(1 for f in files if f.get("verified") is True),
                    unverified_files=sum(1 for f in files if f.get("verified") is None),
                    failed_files=bad, error=error, files=files)
    out = MANIFESTS / set_name
    out.mkdir(parents=True, exist_ok=True)
    (out / f"{src['name']}.json").write_text(json.dumps(manifest, indent=1), encoding="utf-8")
    log(src["name"], f"done: {len(files)} files, {human(total)} in {manifest['seconds']} s"
                     + (f", {len(bad)} FAILED CHECKS" if bad else "") + (f", error: {error}" if error else ""))
    return manifest


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--set", choices=sorted(SETS), default="phase1")
    ap.add_argument("--root", type=Path, default=DEFAULT_ROOT)
    ap.add_argument("--only", nargs="*")
    ap.add_argument("--jobs", type=int, default=4)
    a = ap.parse_args()
    # file names and errors carry any script; the Windows console code page would raise on them
    for stream in (sys.stdout, sys.stderr):
        stream.reconfigure(encoding="utf-8", errors="replace")
    by_name = {s["name"]: s for s in SETS[a.set]}
    unknown = sorted(set(a.only or []) - set(by_name))
    if unknown:
        sys.exit(f"not in the {a.set} set: {unknown}")
    sources = [by_name[n] for n in a.only] if a.only else SETS[a.set]
    sources = sorted(sources, key=lambda s: s["expected_bytes"])  # small first: early failures surface early
    a.root.mkdir(parents=True, exist_ok=True)
    with cf.ThreadPoolExecutor(a.jobs) as pool:
        results = list(pool.map(lambda s: run(s, a.root, a.set), sources))
    failed = [r["name"] for r in results if r["error"] or r["failed_files"]]
    print(f"\n{len(results)} sources, {human(sum(r['bytes'] for r in results))}; "
          f"failed: {failed or 'none'}", flush=True)
    sys.exit(1 if failed else 0)


if __name__ == "__main__":
    main()