File size: 3,206 Bytes
7ca0188 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 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 | """Transient validation and RGB loading for NovaGuide image inputs."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from PIL import Image, UnidentifiedImageError
from src.config import Settings, get_settings
class ImageProcessor:
"""Validate and load images without copying, resizing, or retaining them."""
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
def __init__(self, settings: Settings | None = None) -> None:
self.settings = settings or get_settings()
def validate_image_file(self, file_path: str | None) -> dict[str, Any]:
"""Validate image path, extension, and configured file-size limit."""
result = {
"valid": False, "file_path": file_path or "", "extension": "",
"file_size_mb": 0.0, "error": None,
}
if file_path is None or not str(file_path).strip():
result["error"] = "No image file was provided."
return result
path = Path(str(file_path).strip())
result["file_path"] = str(path)
result["extension"] = path.suffix.lower()
if not path.is_file():
result["error"] = f"Image file not found: {path}"
return result
if path.suffix.lower() not in self.SUPPORTED_EXTENSIONS:
result["error"] = (
f"Unsupported image extension '{path.suffix.lower()}'. Supported: "
f"{', '.join(sorted(self.SUPPORTED_EXTENSIONS))}."
)
return result
size_mb = path.stat().st_size / (1024 * 1024)
result["file_size_mb"] = float(size_mb)
if size_mb > self.settings.max_image_size_mb:
result["error"] = (
f"Image size {size_mb:.2f} MB exceeds the "
f"{self.settings.max_image_size_mb:g} MB limit."
)
return result
result["valid"] = True
return result
def load_image(self, file_path: str) -> Image.Image:
"""Open an image with Pillow, fully load it, and return an RGB copy."""
try:
with Image.open(file_path) as image:
return image.convert("RGB").copy()
except (OSError, UnidentifiedImageError) as exc:
raise ValueError(f"Image could not be opened: {exc}") from exc
def prepare_image(self, file_path: str | None) -> dict[str, Any]:
"""Validate and load one image, preserving the caller's original file."""
validation = self.validate_image_file(file_path)
result = {
"valid": validation["valid"], "file_path": validation["file_path"],
"image": None, "width": None, "height": None, "mode": None,
"file_size_mb": validation["file_size_mb"], "error": validation["error"],
}
if not validation["valid"]:
return result
try:
image = self.load_image(validation["file_path"])
except ValueError as exc:
result["valid"] = False
result["error"] = str(exc)
return result
result.update({"image": image, "width": image.width, "height": image.height, "mode": image.mode})
return result
|