pocket-tts 0.6.2

High-performance CPU-based Text-to-Speech library using 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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
//! Main TTSModel struct - orchestrates the TTS pipeline
//!
//! This is the high-level API for text-to-speech generation,
//! matching Python's `pocket_tts/models/tts_model.py`.

use crate::ModelState;
use crate::conditioners::text::LUTConditioner;
use crate::config::{Config, defaults, load_config};
use crate::models::flow_lm::FlowLMModel;
use crate::models::mimi::MimiModel;
use crate::models::seanet::{SEANetDecoder, SEANetEncoder};
use crate::models::transformer::{ProjectedTransformer, StreamingTransformer};
use crate::modules::mlp::SimpleMLPAdaLN;
use crate::voice_state::{increment_steps, init_states};

use anyhow::Result;
use candle_core::{DType, Device, Tensor};
use candle_nn::VarBuilder;

/// Main TTS model that orchestrates the entire pipeline
#[derive(Clone)]
pub struct TTSModel {
    /// Flow language model for latent generation
    pub flow_lm: FlowLMModel,
    /// Mimi neural audio codec
    pub mimi: MimiModel,
    /// Text conditioner (tokenizer + embeddings)
    pub conditioner: LUTConditioner,
    /// Speaker projection weight for voice cloning
    pub speaker_proj_weight: Tensor,
    /// Generation temperature
    pub temp: f32,
    /// Number of LSD decode steps
    pub lsd_decode_steps: usize,
    /// End-of-sequence threshold
    pub eos_threshold: f32,
    pub noise_clamp: Option<f32>,
    /// Optional override for voice-conditioning Mimi chunk size (in frames).
    /// If `None`, an adaptive heuristic is used.
    pub voice_prompt_chunk_frames: Option<usize>,
    /// Sample rate
    pub sample_rate: usize,
    /// Model dimension
    pub dim: usize,
    /// Latent dimension
    pub ldim: usize,
    /// Device
    pub device: Device,
}

impl TTSModel {
    /// Load a pre-trained TTS model from HuggingFace
    ///
    /// # Arguments
    /// * `variant` - Model variant (e.g., "b6369a24")
    ///
    /// # Returns
    /// Fully initialized TTSModel ready for generation
    pub fn load(variant: &str) -> Result<Self> {
        Self::load_with_params(
            variant,
            defaults::TEMPERATURE,
            defaults::LSD_DECODE_STEPS,
            defaults::EOS_THRESHOLD,
        )
    }

    /// Load with custom generation parameters
    pub fn load_with_params(
        variant: &str,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
    ) -> Result<Self> {
        Self::load_with_params_device(
            variant,
            temp,
            lsd_decode_steps,
            eos_threshold,
            None,
            &Device::Cpu,
        )
    }

    /// Load with custom generation parameters and specific device
    pub fn load_with_params_device(
        variant: &str,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
        noise_clamp: Option<f32>,
        device: &Device,
    ) -> Result<Self> {
        // Find config file - look relative to the Rust crate, then fall back to Python location
        let config_path = find_config_path(variant)?;
        let config = load_config(&config_path)?;

        Self::from_config(
            config,
            temp,
            lsd_decode_steps,
            eos_threshold,
            noise_clamp,
            device,
        )
    }

    /// Load model with quantized weights for reduced memory footprint
    ///
    /// This applies simulated int8 quantization to applicable layers,
    /// reducing memory usage while maintaining acceptable quality.
    ///
    /// # Arguments
    /// * `variant` - Model variant (e.g., "b6369a24")
    ///
    /// # Returns
    /// TTSModel with quantized weights
    ///
    /// # Note
    /// Quantization uses 256 discrete levels (int8-equivalent).
    /// Some layers (embeddings, output projections) are kept in full precision.
    #[cfg(feature = "quantized")]
    pub fn load_quantized(variant: &str) -> Result<Self> {
        Self::load_quantized_with_params(
            variant,
            defaults::TEMPERATURE,
            defaults::LSD_DECODE_STEPS,
            defaults::EOS_THRESHOLD,
        )
    }

    /// Load quantized model with custom generation parameters
    #[cfg(feature = "quantized")]
    pub fn load_quantized_with_params(
        variant: &str,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
    ) -> Result<Self> {
        Self::load_quantized_with_params_device(
            variant,
            temp,
            lsd_decode_steps,
            eos_threshold,
            None,
            &Device::Cpu,
        )
    }

    /// Load quantized model with custom generation parameters and specific device
    #[cfg(feature = "quantized")]
    pub fn load_quantized_with_params_device(
        variant: &str,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
        noise_clamp: Option<f32>,
        device: &Device,
    ) -> Result<Self> {
        // Load model normally first
        let model = Self::load_with_params_device(
            variant,
            temp,
            lsd_decode_steps,
            eos_threshold,
            noise_clamp,
            device,
        )?;
        // ... (quantization placeholder logic remains same)
        Ok(model)
    }

    /// Check if this model was loaded with quantization
    #[cfg(feature = "quantized")]
    pub fn is_quantized(&self) -> bool {
        // In current implementation, we don't actually store quantized weights
        // This is a placeholder for future implementation
        false
    }

