forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_chunker.py
More file actions
250 lines (190 loc) · 6.31 KB
/
Copy pathtext_chunker.py
File metadata and controls
250 lines (190 loc) · 6.31 KB
1
2
3
4
5
6
7
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
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
# Copyright (c) Microsoft. All rights reserved.
"""
Split text in chunks, attempting to leave meaning intact.
For plain text, split looking at new lines first, then periods, and so on.
For markdown, split looking at punctuation first, and so on.
"""
import os
from typing import List
NEWLINE = os.linesep
TEXT_SPLIT_OPTIONS = [
["\n", "\r"],
["."],
["?", "!"],
[";"],
[":"],
[","],
[")", "]", "}"],
[" "],
["-"],
None,
]
MD_SPLIT_OPTIONS = [
["."],
["?", "!"],
[";"],
[":"],
[","],
[")", "]", "}"],
[" "],
["-"],
["\n", "\r"],
None,
]
def split_plaintext_lines(text: str, max_token_per_line: int) -> List[str]:
"""
Split plain text into lines.
it will split on new lines first, and then on punctuation.
"""
return _split_text_lines(text, max_token_per_line, True)
def split_markdown_lines(text: str, max_token_per_line: int) -> List[str]:
"""
Split markdown into lines.
It will split on punctuation first, and then on space and new lines.
"""
return _split_markdown_lines(text, max_token_per_line, True)
def split_plaintext_paragraph(text: List[str], max_tokens: int) -> List[str]:
"""
Split plain text into paragraphs.
"""
split_lines = []
for line in text:
split_lines.extend(_split_text_lines(line, max_tokens, True))
return _split_text_paragraph(split_lines, max_tokens)
def split_markdown_paragraph(text: List[str], max_tokens: int) -> List[str]:
"""
Split markdown into paragraphs.
"""
split_lines = []
for line in text:
split_lines.extend(_split_markdown_lines(line, max_tokens, False))
return _split_text_paragraph(split_lines, max_tokens)
def _split_text_paragraph(text: List[str], max_tokens: int) -> List[str]:
"""
Split text into paragraphs.
"""
if not text:
return []
paragraphs = []
current_paragraph = []
for line in text:
num_tokens_line = _token_count(line)
num_tokens_paragraph = _token_count("".join(current_paragraph))
if (
num_tokens_paragraph + num_tokens_line + 1 >= max_tokens
and len(current_paragraph) > 0
):
paragraphs.append("".join(current_paragraph).strip())
current_paragraph = []
current_paragraph.append(f"{line}{NEWLINE}")
if len(current_paragraph) > 0:
paragraphs.append("".join(current_paragraph).strip())
current_paragraph = []
# Distribute text more evenly in the last paragraphs
# when the last paragraph is too short.
if len(paragraphs) > 1:
last_para = paragraphs[-1]
sec_last_para = paragraphs[-2]
if _token_count(last_para) < max_tokens / 4:
last_para_tokens = last_para.split(" ")
sec_last_para_tokens = sec_last_para.split(" ")
last_para_token_count = len(last_para_tokens)
sec_last_para_token_count = len(sec_last_para_tokens)
if last_para_token_count + sec_last_para_token_count <= max_tokens:
sec_last_para = " ".join(sec_last_para_tokens) + NEWLINE
last_para = " ".join(last_para_tokens)
new_sec_last_para = sec_last_para + last_para
paragraphs[-2] = new_sec_last_para.strip()
paragraphs.pop()
return paragraphs
def _split_markdown_lines(text: str, max_token_per_line: int, trim: bool) -> List[str]:
"""
Split markdown into lines.
"""
lines = _split_str_lines(text, max_token_per_line, MD_SPLIT_OPTIONS, trim)
return lines
def _split_text_lines(text: str, max_token_per_line: int, trim: bool) -> List[str]:
"""
Split text into lines.
"""
lines = _split_str_lines(text, max_token_per_line, TEXT_SPLIT_OPTIONS, trim)
return lines
def _split_str_lines(
text: str, max_tokens: int, separators: List[List[str]], trim: bool
) -> List[str]:
if not text:
return []
text = text.replace("\r\n", "\n")
lines = []
was_split = False
for split_option in separators:
if not lines:
lines, was_split = _split_str(text, max_tokens, split_option, trim)
else:
lines, was_split = _split_list(lines, max_tokens, split_option, trim)
if not was_split:
break
return lines
def _split_str(
text: str, max_tokens: int, separators: List[str], trim: bool
) -> List[str]:
"""
Split text into lines.
"""
if not text:
return []
input_was_split = False
text = text.strip() if trim else text
text_as_is = [text]
if _token_count(text) <= max_tokens:
return text_as_is, input_was_split
input_was_split = True
half = int(len(text) / 2)
cutpoint = -1
if not separators:
cutpoint = half
elif set(separators) & set(text) and len(text) > 2:
for index, text_char in enumerate(text):
if text_char not in separators:
continue
if abs(half - index) < abs(half - cutpoint):
cutpoint = index + 1
else:
return text_as_is, input_was_split
if 0 < cutpoint < len(text):
lines = []
first_split, has_split1 = _split_str(
text[:cutpoint], max_tokens, separators, trim
)
second_split, has_split2 = _split_str(
text[cutpoint:], max_tokens, separators, trim
)
lines.extend(first_split)
lines.extend(second_split)
input_was_split = has_split1 or has_split2
else:
return text_as_is, input_was_split
return lines, input_was_split
def _split_list(
text: List[str], max_tokens: int, separators: List[str], trim: bool
) -> List[str]:
"""
Split list of sring into lines.
"""
if not text:
return []
lines = []
input_was_split = False
for line in text:
split_str, was_split = _split_str(line, max_tokens, separators, trim)
lines.extend(split_str)
input_was_split = input_was_split or was_split
return lines, input_was_split
def _token_count(text: str) -> int:
"""
Count the number of tokens in a string.
TODO: chunking methods should be configurable to allow for different
tokenization strategies depending on the model to be called.
For now, we use an extremely rough estimate.
"""
return int(len(text) / 4)