"""Token-budget chunking with an injectable tokenizer."""
from __future__ import annotations
import re
from collections.abc import Callable
from ..models import ParsedDocument
from ..transformation.models import DocumentChunk
from .models import Tokenizer
[docs]
def chunk_document_by_tokens(
document: ParsedDocument,
*,
tokenizer: Tokenizer | Callable[[str], int],
max_tokens: int = 512,
overlap_tokens: int = 50,
) -> tuple[DocumentChunk, ...]:
"""Chunk text to a tokenizer-defined budget while retaining character offsets.
Tokenizer must expose ``count_tokens(text)`` or be a callable returning a
token count. Binary search bounds tokenizer calls for each chunk. Candidate
boundaries are whitespace boundaries; no tokenizer package or model
download is required by the core distribution.
"""
if max_tokens < 1 or overlap_tokens < 0 or overlap_tokens >= max_tokens:
raise ValueError(
"max_tokens must be positive and overlap_tokens in [0, max_tokens)"
)
count: Callable[[str], int] = (
tokenizer.count_tokens if hasattr(tokenizer, "count_tokens") else tokenizer # type: ignore[union-attr,assignment]
)
text = document.content
if not text:
return ()
words = list(re.finditer(r"\S+", text))
if not words:
return ()
# Match the canonical ParsedDocument element/content joining convention.
spans: list[tuple[int, int, int, object]] = []
cursor = 0
for index, element in enumerate(document.elements):
if not element.text:
continue
start = cursor
end = start + len(element.text)
spans.append((start, end, index, element))
cursor = end + 2
if (
"\n\n".join(element.text for element in document.elements if element.text)
!= text
):
spans = []
chunks: list[DocumentChunk] = []
start_word = 0
while start_word < len(words):
# Find the furthest word boundary that satisfies the token budget.
low, high = start_word + 1, len(words)
best_end = start_word
while low <= high:
middle = (low + high) // 2
candidate = text[words[start_word].start() : words[middle - 1].end()]
if count(candidate) <= max_tokens:
best_end = middle
low = middle + 1
else:
high = middle - 1
if best_end == start_word:
raise ValueError(
"A single token exceeds max_tokens; increase the token budget"
)
start = 0 if start_word == 0 else words[start_word].start()
end = len(text) if best_end == len(words) else words[best_end].start()
content = text[start:end]
contributing = [
(index, element)
for element_start, element_end, index, element in spans
if element_start < end and element_end > start
]
chunks.append(
DocumentChunk(
content=content,
chunk_index=len(chunks),
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={
"token_count": count(content),
"chunking": "token",
},
)
)
if best_end == len(words):
break
# Find the earliest next start whose suffix fits the overlap budget.
low, high = start_word + 1, best_end
next_start = best_end
while low <= high:
middle = (low + high) // 2
suffix = text[words[middle].start() : words[best_end - 1].end()]
if count(suffix) <= overlap_tokens:
next_start = middle
high = middle - 1
else:
low = middle + 1
start_word = max(start_word + 1, next_start)
return tuple(chunks)