Datasets:
License:
Download scripts/download_parallel.py from Loasaster/test_1: direct link, hf CLI and curl.
- Browser
- Download file 5.16 kB
-
https://huggingface.co/datasets/Loasaster/test_1/resolve/main/scripts/download_parallel.py
- Command line
-
hf download hf://datasets/Loasaster/test_1/scripts/download_parallel.py
-
curl -L -o download_parallel.py https://huggingface.co/datasets/Loasaster/test_1/resolve/main/scripts/download_parallel.py
5.16 kB
| """Resumable range download for large pinned legacy-LFS / release assets.""" | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor,as_completed | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import threading | |
| import time | |
| from urllib.parse import quote | |
| import requests | |
| ROOT=Path(__file__).resolve().parents[1] | |
| def download(spec,workers=16,chunk_size=16*1024*1024): | |
| target=ROOT/spec['destination'];target.parent.mkdir(parents=True,exist_ok=True) | |
| def digest(p,kind='sha256'): | |
| h=hashlib.new(kind) | |
| with p.open('rb') as stream: | |
| for b in iter(lambda:stream.read(8*1024*1024),b''):h.update(b) | |
| return h.hexdigest() | |
| if target.is_file() and target.stat().st_size==spec['size']: | |
| if not spec.get('sha256') or digest(target)==spec['sha256']: | |
| print('Already verified',spec['name'],flush=True);return target | |
| url=spec.get('url') or f"https://huggingface.co/{spec['repo']}/resolve/{spec['revision']}/{quote(spec['file'],safe='/')}" | |
| guard=threading.Lock();resolved=None;resolved_at=0 | |
| def current_url(force=False): | |
| nonlocal resolved,resolved_at | |
| with guard: | |
| if not force and resolved and time.time()-resolved_at<2400:return resolved | |
| fresh=url+('&' if '?' in url else '?')+'archive_transfer='+str(int(time.time())) | |
| for attempt in range(8): | |
| try: | |
| with requests.get(fresh,headers={'Range':'bytes=0-0'},stream=True,timeout=(15,40)) as response: | |
| response.raise_for_status();value=response.url | |
| assert response.status_code==206 and response.headers.get('Content-Range','').endswith('/'+str(spec['size'])) | |
| resolved=value;resolved_at=time.time();return resolved | |
| except Exception: | |
| if attempt==7:raise | |
| time.sleep(2) | |
| current_url() | |
| directory=ROOT/'.cache/ranges'/spec['name'];directory.mkdir(parents=True,exist_ok=True) | |
| total=math.ceil(spec['size']/chunk_size);local=threading.local() | |
| def part(index): | |
| start=index*chunk_size;end=min(spec['size'],start+chunk_size)-1 | |
| path=directory/f'{index:05d}.part';size=end-start+1 | |
| if path.is_file() and path.stat().st_size==size:return path | |
| if not hasattr(local,'session'):local.session=requests.Session() | |
| for attempt in range(8): | |
| offset=path.stat().st_size if path.is_file() else 0 | |
| assert offset<=size | |
| if offset==size:return path | |
| try: | |
| begin=start+offset | |
| with local.session.get(current_url(),headers={'Range':f'bytes={begin}-{end}'},stream=True,timeout=(15,45)) as response: | |
| if response.status_code in (401,403):current_url(force=True) | |
| response.raise_for_status() | |
| assert response.status_code==206 | |
| assert response.headers['Content-Range'].startswith(f'bytes {begin}-{end}/') | |
| with path.open('ab') as file: | |
| for block in response.iter_content(65536): | |
| if block:file.write(block) | |
| assert path.stat().st_size==size | |
| return path | |
| except Exception: | |
| if attempt==7:raise | |
| time.sleep(2*(attempt+1)) | |
| with ThreadPoolExecutor(workers) as pool: | |
| futures=[pool.submit(part,index) for index in range(total)] | |
| failed=[] | |
| for n,f in enumerate(as_completed(futures),1): | |
| try:f.result() | |
| except Exception as exc: | |
| failed.append(exc) | |
| print('Part interrupted',spec['name'],type(exc).__name__,flush=True) | |
| if n==1 or n%8==0 or n==total:print(spec['name'],f'{n}/{total} chunks',flush=True) | |
| if failed:raise RuntimeError(f'{len(failed)} ranges interrupted; completed ranges are preserved for resume') | |
| temp=target.with_suffix(target.suffix+'.part') | |
| with temp.open('wb') as output: | |
| for index in range(total): | |
| with (directory/f'{index:05d}.part').open('rb') as source: | |
| for block in iter(lambda:source.read(8*1024*1024),b''):output.write(block) | |
| assert temp.stat().st_size==spec['size'] | |
| value=digest(temp) | |
| assert not spec.get('sha256') or value==spec['sha256'],(spec['name'],value) | |
| assert not spec.get('md5') or digest(temp,'md5')==spec['md5'] | |
| temp.replace(target) | |
| receipt=dict(name=spec['name'],path=str(target.relative_to(ROOT)),sha256=value,bytes=spec['size'],source=url,at=time.time()) | |
| (ROOT/'provenance'/f"{spec['name']}_DOWNLOADED.json").write_text(json.dumps(receipt,indent=2)+'\n') | |
| print('VERIFIED',spec['name'],value,flush=True) | |
| return target | |
| if __name__=='__main__': | |
| parser=argparse.ArgumentParser();parser.add_argument('names',nargs='+');parser.add_argument('--workers',type=int,default=16) | |
| args=parser.parse_args();config=json.loads((ROOT/'configs/weights.json').read_text()) | |
| specs={s['name']:s for s in config['hf']+config['http']} | |
| for name in args.names:download(specs[name],workers=args.workers) | |