voirs-sdk 0.1.0-rc.1

Unified SDK and public API for VoiRS speech synthesis
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
// Convenience methods for common synthesis patterns
//!
//! This module provides helper methods for common VoiRS usage patterns, making it easier
//! to perform frequent operations without boilerplate code.

use crate::{
    audio::AudioBuffer,
    error::Result,
    pipeline::VoirsPipeline,
    types::{AudioFormat, QualityLevel, SynthesisConfig},
    VoirsError,
};
use std::path::Path;

/// Quick-start synthesis methods
impl VoirsPipeline {
    /// Synthesize text and save directly to a WAV file
    ///
    /// This is a convenience method that combines synthesis and file saving in one call.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     pipeline.synthesize_to_wav("Hello, world!", "output.wav").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_to_wav(&self, text: &str, path: impl AsRef<Path>) -> Result<()> {
        let audio = self.synthesize(text).await?;
        audio.save_wav(path)?;
        Ok(())
    }

    /// Synthesize text and save to a file with specified format
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     pipeline.synthesize_to_file(
    ///         "Hello, world!",
    ///         "output.mp3",
    ///         AudioFormat::Mp3
    ///     ).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_to_file(
        &self,
        text: &str,
        path: impl AsRef<Path>,
        format: AudioFormat,
    ) -> Result<()> {
        let audio = self.synthesize(text).await?;

        match format {
            AudioFormat::Wav => audio.save_wav(path)?,
            AudioFormat::Mp3 | AudioFormat::Flac | AudioFormat::Ogg | AudioFormat::Opus => {
                return Err(VoirsError::UnsupportedFileFormat {
                    path: path.as_ref().to_path_buf(),
                    format: format!("{:?}", format),
                });
            }
        }

        Ok(())
    }

    /// Synthesize text with a specific quality level
    ///
    /// This is a convenience method for quick quality-adjusted synthesis.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let audio = pipeline.synthesize_with_quality(
    ///         "High quality speech",
    ///         QualityLevel::High
    ///     ).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_with_quality(
        &self,
        text: &str,
        quality: QualityLevel,
    ) -> Result<AudioBuffer> {
        let config = SynthesisConfig {
            quality,
            ..Default::default()
        };
        self.synthesize_with_config(text, &config).await
    }

    /// Synthesize text with custom speed (speaking rate)
    ///
    /// # Arguments
    ///
    /// * `text` - The text to synthesize
    /// * `speed` - Speaking rate multiplier (0.5 = half speed, 2.0 = double speed)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let fast = pipeline.synthesize_with_speed("Fast speech", 1.5).await?;
    ///     let slow = pipeline.synthesize_with_speed("Slow speech", 0.75).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_with_speed(&self, text: &str, speed: f32) -> Result<AudioBuffer> {
        let config = SynthesisConfig {
            speaking_rate: speed,
            ..Default::default()
        };
        self.synthesize_with_config(text, &config).await
    }

    /// Synthesize text with custom pitch
    ///
    /// # Arguments
    ///
    /// * `text` - The text to synthesize
    /// * `pitch` - Pitch shift in semitones (-12.0 to +12.0)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let higher = pipeline.synthesize_with_pitch("Higher pitch", 3.0).await?;
    ///     let lower = pipeline.synthesize_with_pitch("Lower pitch", -3.0).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_with_pitch(&self, text: &str, pitch: f32) -> Result<AudioBuffer> {
        let config = SynthesisConfig {
            pitch_shift: pitch,
            ..Default::default()
        };
        self.synthesize_with_config(text, &config).await
    }

    /// Synthesize text with both custom speed and pitch
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let audio = pipeline.synthesize_with_speed_and_pitch(
    ///         "Custom voice parameters",
    ///         1.2,  // 20% faster
    ///         2.0   // 2 semitones higher
    ///     ).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_with_speed_and_pitch(
        &self,
        text: &str,
        speed: f32,
        pitch: f32,
    ) -> Result<AudioBuffer> {
        let config = SynthesisConfig {
            speaking_rate: speed,
            pitch_shift: pitch,
            ..Default::default()
        };
        self.synthesize_with_config(text, &config).await
    }

    /// Synthesize multiple texts in batch
    ///
    /// This is a convenience method for synthesizing multiple texts sequentially.
    /// For parallel batch processing with advanced features, use `BatchProcessor`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let texts = vec![
    ///         "First sentence.",
    ///         "Second sentence.",
    ///         "Third sentence."
    ///     ];
    ///     let results = pipeline.synthesize_batch(texts).await?;
    ///     println!("Synthesized {} audio buffers", results.len());
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_batch<S: AsRef<str>>(&self, texts: Vec<S>) -> Result<Vec<AudioBuffer>> {
        let mut results = Vec::with_capacity(texts.len());
        for text in texts {
            let audio = self.synthesize(text.as_ref()).await?;
            results.push(audio);
        }
        Ok(results)
    }

    /// Concatenate multiple texts and synthesize as one
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipelineBuilder::new().build().await?;
    ///     let parts = vec![
    ///         "Hello,",
    ///         "this is a test.",
    ///         "Multiple parts combined."
    ///     ];
    ///     let audio = pipeline.synthesize_concatenated(parts, " ").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn synthesize_concatenated<S: AsRef<str>>(
        &self,
        texts: Vec<S>,
        separator: &str,
    ) -> Result<AudioBuffer> {
        let combined = texts
            .iter()
            .map(|s| s.as_ref())
            .collect::<Vec<_>>()
            .join(separator);
        self.synthesize(&combined).await
    }
}

