Download tools/pack_shards_from_bos.py from SEELE-AI/EVA-Edit: direct link, hf CLI and curl.
- Browser
- Download file 7.75 kB
-
https://huggingface.co/datasets/SEELE-AI/EVA-Edit/resolve/main/tools/pack_shards_from_bos.py
- Command line
-
hf download hf://datasets/SEELE-AI/EVA-Edit/tools/pack_shards_from_bos.py
-
curl -L -o pack_shards_from_bos.py https://huggingface.co/datasets/SEELE-AI/EVA-Edit/resolve/main/tools/pack_shards_from_bos.py
7.75 kB
| #!/usr/bin/env python3 | |
| """Pack complete mesh edit groups into streamable TAR shards.""" | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import hashlib | |
| import json | |
| import os | |
| import shutil | |
| import tarfile | |
| from pathlib import Path | |
| from typing import Any, Iterator | |
| DEFAULT_MAX_SHARD_BYTES = 2 * 1024 * 1024 * 1024 | |
| def iter_records(manifest: Path) -> Iterator[dict[str, Any]]: | |
| with manifest.open('r', encoding='utf-8') as handle: | |
| for line_no, line in enumerate(handle, 1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| record = json.loads(line) | |
| except json.JSONDecodeError as exc: | |
| raise RuntimeError(f'{manifest}:{line_no}: invalid JSON: {exc}') from exc | |
| yield record | |
| def resolve_source(source_root: Path, relative_path: str) -> Path: | |
| relative = Path(relative_path) | |
| if relative.is_absolute() or '..' in relative.parts: | |
| raise RuntimeError(f'unsafe manifest path: {relative_path}') | |
| candidates = [source_root / relative] | |
| if relative.parts and relative.parts[0] == 'meshes': | |
| candidates.append(source_root / Path(*relative.parts[1:])) | |
| for candidate in candidates: | |
| if candidate.is_file(): | |
| return candidate | |
| raise FileNotFoundError(f'source mesh not found for {relative_path}') | |
| class HashReader: | |
| def __init__(self, handle): | |
| self.handle = handle | |
| self.digest = hashlib.sha256() | |
| def read(self, size: int = -1) -> bytes: | |
| data = self.handle.read(size) | |
| if data: | |
| self.digest.update(data) | |
| return data | |
| def add_verified_file(tar: tarfile.TarFile, source: Path, member: str, expected: str | None) -> int: | |
| info = tar.gettarinfo(str(source), arcname=member) | |
| info.uid = 0 | |
| info.gid = 0 | |
| info.uname = '' | |
| info.gname = '' | |
| info.mtime = 0 | |
| info.mode = 0o644 | |
| with source.open('rb') as handle: | |
| reader = HashReader(handle) | |
| tar.addfile(info, reader) | |
| actual = reader.digest.hexdigest() | |
| if expected is not None and actual != expected: | |
| raise RuntimeError(f'checksum mismatch for {member}: expected {expected}, got {actual}') | |
| return info.size | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--manifest', type=Path, required=True, help='Sanitized EVA01-Edit three-stage JSONL manifest') | |
| parser.add_argument('--source-root', type=Path, required=True, help='Mounted source mesh root or its parent dataset root') | |
| parser.add_argument('--output-root', type=Path, required=True, help='Directory containing shards/ and manifest/') | |
| parser.add_argument('--max-shard-bytes', type=int, default=DEFAULT_MAX_SHARD_BYTES, help='Target uncompressed payload per shard') | |
| parser.add_argument('--max-groups', type=int, help='Pack only this many groups for a bounded run') | |
| args = parser.parse_args() | |
| if args.max_shard_bytes < 1: | |
| parser.error('--max-shard-bytes must be positive') | |
| if args.max_groups is not None and args.max_groups < 1: | |
| parser.error('--max-groups must be positive') | |
| shards_dir = args.output_root / 'shards' | |
| manifest_dir = args.output_root / 'manifest' | |
| shards_dir.mkdir(parents=True, exist_ok=True) | |
| manifest_dir.mkdir(parents=True, exist_ok=True) | |
| sharded_manifest = manifest_dir / 'three_stage_sharded.jsonl' | |
| shard_index = manifest_dir / 'shard_index.jsonl' | |
| if sharded_manifest.exists() or shard_index.exists() or any(shards_dir.iterdir()): | |
| raise RuntimeError(f'output directory is not empty: {args.output_root}') | |
| shard_number = 0 | |
| current_tar = None | |
| current_payload = 0 | |
| current_shard_name = None | |
| groups = 0 | |
| mesh_files = 0 | |
| shard_count = 0 | |
| try: | |
| with sharded_manifest.open('w', encoding='utf-8') as manifest_out, shard_index.open('w', encoding='utf-8') as index_out: | |
| for record in iter_records(args.manifest): | |
| if args.max_groups is not None and groups >= args.max_groups: | |
| break | |
| group_key = record.get('group_key') | |
| stages = record.get('stages') | |
| if not isinstance(group_key, str) or not isinstance(stages, list): | |
| raise RuntimeError('manifest record is missing group_key or stages') | |
| sources = [] | |
| group_payload = 0 | |
| for stage in stages: | |
| mesh = stage.get('mesh') if isinstance(stage, dict) else None | |
| if not isinstance(mesh, dict): | |
| raise RuntimeError(f'missing mesh metadata for {group_key}') | |
| member = mesh.get('path') | |
| expected = mesh.get('sha256') | |
| if not isinstance(member, str) or (expected is not None and not isinstance(expected, str)): | |
| raise RuntimeError(f'invalid mesh metadata for {group_key}') | |
| source = resolve_source(args.source_root, member) | |
| size = source.stat().st_size | |
| sources.append((stage, mesh, member, expected, source, size)) | |
| group_payload += size | |
| if current_tar is None or (current_payload and current_payload + group_payload > args.max_shard_bytes): | |
| if current_tar is not None: | |
| current_tar.close() | |
| current_shard_name = f'shards/shard-{shard_number:06d}.tar' | |
| current_tar = tarfile.open(args.output_root / current_shard_name, mode='w') | |
| current_payload = 0 | |
| shard_number += 1 | |
| shard_count += 1 | |
| sharded = copy.deepcopy(record) | |
| index_members = [] | |
| for stage_index, (stage, mesh, member, expected, source, _size) in enumerate(sources): | |
| assert current_tar is not None and current_shard_name is not None | |
| packed_size = add_verified_file(current_tar, source, member, expected) | |
| current_payload += packed_size | |
| mesh_out = sharded['stages'][stage_index]['mesh'] | |
| mesh_out.pop('sha256', None) | |
| mesh_out['shard'] = current_shard_name | |
| mesh_out['member'] = member | |
| index_members.append({'stage': stage['stage'], 'member': member}) | |
| mesh_files += 1 | |
| sharded_line = json.dumps(sharded, ensure_ascii=False, separators=(',', ':')) | |
| manifest_out.write(sharded_line + '\n') | |
| index_out.write(json.dumps({'group_key': group_key, 'shard': current_shard_name, 'members': index_members}, ensure_ascii=False, separators=(',', ':')) + '\n') | |
| groups += 1 | |
| if groups % 100 == 0: | |
| print(json.dumps({'progress_groups': groups, 'mesh_files': mesh_files, 'shards': shard_count, 'current_shard_payload_bytes': current_payload}), flush=True) | |
| finally: | |
| if current_tar is not None: | |
| current_tar.close() | |
| checksum_path = manifest_dir / 'eva01_edit_shard_checksums.txt' | |
| checksum_lines = [] | |
| for tar_path in sorted(shards_dir.glob('*.tar')): | |
| digest = hashlib.sha256() | |
| with tar_path.open('rb') as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b''): | |
| digest.update(chunk) | |
| checksum_lines.append(f'{digest.hexdigest()} shards/{tar_path.name}') | |
| checksum_path.write_text('\n'.join(checksum_lines) + '\n') | |
| print(json.dumps({'groups': groups, 'mesh_files': mesh_files, 'shards': shard_count, 'target_shard_bytes': args.max_shard_bytes}, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |