safechunk 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- safechunk-0.1.0/.gitignore +14 -0
- safechunk-0.1.0/PKG-INFO +60 -0
- safechunk-0.1.0/README.md +33 -0
- safechunk-0.1.0/pyproject.toml +50 -0
- safechunk-0.1.0/src/safechunk/__init__.py +13 -0
- safechunk-0.1.0/src/safechunk/_grapheme.py +87 -0
- safechunk-0.1.0/src/safechunk/_splitter.py +732 -0
- safechunk-0.1.0/src/safechunk/py.typed +0 -0
- safechunk-0.1.0/tests/test_chunk.py +86 -0
safechunk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: safechunk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Intelligent text chunking for Telegram, Discord, and LLMs with Markdown, HTML, and Unicode safety
|
|
5
|
+
Project-URL: Homepage, https://github.com/ProstoAndriuha/safechunk
|
|
6
|
+
Project-URL: Repository, https://github.com/ProstoAndriuha/safechunk
|
|
7
|
+
Project-URL: Issues, https://github.com/ProstoAndriuha/safechunk/issues
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: chunk,chunking,discord,html,llm,markdown,rag,telegram,text-splitting,unicode
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
21
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# safechunk
|
|
29
|
+
|
|
30
|
+
Intelligent text chunking for Telegram, Discord, and LLMs with Markdown, HTML, and Unicode grapheme safety. Zero runtime dependencies.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install safechunk
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from safechunk import chunk
|
|
42
|
+
|
|
43
|
+
parts = chunk("<b>Hello world from chunks</b>", max_size=20, format="html")
|
|
44
|
+
# ['<b>Hello world</b>', '<b>from chunks</b>']
|
|
45
|
+
|
|
46
|
+
telegram_parts = chunk(long_message, target="telegram", format="markdown")
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Options
|
|
50
|
+
|
|
51
|
+
| Parameter | Type | Default | Description |
|
|
52
|
+
| --- | --- | --- | --- |
|
|
53
|
+
| `max_size` | `int \| None` | `None` | Max chunk size in Unicode code points (overrides `target`) |
|
|
54
|
+
| `target` | `"telegram" \| "discord" \| "llm" \| None` | `None` | Preset limit (`4096`, `2000`, `4000`; default `4000`) |
|
|
55
|
+
| `format` | `"plain" \| "markdown" \| "html"` | `"plain"` | Markup-aware splitting mode |
|
|
56
|
+
| `overlap` | `int` | `0` | Code-point overlap between adjacent chunks |
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# safechunk
|
|
2
|
+
|
|
3
|
+
Intelligent text chunking for Telegram, Discord, and LLMs with Markdown, HTML, and Unicode grapheme safety. Zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install safechunk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from safechunk import chunk
|
|
15
|
+
|
|
16
|
+
parts = chunk("<b>Hello world from chunks</b>", max_size=20, format="html")
|
|
17
|
+
# ['<b>Hello world</b>', '<b>from chunks</b>']
|
|
18
|
+
|
|
19
|
+
telegram_parts = chunk(long_message, target="telegram", format="markdown")
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Options
|
|
23
|
+
|
|
24
|
+
| Parameter | Type | Default | Description |
|
|
25
|
+
| --- | --- | --- | --- |
|
|
26
|
+
| `max_size` | `int \| None` | `None` | Max chunk size in Unicode code points (overrides `target`) |
|
|
27
|
+
| `target` | `"telegram" \| "discord" \| "llm" \| None` | `None` | Preset limit (`4096`, `2000`, `4000`; default `4000`) |
|
|
28
|
+
| `format` | `"plain" \| "markdown" \| "html"` | `"plain"` | Markup-aware splitting mode |
|
|
29
|
+
| `overlap` | `int` | `0` | Code-point overlap between adjacent chunks |
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
MIT
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "safechunk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Intelligent text chunking for Telegram, Discord, and LLMs with Markdown, HTML, and Unicode safety"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = [
|
|
14
|
+
"chunk",
|
|
15
|
+
"chunking",
|
|
16
|
+
"text-splitting",
|
|
17
|
+
"telegram",
|
|
18
|
+
"discord",
|
|
19
|
+
"llm",
|
|
20
|
+
"rag",
|
|
21
|
+
"markdown",
|
|
22
|
+
"html",
|
|
23
|
+
"unicode",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 4 - Beta",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
"Operating System :: OS Independent",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Programming Language :: Python :: 3.9",
|
|
32
|
+
"Programming Language :: Python :: 3.10",
|
|
33
|
+
"Programming Language :: Python :: 3.11",
|
|
34
|
+
"Programming Language :: Python :: 3.12",
|
|
35
|
+
"Programming Language :: Python :: 3.13",
|
|
36
|
+
"Topic :: Text Processing :: Markup :: HTML",
|
|
37
|
+
"Topic :: Text Processing :: Markup :: Markdown",
|
|
38
|
+
"Typing :: Typed",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/ProstoAndriuha/safechunk"
|
|
43
|
+
Repository = "https://github.com/ProstoAndriuha/safechunk"
|
|
44
|
+
Issues = "https://github.com/ProstoAndriuha/safechunk/issues"
|
|
45
|
+
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
dev = ["pytest>=8.0"]
|
|
48
|
+
|
|
49
|
+
[tool.hatch.build.targets.wheel]
|
|
50
|
+
packages = ["src/safechunk"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""safechunk: Intelligent text chunking preserving structure, markup, and Unicode graphemes."""
|
|
2
|
+
|
|
3
|
+
from ._splitter import TARGET_LIMITS, Format, Target, chunk
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"TARGET_LIMITS",
|
|
9
|
+
"Format",
|
|
10
|
+
"Target",
|
|
11
|
+
"__version__",
|
|
12
|
+
"chunk",
|
|
13
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Unicode grapheme cluster segmentation using only the Python standard library."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import unicodedata
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Cluster(NamedTuple):
|
|
10
|
+
text: str
|
|
11
|
+
cp_len: int
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def cp_len(text: str) -> int:
|
|
15
|
+
"""Return length in Unicode code points."""
|
|
16
|
+
return len(text)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _is_regional_indicator(cp: int) -> bool:
|
|
20
|
+
return 0x1F1E6 <= cp <= 0x1F1FF
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _is_extend(ch: str, cp: int) -> bool:
|
|
24
|
+
if cp == 0x20E3: # combining enclosing keycap
|
|
25
|
+
return True
|
|
26
|
+
if 0xFE00 <= cp <= 0xFE0F or 0xE0100 <= cp <= 0xE01EF: # variation selectors
|
|
27
|
+
return True
|
|
28
|
+
if 0x1F3FB <= cp <= 0x1F3FF: # emoji skin-tone modifiers
|
|
29
|
+
return True
|
|
30
|
+
if 0xE0020 <= cp <= 0xE007F: # tag characters
|
|
31
|
+
return True
|
|
32
|
+
if unicodedata.category(ch) in ("Mn", "Mc", "Me"):
|
|
33
|
+
return True
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def segment_graphemes(text: str) -> list[Cluster]:
|
|
38
|
+
"""Split text into atomic grapheme clusters safe for chunking."""
|
|
39
|
+
clusters: list[Cluster] = []
|
|
40
|
+
n = len(text)
|
|
41
|
+
i = 0
|
|
42
|
+
|
|
43
|
+
while i < n:
|
|
44
|
+
ch = text[i]
|
|
45
|
+
cp = ord(ch)
|
|
46
|
+
|
|
47
|
+
# CRLF pair
|
|
48
|
+
if ch == "\r" and i + 1 < n and text[i + 1] == "\n":
|
|
49
|
+
clusters.append(Cluster("\r\n", 2))
|
|
50
|
+
i += 2
|
|
51
|
+
continue
|
|
52
|
+
|
|
53
|
+
start = i
|
|
54
|
+
i += 1
|
|
55
|
+
|
|
56
|
+
# Regional indicator flag pairs (pair at most two)
|
|
57
|
+
if _is_regional_indicator(cp):
|
|
58
|
+
if i < n and _is_regional_indicator(ord(text[i])):
|
|
59
|
+
i += 1
|
|
60
|
+
while i < n and _is_extend(text[i], ord(text[i])):
|
|
61
|
+
i += 1
|
|
62
|
+
seg = text[start:i]
|
|
63
|
+
clusters.append(Cluster(seg, len(seg)))
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
# Base + trailing extends and ZWJ sequences
|
|
67
|
+
while i < n:
|
|
68
|
+
nxt = text[i]
|
|
69
|
+
nxt_cp = ord(nxt)
|
|
70
|
+
if _is_extend(nxt, nxt_cp):
|
|
71
|
+
i += 1
|
|
72
|
+
continue
|
|
73
|
+
if nxt_cp == 0x200D and i + 1 < n:
|
|
74
|
+
# Consume ZWJ and the following base (or RI pair) + its extends
|
|
75
|
+
i += 1
|
|
76
|
+
if i < n:
|
|
77
|
+
base_cp = ord(text[i])
|
|
78
|
+
i += 1
|
|
79
|
+
if _is_regional_indicator(base_cp) and i < n and _is_regional_indicator(ord(text[i])):
|
|
80
|
+
i += 1
|
|
81
|
+
continue
|
|
82
|
+
break
|
|
83
|
+
|
|
84
|
+
seg = text[start:i]
|
|
85
|
+
clusters.append(Cluster(seg, len(seg)))
|
|
86
|
+
|
|
87
|
+
return clusters
|
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
"""Core text chunking engine for safechunk."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Literal, Optional
|
|
8
|
+
|
|
9
|
+
from ._grapheme import cp_len, segment_graphemes
|
|
10
|
+
|
|
11
|
+
Target = Literal["telegram", "discord", "llm"]
|
|
12
|
+
Format = Literal["plain", "markdown", "html"]
|
|
13
|
+
|
|
14
|
+
TARGET_LIMITS: dict[Target, int] = {
|
|
15
|
+
"telegram": 4096,
|
|
16
|
+
"discord": 2000,
|
|
17
|
+
"llm": 4000,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
_VALID_TARGETS = ("telegram", "discord", "llm")
|
|
21
|
+
_VALID_FORMATS = ("plain", "markdown", "html")
|
|
22
|
+
|
|
23
|
+
_VOID_HTML_TAGS = frozenset(
|
|
24
|
+
{
|
|
25
|
+
"area",
|
|
26
|
+
"base",
|
|
27
|
+
"br",
|
|
28
|
+
"col",
|
|
29
|
+
"embed",
|
|
30
|
+
"hr",
|
|
31
|
+
"img",
|
|
32
|
+
"input",
|
|
33
|
+
"link",
|
|
34
|
+
"meta",
|
|
35
|
+
"param",
|
|
36
|
+
"source",
|
|
37
|
+
"track",
|
|
38
|
+
"wbr",
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
_PRESERVE_INDENT_HTML_TAGS = frozenset({"pre", "code"})
|
|
43
|
+
|
|
44
|
+
_FENCE_OPEN_RE = re.compile(r"^[ ]{0,3}(`{3,}|~{3,})(.*)$")
|
|
45
|
+
_FENCE_CLOSE_RE = re.compile(r"^[ ]{0,3}(`+|~+)[ \t]*$")
|
|
46
|
+
_HTML_CLOSE_RE = re.compile(r"^</([A-Za-z][A-Za-z0-9:-]*)[ \t\r\n]*>")
|
|
47
|
+
_HTML_TAG_START_RE = re.compile(r"^<([A-Za-z][A-Za-z0-9:-]*)(?=[\s/>])")
|
|
48
|
+
_HTML_ENTITY_RE = re.compile(
|
|
49
|
+
r"^&(?:[A-Za-z][A-Za-z0-9]{1,31}|#[0-9]{1,7}|#x[0-9A-Fa-f]{1,6});"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class _Token:
|
|
55
|
+
kind: str # CLUSTER | FENCE_OPEN | FENCE_CLOSE | HTML_ATOMIC | HTML_OPEN | HTML_CLOSE
|
|
56
|
+
raw: str
|
|
57
|
+
cp_len: int
|
|
58
|
+
fence_char: str = ""
|
|
59
|
+
fence_len: int = 0
|
|
60
|
+
open_prefix: str = ""
|
|
61
|
+
close_line: str = ""
|
|
62
|
+
tag_name: str = ""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class _HtmlEntry:
|
|
67
|
+
tag_name: str
|
|
68
|
+
raw_open: str
|
|
69
|
+
inherited: bool
|
|
70
|
+
has_content: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class _FenceState:
|
|
75
|
+
open_prefix: str
|
|
76
|
+
close_line: str
|
|
77
|
+
inherited: bool
|
|
78
|
+
has_content: bool
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class _OpenState:
|
|
83
|
+
fence: Optional[_FenceState]
|
|
84
|
+
html_stack: list[_HtmlEntry]
|
|
85
|
+
|
|
86
|
+
def clone(self) -> _OpenState:
|
|
87
|
+
fence_copy = (
|
|
88
|
+
_FenceState(
|
|
89
|
+
open_prefix=self.fence.open_prefix,
|
|
90
|
+
close_line=self.fence.close_line,
|
|
91
|
+
inherited=self.fence.inherited,
|
|
92
|
+
has_content=self.fence.has_content,
|
|
93
|
+
)
|
|
94
|
+
if self.fence is not None
|
|
95
|
+
else None
|
|
96
|
+
)
|
|
97
|
+
stack_copy = [
|
|
98
|
+
_HtmlEntry(
|
|
99
|
+
tag_name=e.tag_name,
|
|
100
|
+
raw_open=e.raw_open,
|
|
101
|
+
inherited=e.inherited,
|
|
102
|
+
has_content=e.has_content,
|
|
103
|
+
)
|
|
104
|
+
for e in self.html_stack
|
|
105
|
+
]
|
|
106
|
+
return _OpenState(fence=fence_copy, html_stack=stack_copy)
|
|
107
|
+
|
|
108
|
+
def as_inherited(self) -> _OpenState:
|
|
109
|
+
fence_copy = (
|
|
110
|
+
_FenceState(
|
|
111
|
+
open_prefix=self.fence.open_prefix,
|
|
112
|
+
close_line=self.fence.close_line,
|
|
113
|
+
inherited=True,
|
|
114
|
+
has_content=True,
|
|
115
|
+
)
|
|
116
|
+
if self.fence is not None
|
|
117
|
+
else None
|
|
118
|
+
)
|
|
119
|
+
stack_copy = [
|
|
120
|
+
_HtmlEntry(
|
|
121
|
+
tag_name=e.tag_name,
|
|
122
|
+
raw_open=e.raw_open,
|
|
123
|
+
inherited=True,
|
|
124
|
+
has_content=True,
|
|
125
|
+
)
|
|
126
|
+
for e in self.html_stack
|
|
127
|
+
]
|
|
128
|
+
return _OpenState(fence=fence_copy, html_stack=stack_copy)
|
|
129
|
+
|
|
130
|
+
def preserve_indent(self) -> bool:
|
|
131
|
+
if self.fence is not None:
|
|
132
|
+
return True
|
|
133
|
+
return any(e.tag_name in _PRESERVE_INDENT_HTML_TAGS for e in self.html_stack)
|
|
134
|
+
|
|
135
|
+
def has_empty_new_wrapper(self) -> bool:
|
|
136
|
+
if self.fence is not None and not self.fence.inherited and not self.fence.has_content:
|
|
137
|
+
return True
|
|
138
|
+
for entry in self.html_stack:
|
|
139
|
+
if not entry.inherited and not entry.has_content:
|
|
140
|
+
return True
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
def reopen_prefix(self) -> str:
|
|
144
|
+
parts: list[str] = []
|
|
145
|
+
if self.fence is not None:
|
|
146
|
+
parts.append(self.fence.open_prefix)
|
|
147
|
+
for entry in self.html_stack:
|
|
148
|
+
parts.append(entry.raw_open)
|
|
149
|
+
return "".join(parts)
|
|
150
|
+
|
|
151
|
+
def close_suffix(self, body_ends_with_nl: bool) -> str:
|
|
152
|
+
parts: list[str] = []
|
|
153
|
+
for entry in reversed(self.html_stack):
|
|
154
|
+
parts.append(f"</{entry.tag_name}>")
|
|
155
|
+
if self.fence is not None:
|
|
156
|
+
if body_ends_with_nl:
|
|
157
|
+
parts.append(self.fence.close_line)
|
|
158
|
+
else:
|
|
159
|
+
parts.append("\n" + self.fence.close_line)
|
|
160
|
+
return "".join(parts)
|
|
161
|
+
|
|
162
|
+
def close_len(self, body_ends_with_nl: bool) -> int:
|
|
163
|
+
total = 0
|
|
164
|
+
for entry in self.html_stack:
|
|
165
|
+
total += 3 + len(entry.tag_name)
|
|
166
|
+
if self.fence is not None:
|
|
167
|
+
total += len(self.fence.close_line)
|
|
168
|
+
if not body_ends_with_nl:
|
|
169
|
+
total += 1
|
|
170
|
+
return total
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _is_newline(tok: _Token) -> bool:
|
|
174
|
+
return tok.kind == "CLUSTER" and tok.raw in ("\n", "\r\n")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _is_horiz_ws(tok: _Token) -> bool:
|
|
178
|
+
return tok.kind == "CLUSTER" and tok.raw in (" ", "\t")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _is_any_ws(tok: _Token) -> bool:
|
|
182
|
+
return tok.kind == "CLUSTER" and (tok.raw in (" ", "\t", "\n", "\r\n") or tok.raw.isspace())
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _is_sentence_punct(tok: _Token) -> bool:
|
|
186
|
+
return tok.kind == "CLUSTER" and tok.raw in (".", "!", "?")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _clusters_to_tokens(text: str) -> list[_Token]:
|
|
190
|
+
return [_Token(kind="CLUSTER", raw=c.text, cp_len=c.cp_len) for c in segment_graphemes(text)]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _split_lines_keepends(text: str) -> list[tuple[str, str]]:
|
|
194
|
+
lines: list[tuple[str, str]] = []
|
|
195
|
+
n = len(text)
|
|
196
|
+
start = 0
|
|
197
|
+
i = 0
|
|
198
|
+
while i < n:
|
|
199
|
+
if text[i] == "\r":
|
|
200
|
+
if i + 1 < n and text[i + 1] == "\n":
|
|
201
|
+
lines.append((text[start:i], "\r\n"))
|
|
202
|
+
i += 2
|
|
203
|
+
start = i
|
|
204
|
+
continue
|
|
205
|
+
lines.append((text[start:i], "\r"))
|
|
206
|
+
i += 1
|
|
207
|
+
start = i
|
|
208
|
+
continue
|
|
209
|
+
if text[i] == "\n":
|
|
210
|
+
lines.append((text[start:i], "\n"))
|
|
211
|
+
i += 1
|
|
212
|
+
start = i
|
|
213
|
+
continue
|
|
214
|
+
i += 1
|
|
215
|
+
if start < n:
|
|
216
|
+
lines.append((text[start:n], ""))
|
|
217
|
+
return lines
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _tokenize_markdown(text: str) -> list[_Token]:
|
|
221
|
+
tokens: list[_Token] = []
|
|
222
|
+
active_char: Optional[str] = None
|
|
223
|
+
active_len = 0
|
|
224
|
+
|
|
225
|
+
for body, ending in _split_lines_keepends(text):
|
|
226
|
+
if active_char is None:
|
|
227
|
+
m = _FENCE_OPEN_RE.match(body)
|
|
228
|
+
if m is not None:
|
|
229
|
+
marker = m.group(1)
|
|
230
|
+
info = m.group(2)
|
|
231
|
+
if not (marker[0] == "`" and "`" in info):
|
|
232
|
+
raw = body + ending
|
|
233
|
+
open_prefix = body + (ending if ending else "\n")
|
|
234
|
+
tokens.append(
|
|
235
|
+
_Token(
|
|
236
|
+
kind="FENCE_OPEN",
|
|
237
|
+
raw=raw,
|
|
238
|
+
cp_len=cp_len(raw),
|
|
239
|
+
fence_char=marker[0],
|
|
240
|
+
fence_len=len(marker),
|
|
241
|
+
open_prefix=open_prefix,
|
|
242
|
+
close_line=marker[0] * len(marker),
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
active_char = marker[0]
|
|
246
|
+
active_len = len(marker)
|
|
247
|
+
continue
|
|
248
|
+
else:
|
|
249
|
+
m = _FENCE_CLOSE_RE.match(body)
|
|
250
|
+
if m is not None:
|
|
251
|
+
marker = m.group(1)
|
|
252
|
+
if marker[0] == active_char and len(marker) >= active_len:
|
|
253
|
+
raw = body + ending
|
|
254
|
+
if tokens and _is_newline(tokens[-1]):
|
|
255
|
+
prev_nl = tokens.pop()
|
|
256
|
+
raw = prev_nl.raw + raw
|
|
257
|
+
tokens.append(
|
|
258
|
+
_Token(
|
|
259
|
+
kind="FENCE_CLOSE",
|
|
260
|
+
raw=raw,
|
|
261
|
+
cp_len=cp_len(raw),
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
active_char = None
|
|
265
|
+
active_len = 0
|
|
266
|
+
continue
|
|
267
|
+
|
|
268
|
+
tokens.extend(_clusters_to_tokens(body + ending))
|
|
269
|
+
|
|
270
|
+
return tokens
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _find_tag_end(text: str, start: int) -> int:
|
|
274
|
+
n = len(text)
|
|
275
|
+
i = start + 1
|
|
276
|
+
quote: Optional[str] = None
|
|
277
|
+
while i < n:
|
|
278
|
+
ch = text[i]
|
|
279
|
+
if quote is not None:
|
|
280
|
+
if ch == quote:
|
|
281
|
+
quote = None
|
|
282
|
+
else:
|
|
283
|
+
if ch == '"' or ch == "'":
|
|
284
|
+
quote = ch
|
|
285
|
+
elif ch == ">":
|
|
286
|
+
return i
|
|
287
|
+
i += 1
|
|
288
|
+
return -1
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _tokenize_html(text: str) -> list[_Token]:
|
|
292
|
+
tokens: list[_Token] = []
|
|
293
|
+
n = len(text)
|
|
294
|
+
i = 0
|
|
295
|
+
plain_start = 0
|
|
296
|
+
|
|
297
|
+
def flush_plain(end: int) -> None:
|
|
298
|
+
nonlocal plain_start
|
|
299
|
+
if end > plain_start:
|
|
300
|
+
tokens.extend(_clusters_to_tokens(text[plain_start:end]))
|
|
301
|
+
plain_start = end
|
|
302
|
+
|
|
303
|
+
while i < n:
|
|
304
|
+
ch = text[i]
|
|
305
|
+
if ch == "<":
|
|
306
|
+
if text.startswith("<!--", i):
|
|
307
|
+
end_idx = text.find("-->", i + 4)
|
|
308
|
+
if end_idx != -1:
|
|
309
|
+
flush_plain(i)
|
|
310
|
+
raw = text[i : end_idx + 3]
|
|
311
|
+
tokens.append(_Token(kind="HTML_ATOMIC", raw=raw, cp_len=cp_len(raw)))
|
|
312
|
+
i = end_idx + 3
|
|
313
|
+
plain_start = i
|
|
314
|
+
continue
|
|
315
|
+
elif i + 1 < n and text[i + 1] in ("!", "?"):
|
|
316
|
+
gt = _find_tag_end(text, i)
|
|
317
|
+
if gt != -1:
|
|
318
|
+
flush_plain(i)
|
|
319
|
+
raw = text[i : gt + 1]
|
|
320
|
+
tokens.append(_Token(kind="HTML_ATOMIC", raw=raw, cp_len=cp_len(raw)))
|
|
321
|
+
i = gt + 1
|
|
322
|
+
plain_start = i
|
|
323
|
+
continue
|
|
324
|
+
else:
|
|
325
|
+
close_m = _HTML_CLOSE_RE.match(text[i:])
|
|
326
|
+
if close_m is not None:
|
|
327
|
+
flush_plain(i)
|
|
328
|
+
raw = close_m.group(0)
|
|
329
|
+
tag_name = close_m.group(1).lower()
|
|
330
|
+
tokens.append(
|
|
331
|
+
_Token(kind="HTML_CLOSE", raw=raw, cp_len=cp_len(raw), tag_name=tag_name)
|
|
332
|
+
)
|
|
333
|
+
i += len(raw)
|
|
334
|
+
plain_start = i
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
open_m = _HTML_TAG_START_RE.match(text[i:])
|
|
338
|
+
if open_m is not None:
|
|
339
|
+
gt = _find_tag_end(text, i)
|
|
340
|
+
if gt != -1:
|
|
341
|
+
flush_plain(i)
|
|
342
|
+
raw = text[i : gt + 1]
|
|
343
|
+
tag_name = open_m.group(1).lower()
|
|
344
|
+
is_self_closing = raw[:-1].rstrip().endswith("/")
|
|
345
|
+
if is_self_closing or tag_name in _VOID_HTML_TAGS:
|
|
346
|
+
tokens.append(_Token(kind="HTML_ATOMIC", raw=raw, cp_len=cp_len(raw)))
|
|
347
|
+
else:
|
|
348
|
+
tokens.append(
|
|
349
|
+
_Token(
|
|
350
|
+
kind="HTML_OPEN",
|
|
351
|
+
raw=raw,
|
|
352
|
+
cp_len=cp_len(raw),
|
|
353
|
+
tag_name=tag_name,
|
|
354
|
+
)
|
|
355
|
+
)
|
|
356
|
+
i = gt + 1
|
|
357
|
+
plain_start = i
|
|
358
|
+
continue
|
|
359
|
+
i += 1
|
|
360
|
+
continue
|
|
361
|
+
|
|
362
|
+
if ch == "&":
|
|
363
|
+
ent_m = _HTML_ENTITY_RE.match(text[i:])
|
|
364
|
+
if ent_m is not None:
|
|
365
|
+
flush_plain(i)
|
|
366
|
+
raw = ent_m.group(0)
|
|
367
|
+
tokens.append(_Token(kind="HTML_ATOMIC", raw=raw, cp_len=cp_len(raw)))
|
|
368
|
+
i += len(raw)
|
|
369
|
+
plain_start = i
|
|
370
|
+
continue
|
|
371
|
+
i += 1
|
|
372
|
+
continue
|
|
373
|
+
|
|
374
|
+
i += 1
|
|
375
|
+
|
|
376
|
+
flush_plain(n)
|
|
377
|
+
return tokens
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _tokenize(text: str, fmt: Format) -> list[_Token]:
|
|
381
|
+
if fmt == "plain":
|
|
382
|
+
return _clusters_to_tokens(text)
|
|
383
|
+
if fmt == "markdown":
|
|
384
|
+
return _tokenize_markdown(text)
|
|
385
|
+
return _tokenize_html(text)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _advance_state(state: _OpenState, tok: _Token) -> None:
|
|
389
|
+
if tok.kind == "FENCE_OPEN":
|
|
390
|
+
state.fence = _FenceState(
|
|
391
|
+
open_prefix=tok.open_prefix,
|
|
392
|
+
close_line=tok.close_line,
|
|
393
|
+
inherited=False,
|
|
394
|
+
has_content=False,
|
|
395
|
+
)
|
|
396
|
+
elif tok.kind == "FENCE_CLOSE":
|
|
397
|
+
state.fence = None
|
|
398
|
+
elif tok.kind == "HTML_OPEN":
|
|
399
|
+
state.html_stack.append(
|
|
400
|
+
_HtmlEntry(
|
|
401
|
+
tag_name=tok.tag_name,
|
|
402
|
+
raw_open=tok.raw,
|
|
403
|
+
inherited=False,
|
|
404
|
+
has_content=False,
|
|
405
|
+
)
|
|
406
|
+
)
|
|
407
|
+
elif tok.kind == "HTML_CLOSE":
|
|
408
|
+
for idx in range(len(state.html_stack) - 1, -1, -1):
|
|
409
|
+
if state.html_stack[idx].tag_name == tok.tag_name:
|
|
410
|
+
del state.html_stack[idx:]
|
|
411
|
+
break
|
|
412
|
+
elif tok.kind == "HTML_ATOMIC" or (tok.kind == "CLUSTER" and not _is_any_ws(tok)):
|
|
413
|
+
if state.fence is not None:
|
|
414
|
+
state.fence.has_content = True
|
|
415
|
+
for entry in state.html_stack:
|
|
416
|
+
entry.has_content = True
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
@dataclass
|
|
420
|
+
class _Candidate:
|
|
421
|
+
tier: int
|
|
422
|
+
end_idx: int
|
|
423
|
+
next_start: int
|
|
424
|
+
sep_tokens: list[_Token]
|
|
425
|
+
state: _OpenState
|
|
426
|
+
ends_with_nl: bool
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _compute_overlap_tokens(
|
|
430
|
+
tokens: list[_Token],
|
|
431
|
+
chunk_start: int,
|
|
432
|
+
split_end: int,
|
|
433
|
+
next_start: int,
|
|
434
|
+
sep_tokens: list[_Token],
|
|
435
|
+
overlap: int,
|
|
436
|
+
preserve_indent: bool,
|
|
437
|
+
max_body_budget: int,
|
|
438
|
+
) -> list[_Token]:
|
|
439
|
+
if overlap <= 0 or max_body_budget <= 1 or next_start >= len(tokens):
|
|
440
|
+
return []
|
|
441
|
+
|
|
442
|
+
first_orig_len = tokens[next_start].cp_len
|
|
443
|
+
if first_orig_len >= max_body_budget:
|
|
444
|
+
return []
|
|
445
|
+
|
|
446
|
+
collected: list[_Token] = []
|
|
447
|
+
collected_len = 0
|
|
448
|
+
idx = split_end - 1
|
|
449
|
+
while idx >= chunk_start:
|
|
450
|
+
tok = tokens[idx]
|
|
451
|
+
if tok.kind != "CLUSTER":
|
|
452
|
+
break
|
|
453
|
+
if collected_len + tok.cp_len > overlap:
|
|
454
|
+
break
|
|
455
|
+
collected.append(tok)
|
|
456
|
+
collected_len += tok.cp_len
|
|
457
|
+
idx -= 1
|
|
458
|
+
|
|
459
|
+
if not collected:
|
|
460
|
+
return []
|
|
461
|
+
|
|
462
|
+
collected.reverse()
|
|
463
|
+
|
|
464
|
+
slice_start_idx = idx + 1
|
|
465
|
+
if slice_start_idx > chunk_start:
|
|
466
|
+
prev_tok = tokens[slice_start_idx - 1]
|
|
467
|
+
if prev_tok.kind == "CLUSTER" and not _is_any_ws(prev_tok) and not _is_any_ws(collected[0]):
|
|
468
|
+
ws_pos = -1
|
|
469
|
+
for j, t in enumerate(collected):
|
|
470
|
+
if _is_any_ws(t):
|
|
471
|
+
ws_pos = j
|
|
472
|
+
break
|
|
473
|
+
if ws_pos != -1:
|
|
474
|
+
collected = collected[ws_pos:]
|
|
475
|
+
else:
|
|
476
|
+
return []
|
|
477
|
+
|
|
478
|
+
while collected and _is_newline(collected[0]):
|
|
479
|
+
collected.pop(0)
|
|
480
|
+
if not preserve_indent:
|
|
481
|
+
while collected and _is_horiz_ws(collected[0]):
|
|
482
|
+
collected.pop(0)
|
|
483
|
+
|
|
484
|
+
if not collected:
|
|
485
|
+
return []
|
|
486
|
+
|
|
487
|
+
sep_to_use = sep_tokens[:1] if (not preserve_indent and sep_tokens and all(_is_horiz_ws(t) for t in sep_tokens)) else sep_tokens
|
|
488
|
+
combined = collected + sep_to_use
|
|
489
|
+
combined_len = sum(t.cp_len for t in combined)
|
|
490
|
+
if combined_len + first_orig_len > max_body_budget:
|
|
491
|
+
return []
|
|
492
|
+
|
|
493
|
+
return combined
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _validate_options(
|
|
497
|
+
max_size: Optional[int],
|
|
498
|
+
target: Optional[Target],
|
|
499
|
+
fmt: Format,
|
|
500
|
+
overlap: int,
|
|
501
|
+
) -> int:
|
|
502
|
+
if target is not None and target not in _VALID_TARGETS:
|
|
503
|
+
raise ValueError(f"Invalid target: {target!r}. Expected one of {_VALID_TARGETS}.")
|
|
504
|
+
|
|
505
|
+
if fmt not in _VALID_FORMATS:
|
|
506
|
+
raise ValueError(f"Invalid format: {fmt!r}. Expected one of {_VALID_FORMATS}.")
|
|
507
|
+
|
|
508
|
+
if max_size is not None:
|
|
509
|
+
if isinstance(max_size, bool) or not isinstance(max_size, int) or max_size <= 0:
|
|
510
|
+
raise ValueError(f"max_size must be a positive integer, got {max_size!r}.")
|
|
511
|
+
effective_max_size = max_size
|
|
512
|
+
elif target is not None:
|
|
513
|
+
effective_max_size = TARGET_LIMITS[target]
|
|
514
|
+
else:
|
|
515
|
+
effective_max_size = TARGET_LIMITS["llm"]
|
|
516
|
+
|
|
517
|
+
if isinstance(overlap, bool) or not isinstance(overlap, int) or overlap < 0:
|
|
518
|
+
raise ValueError(f"overlap must be a non-negative integer, got {overlap!r}.")
|
|
519
|
+
if overlap >= effective_max_size:
|
|
520
|
+
raise ValueError(
|
|
521
|
+
f"overlap ({overlap}) must be strictly less than effective max_size ({effective_max_size})."
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
return effective_max_size
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def chunk(
|
|
528
|
+
text: str,
|
|
529
|
+
*,
|
|
530
|
+
max_size: Optional[int] = None,
|
|
531
|
+
target: Optional[Target] = None,
|
|
532
|
+
format: Format = "plain",
|
|
533
|
+
overlap: int = 0,
|
|
534
|
+
) -> list[str]:
|
|
535
|
+
"""Split text into chunks preserving document structure, markup, and Unicode graphemes."""
|
|
536
|
+
effective_max_size = _validate_options(max_size, target, format, overlap)
|
|
537
|
+
|
|
538
|
+
if not text or not text.strip():
|
|
539
|
+
return []
|
|
540
|
+
|
|
541
|
+
if cp_len(text) <= effective_max_size:
|
|
542
|
+
return [text]
|
|
543
|
+
|
|
544
|
+
tokens = _tokenize(text, format)
|
|
545
|
+
chunks: list[str] = []
|
|
546
|
+
open_state = _OpenState(fence=None, html_stack=[])
|
|
547
|
+
start = 0
|
|
548
|
+
overlap_prefix_len = 0
|
|
549
|
+
|
|
550
|
+
while start < len(tokens):
|
|
551
|
+
if open_state.fence is None and not open_state.html_stack:
|
|
552
|
+
if all(_is_any_ws(t) for t in tokens[start:]):
|
|
553
|
+
break
|
|
554
|
+
|
|
555
|
+
reopen_prefix = open_state.reopen_prefix()
|
|
556
|
+
reopen_len = cp_len(reopen_prefix)
|
|
557
|
+
remaining_len = sum(t.cp_len for t in tokens[start:])
|
|
558
|
+
|
|
559
|
+
if reopen_len + remaining_len <= effective_max_size:
|
|
560
|
+
chunks.append(reopen_prefix + "".join(t.raw for t in tokens[start:]))
|
|
561
|
+
break
|
|
562
|
+
|
|
563
|
+
sim_state = open_state.as_inherited()
|
|
564
|
+
used_len = reopen_len
|
|
565
|
+
best_by_tier: dict[int, _Candidate] = {}
|
|
566
|
+
has_non_ws = False
|
|
567
|
+
min_next_start = start + overlap_prefix_len
|
|
568
|
+
|
|
569
|
+
k = start
|
|
570
|
+
n_tokens = len(tokens)
|
|
571
|
+
while k < n_tokens:
|
|
572
|
+
tok = tokens[k]
|
|
573
|
+
if used_len + tok.cp_len > effective_max_size:
|
|
574
|
+
break
|
|
575
|
+
|
|
576
|
+
_advance_state(sim_state, tok)
|
|
577
|
+
used_len += tok.cp_len
|
|
578
|
+
if tok.kind != "CLUSTER" or not _is_any_ws(tok):
|
|
579
|
+
has_non_ws = True
|
|
580
|
+
k += 1
|
|
581
|
+
|
|
582
|
+
if k == n_tokens:
|
|
583
|
+
best_by_tier[1] = _Candidate(
|
|
584
|
+
tier=1,
|
|
585
|
+
end_idx=k,
|
|
586
|
+
next_start=k,
|
|
587
|
+
sep_tokens=[],
|
|
588
|
+
state=sim_state.clone(),
|
|
589
|
+
ends_with_nl=_is_newline(tokens[k - 1]),
|
|
590
|
+
)
|
|
591
|
+
break
|
|
592
|
+
|
|
593
|
+
ends_with_nl = _is_newline(tokens[k - 1])
|
|
594
|
+
close_len = sim_state.close_len(ends_with_nl)
|
|
595
|
+
if used_len + close_len > effective_max_size:
|
|
596
|
+
continue
|
|
597
|
+
|
|
598
|
+
if sim_state.has_empty_new_wrapper():
|
|
599
|
+
continue
|
|
600
|
+
|
|
601
|
+
preserve_indent = sim_state.preserve_indent()
|
|
602
|
+
if not preserve_indent and not has_non_ws:
|
|
603
|
+
continue
|
|
604
|
+
|
|
605
|
+
nxt = tokens[k]
|
|
606
|
+
|
|
607
|
+
# Tier 1: Paragraph break
|
|
608
|
+
if _is_newline(nxt) and k + 1 < n_tokens and _is_newline(tokens[k + 1]):
|
|
609
|
+
if k + 2 > min_next_start:
|
|
610
|
+
best_by_tier[1] = _Candidate(
|
|
611
|
+
tier=1,
|
|
612
|
+
end_idx=k,
|
|
613
|
+
next_start=k + 2,
|
|
614
|
+
sep_tokens=tokens[k : k + 2],
|
|
615
|
+
state=sim_state.clone(),
|
|
616
|
+
ends_with_nl=ends_with_nl,
|
|
617
|
+
)
|
|
618
|
+
continue
|
|
619
|
+
|
|
620
|
+
# Tier 2: Line break
|
|
621
|
+
if _is_newline(nxt):
|
|
622
|
+
if k + 1 > min_next_start:
|
|
623
|
+
best_by_tier[2] = _Candidate(
|
|
624
|
+
tier=2,
|
|
625
|
+
end_idx=k,
|
|
626
|
+
next_start=k + 1,
|
|
627
|
+
sep_tokens=tokens[k : k + 1],
|
|
628
|
+
state=sim_state.clone(),
|
|
629
|
+
ends_with_nl=ends_with_nl,
|
|
630
|
+
)
|
|
631
|
+
continue
|
|
632
|
+
|
|
633
|
+
# Tier 3: Sentence boundary
|
|
634
|
+
if _is_sentence_punct(tokens[k - 1]) and _is_horiz_ws(nxt):
|
|
635
|
+
ns = k
|
|
636
|
+
while ns < n_tokens and _is_horiz_ws(tokens[ns]):
|
|
637
|
+
ns += 1
|
|
638
|
+
if ns > min_next_start:
|
|
639
|
+
best_by_tier[3] = _Candidate(
|
|
640
|
+
tier=3,
|
|
641
|
+
end_idx=k,
|
|
642
|
+
next_start=ns,
|
|
643
|
+
sep_tokens=tokens[k:ns],
|
|
644
|
+
state=sim_state.clone(),
|
|
645
|
+
ends_with_nl=ends_with_nl,
|
|
646
|
+
)
|
|
647
|
+
continue
|
|
648
|
+
|
|
649
|
+
# Tier 4: Word boundary
|
|
650
|
+
if _is_horiz_ws(nxt) and (has_non_ws or not preserve_indent):
|
|
651
|
+
if not _is_horiz_ws(tokens[k - 1]):
|
|
652
|
+
ns = k
|
|
653
|
+
while ns < n_tokens and _is_horiz_ws(tokens[ns]):
|
|
654
|
+
ns += 1
|
|
655
|
+
if ns > min_next_start:
|
|
656
|
+
best_by_tier[4] = _Candidate(
|
|
657
|
+
tier=4,
|
|
658
|
+
end_idx=k,
|
|
659
|
+
next_start=ns,
|
|
660
|
+
sep_tokens=tokens[k:ns],
|
|
661
|
+
state=sim_state.clone(),
|
|
662
|
+
ends_with_nl=ends_with_nl,
|
|
663
|
+
)
|
|
664
|
+
continue
|
|
665
|
+
|
|
666
|
+
# Tier 5: Hard cut
|
|
667
|
+
if k > min_next_start:
|
|
668
|
+
best_by_tier[5] = _Candidate(
|
|
669
|
+
tier=5,
|
|
670
|
+
end_idx=k,
|
|
671
|
+
next_start=k,
|
|
672
|
+
sep_tokens=[],
|
|
673
|
+
state=sim_state.clone(),
|
|
674
|
+
ends_with_nl=ends_with_nl,
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
chosen: Optional[_Candidate] = None
|
|
678
|
+
for tier in (1, 2, 3, 4, 5):
|
|
679
|
+
if tier in best_by_tier:
|
|
680
|
+
chosen = best_by_tier[tier]
|
|
681
|
+
break
|
|
682
|
+
|
|
683
|
+
if chosen is None:
|
|
684
|
+
sim_state = open_state.as_inherited()
|
|
685
|
+
end_idx = max(start + 1, min_next_start + 1)
|
|
686
|
+
if end_idx > n_tokens:
|
|
687
|
+
end_idx = n_tokens
|
|
688
|
+
for idx in range(start, end_idx):
|
|
689
|
+
_advance_state(sim_state, tokens[idx])
|
|
690
|
+
while end_idx < n_tokens and sim_state.has_empty_new_wrapper():
|
|
691
|
+
_advance_state(sim_state, tokens[end_idx])
|
|
692
|
+
end_idx += 1
|
|
693
|
+
chosen = _Candidate(
|
|
694
|
+
tier=5,
|
|
695
|
+
end_idx=end_idx,
|
|
696
|
+
next_start=end_idx,
|
|
697
|
+
sep_tokens=[],
|
|
698
|
+
state=sim_state,
|
|
699
|
+
ends_with_nl=_is_newline(tokens[end_idx - 1]),
|
|
700
|
+
)
|
|
701
|
+
|
|
702
|
+
body = "".join(t.raw for t in tokens[start : chosen.end_idx])
|
|
703
|
+
close_suffix = chosen.state.close_suffix(chosen.ends_with_nl)
|
|
704
|
+
chunks.append(reopen_prefix + body + close_suffix)
|
|
705
|
+
|
|
706
|
+
next_open = chosen.state.as_inherited()
|
|
707
|
+
next_start = chosen.next_start
|
|
708
|
+
next_overlap_prefix_len = 0
|
|
709
|
+
|
|
710
|
+
if overlap > 0 and next_start < n_tokens:
|
|
711
|
+
next_reopen_len = cp_len(next_open.reopen_prefix())
|
|
712
|
+
next_close_len = next_open.close_len(False)
|
|
713
|
+
max_body_budget = effective_max_size - next_reopen_len - next_close_len
|
|
714
|
+
overlap_tokens = _compute_overlap_tokens(
|
|
715
|
+
tokens=tokens,
|
|
716
|
+
chunk_start=start,
|
|
717
|
+
split_end=chosen.end_idx,
|
|
718
|
+
next_start=next_start,
|
|
719
|
+
sep_tokens=chosen.sep_tokens,
|
|
720
|
+
overlap=overlap,
|
|
721
|
+
preserve_indent=next_open.preserve_indent(),
|
|
722
|
+
max_body_budget=max_body_budget,
|
|
723
|
+
)
|
|
724
|
+
if overlap_tokens:
|
|
725
|
+
next_overlap_prefix_len = len(overlap_tokens)
|
|
726
|
+
tokens = tokens[:next_start] + overlap_tokens + tokens[next_start:]
|
|
727
|
+
|
|
728
|
+
open_state = next_open
|
|
729
|
+
start = next_start
|
|
730
|
+
overlap_prefix_len = next_overlap_prefix_len
|
|
731
|
+
|
|
732
|
+
return chunks
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from safechunk import TARGET_LIMITS, chunk
|
|
8
|
+
|
|
9
|
+
FIXTURES_DIR = Path(__file__).resolve().parents[3] / "fixtures"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _load_cases(filename: str) -> list[dict[str, Any]]:
|
|
13
|
+
data = json.loads((FIXTURES_DIR / filename).read_text(encoding="utf-8"))
|
|
14
|
+
return list(data["cases"])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
ALL_CASES = _load_cases("basic.json") + _load_cases("edge_cases.json")
|
|
18
|
+
VALID_CASES = [c for c in ALL_CASES if not c.get("expected_error")]
|
|
19
|
+
ERROR_CASES = [c for c in ALL_CASES if c.get("expected_error")]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@pytest.mark.parametrize("case", VALID_CASES, ids=[c["id"] for c in VALID_CASES])
|
|
23
|
+
def test_shared_valid_fixtures(case: dict[str, Any]) -> None:
|
|
24
|
+
inp = dict(case["input"])
|
|
25
|
+
text = inp.pop("text")
|
|
26
|
+
result = chunk(text, **inp)
|
|
27
|
+
assert result == case["expected"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@pytest.mark.parametrize("case", ERROR_CASES, ids=[c["id"] for c in ERROR_CASES])
|
|
31
|
+
def test_shared_error_fixtures(case: dict[str, Any]) -> None:
|
|
32
|
+
inp = dict(case["input"])
|
|
33
|
+
text = inp.pop("text")
|
|
34
|
+
with pytest.raises(ValueError):
|
|
35
|
+
chunk(text, **inp)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_target_limits_defaults() -> None:
|
|
39
|
+
assert TARGET_LIMITS == {"telegram": 4096, "discord": 2000, "llm": 4000}
|
|
40
|
+
|
|
41
|
+
discord_text = "a" * 2005
|
|
42
|
+
discord_chunks = chunk(discord_text, target="discord")
|
|
43
|
+
assert [len(c) for c in discord_chunks] == [2000, 5]
|
|
44
|
+
|
|
45
|
+
telegram_text = "b" * 4100
|
|
46
|
+
telegram_chunks = chunk(telegram_text, target="telegram")
|
|
47
|
+
assert [len(c) for c in telegram_chunks] == [4096, 4]
|
|
48
|
+
|
|
49
|
+
llm_text = "c" * 4005
|
|
50
|
+
llm_chunks = chunk(llm_text)
|
|
51
|
+
assert [len(c) for c in llm_chunks] == [4000, 5]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_rejects_bool_arguments() -> None:
|
|
55
|
+
with pytest.raises(ValueError):
|
|
56
|
+
chunk("hello", max_size=True) # type: ignore[arg-type]
|
|
57
|
+
with pytest.raises(ValueError):
|
|
58
|
+
chunk("hello", max_size=10, overlap=True) # type: ignore[arg-type]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_oversized_single_grapheme_cluster() -> None:
|
|
62
|
+
# Family emoji has 7 code points; max_size=2 must emit it intact without infinite loop
|
|
63
|
+
assert chunk("๐จโ๐ฉโ๐งโ๐ฆ", max_size=2) == ["๐จโ๐ฉโ๐งโ๐ฆ"]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_html_pre_code_preserves_indent() -> None:
|
|
67
|
+
html_text = "<pre><code> a = 1\n b = 2\n c = 3</code></pre>"
|
|
68
|
+
# "<pre><code>" (11) + " a = 1" (9) + "</code></pre>" (13) == 33
|
|
69
|
+
res = chunk(html_text, max_size=33, format="html")
|
|
70
|
+
assert res == [
|
|
71
|
+
"<pre><code> a = 1</code></pre>",
|
|
72
|
+
"<pre><code> b = 2</code></pre>",
|
|
73
|
+
"<pre><code> c = 3</code></pre>",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_markdown_unclosed_fence_at_eof() -> None:
|
|
78
|
+
md_text = "```py\nline1\nline2\nline3"
|
|
79
|
+
res = chunk(md_text, max_size=18, format="markdown")
|
|
80
|
+
assert res == ["```py\nline1\n```", "```py\nline2\nline3"]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_overlap_clamping_guarantees_forward_progress() -> None:
|
|
84
|
+
res = chunk("abcdefghij klmnop", max_size=6, overlap=5)
|
|
85
|
+
assert len(res) >= 2
|
|
86
|
+
assert all(len(c) <= 6 for c in res)
|