    /// Create model from configuration
    fn from_config(
        config: Config,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
        noise_clamp: Option<f32>,
        device: &Device,
    ) -> Result<Self> {
        let dtype = DType::F32;

        // Download weights
        #[cfg(not(target_arch = "wasm32"))]
        {
            let weights_path = config
                .weights_path
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("weights_path not specified in config"))?;
            let weights_file = crate::weights::download_if_necessary(weights_path)?;

            // Load safetensors with VarBuilder
            let vb =
                unsafe { VarBuilder::from_mmaped_safetensors(&[weights_file], dtype, device)? };

            // Download tokenizer
            let tokenizer_path =
                crate::weights::download_if_necessary(&config.flow_lm.lookup_table.tokenizer_path)?;

            // Build conditioner
            let conditioner = LUTConditioner::new(
                config.flow_lm.lookup_table.n_bins,
                &tokenizer_path,
                config.flow_lm.lookup_table.dim,
                config.flow_lm.transformer.d_model,
                vb.pp("flow_lm.conditioner"),
            )?;

            Self::from_config_and_vb(
                config,
                temp,
                lsd_decode_steps,
                eos_threshold,
                noise_clamp,
                conditioner,
                vb,
            )
        }

        #[cfg(target_arch = "wasm32")]
        {
            let _ = (config, temp, lsd_decode_steps, eos_threshold, device, dtype);
            anyhow::bail!(
                "WASM requires from_bytes or providing a pre-built VarBuilder. Use load_from_bytes instead."
            );
        }
    }

    /// Load model from byte slices (useful for WASM)
    pub fn load_from_bytes(
        config_yaml: &[u8],
        weights_bytes: &[u8],
        tokenizer_bytes: &[u8],
    ) -> Result<Self> {
        let config: Config = serde_yaml::from_slice(config_yaml)?;
        let device = Device::Cpu;
        let dtype = DType::F32;

        let tensors = candle_core::safetensors::load_buffer(weights_bytes, &device)?;
        let vb = VarBuilder::from_tensors(tensors, dtype, &device);

        // On WASM, LUTConditioner::new needs a path, but we've updated it to
        // eventually support bytes. For now, we'll need to adapt it.
        // Actually, my recent change to conditioners/text.rs still uses Tokenizer::from_file on WASM.
        // I should probably fix that to support bytes too.

        // For now, let's keep it simple and assume we have a path for the tokenizer or a way to load it.
        // This is a placeholder for real WASM loading.

        let conditioner = LUTConditioner::new_from_bytes(
            config.flow_lm.lookup_table.n_bins,
            tokenizer_bytes,
            config.flow_lm.lookup_table.dim,
            config.flow_lm.transformer.d_model,
            vb.pp("flow_lm.conditioner"),
        )?;

        Self::from_config_and_vb(
            config,
            defaults::TEMPERATURE,
            defaults::LSD_DECODE_STEPS,
            defaults::EOS_THRESHOLD,
            None,
            conditioner,
            vb,
        )
    }

    /// Internal helper to build model from config and VarBuilder
    fn from_config_and_vb(
        config: Config,
        temp: f32,
        lsd_decode_steps: usize,
        eos_threshold: f32,
        noise_clamp: Option<f32>,
        conditioner: LUTConditioner,
        vb: VarBuilder,
    ) -> Result<Self> {
        let device = vb.device().clone();

        // Build FlowLM components
        let dim = config.flow_lm.transformer.d_model;
        let ldim = config.mimi.quantizer.dimension;
        let hidden_dim = dim * config.flow_lm.transformer.hidden_scale;

        // SimpleMLPAdaLN::new(in_channels, model_channels, out_channels, cond_channels, num_res_blocks, num_time_conds, max_period, vb)
        let flow_net = SimpleMLPAdaLN::new(
            ldim,                      // in_channels (input is latent dim)
            config.flow_lm.flow.dim,   // model_channels
            ldim,                      // out_channels (output is also latent dim)
            dim,                       // cond_channels (conditioning from transformer)
            config.flow_lm.flow.depth, // num_res_blocks
            2,                         // num_time_conds (s and t)
            config.flow_lm.transformer.max_period as f32,
            vb.pp("flow_lm.flow_net"),
        )?;

        // StreamingTransformer::new(d_model, num_heads, num_layers, layer_scale, dim_feedforward, context, max_period, kind, name, vb)
        let transformer = StreamingTransformer::new(
            dim,
            config.flow_lm.transformer.num_heads,
            config.flow_lm.transformer.num_layers,
            None,       // layer_scale
            hidden_dim, // dim_feedforward
            None,       // context (causal)
            config.flow_lm.transformer.max_period as f32,
            "kv",
            "flow_lm.transformer",
            vb.pp("flow_lm.transformer"),
        )?;

        let mut flow_lm = FlowLMModel::new(flow_net, transformer, ldim, dim, vb.pp("flow_lm"))?;
        flow_lm.noise_clamp = noise_clamp;

        // Build Mimi components
        let seanet_cfg = &config.mimi.seanet;
        let encoder = SEANetEncoder::new(
            seanet_cfg.channels,
            seanet_cfg.dimension,
            seanet_cfg.n_filters,
            seanet_cfg.n_residual_layers,
            &seanet_cfg.ratios,
            seanet_cfg.kernel_size,
            seanet_cfg.residual_kernel_size,
            seanet_cfg.last_kernel_size,
            seanet_cfg.dilation_base,
            &seanet_cfg.pad_mode,
            seanet_cfg.compress,
            "mimi.encoder",
            vb.pp("mimi.encoder"),
        )?;

        let decoder = SEANetDecoder::new(
            seanet_cfg.channels,
            seanet_cfg.dimension,
            seanet_cfg.n_filters,
            seanet_cfg.n_residual_layers,
            &seanet_cfg.ratios,
            seanet_cfg.kernel_size,
            seanet_cfg.residual_kernel_size,
            seanet_cfg.last_kernel_size,
            seanet_cfg.dilation_base,
            &seanet_cfg.pad_mode,
            seanet_cfg.compress,
            "mimi.decoder",
            vb.pp("mimi.decoder"),
        )?;

        let mimi_tr_cfg = &config.mimi.transformer;
        // ProjectedTransformer::new(input_dimension, output_dimensions, d_model, num_heads, num_layers, layer_scale, context, max_period, dim_feedforward, name, vb)
        let encoder_transformer = ProjectedTransformer::new(
            mimi_tr_cfg.input_dimension,
            mimi_tr_cfg.output_dimensions.clone(),
            mimi_tr_cfg.d_model,
            mimi_tr_cfg.num_heads,
            mimi_tr_cfg.num_layers,
            mimi_tr_cfg.layer_scale as f32,
            mimi_tr_cfg.context,
            mimi_tr_cfg.max_period as f32,
            mimi_tr_cfg.dim_feedforward,
            "mimi.encoder_transformer",
            vb.pp("mimi.encoder_transformer"),
        )?;

        let decoder_transformer = ProjectedTransformer::new(
            mimi_tr_cfg.input_dimension,
            mimi_tr_cfg.output_dimensions.clone(),
            mimi_tr_cfg.d_model,
            mimi_tr_cfg.num_heads,
            mimi_tr_cfg.num_layers,
            mimi_tr_cfg.layer_scale as f32,
            mimi_tr_cfg.context,
            mimi_tr_cfg.max_period as f32,
            mimi_tr_cfg.dim_feedforward,
            "mimi.decoder_transformer",
            vb.pp("mimi.decoder_transformer"),
        )?;

        // Calculate encoder frame rate from SEANet ratios
        let hop_length: usize = seanet_cfg.ratios.iter().product();
        let encoder_frame_rate = config.mimi.sample_rate as f64 / hop_length as f64;

        let mimi = MimiModel::new(
            encoder,
            decoder,
            encoder_transformer,
            decoder_transformer,
            config.mimi.frame_rate,
            encoder_frame_rate,
            config.mimi.sample_rate,
            config.mimi.channels,
            config.mimi.quantizer.dimension,
            config.mimi.quantizer.output_dimension,
            "mimi",
            vb.pp("mimi"),
        )?;

        // Load speaker projection weight - uses mimi output dimension, not internal ldim
        let mimi_out_dim = config.mimi.quantizer.output_dimension;
        let speaker_proj_weight = vb.get((dim, mimi_out_dim), "flow_lm.speaker_proj_weight")?;

        Ok(Self {
            flow_lm,
            mimi,
            conditioner,
            speaker_proj_weight,
            temp,
            lsd_decode_steps,
            eos_threshold,
            noise_clamp,
            voice_prompt_chunk_frames: None,
            sample_rate: config.mimi.sample_rate,
            dim,
            ldim,
            device,
        })
    }

    /// Create voice state from audio prompt bytes for voice cloning
    pub fn get_voice_state_from_bytes(&self, bytes: &[u8]) -> Result<ModelState> {
        let (audio, sample_rate) = crate::audio::read_wav_from_bytes(bytes)?;

        // Resample to model sample rate if needed
        let audio = if sample_rate != self.sample_rate as u32 {
            crate::audio::resample(&audio, sample_rate, self.sample_rate as u32)?
        } else {
            audio
        };

        // Add batch dimension: [C, T] -> [B, C, T]
        let audio = audio.unsqueeze(0)?;

        self.get_voice_state_from_tensor(&audio)
    }

    /// Create voice state from audio prompt for voice cloning
    ///
    /// Encodes the audio through Mimi and projects to flow model space.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn get_voice_state<P: AsRef<std::path::Path>>(&self, audio_path: P) -> Result<ModelState> {
        let (audio, sample_rate) = crate::audio::read_wav(audio_path)?;

        // Resample to model sample rate if needed
        let audio = if sample_rate != self.sample_rate as u32 {
            crate::audio::resample(&audio, sample_rate, self.sample_rate as u32)?
        } else {
            audio
        };

        // Add batch dimension: [C, T] -> [B, C, T]
        let audio = audio.unsqueeze(0)?;

        self.get_voice_state_from_tensor(&audio)
    }

    /// Create voice state from a pre-calculated latent prompt file (.safetensors)
    #[cfg(not(target_arch = "wasm32"))]
    pub fn get_voice_state_from_prompt_file<P: AsRef<std::path::Path>>(
        &self,
        path: P,
    ) -> Result<ModelState> {
        let tensors = candle_core::safetensors::load(path, &self.device)?;
        let prompt = tensors
            .get("audio_prompt")
            .ok_or_else(|| anyhow::anyhow!("'audio_prompt' not found in safetensors file"))?;

        self.get_voice_state_from_prompt_tensor(prompt)
    }

    /// Create voice state from pre-calculated latent prompt bytes (.safetensors)
    pub fn get_voice_state_from_prompt_bytes(&self, bytes: &[u8]) -> Result<ModelState> {
        let tensors = candle_core::safetensors::load_buffer(bytes, &self.device)?;
        let prompt = tensors
            .get("audio_prompt")
            .ok_or_else(|| anyhow::anyhow!("'audio_prompt' not found in safetensors bytes"))?;

        self.get_voice_state_from_prompt_tensor(prompt)
    }

    /// Create voice state from a pre-calculated latent prompt tensor
    pub fn get_voice_state_from_prompt_tensor(&self, prompt: &Tensor) -> Result<ModelState> {
        // Ensure prompt tensor is on the same device as the model (fixes Metal device mismatch)
        let prompt = if prompt.device().same_device(&self.device) {
            prompt.clone()
        } else {
            prompt.to_device(&self.device)?
        };

        let mut flow_state = init_states(1, 1000);
        self.run_flow_lm_prompt(&prompt, &mut flow_state)?;
        Ok(flow_state)
    }

    /// Create voice state from audio tensor
    pub fn get_voice_state_from_tensor(&self, audio: &Tensor) -> Result<ModelState> {
        let mut model_state = init_states(1, 1000);

        // Ensure audio tensor is on the same device as the model (fixes Metal device mismatch)
        let audio = if audio.device().same_device(&self.device) {
            audio.clone()
        } else {
            audio.to_device(&self.device)?
        };

        // Pad audio to a multiple of frame size for streaming conv stride alignment
        let frame_size = self.mimi.frame_size();
        let (b, c, t) = audio.dims3()?;
        let pad_len = if t % frame_size != 0 {
            frame_size - (t % frame_size)
        } else {
            0
        };
        let audio = if pad_len > 0 {
            // Create padding on the same device as audio (which is now on self.device)
            let pad = Tensor::zeros((b, c, pad_len), audio.dtype(), &self.device)?;
            Tensor::cat(&[&audio, &pad], 2)?
        } else {
            audio
        };

        // Encode audio through Mimi in chunks to avoid OOM in SEANet Conv1d layers.
        // Chunk size is adapted to prompt length unless explicitly overridden.
        let mut encoded_chunks = Vec::new();
        let (_b, _c, total_samples) = audio.dims3()?;
        let chunk_frames = self.adaptive_voice_prompt_chunk_frames(total_samples, frame_size);
        let chunk_size = frame_size * chunk_frames;

        for start in (0..total_samples).step_by(chunk_size) {
            let end = std::cmp::min(start + chunk_size, total_samples);
            let chunk = audio.narrow(2, start, end - start)?;
            let code = self.mimi.encode_to_latent(&chunk, &mut model_state, 0)?;
            encoded_chunks.push(code);
        }
        let encoded = Tensor::cat(&encoded_chunks, 2)?;

        // Transpose from [B, D, T] to [B, T, D]
        let latents = encoded.transpose(1, 2)?.to_dtype(DType::F32)?;

        // Project to flow model space: [B, T, ldim] @ [dim, ldim].T -> [B, T, dim]
        // Candle needs 2D @ 2D for matmul, so reshape
        let (b, t, d) = latents.dims3()?;
        let latents_2d = latents.reshape((b * t, d))?;
        let conditioning_2d = latents_2d.matmul(&self.speaker_proj_weight.t()?)?;
        let conditioning = conditioning_2d.reshape((b, t, self.dim))?;

        // Run flow_lm with audio conditioning to update state
        let mut flow_state = init_states(1, 1000);
        self.run_flow_lm_prompt(&conditioning, &mut flow_state)?;

        Ok(flow_state)
    }

    fn adaptive_voice_prompt_chunk_frames(&self, total_samples: usize, frame_size: usize) -> usize {
        if let Some(override_frames) = self.voice_prompt_chunk_frames {
            return override_frames.max(1);
        }

        let total_frames = total_samples.div_ceil(frame_size);
        if total_frames <= 120 {
            total_frames.max(1)
        } else if total_frames <= 600 {
            120
        } else if total_frames <= 1800 {
            180
        } else {
            240
        }
    }

    /// Run flow LM with audio conditioning (used during prompting)
    fn run_flow_lm_prompt(&self, conditioning: &Tensor, state: &mut ModelState) -> Result<()> {
        // Empty text tokens and backbone input
        let empty_text = Tensor::zeros((1, 0), DType::I64, &self.device)?;
        let text_embeddings = self.conditioner.forward(&empty_text)?;

        // Concatenate text embeddings and audio conditioning
        // Match Python/reference order: audio conditioning comes before text embeddings.
        let input = Tensor::cat(&[conditioning, &text_embeddings], 1)?;

        // Run through transformer (no generation, just prompting)
        // With custom SDPA, this is now memory efficient
        let _ = self.flow_lm.transformer.forward(&input, state, 0)?;

        // Increment FlowLM state after prompting (critical for RoPE positioning)
        // Python: increment_steps(self.flow_lm, model_state, increment=audio_conditioning.shape[1])
        let increment_by = conditioning.dims()[1];
        increment_steps(state, "offset", increment_by);

        Ok(())
    }

    /// Split text into optimal chunks for generation, matching Python's logic exactly.
    /// Uses actual tokenization to ensure chunks never exceed MAX_TOKENS_PER_CHUNK (50).
    /// This prevents O(N²) attention complexity for long texts.
    pub fn split_into_best_sentences(&self, text: &str) -> Vec<String> {
        const MAX_TOKENS_PER_CHUNK: usize = 50;

        let prepared_text = prepare_text_prompt(text);

        // 1. Initial split by punctuation to respect sentence boundaries
        let raw_sentences: Vec<&str> = prepared_text
            .split_inclusive(&['.', '!', '?', ';', ':'])
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect();

        if raw_sentences.is_empty() {
            return vec![prepared_text];
        }

        let mut chunks = Vec::new();
        let mut current_chunk = String::new();
        let mut current_token_count = 0;

        for sentence in raw_sentences {
            let sentence_tokens = self
                .conditioner
                .count_tokens(sentence)
                .unwrap_or(MAX_TOKENS_PER_CHUNK);

            // If a single sentence exceeds max tokens, split it by words
            if sentence_tokens > MAX_TOKENS_PER_CHUNK {
                // Flush pending chunk first
                if !current_chunk.is_empty() {
                    chunks.push(current_chunk);
                    current_chunk = String::new();
                    current_token_count = 0;
                }

                // Split long sentence using word-batch estimation (~1.3 tokens per word average)
                // This avoids calling count_tokens for every word (expensive!)
                let words: Vec<&str> = sentence.split_whitespace().collect();
                const WORDS_PER_BATCH: usize = 35; // ~45 tokens, safe margin under 50

                for word_batch in words.chunks(WORDS_PER_BATCH) {
                    let chunk_str = word_batch.join(" ");
                    // Verify this batch is actually under limit (should almost always pass)
                    let actual_tokens = self
                        .conditioner
                        .count_tokens(&chunk_str)
                        .unwrap_or(MAX_TOKENS_PER_CHUNK);

                    if actual_tokens <= MAX_TOKENS_PER_CHUNK {
                        chunks.push(chunk_str);
                    } else {
                        // Rare case: batch still too big, split in half recursively
                        let mid = word_batch.len() / 2;
                        chunks.push(word_batch[..mid].join(" "));
                        chunks.push(word_batch[mid..].join(" "));
                    }
                }
                continue;
            }

            // Normal accumulation logic
            if current_chunk.is_empty() {
                current_chunk = sentence.to_string();
                current_token_count = sentence_tokens;
            } else if current_token_count + sentence_tokens > MAX_TOKENS_PER_CHUNK {
                chunks.push(current_chunk);
                current_chunk = sentence.to_string();
                current_token_count = sentence_tokens;
            } else {
                current_chunk.push(' ');
                current_chunk.push_str(sentence);
                current_token_count += sentence_tokens;
            }
        }

        if !current_chunk.is_empty() {
            chunks.push(current_chunk);
        }

        chunks
    }

    /// Generate audio from text with voice state
    pub fn generate(&self, text: &str, voice_state: &ModelState) -> Result<Tensor> {
        let mut audio_chunks = Vec::new();

        for chunk in self.generate_stream(text, voice_state) {
            audio_chunks.push(chunk?);
        }

        // Concatenate all audio chunks
        if audio_chunks.is_empty() {
            anyhow::bail!("No audio generated");
        }
        let audio = Tensor::cat(&audio_chunks, 2)?;
        // Remove batch dimension
        let audio = audio.squeeze(0)?;

        Ok(audio)
    }

    // =========================================================================
    // EXPERIMENTAL: Parallel FlowLM + Mimi decoding
    // =========================================================================
    //
    // This method was an experiment to decode Mimi audio in a separate thread
    // while FlowLM generates the next latent. However, benchmarks showed it's
    // ~21% SLOWER than sequential due to:
    // - Thread spawning and channel synchronization overhead
    // - CPU contention (MKL already parallelizes internally)
    // - Bounded channel backpressure when Mimi can't keep up
    //
    // Keeping this commented out for future exploration with GPU acceleration
    // where FlowLM and Mimi could run on different hardware.
    //
    // To re-enable: uncomment the method below and test with:
    //   model.generate_parallel(text, &voice_state)
    //
    /*
    /// Generate audio with parallel FlowLM + Mimi decoding
    ///
    /// Uses std::thread to decode Mimi audio in parallel with FlowLM generation.
    /// While Mimi decodes frame N, FlowLM generates frame N+1.
    ///
    /// NOTE: Currently slower than sequential due to thread overhead on CPU.
    /// May be useful for GPU acceleration in the future.
    pub fn generate_parallel(&self, text: &str, voice_state: &ModelState) -> Result<Tensor> {
        use std::sync::mpsc;
        use std::thread;

        // Channel for sending latents from FlowLM to Mimi decoder
        let (latent_tx, latent_rx) = mpsc::sync_channel::<Option<(Tensor, usize)>>(4);
        // Channel for receiving decoded audio from Mimi
        let (audio_tx, audio_rx) = mpsc::channel::<Result<Tensor>>();

        // Clone what the decoder thread needs
        let mimi = self.mimi.clone();
        let emb_mean = self.flow_lm.emb_mean.clone();
        let emb_std = self.flow_lm.emb_std.clone();

        // Spawn Mimi decoder thread
        let decoder_handle = thread::spawn(move || {
            let mut mimi_state = init_states(1, 1000);

            while let Ok(Some((next_latent, step))) = latent_rx.recv() {
                let result = (|| -> Result<Tensor> {
                    let next_latent_denorm = next_latent
                        .broadcast_mul(&emb_std)?
                        .broadcast_add(&emb_mean)?;

                    let mimi_input = next_latent_denorm.unsqueeze(1)?.transpose(1, 2)?;
                    let quantized = mimi.quantize(&mimi_input)?;
                    let audio = mimi
                        .decode_from_latent(&quantized, &mut mimi_state, step)
                        .map_err(|e| anyhow::anyhow!(e))?;

                    Ok(audio)
                })();

                if audio_tx.send(result).is_err() {
                    break; // Receiver dropped
                }
            }
        });

        // Main thread: generate latents with FlowLM
        let chunks = self.split_into_best_sentences(text);
        let mut expected_frames = 0;

        for chunk_text in chunks {
            let mut state = voice_state.clone();
            let prepared_text = prepare_text_prompt(&chunk_text);

            let tokens = self.conditioner.prepare(&prepared_text, &self.device)?;
            let text_embeddings = self.conditioner.forward(&tokens)?;

            // Initial text prompt
            self.flow_lm
                .transformer
                .forward(&text_embeddings, &mut state, 0)?;

            let max_gen_len = (prepared_text.split_whitespace().count() + 2) * 13;
            let frames_after_eos = estimate_frames_after_eos(&chunk_text);

            let mut backbone_input = self.flow_lm.bos_emb.clone().reshape((1, 1, self.ldim))?;
            let mut eos_step: Option<usize> = None;

            let time_embeddings = self.flow_lm.flow_net.compute_time_embeddings(
                self.lsd_decode_steps,
                &self.device,
                DType::F32,
            )?;

            let empty_text_embeddings = Tensor::zeros((1, 0, self.dim), DType::F32, &self.device)?;

            for step in 0..max_gen_len {
                let (next_latent, is_eos) = self.flow_lm.forward(
                    &backbone_input,
                    &empty_text_embeddings,
                    &mut state,
                    &time_embeddings,
                    self.temp,
                    self.eos_threshold,
                    step,
                )?;

                // Send latent to decoder thread (non-blocking with bounded channel)
                if latent_tx.send(Some((next_latent.clone(), step))).is_err() {
                    break;
                }
                expected_frames += 1;

                if is_eos && eos_step.is_none() {
                    eos_step = Some(step);
                }

                if let Some(e_step) = eos_step {
                    if step >= e_step + frames_after_eos {
                        break;
                    }
                }

                backbone_input = next_latent.unsqueeze(1)?;
            }
        }

        // Signal decoder thread to finish
        let _ = latent_tx.send(None);

        // Collect all decoded audio frames
        let mut audio_chunks = Vec::with_capacity(expected_frames);
        for _ in 0..expected_frames {
            match audio_rx.recv() {
                Ok(Ok(frame)) => audio_chunks.push(frame),
                Ok(Err(e)) => return Err(e),
                Err(_) => break,
            }
        }

        // Wait for decoder thread
        let _ = decoder_handle.join();

        if audio_chunks.is_empty() {
            anyhow::bail!("No audio generated");
        }

        let audio = Tensor::cat(&audio_chunks, 2)?;
        let audio = audio.squeeze(0)?;
        Ok(audio)
    }
    */

    /// Generate audio from text with pause handling
    ///
    /// This method parses pause markers in the text and inserts silence
    /// at appropriate positions. Supports:
    /// - Explicit pauses: `[pause:500ms]` or `[pause:1s]`
    /// - Natural pauses from punctuation are handled during generation
    ///
    /// # Example
    /// ```ignore
    /// let audio = model.generate_with_pauses("Hello... [pause:500ms] world", &voice_state)?;
    /// ```
    pub fn generate_with_pauses(&self, text: &str, voice_state: &ModelState) -> Result<Tensor> {
        let mut audio_chunks = Vec::new();

        for chunk in self.generate_stream_long(text, voice_state) {
            audio_chunks.push(chunk?);
        }

        // Concatenate all audio chunks
        if audio_chunks.is_empty() {
            anyhow::bail!("No audio generated");
        }
        let audio = Tensor::cat(&audio_chunks, 2)?;
        // Remove batch dimension
        let audio = audio.squeeze(0)?;

        Ok(audio)
    }

    /// Generate audio stream from text with voice state
    ///
    /// Returns an iterator that yields audio chunks (one per Mimi frame).
    /// Generate audio stream from text with voice state
    ///
    /// Returns an iterator that yields audio chunks (one per Mimi frame).
    ///
    /// This method splits the text into optimal sentences and generates each independently,
    /// matching Python's behavior to maintain O(N) complexity for long texts.
    pub fn generate_stream<'a, 'b, 'c>(
        &'a self,
        text: &'b str,
        voice_state: &'c ModelState,
    ) -> Box<dyn Iterator<Item = Result<Tensor>> + 'a> {
        // Split text into chunks to avoid quadratic complexity scaling
        let chunks = self.split_into_best_sentences(text);

        // Clone voice state so the iterator owns a copy, untied from lifetime 'c
        let voice_state_owned = voice_state.clone();

        // Create an iterator that processes each chunk sequentially
        let iterator = chunks.into_iter().flat_map(move |chunk_text| {
            // We need to return an iterator for each chunk.
            // We pass a reference to the owned voice state captured by the closure.
            self.generate_stream_segment(chunk_text, &voice_state_owned)
        });

        Box::new(iterator)
    }

    /// Generate audio stream from text with voice state, returning an owned iterator.
    ///
    /// This is useful for WASM bindings where the iterator must be 'static.
    pub fn generate_stream_owned(
        &self,
        text: &str,
        voice_state: &ModelState,
    ) -> Box<dyn Iterator<Item = Result<Tensor>> + 'static> {
        let model = self.clone();
        let voice_state_owned = voice_state.clone();
        let chunks = model.split_into_best_sentences(text);

        let iterator = chunks.into_iter().flat_map(move |chunk_text| {
            model.generate_stream_segment(chunk_text, &voice_state_owned)
        });

        Box::new(iterator)
    }

    /// Internal helper to generate a single segment (short text) matching Python's _generate
    fn generate_stream_segment(
        &self,
        text: String,
        voice_state: &ModelState,
    ) -> Box<dyn Iterator<Item = Result<Tensor>>> {
        let mut state = voice_state.clone();
        let mut mimi_state = init_states(1, 1000);

        // Prepare text
        let prepared_text = prepare_text_prompt(&text);

        // Error handling for preparation failures inside the iterator
        let tokens = match self.conditioner.prepare(&prepared_text, &self.device) {
            Ok(t) => t,
            Err(e) => return Box::new(std::iter::once(Err(e))),
        };

        let text_embeddings = match self.conditioner.forward(&tokens) {
            Ok(e) => e,
            Err(e) => return Box::new(std::iter::once(Err(e))),
        };

        // Initial text prompt
        if let Err(e) = self
            .flow_lm
            .transformer
            .forward(&text_embeddings, &mut state, 0)
        {
            return Box::new(std::iter::once(Err(anyhow::Error::from(e))));
        }

        // Removed redundant increment_steps("offset") - handled internally by RoPE/Attention with current_end_len

        let max_gen_len = (prepared_text.split_whitespace().count() + 2) * 13;
        let frames_after_eos = estimate_frames_after_eos(&text);

        let mut backbone_input = match self.flow_lm.bos_emb.clone().reshape((1, 1, self.ldim)) {
            Ok(t) => t,
            Err(e) => return Box::new(std::iter::once(Err(anyhow::Error::from(e)))),
        };

        let mut eos_step: Option<usize> = None;
        let mut finished = false;

        // We need to move 'self' (reference) and owned data into the closure
        // But 'self' is in `generate_stream` lifetime?
        // We clone needed cheap things or use references.
        // `flow_lm`, `mimi` are part of self.
        // The closure will borrow `self`.

        // To make the iterator valid 'static or bound to self, we use move.
        // But we need access to self inside.
        // We can clone `self` if cheap? No, TTSModel is large (holds models).
        // But TTSModel derives Clone! And models are wrappers around Arcs (Candle tensors/vars).
        // So cloning TTSModel is CHEAP (shallow copy of Arc pointers).
        let model = self.clone();

        // Pre-compute time embeddings for the entire segment to avoid re-computing every frame
        // Now returns a single batched Tensor [num_steps, channels]
        let time_embeddings = match model.flow_lm.flow_net.compute_time_embeddings(
            model.lsd_decode_steps,
            &model.device,
            DType::F32,
        ) {
            Ok(te) => te,
            Err(e) => return Box::new(std::iter::once(Err(anyhow::Error::from(e)))),
        };

        let empty_text_embeddings =
            Tensor::zeros((1, 0, model.dim), DType::F32, &model.device).unwrap();

        Box::new((0..max_gen_len).map_while(move |step| {
            if finished {
                return None;
            }

            // Text embeddings are already processed into state during initialization (line 752-757),
            // so we always pass empty text embeddings during autoregressive generation.
            // Passing text_embeddings again would cause duplicate/repeated speech.
            let text_tokens_to_pass = &empty_text_embeddings;

            let (next_latent, is_eos) = match tracing::info_span!("flow_lm.forward", step = step)
                .in_scope(|| {
                    model.flow_lm.forward(
                        &backbone_input,
                        text_tokens_to_pass,
                        &mut state,
                        &time_embeddings,
                        model.temp,
                        model.eos_threshold,
                        step,
                    )
                }) {
                Ok(res) => res,
                Err(e) => return Some(Err(anyhow::anyhow!(e))),
            };

            let audio_frame = match (|| -> Result<Tensor> {
                let next_latent_denorm = next_latent
                    .broadcast_mul(&model.flow_lm.emb_std)?
                    .broadcast_add(&model.flow_lm.emb_mean)?;

                let mimi_input = next_latent_denorm.unsqueeze(1)?.transpose(1, 2)?;
                let quantized = model.mimi.quantize(&mimi_input)?;
                let audio = tracing::info_span!("mimi.decode_from_latent", step = step)
                    .in_scope(|| {
                        model
                            .mimi
                            .decode_from_latent(&quantized, &mut mimi_state, step)
                    })
                    .map_err(|e| anyhow::anyhow!(e))?;

                // Removed redundant increment_steps("offset") for mimi

                Ok(audio)
            })() {
                Ok(frame) => frame,
                Err(e) => return Some(Err(e)),
            };

            if is_eos && eos_step.is_none() {
                eos_step = Some(step);
            }

            if let Some(e_step) = eos_step
                && step >= e_step + frames_after_eos
            {
                finished = true;
            }

            backbone_input = next_latent.unsqueeze(1).unwrap();

            // Removed redundant increment_steps("offset") for FlowLM - handled by attention state

            Some(Ok(audio_frame))
        }))
    }

    /// Generate audio stream from long text by segmenting it
    pub fn generate_stream_long<'a>(
        &'a self,
        text: &str,
        voice_state: &'a ModelState,
    ) -> impl Iterator<Item = Result<Tensor>> + 'a {
        use crate::pause::{parse_text_with_pauses, silence_samples};

        let parsed = parse_text_with_pauses(text);
        let mut segments = Vec::new();

        // Interleave text chunks and pauses
        let mut last_pos = 0;
        for pause in &parsed.pauses {
            if pause.position > last_pos {
                let text_seg = &parsed.clean_text[last_pos..pause.position];
                if !text_seg.trim().is_empty() {
                    segments.push(Segment::Text(text_seg.to_string()));
                }
            }
            segments.push(Segment::Pause(pause.duration_ms));

            // Explicit pauses were replaced by a single space in clean_text
            // Natural pauses (commas, ellipses) are still in clean_text
            if pause.original.starts_with("[pause:") {
                last_pos = pause.position + 1;
            } else {
                last_pos = pause.position + pause.original.len();
            }
        }
        if last_pos < parsed.clean_text.len() {
            let text_seg = &parsed.clean_text[last_pos..];
            if !text_seg.trim().is_empty() {
                segments.push(Segment::Text(text_seg.to_string()));
            }
        }

        let model = self;
        segments.into_iter().flat_map(move |seg| match seg {
            Segment::Text(s) => {
                let iter = model.generate_stream(&s, voice_state);
                Box::new(iter) as Box<dyn Iterator<Item = Result<Tensor>>>
            }
            Segment::Pause(ms) => {
                let n_samples = silence_samples(ms, model.sample_rate as u32);
                let silence_res = Tensor::zeros(
                    (1, model.mimi.channels, n_samples),
                    DType::F32,
                    &model.device,
                );
                Box::new(std::iter::once(silence_res.map_err(anyhow::Error::from)))
                    as Box<dyn Iterator<Item = Result<Tensor>>>
            }
        })
    }
    pub fn estimate_generation_steps(&self, text: &str) -> usize {
        let prepared = prepare_text_prompt(text);
        (prepared.split_whitespace().count() + 2) * 13
    }
}

