NovaGuide / src /preprocessing /image_processor.py
DKLPDV15\eB
Deploy NovaGuide with versioned runtime configuration
7ca0188
Raw History Blame Contribute Delete
3.21 kB
"""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