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
use crate::vocab::Vocab;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use trustformers_core::errors::{Result, TrustformersError};
use trustformers_core::traits::{TokenizedInput, Tokenizer};

/// Configuration for Chinese tokenization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChineseTokenizerConfig {
    /// Whether to enable word segmentation
    pub enable_word_segmentation: bool,
    /// Whether to keep punctuation as separate tokens
    pub keep_punctuation: bool,
    /// Whether to convert to simplified Chinese
    pub convert_to_simplified: bool,
    /// Whether to handle traditional Chinese
    pub handle_traditional: bool,
    /// Maximum word length for segmentation
    pub max_word_length: usize,
    /// Unknown token
    pub unk_token: String,
    /// Padding token
    pub pad_token: String,
    /// Special tokens
    pub special_tokens: Vec<String>,
}

impl Default for ChineseTokenizerConfig {
    fn default() -> Self {
        Self {
            enable_word_segmentation: true,
            keep_punctuation: true,
            convert_to_simplified: false,
            handle_traditional: true,
            max_word_length: 6,
            unk_token: "[UNK]".to_string(),
            pad_token: "[PAD]".to_string(),
            special_tokens: vec![
                "[PAD]".to_string(),
                "[UNK]".to_string(),
                "[CLS]".to_string(),
                "[SEP]".to_string(),
                "[MASK]".to_string(),
            ],
        }
    }
}

/// Chinese tokenizer with word segmentation support
#[derive(Debug, Clone)]
pub struct ChineseTokenizer {
    config: ChineseTokenizerConfig,
    vocab: Vocab,
    /// Built-in dictionary of common Chinese words
    word_dict: HashSet<String>,
    /// Character frequency map for segmentation scoring
    char_freq: HashMap<char, u32>,
    /// Whether normalizer is enabled (simplified approach)
    use_normalizer: bool,
}

impl ChineseTokenizer {
    /// Create a new Chinese tokenizer
    pub fn new(config: ChineseTokenizerConfig, vocab: Vocab) -> Self {
        let mut tokenizer = Self {
            config,
            vocab,
            word_dict: HashSet::new(),
            char_freq: HashMap::new(),
            use_normalizer: false,
        };

        tokenizer.init_builtin_dict();
        tokenizer.init_char_freq();
        tokenizer
    }

    /// Enable basic text normalization
    pub fn with_normalization(mut self) -> Self {
        self.use_normalizer = true;
        self
    }

    /// Initialize built-in Chinese word dictionary
    fn init_builtin_dict(&mut self) {
        // Common Chinese words (this would be loaded from a file in practice)
        let common_words = vec![
            "中国",
            "人民",
            "共和国",
            "北京",
            "上海",
            "广州",
            "深圳",
            "我们",
            "你们",
            "他们",
            "什么",
            "怎么",
            "为什么",
            "在哪里",
            "今天",
            "明天",
            "昨天",
            "现在",
            "以前",
            "以后",
            "时候",
            "可以",
            "应该",
            "需要",
            "想要",
            "希望",
            "觉得",
            "认为",
            "工作",
            "学习",
            "生活",
            "家庭",
            "朋友",
            "同事",
            "老师",
            "学生",
            "医生",
            "警察",
            "司机",
            "厨师",
            "工程师",
            "律师",
            "喜欢",
            "讨厌",
            "",
            "",
            "高兴",
            "难过",
            "生气",
            "害怕",
            "东西",
            "地方",
            "时间",
            "问题",
            "方法",
            "机会",
            "经验",
            "知识",
            "技能",
            "能力",
            "水平",
            "质量",
            "数量",
            "价格",
        ];

        for word in common_words {
            self.word_dict.insert(word.to_string());
        }
    }

    /// Initialize character frequency map
    fn init_char_freq(&mut self) {
        // Initialize with common Chinese character frequencies
        let common_chars = vec![
            ('', 1000),
            ('', 900),
            ('', 800),
            ('', 700),
            ('', 650),
            ('', 600),
            ('', 550),
            ('', 500),
            ('', 450),
            ('', 400),
            ('', 380),
            ('', 360),
            ('', 340),
            ('', 320),
            ('', 300),
            ('', 280),
            ('', 260),
            ('', 240),
            ('', 220),
            ('', 200),
            ('', 190),
            ('', 180),
            ('', 170),
            ('', 160),
            ('', 150),
            ('', 145),
            ('', 140),
            ('', 135),
            ('', 130),
            ('', 125),
            ('', 120),
            ('', 115),
            ('', 110),
            ('', 105),
            ('', 100),
        ];

        for (ch, freq) in common_chars {
            self.char_freq.insert(ch, freq);
        }
    }