/// Internal segment type for interleaving text and pauses
enum Segment {
    Text(String),
    Pause(u32),
}

/// Find the config file path for a variant
fn find_config_path(variant: &str) -> Result<std::path::PathBuf> {
    let filename = format!("{}.yaml", variant);

    // 1. Try relative to Rust crate (crates/pocket-tts/config)
    let crate_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let crate_config = crate_path.join("config").join(&filename);
    if crate_config.exists() {
        return Ok(crate_config);
    }

    // 2. Try relative to workspace root (for tests/cli)
    // Go up 2 levels if in crates/pocket-tts or crates/pocket-tts-cli
    let mut current = crate_path.as_path();
    for _ in 0..3 {
        let python_config = current
            .join("python-reference")
            .join("pocket_tts")
            .join("config")
            .join(&filename);
        if python_config.exists() {
            return Ok(python_config);
        }

        // Also try new crates structure if running from cli
        let crates_config = current
            .join("crates")
            .join("pocket-tts")
            .join("config")
            .join(&filename);
        if crates_config.exists() {
            return Ok(crates_config);
        }

        if let Some(parent) = current.parent() {
            current = parent;
        } else {
            break;
        }
    }

    // 3. Try current directory
    let local_path = std::path::PathBuf::from("config").join(&filename);
    if local_path.exists() {
        return Ok(local_path);
    }

    anyhow::bail!(
        "Config file {} not found. Checked crate-relative, workspace, and current directory.",
        filename
    )
}

