trustformers-tokenizers 0.1.1

Tokenizers for TrustformeRS
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
//! Training utilities and optimization helpers.
//!
//! This module provides various utility functions for tokenizer training,
//! including coverage analysis, tokenizer comparison, vocabulary optimization,
//! parameter suggestion, and export utilities.

use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::Write;
use trustformers_core::errors::{Result, TrustformersError};

use super::analysis::CoverageAnalysis;
use super::config::TrainingConfig;
use super::metrics::TrainingMetrics;

/// Utility functions for training analysis and validation.
pub struct TrainingUtils;

impl TrainingUtils {
    /// Analyze vocabulary coverage on a test dataset.
    ///
    /// This function evaluates how well a tokenizer covers the vocabulary
    /// of a given test set, providing detailed statistics about tokenization
    /// effectiveness.
    pub fn analyze_coverage<T: trustformers_core::traits::Tokenizer>(
        tokenizer: &T,
        test_texts: &[String],
    ) -> Result<HashMap<String, f64>> {
        let mut stats = HashMap::new();
        let mut total_tokens = 0;
        let mut oov_tokens = 0;
        let mut char_count = 0;

        for text in test_texts {
            let tokenized = tokenizer.encode(text)?;
            total_tokens += tokenized.input_ids.len();
            char_count += text.chars().count();

            for &id in &tokenized.input_ids {
                if id == 1 {
                    // Assuming UNK token has ID 1
                    oov_tokens += 1;
                }
            }
        }

        stats.insert("total_tokens".to_string(), total_tokens as f64);
        stats.insert("oov_tokens".to_string(), oov_tokens as f64);
        stats.insert(
            "oov_rate".to_string(),
            if total_tokens > 0 { oov_tokens as f64 / total_tokens as f64 } else { 0.0 },
        );
        stats.insert("coverage".to_string(), 1.0 - stats["oov_rate"]);
        stats.insert(
            "compression_ratio".to_string(),
            if char_count > 0 { total_tokens as f64 / char_count as f64 } else { 0.0 },
        );

        Ok(stats)
    }

    /// Compare two tokenizers on the same dataset.
    ///
    /// This function provides a side-by-side comparison of two tokenizers,
    /// returning performance metrics for each one.
    pub fn compare_tokenizers<
        T1: trustformers_core::traits::Tokenizer,
        T2: trustformers_core::traits::Tokenizer,
    >(
        tokenizer1: &T1,
        tokenizer2: &T2,
        test_texts: &[String],
    ) -> Result<HashMap<String, (f64, f64)>> {
        let stats1 = Self::analyze_coverage(tokenizer1, test_texts)?;
        let stats2 = Self::analyze_coverage(tokenizer2, test_texts)?;

        let mut comparison = HashMap::new();
        for (key, value1) in stats1 {
            if let Some(&value2) = stats2.get(&key) {
                comparison.insert(key, (value1, value2));
            }
        }

        Ok(comparison)
    }

    /// Export vocabulary to different file formats.
    ///
    /// Supports JSON, TSV, and plain text formats for vocabulary export.
    pub fn export_vocab<T: trustformers_core::traits::Tokenizer>(
        _tokenizer: &T,
        format: &str,
        path: &str,
    ) -> Result<()> {
        // Create a temporary vocab map - this method needs to be implemented in the trait
        let vocab: HashMap<String, u32> = HashMap::new();
        let mut file = File::create(path)?;

        match format {
            "json" => {
                let json_data = serde_json::to_string_pretty(&vocab)?;
                file.write_all(json_data.as_bytes())?;
            },
            "tsv" => {
                writeln!(file, "token\tid")?;
                for (token, id) in vocab {
                    writeln!(file, "{}\t{}", token, id)?;
                }
            },
            "txt" => {
                for (token, _) in vocab {
                    writeln!(file, "{}", token)?;
                }
            },
            _ => {
                return Err(TrustformersError::invalid_input(format!(
                    "Unsupported format: {}",
                    format
                )));
            },
        }

        Ok(())
    }

