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
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
//! Dictionary-based spelling correction
//!
//! This module provides a dictionary-based approach to spelling correction
//! using string similarity metrics to find the closest match for a
//! potentially misspelled word.
//!
//! # Key Components
//!
//! - `DictionaryCorrector`: Main implementation of dictionary-based spelling correction
//! - `DictionaryCorrectorConfig`: Configuration options for the corrector
//!
//! # Example
//!
//! ```
//! use scirs2_text::spelling::{DictionaryCorrector, SpellingCorrector};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a dictionary-based spelling corrector with default settings
//! let corrector = DictionaryCorrector::default();
//!
//! // Correct a misspelled word
//! let corrected = corrector.correct("recieve")?;
//! assert_eq!(corrected, "receive");
//!
//! // Check if a word is correct
//! assert!(corrector.is_correct("computer"));
//! assert!(!corrector.is_correct("computre"));
//! # Ok(())
//! # }
//! ```

use crate::error::{Result, TextError};
use crate::string_metrics::{DamerauLevenshteinMetric, StringMetric};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::sync::Arc;

use super::utils::{dictionary_contains, is_within_length_threshold, normalize_string};
use super::SpellingCorrector;

/// Configuration for the dictionary-based spelling corrector
#[derive(Debug, Clone)]
pub struct DictionaryCorrectorConfig {
    /// Maximum edit distance to consider for corrections
    pub max_edit_distance: usize,
    /// Whether to use case-sensitive matching
    pub case_sensitive: bool,
    /// Maximum number of suggestions to consider
    pub max_suggestions: usize,
    /// Minimum word frequency to consider for suggestions
    pub min_frequency: usize,
    /// Whether to prioritize suggestions by word frequency
    pub prioritize_by_frequency: bool,
}

impl Default for DictionaryCorrectorConfig {
    fn default() -> Self {
        Self {
            max_edit_distance: 2,
            case_sensitive: false,
            max_suggestions: 5,
            min_frequency: 1,
            prioritize_by_frequency: true,
        }
    }
}

/// Dictionary-based spelling corrector
pub struct DictionaryCorrector {
    /// Dictionary of words and their frequencies
    pub(crate) dictionary: HashMap<String, usize>,
    /// Configuration for the corrector
    pub(crate) config: DictionaryCorrectorConfig,
    /// Metric to use for string similarity
    pub(crate) metric: Arc<dyn StringMetric + Send + Sync>,
}

impl Clone for DictionaryCorrector {
    fn clone(&self) -> Self {
        Self {
            dictionary: self.dictionary.clone(),
            config: self.config.clone(),
            metric: self.metric.clone(),
        }
    }
}

impl std::fmt::Debug for DictionaryCorrector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DictionaryCorrector")
            .field("dictionary", &{
                let dict_len = self.dictionary.len();
                format!("<{dict_len} words>")
            })
            .field("config", &self.config)
            .field("metric", &"<StringMetric>")
            .finish()
    }
}

