from __future__ import annotations import shutil import tempfile import zipfile from dataclasses import dataclass from pathlib import Path import cv2 import numpy as np SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"} @dataclass(frozen=True) class BorderCleanupResult: processed: int skipped: int copied: int output: Path def _estimate_background(image: np.ndarray, sample_size: int = 20) -> np.ndarray: h, w = image.shape[:2] s = min(sample_size, max(1, h // 4), max(1, w // 4)) patches = [image[:s, :s], image[:s, w-s:], image[h-s:, :s], image[h-s:, w-s:]] pixels = np.concatenate([p.reshape(-1, image.shape[2]) for p in patches], axis=0) return np.median(pixels, axis=0).astype(np.uint8) def _background_distance(image: np.ndarray, background: np.ndarray) -> np.ndarray: img = image.astype(np.int16) bg = background.astype(np.int16) img_f = img.astype(np.float32, copy=False) bg_f = np.asarray(bg, dtype=np.float32) delta = img_f - bg_f return np.sqrt(np.sum(delta * delta, axis=2)) def _detect_full_edge_lines(image: np.ndarray, background: np.ndarray, *, max_edge_px: int, difference_threshold: float, line_coverage: float) -> np.ndarray: h, w = image.shape[:2] non_background = _background_distance(image, background) > difference_threshold mask = np.zeros((h, w), dtype=np.uint8) edge_x = min(max_edge_px, max(1, w // 10)) edge_y = min(max_edge_px, max(1, h // 10)) for x in range(edge_x): if float(np.mean(non_background[:, x])) >= line_coverage: mask[:, x] = 255 for x in range(w-edge_x, w): if float(np.mean(non_background[:, x])) >= line_coverage: mask[:, x] = 255 for y in range(edge_y): if float(np.mean(non_background[y, :])) >= line_coverage: mask[y, :] = 255 for y in range(h-edge_y, h): if float(np.mean(non_background[y, :])) >= line_coverage: mask[y, :] = 255 return mask def _detect_edge_connected_artifacts(image: np.ndarray, background: np.ndarray, *, border_fraction: float, difference_threshold: float, max_component_depth_fraction: float) -> np.ndarray: h, w = image.shape[:2] candidate = (_background_distance(image, background) > difference_threshold).astype(np.uint8) bx, by = max(2, int(w * border_fraction)), max(2, int(h * border_fraction)) border_region = np.zeros((h, w), dtype=np.uint8) border_region[:, :bx] = 1; border_region[:, w-bx:] = 1 border_region[:by, :] = 1; border_region[h-by:, :] = 1 candidate *= border_region count, labels, stats, _ = cv2.connectedComponentsWithStats(candidate, connectivity=8) output = np.zeros((h, w), dtype=np.uint8) max_dx, max_dy = max(3, int(w * max_component_depth_fraction)), max(3, int(h * max_component_depth_fraction)) for component_id in range(1, count): x, y, cw, ch, _ = stats[component_id] x2, y2 = x + cw, y + ch shallow = ((x == 0 and x2 <= max_dx) or (x2 >= w and x >= w-max_dx) or (y == 0 and y2 <= max_dy) or (y2 >= h and y >= h-max_dy)) if shallow: output[labels == component_id] = 255 return output def _write_image(path: Path, image: np.ndarray) -> None: path.parent.mkdir(parents=True, exist_ok=True) ext = path.suffix.lower() if ext in {".jpg", ".jpeg"}: ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_JPEG_QUALITY, 98]) elif ext == ".png": ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_PNG_COMPRESSION, 3]) elif ext == ".webp": ok = cv2.imwrite(str(path), image, [cv2.IMWRITE_WEBP_QUALITY, 98]) else: ok = cv2.imwrite(str(path), image) if not ok: raise RuntimeError(f"Unable to write image: {path}") def clean_image(input_path: Path, output_path: Path, *, border_fraction: float = 0.035, difference_threshold: float = 18.0, max_component_depth_fraction: float = 0.025, max_edge_px: int = 12, line_coverage: float = 0.35) -> bool: input_path, output_path = Path(input_path), Path(output_path) image = cv2.imread(str(input_path), cv2.IMREAD_COLOR) if image is None: return False original_shape = image.shape background = _estimate_background(image) mask = cv2.bitwise_or( _detect_edge_connected_artifacts(image, background, border_fraction=border_fraction, difference_threshold=difference_threshold, max_component_depth_fraction=max_component_depth_fraction), _detect_full_edge_lines(image, background, max_edge_px=max_edge_px, difference_threshold=difference_threshold, line_coverage=line_coverage), ) cleaned = image.copy() cleaned[mask > 0] = background if cleaned.shape != original_shape: raise RuntimeError(f"Image dimensions changed unexpectedly: {input_path}") _write_image(output_path, cleaned) return True def _process_directory(input_dir: Path, output_dir: Path, **options: object) -> BorderCleanupResult: processed = skipped = copied = 0 for source in sorted(input_dir.rglob("*")): if not source.is_file(): continue target = output_dir / source.relative_to(input_dir) if source.suffix.lower() not in SUPPORTED_EXTENSIONS: target.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(source, target); copied += 1; continue if clean_image(source, target, **options): processed += 1 else: skipped += 1 return BorderCleanupResult(processed, skipped, copied, output_dir) def _extract_zip(zip_path: Path, destination: Path) -> None: with zipfile.ZipFile(zip_path, "r") as archive: root = destination.resolve() for member in archive.infolist(): resolved = (destination / member.filename).resolve() if resolved != root and root not in resolved.parents: raise ValueError(f"Unsafe ZIP entry rejected: {member.filename}") archive.extractall(destination) def _create_zip(source_dir: Path, output_zip: Path) -> None: output_zip.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(output_zip, "w", zipfile.ZIP_DEFLATED) as archive: for path in sorted(source_dir.rglob("*")): if path.is_file(): archive.write(path, path.relative_to(source_dir)) def process_path(input_path: Path, output_path: Path, *, border_fraction: float = 0.035, difference_threshold: float = 18.0, max_component_depth_fraction: float = 0.025, max_edge_px: int = 12, line_coverage: float = 0.35) -> BorderCleanupResult: input_path, output_path = Path(input_path).resolve(), Path(output_path).resolve() options = dict(border_fraction=border_fraction, difference_threshold=difference_threshold, max_component_depth_fraction=max_component_depth_fraction, max_edge_px=max_edge_px, line_coverage=line_coverage) if input_path.is_dir(): return _process_directory(input_path, output_path, **options) if not input_path.is_file(): raise FileNotFoundError(f"Input not found: {input_path}") if input_path.suffix.lower() in SUPPORTED_EXTENSIONS: ok = clean_image(input_path, output_path, **options) return BorderCleanupResult(1 if ok else 0, 0 if ok else 1, 0, output_path) if input_path.suffix.lower() == ".zip": if output_path.suffix.lower() != ".zip": raise ValueError("ZIP input requires a .zip output path") with tempfile.TemporaryDirectory(prefix="acupedia-ops-image-clean-") as temp: temp_root = Path(temp); extracted = temp_root / "input"; cleaned = temp_root / "output" extracted.mkdir(); cleaned.mkdir(); _extract_zip(input_path, extracted) result = _process_directory(extracted, cleaned, **options); _create_zip(cleaned, output_path) return BorderCleanupResult(result.processed, result.skipped, result.copied, output_path) raise ValueError("Input must be a supported image, directory, or ZIP archive")