    /// Optimize vocabulary size using coverage analysis.
    ///
    /// This function performs a binary search to find the optimal vocabulary size
    /// that achieves the target coverage with the minimum number of tokens.
    pub fn optimize_vocab_size<T, U>(
        trainer_factory: T,
        _texts: &[String],
        validation_texts: &[String],
        target_coverage: f64,
        size_range: (usize, usize),
    ) -> Result<(usize, TrainingMetrics)>
    where
        T: Fn(&TrainingConfig) -> Result<U>,
        U: trustformers_core::traits::Tokenizer,
    {
        let (min_size, max_size) = size_range;
        let mut best_size = min_size;
        let mut best_metrics = TrainingMetrics::new();
        let mut best_coverage = 0.0;

        // Binary search for optimal vocabulary size
        let mut low = min_size;
        let mut high = max_size;

        while low <= high {
            let mid = (low + high) / 2;

            let config = TrainingConfig {
                vocab_size: mid,
                ..Default::default()
            };

            match trainer_factory(&config) {
                Ok(tokenizer) => {
                    let stats = Self::analyze_coverage(&tokenizer, validation_texts)?;
                    let coverage = stats.get("coverage").unwrap_or(&0.0);

                    let metrics = TrainingMetrics {
                        vocab_size: mid,
                        coverage: *coverage,
                        compression_ratio: *stats.get("compression_ratio").unwrap_or(&0.0),
                        oov_rate: *stats.get("oov_rate").unwrap_or(&1.0),
                        total_tokens: *stats.get("total_tokens").unwrap_or(&0.0) as usize,
                        ..Default::default()
                    };

                    if *coverage >= target_coverage && *coverage > best_coverage {
                        best_size = mid;
                        best_metrics = metrics;
                        best_coverage = *coverage;
                    }

                    if *coverage < target_coverage {
                        low = mid + 1;
                    } else {
                        high = mid - 1;
                    }
                },
                Err(_) => {
                    // Training failed, try larger vocabulary
                    low = mid + 1;
                },
            }
        }

        Ok((best_size, best_metrics))
    }

    /// Perform detailed coverage analysis with comprehensive statistics.
    pub fn detailed_coverage_analysis<T: trustformers_core::traits::Tokenizer>(
        tokenizer: &T,
        test_texts: &[String],
    ) -> Result<CoverageAnalysis> {
        let mut char_coverage = HashMap::new();
        let mut word_coverage = HashMap::new();
        let mut length_distribution = HashMap::new();
        let mut oov_tokens = Vec::new();

        let mut total_chars = 0;
        let mut total_words = 0;
        let mut total_tokens = 0;
        let mut covered_chars = 0;
        let mut covered_words = 0;

        for text in test_texts {
            let words: Vec<&str> = text.split_whitespace().collect();
            total_words += words.len();
            total_chars += text.chars().count();

            let tokenized = tokenizer.encode(text)?;
            total_tokens += tokenized.input_ids.len();

            // Track token length distribution with actual token lengths
            for &id in &tokenized.input_ids {
                // Get actual token string from the tokenizer and calculate its length
                let len = if let Some(token_str) = tokenizer.id_to_token(id) {
                    token_str.chars().count()
                } else {
                    1 // Default to 1 for unknown tokens
                };
                *length_distribution.entry(len).or_insert(0) += 1;

                if id == 1 {
                    // Assuming UNK token has ID 1
                    oov_tokens.push("[UNK]".to_string());
                }
            }

            // Character-level coverage - simplified without direct vocab access
            for ch in text.chars() {
                // For now, assume all characters are covered
                // In a real implementation, this would require vocabulary access
                covered_chars += 1;
                *char_coverage.entry(ch).or_insert(0) += 1;
            }

            // Word-level coverage - simplified without direct vocab access
            for word in words {
                // For now, assume all words are covered
                // In a real implementation, this would require vocabulary access
                covered_words += 1;
                *word_coverage.entry(word.to_string()).or_insert(0) += 1;
            }
        }

        let char_coverage_rate =
            if total_chars > 0 { covered_chars as f64 / total_chars as f64 } else { 0.0 };
        let word_coverage_rate =
            if total_words > 0 { covered_words as f64 / total_words as f64 } else { 0.0 };
        let compression_ratio =
            if total_chars > 0 { total_tokens as f64 / total_chars as f64 } else { 0.0 };

        Ok(CoverageAnalysis {
            char_coverage_rate,
            word_coverage_rate,
            compression_ratio,
            total_chars,
            total_words,
            total_tokens,
            covered_chars,
            covered_words,
            length_distribution,
            oov_tokens,
            vocab_size: tokenizer.vocab_size(),
        })
    }

