"""Verify, upload, or restore a promoter_diff resource bundle.""" import argparse import hashlib import json import shutil from pathlib import Path def verify_bundle(root: Path, sizes_only: bool = False) -> None: manifest = json.loads((root / "manifest.json").read_text()) for entry in manifest["files"]: path = root / entry["path"] if path.stat().st_size != entry["bytes"]: raise ValueError(f"Size mismatch: {path}") if not sizes_only: with path.open("rb") as handle: digest = hashlib.file_digest(handle, "sha256").hexdigest() if digest != entry["sha256"]: raise ValueError(f"SHA256 mismatch: {path}") print( f"Verified {len(manifest['files'])} files ({'sizes' if sizes_only else 'SHA256'})." ) def localize_ntv3(model_root: Path, code_root: Path) -> None: """Replace cross-repository auto_map references with pinned local modules.""" for source in code_root.glob("*.py"): shutil.copyfile(source, model_root / source.name) for name in ["config.json", "tokenizer_config.json"]: path = model_root / name original = path.read_text() config = json.loads(original) auto_map = config.get("auto_map", {}) for key, value in auto_map.items(): if isinstance(value, str): auto_map[key] = value.split("--", maxsplit=1)[-1] elif isinstance(value, list): auto_map[key] = [ item.split("--", maxsplit=1)[-1] if isinstance(item, str) else item for item in value ] backup = model_root / f"{name}.upstream" if not backup.exists(): backup.write_text(original) path.write_text(json.dumps(config, indent=2) + "\n") def restore_models(root: Path, names: list[str] | None) -> None: from huggingface_hub import snapshot_download models = json.loads((root / "models.json").read_text()) by_name = {model["name"]: model for model in models} selected = set(names) if names else set(by_name) unknown = selected - by_name.keys() if unknown: raise ValueError(f"Unknown models: {sorted(unknown)}") if any(name.startswith("NTv3_") for name in selected): selected.add("ntv3_base_model") for name in sorted(selected, key=lambda name: name != "ntv3_base_model"): model = by_name[name] model_root = root / "model_weights" / name snapshot_download( repo_id=model["repo_id"], revision=model["revision"], local_dir=model_root, ignore_patterns=["jax_model/*", "flax_model*", "tf_model*", "figures/*"], ) if name.startswith("NTv3_"): localize_ntv3( model_root=model_root, code_root=root / "model_weights/ntv3_base_model", ) print(f"Restored {name} at {model['revision']}") def upload_bundle(root: Path, repo_id: str, execute: bool) -> None: manifest = json.loads((root / "manifest.json").read_text()) paths = [entry["path"] for entry in manifest["files"]] + ["manifest.json"] print( f"Dataset: {repo_id}; {len(paths)} files; {manifest['total_bytes'] / 1e9:.3f} GB" ) if not execute: for path in paths: print(path) print("Dry run. Add --execute to upload to an existing dataset repository.") return from huggingface_hub import CommitOperationAdd, HfApi verify_bundle(root=root) # Explicit files follow symlinks as bytes. Git would record symlink targets. # The manifest also prevents accidentally uploading restored model weights. operations = [ CommitOperationAdd(path_in_repo=path, path_or_fileobj=root / path) for path in paths ] result = HfApi().create_commit( repo_id=repo_id, repo_type="dataset", operations=operations, commit_message="Add promoter_diff processed datasets and resource instructions", ) print(result.commit_url) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent) commands = parser.add_subparsers(dest="command", required=True) verify = commands.add_parser("verify") verify.add_argument("--sizes-only", action="store_true") models = commands.add_parser("models") models.add_argument("names", nargs="*") upload = commands.add_parser("upload") upload.add_argument("repo_id") upload.add_argument("--execute", action="store_true") arguments = parser.parse_args() match arguments.command: case "verify": verify_bundle(root=arguments.root, sizes_only=arguments.sizes_only) case "models": restore_models(root=arguments.root, names=arguments.names) case "upload": upload_bundle( root=arguments.root, repo_id=arguments.repo_id, execute=arguments.execute, ) if __name__ == "__main__": main()