torsh-text 0.1.2

Natural language processing utilities for ToRSh deep learning framework
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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
use crate::{Result, TextError};
// ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
use regex::Regex;
use scirs2_core::random::Random;
use scirs2_core::RngExt;
use std::collections::HashMap;

// Static regex patterns for performance optimization
lazy_static::lazy_static! {
    /// Regex pattern for matching multiple whitespace characters
    static ref WHITESPACE_RE: Regex = Regex::new(r"\s+")
        .expect("WHITESPACE_RE: compile-time constant regex should be valid");

    /// Regex pattern for matching URLs
    static ref URL_RE: Regex = Regex::new(r"https?://[^\s]+")
        .expect("URL_RE: compile-time constant regex should be valid");

    /// Regex pattern for matching email addresses
    static ref EMAIL_RE: Regex = Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
        .expect("EMAIL_RE: compile-time constant regex should be valid");

    /// Regex pattern for matching HTML tags
    static ref HTML_RE: Regex = Regex::new(r"<[^>]+>")
        .expect("HTML_RE: compile-time constant regex should be valid");

    /// Regex pattern for matching mentions (@username)
    static ref MENTION_RE: Regex = Regex::new(r"@\w+")
        .expect("MENTION_RE: compile-time constant regex should be valid");

    /// Regex pattern for matching hashtags (#hashtag)
    static ref HASHTAG_RE: Regex = Regex::new(r"#\w+")
        .expect("HASHTAG_RE: compile-time constant regex should be valid");
}

// ============================================================================
// Text Normalization
// ============================================================================

#[derive(Debug, Clone)]
pub struct TextNormalizer {
    lowercase: bool,
    remove_accents: bool,
    remove_punctuation: bool,
    remove_digits: bool,
    remove_extra_spaces: bool,
    normalize_unicode: bool,
}

impl Default for TextNormalizer {
    fn default() -> Self {
        Self {
            lowercase: true,
            remove_accents: false,
            remove_punctuation: false,
            remove_digits: false,
            remove_extra_spaces: true,
            normalize_unicode: true,
        }
    }
}

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

    pub fn lowercase(mut self, value: bool) -> Self {
        self.lowercase = value;
        self
    }

    pub fn remove_accents(mut self, value: bool) -> Self {
        self.remove_accents = value;
        self
    }

    pub fn remove_punctuation(mut self, value: bool) -> Self {
        self.remove_punctuation = value;
        self
    }

    pub fn remove_digits(mut self, value: bool) -> Self {
        self.remove_digits = value;
        self
    }

    pub fn remove_extra_spaces(mut self, value: bool) -> Self {
        self.remove_extra_spaces = value;
        self
    }

    pub fn normalize_unicode(mut self, value: bool) -> Self {
        self.normalize_unicode = value;
        self
    }

    pub fn normalize(&self, text: &str) -> String {
        let mut result = text.to_string();

        if self.normalize_unicode {
            result = self.normalize_unicode_text(&result);
        }

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

        if self.remove_accents {
            result = self.remove_accents_text(&result);
        }

        if self.remove_punctuation {
            result = self.remove_punctuation_text(&result);
        }

        if self.remove_digits {
            result = self.remove_digits_text(&result);
        }

        if self.remove_extra_spaces {
            result = self.remove_extra_spaces_text(&result);
        }

        result.trim().to_string()
    }

    fn normalize_unicode_text(&self, text: &str) -> String {
        // Basic Unicode normalization (NFD)
        let mut result = String::new();
        for c in text.chars() {
            match c {
                '\u{2018}' | '\u{2019}' => result.push('\''), // Smart quotes
                '\u{201C}' | '\u{201D}' => result.push('"'),  // Smart quotes
                '\u{2013}' | '\u{2014}' => result.push('-'),  // En dash, em dash
                '\u{2026}' => result.push_str("..."),         // Ellipsis
                _ => result.push(c),
            }
        }
        result
    }

    fn remove_accents_text(&self, text: &str) -> String {
        // Basic accent removal mapping
        let accent_map: HashMap<char, char> = [
            ('à', 'a'),
            ('á', 'a'),
            ('â', 'a'),
            ('ã', 'a'),
            ('ä', 'a'),
            ('å', 'a'),
            ('è', 'e'),
            ('é', 'e'),
            ('ê', 'e'),
            ('ë', 'e'),
            ('ì', 'i'),
            ('í', 'i'),
            ('î', 'i'),
            ('ï', 'i'),
            ('ò', 'o'),
            ('ó', 'o'),
            ('ô', 'o'),
            ('õ', 'o'),
            ('ö', 'o'),
            ('ù', 'u'),
            ('ú', 'u'),
            ('û', 'u'),
            ('ü', 'u'),
            ('ý', 'y'),
            ('ÿ', 'y'),
            ('ñ', 'n'),
            ('ç', 'c'),
            ('À', 'A'),
            ('Á', 'A'),
            ('Â', 'A'),
            ('Ã', 'A'),
            ('Ä', 'A'),
            ('Å', 'A'),
            ('È', 'E'),
            ('É', 'E'),
            ('Ê', 'E'),
            ('Ë', 'E'),
            ('Ì', 'I'),
            ('Í', 'I'),
            ('Î', 'I'),
            ('Ï', 'I'),
            ('Ò', 'O'),
            ('Ó', 'O'),
            ('Ô', 'O'),
            ('Õ', 'O'),
            ('Ö', 'O'),
            ('Ù', 'U'),
            ('Ú', 'U'),
            ('Û', 'U'),
            ('Ü', 'U'),
            ('Ý', 'Y'),
            ('Ÿ', 'Y'),
            ('Ñ', 'N'),
            ('Ç', 'C'),
        ]
        .iter()
        .cloned()
        .collect();

        text.chars()
            .map(|c| accent_map.get(&c).copied().unwrap_or(c))
            .collect()
    }

    fn remove_punctuation_text(&self, text: &str) -> String {
        text.chars().filter(|c| !c.is_ascii_punctuation()).collect()
    }

    fn remove_digits_text(&self, text: &str) -> String {
        text.chars().filter(|c| !c.is_ascii_digit()).collect()
    }

    fn remove_extra_spaces_text(&self, text: &str) -> String {
        WHITESPACE_RE.replace_all(text, " ").to_string()
    }
}