    /// Suggest optimal training parameters based on corpus analysis.
    ///
    /// This function analyzes the provided corpus and suggests appropriate
    /// training parameters based on corpus characteristics.
    pub fn suggest_training_params(texts: &[String]) -> TrainingConfig {
        let mut char_freq = HashMap::new();
        let mut word_freq = HashMap::new();
        let mut total_chars = 0;
        let mut total_words = 0;

        // Analyze corpus characteristics
        for text in texts {
            total_chars += text.chars().count();
            let words: Vec<&str> = text.split_whitespace().collect();
            total_words += words.len();

            for ch in text.chars() {
                *char_freq.entry(ch).or_insert(0) += 1;
            }

            for word in words {
                *word_freq.entry(word.to_string()).or_insert(0) += 1;
            }
        }

        let _unique_chars = char_freq.len();
        let unique_words = word_freq.len();

        // Calculate corpus statistics
        let avg_word_length =
            if total_words > 0 { total_chars as f64 / total_words as f64 } else { 0.0 };
        let vocab_diversity = unique_words as f64 / total_words as f64;

        // Suggest parameters based on corpus characteristics
        let suggested_vocab_size = if vocab_diversity > 0.1 {
            // High diversity corpus needs larger vocabulary
            (unique_words * 2).clamp(8000, 50000)
        } else {
            // Low diversity corpus can use smaller vocabulary
            (unique_words + 1000).clamp(4000, 30000)
        };

        let min_frequency = if total_words > 100000 {
            // Large corpus can afford higher min frequency
            3
        } else {
            // Small corpus should use lower min frequency
            1
        };

        let max_input_chars = (avg_word_length * 2.0) as usize;

        TrainingConfig {
            vocab_size: suggested_vocab_size,
            min_frequency,
            max_input_chars_per_word: max_input_chars.clamp(50, 200),
            ..Default::default()
        }
    }

