scirs2-text 0.4.3

Text processing module for SciRS2 (scirs2-text)
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
456
457
458
459
460
461
462
463
464
465
466
//! Unicode normalization and language-agnostic tokenization utilities.
//!
//! Provides:
//! - [`Script`]: Unicode script detection for individual characters.
//! - [`UnicodeNormalizer`]: NFC/NFD normalization, accent stripping, case folding.
//! - Language-agnostic tokenization that handles CJK character segmentation.

use unicode_normalization::UnicodeNormalization;

// ─── Script detection ─────────────────────────────────────────────────────────

/// Unicode script classification for a single character.
///
/// Used to determine whether whitespace should be inserted around individual
/// characters (e.g. CJK) or whether a word-based tokenization strategy is
/// appropriate.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Script {
    /// Latin characters (includes Latin Extended).
    Latin,
    /// CJK Unified Ideographs and related blocks.
    Cjk,
    /// Cyrillic script.
    Cyrillic,
    /// Arabic script.
    Arabic,
    /// Devanagari script (used for Hindi, Sanskrit, etc.).
    Devanagari,
    /// Hebrew script.
    Hebrew,
    /// Any script not listed above.
    Other,
}

/// Detect the [`Script`] for a single Unicode character.
///
/// Uses Unicode block ranges.  Characters that straddle multiple blocks
/// (e.g. punctuation) fall into [`Script::Other`].
pub fn detect_script(c: char) -> Script {
    let cp = c as u32;

    // CJK ranges
    if (0x4E00..=0x9FFF).contains(&cp)   // CJK Unified Ideographs
        || (0x3400..=0x4DBF).contains(&cp)  // CJK Extension A
        || (0x20000..=0x2A6DF).contains(&cp) // CJK Extension B
        || (0x2A700..=0x2B73F).contains(&cp) // CJK Extension C
        || (0x2B740..=0x2B81F).contains(&cp) // CJK Extension D
        || (0x2B820..=0x2CEAF).contains(&cp) // CJK Extension E
        || (0xF900..=0xFAFF).contains(&cp)  // CJK Compatibility Ideographs
        || (0x2F800..=0x2FA1F).contains(&cp) // CJK Compatibility Supplement
        || (0x3000..=0x303F).contains(&cp)  // CJK Symbols and Punctuation
        || (0x3040..=0x309F).contains(&cp)  // Hiragana
        || (0x30A0..=0x30FF).contains(&cp)
    // Katakana
    {
        return Script::Cjk;
    }

    // Cyrillic U+0400–U+04FF
    if (0x0400..=0x04FF).contains(&cp) {
        return Script::Cyrillic;
    }

    // Arabic U+0600–U+06FF
    if (0x0600..=0x06FF).contains(&cp) {
        return Script::Arabic;
    }

    // Devanagari U+0900–U+097F
    if (0x0900..=0x097F).contains(&cp) {
        return Script::Devanagari;
    }

    // Hebrew U+0590–U+05FF
    if (0x0590..=0x05FF).contains(&cp) {
        return Script::Hebrew;
    }

    // Latin: Basic Latin letters + Latin-1 Supplement + Latin Extended-A/B
    if (0x0041..=0x005A).contains(&cp)   // A-Z
        || (0x0061..=0x007A).contains(&cp) // a-z
        || (0x00C0..=0x00D6).contains(&cp)
        || (0x00D8..=0x00F6).contains(&cp)
        || (0x00F8..=0x024F).contains(&cp)
    // Latin Extended-A and B
    {
        return Script::Latin;
    }

    Script::Other
}

// ─── NormForm ─────────────────────────────────────────────────────────────────

/// Unicode normalization form.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NormForm {
    /// Canonical Decomposition, followed by Canonical Composition (NFC).
    Nfc,
    /// Canonical Decomposition (NFD).
    Nfd,
}

// ─── UnicodeNormalizerConfig ───────────────────────────────────────────────────

