agentai-audio 0.7.4

Text-to-speech and voice cloning for AgentAI agents.
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
//! The calls of [`SpeechGenerator`]: builders awaited with `.await`.

use crate::generator::SpeechGenerator;
use crate::provider::{AudioError, AudioFormat, SpeechResponse, VoiceId, VoicePreview};
use std::future::{Future, IntoFuture};
use std::pin::Pin;

/// A request to speak a text, made by [`SpeechGenerator::generate`] and sent by awaiting it.
///
/// Unset options are not sent: the provider uses its own defaults.
#[derive(Debug, Clone)]
#[must_use = "a speech request does nothing until it is awaited"]
pub struct SpeechRequest<'a> {
    generator: &'a SpeechGenerator,
    text: String,
    voice: Option<VoiceId>,
    model: Option<String>,
    format: Option<AudioFormat>,
    speed: Option<f64>,
    language: Option<String>,
    instructions: Option<String>,
    timestamps: bool,
    name: Option<String>,
}

impl<'a> SpeechRequest<'a> {
    pub(crate) fn new(generator: &'a SpeechGenerator, text: String) -> Self {
        Self {
            generator,
            text,
            voice: None,
            model: None,
            format: None,
            speed: None,
            language: None,
            instructions: None,
            timestamps: false,
            name: None,
        }
    }

    /// Sets the voice. Without one the API chooses, or fails with
    /// [`AudioError::MissingVoice`] when it needs one (OpenAI, ElevenLabs).
    pub fn with_voice(mut self, voice: impl Into<VoiceId>) -> Self {
        self.voice = Some(voice.into());
        self
    }

    /// Sets the model for this call, instead of the speech model of the provider.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Sets the output format.
    pub fn with_format(mut self, format: AudioFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Sets the speaking speed.
    pub fn with_speed(mut self, speed: f64) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Sets the language of the text.
    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Sets the style instructions. Providers without an equivalent ignore them.
    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// Asks for the time of every word in [`SpeechResponse::timestamps`]. A provider that
    /// cannot give them returns [`AudioError::Unsupported`].
    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
        self.timestamps = timestamps;
        self
    }

    /// Sets the file name of the audio, set as its `Media::name`. Never sent to the provider.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The text to speak.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// The voice, if set.
    pub fn voice(&self) -> Option<&str> {
        self.voice.as_deref()
    }

    /// The model of this call, if set.
    pub fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    /// The output format, if set.
    pub fn format(&self) -> Option<AudioFormat> {
        self.format
    }

    /// The speaking speed, if set.
    pub fn speed(&self) -> Option<f64> {
        self.speed
    }

    /// The language, if set.
    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    /// The style instructions, if set.
    pub fn instructions(&self) -> Option<&str> {
        self.instructions.as_deref()
    }

    /// Whether the time of every word is asked for.
    pub fn timestamps(&self) -> bool {
        self.timestamps
    }

    pub(crate) fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Fails for a request with timestamps, for providers that cannot give them.
    pub(crate) fn without_timestamps(&self) -> Result<(), AudioError> {
        without_timestamps(self.timestamps)
    }
}

impl<'a> IntoFuture for SpeechRequest<'a> {
    type Output = Result<SpeechResponse, AudioError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.generator.speak(&self).await })
    }
}

/// One turn of a dialogue: who speaks and what.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DialogueTurn {
    /// The voice that speaks the turn.
    pub voice: VoiceId,
    /// What the voice says.
    pub text: String,
}

impl DialogueTurn {
    /// Creates a turn of `voice` saying `text`.
    pub fn new(voice: impl Into<VoiceId>, text: impl Into<String>) -> Self {
        Self {
            voice: voice.into(),
            text: text.into(),
        }
    }
}

/// A request to speak a dialogue of several voices, made by
/// [`SpeechGenerator::generate_dialogue`] and sent by awaiting it.
#[derive(Debug, Clone)]
#[must_use = "a dialogue request does nothing until it is awaited"]
pub struct DialogueRequest<'a> {
    generator: &'a SpeechGenerator,
    voices: Vec<VoiceId>,
    turns: Vec<(usize, String)>,
    model: Option<String>,
    format: Option<AudioFormat>,
    speed: Option<f64>,
    language: Option<String>,
    timestamps: bool,
    name: Option<String>,
}

impl<'a> DialogueRequest<'a> {
    pub(crate) fn new(
        generator: &'a SpeechGenerator,
        dialogue: impl IntoIterator<Item = DialogueTurn>,
    ) -> Self {
        let mut voices: Vec<VoiceId> = Vec::new();
        let turns = dialogue
            .into_iter()
            .map(|turn| {
                let speaker = match voices.iter().position(|voice| *voice == turn.voice) {
                    Some(speaker) => speaker,
                    None => {
                        voices.push(turn.voice);
                        voices.len() - 1
                    }
                };
                (speaker, turn.text)
            })
            .collect();
        Self {
            generator,
            voices,
            turns,
            model: None,
            format: None,
            speed: None,
            language: None,
            timestamps: false,
            name: None,
        }
    }

