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
#![allow(dead_code)]
//! The voice library endpoints
//!
//! This module contains endpoints related to the voice library.
//! The voice library is a collection of shared voices that can be used by users.
//! Users can add shared voices to their collection of voices in VoiceLab.
//! The shared voices can be filtered by various criteria such as:
//!
//! - page size
//! - category
//! - gender
//! - age
//! - accent
//! - language
//! - search
//! - use cases
//! - descriptives
//! - featured
//! - rendered app enabled
//! - owner ID
//! - sort
//! - page
//!
//! # Example
//! ```no_run
//! use elevenlabs_rs::*;
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     let c = ElevenLabsClient::default()?;
//!
//!     let mut query = SharedVoicesQuery::default();
//!     query = query
//!         .with_page_size(1)
//!         .with_category(Category::HighQuality)
//!         .with_gender(Gender::Female)
//!         .with_age(Age::Young)
//!         .with_language("en")
//!         .with_accent("indian")
//!         .with_use_cases(vec!["social_media".to_string()]);
//!
//!     let resp = c.hit(GetSharedVoices::new(query)).await?;
//!
//!     if let Some(shared_voice) = resp.voices().first() {
//!         let public_user_id = shared_voice.public_owner_id();
//!         let voice_id = shared_voice.voice_id();
//!         let add_shared_voice = AddSharedVoice::new(public_user_id, voice_id, "Maya");
//!         let resp = c.hit(add_shared_voice).await?;
//!         println!("{:#?}", resp);
//!     } else {
//!         println!("no shared voices found with query")
//!     }
//!     Ok(())
//! }
//! ```
use super::*;
pub use crate::endpoints::voice_generation::Age;
const SHARED_VOICES_PATH: &str = "/v1/shared-voices";
const PAGE_SIZE_QUERY: &str = "page_size";
const CATEGORY_QUERY: &str = "category";
const GENDER_QUERY: &str = "gender";
const AGE_QUERY: &str = "age";
const ACCENT_QUERY: &str = "accent";
const LANGUAGE_QUERY: &str = "language";
const SEARCH_QUERY: &str = "search";
const USE_CASES_QUERY: &str = "use_cases";
const DESCRIPTIVES_QUERY: &str = "descriptives";
const FEATURED_QUERY: &str = "featured";
const RENDERED_APP_ENABLED_QUERY: &str = "rendered_app_enabled";
const OWNER_ID_QUERY: &str = "owner_id";
const SORT_QUERY: &str = "sort";
const PAGE_QUERY: &str = "page";

/// Get shared voices
///
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
/// use elevenlabs_rs::endpoints::voice_library::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let c = ElevenLabsClient::default()?;
///     let mut query = SharedVoicesQuery::default();
///     query = query
///         .with_page_size(1)
///         .with_category(Category::Professional)
///         .with_gender(Gender::Male)
///         .with_age(Age::MiddleAged)
///         .with_accent("irish")
///         .with_language("en")
///         .with_use_cases(vec!["narrative_story".to_string()])
///         .with_descriptives(vec!["confident".to_string()]);
///     let resp = c.hit(GetSharedVoices::new(query)).await?;
///     println!("{:#?}", resp);
///     Ok(())
/// }
/// ```
/// See [ElevenLabs API documentation](https://elevenlabs.io/docs/api-reference/query-library) for more information
#[derive(Clone, Debug)]
pub struct GetSharedVoices(SharedVoicesQuery);

impl GetSharedVoices {
    pub fn new(query: SharedVoicesQuery) -> Self {
        GetSharedVoices(query)
    }
}

impl Endpoint for GetSharedVoices {
    type ResponseBody = SharedVoicesResponse;

    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(SHARED_VOICES_PATH);
        url.set_query(Some(&self.0.to_string()));
        url
    }
}

/// Shared voices response
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SharedVoicesResponse {
    voices: Vec<SharedVoice>,
    has_more: bool,
    last_sort_id: Option<String>,
}

impl SharedVoicesResponse {
    pub fn voices(&self) -> &Vec<SharedVoice> {
        &self.voices
    }
    pub fn has_more(&self) -> bool {
        self.has_more
    }
    pub fn last_sort_id(&self) -> Option<&str> {
        self.last_sort_id.as_deref()
    }
}

/// Shared voice
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SharedVoice {
    public_owner_id: String,
    voice_id: String,
    date_unix: f32,
    name: String,
    accent: String,
    gender: String,
    age: String,
    descriptive: String,
    use_case: String,
    category: String,
    language: String,
    description: String,
    preview_url: String,
    usage_character_count_1y: f32,
    usage_character_count_7d: f32,
    play_api_usage_character_count_1y: f32,
    cloned_by_count: f32,
    rate: f32,
    free_users_allowed: bool,
    live_moderation_enabled: bool,
    featured: bool,
    notice_period: Option<f32>,
    instagram_username: Option<String>,
    twitter_username: Option<String>,
    youtube_username: Option<String>,
    tiktok_username: Option<String>,
}

