Source code for automated_document_parser.loaders.pdf_load.pdfplumber_layout_loader

"""Layout-aware PDF extraction using the MIT-licensed pdfplumber library."""

from __future__ import annotations

import hashlib
import logging
import statistics
from pathlib import Path
from typing import Any

from langchain_core.documents import Document

from .base import BasePDFLoader

logger = logging.getLogger(__name__)


[docs] class PDFPlumberLayoutLoader(BasePDFLoader): """Extract ordered text blocks and tables with page-level coordinates. The backend emits one LangChain document per semantic element. Metadata contains page dimensions, element type, bounding box, reading order and font hints. Tables retain their original cell matrix in ``table_rows``. Reading order uses a heuristic for simple multi-column layouts; complex magazine-style layouts may require custom table or column settings. Optional ``ocr_fallback=True`` invokes local Tesseract OCR only on pages whose native text is below ``ocr_min_characters``. ``image_output_dir`` saves rendered crops for embedded image regions. Both visual capabilities use the optional PDFium renderer; OCR additionally needs Tesseract installed. """
[docs] def load(self) -> list[Document]: """Extract text and tables from a local PDF while preserving layout.""" try: import pdfplumber except ImportError as exc: raise ImportError( "The layout-aware PDF backend requires pdfplumber. " "Install with: pip install 'automated-document-parser[pdf-layout]'" ) from exc source = str(self.file_path) extract_tables = self.kwargs.get("extract_tables", True) detect_headings = self.kwargs.get("detect_headings", True) table_settings = self.kwargs.get("table_settings") ocr_fallback = self.kwargs.get("ocr_fallback", False) ocr_min_characters = self.kwargs.get("ocr_min_characters", 20) ocr_resolution = self.kwargs.get("ocr_resolution", 200) ocr_languages = self.kwargs.get("ocr_languages", "eng") tesseract_config = self.kwargs.get("tesseract_config", "") image_output_dir = self.kwargs.get("image_output_dir") documents: list[Document] = [] try: with pdfplumber.open(source, password=self.kwargs.get("password")) as pdf: pdf_metadata = dict(pdf.metadata or {}) for page_index, page in enumerate(pdf.pages): documents.extend( self._extract_page( page=page, source=source, page_number=page_index, pdf_metadata=pdf_metadata, extract_tables=extract_tables, detect_headings=detect_headings, table_settings=table_settings, ocr_fallback=ocr_fallback, ocr_min_characters=ocr_min_characters, ocr_resolution=ocr_resolution, ocr_languages=ocr_languages, tesseract_config=tesseract_config, image_output_dir=image_output_dir, ) ) except (OSError, ValueError) as exc: raise RuntimeError( f"Failed to extract PDF layout from {source}: {exc}" ) from exc return documents
@staticmethod def _extract_page( *, page: Any, source: str, page_number: int, pdf_metadata: dict[str, Any], extract_tables: bool, detect_headings: bool, table_settings: dict[str, Any] | None, ocr_fallback: bool = False, ocr_min_characters: int = 20, ocr_resolution: int = 200, ocr_languages: str = "eng", tesseract_config: str = "", image_output_dir: str | Path | None = None, ) -> list[Document]: """Extract one page into ordered text and table elements.""" tables: list[dict[str, Any]] = [] table_regions: list[tuple[float, float, float, float]] = [] if extract_tables: found_tables = page.find_tables(table_settings=table_settings) for table_index, table in enumerate(found_tables): rows = table.extract() or [] normalised_rows = [ ["" if cell is None else str(cell) for cell in row] for row in rows ] if not any( any(cell.strip() for cell in row) for row in normalised_rows ): continue bbox = tuple(float(value) for value in table.bbox) table_regions.append(bbox) tables.append( { "top": bbox[1], "x0": bbox[0], "bbox": bbox, "table_index": table_index, "rows": normalised_rows, } ) words = page.extract_words( x_tolerance=2, y_tolerance=3, keep_blank_chars=False, use_text_flow=False, extra_attrs=["fontname", "size"], ) visible_words = [ word for word in words if not _inside_any_region(word, table_regions) ] lines = _group_words_into_lines(visible_words, page_width=float(page.width)) lines, column_centres = _order_lines_by_columns( lines, page_width=float(page.width), page_height=float(page.height), ) sizes = [ float(word["size"]) for line in lines for word in line["words"] if isinstance(word.get("size"), (int, float)) ] typical_size = statistics.median(sizes) if sizes else 10.0 elements: list[dict[str, Any]] = [] for line in lines: line_words = line["words"] text = " ".join(str(word["text"]) for word in line_words).strip() if not text: continue font_sizes = [ float(word["size"]) for word in line_words if isinstance(word.get("size"), (int, float)) ] font_names = [str(word.get("fontname", "")) for word in line_words] max_size = max(font_sizes, default=typical_size) is_bold = any("bold" in font.lower() for font in font_names) is_heading = detect_headings and ( max_size >= typical_size * 1.25 or is_bold and max_size >= typical_size ) elements.append( { "top": line["top"], "x0": line["x0"], "text": text, "element_type": "heading" if is_heading else "paragraph", "bbox": ( min(float(word["x0"]) for word in line_words), min(float(word["top"]) for word in line_words), max(float(word["x1"]) for word in line_words), max(float(word["bottom"]) for word in line_words), ), "font_size": max_size, "font_names": sorted(set(font_names)), "column_order": line.get("column_order", 0), } ) for table in tables: table["column_order"] = ( min( range(len(column_centres)), key=lambda index: abs(table["x0"] - column_centres[index]), ) if column_centres else 0 ) elements.append( { "top": table["top"], "x0": table["x0"], "text": _table_to_markdown(table["rows"]), "element_type": "table", "bbox": table["bbox"], "table_index": table["table_index"], "table_rows": table["rows"], "column_order": table["column_order"], } ) native_text_length = sum( len(str(word.get("text", ""))) for word in visible_words ) + sum(len(cell) for table in tables for row in table["rows"] for cell in row) should_ocr = ocr_fallback and native_text_length < ocr_min_characters should_extract_images = image_output_dir is not None and bool( getattr(page, "images", None) ) rendered_page = ( _render_pdf_page(source, page_number, ocr_resolution) if should_ocr or should_extract_images else None ) if should_ocr: elements.extend( _ocr_page( page, source=source, page_number=page_number, resolution=ocr_resolution, languages=ocr_languages, config=tesseract_config, rendered=rendered_page, ) ) if should_extract_images: elements.extend( _extract_image_regions( page, source=source, page_number=page_number, output_dir=image_output_dir, resolution=ocr_resolution, rendered=rendered_page, ) ) elements.sort( key=lambda item: ( item.get("column_order", 0), item["top"], item["x0"], ) ) documents: list[Document] = [] for reading_order, element in enumerate(elements): metadata = { "source": source, "page": page_number, "page_number": page_number, "page_width": float(page.width), "page_height": float(page.height), "element_type": element["element_type"], "bbox": list(element["bbox"]), "reading_order": reading_order, "extraction_method": element.get( "extraction_method", "pdfplumber-layout" ), "reading_order_strategy": "column-aware-top-to-bottom-left-to-right", "pdf_metadata": pdf_metadata, } for key in ( "font_size", "font_names", "table_index", "table_rows", "confidence", "asset_path", "image_index", "image_extraction_method", ): if key in element: metadata[key] = element[key] documents.append(Document(page_content=element["text"], metadata=metadata)) return documents
[docs] def get_install_command(self) -> str: """Return the installation command for this layout-aware backend.""" extras = ["pdf-layout"] if self.kwargs.get("ocr_fallback"): extras.append("ocr") if self.kwargs.get("image_output_dir") is not None: extras.append("pdf-images") install = f"pip install 'automated-document-parser[{','.join(extras)}]'" if self.kwargs.get("ocr_fallback"): install += " and install the Tesseract OCR system binary" return install
def _ocr_page( page: Any, *, source: str, page_number: int, resolution: int, languages: str, config: str, rendered: Any | None = None, ) -> list[dict[str, Any]]: """OCR a page and return line elements with normalized confidence and coordinates.""" try: import pytesseract from pytesseract import Output except ImportError as exc: raise ImportError( "OCR fallback requires pytesseract and the Tesseract system binary. " "Install with: pip install 'automated-document-parser[ocr]' and install Tesseract OCR." ) from exc try: if rendered is None: rendered = _render_pdf_page(source, page_number, resolution) data = pytesseract.image_to_data( rendered, lang=languages, config=config, output_type=Output.DICT, ) except ImportError: raise except Exception as exc: raise RuntimeError( f"Tesseract OCR failed on page {page_number + 1}: {exc}" ) from exc groups: dict[tuple[int, int, int], list[int]] = {} for index, raw_text in enumerate(data.get("text", [])): text = str(raw_text).strip() try: confidence = float(data["conf"][index]) except (KeyError, TypeError, ValueError, IndexError): confidence = -1 if text and confidence >= 0: key = ( int(data.get("block_num", [0])[index]), int(data.get("par_num", [0])[index]), int(data.get("line_num", [index])[index]), ) groups.setdefault(key, []).append(index) scale_x = float(page.width) / rendered.width scale_y = float(page.height) / rendered.height results: list[dict[str, Any]] = [] for indexes in groups.values(): text = " ".join(str(data["text"][index]).strip() for index in indexes).strip() if not text: continue confidences = [float(data["conf"][index]) for index in indexes] left = min(int(data["left"][index]) for index in indexes) top = min(int(data["top"][index]) for index in indexes) right = max( int(data["left"][index]) + int(data["width"][index]) for index in indexes ) bottom = max( int(data["top"][index]) + int(data["height"][index]) for index in indexes ) results.append( { "top": top * scale_y, "x0": left * scale_x, "text": text, "element_type": "paragraph", "bbox": ( left * scale_x, top * scale_y, right * scale_x, bottom * scale_y, ), "confidence": sum(confidences) / len(confidences) / 100.0, "extraction_method": "tesseract-ocr", } ) return results def _render_pdf_page(source: str, page_number: int, resolution: int) -> Any: """Render a PDF page to Pillow using the optional PDFium backend.""" try: import pypdfium2 as pdfium except ImportError as exc: raise ImportError( "PDF rendering requires pypdfium2. Install with: " "pip install 'automated-document-parser[ocr]' or '[pdf-images]'." ) from exc document = pdfium.PdfDocument(source) page = document[page_number] bitmap = page.render(scale=resolution / 72.0) try: return bitmap.to_pil() finally: bitmap.close() page.close() document.close() def _extract_image_regions( page: Any, *, source: str, page_number: int, output_dir: str | Path, resolution: int, rendered: Any | None = None, ) -> list[dict[str, Any]]: """Save rendered crops for embedded PDF image regions and return asset references.""" try: from PIL import Image except ImportError as exc: raise ImportError( "Image-region extraction requires Pillow. Install with: " "pip install 'automated-document-parser[pdf-images]'" ) from exc output_path = Path(output_dir).expanduser() output_path.mkdir(parents=True, exist_ok=True) if rendered is None: rendered = _render_pdf_page(source, page_number, resolution) scale_x = rendered.width / float(page.width) scale_y = rendered.height / float(page.height) results: list[dict[str, Any]] = [] source_path = Path(source).expanduser().resolve() source_token = hashlib.sha256(str(source_path).encode("utf-8")).hexdigest()[:8] source_stem = ( "".join( character if character.isalnum() or character in "-_" else "_" for character in source_path.stem ) or "document" ) for image_index, image in enumerate(page.images, start=1): bbox = ( float(image["x0"]), float(image["top"]), float(image["x1"]), float(image["bottom"]), ) crop_box = ( max(0, int(bbox[0] * scale_x)), max(0, int(bbox[1] * scale_y)), min(rendered.width, int(bbox[2] * scale_x)), min(rendered.height, int(bbox[3] * scale_y)), ) if crop_box[2] <= crop_box[0] or crop_box[3] <= crop_box[1]: continue asset = output_path / ( f"{source_stem}_{source_token}_page_{page_number + 1:04d}_" f"image_{image_index:03d}.png" ) crop = rendered.crop(crop_box) if not isinstance(crop, Image.Image): continue crop.save(asset, format="PNG") results.append( { "top": bbox[1], "x0": bbox[0], "text": f"[Image region extracted: {asset.name}]", "element_type": "image", "bbox": bbox, "image_index": image_index, "asset_path": str(asset.resolve()), "image_extraction_method": "rendered-page-region-crop", "extraction_method": "pdfplumber-image-region", } ) return results def _group_words_into_lines( words: list[dict[str, Any]], *, page_width: float ) -> list[dict[str, Any]]: """Group words into visual lines without joining separate text columns.""" ordered = sorted(words, key=lambda word: (float(word["top"]), float(word["x0"]))) lines: list[dict[str, Any]] = [] for word in ordered: word_top = float(word["top"]) word_x0 = float(word["x0"]) column_gap = max(24.0, page_width * 0.04) target = next( ( line for line in reversed(lines[-6:]) if abs(line["top"] - word_top) <= 3.0 and word_x0 - max(float(item["x1"]) for item in line["words"]) <= column_gap ), None, ) if target is None: lines.append({"top": word_top, "x0": float(word["x0"]), "words": [word]}) else: target["words"].append(word) target["top"] = min(target["top"], word_top) target["x0"] = min(target["x0"], float(word["x0"])) for line in lines: line["words"].sort(key=lambda word: float(word["x0"])) return lines def _inside_any_region( word: dict[str, Any], regions: list[tuple[float, float, float, float]], ) -> bool: """Return whether a word's centre lies inside an extracted table region.""" x = (float(word["x0"]) + float(word["x1"])) / 2 y = (float(word["top"]) + float(word["bottom"])) / 2 return any(x0 <= x <= x1 and top <= y <= bottom for x0, top, x1, bottom in regions) def _table_to_markdown(rows: list[list[str]]) -> str: """Render table cells as readable Markdown without changing cell values.""" if not rows: return "" escaped = [ [cell.replace("|", "\\|").replace("\n", " ").strip() for cell in row] for row in rows ] width = max(len(row) for row in escaped) padded = [row + [""] * (width - len(row)) for row in escaped] header = padded[0] separator = ["---"] * width lines = [ "| " + " | ".join(header) + " |", "| " + " | ".join(separator) + " |", ] lines.extend("| " + " | ".join(row) + " |" for row in padded[1:]) return "\n".join(lines) def _order_lines_by_columns( lines: list[dict[str, Any]], *, page_width: float, page_height: float ) -> tuple[list[dict[str, Any]], list[float]]: """Detect repeated column starts and return a column-aware reading order. A column is inferred only when at least two lines support each candidate start position. Sparse headings and page furniture remain before or after the main body instead of creating spurious columns. """ if len(lines) < 4: for line in lines: line["column_order"] = 0 return sorted(lines, key=lambda line: (line["top"], line["x0"])), [] body_lines = [ line for line in lines if page_height * 0.05 <= line["top"] <= page_height * 0.95 ] starts = sorted(float(line["x0"]) for line in body_lines) threshold = max(48.0, page_width * 0.14) clusters: list[list[float]] = [] for start in starts: if not clusters or start - clusters[-1][-1] > threshold: clusters.append([start]) else: clusters[-1].append(start) supported = [cluster for cluster in clusters if len(cluster) >= 2] if len(supported) < 2: for line in lines: line["column_order"] = 0 return sorted(lines, key=lambda line: (line["top"], line["x0"])), [] centres = [sum(cluster) / len(cluster) for cluster in supported] for line in lines: if line["top"] < page_height * 0.05: line["column_order"] = -1 elif line["top"] > page_height * 0.95: line["column_order"] = len(centres) else: line["column_order"] = min( range(len(centres)), key=lambda index: abs(line["x0"] - centres[index]), ) return sorted( lines, key=lambda line: (line["column_order"], line["top"], line["x0"]), ), centres