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
/// Additional options for speech synthesis
pub mod synthesis;
/// Defines voices available in the Text to Speech service.
pub mod voices;
use std::str::FromStr;

use hyper::{
    client::HttpConnector,
    header::{self, HeaderName, HeaderValue},
    Body, Client, HeaderMap, Method, Request,
};
use hyper_tls::HttpsConnector;
use serde::Deserialize;
use url::Url;

use crate::{
    core::services::ConfigService,
    core::IamAuthenticator,
    tts::{
        synthesis::map_audio_format,
        voices::{def::Voices, voice_map},
    },
};

use self::{
    synthesis::AudioFormats,
    voices::{def::Voice, AvailableVoices},
};
/// The format to use when getting pronunciations.
#[derive(Debug)]
pub enum PhonemeFormat {
    /// `ibm`
    IBM,
    /// `ipa`
    IPA,
}
impl Default for PhonemeFormat {
    /// `ipa`
    fn default() -> Self {
        Self::IPA
    }
}
/// Pronunciation options to be passed to [pronunciation](TextToSpeech::pronunciation).
pub struct PronunciationOptions<'a> {
    /// The [PhonemeFormat](self::PhonemeFormat) to be used in pronunciation.
    pub format: PhonemeFormat,
    /// The text to be used in pronunciation.
    pub text: &'a str,
    /// The voice (ideally of the same language) to use in getting pronunciation [Voices](voices::AvailableVoices)
    pub voice: AvailableVoices,
}

#[derive(Deserialize)]
struct Pronunciation {
    pronunciation: String,
}

impl<'a> PronunciationOptions<'a> {
    /// Creates a new pronunciation definition.
    ///
    /// # Arguments
    ///
    /// * `format` - the [format](self::PhonemeFormat) to be used in the request for pronunciation.
    /// * `text` - pronunciation query.
    /// * `voice` - the [AvailableVoices](voices::AvailableVoices) to use, ideally of the same language as the query.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::tts::PronunciationOptions;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use ibm_watson::tts::PhonemeFormat;
    /// let mut options = PronunciationOptions::new(
    ///                 PhonemeFormat::default(),
    ///                 "aujourd-hui",
    ///                 AvailableVoices::fr_FR_Renee,
    ///               );
    /// ```
    pub fn new(format: PhonemeFormat, text: &'a str, voice: AvailableVoices) -> Self {
        Self {
            format,
            text,
            voice,
        }
    }
    /// Updates the pronunciation query.
    ///
    /// # Arguments
    ///
    /// * `text` - new pronunciation query.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::tts::PronunciationOptions;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use ibm_watson::tts::PhonemeFormat;
    /// # let mut options = PronunciationOptions::new(
    /// #                PhonemeFormat::default(),
    /// #                "aujourd-hui",
    /// #                AvailableVoices::fr_FR_Renee,
    /// #               );
    ///  options.set_text("bonjour");
    /// ```
    pub fn set_text(&mut self, text: &'a str) {
        self.text = text;
    }

    /// Updates the voice used in pronunciation query.
    ///
    /// # Arguments
    ///
    /// * `voice` - [AvailableVoices](voices::AvailableVoices) to use in getting pronunciation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::tts::PronunciationOptions;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use ibm_watson::tts::PhonemeFormat;
    /// # let mut options = PronunciationOptions::new(
    /// #                PhonemeFormat::default(),
    /// #                "aujourd-hui",
    /// #                AvailableVoices::fr_FR_NicolasV3,
    /// #               );
    ///  options.set_voice(AvailableVoices::fr_FR_NicolasV3);
    /// ```
    pub fn set_voice(&mut self, voice: AvailableVoices) {
        self.voice = voice;
    }

    /// Updates the format used in pronunciation query.
    ///
    /// # Arguments
    ///
    /// * `format` - [PhonemeFormat](self::PhonemeFormat)
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::tts::PronunciationOptions;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use ibm_watson::tts::PhonemeFormat;
    /// # let mut options = PronunciationOptions::new(
    /// #                PhonemeFormat::default(),
    /// #                "aujourd-hui",
    /// #                AvailableVoices::fr_FR_NicolasV3,
    /// #               );
    ///  options.set_format(PhonemeFormat::IBM);
    /// ```
    pub fn set_format(&mut self, format: PhonemeFormat) {
        self.format = format;
    }
}
/// Defines text to speech options.
pub struct TextToSpeech {
    pub(crate) service_url: String,
    pub(crate) headers: HeaderMap,
    pub(crate) client: Client<HttpsConnector<HttpConnector>>,
    pub(crate) voice: AvailableVoices,
}