// ============================================================================
// Text Cleaning
// ============================================================================

#[derive(Debug, Clone)]
pub struct TextCleaner {
    remove_urls: bool,
    remove_emails: bool,
    remove_html: bool,
    remove_mentions: bool,
    remove_hashtags: bool,
    remove_special_chars: bool,
}

impl Default for TextCleaner {
    fn default() -> Self {
        Self {
            remove_urls: true,
            remove_emails: true,
            remove_html: true,
            remove_mentions: false,
            remove_hashtags: false,
            remove_special_chars: false,
        }
    }
}

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

    pub fn remove_urls(mut self, value: bool) -> Self {
        self.remove_urls = value;
        self
    }

    pub fn remove_emails(mut self, value: bool) -> Self {
        self.remove_emails = value;
        self
    }

    pub fn remove_html(mut self, value: bool) -> Self {
        self.remove_html = value;
        self
    }

    pub fn remove_mentions(mut self, value: bool) -> Self {
        self.remove_mentions = value;
        self
    }

    pub fn remove_hashtags(mut self, value: bool) -> Self {
        self.remove_hashtags = value;
        self
    }

    pub fn remove_special_chars(mut self, value: bool) -> Self {
        self.remove_special_chars = value;
        self
    }

    pub fn clean(&self, text: &str) -> String {
        let mut result = text.to_string();

        if self.remove_urls {
            result = self.remove_urls_from_text(&result);
        }

        if self.remove_emails {
            result = self.remove_emails_from_text(&result);
        }

        if self.remove_html {
            result = self.remove_html_from_text(&result);
        }

        if self.remove_mentions {
            result = self.remove_mentions_from_text(&result);
        }

        if self.remove_hashtags {
            result = self.remove_hashtags_from_text(&result);
        }

        if self.remove_special_chars {
            result = self.remove_special_chars_from_text(&result);
        }

        // Clean up extra spaces
        WHITESPACE_RE.replace_all(&result, " ").trim().to_string()
    }

    fn remove_urls_from_text(&self, text: &str) -> String {
        URL_RE.replace_all(text, "").to_string()
    }

    fn remove_emails_from_text(&self, text: &str) -> String {
        EMAIL_RE.replace_all(text, "").to_string()
    }

    fn remove_html_from_text(&self, text: &str) -> String {
        HTML_RE.replace_all(text, "").to_string()
    }

    fn remove_mentions_from_text(&self, text: &str) -> String {
        MENTION_RE.replace_all(text, "").to_string()
    }

    fn remove_hashtags_from_text(&self, text: &str) -> String {
        HASHTAG_RE.replace_all(text, "").to_string()
    }

    fn remove_special_chars_from_text(&self, text: &str) -> String {
        text.chars()
            .filter(|c| c.is_alphanumeric() || c.is_whitespace())
            .collect()
    }
}

// ============================================================================
// Text Augmentation
// ============================================================================