    /// Validate tokenizer performance against quality thresholds.
    pub fn validate_tokenizer_quality<T: trustformers_core::traits::Tokenizer>(
        tokenizer: &T,
        test_texts: &[String],
        quality_thresholds: &QualityThresholds,
    ) -> Result<QualityReport> {
        let coverage_stats = Self::analyze_coverage(tokenizer, test_texts)?;
        let detailed_analysis = Self::detailed_coverage_analysis(tokenizer, test_texts)?;

        let coverage = coverage_stats.get("coverage").unwrap_or(&0.0);
        let compression_ratio = coverage_stats.get("compression_ratio").unwrap_or(&0.0);
        let oov_rate = coverage_stats.get("oov_rate").unwrap_or(&1.0);

        let mut issues = Vec::new();
        let mut warnings = Vec::new();

        // Check coverage threshold
        if *coverage < quality_thresholds.min_coverage {
            issues.push(format!(
                "Coverage {:.2}% below minimum threshold {:.2}%",
                coverage * 100.0,
                quality_thresholds.min_coverage * 100.0
            ));
        }

        // Check OOV rate threshold
        if *oov_rate > quality_thresholds.max_oov_rate {
            issues.push(format!(
                "OOV rate {:.2}% above maximum threshold {:.2}%",
                oov_rate * 100.0,
                quality_thresholds.max_oov_rate * 100.0
            ));
        }

        // Check compression ratio
        if *compression_ratio > quality_thresholds.max_compression_ratio {
            warnings.push(format!(
                "High compression ratio {:.3} may indicate over-tokenization",
                compression_ratio
            ));
        }

        // Check vocabulary size efficiency
        let efficiency_score = detailed_analysis.efficiency_score();
        if efficiency_score < quality_thresholds.min_efficiency_score {
            warnings.push(format!(
                "Low efficiency score {:.3} suggests suboptimal vocabulary",
                efficiency_score
            ));
        }

        let overall_quality = if issues.is_empty() {
            if warnings.is_empty() {
                QualityLevel::Excellent
            } else {
                QualityLevel::Good
            }
        } else if issues.len() < 2 {
            QualityLevel::Acceptable
        } else {
            QualityLevel::Poor
        };

        Ok(QualityReport {
            overall_quality,
            coverage: *coverage,
            oov_rate: *oov_rate,
            compression_ratio: *compression_ratio,
            efficiency_score,
            issues,
            warnings,
            vocab_size: tokenizer.vocab_size(),
        })
    }

    /// Generate comprehensive training recommendations.
    pub fn generate_training_recommendations(
        texts: &[String],
        current_config: Option<&TrainingConfig>,
    ) -> TrainingRecommendations {
        let suggested_config = Self::suggest_training_params(texts);

        let mut recommendations = Vec::new();

        if let Some(current) = current_config {
            // Compare with current configuration and provide specific recommendations
            if current.vocab_size < suggested_config.vocab_size / 2 {
                recommendations
                    .push("Consider increasing vocabulary size for better coverage".to_string());
            } else if current.vocab_size > suggested_config.vocab_size * 2 {
                recommendations
                    .push("Consider reducing vocabulary size to improve efficiency".to_string());
            }

            if current.min_frequency < suggested_config.min_frequency {
                recommendations
                    .push("Consider increasing minimum frequency to reduce noise".to_string());
            }

            if current.max_input_chars_per_word < suggested_config.max_input_chars_per_word {
                recommendations
                    .push("Consider increasing max input characters per word".to_string());
            }
        } else {
            recommendations.push("Use suggested configuration as starting point".to_string());
            recommendations.push("Consider running vocabulary size optimization".to_string());
            recommendations.push("Validate on held-out test set".to_string());
        }

        // Add general recommendations based on corpus size
        let total_words: usize = texts.iter().map(|t| t.split_whitespace().count()).sum();
        if total_words < 10000 {
            recommendations.push("Corpus is small - consider lowering min_frequency".to_string());
        } else if total_words > 1000000 {
            recommendations.push("Large corpus detected - consider streaming training".to_string());
        }

        TrainingRecommendations {
            suggested_config,
            recommendations,
            corpus_size: total_words,
        }
    }