impl TextToSpeech {
    /// Creates a new text to speech options and sets headers based on [IamAuthenticator](super::core::IamAuthenticator).
    ///
    /// # Arguments
    ///
    /// * `auth` - a reference to [IamAuthenticator](super::core::IamAuthenticator) to use, ideally of the same language as the query.
    /// * `service_url` - your IBM Watson TTS endpoint.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// let tts_service_url = String::from("https://my.service.url/foobar");
    /// let auth = IamAuthenticator::new("{myapikey}");
    /// let mut tts = TextToSpeech::new(
    ///                 &auth,
    ///                 tts_service_url,
    ///               );
    /// ```
    pub fn new(auth: &IamAuthenticator, service_url: String) -> Self {
        let mut headers = HeaderMap::default();
        headers.insert(
            header::AUTHORIZATION,
            HeaderValue::from_str(auth.apikey()).expect("Invalid Header Value"),
        );
        headers.insert(
            HeaderName::from_str("X-Watson-Learning-Opt-Out")
                .expect("Invalid HeaderName 'X-Watson-Learning-Opt-Out'"),
            HeaderValue::from_str("true").expect("Failed to Disable IBM Data Collection"),
        );
        Self {
            headers,
            service_url,
            client: Client::builder().build::<_, hyper::Body>(HttpsConnector::new()),
            voice: AvailableVoices::default(),
        }
    }
    /// Changes the voice (from the default).
    ///
    /// # Arguments
    ///
    /// * `voice` - [AvailableVoices](voices::AvailableVoices)
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let mut tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #              );
    /// tts.set_voice(AvailableVoices::en_US_OliviaV3);
    /// ```
    pub fn set_voice(&mut self, voice: AvailableVoices) {
        self.voice = voice;
    }

    /// Returns the `String` equivalent of the current [AvailableVoices](voices::AvailableVoices) set on the current options.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let mut tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #              );
    /// println!("{}", tts.current_voice());
    /// ```
    pub fn current_voice(&self) -> String {
        voice_map(self.voice).to_owned()
    }