impl SharedVoice {
    pub fn public_owner_id(&self) -> &str {
        &self.public_owner_id
    }
    pub fn voice_id(&self) -> &str {
        &self.voice_id
    }
    pub fn date_unix(&self) -> f32 {
        self.date_unix
    }
    pub fn name(&self) -> &str {
        &self.name
    }
    pub fn accent(&self) -> &str {
        &self.accent
    }
    pub fn language(&self) -> &str {
        &self.language
    }
    pub fn description(&self) -> &str {
        &self.description
    }
    pub fn preview_url(&self) -> &str {
        &self.preview_url
    }
    pub fn usage_character_count_1y(&self) -> f32 {
        self.usage_character_count_1y
    }
    pub fn usage_character_count_7d(&self) -> f32 {
        self.usage_character_count_7d
    }
    pub fn play_api_usage_character_count_1y(&self) -> f32 {
        self.play_api_usage_character_count_1y
    }
    pub fn cloned_by_count(&self) -> f32 {
        self.cloned_by_count
    }
    pub fn rate(&self) -> f32 {
        self.rate
    }
    pub fn free_users_allowed(&self) -> bool {
        self.free_users_allowed
    }
    pub fn live_moderation_enabled(&self) -> bool {
        self.live_moderation_enabled
    }
    pub fn featured(&self) -> bool {
        self.featured
    }
    pub fn notice_period(&self) -> Option<f32> {
        self.notice_period
    }
    pub fn instagram_username(&self) -> Option<&str> {
        self.instagram_username.as_deref()
    }
    pub fn twitter_username(&self) -> Option<&str> {
        self.twitter_username.as_deref()
    }
    pub fn youtube_username(&self) -> Option<&str> {
        self.youtube_username.as_deref()
    }
    pub fn tiktok_username(&self) -> Option<&str> {
        self.tiktok_username.as_deref()
    }
}

/// Shared voices query
///
/// See [ElevenLabs API documentation](https://elevenlabs.io/docs/api-reference/query-library) for more information
#[derive(Clone, Debug, Default)]
pub struct SharedVoicesQuery {
    pub page_size: Option<String>,
    pub category: Option<String>,
    pub gender: Option<String>,
    pub age: Option<String>,
    pub accent: Option<String>,
    pub language: Option<String>,
    pub search: Option<String>,
    pub use_cases: Option<String>,
    pub descriptives: Option<String>,
    pub featured: Option<String>,
    pub rendered_app_enabled: Option<String>,
    pub owner_id: Option<String>,
    pub sort: Option<String>,
    pub page: Option<String>,
}

impl SharedVoicesQuery {
    pub fn with_page_size(mut self, page_size: u16) -> Self {
        self.page_size = Some(format!("{}={}", PAGE_SIZE_QUERY, page_size));
        self
    }
    pub fn with_category(mut self, category: Category) -> Self {
        self.category = Some(format!("{}={}", CATEGORY_QUERY, category.as_str()));
        self
    }
    pub fn with_gender(mut self, gender: Gender) -> Self {
        self.gender = Some(format!("{}={}", GENDER_QUERY, gender.as_str()));
        self
    }
    pub fn with_age(mut self, age: Age) -> Self {
        self.age = Some(format!("{}={}", AGE_QUERY, age.as_str()));
        self
    }
    pub fn with_accent(mut self, accent: &str) -> Self {
        self.accent = Some(format!("{}={}", ACCENT_QUERY, accent));
        self
    }
    pub fn with_language(mut self, language: &str) -> Self {
        self.language = Some(format!("{}={}", LANGUAGE_QUERY, language));
        self
    }
    pub fn with_search(mut self, search: &str) -> Self {
        self.search = Some(format!("{}={}", SEARCH_QUERY, search));
        self
    }
    pub fn with_use_cases(mut self, use_cases: Vec<String>) -> Self {
        let use_cases_formatted = use_cases
            .iter()
            .map(|use_case| format!("{}={}", USE_CASES_QUERY, use_case))
            .collect::<Vec<String>>()
            .join("&");
        self.use_cases = Some(use_cases_formatted);
        self
    }
    pub fn with_descriptives(mut self, descriptives: Vec<String>) -> Self {
        let descriptives_formatted = descriptives
            .iter()
            .map(|descriptive| format!("{}={}", DESCRIPTIVES_QUERY, descriptive))
            .collect::<Vec<String>>()
            .join("&");
        self.descriptives = Some(descriptives_formatted);
        self
    }
    pub fn with_featured(mut self, featured: bool) -> Self {
        self.featured = Some(format!("{}={}", FEATURED_QUERY, featured));
        self
    }
    pub fn with_rendered_app_enabled(mut self, rendered_app_enabled: bool) -> Self {
        self.rendered_app_enabled = Some(format!(
            "{}={}",
            RENDERED_APP_ENABLED_QUERY, rendered_app_enabled
        ));
        self
    }
    pub fn with_owner_id(mut self, owner_id: &str) -> Self {
        self.owner_id = Some(format!("{}={}", OWNER_ID_QUERY, owner_id));
        self
    }
    pub fn with_sort(mut self, sort: &str) -> Self {
        self.sort = Some(format!("{}={}", SORT_QUERY, sort));
        self
    }
    pub fn with_page(mut self, page: u16) -> Self {
        self.page = Some(format!("{}={}", PAGE_QUERY, page));
        self
    }

