qwen_tts 0.1.1

Qwen3-TTS text-to-speech model implementation for Candle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! Text processing utilities for TTS.
//!
//! Provides tokenization and chat template formatting for Qwen3-TTS.
//! Uses the Qwen2 tokenizer vocabulary with special TTS tokens.
//!
//! Text is automatically normalized before tokenization to handle
//! typographic characters (smart quotes, em-dashes, etc.) that may
//! not be well-represented in the model's training data.
//!
//! # Batch Processing
//!
//! The processor supports batch tokenization with automatic left-padding:
//!
//! ```no_run
//! use qwen_tts::text::processing::{TextProcessor, PaddingSide};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//! let processor = TextProcessor::from_file("tokenizer.json")?;
//! let texts = vec!["Hello", "World, how are you?"];
//! let output = processor.batch_tokenize_padded(&texts, PaddingSide::Left);
//! // output.input_ids: [[PAD, PAD, id1, id2], [id1, id2, id3, id4]]
//! // output.attention_mask: [[0, 0, 1, 1], [1, 1, 1, 1]]
//! # Ok(())
//! # }
//! ```

use std::path::Path;
use tokenizers::Tokenizer;

/// Normalize text for consistent tokenization and better TTS output.
///
/// This ensures parity with Python's text handling, preventing degraded audio
/// quality when text contains smart/curly quotes, em-dashes, or other
/// typographic characters from word processors that may not be well-represented
/// in the model's training data.
///
/// # Normalizations
///
/// **Typographic characters:**
/// - Smart single quotes (`'` `'`) → ASCII apostrophe (`'`)
/// - Smart double quotes (`"` `"`) → ASCII quote (`"`)
/// - Em dash (`—`) → double hyphen (`--`)
/// - En dash (`–`) → hyphen (`-`)
/// - Horizontal ellipsis (`…`) → three periods (`...`)
///
/// **Whitespace:**
/// - Non-breaking space → regular space
/// - Narrow no-break space → regular space
/// - Ideographic space → regular space
/// - CRLF/CR → LF (Unix line endings)
///
/// **Zero-width characters (removed):**
/// - Zero-width space
/// - Zero-width non-joiner/joiner
/// - Byte order mark (BOM)
pub fn normalize_text(text: &str) -> String {
    text
        // Typographic quotes and punctuation
        .replace(['\u{2019}', '\u{2018}'], "'") // Smart single quotes → apostrophe
        .replace(['\u{201C}', '\u{201D}'], "\"") // Smart double quotes → quote
        .replace('\u{2014}', "--") // Em dash → double hyphen
        .replace('\u{2013}', "-") // En dash → hyphen
        .replace('\u{2026}', "...") // Horizontal ellipsis → three periods
        // Unicode whitespace → ASCII space
        .replace(['\u{00A0}', '\u{202F}', '\u{3000}'], " ")
        // Normalize line endings
        .replace("\r\n", "\n") // Windows CRLF → LF
        .replace('\r', "\n") // Old Mac CR → LF
        // Remove zero-width characters that break tokenization
        .replace(['\u{200B}', '\u{200C}', '\u{200D}', '\u{FEFF}'], "")
}

/// Special token IDs used by Qwen3-TTS.
#[derive(Debug, Clone, Copy)]
pub struct SpecialTokenIds {
    /// `<|im_start|>` token ID
    pub im_start: u32,
    /// `<|im_end|>` token ID
    pub im_end: u32,
    /// TTS padding token ID
    pub tts_pad: u32,
    /// TTS beginning-of-sequence token ID
    pub tts_bos: u32,
    /// TTS end-of-sequence token ID
    pub tts_eos: u32,
}

impl Default for SpecialTokenIds {
    fn default() -> Self {
        Self {
            im_start: 151644,
            im_end: 151645,
            tts_pad: 151671,
            tts_bos: 151672,
            tts_eos: 151673,
        }
    }
}

/// Padding side for batch tokenization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PaddingSide {
    /// Pad on the left (default for TTS, enables proper autoregressive generation).
    #[default]
    Left,
    /// Pad on the right (standard for most NLP tasks).
    Right,
}

/// Output from batch tokenization with padding.
#[derive(Debug, Clone)]
pub struct TokenizerOutput {
    /// Token IDs for each sequence, padded to the same length.
    /// Shape: (batch_size, max_seq_len)
    pub input_ids: Vec<Vec<u32>>,
    /// Attention mask indicating real tokens (1) vs padding (0).
    /// Shape: (batch_size, max_seq_len)
    pub attention_mask: Vec<Vec<u32>>,
    /// Original sequence lengths before padding.
    pub lengths: Vec<usize>,
}

