Source code for automated_document_parser.loaders.pdf_load.pymupdf_loader

"""Native PyMuPDF backend for page-preserving PDF text extraction."""

import logging

from langchain_core.documents import Document

from .base import BasePDFLoader

logger = logging.getLogger(__name__)


[docs] class PyMuPDFLoader(BasePDFLoader): """Extract one LangChain document per page using PyMuPDF directly. This loader intentionally uses the PyMuPDF API rather than depending on ``langchain-community`` for a local PDF parsing backend. """
[docs] def load(self) -> list[Document]: """Extract page text and document metadata from a local PDF file.""" try: try: import pymupdf except ImportError: import fitz as pymupdf except ImportError as exc: raise ImportError( "PyMuPDF is required. Install with: " "pip install 'automated-document-parser[pymupdf]'" ) from exc password = self.kwargs.get("password") sort = self.kwargs.get("sort", False) documents: list[Document] = [] pdf = None try: pdf = pymupdf.open(str(self.file_path)) if password and not pdf.authenticate(password): raise ValueError("The supplied password could not open this PDF") pdf_metadata = { str(key): str(value) for key, value in (pdf.metadata or {}).items() if value is not None } total_pages = len(pdf) for page_number, page in enumerate(pdf): documents.append( Document( page_content=page.get_text("text", sort=sort) or "", metadata={ "source": str(self.file_path), "page": page_number, "page_number": page_number, "total_pages": total_pages, "pdf_metadata": pdf_metadata, "extraction_method": "pymupdf", }, ) ) logger.info("Loaded %s pages with PyMuPDF", len(documents)) return documents except Exception as exc: logger.exception("Error loading PDF with PyMuPDF") raise RuntimeError(f"Failed to load PDF with PyMuPDF: {exc}") from exc finally: if pdf is not None: pdf.close()
[docs] @staticmethod def get_install_command() -> str: """Return the installation command for the native PyMuPDF backend.""" return "pip install 'automated-document-parser[pymupdf]'"