llm-text 0.1.1

A Rust library for processing text for LLM consumption
Documentation
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
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
#[derive(Default)]
pub enum Newlines {
    Space,
    Single,
    #[default]
    TwoPlus,
    None,
}

/// Represents a single step in the text cleaning pipeline.
/// Each step processes a character and updates the cleaning state.
enum CleanStep {
    /// Character should be emitted as-is
    Emit(char),
    /// A whitespace character was encountered
    Whitespace,
    /// A newline sequence was encountered
    Newline(usize),
    /// An escaped whitespace/newline sequence was processed
    EscapedWhitespace,
    /// An escaped newline sequence was processed
    EscapedNewline,
    /// A citation was removed. If true, the next character is punctuation
    /// and we should remove the trailing space before it.
    CitationRemoved(bool),
    /// A non-citation bracket and its contents should be replayed
    ReplayNonCitation(Vec<char>),
}

/// Internal state for the single-pass text cleaner.
struct CleanState {
    result: String,
    consecutive_newlines: usize,
    last_was_space: bool,
}

impl CleanState {
    fn with_capacity(capacity: usize) -> Self {
        Self {
            result: String::with_capacity(capacity),
            consecutive_newlines: 0,
            last_was_space: false,
        }
    }
}

#[derive(Default)]
pub struct TextCleaner {
    pub newlines: Newlines,
    pub remove_non_basic_ascii: bool,
    pub remove_citations: bool,
}

impl TextCleaner {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn do_not_reduce_newlines(mut self) -> Self {
        self.newlines = Newlines::None;
        self
    }

    pub fn reduce_newlines_to_single_space(mut self) -> Self {
        self.newlines = Newlines::Space;
        self
    }

    pub fn reduce_newlines_to_single_newline(mut self) -> Self {
        self.newlines = Newlines::Single;
        self
    }

    pub fn reduce_newlines_to_double_newline(mut self) -> Self {
        self.newlines = Newlines::TwoPlus;
        self
    }

    pub fn remove_non_basic_ascii(mut self) -> Self {
        self.remove_non_basic_ascii = true;
        self
    }

    pub fn remove_citations(mut self) -> Self {
        self.remove_citations = true;
        self
    }

    /// Single-pass text cleaning with integrated citation removal, whitespace
    /// collapsing, and newline normalization. Uses a blacklist approach for
    /// character filtering to preserve all visible text including URLs, code,
    /// and multilingual content.
    pub fn run(&self, text: &str) -> String {
        let mut state = CleanState::with_capacity(text.len());
        let mut chars = text.chars().peekable();

        while let Some(c) = chars.next() {
            let step = self.classify_char(c, &mut chars);

            match step {
                CleanStep::Newline(count) => {
                    self.handle_newline(&mut state, count);
                }
                CleanStep::Whitespace => {
                    self.handle_whitespace(&mut state);
                }
                CleanStep::EscapedWhitespace => {
                    self.handle_escaped_whitespace(&mut state);
                }
                CleanStep::EscapedNewline => {
                    state.consecutive_newlines += 1;
                    state.last_was_space = false;
                }
                CleanStep::CitationRemoved(remove_trailing_space) => {
                    // Citation was already consumed in classify_char
                    // If the next character is punctuation, remove the trailing space
                    if remove_trailing_space && state.last_was_space && state.result.ends_with(' ')
                    {
                        state.result.pop();
                        state.last_was_space = false;
                    }
                }
                CleanStep::ReplayNonCitation(buf) => {
                    self.emit_newlines(&mut state);
                    for ch in buf {
                        state.result.push(ch);
                    }
                    state.last_was_space = false;
                }
                CleanStep::Emit(ch) => {
                    self.emit_newlines(&mut state);
                    if !self.remove_non_basic_ascii || is_valid_text_char(ch) {
                        state.result.push(ch);
                    }
                    state.last_was_space = false;
                }
            }
        }

        // Handle any trailing newlines
        if state.consecutive_newlines > 0 {
            self.emit_newlines(&mut state);
        }

        trim_trailing_spaces(&state.result)
    }

    /// Classify a character and return the appropriate cleaning step.
    fn classify_char(
        &self,
        c: char,
        chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
    ) -> CleanStep {
        match c {
            // Handle various newline sequences
            '\r' => {
                if chars.peek() == Some(&'\n') {
                    chars.next();
                }
                CleanStep::Newline(1)
            }
            '\n' | '\x0B' | '\x0C' | '\u{2028}' => CleanStep::Newline(1),
            '\u{2029}' => CleanStep::Newline(2),

            // Handle various whitespace characters
            ' ' |
            '\t' |
            '\u{00A0}' |
            '\u{1680}' |
            '\u{2000}'..='\u{200A}' |
            '\u{202F}' |
            '\u{205F}' |
            '\u{3000}' => CleanStep::Whitespace,

            // Handle escaped whitespace/newline sequences
            '\\' => self.classify_escape(chars),

            // Handle citations
            '[' if self.remove_citations => self.classify_citation(chars),

            // Regular character
            _ => CleanStep::Emit(c),
        }
    }

