"""Bounded, resumable upload of the inventoried old-256 data. Only reads the source training machine; each object is archived locally and deleted locally only after an HF commit with matching size and SHA-256. Never marks the dataset fully ready: indirect dependencies and complete groups still need independent validation. Stops at first error or the 24-hour boundary. """ import hashlib import json import os import pathlib import re import shlex import subprocess import time ROOT = pathlib.Path(__file__).resolve().parent INV = json.loads((ROOT/'evidence/all_old256_inventory.json').read_text()) STAGE = ROOT/'data_staging'; STAGE.mkdir(exist_ok=True) EVENTS = STAGE/'upload_queue_events.jsonl' STATUS = STAGE/'upload_queue_status.json' REPO = 'FrontRear/VideoObjectMover' REMOTE_ROOT = '/root/autodl-tmp/LampEditTraining/data_v2' PREFIX = 'releases/old256-v001/shards/' DEADLINE = time.time()+24*3600 os.environ['HF_HUB_DISABLE_PROGRESS_BARS'] = '1' os.environ['HF_XET_CACHE'] = str(STAGE/'xet_cache') os.environ['HF_XET_CHUNK_CACHE_SIZE_BYTES'] = '0' def state(stage, **values): p = STATUS.with_suffix('.tmp') p.write_text(json.dumps({'time':time.time(),'stage':stage,**values},ensure_ascii=False,indent=2)+'\n') os.replace(p,STATUS) def chunks(items, size): for n in range(0,len(items),size): yield n//size, items[n:n+size] def valid(path): p = pathlib.PurePosixPath(path) return not p.is_absolute() and all(x not in ('','..') for x in p.parts) def sha(path): h = hashlib.sha256() with path.open('rb') as f: for block in iter(lambda:f.read(8*1024*1024),b''): h.update(block) return h.hexdigest() def tasks(): meta = ['train_manifest.mixed256.json','train_manifest.new118.json','READINESS.json', 'bbox_conditions_v003_20261021/INDEX.json', 'bbox_conditions_v003_20261021/CURRENT_LOADER.json', 'bbox_conditions_v003_20261021/code'] yield 'metadata-00000',meta for n, xs in chunks(INV['bbox_group_paths'],20): yield 'bbox-groups-%05d'%n, xs for n, xs in chunks(INV['bbox_asset_ids'],4): assert all(re.fullmatch(r'[0-9a-f]{32}',x) for x in xs) yield 'bbox-assets-%05d'%n, ['bbox_conditions_v003_20261021/assets/'+x for x in xs] # The preceding separate first-shard job owns data-assets-00000. for n, xs in chunks(INV['data_asset_ids'],100): if n==0: continue assert all(re.fullmatch(r'[0-9a-f]{32}',x) for x in xs) yield 'data-assets-%05d'%n, ['assets/'+x for x in xs] def run(): state('waiting_for_first_shard') first = STAGE/'data-assets-00000.receipt.json' limit = min(DEADLINE,time.time()+3600) while not first.exists() and time.time()=DEADLINE: state('time_limit',completed=completed,total=len(queue)); return assert paths and all(valid(p) for p in paths) part = STAGE/(shard+'.tar.partial'); archive = STAGE/(shard+'.tar') if part.exists() or archive.exists(): raise RuntimeError('Existing local partial/archive requires inspection: '+shard) cmd = ('nice -n 19 ionice -c 3 tar --dereference -C '+shlex.quote(REMOTE_ROOT) +' -cf - -- '+' '.join(shlex.quote(p) for p in paths)) state('archiving',shard=shard,completed=completed,total=len(queue)) with part.open('xb') as f: p=subprocess.run(['ssh','-o','BatchMode=yes','6000D',cmd],stdout=f, stderr=subprocess.PIPE,timeout=3600) if p.returncode: raise RuntimeError('Archive failed; retained partial: '+p.stderr.decode(errors='replace')[-2000:]) part.rename(archive); size=archive.stat().st_size; checksum=sha(archive) name=PREFIX+shard+'.tar' state('uploading',shard=shard,bytes=size,completed=completed,total=len(queue)) commit=api.upload_file(repo_id=REPO,repo_type='dataset',path_or_fileobj=str(archive), path_in_repo=name,commit_message='Upload old 256 data shard '+shard) info=api.get_paths_info(repo_id=REPO,repo_type='dataset',paths=[name]) if len(info)!=1 or info[0].size!=size or not info[0].lfs or info[0].lfs.sha256!=checksum: raise RuntimeError('HF object validation failed; retained local archive: '+shard) record={'shard':shard,'path':name,'bytes':size,'sha256':checksum,'commit':commit.commit_url, 'source_path_count':len(paths),'time':time.time()} with EVENTS.open('a',buffering=1) as f:f.write(json.dumps(record,ensure_ascii=False)+'\n') archive.unlink() # Only the copy made by this script, after verified upload. completed+=1 state('uploaded',shard=shard,completed=completed,total=len(queue)) state('all_inventoried_shards_uploaded_pending_full_data_validation',completed=completed,total=len(queue)) if __name__=='__main__': try:run() except Exception as error: state('failed',error=repr(error)) raise