Datasets:
License:
File size: 6,365 Bytes
1a258c9 72e760c 1a258c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | """Download real inference assets, verify content, and retain a resumable receipt."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import shutil
import tarfile
import threading
import time
import gdown
from huggingface_hub import HfApi, hf_hub_download
import requests
ROOT=Path(__file__).resolve().parents[1]
CACHE=ROOT/'.cache/downloads'
SPEC=json.loads((ROOT/'configs/weights.json').read_text())
LOCK=threading.Lock()
RECORD=ROOT/'manifests/WEIGHTS_DOWNLOADED.json'
STATE=json.loads(RECORD.read_text()) if RECORD.is_file() else {'files':{},'errors':[]}
def sha(path, algorithm='sha256'):
h=hashlib.new(algorithm)
with Path(path).open('rb') as f:
for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
return h.hexdigest()
def register(path,source,expected=None):
digest=sha(path)
assert not expected or digest==expected,(str(path),digest,expected)
row=dict(sha256=digest,bytes=path.stat().st_size,source=source,verified_at=time.time())
with LOCK:
STATE['files'][str(path.relative_to(ROOT))]=row
tmp=RECORD.with_suffix('.tmp')
tmp.write_text(json.dumps(STATE,indent=2)+'\n');tmp.replace(RECORD)
print('VERIFIED',str(path.relative_to(ROOT)),row['bytes'],flush=True)
return row
def hf_one(spec):
target=ROOT/spec['destination'];target.parent.mkdir(parents=True,exist_ok=True)
if target.is_file() and target.stat().st_size==spec.get('size',target.stat().st_size):
try:return register(target,dict(provider='hf',**spec),spec.get('sha256'))
except AssertionError:pass
source=Path(hf_hub_download(spec['repo'],spec['file'],revision=spec['revision'],
local_dir=CACHE/'hf'/spec['repo'].replace('/','__')))
assert 'size' not in spec or source.stat().st_size==spec['size']
if spec.get('sha256'):assert sha(source)==spec['sha256'],spec['name']
shutil.move(str(source),str(target))
return register(target,dict(provider='hf',**spec),spec.get('sha256'))
def http_one(spec):
target=ROOT/spec['destination'];target.parent.mkdir(parents=True,exist_ok=True)
if target.is_file():
try:
assert 'size' not in spec or target.stat().st_size==spec['size']
if spec.get('md5'):assert sha(target,'md5')==spec['md5']
return register(target,dict(provider='http',**spec),spec.get('sha256'))
except AssertionError:pass
temp=target.with_suffix(target.suffix+'.part')
start=temp.stat().st_size if temp.is_file() else 0
headers={'Range':f'bytes={start}-'} if start else {}
with requests.get(spec['url'],headers=headers,stream=True,timeout=(20,120)) as response:
response.raise_for_status()
if start and response.status_code!=206:start=0
with temp.open('ab' if start else 'wb') as file:
for block in response.iter_content(8*1024*1024):
if block:file.write(block)
assert 'size' not in spec or temp.stat().st_size==spec['size'],spec['name']
if spec.get('md5'):assert sha(temp,'md5')==spec['md5']
if spec.get('sha256'):assert sha(temp)==spec['sha256']
temp.replace(target)
return register(target,dict(provider='http',**spec),spec.get('sha256'))
def shared_wav():
s=SPEC['shared_wav2vec']
for name in s['files']:
hf_one(dict(name='wav2vec_'+name,repo=s['repo'],revision=s['revision'],file=name,
destination=s['destination']+'/'+name))
def trevor():
spec=SPEC['l2l_trevor'];CACHE.mkdir(parents=True,exist_ok=True)
tar=CACHE/'trevor_models.tar'
if not tar.is_file() or sha(tar)!=spec['archive_sha256']:
errors=[]
for identifier in spec['google_drive_ids']:
try:
result=gdown.download(id=identifier,output=str(tar),quiet=False,use_cookies=False,resume=True)
assert result and tar.stat().st_size==spec['size']
assert sha(tar)==spec['archive_sha256']
break
except Exception as exc:errors.append(str(exc))
else:raise RuntimeError('Trevor author download failed: '+'; '.join(errors))
dest=ROOT/spec['destination'];dest.mkdir(parents=True,exist_ok=True)
with tarfile.open(tar) as archive:
for member in archive.getmembers():
if not member.isfile() or not member.name.endswith(('.pth','.npz','.json')):continue
relative=Path(member.name)
# The original archive paths start at the author src/ root.
if relative.parts[0] in ['src','trevor_models']:
relative=Path(*relative.parts[1:])
out=dest/relative
assert out.resolve().is_relative_to(dest.resolve()),member.name
out.parent.mkdir(parents=True,exist_ok=True)
with archive.extractfile(member) as source,out.open('wb') as target:shutil.copyfileobj(source,target)
register(out,dict(provider='author-google-drive',archive_sha256=spec['archive_sha256'],member=member.name))
predictor=list(dest.rglob('trevor_delta_v6_er2er_best.pth'))
codebook=list(dest.rglob('trevor_er2er_best.pth'))
assert len(predictor)==len(codebook)==1
assert sha(predictor[0])==spec['predictor_sha256']
assert sha(codebook[0])==spec['codebook_sha256']
def run_job(fn,arg=None):
name=arg['name'] if arg else fn.__name__
for attempt in range(3):
try:
fn(arg) if arg else fn()
return
except Exception as exc:
print('RETRY',name,attempt+1,type(exc).__name__,str(exc)[:300],flush=True)
time.sleep(3*(attempt+1))
error=str(exc)
with LOCK:
STATE['errors'].append(dict(job=name,error=error))
RECORD.write_text(json.dumps(STATE,indent=2)+'\n')
raise RuntimeError(name+' could not be downloaded')
if __name__=='__main__':
CACHE.mkdir(parents=True,exist_ok=True)
jobs=[(hf_one,s) for s in SPEC['hf']]+[(http_one,s) for s in SPEC['http'] if not s.get('optional')]
jobs += [(shared_wav,None),(trevor,None)]
with ThreadPoolExecutor(5) as pool:
results=[pool.submit(run_job,fn,arg) for fn,arg in jobs]
errors=[]
for future in results:
try:future.result()
except Exception as exc:errors.append(str(exc))
if errors:raise SystemExit('; '.join(errors))
|