Skip to content

armgit / rembg

Public Imported from GitHub
0

Rembg is a tool to remove images background

feat: store models in ~/.rembg/models/<model>/ (#844)

Daniel Gatisd3fdebac4b89
diff --git a/README.md b/README.md
index 7c91ef6..ae06798 100644
--- a/README.md
+++ b/README.md
@@ -93,12 +93,14 @@ pip install "rembg[rocm,cli]" # for library + cli
After installation, you can use rembg by typing `rembg` in your terminal.
-The `rembg` command has 4 subcommands, one for each input type:
+The `rembg` command has these subcommands:
- `i` - single files
- `p` - folders (batch processing)
- `s` - HTTP server
- `b` - RGB24 pixel binary stream
+- `d` - download models ahead of time
+- `m` - migrate models from the legacy `~/.u2net` directory
You can get help about the main command using:
@@ -492,20 +494,49 @@ Local ONNX models are automatically downloaded and saved to `~/.u2net/` on first
| Variable | Description |
|----------|-------------|
-| `U2NET_HOME` | Path to the directory where models are stored. Defaults to `$XDG_DATA_HOME/.u2net` (or `~/.u2net` if `XDG_DATA_HOME` is not set). |
-| `XDG_DATA_HOME` | Base data directory used when `U2NET_HOME` is not set. Defaults to `~`. |
+| `REMBG_HOME` | Path to the directory where models are stored. Defaults to `$XDG_DATA_HOME/rembg` (or `~/.rembg` if `XDG_DATA_HOME` is not set). |
+| `XDG_DATA_HOME` | Base data directory used when `REMBG_HOME` is not set. |
+| `U2NET_HOME` | Deprecated. Still honored, and still takes precedence over `REMBG_HOME` when set, so existing setups keep working. Prefer `REMBG_HOME`. |
| `MODEL_CHECKSUM_DISABLED` | When set (e.g. `MODEL_CHECKSUM_DISABLED=1`), disables hash verification for downloaded models. This is useful if you want to use your own custom/converted model files without rembg re-downloading the originals. |
| `OMP_NUM_THREADS` | Sets the number of threads used by ONNX Runtime for inference. |
| `WITHOUTBG_API_KEY` | API key for the `withoutbg` cloud session. [Get 50 free credits with signup](https://withoutbg.com/signup?ref=rembg). |
+### Where models are stored
+
+Each model gets its own directory under `~/.rembg/models/`:
+
+```
+~/.rembg/models/u2net/u2net.onnx
+~/.rembg/models/birefnet-general/birefnet-general.onnx
+~/.rembg/models/sam/sam_vit_b_01ec64.encoder.onnx
+~/.rembg/models/sam/sam_vit_b_01ec64.decoder.onnx
+```
+
+Earlier versions put every model straight into `~/.u2net/`, regardless of its
+architecture. That directory is still read, so upgrading never re-downloads a
+model you already have. New downloads go to the layout above.
+
+To move existing downloads across:
+
+```shell
+rembg m --dry-run # show what would move
+rembg m # copy into the new layout, leaving the originals alone
+```
+
+The originals are kept unless you pass `--delete-source`, so a partial run can
+never lose a multi-gigabyte download. Interrupted downloads leave `tmp*` files
+behind; `--clean-orphans` removes those.
+
### Using custom model files
If you need to use a modified version of a model (e.g. converted to a different ONNX IR version for compatibility with an older CUDA toolkit), you can prevent rembg from overwriting it:
1. Set `MODEL_CHECKSUM_DISABLED=1`
-2. Place your custom `.onnx` file in the models directory (`~/.u2net/` by default) with the expected filename (e.g. `u2net.onnx`)
+2. Place your custom `.onnx` file in that model's directory (e.g. `~/.rembg/models/u2net/u2net.onnx`) with the expected filename
3. Rembg will detect the file exists and use it without re-downloading
+Paths passed as `model_path` must sit inside `~/.rembg` or the legacy `~/.u2net`; anything else is rejected.
+
## FAQ
### When will this library support Python version 3.xx?
diff --git a/rembg/commands/__init__.py b/rembg/commands/__init__.py
index cc2ac69..a6091b3 100644
--- a/rembg/commands/__init__.py
+++ b/rembg/commands/__init__.py
@@ -3,11 +3,13 @@ command_functions = []
from .b_command import b_command
from .d_command import d_command
from .i_command import i_command
+from .m_command import m_command
from .p_command import p_command
from .s_command import s_command
command_functions.append(b_command)
command_functions.append(d_command)
command_functions.append(i_command)
+command_functions.append(m_command)
command_functions.append(p_command)
command_functions.append(s_command)
diff --git a/rembg/commands/m_command.py b/rembg/commands/m_command.py
new file mode 100644
index 0000000..c4e4cb8
--- /dev/null
+++ b/rembg/commands/m_command.py
@@ -0,0 +1,162 @@
+import os
+import pathlib
+import shutil
+
+import click
+
+from ..sessions import sessions_class
+from ..sessions.base import BaseSession
+
+
+def _model_for_file(fname: str) -> str | None:
+ """Work out which model a file in the old flat directory belongs to.
+
+ Returns None for anything unrecognised, so migration never guesses.
+ """
+ names = []
+ for session_class in sessions_class:
+ try:
+ names.append(session_class.name())
+ except Exception:
+ continue
+
+ # SAM ships several files, all sharing a `sam_` prefix.
+ if fname.startswith("sam_"):
+ return "sam" if "sam" in names else None
+
+ stem = fname[: -len(".onnx")] if fname.endswith(".onnx") else fname
+ return stem if stem in names else None
+
+
+def _is_orphan(fname: str) -> bool:
+ """Whether a file is a leftover from an interrupted download."""
+ return fname.startswith("tmp") and "." not in fname
+
+
[email protected]( # type: ignore
+ name="m",
+ help="migrate models from the legacy ~/.u2net directory",
+)
+ "--dry-run",
+ is_flag=True,
+ show_default=True,
+ help="show what would happen without touching any file",
+)
+ "--delete-source",
+ is_flag=True,
+ show_default=True,
+ help="remove each file from the legacy directory once it is copied",
+)
+ "--clean-orphans",
+ is_flag=True,
+ show_default=True,
+ help="also delete leftover tmp files from interrupted downloads",
+)
+def m_command(dry_run: bool, delete_source: bool, clean_orphans: bool) -> None:
+ """
+ Move downloaded models from the old flat layout into the per-model one.
+
+ Files are copied, not moved, unless --delete-source is passed: a partial
+ migration should never be able to lose a multi-gigabyte download.
+ """
+ legacy = pathlib.Path(BaseSession.legacy_home())
+ target_root = pathlib.Path(BaseSession.rembg_home())
+
+ if legacy == target_root:
+ click.echo(
+ "Legacy and current directories are the same "
+ f"({legacy}); nothing to migrate.",
+ err=True,
+ )
+ return
+
+ if not legacy.is_dir():
+ click.echo(f"No legacy directory at {legacy}; nothing to migrate.")
+ return
+
+ entries = sorted(p for p in legacy.iterdir() if p.is_file())
+ if not entries:
+ click.echo(f"Legacy directory {legacy} is empty; nothing to migrate.")
+ return
+
+ planned: list[tuple[pathlib.Path, pathlib.Path]] = []
+ orphans: list[pathlib.Path] = []
+ skipped: list[tuple[pathlib.Path, str]] = []
+ reclaimable: list[pathlib.Path] = []
+
+ for src in entries:
+ if _is_orphan(src.name):
+ orphans.append(src)
+ continue
+
+ model = _model_for_file(src.name)
+ if model is None:
+ skipped.append((src, "unrecognised file"))
+ continue
+
+ dst = target_root / "models" / model / src.name
+ if dst.exists():
+ # Already copied by an earlier run. Only reclaimable if the copy is
+ # intact, otherwise leave the original alone.
+ if delete_source and dst.stat().st_size == src.stat().st_size:
+ reclaimable.append(src)
+ else:
+ skipped.append((src, "already present in the new layout"))
+ continue
+
+ planned.append((src, dst))
+
+ prefix = "[dry-run] " if dry_run else ""
+
+ for src, dst in planned:
+ size_mb = src.stat().st_size / (1024 * 1024)
+ click.echo(f"{prefix}{src.name} -> {dst.parent} ({size_mb:.1f} MB)")
+
+ if dry_run:
+ continue
+
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ # Copy first, then unlink, so an interrupted run cannot lose the file.
+ shutil.copy2(src, dst)
+ if delete_source:
+ os.remove(src)
+
+ for src in reclaimable:
+ size_mb = src.stat().st_size / (1024 * 1024)
+ click.echo(
+ f"{prefix}removing {src.name} from the legacy directory "
+ f"(already migrated, {size_mb:.1f} MB)"
+ )
+ if not dry_run:
+ os.remove(src)
+
+ for src, reason in skipped:
+ click.echo(f"{prefix}skipped {src.name}: {reason}")
+
+ if orphans:
+ total_mb = sum(p.stat().st_size for p in orphans) / (1024 * 1024)
+ if clean_orphans:
+ for src in orphans:
+ click.echo(f"{prefix}removing orphan {src.name}")
+ if not dry_run:
+ os.remove(src)
+ else:
+ click.echo(
+ f"{prefix}found {len(orphans)} leftover download file(s) "
+ f"totalling {total_mb:.1f} MB; pass --clean-orphans to delete them"
+ )
+
+ click.echo(
+ f"{prefix}migrated {len(planned)} file(s), "
+ f"reclaimed {len(reclaimable)}, "
+ f"skipped {len(skipped)}, orphans {len(orphans)}"
+ )
+
+ if planned and not delete_source and not dry_run:
+ click.echo(
+ f"The originals are still in {legacy}. "
+ "Re-run with --delete-source once you have verified the new layout."
+ )
diff --git a/rembg/sessions/base.py b/rembg/sessions/base.py
index 32df82a..91b908a 100644
--- a/rembg/sessions/base.py
+++ b/rembg/sessions/base.py
@@ -46,7 +46,7 @@ class BaseSession:
std: Tuple[float, float, float],
size: Tuple[int, int],
*args,
- **kwargs
+ **kwargs,
) -> Dict[str, np.ndarray]:
im = img.convert("RGB").resize(size, Image.Resampling.LANCZOS)
@@ -101,13 +101,96 @@ class BaseSession:
return os.getenv("MODEL_CHECKSUM_DISABLED", None) is not None
@classmethod
- def u2net_home(cls, *args, **kwargs):
+ def legacy_home(cls, *args, **kwargs):
+ """The pre-0.0.0 flat model directory, kept for reading only.
+
+ Models used to live directly in `~/.u2net`, whatever their architecture.
+ Nothing is written here anymore, but existing downloads are still found
+ so upgrading does not force a re-download.
+ """
return os.path.expanduser(
os.getenv(
"U2NET_HOME", os.path.join(os.getenv("XDG_DATA_HOME", "~"), ".u2net")
)
)
+ @classmethod
+ def rembg_home(cls, *args, **kwargs):
+ """Root directory for rembg data.
+
+ `U2NET_HOME` still wins when set, so anyone who already points it at a
+ shared or pre-seeded directory keeps working.
+ """
+ if os.getenv("U2NET_HOME"):
+ return cls.legacy_home(*args, **kwargs)
+
+ xdg = os.getenv("XDG_DATA_HOME")
+ default = os.path.join(xdg, "rembg") if xdg else os.path.join("~", ".rembg")
+
+ return os.path.expanduser(os.getenv("REMBG_HOME", default))
+
+ @classmethod
+ def u2net_home(cls, *args, **kwargs):
+ """Deprecated alias for `rembg_home`.
+
+ Kept because third-party code calls it. New code should use
+ `rembg_home` for the root or `model_dir` for a model's own directory.
+ """
+ return cls.rembg_home(*args, **kwargs)
+
+ @classmethod
+ def model_dir(cls, *args, **kwargs):
+ """Directory holding this model's files: `<home>/models/<name>`."""
+ return os.path.join(
+ cls.rembg_home(*args, **kwargs), "models", cls.name(*args, **kwargs)
+ )
+
+ @classmethod
+ def resolve_existing(cls, fname, *args, **kwargs):
+ """Return an already-downloaded copy of `fname`, or None.
+
+ Looks in the per-model directory first, then in the old flat layout, so
+ a model downloaded by an earlier version is reused instead of fetched
+ again.
+ """
+ candidates = [
+ os.path.join(cls.model_dir(*args, **kwargs), fname),
+ os.path.join(cls.legacy_home(*args, **kwargs), fname),
+ ]
+
+ for path in candidates:
+ if os.path.exists(path):
+ return path
+
+ return None
+
+ @classmethod
+ def validate_model_path(cls, *args, **kwargs):
+ """Resolve the caller's `model_path`, refusing anything outside the
+ model directories.
+
+ Both the current root and the legacy one are accepted, so a custom model
+ that was placed under `~/.u2net` keeps loading after the move.
+ """
+ model_path = kwargs.get("model_path")
+ if model_path is None:
+ raise ValueError("model_path is required")
+
+ abs_path = os.path.abspath(os.path.expanduser(model_path))
+
+ allowed = [
+ os.path.abspath(cls.rembg_home(*args, **kwargs)),
+ os.path.abspath(cls.legacy_home(*args, **kwargs)),
+ ]
+
+ for root in allowed:
+ if abs_path == root or abs_path.startswith(root + os.sep):
+ return abs_path
+
+ raise ValueError(
+ f"model_path must be within the models directory: {allowed[0]}"
+ )
+
@classmethod
def download_models(cls, *args, **kwargs):
raise NotImplementedError
diff --git a/rembg/sessions/ben_custom.py b/rembg/sessions/ben_custom.py
index 4823631..6875a39 100644
--- a/rembg/sessions/ben_custom.py
+++ b/rembg/sessions/ben_custom.py
@@ -1,4 +1,3 @@
-import os
from typing import List
import numpy as np
@@ -71,17 +70,7 @@ class BenCustomSession(BaseSession):
Returns:
str: The absolute path to the model files.
"""
- model_path = kwargs.get("model_path")
- if model_path is None:
- raise ValueError("model_path is required")
-
- abs_path = os.path.abspath(os.path.expanduser(model_path))
- allowed_dir = os.path.abspath(os.path.expanduser(cls.u2net_home()))
- if not abs_path.startswith(allowed_dir + os.sep) and abs_path != allowed_dir:
- raise ValueError(
- f"model_path must be within the models directory: {allowed_dir}"
- )
- return abs_path
+ return cls.validate_model_path(*args, **kwargs)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_cod.py b/rembg/sessions/birefnet_cod.py
index d678f1a..3aff5af 100644
--- a/rembg/sessions/birefnet_cod.py
+++ b/rembg/sessions/birefnet_cod.py
@@ -23,6 +23,10 @@ class BiRefNetSessionCOD(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-COD-epoch_125.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionCOD(BiRefNetSessionGeneral):
else "md5:f6d0d21ca89d287f17e7afe9f5fd3b45"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_dis.py b/rembg/sessions/birefnet_dis.py
index 76bdb85..405f9f6 100644
--- a/rembg/sessions/birefnet_dis.py
+++ b/rembg/sessions/birefnet_dis.py
@@ -23,6 +23,10 @@ class BiRefNetSessionDIS(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-DIS-epoch_590.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionDIS(BiRefNetSessionGeneral):
else "md5:2d4d44102b446f33a4ebb2e56c051f2b"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_general.py b/rembg/sessions/birefnet_general.py
index 3fa1dca..424dea2 100644
--- a/rembg/sessions/birefnet_general.py
+++ b/rembg/sessions/birefnet_general.py
@@ -62,6 +62,10 @@ class BiRefNetSessionGeneral(BaseSession):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-epoch_244.onnx",
(
@@ -70,11 +74,11 @@ class BiRefNetSessionGeneral(BaseSession):
else "md5:7a35a0141cbbc80de11d9c9a28f52697"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_general_lite.py b/rembg/sessions/birefnet_general_lite.py
index 6196712..b3e0832 100644
--- a/rembg/sessions/birefnet_general_lite.py
+++ b/rembg/sessions/birefnet_general_lite.py
@@ -23,6 +23,10 @@ class BiRefNetSessionGeneralLite(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionGeneralLite(BiRefNetSessionGeneral):
else "md5:4fab47adc4ff364be1713e97b7e66334"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_hrsod.py b/rembg/sessions/birefnet_hrsod.py
index 2260a20..22f7163 100644
--- a/rembg/sessions/birefnet_hrsod.py
+++ b/rembg/sessions/birefnet_hrsod.py
@@ -23,6 +23,10 @@ class BiRefNetSessionHRSOD(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-HRSOD_DHU-epoch_115.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionHRSOD(BiRefNetSessionGeneral):
else "md5:c017ade5de8a50ff0fd74d790d268dda"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_massive.py b/rembg/sessions/birefnet_massive.py
index 79233b8..2138de0 100644
--- a/rembg/sessions/birefnet_massive.py
+++ b/rembg/sessions/birefnet_massive.py
@@ -23,6 +23,10 @@ class BiRefNetSessionMassive(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-massive-TR_DIS5K_TR_TEs-epoch_420.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionMassive(BiRefNetSessionGeneral):
else "md5:33e726a2136a3d59eb0fdf613e31e3e9"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/birefnet_portrait.py b/rembg/sessions/birefnet_portrait.py
index e6a5835..225a424 100644
--- a/rembg/sessions/birefnet_portrait.py
+++ b/rembg/sessions/birefnet_portrait.py
@@ -23,6 +23,10 @@ class BiRefNetSessionPortrait(BiRefNetSessionGeneral):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-portrait-epoch_150.onnx",
(
@@ -31,11 +35,11 @@ class BiRefNetSessionPortrait(BiRefNetSessionGeneral):
else "md5:c3a64a6abf20250d090cd055f12a3b67"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/bria_rmbg.py b/rembg/sessions/bria_rmbg.py
index a1bda82..8a25c7f 100644
--- a/rembg/sessions/bria_rmbg.py
+++ b/rembg/sessions/bria_rmbg.py
@@ -59,6 +59,10 @@ class BriaRmBgSession(BaseSession):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/bria-rmbg-2.0.onnx",
(
@@ -67,11 +71,11 @@ class BriaRmBgSession(BaseSession):
else "sha256:5b486f08200f513f460da46dd701db5fbb47d79b4be4b708a19444bcd4e79958"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/dis_anime.py b/rembg/sessions/dis_anime.py
index 33d09a7..21cd646 100644
--- a/rembg/sessions/dis_anime.py
+++ b/rembg/sessions/dis_anime.py
@@ -57,6 +57,10 @@ class DisSession(BaseSession):
str: The path of the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/isnet-anime.onnx",
(
@@ -65,11 +69,11 @@ class DisSession(BaseSession):
else "md5:6f184e756bb3bd901c8849220a83e38e"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/dis_custom.py b/rembg/sessions/dis_custom.py
index fb1365e..691d2e2 100644
--- a/rembg/sessions/dis_custom.py
+++ b/rembg/sessions/dis_custom.py
@@ -1,4 +1,3 @@
-import os
from typing import List
import numpy as np
@@ -70,17 +69,7 @@ class DisCustomSession(BaseSession):
Returns:
str: The absolute path to the model files.
"""
- model_path = kwargs.get("model_path")
- if model_path is None:
- raise ValueError("model_path is required")
-
- abs_path = os.path.abspath(os.path.expanduser(model_path))
- allowed_dir = os.path.abspath(os.path.expanduser(cls.u2net_home()))
- if not abs_path.startswith(allowed_dir + os.sep) and abs_path != allowed_dir:
- raise ValueError(
- f"model_path must be within the models directory: {allowed_dir}"
- )
- return abs_path
+ return cls.validate_model_path(*args, **kwargs)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/dis_general_use.py b/rembg/sessions/dis_general_use.py
index e5f1d88..eb1a94e 100644
--- a/rembg/sessions/dis_general_use.py
+++ b/rembg/sessions/dis_general_use.py
@@ -55,6 +55,10 @@ class DisSession(BaseSession):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/isnet-general-use.onnx",
(
@@ -63,11 +67,11 @@ class DisSession(BaseSession):
else "md5:fc16ebd8b0c10d971d3513d564d01e29"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/sam.py b/rembg/sessions/sam.py
index 9766275..fe55aa1 100644
--- a/rembg/sessions/sam.py
+++ b/rembg/sessions/sam.py
@@ -320,11 +320,29 @@ class SamSession(BaseSession):
fname_encoder = f"{model_name}.encoder.quant.onnx"
fname_decoder = f"{model_name}.decoder.quant.onnx"
+ existing_encoder = cls.resolve_existing(fname_encoder, *args, **kwargs)
+ existing_decoder = cls.resolve_existing(fname_decoder, *args, **kwargs)
+
+ # The large encoder loads `encoder_data.bin` as a sidecar from its own
+ # directory, so encoder and blob have to stay together. Only reuse a
+ # previous download when the whole set is present in one place.
+ if existing_encoder is not None and existing_decoder is not None:
+ base = os.path.dirname(existing_encoder)
+ needs_blob = fname_encoder == "sam_vit_h_4b8939.encoder.onnx"
+ blob_ok = not needs_blob or os.path.exists(
+ os.path.join(base, "sam_vit_h_4b8939.encoder_data.bin")
+ )
+
+ if os.path.dirname(existing_decoder) == base and blob_ok:
+ return (existing_encoder, existing_decoder)
+
+ target = cls.model_dir(*args, **kwargs)
+
pooch.retrieve(
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_encoder}",
None,
fname=fname_encoder,
- path=cls.u2net_home(*args, **kwargs),
+ path=target,
progressbar=True,
)
@@ -332,14 +350,12 @@ class SamSession(BaseSession):
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_decoder}",
None,
fname=fname_decoder,
- path=cls.u2net_home(*args, **kwargs),
+ path=target,
progressbar=True,
)
if fname_encoder == "sam_vit_h_4b8939.encoder.onnx" and not os.path.exists(
- os.path.join(
- cls.u2net_home(*args, **kwargs), "sam_vit_h_4b8939.encoder_data.bin"
- )
+ os.path.join(target, "sam_vit_h_4b8939.encoder_data.bin")
):
content = bytearray()
@@ -348,29 +364,26 @@ class SamSession(BaseSession):
f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/sam_vit_h_4b8939.encoder_data.{i}.bin",
None,
fname=f"sam_vit_h_4b8939.encoder_data.{i}.bin",
- path=cls.u2net_home(*args, **kwargs),
+ path=target,
progressbar=True,
)
fbin = os.path.join(
- cls.u2net_home(*args, **kwargs),
+ target,
f"sam_vit_h_4b8939.encoder_data.{i}.bin",
)
content.extend(open(fbin, "rb").read())
os.remove(fbin)
with open(
- os.path.join(
- cls.u2net_home(*args, **kwargs),
- "sam_vit_h_4b8939.encoder_data.bin",
- ),
+ os.path.join(target, "sam_vit_h_4b8939.encoder_data.bin"),
"wb",
) as fp:
fp.write(content)
return (
- os.path.join(cls.u2net_home(*args, **kwargs), fname_encoder),
- os.path.join(cls.u2net_home(*args, **kwargs), fname_decoder),
+ os.path.join(target, fname_encoder),
+ os.path.join(target, fname_decoder),
)
@classmethod
diff --git a/rembg/sessions/silueta.py b/rembg/sessions/silueta.py
index 574a33c..d7f54fb 100644
--- a/rembg/sessions/silueta.py
+++ b/rembg/sessions/silueta.py
@@ -61,6 +61,10 @@ class SiluetaSession(BaseSession):
str: The path to the downloaded model file.
"""
fname = f"{cls.name()}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/silueta.onnx",
(
@@ -69,11 +73,11 @@ class SiluetaSession(BaseSession):
else "md5:55e59e0d8062d2f5d013f4725ee84782"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/u2net.py b/rembg/sessions/u2net.py
index 88922ae..6fd046a 100644
--- a/rembg/sessions/u2net.py
+++ b/rembg/sessions/u2net.py
@@ -59,6 +59,10 @@ class U2netSession(BaseSession):
str: The path to the downloaded model file.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx",
(
@@ -67,11 +71,11 @@ class U2netSession(BaseSession):
else "md5:60024c5c889badc19c04ad937298a77b"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/u2net_cloth_seg.py b/rembg/sessions/u2net_cloth_seg.py
index 3e12b68..3b4856a 100644
--- a/rembg/sessions/u2net_cloth_seg.py
+++ b/rembg/sessions/u2net_cloth_seg.py
@@ -124,6 +124,10 @@ class Unet2ClothSession(BaseSession):
@classmethod
def download_models(cls, *args, **kwargs):
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net_cloth_seg.onnx",
(
@@ -132,11 +136,11 @@ class Unet2ClothSession(BaseSession):
else "md5:2434d1f3cb744e0e49386c906e5a08bb"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/u2net_custom.py b/rembg/sessions/u2net_custom.py
index 2e8f12b..0d672c3 100644
--- a/rembg/sessions/u2net_custom.py
+++ b/rembg/sessions/u2net_custom.py
@@ -1,9 +1,7 @@
-import os
from typing import List
import numpy as np
import onnxruntime as ort
-import pooch
from PIL import Image
from PIL.Image import Image as PILImage
@@ -76,17 +74,7 @@ class U2netCustomSession(BaseSession):
Returns:
str: The absolute path to the model files.
"""
- model_path = kwargs.get("model_path")
- if model_path is None:
- raise ValueError("model_path is required")
-
- abs_path = os.path.abspath(os.path.expanduser(model_path))
- allowed_dir = os.path.abspath(os.path.expanduser(cls.u2net_home()))
- if not abs_path.startswith(allowed_dir + os.sep) and abs_path != allowed_dir:
- raise ValueError(
- f"model_path must be within the models directory: {allowed_dir}"
- )
- return abs_path
+ return cls.validate_model_path(*args, **kwargs)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/u2net_human_seg.py b/rembg/sessions/u2net_human_seg.py
index 170e5ab..68f8ddf 100644
--- a/rembg/sessions/u2net_human_seg.py
+++ b/rembg/sessions/u2net_human_seg.py
@@ -59,6 +59,10 @@ class U2netHumanSegSession(BaseSession):
str: The path to the downloaded model weights.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net_human_seg.onnx",
(
@@ -67,11 +71,11 @@ class U2netHumanSegSession(BaseSession):
else "md5:c09ddc2e0104f800e3e1bb4652583d1f"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/rembg/sessions/u2netp.py b/rembg/sessions/u2netp.py
index 2988afd..3a4536b 100644
--- a/rembg/sessions/u2netp.py
+++ b/rembg/sessions/u2netp.py
@@ -51,6 +51,10 @@ class U2netpSession(BaseSession):
str: The path to the downloaded model.
"""
fname = f"{cls.name(*args, **kwargs)}.onnx"
+ existing = cls.resolve_existing(fname, *args, **kwargs)
+ if existing is not None:
+ return existing
+
pooch.retrieve(
"https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2netp.onnx",
(
@@ -59,11 +63,11 @@ class U2netpSession(BaseSession):
else "md5:8e83ca70e441ab06c318d82300c84806"
),
fname=fname,
- path=cls.u2net_home(*args, **kwargs),
+ path=cls.model_dir(*args, **kwargs),
progressbar=True,
)
- return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+ return os.path.join(cls.model_dir(*args, **kwargs), fname)
@classmethod
def name(cls, *args, **kwargs):
diff --git a/tests/test_migrate.py b/tests/test_migrate.py
new file mode 100644
index 0000000..1680c51
--- /dev/null
+++ b/tests/test_migrate.py
@@ -0,0 +1,125 @@
+import pytest
+from click.testing import CliRunner
+
+from rembg.commands.m_command import m_command
+
+
+def layout(monkeypatch, tmp_path):
+ """A legacy directory with a few files, and an empty destination."""
+ monkeypatch.delenv("U2NET_HOME", raising=False)
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "legacy_base"))
+ monkeypatch.setenv("REMBG_HOME", str(tmp_path / "new"))
+
+ legacy = tmp_path / "legacy_base" / ".u2net"
+ legacy.mkdir(parents=True)
+
+ (legacy / "u2net.onnx").write_text("u2net")
+ (legacy / "silueta.onnx").write_text("silueta")
+ (legacy / "sam_vit_b_01ec64.encoder.onnx").write_text("enc")
+ (legacy / "sam_vit_b_01ec64.decoder.onnx").write_text("dec")
+ (legacy / "unknown-thing.onnx").write_text("mystery")
+ (legacy / "tmpABC123").write_text("interrupted download")
+
+ return {"legacy": legacy, "new": tmp_path / "new"}
+
+
+def test_dry_run_touches_nothing(layout):
+ result = CliRunner().invoke(m_command, ["--dry-run"])
+
+ assert result.exit_code == 0
+ assert not layout["new"].exists()
+ assert len(list(layout["legacy"].iterdir())) == 6
+
+
+def test_migrate_copies_into_per_model_dirs(layout):
+ result = CliRunner().invoke(m_command, [])
+
+ assert result.exit_code == 0
+ assert (layout["new"] / "models" / "u2net" / "u2net.onnx").read_text() == "u2net"
+ assert (layout["new"] / "models" / "silueta" / "silueta.onnx").exists()
+
+ # Both SAM files belong to the same model directory.
+ sam_dir = layout["new"] / "models" / "sam"
+ assert (sam_dir / "sam_vit_b_01ec64.encoder.onnx").exists()
+ assert (sam_dir / "sam_vit_b_01ec64.decoder.onnx").exists()
+
+
+def test_migrate_keeps_originals_by_default(layout):
+ CliRunner().invoke(m_command, [])
+
+ # Losing a multi-gigabyte download to a half-finished run is unacceptable.
+ assert (layout["legacy"] / "u2net.onnx").exists()
+
+
+def test_unrecognised_files_are_never_moved(layout):
+ CliRunner().invoke(m_command, ["--delete-source", "--clean-orphans"])
+
+ assert (layout["legacy"] / "unknown-thing.onnx").exists()
+ assert not (layout["new"] / "models" / "unknown-thing").exists()
+
+
+def test_orphans_are_kept_unless_asked(layout):
+ CliRunner().invoke(m_command, [])
+ assert (layout["legacy"] / "tmpABC123").exists()
+
+
+def test_clean_orphans_removes_them(layout):
+ CliRunner().invoke(m_command, ["--clean-orphans"])
+ assert not (layout["legacy"] / "tmpABC123").exists()
+
+
+def test_migrate_is_idempotent(layout):
+ first = CliRunner().invoke(m_command, [])
+ second = CliRunner().invoke(m_command, [])
+
+ assert first.exit_code == 0
+ assert second.exit_code == 0
+ assert "migrated 0 file(s)" in second.output
+
+
+def test_second_pass_reclaims_already_migrated_files(layout):
+ """Copy first, delete later: the documented two-step flow must free space."""
+ CliRunner().invoke(m_command, [])
+ assert (layout["legacy"] / "u2net.onnx").exists()
+
+ result = CliRunner().invoke(m_command, ["--delete-source"])
+
+ assert result.exit_code == 0
+ assert not (layout["legacy"] / "u2net.onnx").exists()
+ assert (layout["new"] / "models" / "u2net" / "u2net.onnx").exists()
+
+
+def test_mismatched_copy_is_left_alone(layout):
+ """A truncated destination must not license deleting the source."""
+ CliRunner().invoke(m_command, [])
+
+ dst = layout["new"] / "models" / "u2net" / "u2net.onnx"
+ dst.write_text("") # simulate a partial copy
+
+ CliRunner().invoke(m_command, ["--delete-source"])
+
+ assert (layout["legacy"] / "u2net.onnx").exists()
+
+
+def test_missing_legacy_dir_is_not_an_error(monkeypatch, tmp_path):
+ monkeypatch.delenv("U2NET_HOME", raising=False)
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "nothing_here"))
+ monkeypatch.setenv("REMBG_HOME", str(tmp_path / "new"))
+
+ result = CliRunner().invoke(m_command, [])
+
+ assert result.exit_code == 0
+ assert "nothing to migrate" in result.output
+
+
+def test_same_source_and_target_is_refused(monkeypatch, tmp_path):
+ """With U2NET_HOME set, both roots collapse to one; migrating is a no-op."""
+ monkeypatch.setenv("U2NET_HOME", str(tmp_path / "shared"))
+ monkeypatch.delenv("REMBG_HOME", raising=False)
+ (tmp_path / "shared").mkdir()
+
+ result = CliRunner().invoke(m_command, [])
+
+ assert result.exit_code == 0
+ assert "nothing to migrate" in result.output
diff --git a/tests/test_model_home.py b/tests/test_model_home.py
new file mode 100644
index 0000000..122e8a9
--- /dev/null
+++ b/tests/test_model_home.py
@@ -0,0 +1,117 @@
+import os
+
+import pytest
+
+from rembg.sessions.base import BaseSession
+from rembg.sessions.u2net import U2netSession
+
+
+def clean_env(monkeypatch):
+ """Start from an environment where none of the path variables are set."""
+ for var in ("U2NET_HOME", "REMBG_HOME", "XDG_DATA_HOME"):
+ monkeypatch.delenv(var, raising=False)
+ return monkeypatch
+
+
+def test_defaults_to_dot_rembg(clean_env):
+ assert U2netSession.rembg_home() == os.path.expanduser("~/.rembg")
+
+
+def test_rembg_home_env_wins_over_default(clean_env):
+ clean_env.setenv("REMBG_HOME", "/tmp/somewhere")
+ assert U2netSession.rembg_home() == "/tmp/somewhere"
+
+
+def test_xdg_data_home_has_no_leading_dot(clean_env):
+ """XDG_DATA_HOME is already a data directory, so the child is not hidden."""
+ clean_env.setenv("XDG_DATA_HOME", "/tmp/xdg")
+ assert U2netSession.rembg_home() == "/tmp/xdg/rembg"
+
+
+def test_legacy_env_still_takes_precedence(clean_env):
+ """Anyone already pointing U2NET_HOME somewhere keeps that directory."""
+ clean_env.setenv("U2NET_HOME", "/tmp/legacy")
+ clean_env.setenv("REMBG_HOME", "/tmp/new")
+ assert U2netSession.rembg_home() == "/tmp/legacy"
+
+
+def test_u2net_home_is_an_alias_for_rembg_home(clean_env):
+ assert U2netSession.u2net_home() == U2netSession.rembg_home()
+
+
+def test_model_dir_is_per_model(clean_env):
+ clean_env.setenv("REMBG_HOME", "/tmp/home")
+ assert U2netSession.model_dir() == "/tmp/home/models/u2net"
+
+
+def test_resolve_existing_prefers_new_layout(clean_env, tmp_path):
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+ clean_env.setenv("U2NET_HOME", "") # empty means unset for the lookup below
+
+ new_dir = tmp_path / "new" / "models" / "u2net"
+ new_dir.mkdir(parents=True)
+ (new_dir / "u2net.onnx").write_text("new")
+
+ assert U2netSession.resolve_existing("u2net.onnx") == str(new_dir / "u2net.onnx")
+
+
+def test_resolve_existing_falls_back_to_legacy(clean_env, tmp_path):
+ """A model downloaded by an older version must not be fetched again."""
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+ clean_env.setenv("XDG_DATA_HOME", str(tmp_path / "legacy_base"))
+
+ legacy_dir = tmp_path / "legacy_base" / ".u2net"
+ legacy_dir.mkdir(parents=True)
+ (legacy_dir / "u2net.onnx").write_text("old")
+
+ assert U2netSession.resolve_existing("u2net.onnx") == str(legacy_dir / "u2net.onnx")
+
+
+def test_resolve_existing_returns_none_when_absent(clean_env, tmp_path):
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+ clean_env.setenv("XDG_DATA_HOME", str(tmp_path / "legacy_base"))
+
+ assert U2netSession.resolve_existing("u2net.onnx") is None
+
+
+def test_validate_model_path_accepts_both_roots(clean_env, tmp_path):
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+ clean_env.setenv("XDG_DATA_HOME", str(tmp_path / "legacy_base"))
+
+ inside_new = str(tmp_path / "new" / "models" / "custom" / "m.onnx")
+ inside_legacy = str(tmp_path / "legacy_base" / ".u2net" / "m.onnx")
+
+ assert BaseSession.validate_model_path(model_path=inside_new) == inside_new
+ assert BaseSession.validate_model_path(model_path=inside_legacy) == inside_legacy
+
+
+def test_validate_model_path_rejects_outside_paths(clean_env, tmp_path):
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+
+ with pytest.raises(ValueError):
+ BaseSession.validate_model_path(model_path="/etc/passwd")
+
+
+def test_validate_model_path_rejects_traversal(clean_env, tmp_path):
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+
+ with pytest.raises(ValueError):
+ BaseSession.validate_model_path(
+ model_path=str(tmp_path / "new" / ".." / ".." / "etc" / "passwd")
+ )
+
+
+def test_validate_model_path_rejects_sibling_prefix(clean_env, tmp_path):
+ """`/x/.rembg-evil` must not pass because it starts with `/x/.rembg`."""
+ clean_env.setenv("REMBG_HOME", str(tmp_path / "new"))
+
+ with pytest.raises(ValueError):
+ BaseSession.validate_model_path(
+ model_path=str(tmp_path / "new-evil" / "m.onnx")
+ )
+
+
+def test_validate_model_path_requires_the_argument(clean_env):
+ with pytest.raises(ValueError):
+ BaseSession.validate_model_path()