    /// Check if a character is Chinese
    pub fn is_chinese_char(ch: char) -> bool {
        let code = ch as u32;
        // CJK Unified Ideographs
        (0x4E00..=0x9FFF).contains(&code) ||
        // CJK Extension A
        (0x3400..=0x4DBF).contains(&code) ||
        // CJK Extension B
        (0x20000..=0x2A6DF).contains(&code) ||
        // CJK Extension C
        (0x2A700..=0x2B73F).contains(&code) ||
        // CJK Extension D
        (0x2B740..=0x2B81F).contains(&code) ||
        // CJK Extension E
        (0x2B820..=0x2CEAF).contains(&code)
    }

    /// Check if a character is Chinese punctuation
    pub fn is_chinese_punctuation(ch: char) -> bool {
        matches!(
            ch,
            '' | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | '\u{201C}' // "
                | '\u{201D}' // "
                | '\u{2018}' // '
                | '\u{2019}' // '
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
                | ''
        )
    }

    /// Preprocess text by normalizing and handling special cases
    fn preprocess_text(&self, text: &str) -> String {
        let mut processed = if self.use_normalizer {
            // Basic normalization: lowercase and whitespace normalization
            text.to_lowercase()
                .chars()
                .filter(|c| !c.is_whitespace() || *c == ' ')
                .collect()
        } else {
            text.to_string()
        };

        // Convert to simplified Chinese if requested
        if self.config.convert_to_simplified {
            processed = self.traditional_to_simplified(&processed);
        }

        processed
    }

    /// Simple traditional to simplified Chinese conversion
    fn traditional_to_simplified(&self, text: &str) -> String {
        // This is a simplified mapping - in practice, you'd use a comprehensive dictionary
        let mapping = vec![
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
            ('', ''),
        ];

        let mut result = text.to_string();
        for (traditional, simplified) in mapping {
            result = result.replace(traditional, &simplified.to_string());
        }
        result
    }

    /// Segment Chinese text into words using dynamic programming
    pub fn segment_text(&self, text: &str) -> Vec<String> {
        if !self.config.enable_word_segmentation {
            return text.chars().map(|c| c.to_string()).collect();
        }

        let chars: Vec<char> = text.chars().collect();
        if chars.is_empty() {
            return Vec::new();
        }

        let n = chars.len();
        let mut dp = vec![f64::NEG_INFINITY; n + 1];
        let mut path = vec![0; n + 1];
        dp[0] = 0.0;

        for i in 0..n {
            if dp[i] == f64::NEG_INFINITY {
                continue;
            }

            // Try all possible word lengths
            for j in 1..=self.config.max_word_length.min(n - i) {
                let word: String = chars[i..i + j].iter().collect();
                let score = self.calculate_word_score(&word);

                if dp[i] + score > dp[i + j] {
                    dp[i + j] = dp[i] + score;
                    path[i + j] = i;
                }
            }
        }

        // Reconstruct the segmentation
        let mut result = Vec::new();
        let mut pos = n;
        while pos > 0 {
            let start = path[pos];
            let word: String = chars[start..pos].iter().collect();
            result.push(word);
            pos = start;
        }

        result.reverse();
        result
    }

    /// Calculate word score for segmentation
    fn calculate_word_score(&self, word: &str) -> f64 {
        if word.len() == 1 {
            let ch = word.chars().next().expect("word with len()==1 must have at least one char");
            if Self::is_chinese_char(ch) {
                // Single character Chinese words have lower score
                return self.char_freq.get(&ch).map(|&f| (f as f64).ln()).unwrap_or(-10.0);
            } else if Self::is_chinese_punctuation(ch) || ch.is_ascii_punctuation() {
                return 0.0; // Neutral score for punctuation
            } else {
                return -5.0; // Lower score for other single characters
            }
        }

        // Multi-character words
        if self.word_dict.contains(word) {
            // Known words get positive score based on length
            5.0 + word.len() as f64
        } else if word.chars().all(Self::is_chinese_char) {
            // Unknown Chinese words get moderate score
            2.0 + word.len() as f64 * 0.5
        } else if word.chars().all(|c| c.is_ascii_alphanumeric()) {
            // English words/numbers
            3.0 + word.len() as f64 * 0.3
        } else {
            // Mixed or special characters
            1.0
        }
    }