impl Default for DictionaryCorrector {
    fn default() -> Self {
        // Create a default dictionary with common English words
        let mut dictionary = HashMap::new();

        // Add some common English words
        let common_words = vec![
            "the",
            "be",
            "to",
            "of",
            "and",
            "a",
            "in",
            "that",
            "have",
            "I",
            "it",
            "for",
            "not",
            "on",
            "with",
            "he",
            "as",
            "you",
            "do",
            "at",
            "this",
            "but",
            "his",
            "by",
            "from",
            "they",
            "we",
            "say",
            "her",
            "she",
            "or",
            "an",
            "will",
            "my",
            "one",
            "all",
            "would",
            "there",
            "their",
            "what",
            "so",
            "up",
            "out",
            "if",
            "about",
            "who",
            "get",
            "which",
            "go",
            "me",
            "when",
            "make",
            "can",
            "like",
            "time",
            "no",
            "just",
            "him",
            "know",
            "take",
            "people",
            "into",
            "year",
            "your",
            "good",
            "some",
            "could",
            "them",
            "see",
            "other",
            "than",
            "then",
            "now",
            "look",
            "only",
            "come",
            "its",
            "over",
            "think",
            "also",
            "back",
            "after",
            "use",
            "two",
            "how",
            "our",
            "work",
            "first",
            "well",
            "way",
            "even",
            "new",
            "want",
            "because",
            "any",
            "these",
            "give",
            "day",
            "most",
            "us",
            "information",
            "computer",
            "system",
            "data",
            "software",
            "program",
            "application",
            "hardware",
            "network",
            "user",
            "file",
            "memory",
            "process",
            "code",
            "function",
            "algorithm",
            "interface",
            "method",
            "language",
            "programming",
            "library",
            "class",
            "object",
            "variable",
            "value",
            "type",
            "reference",
            "pointer",
            "array",
            "string",
            "receive",
            "believe",
            "achieve",
            "field",
            "friend",
            "science",
            "weight",
            "eight",
            "neighbor",
            "height",
            "weird",
            "foreign",
            "sovereign",
            "ceiling",
            "leisure",
            "neither",
            "protein",
            "caffeine",
            "seize",
            "receipt",
            "perceive",
            "conceive",
            "deceive",
            "except",
            "accept",
            "desert",
            "dessert",
            "principal",
            "principle",
            "stationary",
            "stationery",
            "complement",
            "compliment",
            "affect",
            "effect",
            "lose",
            "loose",
            "than",
            "then",
            "your",
            "you're",
            "its",
            "it's",
            "there",
            "their",
            "they're",
            "weather",
            "whether",
            "hear",
            "here",
            "too",
            "to",
            "two",
        ];

        for word in common_words {
            dictionary.insert(word.to_string(), 100);
        }

        Self {
            dictionary,
            config: DictionaryCorrectorConfig::default(),
            metric: Arc::new(DamerauLevenshteinMetric::new()),
        }
    }
}

impl DictionaryCorrector {
    /// Create a new dictionary-based spelling corrector with the given configuration
    pub fn new(config: DictionaryCorrectorConfig) -> Self {
        Self {
            config,
            ..Default::default()
        }
    }

    /// Create a new dictionary-based spelling corrector with a custom dictionary
    pub fn with_dictionary(dictionary: HashMap<String, usize>) -> Self {
        Self {
            dictionary,
            config: DictionaryCorrectorConfig::default(),
            metric: Arc::new(DamerauLevenshteinMetric::new()),
        }
    }

    /// Create a new dictionary-based spelling corrector with a custom metric
    pub fn with_metric<M: StringMetric + Send + Sync + 'static>(metric: M) -> Self {
        Self {
            dictionary: HashMap::new(),
            config: DictionaryCorrectorConfig::default(),
            metric: Arc::new(metric),
        }
    }

    /// Load a dictionary from a file
    ///
    /// The file should contain one word per line, optionally followed by a frequency count.
    /// If no frequency is provided, a default value of 1 is used.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let file = File::open(path)
            .map_err(|e| TextError::IoError(format!("Failed to open dictionary file: {e}")))?;

        let reader = BufReader::new(file);
        let mut dictionary = HashMap::new();

        for line in reader.lines() {
            let line = line.map_err(|e| {
                TextError::IoError(format!("Failed to read line from dictionary file: {e}"))
            })?;

            // Skip empty lines
            if line.trim().is_empty() {
                continue;
            }

            // Parse the line (word + optional frequency)
            let parts: Vec<&str> = line.split_whitespace().collect();
            match parts.len() {
                1 => {
                    // Just a word, use default frequency of 1
                    dictionary.insert(parts[0].to_string(), 1);
                }
                2 => {
                    // Word and frequency
                    let word = parts[0];
                    let frequency = parts[1].parse::<usize>().map_err(|e| {
                        TextError::Other(format!("Failed to parse frequency as integer: {e}"))
                    })?;

                    dictionary.insert(word.to_string(), frequency);
                }
                _ => {
                    // Invalid format, skip this line
                    continue;
                }
            }
        }

        Ok(Self {
            dictionary,
            config: DictionaryCorrectorConfig::default(),
            metric: Arc::new(DamerauLevenshteinMetric::new()),
        })
    }

    /// Add a word to the dictionary
    pub fn add_word(&mut self, word: &str, frequency: usize) {
        self.dictionary.insert(word.to_string(), frequency);
    }

    /// Remove a word from the dictionary
    pub fn remove_word(&mut self, word: &str) {
        self.dictionary.remove(word);
    }

    /// Set the string metric to use for similarity calculations
    pub fn set_metric<M: StringMetric + Send + Sync + 'static>(&mut self, metric: M) {
        self.metric = Arc::new(metric);
    }

    /// Set the configuration
    pub fn set_config(&mut self, config: DictionaryCorrectorConfig) {
        self.config = config;
    }

    /// Get the total number of words in the dictionary
    pub fn dictionary_size(&self) -> usize {
        self.dictionary.len()
    }
}

impl SpellingCorrector for DictionaryCorrector {
    fn correct(&self, word: &str) -> Result<String> {
        // If the word is already correct, return it as is
        if self.is_correct(word) {
            return Ok(word.to_string());
        }

        // Get suggestions and return the best one
        let suggestions = self.get_suggestions(word, 1)?;

        if suggestions.is_empty() {
            // No suggestions found, return the original word
            Ok(word.to_string())
        } else {
            // Return the best suggestion
            Ok(suggestions[0].clone())
        }
    }

    fn get_suggestions(&self, word: &str, limit: usize) -> Result<Vec<String>> {
        // If the word is already correct, return it as the only suggestion
        if self.is_correct(word) {
            return Ok(vec![word.to_string()]);
        }

        let word_to_check = normalize_string(word, self.config.case_sensitive);

        // Find candidates with edit distance less than the threshold
        let mut candidates: Vec<(String, usize, usize)> = Vec::new(); // (word, edit_distance, frequency)

        for (dict_word, frequency) in &self.dictionary {
            if *frequency < self.config.min_frequency {
                continue;
            }

            let dict_word_normalized = normalize_string(dict_word, self.config.case_sensitive);

            // Skip words that are too different in length
            if !is_within_length_threshold(
                &dict_word_normalized,
                &word_to_check,
                self.config.max_edit_distance,
            ) {
                continue;
            }

            // Calculate edit distance
            if let Ok(distance) = self.metric.distance(&word_to_check, &dict_word_normalized) {
                // Convert to usize and check if it's within the threshold
                let distance_usize = distance.round() as usize;
                if distance_usize <= self.config.max_edit_distance {
                    candidates.push((dict_word.clone(), distance_usize, *frequency));
                }
            }
        }

        // Sort candidates by edit distance and optionally by frequency
        if self.config.prioritize_by_frequency {
            candidates.sort_by(|a, b| {
                let (_, dist_a, freq_a) = a;
                let (_, dist_b, freq_b) = b;

                // First, compare by distance
                dist_a.cmp(dist_b)
                    // Then by frequency (higher frequency is better)
                    .then_with(|| freq_b.cmp(freq_a))
            });
        } else {
            candidates.sort_by(|a, b| {
                let (_, dist_a, _) = a;
                let (_, dist_b, _) = b;

                // Sort only by distance
                dist_a.cmp(dist_b)
            });
        }

        // Return the top suggestions, limited by the requested count
        let actual_limit = std::cmp::min(limit, candidates.len());
        let suggestions = candidates[0..actual_limit]
            .iter()
            .map(|(word, _, _)| word.clone())
            .collect();

        Ok(suggestions)
    }

