"""Background removal with the commercially permissive BiRefNet model. The model is provided by ``rembg`` and is downloaded once on first use. See README.md for model attribution and hosting notes. """ # pylint: disable=broad-exception-caught from functools import lru_cache from PIL import Image from rembg import new_session, remove MODEL_NAME = "birefnet-general" @lru_cache(maxsize=1) def get_session(): """Create and retain one BiRefNet inference session per process.""" return new_session(MODEL_NAME) def remove_background(image: Image.Image) -> Image.Image: """Return *image* as an RGBA image with its background made transparent.""" if image is None: raise ValueError("Please upload an image first.") return remove(image.convert("RGBA"), session=get_session()).convert("RGBA")