Datasets:
Download pipeline/streaming.py from faraway00/StyleEdit: direct link, hf CLI and curl.
- Browser
- Download file 8.44 kB
-
https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/streaming.py
- Command line
-
hf download hf://datasets/faraway00/StyleEdit/pipeline/streaming.py
-
curl -L -o streaming.py https://huggingface.co/datasets/faraway00/StyleEdit/resolve/main/pipeline/streaming.py
8.44 kB
| """Bounded HTTP ranges. Split gzip is concatenated logically, never on disk.""" | |
| import io,threading,time,collections,concurrent.futures,sqlite3,tarfile,zlib,functools | |
| from common import * | |
| import requests | |
| SPLIT=21474836480 | |
| def http_get_range(category,start,length): | |
| from huggingface_hub import get_token | |
| blocks=[];pos=start;remaining=length | |
| while remaining: | |
| part=pos//SPLIT+1;within=pos%SPLIT;n=min(remaining,SPLIT-within) | |
| url=f'https://huggingface.co/datasets/{REPO}/resolve/{REV}/videos/{category}/{category}.tar.gz.{part:02d}' | |
| for attempt in range(5): | |
| try: | |
| token=get_token();headers={'User-Agent':'StyleEdit/1.0','Range':f'bytes={within}-{within+n-1}'} | |
| if token:headers['Authorization']='Bearer '+token | |
| r=requests.get(url,params={'styleedit_range':f'{within}-{within+n-1}'},headers=headers,timeout=(30,180)) | |
| r.raise_for_status() | |
| if r.status_code!=206 or r.headers.get('Content-Range','').split('/')[0]!=f'bytes {within}-{within+n-1}':raise ValueError('Server ignored/mismatched Range') | |
| if len(r.content)!=n:raise EOFError('Incomplete range') | |
| blocks.append(r.content);break | |
| except Exception: | |
| if attempt==4:raise | |
| time.sleep(min(16,2**attempt)) | |
| remaining-=n;pos+=n | |
| return b''.join(blocks) | |
| def get_range(category,start,length): | |
| from archive_cache import cached_range | |
| cached=cached_range(category,start,length) | |
| return cached if cached is not None else http_get_range(category,start,length) | |
| class Remote(io.RawIOBase): | |
| """2 cached 8MiB blocks + 1 asynchronous prefetch. Fresh ranges on retries.""" | |
| def __init__(self,category,size,block=8*1024**2): | |
| super().__init__();self.category=category;self.size=size;self.block=block;self.pos=0;self.cache=collections.OrderedDict();self.pool=concurrent.futures.ThreadPoolExecutor(1);self.prefetch=None;self.downloaded=0 | |
| def readable(self):return True | |
| def seekable(self):return True | |
| def tell(self):return self.pos | |
| def seek(self,offset,whence=0): | |
| self.pos=offset if whence==0 else self.pos+offset if whence==1 else self.size+offset | |
| if self.pos<0:raise ValueError('negative seek') | |
| return self.pos | |
| def readinto(self,b): | |
| x=self.read(len(b));b[:len(x)]=x;return len(x) | |
| def read(self,n=-1): | |
| if n<0:raise ValueError('Unbounded remote read forbidden') | |
| n=min(n,max(0,self.size-self.pos));out=[] | |
| while n: | |
| key=self.pos//self.block*self.block | |
| if key not in self.cache: | |
| if self.prefetch and self.prefetch[0]==key:data=self.prefetch[1].result();self.prefetch=None | |
| else:data=get_range(self.category,key,min(self.block,self.size-key)) | |
| self.downloaded+=len(data);self.cache[key]=data | |
| while len(self.cache)>2:self.cache.popitem(last=False) | |
| data=self.cache[key];j=self.pos-key;take=min(n,len(data)-j);out.append(data[j:j+take]);self.pos+=take;n-=take | |
| nxt=key+self.block | |
| if nxt<self.size and nxt not in self.cache and (self.prefetch is None or self.prefetch[0]!=nxt): | |
| self.prefetch=(nxt,self.pool.submit(get_range,self.category,nxt,min(self.block,self.size-nxt))) | |
| return b''.join(out) | |
| def close(self): | |
| self.pool.shutdown(wait=True,cancel_futures=True);super().close() | |
| def archive_sizes(): | |
| from huggingface_hub import HfApi | |
| info=HfApi().dataset_info(REPO,revision=REV,files_metadata=True) | |
| return {c:sum(f.size for f in info.siblings if f.rfilename.startswith('videos/'+c+'/')) for c in ['source','global_style1','global_style2']} | |
| def seed_download(locator,targets): | |
| """Pilot ONLY: checksum-proven ranges from previous inventory, fresh HF reads.""" | |
| category=locator['category'];start=locator['start'];length=locator['length'];t=time.monotonic();found=set();downloaded=0 | |
| if locator['kind']=='sync': | |
| from archive_ranges import decode,members | |
| data=get_range(category,start,length);downloaded=len(data) | |
| for name,body in members(decode(data)): | |
| if name in targets: | |
| for path in targets[name]:Path(path).parent.mkdir(parents=True,exist_ok=True);Path(path).write_bytes(body) | |
| found.add(name) | |
| else: | |
| remote=Remote(category,length) | |
| try: | |
| with tarfile.open(fileobj=remote,mode='r|gz') as tar: | |
| for m in tar: | |
| name=m.name.removeprefix('./') | |
| if name not in targets:continue | |
| if not m.isfile() or not 0<m.size<200*1024**2:raise ValueError('Invalid member') | |
| body=tar.extractfile(m).read() | |
| if len(body)!=m.size:raise EOFError(name) | |
| for path in targets[name]:Path(path).parent.mkdir(parents=True,exist_ok=True);Path(path).write_bytes(body) | |
| found.add(name) | |
| if len(found)==len(targets):break | |
| finally:downloaded=remote.downloaded;remote.close() | |
| if found!=set(targets):raise ValueError('Requested members absent/incomplete: '+str(set(targets)-found)) | |
| return {'category':category,'range_start':start,'requested_bytes':length,'downloaded_bytes':downloaded,'seconds':time.monotonic()-t,'members':len(found)} | |
| def build_index(category,state): | |
| """Exact gzip seek index and tar catalogue. No recovered/approximate decoding. | |
| Initial scan costs archive bandwidth, not archive disk capacity. Checkpoints can | |
| resume at a complete member boundary; emitted catalogue rows are transactional. | |
| """ | |
| import indexed_gzip | |
| state=Path(state);state.mkdir(parents=True,exist_ok=True);db=sqlite3.connect(state/'catalog.sqlite');db.execute('PRAGMA journal_mode=WAL') | |
| db.execute('CREATE TABLE IF NOT EXISTS members(category TEXT,name TEXT,offset INTEGER,size INTEGER,PRIMARY KEY(category,name))');db.execute('CREATE TABLE IF NOT EXISTS checkpoints(category TEXT PRIMARY KEY,offset INTEGER,complete INTEGER)');db.commit() | |
| row=db.execute('SELECT offset,complete FROM checkpoints WHERE category=?',(category,)).fetchone() | |
| if row and row[1]:print('INDEX_ALREADY_COMPLETE',category,flush=True);return | |
| sizes=archive_sizes();remote=Remote(category,sizes[category]);idx=state/(category+'.gzidx');temp=state/(category+'.gzidx.tmp');checkpoint=state/(category+'.checkpoint.json') | |
| gzip=indexed_gzip.IndexedGzipFile(fileobj=remote,spacing=32*1024**2,readbuf_size=1024**2) | |
| # SQLite is authoritative. Index is exported BEFORE checkpoint commits; an index | |
| # ahead of the DB is safe, the opposite ordering would not be resumable. | |
| offset=row[0] if row else 0 | |
| if idx.exists():gzip.import_index(filename=str(idx)) | |
| elif offset:raise RuntimeError('Checkpoint without gzip index') | |
| gzip.seek(offset);last=offset;lastsave=time.monotonic();count=0 | |
| def save(at,complete=False): | |
| gzip.export_index(filename=str(temp));os.replace(temp,idx) | |
| db.execute('INSERT OR REPLACE INTO checkpoints VALUES(?,?,?)',(category,at,int(complete)));db.commit() | |
| atomic(checkpoint,{'category':category,'source_revision':REV,'uncompressed_offset':at,'members_this_session':count,'compressed_download_bytes':remote.downloaded,'complete':complete}) | |
| try: | |
| # Stream forward once. Random tar seeks repeatedly replay gzip dictionaries. | |
| # Stream TarInfo offsets start at zero even when gzip resumes mid-archive. | |
| tar=tarfile.open(fileobj=gzip,mode='r|') | |
| while True: | |
| m=tar.next() | |
| if m is None:break | |
| name=m.name.removeprefix('./') | |
| if m.isfile() and name.endswith('.mp4') and 0<m.size<200*1024**2: | |
| db.execute('INSERT OR IGNORE INTO members VALUES(?,?,?,?)',(category,name,offset+m.offset_data,m.size));count+=1 | |
| last=offset+tar.offset | |
| if time.monotonic()-lastsave>60: | |
| save(last);lastsave=time.monotonic();print('INDEX_PROGRESS',category,count,last,remote.downloaded,flush=True) | |
| # Finish the gzip stream to check the CRC, with bounded buffers. | |
| while gzip.read(8*1024**2):pass | |
| save(last,True) | |
| finally:gzip.close();remote.close();db.close() | |
| def indexed_download(row,side,destination,state): | |
| import indexed_gzip | |
| category=row[side+'_path'].split('/')[0] | |
| state=Path(state) | |
| if (state/category/'catalog.sqlite').exists():state=state/category | |
| db=sqlite3.connect(f'file:{state}/catalog.sqlite?mode=ro',uri=True,timeout=30) | |
| match=db.execute('SELECT offset,size FROM members WHERE category=? AND name=?',(category,row[side+'_path'])).fetchone();db.close() | |
| if not match:raise LookupError('Member not indexed: '+row[side+'_path']) | |
| remote=Remote(category,archive_sizes()[category]);gz=indexed_gzip.IndexedGzipFile(fileobj=remote,spacing=32*1024**2,index_file=str(state/(category+'.gzidx'))) | |
| try: | |
| gz.seek(match[0]);data=gz.read(match[1]) | |
| if len(data)!=match[1]:raise EOFError('Partial indexed member') | |
| Path(destination).write_bytes(data) | |
| finally:gz.close();remote.close() | |
| return {'downloaded_bytes':remote.downloaded,'member_bytes':len(data)} | |