    /// Perform statistical analysis of tokenization patterns.
    pub fn analyze_tokenization_patterns<T: trustformers_core::traits::Tokenizer>(
        tokenizer: &T,
        texts: &[String],
    ) -> Result<TokenizationPatterns> {
        let mut token_lengths = Vec::new();
        let mut tokens_per_sentence = Vec::new();
        let mut unique_tokens = HashSet::new();
        let mut total_tokens = 0;

        for text in texts {
            let tokenized = tokenizer.encode(text)?;
            tokens_per_sentence.push(tokenized.input_ids.len());
            total_tokens += tokenized.input_ids.len();

            for &id in &tokenized.input_ids {
                unique_tokens.insert(id);
                if let Some(token_str) = tokenizer.id_to_token(id) {
                    token_lengths.push(token_str.chars().count());
                }
            }
        }

        // Calculate statistics
        let avg_tokens_per_sentence = if !tokens_per_sentence.is_empty() {
            tokens_per_sentence.iter().sum::<usize>() as f64 / tokens_per_sentence.len() as f64
        } else {
            0.0
        };

        let avg_token_length = if !token_lengths.is_empty() {
            token_lengths.iter().sum::<usize>() as f64 / token_lengths.len() as f64
        } else {
            0.0
        };

        let vocab_utilization = if tokenizer.vocab_size() > 0 {
            unique_tokens.len() as f64 / tokenizer.vocab_size() as f64
        } else {
            0.0
        };

        Ok(TokenizationPatterns {
            avg_tokens_per_sentence,
            avg_token_length,
            vocab_utilization,
            total_unique_tokens: unique_tokens.len(),
            total_tokens,
        })
    }
}

/// Quality thresholds for tokenizer validation.
#[derive(Debug, Clone)]
pub struct QualityThresholds {
    pub min_coverage: f64,
    pub max_oov_rate: f64,
    pub max_compression_ratio: f64,
    pub min_efficiency_score: f64,
}

impl Default for QualityThresholds {
    fn default() -> Self {
        Self {
            min_coverage: 0.95,         // 95% coverage
            max_oov_rate: 0.05,         // 5% OOV rate
            max_compression_ratio: 0.8, // 0.8 tokens per character
            min_efficiency_score: 0.7,  // 0.7 efficiency score
        }
    }
}

/// Quality assessment levels.
#[derive(Debug, Clone, PartialEq)]
pub enum QualityLevel {
    Excellent,
    Good,
    Acceptable,
    Poor,
}

/// Comprehensive quality report for a tokenizer.
#[derive(Debug, Clone)]
pub struct QualityReport {
    pub overall_quality: QualityLevel,
    pub coverage: f64,
    pub oov_rate: f64,
    pub compression_ratio: f64,
    pub efficiency_score: f64,
    pub issues: Vec<String>,
    pub warnings: Vec<String>,
    pub vocab_size: usize,
}

impl QualityReport {
    /// Generate a human-readable quality report.
    pub fn summary(&self) -> String {
        let quality_str = match self.overall_quality {
            QualityLevel::Excellent => "Excellent",
            QualityLevel::Good => "Good",
            QualityLevel::Acceptable => "Acceptable",
            QualityLevel::Poor => "Poor",
        };

        let mut report = format!(
            "Tokenizer Quality Report\n\
             ========================\n\
             Overall Quality: {}\n\
             Coverage: {:.2}%\n\
             OOV Rate: {:.2}%\n\
             Compression Ratio: {:.3}\n\
             Efficiency Score: {:.3}\n\
             Vocabulary Size: {}\n",
            quality_str,
            self.coverage * 100.0,
            self.oov_rate * 100.0,
            self.compression_ratio,
            self.efficiency_score,
            self.vocab_size
        );

        if !self.issues.is_empty() {
            report.push_str("\nIssues:\n");
            for issue in &self.issues {
                report.push_str(&format!("  - {}\n", issue));
            }
        }

        if !self.warnings.is_empty() {
            report.push_str("\nWarnings:\n");
            for warning in &self.warnings {
                report.push_str(&format!("  - {}\n", warning));
            }
        }

        report
    }
}

/// Training recommendations based on corpus analysis.
#[derive(Debug, Clone)]
pub struct TrainingRecommendations {
    pub suggested_config: TrainingConfig,
    pub recommendations: Vec<String>,
    pub corpus_size: usize,
}

