Download tools/fetch.py from Battam/agentic-env-index: direct link, hf CLI and curl.
- Browser
- Download file 89.4 kB
-
https://huggingface.co/datasets/Battam/agentic-env-index/resolve/main/tools/fetch.py
- Command line
-
hf download hf://datasets/Battam/agentic-env-index/tools/fetch.py
-
curl -L -o fetch.py https://huggingface.co/datasets/Battam/agentic-env-index/resolve/main/tools/fetch.py
89.4 kB
| #!/usr/bin/env python3 | |
| """Select rows of the Agentic Env Index, download the files they point to and check them against their rows. | |
| The index is a set of Parquet tables (one row per downloadable item). This script runs one DuckDB query over | |
| them (the default filter plus your own conditions), rebuilds each selected row into a full pointer with | |
| meta/sources.json, downloads the item and checks it against what the row records. It writes the files under | |
| --out and a manifest (fetch_manifest.jsonl) with one line per selected row. | |
| What is checked: a row with hashes has its size (when known) and every hash checked. Some sources publish no | |
| hash; such a row has its size checked when the size is known, and its manifest line says checked "size only" | |
| and carries the sha256 computed on download (unverified says so). A row with neither a hash nor a size is | |
| downloaded within the cap and only its sha256 is computed (manifest fields size_unknown and unverified). | |
| Rolling files (files the source regenerates in place, such as the lichess puzzle and evaluation databases, | |
| or a row whose source_meta has rolling set) carry no hash and their size changes between the index and the | |
| download: a size that differs is not a failure, the manifest line says checked "rolling file, size changed" | |
| with the size the row records in expected_bytes, and the download may grow up to the cap. | |
| Examples: | |
| python fetch.py --tag data-processing --ext csv --limit 50 --out ./files | |
| python fetch.py --source pypi --tier yes --max-size 1000000 --limit 20 --dry-run | |
| python fetch.py --starter office-documents --out ./starter-documents | |
| python fetch.py --data ./local-copy --where "media_type = 'application/pdf'" --limit 5 | |
| python fetch.py --source govdocs1-files --ext pdf --limit 20 --check-content --out ./govdocs | |
| Reading the index from the Hub (the default, hf://datasets/...) starts by asking the Hub API for the commit | |
| the main branch points to and then reads every table at that commit (hf://datasets/<repo>@<commit>/...), so a | |
| long query is not split across an update of the index. If the commit cannot be read, the script prints one | |
| warning line and reads the main branch. A --data root that already names a revision (@...) is read as given. | |
| Requirements: Python 3.9 or newer and the duckdb package (pip install duckdb). Downloads use only the | |
| standard library (plus sevenzip.py for 7z members and the zstandard package for --decompress of .zst). | |
| DuckDB spill files are capped at 100GB by default; DUCKDB_MAX_TEMP changes that limit. | |
| Ways of fetching that the script supports (the unit column of meta/sources.json says which one a source uses): | |
| whole files over HTTP(S) (s3:// and hf:// addresses are turned into their public HTTPS form); byte ranges | |
| (HTTP Range, the server must answer 206); WARC or ARC records (the range is one gzip member: it is | |
| decompressed, the WARC and HTTP headers are removed and the payload hash is checked); members of zip | |
| archives (the local header and the compressed bytes are read with Range requests, then inflated and checked | |
| against size and CRC32); API responses (the body field is taken from the JSON response). Members of packages: | |
| wheels, jars and other zip files through their central directory (Range requests); sdists, npm .tgz and | |
| .crate files by downloading the whole package (within the cap; kept in a temporary directory for the run) | |
| and taking the member out; members of 7z archives with sevenzip.py next to this script (a solid block is | |
| decoded from its start up to the member, within the cap). Members of tar archives stored as gzip (the arXiv | |
| source bundles): the range is one gzip member, decompressed and checked against the CRC32 and length of its | |
| trailer. Single lichess games (rows with a game id): the public export API, one request per second and a full | |
| minute of waiting after HTTP 429; rows without a game id are fetched as the files they point to. | |
| The default filter removes duplicate copies of the same file (meta/duplicates.parquet) and rows found in | |
| public benchmark tasks (meta/bench_overlap.parquet). Only rows of files that were compared with the benchmark | |
| list can be found there; meta/bench_checked.parquet says which files and collections were compared, and its | |
| column default_keep says whether the default filter keeps the rest (docs/selecting.md says which benchmarks, | |
| up to when, and how this copy of the repository handles rows that were not compared). Of rows with the same | |
| hash one copy is kept; rows of a superseded snapshot are removed; of rows that share a natural key (source, | |
| uri, range_offset, member_path) but differ in content, only the one from the latest batch is kept, and its | |
| manifest line says natural_key_conflict. Truncated rows, empty files and rows of batches whose link check was | |
| partial stay in. License tiers, sizes and versions do not remove rows; choose them with --tier, --where or the queries in | |
| docs/selecting.md. | |
| Sizes and caps: a cap applies only when fetching, it never removes a row from the selection. By default every | |
| row has the overall cap (meta/size_caps.json: the 99th percentile of the sizes of all benchmark task files), | |
| which guards against downloading a huge file by mistake. --cap per-class uses the cap of the row's content | |
| class instead (the typical size of benchmark task files of that class; the largest among the row's tags), and | |
| --max-size N uses N bytes for every row. A row whose known size is above its cap is not downloaded; a row of | |
| unknown size (manifest field size_unknown) is downloaded until the cap. Both are recorded with status | |
| too_large, which is not a failure. --decompress also decompresses .gz, .bz2 and .zst files within the cap. | |
| Requester-pays buckets (such as the arXiv source bundles on S3) are charged to your own AWS account: set | |
| AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN for temporary credentials). The script | |
| signs those requests itself (AWS Signature Version 4) and contains no credentials. Without them such rows are | |
| skipped with the reason. Rows that need a login or an access request are skipped with the reason; any other | |
| address form is reported as unsupported. | |
| Content check (--check-content): after a verified download (and after --decompress) each file gets three | |
| checks, recorded in the manifest field content_check. scanned_pdf: a PDF with no fonts (pdffonts) whose | |
| first five pages hold fewer than 20 characters of text per page (pdftotext), most likely a scanned image. | |
| error_page: an HTML, XML or plain text file whose title names an error (404, not found, access denied and | |
| the like), or whose text is under 3000 characters and names one in its first 1500 characters. ext_mismatch: | |
| the type that file --mime-type reports is not one of the types expected for the extension. Each check is | |
| flagged, clean, not_applicable or skipped; a check is skipped when a system tool it needs (file, pdffonts, | |
| pdftotext from poppler-utils) is not installed or fails on the file, and the reason is written in | |
| content_check.skipped. A flagged or skipped check is not a failure and never changes the status. | |
| The manifest status is one of ok, failed, too_large, skipped, unsupported (selected with --dry-run). The exit | |
| code is 1 only when some row failed. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import bz2 | |
| import copy | |
| import datetime | |
| import gzip | |
| import hashlib | |
| import hmac | |
| import http.client | |
| import io | |
| import json | |
| import os | |
| import posixpath | |
| import re | |
| import shutil | |
| import socket | |
| import struct | |
| import subprocess | |
| import sys | |
| import tarfile | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| import zlib | |
| from pathlib import Path | |
| DEFAULT_REPO = "Battam/agentic-env-index" | |
| TIERS = ("yes", "conditional", "no", "unknown") | |
| # hit classes of meta/bench_overlap.parquet that the default filter removes | |
| OVERLAP_REMOVE = ("benchmark_copy", "task_file", "data_address") | |
| CAP_MODES = ("overall", "per-class") | |
| HASH_COLS = (("sha256", 32), ("sha1", 20), ("md5", 16), ("crc32", 4)) | |
| LICENSE_COLS = (("license_spdx", "spdx"), ("license_training_ok", "training_ok"), | |
| ("license_redistribution_ok", "redistribution_ok"), ("license_notes", "notes")) | |
| ZIP_COLS = (("local_header_offset", "zip_local_header_offset"), ("compression_method", "zip_compression_method"), | |
| ("compressed_size", "zip_compressed_size")) | |
| TRUNC_KEY = "content_truncated" | |
| API_BODY_DEFAULT_FIELD = "items.0.body" | |
| UA = "agentic-env-index-fetch/1 (+https://huggingface.co/datasets/" + DEFAULT_REPO + ")" | |
| CHUNK = 1 << 20 | |
| UNKNOWN_SIZE_CAP = 100_000_000 # used only when a row carries no cap (a table without max_size_bytes) | |
| RETRIES = 3 | |
| BACKOFF = 2.0 | |
| # DuckDB settings used when the tables are read over the network (hf:// or another URL). Hugging Face counts | |
| # requests in 5-minute windows and answers 429 when a window is used up; DuckDB reads one file with several | |
| # requests, and a full query touches thousands of files. Retries wait 2, 4, 8, ... 256 seconds (510 seconds | |
| # in all), so the last retry comes after a whole window has passed; each request may take up to 120 seconds; | |
| # fewer threads keep fewer requests in flight. These values are provisional: lower them if your reads never | |
| # hit a limit, raise them if they still do. | |
| HTTP_SETTINGS = {"http_retries": 8, "http_retry_wait_ms": 2000, "http_retry_backoff": 2, "http_timeout": 120} | |
| REMOTE_THREADS = 4 | |
| ZIP_LOCAL_SIG = b"PK\x03\x04" | |
| ZIP_LOCAL_LEN = 30 | |
| MANIFEST = "fetch_manifest.jsonl" | |
| SIZE_ONLY = "size only" | |
| ROLLING_CHANGED = "rolling file, size changed" | |
| NO_HASH_MEMBER = "the source publishes no hash for this member; sha256 computed on download" | |
| # files the source regenerates in place, so the size in the index goes stale (source, collection); a row can | |
| # also say so itself with source_meta.rolling | |
| ROLLING_FILES = frozenset({("lichess", "puzzle"), ("lichess", "eval")}) | |
| # ---------- SQL ---------- | |
| def sql_str(s: str) -> str: | |
| return "'" + str(s).replace("'", "''") + "'" | |
| IS_ROW = "starts_with(coalesce(p.extra, ''), '{\"_row\":')" | |
| def _absent(key: str) -> str: | |
| return f"coalesce(json_contains(json_extract(p.extra, '$._absent'), '\"{key}\"'), false)" | |
| def tier_sql(field: str = "training_ok") -> str: | |
| """License tier of a row: the row's own license_override when it has one, otherwise the batch tier.""" | |
| anycol = "(" + " OR ".join(f"p.{c} IS NOT NULL" for c, _ in LICENSE_COLS) + ")" | |
| own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.license_override.{field}') " | |
| f"WHEN json_type(p.extra, '$.license_override') IS NOT NULL " | |
| f"THEN json_extract_string(p.extra, '$.license_override.{field}') " | |
| f"WHEN {anycol} THEN p.license_{field} " | |
| f"WHEN NOT {_absent('license_override')} THEN b.const_{field} END") | |
| v = f"coalesce(nullif({own}, ''), b.{field})" | |
| return f"(CASE WHEN {v} IN ('yes', 'conditional', 'no') THEN {v} ELSE 'unknown' END)" | |
| def truncated_sql() -> str: | |
| """Why the stored content was cut short (NULL when it was not).""" | |
| own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.{TRUNC_KEY}') " | |
| f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL " | |
| f"THEN json_extract_string(p.extra, '$.source_meta.{TRUNC_KEY}') " | |
| f"WHEN NOT {_absent('source_meta')} THEN b.const_truncated END") | |
| return f"nullif(coalesce(p.truncated, {own}), '')" | |
| def own_sql(key: str, const: str, *, text: bool = True) -> str: | |
| """A top-level field of the full pointer: the row's own value (in extra) when it has one, otherwise the | |
| source constant (a column of the batch table), unless the row lacks the field.""" | |
| f = "json_extract_string" if text else "json_extract" | |
| return (f"(CASE WHEN {IS_ROW} THEN {f}(p.extra, '$._row.{key}') " | |
| f"WHEN json_type(p.extra, '$.{key}') IS NOT NULL THEN {f}(p.extra, '$.{key}') " | |
| f"WHEN NOT {_absent(key)} THEN {const} END)") | |
| def source_meta_sql(key: str) -> str: | |
| """One key of source_meta; key is an SQL expression (a quoted name or a column such as b.meta_key).""" | |
| return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.' || {key}) " | |
| f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL " | |
| f"THEN json_extract_string(p.extra, '$.source_meta.' || {key}) " | |
| f"WHEN NOT {_absent('source_meta')} THEN json_extract_string(b.const_source_meta, '$.' || {key}) END)") | |
| def meta_value_sql() -> str: | |
| """The source_meta value that some tags depend on (forum instance, mailing list, site), see b.meta_key.""" | |
| return f"(CASE WHEN b.meta_key IS NOT NULL THEN {source_meta_sql('b.meta_key')} END)" | |
| def own_content_sql() -> str: | |
| """The row's own content categories as JSON text (NULL when the row takes them from its batch).""" | |
| return f"CAST({own_sql('content', 'b.const_content', text=False)} AS VARCHAR)" | |
| def hash_scope_sql() -> str: | |
| """What the hashes cover: file (default), http_payload (a WARC record's payload) or api_body.""" | |
| return f"coalesce({own_sql('hash_scope', 'b.const_hash_scope')}, 'file')" | |
| def hash_sql(alg: str) -> str: | |
| """One hash of the row as lowercase hex (NULL when the row has none).""" | |
| hx = f"coalesce(json_contains(json_extract(p.extra, '$._hx'), '\"{alg}\"'), false)" | |
| return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.hashes.{alg}') " | |
| f"WHEN json_type(p.extra, '$.hashes.{alg}') IS NOT NULL THEN json_extract_string(p.extra, '$.hashes.{alg}') " | |
| f"WHEN {hx} THEN NULL ELSE lower(hex(p.{alg})) END)") | |
| def uri_sql() -> str: | |
| """The pointer's uri before the address swap (the uri column holds the directly downloadable address).""" | |
| t, f, s = "b.uri_swap_to", "b.uri_swap_from", "b.uri_swap_suffix" | |
| return (f"(CASE WHEN {t} IS NOT NULL AND json_extract_string(p.extra, '$._uri_orig') IS NULL THEN " | |
| f"CASE WHEN starts_with(p.uri, {t}) AND ends_with(p.uri, {s}) AND length(p.uri) >= length({t}) + length({s}) " | |
| f"THEN {f} || substr(p.uri, length({t}) + 1, length(p.uri) - length({t}) - length({s})) END " | |
| f"ELSE p.uri END)") | |
| def pid_sql() -> str: | |
| """pointer_id as written in meta/sources.json (layout.pointer_id), as one SQL expression.""" | |
| par = "p.parent_pointer_id" | |
| rest = f"substr({par}, strpos({par}, ':') + strpos(substr({par}, strpos({par}, ':') + 1), ':') + 1)" | |
| head = "p.source || ':' || p.collection || ':'" | |
| tail = (f"array_to_string(list_slice(string_split({uri_sql()}, '/'), -b.pid_segments, -1), '/') || " | |
| f"CASE WHEN b.pid_at_offset THEN '@' || CAST(p.range_offset AS VARCHAR) ELSE '' END") | |
| return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.pointer_id') " | |
| f"WHEN {_absent('pointer_id')} THEN NULL " | |
| f"WHEN json_type(p.extra, '$.pointer_id') IS NOT NULL THEN json_extract_string(p.extra, '$.pointer_id') " | |
| f"WHEN json_type(p.extra, '$.pid') IS NOT NULL THEN {head} || json_extract_string(p.extra, '$.pid') " | |
| f"WHEN {par} IS NOT NULL AND p.member_path IS NOT NULL THEN " | |
| f"CASE WHEN length({par}) - length(replace({par}, ':', '')) >= 2 " | |
| f"THEN {head} || {rest} || '!/' || p.member_path END " | |
| f"WHEN b.pid_segments IS NOT NULL THEN {head} || {tail} END)") | |
| def size_bucket_sql(col: str = "p.size_bytes") -> str: | |
| return (f"(CASE WHEN {col} IS NULL OR {col} < 0 THEN 'unknown' WHEN {col} < 10000 THEN '<10KB' " | |
| f"WHEN {col} < 1000000 THEN '10KB-1MB' WHEN {col} < 100000000 THEN '1MB-100MB' " | |
| f"WHEN {col} < 1000000000 THEN '100MB-1GB' ELSE '>1GB' END)") | |
| def same_key(a: str, b: str = "p") -> str: | |
| return (f"{a}.source = {b}.source AND {a}.uri = {b}.uri AND {a}.range_offset IS NOT DISTINCT FROM {b}.range_offset " | |
| f"AND {a}.member_path IS NOT DISTINCT FROM {b}.member_path") | |
| def same_row(a: str, b: str = "p") -> str: | |
| """The same row: the same natural key, batch and place in the data files (row_file, row_index).""" | |
| return (same_key(a, b) + f" AND {a}.batch = {b}.batch AND {a}.row_file = {b}.row_file " | |
| f"AND {a}.row_index = {b}.row_index") | |
| def rows_from(files: str) -> str: | |
| """SELECT over the row tables that adds where each row sits: row_file (the last three parts of the file path, | |
| <source>/<batch>/<part file>) and row_index (the row number in that file, from 0). meta/duplicates.parquet | |
| names rows by them; reading them costs nothing extra.""" | |
| return ("SELECT * EXCLUDE (filename, file_row_number), " | |
| "regexp_extract(replace(filename, '\\', '/'), '[^/]+/[^/]+/[^/]+$') AS row_file, " | |
| "file_row_number AS row_index " | |
| f"FROM read_parquet({files}, union_by_name = true, filename = true, file_row_number = true)") | |
| def natural_key_conflict_sql() -> str: | |
| """True for a row kept from a natural-key conflict: other rows with the same natural key (source, uri, | |
| range_offset, member_path) but different content were removed as reason natural_key, naming this row as the | |
| copy kept (the one from the latest batch).""" | |
| return ("EXISTS (SELECT 1 FROM d WHERE d.reason = 'natural_key' AND d.keep_source = p.source " | |
| "AND d.keep_batch = p.batch AND d.keep_row_file = p.row_file AND d.keep_row_index = p.row_index)") | |
| def tag_key_sql() -> str: | |
| """Join condition between a row p and its lines in meta/tags.parquet (t).""" | |
| return ("t.source = p.source AND t.batch = p.batch AND t.collection IS NOT DISTINCT FROM p.collection " | |
| f"AND t.ext IS NOT DISTINCT FROM p.ext AND t.meta_value IS NOT DISTINCT FROM {meta_value_sql()} " | |
| f"AND t.content IS NOT DISTINCT FROM {own_content_sql()}") | |
| def cap_sql() -> str: | |
| """Per-class size cap of a row (--cap per-class): the largest cap among its tags (t.max_size_bytes, the | |
| typical size of benchmark task files of that content class), otherwise the overall cap of its batch | |
| (b.max_size_bytes). See meta/size_caps.json.""" | |
| return f"coalesce((SELECT max(t.max_size_bytes) FROM t WHERE {tag_key_sql()}), b.max_size_bytes)" | |
| def checked_sql(col: str = "checked") -> str: | |
| """True for a row whose file and collection pass column col of meta/bench_checked.parquet (view c): col | |
| checked says the rows were compared with the benchmark list, col default_keep says the default filter keeps | |
| them. A file not listed there (not compared yet, or published after the table was built) takes the value of | |
| the one row with scope unlisted; a collection listed with scope container (a collection whose name matches a benchmark and | |
| that awaits a ruling) must pass too.""" | |
| return (f"coalesce((SELECT bool_and(c.{col}) FROM c WHERE c.scope = 'file' AND c.row_file = p.row_file), " | |
| f"(SELECT bool_and(c.{col}) FROM c WHERE c.scope = 'unlisted'), false) AND NOT EXISTS (SELECT 1 FROM c " | |
| f"WHERE c.scope = 'container' AND NOT c.{col} AND c.source = p.source AND " | |
| f"c.collection = split_part(p.collection, '@', 1))") | |
| def default_conditions(*, overlap: bool = True) -> list: | |
| """The default filter, one (name, SQL condition) per rule: it removes duplicate copies (meta/duplicates.parquet | |
| keeps one copy of each file, and of rows sharing a natural key the one from the latest batch), copies of | |
| benchmark data (meta/bench_overlap.parquet) and the rows meta/bench_checked.parquet does not keep by default | |
| (column default_keep). Tables: p rows, b batches, d duplicates, o bench_overlap, c bench_checked. | |
| License tiers, sizes and versions are not part of it.""" | |
| rem = ", ".join(sql_str(c) for c in OVERLAP_REMOVE) | |
| out = [("not_duplicate", f"NOT EXISTS (SELECT 1 FROM d WHERE {same_row('d')})")] | |
| if overlap: | |
| out += [("not_in_benchmark_row", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'row' AND o.hit_class IN ({rem}) " | |
| f"AND {same_key('o')})"), | |
| ("not_in_benchmark_container", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'container' AND " | |
| f"o.hit_class IN ({rem}) AND o.source = p.source AND " | |
| f"o.collection = split_part(p.collection, '@', 1))"), | |
| ("checked_for_benchmarks", checked_sql("default_keep"))] | |
| return out | |
| def tag_condition(tags) -> str: | |
| vals = ", ".join(sql_str(t) for t in tags) | |
| return f"EXISTS (SELECT 1 FROM t WHERE {tag_key_sql()} AND t.tag IN ({vals}))" | |
| def fetch_order() -> str: | |
| return ("sha256(concat_ws(chr(0), p.source, p.uri, coalesce(CAST(p.range_offset AS VARCHAR), ''), " | |
| "coalesce(p.member_path, '')))") | |
| def build_where(*, tags=(), exts=(), sources=(), tiers=None, min_size=None, max_size=None, where=None, | |
| default=True, overlap=True) -> list: | |
| """The WHERE conditions of the selection. max_size is accepted for older callers and ignored: a size cap | |
| applies when fetching (select_sql), it does not remove rows.""" | |
| conds = [] | |
| if default: | |
| conds += [c for _, c in default_conditions(overlap=overlap)] | |
| if tiers is not None: | |
| conds.append(f"{tier_sql()} IN ({', '.join(sql_str(t) for t in tiers)})") | |
| if min_size is not None: | |
| conds.append(f"p.size_bytes >= {int(min_size)}") | |
| if tags: | |
| conds.append(tag_condition(tags)) | |
| if exts: | |
| conds.append(f"lower(p.ext) IN ({', '.join(sql_str(e.lower().lstrip('.')) for e in exts)})") | |
| if sources: | |
| conds.append(f"p.source IN ({', '.join(sql_str(s) for s in sources)})") | |
| if where: | |
| conds.append(f"({where})") | |
| return conds | |
| def _root(args) -> str: | |
| return args.data.rstrip("/") if args.data else f"hf://datasets/{args.repo}" | |
| def _data_files(root: str, sources=()) -> str: | |
| if sources: | |
| return "[" + ", ".join(sql_str(f"{root}/data/{s}/*/*.parquet") for s in sources) + "]" | |
| return sql_str(f"{root}/data/*/*/*.parquet") | |
| def views_sql(root: str, *, sources=(), starter: str | None = None) -> list: | |
| # starter files already carry row_file and row_index (copied from the row tables when they were built) | |
| rows = (f"SELECT * FROM read_parquet({sql_str(f'{root}/starter/{starter}.parquet')}, union_by_name = true)" | |
| if starter else rows_from(_data_files(root, sources))) | |
| return [f"CREATE OR REPLACE VIEW p AS {rows}", | |
| f"CREATE OR REPLACE VIEW b AS SELECT * FROM read_parquet({sql_str(root + '/meta/batches.parquet')})", | |
| f"CREATE OR REPLACE VIEW d AS SELECT * FROM read_parquet({sql_str(root + '/meta/duplicates.parquet')})", | |
| f"CREATE OR REPLACE VIEW o AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_overlap.parquet')})", | |
| f"CREATE OR REPLACE VIEW t AS SELECT * FROM read_parquet({sql_str(root + '/meta/tags.parquet')})", | |
| f"CREATE OR REPLACE VIEW c AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_checked.parquet')})"] | |
| def select_sql(conds: list, limit: int | None = None, max_size: int | None = None, cap_mode: str = "overall") -> str: | |
| """The rows to fetch, each with size_cap_bytes (the most bytes written for the row: --max-size when given, | |
| otherwise the overall cap of its batch, or with cap_mode per-class the row's class cap from cap_sql), | |
| batch_cap_bytes (the most bytes downloaded for a whole package or read from a solid 7z block: the larger of | |
| the two) and natural_key_conflict (natural_key_conflict_sql).""" | |
| if cap_mode not in CAP_MODES: | |
| raise ValueError(f"unknown cap mode {cap_mode}; use {', '.join(CAP_MODES)}") | |
| cap = (str(int(max_size)) if max_size is not None | |
| else cap_sql() if cap_mode == "per-class" else "b.max_size_bytes") | |
| whole = str(int(max_size)) if max_size is not None else "b.max_size_bytes" | |
| sql = (f"SELECT p.*, {cap} AS size_cap_bytes, {whole} AS batch_cap_bytes, " | |
| f"{natural_key_conflict_sql()} AS natural_key_conflict " | |
| "FROM p JOIN b ON b.source = p.source AND b.batch = p.batch") | |
| if conds: | |
| sql += "\nWHERE " + "\n AND ".join(conds) | |
| sql += f"\nORDER BY {fetch_order()}" | |
| if limit is not None: | |
| sql += f"\nLIMIT {int(limit)}" | |
| return sql | |
| def is_remote(root: str) -> bool: | |
| return "://" in root | |
| HUB_API = "https://huggingface.co/api/datasets/" | |
| HF_DATASETS = "hf://datasets/" | |
| def repo_revision(repo: str, *, token: str | None = None, opener=None, timeout: float = 30) -> str: | |
| """The commit the main branch of the dataset repo points to now (the Hub API answers with it in field sha). | |
| The token (or HF_TOKEN when none is given) is sent when there is one.""" | |
| token = os.environ.get("HF_TOKEN") if token is None else token | |
| headers = {"Authorization": f"Bearer {token}"} if token else {} | |
| with (opener or open_url)(f"{HUB_API}{repo}/revision/main", timeout, headers=headers) as r: | |
| sha = str(json.loads(r.read()).get("sha") or "") | |
| if not re.fullmatch(r"[0-9a-f]{40}", sha): | |
| raise ValueError(f"the Hub API gave no commit for {repo}") | |
| return sha | |
| def pin_root(root: str, *, revision=None, warn=None) -> str: | |
| """hf://datasets/<owner>/<name>[/...] -> the same root at the current commit, hf://datasets/<owner>/<name>@<commit> | |
| [/...] (DuckDB reads hf:// paths at a revision given after @), so every file of a long query comes from one | |
| commit even when the repo gets new commits meanwhile. A root that already names a revision, and any other | |
| root, is returned as it is. When the commit cannot be read the root is returned as it is (the main branch is | |
| read) and warn gets one line saying why.""" | |
| root = root.rstrip("/") | |
| if not root.startswith(HF_DATASETS): | |
| return root | |
| parts = root[len(HF_DATASETS):].split("/", 2) | |
| if len(parts) < 2 or not all(parts[:2]) or "@" in parts[0] or "@" in parts[1]: | |
| return root | |
| repo = f"{parts[0]}/{parts[1]}" | |
| try: | |
| sha = str((revision or repo_revision)(repo) or "") | |
| if not re.fullmatch(r"[0-9a-f]{40}", sha): | |
| raise ValueError(f"not a commit id: {sha[:60]!r}") | |
| except Exception as e: # noqa: BLE001 any failure falls back to main | |
| (warn or _stderr)(f"could not read the current commit of {repo} ({type(e).__name__}: {e}); reading the " | |
| f"main branch, which can change while the query runs") | |
| return root | |
| return f"{HF_DATASETS}{repo}@{sha}" + (f"/{parts[2]}" if len(parts) > 2 else "") | |
| def _stderr(msg: str) -> None: | |
| print(f"warning: {msg}", file=sys.stderr) | |
| DUCKDB_MAX_TEMP = "100GB" | |
| def max_temp_size() -> str: | |
| return os.environ.get("DUCKDB_MAX_TEMP") or DUCKDB_MAX_TEMP | |
| def http_settings(con, threads: int = REMOTE_THREADS) -> None: | |
| """Retries, backoff and timeout for network reads (HTTP_SETTINGS), and fewer threads. A setting this DuckDB | |
| does not know is skipped with a note on stderr.""" | |
| for key, value in [*HTTP_SETTINGS.items(), ("threads", threads)]: | |
| try: | |
| con.execute(f"SET {key} = {int(value)}") | |
| except Exception as e: # noqa: BLE001 (an older DuckDB, or the httpfs extension could not be loaded) | |
| print(f"note: could not set {key}: {type(e).__name__}: {str(e).splitlines()[0][:200]}", file=sys.stderr) | |
| def connect(memory_limit: str | None = None, temp_dir: str | None = None, settings: dict | None = None, *, | |
| remote: bool = False, token: str | None = None): | |
| """A DuckDB connection. remote: the tables are read over the network (see HTTP_SETTINGS). token: the Hugging | |
| Face token to read with; without one the HF_TOKEN environment variable is used when set.""" | |
| try: | |
| import duckdb | |
| except ImportError: | |
| sys.exit("fetch.py needs the duckdb package: pip install duckdb") | |
| con = duckdb.connect() | |
| merged = {"max_temp_directory_size": max_temp_size(), **(settings or {})} | |
| for key, value in merged.items(): | |
| con.execute(f"SET {key} = {sql_str(value)}") | |
| if memory_limit: | |
| con.execute(f"SET memory_limit = {sql_str(memory_limit)}") | |
| if temp_dir: | |
| con.execute(f"SET temp_directory = {sql_str(temp_dir)}") | |
| if remote: | |
| http_settings(con) | |
| token = token or os.environ.get("HF_TOKEN") | |
| if token: | |
| try: | |
| con.execute(f"CREATE SECRET hf_token (TYPE huggingface, TOKEN {sql_str(token)})") | |
| except Exception as e: # noqa: BLE001 (keep the token out of the message) | |
| raise RuntimeError(f"could not register the Hugging Face token: {type(e).__name__}: " | |
| f"{str(e).replace(token, '***')}") from None | |
| return con | |
| def load_specs(con, root: str) -> dict: | |
| text = con.execute(f"SELECT content FROM read_text({sql_str(root + '/meta/sources.json')})").fetchone()[0] | |
| return {s["source"]: s["layout"] for s in json.loads(text)["sources"]} | |
| # ---------- one table row -> the full pointer ---------- | |
| def derive_pid(rule, source, collection, uri, offset): | |
| if not rule or not isinstance(source, str) or not isinstance(collection, str) or not isinstance(uri, str): | |
| return None | |
| tail = "/".join(uri.split("/")[-int(rule["segments"]):]) | |
| if rule.get("at_offset"): | |
| if not (isinstance(offset, int) and not isinstance(offset, bool)): | |
| return None | |
| tail += f"@{offset}" | |
| return f"{source}:{collection}:{tail}" | |
| def member_pid(source, collection, parent, member): | |
| if not all(isinstance(v, str) for v in (source, collection, parent, member)) or parent.count(":") < 2: | |
| return None | |
| return f"{source}:{collection}:{parent.split(':', 2)[2]}!/{member}" | |
| def derive_alts(rule, uri): | |
| if not rule or not isinstance(uri, str): | |
| return None | |
| out = [] | |
| for f, t, suf in rule["pairs"]: | |
| if not uri.startswith(f): | |
| return None | |
| out.append(t + uri[len(f):] + suf) | |
| return out | |
| def derive_hash(seg, uri): | |
| if not isinstance(uri, str): | |
| return None | |
| parts = uri.split("/") | |
| k, j = seg | |
| if k > len(parts): | |
| return None | |
| return "".join(parts[-k:len(parts) - j]) | |
| def unswap(rule, stored): | |
| f, t, suf = rule["pairs"][0] | |
| if not isinstance(stored, str) or not stored.startswith(t) or not stored.endswith(suf) \ | |
| or len(stored) < len(t) + len(suf): | |
| return None | |
| return f + stored[len(t):len(stored) - len(suf)] | |
| def _hex(v): | |
| return v.hex() if isinstance(v, (bytes, bytearray)) else v | |
| def restore(col: dict, spec: dict) -> dict: | |
| """One table row (column name -> value) and the source's layout from meta/sources.json -> the full pointer.""" | |
| x = json.loads(col["extra"]) if col.get("extra") else {} | |
| if "_row" in x: | |
| return x["_row"] | |
| r = copy.deepcopy(spec["constants"]) | |
| r["source"] = col["source"] | |
| for k in ("collection", "ext", "size_bytes"): | |
| r[k] = col.get(k) | |
| arule = spec.get("alt_uris") | |
| uri = col["uri"] | |
| if arule and arule["swap"] and not x.get("_uri_orig"): | |
| r["uri"] = unswap(arule, uri) | |
| r["alt_uris"] = derive_alts(arule, r["uri"]) | |
| else: | |
| r["uri"] = uri | |
| if arule and not x.get("_uri_orig"): | |
| a = derive_alts(arule, uri) | |
| if a is not None: | |
| r["alt_uris"] = a | |
| r["hashes"] = {n: _hex(col[n]) for n, _ in HASH_COLS if col.get(n) is not None} | |
| for h, seg in (spec.get("hash_from_uri") or {}).items(): | |
| v = derive_hash(seg, r["uri"]) | |
| if v is not None: | |
| r["hashes"][h] = v | |
| for h in x.pop("_hx", []): | |
| r["hashes"].pop(h, None) | |
| r["hashes"].update(x.pop("hashes", {})) | |
| for k in ("media_type", "member_path", "parent_pointer_id"): | |
| if col.get(k) is not None: | |
| r[k] = col[k] | |
| if col.get("zip_local_header_offset") is not None: | |
| r["zip_entry"] = {k: col.get(c) for k, c in ZIP_COLS} | |
| if col.get("range_offset") is not None: | |
| r["range"] = {"offset": col["range_offset"], "length": col.get("range_length")} | |
| if col.get("origin_url") is not None: | |
| r["origin"] = {"url": col["origin_url"]} | |
| if col.get("origin_time") is not None: | |
| r["origin"]["captured_at"] = col["origin_time"] | |
| lo = {k: col[c] for c, k in LICENSE_COLS if col.get(c) is not None} | |
| if lo: | |
| r["license_override"] = lo | |
| if "pointer_id" in x: | |
| pid = x.pop("pointer_id") | |
| elif "pid" in x: | |
| pid = f"{r['source']}:{r['collection']}:{x.pop('pid')}" | |
| elif col.get("parent_pointer_id") is not None and col.get("member_path") is not None: | |
| pid = member_pid(r["source"], r["collection"], col["parent_pointer_id"], col["member_path"]) | |
| else: | |
| pid = derive_pid(spec.get("pointer_id"), r["source"], r["collection"], r["uri"], col.get("range_offset")) | |
| r["pointer_id"] = pid | |
| absent = x.pop("_absent", []) | |
| x.pop("_uri_orig", None) | |
| r.update(x) | |
| if col.get("truncated") is not None: | |
| sm = dict(r.get("source_meta") or {}) | |
| sm[TRUNC_KEY] = col["truncated"] | |
| r["source_meta"] = sm | |
| for k in absent: | |
| r.pop(k, None) | |
| return r | |
| # ---------- download and verify ---------- | |
| class Unsupported(Exception): | |
| pass | |
| def to_http(uri: str): | |
| if uri.startswith(("https://", "http://", "file://")): | |
| return uri | |
| if uri.startswith("s3://"): | |
| bucket, _, key = uri[5:].partition("/") | |
| return f"https://s3.amazonaws.com/{bucket}/{urllib.parse.quote(key)}" | |
| if uri.startswith("hf://datasets/"): | |
| rest = uri[len("hf://datasets/"):] | |
| repo_rev, _, path = rest.partition("/") | |
| if "@" not in repo_rev: | |
| name_rev, _, path = path.partition("/") | |
| repo_rev = repo_rev + "/" + name_rev | |
| repo, _, rev = repo_rev.partition("@") | |
| return f"https://huggingface.co/datasets/{repo}/resolve/{rev or 'main'}/{urllib.parse.quote(path)}" | |
| return None | |
| def candidates(row: dict) -> list: | |
| out = [] | |
| for u in [row.get("uri"), *(row.get("alt_uris") or [])]: | |
| h = to_http(u) if isinstance(u, str) else None | |
| if h and h not in out: | |
| out.append(h) | |
| first = to_http(row["uri"]) if isinstance(row.get("uri"), str) else None | |
| if str(row.get("uri")).startswith("s3://") and first in out and len(out) > 1: | |
| out.remove(first) | |
| out.append(first) | |
| return out | |
| def dest_path(root: Path, row: dict) -> Path: | |
| pid = row.get("pointer_id") | |
| if isinstance(pid, str) and pid.count(":") >= 2: | |
| rel = pid.split(":", 2)[2] | |
| else: | |
| key = "\0".join(str(row.get(k)) for k in ("source", "uri", "range", "member_path")) | |
| rel = hashlib.sha256(key.encode("utf-8")).hexdigest()[:24] | |
| parts = [p for p in posixpath.normpath(rel).split("/") if p not in ("", ".")] | |
| if not parts or ".." in parts: | |
| raise ValueError(f"unsafe relative path: {rel}") | |
| return Path(root, str(row.get("source")), str(row.get("collection")), *parts) | |
| class Hasher: | |
| def __init__(self, size): | |
| self.h = {n: hashlib.new(n) for n in ("md5", "sha1", "sha256", "sha512")} | |
| self.git = hashlib.sha1(f"blob {size}\0".encode()) if size is not None else None | |
| self.crc = 0 | |
| self.n = 0 | |
| def update(self, b: bytes) -> None: | |
| for h in self.h.values(): | |
| h.update(b) | |
| if self.git is not None: | |
| self.git.update(b) | |
| self.crc = zlib.crc32(b, self.crc) | |
| self.n += len(b) | |
| def digests(self) -> dict: | |
| out = {n: h.hexdigest() for n, h in self.h.items()} | |
| out["git_blob_sha1"] = self.git.hexdigest() if self.git else "" | |
| out["crc32"] = f"{self.crc & 0xFFFFFFFF:08x}" | |
| return out | |
| def _etag_md5(etag): | |
| if not etag: | |
| return None | |
| e = str(etag).strip().strip('"').replace(""", "") | |
| return e if len(e) == 32 and all(c in "0123456789abcdef" for c in e) else None | |
| def verify(row: dict, size: int, got: dict, names=("md5", "sha1", "sha256", "sha512", "git_blob_sha1")): | |
| """None when the size and every published hash match, otherwise the reason.""" | |
| if row.get("size_bytes") is not None and size != row["size_bytes"]: | |
| return f"size differs: expected {row['size_bytes']}, got {size}" | |
| hashes = row.get("hashes") or {} | |
| if not hashes and row.get("hash_source") == "computed_on_fetch": | |
| return None | |
| checked = 0 | |
| for name in names: | |
| want = str(hashes.get(name) or "").lower() | |
| if want: | |
| checked += 1 | |
| if got[name] != want: | |
| return f"{name} differs: expected {want}, got {got[name]}" | |
| et = _etag_md5(hashes.get("etag")) | |
| if et: | |
| checked += 1 | |
| if got["md5"] != et: | |
| return f"etag (single-part md5) differs: expected {et}, got {got['md5']}" | |
| return None if checked else "no hash that can be checked" | |
| def is_rolling(row: dict) -> bool: | |
| """True for a file the source regenerates in place (ROLLING_FILES, or source_meta.rolling on the row).""" | |
| sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {} | |
| return bool(sm.get("rolling")) or (row.get("source"), row.get("collection")) in ROLLING_FILES | |
| def no_hash_fields(row: dict, res: dict, sha256: str, note: str) -> dict: | |
| """The manifest fields of a row without hashes: unverified, the computed sha256, and checked "size only" | |
| when its size was checked.""" | |
| if row.get("hashes"): | |
| return res | |
| res["unverified"] = note | |
| res["sha256"] = sha256 | |
| if row.get("size_bytes") is not None: | |
| res["checked"] = SIZE_ONLY | |
| return res | |
| def range_header(rng) -> str: | |
| """rng is (offset, length); offset None asks for the last length bytes.""" | |
| if rng[0] is None: | |
| return f"bytes=-{rng[1]}" | |
| return f"bytes={rng[0]}-{rng[0] + rng[1] - 1}" | |
| def open_url(url: str, timeout: float, rng=None, headers=None): | |
| """rng is (offset, length), offset None for the last length bytes. HTTP gets a Range header and must answer | |
| 206. headers are extra request headers (the signed headers of a requester-pays request).""" | |
| if url.startswith("file://"): | |
| f = open(urllib.request.url2pathname(urllib.parse.urlparse(url).path), "rb") | |
| if not rng: | |
| return f | |
| with f: | |
| if rng[0] is None: | |
| f.seek(0, 2) | |
| f.seek(max(0, f.tell() - rng[1])) | |
| else: | |
| f.seek(rng[0]) | |
| return io.BytesIO(f.read(rng[1])) | |
| headers = {"User-Agent": UA, **(headers or {})} | |
| if rng: | |
| headers["Range"] = range_header(rng) | |
| r = urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=timeout) # noqa: S310 | |
| if rng and getattr(r, "status", 206) != 206: | |
| r.close() | |
| raise Unsupported(f"the server ignored the Range request (HTTP {getattr(r, 'status', '?')})") | |
| return r | |
| def transient(e: BaseException) -> bool: | |
| if isinstance(e, urllib.error.HTTPError): | |
| return 500 <= e.code < 600 | |
| if isinstance(e, urllib.error.URLError): | |
| r = e.reason | |
| return isinstance(r, (ConnectionError, TimeoutError, socket.timeout)) or ( | |
| isinstance(r, str) and "timed out" in r) | |
| return isinstance(e, (ConnectionError, TimeoutError, socket.timeout, http.client.IncompleteRead)) | |
| def _write(dest: Path, data: bytes) -> None: | |
| part = dest.with_name(dest.name + ".part") | |
| part.write_bytes(data) | |
| os.replace(part, dest) | |
| def _rng(row: dict): | |
| r = row.get("range") | |
| return (r["offset"], r["length"]) if isinstance(r, dict) and r.get("offset") is not None else None | |
| class TooLarge(Exception): | |
| """The item is larger than the row's cap; nothing is kept.""" | |
| def cap_of(row: dict) -> int: | |
| """The most bytes written for one row: its cap from the query (size_cap_bytes).""" | |
| v = row.get("_size_cap") | |
| return int(v) if v is not None else UNKNOWN_SIZE_CAP | |
| def whole_cap_of(row: dict) -> int: | |
| """The most bytes downloaded or decoded on the way to one row (a whole package, a solid 7z block, a | |
| compressed member): the larger of the row's cap and its batch cap.""" | |
| vals = [int(v) for v in (row.get("_size_cap"), row.get("_batch_cap")) if v is not None] | |
| return max(vals) if vals else UNKNOWN_SIZE_CAP | |
| def fetch_file(row, dest, url, timeout, opener): | |
| want = row.get("size_bytes") | |
| rolling = want is not None and not row.get("hashes") and _rng(row) is None and is_rolling(row) | |
| limit = max(want, cap_of(row)) if rolling else want if want is not None else cap_of(row) | |
| h = Hasher(want) | |
| part = dest.with_name(dest.name + ".part") | |
| try: | |
| with opener(url, timeout, _rng(row)) as src, open(part, "wb") as out: | |
| while True: | |
| b = src.read(CHUNK) | |
| if not b: | |
| break | |
| h.update(b) | |
| out.write(b) | |
| if h.n > limit: | |
| break | |
| except BaseException: | |
| part.unlink(missing_ok=True) | |
| raise | |
| if (want is None or rolling) and h.n > limit: | |
| part.unlink(missing_ok=True) | |
| raise TooLarge(f"rolling file: grew past the cap of {limit} bytes" if rolling | |
| else f"unknown size: stopped after more than the cap of {limit} bytes") | |
| changed = rolling and h.n != want | |
| why = verify({**row, "size_bytes": None} if changed else row, h.n, h.digests()) | |
| if why: | |
| part.unlink(missing_ok=True) | |
| return {"status": "failed", "reason": why, "url": url} | |
| os.replace(part, dest) | |
| res = no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": h.n, "url": url}, | |
| h.digests()["sha256"], "the source publishes no hash; sha256 computed on download") | |
| if changed: | |
| res["checked"] = ROLLING_CHANGED | |
| res["expected_bytes"] = want | |
| return res | |
| # WARC / ARC records | |
| def _split_head(block: bytes) -> tuple: | |
| a, b = block.find(b"\r\n\r\n"), block.find(b"\n\n") | |
| if a < 0 and b < 0: | |
| return block, b"" | |
| if b < 0 or (0 <= a < b): | |
| return block[:a], block[a + 4:] | |
| return block[:b], block[b + 2:] | |
| def _headers(text: bytes) -> dict: | |
| out = {} | |
| for line in text.decode("latin-1").splitlines()[1:]: | |
| k, sep, v = line.partition(":") | |
| if sep: | |
| out[k.strip().lower()] = v.strip() | |
| return out | |
| def parse_record(raw: bytes) -> dict: | |
| data = gzip.decompress(raw) | |
| if data.startswith(b"WARC/"): | |
| head, _, rest = data.partition(b"\r\n\r\n") | |
| wh = _headers(head) | |
| block = rest[:int(wh.get("content-length", len(rest)))] | |
| else: | |
| first, _, rest = data.partition(b"\n") | |
| block = rest[:int(first.split()[-1])] | |
| http_head, payload = _split_head(block) if block.startswith(b"HTTP/") else (b"", block) | |
| return {"http_headers": _headers(http_head) if http_head else {}, "payload": payload} | |
| def dechunk(body: bytes) -> bytes: | |
| out, pos = bytearray(), 0 | |
| while pos < len(body): | |
| eol = body.find(b"\r\n", pos) | |
| if eol < 0: | |
| break | |
| n = int(body[pos:eol].split(b";")[0].strip() or b"0", 16) | |
| if n == 0: | |
| break | |
| out += body[eol + 2:eol + 2 + n] | |
| pos = eol + 2 + n + 2 | |
| return bytes(out) | |
| def payload_variants(rec: dict) -> list: | |
| body = rec["payload"] | |
| if "chunked" in rec["http_headers"].get("transfer-encoding", "").lower(): | |
| return [("dechunked_payload", dechunk(body)), ("payload", body)] | |
| return [("payload", body)] | |
| def verify_payload(row: dict, data: bytes): | |
| want = row.get("payload_size_bytes") | |
| if want is not None and len(data) != want: | |
| return f"payload size differs: expected {want}, got {len(data)}" | |
| h = Hasher(len(data)) | |
| h.update(data) | |
| got = h.digests() | |
| checked = 0 | |
| for name in ("md5", "sha1", "sha256"): | |
| w = str((row.get("hashes") or {}).get(name) or "").lower() | |
| if w: | |
| checked += 1 | |
| if got[name] != w: | |
| return f"{name} differs: expected {w}, got {got[name]}" | |
| return None if checked else "no hash that can be checked" | |
| def fetch_payload(row, dest, url, timeout, opener): | |
| if _rng(row) is None or row.get("size_bytes") is None: | |
| raise Unsupported("a WARC record row needs a byte range and a size") | |
| with opener(url, timeout, _rng(row)) as src: | |
| raw = src.read(row["size_bytes"] + 1) | |
| if len(raw) != row["size_bytes"]: | |
| return {"status": "failed", "url": url, "reason": f"size differs: expected {row['size_bytes']}, got {len(raw)}"} | |
| try: | |
| rec = parse_record(raw) | |
| except Exception as e: # noqa: BLE001 (a cut or misplaced record) | |
| return {"status": "failed", "url": url, "reason": f"cannot parse the record: {type(e).__name__}: {e}"} | |
| whys = [] | |
| for label, data in payload_variants(rec): | |
| why = verify_payload(row, data) | |
| if why is None: | |
| _write(dest, data) | |
| return {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": label, "url": url} | |
| whys.append(f"{label}: {why}") | |
| return {"status": "failed", "url": url, "reason": "; ".join(whys)} | |
| # API responses | |
| def extract_field(doc, path: str): | |
| cur = doc | |
| for part in path.split("."): | |
| if isinstance(cur, list) and part.isdigit(): | |
| cur = cur[int(part)] if int(part) < len(cur) else None | |
| elif isinstance(cur, dict): | |
| cur = cur.get(part) | |
| else: | |
| return None | |
| if cur is None: | |
| return None | |
| return cur | |
| def fetch_api_body(row, dest, url, timeout, opener): | |
| with opener(url, timeout, None) as src: | |
| raw = src.read() | |
| if raw[:2] == b"\x1f\x8b": | |
| raw = gzip.decompress(raw) | |
| try: | |
| doc = json.loads(raw.decode("utf-8")) | |
| except (UnicodeDecodeError, ValueError) as e: | |
| return {"status": "failed", "url": url, "reason": f"the API response is not JSON: {e}"} | |
| path = (row.get("source_meta") or {}).get("api_body_field") or API_BODY_DEFAULT_FIELD | |
| v = extract_field(doc, path) | |
| body = ("" if v is None else v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)).encode("utf-8") | |
| h = Hasher(len(body)) | |
| h.update(body) | |
| why = verify(row, len(body), h.digests()) | |
| if why: | |
| return {"status": "failed", "url": url, "reason": f"{path}: {why}"} | |
| _write(dest, body) | |
| return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(body), | |
| "matched_on": f"api_body:{path}", "url": url}, | |
| h.digests()["sha256"], "the source publishes no hash; sha256 computed on download") | |
| # zip members | |
| def _get_range(url, timeout, start, length, opener): | |
| with opener(url, timeout, (start, length)) as r: | |
| data = r.read(length + 1) | |
| if len(data) != length: | |
| raise Unsupported(f"range {start}+{length} returned {len(data)} bytes") | |
| return data | |
| def member_limit(row: dict) -> int: | |
| """The most bytes kept for one member: its size when the row knows it (a longer result then fails the size | |
| check), otherwise the row's cap.""" | |
| return row["size_bytes"] if row.get("size_bytes") is not None else cap_of(row) | |
| def _too_large_unknown(row: dict, size: int, limit: int) -> None: | |
| if row.get("size_bytes") is None and size > limit: | |
| raise TooLarge(f"the member has {size} bytes, more than the cap of {limit} bytes") | |
| def _finish(row, dest, data, url, matched_on, names=("crc32", "md5", "sha1", "sha256")): | |
| """Check data against the row's size and hashes, write it to dest, -> the manifest fields.""" | |
| h = Hasher(len(data)) | |
| h.update(data) | |
| why = verify(row, len(data), h.digests(), names=names) | |
| if why: | |
| return {"status": "failed", "url": url, "reason": why} | |
| _write(dest, data) | |
| return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": matched_on, | |
| "url": url}, | |
| h.digests()["sha256"], NO_HASH_MEMBER) | |
| def _zip_member_bytes(url, timeout, opener, loff, method, csize, limit): | |
| """The bytes of one zip member (read with Range requests from its local header), at most limit + 1 of them; | |
| None when the local header signature is wrong.""" | |
| head = _get_range(url, timeout, loff, ZIP_LOCAL_LEN, opener) | |
| if head[:4] != ZIP_LOCAL_SIG: | |
| return None | |
| n, m = struct.unpack_from("<HH", head, 26) | |
| start = loff + ZIP_LOCAL_LEN + n + m | |
| raw = _get_range(url, timeout, start, csize, opener) if csize else b"" | |
| if method == 0: | |
| return raw[:limit + 1] | |
| if method == 8: | |
| d = zlib.decompressobj(-15) | |
| data = d.decompress(raw, limit + 1) | |
| if len(data) <= limit and not d.unconsumed_tail: | |
| data += d.flush() | |
| return data | |
| raise Unsupported(f"zip compression method {method}") | |
| def fetch_member(row, dest, url, timeout, opener): | |
| ze = row.get("zip_entry") | |
| if not isinstance(ze, dict) or ze.get("local_header_offset") is None: | |
| raise Unsupported("an archive member row without zip_entry") | |
| limit = member_limit(row) | |
| data = _zip_member_bytes(url, timeout, opener, ze["local_header_offset"], ze["compression_method"], | |
| ze["compressed_size"], limit) | |
| if data is None: | |
| return {"status": "failed", "url": url, "reason": "the zip local header signature is wrong"} | |
| _too_large_unknown(row, len(data), limit) | |
| h = Hasher(len(data)) | |
| h.update(data) | |
| why = verify(row, len(data), h.digests(), names=("crc32", "md5", "sha1", "sha256")) | |
| if why: | |
| return {"status": "failed", "url": url, "reason": why} | |
| _write(dest, data) | |
| return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": "zip_member", | |
| "url": url}, | |
| h.digests()["sha256"], NO_HASH_MEMBER) | |
| # members of software packages: zip-based ones (wheel, jar, nupkg) through the central directory, tar-based | |
| # ones (sdist, npm .tgz, .crate) by downloading the whole package within the cap | |
| ZIP_SUFFIXES = (".whl", ".zip", ".jar", ".nupkg", ".egg") | |
| TAR_SUFFIXES = (".tgz", ".tar.gz", ".crate", ".tar", ".tar.bz2", ".tbz2", ".tar.xz", ".txz") | |
| ZIP_EOCD_SIG = b"PK\x05\x06" | |
| ZIP64_LOCATOR_SIG = b"PK\x06\x07" | |
| ZIP64_EOCD_SIG = b"PK\x06\x06" | |
| ZIP_CD_SIG = b"PK\x01\x02" | |
| ZIP_TAIL = 22 + 0xFFFF # end record plus the longest comment | |
| ZIP_CD_MAX = 64_000_000 | |
| PACKAGE_CACHE_BYTES = 1_000_000_000 # packages kept on disk during one run, oldest dropped first | |
| def package_kind(uri) -> str | None: | |
| path = urllib.parse.urlsplit(str(uri or "")).path.lower() | |
| if path.endswith(ZIP_SUFFIXES): | |
| return "zip_package" | |
| if path.endswith(TAR_SUFFIXES): | |
| return "tar_package" | |
| if path.endswith(".7z"): | |
| return "sevenzip_member" | |
| return None | |
| def zip_central_directory(url, timeout, opener) -> bytes: | |
| """The central directory of a remote zip: the end record is found in the last 64 KB (one Range request), | |
| zip64 archives through their locator. Some servers (files.pythonhosted.org) answer 416 when the file is | |
| shorter than the suffix asked for; the whole file is then read instead, as it is under 64 KB.""" | |
| try: | |
| with opener(url, timeout, (None, ZIP_TAIL)) as r: | |
| tail = r.read(ZIP_TAIL + 1) | |
| except urllib.error.HTTPError as e: | |
| if e.code != 416: | |
| raise | |
| with opener(url, timeout, None) as r: | |
| tail = r.read(ZIP_TAIL + 1) | |
| if len(tail) > ZIP_TAIL: | |
| raise Unsupported("the server refused the 64 KB tail range of a file longer than 64 KB") from None | |
| i = tail.rfind(ZIP_EOCD_SIG) | |
| if i < 0 or len(tail) - i < 22: | |
| raise Unsupported("no zip end record in the last 64 KB") | |
| n_entries, cd_size, cd_off = struct.unpack_from("<HII", tail, i + 10) | |
| if n_entries == 0xFFFF or 0xFFFFFFFF in (cd_size, cd_off): | |
| j = i - 20 | |
| if j < 0 or tail[j:j + 4] != ZIP64_LOCATOR_SIG: | |
| raise Unsupported("zip64 archive without a zip64 locator") | |
| rec = _get_range(url, timeout, struct.unpack_from("<Q", tail, j + 8)[0], 56, opener) | |
| if rec[:4] != ZIP64_EOCD_SIG: | |
| raise Unsupported("the zip64 end record signature is wrong") | |
| cd_size, cd_off = struct.unpack_from("<QQ", rec, 40) | |
| if cd_size > ZIP_CD_MAX: | |
| raise Unsupported(f"the zip central directory has {cd_size} bytes, more than {ZIP_CD_MAX}") | |
| return _get_range(url, timeout, cd_off, cd_size, opener) if cd_size else b"" | |
| def zip_find(cd: bytes, name: str): | |
| """-> {local_header_offset, compression_method, compressed_size, size, crc32} of the entry called name, or | |
| None.""" | |
| pos = 0 | |
| while pos + 46 <= len(cd): | |
| if cd[pos:pos + 4] != ZIP_CD_SIG: | |
| raise Unsupported("the zip central directory is damaged") | |
| flags, method = struct.unpack_from("<HH", cd, pos + 8) | |
| crc, csize, usize = struct.unpack_from("<III", cd, pos + 16) | |
| nlen, xlen, clen = struct.unpack_from("<HHH", cd, pos + 28) | |
| loff = struct.unpack_from("<I", cd, pos + 42)[0] | |
| raw = cd[pos + 46:pos + 46 + nlen] | |
| extra = cd[pos + 46 + nlen:pos + 46 + nlen + xlen] | |
| pos += 46 + nlen + xlen + clen | |
| if raw.decode("utf-8" if flags & 0x800 else "cp437", "replace") != name: | |
| continue | |
| if 0xFFFFFFFF in (usize, csize, loff): | |
| k = 0 | |
| while k + 4 <= len(extra): | |
| hid, hlen = struct.unpack_from("<HH", extra, k) | |
| if hid == 1: | |
| vals = list(struct.unpack_from(f"<{hlen // 8}Q", extra, k + 4)) | |
| if usize == 0xFFFFFFFF and vals: | |
| usize = vals.pop(0) | |
| if csize == 0xFFFFFFFF and vals: | |
| csize = vals.pop(0) | |
| if loff == 0xFFFFFFFF and vals: | |
| loff = vals.pop(0) | |
| break | |
| k += 4 + hlen | |
| return {"local_header_offset": loff, "compression_method": method, "compressed_size": csize, | |
| "size": usize, "crc32": crc} | |
| return None | |
| def fetch_zip_package(row, dest, url, timeout, opener): | |
| name = row.get("member_path") | |
| e = zip_find(zip_central_directory(url, timeout, opener), name) | |
| if e is None: | |
| return {"status": "failed", "url": url, "reason": f"{name} is not in the package's central directory"} | |
| limit = member_limit(row) | |
| _too_large_unknown(row, e["size"], limit) | |
| data = _zip_member_bytes(url, timeout, opener, e["local_header_offset"], e["compression_method"], | |
| e["compressed_size"], max(limit, e["size"])) | |
| if data is None: | |
| return {"status": "failed", "url": url, "reason": "the zip local header signature is wrong"} | |
| if len(data) != e["size"] or zlib.crc32(data) & 0xFFFFFFFF != e["crc32"]: | |
| return {"status": "failed", "url": url, | |
| "reason": "the member does not match the size and CRC32 of the package's central directory"} | |
| return _finish(row, dest, data, url, "zip_package") | |
| _PACKAGES: dict = {"dir": None, "files": {}} | |
| def clear_package_cache() -> None: | |
| """Delete the packages downloaded during this run.""" | |
| d, _PACKAGES["dir"] = _PACKAGES["dir"], None | |
| _PACKAGES["files"].clear() | |
| if d: | |
| shutil.rmtree(d, ignore_errors=True) | |
| def download_package(url, timeout, opener, limit) -> Path: | |
| """Download a whole package into a temporary directory kept for this run (reused for its other members); | |
| stop with TooLarge after limit bytes.""" | |
| files = _PACKAGES["files"] | |
| if url in files: | |
| return files[url] | |
| if _PACKAGES["dir"] is None: | |
| _PACKAGES["dir"] = tempfile.mkdtemp(prefix="fetch-packages-") | |
| path = Path(_PACKAGES["dir"], hashlib.sha256(url.encode("utf-8")).hexdigest()[:24]) | |
| n = 0 | |
| try: | |
| with opener(url, timeout, None) as src, open(path, "wb") as out: | |
| while True: | |
| b = src.read(CHUNK) | |
| if not b: | |
| break | |
| n += len(b) | |
| if n > limit: | |
| raise TooLarge(f"the package is larger than the cap of {limit} bytes; download stopped") | |
| out.write(b) | |
| except BaseException: | |
| path.unlink(missing_ok=True) | |
| raise | |
| while files and sum(p.stat().st_size for p in files.values()) + n > PACKAGE_CACHE_BYTES: | |
| old = next(iter(files)) | |
| files.pop(old).unlink(missing_ok=True) | |
| files[url] = path | |
| return path | |
| def _tar_lookup(tf, name: str): | |
| for n in (name, "./" + name, name[2:] if name.startswith("./") else None): | |
| if n: | |
| try: | |
| return tf.getmember(n) | |
| except KeyError: | |
| continue | |
| return None | |
| def fetch_tar_package(row, dest, url, timeout, opener): | |
| path = download_package(url, timeout, opener, whole_cap_of(row)) | |
| name = row.get("member_path") | |
| limit = member_limit(row) | |
| try: | |
| tf = tarfile.open(path, "r:*") | |
| except (tarfile.TarError, OSError, EOFError) as e: | |
| return {"status": "failed", "url": url, "reason": f"cannot open the package as a tar archive: {e}"} | |
| with tf: | |
| m = _tar_lookup(tf, name) | |
| if m is None: | |
| return {"status": "failed", "url": url, "reason": f"{name} is not in the package"} | |
| if not m.isfile(): | |
| return {"status": "failed", "url": url, "reason": f"{name} is not a regular file in the package"} | |
| _too_large_unknown(row, m.size, limit) | |
| f = tf.extractfile(m) | |
| data = f.read(limit + 1) if f else b"" | |
| return _finish(row, dest, data, url, "tar_package") | |
| # 7z members (the directory is read with Range requests; see sevenzip.py next to this script) | |
| SEVENZIP_PIECE = 8 << 20 | |
| def _sevenzip(): | |
| try: | |
| from . import sevenzip | |
| except ImportError: | |
| try: | |
| import sevenzip | |
| except ImportError: | |
| raise Unsupported("7z members need sevenzip.py next to this script") from None | |
| return sevenzip | |
| def _range_pieces(url, timeout, opener, start, length): | |
| end = start + length | |
| for off in range(start, end, SEVENZIP_PIECE): | |
| yield _get_range(url, timeout, off, min(SEVENZIP_PIECE, end - off), opener) | |
| def fetch_sevenzip_member(row, dest, url, timeout, opener): | |
| sz = _sevenzip() | |
| name = row.get("member_path") | |
| def read(off, ln): | |
| return _get_range(url, timeout, off, ln, opener) | |
| try: | |
| sig = sz.parse_signature_header(read(0, sz.SIGNATURE_HEADER_LEN)) | |
| arc = sz.parse_header(sig, read(sig.header_pos, sig.next_header_size), read) | |
| except sz.Unsupported7z as e: | |
| raise Unsupported(f"7z directory: {e}") from None | |
| except sz.Format7zError as e: | |
| return {"status": "failed", "url": url, "reason": f"cannot read the 7z directory: {e}"} | |
| e = next((x for x in arc.entries if x.name == name and not x.is_dir), None) | |
| if e is None: | |
| return {"status": "failed", "url": url, "reason": f"{name} is not in the 7z directory"} | |
| limit = member_limit(row) | |
| _too_large_unknown(row, e.size, limit) | |
| if e.folder is None or e.size == 0: | |
| return _finish(row, dest, b"", url, "sevenzip_member") | |
| folder = arc.folders[e.folder] | |
| pstart, plen = arc.folder_pack(e.folder) | |
| need = e.offset_in_folder + e.size | |
| whole = whole_cap_of(row) | |
| if need > max(whole, e.size if row.get("size_bytes") is not None else 0): | |
| raise TooLarge(f"the member ends {need} bytes into a solid 7z block, more than the cap of {whole} bytes") | |
| try: | |
| if folder.methods == ["copy"]: | |
| data = read(pstart + e.offset_in_folder, e.size) | |
| if e.crc32 is not None and zlib.crc32(data) & 0xFFFFFFFF != e.crc32: | |
| raise sz.Format7zError(f"{name}: CRC32 differs") | |
| else: | |
| try: | |
| data = b"".join(sz.iter_entry(folder, e, _range_pieces(url, timeout, opener, pstart, plen))) | |
| except sz.Unsupported7z: | |
| if plen > whole or folder.unpack_size > whole: | |
| raise TooLarge(f"the 7z block ({folder.unpack_size} bytes, coders {','.join(folder.methods)}) " | |
| f"must be decoded whole and is larger than the cap of {whole} bytes") from None | |
| data = sz.extract(arc, sz.decode_folder(folder, read(pstart, plen)), e) | |
| except sz.Unsupported7z as x: | |
| raise Unsupported(f"7z block: {x}") from None | |
| except sz.Format7zError as x: | |
| return {"status": "failed", "url": url, "reason": f"7z member: {x}"} | |
| return _finish(row, dest, data, url, "sevenzip_member") | |
| # members of tar archives stored as gzip (the arXiv source bundles): the range is one gzip member | |
| def fetch_gzip_member(row, dest, url, timeout, opener): | |
| rng = _rng(row) | |
| if rng is None or rng[1] is None: | |
| raise Unsupported("a gzip member row needs a byte range") | |
| raw = _get_range(url, timeout, rng[0], rng[1], opener) | |
| limit = whole_cap_of(row) | |
| parts, n, rest = [], 0, raw | |
| while True: # a gzip file may hold several members; each is decompressed in turn | |
| d = zlib.decompressobj(16 + zlib.MAX_WBITS) | |
| try: | |
| piece = d.decompress(rest, limit + 1 - n) | |
| if not d.unconsumed_tail: | |
| piece += d.flush() | |
| except zlib.error as e: | |
| return {"status": "failed", "url": url, "reason": f"cannot decompress the gzip member: {e}"} | |
| n += len(piece) | |
| if n > limit: | |
| raise TooLarge(f"the member decompresses to more than the cap of {limit} bytes") | |
| if not d.eof: | |
| return {"status": "failed", "url": url, "reason": "the gzip member is incomplete"} | |
| parts.append(piece) | |
| rest = d.unused_data | |
| if not rest: | |
| break | |
| last = parts[-1] # the gzip trailer (CRC32, length modulo 2^32) covers the last member only | |
| want = row.get("payload_size_bytes") | |
| if want is not None and len(last) % (1 << 32) != int(want): | |
| return {"status": "failed", "url": url, | |
| "reason": f"decompressed size differs: expected {want} (modulo 2^32), got {len(last)}"} | |
| got = f"{zlib.crc32(last) & 0xFFFFFFFF:08x}" | |
| tail = f"{struct.unpack('<I', raw[-8:-4])[0]:08x}" | |
| want_crc = str((row.get("source_meta") or {}).get("crc32") or "").lower() | |
| if got != tail or (want_crc and got != want_crc): | |
| return {"status": "failed", "url": url, | |
| "reason": f"CRC32 differs: computed {got}, gzip trailer {tail}, pointer {want_crc or '-'}"} | |
| data = b"".join(parts) | |
| hashes = row.get("hashes") or {} | |
| h = Hasher(len(data)) | |
| h.update(data) | |
| dg = h.digests() | |
| for name in ("md5", "sha1", "sha256"): | |
| w = str(hashes.get(name) or "").lower() | |
| if w and dg[name] != w: | |
| return {"status": "failed", "url": url, "reason": f"{name} differs: expected {w}, got {dg[name]}"} | |
| _write(dest, data) | |
| res = {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": "gzip_member", "crc32": got, | |
| "url": url} | |
| if not any(hashes.get(k) for k in ("md5", "sha1", "sha256")): | |
| res["unverified"] = "checked against the gzip CRC32 and length; sha256 computed on download" | |
| res["sha256"] = dg["sha256"] | |
| return res | |
| # requester-pays S3 (the requester's own AWS account pays; credentials come from the environment) | |
| AWS_REGION = "us-east-1" | |
| EMPTY_SHA256 = hashlib.sha256(b"").hexdigest() | |
| def aws_credentials(): | |
| """(access key, secret key, session token or None) from AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and | |
| AWS_SESSION_TOKEN, or None when they are not set. The script never stores or prints them.""" | |
| ak, sk = os.environ.get("AWS_ACCESS_KEY_ID"), os.environ.get("AWS_SECRET_ACCESS_KEY") | |
| return (ak, sk, os.environ.get("AWS_SESSION_TOKEN") or None) if ak and sk else None | |
| def _hmac(key: bytes, msg: str) -> bytes: | |
| return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() | |
| def sigv4_headers(method: str, url: str, headers: dict, access_key: str, secret_key: str, *, | |
| region: str = AWS_REGION, service: str = "s3", now=None, payload_hash: str = EMPTY_SHA256) -> dict: | |
| """AWS Signature Version 4: -> the request headers plus host, x-amz-date, x-amz-content-sha256 and | |
| Authorization. Every header given is signed; the path is encoded once, as S3 expects.""" | |
| u = urllib.parse.urlsplit(url) | |
| now = now or datetime.datetime.now(datetime.timezone.utc) | |
| amz_date = now.strftime("%Y%m%dT%H%M%SZ") | |
| day = amz_date[:8] | |
| h = {k.lower(): " ".join(str(v).split()) for k, v in headers.items()} | |
| h["host"] = u.netloc | |
| h["x-amz-date"] = amz_date | |
| h["x-amz-content-sha256"] = payload_hash | |
| names = sorted(h) | |
| q = urllib.parse.parse_qsl(u.query, keep_blank_values=True) | |
| enc = lambda s, keep: urllib.parse.quote(s, safe="/~" if keep else "~") # noqa: E731 | |
| canon_q = "&".join(f"{enc(k, False)}={enc(v, False)}" for k, v in sorted(q)) | |
| canon = "\n".join([method, enc(urllib.parse.unquote(u.path or "/"), True), canon_q, | |
| "".join(f"{n}:{h[n]}\n" for n in names), ";".join(names), payload_hash]) | |
| scope = f"{day}/{region}/{service}/aws4_request" | |
| to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canon.encode("utf-8")).hexdigest()]) | |
| k = _hmac(_hmac(_hmac(_hmac(("AWS4" + secret_key).encode("utf-8"), day), region), service), "aws4_request") | |
| sig = hmac.new(k, to_sign.encode("utf-8"), hashlib.sha256).hexdigest() | |
| out = {n: h[n] for n in names} | |
| out["authorization"] = (f"AWS4-HMAC-SHA256 Credential={access_key}/{scope}, " | |
| f"SignedHeaders={';'.join(names)}, Signature={sig}") | |
| return out | |
| def requester_pays_opener(opener, creds, region: str = AWS_REGION): | |
| """Wrap opener so that every request is signed and carries x-amz-request-payer: requester.""" | |
| ak, sk, token = creds | |
| def op(url, timeout, rng=None, headers=None): | |
| h = {"x-amz-request-payer": "requester", **(headers or {})} | |
| if rng: | |
| h["range"] = range_header(rng) | |
| if token: | |
| h["x-amz-security-token"] = token | |
| return opener(url, timeout, rng, headers=sigv4_headers("GET", url, h, ak, sk, region=region)) | |
| return op | |
| # single lichess games (public export API, one request at a time) | |
| LICHESS_BASE = "https://lichess.org" | |
| LICHESS_GAP = 1.0 # seconds between two requests | |
| LICHESS_WAIT_429 = 60.0 # lichess asks clients to wait a full minute after HTTP 429 | |
| LICHESS_429_TRIES = 2 | |
| LICHESS_NOT_GAMES = {"training", "practice", "streamer", "tutorial", "analysis", "features", "insights", | |
| "tutorials", "variants"} | |
| LICHESS_GAME_RE = re.compile(r"^https?://(?:www\.)?lichess\.org/([A-Za-z0-9]{8})(?:[A-Za-z0-9]{4})?" | |
| r"(?:/(?:white|black))?/?(?:#\d*)?$") | |
| _LICHESS = {"last": None} | |
| def lichess_game_id(row: dict): | |
| """The 8-character game id of a row that points to one lichess game: source_meta.game_id, or a game page | |
| address (https://lichess.org/<id>, optionally with the 4 player characters, /white or /black, #ply).""" | |
| sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {} | |
| gid = sm.get("game_id") | |
| if gid is None: | |
| m = LICHESS_GAME_RE.match(str(row.get("uri") or "")) | |
| gid = m.group(1) if m and m.group(1).lower() not in LICHESS_NOT_GAMES else None | |
| return gid if isinstance(gid, str) and re.fullmatch(r"[A-Za-z0-9]{8}", gid) else None | |
| def fetch_lichess_game(row, dest, url, timeout, opener, *, sleep=time.sleep): | |
| limit = member_limit(row) | |
| for attempt in range(LICHESS_429_TRIES + 1): | |
| last = _LICHESS["last"] | |
| if last is not None: | |
| wait = LICHESS_GAP - (time.monotonic() - last) | |
| if wait > 0: | |
| sleep(wait) | |
| try: | |
| with opener(url, timeout, None, headers={"Accept": "application/x-chess-pgn"}) as src: | |
| data = src.read(limit + 1) | |
| except urllib.error.HTTPError as e: | |
| if e.code == 429 and attempt < LICHESS_429_TRIES: | |
| sleep(LICHESS_WAIT_429) | |
| continue | |
| raise | |
| finally: | |
| _LICHESS["last"] = time.monotonic() | |
| break | |
| _too_large_unknown(row, len(data), limit) | |
| if not data.strip(): | |
| return {"status": "failed", "url": url, "reason": "the export returned no game"} | |
| h = Hasher(len(data)) | |
| h.update(data) | |
| why = verify(row, len(data), h.digests()) | |
| if why and (row.get("hashes") or row.get("size_bytes") is not None): | |
| return {"status": "failed", "url": url, "reason": why} | |
| _write(dest, data) | |
| return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(data), | |
| "matched_on": "lichess_game_export", "url": url}, | |
| h.digests()["sha256"], "single-game export; sha256 computed on download") | |
| # decompressing a fetched .gz, .bz2 or .zst file (--decompress) | |
| DECOMPRESS = {".gz": "gzip", ".bz2": "bz2", ".zst": "zstd"} | |
| def decompress_target(path: Path, row: dict): | |
| """(kind, output path) for a compressed file, or (None, None).""" | |
| kind = DECOMPRESS.get(path.suffix.lower()) | |
| if kind: | |
| return kind, path.with_suffix("") | |
| kind = DECOMPRESS.get("." + str(row.get("ext") or "").lower().lstrip(".")) | |
| return (kind, path.with_name(path.name + ".decompressed")) if kind else (None, None) | |
| def _decompressor(kind: str, f): | |
| if kind == "gzip": | |
| return gzip.GzipFile(fileobj=f) | |
| if kind == "bz2": | |
| return bz2.BZ2File(f) | |
| try: | |
| import zstandard | |
| except ImportError: | |
| raise Unsupported("decompressing .zst needs the zstandard package (pip install zstandard)") from None | |
| return zstandard.ZstdDecompressor().stream_reader(f, read_across_frames=True) | |
| def decompress_file(path: Path, row: dict, limit: int): | |
| """Stream-decompress a fetched file next to it (every gzip member, bz2 stream or zstd frame), at most limit | |
| bytes. On success the compressed file is deleted; otherwise it is kept. -> manifest fields, or None when | |
| the file is not compressed.""" | |
| kind, out = decompress_target(path, row) | |
| if kind is None: | |
| return None | |
| part = out.with_name(out.name + ".part") | |
| h = Hasher(None) | |
| try: | |
| with open(path, "rb") as f, _decompressor(kind, f) as src, open(part, "wb") as o: | |
| while True: | |
| b = src.read(CHUNK) | |
| if not b: | |
| break | |
| h.update(b) | |
| if h.n > limit: | |
| break | |
| o.write(b) | |
| except Unsupported as e: | |
| part.unlink(missing_ok=True) | |
| return {"status": "unsupported", "reason": str(e)} | |
| except Exception as e: # noqa: BLE001 (any decoder error: the compressed file stays) | |
| part.unlink(missing_ok=True) | |
| return {"status": "failed", "reason": f"cannot decompress ({kind}): {type(e).__name__}: {e}"} | |
| if h.n > limit: | |
| part.unlink(missing_ok=True) | |
| return {"status": "too_large", "reason": f"decompressed size is more than the cap of {limit} bytes; " | |
| "the compressed file is kept"} | |
| os.replace(part, out) | |
| path.unlink() | |
| return {"status": "ok", "path": str(out), "bytes": h.n, "sha256": h.digests()["sha256"], | |
| "compressed_path": str(path)} | |
| def method_of(row: dict) -> str: | |
| if lichess_game_id(row): | |
| return "lichess_game" | |
| if row.get("zip_entry") is not None: | |
| return "zip_member" | |
| scope = row.get("hash_scope") or "file" | |
| if scope == "gzip_member": | |
| return "gzip_member" | |
| if row.get("member_path") is not None and not _rng(row): | |
| kind = package_kind(row.get("uri")) | |
| if kind: | |
| return kind | |
| path = urllib.parse.urlsplit(str(row.get("uri") or "")).path | |
| return f"unsupported:member of {posixpath.basename(path) or 'an unknown container'}" | |
| if scope == "http_payload": | |
| return "warc_record" | |
| if scope == "api_body": | |
| return "api_body" | |
| if scope != "file": | |
| return f"unsupported:{scope}" | |
| return "range" if _rng(row) else "file" | |
| FETCHERS = {"file": fetch_file, "range": fetch_file, "warc_record": fetch_payload, "api_body": fetch_api_body, | |
| "zip_member": fetch_member, "zip_package": fetch_zip_package, "tar_package": fetch_tar_package, | |
| "sevenzip_member": fetch_sevenzip_member, "gzip_member": fetch_gzip_member, | |
| "lichess_game": fetch_lichess_game} | |
| def skip_reason(row: dict): | |
| na = (row.get("access") or {}).get("needs_auth") | |
| if na == "guestbook": | |
| return "the dataset asks for a guestbook form before download; not filled in, no request sent" | |
| if na == "restricted": | |
| return "restricted file; access must be requested from the dataset authors, no request sent" | |
| if na == "requester_pays" and aws_credentials() is None: | |
| return ("requester-pays bucket: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (your own AWS account pays " | |
| "the request and transfer charges); no request sent") | |
| return None | |
| def fetch_one(row: dict, out: Path, *, timeout: float = 120, opener=open_url, retries: int = RETRIES, | |
| backoff: float = BACKOFF, sleep=time.sleep) -> dict: | |
| base = {"pointer_id": row.get("pointer_id")} | |
| why = skip_reason(row) | |
| if why: | |
| return {**base, "status": "skipped", "reason": why} | |
| method = method_of(row) | |
| fn = FETCHERS.get(method) | |
| size, cap = row.get("size_bytes"), cap_of(row) | |
| if size is not None and int(size) > cap: | |
| return {**base, "status": "too_large", "method": method, | |
| "reason": f"size {int(size)} is more than the cap of {cap} bytes; not downloaded"} | |
| if method == "lichess_game": | |
| urls = [f"{LICHESS_BASE}/game/export/{lichess_game_id(row)}"] | |
| fn = (lambda f: lambda *a: f(*a, sleep=sleep))(fn) | |
| else: | |
| urls = [u for u in candidates(row) if method in ("file", "api_body") | |
| or u.startswith(("https://", "http://", "file://"))] | |
| if fn is None or not urls: | |
| return {**base, "status": "unsupported", "method": method, | |
| "reason": "no supported address" if fn else f"fetch method {method}"} | |
| if (row.get("access") or {}).get("needs_auth") == "requester_pays": | |
| opener = requester_pays_opener(opener, aws_credentials(), (row.get("access") or {}).get("region") or AWS_REGION) | |
| dest = dest_path(out, row) | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| errors, n_retry = [], 0 | |
| for url in urls: | |
| for k in range(retries + 1): | |
| try: | |
| res = fn(row, dest, url, timeout, opener) | |
| except TooLarge as e: | |
| return {**base, "status": "too_large", "method": method, "reason": str(e), "url": url, | |
| **({"retries": n_retry} if n_retry else {})} | |
| except Unsupported as e: | |
| errors.append(f"{url}: {e}") | |
| break | |
| except Exception as e: # noqa: BLE001 (network errors: retry the transient ones, then the next address) | |
| if transient(e) and k < retries: | |
| n_retry += 1 | |
| sleep(backoff * 2 ** k) | |
| continue | |
| errors.append(f"{url}: {type(e).__name__}: {e}") | |
| break | |
| return {**base, "method": method, **res, **({"retries": n_retry} if n_retry else {})} | |
| return {**base, "status": "failed", "method": method, "reason": "; ".join(errors) or "no address answered", | |
| **({"retries": n_retry} if n_retry else {})} | |
| # ---------- content check ---------- | |
| CONTENT_CHECKS = ("scanned_pdf", "error_page", "ext_mismatch") | |
| CHECK_TIMEOUT = 60 | |
| CHECK_READ = 200_000 | |
| PDF_PAGES_READ = 5 | |
| PDF_MIN_CHARS_PER_PAGE = 20 | |
| ERROR_BODY_SHORT = 3000 | |
| ERROR_BODY_HEAD = 1500 | |
| ERROR_WORDS = re.compile( | |
| r"\b(404|403|500|502|503)\b|not\s+found|page\s+cannot\s+be|cannot\s+be\s+(found|displayed)|\berror\b|" | |
| r"access\s+denied|forbidden|object\s+moved|has\s+moved|moved\s+permanently|no\s+longer\s+(available|exists)|" | |
| r"temporarily\s+unavailable|session\s+(has\s+)?expired|server\s+error|bad\s+request|invalid\s+(request|url)|" | |
| r"unauthori[sz]ed|redirect", re.I) | |
| TEXT_EXTS = frozenset({"html", "htm", "xhtml", "txt", "text", "xml", "csv", "log", "kml", "sql"}) | |
| _OLE = frozenset({"application/cdfv2", "application/vnd.ms-office", "application/x-ole-storage", | |
| "application/cdfv2-unknown"}) | |
| _TXT = frozenset({"text/plain", "text/html", "text/xml"}) | |
| _OOXML = "application/vnd.openxmlformats-officedocument." | |
| EXT_MIME = { | |
| "pdf": {"application/pdf"}, | |
| "html": _TXT, "htm": _TXT, "xhtml": _TXT | {"application/xhtml+xml"}, | |
| "txt": _TXT | {"text/x-c", "text/x-c++", "text/x-fortran", "text/x-makefile", "text/x-shellscript", "text/x-tex", | |
| "text/x-asm", "text/x-po", "text/x-java", "text/x-perl", "text/csv", "text/x-diff", "text/x-ruby", | |
| "text/x-script.python", "text/rtf", "text/x-pascal", "text/troff", "text/x-lisp", "text/x-awk", | |
| "text/x-msdos-batch", "application/csv", "application/json"}, | |
| "text": _TXT, "log": {"text/plain"}, | |
| "xml": _TXT | {"application/xml", "image/svg+xml"}, | |
| "kml": _TXT | {"application/xml", "application/vnd.google-earth.kml+xml"}, | |
| "csv": {"text/csv", "text/plain", "application/csv"}, | |
| "json": {"application/json", "text/plain"}, | |
| "sql": {"text/plain", "text/x-c", "text/x-c++"}, | |
| "jpg": {"image/jpeg"}, "jpeg": {"image/jpeg"}, "gif": {"image/gif"}, "png": {"image/png"}, | |
| "doc": {"application/msword"} | _OLE, "xls": {"application/vnd.ms-excel"} | _OLE, | |
| "ppt": {"application/vnd.ms-powerpoint"} | _OLE, "pps": {"application/vnd.ms-powerpoint"} | _OLE, | |
| "docx": {_OOXML + "wordprocessingml.document", "application/zip"}, | |
| "xlsx": {_OOXML + "spreadsheetml.sheet", "application/zip"}, | |
| "pptx": {_OOXML + "presentationml.presentation", "application/zip"}, | |
| "ps": {"application/postscript"}, "eps": {"application/postscript", "image/x-eps"}, | |
| "rtf": {"text/rtf"}, | |
| "zip": {"application/zip"}, "gz": {"application/gzip", "application/x-gzip"}, | |
| "swf": {"application/x-shockwave-flash"}, | |
| } | |
| def run_tool(cmd: list, timeout: float = CHECK_TIMEOUT): | |
| """Run a system tool; returns (returncode, stdout) or None when the tool is not installed.""" | |
| if shutil.which(cmd[0]) is None: | |
| return None | |
| try: | |
| r = subprocess.run(cmd, capture_output=True, timeout=timeout, check=False) | |
| except subprocess.TimeoutExpired: | |
| return -9, "" | |
| except OSError: | |
| return None | |
| return r.returncode, r.stdout.decode("utf-8", "replace") | |
| def _text_of(data: bytes): | |
| s = data.decode("latin-1") | |
| m = re.search(r"<title[^>]*>(.*?)</title>", s, re.I | re.S) | |
| title = re.sub(r"\s+", " ", m.group(1)).strip() if m else "" | |
| body = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", s) | |
| body = re.sub(r"(?s)<[^>]+>", " ", body) | |
| body = re.sub(r" | ", " ", body) | |
| return title, re.sub(r"\s+", " ", body).strip() | |
| def _scanned_pdf(path: Path): | |
| """(result, detail, skip reason) for one PDF.""" | |
| fonts = run_tool(["pdffonts", str(path)]) | |
| if fonts is None: | |
| return "skipped", {}, "pdffonts not installed (poppler-utils)" | |
| if fonts[0] != 0: | |
| return "skipped", {}, "pdffonts could not read the file" | |
| text = run_tool(["pdftotext", "-l", str(PDF_PAGES_READ), "-q", str(path), "-"]) | |
| if text is None: | |
| return "skipped", {}, "pdftotext not installed (poppler-utils)" | |
| if text[0] != 0: | |
| return "skipped", {}, "pdftotext could not read the file" | |
| n_fonts = max(0, len(fonts[1].strip().splitlines()) - 2) | |
| pages = max(1, min(PDF_PAGES_READ, text[1].count("\f"))) | |
| chars = len(re.sub(r"\s", "", text[1])) | |
| detail = {"pdf_fonts": n_fonts, "pdf_text_chars": chars, "pdf_pages_read": pages} | |
| flagged = n_fonts == 0 and chars < PDF_MIN_CHARS_PER_PAGE * pages | |
| return ("flagged" if flagged else "clean"), detail, None | |
| def check_content(path: Path, ext: str | None = None) -> dict: | |
| """The three content checks for one downloaded file (see the module docstring).""" | |
| path = Path(path) | |
| ext = (ext or path.suffix).lower().lstrip(".") | |
| out: dict = {} | |
| skipped: dict = {} | |
| with open(path, "rb") as f: | |
| head = f.read(CHECK_READ) | |
| m = run_tool(["file", "-b", "--mime-type", str(path)]) | |
| mime = m[1].strip().lower() if m and m[0] == 0 and m[1].strip() else None | |
| if mime: | |
| out["mime"] = mime | |
| is_pdf = mime == "application/pdf" if mime else head[:1024].lstrip().startswith(b"%PDF-") | |
| if is_pdf: | |
| res, detail, why = _scanned_pdf(path) | |
| out["scanned_pdf"] = res | |
| out.update(detail) | |
| if why: | |
| skipped["scanned_pdf"] = why | |
| else: | |
| out["scanned_pdf"] = "not_applicable" | |
| if ext in TEXT_EXTS or mime in ("text/html", "text/xml", "application/xhtml+xml"): | |
| title, body = _text_of(head) | |
| hit = bool(ERROR_WORDS.search(title)) or ( | |
| len(body) < ERROR_BODY_SHORT and bool(ERROR_WORDS.search(body[:ERROR_BODY_HEAD]))) | |
| out["error_page"] = "flagged" if hit else "clean" | |
| if hit: | |
| out["error_hint"] = (title + " | " + body[:200])[:300] | |
| else: | |
| out["error_page"] = "not_applicable" | |
| allowed = EXT_MIME.get(ext) | |
| if allowed is None: | |
| out["ext_mismatch"] = "not_applicable" | |
| elif path.stat().st_size == 0: | |
| out["ext_mismatch"] = "not_applicable" | |
| out["empty"] = True | |
| elif mime is None: | |
| out["ext_mismatch"] = "skipped" | |
| skipped["ext_mismatch"] = "file not installed" if m is None else "file could not read the file" | |
| else: | |
| out["ext_mismatch"] = "clean" if mime in allowed else "flagged" | |
| out["flags"] = [c for c in CONTENT_CHECKS if out[c] == "flagged"] | |
| if skipped: | |
| out["skipped"] = skipped | |
| return out | |
| # ---------- command line ---------- | |
| def _key(row: dict) -> dict: | |
| rng = row.get("range") if isinstance(row.get("range"), dict) else {} | |
| return {"source": row.get("source"), "uri": row.get("uri"), "range_offset": rng.get("offset"), | |
| "member_path": row.get("member_path")} | |
| def selected_rows(con, sql: str, specs: dict): | |
| cur = con.execute(sql) | |
| names = [d[0] for d in cur.description] | |
| while True: | |
| batch = cur.fetchmany(1000) | |
| if not batch: | |
| break | |
| for t in batch: | |
| col = dict(zip(names, t)) | |
| spec = specs.get(col["source"]) | |
| if spec is None: | |
| yield {**_key({"source": col["source"], "uri": col["uri"], "member_path": col.get("member_path")}), | |
| "status": "unsupported", "reason": "source missing from meta/sources.json"}, None | |
| continue | |
| row = restore(col, spec) | |
| row["_size_cap"] = col.get("size_cap_bytes") | |
| row["_batch_cap"] = col.get("batch_cap_bytes") | |
| row["_nk_conflict"] = bool(col.get("natural_key_conflict")) | |
| yield None, row | |
| def parse_args(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawTextHelpFormatter) | |
| ap.add_argument("--repo", default=DEFAULT_REPO, help=f"dataset repository (default {DEFAULT_REPO})") | |
| ap.add_argument("--data", help="read the tables from this local copy or URL prefix instead of the repository") | |
| ap.add_argument("--tag", action="append", help="use tag (repeatable; see meta/tags.parquet)") | |
| ap.add_argument("--ext", action="append", help="file extension without the dot (repeatable)") | |
| ap.add_argument("--source", action="append", help="source name (repeatable)") | |
| ap.add_argument("--tier", type=lambda s: [x for x in s.split(",") if x], | |
| help="training license tiers, comma separated (default: all tiers)") | |
| ap.add_argument("--min-size", type=int, help="smallest size in bytes") | |
| ap.add_argument("--cap", choices=CAP_MODES, default="overall", | |
| help="size cap used when fetching (default overall: the 99th percentile of all benchmark task\n" | |
| "files; per-class: the cap of the row's content class, see meta/size_caps.json)") | |
| ap.add_argument("--max-size", type=int, | |
| help="size cap in bytes used when fetching, for every row (replaces --cap); it does not\n" | |
| "remove rows from the selection") | |
| ap.add_argument("--where", help="extra SQL condition on the row table p (and the batch table b)") | |
| ap.add_argument("--limit", type=int, help="at most this many rows (spread over the selection in a fixed order)") | |
| ap.add_argument("--starter", help="read starter/<tag>.parquet instead of the full tables") | |
| ap.add_argument("--no-default-filter", action="store_true", help="apply only the conditions given here") | |
| ap.add_argument("--out", default="fetched", help="directory for the files and the manifest (default ./fetched)") | |
| ap.add_argument("--dry-run", action="store_true", help="write the manifest of selected rows, download nothing") | |
| ap.add_argument("--print-sql", action="store_true", help="print the query and exit") | |
| ap.add_argument("--memory-limit", help="DuckDB memory limit, for example 4GB") | |
| ap.add_argument("--temp-dir", help="DuckDB spill directory") | |
| ap.add_argument("--decompress", action="store_true", | |
| help="after a verified download, decompress .gz, .bz2 and .zst files (within the row's cap)\n" | |
| "and delete the compressed file; .zst needs pip install zstandard") | |
| ap.add_argument("--check-content", action="store_true", | |
| help="after a verified download, flag scanned PDFs, error pages saved as files and extensions\n" | |
| "that do not match the content (manifest field content_check); needs the file command\n" | |
| "and poppler-utils (pdffonts, pdftotext), a missing tool skips its check") | |
| ap.add_argument("--timeout", type=float, default=120) | |
| a = ap.parse_args(argv) | |
| for t in a.tier or (): | |
| if t not in TIERS: | |
| ap.error(f"unknown tier {t}; use {', '.join(TIERS)}") | |
| return a | |
| def main(argv=None, *, opener=open_url, sleep=time.sleep) -> int: | |
| args = parse_args(argv) | |
| root = _root(args) | |
| conds = build_where(tags=args.tag or (), exts=args.ext or (), sources=args.source or (), tiers=args.tier, | |
| min_size=args.min_size, where=args.where, | |
| default=not args.no_default_filter) | |
| if args.print_sql: | |
| print(";\n".join(views_sql(root, sources=args.source or (), starter=args.starter)) + ";") | |
| print(select_sql(conds, args.limit, args.max_size, args.cap) + ";") | |
| return 0 | |
| root = pin_root(root, revision=lambda repo: repo_revision(repo, opener=opener)) | |
| con = connect(args.memory_limit, args.temp_dir, remote=is_remote(root)) | |
| for s in views_sql(root, sources=args.source or (), starter=args.starter): | |
| con.execute(s) | |
| specs = load_specs(con, root) | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| counts: dict = {} | |
| try: | |
| with open(out / MANIFEST, "w", encoding="utf-8") as man: | |
| for early, row in selected_rows(con, select_sql(conds, args.limit, args.max_size, args.cap), specs): | |
| if early is not None: | |
| res = early | |
| elif args.dry_run: | |
| res = {**_key(row), "pointer_id": row.get("pointer_id"), "status": "selected", | |
| "method": method_of(row), "size_bytes": row.get("size_bytes"), | |
| "size_cap_bytes": row.get("_size_cap")} | |
| else: | |
| res = {**_key(row), **fetch_one(row, out, timeout=args.timeout, opener=opener, sleep=sleep)} | |
| if args.decompress and res.get("status") == "ok" and res.get("path"): | |
| d = decompress_file(Path(res["path"]), row, cap_of(row)) | |
| if d is not None: | |
| res["decompress"] = d | |
| if d["status"] == "ok": | |
| res["path"] = d["path"] | |
| if args.check_content and res.get("status") == "ok" and res.get("path"): | |
| p = Path(res["path"]) | |
| ext = None if res.get("decompress", {}).get("status") == "ok" else row.get("ext") | |
| try: | |
| res["content_check"] = check_content(p, ext) | |
| except OSError as e: | |
| res["content_check"] = {"skipped": {"all": f"could not read the file: {e}"}} | |
| if row is not None and row.get("size_bytes") is None: | |
| res["size_unknown"] = True | |
| if row is not None and row.get("_nk_conflict"): | |
| res["natural_key_conflict"] = True | |
| counts[res["status"]] = counts.get(res["status"], 0) + 1 | |
| man.write(json.dumps(res, ensure_ascii=False, sort_keys=True) + "\n") | |
| finally: | |
| clear_package_cache() | |
| print(json.dumps({"manifest": str(out / MANIFEST), "counts": counts}, sort_keys=True)) | |
| return 0 if not counts.get("failed") else 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |