elevenlabs_rs 0.3.2

A lib crate for ElevenLabs
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
#![allow(dead_code)]
//! The voice endpoints
//!
//! See the [ElevenLabs docs](https://elevenlabs.io/docs/api-reference/get-voices) for more information.
//!
use super::*;
use crate::error::Error;
use std::collections::HashMap;
use std::path::Path;

const EDIT_VOICE_PATH: &str = "/edit";
const EDIT_VOICE_SETTINGS_PATH: &str = "/settings/edit";
const DEFAULT_SETTINGS_PATH: &str = "/v1/voices/settings/default";
const VOICE_SETTINGS_PATH: &str = "/settings";
const WITH_SETTINGS_QUERY: &str = "with_settings=true";

/// Get all voices endpoint
///
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///    let c = ElevenLabsClient::default()?;
///    let voices = c.hit(GetVoices).await?;
///    println!("{:#?}", voices);
///    Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct GetVoices;

impl Endpoint for GetVoices {
    type ResponseBody = VoicesResponseBody;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(VOICES_PATH);
        url
    }
}

/// Hits [GetVoices] endpoint then finds the voices by name given
#[derive(Clone, Debug)]
pub struct GetVoiceIDByName(String);

impl GetVoiceIDByName {
    pub fn new(name: &str) -> Self {
        GetVoiceIDByName(name.to_string())
    }
}

impl Endpoint for GetVoiceIDByName {
    type ResponseBody = String;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        let resp = resp.json::<VoicesResponseBody>().await?;
        let voice = resp.voices.iter().find(|v| v.name == self.0);
        let voice_id = voice
            .ok_or(Box::new(Error::VoiceNotFound))?
            .voice_id
            .clone();
        Ok(voice_id)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(VOICES_PATH);
        url
    }
}

/// Get the default voice settings endpoint
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///    let c = ElevenLabsClient::default()?;
///    let default_settings = c.hit(GetDefaultSettings).await?;
///    println!("{:#?}", default_settings);
///    Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct GetDefaultSettings;

impl Endpoint for GetDefaultSettings {
    type ResponseBody = VoiceSettings;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(DEFAULT_SETTINGS_PATH);
        url
    }
}

/// Get the voice settings endpoint
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///   let c = ElevenLabsClient::default()?;
///   // Or for a premade voice: GetVoiceSettings::new(PreMadeVoiceID::Adam)
///   let voice_settings = c.hit(GetVoiceSettings::new("some_voice_id")).await?;
///   println!("{:#?}", voice_settings);
///   Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct GetVoiceSettings(VoiceID);

impl GetVoiceSettings {
    pub fn new<T: Into<String>>(voice_id: T) -> Self {
        GetVoiceSettings(VoiceID::from(voice_id.into()))
    }
}

impl Endpoint for GetVoiceSettings {
    type ResponseBody = VoiceSettings;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!(
            "{}/{}{}",
            VOICES_PATH, self.0 .0, VOICE_SETTINGS_PATH
        ));
        url
    }
}

/// Get a voice endpoint
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///    let c = ElevenLabsClient::default()?;
///    // Or for IVC's & PVC's: GetVoice::new("some_voice_id")
///    let voice = c.hit(GetVoice::new(PreMadeVoiceID::Brian)).await?;
///    println!("{:#?}", voice);
///   Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct GetVoice(VoiceID);

impl GetVoice {
    pub fn new<T: Into<String>>(voice_id: T) -> Self {
        GetVoice(VoiceID::from(voice_id.into()))
    }
}


impl Endpoint for GetVoice {
    type ResponseBody = VoiceResponseBody;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!("{}/{}", VOICES_PATH, self.0 .0));
        url
    }
}

/// Hits [GetVoice] endpoint with the query `with_settings=true`
#[derive(Clone, Debug)]
pub struct GetVoiceWithSettings(VoiceID);

impl GetVoiceWithSettings {
    pub fn new<T: Into<String>>(voice_id: T) -> Self {
        GetVoiceWithSettings(VoiceID::from(voice_id.into()))
    }
}

impl Endpoint for GetVoiceWithSettings {
    type ResponseBody = VoiceResponseBody;

    fn method(&self) -> Method {
        Method::GET
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!("{}/{}", VOICES_PATH, self.0 .0));
        url.set_query(Some(WITH_SETTINGS_QUERY));
        url
    }
}

/// Delete a voice endpoint
#[derive(Clone, Debug)]
pub struct DeleteVoice(VoiceID);

impl DeleteVoice {
    pub fn new<T: Into<String>>(voice_id: T) -> Self {
        DeleteVoice(VoiceID::from(voice_id.into()))
    }
}

impl Endpoint for DeleteVoice {
    type ResponseBody = StatusResponseBody;

    fn method(&self) -> Method {
        Method::DELETE
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!("{}/{}", VOICES_PATH, self.0 .0));
        url
    }
}

/// Edit voice settings endpoint
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///   let c = ElevenLabsClient::default()?;
///   let body = EditVoiceSettingsBody::new(0.5, 0.7)
///         .with_style(0.5)
///         .with_use_speaker_boost(true);
///   let endpoint = EditVoiceSettings::new("some_voice_id", body);
///   let resp = c.hit(endpoint).await?;
///   println!("{:#?}", resp);
///   Ok(())
/// }
#[derive(Clone, Debug)]
pub struct EditVoiceSettings {
    voice_id: VoiceID,
    body: EditVoiceSettingsBody,
}

impl EditVoiceSettings {
    pub fn new<T: Into<String>>(voice_id: T, body: EditVoiceSettingsBody) -> Self {
        EditVoiceSettings {
            voice_id: VoiceID::from(voice_id.into()),
            body,
        }
    }
}

impl Endpoint for EditVoiceSettings {
    type ResponseBody = StatusResponseBody;

    fn method(&self) -> Method {
        Method::POST
    }
    fn request_body(&self) -> Result<RequestBody> {
        Ok(RequestBody::Json(serde_json::to_value(&self.body)?))
    }
    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!(
            "{}/{}{}",
            VOICES_PATH, self.voice_id.0, EDIT_VOICE_SETTINGS_PATH
        ));
        url
    }
}

/// Edit voice settings body
#[derive(Clone, Debug, Serialize)]
pub struct EditVoiceSettingsBody {
    similarity_boost: f32,
    stability: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    style: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    use_speaker_boost: Option<bool>,
}

impl EditVoiceSettingsBody {
    pub fn new(similarity_boost: f32, stability: f32) -> Self {
        Self {
            similarity_boost,
            stability,
            style: None,
            use_speaker_boost: None,
        }
    }
    pub fn with_style(mut self, style: f32) -> Self {
        self.style = Some(style);
        self
    }
    pub fn with_use_speaker_boost(mut self, use_speaker_boost: bool) -> Self {
        self.use_speaker_boost = Some(use_speaker_boost);
        self
    }
}

/// Add a voice endpoint
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let c = ElevenLabsClient::default()?;
///     let samples = vec!["some_file_path.mp3".to_string(), "another.mp3".into(),];
///     let labels = vec![("age".to_string(), "old".into()), ("gender".into(), "male".into())];
///     let body = AddVoiceBody::new("John Doe", samples)
///         .with_description("A public intellectual")
///         .with_labels(labels);
///     let endpoint = AddVoice::new(body);
///     let resp = c.hit(endpoint).await?;
///     println!("{:#?}", resp);
///     Ok(())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct AddVoice(AddVoiceBody);

impl AddVoice {
    pub fn new(body: AddVoiceBody) -> Self {
        AddVoice(body)
    }
}

impl Endpoint for AddVoice {
    type ResponseBody = AddVoiceResponse;

    fn method(&self) -> Method {
        Method::POST
    }

    fn request_body(&self) -> Result<RequestBody> {
        Ok(RequestBody::Multipart(to_multipart(
            self.0.name.clone(),
            Some(self.0.files.clone()),
            self.0.description.clone(),
            self.0.labels.clone(),
        )?))
    }

    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!("{}{}", VOICES_PATH, ADD_VOICE_PATH));
        url
    }
}

/// Add voice body
#[derive(Clone, Debug)]
pub struct AddVoiceBody {
    name: String,
    files: Vec<String>,
    description: Option<String>,
    labels: Option<Vec<(String, String)>>,
}

impl AddVoiceBody {
    pub fn new(name: &str, files: Vec<String>) -> Self {
        Self {
            name: name.to_string(),
            files,
            description: None,
            labels: None,
        }
    }
    pub fn with_description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }
    pub fn with_labels(mut self, labels: Vec<(String, String)>) -> Self {
        self.labels = Some(labels);
        self
    }
}

/// Add voice response
#[derive(Clone, Debug, Deserialize)]
pub struct AddVoiceResponse {
    voice_id: String,
}

impl AddVoiceResponse {
    pub fn get_voice_id(&self) -> &String {
        &self.voice_id
    }
}

/// Edit a voice endpoint
#[derive(Clone, Debug)]
pub struct EditVoice {
    voice_id: VoiceID,
    body: EditVoiceBody,
}

impl EditVoice {
    pub fn new<T: Into<String>>(voice_id: T, body: EditVoiceBody) -> Self {
        EditVoice {
            voice_id: VoiceID::from(voice_id.into()),
            body,
        }
    }
}

impl Endpoint for EditVoice {
    type ResponseBody = StatusResponseBody;

    fn method(&self) -> Method {
        Method::POST
    }
    fn request_body(&self) -> Result<RequestBody> {
        Ok(RequestBody::Multipart(to_multipart(
            self.body.name.clone(),
            self.body.files.clone(),
            self.body.description.clone(),
            self.body.labels.clone(),
        )?))
    }

    async fn response_body(self, resp: Response) -> Result<Self::ResponseBody> {
        Ok(resp.json().await?)
    }
    fn url(&self) -> Url {
        let mut url = BASE_URL.parse::<Url>().unwrap();
        url.set_path(&format!(
            "{}/{}{}",
            VOICES_PATH, self.voice_id.0, EDIT_VOICE_PATH
        ));
        url
    }
}

/// Edit voice body
#[derive(Clone, Debug)]
pub struct EditVoiceBody {
    name: String,
    files: Option<Vec<String>>,
    description: Option<String>,
    labels: Option<Vec<(String, String)>>,
}

impl EditVoiceBody {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            files: None,
            description: None,
            labels: None,
        }
    }
    pub fn with_files(mut self, files: Vec<String>) -> Self {
        self.files = Some(files);
        self
    }
    pub fn with_description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }
    pub fn with_labels(mut self, labels: Vec<(String, String)>) -> Self {
        self.labels = Some(labels);
        self
    }
}

/// Get all voices response body
#[derive(Clone, Debug, Deserialize)]
pub struct VoicesResponseBody {
    voices: Vec<VoiceResponseBody>,
}

impl VoicesResponseBody {
    pub fn get_voices(&self) -> &Vec<VoiceResponseBody> {
        &self.voices
    }
}

// TODO: update this
/// Voice response body
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct VoiceResponseBody {
    voice_id: String,
    name: String,
    samples: Option<Vec<VoiceSample>>,
    category: Option<String>,
    labels: Option<HashMap<String, String>>,
    description: Option<String>,
    preview_url: Option<String>,
    settings: Option<VoiceSettings>,
}

/// Voice sample
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct VoiceSample {
    sample_id: String,
    file_name: String,
    mime_type: String,
    size_bytes: Option<u64>,
    hash: String,
}

impl VoiceSample {
    pub fn get_sample_id(&self) -> &String {
        &self.sample_id
    }
    pub fn get_file_name(&self) -> &String {
        &self.file_name
    }
    pub fn get_mime_type(&self) -> &String {
        &self.mime_type
    }
    pub fn get_size_bytes(&self) -> Option<u64> {
        self.size_bytes
    }
    pub fn get_hash(&self) -> &String {
        &self.hash
    }
}

/// Voice settings
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct VoiceSettings {
    similarity_boost: f32,
    stability: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    style: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    use_speaker_boost: Option<bool>,
}

impl VoiceSettings {
    pub fn new(similarity_boost: f32, stability: f32) -> Self {
        VoiceSettings {
            similarity_boost,
            stability,
            style: None,
            use_speaker_boost: None,
        }
    }
    pub fn with_style(mut self, style: f32) -> Self {
        self.style = Some(style);
        self
    }
    pub fn with_use_speaker_boost(mut self, use_speaker_boost: bool) -> Self {
        self.use_speaker_boost = Some(use_speaker_boost);
        self
    }

    pub fn similarity_boost(&self) -> f32 {
        self.similarity_boost
    }

    pub fn stability(&self) -> f32 {
        self.stability
    }

    pub fn style(&self) -> Option<f32> {
        self.style
    }

    pub fn use_speaker_boost(&self) -> Option<bool> {
        self.use_speaker_boost
    }
}

impl Default for VoiceSettings {
    fn default() -> Self {
        VoiceSettings {
            similarity_boost: 0.75,
            stability: 0.5,
            style: Some(0.5),
            use_speaker_boost: Some(true),
        }
    }
}

impl VoiceResponseBody {
    pub fn get_voice_id(&self) -> &String {
        &self.voice_id
    }
    pub fn get_name(&self) -> &String {
        &self.name
    }
    pub fn get_samples(&self) -> Option<&Vec<VoiceSample>> {
        self.samples.as_ref()
    }
    pub fn get_category(&self) -> Option<&String> {
        self.category.as_ref()
    }
    pub fn get_labels(&self) -> Option<&HashMap<String, String>> {
        self.labels.as_ref()
    }
    pub fn get_description(&self) -> Option<&String> {
        self.description.as_ref()
    }
    pub fn get_preview_url(&self) -> Option<&String> {
        self.preview_url.as_ref()
    }
    pub fn get_settings(&self) -> Option<&VoiceSettings> {
        self.settings.as_ref()
    }
}

fn to_multipart<P: AsRef<Path>>(
    voice_name: String,
    file_paths: Option<Vec<P>>,
    description: Option<String>,
    labels: Option<Vec<(String, String)>>,
) -> Result<Form> {
    let mut form = Form::new();
    form = form.text("name", voice_name);

    if let Some(file_paths) = file_paths {
        for file_path in file_paths {
            let fp = file_path.as_ref();
            let audio_bytes = std::fs::read(fp)?;
            let mut part = Part::bytes(audio_bytes);
            let file_path_str = fp.to_str().ok_or(Box::new(Error::PathNotValidUTF8))?;
            part = part.file_name(file_path_str.to_string());
            let mime_subtype = fp
                .extension()
                .ok_or(Box::new(Error::FileExtensionNotFound))?
                .to_str()
                .ok_or(Box::new(Error::FileExtensionNotValidUTF8))?;
            let mime = format!("audio/{}", mime_subtype);
            part = part.mime_str(&mime)?;
            form = form.part("files", part);
        }
        if let Some(description) = description {
            form = form.text("description", description)
        }
        if let Some(labels) = labels {
            let mut label_map = HashMap::new();
            for (k, v) in labels {
                label_map.insert(k, v);
            }
            form = form.text("labels", serde_json::to_string(&label_map)?)
        }
    }
    Ok(form)
}