Download tools/rebuild_publication.py from Lexmount/LexBench-Web-Fetch: direct link, hf CLI and curl.
- Browser
- Download file 6.31 kB
-
https://huggingface.co/datasets/Lexmount/LexBench-Web-Fetch/resolve/refs%2Fpr%2F3/tools/rebuild_publication.py
- Command line
-
hf download hf://datasets/Lexmount/LexBench-Web-Fetch@refs/pr/3/tools/rebuild_publication.py
-
curl -L -o rebuild_publication.py https://huggingface.co/datasets/Lexmount/LexBench-Web-Fetch/resolve/refs%2Fpr%2F3/tools/rebuild_publication.py
6.31 kB
| """Rebuild the definitions archive while preserving the published population metadata. | |
| This dataset-local wrapper does not regenerate task populations or viewer rows. | |
| The source revision must name an uploaded commit containing the input definitions. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import io | |
| import json | |
| from pathlib import Path | |
| import re | |
| import tarfile | |
| NOTICES = {'LICENSE', 'NOTICE', 'THIRD_PARTY.md', 'VERSIONING.md'} | |
| def encoded(value): | |
| return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + '\n').encode() | |
| def sha(raw): | |
| return hashlib.sha256(raw).hexdigest() | |
| def population(root, manifest): | |
| edition = manifest.get('edition') | |
| if not isinstance(edition, dict) or not edition.get('population_sha256'): | |
| raise ValueError('The existing edition metadata must be retained') | |
| rows, configurations = [], [] | |
| for configuration in edition['configurations']: | |
| name = configuration['name'] | |
| if not re.fullmatch(r'[a-z][a-z0-9-]*', name): | |
| raise ValueError('Unsafe viewer configuration') | |
| path = root / 'data' / (name + '.jsonl') | |
| records = [json.loads(line) for line in path.read_text().splitlines()] | |
| if len(records) != configuration['count']: | |
| raise ValueError('Edition configuration count changed: ' + name) | |
| configurations.append(name) | |
| for row in records: | |
| task = json.loads(row['task']) | |
| if task['id'] != row['id']: | |
| raise ValueError('Viewer identity differs from its task') | |
| rows.append({'suite': row['source_suite'], 'id': row['id'], | |
| 'task_sha256': sha(encoded(task))}) | |
| rows.sort(key=lambda row: (row['suite'], row['id'])) | |
| if (len(rows) != edition['task_count'] | |
| or len({(row['suite'], row['id']) for row in rows}) != len(rows) | |
| or sha(encoded(rows)) != edition['population_sha256'] | |
| or len(set(configurations)) != len(configurations)): | |
| raise ValueError('The unchanged default population no longer matches the edition') | |
| return edition | |
| def publication_files(root): | |
| paths = list((root / 'definitions').rglob('*')) | |
| paths += [root / name for name in NOTICES] | |
| files = {} | |
| for path in paths: | |
| if path.is_symlink(): | |
| raise ValueError('Publication files cannot be symbolic links') | |
| if path.is_file(): | |
| name = path.relative_to(root).as_posix() | |
| if (name.startswith('definitions/') and path.suffix not in {'.json', '.md'}): | |
| raise ValueError('Unexpected public definition file: ' + name) | |
| files[name] = path.read_bytes() | |
| return files | |
| def rebuild(root, source_revision): | |
| if not re.fullmatch(r'[0-9a-f]{40}', source_revision): | |
| raise ValueError('Use a full uploaded source commit, not a local label') | |
| path = root / 'manifest.json' | |
| manifest = json.loads(path.read_text()) | |
| edition = population(root, manifest) | |
| files = publication_files(root) | |
| files.update({p.relative_to(root).as_posix(): p.read_bytes() | |
| for p in (root / 'data').glob('*.jsonl')}) | |
| manifest['files'] = {name: {'sha256': sha(raw), 'size': len(raw)} | |
| for name, raw in sorted(files.items())} | |
| manifest['source_revision'] = source_revision | |
| # Restore the exact edition object after rebuilding hashes; never invent a tag. | |
| manifest['edition'] = edition | |
| buffer = io.BytesIO() | |
| with gzip.GzipFile(fileobj=buffer, mode='wb', mtime=0, filename='') as compressed: | |
| with tarfile.open(fileobj=compressed, mode='w') as archive: | |
| for name, raw in sorted(files.items()): | |
| if name.startswith('data/'): | |
| continue | |
| entry = tarfile.TarInfo(name) | |
| entry.size, entry.mode, entry.mtime = len(raw), 0o644, 0 | |
| archive.addfile(entry, io.BytesIO(raw)) | |
| raw = buffer.getvalue() | |
| (root / 'definitions.tar.gz').write_bytes(raw) | |
| manifest['archive'] = {'path': 'definitions.tar.gz', 'sha256': sha(raw), 'size': len(raw)} | |
| path.write_bytes(encoded(manifest)) | |
| check(root) | |
| return manifest | |
| def check(root): | |
| manifest = json.loads((root / 'manifest.json').read_text()) | |
| population(root, manifest) | |
| expected_names = set(publication_files(root)) | {p.relative_to(root).as_posix() for p in (root / 'data').glob('*.jsonl')} | |
| if set(manifest['files']) != expected_names: | |
| raise ValueError('Publication manifest inventory differs from current files') | |
| for name, binding in manifest['files'].items(): | |
| path = root / name | |
| if Path(name).is_absolute() or '..' in Path(name).parts or path.is_symlink(): | |
| raise ValueError('Unsafe publication path') | |
| raw = path.read_bytes() | |
| if sha(raw) != binding['sha256'] or len(raw) != binding['size']: | |
| raise ValueError('Changed publication file: ' + name) | |
| raw = (root / 'definitions.tar.gz').read_bytes() | |
| if sha(raw) != manifest['archive']['sha256'] or len(raw) != manifest['archive']['size']: | |
| raise ValueError('Changed definitions archive') | |
| files = publication_files(root) | |
| with tarfile.open(fileobj=io.BytesIO(raw)) as archive: | |
| names = archive.getnames() | |
| if len(names) != len(set(names)) or set(names) != set(files): | |
| raise ValueError('Archive inventory differs from current definitions') | |
| for item in archive: | |
| if not item.isfile() or archive.extractfile(item).read() != files[item.name]: | |
| raise ValueError('Archive member differs: ' + item.name) | |
| return {'task_count': manifest['edition']['task_count'], 'archive_members': len(files)} | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument('--source-revision') | |
| parser.add_argument('--check', action='store_true') | |
| args = parser.parse_args() | |
| if args.check: | |
| print(json.dumps(check(args.root))) | |
| elif args.source_revision: | |
| print(json.dumps(rebuild(args.root, args.source_revision)['archive'])) | |
| else: | |
| parser.error('--source-revision is required when rebuilding') | |