"""Find or download the Segment Anything (SAM) checkpoint used by the VLM node.
The checkpoints are downloaded from Meta's official release (https://github.com/facebookresearch/segment-anything#model-checkpoints).
Search order in :func:`resolve_sam_checkpoint`:
1. ``$SAM_MODEL_PATH`` if it points to an existing file;
2. ``checkpoint`` itself if it is an existing (absolute or ``~``) path;
3. the checkpoint file name in each directory of ``search_dirs``;
4. the toolkit cache, ``$TCC_IRONL_MODELS`` or ``~/.cache/tcc_ironl``.
"""
import os
import shutil
import sys
import urllib.request
from typing import Iterable, Optional
_BASE_URL = "https://dl.fbaipublicfiles.com/segment_anything/"
#: model type -> official checkpoint file name
SAM_CHECKPOINTS = {
"vit_b": "sam_vit_b_01ec64.pth", # ~375 MB, the default
"vit_l": "sam_vit_l_0b3195.pth", # ~1.2 GB
"vit_h": "sam_vit_h_4b8939.pth", # ~2.6 GB
}
def sam_url(model_type: str = "vit_b") -> str:
return _BASE_URL + _filename(model_type)
def _filename(model_type: str) -> str:
if model_type not in SAM_CHECKPOINTS:
raise ValueError(f"Unknown SAM model type {model_type!r}; choose {', '.join(SAM_CHECKPOINTS)}")
return SAM_CHECKPOINTS[model_type]
def cache_dir() -> str:
return os.path.expanduser(os.getenv("TCC_IRONL_MODELS") or os.path.join("~", ".cache", "tcc_ironl"))
[docs]
def resolve_sam_checkpoint(
checkpoint: str = "",
model_type: str = "vit_b",
search_dirs: Iterable[str] = (),
) -> Optional[str]:
"""Return the path of an existing SAM checkpoint, or ``None``."""
env_path = os.getenv("SAM_MODEL_PATH")
if env_path and os.path.isfile(os.path.expanduser(env_path)):
return os.path.abspath(os.path.expanduser(env_path))
checkpoint = os.path.expanduser(checkpoint or "")
if checkpoint and os.path.isabs(checkpoint) and os.path.isfile(checkpoint):
return checkpoint
name = os.path.basename(checkpoint) if checkpoint else _filename(model_type)
for directory in list(search_dirs) + [cache_dir()]:
candidate = os.path.join(os.path.expanduser(directory), name)
if os.path.isfile(candidate):
return os.path.abspath(candidate)
return None
[docs]
def download_sam(model_type: str = "vit_b", dest_dir: Optional[str] = None,
force: bool = False, quiet: bool = False) -> str:
"""Download a SAM checkpoint into ``dest_dir`` (default: :func:`cache_dir`)."""
dest_dir = os.path.expanduser(dest_dir or cache_dir())
os.makedirs(dest_dir, exist_ok=True)
target = os.path.join(dest_dir, _filename(model_type))
if os.path.isfile(target) and not force:
if not quiet:
print(f"Already present: {target}")
return target
url = sam_url(model_type)
tmp = target + ".part"
if not quiet:
print(f"Downloading {url}\n -> {target}")
with urllib.request.urlopen(url) as response, open(tmp, "wb") as out:
total = int(response.headers.get("Content-Length") or 0)
done = 0
while True:
chunk = response.read(1 << 20)
if not chunk:
break
out.write(chunk)
done += len(chunk)
if not quiet and total:
sys.stdout.write(f"\r {done / 1e6:7.1f} / {total / 1e6:.1f} MB")
sys.stdout.flush()
if total and done != total:
os.remove(tmp)
raise IOError(f"Incomplete download of {url}: got {done} of {total} bytes")
shutil.move(tmp, target)
if not quiet:
print()
return target