AnswerReuse-Arena / restore.py
DoctorJia's picture
Release AnswerReuse-Arena benchmark, frozen inputs and construction vectors
6b5c608 verified
Raw History Blame Contribute Delete
2.77 kB
"""Verify and restore selected downloaded release files into an AttrSC checkout."""
from pathlib import Path
import argparse
import hashlib
import json
import shutil
def sha256(path):
h = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(8 * 1024**2), b''):
h.update(block)
return h.hexdigest()
def safe_path(root, relative):
path = Path(relative)
if path.is_absolute() or '..' in path.parts:
raise ValueError(f'Unsafe manifest path: {relative}')
result = root / path
if not result.resolve().is_relative_to(root.resolve()):
raise ValueError(f'Path escapes selected root: {relative}')
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--target', type=Path, required=True, help='Existing AttrSC checkout root')
parser.add_argument('--components', nargs='+', default=['benchmark', 'paper', 'evaluation_embeddings'],
choices=['benchmark', 'paper', 'evaluation_embeddings', 'construction'])
parser.add_argument('--verify-only', action='store_true')
args = parser.parse_args()
release = Path(__file__).resolve().parent
target = args.target.resolve()
if not target.is_dir():
raise ValueError('Target must be an existing directory')
manifest = json.loads((release / 'restore_map.json').read_text())
chosen = [x for x in manifest['files'] if x['component'] in args.components]
# Validate all requested inputs and existing destinations before copying.
copies = []
for record in chosen:
src = safe_path(release, record['path'])
dst = safe_path(target, record['local_path'])
if not src.is_file() or src.stat().st_size != record['bytes'] or sha256(src) != record['sha256']:
raise ValueError(f'Missing or changed release file: {record["path"]}')
if not args.verify_only and dst.exists():
if not dst.is_file() or dst.stat().st_size != record['bytes'] or sha256(dst) != record['sha256']:
raise FileExistsError(f'Destination differs; preserve or move it before restoring: {dst}')
elif not args.verify_only:
copies.append((src, dst))
for src, dst in copies:
dst.parent.mkdir(parents=True, exist_ok=True)
# Exclusive creation protects existing files from concurrent changes.
with src.open('rb') as reader, dst.open('xb') as writer:
shutil.copyfileobj(reader, writer, length=8 * 1024**2)
print(f'Verified {len(chosen)} files; restored {len(copies)} files.')
print('For a relocated checkout, prepare a new local paper bundle instead of rewriting frozen manifests.')
if __name__ == '__main__':
main()