/// Text processor for preparing input to the TTS model.
///
/// Handles text tokenization using the Qwen2 tokenizer and provides
/// chat template formatting methods for different TTS modes.
#[derive(Debug, Clone)]
pub struct TextProcessor {
    /// The underlying tokenizer (Qwen2)
    tokenizer: Option<Tokenizer>,
    /// Special token IDs
    pub special_tokens: SpecialTokenIds,
}

impl TextProcessor {
    /// Create a new text processor without a loaded tokenizer.
    ///
    /// Use `load()` or `from_file()` to create a processor with a tokenizer.
    pub fn new() -> Self {
        Self {
            tokenizer: None,
            special_tokens: SpecialTokenIds::default(),
        }
    }

    /// Create a text processor with custom special token IDs.
    pub fn with_special_tokens(special_tokens: SpecialTokenIds) -> Self {
        Self {
            tokenizer: None,
            special_tokens,
        }
    }

    /// Load tokenizer from a model directory.
    ///
    /// Tries multiple loading strategies in order:
    /// 1. `tokenizer.json` (HuggingFace fast tokenizer format)
    /// 2. `vocab.json` + `merges.txt` + `tokenizer_config.json` (BPE format with special tokens)
    ///
    /// # Arguments
    /// * `model_dir` - Path to the model directory
    ///
    /// # Example
    /// ```no_run
    /// use qwen_tts::text::processing::TextProcessor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let processor = TextProcessor::from_pretrained("/path/to/model")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_pretrained<P: AsRef<Path>>(
        model_dir: P,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let model_dir = model_dir.as_ref();

        // Strategy 1: Try tokenizer.json (fast tokenizer format) - PREFERRED
        let tokenizer_json = model_dir.join("tokenizer.json");
        if tokenizer_json.exists() {
            tracing::debug!("Loading tokenizer from tokenizer.json (HuggingFace fast format)");
            return Self::from_file(&tokenizer_json);
        }

        // Strategy 2: Try vocab.json + merges.txt + tokenizer_config.json (BPE format)
        let vocab_json = model_dir.join("vocab.json");
        let merges_txt = model_dir.join("merges.txt");
        let tokenizer_config = model_dir.join("tokenizer_config.json");
        if vocab_json.exists() {
            tracing::debug!(
                "Loading tokenizer from vocab.json + merges.txt + tokenizer_config.json"
            );
            return Self::from_bpe_files_with_config(
                &vocab_json,
                if merges_txt.exists() {
                    Some(&merges_txt)
                } else {
                    None
                },
                if tokenizer_config.exists() {
                    Some(&tokenizer_config)
                } else {
                    None
                },
            );
        }