impl TrainingRecommendations {
    /// Generate a formatted recommendations report.
    pub fn report(&self) -> String {
        let mut report = format!(
            "Training Recommendations\n\
             ========================\n\
             Corpus Size: {} words\n\
             \n\
             Suggested Configuration:\n\
             - Vocabulary Size: {}\n\
             - Min Frequency: {}\n\
             - Max Input Chars: {}\n\
             \n\
             Recommendations:\n",
            self.corpus_size,
            self.suggested_config.vocab_size,
            self.suggested_config.min_frequency,
            self.suggested_config.max_input_chars_per_word
        );

        for rec in &self.recommendations {
            report.push_str(&format!("  - {}\n", rec));
        }

        report
    }
}

/// Statistical analysis of tokenization patterns.
#[derive(Debug, Clone)]
pub struct TokenizationPatterns {
    pub avg_tokens_per_sentence: f64,
    pub avg_token_length: f64,
    pub vocab_utilization: f64,
    pub total_unique_tokens: usize,
    pub total_tokens: usize,
}

impl TokenizationPatterns {
    /// Generate a pattern analysis report.
    pub fn report(&self) -> String {
        format!(
            "Tokenization Patterns Analysis\n\
             ==============================\n\
             Average Tokens per Sentence: {:.2}\n\
             Average Token Length: {:.2} characters\n\
             Vocabulary Utilization: {:.2}%\n\
             Total Unique Tokens: {}\n\
             Total Tokens: {}",
            self.avg_tokens_per_sentence,
            self.avg_token_length,
            self.vocab_utilization * 100.0,
            self.total_unique_tokens,
            self.total_tokens
        )
    }
}

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

    #[test]
    fn test_suggest_training_params() {
        let texts = vec![
            "hello world".to_string(),
            "hello there".to_string(),
            "world peace".to_string(),
        ];

        let config = TrainingUtils::suggest_training_params(&texts);
        assert!(config.vocab_size > 0);
        assert!(config.min_frequency > 0);
        assert!(config.max_input_chars_per_word >= 50);
    }

    #[test]
    fn test_quality_thresholds() {
        let thresholds = QualityThresholds::default();
        assert_eq!(thresholds.min_coverage, 0.95);
        assert_eq!(thresholds.max_oov_rate, 0.05);
        assert!(thresholds.max_compression_ratio > 0.0);
        assert!(thresholds.min_efficiency_score > 0.0);
    }

    #[test]
    fn test_quality_report() {
        let report = QualityReport {
            overall_quality: QualityLevel::Good,
            coverage: 0.92,
            oov_rate: 0.08,
            compression_ratio: 0.6,
            efficiency_score: 0.75,
            issues: vec!["Test issue".to_string()],
            warnings: vec!["Test warning".to_string()],
            vocab_size: 5000,
        };

        let summary = report.summary();
        assert!(summary.contains("Good"));
        assert!(summary.contains("92.00%"));
        assert!(summary.contains("Test issue"));
        assert!(summary.contains("Test warning"));
    }

    #[test]
    fn test_training_recommendations() {
        let recommendations = TrainingRecommendations {
            suggested_config: TrainingConfig::default(),
            recommendations: vec![
                "Increase vocabulary size".to_string(),
                "Use validation set".to_string(),
            ],
            corpus_size: 10000,
        };

        let report = recommendations.report();
        assert!(report.contains("10000 words"));
        assert!(report.contains("Increase vocabulary size"));
        assert!(report.contains("30000")); // Default vocab size
    }

    #[test]
    fn test_tokenization_patterns() {
        let patterns = TokenizationPatterns {
            avg_tokens_per_sentence: 8.5,
            avg_token_length: 4.2,
            vocab_utilization: 0.75,
            total_unique_tokens: 1500,
            total_tokens: 10000,
        };

        let report = patterns.report();
        assert!(report.contains("8.50"));
        assert!(report.contains("4.20"));
        assert!(report.contains("75.00%"));
        assert!(report.contains("1500"));
        assert!(report.contains("10000"));
    }

    #[test]
    fn test_quality_levels() {
        assert_eq!(QualityLevel::Excellent, QualityLevel::Excellent);
        assert_ne!(QualityLevel::Good, QualityLevel::Poor);
    }
}