test_1 / scripts /fetch_weights.py
Loasaster's picture
Prepare ViCo test43 inference code and verified baseline assets
72e760c verified
Raw History Blame Contribute Delete
6.37 kB
"""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))