Download examples/prepare_dataset.py from moddemod/xarch: direct link, hf CLI and curl.
- Browser
- Download file 5.9 kB
-
https://huggingface.co/datasets/moddemod/xarch/resolve/main/examples/prepare_dataset.py
- Command line
-
hf download hf://datasets/moddemod/xarch/examples/prepare_dataset.py
-
curl -L -o prepare_dataset.py https://huggingface.co/datasets/moddemod/xarch/resolve/main/examples/prepare_dataset.py
5.9 kB
| """Download and verify XArch, then extract the requested JSONL view (Python 3.10+).""" | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import tarfile | |
| import tempfile | |
| REPO = 'moddemod/xarch' | |
| ARCHIVE = 'xarch-bbdisasm-v2.tar.gz' | |
| RELEASE = 'xarch-bbdisasm-v2' | |
| SPLITS = ['train', 'validation', 'test'] | |
| METADATA = {'README.txt', 'summary.json', 'SHA256SUMS', 'example_read.py'} | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with Path(path).open('rb') as stream: | |
| for block in iter(lambda: stream.read(1024 * 1024), b''): | |
| h.update(block) | |
| return h.hexdigest() | |
| def extract_verified(archive, output_dir, views, splits, expected_sha256): | |
| archive, output_dir = Path(archive), Path(output_dir).resolve() | |
| if sha256(archive) != expected_sha256: | |
| raise ValueError('Archive SHA256 mismatch; no dataset files were replaced.') | |
| selected = {f'{s}.functions.jsonl' for s in splits} if 'functions' in views else set() | |
| if 'pairs' in views: | |
| selected |= {f'{s}.jsonl' for s in splits} | |
| wanted = selected | METADATA | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory(prefix='.xarch-stage-', dir=output_dir) as temp: | |
| staging = Path(temp) | |
| seen = set() | |
| with tarfile.open(archive, 'r|gz') as tar: | |
| for member in tar: | |
| relative = PurePosixPath(member.name) | |
| if relative.is_absolute() or '..' in relative.parts or not relative.parts or relative.parts[0] != RELEASE: | |
| raise ValueError('Unsafe or unexpected archive path') | |
| if not member.isdir() and not member.isfile(): | |
| raise ValueError('Only regular files and directories are accepted') | |
| if not member.isfile(): | |
| continue | |
| if len(relative.parts) != 2: | |
| raise ValueError('Unexpected nested file') | |
| name = relative.name | |
| if name not in wanted: | |
| continue | |
| if name in seen: | |
| raise ValueError('Duplicate archive member') | |
| seen.add(name) | |
| with tar.extractfile(member) as source, (staging / name).open('wb') as target: | |
| shutil.copyfileobj(source, target, length=1024 * 1024) | |
| if seen != wanted: | |
| raise ValueError('Requested files or release metadata are missing') | |
| summary = json.loads((staging / 'summary.json').read_text()) | |
| for name in selected: | |
| spec = summary['files'][name] | |
| if (staging / name).stat().st_size != spec['bytes'] or sha256(staging / name) != spec['sha256']: | |
| raise ValueError('Extracted JSONL does not match the release manifest') | |
| checksums = {} | |
| for line in (staging / 'SHA256SUMS').read_text().splitlines(): | |
| checksum, name = line.split(maxsplit=1) | |
| checksums[name.lstrip('*')] = checksum | |
| for name in wanted - {'SHA256SUMS'}: | |
| if sha256(staging / name) != checksums[name]: | |
| raise ValueError('Release checksum mismatch: ' + name) | |
| target = output_dir / RELEASE | |
| if target.is_symlink(): | |
| raise FileExistsError('The destination release directory must not be a symlink') | |
| target.mkdir(exist_ok=True) | |
| # Check every destination before replacing anything. A partial extraction | |
| # may be extended with another view, but conflicting files are refused. | |
| for name in wanted: | |
| if (target / name).is_symlink(): | |
| raise FileExistsError('Refusing an existing symlink: ' + str(target / name)) | |
| if (target / name).exists() and sha256(target / name) != sha256(staging / name): | |
| raise FileExistsError('Conflicting existing file: ' + str(target / name)) | |
| for name in sorted(wanted): | |
| if not (target / name).exists(): | |
| (staging / name).replace(target / name) | |
| return target | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--output-dir', default='./data') | |
| parser.add_argument('--view', choices=['functions', 'pairs', 'both'], default='functions') | |
| parser.add_argument('--splits', nargs='+', choices=SPLITS, default=SPLITS) | |
| parser.add_argument('--revision', default='main') | |
| parser.add_argument('--archive', type=Path, help='Use an already downloaded archive') | |
| parser.add_argument('--expected-sha256', help='Optional explicit checksum for --archive') | |
| args = parser.parse_args() | |
| if args.archive: | |
| archive = args.archive | |
| checksum_file = archive.with_name(archive.name + '.sha256') | |
| if args.expected_sha256: | |
| checksum = args.expected_sha256 | |
| elif checksum_file.exists(): | |
| checksum = checksum_file.read_text().split()[0] | |
| else: | |
| parser.error('Provide the neighboring .sha256 file or --expected-sha256') | |
| revision = 'local archive' | |
| else: | |
| from huggingface_hub import HfApi, hf_hub_download | |
| # Resolve main once so both downloaded files belong to the same commit. | |
| revision = HfApi().dataset_info(REPO, revision=args.revision).sha | |
| archive = hf_hub_download(REPO, ARCHIVE, repo_type='dataset', revision=revision) | |
| checksum_file = hf_hub_download(REPO, ARCHIVE + '.sha256', repo_type='dataset', revision=revision) | |
| checksum = Path(checksum_file).read_text().split()[0] | |
| views = ['functions', 'pairs'] if args.view == 'both' else [args.view] | |
| target = extract_verified(archive, args.output_dir, views, args.splits, checksum) | |
| print(json.dumps({'dataset_dir': str(target), 'views': views, 'splits': args.splits, | |
| 'revision': revision, 'archive_sha256': checksum}, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |