1use crate::transforms::Transform;
17use std::collections::HashSet;
18use torsh_core::error::Result;
19
20#[derive(Debug, Clone, Default)]
22pub struct ToLowercase;
23
24impl Transform<String> for ToLowercase {
25 type Output = String;
26
27 fn transform(&self, input: String) -> Result<Self::Output> {
28 Ok(input.to_lowercase())
29 }
30}
31
32#[derive(Debug, Clone, Default)]
34pub struct RemovePunctuation;
35
36impl Transform<String> for RemovePunctuation {
37 type Output = String;
38
39 fn transform(&self, input: String) -> Result<Self::Output> {
40 Ok(input
41 .chars()
42 .filter(|c| !c.is_ascii_punctuation())
43 .collect())
44 }
45}
46
47#[derive(Debug, Clone)]
49pub struct Tokenize {
50 delimiter: String,
51}
52
53impl Tokenize {
54 pub fn new(delimiter: String) -> Self {
56 Self { delimiter }
57 }
58
59 pub fn whitespace() -> Self {
61 Self::new(" ".to_string())
62 }
63
64 pub fn any_whitespace() -> Self {
66 Self::new("".to_string()) }
68}
69
70impl Transform<String> for Tokenize {
71 type Output = Vec<String>;
72
73 fn transform(&self, input: String) -> Result<Self::Output> {
74 if self.delimiter.is_empty() {
75 Ok(input.split_whitespace().map(|s| s.to_string()).collect())
77 } else {
78 Ok(input
79 .split(&self.delimiter)
80 .map(|s| s.to_string())
81 .collect())
82 }
83 }
84}
85
86#[derive(Debug, Clone, Default)]
88pub struct TrimWhitespace;
89
90impl Transform<String> for TrimWhitespace {
91 type Output = String;
92
93 fn transform(&self, input: String) -> Result<Self::Output> {
94 Ok(input.trim().to_string())
95 }
96}
97
98#[derive(Debug, Clone, Default)]
100pub struct CollapseWhitespace;
101
102impl Transform<String> for CollapseWhitespace {
103 type Output = String;
104
105 fn transform(&self, input: String) -> Result<Self::Output> {
106 let mut result = String::with_capacity(input.len());
107 let mut prev_was_space = false;
108
109 for ch in input.chars() {
110 if ch.is_whitespace() {
111 if !prev_was_space {
112 result.push(' ');
113 prev_was_space = true;
114 }
115 } else {
116 result.push(ch);
117 prev_was_space = false;
118 }
119 }
120
121 Ok(result.trim().to_string())
122 }
123}
124
125#[derive(Debug, Clone, Default)]
127pub struct RemoveNumbers;
128
129impl Transform<String> for RemoveNumbers {
130 type Output = String;
131
132 fn transform(&self, input: String) -> Result<Self::Output> {
133 Ok(input.chars().filter(|c| !c.is_ascii_digit()).collect())
134 }
135}
136
137#[derive(Debug, Clone)]
139pub struct RemoveStopwords {
140 stopwords: HashSet<String>,
141}
142
143impl RemoveStopwords {
144 pub fn english() -> Self {
146 let stopwords = [
147 "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he", "in",
148 "is", "it", "its", "of", "on", "that", "the", "to", "was", "were", "will", "with",
149 "the", "this", "but", "they", "have", "had", "what", "said", "each", "which", "their",
150 "time", "will", "about", "if", "up", "out", "many", "then", "them", "these", "so",
151 "some", "her", "would", "make", "like", "into", "him", "has", "two", "more", "go",
152 "no", "way", "could", "my", "than", "first", "been", "call", "who", "oil", "sit",
153 "now", "find", "down", "day", "did", "get", "come", "made", "may", "part", "over",
154 "new", "sound", "take", "only", "little", "work", "know", "place", "year", "live",
155 "me", "back", "give", "most", "very", "after", "thing", "our", "just", "name", "good",
156 "sentence", "man", "think", "say", "great", "where", "help", "through", "much",
157 "before", "line", "right", "too", "mean", "old", "any", "same", "tell", "boy",
158 "follow", "came", "want", "show", "also", "around", "form", "three", "small", "set",
159 "put", "end", "why", "again", "turn", "here", "off", "went", "old", "number", "great",
160 "tell", "men", "say", "small", "every", "found", "still", "between", "mea", "another",
161 "even", "why", "must", "big", "because", "does", "each", "how", "let", "might", "move",
162 "own", "seem", "such", "turn", "under", "well", "without", "see", "use",
163 ]
164 .iter()
165 .map(|&s| s.to_string())
166 .collect();
167
168 Self { stopwords }
169 }
170
171 pub fn new(stopwords: Vec<String>) -> Self {
173 Self {
174 stopwords: stopwords.into_iter().collect(),
175 }
176 }
177
178 pub fn add_stopword(&mut self, word: String) {
180 self.stopwords.insert(word.to_lowercase());
181 }
182
183 pub fn stopword_count(&self) -> usize {
185 self.stopwords.len()
186 }
187}
188
189impl Transform<Vec<String>> for RemoveStopwords {
190 type Output = Vec<String>;
191
192 fn transform(&self, input: Vec<String>) -> Result<Self::Output> {
193 Ok(input
194 .into_iter()
195 .filter(|word| !self.stopwords.contains(&word.to_lowercase()))
196 .collect())
197 }
198}
199
200#[derive(Debug, Clone, Default)]
205pub struct PorterStemmer;
206
207impl PorterStemmer {
208 fn is_vowel(word: &str, i: usize) -> bool {
210 if i >= word.len() {
211 return false;
212 }
213 let chars: Vec<char> = word.chars().collect();
214 let ch = chars[i];
215 if "aeiou".contains(ch) {
216 return true;
217 }
218 if ch == 'y' && i > 0 && !Self::is_vowel(word, i - 1) {
219 return true;
220 }
221 false
222 }
223
224 fn measure(&self, word: &str) -> usize {
226 let mut m = 0;
227 let len = word.len();
228 let mut i = 0;
229
230 while i < len && !Self::is_vowel(word, i) {
232 i += 1;
233 }
234
235 while i < len {
236 while i < len && Self::is_vowel(word, i) {
238 i += 1;
239 }
240 if i >= len {
241 break;
242 }
243 m += 1;
244
245 while i < len && !Self::is_vowel(word, i) {
247 i += 1;
248 }
249 }
250
251 m
252 }
253
254 fn ends_with(&self, word: &str, suffix: &str) -> bool {
256 word.ends_with(suffix)
257 }
258
259 fn replace_suffix(&self, word: &str, old_suffix: &str, new_suffix: &str) -> String {
261 if let Some(stem) = word.strip_suffix(old_suffix) {
262 format!("{stem}{new_suffix}")
263 } else {
264 word.to_string()
265 }
266 }
267
268 fn step1a(&self, word: &str) -> String {
270 if self.ends_with(word, "sses") {
271 self.replace_suffix(word, "sses", "ss")
272 } else if self.ends_with(word, "ies") {
273 self.replace_suffix(word, "ies", "i")
274 } else if self.ends_with(word, "ss") {
275 word.to_string()
276 } else if self.ends_with(word, "s") && word.len() > 1 {
277 self.replace_suffix(word, "s", "")
278 } else {
279 word.to_string()
280 }
281 }
282
283 fn step1b(&self, word: &str) -> String {
285 if self.ends_with(word, "eed") {
286 let stem = &word[..word.len() - 3];
287 if self.measure(stem) > 0 {
288 self.replace_suffix(word, "eed", "ee")
289 } else {
290 word.to_string()
291 }
292 } else if self.ends_with(word, "ed") {
293 let stem = &word[..word.len() - 2];
294 if self.contains_vowel(stem) {
295 let result = stem;
296 if self.ends_with(result, "at")
297 || self.ends_with(result, "bl")
298 || self.ends_with(result, "iz")
299 {
300 format!("{result}e")
301 } else {
302 result.to_string()
303 }
304 } else {
305 word.to_string()
306 }
307 } else if self.ends_with(word, "ing") {
308 let stem = &word[..word.len() - 3];
309 if self.contains_vowel(stem) {
310 stem.to_string()
311 } else {
312 word.to_string()
313 }
314 } else {
315 word.to_string()
316 }
317 }
318
319 fn contains_vowel(&self, word: &str) -> bool {
321 for i in 0..word.len() {
322 if Self::is_vowel(word, i) {
323 return true;
324 }
325 }
326 false
327 }
328}
329
330impl Transform<String> for PorterStemmer {
331 type Output = String;
332
333 fn transform(&self, input: String) -> Result<Self::Output> {
334 if input.len() <= 2 {
335 return Ok(input);
336 }
337
338 let word = input.to_lowercase();
339 let word = self.step1a(&word);
340 let word = self.step1b(&word);
341
342 Ok(word)
343 }
344}
345
346#[derive(Debug, Clone)]
348pub struct NGramGenerator {
349 n: usize,
350}
351
352impl NGramGenerator {
353 pub fn new(n: usize) -> Self {
359 assert!(n > 0, "N must be greater than 0");
360 Self { n }
361 }
362
363 pub fn try_new(n: usize) -> Result<Self> {
366 crate::utils::validate_positive(n, "n")?;
367 Ok(Self { n })
368 }
369
370 pub fn bigram() -> Self {
372 Self::new(2)
373 }
374
375 pub fn trigram() -> Self {
377 Self::new(3)
378 }
379
380 pub fn unigram() -> Self {
382 Self::new(1)
383 }
384
385 pub fn n(&self) -> usize {
387 self.n
388 }
389}
390
391impl Transform<Vec<String>> for NGramGenerator {
392 type Output = Vec<String>;
393
394 fn transform(&self, input: Vec<String>) -> Result<Self::Output> {
395 if input.len() < self.n {
396 return Ok(Vec::new());
397 }
398
399 let mut ngrams = Vec::new();
400 for i in 0..=input.len() - self.n {
401 let ngram = input[i..i + self.n].join(" ");
402 ngrams.push(ngram);
403 }
404
405 Ok(ngrams)
406 }
407}
408
409#[derive(Debug, Clone)]
411pub struct FilterByLength {
412 min_length: usize,
413 max_length: Option<usize>,
414}
415
416impl FilterByLength {
417 pub fn new(min_length: usize, max_length: Option<usize>) -> Self {
419 Self {
420 min_length,
421 max_length,
422 }
423 }
424
425 pub fn min_only(min_length: usize) -> Self {
427 Self::new(min_length, None)
428 }
429
430 pub fn max_only(max_length: usize) -> Self {
432 Self::new(0, Some(max_length))
433 }
434
435 pub fn range(min_length: usize, max_length: usize) -> Self {
437 Self::new(min_length, Some(max_length))
438 }
439}
440
441impl Transform<Vec<String>> for FilterByLength {
442 type Output = Vec<String>;
443
444 fn transform(&self, input: Vec<String>) -> Result<Self::Output> {
445 Ok(input
446 .into_iter()
447 .filter(|word| {
448 let len = word.len();
449 len >= self.min_length && self.max_length.map_or(true, |max| len <= max)
450 })
451 .collect())
452 }
453}
454
455#[derive(Debug, Clone)]
457pub struct ReplacePattern {
458 pattern: String,
459 replacement: String,
460}
461
462impl ReplacePattern {
463 pub fn new(pattern: String, replacement: String) -> Self {
465 Self {
466 pattern,
467 replacement,
468 }
469 }
470
471 pub fn remove(pattern: String) -> Self {
473 Self::new(pattern, String::new())
474 }
475}
476
477impl Transform<String> for ReplacePattern {
478 type Output = String;
479
480 fn transform(&self, input: String) -> Result<Self::Output> {
481 Ok(input.replace(&self.pattern, &self.replacement))
482 }
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum CaseMode {
488 Lower,
490 Upper,
492 Title,
494}
495
496#[derive(Debug, Clone)]
498pub struct ChangeCase {
499 mode: CaseMode,
500}
501
502impl ChangeCase {
503 pub fn new(mode: CaseMode) -> Self {
505 Self { mode }
506 }
507
508 pub fn lower() -> Self {
510 Self::new(CaseMode::Lower)
511 }
512
513 pub fn upper() -> Self {
515 Self::new(CaseMode::Upper)
516 }
517
518 pub fn title() -> Self {
520 Self::new(CaseMode::Title)
521 }
522}
523
524impl Transform<String> for ChangeCase {
525 type Output = String;
526
527 fn transform(&self, input: String) -> Result<Self::Output> {
528 match self.mode {
529 CaseMode::Lower => Ok(input.to_lowercase()),
530 CaseMode::Upper => Ok(input.to_uppercase()),
531 CaseMode::Title => {
532 let mut result = String::with_capacity(input.len());
533 let mut capitalize_next = true;
534
535 for ch in input.chars() {
536 if ch.is_alphabetic() {
537 if capitalize_next {
538 result.push(ch.to_uppercase().next().unwrap_or(ch));
539 capitalize_next = false;
540 } else {
541 result.push(ch.to_lowercase().next().unwrap_or(ch));
542 }
543 } else {
544 result.push(ch);
545 capitalize_next = ch.is_whitespace();
546 }
547 }
548
549 Ok(result)
550 }
551 }
552 }
553}
554
555pub fn tokenize_whitespace() -> Tokenize {
559 Tokenize::whitespace()
560}
561
562pub fn tokenize(delimiter: &str) -> Tokenize {
564 Tokenize::new(delimiter.to_string())
565}
566
567pub fn remove_english_stopwords() -> RemoveStopwords {
569 RemoveStopwords::english()
570}
571
572pub fn porter_stemmer() -> PorterStemmer {
574 PorterStemmer
575}
576
577pub fn bigrams() -> NGramGenerator {
579 NGramGenerator::bigram()
580}
581
582pub fn trigrams() -> NGramGenerator {
584 NGramGenerator::trigram()
585}
586
587pub fn filter_by_length(min: usize, max: Option<usize>) -> FilterByLength {
589 FilterByLength::new(min, max)
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595
596 #[test]
597 fn test_to_lowercase() {
598 let transform = ToLowercase;
599 assert_eq!(
600 transform.transform("Hello World".to_string()).unwrap(),
601 "hello world"
602 );
603 }
604
605 #[test]
606 fn test_remove_punctuation() {
607 let transform = RemovePunctuation;
608 assert_eq!(
609 transform.transform("Hello, World!".to_string()).unwrap(),
610 "Hello World"
611 );
612 }
613
614 #[test]
615 fn test_tokenize_whitespace() {
616 let transform = Tokenize::whitespace();
617 let result = transform.transform("hello world test".to_string()).unwrap();
618 assert_eq!(result, vec!["hello", "world", "test"]);
619 }
620
621 #[test]
622 fn test_tokenize_custom_delimiter() {
623 let transform = Tokenize::new(",".to_string());
624 let result = transform.transform("a,b,c".to_string()).unwrap();
625 assert_eq!(result, vec!["a", "b", "c"]);
626 }
627
628 #[test]
629 fn test_trim_whitespace() {
630 let transform = TrimWhitespace;
631 assert_eq!(
632 transform.transform(" hello world ".to_string()).unwrap(),
633 "hello world"
634 );
635 }
636
637 #[test]
638 fn test_collapse_whitespace() {
639 let transform = CollapseWhitespace;
640 assert_eq!(
641 transform
642 .transform("hello world test".to_string())
643 .unwrap(),
644 "hello world test"
645 );
646 }
647
648 #[test]
649 fn test_remove_numbers() {
650 let transform = RemoveNumbers;
651 assert_eq!(
652 transform.transform("hello123world456".to_string()).unwrap(),
653 "helloworld"
654 );
655 }
656
657 #[test]
658 fn test_remove_stopwords() {
659 let stopwords = RemoveStopwords::english();
660 let input = vec!["the".to_string(), "quick".to_string(), "brown".to_string()];
661 let result = stopwords.transform(input).unwrap();
662 assert_eq!(result, vec!["quick", "brown"]);
663 }
664
665 #[test]
666 fn test_porter_stemmer() {
667 let stemmer = PorterStemmer;
668
669 assert_eq!(stemmer.transform("running".to_string()).unwrap(), "runn");
670 assert_eq!(stemmer.transform("flies".to_string()).unwrap(), "fli");
671 assert_eq!(stemmer.transform("died".to_string()).unwrap(), "di");
672 assert_eq!(stemmer.transform("agreed".to_string()).unwrap(), "agree");
673 assert_eq!(stemmer.transform("sing".to_string()).unwrap(), "sing"); }
675
676 #[test]
677 fn test_ngram_generator() {
678 let words = vec![
679 "the".to_string(),
680 "quick".to_string(),
681 "brown".to_string(),
682 "fox".to_string(),
683 ];
684
685 let bigram = NGramGenerator::bigram();
687 let bigrams = bigram.transform(words.clone()).unwrap();
688 assert_eq!(bigrams, vec!["the quick", "quick brown", "brown fox"]);
689
690 let trigram = NGramGenerator::trigram();
692 let trigrams = trigram.transform(words).unwrap();
693 assert_eq!(trigrams, vec!["the quick brown", "quick brown fox"]);
694 }
695
696 #[test]
697 fn test_length_filter() {
698 let words = vec![
699 "a".to_string(),
700 "the".to_string(),
701 "quick".to_string(),
702 "brown".to_string(),
703 "foxes".to_string(),
704 ];
705
706 let filter = FilterByLength::new(3, Some(5));
707 let filtered = filter.transform(words).unwrap();
708 assert_eq!(filtered, vec!["the", "quick", "brown", "foxes"]);
709 }
710
711 #[test]
712 fn test_case_transforms() {
713 let text = "Hello World Test".to_string();
714
715 let lower = ChangeCase::lower();
716 assert_eq!(lower.transform(text.clone()).unwrap(), "hello world test");
717
718 let upper = ChangeCase::upper();
719 assert_eq!(upper.transform(text.clone()).unwrap(), "HELLO WORLD TEST");
720
721 let title = ChangeCase::title();
722 assert_eq!(
723 title.transform("hello world".to_string()).unwrap(),
724 "Hello World"
725 );
726 }
727
728 #[test]
729 fn test_replace_pattern() {
730 let replacer = ReplacePattern::new("world".to_string(), "universe".to_string());
731 assert_eq!(
732 replacer.transform("hello world".to_string()).unwrap(),
733 "hello universe"
734 );
735
736 let remover = ReplacePattern::remove("test ".to_string());
737 assert_eq!(
738 remover
739 .transform("test hello test world".to_string())
740 .unwrap(),
741 "hello world"
742 );
743 }
744
745 #[test]
746 fn test_convenience_functions() {
747 let _tokenizer = tokenize_whitespace();
748 let _custom_tokenizer = tokenize(",");
749 let _stopwords = remove_english_stopwords();
750 let _stemmer = porter_stemmer();
751 let _bigrams = bigrams();
752 let _trigrams = trigrams();
753 let _filter = filter_by_length(3, Some(10));
754 }
755}