darachhat
feat: build production-ready Khmer Document Corpus v0.2.0 with Typer CLI, PyMuPDF, Polars, and DI architecture
c4e128a | """PDF page preview renderer using PyMuPDF and Pillow.""" | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from loguru import logger | |
| from PIL import Image | |
| from app.utils.file import ensure_dir, safe_stem | |
| class PreviewRenderer: | |
| """Renders PDF page preview images using PyMuPDF pixmaps and Pillow.""" | |
| def __init__( | |
| self, | |
| out_dir: Path = Path("preview"), | |
| dpi: int = 150, | |
| fmt: str = "png", | |
| max_pages: int = 1, | |
| ) -> None: | |
| self._out_dir = Path(out_dir).resolve() | |
| self._dpi = dpi | |
| self._fmt = fmt.lower() | |
| self._max_pages = max_pages | |
| def render(self, pdf_path: Path) -> Path: | |
| """ | |
| Render preview image(s) for a PDF document. | |
| Returns path to the output document preview directory. | |
| """ | |
| import fitz # PyMuPDF | |
| pdf_path = Path(pdf_path).resolve() | |
| if not pdf_path.exists(): | |
| raise FileNotFoundError(f"PDF file not found: {pdf_path}") | |
| doc_dir = ensure_dir(self._out_dir / safe_stem(pdf_path)) | |
| doc = fitz.open(pdf_path) | |
| zoom = self._dpi / 72.0 | |
| matrix = fitz.Matrix(zoom, zoom) | |
| pages_to_render = min(len(doc), self._max_pages) | |
| for i in range(pages_to_render): | |
| page = doc[i] | |
| pix = page.get_pixmap(matrix=matrix, alpha=False) | |
| img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) | |
| out_file = doc_dir / f"page_{i + 1:04d}.{self._fmt}" | |
| img.save(out_file) | |
| logger.debug("Rendered preview: {}", out_file) | |
| doc.close() | |
| return doc_dir | |