aisop/tools/download_imajev_local.py

101 lines
5.8 KiB
Python

"""Download pinned model files with resumable, verified HTTP ranges (Imajev-2B by default)."""
import argparse
import concurrent.futures
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import urllib.request
MODELS = [
("Qwen/Qwen3.5-2B", "15852e8c16360a2fea060d615a32b45270f8a8fc", "models/Qwen3.5-2B", None),
("mohit67890/imajev-2b", "e8cb9fc6e054a61ee3fdcff3cd20005ea6194588", "adapters/imajev-2b",
{"adapter_config.json", "adapter_model.safetensors", "decision_readout.json", "decision_readout.safetensors", "calibration.json", "README.md", "RELEASE-SPEC.md"}),
]
def digest(path):
with path.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path(r"E:\Imajev"))
parser.add_argument("--workers", type=int, default=16)
parser.add_argument("--modelscope-base", action="store_true", help="Fetch base weights from ModelScope; still require pinned Hugging Face size/SHA-256")
parser.add_argument("--repo", help="Download one other repository instead of the default Imajev pair")
parser.add_argument("--revision", help="Required immutable 40-character revision when --repo is supplied")
parser.add_argument("--modelscope", action="store_true", help="Fetch files from ModelScope, verified against pinned Hugging Face metadata")
args = parser.parse_args()
curl = shutil.which("curl.exe") or shutil.which("curl")
if not curl:
raise RuntimeError("curl is required")
root = args.root.resolve()
if args.repo and (not args.revision or len(args.revision) != 40 or any(c not in "0123456789abcdef" for c in args.revision)):
parser.error("--repo requires an immutable 40-character hexadecimal --revision")
models = [(args.repo, args.revision, "model", None)] if args.repo else MODELS
manifest = []
for repo, revision, folder, allowed in models:
with urllib.request.urlopen(f"https://huggingface.co/api/models/{repo}/revision/{revision}?blobs=true", timeout=30) as response:
metadata = json.load(response)
entry = {"repo": repo, "revision": revision, "files": {}}
for file in metadata["siblings"]:
name = file["rfilename"]
if name == ".gitattributes" or "/" in name or (allowed is not None and name not in allowed):
continue
dest = root / folder / name
dest.parent.mkdir(parents=True, exist_ok=True)
size = file["size"]
expected = file.get("lfs", {}).get("sha256")
if not (dest.exists() and dest.stat().st_size == size and (not expected or digest(dest) == expected)):
url = f"https://huggingface.co/{repo}/resolve/{revision}/{name}"
if args.modelscope or args.modelscope_base and repo == "Qwen/Qwen3.5-2B":
url = f"https://modelscope.cn/models/{repo}/resolve/master/{name}"
print(f"Downloading {repo}/{name}: {size / 1024**2:.1f} MiB", flush=True)
partial = dest.with_name(dest.name + ".partial")
if size > 16 * 1024**2:
part_dir = root / "downloads" / folder.replace("/", "-") / name
part_dir.mkdir(parents=True, exist_ok=True)
chunk = 8 * 1024**2
count = (size + chunk - 1) // chunk
def fetch(index):
start = index * chunk
end = min(size, start + chunk) - 1
part = part_dir / f"{index:05d}.part"
if not part.exists() or part.stat().st_size != end - start + 1:
subprocess.run([curl, "-sS", "-L", "--fail", "--retry", "3", "--connect-timeout", "15", "--max-time", "600",
"-r", f"{start}-{end}", "-o", str(part), url + f"?part={index}"], check=True)
if part.stat().st_size != end - start + 1:
raise RuntimeError(f"Incorrect range length: {part}")
return part
with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(fetch, index) for index in range(count)]
for completed, future in enumerate(concurrent.futures.as_completed(futures), 1):
future.result()
if completed % 25 == 0 or completed == count:
print(f"{repo}/{name}: {completed}/{count} chunks", flush=True)
with partial.open("wb") as output:
for index in range(count):
with (part_dir / f"{index:05d}.part").open("rb") as source:
shutil.copyfileobj(source, output, 8 * 1024**2)
else:
subprocess.run([curl, "-sS", "-L", "--fail", "--retry", "3", "--max-time", "120", "-o", str(partial), url], check=True)
if partial.stat().st_size != size or (expected and digest(partial) != expected):
raise RuntimeError(f"Size/SHA-256 verification failed: {partial}")
partial.replace(dest)
entry["files"][name] = {"sha256": digest(dest), "bytes": size}
manifest.append(entry)
print(f"Verified {repo}", flush=True)
(root / "local-model-manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
if not args.repo:
(root / "artifacts").mkdir(exist_ok=True)
(root / "artifacts/model-local-2b.json").write_text(json.dumps({"repo": MODELS[0][0], "revision": MODELS[0][1], "path": str(root / MODELS[0][2])}, indent=2), encoding="utf-8")
if __name__ == "__main__":
main()