#[derive(Debug, Clone, Default)]
pub struct TextAugmenter {
    // RNG is created locally in methods to avoid Send/Sync issues with ThreadRng
}

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

    pub fn synonym_replacement(&self, text: &str, replacement_prob: f32) -> String {
        // ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
        let mut rng = Random::seed(42);
        // Simple word replacement (would need a synonym dictionary in practice)
        let synonyms: HashMap<&str, Vec<&str>> = [
            ("good", vec!["great", "excellent", "wonderful"]),
            ("bad", vec!["terrible", "awful", "horrible"]),
            ("big", vec!["large", "huge", "enormous"]),
            ("small", vec!["tiny", "little", "miniature"]),
        ]
        .iter()
        .cloned()
        .collect();

        let words: Vec<&str> = text.split_whitespace().collect();
        let mut result_words = Vec::new();

        for word in words {
            if rng.random::<f32>() < replacement_prob {
                if let Some(syns) = synonyms.get(word.to_lowercase().as_str()) {
                    let idx = rng.gen_range(0..syns.len());
                    result_words.push(syns[idx].to_string());
                } else {
                    result_words.push(word.to_string());
                }
            } else {
                result_words.push(word.to_string());
            }
        }

        result_words.join(" ")
    }

    pub fn random_insertion(&self, text: &str, insertion_prob: f32) -> String {
        // ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
        let mut rng = Random::seed(42);
        let words: Vec<&str> = text.split_whitespace().collect();
        let mut result_words = Vec::new();

        // Simple words to insert (would need better vocabulary in practice)
        let insert_words = ["the", "a", "an", "very", "really", "quite"];

        for word in words {
            result_words.push(word.to_string());

            if rng.random::<f32>() < insertion_prob {
                let idx = rng.gen_range(0..insert_words.len());
                result_words.push(insert_words[idx].to_string());
            }
        }

        result_words.join(" ")
    }

    pub fn random_deletion(&self, text: &str, deletion_prob: f32) -> String {
        // ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
        let mut rng = Random::seed(42);
        let words: Vec<&str> = text.split_whitespace().collect();
        let mut result_words = Vec::new();

        for word in words {
            if rng.random::<f32>() >= deletion_prob {
                result_words.push(word.to_string());
            }
        }

        if result_words.is_empty() {
            text.to_string()
        } else {
            result_words.join(" ")
        }
    }

    pub fn random_swap(&self, text: &str, swap_prob: f32) -> String {
        // ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
        let mut rng = Random::seed(42);
        let mut words: Vec<String> = text.split_whitespace().map(|s| s.to_string()).collect();

        if words.len() < 2 {
            return text.to_string();
        }

        for i in 0..words.len() {
            if rng.random::<f32>() < swap_prob {
                let j = rng.gen_range(0..words.len());
                words.swap(i, j);
            }
        }

        words.join(" ")
    }

    pub fn back_translation_simulation(&self, text: &str) -> String {
        // Simulate back translation by introducing small changes
        let mut result = self.synonym_replacement(text, 0.1);
        result = self.random_swap(&result, 0.05);
        result
    }

    /// Apply augmentation to text with default parameters
    pub fn augment(&self, text: &str) -> String {
        // Apply a combination of augmentation techniques with low probabilities
        let mut result = self.synonym_replacement(text, 0.1);
        result = self.random_insertion(&result, 0.05);
        result = self.random_deletion(&result, 0.05);
        result = self.random_swap(&result, 0.05);
        result
    }
}

// ============================================================================
// Padding and Truncation
// ============================================================================

#[derive(Debug, Clone, Copy)]
pub enum PaddingStrategy {
    Left,
    Right,
    Center,
}

#[derive(Debug, Clone, Copy)]
pub enum TruncationStrategy {
    Left,
    Right,
    Center,
}

pub fn pad_sequence(
    tokens: &[u32],
    max_length: usize,
    pad_token_id: u32,
    strategy: PaddingStrategy,
) -> Vec<u32> {
    if tokens.len() >= max_length {
        return tokens.to_vec();
    }

    let padding_needed = max_length - tokens.len();
    let mut result = Vec::with_capacity(max_length);

    match strategy {
        PaddingStrategy::Left => {
            result.extend(vec![pad_token_id; padding_needed]);
            result.extend_from_slice(tokens);
        }
        PaddingStrategy::Right => {
            result.extend_from_slice(tokens);
            result.extend(vec![pad_token_id; padding_needed]);
        }
        PaddingStrategy::Center => {
            let left_padding = padding_needed / 2;
            let right_padding = padding_needed - left_padding;
            result.extend(vec![pad_token_id; left_padding]);
            result.extend_from_slice(tokens);
            result.extend(vec![pad_token_id; right_padding]);
        }
    }

    result
}

pub fn truncate_sequence(
    tokens: &[u32],
    max_length: usize,
    strategy: TruncationStrategy,
) -> Vec<u32> {
    if tokens.len() <= max_length {
        return tokens.to_vec();
    }

    match strategy {
        TruncationStrategy::Left => tokens[tokens.len() - max_length..].to_vec(),
        TruncationStrategy::Right => tokens[..max_length].to_vec(),
        TruncationStrategy::Center => {
            let remove_from_each_side = (tokens.len() - max_length) / 2;
            let start = remove_from_each_side;
            let end = tokens.len() - (tokens.len() - max_length - remove_from_each_side);
            tokens[start..end].to_vec()
        }
    }
}

