Skip to main content

is_it_slop_preprocessing/pre_processor/
cleaner.rs

1//! Text cleaning for consistent preprocessing.
2//!
3//! This module provides two-stage text cleaning:
4//!
5//! 1. **Universal Cleaning** (always applied):
6//!    - HTML entities (`"`, `'`, etc.)
7//!    - Encoding artifacts (malformed UTF-8, byte order marks)
8//!    - Markdown formatting (bold, headers, bullets, code blocks)
9//!    - Cyrillic encoding corruption artifacts
10//!    - Whitespace normalization
11//!
12//! 2. **Dataset Artifact Cleaning** (training only):
13//!    - Academic citations `[1]`, `[2]`
14//!    - News wire metadata (datelines, agency attributions)
15//!    - Academic section headers
16//!    - Timestamps and timezone abbreviations
17//!
18//! The two-stage approach ensures consistent tokenization while preventing the model
19//! from learning dataset collection artifacts as AI signals.
20//!
21//! # Usage
22//!
23//! ```rust
24//! use is_it_slop_preprocessing::pre_processor::{
25//!     text_cleaner_for_inference, text_cleaner_for_training,
26//! };
27//!
28//! // Inference: Universal cleaning only
29//! let cleaner = text_cleaner_for_inference();
30//! let cleaned = cleaner.clean("Text with "quotes"");
31//!
32//! // Training: Universal + dataset artifact cleaning
33//! let cleaner = text_cleaner_for_training();
34//! let cleaned = cleaner.clean("WASHINGTON — News text [1]");
35//! ```
36
37use std::{borrow::Cow, sync::LazyLock};
38
39use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
40use regex::Regex;
41
42/// Universal text cleaning - applied at BOTH training and inference
43#[derive(Debug, Clone)]
44struct UniversalCleaner {
45    // Encoding artifacts
46    zero_width_spaces: Regex,
47    non_breaking_space: Regex,
48    // Malformed UTF-8 quotes/dashes
49    right_single_quote: Regex,
50    left_double_quote: Regex,
51    right_double_quote: Regex,
52    em_dash_1: Regex,
53    en_dash: Regex,
54    // HTML entities
55    html_apostrophe: Regex,
56    html_quote: Regex,
57    html_amp: Regex,
58    html_lt: Regex,
59    html_gt: Regex,
60    html_nbsp: Regex,
61    html_numeric: Regex,
62    partial_apostrophe: Regex,
63    partial_quote: Regex,
64    // HTML tags
65    br_tag: Regex,
66    common_tags: Regex,
67    // Whitespace normalization
68    multiple_spaces: Regex,
69    multiple_newlines: Regex,
70    space_newline: Regex,
71    newline_space: Regex,
72}
73
74impl UniversalCleaner {
75    fn new() -> Self {
76        Self {
77            // Encoding artifacts
78            zero_width_spaces: Regex::new(r"[\u{200B}-\u{200D}\u{FEFF}]").unwrap(),
79            non_breaking_space: Regex::new(r"\u{00A0}").unwrap(),
80
81            // Malformed UTF-8
82            right_single_quote: Regex::new(r"’").unwrap(),
83            left_double_quote: Regex::new(r"“").unwrap(),
84            right_double_quote: Regex::new(r"â€\u{009D}").unwrap(),
85            em_dash_1: Regex::new(r#"â€""#).unwrap(),
86            en_dash: Regex::new(r#"â€""#).unwrap(),
87
88            // HTML entities
89            html_apostrophe: Regex::new(r"'").unwrap(),
90            html_quote: Regex::new(r""").unwrap(),
91            html_amp: Regex::new(r"&").unwrap(),
92            html_lt: Regex::new(r"<").unwrap(),
93            html_gt: Regex::new(r">").unwrap(),
94            html_nbsp: Regex::new(r" ").unwrap(),
95            html_numeric: Regex::new(r"&#(\d+);").unwrap(),
96            partial_apostrophe: Regex::new(r"&?#39;?").unwrap(),
97            partial_quote: Regex::new(r"&?quot;").unwrap(),
98
99            // HTML tags
100            br_tag: Regex::new(r"<br\s*/?>").unwrap(),
101            common_tags: Regex::new(r"</?(p|div|span|strong|em|b|i|ul|ol|li|h[1-6])>").unwrap(),
102
103            // Whitespace
104            multiple_spaces: Regex::new(r"  +").unwrap(),
105            multiple_newlines: Regex::new(r"\n\n\n+").unwrap(),
106            space_newline: Regex::new(r" \n").unwrap(),
107            newline_space: Regex::new(r"\n ").unwrap(),
108        }
109    }
110
111    fn clean<'a>(&self, mut text: Cow<'a, str>) -> Cow<'a, str> {
112        macro_rules! apply {
113            ($regex:expr, $replacement:expr) => {
114                if let Cow::Owned(new) = $regex.replace_all(text.as_ref(), $replacement) {
115                    text = Cow::Owned(new);
116                }
117            };
118        }
119
120        apply!(self.zero_width_spaces, "");
121        apply!(self.non_breaking_space, " ");
122        apply!(self.right_single_quote, "'");
123        apply!(self.left_double_quote, "\"");
124        apply!(self.right_double_quote, "\"");
125        apply!(self.em_dash_1, "—");
126        apply!(self.en_dash, "–");
127        apply!(self.html_apostrophe, "'");
128        apply!(self.html_quote, "\"");
129        apply!(self.html_amp, "&");
130        apply!(self.html_lt, "<");
131        apply!(self.html_gt, ">");
132        apply!(self.html_nbsp, " ");
133        apply!(self.html_numeric, "");
134        apply!(self.partial_apostrophe, "'");
135        apply!(self.partial_quote, "\"");
136        apply!(self.br_tag, " ");
137        apply!(self.common_tags, "");
138        apply!(self.multiple_spaces, " ");
139        apply!(self.multiple_newlines, "\n\n");
140        apply!(self.space_newline, "\n");
141        apply!(self.newline_space, "\n");
142
143        text
144    }
145}
146
147impl Default for UniversalCleaner {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153/// Dataset-specific artifact cleaning - applied ONLY during training
154#[derive(Debug, Clone)]
155struct DatasetArtifactCleaner {
156    // Citation markers (Wikipedia/academic artifacts)
157    citation_with_punct: Regex,
158    malformed_citation: Regex,
159    citation_newline: Regex,
160    citation_open: Regex,
161    citation_close: Regex,
162    citation_full: Regex,
163
164    // News wire attributions
165    news_agency_parens: Regex,
166    news_agency_dash: Regex,
167    news_agency_extended: Regex,
168    news_agency_dash_extended: Regex,
169    dateline_start: Regex,
170    dateline_newline: Regex,
171    dateline_ending: Regex,
172    dateline_cities_start: Regex,
173    dateline_cities_newline: Regex,
174    state_abbreviations: Regex,
175    em_dash_parens: Regex,
176
177    // Academic headers (dataset collection artifacts)
178    academic_keywords: Regex,
179    academic_section_headers: Regex,
180    wikipedia_headers: Regex,
181    wikipedia_headers_start: Regex,
182    description_header: Regex,
183    description_header_start: Regex,
184
185    // Timestamp markers (news metadata)
186    timezone_abbrev: Regex,
187    time_pattern: Regex,
188
189    // Academic prompts (dataset-specific)
190    academic_prompt_start: Regex,
191    academic_prompt_newline: Regex,
192
193    // Numbered lists (when at document start - likely table of contents artifacts)
194    numbered_start: Regex,
195    numbered_newline: Regex,
196}
197
198impl DatasetArtifactCleaner {
199    fn new() -> Self {
200        Self {
201            // Citations
202            citation_with_punct: Regex::new(r"\[\d+\]([\.,;:\)\]])?").unwrap(),
203            malformed_citation: Regex::new(r"\s+\d+\]([\.,;])?").unwrap(),
204            citation_newline: Regex::new(r"\[\d+\]\s*\n").unwrap(),
205            citation_open: Regex::new(r"\[\d+").unwrap(),
206            citation_close: Regex::new(r"\d+\]").unwrap(),
207            citation_full: Regex::new(r"\[\d+\]").unwrap(),
208
209            // News wire
210            news_agency_parens: Regex::new(r"\s*\((?:AP|AFP|Reuters|UPI|Bloomberg)\)\s*").unwrap(),
211            news_agency_dash: Regex::new(r"\b(?:AP|AFP|Reuters|UPI|Bloomberg)\s*[-—]\s*").unwrap(),
212            news_agency_extended: Regex::new(r"\s*\([A-Z]{2,}\)\s*").unwrap(),
213            news_agency_dash_extended: Regex::new(r"\b[A-Z]{2,}\s*[-—]\s*").unwrap(),
214            dateline_start: Regex::new(
215                r"^(?:WASHINGTON|NEW YORK|LONDON|PARIS|BEIJING|MOSCOW|TOKYO|BERLIN|BRUSSELS|GENEVA|ROME|MADRID|SEOUL|SYDNEY|MEXICO CITY|LOS ANGELES|SAN\s*FRANCISCO|CHICAGO|BOSTON|MIAMI|ATLANTA|HOUSTON|DALLAS|PHILADELPHIA|PHOENIX|SAN DIEGO|SEATTLE|DETROIT|DENVER)(?:,\s*[A-Z][A-Za-z.]*\s*)?[,—]\s*"
216            ).unwrap(),
217            dateline_newline: Regex::new(
218                r"\n(?:WASHINGTON|NEW YORK|LONDON|PARIS|BEIJING|MOSCOW|TOKYO|BERLIN|BRUSSELS|GENEVA|ROME|MADRID|SEOUL|SYDNEY|MEXICO CITY|LOS ANGELES|SAN\s*FRANCISCO|CHICAGO|BOSTON|MIAMI|ATLANTA|HOUSTON|DALLAS|PHILADELPHIA|PHOENIX|SAN DIEGO|SEATTLE|DETROIT|DENVER)(?:,\s*[A-Za-z.]+\s*)?[,—]\s*"
219            ).unwrap(),
220            dateline_ending: Regex::new(r"—\s+(The|A)\s+").unwrap(),
221            dateline_cities_start: Regex::new(
222                r"^[A-Z][A-Z\s]+(?:,\s*(?:Ala|Ariz|Ark|Calif|Colo|Conn|Del|Fla|Ga|Ill|Ind|Kan|Ky|La|Md|Mass|Mich|Minn|Miss|Mo|Mont|Neb|Nev|N\.Y|N\.C|N\.D|Ohio|Okla|Ore|Pa|R\.I|S\.C|S\.D|Tenn|Tex|Vt|Va|Wash|W\.Va|Wis|Wyo)\.\s*)?[,—]\s*"
223            ).unwrap(),
224            dateline_cities_newline: Regex::new(
225                r"\n[A-Z][A-Z\s]+(?:,\s*(?:Ala|Ariz|Ark|Calif|Colo|Conn|Del|Fla|Ga|Ill|Ind|Kan|Ky|La|Md|Mass|Mich|Minn|Miss|Mo|Mont|Neb|Nev|N\.Y|N\.C|N\.D|Ohio|Okla|Ore|Pa|R\.I|S\.C|S\.D|Tenn|Tex|Vt|Va|Wash|W\.Va|Wis|Wyo)\.\s*)?[,—]\s*"
226            ).unwrap(),
227            state_abbreviations: Regex::new(
228                r",\s*(?:Ala|Ariz|Ark|Calif|Colo|Conn|Del|Fla|Ga|Ill|Ind|Kan|Ky|La|Md|Mass|Mich|Minn|Miss|Mo|Mont|Neb|Nev|N\.Y|N\.C|N\.D|Ohio|Okla|Ore|Pa|R\.I|S\.C|S\.D|Tenn|Tex|Vt|Va|Wash|W\.Va|Wis|Wyo)\.\s+"
229            ).unwrap(),
230            em_dash_parens: Regex::new(r"\([A-Z]+\)\s*—\s*").unwrap(),
231
232            // Academic
233            academic_keywords: Regex::new(
234                r"\b(?:ABSTRACT|BACKGROUND|OBJECTIVE|METHODS?|RESULTS?|CONCLUSIONS?|DISCUSSION|INTRODUCTION)[\s:]*"
235            ).unwrap(),
236            academic_section_headers: Regex::new(
237                r"(?:^|\n)\s*(?:BACKGROUND|OBJECTIVE|METHODS|RESULTS|CONCLUSION|CONCLUSIONS|INTRODUCTION|DISCUSSION|ABSTRACT|SUMMARY):\s*"
238            ).unwrap(),
239            wikipedia_headers: Regex::new(
240                r"\.\s*(?:History|Biography|Early life|Background|Career|Personal life|Death|Legacy|Education|Awards|References|External links)\s*\n"
241            ).unwrap(),
242            wikipedia_headers_start: Regex::new(
243                r"^\s*(?:History|Biography|Early life|Background|Career|Personal life|Death|Legacy|Education|Awards|References|External links)\s*\n"
244            ).unwrap(),
245            description_header: Regex::new(r"\.\s*Description\s*\n").unwrap(),
246            description_header_start: Regex::new(r"^\s*Description\s*\n").unwrap(),
247
248            // Timestamps
249            timezone_abbrev: Regex::new(r"\s+(?:EST|EDT|CST|CDT|MST|MDT|PST|PDT|GMT|UTC)([,\.]?)\s+").unwrap(),
250            time_pattern: Regex::new(
251                r"\s+at\s+\d{1,2}:\d{2}\s*(?:AM|PM|am|pm)?\s*(?:EST|EDT|CST|CDT|MST|MDT|PST|PDT|GMT|UTC)?\s*[,\.]?"
252            ).unwrap(),
253
254            // Academic prompts
255            academic_prompt_start: Regex::new(r"^This (?:paper|study|article|abstract|research|work)\s+(?:presents|discusses|examines|explores|investigates|demonstrates|shows|describes)\s*").unwrap(),
256            academic_prompt_newline: Regex::new(r"\nThis (?:paper|study|article|abstract|research|work)\s+(?:presents|discusses|examines|explores|investigates|demonstrates|shows|describes)\s*").unwrap(),
257
258            // Numbered lists
259            numbered_start: Regex::new(r"^\d+\.\s+").unwrap(),
260            numbered_newline: Regex::new(r"\n\d+\.\s+").unwrap(),
261        }
262    }
263
264    fn clean<'a>(&self, mut text: Cow<'a, str>) -> Cow<'a, str> {
265        // let mut text = text.into();
266        macro_rules! apply {
267            ($regex:expr, $replacement:expr) => {
268                if let Cow::Owned(new) = $regex.replace_all(&text, $replacement) {
269                    text = Cow::Owned(new);
270                }
271            };
272        }
273        // Citations
274        apply!(self.citation_with_punct, "$1");
275        apply!(self.malformed_citation, "$1");
276        apply!(self.citation_newline, "\n");
277        apply!(self.citation_open, "");
278        apply!(self.citation_close, "");
279        apply!(self.citation_full, "");
280
281        // News wire
282        apply!(self.em_dash_parens, "— ");
283        apply!(self.news_agency_parens, "");
284        apply!(self.news_agency_dash, "");
285        apply!(self.news_agency_extended, " ");
286        apply!(self.news_agency_dash_extended, "");
287        apply!(self.dateline_start, "");
288        apply!(self.dateline_newline, "\n");
289        apply!(self.dateline_ending, " $1 ");
290        apply!(self.state_abbreviations, ", ");
291        apply!(self.dateline_cities_start, "");
292        apply!(self.dateline_cities_newline, "\n");
293
294        // Academic
295        apply!(self.academic_keywords, "");
296        apply!(self.academic_section_headers, "\n");
297        apply!(self.wikipedia_headers, ".\n");
298        apply!(self.wikipedia_headers_start, "");
299        apply!(self.description_header, ".\n");
300        apply!(self.description_header_start, "");
301
302        // Timestamps
303        apply!(self.timezone_abbrev, "$1 ");
304        apply!(self.time_pattern, " ");
305
306        // Academic prompts
307        apply!(self.academic_prompt_start, "");
308        apply!(self.academic_prompt_newline, "\n");
309
310        // Numbered lists
311        apply!(self.numbered_start, "");
312        apply!(self.numbered_newline, "\n");
313
314        text
315    }
316}
317
318impl Default for DatasetArtifactCleaner {
319    fn default() -> Self {
320        Self::new()
321    }
322}
323
324/// Main text cleaner that combines universal and dataset-specific cleaning
325#[derive(Debug, Clone)]
326/// Two-stage text cleaner for training and inference.
327///
328/// Combines universal cleaning (always applied) with optional dataset artifact
329/// cleaning (training only).
330///
331/// # Stages
332///
333/// 1. **Dataset Artifacts** (if enabled): Remove training-specific patterns
334///    - Academic citations, news metadata, timestamps
335/// 2. **Universal Cleaning** (always): Normalize text for consistent tokenization
336///    - HTML entities, encoding artifacts, markdown formatting
337///
338/// # Usage
339///
340/// ```rust
341/// use is_it_slop_preprocessing::pre_processor::{
342///     text_cleaner_for_inference, text_cleaner_for_training,
343/// };
344///
345/// // Inference: Universal cleaning only
346/// let cleaner = text_cleaner_for_inference();
347/// let result = cleaner.clean("Text with &quot;HTML&quot;");
348///
349/// // Training: Both stages
350/// let cleaner = text_cleaner_for_training();
351/// let result = cleaner.clean("Article text [1] with citations");
352/// ```
353pub struct TextCleaner {
354    universal: UniversalCleaner,
355    dataset_artifacts: Option<DatasetArtifactCleaner>,
356}
357
358impl TextCleaner {
359    /// Clean the input text before tokenization
360    #[must_use]
361    pub fn clean<'a>(&self, text: &'a str) -> Cow<'a, str> {
362        // Apply dataset cleaning first if enabled
363        let text = self
364            .dataset_artifacts
365            .as_ref()
366            .map_or_else(|| text.into(), |cleaner| cleaner.clean(text.into()));
367
368        // Apply universal cleaning
369        let text = self.universal.clean(text);
370
371        let trimmed = text.trim().trim_matches(|c: char| c == '\'' || c == '"');
372        if trimmed.len() == text.len() {
373            text
374        } else {
375            Cow::Owned(trimmed.to_string())
376        }
377    }
378
379    /// Clean a batch of texts in parallel
380    pub fn clean_batch<T: AsRef<str> + Sync>(&self, texts: &[T]) -> Vec<String> {
381        texts
382            .par_iter()
383            .map(|text| self.clean(text.as_ref()).to_string())
384            .collect()
385    }
386}
387
388// Use lazy lock to avoid recompiling regexes on each call
389static UNIVERSAL_CLEANER: LazyLock<UniversalCleaner> = LazyLock::new(UniversalCleaner::new);
390static DATASET_ARTIFACT_CLEANER: LazyLock<DatasetArtifactCleaner> =
391    LazyLock::new(DatasetArtifactCleaner::new);
392
393static TRAINING_CLEANER: LazyLock<TextCleaner> = LazyLock::new(|| TextCleaner {
394    universal: UNIVERSAL_CLEANER.clone(),
395    dataset_artifacts: Some(DATASET_ARTIFACT_CLEANER.clone()),
396});
397
398static INFERENCE_CLEANER: LazyLock<TextCleaner> = LazyLock::new(|| TextCleaner {
399    universal: UNIVERSAL_CLEANER.clone(),
400    dataset_artifacts: None,
401});
402
403/// Create a `TextCleaner` for inference
404#[must_use]
405pub fn text_cleaner_for_inference() -> &'static TextCleaner {
406    &INFERENCE_CLEANER
407}
408
409/// Create a `TextCleaner` for training
410#[must_use]
411pub fn text_cleaner_for_training() -> &'static TextCleaner {
412    &TRAINING_CLEANER
413}
414#[cfg(test)]
415mod tests {
416    use super::*;
417
418    // ============================================================================
419    // Universal Cleaner Tests (apply to both training and inference)
420    // ============================================================================
421
422    mod universal_cleaner {
423        use super::*;
424
425        #[test]
426        fn test_zero_width_spaces() {
427            let cleaner = UniversalCleaner::new();
428            // Note: These might not be in the text when copy-pasted
429            // Test with explicit unicode escapes
430            let input = Cow::Borrowed("hello\u{200B}world");
431            let result = cleaner.clean(input);
432            // The regex removes zero-width space, but doesn't add space
433            assert_eq!(result, "helloworld");
434
435            assert_eq!(cleaner.clean("test\u{200C}ing".into()), "testing");
436            assert_eq!(cleaner.clean("no\u{200D}space".into()), "nospace");
437        }
438
439        #[test]
440        fn test_non_breaking_spaces() {
441            let cleaner = UniversalCleaner::new();
442            assert_eq!(cleaner.clean("hello\u{00A0}world".into()), "hello world");
443            // Multiple non-breaking spaces become regular spaces
444            // But then multiple_spaces regex collapses them
445            assert_eq!(
446                cleaner.clean("multiple\u{00A0}\u{00A0}spaces".into()),
447                "multiple spaces"
448            );
449        }
450
451        #[test]
452        fn test_malformed_utf8_quotes() {
453            let cleaner = UniversalCleaner::new();
454            // For now, test what we CAN match:
455            assert_eq!(cleaner.clean("It’s".into()), "It's");
456            // If the regex doesn't match, it returns unchanged:
457            assert_eq!(cleaner.clean("It's".into()), "It's"); // Already correct
458        }
459        #[test]
460        fn test_malformed_utf8_dashes() {
461            let cleaner = UniversalCleaner::new();
462            assert_eq!(cleaner.clean("em dashâ€\"here".into()), "em dash—here");
463            assert_eq!(cleaner.clean("en dashâ€\"here".into()), "en dash—here");
464        }
465
466        #[test]
467        fn test_html_entities() {
468            let cleaner = UniversalCleaner::new();
469            assert_eq!(cleaner.clean("It&#39;s great".into()), "It's great");
470            assert_eq!(cleaner.clean("&quot;Hello&quot;".into()), "\"Hello\"");
471            assert_eq!(cleaner.clean("A&amp;B".into()), "A&B");
472            assert_eq!(cleaner.clean("&lt;tag&gt;".into()), "<tag>");
473            assert_eq!(cleaner.clean("&nbsp;space".into()), " space");
474        }
475
476        #[test]
477        fn test_html_numeric_entities() {
478            let cleaner = UniversalCleaner::new();
479            // Numeric entities are removed entirely
480            assert_eq!(cleaner.clean("test&#65;here".into()), "testhere");
481            assert_eq!(cleaner.clean("&#160;space".into()), "space");
482        }
483
484        #[test]
485        fn test_partial_html_entities() {
486            let cleaner = UniversalCleaner::new();
487            assert_eq!(cleaner.clean("test#39;here".into()), "test'here");
488            assert_eq!(cleaner.clean("testquot;mark".into()), "test\"mark");
489        }
490
491        #[test]
492        fn test_html_tags() {
493            let cleaner = UniversalCleaner::new();
494            assert_eq!(cleaner.clean("Hello<br>world".into()), "Hello world");
495            assert_eq!(cleaner.clean("Hello<br/>world".into()), "Hello world");
496            assert_eq!(cleaner.clean("Hello<br />world".into()), "Hello world");
497            assert_eq!(cleaner.clean("<p>paragraph</p>".into()), "paragraph");
498            assert_eq!(cleaner.clean("<strong>bold</strong>".into()), "bold");
499            assert_eq!(
500                cleaner.clean("<div><span>nested</span></div>".into()),
501                "nested"
502            );
503        }
504
505        #[test]
506        fn test_whitespace_normalization() {
507            let cleaner = UniversalCleaner::new();
508            assert_eq!(
509                cleaner.clean("too   many    spaces".into()),
510                "too many spaces"
511            );
512            assert_eq!(
513                cleaner.clean("too\n\n\n\nmany\nlines".into()),
514                "too\n\nmany\nlines"
515            );
516            assert_eq!(
517                cleaner.clean("space before \nnewline".into()),
518                "space before\nnewline"
519            );
520            assert_eq!(
521                cleaner.clean("newline after\n space".into()),
522                "newline after\nspace"
523            );
524        }
525
526        #[test]
527        fn test_empty_and_whitespace_only() {
528            let cleaner = UniversalCleaner::new();
529            assert_eq!(cleaner.clean("".into()), "");
530            assert_eq!(cleaner.clean("   ".into()), " ");
531            assert_eq!(cleaner.clean("  \n  ".into()), "\n");
532        }
533
534        #[test]
535        fn test_no_changes_needed() {
536            let cleaner = UniversalCleaner::new();
537            let clean_text = "This is already clean text.";
538            assert_eq!(cleaner.clean(clean_text.into()), clean_text);
539        }
540
541        #[test]
542        fn test_multiple_issues() {
543            let cleaner = UniversalCleaner::new();
544            let input = "It&#39;s  <strong>working</strong>&nbsp;&nbsp;fine";
545            let expected = "It's working fine";
546            assert_eq!(cleaner.clean(input.into()), expected);
547        }
548
549        #[test]
550        fn test_accepts_string() {
551            let cleaner = UniversalCleaner::new();
552            let owned = String::from("test&#39;s");
553            assert_eq!(cleaner.clean(owned.into()), "test's");
554        }
555
556        #[test]
557        fn test_accepts_str() {
558            let cleaner = UniversalCleaner::new();
559            assert_eq!(cleaner.clean("test&#39;s".into()), "test's");
560        }
561    }
562
563    // ============================================================================
564    // Dataset Artifact Cleaner Tests (training only)
565    // ============================================================================
566
567    mod dataset_artifact_cleaner {
568        use super::*;
569
570        #[test]
571        fn test_citation_markers() {
572            let cleaner = DatasetArtifactCleaner::new();
573            assert_eq!(
574                cleaner.clean("This is a fact[1].".into()),
575                "This is a fact."
576            );
577            assert_eq!(
578                cleaner.clean("Multiple[1][2][3] refs".into()),
579                "Multiple refs"
580            );
581            assert_eq!(cleaner.clean("Test[123].".into()), "Test.");
582            assert_eq!(
583                cleaner.clean("Test[1], continues".into()),
584                "Test, continues"
585            );
586        }
587
588        #[test]
589        fn test_malformed_citations() {
590            let cleaner = DatasetArtifactCleaner::new();
591            assert_eq!(cleaner.clean("Test 1].".into()), "Test.");
592            assert_eq!(cleaner.clean("Test 42], here".into()), "Test, here");
593        }
594
595        #[test]
596        fn test_citation_with_newline() {
597            let cleaner = DatasetArtifactCleaner::new();
598            assert_eq!(cleaner.clean("Test[1].\nNext".into()), "Test.\nNext");
599        }
600
601        #[test]
602        fn test_news_agency_parentheses() {
603            let cleaner = DatasetArtifactCleaner::new();
604            assert_eq!(cleaner.clean("(AP) The story".into()), "The story");
605            assert_eq!(
606                cleaner.clean("(Reuters) Breaking news".into()),
607                "Breaking news"
608            );
609            assert_eq!(cleaner.clean("(UPI) Update".into()), "Update");
610            assert_eq!(cleaner.clean("(AFP) Report".into()), "Report");
611            assert_eq!(cleaner.clean("(Bloomberg) Markets".into()), "Markets");
612        }
613
614        #[test]
615        fn test_news_agency_dash() {
616            let cleaner = DatasetArtifactCleaner::new();
617            assert_eq!(cleaner.clean("AP - The story".into()), "The story");
618            assert_eq!(cleaner.clean("Reuters — Breaking".into()), "Breaking");
619            assert_eq!(cleaner.clean("UPI - Update".into()), "Update");
620        }
621
622        #[test]
623        fn test_dateline_cities() {
624            let cleaner = DatasetArtifactCleaner::new();
625            assert_eq!(
626                cleaner.clean("WASHINGTON — The president".into()),
627                "The president"
628            );
629            assert_eq!(cleaner.clean("NEW YORK, Officials".into()), "Officials");
630            assert_eq!(cleaner.clean("LONDON — Markets".into()), "Markets");
631            assert_eq!(cleaner.clean("PARIS, The summit".into()), "The summit");
632        }
633
634        #[test]
635        fn test_dateline_cities_after_newline() {
636            let cleaner = DatasetArtifactCleaner::new();
637            assert_eq!(
638                cleaner.clean("Previous.\nWASHINGTON — Next".into()),
639                "Previous.\nNext"
640            );
641        }
642
643        #[test]
644        fn test_extended_dateline_cities() {
645            let cleaner = DatasetArtifactCleaner::new();
646            assert_eq!(cleaner.clean("TOKYO — Report".into()), "Report");
647            assert_eq!(cleaner.clean("BRUSSELS, Meeting".into()), "Meeting");
648            assert_eq!(cleaner.clean("SYDNEY — News".into()), "News");
649        }
650
651        #[test]
652        fn test_state_abbreviations() {
653            let cleaner = DatasetArtifactCleaner::new();
654            assert_eq!(cleaner.clean("City, Calif. Story".into()), "City, Story");
655            assert_eq!(cleaner.clean("Town, N.Y. News".into()), "Town, News");
656            assert_eq!(cleaner.clean("Place, Mass. Update".into()), "Place, Update");
657        }
658
659        #[test]
660        fn test_dateline_endings() {
661            let cleaner = DatasetArtifactCleaner::new();
662            assert_eq!(cleaner.clean("CITY — The story".into()), "The story");
663            assert_eq!(cleaner.clean("PLACE — A report".into()), "A report");
664        }
665
666        #[test]
667        fn test_em_dash_parentheses() {
668            let cleaner = DatasetArtifactCleaner::new();
669            assert_eq!(cleaner.clean("(AP) — Story".into()), "— Story");
670        }
671
672        #[test]
673        fn test_academic_keywords() {
674            let cleaner = DatasetArtifactCleaner::new();
675            assert_eq!(cleaner.clean("ABSTRACT: Text here".into()), "Text here");
676            assert_eq!(cleaner.clean("INTRODUCTION Text".into()), "Text");
677            assert_eq!(cleaner.clean("METHODS: Study".into()), "Study");
678            assert_eq!(cleaner.clean("RESULTS Data".into()), "Data");
679            assert_eq!(cleaner.clean("CONCLUSION: Final".into()), "Final");
680        }
681
682        #[test]
683        fn test_academic_section_headers() {
684            let cleaner = DatasetArtifactCleaner::new();
685            assert_eq!(cleaner.clean("ABSTRACT: Study".into()), "Study");
686            assert_eq!(cleaner.clean("\nMETHODS: Data".into()), "\nData");
687            assert_eq!(cleaner.clean("DISCUSSION: Findings".into()), "Findings");
688        }
689
690        #[test]
691        fn test_wikipedia_headers() {
692            let cleaner = DatasetArtifactCleaner::new();
693            assert_eq!(cleaner.clean("Text. Biography\nMore".into()), "Text.\nMore");
694            assert_eq!(
695                cleaner.clean("Info. Early life\nData".into()),
696                "Info.\nData"
697            );
698            assert_eq!(cleaner.clean("Story. Career\nNext".into()), "Story.\nNext");
699        }
700
701        #[test]
702        fn test_wikipedia_headers_at_start() {
703            let cleaner = DatasetArtifactCleaner::new();
704            assert_eq!(cleaner.clean("Biography\nText".into()), "Text");
705            assert_eq!(cleaner.clean("History\nContent".into()), "Content");
706        }
707
708        #[test]
709        fn test_description_headers() {
710            let cleaner = DatasetArtifactCleaner::new();
711            assert_eq!(
712                cleaner.clean("Intro. Description\nText".into()),
713                "Intro.\nText"
714            );
715            assert_eq!(cleaner.clean("Description\nContent".into()), "Content");
716        }
717
718        #[test]
719        fn test_timezone_abbreviations() {
720            let cleaner = DatasetArtifactCleaner::new();
721            assert_eq!(cleaner.clean("Meeting EST today".into()), "Meeting today");
722            assert_eq!(cleaner.clean("Call PST, tomorrow".into()), "Call, tomorrow");
723            assert_eq!(cleaner.clean("Event GMT. here".into()), "Event. here");
724        }
725
726        #[test]
727        fn test_time_patterns() {
728            let cleaner = DatasetArtifactCleaner::new();
729            assert_eq!(
730                cleaner.clean("Call at 3:00 PM EST today".into()),
731                "Call today"
732            );
733            assert_eq!(
734                cleaner.clean("Meeting at 10:30 tomorrow".into()),
735                "Meeting tomorrow"
736            );
737        }
738
739        #[test]
740        fn test_academic_prompts() {
741            let cleaner = DatasetArtifactCleaner::new();
742            assert_eq!(
743                cleaner.clean("This paper presents a method".into()),
744                "a method"
745            );
746            assert_eq!(cleaner.clean("This study shows results".into()), "results");
747            assert_eq!(cleaner.clean("\nThis article discusses".into()), "\n");
748        }
749
750        #[test]
751        fn test_numbered_lists() {
752            let cleaner = DatasetArtifactCleaner::new();
753            assert_eq!(cleaner.clean("1. First item".into()), "First item");
754            assert_eq!(cleaner.clean("Text\n2. Second".into()), "Text\nSecond");
755            assert_eq!(cleaner.clean("123. Many".into()), "Many");
756        }
757
758        #[test]
759        fn test_complex_news_article() {
760            let cleaner = DatasetArtifactCleaner::new();
761            let input = "WASHINGTON — (AP) The president said[1] today.";
762            let expected = "The president said today.";
763            assert_eq!(cleaner.clean(input.into()), expected);
764        }
765
766        #[test]
767        fn test_complex_academic_abstract() {
768            let cleaner = DatasetArtifactCleaner::new();
769            let input = "ABSTRACT: This study presents[1] results.\nMETHODS: Data collected.";
770            let expected = "results.\nData collected.";
771            assert_eq!(cleaner.clean(input.into()), expected);
772        }
773
774        #[test]
775        fn test_raid_bench_artifacts() {
776            let cleaner = DatasetArtifactCleaner::new();
777            assert_eq!(
778                cleaner.clean("This is important!!".into()),
779                "This is important!!"
780            );
781            assert_eq!(
782                cleaner.clean("Alert!! Please read".into()),
783                "Alert!! Please read"
784            );
785        }
786    }
787
788    // ============================================================================
789    // TextCleaner Tests (mode-specific behavior)
790    // ============================================================================
791
792    mod text_cleaner {
793        use super::*;
794
795        #[test]
796        fn test_inference_mode_universal_only() {
797            let cleaner = text_cleaner_for_inference();
798
799            // Should clean HTML entities (universal)
800            let input = "Test&#39;s working";
801            assert_eq!(cleaner.clean(input), "Test's working");
802
803            // Should NOT remove citations (dataset artifact)
804            let input = "Fact[1] remains";
805            assert_eq!(cleaner.clean(input), "Fact[1] remains");
806
807            // Should NOT remove datelines (dataset artifact)
808            let input = "WASHINGTON — Story";
809            assert_eq!(cleaner.clean(input), "WASHINGTON — Story");
810        }
811
812        #[test]
813        fn test_training_mode_both_cleaners() {
814            let cleaner = text_cleaner_for_training();
815
816            // Should clean HTML entities (universal)
817            let input = "Test&#39;s working";
818            assert_eq!(cleaner.clean(input), "Test's working");
819
820            // Should remove citations (dataset artifact)
821            let input = "Fact[1] remains";
822            assert_eq!(cleaner.clean(input), "Fact remains");
823
824            // Should remove datelines (dataset artifact)
825            let input = "WASHINGTON — Story";
826            assert_eq!(cleaner.clean(input), "Story");
827        }
828
829        #[test]
830        fn test_trimming() {
831            let cleaner = text_cleaner_for_inference();
832
833            // Leading/trailing whitespace
834            assert_eq!(cleaner.clean("  text  "), "text");
835
836            // Leading/trailing quotes
837            assert_eq!(cleaner.clean("'quote'"), "quote");
838            assert_eq!(cleaner.clean("\"quote\""), "quote");
839
840            // Both whitespace and quotes
841            assert_eq!(cleaner.clean("  'text'  "), "text");
842        }
843
844        #[test]
845        fn test_empty_after_cleaning() {
846            let cleaner = text_cleaner_for_training();
847
848            assert_eq!(cleaner.clean("   "), "");
849            assert_eq!(cleaner.clean("'\"'"), "");
850            assert_eq!(cleaner.clean("[1][2][3]"), "");
851        }
852
853        #[test]
854        fn test_complex_mixed_artifacts() {
855            let cleaner = text_cleaner_for_training();
856
857            let input = "  WASHINGTON — (AP) The &quot;president&quot; said[1]  ";
858            let expected = "The \"president\" said";
859            assert_eq!(cleaner.clean(input), expected);
860        }
861
862        #[test]
863        fn test_real_world_news_article() {
864            let cleaner = text_cleaner_for_training();
865
866            let input = "WASHINGTON, D.C. — (Reuters) President Biden announced[1] today that &quot;climate change&quot; is a priority. The announcement at 3:00 PM EST came after consultations[2][3].";
867
868            let expected = "President Biden announced today that \"climate change\" is a priority. The announcement came after consultations.";
869
870            assert_eq!(cleaner.clean(input), expected);
871        }
872
873        #[test]
874        fn test_real_world_academic_paper() {
875            let cleaner = text_cleaner_for_training();
876
877            let input = "ABSTRACT: This paper presents a novel approach[1] to text classification.\nMETHODS: We collected data from multiple sources[2].";
878
879            let expected = "a novel approach to text classification.\nWe collected data from multiple sources.";
880
881            assert_eq!(cleaner.clean(input), expected);
882        }
883
884        #[test]
885        fn test_preserves_legitimate_content() {
886            let cleaner = text_cleaner_for_inference();
887
888            // Should preserve markdown-like formatting (legitimate AI signals)
889            let input = "## Introduction\n\nThis is **important** text.";
890            assert_eq!(
891                cleaner.clean(input),
892                "## Introduction\n\nThis is **important** text."
893            );
894
895            // Should preserve bullet points
896            let input = "- First point\n- Second point";
897            assert_eq!(cleaner.clean(input), "- First point\n- Second point");
898
899            // Should preserve legitimate numbered lists in content
900            let input = "Here are 3 steps:\n1. Do this\n2. Then this";
901            // Note: Training mode would strip the numbers at line start
902            assert_eq!(
903                cleaner.clean(input),
904                "Here are 3 steps:\n1. Do this\n2. Then this"
905            );
906        }
907
908        #[test]
909        fn test_accepts_string_ownership() {
910            let cleaner = text_cleaner_for_inference();
911
912            let owned = String::from("test&#39;s");
913            let result = cleaner.clean(&owned);
914            assert_eq!(result, "test's");
915        }
916
917        #[test]
918        fn test_accepts_str_reference() {
919            let cleaner = text_cleaner_for_inference();
920
921            let result = cleaner.clean("test&#39;s");
922            assert_eq!(result, "test's");
923        }
924
925        #[test]
926        fn test_unicode_preservation() {
927            let cleaner = text_cleaner_for_inference();
928
929            // Should preserve legitimate unicode
930            assert_eq!(cleaner.clean("Café résumé"), "Café résumé");
931            assert_eq!(cleaner.clean("日本語"), "日本語");
932            assert_eq!(cleaner.clean("Привет"), "Привет");
933        }
934
935        #[test]
936        fn test_long_text_performance() {
937            use std::fmt::Write;
938            let cleaner = text_cleaner_for_training();
939
940            // Generate a longer text with multiple issues
941            let input = (0..100).fold(String::new(), |mut output, i| {
942                let _ = write!(output, "Sentence {i}[{i}] with &quot;quotes&quot; here. ");
943                output
944            });
945
946            let result = cleaner.clean(&input);
947
948            // Should clean all instances
949            assert!(!result.contains('['));
950            assert!(!result.contains("&quot;"));
951            assert!(result.contains("Sentence"));
952        }
953    }
954
955    // ============================================================================
956    // Edge Cases and Regression Tests
957    // ============================================================================
958
959    mod edge_cases {
960        use super::*;
961
962        #[test]
963        fn test_extremely_long_citation() {
964            let cleaner = DatasetArtifactCleaner::new();
965            assert_eq!(cleaner.clean("Text[123456789]".into()), "Text");
966        }
967
968        #[test]
969        fn test_mixed_quote_styles() {
970            let cleaner = UniversalCleaner::new();
971            assert_eq!(
972                cleaner.clean("&#39;single&#39; and &quot;double&quot;".into()),
973                "'single' and \"double\""
974            );
975        }
976
977        #[test]
978        fn test_nested_html_tags() {
979            let cleaner = UniversalCleaner::new();
980            assert_eq!(
981                cleaner.clean("<div><p><strong>nested</strong></p></div>".into()),
982                "nested"
983            );
984        }
985
986        #[test]
987        fn test_consecutive_artifacts() {
988            let cleaner = DatasetArtifactCleaner::new();
989            assert_eq!(cleaner.clean("[1][2][3][4][5]".into()), "");
990        }
991
992        #[test]
993        fn test_only_whitespace_and_artifacts() {
994            let cleaner = text_cleaner_for_training();
995            assert_eq!(cleaner.clean("  [1]  [2]  "), "");
996        }
997
998        #[test]
999        fn test_newlines_preserved_correctly() {
1000            let cleaner = text_cleaner_for_inference();
1001            assert_eq!(
1002                cleaner.clean("Line1\nLine2\n\nLine3"),
1003                "Line1\nLine2\n\nLine3"
1004            );
1005        }
1006
1007        #[test]
1008        fn test_no_over_trimming() {
1009            let cleaner = text_cleaner_for_inference();
1010            // Should preserve internal quotes
1011            assert_eq!(
1012                cleaner.clean("He said 'hello' there"),
1013                "He said 'hello' there"
1014            );
1015        }
1016
1017        #[test]
1018        fn test_clean_batch_equivalence() {
1019            let texts: Vec<&str> = vec![
1020                "Hello &amp; world [1]",
1021                "",
1022                "Text with &quot;quotes&quot; and  multiple  spaces",
1023            ];
1024
1025            let batch_results = text_cleaner_for_training().clean_batch(&texts);
1026            let sequential: Vec<String> = texts
1027                .iter()
1028                .map(|t| text_cleaner_for_training().clean(t).to_string())
1029                .collect();
1030
1031            assert_eq!(batch_results.len(), sequential.len());
1032            for (i, (batch, seq)) in batch_results.iter().zip(sequential.iter()).enumerate() {
1033                assert_eq!(batch, seq, "clean_batch and clean disagree at index {i}");
1034            }
1035        }
1036    }
1037}