darachhat
feat: build production-ready Khmer Document Corpus v0.2.0 with Typer CLI, PyMuPDF, Polars, and DI architecture
c4e128a | """PDF metadata extraction using PyMuPDF (fitz) with pypdf fallback.""" | |
| from __future__ import annotations | |
| import re | |
| from pathlib import Path | |
| from loguru import logger | |
| from app.models.document import Category, DocumentMeta, Language, PageMeta | |
| from app.utils.file import file_sha256 | |
| # Regex pattern to identify Khmer Unicode range U+1780 to U+17FF and U+19E0 to U+19FF | |
| KHMER_CHAR_PATTERN = re.compile(r"[\u1780-\u17ff\u19e0-\u19ff]") | |
| ENGLISH_CHAR_PATTERN = re.compile(r"[a-zA-Z]") | |
| def _detect_language(text: str) -> Language: | |
| """Heuristic language detection based on character occurrences.""" | |
| if not text.strip(): | |
| return Language.unknown | |
| has_khmer = bool(KHMER_CHAR_PATTERN.search(text)) | |
| has_english = bool(ENGLISH_CHAR_PATTERN.search(text)) | |
| if has_khmer and has_english: | |
| return Language.mixed | |
| elif has_khmer: | |
| return Language.km | |
| elif has_english: | |
| return Language.en | |
| return Language.unknown | |
| class MetadataExtractor: | |
| """ | |
| Extracts structural, textual, and spatial metadata from PDF documents. | |
| Primary engine: PyMuPDF (fitz). | |
| Fallback engine: pypdf. | |
| """ | |
| def __init__(self, *, fallback_to_pypdf: bool = True) -> None: | |
| self._fallback_to_pypdf = fallback_to_pypdf | |
| def extract(self, pdf_path: Path, category_hint: str = "other") -> DocumentMeta: | |
| """Extract metadata from a PDF file.""" | |
| pdf_path = Path(pdf_path).resolve() | |
| if not pdf_path.exists(): | |
| raise FileNotFoundError(f"PDF file not found: {pdf_path}") | |
| file_size_bytes = pdf_path.stat().st_size | |
| sha256_hash = file_sha256(pdf_path) | |
| try: | |
| return self._extract_pymupdf(pdf_path, file_size_bytes, sha256_hash, category_hint) | |
| except Exception as exc: | |
| logger.warning("PyMuPDF failed on {}: {}", pdf_path.name, exc) | |
| if self._fallback_to_pypdf: | |
| logger.info("Attempting pypdf fallback for {}", pdf_path.name) | |
| return self._extract_pypdf(pdf_path, file_size_bytes, sha256_hash, category_hint) | |
| raise | |
| def _extract_pymupdf( | |
| self, | |
| pdf_path: Path, | |
| file_size_bytes: int, | |
| sha256_hash: str, | |
| category_hint: str, | |
| ) -> DocumentMeta: | |
| import fitz # PyMuPDF | |
| doc = fitz.open(pdf_path) | |
| pages_count = len(doc) | |
| pages_meta: list[PageMeta] = [] | |
| total_text = "" | |
| has_images = False | |
| has_tables = False | |
| has_text_layer = False | |
| for idx, page in enumerate(doc, start=1): | |
| rect = page.rect | |
| width, height = rect.width, rect.height | |
| text = page.get_text("text") | |
| char_count = len(text) | |
| total_text += text + " " | |
| images = page.get_images() | |
| img_count = len(images) | |
| if img_count > 0: | |
| has_images = True | |
| page_has_text = char_count > 10 | |
| if page_has_text: | |
| has_text_layer = True | |
| # Basic table heuristic via PyMuPDF find_tables if available | |
| try: | |
| tables = page.find_tables() | |
| if tables and len(tables.tables) > 0: | |
| has_tables = True | |
| except AttributeError: | |
| pass | |
| pages_meta.append( | |
| PageMeta( | |
| page_number=idx, | |
| width_pt=float(width), | |
| height_pt=float(height), | |
| text_char_count=char_count, | |
| image_count=img_count, | |
| has_text_layer=page_has_text, | |
| ) | |
| ) | |
| doc.close() | |
| lang = _detect_language(total_text) | |
| native_pdf = has_text_layer | |
| scanned = not has_text_layer and has_images | |
| cat_val = category_hint if category_hint in Category.__members__ else "other" | |
| return DocumentMeta( | |
| filename=pdf_path.name, | |
| language=lang, | |
| category=Category(cat_val), | |
| pages=pages_count, | |
| file_size_bytes=file_size_bytes, | |
| native_pdf=native_pdf, | |
| scanned=scanned, | |
| has_tables=has_tables, | |
| has_images=has_images, | |
| has_header=False, | |
| has_footer=False, | |
| sha256=sha256_hash, | |
| pdf_path=str(pdf_path), | |
| pages_meta=pages_meta, | |
| ) | |
| def _extract_pypdf( | |
| self, | |
| pdf_path: Path, | |
| file_size_bytes: int, | |
| sha256_hash: str, | |
| category_hint: str, | |
| ) -> DocumentMeta: | |
| from pypdf import PdfReader | |
| reader = PdfReader(pdf_path) | |
| pages_count = len(reader.pages) | |
| pages_meta: list[PageMeta] = [] | |
| total_text = "" | |
| has_images = False | |
| has_text_layer = False | |
| for idx, page in enumerate(reader.pages, start=1): | |
| box = page.mediabox | |
| width = float(box.width) | |
| height = float(box.height) | |
| text = page.extract_text() or "" | |
| char_count = len(text) | |
| total_text += text + " " | |
| img_count = len(page.images) | |
| if img_count > 0: | |
| has_images = True | |
| page_has_text = char_count > 10 | |
| if page_has_text: | |
| has_text_layer = True | |
| pages_meta.append( | |
| PageMeta( | |
| page_number=idx, | |
| width_pt=width, | |
| height_pt=height, | |
| text_char_count=char_count, | |
| image_count=img_count, | |
| has_text_layer=page_has_text, | |
| ) | |
| ) | |
| lang = _detect_language(total_text) | |
| native_pdf = has_text_layer | |
| scanned = not has_text_layer and has_images | |
| cat_val = category_hint if category_hint in Category.__members__ else "other" | |
| return DocumentMeta( | |
| filename=pdf_path.name, | |
| language=lang, | |
| category=Category(cat_val), | |
| pages=pages_count, | |
| file_size_bytes=file_size_bytes, | |
| native_pdf=native_pdf, | |
| scanned=scanned, | |
| has_tables=False, | |
| has_images=has_images, | |
| has_header=False, | |
| has_footer=False, | |
| sha256=sha256_hash, | |
| pdf_path=str(pdf_path), | |
| pages_meta=pages_meta, | |
| ) | |