next-gpt-lite / tools /fetch.py
setariaa's picture
Code + report (attempt 1)
0b0e1c1 verified
Raw History Blame Contribute Delete
3.64 kB
"""Parallel, resumable HTTP downloader for hf-mirror / pytorch index."""
import concurrent.futures as cf
import os
import pathlib
import threading
import time
import urllib.request
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) nlp-course/1.0"
def _head(url, retries=6):
"""Content-Length via HEAD, falling back to a one-byte ranged GET.
Some mirrors answer HEAD on LFS objects slowly or not at all, while ranged GET works.
The network here resets connections intermittently, so both probes are retried.
"""
for i in range(retries):
try:
req = urllib.request.Request(url, headers={"User-Agent": UA}, method="HEAD")
with urllib.request.urlopen(req, timeout=25) as r:
size = int(r.headers.get("Content-Length") or 0)
if size:
return size, r.headers.get("Accept-Ranges", "")
except Exception:
pass
try:
req = urllib.request.Request(url, headers={"User-Agent": UA, "Range": "bytes=0-0"})
with urllib.request.urlopen(req, timeout=25) as r:
cr = r.headers.get("Content-Range") or ""
if "/" in cr:
return int(cr.rsplit("/", 1)[1]), "bytes"
except Exception:
time.sleep(2 + 2 * i)
return 0, ""
def _fetch_range(url, start, end, path, idx, retries=4):
for attempt in range(retries):
try:
req = urllib.request.Request(url, headers={"User-Agent": UA, "Range": f"bytes={start}-{end}"})
with urllib.request.urlopen(req, timeout=120) as r, open(path, "r+b") as f:
f.seek(start)
while True:
chunk = r.read(1 << 20)
if not chunk:
break
f.write(chunk)
return True
except Exception:
time.sleep(1.5 * (attempt + 1))
return False
def download(url, dest, threads=8, min_chunk=4 << 20, log=print, attempts=3):
dest = pathlib.Path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
last = None
for attempt in range(attempts):
try:
return _download_once(url, dest, threads, min_chunk, log)
except Exception as e: # network reset: back off and retry
last = e
log(f"retry {attempt+1}/{attempts} {dest.name}: {type(e).__name__} {e}")
time.sleep(5 * (attempt + 1))
raise RuntimeError(f"download failed: {url}") from last
def _download_once(url, dest, threads, min_chunk, log):
size, accept = _head(url)
if size == 0:
raise RuntimeError(f"HEAD failed: {url}")
if dest.exists() and dest.stat().st_size == size:
log(f"skip {dest.name} ({size/1e6:.1f}MB)")
return dest
tmp = dest.with_suffix(dest.suffix + ".part")
with open(tmp, "wb") as f:
f.truncate(size)
n = max(1, min(threads, size // min_chunk + 1))
step = size // n
ranges = [(i * step, (size - 1) if i == n - 1 else (i + 1) * step - 1) for i in range(n)]
t0 = time.time()
ok = True
with cf.ThreadPoolExecutor(max_workers=n) as ex:
futs = [ex.submit(_fetch_range, url, a, b, str(tmp), i) for i, (a, b) in enumerate(ranges)]
for fu in cf.as_completed(futs):
ok = ok and fu.result()
if not ok:
raise RuntimeError(f"download failed: {url}")
os.replace(tmp, dest)
log(f"ok {dest.name} {size/1e6:.1f}MB in {time.time()-t0:.1f}s ({size/1e6/max(0.1,time.time()-t0):.2f}MB/s)")
return dest
if __name__ == "__main__":
import sys
download(sys.argv[1], sys.argv[2])