Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(parse): limit the formats and sizes ImageParser decodes (#2079)
Sameer Kadam0a2731c82234
diff --git a/semantica/parse/image_parser.py b/semantica/parse/image_parser.pyindex 57329a10..c17a7f3b 100644--- a/semantica/parse/image_parser.py+++ b/semantica/parse/image_parser.py@@ -7,7 +7,9 @@ and image analysis, including metadata extraction and OCR processing.Key Features:- Image metadata extraction (EXIF, format, size)- OCR text extraction using Tesseract- - Image format support (JPEG, PNG, GIF, BMP, TIFF)+ - Image format support (PNG, JPEG, WebP, BMP by default; TIFF and GIF+ opt-in via the allowed_formats config)+ - File size and pixel count limits on untrusted input- Image analysis and properties- Optional Tesseract OCR integration- PIL/Pillow integration@@ -28,11 +30,14 @@ Author: Semantica ContributorsLicense: MIT"""+import io+import os+import statfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Union-from PIL import ExifTags, Image+from PIL import ExifTags, Image, UnidentifiedImageErrorfrom PIL.Image import Image as PILImagefrom ..utils.exceptions import ProcessingError, ValidationError@@ -43,6 +48,95 @@ from ..utils.helpers import safe_importpytesseract, TESSERACT_AVAILABLE = safe_import("pytesseract")+# Pillow formats opened by default. The TIFF and GIF decoders carry open+# pillow 12.3.0 advisories that can't be fixed until docling allows pillow 13+# (#2067), so callers that need them opt in through `allowed_formats`.+DEFAULT_ALLOWED_FORMATS = ("PNG", "JPEG", "WEBP", "BMP")++# Never opened, even when requested: Pillow renders EPS by running+# Ghostscript on the file.+BLOCKED_FORMATS = frozenset({"EPS"})++# Common names that aren't Pillow open-plugin names. Multi-picture JPEGs (MPO)+# are opened by the JPEG plugin.+FORMAT_ALIASES = {"JPG": "JPEG", "TIF": "TIFF", "MPO": "JPEG"}++DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024 # bytes++# Image modes Pillow's PNG encoder can write.+PNG_MODES = frozenset({"1", "L", "LA", "I", "I;16", "I;16B", "P", "RGB", "RGBA"})++# Pillow's own default for Image.MAX_IMAGE_PIXELS, used when an application+# has set that to None to disable Pillow's check.+DEFAULT_MAX_PIXELS = 89_478_485+++def _webp_canvas_size(data: bytes) -> Optional[tuple]:+ """+ Read the canvas size from a WebP header without decoding.++ Pillow builds the libwebp decoder, which allocates the full canvas,+ before it checks the image size, so a tiny WebP can claim a huge canvas.++ Args:+ data: File contents++ Returns:+ tuple: (width, height), or None if the header can't be read+ """+ if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":+ return None+ chunk = data[12:16]+ if chunk == b"VP8X":+ # Extended format: 24-bit canvas width - 1 and height - 1.+ return (+ 1 + int.from_bytes(data[24:27], "little"),+ 1 + int.from_bytes(data[27:30], "little"),+ )+ if chunk == b"VP8 ":+ # Lossy: frame tag, start code, then 14-bit width and height.+ if data[23:26] != b"\x9d\x01\x2a":+ return None+ return (+ int.from_bytes(data[26:28], "little") & 0x3FFF,+ int.from_bytes(data[28:30], "little") & 0x3FFF,+ )+ if chunk == b"VP8L":+ # Lossless: signature byte, then 14-bit width - 1 and height - 1.+ if data[20] != 0x2F:+ return None+ bits = int.from_bytes(data[21:25], "little")+ return ((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)+ return None+++def _ocr_copy(img: PILImage) -> PILImage:+ """+ Make the RGB copy that is handed to tesseract.++ A plain convert("RGB") loses text in two common cases: it clips 16- and+ 32-bit grayscale to white instead of scaling it, and it drops alpha, so+ dark text on a transparent dark background turns solid black.++ Args:+ img: Opened image++ Returns:+ PILImage: An RGB copy with no format set+ """+ if img.mode == "I" or img.mode.startswith("I;16"):+ img = img.point(lambda value: value / 256).convert("L")++ has_alpha = "A" in img.getbands()+ if has_alpha or (img.mode == "P" and "transparency" in img.info):+ # Flatten onto white, as pytesseract does for images with alpha.+ rgba = img.convert("RGBA")+ background = Image.new("RGB", rgba.size, (255, 255, 255))+ background.paste(rgba, (0, 0), rgba.getchannel("A"))+ return background++ return img.convert("RGB")+@dataclassclass ImageMetadata:@@ -75,7 +169,23 @@ class ImageParser:Initialize image parser.Args:- **config: Parser configuration+ **config: Parser configuration:+ - tesseract_path: Path to the tesseract binary+ - allowed_formats: Pillow format names to accept. Replaces+ the default list (PNG, JPEG, WEBP, BMP), so include every+ format you need. Adding "TIFF" or "GIF" re-exposes their+ open advisories (#2067); "EPS" is always refused. "JPEG"+ also accepts multi-picture JPEGs (MPO).+ - max_file_size: Largest file accepted, in bytes+ (default: 50 MB; None for no limit)+ - max_pixels: Largest width * height accepted+ (default: PIL.Image.MAX_IMAGE_PIXELS, or 89,478,485 if+ that is None). Pillow refuses anything over twice+ MAX_IMAGE_PIXELS on its own, so it can't be raised past+ that cap, and between 1x and 2x Pillow still emits its+ DecompressionBombWarning. Lower it on memory-constrained+ hosts: OCR and preprocessing decode the full image, and a+ WebP at the default limit can take about 2 GB."""self.logger = get_logger("image_parser")self.config = config@@ -84,6 +194,214 @@ class ImageParser:if self.tesseract_path:pytesseract.pytesseract.tesseract_cmd = self.tesseract_path+ self.allowed_formats = self._validate_formats(+ config.get("allowed_formats", DEFAULT_ALLOWED_FORMATS)+ )+ self.max_file_size = config.get("max_file_size", DEFAULT_MAX_FILE_SIZE)+ if self.max_file_size is not None and (+ not isinstance(self.max_file_size, int)+ or isinstance(self.max_file_size, bool)+ or self.max_file_size < 1+ ):+ raise ValidationError("max_file_size must be a positive int or None")+ self.max_pixels = self._validate_max_pixels(+ config.get("max_pixels", Image.MAX_IMAGE_PIXELS or DEFAULT_MAX_PIXELS)+ )++ @staticmethod+ def _validate_formats(formats: Any) -> tuple:+ """+ Normalise allowed_formats and check every name is a Pillow format.++ Pillow only looks a format name up when a file reaches it, and then+ raises a bare KeyError, so bad names are rejected here instead.++ Args:+ formats: The allowed_formats config value++ Returns:+ tuple: Upper-case Pillow format names+ """+ if isinstance(formats, str) or not isinstance(formats, (list, tuple, set)):+ raise ValidationError(+ "allowed_formats must be a list of format names, "+ f'such as ["PNG", "JPEG"], not {formats!r}'+ )+ if isinstance(formats, set):+ # A set has no order; sort so Pillow tries formats predictably.+ formats = sorted(formats, key=str)+ names = tuple(+ FORMAT_ALIASES.get(str(fmt).upper(), str(fmt).upper()) for fmt in formats+ )+ if not names:+ raise ValidationError("allowed_formats must name at least one format")++ blocked = BLOCKED_FORMATS.intersection(names)+ if blocked:+ raise ValidationError(+ f"Image formats {sorted(blocked)} cannot be enabled: Pillow "+ "decodes them by running external tools on the file."+ )++ # Registers every plugin Pillow has, so Image.OPEN is complete. A+ # format can be registered but still unusable (WEBP without+ # libwebp); such files are then refused as unidentified at open.+ Image.init()+ unknown = [name for name in names if name not in Image.OPEN]+ if unknown:+ raise ValidationError(+ f"Unknown or unavailable image formats {unknown}. "+ f"Available: {', '.join(sorted(Image.OPEN))}"+ )+ return names++ @staticmethod+ def _validate_max_pixels(max_pixels: Any) -> int:+ """+ Check max_pixels against Pillow's own hard limit.++ Args:+ max_pixels: The max_pixels config value++ Returns:+ int: The validated limit+ """+ if (+ not isinstance(max_pixels, int)+ or isinstance(max_pixels, bool)+ or max_pixels < 1+ ):+ raise ValidationError("max_pixels must be a positive int")+ if (+ Image.MAX_IMAGE_PIXELS is not None+ and max_pixels > 2 * Image.MAX_IMAGE_PIXELS+ ):+ raise ValidationError(+ f"max_pixels can't exceed {2 * Image.MAX_IMAGE_PIXELS}: Pillow "+ "refuses larger images itself (2 * PIL.Image.MAX_IMAGE_PIXELS)."+ )+ return max_pixels++ def _open_image(self, file_path: Path) -> PILImage:+ """+ Open an image with the format, file size and pixel limits applied.++ Every Pillow decode in this class goes through here, so untrusted+ files only ever reach the decoders for allowed formats.++ Args:+ file_path: Path to image file++ Returns:+ PILImage: The opened image. Pixel data isn't decoded yet, though+ some later reads load it (PNG EXIF, convert, verify).++ Raises:+ ValidationError: If the file is missing, not a regular file, too+ large, in a format that is not allowed, or has too many pixels+ """+ data = self._read_file(file_path)++ # Pillow's WebP plugin allocates the whole canvas before any size+ # check, so check the header first.+ is_webp = data[:4] == b"RIFF" and data[8:12] == b"WEBP"+ if is_webp and "WEBP" in self.allowed_formats:+ size = _webp_canvas_size(data)+ if size is None:+ raise ValidationError(f"Unreadable WebP header: {file_path}")+ self._check_pixels(size, file_path)++ try:+ img = Image.open(io.BytesIO(data), formats=self.allowed_formats)+ except UnidentifiedImageError:+ raise ValidationError(+ f"Not a supported image, or a damaged one: {file_path}. "+ f"Allowed formats: {', '.join(self.allowed_formats)}. To accept "+ "TIFF or GIF, add them to allowed_formats, e.g. ImageParser("+ 'allowed_formats=["PNG", "JPEG", "WEBP", "BMP", "TIFF"]).'+ )+ except (Image.DecompressionBombError, Image.DecompressionBombWarning) as e:+ # The warning only arrives as an exception when warnings are+ # errors (-W error). It isn't suppressed with catch_warnings(),+ # which changes process-wide state and isn't thread-safe.+ raise ValidationError(f"Image exceeds the pixel limit: {e}")++ try:+ self._check_pixels(img.size, file_path)+ except ValidationError:+ img.close()+ raise+ return img++ def _read_file(self, file_path: Path) -> bytes:+ """+ Read a file once, bounded by max_file_size.++ Decoding this snapshot instead of reopening the path means a file+ that changes after the checks can't get past them.++ Args:+ file_path: Path to image file++ Returns:+ bytes: File contents++ Raises:+ ValidationError: If the file is missing, not a regular file or+ over max_file_size+ """+ # O_NONBLOCK so opening a FIFO returns at once instead of waiting for+ # a writer; it has no effect on regular files.+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)+ try:+ fd = os.open(file_path, flags)+ except FileNotFoundError:+ raise ValidationError(f"Image file not found: {file_path}")+ except IsADirectoryError:+ raise ValidationError(f"Not a regular file: {file_path}")+ except PermissionError:+ # Windows reports a directory as EACCES rather than EISDIR.+ if os.path.isdir(file_path):+ raise ValidationError(f"Not a regular file: {file_path}")+ raise++ # Checked on the open descriptor, so the path can't be swapped for a+ # FIFO, device or directory after the check.+ try:+ if not stat.S_ISREG(os.fstat(fd).st_mode):+ raise ValidationError(f"Not a regular file: {file_path}")+ f = os.fdopen(fd, "rb")+ except BaseException:+ os.close(fd)+ raise++ with f:+ if self.max_file_size is None:+ data = f.read()+ else:+ data = f.read(self.max_file_size + 1)++ if self.max_file_size is not None and len(data) > self.max_file_size:+ raise ValidationError(+ f"Image file is over the {self.max_file_size} byte limit: {file_path}"+ )+ return data++ def _check_pixels(self, size: tuple, file_path: Path) -> None:+ """+ Reject an image whose width * height is over max_pixels.++ Args:+ size: (width, height)+ file_path: Path to image file, for the error message+ """+ pixels = size[0] * size[1]+ if pixels > self.max_pixels:+ raise ValidationError(+ f"Image has {pixels} pixels, over the {self.max_pixels} pixel "+ f"limit: {file_path}"+ )+def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:"""Parse image file.@@ -114,20 +432,22 @@ class ImageParser:# Validate image filetry:- with Image.open(file_path) as img:+ with self._open_image(file_path) as img:img.verify()+ except ValidationError:+ raiseexcept Exception as e:raise ValidationError(f"Invalid image file: {e}")try:- with Image.open(file_path) as img:+ with self._open_image(file_path) as img:# Extract metadatametadata = Noneif options.get("extract_metadata", True):self.progress_tracker.update_tracking(tracking_id, message="Extracting metadata...")- metadata = self._extract_metadata(img, file_path)+ metadata = self._extract_metadata(img)# Extract text using OCRocr_result = None@@ -150,6 +470,10 @@ class ImageParser:"text": ocr_result.text if ocr_result else None,}+ # A rejected file stays a ValidationError, and extract_text's+ # ProcessingError isn't wrapped a second time.+ except (ValidationError, ProcessingError):+ raiseexcept Exception as e:self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e)@@ -184,17 +508,20 @@ class ImageParser:file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Image file not found: {file_path}")-try:- # Extract text- text = pytesseract.image_to_string(str(file_path), lang=language)-- # Get detailed data with boxes- data = pytesseract.image_to_data(- str(file_path), lang=language, output_type=pytesseract.Output.DICT- )+ # Given a path, tesseract decodes the raw file with its own image+ # libraries, outside the format allowlist. Hand it a converted+ # copy instead: with no format set, pytesseract writes it out as+ # PNG, which also covers MPO JPEGs (pytesseract rejects that+ # format) and keeps the TIFF and GIF encoders off the OCR path.+ with self._open_image(file_path) as img, _ocr_copy(img) as ocr_img:+ # Extract text+ text = pytesseract.image_to_string(ocr_img, lang=language)++ # Get detailed data with boxes+ data = pytesseract.image_to_data(+ ocr_img, lang=language, output_type=pytesseract.Output.DICT+ )# Calculate average confidenceconfidences = [conf for conf in data["conf"] if conf != -1]@@ -223,6 +550,8 @@ class ImageParser:boxes=boxes,)+ except ValidationError:+ raiseexcept Exception as e:self.logger.error(f"Failed to extract text from image {file_path}: {e}")raise ProcessingError(f"Failed to extract text from image: {e}")@@ -239,33 +568,44 @@ class ImageParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Image file not found: {file_path}")-try:- with Image.open(file_path) as img:- # Extract EXIF data- exif_data = {}- if hasattr(img, "_getexif") and img._getexif():- exif_dict = img._getexif()- for tag_id, value in exif_dict.items():- tag = ExifTags.TAGS.get(tag_id, tag_id)- exif_data[str(tag)] = str(value)-- return ImageMetadata(- format=img.format,- mode=img.mode,- size=img.size,- width=img.width,- height=img.height,- exif=exif_data,- info=img.info or {},- )+ with self._open_image(file_path) as img:+ return self._extract_metadata(img)+ except ValidationError:+ raiseexcept Exception as e:self.logger.error(f"Failed to extract metadata from image {file_path}: {e}")raise ProcessingError(f"Failed to extract metadata from image: {e}")+ def _extract_metadata(self, img: PILImage) -> ImageMetadata:+ """+ Extract metadata from an already opened image.++ Args:+ img: Opened image++ Returns:+ ImageMetadata: Image metadata+ """+ # Extract EXIF data. For PNG, _getexif() loads the pixel data.+ exif_data = {}+ exif_dict = img._getexif() if hasattr(img, "_getexif") else None+ if exif_dict:+ for tag_id, value in exif_dict.items():+ tag = ExifTags.TAGS.get(tag_id, tag_id)+ exif_data[str(tag)] = str(value)++ return ImageMetadata(+ format=img.format,+ mode=img.mode,+ size=img.size,+ width=img.width,+ height=img.height,+ exif=exif_data,+ info=img.info or {},+ )+def preprocess_image(self, file_path: Union[str, Path], **options) -> Path:"""Preprocess image for better OCR results.@@ -278,35 +618,49 @@ class ImageParser:- enhance_contrast: Enhance contrastReturns:- Path: Path to preprocessed image+ Path: Path to the preprocessed image, always written as PNG+ (<stem>_preprocessed.png next to the input). Inputs that+ differ only by extension, such as a.png and a.jpg, share an+ output path, so the later call overwrites the earlier one."""file_path = Path(file_path)- with Image.open(file_path) as img:- # Convert to grayscale if requested- if options.get("grayscale", True):- img = img.convert("L")-- # Resize if requested- if options.get("resize"):- resize_factor = options["resize"]- new_size = (- int(img.width * resize_factor),- int(img.height * resize_factor),- )- img = img.resize(new_size, Image.Resampling.LANCZOS)+ try:+ with self._open_image(file_path) as img:+ # Convert to grayscale if requested+ if options.get("grayscale", True):+ img = img.convert("L")++ # Resize if requested, within the same pixel limit as input+ if options.get("resize"):+ resize_factor = options["resize"]+ new_size = (+ int(img.width * resize_factor),+ int(img.height * resize_factor),+ )+ self._check_pixels(new_size, file_path)+ img = img.resize(new_size, Image.Resampling.LANCZOS)- # Enhance contrast if requested- if options.get("enhance_contrast", True):- from PIL import ImageEnhance+ # Enhance contrast if requested+ if options.get("enhance_contrast", True):+ from PIL import ImageEnhance- enhancer = ImageEnhance.Contrast(img)- img = enhancer.enhance(1.5)+ enhancer = ImageEnhance.Contrast(img)+ img = enhancer.enhance(1.5)- # Save preprocessed image- output_path = (- file_path.parent / f"{file_path.stem}_preprocessed{file_path.suffix}"- )- img.save(output_path)+ # Save as PNG whatever the input's extension: choosing the+ # encoder from the extension would let a file named .tiff or+ # .gif reach the TIFF or GIF encoder.+ output_path = file_path.parent / f"{file_path.stem}_preprocessed.png"+ # PNG can't store modes such as CMYK (JPEG) or YCbCr.+ if img.mode not in PNG_MODES:+ img = img.convert("RGB")+ img.save(output_path, format="PNG")- return output_path+ return output_path++ except ValidationError:+ raise+ except Exception as e:+ self.logger.error(f"Failed to preprocess image {file_path}: {e}")+ raise ProcessingError(f"Failed to preprocess image: {e}")diff --git a/semantica/parse/parse_usage.md b/semantica/parse/parse_usage.mdindex a8fb8fc9..9972060f 100644--- a/semantica/parse/parse_usage.md+++ b/semantica/parse/parse_usage.md@@ -477,6 +477,34 @@ print(f"Text: {ocr_result.text}")print(f"Confidence: {ocr_result.confidence}")```+`ImageParser` only opens PNG, JPEG (including multi-picture JPEGs), WebP and+BMP by default, and rejects files over 50 MB or `PIL.Image.MAX_IMAGE_PIXELS`+pixels. The format is detected from the file contents, not the extension.++- TIFF and GIF must be enabled explicitly. Their Pillow decoders have open+ advisories (#2067), and enabling TIFF re-exposes all four TIFF ones.+- `allowed_formats` replaces the default list, so include every format you+ need. `"JPG"` and `"TIF"` are accepted as aliases. EPS can't be enabled.+- `max_pixels` can't exceed `2 * PIL.Image.MAX_IMAGE_PIXELS`, because Pillow+ refuses larger images itself. If your application sets+ `PIL.Image.MAX_IMAGE_PIXELS = None`, the default is 89,478,485 pixels.+- On memory-constrained hosts, lower `max_pixels`: `extract_text()` and+ `preprocess_image()` decode the whole image, and a WebP at the default+ limit can take about 2 GB.+- Rejected files raise `ValidationError`, not `ProcessingError`; both derive+ from `SemanticaError`.+- `preprocess_image()` always writes PNG, as `<stem>_preprocessed.png` next+ to the input. Inputs that differ only by extension (`a.png`, `a.jpg`)+ share that output path.++```python+image_parser = ImageParser(+ allowed_formats=["PNG", "JPEG", "WEBP", "BMP", "TIFF"], # defaults + TIFF+ max_file_size=20 * 1024 * 1024, # bytes+ max_pixels=50_000_000,+)+```+### Media File Parsing```pythondiff --git a/tests/parse/test_image_parser.py b/tests/parse/test_image_parser.pynew file mode 100644index 00000000..554817df--- /dev/null+++ b/tests/parse/test_image_parser.py@@ -0,0 +1,481 @@+"""+Tests for the untrusted-input limits in ImageParser (#2067).++Covers:+ - Default formats (PNG, JPEG, WEBP, BMP) open; TIFF and GIF are refused+ unless enabled through allowed_formats+ - EPS can never be enabled+ - File size and pixel count limits+ - Every entry point (parse, extract_metadata, preprocess_image,+ extract_text) applies the limits+ - The size limit applies to the bytes read; FIFOs and directories are+ refused without blocking+ - Unexpected open failures are logged and wrapped as ProcessingError+ - The OCR input keeps text in 16-bit and transparent images+ - Config validation, pixel limits (including WebP headers and Pillow's+ own bomb check) and error mapping+"""++import os+import struct+import tempfile+import threading+import unittest+import warnings+import zlib+from pathlib import Path+from unittest.mock import MagicMock, patch++from PIL import Image++from semantica.parse.image_parser import ImageParser, _webp_canvas_size+from semantica.utils.exceptions import ProcessingError, ValidationError+++class TestImageParserLimits(unittest.TestCase):+ def setUp(self):+ logger_patcher = patch("semantica.parse.image_parser.get_logger")+ tracker_patcher = patch("semantica.parse.image_parser.get_progress_tracker")+ logger_patcher.start()+ tracker_patcher.start()+ self.addCleanup(logger_patcher.stop)+ self.addCleanup(tracker_patcher.stop)++ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.dir = Path(tmp.name)++ def _image(self, name, fmt, size=(8, 8)):+ path = self.dir / name+ Image.new("RGB", size, "white").save(path, format=fmt)+ return path++ def test_default_formats_parse(self):+ parser = ImageParser()+ for name, fmt in [+ ("a.png", "PNG"),+ ("a.jpg", "JPEG"),+ ("a.webp", "WEBP"),+ ("a.bmp", "BMP"),+ ]:+ with self.subTest(fmt=fmt):+ result = parser.parse(self._image(name, fmt))+ self.assertEqual(result["metadata"]["format"], fmt)++ def test_tiff_and_gif_refused_by_default(self):+ parser = ImageParser()+ for name, fmt in [("a.tiff", "TIFF"), ("a.gif", "GIF")]:+ with self.subTest(fmt=fmt):+ with self.assertRaises(ValidationError):+ parser.parse(self._image(name, fmt))++ def test_tiff_and_gif_open_when_allowed(self):+ parser = ImageParser(allowed_formats=["png", "tiff", "gif"])+ for name, fmt in [("a.tiff", "TIFF"), ("a.gif", "GIF")]:+ with self.subTest(fmt=fmt):+ metadata = parser.extract_metadata(self._image(name, fmt))+ self.assertEqual(metadata.format, fmt)++ def test_extension_does_not_bypass_format_check(self):+ # A TIFF renamed to .png is still decoded as TIFF, so it's refused.+ path = self.dir / "disguised.png"+ Image.new("RGB", (8, 8)).save(path, format="TIFF")+ with self.assertRaises(ValidationError):+ ImageParser().parse(path)++ def test_eps_cannot_be_enabled(self):+ with self.assertRaises(ValidationError):+ ImageParser(allowed_formats=["PNG", "eps"])++ def test_file_size_limit(self):+ path = self._image("a.png", "PNG")+ parser = ImageParser(max_file_size=path.stat().st_size - 1)+ with self.assertRaises(ValidationError):+ parser.parse(path)++ def test_pixel_limit(self):+ path = self._image("a.png", "PNG", size=(20, 20))+ parser = ImageParser(max_pixels=399)+ with self.assertRaises(ValidationError):+ parser.extract_metadata(path)+ self.assertEqual(ImageParser(max_pixels=400).extract_metadata(path).width, 20)++ def test_missing_file(self):+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(self.dir / "missing.png")++ @unittest.skipUnless(hasattr(os, "mkfifo"), "needs os.mkfifo")+ def test_fifo_is_refused_without_blocking(self):+ fifo = self.dir / "pipe.png"+ os.mkfifo(fifo)+ errors = []++ def run():+ try:+ ImageParser().extract_metadata(fifo)+ except Exception as e:+ errors.append(e)++ # In a thread with a timeout, so a regression fails instead of+ # hanging the test run.+ worker = threading.Thread(target=run, daemon=True)+ worker.start()+ worker.join(timeout=5)+ self.assertFalse(worker.is_alive(), "opening a FIFO blocked")+ self.assertEqual(len(errors), 1)+ self.assertIsInstance(errors[0], ValidationError)++ def test_unexpected_open_error_is_logged_and_wrapped(self):+ parser = ImageParser()+ path = self._image("a.png", "PNG")+ with patch.object(parser, "_open_image", side_effect=OSError("disk error")):+ with self.assertRaises(ProcessingError):+ parser.extract_metadata(path)+ parser.logger.error.assert_called_once()++ def test_rejected_input_is_not_wrapped(self):+ # ValidationError for a rejected file must reach the caller as is,+ # not as a ProcessingError.+ with self.assertRaises(ValidationError) as ctx:+ ImageParser().extract_metadata(self._image("a.gif", "GIF"))+ self.assertNotIsInstance(ctx.exception, ProcessingError)++ def test_preprocess_image_applies_limits(self):+ parser = ImageParser()+ with self.assertRaises(ValidationError):+ parser.preprocess_image(self._image("a.gif", "GIF"))+ output = parser.preprocess_image(self._image("a.png", "PNG"))+ self.assertTrue(output.exists())++ def test_preprocess_image_always_writes_png(self):+ # The output encoder must not follow the input's extension: a PNG+ # named .tiff would otherwise be written by the TIFF encoder.+ path = self.dir / "scan.tiff"+ Image.new("RGB", (8, 8)).save(path, format="PNG")+ output = ImageParser().preprocess_image(path)+ self.assertEqual(output.name, "scan_preprocessed.png")+ with Image.open(output) as out:+ self.assertEqual(out.format, "PNG")++ def test_preprocess_resize_is_limited(self):+ parser = ImageParser(max_pixels=1000)+ with self.assertRaises(ValidationError):+ parser.preprocess_image(self._image("a.png", "PNG"), resize=10)++ def test_preprocess_cmyk_without_grayscale(self):+ # PNG can't store CMYK, so a CMYK JPEG must be converted to RGB.+ path = self.dir / "cmyk.jpg"+ Image.new("CMYK", (8, 8), (0, 255, 255, 0)).save(path, format="JPEG")+ output = ImageParser().preprocess_image(path, grayscale=False)+ with Image.open(output) as out:+ self.assertEqual((out.format, out.mode), ("PNG", "RGB"))++ def _fake_tesseract(self):+ fake = MagicMock()+ fake.image_to_string.return_value = "hello"+ fake.image_to_data.return_value = {+ "level": [1],+ "conf": [90],+ "text": ["hello"],+ "left": [0],+ "top": [0],+ "width": [8],+ "height": [8],+ }+ return fake++ def test_extract_text_passes_checked_image_to_tesseract(self):+ fake_tesseract = self._fake_tesseract()+ with (+ patch("semantica.parse.image_parser.TESSERACT_AVAILABLE", True),+ patch("semantica.parse.image_parser.pytesseract", fake_tesseract),+ ):+ parser = ImageParser()+ with self.assertRaises(ValidationError):+ parser.extract_text(self._image("a.gif", "GIF"))+ fake_tesseract.image_to_string.assert_not_called()++ result = parser.extract_text(self._image("a.png", "PNG"))++ self.assertEqual(result.text, "hello")+ # Tesseract gets a checked, converted image, never the path, so it+ # can't decode the raw file with its own image libraries.+ passed = fake_tesseract.image_to_string.call_args.args[0]+ self.assertIsInstance(passed, Image.Image)++ def test_extract_text_hands_tesseract_a_formatless_rgb_copy(self):+ # pytesseract re-saves an image in its own format and rejects MPO;+ # a converted copy has no format, so it is written as PNG.+ path = self.dir / "phone.jpg"+ first, second = Image.new("RGB", (8, 8)), Image.new("RGB", (8, 8))+ first.save(path, format="MPO", save_all=True, append_images=[second])+ with Image.open(path) as check:+ self.assertEqual(check.format, "MPO")++ fake_tesseract = self._fake_tesseract()+ with (+ patch("semantica.parse.image_parser.TESSERACT_AVAILABLE", True),+ patch("semantica.parse.image_parser.pytesseract", fake_tesseract),+ ):+ ImageParser().extract_text(path)++ passed = fake_tesseract.image_to_string.call_args.args[0]+ self.assertIsNone(passed.format)+ self.assertEqual(passed.mode, "RGB")++ def _ocr_input(self, path):+ """Run extract_text and return a copy of the image tesseract got."""+ captured = []+ fake_tesseract = self._fake_tesseract()+ fake_tesseract.image_to_string.side_effect = lambda img, **kwargs: (+ captured.append(img.copy()) or "hello"+ )+ with (+ patch("semantica.parse.image_parser.TESSERACT_AVAILABLE", True),+ patch("semantica.parse.image_parser.pytesseract", fake_tesseract),+ ):+ ImageParser().extract_text(path)+ return captured[0]++ def test_ocr_input_scales_16_bit_grayscale(self):+ # A plain convert("RGB") clips 16-bit values, turning the text and+ # the background both white.+ path = self.dir / "scan16.png"+ img = Image.new("I;16", (8, 8), 60000)+ img.putpixel((0, 0), 8000)+ img.save(path, format="PNG")++ ocr_input = self._ocr_input(path)+ self.assertEqual(ocr_input.mode, "RGB")+ self.assertEqual(ocr_input.getpixel((0, 0)), (31, 31, 31))+ self.assertEqual(ocr_input.getpixel((1, 1)), (234, 234, 234))++ def test_ocr_input_flattens_alpha_onto_white(self):+ # Black text on a transparent black background must stay readable,+ # not turn solid black.+ path = self.dir / "transparent.png"+ img = Image.new("RGBA", (8, 8), (0, 0, 0, 0))+ img.putpixel((0, 0), (0, 0, 0, 255))+ img.save(path, format="PNG")++ ocr_input = self._ocr_input(path)+ self.assertEqual(ocr_input.getpixel((0, 0)), (0, 0, 0))+ self.assertEqual(ocr_input.getpixel((1, 1)), (255, 255, 255))++ def test_ocr_input_flattens_palette_transparency(self):+ path = self.dir / "palette.png"+ img = Image.new("P", (8, 8), 0)+ img.putpalette([0, 0, 0] * 256)+ img.putpixel((0, 0), 1)+ img.info["transparency"] = 0+ img.save(path, format="PNG", transparency=0)++ ocr_input = self._ocr_input(path)+ self.assertEqual(ocr_input.getpixel((0, 0)), (0, 0, 0))+ self.assertEqual(ocr_input.getpixel((1, 1)), (255, 255, 255))++ # --- Config validation ---++ def test_allowed_formats_validation(self):+ for bad in ["PNG", None, ["FOO"], [], ["PNG", "EPS"]]:+ with self.subTest(allowed_formats=bad):+ with self.assertRaises(ValidationError):+ ImageParser(allowed_formats=bad)++ def test_allowed_formats_aliases(self):+ parser = ImageParser(allowed_formats=["png", "jpg", "tif", "mpo"])+ self.assertEqual(parser.allowed_formats, ("PNG", "JPEG", "TIFF", "JPEG"))+ metadata = parser.extract_metadata(self._image("a.tiff", "TIFF"))+ self.assertEqual(metadata.format, "TIFF")++ def test_allowed_formats_set_has_stable_order(self):+ parser = ImageParser(allowed_formats={"WEBP", "BMP", "PNG", "JPEG"})+ self.assertEqual(parser.allowed_formats, ("BMP", "JPEG", "PNG", "WEBP"))++ def test_max_pixels_validation(self):+ for bad in [0, -1, None, True, "100", 2 * Image.MAX_IMAGE_PIXELS + 1]:+ with self.subTest(max_pixels=bad):+ with self.assertRaises(ValidationError):+ ImageParser(max_pixels=bad)++ def test_max_file_size_validation(self):+ for bad in [0, -1, True, "100"]:+ with self.subTest(max_file_size=bad):+ with self.assertRaises(ValidationError):+ ImageParser(max_file_size=bad)+ ImageParser(max_file_size=None)++ def test_constructs_when_pillow_limit_disabled(self):+ # Applications that accept large scans set MAX_IMAGE_PIXELS = None;+ # the parser must still construct, with Pillow's usual default.+ with patch.object(Image, "MAX_IMAGE_PIXELS", None):+ parser = ImageParser()+ self.assertEqual(parser.max_pixels, 89_478_485)+ path = self._image("a.png", "PNG")+ self.assertEqual(parser.extract_metadata(path).format, "PNG")++ # --- Paths ---++ def test_directory_is_refused(self):+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(self.dir)++ def test_directory_reported_as_permission_error_is_refused(self):+ # Windows raises PermissionError, not IsADirectoryError, when+ # opening a directory.+ with patch("semantica.parse.image_parser.os.open", side_effect=PermissionError):+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(self.dir)++ def test_permission_error_on_a_file_is_not_hidden(self):+ path = self._image("a.png", "PNG")+ with patch("semantica.parse.image_parser.os.open", side_effect=PermissionError):+ with self.assertRaises(ProcessingError):+ ImageParser().extract_metadata(path)++ # --- Pixel limits ---++ def _png_header(self, width, height):+ """A PNG with only a header and an empty IDAT: opens, never decodes."""++ def chunk(kind, body):+ return (+ struct.pack(">I", len(body))+ + kind+ + body+ + struct.pack(">I", zlib.crc32(kind + body))+ )++ ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)+ path = self.dir / f"{width}x{height}.png"+ path.write_bytes(+ b"\x89PNG\r\n\x1a\n"+ + chunk(b"IHDR", ihdr)+ + chunk(b"IDAT", b"")+ + chunk(b"IEND", b"")+ )+ return path++ def test_over_pillow_hard_limit_is_validation_error(self):+ # Over 2 * MAX_IMAGE_PIXELS, Pillow raises DecompressionBombError.+ side = int((2 * Image.MAX_IMAGE_PIXELS) ** 0.5) + 10+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(self._png_header(side, side))++ def test_pillow_warning_does_not_escape(self):+ # Between MAX and 2 * MAX Pillow only warns; our own check must+ # still produce a ValidationError, even when warnings are errors.+ side = int((1.5 * Image.MAX_IMAGE_PIXELS) ** 0.5)+ path = self._png_header(side, side)+ with warnings.catch_warnings():+ warnings.simplefilter("error")+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(path)++ def test_opening_leaves_global_warning_filters_alone(self):+ # The parser must not change process-wide warning filters (as+ # catch_warnings() + simplefilter() do), which other threads+ # depend on.+ parser = ImageParser()+ png = self._image("a.png", "PNG")+ oversized = self._png_header(10_000, 10_000)++ # Pillow's own warning still reaches the caller as usual; our check+ # then rejects the image.+ with self.assertWarns(Image.DecompressionBombWarning):+ with patch.object(+ warnings,+ "simplefilter",+ side_effect=AssertionError("warning filters changed"),+ ):+ parser.extract_metadata(png)+ with self.assertRaises(ValidationError):+ parser.extract_metadata(oversized)++ def test_webp_canvas_checked_before_pillow_opens_it(self):+ # A tiny WebP claiming a 16384 x 16384 canvas: libwebp would+ # allocate it inside Image.open, so it must be refused before that.+ path = self._image("a.webp", "WEBP")+ data = bytearray(path.read_bytes())+ vp8x = b"VP8X" + struct.pack("<I", 10) + b"\x00" * 4+ vp8x += (16383).to_bytes(3, "little") * 2+ data[12:12] = vp8x+ struct.pack_into("<I", data, 4, len(data) - 8)+ path.write_bytes(bytes(data))++ with patch("semantica.parse.image_parser.Image.open") as image_open:+ with self.assertRaises(ValidationError):+ ImageParser().extract_metadata(path)+ image_open.assert_not_called()++ def test_webp_header_size_matches_pillow(self):+ # The header reader must agree with Pillow for every WebP variant.+ variants = {+ "lossy": {"lossless": False},+ "lossless": {"lossless": True},+ "animated": {+ "save_all": True,+ "append_images": [Image.new("RGB", (37, 21), "red")],+ },+ }+ for name, kwargs in variants.items():+ with self.subTest(variant=name):+ path = self.dir / f"{name}.webp"+ Image.new("RGB", (37, 21)).save(path, format="WEBP", **kwargs)+ with Image.open(path) as img:+ expected = img.size+ self.assertEqual(_webp_canvas_size(path.read_bytes()), expected)++ # --- Error mapping and metadata ---++ def test_corrupt_allowed_image_fails_validation(self):+ path = self._image("a.png", "PNG")+ data = bytearray(path.read_bytes())+ data[-20] ^= 0xFF # corrupt the IDAT data, so verify() fails+ path.write_bytes(bytes(data))+ with self.assertRaises(ValidationError):+ ImageParser().parse(path)++ def test_parse_keeps_validation_error_from_second_open(self):+ # The file can change between parse()'s two opens; a rejection on+ # the second one must still be a ValidationError.+ parser = ImageParser()+ path = self._image("a.png", "PNG")+ real_open = parser._open_image+ calls = []++ def open_then_reject(file_path):+ calls.append(file_path)+ if len(calls) == 2:+ raise ValidationError("now a TIFF")+ return real_open(file_path)++ with patch.object(parser, "_open_image", side_effect=open_then_reject):+ with self.assertRaises(ValidationError) as ctx:+ parser.parse(path)+ self.assertNotIsInstance(ctx.exception, ProcessingError)++ def test_parse_does_not_double_wrap_ocr_errors(self):+ parser = ImageParser()+ path = self._image("a.png", "PNG")+ with (+ patch("semantica.parse.image_parser.TESSERACT_AVAILABLE", True),+ patch.object(+ parser, "extract_text", side_effect=ProcessingError("ocr failed")+ ),+ ):+ with self.assertRaises(ProcessingError) as ctx:+ parser.parse(path, extract_text=True)+ self.assertEqual(str(ctx.exception), "ocr failed")++ def test_jpeg_exif_is_extracted(self):+ path = self.dir / "photo.jpg"+ exif = Image.Exif()+ exif[0x010F] = "TestCam" # Make+ Image.new("RGB", (8, 8)).save(path, format="JPEG", exif=exif)+ metadata = ImageParser().extract_metadata(path)+ self.assertEqual(metadata.exif.get("Make"), "TestCam")+++if __name__ == "__main__":+ unittest.main()