Download parallel_resume_get.py from hk239/VISOR: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/datasets/hk239/VISOR/resolve/main/parallel_resume_get.py
- Command line
-
hf download hf://datasets/hk239/VISOR/parallel_resume_get.py
-
curl -L -o parallel_resume_get.py https://huggingface.co/datasets/hk239/VISOR/resolve/main/parallel_resume_get.py
8.41 kB
| #!/usr/bin/env python3 | |
| """Multi-connection HTTP Range download with resume (sidecar progress file).""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import sys | |
| import threading | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| URL = os.environ.get( | |
| "DL_URL", | |
| "https://data.bris.ac.uk/datasets/tar/2v6cgv1x04ol22qp9rm9x2j6a7.zip", | |
| ) | |
| DEST = os.environ.get( | |
| "DL_DEST", | |
| os.path.join(os.path.dirname(os.path.abspath(__file__)), "2v6cgv1x04ol22qp9rm9x2j6a7.zip"), | |
| ) | |
| WORKERS = int(os.environ.get("DL_WORKERS", "16")) | |
| CHUNK = int(os.environ.get("DL_CHUNK", str(32 * 1024 * 1024))) | |
| PROGRESS_PATH = DEST + ".progress.json" | |
| LOCK_PATH = DEST + ".lock" | |
| print_lock = threading.Lock() | |
| progress_lock = threading.Lock() | |
| bytes_lock = threading.Lock() | |
| session_bytes = 0 | |
| def log(msg: str) -> None: | |
| with print_lock: | |
| print(msg, flush=True) | |
| def head_length(url: str) -> int: | |
| req = urllib.request.Request(url, method="HEAD") | |
| with urllib.request.urlopen(req, timeout=60) as resp: | |
| length = resp.headers.get("Content-Length") | |
| accept = resp.headers.get("Accept-Ranges", "") | |
| if "bytes" not in accept.lower(): | |
| log(f"WARN Accept-Ranges={accept!r}") | |
| if not length: | |
| raise SystemExit("no Content-Length") | |
| return int(length) | |
| def load_progress(total: int, dest_size: int) -> list[list[int]]: | |
| if os.path.exists(PROGRESS_PATH): | |
| with open(PROGRESS_PATH) as f: | |
| data = json.load(f) | |
| if data.get("url") == URL and data.get("total") == total: | |
| return merge_intervals(data.get("completed") or []) | |
| if 0 < dest_size < total: | |
| return [[0, dest_size]] | |
| return [] | |
| def save_progress(total: int, completed: list[list[int]]) -> None: | |
| tmp = PROGRESS_PATH + ".tmp" | |
| payload = {"url": URL, "total": total, "completed": merge_intervals(completed)} | |
| with open(tmp, "w") as f: | |
| json.dump(payload, f) | |
| os.replace(tmp, PROGRESS_PATH) | |
| def merge_intervals(intervals: list[list[int]]) -> list[list[int]]: | |
| if not intervals: | |
| return [] | |
| items = sorted((int(a), int(b)) for a, b in intervals if b > a) | |
| out = [list(items[0])] | |
| for a, b in items[1:]: | |
| if a <= out[-1][1]: | |
| out[-1][1] = max(out[-1][1], b) | |
| else: | |
| out.append([a, b]) | |
| return out | |
| def gaps(total: int, completed: list[list[int]]) -> list[tuple[int, int]]: | |
| done = merge_intervals(completed) | |
| pos = 0 | |
| missing: list[tuple[int, int]] = [] | |
| for a, b in done: | |
| if pos < a: | |
| missing.append((pos, a)) | |
| pos = max(pos, b) | |
| if pos < total: | |
| missing.append((pos, total)) | |
| return missing | |
| def split_gaps(missing: list[tuple[int, int]], chunk: int) -> list[tuple[int, int]]: | |
| tasks = [] | |
| for a, b in missing: | |
| s = a | |
| while s < b: | |
| e = min(s + chunk, b) | |
| tasks.append((s, e)) | |
| s = e | |
| return tasks | |
| def fetch_range(url: str, start: int, end: int, fd: int, retries: int = 8) -> int: | |
| """Download [start, end) into fd. Returns bytes written.""" | |
| last_err: Exception | None = None | |
| for attempt in range(retries): | |
| written = 0 | |
| offset = start | |
| try: | |
| req = urllib.request.Request( | |
| url, | |
| headers={ | |
| "Range": f"bytes={start}-{end - 1}", | |
| "User-Agent": "parallel-resume-get/1.0", | |
| }, | |
| ) | |
| with urllib.request.urlopen(req, timeout=120) as resp: | |
| if resp.status not in (200, 206): | |
| raise RuntimeError(f"HTTP {resp.status}") | |
| while offset < end: | |
| want = min(1024 * 1024, end - offset) | |
| buf = resp.read(want) | |
| if not buf: | |
| raise RuntimeError(f"short read at {offset}") | |
| os.pwrite(fd, buf, offset) | |
| n = len(buf) | |
| offset += n | |
| written += n | |
| with bytes_lock: | |
| global session_bytes | |
| session_bytes += n | |
| if offset != end: | |
| raise RuntimeError(f"incomplete {offset} != {end}") | |
| return written | |
| except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc: | |
| last_err = exc | |
| time.sleep(min(2 ** attempt, 30)) | |
| raise RuntimeError(f"range {start}-{end} failed: {last_err}") | |
| def main() -> int: | |
| if os.path.exists(LOCK_PATH): | |
| try: | |
| with open(LOCK_PATH) as f: | |
| old = int(f.read().strip() or "0") | |
| os.kill(old, 0) | |
| log(f"another downloader is running (pid {old})") | |
| return 1 | |
| except (OSError, ValueError): | |
| pass | |
| with open(LOCK_PATH, "w") as f: | |
| f.write(str(os.getpid())) | |
| try: | |
| total = head_length(URL) | |
| dest_size = os.path.getsize(DEST) if os.path.exists(DEST) else 0 | |
| completed = load_progress(total, dest_size) | |
| log(f"url={URL}") | |
| log(f"dest={DEST}") | |
| log(f"total={total} ({total / 1024**3:.2f} GiB) workers={WORKERS} chunk={CHUNK}") | |
| log(f"already={sum(b - a for a, b in completed)} bytes in {len(completed)} interval(s)") | |
| flags = os.O_RDWR | os.O_CREAT | |
| fd = os.open(DEST, flags, 0o644) | |
| try: | |
| if dest_size != total: | |
| os.ftruncate(fd, total) | |
| tasks = split_gaps(gaps(total, completed), CHUNK) | |
| if not tasks: | |
| log("nothing to download") | |
| return 0 | |
| log(f"tasks={len(tasks)} remaining={sum(e - s for s, e in tasks)}") | |
| t0 = time.time() | |
| done_tasks = 0 | |
| def worker(se: tuple[int, int]) -> tuple[int, int]: | |
| s, e = se | |
| fetch_range(URL, s, e, fd) | |
| with progress_lock: | |
| completed.append([s, e]) | |
| save_progress(total, completed) | |
| return s, e | |
| with ThreadPoolExecutor(max_workers=WORKERS) as pool: | |
| futs = [pool.submit(worker, se) for se in tasks] | |
| last_report = t0 | |
| last_bytes = 0 | |
| pending = set(futs) | |
| while pending: | |
| finished = [] | |
| for fut in list(pending): | |
| if fut.done(): | |
| finished.append(fut) | |
| pending.remove(fut) | |
| for fut in finished: | |
| fut.result() | |
| done_tasks += 1 | |
| now = time.time() | |
| if now - last_report >= 5 or not pending: | |
| with bytes_lock: | |
| cur = session_bytes | |
| dt = now - last_report | |
| inst = (cur - last_bytes) / dt if dt > 0 else 0 | |
| avg = cur / (now - t0) if now > t0 else 0 | |
| remain = sum(e - s for s, e in tasks) - cur | |
| eta = remain / inst if inst > 0 else float("inf") | |
| log( | |
| f"chunks {done_tasks}/{len(tasks)} " | |
| f"+{cur / 1024**3:.2f} GiB this run " | |
| f"{inst / 1024**2:.2f} MiB/s inst " | |
| f"{avg / 1024**2:.2f} MiB/s avg " | |
| f"eta {eta / 60:.1f} min" | |
| ) | |
| last_report = now | |
| last_bytes = cur | |
| if pending: | |
| time.sleep(0.4) | |
| finally: | |
| os.close(fd) | |
| final = merge_intervals(completed) | |
| if gaps(total, final): | |
| log(f"INCOMPLETE gaps={gaps(total, final)[:5]}") | |
| return 1 | |
| size = os.path.getsize(DEST) | |
| if size != total: | |
| log(f"size mismatch {size} != {total}") | |
| return 1 | |
| log(f"DONE {DEST} size={size}") | |
| try: | |
| os.remove(PROGRESS_PATH) | |
| except OSError: | |
| pass | |
| return 0 | |
| finally: | |
| try: | |
| os.remove(LOCK_PATH) | |
| except OSError: | |
| pass | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |