libgrammstein 0.1.0

Hybrid language model (N-gram + Embeddings) for WFST text correction
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Text preprocessing for corpus normalization.
//!
//! This module provides configurable text preprocessing to normalize text
//! before training language models. Preprocessing steps include:
//!
//! - Number normalization (digits -> `<NUM>`)
//! - URL normalization (URLs -> `<URL>`)
//! - Email normalization (emails -> `<EMAIL>`)
//! - Contraction expansion ("can't" -> "cannot")
//! - Unicode normalization (NFC/NFD/NFKC/NFKD)
//! - Whitespace normalization
//!
//! # Example
//!
//! ```ignore
//! use libgrammstein::corpus::TextPreprocessor;
//!
//! let preprocessor = TextPreprocessor::builder()
//!     .normalize_numbers(true)
//!     .normalize_urls(true)
//!     .expand_contractions(true)
//!     .build();
//!
//! let text = "I can't visit https://example.com in 2024.";
//! let normalized = preprocessor.process(text);
//! // Result: "I cannot visit <URL> in <NUM>."
//! ```

use lazy_static::lazy_static;
use regex::Regex;
use unicode_normalization::UnicodeNormalization;

/// Special tokens used for normalization.
pub mod tokens {
    /// Token for normalized numbers.
    pub const NUM: &str = "<NUM>";
    /// Token for normalized URLs.
    pub const URL: &str = "<URL>";
    /// Token for normalized emails.
    pub const EMAIL: &str = "<EMAIL>";
    /// Token for normalized usernames/mentions.
    pub const USER: &str = "<USER>";
    /// Token for normalized hashtags.
    pub const HASHTAG: &str = "<HASHTAG>";
    /// Token for unknown/rare words.
    pub const UNK: &str = "<UNK>";
}

lazy_static! {
    // URL pattern - matches http(s), ftp, file URLs
    static ref URL_REGEX: Regex = Regex::new(
        r"(?i)(?:https?|ftp|file)://[^\s<>]+"
    ).expect("Invalid URL regex");

    // Email pattern
    static ref EMAIL_REGEX: Regex = Regex::new(
        r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
    ).expect("Invalid email regex");

    // Number pattern - matches integers, decimals, percentages, ordinals
    static ref NUMBER_REGEX: Regex = Regex::new(
        r"\b\d+(?:,\d{3})*(?:\.\d+)?(?:%|st|nd|rd|th)?\b"
    ).expect("Invalid number regex");

    // Twitter-style username
    static ref USERNAME_REGEX: Regex = Regex::new(
        r"@[a-zA-Z0-9_]+"
    ).expect("Invalid username regex");

    // Hashtag pattern
    static ref HASHTAG_REGEX: Regex = Regex::new(
        r"#[a-zA-Z0-9_]+"
    ).expect("Invalid hashtag regex");

    // Multiple whitespace
    static ref MULTI_SPACE_REGEX: Regex = Regex::new(r"\s+").expect("Invalid whitespace regex");
}

/// English contractions and their expansions.
const CONTRACTIONS: &[(&str, &str)] = &[
    // Negations
    ("can't", "cannot"),
    ("cannot", "cannot"),
    ("won't", "will not"),
    ("n't", " not"),
    // Be verbs
    ("'m", " am"),
    ("'re", " are"),
    ("'s", " is"), // Note: also possessive, context-dependent
    // Have verbs
    ("'ve", " have"),
    ("'d", " would"), // Also "had", context-dependent
    ("'ll", " will"),
    // Informal
    ("gonna", "going to"),
    ("gotta", "got to"),
    ("wanna", "want to"),
    ("lemme", "let me"),
    ("gimme", "give me"),
    ("kinda", "kind of"),
    ("sorta", "sort of"),
    ("dunno", "do not know"),
    ("'cause", "because"),
    ("'til", "until"),
    // Possessive contractions (less common to expand)
    ("let's", "let us"),
    ("that's", "that is"),
    ("there's", "there is"),
    ("here's", "here is"),
    ("what's", "what is"),
    ("who's", "who is"),
    ("how's", "how is"),
    ("where's", "where is"),
    ("it's", "it is"),
];

/// Unicode normalization form.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UnicodeNorm {
    /// No Unicode normalization.
    None,
    /// NFC (Canonical Decomposition, followed by Canonical Composition).
    #[default]
    Nfc,
    /// NFD (Canonical Decomposition).
    Nfd,
    /// NFKC (Compatibility Decomposition, followed by Canonical Composition).
    Nfkc,
    /// NFKD (Compatibility Decomposition).
    Nfkd,
}