pub fn pad_and_truncate_sequences(
    sequences: &[Vec<u32>],
    max_length: Option<usize>,
    pad_token_id: u32,
    padding_strategy: PaddingStrategy,
    truncation_strategy: TruncationStrategy,
) -> Vec<Vec<u32>> {
    let max_len =
        max_length.unwrap_or_else(|| sequences.iter().map(|seq| seq.len()).max().unwrap_or(0));

    sequences
        .iter()
        .map(|seq| {
            let truncated = truncate_sequence(seq, max_len, truncation_strategy);
            pad_sequence(&truncated, max_len, pad_token_id, padding_strategy)
        })
        .collect()
}

// ============================================================================
// Encoding Schemes
// ============================================================================

pub fn one_hot_encode(token_ids: &[u32], vocab_size: usize) -> Vec<Vec<f32>> {
    token_ids
        .iter()
        .map(|&token_id| {
            let mut encoding = vec![0.0; vocab_size];
            if (token_id as usize) < vocab_size {
                encoding[token_id as usize] = 1.0;
            }
            encoding
        })
        .collect()
}

pub fn label_encode(labels: &[String]) -> (Vec<u32>, HashMap<String, u32>) {
    let mut label_to_id = HashMap::new();
    let mut id_counter = 0u32;

    let encoded: Vec<u32> = labels
        .iter()
        .map(|label| {
            if let Some(&id) = label_to_id.get(label) {
                id
            } else {
                let id = id_counter;
                label_to_id.insert(label.clone(), id);
                id_counter += 1;
                id
            }
        })
        .collect();

    (encoded, label_to_id)
}

// ============================================================================
// Unified Preprocessing Pipeline
// ============================================================================

/// Unified text preprocessing pipeline that combines all preprocessing steps
#[derive(Debug)]
pub struct TextPreprocessingPipeline {
    normalizer: Option<TextNormalizer>,
    cleaner: Option<TextCleaner>,
    augmenter: Option<TextAugmenter>,
    custom_steps: Vec<Box<dyn PreprocessingStep>>,
}

/// Trait for custom preprocessing steps
pub trait PreprocessingStep: std::fmt::Debug + Send + Sync {
    fn process(&self, text: &str) -> Result<String>;
    fn name(&self) -> &str;
}

/// Wrapper for custom closures that implement PreprocessingStep
pub struct CustomStep<F>
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    function: F,
    name: String,
}

impl<F> CustomStep<F>
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    pub fn new(function: F, name: String) -> Self {
        Self { function, name }
    }
}

impl<F> std::fmt::Debug for CustomStep<F>
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomStep")
            .field("name", &self.name)
            .finish()
    }
}

impl<F> PreprocessingStep for CustomStep<F>
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    fn process(&self, text: &str) -> Result<String> {
        Ok((self.function)(text))
    }

    fn name(&self) -> &str {
        &self.name
    }
}

impl Clone for TextPreprocessingPipeline {
    fn clone(&self) -> Self {
        Self {
            normalizer: self.normalizer.clone(),
            cleaner: self.cleaner.clone(),
            augmenter: self.augmenter.clone(),
            custom_steps: Vec::new(), // Custom steps can't be cloned, so we create an empty vec
        }
    }
}

impl TextPreprocessingPipeline {
    pub fn new() -> Self {
        Self {
            normalizer: None,
            cleaner: None,
            augmenter: None,
            custom_steps: Vec::new(),
        }
    }

    pub fn with_normalization(mut self, normalizer: TextNormalizer) -> Self {
        self.normalizer = Some(normalizer);
        self
    }

    pub fn with_cleaning(mut self, cleaner: TextCleaner) -> Self {
        self.cleaner = Some(cleaner);
        self
    }

    pub fn with_augmentation(mut self, augmenter: TextAugmenter) -> Self {
        self.augmenter = Some(augmenter);
        self
    }

    pub fn add_custom_step(mut self, step: Box<dyn PreprocessingStep>) -> Self {
        self.custom_steps.push(step);
        self
    }

    /// Process a single text through the entire pipeline
    pub fn process_text(&self, text: &str) -> Result<String> {
        let mut result = text.to_string();

        // Apply normalization
        if let Some(normalizer) = &self.normalizer {
            result = normalizer.normalize(&result);
        }

        // Apply cleaning
        if let Some(cleaner) = &self.cleaner {
            result = cleaner.clean(&result);
        }

        // Apply custom steps
        for step in &self.custom_steps {
            result = step.process(&result)?;
        }

        // Apply augmentation (typically for training data)
        if let Some(augmenter) = &self.augmenter {
            result = augmenter.augment(&result);
        }

        Ok(result)
    }

