Download code/scripts/range_download.py from CollinMa/nextgpt-chapter6-report: direct link, hf CLI and curl.
- Browser
- Download file 5.74 kB
-
https://huggingface.co/spaces/CollinMa/nextgpt-chapter6-report/resolve/main/code/scripts/range_download.py
- Command line
-
hf download hf://spaces/CollinMa/nextgpt-chapter6-report/code/scripts/range_download.py
-
curl -L -o range_download.py https://huggingface.co/spaces/CollinMa/nextgpt-chapter6-report/resolve/main/code/scripts/range_download.py
5.74 kB
| """Resumable parallel public downloads, with trusted SHA verification before rename.""" | |
| import concurrent.futures | |
| import hashlib | |
| import json | |
| import math | |
| import threading | |
| import time | |
| from pathlib import Path | |
| import requests | |
| LOCAL = threading.local() | |
| def session(): | |
| if not hasattr(LOCAL, "session"): | |
| LOCAL.session = requests.Session() | |
| return LOCAL.session | |
| def download(url, target, size, sha256=None, git_sha1=None, workers=24, seed_prefix=None): | |
| target = Path(target) | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| if target.is_file() and target.stat().st_size == size: | |
| verify(target, size, sha256, git_sha1) | |
| print("Verified existing " + target.name, flush=True) | |
| return | |
| parts = target.parent / (target.name + ".parts8") | |
| parts.mkdir(exist_ok=True) | |
| chunk_size = 8 * 1024 * 1024 | |
| count = math.ceil(size/chunk_size) | |
| old_parts = target.parent / (target.name + ".parts") | |
| if old_parts.is_dir(): | |
| # Reuse ranges fetched by the earlier 64 MiB layout. | |
| for old_piece in old_parts.iterdir(): | |
| if not old_piece.name.isdigit(): | |
| continue | |
| first = int(old_piece.name)*8 | |
| with old_piece.open('rb') as source: | |
| for offset in range(8): | |
| block = source.read(chunk_size) | |
| if not block: | |
| break | |
| piece = parts / f"{first+offset:06d}" | |
| if not piece.exists() or piece.stat().st_size < len(block): | |
| piece.write_bytes(block) | |
| if seed_prefix: | |
| with Path(seed_prefix).open("rb") as source: | |
| for i in range(min(count, Path(seed_prefix).stat().st_size//chunk_size)): | |
| piece = parts / f"{i:06d}" | |
| if piece.is_file() and piece.stat().st_size == chunk_size: | |
| source.seek(chunk_size, 1) | |
| else: | |
| piece.write_bytes(source.read(chunk_size)) | |
| def transfer(i): | |
| start = i*chunk_size | |
| end = min(size, start+chunk_size)-1 | |
| piece = parts / f"{i:06d}" | |
| if piece.is_file() and piece.stat().st_size == end-start+1: | |
| return i | |
| for retry in range(12): | |
| try: | |
| completed = piece.stat().st_size if piece.exists() else 0 | |
| if completed > end-start+1: | |
| completed = 0 | |
| if completed == end-start+1: | |
| return i | |
| range_start = start+completed | |
| # Anonymous request: no cached HF token is forwarded to mirrors. | |
| with session().get(url + ("&" if "?" in url else "?") + f"range_part={i}_{range_start}", | |
| headers={"Range": f"bytes={range_start}-{end}"}, stream=True, timeout=(30, 90)) as response: | |
| response.raise_for_status() | |
| expected = f"bytes {range_start}-{end}/{size}" | |
| full_response = range_start == 0 and end == size-1 and response.status_code == 200 | |
| if not full_response and (response.status_code != 206 or response.headers.get("Content-Range") != expected): | |
| raise IOError("Server returned an unexpected byte range") | |
| with piece.open("ab" if completed else "wb") as output: | |
| for block in response.iter_content(1024*1024): | |
| output.write(block) | |
| if piece.stat().st_size != end-start+1: | |
| raise IOError("Truncated byte range") | |
| print(f"{target.name}: part {i+1}/{count} complete", flush=True) | |
| return i | |
| except Exception as exc: | |
| print(f"{target.name}: retry {retry+1} part {i+1}: {type(exc).__name__}: {exc}", flush=True) | |
| if retry == 11: | |
| raise | |
| time.sleep(2) | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: | |
| list(pool.map(transfer, range(count))) | |
| partial = target.with_name(target.name + ".verified-part") | |
| with partial.open("wb") as output: | |
| for i in range(count): | |
| with (parts / f"{i:06d}").open("rb") as source: | |
| while True: | |
| block = source.read(8*1024*1024) | |
| if not block: | |
| break | |
| output.write(block) | |
| verify(partial, size, sha256, git_sha1) | |
| partial.replace(target) | |
| # Only remove exact temporary files created by this downloader. | |
| for i in range(count): | |
| piece = parts / f"{i:06d}" | |
| if piece.parent.resolve() != parts.resolve(): | |
| raise ValueError("Unexpected cleanup path") | |
| piece.unlink() | |
| parts.rmdir() | |
| if old_parts.is_dir(): | |
| for old_piece in old_parts.iterdir(): | |
| if old_piece.name.isdigit() and old_piece.is_file(): | |
| old_piece.unlink() | |
| if not any(old_parts.iterdir()): | |
| old_parts.rmdir() | |
| print("SHA verified: " + target.name, flush=True) | |
| def verify(path, size, sha256=None, git_sha1=None): | |
| if Path(path).stat().st_size != size: | |
| raise ValueError("Unexpected file size") | |
| digest = hashlib.sha256() if sha256 else hashlib.sha1() | |
| if not sha256: | |
| if not git_sha1: | |
| raise ValueError("Trusted digest is required") | |
| digest.update(f"blob {size}\0".encode()) | |
| with Path(path).open("rb") as source: | |
| while True: | |
| block = source.read(8*1024*1024) | |
| if not block: | |
| break | |
| digest.update(block) | |
| if digest.hexdigest() != (sha256 or git_sha1): | |
| raise ValueError("Digest mismatch; file was not accepted") | |