/// Text preprocessor for corpus normalization.
#[derive(Debug, Clone)]
pub struct TextPreprocessor {
    /// Whether to normalize numbers to <NUM>.
    normalize_numbers: bool,
    /// Whether to normalize URLs to <URL>.
    normalize_urls: bool,
    /// Whether to normalize emails to <EMAIL>.
    normalize_emails: bool,
    /// Whether to normalize @mentions to <USER>.
    normalize_usernames: bool,
    /// Whether to normalize #hashtags to <HASHTAG>.
    normalize_hashtags: bool,
    /// Whether to expand contractions.
    expand_contractions: bool,
    /// Whether to lowercase text.
    lowercase: bool,
    /// Unicode normalization form.
    unicode_norm: UnicodeNorm,
    /// Whether to normalize whitespace.
    normalize_whitespace: bool,
    /// Whether to strip leading/trailing whitespace.
    strip: bool,
}

impl Default for TextPreprocessor {
    fn default() -> Self {
        Self {
            normalize_numbers: true,
            normalize_urls: true,
            normalize_emails: true,
            normalize_usernames: false,
            normalize_hashtags: false,
            expand_contractions: false,
            lowercase: false,
            unicode_norm: UnicodeNorm::Nfc,
            normalize_whitespace: true,
            strip: true,
        }
    }
}

impl TextPreprocessor {
    /// Create a new preprocessor with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a builder for custom configuration.
    pub fn builder() -> TextPreprocessorBuilder {
        TextPreprocessorBuilder::new()
    }

    /// Create a minimal preprocessor (only whitespace normalization).
    pub fn minimal() -> Self {
        Self {
            normalize_numbers: false,
            normalize_urls: false,
            normalize_emails: false,
            normalize_usernames: false,
            normalize_hashtags: false,
            expand_contractions: false,
            lowercase: false,
            unicode_norm: UnicodeNorm::Nfc,
            normalize_whitespace: true,
            strip: true,
        }
    }

    /// Create an aggressive preprocessor (all normalizations enabled).
    pub fn aggressive() -> Self {
        Self {
            normalize_numbers: true,
            normalize_urls: true,
            normalize_emails: true,
            normalize_usernames: true,
            normalize_hashtags: true,
            expand_contractions: true,
            lowercase: true,
            unicode_norm: UnicodeNorm::Nfkc,
            normalize_whitespace: true,
            strip: true,
        }
    }

    /// Process a text string.
    pub fn process(&self, text: &str) -> String {
        let mut result = text.to_string();

        // Unicode normalization (do first for consistent matching)
        result = self.apply_unicode_norm(&result);

        // URL normalization (before email to avoid partial matches)
        if self.normalize_urls {
            result = URL_REGEX.replace_all(&result, tokens::URL).to_string();
        }

        // Email normalization
        if self.normalize_emails {
            result = EMAIL_REGEX.replace_all(&result, tokens::EMAIL).to_string();
        }

        // Username normalization
        if self.normalize_usernames {
            result = USERNAME_REGEX
                .replace_all(&result, tokens::USER)
                .to_string();
        }

        // Hashtag normalization
        if self.normalize_hashtags {
            result = HASHTAG_REGEX
                .replace_all(&result, tokens::HASHTAG)
                .to_string();
        }

        // Number normalization
        if self.normalize_numbers {
            result = NUMBER_REGEX.replace_all(&result, tokens::NUM).to_string();
        }

        // Contraction expansion
        if self.expand_contractions {
            result = self.expand_contractions_in(&result);
        }

        // Lowercase
        if self.lowercase {
            result = result.to_lowercase();
        }

        // Whitespace normalization
        if self.normalize_whitespace {
            result = MULTI_SPACE_REGEX.replace_all(&result, " ").to_string();
        }

        // Strip
        if self.strip {
            result = result.trim().to_string();
        }

        result
    }

    /// Process multiple texts.
    pub fn process_batch<'a, I>(&'a self, texts: I) -> impl Iterator<Item = String> + 'a
    where
        I: Iterator<Item = &'a str> + 'a,
    {
        texts.map(move |t| self.process(t))
    }

    /// Apply Unicode normalization.
    fn apply_unicode_norm(&self, text: &str) -> String {
        match self.unicode_norm {
            UnicodeNorm::None => text.to_string(),
            UnicodeNorm::Nfc => text.nfc().collect(),
            UnicodeNorm::Nfd => text.nfd().collect(),
            UnicodeNorm::Nfkc => text.nfkc().collect(),
            UnicodeNorm::Nfkd => text.nfkd().collect(),
        }
    }

    /// Expand contractions in text.
    fn expand_contractions_in(&self, text: &str) -> String {
        let mut result = text.to_string();

        for (contraction, expansion) in CONTRACTIONS {
            // Case-insensitive replacement
            let pattern = format!(r"(?i){}", regex::escape(contraction));
            if let Ok(re) = Regex::new(&pattern) {
                result = re.replace_all(&result, *expansion).to_string();
            }
        }

        result
    }
}