    fn to_string(&self) -> String {
        let mut result = String::new();

        if let Some(value) = self.page_size.as_ref() {
            result.push_str(&value);
        }
        if let Some(value) = self.category.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.gender.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.age.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.accent.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.language.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.search.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.use_cases.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.descriptives.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.featured.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.rendered_app_enabled.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.owner_id.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.sort.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        if let Some(value) = self.page.as_ref() {
            if !result.is_empty() {
                result.push('&');
            }
            result.push_str(&value);
        }
        result
    }
}

#[derive(Clone, Debug)]
pub enum Gender {
    Female,
    Male,
    Neutral,
}

impl Gender {
    pub fn as_str(&self) -> &str {
        match self {
            Gender::Female => "female",
            Gender::Male => "male",
            Gender::Neutral => "neutral",
        }
    }
}

#[derive(Clone, Debug)]
pub enum Category {
    Generated,
    HighQuality,
    Professional,
}

impl Category {
    pub fn as_str(&self) -> &str {
        match self {
            Category::Generated => "generated",
            Category::HighQuality => "high_quality",
            Category::Professional => "professional",
        }
    }
}

/// Add a sharing voice to your collection of voices in VoiceLab.
///
/// # Example
/// ```no_run
/// use elevenlabs_rs::*;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     let c = ElevenLabsClient::default()?;
///     let public_user_id = "some_public_user_id";
///     let voice_id = "some_voice_id";
///     let name = "new_voice_name";
///     let endpoint = AddSharedVoice::new(public_user_id, voice_id, name);
///     let resp = c.hit(endpoint).await?;
///     println!("{:#?}", resp);
///     Ok(())
/// }
/// ```
/// See [ElevenLabs API documentation](https://elevenlabs.io/docs/api-reference/add-shared-voice) for more information
#[derive(Clone, Debug)]
pub struct AddSharedVoice {
    pub params: AddSharedVoiceParams,
    pub body: AddSharedVoiceBody,
}

impl AddSharedVoice {
    pub fn new(public_user_id: &str, voice_id: &str, new_name: &str) -> Self {
        let params = AddSharedVoiceParams::new(public_user_id, voice_id);
        let body = AddSharedVoiceBody::new(new_name);
        AddSharedVoice { params, body }
    }
    /// If you don't care about changing the name of the voice, use `from_shared_voice`
    ///
    /// # Example
    /// ```no_run
    /// use elevenlabs_rs::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let c = ElevenLabsClient::default()?;
    ///     let mut query = SharedVoicesQuery::default();
    ///     query = query
    ///         .with_page_size(1)
    ///         .with_use_cases(vec!["characters_animation".to_string()])
    ///         .with_descriptives(vec!["deep".to_string()]);
    ///     let resp = c.hit(GetSharedVoices::new(query)).await?;
    ///     println!("{:#?}", resp);
    ///     if let Some(shared_voice) = resp.voices().first() {
    ///         let resp = c.hit(AddSharedVoice::from_shared_voice(shared_voice)).await?;
    ///         println!("{:#?}", resp);
    ///     } else {
    ///         println!("no shared voices found with query")
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub fn from_shared_voice(v: &SharedVoice) -> Self {
        AddSharedVoice::new(v.public_owner_id(), v.voice_id(), v.name())
    }
}

impl Endpoint for AddSharedVoice {
    type ResponseBody = AddSharedVoiceResponse;

    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, ADD_VOICE_PATH, self.params.public_user_id.0, self.params.voice_id.0
        ));
        url
    }
}

/// Response for adding a shared voice
#[derive(Clone, Debug, Deserialize)]
pub struct AddSharedVoiceResponse {
    voice_id: String,
}

/// Parameters for adding a shared voice
#[derive(Clone, Debug)]
pub struct AddSharedVoiceParams {
    public_user_id: PublicUserID,
    voice_id: VoiceID,
}

impl AddSharedVoiceParams {
    pub fn new(public_user_id: &str, voice_id: &str) -> Self {
        let public_user_id = PublicUserID::from(public_user_id);
        let voice_id = VoiceID::from(voice_id.to_string());
        AddSharedVoiceParams {
            public_user_id,
            voice_id,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct PublicUserID(pub(crate) String);

impl From<&str> for PublicUserID {
    fn from(id: &str) -> Self {
        PublicUserID(id.to_string())
    }
}

/// The name that identifies this voice. This will be displayed in the dropdown of the website.
#[derive(Clone, Debug, Serialize)]
pub struct AddSharedVoiceBody {
    pub new_name: String,
}

impl AddSharedVoiceBody {
    pub fn new(new_name: &str) -> Self {
        AddSharedVoiceBody {
            new_name: new_name.to_string(),
        }
    }
}