    /// Process multiple texts in batch
    pub fn process_batch(&self, texts: &[String]) -> Result<Vec<String>> {
        texts.iter().map(|text| self.process_text(text)).collect()
    }

    /// Process texts in parallel for better performance
    pub fn process_batch_parallel(&self, texts: &[String]) -> Result<Vec<String>> {
        use scirs2_core::parallel_ops::*;

        texts
            .par_iter()
            .map(|text| self.process_text(text))
            .collect()
    }

    /// Get a summary of the pipeline steps
    pub fn summary(&self) -> Vec<String> {
        let mut steps = Vec::new();

        if self.normalizer.is_some() {
            steps.push("Text Normalization".to_string());
        }

        if self.cleaner.is_some() {
            steps.push("Text Cleaning".to_string());
        }

        for step in &self.custom_steps {
            steps.push(format!("Custom: {}", step.name()));
        }

        if self.augmenter.is_some() {
            steps.push("Text Augmentation".to_string());
        }

        steps
    }
}

impl Default for TextPreprocessingPipeline {
    fn default() -> Self {
        Self::new()
            .with_normalization(TextNormalizer::default())
            .with_cleaning(TextCleaner::default())
    }
}

/// Common preprocessing steps as implementations of PreprocessingStep
#[derive(Debug)]
pub struct RemoveExtraWhitespaceStep;

impl PreprocessingStep for RemoveExtraWhitespaceStep {
    fn process(&self, text: &str) -> Result<String> {
        Ok(WHITESPACE_RE.replace_all(text, " ").trim().to_string())
    }

    fn name(&self) -> &str {
        "Remove Extra Whitespace"
    }
}

#[derive(Debug)]
pub struct MinLengthFilterStep {
    min_length: usize,
}

impl MinLengthFilterStep {
    pub fn new(min_length: usize) -> Self {
        Self { min_length }
    }
}

impl PreprocessingStep for MinLengthFilterStep {
    fn process(&self, text: &str) -> Result<String> {
        if text.len() < self.min_length {
            Err(TextError::ValidationError(format!(
                "Text too short: {} < {}",
                text.len(),
                self.min_length
            )))
        } else {
            Ok(text.to_string())
        }
    }

    fn name(&self) -> &str {
        "Minimum Length Filter"
    }
}

#[derive(Debug)]
pub struct MaxLengthTruncateStep {
    max_length: usize,
}

impl MaxLengthTruncateStep {
    pub fn new(max_length: usize) -> Self {
        Self { max_length }
    }
}

impl PreprocessingStep for MaxLengthTruncateStep {
    fn process(&self, text: &str) -> Result<String> {
        if text.len() > self.max_length {
            Ok(text.chars().take(self.max_length).collect())
        } else {
            Ok(text.to_string())
        }
    }

    fn name(&self) -> &str {
        "Maximum Length Truncate"
    }
}

/// Preprocessing utilities for common operations
pub struct PreprocessingUtils;

impl PreprocessingUtils {
    /// Create a basic preprocessing pipeline for classification tasks
    pub fn classification_pipeline() -> TextPreprocessingPipeline {
        TextPreprocessingPipeline::new()
            .with_normalization(
                TextNormalizer::new()
                    .lowercase(true)
                    .remove_extra_spaces(true)
                    .normalize_unicode(true),
            )
            .with_cleaning(
                TextCleaner::new()
                    .remove_urls(true)
                    .remove_emails(true)
                    .remove_special_chars(true),
            )
            .add_custom_step(Box::new(RemoveExtraWhitespaceStep))
    }

    /// Create a preprocessing pipeline for language modeling
    pub fn language_modeling_pipeline() -> TextPreprocessingPipeline {
        TextPreprocessingPipeline::new()
            .with_normalization(
                TextNormalizer::new()
                    .normalize_unicode(true)
                    .remove_extra_spaces(true),
            )
            .add_custom_step(Box::new(RemoveExtraWhitespaceStep))
            .add_custom_step(Box::new(MinLengthFilterStep::new(10)))
    }

    /// Create a preprocessing pipeline for machine translation
    pub fn translation_pipeline() -> TextPreprocessingPipeline {
        TextPreprocessingPipeline::new()
            .with_normalization(
                TextNormalizer::new()
                    .normalize_unicode(true)
                    .remove_extra_spaces(true),
            )
            .add_custom_step(Box::new(RemoveExtraWhitespaceStep))
            .add_custom_step(Box::new(MaxLengthTruncateStep::new(512)))
    }