/// Prepare text for generation, stripping pause markers for TTS processing
fn prepare_text_prompt(text: &str) -> String {
    // First strip any explicit pause markers
    let text = crate::pause::strip_pause_markers(text);

    let mut text = text.trim().to_string();
    if text.is_empty() {
        return ".".to_string(); // Or handle error
    }

    text = text.replace(['\n', '\r'], " ").replace("  ", " ");

    let word_count = text.split_whitespace().count();

    // Ensure first character is uppercase
    if let Some(first) = text.chars().next()
        && !first.is_uppercase()
    {
        text = format!("{}{}", first.to_uppercase(), &text[first.len_utf8()..]);
    }

    // Ensure ends with punctuation
    if let Some(last) = text.chars().last()
        && last.is_alphanumeric()
    {
        text.push('.');
    }

    // Python logic: prepend spaces if too short
    if word_count < 5 {
        text = format!("{}{}", " ".repeat(8), text);
    }

    text
}

/// Estimate frames after EOS based on text length
pub fn estimate_frames_after_eos(text: &str) -> usize {
    let word_count = text.split_whitespace().count();
    if word_count <= 4 {
        3 + 2 // prepare_text_prompt guess + 2
    } else {
        1 + 2 // prepare_text_prompt guess + 2
    }
}

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

    #[test]
    fn test_prepare_text_prompt() {
        // Short texts (<5 words) get 8 spaces prepended
        assert_eq!(prepare_text_prompt("hello world"), "        Hello world.");
        assert_eq!(prepare_text_prompt("Hello world."), "        Hello world.");
        assert_eq!(prepare_text_prompt("  hello  "), "        Hello.");
        // Long texts don't get spaces
        assert_eq!(
            prepare_text_prompt("one two three four five"),
            "One two three four five."
        );
    }

    #[test]
    fn test_find_config_path() {
        // This MUST pass now that we've moved the config into the crate
        let result = find_config_path("b6369a24");
        assert!(result.is_ok(), "Config file should be found");
        let path = result.unwrap();
        assert!(path.exists(), "Config file path should exist");
    }

    #[test]
    fn test_prepare_text_prompt_strips_pause_markers() {
        // Pause markers should be stripped from text
        let result = prepare_text_prompt("Hello [pause:500ms] world");
        // The pause marker should be gone, replaced with space
        assert!(!result.contains("[pause:"));
        assert!(result.contains("Hello"));
        assert!(result.contains("world"));
    }

    #[test]
    fn test_prepare_text_prompt_handles_multiple_pauses() {
        let result = prepare_text_prompt("One [pause:100ms] two [pause:1s] three");
        assert!(!result.contains("[pause:"));
        assert!(result.contains("One"));
        assert!(result.contains("two"));
        assert!(result.contains("three"));
    }

    #[test]
    fn test_estimate_frames_after_eos() {
        // Short text (<= 4 words)
        assert_eq!(estimate_frames_after_eos("Hello world"), 5);
        // Longer text (> 4 words)
        assert_eq!(estimate_frames_after_eos("One two three four five"), 3);
    }

    #[test]
    #[cfg(feature = "quantized")]
    fn test_load_quantized_requires_feature() {
        // This test only runs with --features quantized
        // It verifies the load_quantized method exists and compiles
        // Actual model loading requires HF_TOKEN
    }
}