        Err(format!(
            "No tokenizer found in {}. Expected tokenizer.json or vocab.json",
            model_dir.display()
        )
        .into())
    }

    /// Load tokenizer from vocab.json, merges.txt, and tokenizer_config.json.
    ///
    /// This replicates Python's Qwen2Tokenizer.__init__() from:
    /// transformers/src/transformers/models/qwen2/tokenization_qwen2.py
    ///
    /// The tokenizer is constructed programmatically with:
    /// - BPE model from vocab.json + merges.txt
    /// - NFC normalizer
    /// - Pre-tokenizer: Split(GPT-4 regex) + ByteLevel
    /// - Decoder: ByteLevel
    /// - Special tokens from tokenizer_config.json's added_tokens_decoder
    ///
    /// # Arguments
    /// * `vocab_path` - Path to vocab.json
    /// * `merges_path` - Optional path to merges.txt
    /// * `config_path` - Optional path to tokenizer_config.json (for special tokens)
    pub fn from_bpe_files_with_config(
        vocab_path: &Path,
        merges_path: Option<&Path>,
        config_path: Option<&Path>,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        use std::fs;
        use tokenizers::decoders::byte_level::ByteLevel as ByteLevelDecoder;
        use tokenizers::models::bpe::BPE;
        use tokenizers::normalizers::NFC;
        use tokenizers::pre_tokenizers::byte_level::ByteLevel;
        use tokenizers::pre_tokenizers::sequence::Sequence;
        use tokenizers::pre_tokenizers::split::Split;
        use tokenizers::{AddedToken, SplitDelimiterBehavior, TokenizerImpl};

        tracing::debug!("Building Qwen2-style tokenizer (replicating tokenization_qwen2.py)");

        // Parse vocab.json -> AHashMap<String, u32>
        let vocab_content = fs::read_to_string(vocab_path)?;
        let vocab_std: std::collections::HashMap<String, u32> =
            serde_json::from_str(&vocab_content)?;
        let vocab: tokenizers::models::bpe::Vocab = vocab_std.into_iter().collect();
        tracing::debug!(entries = vocab.len(), "Loaded vocab");

        // Parse merges.txt -> Vec<(String, String)>
        let merges: tokenizers::models::bpe::Merges = if let Some(merges_path) = merges_path {
            let merges_content = fs::read_to_string(merges_path)?;
            merges_content
                .lines()
                .skip(1) // Skip header "#version: ..."
                .filter(|l| !l.is_empty() && !l.starts_with('#'))
                .filter_map(|line| {
                    let parts: Vec<&str> = line.split(' ').collect();
                    if parts.len() == 2 {
                        Some((parts[0].to_string(), parts[1].to_string()))
                    } else {
                        None
                    }
                })
                .collect()
        } else {
            vec![]
        };
        tracing::debug!(count = merges.len(), "Loaded merges");

        // Parse tokenizer_config.json for special tokens
        let added_tokens: Vec<(u32, String, bool)> = if let Some(config_path) = config_path {
            let config_content = fs::read_to_string(config_path)?;
            let config: serde_json::Value = serde_json::from_str(&config_content)?;

            if let Some(added_tokens_decoder) = config
                .get("added_tokens_decoder")
                .and_then(|v| v.as_object())
            {
                let mut tokens: Vec<(u32, String, bool)> = added_tokens_decoder
                    .iter()
                    .filter_map(|(id_str, token_info)| {
                        let id: u32 = id_str.parse().ok()?;
                        let content = token_info.get("content")?.as_str()?.to_string();
                        let special = token_info
                            .get("special")
                            .and_then(|v| v.as_bool())
                            .unwrap_or(false);
                        Some((id, content, special))
                    })
                    .collect();
                tokens.sort_by_key(|(id, _, _)| *id);
                tracing::debug!(count = tokens.len(), "Found added tokens");
                tokens
            } else {
                vec![]
            }
        } else {
            vec![]
        };

        // Build BPE model exactly like Python (tokenization_qwen2.py:61-72):
        // BPE(vocab=vocab, merges=merges, ...)
        let bpe = BPE::new(vocab, merges);

        // GPT-4 style regex pattern (from Python PRETOKENIZE_REGEX, tokenization_qwen2.py:33)
        let pretokenize_regex = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+";

        // Build pre-tokenizer exactly like Python (tokenization_qwen2.py:75-87):
        // pre_tokenizers.Sequence([
        //     pre_tokenizers.Split(Regex(PRETOKENIZE_REGEX), behavior="isolated", invert=False),
        //     pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False),
        // ])
        let split = Split::new(pretokenize_regex, SplitDelimiterBehavior::Isolated, false)?;
        let byte_level = ByteLevel::new(false, true, false);
        let pre_tokenizer = Sequence::new(vec![split.into(), byte_level.into()]);

        // Assemble tokenizer like Python (tokenization_qwen2.py:61-87):
        // self._tokenizer = Tokenizer(BPE(...))
        // self._tokenizer.normalizer = normalizers.NFC()
        // self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence([...])
        // self._tokenizer.decoder = decoders.ByteLevel()
        use tokenizers::{
            DecoderWrapper, NormalizerWrapper, PostProcessorWrapper, PreTokenizerWrapper,
        };
        type FullTokenizer = TokenizerImpl<
            BPE,
            NormalizerWrapper,
            PreTokenizerWrapper,
            PostProcessorWrapper,
            DecoderWrapper,
        >;
        let mut tokenizer: FullTokenizer = TokenizerImpl::new(bpe);
        tokenizer.with_normalizer(Some(NFC));
        tokenizer.with_pre_tokenizer(Some(pre_tokenizer));
        tokenizer.with_decoder(Some(ByteLevelDecoder::new(false, true, true)));

        // Convert to Tokenizer (the wrapper type we use)
        let mut tokenizer: Tokenizer = tokenizer.into();

        // Add special tokens from tokenizer_config.json (tokenization_qwen2.py:98):
        // self.add_tokens([AddedToken(token, special=True) for token in self.all_special_tokens])
        if !added_tokens.is_empty() {
            let special_tokens: Vec<AddedToken> = added_tokens
                .iter()
                .filter(|(_, _, special)| *special)
                .map(|(_, content, _)| {
                    AddedToken::from(content.clone(), true)
                        .single_word(false)
                        .lstrip(false)
                        .rstrip(false)
                        .normalized(false)
                })
                .collect();

            if !special_tokens.is_empty() {
                tracing::debug!(count = special_tokens.len(), "Adding special tokens");
                tokenizer.add_special_tokens(&special_tokens);
            }
        }

        tracing::debug!("Tokenizer built successfully");

        Ok(Self {
            tokenizer: Some(tokenizer),
            special_tokens: SpecialTokenIds::default(),
        })
    }

    /// Load tokenizer from vocab.json and optional merges.txt (BPE format).
    ///
    /// DEPRECATED: Use from_bpe_files_with_config instead to properly handle special tokens.
    ///
    /// # Arguments
    /// * `vocab_path` - Path to vocab.json
    /// * `merges_path` - Optional path to merges.txt
    pub fn from_bpe_files<P: AsRef<Path>>(
        vocab_path: P,
        merges_path: Option<&Path>,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Self::from_bpe_files_with_config(vocab_path.as_ref(), merges_path, None)
    }

    /// Load tokenizer from a HuggingFace tokenizer.json file.
    ///
    /// # Arguments
    /// * `path` - Path to the tokenizer.json file
    ///
    /// # Example
    /// ```no_run
    /// use qwen_tts::text::processing::TextProcessor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let processor = TextProcessor::from_file("path/to/tokenizer.json")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_file<P: AsRef<Path>>(
        path: P,
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let tokenizer = Tokenizer::from_file(path)?;
        Ok(Self {
            tokenizer: Some(tokenizer),
            special_tokens: SpecialTokenIds::default(),
        })
    }

    /// Load tokenizer from bytes (tokenizer.json content).
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let tokenizer = Tokenizer::from_bytes(bytes)?;
        Ok(Self {
            tokenizer: Some(tokenizer),
            special_tokens: SpecialTokenIds::default(),
        })
    }

    /// Check if a tokenizer is loaded.
    pub fn has_tokenizer(&self) -> bool {
        self.tokenizer.is_some()
    }

    /// Build assistant text with chat template.
    ///
    /// Format: `<|im_start|>assistant\n{text}<|im_end|>\n<|im_start|>assistant\n`
    ///
    /// This is used for the main text-to-speech input.
    pub fn build_assistant_text(&self, text: &str) -> String {
        format!(
            "<|im_start|>assistant\n{}<|im_end|>\n<|im_start|>assistant\n",
            text
        )
    }

    /// Build reference text with chat template.
    ///
    /// Format: `<|im_start|>assistant\n{text}<|im_end|>\n`
    ///
    /// This is used for reference text in voice cloning ICL mode.
    pub fn build_ref_text(&self, text: &str) -> String {
        format!("<|im_start|>assistant\n{}<|im_end|>\n", text)
    }

    /// Build instruction text with chat template.
    ///
    /// Format: `<|im_start|>user\n{instruct}<|im_end|>\n`
    ///
    /// This is used for voice design instructions.
    pub fn build_instruct_text(&self, instruct: &str) -> String {
        format!("<|im_start|>user\n{}<|im_end|>\n", instruct)
    }

    /// Tokenize text into token IDs.
    ///
    /// Text is automatically normalized before tokenization to handle
    /// typographic characters (smart quotes, em-dashes, etc.).
    ///
    /// # Arguments
    /// * `text` - The text to tokenize
    ///
    /// # Returns
    /// Vector of token IDs, or empty vector if no tokenizer is loaded.
    ///
    /// # Panics
    /// Panics if the tokenizer fails to encode the text.
    pub fn tokenize(&self, text: &str) -> Vec<u32> {
        // Normalize typographic characters before tokenization
        let normalized = normalize_text(text);
        match &self.tokenizer {
            Some(tokenizer) => {
                let encoding = tokenizer
                    .encode(normalized.as_str(), false)
                    .unwrap_or_else(|e| {
                        panic!(
                            "Failed to encode text: {:?}\n\
                            This may indicate that special tokens like <|im_start|> or <|im_end|> \
                            are not properly defined in the tokenizer. \
                            Ensure you're using a valid tokenizer.json from the Qwen model.\n\
                            Text being tokenized (first 200 chars): {:?}",
                            e,
                            &text.chars().take(200).collect::<String>()
                        )
                    });
                encoding.get_ids().to_vec()
            }
            None => {
                tracing::warn!("No tokenizer loaded, returning empty token list");
                vec![]
            }
        }
    }

    /// Tokenize text with error handling.
    ///
    /// Text is automatically normalized before tokenization to handle
    /// typographic characters (smart quotes, em-dashes, etc.).
    ///
    /// # Arguments
    /// * `text` - The text to tokenize
    ///
    /// # Returns
    /// Result containing token IDs or an error.
    pub fn try_tokenize(
        &self,
        text: &str,
    ) -> Result<Vec<u32>, Box<dyn std::error::Error + Send + Sync>> {
        // Normalize typographic characters before tokenization
        let normalized = normalize_text(text);
        match &self.tokenizer {
            Some(tokenizer) => {
                let encoding = tokenizer.encode(normalized.as_str(), false)?;
                Ok(encoding.get_ids().to_vec())
            }
            None => Err("No tokenizer loaded".into()),
        }
    }

    /// Tokenize text for TTS with chat template formatting.
    ///
    /// Wraps the text in the assistant chat template before tokenizing.
    ///
    /// # Arguments
    /// * `text` - The text to convert to speech
    ///
    /// # Returns
    /// Vector of token IDs ready for the TTS model.
    pub fn tokenize_for_tts(&self, text: &str) -> Vec<u32> {
        let formatted = self.build_assistant_text(text);
        let tokens = self.tokenize(&formatted);

        if tracing::enabled!(tracing::Level::DEBUG) {
            tracing::debug!(
                input_text = %formatted,
                token_count = tokens.len(),
                token_ids = ?tokens,
                "tokenize_for_tts"
            );
            if let Some(ref tokenizer) = self.tokenizer {
                let decoded_tokens: Vec<String> = tokens
                    .iter()
                    .map(|&id| {
                        tokenizer
                            .decode(&[id], true)
                            .unwrap_or_else(|_| format!("<{}>", id))
                    })
                    .collect();
                tracing::debug!(decoded_tokens = ?decoded_tokens, "tokenize_for_tts decoded");
            }
        }

        tokens
    }

    /// Tokenize reference text for voice cloning.
    ///
    /// # Arguments
    /// * `text` - The reference text
    ///
    /// # Returns
    /// Vector of token IDs for the reference text.
    pub fn tokenize_ref_text(&self, text: &str) -> Vec<u32> {
        let formatted = self.build_ref_text(text);
        self.tokenize(&formatted)
    }

    /// Tokenize instruction for voice design.
    ///
    /// # Arguments
    /// * `instruct` - The voice design instruction
    ///
    /// # Returns
    /// Vector of token IDs for the instruction.
    pub fn tokenize_instruct(&self, instruct: &str) -> Vec<u32> {
        let formatted = self.build_instruct_text(instruct);
        self.tokenize(&formatted)
    }

    /// Add TTS special tokens to a token sequence.
    ///
    /// # Arguments
    /// * `token_ids` - The token IDs to wrap
    ///
    /// # Returns
    /// Token IDs with TTS BOS prepended.
    pub fn add_tts_tokens(&self, token_ids: Vec<u32>) -> Vec<u32> {
        let mut result = vec![self.special_tokens.tts_bos];
        result.extend(token_ids);
        result
    }

    /// Decode token IDs back to text.
    ///
    /// # Arguments
    /// * `token_ids` - The token IDs to decode
    ///
    /// # Returns
    /// The decoded text, or None if no tokenizer is loaded.
    pub fn decode(&self, token_ids: &[u32]) -> Option<String> {
        self.tokenizer
            .as_ref()
            .map(|tokenizer| tokenizer.decode(token_ids, true).unwrap_or_default())
    }

    /// Get the vocabulary size.
    pub fn vocab_size(&self) -> Option<usize> {
        self.tokenizer.as_ref().map(|t| t.get_vocab_size(true))
    }

    // =========================================================================
    // Batch Tokenization Methods
    // =========================================================================

    /// Tokenize multiple texts into token ID sequences.
    ///
    /// # Arguments
    /// * `texts` - The texts to tokenize
    ///
    /// # Returns
    /// Vector of token ID vectors for each text.
    pub fn batch_tokenize(&self, texts: &[&str]) -> Vec<Vec<u32>> {
        texts.iter().map(|text| self.tokenize(text)).collect()
    }

    /// Tokenize multiple texts with error handling.
    ///
    /// # Arguments
    /// * `texts` - The texts to tokenize
    ///
    /// # Returns
    /// Result containing token IDs for each text or an error.
    pub fn try_batch_tokenize(
        &self,
        texts: &[&str],
    ) -> Result<Vec<Vec<u32>>, Box<dyn std::error::Error + Send + Sync>> {
        if self.tokenizer.is_none() {
            return Err("No tokenizer loaded".into());
        }
        texts.iter().map(|text| self.try_tokenize(text)).collect()
    }

    /// Tokenize multiple texts with automatic padding.
    ///
    /// Sequences are padded to the maximum length in the batch.
    /// Default padding uses the TTS pad token (151671).
    ///
    /// # Arguments
    /// * `texts` - The texts to tokenize
    /// * `padding_side` - Whether to pad on the left (default) or right
    ///
    /// # Returns
    /// `TokenizerOutput` with padded input_ids, attention_mask, and original lengths.
    pub fn batch_tokenize_padded(
        &self,
        texts: &[&str],
        padding_side: PaddingSide,
    ) -> Result<TokenizerOutput, Box<dyn std::error::Error + Send + Sync>> {
        self.batch_tokenize_padded_with_pad_token(texts, padding_side, self.special_tokens.tts_pad)
    }

    /// Tokenize multiple texts with automatic padding using a custom pad token.
    ///
    /// # Arguments
    /// * `texts` - The texts to tokenize
    /// * `padding_side` - Whether to pad on the left or right
    /// * `pad_token_id` - The token ID to use for padding
    ///
    /// # Returns
    /// `TokenizerOutput` with padded input_ids, attention_mask, and original lengths.
    pub fn batch_tokenize_padded_with_pad_token(
        &self,
        texts: &[&str],
        padding_side: PaddingSide,
        pad_token_id: u32,
    ) -> Result<TokenizerOutput, Box<dyn std::error::Error + Send + Sync>> {
        let sequences = self.try_batch_tokenize(texts)?;
        Ok(Self::pad_sequences(&sequences, padding_side, pad_token_id))
    }

    /// Tokenize texts for TTS with chat template and padding.
    ///
    /// Each text is wrapped in the assistant chat template before tokenizing,
    /// then all sequences are padded to the same length.
    ///
    /// # Arguments
    /// * `texts` - The texts to convert to speech
    /// * `padding_side` - Whether to pad on the left (default) or right
    ///
    /// # Returns
    /// `TokenizerOutput` with padded input_ids ready for the TTS model.
    pub fn batch_tokenize_for_tts(
        &self,
        texts: &[&str],
        padding_side: PaddingSide,
    ) -> Result<TokenizerOutput, Box<dyn std::error::Error + Send + Sync>> {
        let formatted: Vec<String> = texts.iter().map(|t| self.build_assistant_text(t)).collect();
        let formatted_refs: Vec<&str> = formatted.iter().map(|s| s.as_str()).collect();
        self.batch_tokenize_padded(&formatted_refs, padding_side)
    }

    /// Pad a batch of token sequences to the same length.
    ///
    /// # Arguments
    /// * `sequences` - The token sequences to pad
    /// * `padding_side` - Whether to pad on the left or right
    /// * `pad_token_id` - The token ID to use for padding
    ///
    /// # Returns
    /// `TokenizerOutput` with padded sequences and attention masks.
    pub fn pad_sequences(
        sequences: &[Vec<u32>],
        padding_side: PaddingSide,
        pad_token_id: u32,
    ) -> TokenizerOutput {
        if sequences.is_empty() {
            return TokenizerOutput {
                input_ids: vec![],
                attention_mask: vec![],
                lengths: vec![],
            };
        }

        let lengths: Vec<usize> = sequences.iter().map(|s| s.len()).collect();
        let max_len = lengths.iter().copied().max().unwrap_or(0);

        let mut input_ids = Vec::with_capacity(sequences.len());
        let mut attention_mask = Vec::with_capacity(sequences.len());

        for seq in sequences {
            let pad_len = max_len - seq.len();
            let mut padded_ids = Vec::with_capacity(max_len);
            let mut mask = Vec::with_capacity(max_len);

            match padding_side {
                PaddingSide::Left => {
                    // Add padding on the left
                    padded_ids.extend(std::iter::repeat_n(pad_token_id, pad_len));
                    padded_ids.extend(seq.iter().copied());
                    // Mask: 0 for padding, 1 for real tokens
                    mask.extend(std::iter::repeat_n(0u32, pad_len));
                    mask.extend(std::iter::repeat_n(1u32, seq.len()));
                }
                PaddingSide::Right => {
                    // Add padding on the right
                    padded_ids.extend(seq.iter().copied());
                    padded_ids.extend(std::iter::repeat_n(pad_token_id, pad_len));
                    // Mask: 1 for real tokens, 0 for padding
                    mask.extend(std::iter::repeat_n(1u32, seq.len()));
                    mask.extend(std::iter::repeat_n(0u32, pad_len));
                }
            }

            input_ids.push(padded_ids);
            attention_mask.push(mask);
        }

        TokenizerOutput {
            input_ids,
            attention_mask,
            lengths,
        }
    }

    /// Decode multiple token sequences back to text.
    ///
    /// # Arguments
    /// * `batch_ids` - The batch of token ID sequences to decode
    ///
    /// # Returns
    /// Vector of decoded strings, or empty vector if no tokenizer is loaded.
    pub fn batch_decode(&self, batch_ids: &[&[u32]]) -> Vec<Option<String>> {
        batch_ids.iter().map(|ids| self.decode(ids)).collect()
    }

    /// Decode multiple token sequences, skipping special tokens.
    ///
    /// # Arguments
    /// * `batch_ids` - The batch of token ID sequences to decode
    /// * `skip_special_tokens` - Whether to skip special tokens in decoding
    ///
    /// # Returns
    /// Vector of decoded strings.
    pub fn batch_decode_with_options(
        &self,
        batch_ids: &[&[u32]],
        skip_special_tokens: bool,
    ) -> Vec<Option<String>> {
        match &self.tokenizer {
            Some(tokenizer) => batch_ids
                .iter()
                .map(|ids| tokenizer.decode(ids, skip_special_tokens).ok())
                .collect(),
            None => batch_ids.iter().map(|_| None).collect(),
        }
    }
}

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

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

    #[test]
    fn test_normalize_text() {
        // Smart quotes
        assert_eq!(normalize_text("\u{2018}hello\u{2019}"), "'hello'");
        assert_eq!(normalize_text("\u{201C}world\u{201D}"), "\"world\"");

        // Dashes
        assert_eq!(normalize_text("one\u{2013}two"), "one-two"); // en-dash
        assert_eq!(normalize_text("one\u{2014}two"), "one--two"); // em-dash

        // Ellipsis
        assert_eq!(normalize_text("wait\u{2026}"), "wait...");

        // Unicode whitespace
        assert_eq!(normalize_text("hello\u{00A0}world"), "hello world"); // NBSP
        assert_eq!(normalize_text("hello\u{202F}world"), "hello world"); // narrow NBSP
        assert_eq!(normalize_text("hello\u{3000}world"), "hello world"); // ideographic space

        // Line endings
        assert_eq!(normalize_text("a\r\nb"), "a\nb"); // CRLF
        assert_eq!(normalize_text("a\rb"), "a\nb"); // CR

        // Zero-width characters (removed)
        assert_eq!(normalize_text("hel\u{200B}lo"), "hello"); // ZWSP
        assert_eq!(normalize_text("hel\u{FEFF}lo"), "hello"); // BOM
        assert_eq!(normalize_text("hel\u{200C}lo"), "hello"); // ZWNJ
        assert_eq!(normalize_text("hel\u{200D}lo"), "hello"); // ZWJ

        // Combined typographic
        assert_eq!(
            normalize_text("He said, \u{201C}It\u{2019}s\u{2014}well\u{2026}\u{201D}"),
            "He said, \"It's--well...\""
        );

        // ASCII passthrough
        assert_eq!(normalize_text("Hello, world!"), "Hello, world!");
    }

    #[test]
    fn test_chat_templates() {
        let processor = TextProcessor::new();

        let assistant = processor.build_assistant_text("Hello world");
        assert_eq!(
            assistant,
            "<|im_start|>assistant\nHello world<|im_end|>\n<|im_start|>assistant\n"
        );

        let ref_text = processor.build_ref_text("Reference");
        assert_eq!(ref_text, "<|im_start|>assistant\nReference<|im_end|>\n");

        let instruct = processor.build_instruct_text("Speak slowly");
        assert_eq!(instruct, "<|im_start|>user\nSpeak slowly<|im_end|>\n");
    }

    #[test]
    fn test_special_token_defaults() {
        let tokens = SpecialTokenIds::default();
        assert_eq!(tokens.im_start, 151644);
        assert_eq!(tokens.im_end, 151645);
        assert_eq!(tokens.tts_bos, 151672);
    }

    #[test]
    fn test_tokenize_without_tokenizer() {
        let processor = TextProcessor::new();
        let tokens = processor.tokenize("Hello");
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_add_tts_tokens() {
        let processor = TextProcessor::new();
        let tokens = vec![1, 2, 3];
        let with_tts = processor.add_tts_tokens(tokens);
        assert_eq!(with_tts, vec![151672, 1, 2, 3]);
    }

    #[test]
    fn test_padding_side_default() {
        let side = PaddingSide::default();
        assert_eq!(side, PaddingSide::Left);
    }

    #[test]
    fn test_pad_sequences_left() {
        // Test left padding with variable length sequences
        let sequences = vec![vec![1, 2], vec![3, 4, 5, 6], vec![7]];
        let output = TextProcessor::pad_sequences(&sequences, PaddingSide::Left, 0);

        // Max length is 4, all should be padded to 4
        assert_eq!(output.input_ids.len(), 3);
        assert_eq!(output.input_ids[0], vec![0, 0, 1, 2]); // 2 pads on left
        assert_eq!(output.input_ids[1], vec![3, 4, 5, 6]); // no padding
        assert_eq!(output.input_ids[2], vec![0, 0, 0, 7]); // 3 pads on left

        // Attention masks
        assert_eq!(output.attention_mask[0], vec![0, 0, 1, 1]);
        assert_eq!(output.attention_mask[1], vec![1, 1, 1, 1]);
        assert_eq!(output.attention_mask[2], vec![0, 0, 0, 1]);

        // Original lengths
        assert_eq!(output.lengths, vec![2, 4, 1]);
    }

    #[test]
    fn test_pad_sequences_right() {
        let sequences = vec![vec![1, 2], vec![3, 4, 5]];
        let output = TextProcessor::pad_sequences(&sequences, PaddingSide::Right, 99);

        assert_eq!(output.input_ids[0], vec![1, 2, 99]); // 1 pad on right
        assert_eq!(output.input_ids[1], vec![3, 4, 5]); // no padding

        assert_eq!(output.attention_mask[0], vec![1, 1, 0]);
        assert_eq!(output.attention_mask[1], vec![1, 1, 1]);
    }

    #[test]
    fn test_pad_sequences_empty() {
        let sequences: Vec<Vec<u32>> = vec![];
        let output = TextProcessor::pad_sequences(&sequences, PaddingSide::Left, 0);
        assert!(output.input_ids.is_empty());
        assert!(output.attention_mask.is_empty());
        assert!(output.lengths.is_empty());
    }

    #[test]
    fn test_pad_sequences_single() {
        let sequences = vec![vec![1, 2, 3]];
        let output = TextProcessor::pad_sequences(&sequences, PaddingSide::Left, 0);

        assert_eq!(output.input_ids.len(), 1);
        assert_eq!(output.input_ids[0], vec![1, 2, 3]); // no padding needed
        assert_eq!(output.attention_mask[0], vec![1, 1, 1]);
        assert_eq!(output.lengths, vec![3]);
    }

    #[test]
    fn test_batch_tokenize_without_tokenizer() {
        let processor = TextProcessor::new();
        let results = processor.batch_tokenize(&["Hello", "World"]);
        assert_eq!(results.len(), 2);
        assert!(results[0].is_empty());
        assert!(results[1].is_empty());
    }

    #[test]
    fn test_try_batch_tokenize_without_tokenizer() {
        let processor = TextProcessor::new();
        let result = processor.try_batch_tokenize(&["Hello", "World"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_batch_decode_without_tokenizer() {
        let processor = TextProcessor::new();
        let ids: &[&[u32]] = &[&[1, 2, 3], &[4, 5]];
        let results = processor.batch_decode(ids);
        assert_eq!(results.len(), 2);
        assert!(results[0].is_none());
        assert!(results[1].is_none());
    }

    #[test]
    fn test_tokenizer_output_structure() {
        let output = TokenizerOutput {
            input_ids: vec![vec![1, 2], vec![3, 4]],
            attention_mask: vec![vec![1, 1], vec![1, 1]],
            lengths: vec![2, 2],
        };
        assert_eq!(output.input_ids.len(), 2);
        assert_eq!(output.attention_mask.len(), 2);
        assert_eq!(output.lengths.len(), 2);
    }
}