    /// Validate and filter texts based on criteria
    pub fn filter_texts(
        texts: &[String],
        min_length: Option<usize>,
        max_length: Option<usize>,
        allowed_chars: Option<&str>,
    ) -> Vec<String> {
        texts
            .iter()
            .filter(|text| {
                // Length checks
                if let Some(min) = min_length {
                    if text.len() < min {
                        return false;
                    }
                }
                if let Some(max) = max_length {
                    if text.len() > max {
                        return false;
                    }
                }

                // Character validation
                if let Some(allowed) = allowed_chars {
                    let allowed_set: std::collections::HashSet<char> = allowed.chars().collect();
                    for ch in text.chars() {
                        if !allowed_set.contains(&ch) && !ch.is_whitespace() {
                            return false;
                        }
                    }
                }

                true
            })
            .cloned()
            .collect()
    }

    /// Batch statistics for analyzing preprocessing effects
    pub fn compute_batch_stats(texts: &[String]) -> PreprocessingStats {
        let total_texts = texts.len();
        let total_chars: usize = texts.iter().map(|t| t.len()).sum();
        let total_words: usize = texts.iter().map(|t| t.split_whitespace().count()).sum();

        let avg_chars = if total_texts > 0 {
            total_chars as f32 / total_texts as f32
        } else {
            0.0
        };
        let avg_words = if total_texts > 0 {
            total_words as f32 / total_texts as f32
        } else {
            0.0
        };

        let min_chars = texts.iter().map(|t| t.len()).min().unwrap_or(0);
        let max_chars = texts.iter().map(|t| t.len()).max().unwrap_or(0);

        PreprocessingStats {
            total_texts,
            total_chars,
            total_words,
            avg_chars_per_text: avg_chars,
            avg_words_per_text: avg_words,
            min_text_length: min_chars,
            max_text_length: max_chars,
        }
    }
}

#[derive(Debug, Clone)]
pub struct PreprocessingStats {
    pub total_texts: usize,
    pub total_chars: usize,
    pub total_words: usize,
    pub avg_chars_per_text: f32,
    pub avg_words_per_text: f32,
    pub min_text_length: usize,
    pub max_text_length: usize,
}

// ============================================================================
// Legacy functions (deprecated - use TextPreprocessingPipeline instead)
// ============================================================================

#[deprecated(
    note = "Use TextPreprocessingPipeline::classification_pipeline().process_text() instead"
)]
pub fn normalize_text(text: &str) -> String {
    TextNormalizer::default().normalize(text)
}

#[deprecated(note = "Use proper sentence segmentation libraries instead")]
pub fn split_sentences(text: &str) -> Vec<String> {
    let mut sentences = Vec::new();
    let mut current = String::new();

    for ch in text.chars() {
        current.push(ch);
        if ch == '.' || ch == '!' || ch == '?' {
            let sentence = current.trim().to_string();
            if !sentence.is_empty() {
                sentences.push(sentence);
            }
            current.clear();
        }
    }

    // Add any remaining text as a sentence
    let remaining = current.trim().to_string();
    if !remaining.is_empty() {
        sentences.push(remaining);
    }

    sentences
}

pub fn count_words(text: &str) -> usize {
    text.split_whitespace().count()
}

#[deprecated(
    note = "Use TextPreprocessingPipeline::classification_pipeline().process_text() instead"
)]
pub fn clean_text(text: &str) -> String {
    TextCleaner::default().clean(text)
}

// ============================================================================
// Optimized Batch Processing
// ============================================================================

/// High-performance batch processor for text operations
pub struct BatchProcessor {
    chunk_size: usize,
    parallel: bool,
    cache_enabled: bool,
    cache: Option<std::collections::HashMap<String, String>>,
}

impl BatchProcessor {
    pub fn new() -> Self {
        Self {
            chunk_size: 1000,
            parallel: true,
            cache_enabled: false,
            cache: None,
        }
    }

    pub fn with_chunk_size(mut self, size: usize) -> Self {
        self.chunk_size = size;
        self
    }

    pub fn with_parallel(mut self, parallel: bool) -> Self {
        self.parallel = parallel;
        self
    }

    pub fn with_cache(mut self, enable: bool) -> Self {
        self.cache_enabled = enable;
        if enable {
            self.cache = Some(std::collections::HashMap::new());
        } else {
            self.cache = None;
        }
        self
    }

    /// Process texts in optimized batches with a processing function
    pub fn process_with_function<F, T>(
        &mut self,
        texts: &[String],
        mut processor: F,
    ) -> Result<Vec<T>>
    where
        F: FnMut(&str) -> Result<T> + Send + Sync,
        T: Send + Sync,
    {
        if self.parallel && texts.len() > self.chunk_size {
            self.process_parallel_chunked(texts, processor)
        } else {
            texts.iter().map(|text| processor(text)).collect()
        }
    }

