from __future__ import annotations import io import os import re import shutil import tempfile import zipfile from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass from functools import lru_cache from pathlib import Path from typing import Callable import numpy as np from PIL import Image, ImageFilter DEFAULT_BG_COLOR = "241,242,242" DEFAULT_FOLDER_NAME = "Grey" DEFAULT_REMBG_MODEL = os.getenv("BACKDROPSTUDIO_REMBG_MODEL", "isnet-general-use") DEFAULT_QUALITY_PROFILE = "pro" DEFAULT_OUTPUT_MODE = "preserve_original" DEFAULT_MAX_WORKERS = max(1, min(4, int(os.getenv("BACKDROPSTUDIO_MAX_WORKERS", "2")))) DEFAULT_NUMBA_CACHE_DIR = Path(__file__).resolve().parent / "temp" / "numba-cache" DEFAULT_U2NET_HOME = Path(__file__).resolve().parent / "temp" / "u2net" IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} QUALITY_PROFILES = {"pro", "balanced", "fast"} OUTPUT_MODES = {"preserve_original", "lossless_png"} os.environ.setdefault("NUMBA_CACHE_DIR", str(DEFAULT_NUMBA_CACHE_DIR)) os.environ.setdefault("U2NET_HOME", str(DEFAULT_U2NET_HOME)) class ZipSlipError(ValueError): """Raised when a ZIP member tries to escape the extraction directory.""" class DuplicateOutputNameError(ValueError): """Raised when flattening would overwrite an already processed image.""" @dataclass(frozen=True) class ProcessResult: output_zip_path: Path total: int completed: int failed_files: list[str] ProgressCallback = Callable[[int, int, list[str]], None] BackgroundRemover = Callable[[Image.Image], Image.Image | bytes] @dataclass(frozen=True) class ProcessingProfile: name: str alpha_matting: bool alpha_foreground_threshold: int alpha_background_threshold: int alpha_erode_size: int post_process_mask: bool feather_radius: float edge_contrast: float decontaminate_strength: float PROFILE_CONFIGS = { "pro": ProcessingProfile( name="pro", alpha_matting=True, alpha_foreground_threshold=240, alpha_background_threshold=10, alpha_erode_size=6, post_process_mask=True, feather_radius=0.35, edge_contrast=1.08, decontaminate_strength=0.72, ), "balanced": ProcessingProfile( name="balanced", alpha_matting=True, alpha_foreground_threshold=245, alpha_background_threshold=8, alpha_erode_size=4, post_process_mask=True, feather_radius=0.2, edge_contrast=1.04, decontaminate_strength=0.45, ), "fast": ProcessingProfile( name="fast", alpha_matting=False, alpha_foreground_threshold=240, alpha_background_threshold=10, alpha_erode_size=10, post_process_mask=False, feather_radius=0, edge_contrast=1, decontaminate_strength=0, ), } def parse_bg_color(value: str) -> tuple[int, int, int]: color = value.strip() if color.startswith("#"): if not re.fullmatch(r"#[0-9a-fA-F]{6}", color): raise ValueError("Background color must be #RRGGBB or R,G,B.") return tuple(int(color[index : index + 2], 16) for index in (1, 3, 5)) # type: ignore[return-value] parts = [part.strip() for part in color.split(",")] if len(parts) != 3: raise ValueError("Background color must be #RRGGBB or R,G,B.") try: rgb = tuple(int(part) for part in parts) except ValueError as exc: raise ValueError("RGB values must be whole numbers.") from exc if any(channel < 0 or channel > 255 for channel in rgb): raise ValueError("RGB values must be between 0 and 255.") return rgb # type: ignore[return-value] def validate_quality_profile(value: str) -> str: profile = value.strip().lower() if profile not in QUALITY_PROFILES: raise ValueError("Quality profile must be pro, balanced, or fast.") return profile def validate_output_mode(value: str) -> str: output_mode = value.strip().lower() if output_mode not in OUTPUT_MODES: raise ValueError("Output mode must be preserve_original or lossless_png.") return output_mode def sanitize_folder_name(folder_name: str) -> str: cleaned = folder_name.strip() if not cleaned: raise ValueError("Output folder name is required.") if cleaned in {".", ".."} or ".." in Path(cleaned).parts: raise ValueError("Output folder name cannot contain parent path segments.") if any(separator in cleaned for separator in ("/", "\\")): raise ValueError("Output folder name cannot contain path separators.") if ":" in cleaned or "\x00" in cleaned: raise ValueError("Output folder name contains invalid characters.") return cleaned def _is_within_directory(base_dir: Path, target_path: Path) -> bool: try: target_path.resolve().relative_to(base_dir.resolve()) return True except ValueError: return False def safe_extract_zip(zip_path: Path, destination: Path) -> None: destination.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(zip_path) as archive: for member in archive.infolist(): if member.is_dir(): continue target_path = destination / member.filename if not _is_within_directory(destination, target_path): raise ZipSlipError(f"Unsafe ZIP member path: {member.filename}") target_path.parent.mkdir(parents=True, exist_ok=True) with archive.open(member) as source, target_path.open("wb") as target: shutil.copyfileobj(source, target) def collect_image_files(root: Path) -> list[Path]: return sorted( path for path in root.rglob("*") if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS ) def get_max_workers() -> int: raw_value = os.getenv("BACKDROPSTUDIO_MAX_WORKERS", str(DEFAULT_MAX_WORKERS)) try: return max(1, min(8, int(raw_value))) except ValueError: return DEFAULT_MAX_WORKERS @lru_cache(maxsize=4) def _get_rembg_session(model_name: str): from rembg import new_session try: return new_session(model_name) except Exception: if model_name == "u2net": raise return new_session("u2net") @lru_cache(maxsize=12) def build_background_remover( model_name: str = DEFAULT_REMBG_MODEL, quality_profile: str = DEFAULT_QUALITY_PROFILE, ) -> BackgroundRemover: profile = PROFILE_CONFIGS[validate_quality_profile(quality_profile)] Path(os.environ["NUMBA_CACHE_DIR"]).mkdir(parents=True, exist_ok=True) Path(os.environ["U2NET_HOME"]).mkdir(parents=True, exist_ok=True) from rembg import remove session = _get_rembg_session(model_name) def remover(image: Image.Image) -> Image.Image | bytes: return remove( image.convert("RGBA"), alpha_matting=profile.alpha_matting, alpha_matting_foreground_threshold=profile.alpha_foreground_threshold, alpha_matting_background_threshold=profile.alpha_background_threshold, alpha_matting_erode_size=profile.alpha_erode_size, post_process_mask=profile.post_process_mask, session=session, ) return remover def remove_background( image: Image.Image, model_name: str = DEFAULT_REMBG_MODEL, quality_profile: str = DEFAULT_QUALITY_PROFILE, ) -> Image.Image: cutout = build_background_remover(model_name, quality_profile)(image) if isinstance(cutout, Image.Image): return cutout.convert("RGBA") return Image.open(io.BytesIO(cutout)).convert("RGBA") def _save_kwargs_for(path: Path, source_info: dict) -> dict[str, int | bool | bytes]: kwargs: dict[str, int | bool | bytes] = {} if source_info.get("icc_profile"): kwargs["icc_profile"] = source_info["icc_profile"] if source_info.get("exif") and path.suffix.lower() in {".jpg", ".jpeg", ".webp"}: kwargs["exif"] = source_info["exif"] suffix = path.suffix.lower() if suffix in {".jpg", ".jpeg"}: kwargs.update({"quality": 100, "subsampling": 0, "optimize": True}) elif suffix == ".webp": kwargs.update({"quality": 100, "lossless": True, "method": 6}) elif suffix == ".png": kwargs.update({"compress_level": 4}) return kwargs def _output_name_for(image_path: Path, output_mode: str) -> str: if output_mode == "lossless_png": return f"{image_path.stem}.png" return image_path.name def _refine_alpha(alpha: Image.Image, profile: ProcessingProfile) -> Image.Image: refined = alpha.convert("L") if profile.feather_radius > 0: refined = refined.filter(ImageFilter.GaussianBlur(profile.feather_radius)) if profile.edge_contrast != 1: contrast = profile.edge_contrast refined = refined.point( lambda value: max(0, min(255, int((value - 128) * contrast + 128))) ) return refined def _decontaminate_white_edges(cutout: Image.Image, alpha: Image.Image, strength: float) -> Image.Image: if strength <= 0: cutout.putalpha(alpha) return cutout rgba = np.asarray(cutout.convert("RGBA"), dtype=np.float32).copy() alpha_array = np.asarray(alpha, dtype=np.float32) / 255.0 edge_mask = (alpha_array > 0.02) & (alpha_array < 0.98) if not edge_mask.any(): rgba[..., 3] = np.asarray(alpha, dtype=np.float32) return Image.fromarray(np.clip(rgba, 0, 255).astype(np.uint8), "RGBA") rgb = rgba[..., :3] denominator = np.maximum(alpha_array[..., None], 0.02) decontaminated = (rgb - ((1.0 - alpha_array[..., None]) * 255.0 * strength)) / denominator blend = np.zeros_like(alpha_array) blend[edge_mask] = strength rgba[..., :3] = (rgb * (1.0 - blend[..., None])) + ( np.clip(decontaminated, 0, 255) * blend[..., None] ) rgba[..., 3] = np.asarray(alpha, dtype=np.float32) return Image.fromarray(np.clip(rgba, 0, 255).astype(np.uint8), "RGBA") def _prepare_cutout(cutout: Image.Image, size: tuple[int, int], profile: ProcessingProfile) -> Image.Image: prepared = cutout.convert("RGBA") if prepared.size != size: prepared = prepared.resize(size, Image.Resampling.LANCZOS) alpha = _refine_alpha(prepared.getchannel("A"), profile) return _decontaminate_white_edges(prepared, alpha, profile.decontaminate_strength) def _composite_on_background(cutout: Image.Image, bg_rgb: tuple[int, int, int]) -> Image.Image: canvas = Image.new("RGB", cutout.size, bg_rgb) canvas.paste(cutout, (0, 0), cutout) return canvas def _process_one_image( image_path: Path, output_path: Path, bg_rgb: tuple[int, int, int], profile: ProcessingProfile, remover: BackgroundRemover, ) -> None: with Image.open(image_path) as image: source_info = dict(image.info) cutout = _normalize_cutout(remover(image)) prepared_cutout = _prepare_cutout(cutout, image.size, profile) canvas = _composite_on_background(prepared_cutout, bg_rgb) canvas.save(output_path, **_save_kwargs_for(output_path, source_info)) def _zip_output_folder(output_root: Path, folder_name: str, output_zip_path: Path) -> None: folder_path = output_root / folder_name with zipfile.ZipFile(output_zip_path, "w", zipfile.ZIP_DEFLATED) as archive: archive.writestr(f"{folder_name}/", b"") for path in sorted(folder_path.rglob("*")): if path.is_file(): archive.write(path, path.relative_to(output_root).as_posix()) def _normalize_cutout(cutout: Image.Image | bytes) -> Image.Image: if isinstance(cutout, Image.Image): return cutout.convert("RGBA") return Image.open(io.BytesIO(cutout)).convert("RGBA") def process_zip( zip_path: Path, output_zip_path: Path, folder_name: str, bg_rgb: tuple[int, int, int], *, model_name: str = DEFAULT_REMBG_MODEL, quality_profile: str = DEFAULT_QUALITY_PROFILE, output_mode: str = DEFAULT_OUTPUT_MODE, progress_callback: ProgressCallback | None = None, remover: BackgroundRemover | None = None, ) -> ProcessResult: folder_name = sanitize_folder_name(folder_name) validated_profile = validate_quality_profile(quality_profile) validated_output_mode = validate_output_mode(output_mode) profile = PROFILE_CONFIGS[validated_profile] output_zip_path.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="backdropstudio-") as work_dir_name: work_dir = Path(work_dir_name) extract_dir = work_dir / "source" output_root = work_dir / "output" output_folder = output_root / folder_name output_folder.mkdir(parents=True, exist_ok=True) safe_extract_zip(zip_path, extract_dir) image_files = collect_image_files(extract_dir) total = len(image_files) completed = 0 failed_files: list[str] = [] seen_output_names: set[str] = set() tasks: list[tuple[int, Path, str, Path]] = [] if progress_callback: progress_callback(total, completed, failed_files.copy()) active_remover = remover or build_background_remover(model_name, validated_profile) last_error: Exception | None = None for index, image_path in enumerate(image_files): relative_name = image_path.relative_to(extract_dir).as_posix() output_name = _output_name_for(image_path, validated_output_mode) output_path = output_folder / output_name if output_name.lower() in seen_output_names: last_error = DuplicateOutputNameError( f"Duplicate filename would overwrite output: {output_name}" ) failed_files.append(relative_name) completed += 1 if progress_callback: progress_callback(total, completed, failed_files.copy()) continue seen_output_names.add(output_name.lower()) tasks.append((index, image_path, relative_name, output_path)) failed_records: list[tuple[int, str]] = [] max_workers = min(get_max_workers(), max(1, len(tasks))) with ThreadPoolExecutor(max_workers=max_workers) as executor: futures = { executor.submit( _process_one_image, image_path, output_path, bg_rgb, profile, active_remover, ): (index, relative_name) for index, image_path, relative_name, output_path in tasks } for future in as_completed(futures): index, relative_name = futures[future] try: future.result() except Exception as exc: last_error = exc failed_records.append((index, relative_name)) completed += 1 failed_files = [ name for _, name in sorted(failed_records) ] + [ name for name in failed_files if name not in {record_name for _, record_name in failed_records} ] if progress_callback: progress_callback(total, completed, failed_files.copy()) if total > 0 and len(failed_files) == total: detail = f" Last error: {last_error}" if last_error else "" raise RuntimeError(f"All {total} image files failed during processing.{detail}") _zip_output_folder(output_root, folder_name, output_zip_path) return ProcessResult( output_zip_path=output_zip_path, total=total, completed=completed, failed_files=failed_files, )