/// Configuration for [`UnicodeNormalizer`].
#[derive(Debug, Clone)]
pub struct UnicodeNormalizerConfig {
    /// Normalization form to apply.
    pub form: NormForm,
    /// Strip combining diacritical marks (accent removal).
    pub strip_accents: bool,
    /// Fold all characters to lowercase.
    pub lowercase: bool,
    /// Insert whitespace around CJK characters to facilitate word splitting.
    pub tokenize_cjk: bool,
}

impl Default for UnicodeNormalizerConfig {
    fn default() -> Self {
        UnicodeNormalizerConfig {
            form: NormForm::Nfc,
            strip_accents: false,
            lowercase: false,
            tokenize_cjk: true,
        }
    }
}

// ─── UnicodeNormalizer ────────────────────────────────────────────────────────

/// Unicode-aware text normalizer.
///
/// Supports NFC/NFD normalization, accent stripping, case folding, and
/// language-agnostic CJK tokenization.
///
/// # Example
///
/// ```rust
/// use scirs2_text::tokenization::unicode_normalizer::{UnicodeNormalizer, UnicodeNormalizerConfig, NormForm};
///
/// let config = UnicodeNormalizerConfig {
///     form: NormForm::Nfc,
///     strip_accents: true,
///     lowercase: true,
///     tokenize_cjk: true,
/// };
/// let normalizer = UnicodeNormalizer::new(config);
/// let tokens = normalizer.tokenize_language_agnostic("Héllo 世界");
/// assert!(tokens.len() >= 3); // "hello", "世", "界"
/// ```
#[derive(Debug, Clone)]
pub struct UnicodeNormalizer {
    config: UnicodeNormalizerConfig,
}

impl UnicodeNormalizer {
    /// Create a new [`UnicodeNormalizer`] with the given configuration.
    pub fn new(config: UnicodeNormalizerConfig) -> Self {
        UnicodeNormalizer { config }
    }

    /// Create a normalizer with default settings.
    pub fn default_normalizer() -> Self {
        UnicodeNormalizer::new(UnicodeNormalizerConfig::default())
    }

    /// Normalize `text` according to the configuration.
    ///
    /// Steps applied in order:
    /// 1. Lowercase (if configured)
    /// 2. NFD decomposition + accent stripping (if configured)
    /// 3. NFC composition (if configured, after potential NFD strip)
    pub fn normalize(&self, text: &str) -> String {
        // Step 1: Lowercase
        let s = if self.config.lowercase {
            text.to_lowercase()
        } else {
            text.to_owned()
        };

        // Step 2 & 3: Normalize form + optional accent strip
        match self.config.form {
            NormForm::Nfd => {
                if self.config.strip_accents {
                    // NFD then remove combining marks
                    s.nfd().filter(|&c| !is_combining_diacritic(c)).collect()
                } else {
                    s.nfd().collect()
                }
            }
            NormForm::Nfc => {
                if self.config.strip_accents {
                    // NFD decompose → strip accents → NFC recompose
                    let stripped: String =
                        s.nfd().filter(|&c| !is_combining_diacritic(c)).collect();
                    stripped.nfc().collect()
                } else {
                    s.nfc().collect()
                }
            }
        }
    }

    /// Tokenize `text` in a language-agnostic manner.
    ///
    /// Algorithm:
    /// 1. Normalize the text.
    /// 2. Insert whitespace around CJK characters (when `tokenize_cjk` is set).
    /// 3. Split on Unicode whitespace.
    /// 4. Filter empty tokens.
    ///
    /// This approach works across scripts without any language-specific logic.
    pub fn tokenize_language_agnostic(&self, text: &str) -> Vec<String> {
        let normalized = self.normalize(text);

        let mut spaced = String::with_capacity(normalized.len() * 2);
        for ch in normalized.chars() {
            if self.config.tokenize_cjk && is_cjk_character(ch) {
                // Surround each CJK character with spaces so it becomes its own token
                spaced.push(' ');
                spaced.push(ch);
                spaced.push(' ');
            } else {
                spaced.push(ch);
            }
        }

        spaced
            .split(|c: char| c.is_whitespace())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_owned())
            .collect()
    }

    /// Return the configuration.
    pub fn config(&self) -> &UnicodeNormalizerConfig {
        &self.config
    }
}