    /// Process texts with caching support
    pub fn process_with_cache<F>(
        &mut self,
        texts: &[String],
        mut processor: F,
    ) -> Result<Vec<String>>
    where
        F: FnMut(&str) -> Result<String> + Send + Sync,
    {
        let mut results = Vec::with_capacity(texts.len());

        for text in texts {
            if self.cache_enabled {
                if let Some(cache) = &self.cache {
                    if let Some(cached_result) = cache.get(text) {
                        results.push(cached_result.clone());
                        continue;
                    }
                }
            }

            let result = processor(text)?;

            if self.cache_enabled {
                if let Some(cache) = &mut self.cache {
                    cache.insert(text.clone(), result.clone());
                }
            }

            results.push(result);
        }

        Ok(results)
    }

    fn process_parallel_chunked<F, T>(&self, texts: &[String], processor: F) -> Result<Vec<T>>
    where
        F: FnMut(&str) -> Result<T> + Send + Sync,
        T: Send + Sync,
    {
        use scirs2_core::parallel_ops::*;
        use std::sync::Mutex;

        let processor = Mutex::new(processor);

        texts
            .par_chunks(self.chunk_size)
            .map(|chunk| {
                chunk
                    .iter()
                    .map(|text| {
                        let mut proc = processor.lock().expect("lock should not be poisoned");
                        proc(text)
                    })
                    .collect::<Result<Vec<T>>>()
            })
            .collect::<Result<Vec<Vec<T>>>>()
            .map(|chunks| chunks.into_iter().flatten().collect())
    }

    /// Clear cache if enabled
    pub fn clear_cache(&mut self) {
        if let Some(cache) = &mut self.cache {
            cache.clear();
        }
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> Option<(usize, usize)> {
        self.cache
            .as_ref()
            .map(|cache| (cache.len(), cache.capacity()))
    }
}

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

/// Optimized batch operations for common text processing tasks
pub struct OptimizedBatchOps;

impl OptimizedBatchOps {
    /// Optimized batch tokenization
    pub fn batch_tokenize(
        texts: &[String],
        tokenizer: &dyn crate::tokenization::Tokenizer,
        parallel: bool,
    ) -> Result<Vec<Vec<u32>>> {
        if parallel && texts.len() > 100 {
            use scirs2_core::parallel_ops::*;
            texts
                .par_iter()
                .map(|text| tokenizer.encode(text))
                .collect()
        } else {
            texts.iter().map(|text| tokenizer.encode(text)).collect()
        }
    }

    /// Optimized batch text cleaning with memory pooling
    pub fn batch_clean(texts: &[String], cleaner: &TextCleaner) -> Vec<String> {
        let mut processor = BatchProcessor::new()
            .with_parallel(true)
            .with_chunk_size(500)
            .with_cache(texts.len() > 1000);

        processor
            .process_with_cache(texts, |text| Ok(cleaner.clean(text)))
            .unwrap_or_else(|_| texts.iter().map(|t| cleaner.clean(t)).collect())
    }

    /// Optimized batch normalization
    pub fn batch_normalize(texts: &[String], normalizer: &TextNormalizer) -> Vec<String> {
        use scirs2_core::parallel_ops::*;

        if texts.len() > 100 {
            texts
                .par_iter()
                .map(|text| normalizer.normalize(text))
                .collect()
        } else {
            texts
                .iter()
                .map(|text| normalizer.normalize(text))
                .collect()
        }
    }

    /// Memory-efficient batch statistics computation
    pub fn batch_statistics(texts: &[String]) -> BatchTextStats {
        use scirs2_core::parallel_ops::*;

        let chunk_size = 1000;

        if texts.len() > chunk_size {
            // Process in parallel chunks to avoid memory pressure
            let partial_stats: Vec<BatchTextStats> = texts
                .par_chunks(chunk_size)
                .map(Self::compute_chunk_stats)
                .collect();

            // Merge partial statistics
            Self::merge_stats(partial_stats)
        } else {
            Self::compute_chunk_stats(texts)
        }
    }

    fn compute_chunk_stats(texts: &[String]) -> BatchTextStats {
        let mut total_chars = 0;
        let mut total_words = 0;
        let mut min_length = usize::MAX;
        let mut max_length = 0;
        let mut char_distribution = std::collections::HashMap::new();

        for text in texts {
            let char_count = text.chars().count();
            let word_count = text.split_whitespace().count();

            total_chars += char_count;
            total_words += word_count;
            min_length = min_length.min(char_count);
            max_length = max_length.max(char_count);

            // Sample character distribution (for performance)
            if texts.len() < 10000 {
                for ch in text.chars() {
                    *char_distribution.entry(ch).or_insert(0) += 1;
                }
            }
        }

        if min_length == usize::MAX {
            min_length = 0;
        }

        BatchTextStats {
            text_count: texts.len(),
            total_chars,
            total_words,
            min_length,
            max_length,
            avg_length: if texts.is_empty() {
                0.0
            } else {
                total_chars as f64 / texts.len() as f64
            },
            avg_words: if texts.is_empty() {
                0.0
            } else {
                total_words as f64 / texts.len() as f64
            },
            char_distribution,
        }
    }

