"""Open supported PDF and image inputs as PDF documents.""" from __future__ import annotations from pathlib import Path import fitz PDF_EXTENSIONS = {".pdf"} IMAGE_EXTENSIONS = { ".bmp", ".gif", ".jpeg", ".jpg", ".png", ".tif", ".tiff", ".webp", } SUPPORTED_EXTENSIONS = PDF_EXTENSIONS | IMAGE_EXTENSIONS def is_image_input(path: str | Path) -> bool: """Return whether the selected input is a supported image.""" return Path(path).suffix.lower() in IMAGE_EXTENSIONS def open_input_document(path: str | Path) -> fitz.Document: """Open a PDF directly or wrap an image in an in-memory PDF.""" input_path = Path(path) extension = input_path.suffix.lower() if extension not in SUPPORTED_EXTENSIONS: supported = ", ".join(sorted(SUPPORTED_EXTENSIONS)) raise ValueError(f"Unsupported input type. Supported: {supported}") document = fitz.open(str(input_path)) if extension in PDF_EXTENSIONS: return document try: pdf_bytes = document.convert_to_pdf() finally: document.close() return fitz.open("pdf", pdf_bytes)