"""Download pinned WanAnimate weights. Does not start models or enable services. python scripts/download_video_edit_models.py --workspace /workspace --metadata-dir /workspace/model-metadata Canonical metadata cache filenames: animate-diffusers-source.json, animate-original-source.json. Missing metadata is fetched from Hugging Face at the fixed revision. Replica bytes are accepted only after matching the canonical LFS SHA256 or Git blob hash. """ import argparse import hashlib import json import re import shutil import subprocess from pathlib import Path, PurePosixPath from urllib.parse import quote from urllib.request import urlopen MODEL_REPO = "Wan-AI/Wan2.2-Animate-14B-Diffusers" MODEL_REVISION = "6f4df10861c758af86ac3c979aacc1bf5c03eff0" PREPROCESS_REPO = "Wan-AI/Wan2.2-Animate-14B" PREPROCESS_REVISION = "cb93a225fbaf1ca100f54e79da8f994995b689b3" CODE_REPO = "Wan-Video/Wan2.2" CODE_REVISION = "1ea34ff48f87168174e12956e200b1d908b1c5ff" CODE_PREFIX = "wan/modules/animate/preprocess" CODE_FILES = { "pose2d.py": "b71792fa2222c4c8eacf43dba21b4c8e4b510fbdcbd9505353a108a095e47f19", "pose2d_utils.py": "a5fc3867420b5ee985ba0cc4e304cb57de177d221941df99116db1c83ddc2047", "human_visualization.py": "962813c71b2f2e09f7cd745b35b31a0d278b122b5f2f429018d0576c795eda33", "utils.py": "59cf48da9d816156218dc37f8daec3385f4260714fc40bedfe2f8d8ff6898c0f", } SPECS = ( ( "wan2.2-animate-14b", MODEL_REPO, MODEL_REVISION, "model", "animate-diffusers-source.json", ), ( "wan2.2-animate-preprocess", PREPROCESS_REPO, PREPROCESS_REVISION, "preprocess", "animate-original-source.json", ), ) def child_path(root, name): root = Path(root).resolve() relative = PurePosixPath(name) if ( not name or "\\" in name or ":" in name or relative.is_absolute() or ".." in relative.parts or "." == name ): raise ValueError("Invalid relative deployment path") path = root for part in relative.parts: path = path / part if path.is_symlink(): raise ValueError("Symlink deployment targets are forbidden") if not path.resolve().is_relative_to(root): raise ValueError("Deployment path escapes workspace") return path def confined(root, path): root = Path(root).resolve(strict=True) candidate = Path(path).absolute() try: relative = candidate.relative_to(root).as_posix() except ValueError as exc: raise ValueError("Deployment path must stay inside workspace") from exc return child_path(root, relative) def hash_file(path, algorithm="sha256", git_blob=False): digest = hashlib.new(algorithm) if git_blob: digest.update(b"blob " + str(path.stat().st_size).encode() + b"\0") with path.open("rb") as source: for block in iter(lambda: source.read(8 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest() def checksum(path, item): expected = item.get("lfs", {}).get("sha256") or item.get("blobId") lfs = bool(item.get("lfs", {}).get("sha256")) if not isinstance(expected, str) or not re.fullmatch( "[0-9a-f]{" + ("64" if lfs else "40") + "}", expected ): raise ValueError("Canonical file hash is required") path = Path(path) size = item.get("size", item.get("lfs", {}).get("size")) if type(size) is not int or size < 0: raise ValueError("Canonical file size is required") return ( path.is_file() and not path.is_symlink() and path.stat().st_size == size and hash_file(path, "sha256" if lfs else "sha1", not lfs) == expected ) def select_files(files, kind): if kind == "preprocess": return [ item for item in files if item["rfilename"].startswith("process_checkpoint/pose2d/") or item["rfilename"] in { "process_checkpoint/det/yolov10m.onnx", "process_checkpoint/sam2/sam2_hiera_large.pt", } ] return [ item for item in files if not any( part.startswith(".") for part in PurePosixPath(item["rfilename"]).parts ) ] def validate_metadata(data, repo, revision, kind): if data.get("id") != repo or data.get("sha") != revision: raise ValueError("Unexpected canonical repository/revision") selected = select_files(data.get("siblings", []), kind) names = {item["rfilename"] for item in selected} if len(names) != len(selected): raise ValueError("Duplicate metadata path") required = ( {"model_index.json", "transformer/config.json", "vae/config.json"} if kind == "model" else { "process_checkpoint/det/yolov10m.onnx", "process_checkpoint/sam2/sam2_hiera_large.pt", "process_checkpoint/pose2d/vitpose_h_wholebody.onnx/end2end.onnx", } ) if not required <= names or ( kind == "model" and not any( name.startswith("transformer/") and name.endswith(".safetensors") for name in names ) ): raise ValueError("Canonical metadata is missing required model files") for item in selected: child_path(Path.cwd(), item["rfilename"]) # 校验元数据必须带canonical hash;不存在的探测路径不会触发下载。 checksum(Path("/__video_edit_nonexistent__"), item) return selected def fetch_bytes(url, target): with urlopen(url, timeout=120) as response, target.open("wb") as stream: shutil.copyfileobj(response, stream, length=4 * 1024 * 1024) def download_file(repo, revision, item, target, fetch=fetch_bytes): path = child_path(target, item["rfilename"]) if path.exists(): if checksum(path, item): return path # 不覆盖可能属于既有部署的文件;由运维审查后显式移走损坏文件。 raise ValueError("Refusing to overwrite existing mismatched file: " + str(path)) path.parent.mkdir(parents=True, exist_ok=True) partial = child_path(target, item["rfilename"] + ".incomplete") name = quote(item["rfilename"], safe="/") urls = [ f"https://modelscope.cn/models/{repo}/resolve/master/{name}", f"https://huggingface.co/{repo}/resolve/{revision}/{name}", ] failures = [] for url in urls: try: if ( fetch is fetch_bytes and item.get("size", 0) > 64 * 1024**2 and shutil.which("aria2c") ): child_path(target, item["rfilename"] + ".incomplete.aria2") args = [ "aria2c", "--continue=true", "--auto-file-renaming=false", "--allow-overwrite=true", "--file-allocation=none", "--split=4", "--max-connection-per-server=4", "--max-tries=4", "--dir=" + str(partial.parent), "--out=" + partial.name, ] if item.get("lfs", {}).get("sha256"): args.append("--checksum=sha-256=" + item["lfs"]["sha256"]) subprocess.run(args + [url], check=True, timeout=21600) else: fetch(url, partial) if not checksum(partial, item): raise ValueError("Canonical checksum mismatch") if path.exists(): raise ValueError( "Target appeared while downloading; refusing overwrite" ) partial.replace(path) return path except (OSError, ValueError, subprocess.SubprocessError) as exc: failures.append(str(exc)) if partial.exists() and not checksum(partial, item): partial.unlink() raise ValueError("Download/checksum verification failed: " + "; ".join(failures)) def load_metadata(directory, cache_name, repo, revision, offline=False): path = child_path(directory, cache_name) if not path.exists(): if offline: raise ValueError("Missing canonical metadata cache: " + cache_name) path.parent.mkdir(parents=True, exist_ok=True) with urlopen( f"https://huggingface.co/api/models/{repo}/revision/{revision}?blobs=true", timeout=120, ) as response: data = json.load(response) if data.get("sha") != revision or data.get("id") != repo: raise ValueError("Unexpected canonical repository/revision") with path.open("x", encoding="utf-8") as handle: json.dump(data, handle) return json.loads(path.read_text(encoding="utf-8")) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--workspace", type=Path, default=Path("/workspace")) parser.add_argument("--metadata-dir", type=Path, required=True) parser.add_argument( "--verify-only", action="store_true", help="No network and no file modifications", ) args = parser.parse_args(argv) workspace = args.workspace.resolve(strict=True) metadata = confined(workspace, args.metadata_dir) for folder, repo, revision, kind, cache in SPECS: selected = validate_metadata( load_metadata(metadata, cache, repo, revision, args.verify_only), repo, revision, kind, ) target = child_path(workspace, "models/" + folder) for item in selected: path = child_path(target, item["rfilename"]) if args.verify_only: if not checksum(path, item): raise ValueError("Model checksum mismatch: " + str(path)) else: download_file(repo, revision, item, target) print( json.dumps( { "repo": repo, "revision": revision, "verified_files": len(selected), "validated": False, } ) ) code = child_path(workspace, "models/wan2.2-animate-preprocess/code") for name, expected in CODE_FILES.items(): path = child_path(code, name) if path.exists(): if hash_file(path) != expected: raise ValueError( "Existing preprocessing code differs from pinned source" ) elif args.verify_only: raise ValueError("Missing pinned preprocessing code: " + name) else: path.parent.mkdir(parents=True, exist_ok=True) partial = child_path(code, name + ".incomplete") fetch_bytes( f"https://raw.githubusercontent.com/{CODE_REPO}/{CODE_REVISION}/{CODE_PREFIX}/{name}", partial, ) if hash_file(partial) != expected: raise ValueError("Pinned preprocessing source checksum mismatch") if path.exists(): raise ValueError("Source appeared during download; refusing overwrite") partial.replace(path) print( json.dumps( { "code_revision": CODE_REVISION, "verified_files": len(CODE_FILES), "validated": False, } ) ) return 0 if __name__ == "__main__": raise SystemExit(main())