    /// Sets the model for this call, instead of the dialogue model of the provider.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Sets the output format.
    pub fn with_format(mut self, format: AudioFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Sets the speaking speed of every turn. A provider that cannot set it for a dialogue
    /// returns [`AudioError::Unsupported`].
    pub fn with_speed(mut self, speed: f64) -> Self {
        self.speed = Some(speed);
        self
    }

    /// Sets the language of the text.
    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Asks for the time of every word in [`SpeechResponse::timestamps`]. A provider that
    /// cannot give them returns [`AudioError::Unsupported`].
    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
        self.timestamps = timestamps;
        self
    }

    /// Sets the file name of the audio, set as its `Media::name`. Never sent to the provider.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The distinct voices, in the order they first speak. A voice's index is its speaker
    /// number in [`turns`](Self::turns).
    pub fn voices(&self) -> &[VoiceId] {
        &self.voices
    }

    /// Every turn as the index of its voice in [`voices`](Self::voices) and its text.
    pub fn turns(&self) -> &[(usize, String)] {
        &self.turns
    }

    /// The speaking speed, if set.
    pub fn speed(&self) -> Option<f64> {
        self.speed
    }

    /// The model of this call, if set.
    pub fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }

    /// The output format, if set.
    pub fn format(&self) -> Option<AudioFormat> {
        self.format
    }

    /// The language, if set.
    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    /// Whether the time of every word is asked for.
    pub fn timestamps(&self) -> bool {
        self.timestamps
    }

    pub(crate) fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Fails for a request with timestamps, for providers that cannot give them.
    pub(crate) fn without_timestamps(&self) -> Result<(), AudioError> {
        without_timestamps(self.timestamps)
    }
}

impl<'a> IntoFuture for DialogueRequest<'a> {
    type Output = Result<SpeechResponse, AudioError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.generator.speak_dialogue(&self).await })
    }
}

/// A request to design voices from a description, made by [`SpeechGenerator::design_voice`]
/// and sent by awaiting it. It returns previews to listen to.
#[derive(Debug, Clone)]
#[must_use = "a voice design request does nothing until it is awaited"]
pub struct DesignVoiceRequest<'a> {
    generator: &'a SpeechGenerator,
    description: String,
    text: Option<String>,
    language: Option<String>,
    count: usize,
    model: Option<String>,
}

impl<'a> DesignVoiceRequest<'a> {
    pub(crate) fn new(generator: &'a SpeechGenerator, description: String) -> Self {
        Self {
            generator,
            description,
            text: None,
            language: None,
            count: 1,
            model: None,
        }
    }

    /// Sets the text the previews say, for providers that let you choose.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Sets the language of the voice (a BCP-47 code such as `pl`). Fish Audio and oMLX send it;
    /// ElevenLabs has no such setting and ignores it.
    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Sets how many previews to ask for (1 by default). A provider may return its own number.
    pub fn with_count(mut self, count: usize) -> Self {
        self.count = count;
        self
    }

    /// Sets the model for this call, instead of the design model of the provider. It does not
    /// turn on voice design for a provider without a design model.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// The description of the voice.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// The text of the previews, if set.
    pub fn text(&self) -> Option<&str> {
        self.text.as_deref()
    }

    /// The language of the voice, if set.
    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    /// How many previews to ask for.
    pub fn count(&self) -> usize {
        self.count
    }

    /// The model of this call, if set.
    pub fn model(&self) -> Option<&str> {
        self.model.as_deref()
    }
}

impl<'a> IntoFuture for DesignVoiceRequest<'a> {
    type Output = Result<Vec<VoicePreview>, AudioError>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.generator.design(&self).await })
    }
}

fn without_timestamps(timestamps: bool) -> Result<(), AudioError> {
    if timestamps {
        Err(AudioError::Unsupported("word timestamps"))
    } else {
        Ok(())
    }
}

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

    struct NoProvider;

    #[async_trait]
    impl SpeechProvider for NoProvider {
        async fn generate(&self, _: &SpeechRequest<'_>) -> Result<SpeechResponse, AudioError> {
            unreachable!()
        }
    }

    #[test]
    fn dialogue_voices_are_distinct_in_order_of_first_turn() {
        let generator = SpeechGenerator::from_provider(NoProvider);
        let request = generator.generate_dialogue([
            DialogueTurn::new("b", "1"),
            DialogueTurn::new("a", "2"),
            DialogueTurn::new("b", "3"),
        ]);
        assert_eq!(request.voices(), ["b", "a"]);
        assert_eq!(
            request.turns(),
            [
                (0, "1".to_string()),
                (1, "2".to_string()),
                (0, "3".to_string())
            ]
        );
    }
}