    /// Add word to dictionary
    pub fn add_word(&mut self, word: String) {
        self.word_dict.insert(word);
    }

    /// Remove word from dictionary
    pub fn remove_word(&mut self, word: &str) -> bool {
        self.word_dict.remove(word)
    }

    /// Load dictionary from text file
    pub fn load_dictionary(&mut self, words: Vec<String>) {
        for word in words {
            self.word_dict.insert(word);
        }
    }

    /// Get dictionary size
    pub fn dictionary_size(&self) -> usize {
        self.word_dict.len()
    }

    /// Check if word is in dictionary
    pub fn contains_word(&self, word: &str) -> bool {
        self.word_dict.contains(word)
    }

    /// Tokenize with proper handling of special tokens
    fn tokenize_segments(&self, segments: Vec<String>) -> Vec<String> {
        let mut tokens = Vec::new();

        for segment in segments {
            // Check if it's a special token
            if self.config.special_tokens.contains(&segment) {
                tokens.push(segment);
                continue;
            }

            // Handle punctuation
            if segment.len() == 1 {
                let ch = segment
                    .chars()
                    .next()
                    .expect("segment with len()==1 must have at least one char");
                if Self::is_chinese_punctuation(ch) || ch.is_ascii_punctuation() {
                    if self.config.keep_punctuation {
                        tokens.push(segment);
                    }
                    continue;
                }
            }

            // Regular token
            tokens.push(segment);
        }

        tokens
    }
}

impl Tokenizer for ChineseTokenizer {
    fn encode(&self, text: &str) -> Result<TokenizedInput> {
        let processed_text = self.preprocess_text(text);
        let segments = self.segment_text(&processed_text);
        let tokens = self.tokenize_segments(segments);

        let mut token_ids = Vec::new();
        let mut attention_mask = Vec::new();

        for token in &tokens {
            if let Some(id) = self.vocab.get_id(token) {
                token_ids.push(id);
                attention_mask.push(1);
            } else {
                // Use UNK token
                if let Some(unk_id) = self.vocab.get_id(&self.config.unk_token) {
                    token_ids.push(unk_id);
                    attention_mask.push(1);
                } else {
                    return Err(TrustformersError::other(
                        "UNK token not found in vocabulary".to_string(),
                    ));
                }
            }
        }

        Ok(TokenizedInput {
            input_ids: token_ids,
            attention_mask,
            token_type_ids: None,
            special_tokens_mask: None,
            offset_mapping: None,
            overflowing_tokens: None,
        })
    }

    fn decode(&self, token_ids: &[u32]) -> Result<String> {
        let mut result = String::new();

        for &token_id in token_ids {
            if let Some(token) = self.vocab.get_token(token_id) {
                // Skip padding tokens
                if *token == self.config.pad_token {
                    continue;
                }
                result.push_str(&token);
            } else {
                result.push_str(&self.config.unk_token);
            }
        }

        Ok(result)
    }

    fn encode_pair(&self, text_a: &str, text_b: &str) -> Result<TokenizedInput> {
        let processed_a = self.preprocess_text(text_a);
        let processed_b = self.preprocess_text(text_b);

        let segments_a = self.segment_text(&processed_a);
        let segments_b = self.segment_text(&processed_b);

        let tokens_a = self.tokenize_segments(segments_a);
        let tokens_b = self.tokenize_segments(segments_b);

        let mut all_tokens = tokens_a;
        all_tokens.push("[SEP]".to_string()); // Add separator
        all_tokens.extend(tokens_b);

        let mut token_ids = Vec::new();
        let mut attention_mask = Vec::new();
        let mut token_type_ids = Vec::new();

        let sep_pos = all_tokens.iter().position(|t| t == "[SEP]").unwrap_or(0);

        for (i, token) in all_tokens.iter().enumerate() {
            if let Some(id) = self.vocab.get_id(token) {
                token_ids.push(id);
                attention_mask.push(1);
                token_type_ids.push(if i <= sep_pos { 0 } else { 1 });
            } else if let Some(unk_id) = self.vocab.get_id(&self.config.unk_token) {
                token_ids.push(unk_id);
                attention_mask.push(1);
                token_type_ids.push(if i <= sep_pos { 0 } else { 1 });
            } else {
                return Err(TrustformersError::other(
                    "UNK token not found in vocabulary".to_string(),
                ));
            }
        }

        Ok(TokenizedInput {
            input_ids: token_ids,
            attention_mask,
            token_type_ids: Some(token_type_ids),
            special_tokens_mask: None,
            offset_mapping: None,
            overflowing_tokens: None,
        })
    }

