Splitter¶
Introduction¶
The Splitter component implements the main functionality of this library. This component is designed to deliver classes (inherited from BaseSplitter) which supports to split a markdown text or a string following many different strategies.
Splitter strategies description¶
| Splitting Technique | Description |
|---|---|
| Character Splitter | Splits text into chunks based on a specified number of characters. Supports overlapping by character count or percentage. Parameters: chunk_size (max chars per chunk), chunk_overlap (overlapping chars: int or %). Compatible with: Text. |
| Word Splitter | Splits text into chunks based on a specified number of words. Supports overlapping by word count or percentage. Parameters: chunk_size (max words per chunk), chunk_overlap (overlapping words: int or %). Compatible with: Text. |
| Sentence Splitter | Splits text into chunks by a specified number of sentences. Allows overlap defined by a number or percentage of words from the end of the previous chunk. Customizable sentence separators (e.g., ., !, ?). Parameters: chunk_size (max sentences per chunk), chunk_overlap (overlapping words: int or %), sentence_separators (list of characters). Compatible with: Text. |
| Paragraph Splitter | Splits text into chunks based on a specified number of paragraphs. Allows overlapping by word count or percentage, and customizable line breaks. Parameters: chunk_size (max paragraphs per chunk), chunk_overlap (overlapping words: int or %), line_break (delimiter(s) for paragraphs). Compatible with: Text. |
| Recursive Splitter | Recursively splits text based on a hierarchy of separators (e.g., paragraph, sentence, word, character) until chunks reach a target size. Tries to preserve semantic units as long as possible. Parameters: chunk_size (max chars per chunk), chunk_overlap (overlapping chars), separators (list of characters to split on, e.g., ["\n\n", "\n", " ", ""]). Compatible with: Text. |
| Keyword Splitter | Splits text into chunks around matches of specified keywords, using one or more regex patterns. Supports precise boundary control—matched keywords can be included before, after, both sides, or omitted from the split. Each keyword can have a custom name (via dict) for metadata counting. Secondary soft-wrapping by chunk_size is supported. Parameters: patterns (list of regex patterns, or dict mapping names to patterns), include_delimiters ("before", "after", "both", or "none"), flags (regex flags, e.g. re.MULTILINE), chunk_size (max chars per chunk, soft-wrapped). Compatible with: Text. |
| Token Splitter | Splits text into chunks based on the number of tokens, using various tokenization models (e.g., tiktoken, spaCy, NLTK). Useful for ensuring chunks are compatible with LLM context limits. Parameters: chunk_size (max tokens per chunk), model_name (tokenizer/model, e.g., "tiktoken/cl100k_base", "spacy/en_core_web_sm", "nltk/punkt"), language (for NLTK). Compatible with: Text. |
| Paged Splitter | Splits text by pages for documents that have page structure. Each chunk contains a specified number of pages, with optional word overlap. Parameters: num_pages (pages per chunk), chunk_overlap (overlapping words). Compatible with: Word, PDF, Excel, PowerPoint. |
| Row/Column Splitter | For tabular formats, splits data by a set number of rows or columns per chunk, with possible overlap. Row-based and column-based splitting are mutually exclusive. Parameters: num_rows, num_cols (rows/columns per chunk), overlap (overlapping rows or columns). Compatible with: Tabular formats (csv, tsv, parquet, flat json). |
| JSON Splitter | Recursively splits JSON documents into smaller sub-structures that preserve the original JSON schema. Parameters: max_chunk_size (max chars per chunk), min_chunk_size (min chars per chunk). Compatible with: JSON. |
| Semantic Splitter | Splits text into chunks based on semantic similarity, using an embedding model and a max tokens parameter. Useful for meaningful semantic groupings. Parameters: embedding_model (model for embeddings), max_tokens (max tokens per chunk). Compatible with: Text. |
| HTML Tag Splitter | Splits HTML content based on a specified tag, or automatically detects the most frequent and shallowest tag if not specified. Each chunk is a complete HTML fragment for that tag. Parameters: chunk_size (max chars per chunk), tag (HTML tag to split on, optional). Compatible with: HTML. |
| Header Splitter | Splits Markdown or HTML documents into chunks using header levels (e.g., #, ##, or <h1>, <h2>). Uses configurable headers for chunking. Parameters: headers_to_split_on (list of headers and semantic names), chunk_size (unused, for compatibility). Compatible with: Markdown, HTML. |
| Code Splitter | Splits source code files into programmatically meaningful chunks (functions, classes, methods, etc.), aware of the syntax of the specified programming language (e.g., Python, Java, Kotlin). Uses language-aware logic to avoid splitting inside code blocks. Parameters: chunk_size (max chars per chunk), language (programming language as string, e.g., "python", "java"). Compatible with: Source code files (Python, Java, Kotlin, C++, JavaScript, Go, etc.). |
Output format¶
Bases: BaseModel
Pydantic model defining the output structure for all splitters.
Attributes:
| Name | Type | Description |
|---|---|---|
chunks |
List[str]
|
List of text chunks produced by splitting. |
chunk_id |
List[str]
|
List of unique IDs corresponding to each chunk. |
document_name |
Optional[str]
|
The name of the document. |
document_path |
str
|
The path to the document. |
document_id |
Optional[str]
|
A unique identifier for the document. |
conversion_method |
Optional[str]
|
The method used for document conversion. |
reader_method |
Optional[str]
|
The method used for reading the document. |
ocr_method |
Optional[str]
|
The OCR method used, if any. |
split_method |
str
|
The method used to split the document. |
split_params |
Optional[Dict[str, Any]]
|
Parameters used during the splitting process. |
metadata |
Optional[Dict[str, Any]]
|
Additional metadata associated with the splitting. |
Source code in src/splitter_mr/schema/models.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
append_metadata(metadata)
¶
Append (update) the metadata dictionary with new key-value pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
Dict[str, Any]
|
The metadata to add or update. |
required |
Source code in src/splitter_mr/schema/models.py
185 186 187 188 189 190 191 192 193 194 | |
from_chunks(chunks)
classmethod
¶
Create a SplitterOutput from a list of chunks, with all other fields set to their defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
List[str]
|
A list of text chunks. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
An instance of SplitterOutput with the given chunks. |
Source code in src/splitter_mr/schema/models.py
172 173 174 175 176 177 178 179 180 181 182 183 | |
validate_and_set_defaults()
¶
Validates and sets defaults for the SplitterOutput instance.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Returns:
| Name | Type | Description |
|---|---|---|
self |
SplitterOutput
|
The validated and updated instance. |
Source code in src/splitter_mr/schema/models.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
Splitters¶
BaseSplitter¶
BaseSplitter
¶
Bases: ABC
Abstract base class for all splitter implementations.
This class defines the common interface and utility methods for splitters that
divide text or data into smaller chunks, typically for downstream natural language
processing tasks or information retrieval. Subclasses should implement the split
method, which takes a :class:ReaderOutput and returns a :class:SplitterOutput
containing the resulting chunks and associated metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
chunk_size |
int
|
The maximum number of units (characters, sentences, rows, etc.) that a derived splitter is allowed to place in a chunk (semantic meaning depends on the subclass). |
Methods:
| Name | Description |
|---|---|
split |
Abstract method. Must be implemented by subclasses to perform the actual domain-specific splitting logic. |
_generate_chunk_ids |
Utility to generate a list of unique UUID4-based identifiers for chunk tracking. |
_default_metadata |
Returns a default (empty) metadata dictionary. Subclasses may
override or extend this to attach extra information to the final
:class: |
Example
Creating a simple custom splitter that breaks text every N characters:
from splitter_mr.schema import ReaderOutput, SplitterOutput
from splitter_mr.splitter.base_splitter import BaseSplitter
class FixedCharSplitter(BaseSplitter):
def split(self, reader_output: ReaderOutput) -> SplitterOutput:
text = reader_output.text or ""
chunks = [
text[i : i + self.chunk_size]
for i in range(0, len(text), self.chunk_size)
]
chunk_ids = self._generate_chunk_ids(len(chunks))
return SplitterOutput(
chunks=chunks,
chunk_id=chunk_ids,
document_name=reader_output.document_name,
document_path=reader_output.document_path,
document_id=reader_output.document_id,
conversion_method=reader_output.conversion_method,
reader_method=reader_output.reader_method,
ocr_method=reader_output.ocr_method,
split_method="fixed_char_splitter",
split_params={"chunk_size": self.chunk_size},
metadata=self._default_metadata(),
)
ro = ReaderOutput(text="abcdefghijklmnopqrstuvwxyz")
splitter = FixedCharSplitter(chunk_size=5)
out = splitter.split(ro)
print(out.chunks)
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']
Source code in src/splitter_mr/splitter/base_splitter.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
__init__(chunk_size=1000)
¶
Initializer method for BaseSplitter classes
Source code in src/splitter_mr/splitter/base_splitter.py
80 81 82 83 84 | |
split(reader_output)
abstractmethod
¶
Abstract method to split input data into chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Input data, typically from a document reader, including the text to split and any relevant metadata. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
A dictionary containing split chunks and associated metadata. |
Source code in src/splitter_mr/splitter/base_splitter.py
86 87 88 89 90 91 92 93 94 95 96 97 | |
CharacterSplitter¶
CharacterSplitter
¶
Bases: BaseSplitter
Splits textual input into fixed-size character chunks with optional overlap.
The CharacterSplitter is a simple and robust splitter that divides text into
overlapping or non-overlapping chunks, based on the specified number of characters
per chunk. It is commonly used in document-processing or NLP pipelines where
preserving context between chunks is important.
The splitter can be configured to use
chunk_size: maximum number of characters per chunk.chunk_overlap: the number (or fraction) of overlapping characters between consecutive chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of characters per chunk. Must be >= 1. |
1000
|
chunk_overlap
|
Union[int, float]
|
Number or percentage of overlapping characters between chunks. If float, must be in [0.0, 1.0). |
0
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If either |
Source code in src/splitter_mr/splitter/splitters/character_splitter.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
split(reader_output)
¶
Split the provided text into character-based chunks with optional overlap.
The method iterates through the text and produces fixed-size chunks that can optionally overlap. Each chunk is accompanied by automatically generated unique identifiers and metadata inherited from the original document.
Input validity is checked and warnings may be emitted for empty or invalid text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
A validated input object containing at least
a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Structured splitter output including:
- |
Raises:
| Type | Description |
|---|---|
ValueError
|
If initialization parameters are invalid. |
InvalidChunkException
|
If chunks cannot be properly created (e.g., all empty). |
SplitterOutputException
|
If the final SplitterOutput cannot be validated or built. |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
If text is empty or cannot be parsed as JSON. |
Example
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter import CharacterSplitter
reader_output = ReaderOutput(
text="Hello world! This is a test text for splitting.",
document_name="example.txt",
document_path="/path/example.txt"
)
splitter = CharacterSplitter(chunk_size=10, chunk_overlap=0.2)
output = splitter.split(reader_output)
print(output.chunks)
['Hello worl', 'world! Thi', 'is is a te', ...]
Source code in src/splitter_mr/splitter/splitters/character_splitter.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
WordSplitter¶
WordSplitter
¶
Bases: BaseSplitter
Split text into overlapping or non-overlapping word-based chunks.
This splitter is configurable with a maximum chunk size (chunk_size in
words) and an overlap between consecutive chunks (chunk_overlap). The
overlap can be specified either as an integer (number of words) or as a
float between 0 and 1 (fraction of chunk size). It is useful for NLP tasks
where word-based boundaries are important for context preservation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of words per chunk. Must be a positive integer. |
5
|
chunk_overlap
|
Union[int, float]
|
Number or percentage of overlapping words between
chunks. If a float is provided, it must satisfy
|
0
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Source code in src/splitter_mr/splitter/splitters/word_splitter.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
split(reader_output)
¶
Split the input text into word-based chunks.
The splitter uses simple whitespace tokenization and supports either integer or fractional overlap between consecutive chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Input text and associated metadata. |
required |
Returns:
| Type | Description |
|---|---|
SplitterOutput
|
A |
SplitterOutput
|
|
SplitterOutput
|
|
SplitterOutput
|
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If the configuration is invalid (for example, overlap is too large). |
InvalidChunkException
|
If the internal chunk ID generation does not match the number of produced chunks. |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
If the input text is empty or whitespace-only. |
ChunkUnderflowWarning
|
If no chunks are produced (for example, due to empty input or aggressive filtering). |
Example
from splitter_mr.splitter import WordSplitter
reader_output = ReaderOutput(
text: "My Wonderful Family\nI live in a house near the mountains.I have two brothers and one sister, and I was born last...",
document_name: "my_wonderful_family.txt",
document_path: "https://raw.githubusercontent.com/andreshere00/Splitter_MR/refs/heads/main/data/my_wonderful_family.txt",
)
# Split into chunks of 5 words, overlapping by 2 words
splitter = WordSplitter(chunk_size=5, chunk_overlap=2)
output = splitter.split(reader_output)
print(output["chunks"])
['My Wonderful Family\nI live','I live in a house near','house near the mountains.I', ...]
Source code in src/splitter_mr/splitter/splitters/word_splitter.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
SentenceSplitter¶
SentenceSplitter
¶
Bases: BaseSplitter
SentenceSplitter splits a given text into overlapping or non-overlapping chunks, where each chunk contains a specified number of sentences, and overlap is defined by a number or percentage of words from the end of the previous chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of sentences per chunk. |
5
|
chunk_overlap
|
Union[int, float]
|
Number or percentage of overlapping words between chunks. If a float in [0, 1), it is treated as a fraction of the maximum sentence length (in words); otherwise it is interpreted as an absolute number of words. |
0
|
separators
|
Union[str, List[str]]
|
Sentence boundary separators. If a list, it is normalised into a regex pattern (legacy path). If a string, it is treated as a full regex pattern. |
DEFAULT_SENTENCE_SEPARATORS
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Source code in src/splitter_mr/splitter/splitters/sentence_splitter.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
split(reader_output)
¶
Splits the input text from reader_output into sentence-based chunks,
allowing for overlap at the word level.
Pipeline:
- Validate and normalise
reader_output.text. - Split into sentences.
- Compute word overlap.
- Build chunks (with overlap).
- Build the final :class:
SplitterOutput.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Dataclass containing at least a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Dataclass defining the output structure for all splitters. |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
InvalidChunkException
|
If the number of generated chunk IDs does not match the number of chunks. |
SplitterOutputException
|
If constructing :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
When the input text is empty or whitespace-only. |
SplitterOutputWarning
|
When no non-empty sentences are found, causing the splitter to fall back to a single empty chunk. |
ChunkUnderflowWarning
|
When fewer chunks than |
Example
from splitter_mr.splitter import SentenceSplitter
reader_output = ReaderOutput(
text: "My Wonderful Family\nI live in a house near the mountains.I have two brothers and one sister, and I was born last...",
document_name: "my_wonderful_family.txt",
document_path: "https://raw.githubusercontent.com/andreshere00/Splitter_MR/refs/heads/main/data/my_wonderful_family.txt",
)
# Split into chunks of 2 sentences, no overlapping
splitter = SentenceSplitter(chunk_size=2, chunk_overlap=0)
output = splitter.split(reader_output)
print(output["chunks"])
['My Wonderful Family. I live in a house near the mountains.', 'I have two brothers and one sister, and I was born last...', ...]
Source code in src/splitter_mr/splitter/splitters/sentence_splitter.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
ParagraphSplitter¶
ParagraphSplitter
¶
Bases: BaseSplitter
ParagraphSplitter splits a given text into overlapping or non-overlapping chunks, where each chunk contains a specified number of paragraphs, and overlap is defined by a number or percentage of words from the end of the previous chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of paragraphs per chunk. |
3
|
chunk_overlap
|
Union[int, float]
|
Number or percentage of overlapping words between chunks. If a float in [0, 1), it is treated as a fraction of the maximum paragraph length (in words); otherwise it is interpreted as an absolute number of words. |
0
|
line_break
|
Union[str, List[str]]
|
Character(s) used to split text into paragraphs. A single string or a list of strings. |
DEFAULT_PARAGRAPH_SEPARATORS
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Source code in src/splitter_mr/splitter/splitters/paragraph_splitter.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
split(reader_output)
¶
Split the text in reader_output.text into paragraph-based chunks.
Pipeline:
- Validate and normalise
reader_output.text. - Split into paragraphs.
- Compute word overlap.
- Build chunks (with overlap).
- Build the final :class:
SplitterOutput.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Dataclass containing at least a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Dataclass defining the output structure for all splitters. |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
InvalidChunkException
|
If the number of generated chunk IDs does not match the number of chunks. |
SplitterOutputException
|
If constructing :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
When the input text is empty or whitespace-only. |
SplitterOutputWarning
|
When no non-empty paragraphs are found, causing the splitter to fall back to a single empty chunk. |
Example
Basic usage with default line breaks and no overlap:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters import ParagraphSplitter
text = (
"First paragraph.\n\n"
"Second paragraph with more text.\n\n"
"Third paragraph."
)
ro = ReaderOutput(
text=text,
document_name="example.txt",
document_path="/tmp/example.txt",
document_id="doc-1",
conversion_method="text",
reader_method="plain",
ocr_method=None,
metadata={},
)
splitter = ParagraphSplitter(chunk_size=2, chunk_overlap=0)
output = splitter.split(ro)
print(output.chunks)
['First paragraph.\n\nSecond paragraph with more text.', 'Third paragraph.']
Example with custom line breaks and word overlap between chunks:
text = (
"Intro paragraph.@@"
"Details paragraph one.@@"
"Details paragraph two.@@"
"Conclusion paragraph."
)
ro = ReaderOutput(text=text, document_name="custom_sep.txt")
splitter = ParagraphSplitter(
chunk_size=2,
chunk_overlap=3, # reuse last 3 words from previous chunk
line_break="@@", # custom paragraph separator
)
output = splitter.split(ro)
for chunk in output.chunks:
print("--- CHUNK ---")
print(chunk)
Source code in src/splitter_mr/splitter/splitters/paragraph_splitter.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
RecursiveCharacterSplitter¶
RecursiveCharacterSplitter
¶
Bases: BaseSplitter
RecursiveCharacterSplitter splits a given text into overlapping or non-overlapping chunks,
where each chunk is created by repeatedly breaking down the text until it reaches the
desired chunk size. This splitter is backed by LangChain's
:class:RecursiveCharacterTextSplitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
the number of characters per chunks (approximately). |
1000
|
chunk_overlap
|
int | float
|
the number of characters which matches between contiguous chunks, or a fraction of chunk_size when 0 <= value < 1. |
0.1
|
separators
|
str | List[str]
|
the list of characters or regex patterns which defines how text is split. |
DEFAULT_RECURSIVE_SEPARATORS
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Source code in src/splitter_mr/splitter/splitters/recursive_splitter.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
split(reader_output)
¶
Splits the input text into character-based chunks using a recursive splitting strategy
(via LangChain's :class:RecursiveCharacterTextSplitter), supporting configurable
separators, chunk size, and overlap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Dataclass containing at least a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Dataclass defining the output structure for all splitters. |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
SplitterConfigException
|
If (effective) |
InvalidChunkException
|
If the number of generated chunk IDs does not match the number of chunks. |
SplitterOutputException
|
If constructing :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
When the input text is empty or whitespace-only. |
SplitterOutputWarning
|
When no chunks are produced and the splitter falls back to a single empty chunk. |
Example
Basic usage with a simple text string:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter import RecursiveCharacterSplitter
# Sample text (short for demonstration)
text = (
"LangChain makes it easy to build LLM-powered applications. "
"Recursive splitting helps maintain semantic coherence while "
"still enforcing chunk-size limits."
)
reader_output = ReaderOutput(
text=text,
document_name="example.txt",
document_path="/tmp/example.txt",
document_id="abc123",
conversion_method="text",
metadata={}
)
splitter = RecursiveCharacterSplitter(
chunk_size=50,
chunk_overlap=0.2, # 20% of chunk_size overlap
separators=["\n\n", ".", " "] # recursive fallback separators
)
output = splitter.split(reader_output)
# Inspect results
print(output.chunks)
print(output.chunk_id)
print(output.split_params)
Source code in src/splitter_mr/splitter/splitters/recursive_splitter.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
KeywordSplitter¶
KeywordSplitter
¶
Bases: BaseSplitter
Splitter that chunks text around keyword boundaries using regular expressions.
This splitter searches the input text for one or more keyword patterns (regex)
and creates chunks at each match boundary. You can control how the matched
delimiter is attached to the resulting chunks (before/after/both/none) and apply a
secondary, size-based re-chunking to respect chunk_size.
Notes
- All regexes are compiled into one alternation with named groups when
patternsis a dict. This simplifies per-keyword accounting. - If the input text is empty or no matches are found, the entire text becomes a single chunk (subject to size-based re-chunking).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns
|
Union[List[str], Dict[str, str]]
|
A list of regex pattern strings or a mapping of
|
required |
flags
|
int
|
Standard |
0
|
include_delimiters
|
str
|
Where to attach the matched keyword delimiter.
One of |
DEFAULT_KEYWORD_DELIMITER_POS
|
chunk_size
|
int
|
Target maximum size (in characters) for each chunk. When a produced chunk exceeds this value, it is soft-wrapped by whitespace using a greedy strategy. |
100000
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
ReaderOutputException
|
If |
InvalidChunkException
|
If internal chunk accounting becomes inconsistent. |
SplitterOutputException
|
If building :class: |
Source code in src/splitter_mr/splitter/splitters/keyword_splitter.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
split(reader_output)
¶
Split ReaderOutput into keyword-delimited chunks and build structured output.
The method first splits around regex keyword matches (respecting
include_delimiters), then performs a secondary size-based soft wrap to
respect chunk_size. It returns a fully populated :class:SplitterOutput.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Input document and metadata. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Output structure with chunked text and metadata. |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
InvalidChunkException
|
If the number of chunks and chunk IDs diverge. |
SplitterOutputException
|
If constructing the output object fails. |
Example
Basic usage with a list of patterns:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters import KeywordSplitter
text = "Alpha KEY Beta KEY Gamma"
ro = ReaderOutput(
text=text,
document_name="demo.txt",
document_path="/tmp/demo.txt",
)
splitter = KeywordSplitter(patterns=[r"KEY"])
out = splitter.split(ro)
print(out.chunks)
['Alpha KEY', 'Beta KEY', 'Gamma']
Using a dict of named patterns (names appear in metadata):
patterns = {
"plus": r"\+",
"minus": r"-",
}
text = "A + B - C + D"
ro = ReaderOutput(text=text)
splitter = KeywordSplitter(patterns=patterns)
out = splitter.split(ro)
print(out.chunks)
['A +', 'B -', 'C +', 'D']
print(out.metadata["keyword_matches"]["counts"])
{'plus': 2, 'minus': 1}
Demonstrating include_delimiters modes:
text = "A#B#C"
splitter = KeywordSplitter(patterns=[r"#"], include_delimiters="after")
out = splitter.split(ReaderOutput(text=text))
print(out.chunks)
['A#', 'B#', 'C']
splitter = KeywordSplitter(patterns=[r"#"], include_delimiters="none")
out = splitter.split(ReaderOutput(text=text))
print(out.chunks)
['A', 'B', 'C']
Example showing size-based soft wrapping (chunk_size=5):
text = "abcdefghijklmnopqrstuvwxyz"
splitter = KeywordSplitter(patterns=[r"x"], chunk_size=5)
out = splitter.split(ReaderOutput(text=text))
print(out.chunks)
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']
Example with multiple patterns and mixed text:
splitter = KeywordSplitter(
patterns=[r"ERROR", r"WARNING"],
include_delimiters="after",
)
log = "INFO Start\nERROR Failure occurred\nWARNING Low RAM\nINFO End"
out = splitter.split(ReaderOutput(text=log))
print(out.chunks)
['INFO Start\nERROR', 'Failure occurred\nWARNING', 'Low RAM\nINFO End']
Source code in src/splitter_mr/splitter/splitters/keyword_splitter.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
HeaderSplitter¶
HeaderSplitter
¶
Bases: BaseSplitter
Split HTML or Markdown documents into chunks by header levels (H1–H6).
- If the input looks like HTML, it is first converted to Markdown using the
project's HtmlToMarkdown utility, which emits ATX-style headings (
#,##, ...). - If the input is Markdown, Setext-style headings (underlines with
===/---) are normalized to ATX so headers are reliably detected. - Splitting is performed with LangChain's MarkdownHeaderTextSplitter.
- If no headers are detected after conversion/normalization, a safe fallback splitter (RecursiveCharacterTextSplitter) is used to avoid returning a single, excessively large chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Size hint for fallback splitting; not used by header splitting itself. |
1000
|
headers_to_split_on
|
Optional[Sequence[ALLOWED_HEADERS_LITERAL]]
|
Semantic header names like |
None
|
group_header_with_content
|
bool
|
If |
True
|
Raises:
| Type | Description |
|---|---|
InvalidHeaderNameError
|
If any header is not present in |
Source code in src/splitter_mr/splitter/splitters/header_splitter.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
split(reader_output)
¶
Perform header-based splitting with HTML→Markdown conversion and safe fallback.
Steps
- Detect filetype (HTML/MD).
- If HTML, convert to Markdown with HtmlToMarkdown (emits ATX headings).
- If Markdown, normalize Setext headings to ATX.
- Split by headers via MarkdownHeaderTextSplitter.
- If no headers found, fallback to RecursiveCharacterTextSplitter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
The reader output containing text and metadata. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
A populated splitter output with chunk contents and metadata. |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
if text field in ReaderOutput is missing or void. |
Raises:
| Type | Description |
|---|---|
HtmlConversionError
|
if HTML Conversion fails. |
Example
Basic Markdown input with default headers (H1–H6), keeping headers with content:
from splitter_mr.splitter import HeaderSplitter
from splitter_mr.schema.models import ReaderOutput
md = (
"# Title\n"
"Intro paragraph.\n\n"
"## Section A\n"
"Content A.\n\n"
"## Section B\n"
"Content B."
)
ro = ReaderOutput(text=md, document_name="example.md")
splitter = HeaderSplitter(group_header_with_content=True) # keep headers in chunks
out = splitter.split(ro)
print(out.chunks)
[
"# Title\nIntro paragraph.",
"## Section A\nContent A.",
"## Section B\nContent B."
]
HTML input with a restricted set of headers and stripping headers from chunks:
html = (
"<h1>Title</h1>"
"<p>Intro paragraph.</p>"
"<h2>Section A</h2>"
"<p>Content A.</p>"
"<h3>Sub A.1</h3>"
"<p>Detail A.1</p>"
)
ro = ReaderOutput(text=html, document_name="example.html")
# Only split on Header 1 and Header 2 (i.e., H1/H2)
splitter = HeaderSplitter(
headers_to_split_on=("Header 1", "Header 2"),
group_header_with_content=False # drop headers from chunks
)
out = splitter.split(ro)
print(out.chunks)
[
"Intro paragraph.",
"Content A.\nSub A.1\nDetail A.1"
]
Source code in src/splitter_mr/splitter/splitters/header_splitter.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
RecursiveJSONSplitter¶
RecursiveJSONSplitter
¶
Bases: BaseSplitter
Split a JSON string or structure into overlapping or non-overlapping chunks, using the Langchain RecursiveJsonSplitter. This splitter is designed to recursively break down JSON data (including nested objects and arrays) into manageable pieces based on keys, arrays, or other separators, until the desired chunk size is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum chunk size, measured in the number of characters per chunk. |
1000
|
min_chunk_size
|
int
|
Minimum chunk size, in characters. |
200
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
if parameters are not provided with the expected type. |
Notes
Source code in src/splitter_mr/splitter/splitters/json_splitter.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
split(reader_output)
¶
Splits the input JSON text from the reader_output dictionary into recursively chunked pieces, allowing for overlap by number or percentage of characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
Dict[str, Any]
|
Dictionary containing at least a 'text' key (str) and optional document metadata (e.g., 'document_name', 'document_path', etc.). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Dataclass defining the output structure for all splitters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the 'text' field is missing from reader_output. |
JSONDecodeError
|
If the 'text' field contains invalid JSON. |
Example
from splitter_mr.splitter import RecursiveJSONSplitter
# This dictionary has been obtained from `VanillaReader`
reader_output = ReaderOutput(
text: '{"company": {"name": "TechCorp", "employees": [{"name": "Alice"}, {"name": "Bob"}]}}'
document_name: "company_data.json",
document_path: "https://raw.githubusercontent.com/andreshere00/Splitter_MR/refs/heads/main/data/company_data.json",
document_id: "doc123",
conversion_method: "vanilla",
ocr_method: None
)
splitter = RecursiveJSONSplitter(chunk_size=100, min_chunk_size=20)
output = splitter.split(reader_output)
print(output["chunks"])
['{"company": {"name": "TechCorp"}}', '{"employees": [{"name": "Alice"}, {"name": "Bob"}]}']
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
if input does not contain a valid JSON. |
InvalidChunkException
|
if returned chunks are not in a valid format. |
SplitterOutputException
|
if response has not been generated as expected |
Source code in src/splitter_mr/splitter/splitters/json_splitter.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
HTMLTagSplitter¶
HTMLTagSplitter
¶
Bases: BaseSplitter
Split HTML content by tag, with optional batching and Markdown conversion.
Behavior
- When
tagis provided (e.g.,div), split by all matching elements. - When
tagisNone, auto-detect the most frequent and shallowest tag. - Tables receive special handling to preserve header context when batching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum chunk size in characters for batching. If |
1
|
tag
|
Optional[str]
|
HTML tag to split on (e.g., |
None
|
batch
|
bool
|
If True, group elements up to |
True
|
to_markdown
|
bool
|
If True, convert each emitted chunk from HTML to Markdown. |
True
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Source code in src/splitter_mr/splitter/splitters/html_tag_splitter.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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 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 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 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | |
split(reader_output)
¶
Split HTML using the configured tag and batching, then optionally convert to Markdown.
Semantics
-
Tables
batch=False: one chunk per requested element. If splitting by a row-level tag (e.g.,tr), emit a mini-table per row with<thead>once and that row in<tbody>.batch=Trueandchunk_size in (0, 1, None): all tables grouped into one chunk.batch=Trueandchunk_size > 1: split each table into multiple chunks by batching<tr>rows; copy<thead>into every chunk and skip the header row from<tbody>.
-
Non-table tags
batch=False: one chunk per element.batch=Trueandchunk_size in (0, 1, None): all elements grouped into one chunk. -batch=Trueandchunk_size > 1: batch by total HTML length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Reader output containing at least |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
The split result with chunks and metadata. |
Raises:
| Type | Description |
|---|---|
HtmlConversionError
|
If parsing the HTML or converting chunks to Markdown fails. |
InvalidHtmlTagError
|
If the tag lookup ( |
SplitterOutputException
|
If building the final |
Example
Basic usage splitting all <div> elements:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters import HTMLTagSplitter
html = '''
<div>First block</div>
<div>Second block</div>
<div>Third block</div>
'''
ro = ReaderOutput(
text=html,
document_name="sample.html",
document_path="/tmp/sample.html",
)
splitter = HTMLTagSplitter(chunk_size=10, tag="div", batch=False)
output = splitter.split(ro)
print(output.chunks)
['<div>First block</div>','<div>Second block</div>','<div>Third block</div>']
Example with batching (all <p> elements grouped into one chunk)::
html = "<p>A</p><p>B</p><p>C</p>"
ro = ReaderOutput(text=html, document_name="demo.html")
splitter = HTMLTagSplitter(chunk_size=1, tag="p", batch=True)
out = splitter.split(ro)
print(out.chunks[0])
'<p>A</p>\n<p>B</p>\n<p>C</p>'
Example with table batching (each chunk contains a header and 2 rows):
html = '''
<table>
<thead><tr><th>H1</th><th>H2</th></tr></thead>
<tbody>
<tr><td>A</td><td>1</td></tr>
<tr><td>B</td><td>2</td></tr>
<tr><td>C</td><td>3</td></tr>
</tbody>
</table>
'''
ro = ReaderOutput(text=html, document_name="table.html")
splitter = HTMLTagSplitter(
chunk_size=2, # batch <tr> rows in groups of 2
tag="tr", # split by table rows
batch=True,
)
out = splitter.split(ro)
for i, c in enumerate(out.chunks, 1):
print(f"--- CHUNK {i} ---")
print(c)
Example enabling Markdown conversion:
html = "<h1>Title</h1><p>Paragraph text</p>"
ro = ReaderOutput(text=html)
splitter = HTMLTagSplitter(
chunk_size=5,
tag=None,
batch=False,
to_markdown=True,
)
out = splitter.split(ro)
print(out.chunks)
['# Title', 'Paragraph text']
Notes
If the input text is empty/whitespace-only, a warning is emitted and a single empty chunk is returned.
Source code in src/splitter_mr/splitter/splitters/html_tag_splitter.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
RowColumnSplitter¶
RowColumnSplitter
¶
Bases: BaseSplitter
Split tabular data by rows, columns, or character-based chunk size.
RowColumnSplitter splits tabular data (such as CSV, TSV, Markdown tables, or JSON tables) into smaller tables based on rows, columns, or by total character size while preserving row integrity.
This splitter supports several modes:
- By rows: Split the table into chunks with a fixed number of rows, with optional overlapping rows between chunks.
- By columns: Split the table into chunks by columns, with optional overlapping columns between chunks.
- By chunk size: Split the table into markdown-formatted table chunks, where each chunk contains as many complete rows as fit under the specified character limit, optionally overlapping a fixed number of rows between chunks.
Supported formats for the input text are:
- CSV / TSV / TXT (comma- or tab-separated values).
- Markdown tables.
- JSON in tabular shape (list of dicts or dict of lists).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of characters per chunk when using character-based
splitting. Defaults to |
1000
|
num_rows
|
int
|
Number of rows per chunk when splitting by rows. Mutually
exclusive with |
0
|
num_cols
|
int
|
Number of columns per chunk when splitting by columns. Mutually
exclusive with |
0
|
chunk_overlap
|
int | float
|
Overlap between chunks. Interpretation depends on the mode:
Defaults to |
0
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If configuration is invalid, e.g.:
|
Source code in src/splitter_mr/splitter/splitters/row_column_splitter.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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 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 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 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 | |
split(reader_output)
¶
Split the input tabular data into chunks.
The splitting strategy is determined by the configuration:
- If
num_rows > 0: split by rows. - Else if
num_cols > 0: split by columns. - Else: split by character-based chunk size in markdown format, preserving a header row and never cutting data rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Reader output containing at least
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Populated splitter output with:
|
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
InvalidChunkException
|
If the number of generated chunk IDs does not match the number of chunks. |
SplitterOutputException
|
If constructing :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
If the input text is empty/whitespace-only or if the
|
SplitterOutputWarning
|
If non-empty text produces an empty DataFrame, which may indicate malformed input. |
Example
Splitting a CSV table by rows with overlap:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters import RowColumnSplitter
csv_text = (
"id,name,amount\n"
"1,A,10\n"
"2,B,20\n"
"3,C,30\n"
"4,D,40\n"
)
ro = ReaderOutput(
text=csv_text,
conversion_method="csv",
document_name="payments.csv",
document_path="/tmp/payments.csv",
document_id="payments-1",
)
splitter = RowColumnSplitter(
num_rows=2, # 2 rows per chunk
chunk_overlap=1, # reuse last 1 row in the next chunk
)
out = splitter.split(ro)
print(out.chunks)
[
'id,name,amount\n1,A,10\n2,B,20',
'id,name,amount\n2,B,20\n3,C,30',
'id,name,amount\n3,C,30\n4,D,40',
]
print(out.metadata["chunks"][0])
{'rows': [0, 1], 'type': 'row'}
Splitting a CSV table by columns::
splitter = RowColumnSplitter(
num_cols=2, # 2 columns per chunk
chunk_overlap=1, # reuse 1 column in the next chunk
)
out = splitter.split(ro)
print(out.chunks)
[['id', 1, 2, 3, 4], ['name', 'A', 'B', 'C', 'D']]
print(out.metadata["chunks"][0])
{'cols': ['id', 'name'], 'type': 'column'}
Splitting by character-based chunk size (markdown output)::
md_text = '''
| id | name | amount |
|----|------|--------|
| 1 | A | 10 |
| 2 | B | 20 |
| 3 | C | 30 |
| 4 | D | 40 |
'''.strip()
ro = ReaderOutput(
text=md_text,
conversion_method="markdown",
document_name="table.md",
)
splitter = RowColumnSplitter(
chunk_size=80, # max ~80 chars per chunk
chunk_overlap=0.25, # 25% row overlap between chunks
)
out = splitter.split(ro)
for i, (chunk, meta) in enumerate(
zip(out.chunks, out.metadata["chunks"]), start=1
):
print(f"--- CHUNK {i} ---")
print(chunk)
print("rows:", meta["rows"]) # original row indices
Handling unknown conversion_method with JSON/CSV fallback::
json_text = '''
[
{"id": 1, "name": "A", "amount": 10},
{"id": 2, "name": "B", "amount": 20}
]
'''.strip()
ro = ReaderOutput(
text=json_text,
conversion_method="unknown", # triggers JSON → CSV fallback logic
)
splitter = RowColumnSplitter(num_rows=1)
out = splitter.split(ro)
print(out.chunks)
Source code in src/splitter_mr/splitter/splitters/row_column_splitter.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | |
CodeSplitter¶
CodeSplitter
¶
Bases: BaseSplitter
Recursively splits source code into language-aware, semantically meaningful chunks.
The CodeSplitter uses LangChain's
:func:RecursiveCharacterTextSplitter.from_language method to generate
code chunks that align with syntactic boundaries such as functions,
methods, and classes. This allows for better context preservation during
code analysis, summarization, or embedding.
Attributes:
| Name | Type | Description |
|---|---|---|
language |
str
|
Programming language to split (e.g., |
chunk_size |
int
|
Maximum number of characters per chunk. |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
Emitted when the input text is empty or whitespace-only,
or when |
Raises:
| Type | Description |
|---|---|
UnsupportedCodeLanguage
|
If the requested language is not supported by LangChain. |
InvalidChunkException
|
If chunk generation fails or produces invalid chunks. |
SplitterOutputException
|
If the final :class: |
Source code in src/splitter_mr/splitter/splitters/code_splitter.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
split(reader_output)
¶
Split the provided source code into language-aware chunks.
The method performs input validation and warning emission, determines
the appropriate language enum, builds code chunks via LangChain,
and returns a fully validated :class:SplitterOutput instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
A validated input object containing
at least a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Structured splitter output containing:
* |
Raises:
| Type | Description |
|---|---|
UnsupportedCodeLanguage
|
If |
InvalidChunkException
|
If chunk construction fails or yields invalid chunks. |
SplitterOutputException
|
If the :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
If text is empty, whitespace-only, or invalid JSON. |
Example
from splitter_mr.splitter import CodeSplitter
from splitter_mr.schema.models import ReaderOutput
reader_output = ReaderOutput(
text="def foo():\n pass\n\nclass Bar:\n def baz(self):\n pass",
document_name="example.py",
document_path="/tmp/example.py",
)
splitter = CodeSplitter(chunk_size=50, language="python")
output = splitter.split(reader_output)
print(output.chunks)
['def foo():\n pass\n', 'class Bar:\n def baz(self):\n pass']
Source code in src/splitter_mr/splitter/splitters/code_splitter.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
get_langchain_language(lang_str)
¶
Resolve a string name to a LangChain Language enum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lang_str
|
str
|
Case-insensitive programming language name
(e.g., |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Language |
Language
|
The corresponding LangChain language enumeration. |
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If the provided language is not supported
by the LangChain |
Source code in src/splitter_mr/splitter/splitters/code_splitter.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
TokenSplitter¶
TokenSplitter
¶
Bases: BaseSplitter
Split text into token-based chunks using multiple tokenizer backends.
TokenSplitter splits a given text into chunks based on token counts derived from different tokenization models or libraries.
This splitter supports tokenization via tiktoken (OpenAI tokenizer),
spacy (spaCy tokenizer), and nltk (NLTK tokenizer). It allows splitting
text into chunks of a maximum number of tokens (chunk_size), using the
specified tokenizer model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Maximum number of tokens per chunk. |
1000
|
model_name
|
str
|
Tokenizer and model in the format
|
DEFAULT_TOKENIZER
|
language
|
str
|
Language code for the NLTK tokenizer (for example, |
DEFAULT_TOKEN_LANGUAGE
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Notes
See the LangChain documentation for more details about splitting by tokens: https://python.langchain.com/docs/how_to/split_by_token/
Source code in src/splitter_mr/splitter/splitters/token_splitter.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | |
list_nltk_punkt_languages()
staticmethod
¶
Return a sorted list of available NLTK Punkt models.
Returns:
| Name | Type | Description |
|---|---|---|
model_list |
List[str]
|
A sorted list of language codes corresponding to available |
List[str]
|
Punkt sentence tokenizer models in the local NLTK data path. |
Source code in src/splitter_mr/splitter/splitters/token_splitter.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
split(reader_output)
¶
Split the input text into token-based chunks.
The splitter uses the backend specified by model_name and
delegates to a tokenizer-specific implementation:
- tiktoken: Uses OpenAI encodings via
RecursiveCharacterTextSplitter. - spaCy: Uses the specified pipeline via
SpacyTextSplitter. - NLTK: Uses the Punkt sentence tokenizer via
NLTKTextSplitter.
Models or language data are downloaded automatically if missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Input text and associated metadata to be split. |
required |
Returns:
| Type | Description |
|---|---|
SplitterOutput
|
A |
SplitterOutput
|
|
SplitterOutput
|
|
SplitterOutput
|
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
InvalidChunkException
|
If the underlying splitter returns an invalid chunks structure. |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
If the input text is empty or whitespace-only. |
ChunkUnderflowWarning
|
If no chunks are produced from a non-empty input. |
Example
Basic usage with tiktoken:
from splitter_mr.splitter import TokenSplitter
from splitter_mr.schema.models import ReaderOutput
text = (
"This is a demonstration of the TokenSplitter. "
"It splits text into chunks based on token counts."
)
ro = ReaderOutput(text=text, document_name="demo.txt")
splitter = TokenSplitter(
chunk_size=20,
model_name="tiktoken/cl100k_base",
)
output = splitter.split(ro)
print(output.chunks)
Using spaCy:
splitter = TokenSplitter(
chunk_size=50,
model_name="spacy/en_core_web_sm",
)
output = splitter.split(ro)
print(output.chunks)
Using NLTK:
splitter = TokenSplitter(
chunk_size=40,
model_name="nltk/punkt_tab",
language="english",
)
output = splitter.split(ro)
print(output.chunks)
Source code in src/splitter_mr/splitter/splitters/token_splitter.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
PagedSplitter¶
Splits text by pages for documents that have page structure. Each chunk contains a specified number of pages, with optional word overlap.
PagedSplitter
¶
Bases: BaseSplitter
Splits a multi-page document into page-based or multi-page chunks using a placeholder marker.
This splitter uses the page_placeholder field of :class:ReaderOutput to break
the text into logical "pages" and then groups those pages into chunks. It can also
introduce character-based overlap between consecutive chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk_size
|
int
|
Number of pages per chunk. |
1
|
chunk_overlap
|
int
|
Number of overlapping characters to include from the end of the previous chunk. |
0
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
If |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
When the input text is empty or whitespace-only. |
SplitterOutputWarning
|
When no non-empty pages are found after splitting on the placeholder and the splitter falls back to a single empty chunk. |
Source code in src/splitter_mr/splitter/splitters/paged_splitter.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
split(reader_output)
¶
Split the input text into page-based chunks using the page placeholder.
The splitting process is:
- Validate and normalise the :class:
ReaderOutputand extracttext/page_placeholder. - Split the text into pages using
page_placeholder. - Group pages into chunks (with optional character-based overlap).
- Build the final :class:
SplitterOutput.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
The output from a reader containing text,
metadata, and a |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
The result with chunks and related metadata. |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If |
InvalidChunkException
|
If the number of generated |
SplitterOutputException
|
If constructing :class: |
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
When the input text is empty or whitespace-only. |
SplitterOutputWarning
|
When no non-empty pages are found after splitting on the placeholder and the splitter falls back to a single empty chunk. |
Example
Basic usage with a simple placeholder:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters import PagedSplitter
text = "<!-- page -->Page 1<!-- page -->Page 2<!-- page -->Page 3"
ro = ReaderOutput(
text=text,
page_placeholder="<!-- page -->",
document_name="demo.txt",
document_path="/tmp/demo.txt",
)
splitter = PagedSplitter(chunk_size=1, chunk_overlap=0)
out = splitter.split(ro)
print(out.chunks)
['Page 1', 'Page 2', 'Page 3']
Grouping multiple pages into a single chunk:
splitter = PagedSplitter(chunk_size=2)
out = splitter.split(ro)
print(out.chunks)
['Page 1\nPage 2', 'Page 3']
Applying character-based overlap between chunks:
text = "<p>One</p><!-- page --><p>Two</p><!-- page --><p>Three</p>"
ro = ReaderOutput(text=text, page_placeholder="<!-- page -->")
# Overlap last 5 characters from each previous chunk
splitter = PagedSplitter(chunk_size=1, chunk_overlap=5)
out = splitter.split(ro)
print(out.chunks)
['<p>One</p>', 'ne</p><p>Two</p>', 'o</p><p>Three</p>']
Metadata propagation:
ro = ReaderOutput(
text="<!-- page -->A<!-- page -->B",
page_placeholder="<!-- page -->",
document_name="source.txt",
document_path="/tmp/source.txt",
document_id="abc123",
)
splitter = PagedSplitter(chunk_size=1)
out = splitter.split(ro)
print(out.document_name)
'source.txt'
print(out.split_method)
'paged_splitter'
print(out.split_params)
{'chunk_size': 1, 'chunk_overlap': 0}
Source code in src/splitter_mr/splitter/splitters/paged_splitter.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
SemanticSplitter¶
Splits text into chunks based on semantic similarity, using an embedding model and a max tokens parameter. Useful for meaningful semantic groupings.
SemanticSplitter
¶
Bases: BaseSplitter
Split text into semantically coherent chunks using embedding similarity.
Pipeline:
- Split text into sentences via
SentenceSplitter(one sentence chunks). - Build a sliding window around each sentence (
buffer_size). - Embed each window with
BaseEmbedding(batched). - Compute cosine distances between consecutive windows (1 - cosine_sim).
- Pick breakpoints using a thresholding strategy, or aim for
number_of_chunks. - Join sentences between breakpoints; enforce minimum size via
chunk_size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding
|
BaseEmbedding
|
Embedding backend implementing an |
required |
buffer_size
|
int
|
Number of neighbouring sentences to include on each side
when building the contextual window for each sentence. A value of
|
1
|
breakpoint_threshold_type
|
BreakpointThresholdType
|
Strategy used to decide where to place breakpoints. Supported values are:
|
'percentile'
|
breakpoint_threshold_amount
|
Optional[float]
|
Strength of the threshold for the
chosen strategy. Meaning depends on
|
None
|
number_of_chunks
|
Optional[int]
|
Desired number of output chunks. When provided,
the splitter selects the largest distances to approximate this
target (subject to document length and |
None
|
chunk_size
|
int
|
Minimum allowed chunk size in characters. Short segments below this size are merged forward to avoid excessively small, fragmented chunks. |
1000
|
Raises:
| Type | Description |
|---|---|
SplitterConfigException
|
|
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
|
Source code in src/splitter_mr/splitter/splitters/semantic_splitter.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 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 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 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 612 613 614 615 616 617 | |
split(reader_output)
¶
Split the document text into semantically coherent chunks.
This method uses sentence embeddings to find semantic breakpoints.
Sentences are embedded in overlapping windows (controlled by buffer_size),
then cosine distances between consecutive windows are used to detect topic
shifts. Breakpoints are determined using either a threshold strategy
(percentile, std-dev, IQR, gradient) or by targeting a number of chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader_output
|
ReaderOutput
|
Input text and associated metadata. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SplitterOutput |
SplitterOutput
|
Structured splitter output containing:
* |
Raises:
| Type | Description |
|---|---|
ReaderOutputException
|
If the provided text is empty, None, or otherwise invalid. |
SplitterConfigException
|
If an invalid configuration is detected at runtime (defensive re-checks). |
SplitterOutputException
|
|
Warns:
| Type | Description |
|---|---|
SplitterInputWarning
|
|
SplitterOutputWarning
|
|
Notes
- With a single sentence (or 2 in gradient mode), returns text as-is.
chunk_sizeacts as the minimum allowed chunk size; small segments are merged forward.- The
buffer_sizedefines how much contextual overlap each sentence has for embedding (e.g., 1 = one sentence on either side).
Example
Basic usage with a custom embedding backend:
from splitter_mr.schema import ReaderOutput
from splitter_mr.splitter.splitters.semantic_splitter import SemanticSplitter
from splitter_mr.embedding import BaseEmbedding
class DummyEmbedding(BaseEmbedding):
"""Minimal embedding backend for demonstration purposes."""
model_name = "dummy-semantic-model"
def embed_documents(self, texts: list[str]) -> list[list[float]]:
# Return a simple fixed-length vector per text
dim = 8
return [[float(i) for i in range(dim)] for _ in texts]
text = (
"Cats like to sleep in the sun. "
"They often chase laser pointers. "
"Neural networks can classify animal images. "
"Transformers are widely used in NLP."
)
ro = ReaderOutput(text=text, document_name="semantic_demo.txt")
splitter = SemanticSplitter(
embedding=DummyEmbedding(),
buffer_size=1,
breakpoint_threshold_type="percentile",
breakpoint_threshold_amount=75.0,
chunk_size=50,
)
output = splitter.split(ro)
print(output.chunks)
Targeting a specific number of chunks:
splitter = SemanticSplitter(
embedding=DummyEmbedding(),
buffer_size=1,
number_of_chunks=3,
chunk_size=40,
)
output = splitter.split(ro)
print(output.chunks) # ~3 semantic chunks (subject to document length)
print(output.split_method) # "semantic_splitter"
print(output.split_params) # includes threshold config and model name
Source code in src/splitter_mr/splitter/splitters/semantic_splitter.py
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |