EchoScout-FourTask / scripts /extract_data.py
zhizeng115's picture
Complete four-task dataset and portable code release
7e7a152 verified
Raw History Blame Contribute Delete
3.6 kB
"""Verify the complete release and safely extract its data into the code tree."""
import argparse, hashlib, json, os, tarfile
from pathlib import Path, PurePosixPath
def digest(path):
with path.open('rb') as f:
h=hashlib.sha256()
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
return h.hexdigest()
def safe_target(root, name):
p=PurePosixPath(name)
if p.is_absolute() or '..' in p.parts or not p.parts or p.parts[0] not in ('datasets','metadata'):
raise ValueError('Unsafe archive path: '+name)
target=root.joinpath(*p.parts)
if not target.resolve().is_relative_to(root.resolve()): raise ValueError('Path escapes destination')
for parent in [target]+list(target.parents):
if parent==root:break
if parent.is_symlink():raise ValueError('Refusing destination symlink')
return target
def extract(repo, destination):
manifest=json.loads((repo/'metadata/archives.json').read_text())
files_path=repo/'metadata/files.jsonl'
if digest(files_path)!=manifest['files_manifest_sha256']:raise ValueError('File manifest checksum mismatch')
rows=[json.loads(s) for s in files_path.read_text().splitlines() if s.strip()]
expected={r['path']:r for r in rows}
if len(expected)!=len(rows) or len(rows)!=manifest['file_count']:raise ValueError('Invalid manifest counts')
seen=set(); destination.mkdir(parents=True,exist_ok=True)
for archive in manifest['archives']:
ap=PurePosixPath(archive['path'])
if ap.is_absolute() or '..' in ap.parts or ap.parts[0]!='archives':raise ValueError('Invalid archive path')
path=repo.joinpath(*ap.parts)
if path.stat().st_size!=archive['size'] or digest(path)!=archive['sha256']:raise ValueError('Archive checksum mismatch: '+archive['path'])
count=0
with tarfile.open(path,'r:gz') as tar:
for m in tar:
if not m.isfile():raise ValueError('Only regular files are permitted')
if m.name.startswith('__shards__/'):continue
if m.name not in expected or m.name in seen:raise ValueError('Unexpected or repeated member')
row=expected[m.name]
if row['archive']!=archive['path'] or row['size']!=m.size:raise ValueError('Manifest member mismatch')
dest=safe_target(destination,m.name)
if dest.exists():
if not dest.is_file() or digest(dest)!=row['sha256']:raise ValueError('Existing file differs: '+m.name)
else:
dest.parent.mkdir(parents=True,exist_ok=True)
temp=dest.with_name(dest.name+'.extract-partial')
# Exclusive creation avoids overwriting any existing user file.
with temp.open('xb') as out, tar.extractfile(m) as inp:
for b in iter(lambda:inp.read(1024*1024),b''):out.write(b)
if digest(temp)!=row['sha256']:raise ValueError('Extracted file checksum mismatch')
temp.replace(dest)
seen.add(m.name);count+=1
if count!=archive['file_count']:raise ValueError('Archive member count mismatch')
print('Verified',archive['path'],count,'files',flush=True)
if seen!=set(expected):raise ValueError('Incomplete extraction')
print('Complete:',len(seen),'verified files')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--destination',type=Path,default=Path('code'));args=p.parse_args()
extract(Path(__file__).resolve().parents[1],args.destination.resolve())