mvd001's picture
download
raw
3.17 kB
#!/usr/bin/env python3
"""Code-tier downloader: resumable aria2c (8 connections) with retries, md5 check vs upstream (when given), sha256 receipt.
Appends one JSON record per file to logs/code/downloads.jsonl (merged into sources.yaml by make_code_manifest.py).
Usage: fetch.py <dataset> <version> <url> <dest_name> [--md5 X] [--license L] [--gdrive ID] [--tries N]"""
import argparse, datetime, hashlib, json, os, subprocess, sys, time
ROOT = "/workspace/security-dataset"
IST = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
LOG = f"{ROOT}/logs/code/downloads.jsonl"
def hfile(p, algo):
h = hashlib.new(algo)
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 22), b""): h.update(b)
return h.hexdigest()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dataset"); ap.add_argument("version"); ap.add_argument("url"); ap.add_argument("dest_name")
ap.add_argument("--md5"); ap.add_argument("--license", default=""); ap.add_argument("--gdrive")
ap.add_argument("--tries", type=int, default=4)
a = ap.parse_args()
d = f"{ROOT}/raw/code/{a.dataset}/{a.version}"; os.makedirs(d, exist_ok=True)
dest = f"{d}/{a.dest_name}"; ok = dest + ".ok.json"
if os.path.exists(ok): print("[skip]", dest); print(open(ok).read()); return 0
err = None
for t in range(1, a.tries + 1):
try:
if a.gdrive:
import gdown
r = gdown.download(id=a.gdrive, output=dest + ".part", quiet=False, resume=True)
if not r: raise RuntimeError("gdown returned None (quota / permission?)")
else:
subprocess.run(["aria2c", "-x", "8", "-s", "8", "-k", "20M", "--file-allocation=none", "--summary-interval=60",
"--console-log-level=warn", "--max-tries=5", "--retry-wait=10", "-c",
"-U", "security-dataset-builder/0.2 (personal research)", "-d", d, "-o", a.dest_name + ".part", a.url], check=True)
if a.md5:
got = hfile(dest + ".part", "md5")
if got != a.md5: os.remove(dest + ".part"); raise RuntimeError(f"md5 mismatch {got} != {a.md5}")
os.replace(dest + ".part", dest); err = None; break
except Exception as e:
err = f"attempt {t}: {type(e).__name__}: {e}"; print(err, file=sys.stderr, flush=True); time.sleep(20 * t)
if err:
rec = dict(dataset=a.dataset, version=a.version, url=a.url, status="failed", error=err, at=datetime.datetime.now(IST).isoformat())
open(LOG, "a").write(json.dumps(rec) + "\n"); print(json.dumps(rec)); return 2
rec = dict(dataset=a.dataset, version=a.version, url=a.url, gdrive_id=a.gdrive, path=os.path.relpath(dest, ROOT), size_bytes=os.path.getsize(dest),
sha256=hfile(dest, "sha256"), md5_upstream=a.md5, md5_verified=bool(a.md5), license=a.license, status="ok",
downloaded_ist=datetime.datetime.now(IST).strftime("%Y-%m-%d %H:%M IST"))
open(LOG, "a").write(json.dumps(rec) + "\n"); json.dump(rec, open(ok, "w")); print(json.dumps(rec)); return 0
if __name__ == "__main__": sys.exit(main())

Xet Storage Details

Size:
3.17 kB
·
Xet hash:
abc2a8eb86a555ac8e01b521c07adae9da02bd96d7213d1dfbb52b1e05182b76

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.