    fn vocab_size(&self) -> usize {
        self.vocab.size()
    }

    fn get_vocab(&self) -> HashMap<String, u32> {
        self.vocab.get_token_to_id_map().clone()
    }

    fn token_to_id(&self, token: &str) -> Option<u32> {
        self.vocab.get_id(token)
    }

    fn id_to_token(&self, id: u32) -> Option<String> {
        self.vocab.get_token(id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vocab::Vocab;
    use std::collections::HashMap;

    fn create_test_vocab() -> Vocab {
        let mut token_to_id = HashMap::new();

        let tokens = [
            "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "中国", "人民", "今天", "明天", "昨天",
            "", "", "", "",
        ];

        for (i, token) in tokens.iter().enumerate() {
            token_to_id.insert(token.to_string(), i as u32);
        }

        Vocab::from_map(token_to_id)
    }

    #[test]
    fn test_chinese_char_detection() {
        assert!(ChineseTokenizer::is_chinese_char(''));
        assert!(ChineseTokenizer::is_chinese_char(''));
        assert!(!ChineseTokenizer::is_chinese_char('a'));
        assert!(!ChineseTokenizer::is_chinese_char('1'));
    }

    #[test]
    fn test_chinese_punctuation_detection() {
        assert!(ChineseTokenizer::is_chinese_punctuation(''));
        assert!(ChineseTokenizer::is_chinese_punctuation(''));
        assert!(!ChineseTokenizer::is_chinese_punctuation(','));
        assert!(!ChineseTokenizer::is_chinese_punctuation('.'));
    }

    #[test]
    fn test_text_segmentation() {
        let config = ChineseTokenizerConfig::default();
        let vocab = create_test_vocab();
        let tokenizer = ChineseTokenizer::new(config, vocab);

        let segments = tokenizer.segment_text("中国人民");
        assert!(segments.len() > 0);
        assert!(segments.contains(&"中国".to_string()) || segments.contains(&"".to_string()));
    }

    #[test]
    fn test_tokenization() {
        let config = ChineseTokenizerConfig::default();
        let vocab = create_test_vocab();
        let tokenizer = ChineseTokenizer::new(config, vocab);

        let result = tokenizer.encode("中国人民").expect("Encoding failed");
        assert!(!result.input_ids.is_empty());
        assert_eq!(result.input_ids.len(), result.attention_mask.len());
    }

    #[test]
    fn test_decode() {
        let config = ChineseTokenizerConfig::default();
        let vocab = create_test_vocab();
        let tokenizer = ChineseTokenizer::new(config, vocab);

        let token_ids = vec![5, 6, 7]; // "中", "国", "人"
        let decoded = tokenizer.decode(&token_ids).expect("Decoding failed");
        assert_eq!(decoded, "中国人");
    }

    #[test]
    fn test_pair_encoding() {
        let config = ChineseTokenizerConfig::default();
        let vocab = create_test_vocab();
        let tokenizer = ChineseTokenizer::new(config, vocab);

        let result = tokenizer.encode_pair("中国", "人民").expect("Operation failed in test");
        assert!(!result.input_ids.is_empty());
        assert!(result.token_type_ids.is_some());

        let token_type_ids = result.token_type_ids.expect("Operation failed in test");
        assert!(token_type_ids.contains(&0)); // First sequence
        assert!(token_type_ids.contains(&1)); // Second sequence
    }

    #[test]
    fn test_dictionary_management() {
        let config = ChineseTokenizerConfig::default();
        let vocab = create_test_vocab();
        let mut tokenizer = ChineseTokenizer::new(config, vocab);

        let initial_size = tokenizer.dictionary_size();

        tokenizer.add_word("测试".to_string());
        assert_eq!(tokenizer.dictionary_size(), initial_size + 1);
        assert!(tokenizer.contains_word("测试"));

        assert!(tokenizer.remove_word("测试"));
        assert_eq!(tokenizer.dictionary_size(), initial_size);
        assert!(!tokenizer.contains_word("测试"));
    }

    #[test]
    fn test_traditional_to_simplified() {
        let config = ChineseTokenizerConfig {
            convert_to_simplified: true,
            ..Default::default()
        };
        let vocab = create_test_vocab();
        let tokenizer = ChineseTokenizer::new(config, vocab);

        let simplified = tokenizer.traditional_to_simplified("東西");
        assert_eq!(simplified, "东西");
    }
}