    fn is_correct(&self, word: &str) -> bool {
        dictionary_contains(&self.dictionary, word, self.config.case_sensitive)
    }
}

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

    #[test]
    fn test_dictionary_corrector_basics() {
        let corrector = DictionaryCorrector::default();

        // Test some common misspellings
        assert_eq!(
            corrector.correct("recieve").expect("Operation failed"),
            "receive"
        );
        assert_eq!(
            corrector.correct("freind").expect("Operation failed"),
            "friend"
        );
        assert_eq!(
            corrector.correct("belive").expect("Operation failed"),
            "believe"
        );

        // Test correct words
        assert_eq!(
            corrector.correct("computer").expect("Operation failed"),
            "computer"
        );
        assert_eq!(
            corrector.correct("programming").expect("Operation failed"),
            "programming"
        );

        // Test is_correct
        assert!(corrector.is_correct("computer"));
        assert!(!corrector.is_correct("computre"));
    }

    #[test]
    fn test_dictionary_corrector_with_custom_dictionary() {
        let mut dictionary = HashMap::new();

        // Add some domain-specific terms
        dictionary.insert("rust".to_string(), 100);
        dictionary.insert("cargo".to_string(), 80);
        dictionary.insert("crate".to_string(), 75);
        dictionary.insert("trait".to_string(), 60);
        dictionary.insert("struct".to_string(), 55);
        dictionary.insert("enum".to_string(), 50);

        let corrector = DictionaryCorrector::with_dictionary(dictionary);

        // Test domain-specific corrections
        assert_eq!(corrector.correct("rsut").expect("Operation failed"), "rust");
        assert_eq!(
            corrector.correct("crago").expect("Operation failed"),
            "cargo"
        );
        assert_eq!(
            corrector.correct("crat").expect("Operation failed"),
            "crate"
        );

        // Test is_correct with domain-specific terms
        assert!(corrector.is_correct("rust"));
        assert!(corrector.is_correct("cargo"));
        assert!(!corrector.is_correct("python")); // Not in dictionary
    }

    #[test]
    fn test_dictionary_corrector_with_custom_config() {
        let config = DictionaryCorrectorConfig {
            max_edit_distance: 1, // More strict
            case_sensitive: true, // Case-sensitive
            max_suggestions: 3,
            min_frequency: 10,
            prioritize_by_frequency: true,
        };

        let mut corrector = DictionaryCorrector::new(config);

        // Add the word deliberately for testing
        corrector.add_word("recieve", 100); // Misspelled version

        // Should return "recieve" itself since it's in the dictionary (even though misspelled)
        assert_eq!(
            corrector.correct("recieve").expect("Operation failed"),
            "recieve"
        );

        // Test case sensitivity
        assert!(corrector.is_correct("I")); // In dictionary as uppercase
        assert!(!corrector.is_correct("i")); // Not found as lowercase
    }

    #[test]
    fn test_dictionary_corrector_get_suggestions() {
        let mut corrector = DictionaryCorrector::default();

        // Add programming explicitly to ensure test consistency
        corrector.add_word("programming", 100);

        // Test getting multiple suggestions
        let suggestions = corrector
            .get_suggestions("programing", 3)
            .expect("Operation failed");
        assert!(suggestions.contains(&"programming".to_string()));

        // Test with an artificial word that should have no suggestions
        let suggestions = corrector
            .get_suggestions("xyzabc123", 3)
            .expect("Operation failed");
        assert!(suggestions.is_empty());
    }

    #[test]
    fn test_dictionary_corrector_correcttext() {
        let mut corrector = DictionaryCorrector::default();

        // Add required words to the dictionary with specific corrections
        corrector.add_word("believe", 100);
        corrector.add_word("received", 100);
        corrector.add_word("was", 100);
        corrector.add_word("correct", 100);

        let text = "I beleive the recieved information was corect.";

        // Create a custom corrector for the test to ensure consistent behavior
        let corrected = corrector.correcttext(text).expect("Operation failed");

        // Check each word individually to be more robust
        assert!(corrected.contains("believe"));
        assert!(corrected.contains("received"));
        assert!(corrected.contains("was"));
        assert!(corrected.contains("correct"));
    }
}