Source code for automated_document_parser.transformation.chunking

"""Structure-aware document chunking."""

from __future__ import annotations

from ..models import ParsedDocument
from .models import DocumentChunk


def _element_spans(document: ParsedDocument):
    cursor = 0
    for index, element in enumerate(document.elements):
        if not element.text:
            continue
        start = cursor
        end = start + len(element.text)
        yield start, end, index, element
        cursor = end + 2


def _split_text(text: str, max_chars: int, overlap: int) -> list[tuple[int, int]]:
    spans: list[tuple[int, int]] = []
    start = 0
    while start < len(text):
        hard_end = min(len(text), start + max_chars)
        end = hard_end
        if hard_end < len(text):
            # Prefer paragraph, line, sentence, then word boundaries.
            minimum = start + max(1, max_chars // 2)
            for separator in ("\n\n", "\n", ". ", " "):
                candidate = text.rfind(separator, minimum, hard_end)
                if candidate >= minimum:
                    end = candidate + (len(separator) if separator != " " else 0)
                    break
        if end <= start:
            end = hard_end
        spans.append((start, end))
        if end >= len(text):
            break
        start = max(start + 1, end - overlap)
    return spans


[docs] def chunk_document( document: ParsedDocument, *, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True, ) -> tuple[DocumentChunk, ...]: """Split a document while retaining source offsets and layout metadata. Chunks prefer existing element boundaries. Oversized elements are split at paragraph/line/sentence/word boundaries, with bounded character overlap. Offsets always refer to ``ParsedDocument.content``. """ if max_chars < 1: raise ValueError("max_chars must be at least 1") if overlap is None: overlap = min(200, max_chars // 10) if overlap < 0 or overlap >= max_chars: raise ValueError("overlap must be non-negative and smaller than max_chars") if not document.content: return () spans = list(_element_spans(document)) if ( not spans or "\n\n".join(item.text for item in document.elements if item.text) != document.content ): spans = [(0, len(document.content), 0, None)] ranges: list[tuple[int, int]] = [] if respect_element_boundaries: pending_start: int | None = None pending_end = 0 for start, end, _, _ in spans: if pending_start is None: pending_start, pending_end = start, end elif end - pending_start <= max_chars: pending_end = end else: if pending_end - pending_start <= max_chars: ranges.append((pending_start, pending_end)) else: ranges.extend( (pending_start + left, pending_start + right) for left, right in _split_text( document.content[pending_start:pending_end], max_chars, overlap, ) ) pending_start, pending_end = start, end if pending_start is not None: if pending_end - pending_start <= max_chars: ranges.append((pending_start, pending_end)) else: ranges.extend( (pending_start + left, pending_start + right) for left, right in _split_text( document.content[pending_start:pending_end], max_chars, overlap ) ) else: ranges = _split_text(document.content, max_chars, overlap) chunks: list[DocumentChunk] = [] for chunk_index, (start, end) in enumerate(ranges): contributing = [ (index, element) for element_start, element_end, index, element in spans if element is not None and element_start < end and element_end > start ] chunks.append( DocumentChunk( content=document.content[start:end], chunk_index=chunk_index, source=document.source, start_offset=start, end_offset=end, page_numbers=tuple( dict.fromkeys( element.page_number for _, element in contributing if element.page_number is not None ) ), element_indices=tuple(index for index, _ in contributing), element_types=tuple( dict.fromkeys(element.element_type for _, element in contributing) ), metadata={"source_metadata": dict(document.metadata)}, ) ) return tuple(chunks)