Rembg is a tool to remove images background
Feat/withoutbg session (#836)
Imran Kocabiyikb60806e9e702
diff --git a/README.md b/README.mdindex 301fa58..2a9aa3b 100644--- a/README.md+++ b/README.md@@ -167,6 +167,21 @@ rembg i -m sam -x '{ "sam_prompt": [{"type": "point", "data": [724, 740], "labelrembg i -m u2net_custom -x '{"model_path": "~/.u2net/u2net.onnx"}' path/to/input.png path/to/output.png```+**Use the withoutBG cloud API:**++[Get 50 free credits with signup](https://withoutbg.com/signup?ref=rembg). [Sample results](https://withoutbg.com/pro-model/results?ref=rembg).++```shell+export WITHOUTBG_API_KEY=sk_...+rembg i -m withoutbg path/to/input.png path/to/output.png+```++Or pass the key via extras:++```shell+rembg i -m withoutbg -x '{"api_key":"sk_..."}' path/to/input.png path/to/output.png+```+### rembg `p`Used for batch processing entire folders.@@ -302,6 +317,22 @@ for file in Path('path/to/folder').glob('*.png'):o.write(output)```+**withoutBG cloud API:**++[Get 50 free credits with signup](https://withoutbg.com/signup?ref=rembg). [Sample results](https://withoutbg.com/pro-model/results?ref=rembg).++```python+from rembg import remove, new_session++session = new_session("withoutbg", api_key="sk_...")+# or set WITHOUTBG_API_KEY and omit api_key=++with open('input.png', 'rb') as i:+ with open('output.png', 'wb') as o:+ output = remove(i.read(), session=session)+ o.write(output)+```+For more examples, see the [examples](USAGE.md) page.## Usage with Docker@@ -341,7 +372,7 @@ sudo docker run --rm -it --gpus all -v /dev/dri:/dev/dri -v $PWD:/data rembg-nvi## Models-All models are automatically downloaded and saved to `~/.u2net/` on first use.+Local ONNX models are automatically downloaded and saved to `~/.u2net/` on first use. The `withoutbg` model is a cloud API backend and does not download a local model.### Available Models@@ -361,6 +392,7 @@ All models are automatically downloaded and saved to `~/.u2net/` on first use.- birefnet-cod ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-COD-epoch_125.onnx), [source](https://github.com/ZhengPeng7/BiRefNet)): A pre-trained model for concealed object detection (COD).- birefnet-massive ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-massive-TR_DIS5K_TR_TEs-epoch_420.onnx), [source](https://github.com/ZhengPeng7/BiRefNet)): A pre-trained model with massive dataset.- bria-rmbg ([download](https://github.com/danielgatis/rembg/releases/download/v0.0.0/bria-rmbg-2.0.onnx), [source](https://huggingface.co/briaai/RMBG-2.0)): A state-of-the-art background removal model by BRIA AI.+- withoutbg ([API](https://withoutbg.com/?ref=rembg), [sample results](https://withoutbg.com/pro-model/results?ref=rembg)): Cloud API backend. [Get 50 free credits with signup](https://withoutbg.com/signup?ref=rembg). Pass `api_key` via `-x` / `new_session(...)`, or set `WITHOUTBG_API_KEY`. Images are sent to withoutBG's servers; max upload size is 20 MB.## Environment Variables@@ -370,6 +402,7 @@ All models are automatically downloaded and saved to `~/.u2net/` on first use.| `XDG_DATA_HOME` | Base data directory used when `U2NET_HOME` is not set. Defaults to `~`. || `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). |### Using custom model filesdiff --git a/rembg/sessions/__init__.py b/rembg/sessions/__init__.pyindex 9e9bffd..8abad04 100644--- a/rembg/sessions/__init__.py+++ b/rembg/sessions/__init__.py@@ -82,6 +82,10 @@ from .ben_custom import BenCustomSessionsessions[BenCustomSession.name()] = BenCustomSession+from .withoutbg import WithoutBgSession++sessions[WithoutBgSession.name()] = WithoutBgSession+sessions_names = list(sessions.keys())sessions_class = list(sessions.values())diff --git a/rembg/sessions/withoutbg.py b/rembg/sessions/withoutbg.pynew file mode 100644index 0000000..07c6ac5--- /dev/null+++ b/rembg/sessions/withoutbg.py@@ -0,0 +1,151 @@+import io+import json+import os+import uuid+from typing import List+from urllib import error, request++from PIL import Image+from PIL.Image import Image as PILImage++from .base import BaseSession++API_URL = "https://api.withoutbg.com/v1.0/alpha-channel"+DEFAULT_TIMEOUT = 60+MAX_UPLOAD_BYTES = 20 * 1024 * 1024++try:+ from importlib.metadata import PackageNotFoundError, version++ try:+ _VERSION = version("rembg")+ except PackageNotFoundError:+ _VERSION = "0.0.0"+except ImportError:+ _VERSION = "0.0.0"++USER_AGENT = f"rembg/{_VERSION}"+++class WithoutBgSession(BaseSession):+ """Session that removes backgrounds via the withoutBG cloud API."""++ def __init__(self, model_name: str, sess_opts, *args, **kwargs):+ """+ Initialize a WithoutBgSession.++ Does not call BaseSession.__init__ because no local ONNX model is used.++ Parameters:+ model_name (str): The name of the model.+ sess_opts: Ignored; accepted for BaseSession compatibility.+ *args: Additional positional arguments.+ **kwargs: May include api_key. Falls back to WITHOUTBG_API_KEY.++ Raises:+ ValueError: If no API key is provided.+ """+ self.model_name = model_name+ api_key = kwargs.get("api_key") or os.getenv("WITHOUTBG_API_KEY")+ if not isinstance(api_key, str) or not api_key:+ raise ValueError(+ "withoutbg requires an API key. Pass api_key=... to new_session() "+ "or set the WITHOUTBG_API_KEY environment variable. "+ "Get 50 free credits at https://withoutbg.com/signup?ref=rembg"+ )+ self.api_key: str = api_key+ self.timeout = kwargs.get("timeout", DEFAULT_TIMEOUT)++ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:+ """+ Predict the alpha mask for the input image via the withoutBG API.++ Parameters:+ img (PILImage): The input image.+ *args: Additional positional arguments.+ **kwargs: Additional keyword arguments.++ Returns:+ List[PILImage]: A single-item list with the L-mode alpha mask.++ Raises:+ ValueError: If the PNG-encoded image exceeds the 20 MB upload limit.+ RuntimeError: If the API returns a non-200 response.+ """+ buf = io.BytesIO()+ img.save(buf, format="PNG")+ image_bytes = buf.getvalue()++ if len(image_bytes) > MAX_UPLOAD_BYTES:+ raise ValueError(+ f"withoutbg upload exceeds the {MAX_UPLOAD_BYTES // (1024 * 1024)} MB limit "+ f"({len(image_bytes)} bytes after PNG encode). "+ "Resize or compress the image and try again."+ )++ boundary = f"----rembg{uuid.uuid4().hex}"+ body = (+ (+ f"--{boundary}\r\n"+ f'Content-Disposition: form-data; name="file"; filename="image.png"\r\n'+ f"Content-Type: image/png\r\n\r\n"+ ).encode("utf-8")+ + image_bytes+ + f"\r\n--{boundary}--\r\n".encode("utf-8")+ )++ req = request.Request(+ API_URL,+ data=body,+ method="POST",+ headers={+ "X-API-Key": self.api_key,+ "User-Agent": USER_AGENT,+ "Content-Type": f"multipart/form-data; boundary={boundary}",+ "Content-Length": str(len(body)),+ },+ )++ try:+ with request.urlopen(req, timeout=self.timeout) as resp:+ mask_bytes = resp.read()+ except error.HTTPError as e:+ detail = e.read().decode("utf-8", errors="replace")+ try:+ detail = json.loads(detail).get("detail", detail)+ except (json.JSONDecodeError, AttributeError):+ pass+ raise RuntimeError(f"withoutbg API error ({e.code}): {detail}") from e+ except error.URLError as e:+ raise RuntimeError(f"withoutbg API request failed: {e.reason}") from e++ mask = Image.open(io.BytesIO(mask_bytes)).convert("L")+ if mask.size != img.size:+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)++ return [mask]++ @classmethod+ def is_local(cls, *args, **kwargs) -> bool:+ """Inference runs on withoutBG's servers, not this machine."""+ return False++ @classmethod+ def requires_credentials(cls, *args, **kwargs) -> bool:+ """Construction needs an API key (api_key= or WITHOUTBG_API_KEY)."""+ return True++ @classmethod+ def has_usage_cost(cls, *args, **kwargs) -> bool:+ """Each prediction bills against the withoutBG API key."""+ return True++ @classmethod+ def download_models(cls, *args, **kwargs):+ """No local model to download for the withoutBG cloud API."""+ return ""++ @classmethod+ def name(cls, *args, **kwargs):+ """Return the session name."""+ return "withoutbg"diff --git a/tests/test_withoutbg.py b/tests/test_withoutbg.pynew file mode 100644index 0000000..a944bd0--- /dev/null+++ b/tests/test_withoutbg.py@@ -0,0 +1,115 @@+import io+import json+from unittest.mock import MagicMock, patch+from urllib import error++import pytest+from PIL import Image++from rembg.sessions.withoutbg import MAX_UPLOAD_BYTES, WithoutBgSession+++def _png_bytes(mode: str, size=(32, 24), color=0):+ buf = io.BytesIO()+ Image.new(mode, size, color).save(buf, format="PNG")+ return buf.getvalue()+++def test_missing_api_key_raises(monkeypatch):+ monkeypatch.delenv("WITHOUTBG_API_KEY", raising=False)+ with pytest.raises(ValueError, match="API key"):+ WithoutBgSession("withoutbg", None)+++def test_api_key_from_env(monkeypatch):+ monkeypatch.setenv("WITHOUTBG_API_KEY", "sk_from_env")+ session = WithoutBgSession("withoutbg", None)+ assert session.api_key == "sk_from_env"+++def test_api_key_kwarg_overrides_env(monkeypatch):+ monkeypatch.setenv("WITHOUTBG_API_KEY", "sk_from_env")+ session = WithoutBgSession("withoutbg", None, api_key="sk_kwarg")+ assert session.api_key == "sk_kwarg"+++def test_name_and_download_models():+ assert WithoutBgSession.name() == "withoutbg"+ assert WithoutBgSession.download_models() == ""+++def test_capability_flags():+ assert WithoutBgSession.is_local() is False+ assert WithoutBgSession.requires_credentials() is True+ assert WithoutBgSession.has_usage_cost() is True+++def test_predict_rejects_oversized_upload(monkeypatch):+ monkeypatch.setenv("WITHOUTBG_API_KEY", "sk_test")+ session = WithoutBgSession("withoutbg", None)+ img = Image.new("RGB", (10, 10), (0, 0, 0))++ with patch.object(+ img,+ "save",+ side_effect=lambda buf, *args, **kwargs: buf.write(+ b"x" * (MAX_UPLOAD_BYTES + 1)+ ),+ ):+ with patch("rembg.sessions.withoutbg.request.urlopen") as mock_urlopen:+ with pytest.raises(ValueError, match="20 MB limit"):+ session.predict(img)+ mock_urlopen.assert_not_called()+++def test_predict_returns_mask_matching_input_size(monkeypatch):+ monkeypatch.setenv("WITHOUTBG_API_KEY", "sk_test")+ session = WithoutBgSession("withoutbg", None)++ img = Image.new("RGB", (40, 30), (255, 0, 0))+ # API returns a differently sized mask; session should resize to input.+ mask_bytes = _png_bytes("L", size=(20, 15), color=200)++ mock_resp = MagicMock()+ mock_resp.read.return_value = mask_bytes+ mock_resp.__enter__.return_value = mock_resp+ mock_resp.__exit__.return_value = False++ with patch(+ "rembg.sessions.withoutbg.request.urlopen", return_value=mock_resp+ ) as mock_urlopen:+ masks = session.predict(img)++ assert len(masks) == 1+ assert masks[0].mode == "L"+ assert masks[0].size == img.size++ req = mock_urlopen.call_args[0][0]+ assert req.get_header("X-api-key") == "sk_test"+ assert "multipart/form-data" in req.get_header("Content-type")+ assert b'name="file"' in req.data+++def test_predict_http_error_raises(monkeypatch):+ monkeypatch.setenv("WITHOUTBG_API_KEY", "sk_test")+ session = WithoutBgSession("withoutbg", None)+ img = Image.new("RGB", (10, 10), (0, 0, 0))++ http_error = error.HTTPError(+ url="https://api.withoutbg.com/v1.0/alpha-channel",+ code=401,+ msg="Unauthorized",+ hdrs=None,+ fp=io.BytesIO(json.dumps({"detail": "Invalid API Key"}).encode("utf-8")),+ )++ with patch("rembg.sessions.withoutbg.request.urlopen", side_effect=http_error):+ with pytest.raises(RuntimeError, match="Invalid API Key"):+ session.predict(img)+++def test_session_registered():+ from rembg.sessions import sessions++ assert "withoutbg" in sessions+ assert sessions["withoutbg"] is WithoutBgSession