code-paper / trajectory_project /scripts /download_sam_checkpoint.py
Tinghong-Ye22's picture
Add files using upload-large-folder tool
c3099b3 verified
Raw History Blame Contribute Delete
1.6 kB
#!/usr/bin/env python3
"""Download and verify the SAM ViT-B checkpoint used by v2."""
from __future__ import annotations
import argparse
import hashlib
import shutil
import urllib.request
from pathlib import Path
URL = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
SHA256 = "ec2df62732614e57411cdcf32a23ffdf28910380d03139ee0f4fcbe91eb8c912"
DEFAULT_DEST = Path(__file__).resolve().parents[1] / "models" / "sam_vit_b_01ec64.pth"
def sha256sum(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dest", type=Path, default=DEFAULT_DEST)
args = parser.parse_args()
dest = args.dest.expanduser().resolve()
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and sha256sum(dest) == SHA256:
print(f"Checkpoint already verified: {dest}")
return 0
temporary = dest.with_suffix(dest.suffix + ".download")
with urllib.request.urlopen(URL) as response, temporary.open("wb") as handle:
shutil.copyfileobj(response, handle)
actual = sha256sum(temporary)
if actual != SHA256:
temporary.unlink(missing_ok=True)
raise RuntimeError(f"SHA256 mismatch: expected {SHA256}, got {actual}")
temporary.replace(dest)
print(f"Downloaded and verified: {dest}")
return 0
if __name__ == "__main__":
raise SystemExit(main())