"""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/); 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/). DIR defaults to carbon-data next to the repository, outside it, so `git clean` can never touch it. Each source gets data/manifests//.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]+)", 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"([^<]+)", 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()