File size: 3,258 Bytes
3bc5d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download a dataset group, verify checksums, decompress it and restore shared paths."""
import argparse,hashlib,json,os,tempfile,shutil
from pathlib import Path,PurePosixPath

def sha(path):
 h=hashlib.sha256()
 with open(path,'rb') as f:
  for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
 return h.hexdigest()

def within(root,name):
 parts=PurePosixPath(name)
 if parts.is_absolute() or '..' in parts.parts:raise ValueError('Unsafe path')
 path=root.joinpath(*parts.parts)
 if not path.resolve().is_relative_to(root.resolve()):raise ValueError('Destination escapes output directory')
 return path

def main():
 ap=argparse.ArgumentParser(description=__doc__)
 ap.add_argument('--group',required=True,help='Path below data/, e.g. synthetic_2d/throwing')
 ap.add_argument('--output',type=Path,required=True)
 ap.add_argument('--revision',required=True,help='Repository commit SHA')
 ap.add_argument('--repo-id',default='DocD0c/VorA')
 ap.add_argument('--index-root',type=Path,default=Path(__file__).resolve().parent.parent)
 ap.add_argument('--local-repository',type=Path,help='Read stored files from this checkout instead of downloading')
 ap.add_argument('--dry-run',action='store_true')
 args=ap.parse_args()
 entries=[json.loads(x) for x in (args.index_root/'data/index.jsonl').open()]
 prefix='data/'+args.group.strip('/')+'/'
 selected=[x for x in entries if x['path'].startswith(prefix)]
 objects={x['sha256']:x for x in selected}
 print(json.dumps({'logical_files':len(selected),'unique_contents':len(objects),'download_bytes':sum(x['stored_size'] for x in objects.values()),'uncompressed_unique_bytes':sum(x['size'] for x in objects.values())}))
 if args.dry_run:return
 if not selected:raise SystemExit('No matching dataset group')
 args.output.mkdir(parents=True,exist_ok=True);restored={}
 for entry in selected:
  target=within(args.output,entry['path'].removeprefix('data/'));target.parent.mkdir(parents=True,exist_ok=True)
  if target.exists():
   if sha(target)!=entry['sha256']:raise RuntimeError('Existing file checksum mismatch: '+str(target))
   restored.setdefault(entry['sha256'],target);continue
  if entry['sha256'] in restored:
   os.link(restored[entry['sha256']],target);continue
  if args.local_repository:source=within(args.local_repository,entry['stored_path'])
  else:
   from huggingface_hub import hf_hub_download
   source=Path(hf_hub_download(args.repo_id,entry['stored_path'],repo_type='dataset',revision=args.revision))
  if source.stat().st_size!=entry['stored_size'] or sha(source)!=entry['stored_sha256']:raise RuntimeError('Stored file checksum mismatch')
  fd,tmp=tempfile.mkstemp(prefix='.materialize-',dir=target.parent)
  try:
   with os.fdopen(fd,'wb') as dst,source.open('rb') as src:
    if entry['compression']=='zstd':
     import zstandard
     zstandard.ZstdDecompressor().copy_stream(src,dst)
    else:shutil.copyfileobj(src,dst,8*1024*1024)
   if Path(tmp).stat().st_size!=entry['size'] or sha(tmp)!=entry['sha256']:raise RuntimeError('Restored content checksum mismatch')
   os.link(tmp,target)
  finally:os.unlink(tmp)
  restored[entry['sha256']]=target
 print('Dataset restored; every selected file verified. Shared hardlinks must be treated as read-only.')
if __name__=='__main__':main()