Download archive.py from openmodelai/Terra-2.5: direct link, hf CLI and curl.
- Browser
- Download file 5.3 kB
-
https://huggingface.co/openmodelai/Terra-2.5/resolve/main/archive.py
- Command line
-
hf download hf://openmodelai/Terra-2.5/archive.py
-
curl -L -o archive.py https://huggingface.co/openmodelai/Terra-2.5/resolve/main/archive.py
5.3 kB
| """Package/restore a checkpoint ZIP with SHA-256 verification; standard library only.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import stat | |
| import tempfile | |
| import zipfile | |
| MAX_UNPACKED = 2 * 1024**3 | |
| REQUIRED = {"config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json", | |
| "training_state.pt", "training_meta.json"} | |
| def sha256(path): | |
| h = hashlib.sha256() | |
| with open(path, "rb") as stream: | |
| for chunk in iter(lambda: stream.read(1024 * 1024), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def pack(source, destination, compression="deflate"): | |
| if compression not in ("deflate", "lzma"): | |
| raise ValueError("Compression must be deflate or lzma") | |
| method = zipfile.ZIP_LZMA if compression == "lzma" else zipfile.ZIP_DEFLATED | |
| source, destination = Path(source).resolve(), Path(destination).resolve() | |
| if destination.is_relative_to(source): | |
| raise ValueError("Архив нельзя создавать внутри checkpoint") | |
| files = sorted(p for p in source.rglob("*") if p.is_file()) | |
| if any(p.is_symlink() for p in source.rglob("*")): | |
| raise ValueError("Ссылки запрещены") | |
| names = {p.relative_to(source).as_posix() for p in files} | |
| if not REQUIRED <= names or "manifest.json" in names: | |
| raise ValueError("Неполный checkpoint или конфликт manifest.json") | |
| if sum(p.stat().st_size for p in files) > MAX_UNPACKED: | |
| raise ValueError("Checkpoint превышает лимит 2 GiB") | |
| manifest = {p.relative_to(source).as_posix(): sha256(p) for p in files} | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| temp = destination.with_name(destination.name + ".partial") | |
| try: | |
| with zipfile.ZipFile(temp, "w", compression=method, compresslevel=6) as archive: | |
| for p in files: | |
| archive.write(p, p.relative_to(source).as_posix()) | |
| archive.writestr("manifest.json", json.dumps(manifest, indent=2) + "\n") | |
| os.replace(temp, destination) | |
| finally: | |
| temp.unlink(missing_ok=True) | |
| checksum = sha256(destination) | |
| destination.with_name(destination.name + ".sha256").write_text(f"{checksum} {destination.name}\n") | |
| return checksum | |
| def restore(source, destination): | |
| destination = Path(destination) | |
| if destination.exists(): | |
| raise ValueError("Каталог назначения уже существует; выберите новый") | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = Path(tempfile.mkdtemp(prefix=".terra-restore-", dir=destination.parent)) | |
| try: | |
| with zipfile.ZipFile(source) as archive: | |
| infos = archive.infolist() | |
| names = [i.filename for i in infos] | |
| if len(names) != len(set(names)) or len(names) > 10000: | |
| raise ValueError("Повторяющиеся имена или слишком много файлов") | |
| if sum(i.file_size for i in infos) > MAX_UNPACKED: | |
| raise ValueError("Архив превышает лимит 2 GiB") | |
| for info in infos: | |
| p = PurePosixPath(info.filename) | |
| if (p.is_absolute() or ".." in p.parts or "\\" in info.filename or ":" in info.filename | |
| or info.is_dir() or p.as_posix() != info.filename | |
| or stat.S_ISLNK(info.external_attr >> 16)): | |
| raise ValueError("Небезопасный путь в архиве") | |
| if "manifest.json" not in names or archive.getinfo("manifest.json").file_size > 1024**2: | |
| raise ValueError("Отсутствует или слишком велик manifest.json") | |
| manifest = json.loads(archive.read("manifest.json")) | |
| if not isinstance(manifest, dict) or set(manifest) != set(names) - {"manifest.json"}: | |
| raise ValueError("Manifest не совпадает с составом архива") | |
| if not REQUIRED <= set(manifest): | |
| raise ValueError("Неполный checkpoint") | |
| for name, expected in manifest.items(): | |
| dest = tmp / name | |
| dest.parent.mkdir(parents=True, exist_ok=True) | |
| with archive.open(name) as src, dest.open("wb") as dst: | |
| shutil.copyfileobj(src, dst, 1024 * 1024) | |
| if sha256(dest) != expected: | |
| raise ValueError(f"Неверная контрольная сумма: {name}") | |
| tmp.rename(destination) | |
| finally: | |
| if tmp.exists(): | |
| shutil.rmtree(tmp) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("action", choices=["pack", "restore"]) | |
| parser.add_argument("source") | |
| parser.add_argument("destination") | |
| parser.add_argument("--compression", choices=["deflate", "lzma"], default="deflate") | |
| args = parser.parse_args() | |
| if args.action == "pack": | |
| print(f"SHA256: {pack(args.source, args.destination, compression=args.compression)}") | |
| else: | |
| restore(args.source, args.destination) | |
| print(f"Восстановлено: {args.destination}") | |
| if __name__ == "__main__": | |
| main() | |