"""Stable, framework-friendly representations of parsed documents."""
from __future__ import annotations
import json
from collections.abc import Iterable
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from langchain_core.documents import Document
[docs]
@dataclass(frozen=True, slots=True)
class DocumentElement:
"""A source-preserving unit of extracted document content."""
text: str
element_type: str = "text"
page_number: int | None = None
bbox: tuple[float, float, float, float] | None = None
reading_order: int | None = None
confidence: float | None = None
metadata: dict[str, Any] = field(default_factory=dict)
[docs]
@dataclass(frozen=True, slots=True)
class ParsedDocument:
"""Normalised representation of a source document.
The model keeps the original source, combined text, backend metadata and
per-document elements together. Layout-aware backends can populate element
types, page coordinates, reading order and confidence without changing the
compatibility API.
"""
source: str
content: str
metadata: dict[str, Any] = field(default_factory=dict)
elements: tuple[DocumentElement, ...] = ()
[docs]
@classmethod
def from_documents(
cls,
documents: Iterable[Document],
source: str | Path,
) -> ParsedDocument:
"""Create a normalised document from LangChain documents."""
source_path = str(Path(source).expanduser().resolve())
elements: list[DocumentElement] = []
metadata: dict[str, Any] = {}
for index, document in enumerate(documents):
document_metadata = dict(document.metadata)
if index == 0:
metadata = document_metadata.copy()
page_number = document_metadata.get(
"page_number", document_metadata.get("page")
)
if not isinstance(page_number, int):
page_number = None
raw_bbox = document_metadata.get("bbox")
bbox = (
tuple(float(value) for value in raw_bbox)
if isinstance(raw_bbox, (list, tuple)) and len(raw_bbox) == 4
else None
)
reading_order = document_metadata.get("reading_order")
if not isinstance(reading_order, int):
reading_order = None
confidence = document_metadata.get("confidence")
if not isinstance(confidence, (int, float)):
confidence = None
elements.append(
DocumentElement(
text=document.page_content,
element_type=str(document_metadata.get("element_type", "text")),
page_number=page_number,
bbox=bbox,
reading_order=reading_order,
confidence=float(confidence) if confidence is not None else None,
metadata=document_metadata,
)
)
content = "\n\n".join(element.text for element in elements if element.text)
metadata.setdefault("source", source_path)
metadata["element_count"] = len(elements)
return cls(
source=source_path,
content=content,
metadata=metadata,
elements=tuple(elements),
)
[docs]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-compatible structure when metadata values are serialisable."""
return asdict(self)
[docs]
def to_json(self, *, indent: int | None = 2) -> str:
"""Serialise the document to JSON.
Raises:
TypeError: If a loader has attached non-JSON-serialisable metadata.
"""
return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
[docs]
def to_langchain_documents(self) -> list[Document]:
"""Convert elements back to LangChain ``Document`` instances."""
return [
Document(page_content=element.text, metadata=dict(element.metadata))
for element in self.elements
]