impl Default for UnicodeNormalizer {
    fn default() -> Self {
        UnicodeNormalizer::new(UnicodeNormalizerConfig::default())
    }
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Return `true` for Unicode combining diacritical marks (U+0300–U+036F and
/// related blocks).
fn is_combining_diacritic(ch: char) -> bool {
    let cp = ch as u32;
    // Combining Diacritical Marks
    (0x0300..=0x036F).contains(&cp)
    // Combining Diacritical Marks Supplement
    || (0x1DC0..=0x1DFF).contains(&cp)
    // Combining Diacritical Marks Extended
    || (0x1AB0..=0x1AFF).contains(&cp)
    // Combining Half Marks
    || (0xFE20..=0xFE2F).contains(&cp)
}

/// Return `true` for CJK characters that should be individually tokenized.
fn is_cjk_character(ch: char) -> bool {
    let cp = ch as u32;
    (0x4E00..=0x9FFF).contains(&cp)
        || (0x3400..=0x4DBF).contains(&cp)
        || (0x20000..=0x2A6DF).contains(&cp)
        || (0x2A700..=0x2B73F).contains(&cp)
        || (0x2B740..=0x2B81F).contains(&cp)
        || (0x2B820..=0x2CEAF).contains(&cp)
        || (0xF900..=0xFAFF).contains(&cp)
        || (0x2F800..=0x2FA1F).contains(&cp)
        || (0x3040..=0x309F).contains(&cp) // Hiragana
        || (0x30A0..=0x30FF).contains(&cp) // Katakana
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    // ── detect_script ───────────────────────────────────────────────────

    #[test]
    fn test_detect_script_latin() {
        assert_eq!(detect_script('a'), Script::Latin);
        assert_eq!(detect_script('Z'), Script::Latin);
        assert_eq!(detect_script('é'), Script::Latin); // U+00E9 Latin Small Letter E with Acute
    }

    #[test]
    fn test_detect_script_cjk() {
        assert_eq!(detect_script(''), Script::Cjk); // U+4E2D
        assert_eq!(detect_script(''), Script::Cjk); // U+65E5
        assert_eq!(detect_script(''), Script::Cjk); // U+8A9E
    }

    #[test]
    fn test_detect_script_cyrillic() {
        assert_eq!(detect_script('А'), Script::Cyrillic); // U+0410
        assert_eq!(detect_script('я'), Script::Cyrillic); // U+044F
    }

    #[test]
    fn test_detect_script_arabic() {
        assert_eq!(detect_script('ع'), Script::Arabic); // U+0639
        assert_eq!(detect_script('م'), Script::Arabic); // U+0645
    }

    #[test]
    fn test_detect_script_devanagari() {
        assert_eq!(detect_script(''), Script::Devanagari); // U+0915
        assert_eq!(detect_script(''), Script::Devanagari); // U+093E
    }

    #[test]
    fn test_detect_script_hebrew() {
        assert_eq!(detect_script('א'), Script::Hebrew); // U+05D0
        assert_eq!(detect_script('ש'), Script::Hebrew); // U+05E9
    }

    #[test]
    fn test_detect_script_other() {
        assert_eq!(detect_script('!'), Script::Other);
        assert_eq!(detect_script(' '), Script::Other);
        assert_eq!(detect_script('1'), Script::Other);
    }

    // ── UnicodeNormalizer::normalize ────────────────────────────────────

    #[test]
    fn test_normalize_lowercase() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            lowercase: true,
            ..Default::default()
        });
        assert_eq!(n.normalize("Hello WORLD"), "hello world");
    }

    #[test]
    fn test_normalize_no_lowercase() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            lowercase: false,
            ..Default::default()
        });
        assert_eq!(n.normalize("Hello WORLD"), "Hello WORLD");
    }

    #[test]
    fn test_normalize_strip_accents_nfc() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            form: NormForm::Nfc,
            strip_accents: true,
            lowercase: false,
            tokenize_cjk: false,
        });
        // "café" → "cafe"
        let result = n.normalize("café");
        assert_eq!(result, "cafe");
    }

    #[test]
    fn test_normalize_strip_accents_nfd() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            form: NormForm::Nfd,
            strip_accents: true,
            lowercase: false,
            tokenize_cjk: false,
        });
        let result = n.normalize("résumé");
        assert_eq!(result, "resume");
    }

    #[test]
    fn test_normalize_nfc_idempotent_on_ascii() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            form: NormForm::Nfc,
            strip_accents: false,
            lowercase: false,
            tokenize_cjk: false,
        });
        let text = "hello world 123";
        assert_eq!(n.normalize(text), text);
    }

    // ── tokenize_language_agnostic ───────────────────────────────────────

    #[test]
    fn test_cjk_chars_split() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            tokenize_cjk: true,
            lowercase: false,
            strip_accents: false,
            form: NormForm::Nfc,
        });
        let tokens = n.tokenize_language_agnostic("Hello世界");
        // "Hello" should be one token; "世" and "界" should each be their own
        assert!(tokens.contains(&"Hello".to_string()), "got: {:?}", tokens);
        assert!(tokens.contains(&"".to_string()), "got: {:?}", tokens);
        assert!(tokens.contains(&"".to_string()), "got: {:?}", tokens);
    }

    #[test]
    fn test_cjk_split_mixed_text() {
        let n = UnicodeNormalizer::default();
        let tokens = n.tokenize_language_agnostic("我 love Rust");
        // "我" is CJK and should be its own token
        assert!(tokens.iter().any(|t| t == ""), "got: {:?}", tokens);
        assert!(tokens.iter().any(|t| t == "love"), "got: {:?}", tokens);
        assert!(tokens.iter().any(|t| t == "Rust"), "got: {:?}", tokens);
    }

    #[test]
    fn test_tokenize_latin_only() {
        let n = UnicodeNormalizer::default();
        let tokens = n.tokenize_language_agnostic("the quick brown fox");
        assert_eq!(tokens, vec!["the", "quick", "brown", "fox"]);
    }

    #[test]
    fn test_tokenize_empty() {
        let n = UnicodeNormalizer::default();
        let tokens = n.tokenize_language_agnostic("   ");
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_tokenize_with_lowercase_and_accent_strip() {
        let n = UnicodeNormalizer::new(UnicodeNormalizerConfig {
            form: NormForm::Nfc,
            strip_accents: true,
            lowercase: true,
            tokenize_cjk: true,
        });
        let tokens = n.tokenize_language_agnostic("Héllo Wörld");
        assert!(tokens.iter().any(|t| t == "hello"), "got: {:?}", tokens);
        assert!(tokens.iter().any(|t| t == "world"), "got: {:?}", tokens);
    }

    #[test]
    fn test_combining_mark_detection() {
        // U+0301 is COMBINING ACUTE ACCENT — a combining diacritic
        assert!(is_combining_diacritic('\u{0301}'));
        assert!(is_combining_diacritic('\u{0300}'));
        assert!(is_combining_diacritic('\u{036F}'));
        // Regular ASCII should not be diacritics
        assert!(!is_combining_diacritic('a'));
        assert!(!is_combining_diacritic('é')); // precomposed — single codepoint
    }

    #[test]
    fn test_cjk_character_detection() {
        assert!(is_cjk_character(''));
        assert!(is_cjk_character(''));
        assert!(is_cjk_character('')); // Hiragana
        assert!(is_cjk_character('')); // Katakana
        assert!(!is_cjk_character('a'));
        assert!(!is_cjk_character('1'));
        assert!(!is_cjk_character(' '));
    }
}