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55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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,
    )