    /// Returns a `Vec` of all the [Voices](voices::def::Voice) IBM Watson has.
    ///
    /// # Examples
    ///
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use std::error::Error;
    /// # async fn foo()->Result<(),Box<dyn Error>> {
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #              );
    /// let voices = tts.voices().await?;
    /// for i in &voices {
    ///    println!("{}", i.name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn voices(&self) -> Result<Vec<Voice>, anyhow::Error> {
        let mut request = self.template_request();
        *request.method_mut() = Method::GET;
        let uri = format!("{}/v1/voices", &self.service_url);
        *request.uri_mut() = uri.parse()?;
        *request.body_mut() = Body::empty();
        let res = self.client.request(request).await?;
        assert_eq!(res.status(), hyper::StatusCode::OK);
        let bytes = hyper::body::to_bytes(res.into_body()).await?;
        let root: Voices = serde_json::from_slice(bytes.to_vec().as_slice())?;
        Ok(root.voices)
    }

    /// Returns [details](voices::def::Voice) about a selected voice from [](voices::AvailableVoices)
    ///
    /// # Examples
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use std::error::Error;
    /// # async fn foo()->Result<(),Box<dyn Error>> {
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #              );
    /// let olivia = tts.voice(AvailableVoices::en_US_OliviaV3).await?;
    /// println!("{:#?}", olivia);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn voice(&self, voice: AvailableVoices) -> Result<Voice, anyhow::Error> {
        let mut request = self.template_request();
        *request.method_mut() = Method::GET;
        let uri = format!("{}/v1/voices/{}", &self.service_url, voice_map(voice));
        *request.uri_mut() = uri.parse()?;
        *request.body_mut() = Body::empty();
        let res = self.client.request(request).await?;
        assert_eq!(res.status(), hyper::StatusCode::OK);
        let bytes = hyper::body::to_bytes(res.into_body()).await?;
        let root: Voice = serde_json::from_slice(bytes.to_vec().as_slice())?;
        Ok(root)
    }
    /// Returns a stream of bytes containing synthesised text.
    ///
    /// # Arguments
    ///
    /// * `utterance` - text to synthesise.
    /// * `format` - audio [format](synthesis::AudioFormats) to return.
    ///
    /// # Examples
    /// ```
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use std::error::Error;
    /// # use ibm_watson::tts::synthesis::AudioFormats;
    /// # async fn foo()->Result<(),Box<dyn Error>> {
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let mut tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #               );
    /// let synth_bytes = tts.synthesise_text(
    ///                         "This is just fantastic",
    ///                         AudioFormats::default()
    ///                   ).await?;
    /// tts.set_voice(AvailableVoices::en_US_LisaV3);
    /// let synth_bytes = tts.synthesise_text(
    ///                         "I have changed the voice",
    ///                         AudioFormats::AudioWav
    ///                   ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn synthesise_text(
        &self,
        utterance: &str,
        format: AudioFormats,
    ) -> Result<hyper::body::Bytes, anyhow::Error> {
        let mut url = Url::parse(&self.service_url)?;
        url.set_path("v1/synthesize");
        let accept = map_audio_format(format);
        let mut request = self.template_request();
        url.set_query(Some(format!("accept={}", accept).as_str()));
        let mut stub: String = url.into();
        stub = format!("{}&text={}", stub, utterance);
        stub = Url::parse(&stub)?.to_string();
        *request.method_mut() = Method::GET;
        *request.uri_mut() = format!("{}&voice={}", stub, voice_map(self.voice)).parse()?;
        let res = self.client.request(request).await?;
        assert_eq!(res.status(), hyper::StatusCode::OK);
        let bytes = hyper::body::to_bytes(res.into_body()).await?;
        Ok(bytes)
    }

    /// Gets the phonetic pronunciation for the specified word. You can request the pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model.
    ///
    /// # Arguments
    ///
    /// * `utterance` - text to synthesise.
    /// * `format` - audio [format](synthesis::AudioFormats) to return.
    ///
    /// # Examples
    /// ```
    /// # use ibm_watson::tts::PronunciationOptions;
    /// # use ibm_watson::tts::voices::AvailableVoices;
    /// # use ibm_watson::tts::PhonemeFormat;
    /// # use ibm_watson::core::IamAuthenticator;
    /// # use ibm_watson::tts::TextToSpeech;
    /// # use std::error::Error;
    /// # use ibm_watson::tts::synthesis::AudioFormats;
    /// # async fn foo()->Result<(),Box<dyn Error>> {
    /// # let tts_service_url = String::from("https://my.service.url/foobar");
    /// # let auth = IamAuthenticator::new("{myapikey}");
    /// # let mut tts = TextToSpeech::new(
    /// #                &auth,
    /// #                tts_service_url,
    /// #               );
    /// let options = PronunciationOptions::new(
    ///                 PhonemeFormat::default(),
    ///                 "ça va",
    ///                 AvailableVoices::fr_FR_Renee,
    ///               );
    /// let pronunciation = tts.pronunciation(&options).await?;
    /// println!("{}", pronunciation);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn pronunciation<'a>(
        &self,
        options: &PronunciationOptions<'a>,
    ) -> Result<String, anyhow::Error> {
        let mut url = Url::parse(&self.service_url)?;
        url.set_path("v1/pronunciation");
        let mut request = self.template_request();
        url.set_query(Some(format!("text={}", options.text).as_str()));
        let mut stub: String = url.into();
        stub = format!(
            "{}&format={}",
            stub,
            match options.format {
                PhonemeFormat::IBM => "ibm",
                PhonemeFormat::IPA => "ipa",
            }
        );

        *request.method_mut() = Method::GET;
        *request.uri_mut() = format!("{}&voice={}", stub, voice_map(options.voice)).parse()?;
        let res = self.client.request(request).await?;
        assert_eq!(res.status(), hyper::StatusCode::OK);
        let bytes = hyper::body::to_bytes(res.into_body()).await?;
        let root: Pronunciation = serde_json::from_slice(bytes.to_vec().as_slice())?;
        Ok(root.pronunciation)
    }

    fn template_request(&self) -> Request<Body> {
        let mut request = Request::default();
        *request.headers_mut() = self.headers.clone();
        request
    }
}

impl ConfigService for TextToSpeech {
    fn set_service_url(&mut self, service_url: String) {
        self.service_url = service_url;
    }

    fn set_default_headers(
        &mut self,
        headers: std::collections::HashMap<String, String>,
    ) -> Result<(), anyhow::Error> {
        for (key, value) in &headers {
            self.headers
                .insert(HeaderName::from_str(&key)?, HeaderValue::from_str(&value)?);
        }
        Ok(())
    }

    fn enable_ibm_data_collection(&mut self) {
        self.headers.insert(
            HeaderName::from_str("X-Watson-Learning-Opt-Out")
                .expect("Invalid HeaderName 'X-Watson-Learning-Opt-Out'"),
            HeaderValue::from_str("false").expect("Failed to Enable IBM Data Collection"),
        );
    }
    fn disable_ibm_data_collection(&mut self) {
        self.headers.insert(
            HeaderName::from_str("X-Watson-Learning-Opt-Out")
                .expect("Invalid HeaderName 'X-Watson-Learning-Opt-Out'"),
            HeaderValue::from_str("true").expect("Failed to Disable IBM Data Collection"),
        );
    }
}