/// Builder for TextPreprocessor.
#[derive(Debug, Clone)]
pub struct TextPreprocessorBuilder {
    preprocessor: TextPreprocessor,
}

impl TextPreprocessorBuilder {
    /// Create a new builder with default settings.
    pub fn new() -> Self {
        Self {
            preprocessor: TextPreprocessor::default(),
        }
    }

    /// Set whether to normalize numbers.
    pub fn normalize_numbers(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_numbers = enable;
        self
    }

    /// Set whether to normalize URLs.
    pub fn normalize_urls(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_urls = enable;
        self
    }

    /// Set whether to normalize emails.
    pub fn normalize_emails(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_emails = enable;
        self
    }

    /// Set whether to normalize @mentions.
    pub fn normalize_usernames(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_usernames = enable;
        self
    }

    /// Set whether to normalize #hashtags.
    pub fn normalize_hashtags(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_hashtags = enable;
        self
    }

    /// Set whether to expand contractions.
    pub fn expand_contractions(mut self, enable: bool) -> Self {
        self.preprocessor.expand_contractions = enable;
        self
    }

    /// Set whether to lowercase text.
    pub fn lowercase(mut self, enable: bool) -> Self {
        self.preprocessor.lowercase = enable;
        self
    }

    /// Set Unicode normalization form.
    pub fn unicode_norm(mut self, form: UnicodeNorm) -> Self {
        self.preprocessor.unicode_norm = form;
        self
    }

    /// Set whether to normalize whitespace.
    pub fn normalize_whitespace(mut self, enable: bool) -> Self {
        self.preprocessor.normalize_whitespace = enable;
        self
    }

    /// Set whether to strip leading/trailing whitespace.
    pub fn strip(mut self, enable: bool) -> Self {
        self.preprocessor.strip = enable;
        self
    }

    /// Build the preprocessor.
    pub fn build(self) -> TextPreprocessor {
        self.preprocessor
    }
}

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

/// Preprocessing pipeline that combines multiple steps.
#[derive(Debug, Clone)]
pub struct PreprocessingPipeline {
    /// Text preprocessor.
    preprocessor: TextPreprocessor,
    /// Optional quality filter.
    quality_filter: Option<super::QualityFilter>,
    /// Optional deduplicator.
    dedup_mode: Option<super::DeduplicationMode>,
}

impl PreprocessingPipeline {
    /// Create a new pipeline with default settings.
    pub fn new() -> Self {
        Self {
            preprocessor: TextPreprocessor::default(),
            quality_filter: None,
            dedup_mode: None,
        }
    }

    /// Create a builder for the pipeline.
    pub fn builder() -> PreprocessingPipelineBuilder {
        PreprocessingPipelineBuilder::new()
    }

    /// Process a sentence through the pipeline.
    ///
    /// Returns `Some(processed_text)` if the sentence passes all filters,
    /// `None` if it should be filtered out.
    pub fn process(&self, text: &str) -> Option<String> {
        // Preprocess first
        let processed = self.preprocessor.process(text);

        // Quality filter
        if let Some(ref filter) = self.quality_filter {
            if !filter.is_quality(&processed) {
                return None;
            }
        }

        Some(processed)
    }

    /// Process a batch of sentences through the pipeline.
    ///
    /// Returns an iterator of processed sentences that pass all filters.
    /// Includes deduplication if configured.
    pub fn process_batch<'a, I>(&'a self, texts: I) -> Box<dyn Iterator<Item = String> + 'a>
    where
        I: Iterator<Item = String> + 'a,
    {
        let processed = texts.filter_map(move |t| self.process(&t));

        if let Some(mode) = &self.dedup_mode {
            let mut dedup = super::Deduplicator::new(*mode);
            Box::new(processed.filter(move |s| dedup.is_unique(s)))
        } else {
            Box::new(processed)
        }
    }
}

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

/// Builder for PreprocessingPipeline.
#[derive(Debug, Clone)]
pub struct PreprocessingPipelineBuilder {
    pipeline: PreprocessingPipeline,
}

