Rahul4112 commited on
Commit
0d7bef5
·
0 Parent(s):

first commit

Browse files
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .coverage
5
+ htmlcov/
6
+
7
+ app/temp/
8
+ app/output/
9
+
10
+ .env
11
+ .venv/
12
+ venv/
Grey.zip ADDED
Binary file (110 Bytes). View file
 
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """BackDropStudio application package."""
app/main.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ import time
5
+ from pathlib import Path
6
+ from threading import RLock
7
+ from typing import Any
8
+ from uuid import uuid4
9
+
10
+ from fastapi import BackgroundTasks, FastAPI, File, Form, HTTPException, Request, UploadFile
11
+ from fastapi.responses import FileResponse
12
+ from fastapi.staticfiles import StaticFiles
13
+
14
+ try:
15
+ from .processor import (
16
+ DEFAULT_BG_COLOR,
17
+ DEFAULT_FOLDER_NAME,
18
+ DEFAULT_OUTPUT_MODE,
19
+ DEFAULT_QUALITY_PROFILE,
20
+ parse_bg_color,
21
+ process_zip,
22
+ sanitize_folder_name,
23
+ validate_output_mode,
24
+ validate_quality_profile,
25
+ )
26
+ except ImportError: # Allows `uvicorn main:app` from inside the app directory.
27
+ from processor import (
28
+ DEFAULT_BG_COLOR,
29
+ DEFAULT_FOLDER_NAME,
30
+ DEFAULT_OUTPUT_MODE,
31
+ DEFAULT_QUALITY_PROFILE,
32
+ parse_bg_color,
33
+ process_zip,
34
+ sanitize_folder_name,
35
+ validate_output_mode,
36
+ validate_quality_profile,
37
+ )
38
+
39
+
40
+ APP_NAME = "BackDropStudio"
41
+ MAX_UPLOAD_BYTES = 500 * 1024 * 1024
42
+ RETENTION_SECONDS = 60 * 60
43
+ BASE_DIR = Path(__file__).resolve().parent
44
+ STATIC_DIR = BASE_DIR / "static"
45
+ TEMP_DIR = BASE_DIR / "temp"
46
+
47
+ app = FastAPI(title=APP_NAME)
48
+ app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
49
+
50
+ jobs: dict[str, dict[str, Any]] = {}
51
+ jobs_lock = RLock()
52
+
53
+
54
+ def _now() -> float:
55
+ return time.time()
56
+
57
+
58
+ def _public_job(record: dict[str, Any]) -> dict[str, Any]:
59
+ return {
60
+ "status": record["status"],
61
+ "total": record["total"],
62
+ "completed": record["completed"],
63
+ "failed_files": record["failed_files"],
64
+ }
65
+
66
+
67
+ def _update_job(job_id: str, **changes: Any) -> None:
68
+ with jobs_lock:
69
+ if job_id not in jobs:
70
+ return
71
+ jobs[job_id].update(changes)
72
+ jobs[job_id]["updated_at"] = _now()
73
+
74
+
75
+ def _cleanup_stale_jobs() -> None:
76
+ cutoff = _now() - RETENTION_SECONDS
77
+ expired: list[dict[str, Any]] = []
78
+ with jobs_lock:
79
+ for job_id, record in list(jobs.items()):
80
+ if record["status"] in {"done", "failed"} and record["updated_at"] < cutoff:
81
+ expired.append(jobs.pop(job_id))
82
+
83
+ for record in expired:
84
+ shutil.rmtree(record["job_dir"], ignore_errors=True)
85
+
86
+
87
+ async def _save_upload(upload: UploadFile, destination: Path) -> None:
88
+ destination.parent.mkdir(parents=True, exist_ok=True)
89
+ size = 0
90
+ with destination.open("wb") as target:
91
+ while chunk := await upload.read(1024 * 1024):
92
+ size += len(chunk)
93
+ if size > MAX_UPLOAD_BYTES:
94
+ raise HTTPException(
95
+ status_code=413,
96
+ detail="Upload is too large. Maximum ZIP size is 500MB.",
97
+ )
98
+ target.write(chunk)
99
+
100
+
101
+ def _run_processing_job(
102
+ job_id: str,
103
+ zip_path: Path,
104
+ output_zip_path: Path,
105
+ folder_name: str,
106
+ bg_rgb: tuple[int, int, int],
107
+ quality_profile: str,
108
+ output_mode: str,
109
+ ) -> None:
110
+ def report_progress(total: int, completed: int, failed_files: list[str]) -> None:
111
+ _update_job(job_id, total=total, completed=completed, failed_files=failed_files)
112
+
113
+ try:
114
+ result = process_zip(
115
+ zip_path,
116
+ output_zip_path,
117
+ folder_name,
118
+ bg_rgb,
119
+ quality_profile=quality_profile,
120
+ output_mode=output_mode,
121
+ progress_callback=report_progress,
122
+ )
123
+ _update_job(
124
+ job_id,
125
+ status="done",
126
+ total=result.total,
127
+ completed=result.completed,
128
+ failed_files=result.failed_files,
129
+ output_zip_path=result.output_zip_path,
130
+ )
131
+ except Exception as exc:
132
+ _update_job(job_id, status="failed", error=str(exc))
133
+ finally:
134
+ zip_path.unlink(missing_ok=True)
135
+
136
+
137
+ @app.get("/", include_in_schema=False)
138
+ async def index() -> FileResponse:
139
+ return FileResponse(STATIC_DIR / "index.html")
140
+
141
+
142
+ @app.post("/api/process")
143
+ async def process_upload(
144
+ request: Request,
145
+ background_tasks: BackgroundTasks,
146
+ file: UploadFile = File(...),
147
+ bg_color: str = Form(DEFAULT_BG_COLOR),
148
+ folder_name: str = Form(DEFAULT_FOLDER_NAME),
149
+ quality_profile: str = Form(DEFAULT_QUALITY_PROFILE),
150
+ output_mode: str = Form(DEFAULT_OUTPUT_MODE),
151
+ ) -> dict[str, str]:
152
+ _cleanup_stale_jobs()
153
+
154
+ filename = file.filename or ""
155
+ if Path(filename).suffix.lower() != ".zip":
156
+ raise HTTPException(status_code=400, detail="Please upload a .zip file.")
157
+
158
+ content_length = request.headers.get("content-length")
159
+ if content_length and content_length.isdigit() and int(content_length) > MAX_UPLOAD_BYTES + 1024 * 1024:
160
+ raise HTTPException(
161
+ status_code=413,
162
+ detail="Upload is too large. Maximum ZIP size is 500MB.",
163
+ )
164
+
165
+ try:
166
+ bg_rgb = parse_bg_color(bg_color)
167
+ safe_folder_name = sanitize_folder_name(folder_name)
168
+ safe_quality_profile = validate_quality_profile(quality_profile)
169
+ safe_output_mode = validate_output_mode(output_mode)
170
+ except ValueError as exc:
171
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
172
+
173
+ job_id = str(uuid4())
174
+ job_dir = TEMP_DIR / job_id
175
+ zip_path = job_dir / "upload.zip"
176
+ output_zip_path = job_dir / "backdropstudio-output.zip"
177
+
178
+ try:
179
+ await _save_upload(file, zip_path)
180
+ except Exception:
181
+ shutil.rmtree(job_dir, ignore_errors=True)
182
+ raise
183
+ finally:
184
+ await file.close()
185
+
186
+ with jobs_lock:
187
+ jobs[job_id] = {
188
+ "status": "processing",
189
+ "total": 0,
190
+ "completed": 0,
191
+ "failed_files": [],
192
+ "error": None,
193
+ "output_zip_path": None,
194
+ "folder_name": safe_folder_name,
195
+ "quality_profile": safe_quality_profile,
196
+ "output_mode": safe_output_mode,
197
+ "job_dir": job_dir,
198
+ "created_at": _now(),
199
+ "updated_at": _now(),
200
+ }
201
+
202
+ background_tasks.add_task(
203
+ _run_processing_job,
204
+ job_id,
205
+ zip_path,
206
+ output_zip_path,
207
+ safe_folder_name,
208
+ bg_rgb,
209
+ safe_quality_profile,
210
+ safe_output_mode,
211
+ )
212
+ return {"job_id": job_id}
213
+
214
+
215
+ @app.get("/api/status/{job_id}")
216
+ async def get_status(job_id: str) -> dict[str, Any]:
217
+ _cleanup_stale_jobs()
218
+ with jobs_lock:
219
+ record = jobs.get(job_id)
220
+ if not record:
221
+ raise HTTPException(status_code=404, detail="Job not found.")
222
+ response = _public_job(record)
223
+ if record.get("error"):
224
+ response["error"] = record["error"]
225
+ return response
226
+
227
+
228
+ @app.get("/api/download/{job_id}")
229
+ async def download(job_id: str) -> FileResponse:
230
+ _cleanup_stale_jobs()
231
+ with jobs_lock:
232
+ record = jobs.get(job_id)
233
+ if not record:
234
+ raise HTTPException(status_code=404, detail="Job not found.")
235
+ if record["status"] != "done":
236
+ raise HTTPException(status_code=409, detail="Output ZIP is not ready yet.")
237
+ output_zip_path = record["output_zip_path"]
238
+ folder_name = record["folder_name"]
239
+
240
+ if not output_zip_path or not Path(output_zip_path).exists():
241
+ raise HTTPException(status_code=404, detail="Output ZIP has expired.")
242
+
243
+ return FileResponse(
244
+ output_zip_path,
245
+ media_type="application/zip",
246
+ filename=f"{folder_name}.zip",
247
+ )
app/processor.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ import re
6
+ import shutil
7
+ import tempfile
8
+ import zipfile
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from dataclasses import dataclass
11
+ from functools import lru_cache
12
+ from pathlib import Path
13
+ from typing import Callable
14
+
15
+ import numpy as np
16
+ from PIL import Image, ImageFilter
17
+
18
+ DEFAULT_BG_COLOR = "241,242,242"
19
+ DEFAULT_FOLDER_NAME = "Grey"
20
+ DEFAULT_REMBG_MODEL = os.getenv("BACKDROPSTUDIO_REMBG_MODEL", "isnet-general-use")
21
+ DEFAULT_QUALITY_PROFILE = "pro"
22
+ DEFAULT_OUTPUT_MODE = "preserve_original"
23
+ DEFAULT_MAX_WORKERS = max(1, min(4, int(os.getenv("BACKDROPSTUDIO_MAX_WORKERS", "2"))))
24
+ DEFAULT_NUMBA_CACHE_DIR = Path(__file__).resolve().parent / "temp" / "numba-cache"
25
+ DEFAULT_U2NET_HOME = Path(__file__).resolve().parent / "temp" / "u2net"
26
+ IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
27
+ QUALITY_PROFILES = {"pro", "balanced", "fast"}
28
+ OUTPUT_MODES = {"preserve_original", "lossless_png"}
29
+
30
+ os.environ.setdefault("NUMBA_CACHE_DIR", str(DEFAULT_NUMBA_CACHE_DIR))
31
+ os.environ.setdefault("U2NET_HOME", str(DEFAULT_U2NET_HOME))
32
+
33
+
34
+ class ZipSlipError(ValueError):
35
+ """Raised when a ZIP member tries to escape the extraction directory."""
36
+
37
+
38
+ class DuplicateOutputNameError(ValueError):
39
+ """Raised when flattening would overwrite an already processed image."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ProcessResult:
44
+ output_zip_path: Path
45
+ total: int
46
+ completed: int
47
+ failed_files: list[str]
48
+
49
+
50
+ ProgressCallback = Callable[[int, int, list[str]], None]
51
+ BackgroundRemover = Callable[[Image.Image], Image.Image | bytes]
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ProcessingProfile:
56
+ name: str
57
+ alpha_matting: bool
58
+ alpha_foreground_threshold: int
59
+ alpha_background_threshold: int
60
+ alpha_erode_size: int
61
+ post_process_mask: bool
62
+ feather_radius: float
63
+ edge_contrast: float
64
+ decontaminate_strength: float
65
+
66
+
67
+ PROFILE_CONFIGS = {
68
+ "pro": ProcessingProfile(
69
+ name="pro",
70
+ alpha_matting=True,
71
+ alpha_foreground_threshold=240,
72
+ alpha_background_threshold=10,
73
+ alpha_erode_size=6,
74
+ post_process_mask=True,
75
+ feather_radius=0.35,
76
+ edge_contrast=1.08,
77
+ decontaminate_strength=0.72,
78
+ ),
79
+ "balanced": ProcessingProfile(
80
+ name="balanced",
81
+ alpha_matting=True,
82
+ alpha_foreground_threshold=245,
83
+ alpha_background_threshold=8,
84
+ alpha_erode_size=4,
85
+ post_process_mask=True,
86
+ feather_radius=0.2,
87
+ edge_contrast=1.04,
88
+ decontaminate_strength=0.45,
89
+ ),
90
+ "fast": ProcessingProfile(
91
+ name="fast",
92
+ alpha_matting=False,
93
+ alpha_foreground_threshold=240,
94
+ alpha_background_threshold=10,
95
+ alpha_erode_size=10,
96
+ post_process_mask=False,
97
+ feather_radius=0,
98
+ edge_contrast=1,
99
+ decontaminate_strength=0,
100
+ ),
101
+ }
102
+
103
+
104
+ def parse_bg_color(value: str) -> tuple[int, int, int]:
105
+ color = value.strip()
106
+ if color.startswith("#"):
107
+ if not re.fullmatch(r"#[0-9a-fA-F]{6}", color):
108
+ raise ValueError("Background color must be #RRGGBB or R,G,B.")
109
+ return tuple(int(color[index : index + 2], 16) for index in (1, 3, 5)) # type: ignore[return-value]
110
+
111
+ parts = [part.strip() for part in color.split(",")]
112
+ if len(parts) != 3:
113
+ raise ValueError("Background color must be #RRGGBB or R,G,B.")
114
+
115
+ try:
116
+ rgb = tuple(int(part) for part in parts)
117
+ except ValueError as exc:
118
+ raise ValueError("RGB values must be whole numbers.") from exc
119
+
120
+ if any(channel < 0 or channel > 255 for channel in rgb):
121
+ raise ValueError("RGB values must be between 0 and 255.")
122
+ return rgb # type: ignore[return-value]
123
+
124
+
125
+ def validate_quality_profile(value: str) -> str:
126
+ profile = value.strip().lower()
127
+ if profile not in QUALITY_PROFILES:
128
+ raise ValueError("Quality profile must be pro, balanced, or fast.")
129
+ return profile
130
+
131
+
132
+ def validate_output_mode(value: str) -> str:
133
+ output_mode = value.strip().lower()
134
+ if output_mode not in OUTPUT_MODES:
135
+ raise ValueError("Output mode must be preserve_original or lossless_png.")
136
+ return output_mode
137
+
138
+
139
+ def sanitize_folder_name(folder_name: str) -> str:
140
+ cleaned = folder_name.strip()
141
+ if not cleaned:
142
+ raise ValueError("Output folder name is required.")
143
+ if cleaned in {".", ".."} or ".." in Path(cleaned).parts:
144
+ raise ValueError("Output folder name cannot contain parent path segments.")
145
+ if any(separator in cleaned for separator in ("/", "\\")):
146
+ raise ValueError("Output folder name cannot contain path separators.")
147
+ if ":" in cleaned or "\x00" in cleaned:
148
+ raise ValueError("Output folder name contains invalid characters.")
149
+ return cleaned
150
+
151
+
152
+ def _is_within_directory(base_dir: Path, target_path: Path) -> bool:
153
+ try:
154
+ target_path.resolve().relative_to(base_dir.resolve())
155
+ return True
156
+ except ValueError:
157
+ return False
158
+
159
+
160
+ def safe_extract_zip(zip_path: Path, destination: Path) -> None:
161
+ destination.mkdir(parents=True, exist_ok=True)
162
+ with zipfile.ZipFile(zip_path) as archive:
163
+ for member in archive.infolist():
164
+ if member.is_dir():
165
+ continue
166
+
167
+ target_path = destination / member.filename
168
+ if not _is_within_directory(destination, target_path):
169
+ raise ZipSlipError(f"Unsafe ZIP member path: {member.filename}")
170
+
171
+ target_path.parent.mkdir(parents=True, exist_ok=True)
172
+ with archive.open(member) as source, target_path.open("wb") as target:
173
+ shutil.copyfileobj(source, target)
174
+
175
+
176
+ def collect_image_files(root: Path) -> list[Path]:
177
+ return sorted(
178
+ path
179
+ for path in root.rglob("*")
180
+ if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS
181
+ )
182
+
183
+
184
+ def get_max_workers() -> int:
185
+ raw_value = os.getenv("BACKDROPSTUDIO_MAX_WORKERS", str(DEFAULT_MAX_WORKERS))
186
+ try:
187
+ return max(1, min(8, int(raw_value)))
188
+ except ValueError:
189
+ return DEFAULT_MAX_WORKERS
190
+
191
+
192
+ @lru_cache(maxsize=4)
193
+ def _get_rembg_session(model_name: str):
194
+ from rembg import new_session
195
+
196
+ try:
197
+ return new_session(model_name)
198
+ except Exception:
199
+ if model_name == "u2net":
200
+ raise
201
+ return new_session("u2net")
202
+
203
+
204
+ @lru_cache(maxsize=12)
205
+ def build_background_remover(
206
+ model_name: str = DEFAULT_REMBG_MODEL,
207
+ quality_profile: str = DEFAULT_QUALITY_PROFILE,
208
+ ) -> BackgroundRemover:
209
+ profile = PROFILE_CONFIGS[validate_quality_profile(quality_profile)]
210
+ Path(os.environ["NUMBA_CACHE_DIR"]).mkdir(parents=True, exist_ok=True)
211
+ Path(os.environ["U2NET_HOME"]).mkdir(parents=True, exist_ok=True)
212
+
213
+ from rembg import remove
214
+
215
+ session = _get_rembg_session(model_name)
216
+
217
+ def remover(image: Image.Image) -> Image.Image | bytes:
218
+ return remove(
219
+ image.convert("RGBA"),
220
+ alpha_matting=profile.alpha_matting,
221
+ alpha_matting_foreground_threshold=profile.alpha_foreground_threshold,
222
+ alpha_matting_background_threshold=profile.alpha_background_threshold,
223
+ alpha_matting_erode_size=profile.alpha_erode_size,
224
+ post_process_mask=profile.post_process_mask,
225
+ session=session,
226
+ )
227
+
228
+ return remover
229
+
230
+
231
+ def remove_background(
232
+ image: Image.Image,
233
+ model_name: str = DEFAULT_REMBG_MODEL,
234
+ quality_profile: str = DEFAULT_QUALITY_PROFILE,
235
+ ) -> Image.Image:
236
+ cutout = build_background_remover(model_name, quality_profile)(image)
237
+ if isinstance(cutout, Image.Image):
238
+ return cutout.convert("RGBA")
239
+ return Image.open(io.BytesIO(cutout)).convert("RGBA")
240
+
241
+
242
+ def _save_kwargs_for(path: Path, source_info: dict) -> dict[str, int | bool | bytes]:
243
+ kwargs: dict[str, int | bool | bytes] = {}
244
+ if source_info.get("icc_profile"):
245
+ kwargs["icc_profile"] = source_info["icc_profile"]
246
+ if source_info.get("exif") and path.suffix.lower() in {".jpg", ".jpeg", ".webp"}:
247
+ kwargs["exif"] = source_info["exif"]
248
+
249
+ suffix = path.suffix.lower()
250
+ if suffix in {".jpg", ".jpeg"}:
251
+ kwargs.update({"quality": 100, "subsampling": 0, "optimize": True})
252
+ elif suffix == ".webp":
253
+ kwargs.update({"quality": 100, "lossless": True, "method": 6})
254
+ elif suffix == ".png":
255
+ kwargs.update({"compress_level": 4})
256
+ return kwargs
257
+
258
+
259
+ def _output_name_for(image_path: Path, output_mode: str) -> str:
260
+ if output_mode == "lossless_png":
261
+ return f"{image_path.stem}.png"
262
+ return image_path.name
263
+
264
+
265
+ def _refine_alpha(alpha: Image.Image, profile: ProcessingProfile) -> Image.Image:
266
+ refined = alpha.convert("L")
267
+ if profile.feather_radius > 0:
268
+ refined = refined.filter(ImageFilter.GaussianBlur(profile.feather_radius))
269
+ if profile.edge_contrast != 1:
270
+ contrast = profile.edge_contrast
271
+ refined = refined.point(
272
+ lambda value: max(0, min(255, int((value - 128) * contrast + 128)))
273
+ )
274
+ return refined
275
+
276
+
277
+ def _decontaminate_white_edges(cutout: Image.Image, alpha: Image.Image, strength: float) -> Image.Image:
278
+ if strength <= 0:
279
+ cutout.putalpha(alpha)
280
+ return cutout
281
+
282
+ rgba = np.asarray(cutout.convert("RGBA"), dtype=np.float32).copy()
283
+ alpha_array = np.asarray(alpha, dtype=np.float32) / 255.0
284
+ edge_mask = (alpha_array > 0.02) & (alpha_array < 0.98)
285
+ if not edge_mask.any():
286
+ rgba[..., 3] = np.asarray(alpha, dtype=np.float32)
287
+ return Image.fromarray(np.clip(rgba, 0, 255).astype(np.uint8), "RGBA")
288
+
289
+ rgb = rgba[..., :3]
290
+ denominator = np.maximum(alpha_array[..., None], 0.02)
291
+ decontaminated = (rgb - ((1.0 - alpha_array[..., None]) * 255.0 * strength)) / denominator
292
+ blend = np.zeros_like(alpha_array)
293
+ blend[edge_mask] = strength
294
+ rgba[..., :3] = (rgb * (1.0 - blend[..., None])) + (
295
+ np.clip(decontaminated, 0, 255) * blend[..., None]
296
+ )
297
+ rgba[..., 3] = np.asarray(alpha, dtype=np.float32)
298
+ return Image.fromarray(np.clip(rgba, 0, 255).astype(np.uint8), "RGBA")
299
+
300
+
301
+ def _prepare_cutout(cutout: Image.Image, size: tuple[int, int], profile: ProcessingProfile) -> Image.Image:
302
+ prepared = cutout.convert("RGBA")
303
+ if prepared.size != size:
304
+ prepared = prepared.resize(size, Image.Resampling.LANCZOS)
305
+
306
+ alpha = _refine_alpha(prepared.getchannel("A"), profile)
307
+ return _decontaminate_white_edges(prepared, alpha, profile.decontaminate_strength)
308
+
309
+
310
+ def _composite_on_background(cutout: Image.Image, bg_rgb: tuple[int, int, int]) -> Image.Image:
311
+ canvas = Image.new("RGB", cutout.size, bg_rgb)
312
+ canvas.paste(cutout, (0, 0), cutout)
313
+ return canvas
314
+
315
+
316
+ def _process_one_image(
317
+ image_path: Path,
318
+ output_path: Path,
319
+ bg_rgb: tuple[int, int, int],
320
+ profile: ProcessingProfile,
321
+ remover: BackgroundRemover,
322
+ ) -> None:
323
+ with Image.open(image_path) as image:
324
+ source_info = dict(image.info)
325
+ cutout = _normalize_cutout(remover(image))
326
+ prepared_cutout = _prepare_cutout(cutout, image.size, profile)
327
+ canvas = _composite_on_background(prepared_cutout, bg_rgb)
328
+ canvas.save(output_path, **_save_kwargs_for(output_path, source_info))
329
+
330
+
331
+ def _zip_output_folder(output_root: Path, folder_name: str, output_zip_path: Path) -> None:
332
+ folder_path = output_root / folder_name
333
+ with zipfile.ZipFile(output_zip_path, "w", zipfile.ZIP_DEFLATED) as archive:
334
+ archive.writestr(f"{folder_name}/", b"")
335
+ for path in sorted(folder_path.rglob("*")):
336
+ if path.is_file():
337
+ archive.write(path, path.relative_to(output_root).as_posix())
338
+
339
+
340
+ def _normalize_cutout(cutout: Image.Image | bytes) -> Image.Image:
341
+ if isinstance(cutout, Image.Image):
342
+ return cutout.convert("RGBA")
343
+ return Image.open(io.BytesIO(cutout)).convert("RGBA")
344
+
345
+
346
+ def process_zip(
347
+ zip_path: Path,
348
+ output_zip_path: Path,
349
+ folder_name: str,
350
+ bg_rgb: tuple[int, int, int],
351
+ *,
352
+ model_name: str = DEFAULT_REMBG_MODEL,
353
+ quality_profile: str = DEFAULT_QUALITY_PROFILE,
354
+ output_mode: str = DEFAULT_OUTPUT_MODE,
355
+ progress_callback: ProgressCallback | None = None,
356
+ remover: BackgroundRemover | None = None,
357
+ ) -> ProcessResult:
358
+ folder_name = sanitize_folder_name(folder_name)
359
+ validated_profile = validate_quality_profile(quality_profile)
360
+ validated_output_mode = validate_output_mode(output_mode)
361
+ profile = PROFILE_CONFIGS[validated_profile]
362
+ output_zip_path.parent.mkdir(parents=True, exist_ok=True)
363
+
364
+ with tempfile.TemporaryDirectory(prefix="backdropstudio-") as work_dir_name:
365
+ work_dir = Path(work_dir_name)
366
+ extract_dir = work_dir / "source"
367
+ output_root = work_dir / "output"
368
+ output_folder = output_root / folder_name
369
+ output_folder.mkdir(parents=True, exist_ok=True)
370
+
371
+ safe_extract_zip(zip_path, extract_dir)
372
+ image_files = collect_image_files(extract_dir)
373
+ total = len(image_files)
374
+ completed = 0
375
+ failed_files: list[str] = []
376
+ seen_output_names: set[str] = set()
377
+ tasks: list[tuple[int, Path, str, Path]] = []
378
+
379
+ if progress_callback:
380
+ progress_callback(total, completed, failed_files.copy())
381
+
382
+ active_remover = remover or build_background_remover(model_name, validated_profile)
383
+ last_error: Exception | None = None
384
+
385
+ for index, image_path in enumerate(image_files):
386
+ relative_name = image_path.relative_to(extract_dir).as_posix()
387
+ output_name = _output_name_for(image_path, validated_output_mode)
388
+ output_path = output_folder / output_name
389
+
390
+ if output_name.lower() in seen_output_names:
391
+ last_error = DuplicateOutputNameError(
392
+ f"Duplicate filename would overwrite output: {output_name}"
393
+ )
394
+ failed_files.append(relative_name)
395
+ completed += 1
396
+ if progress_callback:
397
+ progress_callback(total, completed, failed_files.copy())
398
+ continue
399
+
400
+ seen_output_names.add(output_name.lower())
401
+ tasks.append((index, image_path, relative_name, output_path))
402
+
403
+ failed_records: list[tuple[int, str]] = []
404
+ max_workers = min(get_max_workers(), max(1, len(tasks)))
405
+
406
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
407
+ futures = {
408
+ executor.submit(
409
+ _process_one_image,
410
+ image_path,
411
+ output_path,
412
+ bg_rgb,
413
+ profile,
414
+ active_remover,
415
+ ): (index, relative_name)
416
+ for index, image_path, relative_name, output_path in tasks
417
+ }
418
+
419
+ for future in as_completed(futures):
420
+ index, relative_name = futures[future]
421
+ try:
422
+ future.result()
423
+ except Exception as exc:
424
+ last_error = exc
425
+ failed_records.append((index, relative_name))
426
+
427
+ completed += 1
428
+ failed_files = [
429
+ name for _, name in sorted(failed_records)
430
+ ] + [
431
+ name
432
+ for name in failed_files
433
+ if name not in {record_name for _, record_name in failed_records}
434
+ ]
435
+ if progress_callback:
436
+ progress_callback(total, completed, failed_files.copy())
437
+
438
+ if total > 0 and len(failed_files) == total:
439
+ detail = f" Last error: {last_error}" if last_error else ""
440
+ raise RuntimeError(f"All {total} image files failed during processing.{detail}")
441
+
442
+ _zip_output_folder(output_root, folder_name, output_zip_path)
443
+
444
+ return ProcessResult(
445
+ output_zip_path=output_zip_path,
446
+ total=total,
447
+ completed=completed,
448
+ failed_files=failed_files,
449
+ )
app/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ python-multipart
4
+ rembg[cpu]
5
+ pillow>=12.1
6
+ onnxruntime
7
+ msvc-runtime; platform_system == "Windows"
app/static/index.html ADDED
@@ -0,0 +1,923 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>BackDropStudio</title>
7
+ <style>
8
+ :root {
9
+ --bg: #f6f8fb;
10
+ --surface: #ffffff;
11
+ --surface-soft: #eef5f5;
12
+ --surface-strong: #e6eeee;
13
+ --text: #101827;
14
+ --muted: #5b6678;
15
+ --subtle: #7b8493;
16
+ --border: #d8e0e8;
17
+ --border-strong: #b8c6d3;
18
+ --accent: #007f86;
19
+ --accent-dark: #00626a;
20
+ --accent-soft: #e1f4f4;
21
+ --ink: #0d1628;
22
+ --success: #157347;
23
+ --danger: #b42318;
24
+ --warning: #a15c07;
25
+ --focus: rgba(0, 127, 134, 0.18);
26
+ --shadow: 0 24px 70px rgba(16, 24, 39, 0.12);
27
+ --radius: 8px;
28
+ }
29
+
30
+ * {
31
+ box-sizing: border-box;
32
+ }
33
+
34
+ html {
35
+ color-scheme: light;
36
+ }
37
+
38
+ body {
39
+ margin: 0;
40
+ min-height: 100vh;
41
+ background:
42
+ linear-gradient(145deg, rgba(0, 127, 134, 0.1), rgba(246, 248, 251, 0) 34%),
43
+ linear-gradient(320deg, rgba(219, 165, 75, 0.08), rgba(246, 248, 251, 0) 38%),
44
+ var(--bg);
45
+ color: var(--text);
46
+ font-family:
47
+ Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
48
+ sans-serif;
49
+ line-height: 1.5;
50
+ }
51
+
52
+ button,
53
+ input {
54
+ font: inherit;
55
+ }
56
+
57
+ button,
58
+ label {
59
+ -webkit-tap-highlight-color: transparent;
60
+ }
61
+
62
+ .shell {
63
+ width: min(1160px, calc(100% - 32px));
64
+ margin: 0 auto;
65
+ padding: 30px 0 48px;
66
+ }
67
+
68
+ header {
69
+ display: flex;
70
+ align-items: center;
71
+ justify-content: space-between;
72
+ gap: 24px;
73
+ margin-bottom: 34px;
74
+ }
75
+
76
+ .brand {
77
+ display: inline-flex;
78
+ align-items: center;
79
+ gap: 12px;
80
+ color: var(--text);
81
+ font-size: 1.03rem;
82
+ font-weight: 820;
83
+ letter-spacing: 0;
84
+ }
85
+
86
+ .brand-mark {
87
+ display: grid;
88
+ width: 38px;
89
+ height: 38px;
90
+ place-items: center;
91
+ border-radius: var(--radius);
92
+ background: var(--ink);
93
+ color: #ffffff;
94
+ }
95
+
96
+ .brand-mark svg {
97
+ width: 21px;
98
+ height: 21px;
99
+ }
100
+
101
+ .header-note {
102
+ margin: 0;
103
+ color: var(--muted);
104
+ font-size: 0.92rem;
105
+ }
106
+
107
+ main {
108
+ display: grid;
109
+ grid-template-columns: minmax(0, 0.92fr) minmax(390px, 1.08fr);
110
+ gap: 34px;
111
+ align-items: start;
112
+ }
113
+
114
+ .intro {
115
+ padding-top: 22px;
116
+ }
117
+
118
+ h1 {
119
+ margin: 0;
120
+ max-width: 690px;
121
+ color: var(--ink);
122
+ font-size: clamp(2.45rem, 5vw, 5.25rem);
123
+ font-weight: 860;
124
+ line-height: 0.96;
125
+ letter-spacing: 0;
126
+ }
127
+
128
+ .intro-copy {
129
+ max-width: 575px;
130
+ margin: 24px 0 0;
131
+ color: var(--muted);
132
+ font-size: 1.06rem;
133
+ }
134
+
135
+ .proof-strip {
136
+ display: grid;
137
+ grid-template-columns: repeat(3, minmax(0, 1fr));
138
+ gap: 10px;
139
+ max-width: 600px;
140
+ margin-top: 30px;
141
+ }
142
+
143
+ .proof-item {
144
+ min-height: 92px;
145
+ padding: 15px;
146
+ border: 1px solid var(--border);
147
+ border-radius: var(--radius);
148
+ background: rgba(255, 255, 255, 0.62);
149
+ }
150
+
151
+ .proof-item strong {
152
+ display: block;
153
+ color: var(--ink);
154
+ font-size: 0.93rem;
155
+ line-height: 1.25;
156
+ }
157
+
158
+ .proof-item span {
159
+ display: block;
160
+ margin-top: 6px;
161
+ color: var(--muted);
162
+ font-size: 0.84rem;
163
+ line-height: 1.4;
164
+ }
165
+
166
+ .panel {
167
+ overflow: hidden;
168
+ border: 1px solid var(--border);
169
+ border-radius: var(--radius);
170
+ background: var(--surface);
171
+ box-shadow: var(--shadow);
172
+ }
173
+
174
+ .panel-header {
175
+ display: flex;
176
+ align-items: center;
177
+ justify-content: space-between;
178
+ gap: 16px;
179
+ padding: 22px 24px;
180
+ border-bottom: 1px solid var(--border);
181
+ background: #fbfcfd;
182
+ }
183
+
184
+ .panel-header h2 {
185
+ margin: 0;
186
+ color: var(--ink);
187
+ font-size: 1rem;
188
+ line-height: 1.25;
189
+ }
190
+
191
+ .status-dot {
192
+ display: inline-flex;
193
+ align-items: center;
194
+ gap: 8px;
195
+ min-width: max-content;
196
+ color: var(--muted);
197
+ font-size: 0.86rem;
198
+ font-weight: 720;
199
+ }
200
+
201
+ .status-dot::before {
202
+ content: "";
203
+ width: 8px;
204
+ height: 8px;
205
+ border-radius: 50%;
206
+ background: var(--accent);
207
+ }
208
+
209
+ .status-dot[data-state="done"]::before {
210
+ background: var(--success);
211
+ }
212
+
213
+ .status-dot[data-state="error"]::before {
214
+ background: var(--danger);
215
+ }
216
+
217
+ form {
218
+ display: grid;
219
+ gap: 20px;
220
+ padding: 24px;
221
+ }
222
+
223
+ .field {
224
+ display: grid;
225
+ gap: 8px;
226
+ }
227
+
228
+ .field-row {
229
+ display: grid;
230
+ grid-template-columns: repeat(2, minmax(0, 1fr));
231
+ gap: 16px;
232
+ }
233
+
234
+ .field-label {
235
+ display: flex;
236
+ align-items: baseline;
237
+ justify-content: space-between;
238
+ gap: 12px;
239
+ color: var(--ink);
240
+ font-size: 0.9rem;
241
+ font-weight: 760;
242
+ }
243
+
244
+ .field-label span {
245
+ color: var(--subtle);
246
+ font-size: 0.78rem;
247
+ font-weight: 650;
248
+ }
249
+
250
+ .field-help {
251
+ margin: 0;
252
+ color: var(--muted);
253
+ font-size: 0.84rem;
254
+ }
255
+
256
+ .drop-zone {
257
+ display: grid;
258
+ gap: 12px;
259
+ min-height: 154px;
260
+ padding: 22px;
261
+ place-items: center;
262
+ border: 1.5px dashed var(--border-strong);
263
+ border-radius: var(--radius);
264
+ background:
265
+ linear-gradient(180deg, rgba(225, 244, 244, 0.5), rgba(255, 255, 255, 0.72)),
266
+ var(--surface);
267
+ color: var(--text);
268
+ cursor: pointer;
269
+ text-align: center;
270
+ transition:
271
+ border-color 160ms ease,
272
+ background 160ms ease,
273
+ transform 160ms ease;
274
+ }
275
+
276
+ .drop-zone:hover,
277
+ .drop-zone.is-dragging {
278
+ border-color: var(--accent);
279
+ background: var(--accent-soft);
280
+ transform: translateY(-1px);
281
+ }
282
+
283
+ .drop-zone:focus-within {
284
+ border-color: var(--accent);
285
+ box-shadow: 0 0 0 4px var(--focus);
286
+ }
287
+
288
+ .drop-icon {
289
+ display: grid;
290
+ width: 44px;
291
+ height: 44px;
292
+ place-items: center;
293
+ border-radius: var(--radius);
294
+ background: var(--ink);
295
+ color: #ffffff;
296
+ }
297
+
298
+ .drop-icon svg {
299
+ width: 23px;
300
+ height: 23px;
301
+ }
302
+
303
+ .drop-copy strong {
304
+ display: block;
305
+ font-size: 1rem;
306
+ font-weight: 780;
307
+ }
308
+
309
+ .drop-copy span,
310
+ .file-name {
311
+ display: block;
312
+ margin-top: 3px;
313
+ color: var(--muted);
314
+ font-size: 0.86rem;
315
+ }
316
+
317
+ .file-input {
318
+ position: absolute;
319
+ width: 1px;
320
+ height: 1px;
321
+ overflow: hidden;
322
+ clip: rect(0, 0, 0, 0);
323
+ white-space: nowrap;
324
+ }
325
+
326
+ input[type="text"] {
327
+ width: 100%;
328
+ height: 46px;
329
+ padding: 0 14px;
330
+ border: 1px solid var(--border);
331
+ border-radius: var(--radius);
332
+ background: var(--surface);
333
+ color: var(--text);
334
+ font-size: 0.96rem;
335
+ outline: none;
336
+ transition:
337
+ border-color 150ms ease,
338
+ box-shadow 150ms ease;
339
+ }
340
+
341
+ input[type="color"] {
342
+ width: 50px;
343
+ height: 46px;
344
+ padding: 4px;
345
+ border: 1px solid var(--border);
346
+ border-radius: var(--radius);
347
+ background: var(--surface);
348
+ cursor: pointer;
349
+ }
350
+
351
+ input:focus-visible {
352
+ border-color: var(--accent);
353
+ box-shadow: 0 0 0 4px var(--focus);
354
+ }
355
+
356
+ .color-row {
357
+ display: grid;
358
+ grid-template-columns: 50px minmax(0, 1fr);
359
+ gap: 10px;
360
+ align-items: center;
361
+ }
362
+
363
+ .segmented {
364
+ display: grid;
365
+ grid-template-columns: repeat(3, minmax(0, 1fr));
366
+ gap: 6px;
367
+ padding: 5px;
368
+ border: 1px solid var(--border);
369
+ border-radius: var(--radius);
370
+ background: var(--surface-soft);
371
+ }
372
+
373
+ .segmented.two {
374
+ grid-template-columns: repeat(2, minmax(0, 1fr));
375
+ }
376
+
377
+ .segmented input {
378
+ position: absolute;
379
+ opacity: 0;
380
+ pointer-events: none;
381
+ }
382
+
383
+ .segmented label {
384
+ display: grid;
385
+ min-height: 54px;
386
+ place-items: center;
387
+ padding: 8px 10px;
388
+ border: 1px solid transparent;
389
+ border-radius: 7px;
390
+ color: var(--muted);
391
+ cursor: pointer;
392
+ font-size: 0.82rem;
393
+ font-weight: 780;
394
+ line-height: 1.15;
395
+ text-align: center;
396
+ transition:
397
+ background 150ms ease,
398
+ border-color 150ms ease,
399
+ color 150ms ease,
400
+ box-shadow 150ms ease;
401
+ }
402
+
403
+ .segmented input:checked + label {
404
+ border-color: var(--border);
405
+ background: var(--surface);
406
+ color: var(--ink);
407
+ box-shadow: 0 6px 18px rgba(16, 24, 39, 0.08);
408
+ }
409
+
410
+ .segmented input:focus-visible + label {
411
+ box-shadow: 0 0 0 4px var(--focus);
412
+ }
413
+
414
+ .submit-button,
415
+ .download-button {
416
+ display: inline-flex;
417
+ align-items: center;
418
+ justify-content: center;
419
+ gap: 10px;
420
+ width: 100%;
421
+ min-height: 50px;
422
+ border: 0;
423
+ border-radius: var(--radius);
424
+ background: var(--accent);
425
+ color: #ffffff;
426
+ cursor: pointer;
427
+ font-size: 0.98rem;
428
+ font-weight: 820;
429
+ text-decoration: none;
430
+ transition:
431
+ background 150ms ease,
432
+ transform 150ms ease,
433
+ box-shadow 150ms ease;
434
+ }
435
+
436
+ .submit-button:hover,
437
+ .download-button:hover {
438
+ background: var(--accent-dark);
439
+ box-shadow: 0 12px 28px rgba(0, 127, 134, 0.2);
440
+ transform: translateY(-1px);
441
+ }
442
+
443
+ .submit-button:disabled {
444
+ cursor: not-allowed;
445
+ opacity: 0.62;
446
+ box-shadow: none;
447
+ transform: none;
448
+ }
449
+
450
+ .submit-button svg,
451
+ .download-button svg {
452
+ width: 19px;
453
+ height: 19px;
454
+ }
455
+
456
+ .progress-area {
457
+ display: grid;
458
+ gap: 14px;
459
+ padding: 0 24px 24px;
460
+ }
461
+
462
+ .progress-shell {
463
+ overflow: hidden;
464
+ height: 12px;
465
+ border-radius: 999px;
466
+ background: var(--surface-strong);
467
+ }
468
+
469
+ .progress-fill {
470
+ width: 0%;
471
+ height: 100%;
472
+ border-radius: inherit;
473
+ background: linear-gradient(90deg, var(--accent), #0e9f8f);
474
+ transition: width 260ms ease;
475
+ }
476
+
477
+ .progress-copy {
478
+ margin: 0;
479
+ color: var(--muted);
480
+ font-size: 0.92rem;
481
+ }
482
+
483
+ .message {
484
+ display: none;
485
+ margin: 0;
486
+ padding: 13px 14px;
487
+ border-radius: var(--radius);
488
+ font-size: 0.9rem;
489
+ }
490
+
491
+ .message.is-visible {
492
+ display: block;
493
+ }
494
+
495
+ .message.error {
496
+ border: 1px solid rgba(180, 35, 24, 0.24);
497
+ background: #fff1f0;
498
+ color: var(--danger);
499
+ }
500
+
501
+ .message.warning {
502
+ border: 1px solid rgba(161, 92, 7, 0.24);
503
+ background: #fff7ed;
504
+ color: var(--warning);
505
+ }
506
+
507
+ .download-slot {
508
+ display: none;
509
+ }
510
+
511
+ .download-slot.is-visible {
512
+ display: block;
513
+ }
514
+
515
+ @media (max-width: 920px) {
516
+ .shell {
517
+ width: min(100% - 24px, 720px);
518
+ padding-top: 22px;
519
+ }
520
+
521
+ header {
522
+ align-items: flex-start;
523
+ flex-direction: column;
524
+ margin-bottom: 24px;
525
+ }
526
+
527
+ main {
528
+ grid-template-columns: 1fr;
529
+ gap: 28px;
530
+ }
531
+
532
+ .intro {
533
+ padding-top: 0;
534
+ }
535
+
536
+ h1 {
537
+ font-size: clamp(2.35rem, 12vw, 4.2rem);
538
+ }
539
+ }
540
+
541
+ @media (max-width: 620px) {
542
+ .field-row,
543
+ .proof-strip {
544
+ grid-template-columns: 1fr;
545
+ }
546
+
547
+ .segmented {
548
+ grid-template-columns: 1fr;
549
+ }
550
+
551
+ .segmented.two {
552
+ grid-template-columns: 1fr;
553
+ }
554
+
555
+ .panel-header,
556
+ form,
557
+ .progress-area {
558
+ padding-left: 18px;
559
+ padding-right: 18px;
560
+ }
561
+
562
+ .drop-zone {
563
+ min-height: 142px;
564
+ padding: 18px;
565
+ }
566
+ }
567
+
568
+ @media (prefers-reduced-motion: reduce) {
569
+ *,
570
+ *::before,
571
+ *::after {
572
+ scroll-behavior: auto !important;
573
+ transition: none !important;
574
+ }
575
+ }
576
+ </style>
577
+ </head>
578
+ <body>
579
+ <div class="shell">
580
+ <header>
581
+ <div class="brand" aria-label="BackDropStudio">
582
+ <span class="brand-mark" aria-hidden="true">
583
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
584
+ <path d="M4 7h16" />
585
+ <path d="M4 17h16" />
586
+ <path d="M7 4v16" />
587
+ <path d="M17 4v16" />
588
+ </svg>
589
+ </span>
590
+ BackDropStudio
591
+ </div>
592
+ <p class="header-note">Local batch background replacement</p>
593
+ </header>
594
+
595
+ <main>
596
+ <section class="intro" aria-labelledby="page-title">
597
+ <h1 id="page-title">Catalog-ready backgrounds without filename drift.</h1>
598
+ <p class="intro-copy">
599
+ Upload a ZIP, choose the exact backdrop color, and export a clean batch
600
+ with dimensions preserved for SKU-driven imports.
601
+ </p>
602
+
603
+ <div class="proof-strip" aria-label="Processing guarantees">
604
+ <div class="proof-item">
605
+ <strong>Exact canvas color</strong>
606
+ <span>PNG mode preserves edited pixels without lossy compression.</span>
607
+ </div>
608
+ <div class="proof-item">
609
+ <strong>Refined edges</strong>
610
+ <span>Pro mode uses alpha matting, feathering, and white-edge cleanup.</span>
611
+ </div>
612
+ <div class="proof-item">
613
+ <strong>Batch-safe output</strong>
614
+ <span>Dimensions stay fixed and filenames remain import-friendly.</span>
615
+ </div>
616
+ </div>
617
+ </section>
618
+
619
+ <section class="panel" aria-labelledby="upload-title">
620
+ <div class="panel-header">
621
+ <h2 id="upload-title">Batch setup</h2>
622
+ <span class="status-dot" id="statusLabel" data-state="ready">Ready</span>
623
+ </div>
624
+
625
+ <form id="processForm">
626
+ <div class="field">
627
+ <label class="field-label" for="zipFile">Product photo ZIP <span>Max 500MB</span></label>
628
+ <label class="drop-zone" id="dropZone" for="zipFile">
629
+ <span class="drop-icon" aria-hidden="true">
630
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
631
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
632
+ <path d="M17 8 12 3 7 8" />
633
+ <path d="M12 3v12" />
634
+ </svg>
635
+ </span>
636
+ <span class="drop-copy">
637
+ <strong>Drop your ZIP here or browse</strong>
638
+ <span>JPG, PNG, and WebP files are detected automatically.</span>
639
+ <span class="file-name" id="fileName">No file selected</span>
640
+ </span>
641
+ </label>
642
+ <input class="file-input" id="zipFile" name="file" type="file" accept=".zip,application/zip" required />
643
+ </div>
644
+
645
+ <div class="field-row">
646
+ <div class="field">
647
+ <label class="field-label" for="bgColor">Background color</label>
648
+ <div class="color-row">
649
+ <input id="colorPicker" type="color" value="#f1f2f2" aria-label="Pick background color" />
650
+ <input id="bgColor" name="bg_color" type="text" value="241,242,242" autocomplete="off" />
651
+ </div>
652
+ <p class="field-help">Use RGB like 241,242,242 or hex like #F1F2F2.</p>
653
+ </div>
654
+
655
+ <div class="field">
656
+ <label class="field-label" for="folderName">Output folder</label>
657
+ <input id="folderName" name="folder_name" type="text" value="Grey" autocomplete="off" />
658
+ <p class="field-help">This becomes the subfolder inside the ZIP.</p>
659
+ </div>
660
+ </div>
661
+
662
+ <div class="field">
663
+ <span class="field-label">Quality profile</span>
664
+ <div class="segmented" role="radiogroup" aria-label="Quality profile">
665
+ <input id="qualityPro" name="quality_profile" type="radio" value="pro" checked />
666
+ <label for="qualityPro">Pro quality</label>
667
+ <input id="qualityBalanced" name="quality_profile" type="radio" value="balanced" />
668
+ <label for="qualityBalanced">Balanced</label>
669
+ <input id="qualityFast" name="quality_profile" type="radio" value="fast" />
670
+ <label for="qualityFast">Fast</label>
671
+ </div>
672
+ </div>
673
+
674
+ <div class="field">
675
+ <span class="field-label">Output mode</span>
676
+ <div class="segmented two" role="radiogroup" aria-label="Output mode">
677
+ <input id="outputOriginal" name="output_mode" type="radio" value="preserve_original" checked />
678
+ <label for="outputOriginal">Preserve names</label>
679
+ <input id="outputPng" name="output_mode" type="radio" value="lossless_png" />
680
+ <label for="outputPng">Lossless PNG</label>
681
+ </div>
682
+ <p class="field-help">Preserve names keeps extensions. Lossless PNG gives exact edited pixels.</p>
683
+ </div>
684
+
685
+ <button class="submit-button" id="submitButton" type="submit">
686
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
687
+ <path d="M5 12h14" />
688
+ <path d="m12 5 7 7-7 7" />
689
+ </svg>
690
+ Start processing
691
+ </button>
692
+ </form>
693
+
694
+ <div class="progress-area" aria-live="polite">
695
+ <div class="progress-shell" aria-hidden="true">
696
+ <div class="progress-fill" id="progressFill"></div>
697
+ </div>
698
+ <p class="progress-copy" id="progressText">No job running.</p>
699
+ <p class="message error" id="errorMessage"></p>
700
+ <p class="message warning" id="warningMessage"></p>
701
+ <div class="download-slot" id="downloadSlot">
702
+ <a class="download-button" id="downloadButton" href="#">
703
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
704
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
705
+ <path d="M7 10l5 5 5-5" />
706
+ <path d="M12 15V3" />
707
+ </svg>
708
+ Download ZIP
709
+ </a>
710
+ </div>
711
+ </div>
712
+ </section>
713
+ </main>
714
+ </div>
715
+
716
+ <script>
717
+ const form = document.querySelector("#processForm");
718
+ const zipFile = document.querySelector("#zipFile");
719
+ const fileName = document.querySelector("#fileName");
720
+ const dropZone = document.querySelector("#dropZone");
721
+ const submitButton = document.querySelector("#submitButton");
722
+ const statusLabel = document.querySelector("#statusLabel");
723
+ const progressFill = document.querySelector("#progressFill");
724
+ const progressText = document.querySelector("#progressText");
725
+ const errorMessage = document.querySelector("#errorMessage");
726
+ const warningMessage = document.querySelector("#warningMessage");
727
+ const downloadSlot = document.querySelector("#downloadSlot");
728
+ const downloadButton = document.querySelector("#downloadButton");
729
+ const bgColor = document.querySelector("#bgColor");
730
+ const colorPicker = document.querySelector("#colorPicker");
731
+
732
+ let pollTimer = null;
733
+
734
+ function rgbToHex(rgb) {
735
+ return `#${rgb.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
736
+ }
737
+
738
+ function parseColor(value) {
739
+ const trimmed = value.trim();
740
+ if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {
741
+ return {
742
+ hex: trimmed.toLowerCase(),
743
+ rgb: [1, 3, 5].map((index) => Number.parseInt(trimmed.slice(index, index + 2), 16)),
744
+ };
745
+ }
746
+
747
+ const parts = trimmed.split(",").map((part) => Number.parseInt(part.trim(), 10));
748
+ if (parts.length === 3 && parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
749
+ return { hex: rgbToHex(parts), rgb: parts };
750
+ }
751
+ return null;
752
+ }
753
+
754
+ function setStatus(text, state = "ready") {
755
+ statusLabel.textContent = text;
756
+ statusLabel.dataset.state = state;
757
+ }
758
+
759
+ function showMessage(element, message) {
760
+ element.textContent = message || "";
761
+ element.classList.toggle("is-visible", Boolean(message));
762
+ }
763
+
764
+ function resetMessages() {
765
+ showMessage(errorMessage, "");
766
+ showMessage(warningMessage, "");
767
+ downloadSlot.classList.remove("is-visible");
768
+ downloadButton.removeAttribute("href");
769
+ }
770
+
771
+ function updateFileName() {
772
+ const selectedFile = zipFile.files && zipFile.files[0];
773
+ fileName.textContent = selectedFile ? selectedFile.name : "No file selected";
774
+ }
775
+
776
+ function syncColorFromText() {
777
+ const parsed = parseColor(bgColor.value);
778
+ if (parsed) {
779
+ colorPicker.value = parsed.hex;
780
+ }
781
+ }
782
+
783
+ function syncColorFromPicker() {
784
+ const parsed = parseColor(colorPicker.value);
785
+ if (parsed) {
786
+ bgColor.value = parsed.rgb.join(",");
787
+ }
788
+ }
789
+
790
+ function setProgress(status) {
791
+ const total = status.total || 0;
792
+ const completed = status.completed || 0;
793
+ const percent = total > 0 ? Math.round((completed / total) * 100) : 0;
794
+ progressFill.style.width = `${Math.min(percent, 100)}%`;
795
+
796
+ if (status.status === "processing") {
797
+ progressText.textContent = total > 0 ? `Processing ${completed} / ${total} files...` : "Preparing the batch...";
798
+ setStatus("Processing", "processing");
799
+ } else if (status.status === "done") {
800
+ progressFill.style.width = "100%";
801
+ progressText.textContent = `Done. Exported ${completed} image${completed === 1 ? "" : "s"}.`;
802
+ setStatus("Ready to download", "done");
803
+ } else if (status.status === "failed") {
804
+ progressText.textContent = "The job failed before a ZIP could be created.";
805
+ setStatus("Failed", "error");
806
+ }
807
+ }
808
+
809
+ async function pollStatus(jobId) {
810
+ try {
811
+ const response = await fetch(`/api/status/${jobId}`);
812
+ if (!response.ok) {
813
+ throw new Error("Unable to read job status.");
814
+ }
815
+
816
+ const status = await response.json();
817
+ setProgress(status);
818
+
819
+ if (status.failed_files && status.failed_files.length > 0) {
820
+ showMessage(
821
+ warningMessage,
822
+ `Skipped ${status.failed_files.length} file${status.failed_files.length === 1 ? "" : "s"}: ${status.failed_files.join(", ")}`
823
+ );
824
+ }
825
+
826
+ if (status.status === "done") {
827
+ window.clearInterval(pollTimer);
828
+ pollTimer = null;
829
+ submitButton.disabled = false;
830
+ downloadButton.href = `/api/download/${jobId}`;
831
+ downloadSlot.classList.add("is-visible");
832
+ }
833
+
834
+ if (status.status === "failed") {
835
+ window.clearInterval(pollTimer);
836
+ pollTimer = null;
837
+ submitButton.disabled = false;
838
+ showMessage(errorMessage, status.error || "Processing failed.");
839
+ }
840
+ } catch (error) {
841
+ window.clearInterval(pollTimer);
842
+ pollTimer = null;
843
+ submitButton.disabled = false;
844
+ setStatus("Error", "error");
845
+ showMessage(errorMessage, error.message || "Unable to check status.");
846
+ }
847
+ }
848
+
849
+ zipFile.addEventListener("change", updateFileName);
850
+ bgColor.addEventListener("input", syncColorFromText);
851
+ colorPicker.addEventListener("input", syncColorFromPicker);
852
+ syncColorFromText();
853
+
854
+ ["dragenter", "dragover"].forEach((eventName) => {
855
+ dropZone.addEventListener(eventName, (event) => {
856
+ event.preventDefault();
857
+ dropZone.classList.add("is-dragging");
858
+ });
859
+ });
860
+
861
+ ["dragleave", "drop"].forEach((eventName) => {
862
+ dropZone.addEventListener(eventName, (event) => {
863
+ event.preventDefault();
864
+ dropZone.classList.remove("is-dragging");
865
+ });
866
+ });
867
+
868
+ dropZone.addEventListener("drop", (event) => {
869
+ const [file] = event.dataTransfer.files;
870
+ if (!file) {
871
+ return;
872
+ }
873
+
874
+ const dataTransfer = new DataTransfer();
875
+ dataTransfer.items.add(file);
876
+ zipFile.files = dataTransfer.files;
877
+ updateFileName();
878
+ });
879
+
880
+ form.addEventListener("submit", async (event) => {
881
+ event.preventDefault();
882
+ resetMessages();
883
+
884
+ if (!parseColor(bgColor.value)) {
885
+ showMessage(errorMessage, "Use a valid RGB value or #RRGGBB color.");
886
+ setStatus("Error", "error");
887
+ return;
888
+ }
889
+
890
+ submitButton.disabled = true;
891
+ setStatus("Uploading", "processing");
892
+ progressText.textContent = "Uploading ZIP...";
893
+ progressFill.style.width = "0%";
894
+
895
+ if (pollTimer) {
896
+ window.clearInterval(pollTimer);
897
+ pollTimer = null;
898
+ }
899
+
900
+ try {
901
+ const response = await fetch("/api/process", {
902
+ method: "POST",
903
+ body: new FormData(form),
904
+ });
905
+
906
+ const payload = await response.json().catch(() => ({}));
907
+ if (!response.ok) {
908
+ throw new Error(payload.detail || "Upload failed.");
909
+ }
910
+
911
+ const jobId = payload.job_id;
912
+ await pollStatus(jobId);
913
+ pollTimer = window.setInterval(() => pollStatus(jobId), 1500);
914
+ } catch (error) {
915
+ submitButton.disabled = false;
916
+ setStatus("Error", "error");
917
+ progressText.textContent = "No job running.";
918
+ showMessage(errorMessage, error.message || "Upload failed.");
919
+ }
920
+ });
921
+ </script>
922
+ </body>
923
+ </html>
test bg.zip ADDED
Binary file (84.5 kB). View file
 
tests/test_api.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ import zipfile
3
+ from pathlib import Path
4
+ from unittest.mock import patch
5
+
6
+ try:
7
+ from fastapi.testclient import TestClient
8
+
9
+ from app.main import app
10
+ from app.processor import ProcessResult
11
+
12
+ FASTAPI_IMPORT_ERROR = None
13
+ except Exception as exc: # pragma: no cover
14
+ TestClient = None
15
+ app = None
16
+ FASTAPI_IMPORT_ERROR = exc
17
+
18
+
19
+ @unittest.skipIf(TestClient is None, f"FastAPI test client unavailable: {FASTAPI_IMPORT_ERROR}")
20
+ class ApiTests(unittest.TestCase):
21
+ def setUp(self):
22
+ self.client = TestClient(app)
23
+
24
+ def test_process_rejects_non_zip_uploads(self):
25
+ response = self.client.post(
26
+ "/api/process",
27
+ files={"file": ("photo.jpg", b"not a zip", "image/jpeg")},
28
+ data={"bg_color": "241,242,242", "folder_name": "Grey"},
29
+ )
30
+
31
+ self.assertEqual(response.status_code, 400)
32
+ self.assertEqual(response.json()["detail"], "Please upload a .zip file.")
33
+
34
+ def test_status_returns_not_found_for_unknown_job(self):
35
+ response = self.client.get("/api/status/missing-job")
36
+
37
+ self.assertEqual(response.status_code, 404)
38
+
39
+ def test_process_accepts_new_quality_fields(self):
40
+ def fake_process_zip(
41
+ zip_path,
42
+ output_zip_path,
43
+ folder_name,
44
+ bg_rgb,
45
+ *,
46
+ quality_profile,
47
+ output_mode,
48
+ progress_callback,
49
+ ):
50
+ self.assertEqual(folder_name, "Grey")
51
+ self.assertEqual(bg_rgb, (241, 242, 242))
52
+ self.assertEqual(quality_profile, "pro")
53
+ self.assertEqual(output_mode, "lossless_png")
54
+ progress_callback(1, 0, [])
55
+ with zipfile.ZipFile(output_zip_path, "w") as archive:
56
+ archive.writestr("Grey/", b"")
57
+ archive.writestr("Grey/SKU-100.png", b"fake")
58
+ progress_callback(1, 1, [])
59
+ return ProcessResult(Path(output_zip_path), 1, 1, [])
60
+
61
+ with patch("app.main.process_zip", side_effect=fake_process_zip):
62
+ response = self.client.post(
63
+ "/api/process",
64
+ files={"file": ("input.zip", b"PK\x05\x06" + b"\x00" * 18, "application/zip")},
65
+ data={
66
+ "bg_color": "#F1F2F2",
67
+ "folder_name": "Grey",
68
+ "quality_profile": "pro",
69
+ "output_mode": "lossless_png",
70
+ },
71
+ )
72
+
73
+ self.assertEqual(response.status_code, 200)
74
+ status = self.client.get(f"/api/status/{response.json()['job_id']}")
75
+ self.assertEqual(status.json()["status"], "done")
76
+ self.assertEqual(status.json()["failed_files"], [])
77
+
78
+ def test_process_rejects_invalid_quality_profile(self):
79
+ response = self.client.post(
80
+ "/api/process",
81
+ files={"file": ("input.zip", b"PK\x05\x06" + b"\x00" * 18, "application/zip")},
82
+ data={"quality_profile": "ultra"},
83
+ )
84
+
85
+ self.assertEqual(response.status_code, 400)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ unittest.main()
tests/test_processor.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import unittest
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ try:
7
+ from PIL import Image
8
+ except ImportError: # pragma: no cover
9
+ Image = None
10
+
11
+ from app.processor import (
12
+ ZipSlipError,
13
+ _save_kwargs_for,
14
+ parse_bg_color,
15
+ process_zip,
16
+ safe_extract_zip,
17
+ sanitize_folder_name,
18
+ validate_output_mode,
19
+ validate_quality_profile,
20
+ )
21
+
22
+
23
+ class ProcessorValidationTests(unittest.TestCase):
24
+ def test_parse_bg_color_accepts_rgb_and_hex(self):
25
+ self.assertEqual(parse_bg_color("241, 242, 242"), (241, 242, 242))
26
+ self.assertEqual(parse_bg_color("#F1F2F2"), (241, 242, 242))
27
+
28
+ def test_parse_bg_color_rejects_invalid_values(self):
29
+ with self.assertRaises(ValueError):
30
+ parse_bg_color("300,0,0")
31
+ with self.assertRaises(ValueError):
32
+ parse_bg_color("#XYZ123")
33
+
34
+ def test_sanitize_folder_name(self):
35
+ self.assertEqual(sanitize_folder_name(" Grey "), "Grey")
36
+ for unsafe in ("", "../Grey", "Grey/Blue", "Grey\\Blue", "C:Grey"):
37
+ with self.subTest(unsafe=unsafe):
38
+ with self.assertRaises(ValueError):
39
+ sanitize_folder_name(unsafe)
40
+
41
+ def test_validates_quality_profile_and_output_mode(self):
42
+ self.assertEqual(validate_quality_profile("Pro"), "pro")
43
+ self.assertEqual(validate_output_mode("lossless_png"), "lossless_png")
44
+
45
+ with self.assertRaises(ValueError):
46
+ validate_quality_profile("ultra")
47
+ with self.assertRaises(ValueError):
48
+ validate_output_mode("gif")
49
+
50
+
51
+ class ZipSafetyTests(unittest.TestCase):
52
+ def test_safe_extract_blocks_zip_slip(self):
53
+ with tempfile.TemporaryDirectory() as temp_dir_name:
54
+ temp_dir = Path(temp_dir_name)
55
+ zip_path = temp_dir / "bad.zip"
56
+ extract_dir = temp_dir / "extract"
57
+
58
+ with zipfile.ZipFile(zip_path, "w") as archive:
59
+ archive.writestr("../escape.txt", "nope")
60
+
61
+ with self.assertRaises(ZipSlipError):
62
+ safe_extract_zip(zip_path, extract_dir)
63
+
64
+ self.assertFalse((temp_dir / "escape.txt").exists())
65
+
66
+
67
+ @unittest.skipIf(Image is None, "Pillow is not installed")
68
+ class ProcessZipTests(unittest.TestCase):
69
+ def test_process_zip_preserves_filename_dimensions_and_reports_failures(self):
70
+ with tempfile.TemporaryDirectory() as temp_dir_name:
71
+ temp_dir = Path(temp_dir_name)
72
+ zip_path = temp_dir / "input.zip"
73
+ output_zip = temp_dir / "result.zip"
74
+ image_path = temp_dir / "SKU-100.jpg"
75
+
76
+ Image.new("RGB", (12, 8), (255, 255, 255)).save(image_path, "JPEG")
77
+
78
+ with zipfile.ZipFile(zip_path, "w") as archive:
79
+ archive.write(image_path, "SKU-100.jpg")
80
+ archive.writestr("broken.png", b"not an image")
81
+ archive.writestr("notes.txt", "ignore me")
82
+
83
+ progress_events = []
84
+
85
+ def fake_remove(image):
86
+ return image.convert("RGBA")
87
+
88
+ result = process_zip(
89
+ zip_path,
90
+ output_zip,
91
+ "Grey",
92
+ (241, 242, 242),
93
+ remover=fake_remove,
94
+ progress_callback=lambda total, completed, failed: progress_events.append(
95
+ (total, completed, failed)
96
+ ),
97
+ )
98
+
99
+ self.assertEqual(result.total, 2)
100
+ self.assertEqual(result.completed, 2)
101
+ self.assertEqual(result.failed_files, ["broken.png"])
102
+ self.assertTrue(output_zip.exists())
103
+ self.assertEqual(progress_events[0], (2, 0, []))
104
+ self.assertEqual(progress_events[-1], (2, 2, ["broken.png"]))
105
+
106
+ with zipfile.ZipFile(output_zip) as archive:
107
+ names = set(archive.namelist())
108
+ self.assertIn("Grey/SKU-100.jpg", names)
109
+ self.assertNotIn("Grey/notes.txt", names)
110
+
111
+ extracted = temp_dir / "out"
112
+ archive.extract("Grey/SKU-100.jpg", extracted)
113
+ with Image.open(extracted / "Grey" / "SKU-100.jpg") as output_image:
114
+ self.assertEqual(output_image.size, (12, 8))
115
+
116
+ def test_lossless_png_output_has_exact_background_pixel_and_png_name(self):
117
+ with tempfile.TemporaryDirectory() as temp_dir_name:
118
+ temp_dir = Path(temp_dir_name)
119
+ zip_path = temp_dir / "input.zip"
120
+ output_zip = temp_dir / "result.zip"
121
+ image_path = temp_dir / "SKU-200.jpg"
122
+
123
+ Image.new("RGB", (4, 4), (255, 255, 255)).save(image_path, "JPEG")
124
+ with zipfile.ZipFile(zip_path, "w") as archive:
125
+ archive.write(image_path, "nested/SKU-200.jpg")
126
+
127
+ def fake_remove(_image):
128
+ cutout = Image.new("RGBA", (4, 4), (0, 0, 0, 0))
129
+ cutout.putpixel((1, 1), (20, 40, 60, 255))
130
+ cutout.putpixel((2, 1), (20, 40, 60, 255))
131
+ return cutout
132
+
133
+ result = process_zip(
134
+ zip_path,
135
+ output_zip,
136
+ "Grey",
137
+ (241, 242, 242),
138
+ quality_profile="pro",
139
+ output_mode="lossless_png",
140
+ remover=fake_remove,
141
+ )
142
+
143
+ self.assertEqual(result.failed_files, [])
144
+ with zipfile.ZipFile(output_zip) as archive:
145
+ names = set(archive.namelist())
146
+ self.assertIn("Grey/SKU-200.png", names)
147
+ extracted = temp_dir / "png-out"
148
+ archive.extract("Grey/SKU-200.png", extracted)
149
+ with Image.open(extracted / "Grey" / "SKU-200.png") as output_image:
150
+ self.assertEqual(output_image.size, (4, 4))
151
+ self.assertEqual(output_image.getpixel((0, 0)), (241, 242, 242))
152
+
153
+ def test_all_failed_images_raise_clear_error(self):
154
+ with tempfile.TemporaryDirectory() as temp_dir_name:
155
+ temp_dir = Path(temp_dir_name)
156
+ zip_path = temp_dir / "input.zip"
157
+ output_zip = temp_dir / "result.zip"
158
+
159
+ with zipfile.ZipFile(zip_path, "w") as archive:
160
+ archive.writestr("broken.png", b"not an image")
161
+
162
+ with self.assertRaisesRegex(RuntimeError, "All 1 image files failed"):
163
+ process_zip(
164
+ zip_path,
165
+ output_zip,
166
+ "Grey",
167
+ (241, 242, 242),
168
+ remover=lambda image: image.convert("RGBA"),
169
+ )
170
+
171
+ def test_jpeg_save_kwargs_use_maximum_practical_quality(self):
172
+ kwargs = _save_kwargs_for(Path("SKU-100.jpg"), {"icc_profile": b"icc", "exif": b"exif"})
173
+
174
+ self.assertEqual(kwargs["quality"], 100)
175
+ self.assertEqual(kwargs["subsampling"], 0)
176
+ self.assertTrue(kwargs["optimize"])
177
+ self.assertEqual(kwargs["icc_profile"], b"icc")
178
+ self.assertEqual(kwargs["exif"], b"exif")
179
+
180
+
181
+ if __name__ == "__main__":
182
+ unittest.main()