turkrag.chunking¶
Sentence-boundary-safe chunkers for Turkish text.
All chunkers split text with :class:turkrag.text.SentenceSplitter, so
abbreviations such as Dr., vb. or T.C. never cause a cut, and a
chunk boundary always falls between two sentences.
Examples:
>>> from turkrag.chunking import SentenceChunker
>>> SentenceChunker(max_chars=800).split("Prof. Dr. Ali geldi. Ders başladı.")
['Prof. Dr. Ali geldi. Ders başladı.']
Chunk
dataclass
¶
A piece of a document.
Attributes:
| Name | Type | Description |
|---|---|---|
text |
str
|
Chunk text, an exact slice of the source: |
start |
int
|
Start character offset in the source text. |
end |
int
|
End character offset (exclusive) in the source text. |
index |
int
|
Position of the chunk in the output list. |
metadata |
dict[str, Any]
|
Extra information, e.g. the number of sentences. |
from_dict(data)
classmethod
¶
Create a chunk from a dictionary produced by :meth:to_dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary with the keys |
required |
Returns:
| Type | Description |
|---|---|
Chunk
|
The chunk; its |
Examples:
>>> chunk = Chunk("Bir.", 0, 4, 0, {"n_sentences": 1})
>>> Chunk.from_dict(chunk.to_dict()) == chunk
True
to_dict()
¶
Convert the chunk to a plain dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with the keys |
dict[str, Any]
|
and |
Examples:
>>> Chunk("Bir.", 0, 4, 0, {"n_sentences": 1}).to_dict()
{'text': 'Bir.', 'start': 0, 'end': 4, 'index': 0, 'metadata': {'n_sentences': 1}}
Chunker
¶
Bases: ABC
Base class for all chunkers.
Subclasses implement :meth:chunk. Every chunker in TürkRAG keeps sentences
intact: a chunk boundary always falls between two sentences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
splitter
|
SentenceSplitter | None
|
Sentence splitter. Defaults to a :class: |
None
|
chunk(text)
abstractmethod
¶
Split text into chunks with offsets and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source document. |
required |
Returns:
| Type | Description |
|---|---|
list[Chunk]
|
Chunks in document order. |
split(text)
¶
Split text into chunk strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Source document. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Chunk texts in document order. |
split_many(texts)
¶
Split several documents and concatenate the chunk strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
Iterable[str]
|
Source documents. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
All chunk texts, document by document. |
MarkdownHeaderChunker
¶
Bases: Chunker
Split Markdown at # headings and keep the heading path in metadata.
Sentences are never cut. Each heading section is packed independently, so chunks never cross a heading boundary. Heading matches inside fenced code blocks are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_chars
|
int
|
Maximum chunk length in characters. |
1500
|
overlap_sentences
|
int
|
Number of trailing sentences of a chunk repeated at the start of the next one (only within the same heading section). |
0
|
splitter
|
SentenceSplitter | None
|
Custom sentence splitter. |
None
|
Examples:
>>> text = "# Başlık\nİçerik.\n## Alt\nDaha fazla."
>>> [c.metadata["headings"] for c in MarkdownHeaderChunker().chunk(text)]
['# Başlık', '# Başlık > ## Alt']
ParagraphChunker
¶
Bases: Chunker
Pack whole paragraphs into chunks of at most max_chars characters.
Paragraphs are separated by an empty line. Consecutive paragraphs are merged
while they fit. A paragraph longer than max_chars is split between its
sentences, never inside a sentence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_chars
|
int
|
Maximum chunk length, measured with |
1500
|
overlap_sentences
|
int
|
Number of trailing sentences of a chunk repeated at
the start of the next one (only if they fit within |
0
|
length_function
|
Callable[[str], int]
|
Measure chunk size with this function instead of
character count, e.g. |
len
|
splitter
|
SentenceSplitter | None
|
Custom sentence splitter. |
None
|
Examples:
>>> text = "Birinci paragraf. İki cümle.\n\nİkinci paragraf."
>>> ParagraphChunker(max_chars=30).split(text)
['Birinci paragraf. İki cümle.', 'İkinci paragraf.']
SemanticChunker
¶
Bases: Chunker
Start a new chunk when consecutive sentences drift apart in meaning.
Every sentence is embedded once with embedder.embed_documents. Cosine
similarity is computed between neighbouring sentence vectors; a new chunk
starts where it falls below threshold. Sentences are never cut.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedder
|
Embedder
|
Any object with |
required |
threshold
|
float
|
Minimum cosine similarity to keep two sentences together. |
0.5
|
max_chars
|
int | None
|
Optional maximum chunk length in characters. A new chunk also starts when adding the next sentence would exceed this limit. |
None
|
splitter
|
SentenceSplitter | None
|
Custom sentence splitter. |
None
|
Examples:
>>> class FakeEmbedder:
... def embed_documents(self, texts):
... vectors = []
... for text in texts:
... lowered = text.lower()
... hit = float(lowered.count("cümle"))
... miss = float(lowered.count("farklı"))
... vectors.append([hit, miss])
... return vectors
... def embed_query(self, text):
... return [0.0, 0.0]
>>> text = "Cümle bir. Cümle iki. Tamamen farklı konu."
>>> len(SemanticChunker(FakeEmbedder(), 0.5).split(text))
2
chunk(text)
¶
Split text where neighbouring sentence embeddings diverge.
SentenceChunker
¶
Bases: Chunker
Pack consecutive sentences into chunks of at most max_chars characters.
Sentences are never cut. A single sentence longer than max_chars becomes
a chunk on its own (so max_chars is a soft limit).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_chars
|
int
|
Maximum chunk length, measured with |
800
|
overlap_sentences
|
int
|
Number of trailing sentences of a chunk repeated at
the start of the next one (only if they fit within |
0
|
length_function
|
Callable[[str], int]
|
Measure chunk size with this function instead of
character count, e.g. |
len
|
splitter
|
SentenceSplitter | None
|
Custom sentence splitter. |
None
|
Examples:
>>> text = "Dr. Ayşe geldi. Toplantı başladı. Konu T.C. bütçesiydi."
>>> SentenceChunker(max_chars=40, overlap_sentences=1).split(text)
['Dr. Ayşe geldi. Toplantı başladı.', 'Toplantı başladı. Konu T.C. bütçesiydi.']
WindowChunker
¶
Bases: Chunker
Slide a fixed-size window of sentences over the text.
Each chunk holds window_sentences sentences; consecutive chunks share
overlap_sentences sentences. If max_chars is set, a window is
shortened (down to one sentence) until it fits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_sentences
|
int
|
Number of sentences per chunk. |
3
|
overlap_sentences
|
int
|
Number of sentences shared by consecutive chunks.
Must be smaller than |
1
|
max_chars
|
int | None
|
Optional maximum chunk length in characters. |
None
|
splitter
|
SentenceSplitter | None
|
Custom sentence splitter. |
None
|
Examples:
>>> text = "Bir. İki. Üç. Dört."
>>> WindowChunker(window_sentences=2, overlap_sentences=1).split(text)
['Bir. İki.', 'İki. Üç.', 'Üç. Dört.']
get_chunker(name, **kwargs)
¶
Create a registered chunker by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
required |
**kwargs
|
Any
|
Constructor arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Chunker
|
A chunker instance. |
Examples:
>>> get_chunker("sentence", max_chars=200).split("Dr. Ali geldi. Gitti.")
['Dr. Ali geldi. Gitti.']