chunklet.document_chunker.document_chunker
Classes:
-
DocumentChunker–A comprehensive document chunker that handles various file formats.
DocumentChunker
DocumentChunker(
lang: str,
max_tokens: Annotated[int | None, Field(ge=12)] = None,
max_sentences: Annotated[
int | None, Field(ge=1)
] = None,
max_section_breaks: Annotated[
int | None, Field(ge=1)
] = None,
overlap_percent: Annotated[
int, Field(ge=0, le=75)
] = 20,
token_counter: Callable[[str], int] | None = None,
processor_registry: CustomProcessorRegistry
| None = None,
continuation_marker: str = "...",
verbose: bool = False,
)
Bases: BaseChunker
A comprehensive document chunker that handles various file formats.
This class provides a high-level interface to chunk text from different
document types. It automatically detects the file format and uses the
appropriate method to extract content before passing it to an underlying
PlainTextChunker instance.
Key Features
- Multi-Format Support: Chunks text from PDF, TXT, MD, and RST files.
- Metadata Enrichment: Automatically adds source file path and other
document-level metadata (e.g., PDF page numbers) to each chunk. - Bulk Processing: Efficiently chunks multiple documents in a single call. - Pluggable Document processors: Integrate custom processors allowing definition of specific logic for extracting text from various file types.
Initializes the DocumentChunker.
Parameters:
-
(langstr) –Language code (e.g., 'en', 'fr', 'auto').
-
(max_tokensAnnotated[int | None, Field(ge=12)], default:None) –Maximum number of tokens per chunk. Must be >= 12.
-
(max_sentencesAnnotated[int | None, Field(ge=1)], default:None) –Maximum number of sentences per chunk. Must be >= 1.
-
(max_section_breaksAnnotated[int | None, Field(ge=1)], default:None) –Maximum number of section breaks per chunk. Section breaks include Markdown headings (# to ######), horizontal rules (---, ***, ___), and
tags. Must be >= 1. -
(overlap_percentAnnotated[int, Field(ge=0, le=75)], default:20) –Percentage of overlap between chunks (0-75). Defaults to 20.
-
(token_counterCallable[[str], int] | None, default:None) –Function that counts tokens in text. If None, must be provided (or token-based limits disabled).
-
(processor_registryCustomProcessorRegistry | None, default:None) –An optional CustomProcessorRegistry instance to use for custom document processors. If None, a fresh registry is created.
-
(continuation_markerstr, default:'...') –The marker to prepend to unfitted clauses. Defaults to '...'.
-
(verbosebool, default:False) –Enable verbose logging.
Methods:
-
chunk_file–Chunks a single document from a given path using the constraints
-
chunk_files–Chunks multiple documents from a list of file paths using the constraints
-
chunk_text–Chunks raw text content using the constraints configured at initialization.
-
chunk_texts–Chunks multiple text contents using the constraints configured
-
extract_text_and_metadata–Extracts text content and metadata from a document.
Attributes:
-
supported_extensions–Get the supported extensions, including the custom ones.
-
verbose(bool) –Get the verbosity status.
Source code in src/chunklet/document_chunker/document_chunker.py
supported_extensions
property
Get the supported extensions, including the custom ones.
chunk_file
chunk_file(
path: str | Path,
*,
token_counter: Callable[[str], int] | None = None,
) -> list[DotDict]
Chunks a single document from a given path using the constraints configured at initialization.
This method automatically detects the file type and uses the appropriate processor to extract text before chunking. It then adds document-level metadata to each resulting chunk.
Parameters:
-
(pathstr | Path) –The path to the document file.
-
(token_counterCallable[[str], int] | None, default:None) –Optional token counting function.
Returns:
-
list[DotDict]–A list of
DotDictobjects, each representing -
list[DotDict]–a chunk with its content and metadata.
Raises:
-
InvalidInputError–If the input arguments aren't valid.
-
FileNotFoundError–If provided file path not found.
-
UnsupportedFileTypeError–If the file extension is not supported or is missing.
-
MissingTokenCounterError–If
max_tokensis provided but notoken_counteris provided. -
CallbackError–If a callback function (e.g., custom processors callbacks) fails during execution.
Source code in src/chunklet/document_chunker/document_chunker.py
chunk_files
chunk_files(
paths: IterableOfPath,
*,
token_counter: Callable[[str], int] | None = None,
separator: Any = None,
n_jobs: Annotated[int, Field(ge=1)] | None = None,
show_progress: bool = False,
on_errors: Literal["raise", "skip", "break"] = "raise",
) -> Generator[DotDict, None, None]
Chunks multiple documents from a list of file paths using the constraints configured at initialization.
This method is a memory-efficient generator that yields chunks as they are processed, without loading all documents into memory at once. It handles various file types.
Parameters:
-
(pathsIterableOfPath) –A non-string iterable of paths to the document files.
-
(token_counterCallable[[str], int] | None, default:None) –Optional token counting function.
-
(separatorAny, default:None) –A value to be yielded after the chunks of each source are processed. Note: None cannot be used as a separator.
-
(n_jobsAnnotated[int, Field(ge=1)] | None, default:None) –Number of parallel workers to use. If None, uses all available CPUs. Must be >= 1 if specified.
-
(show_progressbool, default:False) –Display progress bar during processing. Defaults to False.
-
(on_errorsLiteral['raise', 'skip', 'break'], default:'raise') –How to handle errors during processing. Can be 'raise', 'ignore', or 'break'.
Yields:
-
DotDict–DotDictobject, representing a chunk with its content and metadata.
Raises:
-
InvalidInputError–If the input arguments aren't valid.
-
FileNotFoundError–If provided file path not found.
-
UnsupportedFileTypeError–If the file extension is not supported or is missing.
-
MissingTokenCounterError–If
max_tokensis provided but notoken_counteris provided. -
CallbackError–If a callback function (e.g., custom processors callbacks) fails during execution.
Source code in src/chunklet/document_chunker/document_chunker.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
chunk_text
chunk_text(
text: str,
*,
token_counter: Callable[[str], int] | None = None,
base_metadata: dict[str, Any] | None = None,
) -> list[DotDict]
Chunks raw text content using the constraints configured at initialization.
Parameters:
-
(textstr) –The raw text to chunk.
-
(token_counterCallable[[str], int] | None, default:None) –Optional token counting function.
-
(base_metadatadict[str, Any] | None, default:None) –Optional dictionary to be included with each chunk.
Returns:
-
list[DotDict]–A list of
DotDictobjects, each representing a chunk.
Source code in src/chunklet/document_chunker/document_chunker.py
chunk_texts
chunk_texts(
texts: IterableOfStr,
*,
token_counter: Callable[[str], int] | None = None,
base_metadata: dict[str, Any] | None = None,
separator: Any = None,
n_jobs: Annotated[int, Field(ge=1)] | None = None,
show_progress: bool = False,
on_errors: Literal["raise", "skip", "break"] = "raise",
) -> Generator[DotDict, None, None]
Chunks multiple text contents using the constraints configured at initialization.
Parameters:
-
(textsIterableOfStr) –A non-string iterable of texts to chunk.
-
(token_counterCallable[[str], int] | None, default:None) –Optional token counting function.
-
(base_metadatadict[str, Any] | None, default:None) –Optional dictionary to be included with each chunk.
-
(separatorAny, default:None) –A value to be yielded after the chunks of each text are processed.
-
(n_jobsAnnotated[int, Field(ge=1)] | None, default:None) –Number of parallel workers.
-
(show_progressbool, default:False) –Display progress bar during processing. Defaults to False.
-
(on_errorsLiteral['raise', 'skip', 'break'], default:'raise') –How to handle errors.
Yields:
-
DotDict–DotDictobject, representing a chunk with its content and metadata.
Raises:
-
InvalidInputError–If the input arguments aren't valid.
-
UnsupportedFileTypeError–If the file extension is not supported or is missing.
-
MissingTokenCounterError–If
max_tokensis provided but notoken_counteris provided. -
CallbackError–If a callback function (e.g., custom processors callbacks) fails during execution.
Source code in src/chunklet/document_chunker/document_chunker.py
extract_text_and_metadata
extract_text_and_metadata(
path: str | Path, ext: str
) -> tuple[
str | Generator[str, None, None], dict[str, Any]
]
Extracts text content and metadata from a document.
Parameters:
-
(pathstr | Path) –The path to the document file.
-
(extstr) –The file extension.
Returns:
-
str | Generator[str, None, None]–A tuple containing
-
dict[str, Any]–either a string (for simple text files) or a generator of strings (for processed documents)
-
tuple[str | Generator[str, None, None], dict[str, Any]]–and a dictionary of metadata.