    /// Classify an escape sequence after backslash.
    fn classify_escape(&self, chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> CleanStep {
        if let Some(&next) = chars.peek() {
            match next {
                's' | 't' => {
                    chars.next();
                    CleanStep::EscapedWhitespace
                }
                'n' | 'r' => {
                    chars.next();
                    CleanStep::EscapedNewline
                }
                _ => CleanStep::Emit('\\'),
            }
        } else {
            CleanStep::Emit('\\')
        }
    }

    /// Classify a potential citation starting with '['.
    fn classify_citation(&self, chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> CleanStep {
        let mut buf = vec!['['];
        let mut is_citation = false;

        while let Some(&next) = chars.peek() {
            if next.is_ascii_digit() || next == ',' || next == '-' || next == ' ' {
                buf.push(next);
                chars.next();
            } else if next == ']' && buf.len() > 1 && buf[1..].iter().any(|b| b.is_ascii_digit()) {
                is_citation = true;
                chars.next();
                break;
            } else {
                break;
            }
        }

        if is_citation {
            // Check if the next character is punctuation - if so, we should
            // remove the trailing space before it
            let next_is_punctuation =
                chars.peek().is_some_and(|&c| matches!(c, '.' | ',' | '?' | '!' | ':' | ';'));
            CleanStep::CitationRemoved(next_is_punctuation)
        } else {
            CleanStep::ReplayNonCitation(buf)
        }
    }

    /// Handle a newline character by updating the consecutive newline count.
    fn handle_newline(&self, state: &mut CleanState, count: usize) {
        state.consecutive_newlines += count;
        state.last_was_space = false;
    }

    /// Handle a whitespace character, emitting pending newlines if needed.
    fn handle_whitespace(&self, state: &mut CleanState) {
        if state.consecutive_newlines > 0 {
            match self.newlines {
                Newlines::Space => {
                    state.result.push(' ');
                    state.consecutive_newlines = 0;
                    state.last_was_space = true;
                    return;
                }
                Newlines::Single => {
                    state.result.push('\n');
                    state.consecutive_newlines = 0;
                }
                Newlines::TwoPlus => {
                    let count = state.consecutive_newlines.min(2);
                    for _ in 0..count {
                        state.result.push('\n');
                    }
                    state.consecutive_newlines = 0;
                }
                Newlines::None => {
                    for _ in 0..state.consecutive_newlines {
                        state.result.push('\n');
                    }
                    state.consecutive_newlines = 0;
                }
            }
        }
        if !state.last_was_space {
            state.result.push(' ');
            state.last_was_space = true;
        }
    }

    /// Handle an escaped whitespace sequence (e.g., \s, \t).
    fn handle_escaped_whitespace(&self, state: &mut CleanState) {
        if !state.last_was_space && state.consecutive_newlines == 0 {
            state.result.push(' ');
            state.last_was_space = true;
        }
    }

    /// Emit accumulated newlines to the result buffer.
    fn emit_newlines(&self, state: &mut CleanState) {
        if state.consecutive_newlines == 0 {
            return;
        }
        match self.newlines {
            Newlines::Space => {
                state.result.push(' ');
            }
            Newlines::Single => {
                state.result.push('\n');
            }
            Newlines::TwoPlus => {
                let count = state.consecutive_newlines.min(2);
                for _ in 0..count {
                    state.result.push('\n');
                }
            }
            Newlines::None => {
                for _ in 0..state.consecutive_newlines {
                    state.result.push('\n');
                }
            }
        }
        state.consecutive_newlines = 0;
    }
}

/// Check if a character should be kept in cleaned text.
/// Uses a blacklist approach: only removes ASCII control characters (except
/// whitespace), preserving all visible text including Unicode, URLs, code, etc.
fn is_valid_text_char(c: char) -> bool {
    !(c.is_control() && c != '\t' && c != '\n' && c != '\r')
}

/// Trim leading whitespace, trailing spaces, and normalize trailing newlines to max 2.
fn trim_trailing_spaces(text: &str) -> String {
    let trimmed = text.trim_start();
    if trimmed.is_empty() {
        return String::new();
    }
    // Trim trailing spaces and tabs
    let trimmed = trimmed.trim_end_matches([' ', '\t']);
    // Count and normalize trailing newlines
    let newline_count = trimmed.chars().rev().take_while(|&c| c == '\n' || c == '\r').count();
    if newline_count == 0 {
        return trimmed.to_string();
    }
    let body = &trimmed[..trimmed.len() - newline_count];
    let clamped = newline_count.min(2);
    let mut result = String::with_capacity(body.len() + clamped);
    result.push_str(body);
    for _ in 0..clamped {
        result.push('\n');
    }
    result
}

/// Normalize whitespace in text using single-pass processing
pub fn normalize_whitespace(text: &str) -> String {
    TextCleaner::new().do_not_reduce_newlines().run(text)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_clean_to_single_spaces() {
        let ascii_text =
            "Ascii\tspaces here. Unicode\u{00A0}spaces here.\n And\nof course, newlines.\n\n";
        let ascii_result = "Ascii spaces here. Unicode spaces here. And of course, newlines.";
        assert_eq!(
            TextCleaner::new().reduce_newlines_to_single_space().run(ascii_text),
            ascii_result
        );
    }

    #[test]
    fn test_clean_to_single_newlines() {
        let ascii_text =
            "Ascii\tspaces here. Unicode\u{00A0}spaces here.\nAnd of course, newlines.\n\nCool.";
        let ascii_result =
            "Ascii spaces here. Unicode spaces here.\nAnd of course, newlines.\nCool.";
        assert_eq!(
            TextCleaner::new().reduce_newlines_to_single_newline().run(ascii_text),
            ascii_result
        );
    }

    #[test]
    fn test_clean_to_double_newlines() {
        let ascii_text = "Ascii\tspaces here. Unicode\u{00A0}spaces here.\n\nAscii\n\nparagraphs.\r\n\r\nUnicode\u{2029}paragraphs.\u{2029}\u{2028} Literal\\n\\nparagraphs.\\r\\n\\r\\n";
        let ascii_result = "Ascii spaces here. Unicode spaces here.\n\nAscii\n\nparagraphs.\n\nUnicode\n\nparagraphs.\n\n Literal\n\nparagraphs.\n\n";
        assert_eq!(
            TextCleaner::new().reduce_newlines_to_double_newline().run(ascii_text),
            ascii_result
        );
    }

    #[test]
    fn test_strip_control_chars() {
        // Blacklist approach: only control chars are removed, all visible text
        // including multilingual content is preserved
        let text_with_controls = "Hello\x00World\x01Test\u{00A0}Normal\u{2029}End";
        let expected = "HelloWorldTest Normal\n\nEnd";
        assert_eq!(
            TextCleaner::new()
                .do_not_reduce_newlines()
                .remove_non_basic_ascii()
                .run(text_with_controls),
            expected
        );
    }

    #[test]
    fn test_preserves_urls_and_code() {
        let text = "Visit https://example.com/path_to/file and run x = y + 1";
        let expected = "Visit https://example.com/path_to/file and run x = y + 1";
        assert_eq!(
            TextCleaner::new().do_not_reduce_newlines().remove_non_basic_ascii().run(text),
            expected
        );
    }

    #[test]
    fn test_preserves_multilingual_text() {
        let text = "Hello 世界 Bonne année Привет";
        assert_eq!(
            TextCleaner::new().do_not_reduce_newlines().remove_non_basic_ascii().run(text),
            text
        );
    }

    #[test]
    fn test_normalize_whitespace() {
        let ascii_text = "Ascii\tspaces here. Unicode\u{00A0}spaces here. Literal\\sspaces\\t.";
        let ascii_result = "Ascii spaces here. Unicode spaces here. Literal spaces .";
        assert_eq!(normalize_whitespace(ascii_text), ascii_result);

        let ascii_text =
            "Ascii\nnewlines\n. Unicode\u{2028}newlines.\u{2028}. Literal\\nnewlines.\\n";
        let ascii_result = "Ascii\nnewlines\n. Unicode\nnewlines.\n. Literal\nnewlines.\n";
        assert_eq!(normalize_whitespace(ascii_text), ascii_result);

        let ascii_text = "Ascii\n\nparagraphs\r\n\r\n.Unicode\u{2029}paragraphs.\u{2029} Literal\\n\\nparagraphs.\\r\\n\\r\\n";
        let result = normalize_whitespace(ascii_text);
        let ascii_result =
            "Ascii\n\nparagraphs\n\n.Unicode\n\nparagraphs.\n\n Literal\n\nparagraphs.\n\n";
        assert_eq!(result, ascii_result);
    }

    #[test]
    fn test_remove_compound_citations() {
        let text = "Studies show this [1, 2] and also [3-5] plus [6, 7, 8].";
        let expected = "Studies show this and also plus.";
        assert_eq!(TextCleaner::new().remove_citations().run(text), expected);
    }

    #[test]
    fn test_preserves_non_citation_brackets() {
        let text = "Array [1, 2, 3] and link [click here] are not citations.";
        let expected = "Array and link [click here] are not citations.";
        assert_eq!(TextCleaner::new().remove_citations().run(text), expected);
    }

    #[test]
    fn test_preserves_markdown_links() {
        let text = "See [this link](https://example.com) for details.";
        let expected = "See [this link](https://example.com) for details.";
        assert_eq!(TextCleaner::new().remove_citations().run(text), expected);
    }
}