Datasets:
Download prepare_for_unibuild.py from WeiHuang95/UniBuild: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/datasets/WeiHuang95/UniBuild/resolve/main/prepare_for_unibuild.py
- Command line
-
hf download hf://datasets/WeiHuang95/UniBuild/prepare_for_unibuild.py
-
curl -L -o prepare_for_unibuild.py https://huggingface.co/datasets/WeiHuang95/UniBuild/resolve/main/prepare_for_unibuild.py
11.9 kB
| # SPDX-License-Identifier: MIT | |
| """Restore the original UniBuild RSSeg layout and configure an existing code checkout. | |
| Download WeiHuang95/UniBuild, then run this file from that download: | |
| python prepare_for_unibuild.py --code-root /path/to/UniBuild | |
| Data defaults to /path/to/UniBuild/data/RSSeg; use --data-root for another disk. | |
| Missing LMDBs are built by default; --storage files retains direct file loading. | |
| Existing images are never replaced with different contents. Changed code/split | |
| files are backed up before the small integration hook is installed. | |
| """ | |
| import argparse | |
| import ast | |
| import hashlib | |
| import json | |
| from pathlib import Path, PurePosixPath | |
| import re | |
| import tarfile | |
| import tempfile | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with Path(path).open('rb') as file: | |
| for chunk in iter(lambda: file.read(8*1024*1024), b''): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def write_with_backup(path, data): | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| mode = path.stat().st_mode & 0o777 if path.exists() else None | |
| if path.exists(): | |
| old = path.read_bytes() | |
| if old == data: | |
| return | |
| backup = path.with_name(path.name + '.before_hf_' + hashlib.sha256(old).hexdigest()[:12]) | |
| if not backup.exists(): | |
| backup.write_bytes(old) | |
| temporary = path.with_name(path.name + '.hf_tmp') | |
| temporary.write_bytes(data) | |
| if mode is not None: | |
| temporary.chmod(mode) | |
| temporary.replace(path) | |
| def extract_shard(archive_path, expected, dataset, destination, archive_hash): | |
| if sha256(archive_path) != archive_hash: | |
| raise ValueError(f'Archive SHA-256 mismatch: {archive_path}') | |
| seen = set() | |
| destination = destination.resolve() | |
| destination.mkdir(parents=True, exist_ok=True) | |
| with tarfile.open(archive_path, 'r:') as archive: | |
| for member in archive: | |
| parts = PurePosixPath(member.name).parts | |
| if (not member.isfile() or not parts or parts[0] != dataset | |
| or '..' in parts or PurePosixPath(member.name).is_absolute() | |
| or '\\' in member.name or ':' in member.name): | |
| raise ValueError(f'Unexpected or unsafe archive member: {member.name}') | |
| record = expected.get(member.name) | |
| if record is None or record['size'] != member.size or member.name in seen: | |
| raise ValueError(f'Archive member differs from catalog: {member.name}') | |
| seen.add(member.name) | |
| target = destination.joinpath(*parts[1:]) | |
| if not target.resolve().is_relative_to(destination): | |
| raise ValueError(f'Archive target leaves dataset directory: {target}') | |
| if target.exists(): | |
| if target.is_file() and target.stat().st_size == member.size and sha256(target) == record['sha256']: | |
| continue | |
| raise FileExistsError(f'Existing data differs; it has not been overwritten: {target}') | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = None | |
| try: | |
| h = hashlib.sha256() | |
| with archive.extractfile(member) as source, tempfile.NamedTemporaryFile( | |
| dir=target.parent, prefix='.unibuild_', suffix='.part', delete=False) as output: | |
| temporary = Path(output.name) | |
| for chunk in iter(lambda: source.read(1024*1024), b''): | |
| output.write(chunk) | |
| h.update(chunk) | |
| if h.hexdigest() != record['sha256']: | |
| raise ValueError(f'Extracted member SHA-256 mismatch: {member.name}') | |
| temporary.chmod(0o644) | |
| temporary.replace(target) | |
| finally: | |
| if temporary is not None and temporary.exists(): | |
| temporary.unlink() | |
| if seen != set(expected): | |
| raise ValueError(f'Archive is missing expected members: {archive_path}') | |
| def install_hook(code_root, release_root): | |
| helper = release_root / 'unibuild_data.py' | |
| if not helper.is_file(): | |
| raise FileNotFoundError(f'Missing integration helper: {helper}') | |
| config_path = code_root / 'configs.py' | |
| source = config_path.read_text(encoding='utf-8-sig') | |
| tree = ast.parse(source) | |
| cls = next((n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Config'), None) | |
| init = next((n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == '__init__'), None) if cls else None | |
| if init is None: | |
| raise ValueError('Expected Config.__init__ in configs.py; no code has been changed') | |
| hook_present = any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name) | |
| and n.func.id == 'apply_release_config' for n in ast.walk(init)) | |
| if not hook_present: | |
| lines = source.splitlines(keepends=True) | |
| hook = '\n # Optional paths/settings installed by the HF dataset preparation tool.\n' | |
| hook += ' from unibuild_data import apply_release_config\n' | |
| hook += ' apply_release_config(self, __file__)\n' | |
| lines.insert(init.end_lineno, hook) | |
| source = ''.join(lines) | |
| ast.parse(source) | |
| write_with_backup(code_root/'unibuild_data.py', helper.read_bytes()) | |
| for source_name, target_name in [('unibuild_lmdb.py', 'unibuild_lmdb.py'), | |
| ('prepare_lmdb.py', 'scripts/data/prepare_lmdb.py')]: | |
| if (release_root/source_name).is_file(): | |
| write_with_backup(code_root/target_name, (release_root/source_name).read_bytes()) | |
| write_with_backup(config_path, source.encode('utf-8')) | |
| launcher = code_root/'scripts/training/train.sh' | |
| if launcher.is_file(): | |
| shell = launcher.read_text(encoding='utf-8') | |
| # The published UniBuild launcher previously forced the withheld Potsdam | |
| # dataset; respect Config/--datasets instead of that stale example default. | |
| updated = re.sub(r"(?m)^datasets=\((?:'potsdam'|\"potsdam\"|potsdam)\)\s*$", | |
| 'datasets=()', shell) | |
| if updated != shell: | |
| write_with_backup(launcher, updated.encode('utf-8')) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--release-root', type=Path, default=Path(__file__).resolve().parent) | |
| parser.add_argument('--code-root', type=Path, required=True) | |
| parser.add_argument('--data-root', type=Path, help='RSSeg directory; default: CODE_ROOT/data/RSSeg') | |
| parser.add_argument('--datasets', nargs='+', help='Default: all published components') | |
| parser.add_argument('--storage', choices=['lmdb', 'files'], default='lmdb', | |
| help='Default: create missing LMDBs and train from LMDB') | |
| args = parser.parse_args() | |
| release = args.release_root.expanduser().resolve() | |
| code = args.code_root.expanduser().resolve() | |
| if not (code/'configs.py').is_file() or not (code/'train.py').is_file(): | |
| parser.error('--code-root must be a UniBuild training checkout with configs.py and train.py') | |
| if release == code: | |
| parser.error('Use separate directories for the HF download and the training checkout') | |
| ensure_lmdb = None | |
| if args.storage == 'lmdb': | |
| import importlib.util | |
| if importlib.util.find_spec('lmdb') is None: | |
| raise ModuleNotFoundError('LMDB mode requires lmdb; install UniBuild requirements or use --storage files') | |
| module_path = release/'unibuild_lmdb.py' | |
| if not module_path.is_file(): | |
| raise FileNotFoundError(f'Missing {module_path}; download the updated preparation tools') | |
| spec = importlib.util.spec_from_file_location('release_lmdb_builder', module_path) | |
| module = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(module) | |
| ensure_lmdb = module.ensure_dataset_lmdb | |
| data = (args.data_root.expanduser() if args.data_root else code/'data/RSSeg').resolve() | |
| layout = json.loads((release/'unibuild_layout.json').read_text(encoding='utf-8')) | |
| catalog = json.loads((release/'dataset_configs.json').read_text(encoding='utf-8')) | |
| selected = args.datasets or list(catalog) | |
| if not selected or len(selected) != len(set(selected)) or any(n not in catalog or n not in layout['datasets'] for n in selected): | |
| parser.error('--datasets must be distinct published dataset names') | |
| sums = dict(line.strip().split(None, 1)[::-1] for line in (release/'SHA256SUMS').read_text().splitlines() if line.strip()) | |
| pending = {} | |
| for name in selected: | |
| original_folder = PurePosixPath(layout['datasets'][name]['original_folder']) | |
| if (not original_folder.parts or original_folder.is_absolute() or '..' in original_folder.parts | |
| or '\\' in str(original_folder) or ':' in str(original_folder)): | |
| raise ValueError(f'Unsafe original dataset directory: {original_folder}') | |
| records = [json.loads(p.read_text()) for p in sorted((release/'checksums'/name).glob('*.json'))] | |
| if not records: | |
| raise FileNotFoundError(f'No archive checksums for {name}; download its complete component') | |
| # Preflight all shards before extracting this component. | |
| for record in records: | |
| relative = PurePosixPath(record['archive']) | |
| archive = release.joinpath(*relative.parts) | |
| if (relative.is_absolute() or '..' in relative.parts or not archive.resolve().is_relative_to(release) | |
| or sums.get(record['archive']) != record['sha256'] or not archive.is_file()): | |
| raise ValueError(f'Missing/unsafe archive or inconsistent checksum: {record["archive"]}') | |
| target = data.joinpath(*original_folder.parts) | |
| if not target.resolve().is_relative_to(data): | |
| raise ValueError(f'Dataset path leaves RSSeg root: {target}') | |
| for record in records: | |
| expected = {member['path']: member for member in record['members']} | |
| extract_shard(release/record['archive'], expected, name, target, record['sha256']) | |
| print('EXTRACTED_VERIFIED', record['archive'], flush=True) | |
| split_root = code/'data/splits'/name | |
| for split in ['train', 'val', 'test']: | |
| original = release/'splits'/name/f'{split}.txt' | |
| text = original.read_text(encoding='utf-8') | |
| for line in text.splitlines(): | |
| if not line.strip(): | |
| continue | |
| pair = line.split() | |
| if len(pair) != 2: | |
| raise ValueError(f'Invalid split row in {original}') | |
| for relative in pair: | |
| actual = (target/relative).resolve() | |
| if not actual.is_relative_to(target.resolve()) or not actual.is_file(): | |
| raise ValueError(f'Split references missing/unsafe file: {relative}') | |
| write_with_backup(split_root/f'{split}.txt', text.encode('utf-8')) | |
| entry = dict(catalog[name]) | |
| if ensure_lmdb is not None: | |
| ensure_lmdb(target, split_root) | |
| entry.update(data_dir=str(target), split_dir=str(split_root), use_lmdb=args.storage == 'lmdb') | |
| pending[name] = entry | |
| print('PREPARED', name, str(target), flush=True) | |
| state = {'format_version':1, 'repo_id':'WeiHuang95/UniBuild', 'datasets':selected, 'datasets_dict':pending} | |
| install_hook(code, release) | |
| registry = code/'data/unibuild_release.json' | |
| write_with_backup(registry, (json.dumps(state,indent=2)+'\n').encode('utf-8')) | |
| print('UNIBUILD_READY', str(registry), flush=True) | |
| print('Train from the code checkout: bash scripts/training/train.sh', flush=True) | |
| print('Override a subset as usual with TRAIN_DATASETS or train.py --datasets.', flush=True) | |
| if __name__ == '__main__': | |
| main() | |