Rembg is a tool to remove images background
feat: let sessions declare non-local capabilities (#839)
Daniel Gatis930708c40cf3
diff --git a/rembg/bg.py b/rembg/bg.pyindex d878287..68de0cd 100644--- a/rembg/bg.py+++ b/rembg/bg.py@@ -28,7 +28,7 @@ from scipy.ndimage import binary_erosion, gaussian_filterfrom skimage.morphology import disk, openingfrom .session_factory import new_session-from .sessions import sessions, sessions_names+from .sessions import sessions, sessions_names, sessions_names_downloadablefrom .sessions.base import BaseSessionort.set_default_logger_severity(3)@@ -208,13 +208,15 @@ def download_models(models: tuple[str, ...]) -> None:"""if len(models) == 0:print("No models specified, downloading all models")- models = tuple(sessions_names)+ models = tuple(sessions_names_downloadable)for model in models:session = sessions.get(model)if session is None:print(f"Error: no model found: {model}")sys.exit(1)+ elif not session.is_local():+ print(f"Skipping {model}: remote backend, nothing to download")else:print(f"Downloading model: {model}")try:diff --git a/rembg/commands/p_command.py b/rembg/commands/p_command.pyindex 9157994..77fc5ec 100644--- a/rembg/commands/p_command.py+++ b/rembg/commands/p_command.py@@ -1,7 +1,8 @@import jsonimport pathlib+import sysimport time-from typing import cast+from typing import List, castimport clickimport filetype@@ -11,7 +12,71 @@ from watchdog.observers import Observerfrom ..bg import removefrom ..session_factory import new_session-from ..sessions import sessions_names+from ..sessions import sessions, sessions_names+++def _billable_count(inputs: List[pathlib.Path], output: pathlib.Path) -> int:+ """Count inputs that would actually reach the model.++ Mirrors the skips in `process`: directories, non-images, and inputs whose+ output already exists are never sent, so counting the raw glob would+ overstate the cost.+ """+ count = 0+ for each_input in inputs:+ if each_input.is_dir():+ continue+ mimetype = filetype.guess(each_input)+ if mimetype is None or mimetype.mime.find("image") < 0:+ continue+ if (output / each_input.name).with_suffix(".png").exists():+ continue+ count += 1+ return count+++def _confirm_usage_cost(+ model: str,+ inputs: List[pathlib.Path],+ output: pathlib.Path,+ watch: bool,+ accept_usage_cost: bool,+) -> None:+ """Warn before a billed batch, and confirm unless the cost was accepted.++ Non-interactive runs must pass --accept-usage-cost. Prompting would hang a+ pipeline, and proceeding on its own would spend the user's money with no+ way to decline.+ """+ if watch:+ click.echo(+ f"Warning: '{model}' bills per image and --watch has no fixed end. "+ "Every file added to the folder will be sent and charged.",+ err=True,+ )+ else:+ count = _billable_count(inputs, output)+ if count == 0:+ return+ click.echo(+ f"Warning: '{model}' bills per image. "+ f"This run will send {count} image{'s' if count != 1 else ''} "+ "to a remote service.",+ err=True,+ )++ if accept_usage_cost:+ return++ if not sys.stdin.isatty():+ click.echo(+ "Refusing to run unattended. Pass --accept-usage-cost to proceed.",+ err=True,+ )+ raise click.Abort()++ if not click.confirm("Continue?", default=False, err=True):+ raise click.Abort()@click.command( # type: ignore@@ -88,6 +153,13 @@ from ..sessions import sessions_namesshow_default=True,help="delete input file after processing",)+ "--accept-usage-cost",+ default=False,+ is_flag=True,+ show_default=True,+ help="proceed without confirming for models that bill per image",+)@click.option("-bgc","--bgcolor",@@ -124,6 +196,7 @@ def p_command(output: pathlib.Path,watch: bool,delete_input: bool,+ accept_usage_cost: bool,**kwargs,) -> None:"""@@ -142,6 +215,7 @@ def p_command(output (pathlib.Path): The path to the output folder.watch (bool): Whether to watch the input folder for changes.delete_input (bool): Whether to delete the input file after processing.+ accept_usage_cost (bool): Proceed without confirming for models that bill per image.**kwargs: Additional keyword arguments.Returns:@@ -185,6 +259,10 @@ def p_command(print(e)inputs = list(input.glob("**/*"))++ if sessions[model].has_usage_cost():+ _confirm_usage_cost(model, inputs, output, watch, accept_usage_cost)+inputs_tqdm = inputs if watch else tqdm(inputs)for each_input in inputs_tqdm:diff --git a/rembg/commands/s_command.py b/rembg/commands/s_command.pyindex 5502133..1d7897d 100644--- a/rembg/commands/s_command.py+++ b/rembg/commands/s_command.py@@ -71,7 +71,7 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -This function starts the FastAPI web server with the specified port and log level.If the number of worker threads is specified, it sets the thread limiter accordingly."""- sessions: dict[str, BaseSession] = {}+ sessions: dict[tuple, BaseSession] = {}tags_metadata = [{"name": "Background Removal",@@ -206,10 +206,13 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -except Exception:pass- session = sessions.get(commons.model)+ # Extras are part of the key: a session built with one caller's api_key+ # or model_path must not be handed to a request that passed another.+ cache_key = (commons.model, json.dumps(kwargs, sort_keys=True, default=str))+ session = sessions.get(cache_key)if session is None:session = new_session(commons.model, **kwargs)- sessions[commons.model] = session+ sessions[cache_key] = sessionreturn Response(remove(@@ -396,13 +399,18 @@ def s_command(port: int, host: str, log_level: str, threads: int, no_ui: bool) -"post_process_mask": ppm,}+ extras = {}if cmd_args:- kwargs.update(json.loads(cmd_args))+ extras = json.loads(cmd_args)+ kwargs.update(extras)- session = sessions.get(model)+ # Extras are part of the key: a session built with one api_key or+ # model_path must not be reused for a request that passed another.+ cache_key = (model, json.dumps(extras, sort_keys=True, default=str))+ session = sessions.get(cache_key)if session is None:session = new_session(model, **kwargs)- sessions[model] = session+ sessions[cache_key] = sessionkwargs["session"] = sessionreturn remove(input_image, **kwargs)diff --git a/rembg/sessions/__init__.py b/rembg/sessions/__init__.pyindex b8c803c..9e9bffd 100644--- a/rembg/sessions/__init__.py+++ b/rembg/sessions/__init__.py@@ -84,3 +84,14 @@ sessions[BenCustomSession.name()] = BenCustomSessionsessions_names = list(sessions.keys())sessions_class = list(sessions.values())++# Sessions that can be constructed from a model name alone, with no credential.+# Interfaces that build a session on the user's behalf (the web UI, the HTTP+# endpoint) should offer these rather than every registered name.+sessions_names_no_credentials = [+ name for name, cls in sessions.items() if not cls.requires_credentials()+]++# Sessions backed by a downloadable local model file. `rembg d` iterates these,+# so remote backends do not show up as a download that does nothing.+sessions_names_downloadable = [name for name, cls in sessions.items() if cls.is_local()]diff --git a/rembg/sessions/base.py b/rembg/sessions/base.pyindex 7845049..32df82a 100644--- a/rembg/sessions/base.py+++ b/rembg/sessions/base.py@@ -69,6 +69,33 @@ class BaseSession:def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:raise NotImplementedError+ @classmethod+ def is_local(cls, *args, **kwargs) -> bool:+ """Whether inference runs on this machine.++ Return False for sessions that send the image to a remote service, so+ callers can tell the user their data leaves the machine.+ """+ return True++ @classmethod+ def requires_credentials(cls, *args, **kwargs) -> bool:+ """Whether constructing this session needs a credential.++ Sessions that return True cannot be instantiated from a bare model name,+ so interfaces that build sessions on the user's behalf should skip them+ rather than fail at construction time.+ """+ return False++ @classmethod+ def has_usage_cost(cls, *args, **kwargs) -> bool:+ """Whether each prediction bills the user.++ Batch entry points should warn before spending on a large run.+ """+ return False+@classmethoddef checksum_disabled(cls, *args, **kwargs):return os.getenv("MODEL_CHECKSUM_DISABLED", None) is not None