impl PreprocessingPipelineBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            pipeline: PreprocessingPipeline::new(),
        }
    }

    /// Set the text preprocessor.
    pub fn preprocessor(mut self, preprocessor: TextPreprocessor) -> Self {
        self.pipeline.preprocessor = preprocessor;
        self
    }

    /// Set the quality filter.
    pub fn quality_filter(mut self, filter: super::QualityFilter) -> Self {
        self.pipeline.quality_filter = Some(filter);
        self
    }

    /// Set the deduplication mode.
    pub fn deduplication(mut self, mode: super::DeduplicationMode) -> Self {
        self.pipeline.dedup_mode = Some(mode);
        self
    }

    /// Build the pipeline.
    pub fn build(self) -> PreprocessingPipeline {
        self.pipeline
    }
}

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

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

    #[test]
    fn test_url_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_urls(true)
            .normalize_numbers(false)
            .build();

        assert_eq!(
            pp.process("Visit https://example.com for more."),
            "Visit <URL> for more."
        );

        assert_eq!(
            pp.process("See http://foo.bar/baz?q=1 and https://a.b"),
            "See <URL> and <URL>"
        );
    }

    #[test]
    fn test_email_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_emails(true)
            .normalize_urls(false)
            .normalize_numbers(false)
            .build();

        assert_eq!(
            pp.process("Contact user@example.com for help."),
            "Contact <EMAIL> for help."
        );
    }

    #[test]
    fn test_number_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_numbers(true)
            .normalize_urls(false)
            .build();

        assert_eq!(pp.process("I have 42 apples."), "I have <NUM> apples.");
        assert_eq!(pp.process("It costs $1,234.56"), "It costs $<NUM>");
        assert_eq!(pp.process("The 1st place winner"), "The <NUM> place winner");
    }

    #[test]
    fn test_contraction_expansion() {
        let pp = TextPreprocessor::builder()
            .expand_contractions(true)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        assert_eq!(pp.process("I can't do it."), "I cannot do it.");
        assert_eq!(pp.process("They won't come."), "They will not come.");
        assert_eq!(pp.process("I'm going home."), "I am going home.");
    }

    #[test]
    fn test_lowercase() {
        let pp = TextPreprocessor::builder()
            .lowercase(true)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        assert_eq!(pp.process("Hello WORLD!"), "hello world!");
    }

    #[test]
    fn test_whitespace_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_whitespace(true)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        assert_eq!(
            pp.process("  Multiple   spaces   here  "),
            "Multiple spaces here"
        );
    }

    #[test]
    fn test_username_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_usernames(true)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        assert_eq!(
            pp.process("Hey @user123, check this out!"),
            "Hey <USER>, check this out!"
        );
    }

    #[test]
    fn test_hashtag_normalization() {
        let pp = TextPreprocessor::builder()
            .normalize_hashtags(true)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        assert_eq!(
            pp.process("Loving this #coding life!"),
            "Loving this <HASHTAG> life!"
        );
    }

    #[test]
    fn test_combined_preprocessing() {
        let pp = TextPreprocessor::aggressive();

        let text = "Hey @user, I can't visit https://example.com in 2024! #excited";
        let result = pp.process(text);

        // Aggressive mode lowercases everything, including tokens
        assert!(result.contains("<user>"), "Expected <user> in: {}", result);
        assert!(result.contains("<url>"), "Expected <url> in: {}", result);
        assert!(result.contains("<num>"), "Expected <num> in: {}", result);
        assert!(
            result.contains("<hashtag>"),
            "Expected <hashtag> in: {}",
            result
        );
        assert!(
            result.contains("cannot"),
            "Expected 'cannot' in: {}",
            result
        );
        assert_eq!(result, result.to_lowercase());
    }

    #[test]
    fn test_minimal_preprocessor() {
        let pp = TextPreprocessor::minimal();

        let text = "  Hello  123  world@example.com  ";
        let result = pp.process(text);

        assert_eq!(result, "Hello 123 world@example.com");
    }

    #[test]
    fn test_unicode_normalization() {
        let pp = TextPreprocessor::builder()
            .unicode_norm(UnicodeNorm::Nfc)
            .normalize_numbers(false)
            .normalize_urls(false)
            .build();

        // Combining character (e + combining acute = e with accent)
        let composed = "cafe\u{0301}"; // cafe + combining acute
        let result = pp.process(composed);

        // After NFC, the combining character should be composed
        assert_eq!(result.chars().count(), 4); // c-a-f-e with accent as one char
    }

    #[test]
    fn test_pipeline() {
        use super::super::{DeduplicationMode, QualityFilter};

        let pipeline = PreprocessingPipeline::builder()
            .preprocessor(TextPreprocessor::default())
            .quality_filter(QualityFilter::builder().min_words(3).build())
            .deduplication(DeduplicationMode::Normalized)
            .build();

        // Short sentence should be filtered out
        assert!(pipeline.process("Hi.").is_none());

        // Good sentence should pass
        let result = pipeline.process("This is a good sentence with enough words.");
        assert!(result.is_some());
    }

    #[test]
    fn test_batch_processing() {
        let pp = TextPreprocessor::builder()
            .normalize_numbers(true)
            .normalize_urls(false)
            .build();

        let texts = vec!["I have 5 apples.", "You have 10 oranges."];
        let results: Vec<String> = pp.process_batch(texts.iter().map(|s| *s)).collect();

        assert_eq!(results[0], "I have <NUM> apples.");
        assert_eq!(results[1], "You have <NUM> oranges.");
    }
}