/// Quick-start factory methods for VoirsPipeline
impl VoirsPipeline {
    /// Create a pipeline with default settings (quick start)
    ///
    /// This is the fastest way to get started with VoiRS.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipeline::default().await?;
    ///     let audio = pipeline.synthesize("Hello!").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn default() -> Result<Self> {
        Self::builder().build().await
    }

    /// Create a high-quality pipeline preset
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipeline::high_quality().await?;
    ///     let audio = pipeline.synthesize("High quality output").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn high_quality() -> Result<Self> {
        Self::builder()
            .with_quality(QualityLevel::High)
            .build()
            .await
    }

    /// Create a fast synthesis pipeline preset
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipeline::fast().await?;
    ///     let audio = pipeline.synthesize("Fast synthesis").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn fast() -> Result<Self> {
        use crate::builder::VoirsPipelineBuilder;
        VoirsPipelineBuilder::new()
            .with_quality(QualityLevel::Low)
            .with_preset(crate::builder::PresetProfile::FastSynthesis)
            .build()
            .await
    }

    /// Create a low-memory pipeline preset
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use voirs_sdk::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let pipeline = VoirsPipeline::low_memory().await?;
    ///     let audio = pipeline.synthesize("Memory efficient").await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn low_memory() -> Result<Self> {
        use crate::builder::VoirsPipelineBuilder;
        VoirsPipelineBuilder::new()
            .with_preset(crate::builder::PresetProfile::LowMemory)
            .build()
            .await
    }
}

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

    #[tokio::test]
    async fn test_synthesize_to_wav() {
        use std::env::temp_dir;

        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let temp_path = temp_dir().join("test_output.wav");
        pipeline
            .synthesize_to_wav("Test synthesis", &temp_path)
            .await
            .unwrap();

        assert!(temp_path.exists());
        std::fs::remove_file(temp_path).ok();
    }

    #[tokio::test]
    async fn test_synthesize_with_quality() {
        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let audio = pipeline
            .synthesize_with_quality("High quality test", QualityLevel::High)
            .await
            .unwrap();

        assert!(!audio.samples().is_empty());
    }

    #[tokio::test]
    async fn test_synthesize_with_speed() {
        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let fast = pipeline.synthesize_with_speed("Fast", 1.5).await.unwrap();
        let slow = pipeline.synthesize_with_speed("Slow", 0.75).await.unwrap();

        assert!(!fast.samples().is_empty());
        assert!(!slow.samples().is_empty());
    }

    #[tokio::test]
    async fn test_synthesize_with_pitch() {
        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let higher = pipeline.synthesize_with_pitch("Higher", 3.0).await.unwrap();
        let lower = pipeline.synthesize_with_pitch("Lower", -3.0).await.unwrap();

        assert!(!higher.samples().is_empty());
        assert!(!lower.samples().is_empty());
    }

    #[tokio::test]
    async fn test_synthesize_batch() {
        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let texts = vec!["First", "Second", "Third"];
        let results = pipeline.synthesize_batch(texts).await.unwrap();

        assert_eq!(results.len(), 3);
        for audio in results {
            assert!(!audio.samples().is_empty());
        }
    }

    #[tokio::test]
    async fn test_synthesize_concatenated() {
        let pipeline = VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await
            .unwrap();

        let parts = vec!["Part one.", "Part two.", "Part three."];
        let audio = pipeline.synthesize_concatenated(parts, " ").await.unwrap();

        assert!(!audio.samples().is_empty());
    }

    #[tokio::test]
    async fn test_factory_methods() {
        // Note: Factory methods cannot enable test_mode automatically
        // so they may not work in test environments without proper models.
        // This is expected behavior - use builder with test_mode for testing.

        // Test that the factory methods at least construct the builders correctly
        // by using the builder pattern with test mode

        // Test default equivalent
        let default = crate::prelude::VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await;
        assert!(default.is_ok());

        // Test high_quality equivalent
        let hq = crate::prelude::VoirsPipelineBuilder::new()
            .with_quality(QualityLevel::High)
            .with_test_mode(true)
            .build()
            .await;
        assert!(hq.is_ok());

        // Test fast equivalent
        let fast = crate::prelude::VoirsPipelineBuilder::new()
            .with_quality(QualityLevel::Low)
            .with_test_mode(true)
            .build()
            .await;
        assert!(fast.is_ok());

        // Test low_memory equivalent
        let lm = crate::prelude::VoirsPipelineBuilder::new()
            .with_test_mode(true)
            .build()
            .await;
        assert!(lm.is_ok());
    }
}