File size: 17,491 Bytes
63c2fe4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | #!/usr/bin/env python3
"""Download the files of a selection of pointers and verify each one.
Usage:
python fetch_selected.py SELECTION --dest files/ [--manifests manifests/]
SELECTION is a CSV, TSV, JSON Lines or Parquet file (Parquet needs pyarrow).
Each row is either a row of a catalog table (columns uri, size_bytes, sha256,
md5, alt_uris, ...) or a full pointer from a manifest (fields uri, size_bytes,
hashes, range, ...). With --manifests, rows are completed from the downloaded
manifests by pointer_id, which adds the byte ranges and every hash that the
catalog tables do not carry; a selection then needs only a pointer_id column
(source and batch columns, when present, limit which batches are read).
For every row the script downloads uri (or, if that fails, each address in
alt_uris), requests only the byte range when the pointer has range, and checks
the number of bytes against size_bytes and the content against the sha256 and
md5 of the pointer. A file is written under --dest only when every check
passes. Rows that fail are listed in the failures file with the reason and
never replace an existing file. Only the Python standard library is needed.
"""
from __future__ import annotations
import argparse
import csv
import gzip
import hashlib
import json
import os
import posixpath
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
CHUNK = 1 << 20
USER_AGENT = "fetch_selected/1.0"
RETRIES = 3
HASHES = ("sha256", "md5")
# ---------- reading the selection ----------
def _maybe_json(v):
"""Parse a JSON object or list kept as text in a CSV cell."""
if isinstance(v, str) and v[:1] in "{[":
try:
return json.loads(v)
except ValueError:
return v
return v
def _lines(text: str) -> list:
# Split on newlines only: identifiers may contain other line separators.
return [x for x in text.split("\n") if x.strip()]
def read_table(path: Path) -> list:
"""Read a selection file into a list of dicts."""
name = path.name.lower()
if name.endswith(".parquet"):
try:
import pyarrow.parquet as pq
except ImportError:
sys.exit("reading Parquet needs pyarrow: pip install pyarrow (or save the selection as CSV)")
return pq.read_table(str(path)).to_pylist()
if name.endswith((".jsonl", ".ndjson", ".jsonl.gz")):
opener = gzip.open if name.endswith(".gz") else open
with opener(path, "rt", encoding="utf-8") as f:
return [json.loads(x) for x in _lines(f.read())]
if name.endswith((".csv", ".tsv")):
with path.open(encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f, delimiter="\t" if name.endswith(".tsv") else ","))
return [{k: _maybe_json(v) for k, v in r.items()} for r in rows]
sys.exit(f"{path}: unsupported selection format (use .csv, .tsv, .jsonl or .parquet)")
def _nullable_int(v):
if v is None or v == "" or isinstance(v, bool):
return None
try:
return int(v)
except (TypeError, ValueError):
return None
def normalize(row: dict) -> dict:
"""Bring a catalog row or a manifest pointer to one shape."""
hashes = row.get("hashes")
hashes = dict(hashes) if isinstance(hashes, dict) else {}
for name in HASHES:
if row.get(name) and not hashes.get(name):
hashes[name] = row[name]
alt = row.get("alt_uris") or []
if isinstance(alt, str):
# A list written to CSV by DuckDB looks like [a, b], without quotes.
alt = [x.strip().strip("'\"") for x in alt.strip("[]").split(",")] if alt.startswith("[") else [alt]
rng = row.get("range")
if not isinstance(rng, dict):
off, length = _nullable_int(row.get("range_offset")), _nullable_int(row.get("range_length"))
rng = {"offset": off, "length": length} if off is not None and length is not None else None
access = row.get("access") if isinstance(row.get("access"), dict) else {}
needs_auth = row.get("needs_auth")
if needs_auth is None:
needs_auth = access.get("needs_auth")
has_range = row.get("has_range")
return {
"pointer_id": str(row.get("pointer_id") or ""),
"source": row.get("source") or "",
"batch": row.get("batch") or "",
"uri": row.get("uri") or "",
"alt_uris": [str(u) for u in alt if u],
"size_bytes": _nullable_int(row.get("size_bytes")),
"hashes": {k: str(v).lower() for k, v in hashes.items() if k in HASHES and v},
"hash_source": row.get("hash_source") or "",
"hash_scope": row.get("hash_scope") or "file",
"range": rng,
"has_range": has_range in (True, "true", "True", "1", 1),
"needs_auth": needs_auth,
}
def manifest_rows(root: Path, scopes: set | None):
"""Yield every pointer in the manifests under root (a manifests folder or one batch folder)."""
if (root / "collection.json").is_file():
dirs = [root]
elif scopes:
dirs = [root / s / b for s, b in sorted(scopes) if (root / s / b / "collection.json").is_file()]
else:
dirs = sorted(p.parent for p in root.rglob("collection.json"))
for d in dirs:
for part in sorted(d.glob("part-*.jsonl.gz")) + sorted(d.glob("part-*.jsonl")):
opener = gzip.open if part.name.endswith(".gz") else open
with opener(part, "rt", encoding="utf-8") as f:
for line in f.read().split("\n"):
if line.strip():
yield json.loads(line)
def complete_from_manifests(rows: list, root: Path) -> tuple:
"""Replace each selected row by its full pointer from the manifests. Returns (rows, missing ids)."""
ids = [str(r.get("pointer_id") or "") for r in rows]
if not all(ids):
sys.exit("with --manifests, every row of the selection needs a pointer_id")
want = set(ids)
scopes = None
if all(r.get("source") and r.get("batch") for r in rows):
scopes = {(str(r["source"]), str(r["batch"])) for r in rows}
found = {}
for p in manifest_rows(root, scopes):
pid = p.get("pointer_id")
if pid in want and pid not in found:
found[pid] = p
if len(found) == len(want):
break
ordered = list(dict.fromkeys(ids))
return [found[i] for i in ordered if i in found], [i for i in ordered if i not in found]
# ---------- addresses and destinations ----------
def to_http(uri: str) -> str | None:
"""Turn a pointer address into one urllib can open, or None."""
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/"):
# hf://datasets/<owner>/<name>@<revision>/<path>
owner, _, rest = uri[len("hf://datasets/"):].partition("/")
name_rev, _, path = rest.partition("/")
name, _, rev = name_rev.partition("@")
return f"https://huggingface.co/datasets/{owner}/{name}/resolve/{rev or 'main'}/{urllib.parse.quote(path)}"
return None
def addresses(row: dict) -> list:
out = []
for u in [row["uri"], *row["alt_uris"]]:
h = to_http(u)
if h and h not in out:
out.append(h)
# The generic s3 address goes last: regional buckets are reached through alt_uris.
if row["uri"].startswith("s3://") and len(out) > 1 and out[0] == to_http(row["uri"]):
out.append(out.pop(0))
return out
def destination(root: Path, row: dict) -> Path:
"""dest/<source>/<collection>/<path>, from the pointer_id <source>:<collection>:<path>."""
pid = row["pointer_id"]
parts = pid.split(":", 2)
if len(parts) == 3:
rel = "/".join(parts)
else:
rel = "/".join(x for x in (row["source"], hashlib.sha256((pid or row["uri"]).encode()).hexdigest()) if x)
rel = rel.replace("\\", "/")
clean = [p for p in posixpath.normpath(rel).split("/") if p not in ("", ".")]
if not clean or ".." in rel.split("/") or rel.startswith("/"):
raise ValueError(f"unsafe path in pointer_id: {pid!r}")
return Path(root, *clean)
# ---------- downloading and checking ----------
class Transient(Exception):
"""A network error worth retrying at the same address."""
def open_url(url: str, rng: dict | None, timeout: float):
"""Open url, or only its byte range. Returns a readable file object."""
if url.startswith("file://"):
f = open(urllib.request.url2pathname(urllib.parse.urlparse(url).path), "rb")
if rng:
f.seek(int(rng["offset"]))
return f
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
if rng:
start = int(rng["offset"])
req.add_header("Range", f"bytes={start}-{start + int(rng['length']) - 1}")
try:
resp = urllib.request.urlopen(req, timeout=timeout)
except urllib.error.HTTPError as e:
if e.code >= 500 or e.code == 429:
raise Transient(f"HTTP {e.code}") from e
raise
except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
raise Transient(str(e)) from e
if rng and resp.status != 206:
resp.close()
raise ValueError(f"the server ignored the byte range (HTTP {resp.status}, not 206)")
return resp
def check(row: dict, size: int, got: dict) -> str | None:
"""None when the download matches the pointer, else the reason it does not."""
if row["size_bytes"] is not None and size != row["size_bytes"]:
return f"size mismatch: expected {row['size_bytes']}, got {size}"
for name in HASHES:
want = row["hashes"].get(name)
if want and got[name] != want:
return f"{name} mismatch: expected {want}, got {got[name]}"
return None
def download(url: str, row: dict, part: Path, timeout: float) -> tuple:
"""Stream url into part while hashing. Returns (bytes read, digests)."""
hs = {name: hashlib.new(name) for name in HASHES}
limit = int(row["range"]["length"]) if row["range"] else None
n = 0
with open_url(url, row["range"], timeout) as src, open(part, "wb") as out:
while True:
want = CHUNK if limit is None else min(CHUNK, limit - n)
if want <= 0:
break
try:
b = src.read(want)
except (TimeoutError, ConnectionError, OSError) as e:
raise Transient(str(e)) from e
if not b:
break
out.write(b)
for h in hs.values():
h.update(b)
n += len(b)
return n, {k: h.hexdigest() for k, h in hs.items()}
def hash_file(path: Path) -> tuple:
hs = {name: hashlib.new(name) for name in HASHES}
n = 0
with open(path, "rb") as f:
for b in iter(lambda: f.read(CHUNK), b""):
for h in hs.values():
h.update(b)
n += len(b)
return n, {k: h.hexdigest() for k, h in hs.items()}
def precheck(row: dict) -> str | None:
"""Reasons a row cannot be fetched and verified by this script."""
if not row["uri"]:
return "no uri"
if row["needs_auth"] not in (None, False, "", "no", "false", "False", "unknown"):
return "the source requires a login, a guestbook or a form; follow its procedure"
if row["hash_scope"] != "file":
return f"hash_scope {row['hash_scope']} is not supported here; see retrieval.md"
if row["has_range"] and not row["range"]:
return "the pointer has a byte range that the selection does not carry; rerun with --manifests"
if not row["hashes"] and row["hash_source"] != "computed_on_fetch":
return "no sha256 or md5 to check against"
return None
def fetch_row(row: dict, dest_root: Path, timeout: float, sleep=time.sleep) -> dict:
"""Fetch and verify one row. Returns a result dict with status ok, present, unverified or failed."""
res = {"pointer_id": row["pointer_id"], "uri": row["uri"]}
why = precheck(row)
if why:
return {**res, "status": "failed", "reason": why}
try:
dest = destination(dest_root, row)
except ValueError as e:
return {**res, "status": "failed", "reason": str(e)}
res["path"] = str(dest)
if dest.exists():
size, got = hash_file(dest)
why = check(row, size, got)
if why:
return {**res, "status": "failed", "reason": f"a different file is already there, not replaced ({why})"}
return {**res, "status": "present"}
urls = addresses(row)
if not urls:
return {**res, "status": "failed", "reason": f"no downloadable address for {row['uri']}"}
dest.parent.mkdir(parents=True, exist_ok=True)
part = dest.with_name(dest.name + ".part")
errors = []
for url in urls:
for attempt in range(RETRIES + 1):
try:
size, got = download(url, row, part, timeout)
except Transient as e:
part.unlink(missing_ok=True)
if attempt < RETRIES:
sleep(2 ** attempt)
continue
errors.append(f"{url}: {e}")
break
except (urllib.error.HTTPError, ValueError, OSError) as e:
part.unlink(missing_ok=True)
errors.append(f"{url}: {e}")
break
why = check(row, size, got)
if why:
part.unlink(missing_ok=True)
errors.append(f"{url}: {why}")
break
if dest.exists():
part.unlink(missing_ok=True)
return {**res, "status": "failed", "reason": "a file appeared at the destination meanwhile, not replaced"}
os.replace(part, dest)
status = "ok" if row["hashes"] else "unverified"
out = {**res, "status": status, "url": url, "size_bytes": size}
if status == "unverified":
# The source publishes no hash: keep the one computed here with the file.
out["computed"] = got
return out
return {**res, "status": "failed", "reason": "; ".join(errors)}
def run(rows: list, dest_root: Path, failures: Path, *, timeout: float = 120, max_files: int | None = None,
max_bytes: int | None = None, missing: list = (), sleep=time.sleep) -> dict:
"""Fetch every row; write failures (and ids not found) to the failures file. Returns a summary."""
counts = {"ok": 0, "present": 0, "unverified": 0, "failed": 0, "not_found": len(missing), "over_limit": 0}
unverified = []
total = 0
failures.parent.mkdir(parents=True, exist_ok=True)
with open(failures, "w", encoding="utf-8") as fail:
for pid in missing:
fail.write(json.dumps({"pointer_id": pid, "status": "failed",
"reason": "not found in the manifests"}, ensure_ascii=False) + "\n")
fetched = 0
for raw in rows:
row = normalize(raw)
size = row["size_bytes"] or 0
if (max_files is not None and fetched >= max_files) or (max_bytes is not None and total + size > max_bytes):
counts["over_limit"] += 1
continue
r = fetch_row(row, dest_root, timeout, sleep)
counts[r["status"]] += 1
if r["status"] == "failed":
fail.write(json.dumps(r, ensure_ascii=False) + "\n")
elif r["status"] == "unverified":
unverified.append(r)
if r["status"] in ("ok", "unverified"):
fetched += 1
total += r.get("size_bytes") or 0
if unverified:
with open(dest_root / "unverified.jsonl", "a", encoding="utf-8") as f:
for r in unverified:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
return {**counts, "bytes": total, "failures_file": str(failures)}
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Download and verify the files of a selection of pointers.")
ap.add_argument("selection", type=Path, help="CSV, TSV, JSON Lines or Parquet file of selected pointers")
ap.add_argument("--dest", type=Path, required=True, help="folder to write the files under")
ap.add_argument("--manifests", type=Path, help="downloaded manifests folder, to complete rows by pointer_id")
ap.add_argument("--failures", type=Path, help="where to list failed rows (default: <dest>/failures.jsonl)")
ap.add_argument("--max-files", type=int, help="stop after this many downloaded files")
ap.add_argument("--max-bytes", type=int, help="skip files that would take the total over this many bytes")
ap.add_argument("--timeout", type=float, default=120, help="seconds to wait on a stalled connection")
a = ap.parse_args(argv)
rows = read_table(a.selection)
missing = []
if a.manifests:
rows, missing = complete_from_manifests(rows, a.manifests)
a.dest.mkdir(parents=True, exist_ok=True)
summary = run(rows, a.dest, a.failures or a.dest / "failures.jsonl", timeout=a.timeout,
max_files=a.max_files, max_bytes=a.max_bytes, missing=missing)
print(json.dumps(summary, indent=2))
return 0 if summary["failed"] == 0 and summary["not_found"] == 0 else 1
if __name__ == "__main__":
sys.exit(main())
|