Skip to content

armgit / rembg

Public Imported from GitHub
0

Rembg is a tool to remove images background

feat: add atlascloud remote session (#854)

nb213dcced408dca8
diff --git a/README.md b/README.md
index 1529a25..6af313b 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,15 @@ export WITHOUTBG_API_KEY=sk_...
rembg i -m withoutbg path/to/input.png path/to/output.png
```
+**Use the Atlas Cloud API (hosted Midjourney background removal):**
+
+```shell
+export ATLASCLOUD_API_KEY=apikey-...
+rembg i -m atlascloud path/to/input.png path/to/output.png
+```
+
+The job is asynchronous and can take over a minute per image. Pick another [Atlas Cloud](https://www.atlascloud.ai) model with `ATLASCLOUD_MODEL` or `-x '{"model": "midjourney/v8.1/remove-background"}'`.
+
Or pass the key via extras:
```shell
@@ -343,6 +352,20 @@ with open('input.png', 'rb') as i:
o.write(output)
```
+**Atlas Cloud API:**
+
+```python
+from rembg import remove, new_session
+
+session = new_session("atlascloud", api_key="apikey-...")
+# or set ATLASCLOUD_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.
## Choosing an edge mode
@@ -506,6 +529,7 @@ Local ONNX models are automatically downloaded on first use and saved under `~/.
- 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)): **The default.** A state-of-the-art background removal model by BRIA AI. At ~1.02 GB it is the largest local model here and runs at 1024x1024, so it is slower than u2net; pass `-m u2net` for a smaller, faster model with blockier edges. Note that RMBG-2.0 is released under a [BRIA license](https://huggingface.co/briaai/RMBG-2.0) that requires a paid agreement for commercial use. Model weights carry their own licenses, independent of rembg's MIT license — check the linked source before using any model commercially.
- 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.
+- atlascloud ([API](https://www.atlascloud.ai)): Cloud API backend running `midjourney/v8.2/remove-background` by default. Pass `api_key` via `-x` / `new_session(...)`, or set `ATLASCLOUD_API_KEY`; change the model with `model` or `ATLASCLOUD_MODEL`. Requests are asynchronous and can take over a minute. Images are sent to Atlas Cloud's servers; max upload size is 20 MB.
## Environment Variables
@@ -517,6 +541,8 @@ Local ONNX models are automatically downloaded on first use and saved under `~/.
| `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). |
+| `ATLASCLOUD_API_KEY` | API key for the `atlascloud` cloud session. |
+| `ATLASCLOUD_MODEL` | Atlas Cloud model used by the `atlascloud` session. Defaults to `midjourney/v8.2/remove-background`. |
### Where models are stored
diff --git a/rembg/sessions/__init__.py b/rembg/sessions/__init__.py
index 8abad04..05a25c7 100644
--- a/rembg/sessions/__init__.py
+++ b/rembg/sessions/__init__.py
@@ -86,6 +86,10 @@ from .withoutbg import WithoutBgSession
sessions[WithoutBgSession.name()] = WithoutBgSession
+from .atlascloud import AtlasCloudSession
+
+sessions[AtlasCloudSession.name()] = AtlasCloudSession
+
sessions_names = list(sessions.keys())
sessions_class = list(sessions.values())
diff --git a/rembg/sessions/atlascloud.py b/rembg/sessions/atlascloud.py
new file mode 100644
index 0000000..25dc487
--- /dev/null
+++ b/rembg/sessions/atlascloud.py
@@ -0,0 +1,218 @@
+import base64
+import io
+import json
+import os
+import time
+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_BASE = "https://api.atlascloud.ai"
+GENERATE_URL = f"{API_BASE}/api/v1/model/generateImage"
+PREDICTION_URL = f"{API_BASE}/api/v1/model/prediction"
+DEFAULT_MODEL = "midjourney/v8.2/remove-background"
+DEFAULT_TIMEOUT = 60
+POLL_INTERVAL = 2
+POLL_TIMEOUT = 180
+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 AtlasCloudSession(BaseSession):
+ """Session that removes backgrounds via the Atlas Cloud API."""
+
+ def __init__(self, model_name: str, sess_opts, *args, **kwargs):
+ """
+ Initialize an AtlasCloudSession.
+
+ 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, model and timeout. api_key falls back
+ to ATLASCLOUD_API_KEY, model to ATLASCLOUD_MODEL.
+
+ Raises:
+ ValueError: If no API key is provided.
+ """
+ self.model_name = model_name
+ api_key = kwargs.get("api_key") or os.getenv("ATLASCLOUD_API_KEY")
+ if not isinstance(api_key, str) or not api_key:
+ raise ValueError(
+ "atlascloud requires an API key. Pass api_key=... to new_session() "
+ "or set the ATLASCLOUD_API_KEY environment variable. "
+ "Keys are created at https://www.atlascloud.ai"
+ )
+ self.api_key: str = api_key
+ self.model: str = kwargs.get("model") or os.getenv(
+ "ATLASCLOUD_MODEL", DEFAULT_MODEL
+ )
+ self.timeout = kwargs.get("timeout", DEFAULT_TIMEOUT)
+ self.poll_timeout = kwargs.get("poll_timeout", POLL_TIMEOUT)
+
+ def _headers(self) -> dict:
+ return {
+ "Authorization": f"Bearer {self.api_key}",
+ "User-Agent": USER_AGENT,
+ }
+
+ def _request_json(self, url: str, data: bytes = None) -> dict:
+ headers = self._headers()
+ if data is not None:
+ headers["Content-Type"] = "application/json"
+ req = request.Request(url, data=data, headers=headers)
+
+ try:
+ with request.urlopen(req, timeout=self.timeout) as resp:
+ return json.loads(resp.read().decode("utf-8"))
+ except error.HTTPError as e:
+ detail = e.read().decode("utf-8", errors="replace")
+ try:
+ detail = json.loads(detail).get("message", detail) or detail
+ except (json.JSONDecodeError, AttributeError):
+ pass
+ raise RuntimeError(f"atlascloud API error ({e.code}): {detail}") from e
+ except error.URLError as e:
+ raise RuntimeError(f"atlascloud API request failed: {e.reason}") from e
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predict the alpha mask for the input image via the Atlas Cloud API.
+
+ The endpoint is asynchronous: the image is submitted, the returned
+ request id is polled until the prediction completes, and the resulting
+ cutout's alpha channel is used as the mask.
+
+ 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 errors, the prediction fails, or it does
+ not finish within the polling timeout.
+ """
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ image_bytes = buf.getvalue()
+
+ if len(image_bytes) > MAX_UPLOAD_BYTES:
+ raise ValueError(
+ f"atlascloud 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."
+ )
+
+ payload = json.dumps(
+ {
+ "model": self.model,
+ "image": "data:image/png;base64,"
+ + base64.b64encode(image_bytes).decode("ascii"),
+ "enable_base64_output": False,
+ }
+ ).encode("utf-8")
+
+ submitted = self._request_json(GENERATE_URL, payload).get("data") or {}
+ request_id = submitted.get("id")
+ if not request_id:
+ raise RuntimeError(
+ f"atlascloud response did not contain a request id: {submitted}"
+ )
+
+ outputs = self._poll(request_id)
+ cutout_bytes = self._fetch(outputs[0])
+
+ cutout = Image.open(io.BytesIO(cutout_bytes))
+ if "A" not in cutout.getbands():
+ cutout = cutout.convert("RGBA")
+ mask = cutout.getchannel("A")
+ if mask.size != img.size:
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ def _poll(self, request_id: str) -> List[str]:
+ """Poll a prediction until it produces outputs, or fails, or times out."""
+ deadline = time.monotonic() + self.poll_timeout
+
+ while True:
+ result = (
+ self._request_json(f"{PREDICTION_URL}/{request_id}").get("data") or {}
+ )
+ outputs = result.get("outputs")
+ if outputs:
+ return outputs
+
+ status = (result.get("status") or "").lower()
+ if status in ("failed", "error", "canceled", "cancelled"):
+ raise RuntimeError(
+ f"atlascloud prediction {status}: "
+ f"{result.get('error') or 'no error detail returned'}"
+ )
+
+ if time.monotonic() >= deadline:
+ raise RuntimeError(
+ f"atlascloud prediction {request_id} did not finish within "
+ f"{self.poll_timeout}s (last status: {status or 'unknown'})"
+ )
+
+ time.sleep(POLL_INTERVAL)
+
+ def _fetch(self, url: str) -> bytes:
+ """Download a prediction output."""
+ req = request.Request(url, headers={"User-Agent": USER_AGENT})
+ try:
+ with request.urlopen(req, timeout=self.timeout) as resp:
+ return resp.read()
+ except error.HTTPError as e:
+ raise RuntimeError(
+ f"atlascloud output download failed ({e.code}): {url}"
+ ) from e
+ except error.URLError as e:
+ raise RuntimeError(f"atlascloud output download failed: {e.reason}") from e
+
+ @classmethod
+ def is_local(cls, *args, **kwargs) -> bool:
+ """Inference runs on Atlas Cloud's servers, not this machine."""
+ return False
+
+ @classmethod
+ def requires_credentials(cls, *args, **kwargs) -> bool:
+ """Construction needs an API key (api_key= or ATLASCLOUD_API_KEY)."""
+ return True
+
+ @classmethod
+ def has_usage_cost(cls, *args, **kwargs) -> bool:
+ """Each prediction bills against the Atlas Cloud API key."""
+ return True
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """No local model to download for the Atlas Cloud API."""
+ return ""
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """Return the session name."""
+ return "atlascloud"
diff --git a/tests/test_atlascloud.py b/tests/test_atlascloud.py
new file mode 100644
index 0000000..6dcff57
--- /dev/null
+++ b/tests/test_atlascloud.py
@@ -0,0 +1,194 @@
+import io
+import json
+from unittest.mock import MagicMock, patch
+from urllib import error
+
+import pytest
+from PIL import Image
+
+from rembg.sessions.atlascloud import (
+ DEFAULT_MODEL,
+ MAX_UPLOAD_BYTES,
+ AtlasCloudSession,
+)
+
+
+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 _json_resp(payload):
+ resp = MagicMock()
+ resp.read.return_value = json.dumps(payload).encode("utf-8")
+ resp.__enter__.return_value = resp
+ resp.__exit__.return_value = False
+ return resp
+
+
+def _bytes_resp(raw):
+ resp = MagicMock()
+ resp.read.return_value = raw
+ resp.__enter__.return_value = resp
+ resp.__exit__.return_value = False
+ return resp
+
+
+def test_missing_api_key_raises(monkeypatch):
+ monkeypatch.delenv("ATLASCLOUD_API_KEY", raising=False)
+ with pytest.raises(ValueError, match="API key"):
+ AtlasCloudSession("atlascloud", None)
+
+
+def test_api_key_from_env(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_from_env")
+ session = AtlasCloudSession("atlascloud", None)
+ assert session.api_key == "apikey_from_env"
+ assert session.model == DEFAULT_MODEL
+
+
+def test_api_key_kwarg_overrides_env(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_from_env")
+ session = AtlasCloudSession("atlascloud", None, api_key="apikey_kwarg")
+ assert session.api_key == "apikey_kwarg"
+
+
+def test_model_override(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ monkeypatch.setenv("ATLASCLOUD_MODEL", "youchuan/v8.1/remove-background")
+ assert AtlasCloudSession("atlascloud", None).model == (
+ "youchuan/v8.1/remove-background"
+ )
+ session = AtlasCloudSession("atlascloud", None, model="other/model")
+ assert session.model == "other/model"
+
+
+def test_name_and_download_models():
+ assert AtlasCloudSession.name() == "atlascloud"
+ assert AtlasCloudSession.download_models() == ""
+
+
+def test_capability_flags():
+ assert AtlasCloudSession.is_local() is False
+ assert AtlasCloudSession.requires_credentials() is True
+ assert AtlasCloudSession.has_usage_cost() is True
+
+
+def test_predict_rejects_oversized_upload(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ session = AtlasCloudSession("atlascloud", 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.atlascloud.request.urlopen") as mock_urlopen:
+ with pytest.raises(ValueError, match="20 MB limit"):
+ session.predict(img)
+ mock_urlopen.assert_not_called()
+
+
+def test_predict_polls_then_returns_mask_matching_input_size(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ monkeypatch.setattr("rembg.sessions.atlascloud.POLL_INTERVAL", 0)
+ session = AtlasCloudSession("atlascloud", None)
+
+ img = Image.new("RGB", (40, 30), (255, 0, 0))
+ # The API returns a cutout whose alpha channel is the mask, at its own size.
+ cutout_bytes = _png_bytes("RGBA", size=(20, 15), color=(1, 2, 3, 200))
+
+ responses = [
+ _json_resp({"data": {"id": "req-1", "status": "processing"}}),
+ _json_resp({"data": {"status": "processing", "outputs": None}}),
+ _json_resp({"data": {"status": "completed", "outputs": ["https://cdn/x.png"]}}),
+ _bytes_resp(cutout_bytes),
+ ]
+
+ with patch(
+ "rembg.sessions.atlascloud.request.urlopen", side_effect=responses
+ ) as mock_urlopen:
+ masks = session.predict(img)
+
+ assert len(masks) == 1
+ assert masks[0].mode == "L"
+ assert masks[0].size == img.size
+
+ submit_req = mock_urlopen.call_args_list[0][0][0]
+ assert submit_req.get_header("Authorization") == "Bearer apikey_test"
+ body = json.loads(submit_req.data.decode("utf-8"))
+ assert body["model"] == DEFAULT_MODEL
+ assert body["image"].startswith("data:image/png;base64,")
+
+
+def test_predict_raises_when_prediction_fails(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ monkeypatch.setattr("rembg.sessions.atlascloud.POLL_INTERVAL", 0)
+ session = AtlasCloudSession("atlascloud", None)
+ img = Image.new("RGB", (10, 10), (0, 0, 0))
+
+ responses = [
+ _json_resp({"data": {"id": "req-1", "status": "processing"}}),
+ _json_resp({"data": {"status": "failed", "error": "upstream rejected"}}),
+ ]
+
+ with patch("rembg.sessions.atlascloud.request.urlopen", side_effect=responses):
+ with pytest.raises(RuntimeError, match="upstream rejected"):
+ session.predict(img)
+
+
+def test_predict_times_out(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ monkeypatch.setattr("rembg.sessions.atlascloud.POLL_INTERVAL", 0)
+ session = AtlasCloudSession("atlascloud", None, poll_timeout=0)
+ img = Image.new("RGB", (10, 10), (0, 0, 0))
+
+ responses = [
+ _json_resp({"data": {"id": "req-1", "status": "processing"}}),
+ _json_resp({"data": {"status": "processing"}}),
+ ]
+
+ with patch("rembg.sessions.atlascloud.request.urlopen", side_effect=responses):
+ with pytest.raises(RuntimeError, match="did not finish within"):
+ session.predict(img)
+
+
+def test_predict_http_error_raises(monkeypatch):
+ monkeypatch.setenv("ATLASCLOUD_API_KEY", "apikey_test")
+ session = AtlasCloudSession("atlascloud", None)
+ img = Image.new("RGB", (10, 10), (0, 0, 0))
+
+ http_error = error.HTTPError(
+ url="https://api.atlascloud.ai/api/v1/model/generateImage",
+ code=401,
+ msg="Unauthorized",
+ hdrs=None,
+ fp=io.BytesIO(json.dumps({"message": "invalid api key"}).encode("utf-8")),
+ )
+
+ with patch("rembg.sessions.atlascloud.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, sessions_names_downloadable
+
+ assert "atlascloud" in sessions
+ assert sessions["atlascloud"] is AtlasCloudSession
+ # Remote backends must not appear as a download that does nothing.
+ assert "atlascloud" not in sessions_names_downloadable
+
+
+def test_default_model_is_the_served_remove_background_model(monkeypatch):
+ """The default must be a model id Atlas Cloud serves; a stale id fails every request."""
+ from rembg.sessions import atlascloud
+
+ assert atlascloud.DEFAULT_MODEL == "midjourney/v8.2/remove-background"
+ monkeypatch.delenv("ATLASCLOUD_MODEL", raising=False)
+ session = atlascloud.AtlasCloudSession("atlascloud", None, api_key="synthetic-key")
+ assert session.model == "midjourney/v8.2/remove-background"