chunklet.document_chunker.document_chunker
Classes:
-
DocumentChunker–A comprehensive document chunker that handles various file formats.
DocumentChunker
DocumentChunker(
sentence_splitter: Any | None = None,
verbose: bool = False,
continuation_marker: str = "...",
token_counter: Callable[[str], int] | None = None,
)
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:
-
(sentence_splitterBaseSplitter | None, default:None) –An optional BaseSplitter instance. If None, a default SentenceSplitter will be initialized.
-
(verbosebool, default:False) –Enable verbose logging.
-
(continuation_markerstr, default:'...') –The marker to prepend to unfitted clauses. Defaults to '...'.
-
(token_counterCallable[[str], int] | None, default:None) –Function that counts tokens in text. If None, must be provided when calling chunk() methods.
Raises:
-
InvalidInputError–If any of the input arguments are invalid or if the provided
sentence_splitteris not an instance ofBaseSplitter.
Methods:
-
batch_chunk–Batch chunk multiple document files.
-
chunk–Chunk a document file into semantic pieces.
-
chunk_file–Chunks a single document from a given path.
-
chunk_files–Chunks multiple documents from a list of file paths.
-
chunk_text–Chunks raw text content.
-
chunk_texts–Chunks multiple text contents.
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.
batch_chunk
batch_chunk(
paths: restricted_iterable(str | Path),
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
token_counter: Callable[[str], int] | None = None,
separator: Any = None,
n_jobs: Annotated[int, Field(ge=1)] | None = None,
show_progress: bool = True,
on_errors: Literal["raise", "skip", "break"] = "raise"
) -> Generator[Box, None, None]
Batch chunk multiple document files.
Note
Deprecated since v2.2.0. Will be removed in v3.0.0. Use chunk_files instead.
Source code in src/chunklet/document_chunker/document_chunker.py
chunk
chunk(
path: str | Path,
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
token_counter: Callable[[str], int] | None = None
) -> list[Box]
Chunk a document file into semantic pieces.
Note
Deprecated since v2.2.0. Will be removed in v3.0.0. Use chunk_file instead.
Source code in src/chunklet/document_chunker/document_chunker.py
chunk_file
chunk_file(
path: str | Path,
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
token_counter: Callable[[str], int] | None = None
) -> list[Box]
Chunks a single document from a given path.
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.
-
(langstr, default:'auto') –The language of the text (e.g., 'en', 'fr', 'auto'). Defaults to "auto".
-
(max_tokensint, default:None) –Maximum number of tokens per chunk. Must be >= 12.
-
(max_sentencesint, default:None) –Maximum number of sentences per chunk. Must be >= 1.
-
(max_section_breaksint, default:None) –Maximum number of section breaks per chunk. Section breaks include Markdown headings (# to ######), horizontal rules (---, ***, ___), and
tags. Must be >= 1. -
(overlap_percentint | float, default:20) –Percentage of overlap between chunks (0-85).
-
(offsetint, default:0) –Starting sentence offset for chunking. Defaults to 0.
-
(token_countercallable | None, default:None) –Optional token counting function. Required if
max_tokensis provided.
Returns:
-
list[Box]–list[Box]: A list of
Boxobjects, each representing -
list[Box]–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
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 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 | |
chunk_files
chunk_files(
paths: restricted_iterable(str | Path),
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
token_counter: Callable[[str], int] | None = None,
separator: Any = None,
n_jobs: Annotated[int, Field(ge=1)] | None = None,
show_progress: bool = True,
on_errors: Literal["raise", "skip", "break"] = "raise"
) -> Generator[Box, None, None]
Chunks multiple documents from a list of file paths.
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:
-
(pathsrestricted_iterable[str | Path]) –A restricted iterable of paths to the document files.
-
(langstr, default:'auto') –The language of the text (e.g., 'en', 'fr', 'auto'). Defaults to "auto".
-
(max_tokensint, default:None) –Maximum number of tokens per chunk. Must be >= 12.
-
(max_sentencesint, default:None) –Maximum number of sentences per chunk. Must be >= 1.
-
(max_section_breaksint, default:None) –Maximum number of section breaks per chunk. Section breaks include Markdown headings (# to ######), horizontal rules (---, ***, ___), and
tags. Must be >= 1. -
(overlap_percentint | float, default:20) –Percentage of overlap between chunks (0-85).
-
(offsetint, default:0) –Starting sentence offset for chunking. Defaults to 0.
-
(token_countercallable | None, default:None) –Optional token counting function. Required if
max_tokensis provided. -
(separatorAny, default:None) –A value to be yielded after the chunks of each text are processed. Note: None cannot be used as a separator.
-
(n_jobsint | None, default:None) –Number of parallel workers to use. If None, uses all available CPUs. Must be >= 1 if specified.
-
(show_progressbool, default:True) –Flag to show or disable the loading bar.
-
(on_errorsLiteral['raise', 'skip', 'break'], default:'raise') –How to handle errors during processing. Can be 'raise', 'ignore', or 'break'.
Yields:
-
Box(Box) –Boxobject, 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
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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 | |
chunk_text
chunk_text(
text: str,
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
token_counter: Callable[[str], int] | None = None,
base_metadata: dict[str, Any] | None = None
) -> list[Box]
Chunks raw text content.
Parameters:
-
(textstr) –The raw text to chunk.
-
(langstr, default:'auto') –The language of the text (e.g., 'en', 'fr', 'auto'). Defaults to "auto".
-
(max_tokensint, default:None) –Maximum number of tokens per chunk. Must be >= 12.
-
(max_sentencesint, default:None) –Maximum number of sentences per chunk. Must be >= 1.
-
(max_section_breaksint, default:None) –Maximum number of section breaks per chunk. Section breaks include Markdown headings (# to ######), horizontal rules (---, ***, ___), and
tags. Must be >= 1. -
(overlap_percentint | float, default:20) –Percentage of overlap between chunks (0-85).
-
(offsetint, default:0) –Starting sentence offset for chunking. Defaults to 0.
-
(token_countercallable | None, default:None) –Optional token counting function. Required if
max_tokensis provided. -
(base_metadatadict[str, Any], default:None) –Optional dictionary to be included with each chunk.
Returns:
-
list[Box]–list[Box]: A list of
Boxobjects, each representing a chunk.
Source code in src/chunklet/document_chunker/document_chunker.py
chunk_texts
chunk_texts(
texts: restricted_iterable(str),
*,
lang: str = "auto",
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,
offset: Annotated[int, Field(ge=0)] = 0,
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 = True,
on_errors: Literal["raise", "skip", "break"] = "raise"
) -> Generator[Box, None, None]
Chunks multiple text contents.
Parameters:
-
(textsrestricted_iterable(str)) –A restricted iterable of texts to chunk.
-
(langstr, default:'auto') –The language of the text (e.g., 'en', 'fr', 'auto'). Defaults to "auto".
-
(max_tokensint, default:None) –Maximum number of tokens per chunk. Must be >= 12.
-
(max_sentencesint, default:None) –Maximum number of sentences per chunk. Must be >= 1.
-
(max_section_breaksint, default:None) –Maximum number of section breaks per chunk. Section breaks include Markdown headings (# to ######), horizontal rules (---, ***, ___), and
tags. Must be >= 1. -
(overlap_percentint | float, default:20) –Percentage of overlap between chunks (0-85).
-
(offsetint, default:0) –Starting sentence offset for chunking. Defaults to 0.
-
(token_countercallable | None, default:None) –Optional token counting function. Required if
max_tokensis provided. -
(base_metadatadict[str, Any], 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_jobsint | None, default:None) –Number of parallel workers.
-
(show_progressbool, default:True) –Show progress bar.
-
(on_errorsstr, default:'raise') –How to handle errors.
Yields:
-
Box(Box) –Boxobject, 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.