    fn merge_stats(stats: Vec<BatchTextStats>) -> BatchTextStats {
        let mut merged = BatchTextStats::default();

        for stat in stats {
            merged.text_count += stat.text_count;
            merged.total_chars += stat.total_chars;
            merged.total_words += stat.total_words;
            merged.min_length = merged.min_length.min(stat.min_length);
            merged.max_length = merged.max_length.max(stat.max_length);

            // Merge character distributions
            for (ch, count) in stat.char_distribution {
                *merged.char_distribution.entry(ch).or_insert(0) += count;
            }
        }

        // Recalculate averages
        if merged.text_count > 0 {
            merged.avg_length = merged.total_chars as f64 / merged.text_count as f64;
            merged.avg_words = merged.total_words as f64 / merged.text_count as f64;
        }

        merged
    }

    /// Optimized batch filtering with early termination
    pub fn batch_filter<F>(texts: &[String], predicate: F) -> Vec<String>
    where
        F: Fn(&str) -> bool + Send + Sync,
    {
        use scirs2_core::parallel_ops::*;

        if texts.len() > 1000 {
            texts
                .par_iter()
                .filter(|text| predicate(text))
                .cloned()
                .collect()
        } else {
            texts
                .iter()
                .filter(|text| predicate(text))
                .cloned()
                .collect()
        }
    }

    /// Memory-mapped batch processing for very large datasets
    pub fn process_large_file<F>(
        file_path: &std::path::Path,
        processor: F,
        output_path: &std::path::Path,
    ) -> Result<()>
    where
        F: Fn(&str) -> String + Send + Sync,
    {
        use std::fs::File;
        use std::io::{BufRead, BufReader, BufWriter, Write};

        let input_file = File::open(file_path)?;
        let reader = BufReader::new(input_file);

        let output_file = File::create(output_path)?;
        let mut writer = BufWriter::new(output_file);

        const BATCH_SIZE: usize = 1000;
        let mut batch = Vec::with_capacity(BATCH_SIZE);

        for line in reader.lines() {
            let line = line?;
            batch.push(line);

            if batch.len() >= BATCH_SIZE {
                // Process batch
                let processed: Vec<String> = if batch.len() > 100 {
                    use scirs2_core::parallel_ops::*;
                    batch.par_iter().map(|text| processor(text)).collect()
                } else {
                    batch.iter().map(|text| processor(text)).collect()
                };

                // Write results
                for result in processed {
                    writeln!(writer, "{result}")?;
                }

                batch.clear();
            }
        }

        // Process remaining items
        if !batch.is_empty() {
            let processed: Vec<String> = batch.iter().map(|text| processor(text)).collect();
            for result in processed {
                writeln!(writer, "{result}")?;
            }
        }

        writer.flush()?;
        Ok(())
    }
}

#[derive(Debug, Clone, Default)]
pub struct BatchTextStats {
    pub text_count: usize,
    pub total_chars: usize,
    pub total_words: usize,
    pub min_length: usize,
    pub max_length: usize,
    pub avg_length: f64,
    pub avg_words: f64,
    pub char_distribution: std::collections::HashMap<char, usize>,
}

/// Type alias for streaming batch processor function
type StreamingProcessorFn<T> = Box<dyn FnMut(&[T]) -> Result<Vec<T>>>;

/// Streaming batch processor for memory-efficient processing of large datasets
pub struct StreamingBatchProcessor<T> {
    batch_size: usize,
    buffer: Vec<T>,
    processor: StreamingProcessorFn<T>,
}

impl<T> StreamingBatchProcessor<T> {
    pub fn new<F>(batch_size: usize, processor: F) -> Self
    where
        F: FnMut(&[T]) -> Result<Vec<T>> + 'static,
    {
        Self {
            batch_size,
            buffer: Vec::with_capacity(batch_size),
            processor: Box::new(processor),
        }
    }

    pub fn add_item(&mut self, item: T) -> Result<Option<Vec<T>>> {
        self.buffer.push(item);

        if self.buffer.len() >= self.batch_size {
            let result = (self.processor)(&self.buffer)?;
            self.buffer.clear();
            Ok(Some(result))
        } else {
            Ok(None)
        }
    }

    pub fn finish(mut self) -> Result<Vec<T>> {
        if !self.buffer.is_empty() {
            (self.processor)(&self.buffer)
        } else {
            Ok(Vec::new())
        }
    }
}