troupekit_context/
chunk.rs1use crate::error::ContextError;
2use crate::text::CHARS_PER_TOKEN;
3
4const PARAGRAPH_SEP: &str = "\n\n";
5const SPACE_SEP: &str = " ";
6const NO_SEP: &str = "";
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ChunkConfig {
13 pub max_tokens: usize,
14 pub overlap_tokens: usize,
15}
16
17struct Unit {
21 sep: &'static str,
22 text: String,
23}
24
25pub fn chunk(text: &str, cfg: &ChunkConfig) -> Result<Vec<String>, ContextError> {
30 if cfg.max_tokens == 0 {
31 return Err(ContextError::Invalid("max_tokens must be positive".into()));
32 }
33 if cfg.overlap_tokens >= cfg.max_tokens {
34 return Err(ContextError::Invalid("overlap_tokens must be below max_tokens".into()));
35 }
36 let max = cfg.max_tokens.checked_mul(CHARS_PER_TOKEN).ok_or_else(|| ContextError::Invalid("max_tokens too large".into()))?;
37 let overlap = cfg.overlap_tokens * CHARS_PER_TOKEN;
38 let piece = max - overlap - 1;
39 let mut chunks = Vec::new();
40 let mut cur = String::new();
41 for unit in units(text, max, piece) {
42 let unit_len = char_len(&unit.text);
43 if cur.is_empty() {
44 cur = unit.text;
45 continue;
46 }
47 if char_len(&cur) + unit.sep.len() + unit_len <= max {
48 cur.push_str(unit.sep);
49 cur.push_str(&unit.text);
50 continue;
51 }
52 let tail = overlap_tail(&cur, overlap);
53 chunks.push(std::mem::take(&mut cur));
54 cur = if !tail.is_empty() && char_len(&tail) + unit.sep.len() + unit_len <= max {
55 format!("{tail}{}{}", unit.sep, unit.text)
56 } else {
57 unit.text
58 };
59 }
60 if !cur.is_empty() {
61 chunks.push(cur);
62 }
63 for c in &chunks {
64 assert!(!c.is_empty() && char_len(c) <= max, "chunk outside its limit");
65 }
66 Ok(chunks)
67}
68
69fn char_len(s: &str) -> usize {
73 s.chars().count()
74}
75
76fn units(text: &str, max: usize, piece: usize) -> Vec<Unit> {
80 let mut out = Vec::new();
81 for para in paragraphs(text) {
82 if char_len(¶) <= max {
83 out.push(Unit { sep: PARAGRAPH_SEP, text: para });
84 continue;
85 }
86 for (i, (sentence, sep)) in sentences(¶).into_iter().enumerate() {
87 let sep = if i == 0 { PARAGRAPH_SEP } else { sep };
88 if char_len(&sentence) <= max {
89 out.push(Unit { sep, text: sentence });
90 continue;
91 }
92 for (j, word) in sentence.split_whitespace().enumerate() {
93 let sep = if j == 0 { sep } else { SPACE_SEP };
94 if char_len(word) <= max {
95 out.push(Unit { sep, text: word.to_string() });
96 continue;
97 }
98 let chars: Vec<char> = word.chars().collect();
99 for (k, window) in chars.chunks(piece).enumerate() {
100 out.push(Unit { sep: if k == 0 { sep } else { NO_SEP }, text: window.iter().collect() });
101 }
102 }
103 }
104 }
105 out
106}
107
108fn paragraphs(text: &str) -> Vec<String> {
112 let mut out = Vec::new();
113 let mut lines: Vec<&str> = Vec::new();
114 for line in text.lines().chain(std::iter::once("")) {
115 if line.trim().is_empty() {
116 let para = lines.join("\n").trim().to_string();
117 if !para.is_empty() {
118 out.push(para);
119 }
120 lines.clear();
121 } else {
122 lines.push(line.trim_end());
123 }
124 }
125 out
126}
127
128fn sentences(para: &str) -> Vec<(String, &'static str)> {
132 let mut out = Vec::new();
133 let mut buf = String::new();
134 let mut sep = NO_SEP;
135 let mut chars = para.chars().peekable();
136 while let Some(c) = chars.next() {
137 buf.push(c);
138 let next = chars.peek().copied();
139 let ends = matches!(c, '。' | '!' | '?') || (matches!(c, '.' | '!' | '?') && next.is_none_or(char::is_whitespace));
140 if ends {
141 let sentence = buf.trim().to_string();
142 if !sentence.is_empty() {
143 out.push((sentence, sep));
144 }
145 buf.clear();
146 sep = if next.is_some_and(char::is_whitespace) { SPACE_SEP } else { NO_SEP };
147 }
148 }
149 let rest = buf.trim().to_string();
150 if !rest.is_empty() {
151 out.push((rest, sep));
152 }
153 out
154}
155
156fn overlap_tail(chunk: &str, overlap: usize) -> String {
160 if overlap == 0 {
161 return String::new();
162 }
163 let start = char_len(chunk).saturating_sub(overlap);
164 let tail: String = chunk.chars().skip(start).collect();
165 match tail.find(char::is_whitespace) {
166 Some(i) if start > 0 => tail[i..].trim_start().to_string(),
167 _ => tail,
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 fn cfg(max_tokens: usize, overlap_tokens: usize) -> ChunkConfig {
176 ChunkConfig { max_tokens, overlap_tokens }
177 }
178
179 fn len(s: &str) -> usize {
180 s.chars().count()
181 }
182
183 fn shares_overlap(prev: &str, next: &str) -> bool {
184 let next: Vec<char> = next.chars().collect();
185 (1..=next.len()).any(|k| prev.ends_with(&next[..k].iter().collect::<String>()))
186 }
187
188 #[test]
189 fn empty_and_blank_give_no_chunks() {
190 assert!(chunk("", &cfg(10, 2)).unwrap().is_empty());
191 assert!(chunk(" \n\n \t", &cfg(10, 2)).unwrap().is_empty());
192 }
193
194 #[test]
195 fn rejects_bad_config() {
196 assert!(matches!(chunk("a", &cfg(0, 0)), Err(ContextError::Invalid(_))));
197 assert!(matches!(chunk("a", &cfg(5, 5)), Err(ContextError::Invalid(_))));
198 assert!(matches!(chunk("a", &cfg(5, 9)), Err(ContextError::Invalid(_))));
199 }
200
201 #[test]
202 fn small_paragraphs_pack_into_one_chunk() {
203 assert_eq!(chunk("a b.\n\n \nc d.", &cfg(100, 10)).unwrap(), vec!["a b.\n\nc d."]);
204 }
205
206 #[test]
207 fn splits_long_paragraph_on_sentences_with_overlap() {
208 let sentences: Vec<String> = (0..10).map(|i| format!("Sentence number {i} talks about protein intake.")).collect();
209 let text = sentences.join(" ");
210 let chunks = chunk(&text, &cfg(25, 5)).unwrap();
211 assert!(chunks.len() > 1);
212 for c in &chunks {
213 assert!(len(c) <= 100, "chunk too long: {c}");
214 }
215 for pair in chunks.windows(2) {
216 assert!(shares_overlap(&pair[0], &pair[1]), "no overlap between {:?} and {:?}", pair[0], pair[1]);
217 }
218 for s in &sentences {
219 assert!(chunks.iter().any(|c| c.contains(s.as_str())), "lost sentence {s}");
220 }
221 }
222
223 #[test]
224 fn huge_paragraph_without_boundaries_is_hard_split() {
225 let text: String = (0..5000).map(|i| char::from(b'0' + (i % 7) as u8)).collect();
226 let chunks = chunk(&text, &cfg(50, 10)).unwrap();
227 assert!(chunks.len() > 1);
228 let mut rebuilt = chunks[0].clone();
229 for c in &chunks {
230 assert!(len(c) <= 200);
231 }
232 for pair in chunks.windows(2) {
233 let tail: String = pair[0].chars().skip(len(&pair[0]) - 40).collect();
234 assert!(pair[1].starts_with(&tail));
235 rebuilt.push_str(&pair[1][tail.len()..]);
236 }
237 assert_eq!(rebuilt, text);
238 }
239
240 #[test]
241 fn long_sentence_with_spaces_splits_on_words() {
242 let text = vec!["word"; 300].join(" ");
243 let chunks = chunk(&text, &cfg(20, 4)).unwrap();
244 for c in &chunks {
245 assert!(len(c) <= 80);
246 assert!(c.split(' ').all(|w| w == "word"), "cut inside a word: {c}");
247 }
248 }
249
250 #[test]
251 fn unicode_never_splits_code_points() {
252 let text = format!("{}\n\n{}", "日本語の文章です。".repeat(300), "😀".repeat(500));
253 let chunks = chunk(&text, &cfg(30, 5)).unwrap();
254 for c in &chunks {
255 assert!(len(c) <= 120);
256 }
257 let cjk: Vec<&String> = chunks.iter().filter(|c| c.contains('日') && !c.contains('😀')).collect();
258 assert!(cjk.len() > 1);
259 for c in &cjk {
260 assert!(c.ends_with('。'), "sentence cut: {c}");
261 assert!(!c.contains(' '));
262 }
263 let emoji: usize = chunks.iter().map(|c| c.matches('😀').count()).sum();
264 assert!(emoji >= 500);
265 }
266
267 #[test]
268 fn deterministic() {
269 let text = "One. Two! Three?\n\nFour five six. ".repeat(40);
270 assert_eq!(chunk(&text, &cfg(12, 3)).unwrap(), chunk(&text, &cfg(12, 3)).unwrap());
271 }
272}