-
Notifications
You must be signed in to change notification settings - Fork 206
/
TextToSpeechService.cs
2223 lines (1932 loc) · 108 KB
/
TextToSpeechService.cs
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* (C) Copyright IBM Corp. 2019, 2022.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428
*/
using System.Collections.Generic;
using System.Text;
using IBM.Cloud.SDK;
using IBM.Cloud.SDK.Authentication;
using IBM.Cloud.SDK.Connection;
using IBM.Cloud.SDK.Utilities;
using IBM.Watson.TextToSpeech.V1.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using UnityEngine.Networking;
namespace IBM.Watson.TextToSpeech.V1
{
public partial class TextToSpeechService : BaseService
{
private const string defaultServiceName = "text_to_speech";
private const string defaultServiceUrl = "https://api.us-south.text-to-speech.watson.cloud.ibm.com";
#region DisableSslVerification
private bool disableSslVerification = false;
/// <summary>
/// Gets and sets the option to disable ssl verification
/// </summary>
public bool DisableSslVerification
{
get { return disableSslVerification; }
set { disableSslVerification = value; }
}
#endregion
/// <summary>
/// TextToSpeechService constructor.
/// </summary>
public TextToSpeechService() : this(defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {}
/// <summary>
/// TextToSpeechService constructor.
/// </summary>
/// <param name="authenticator">The service authenticator.</param>
public TextToSpeechService(Authenticator authenticator) : this(defaultServiceName, authenticator) {}
/// <summary>
/// TextToSpeechService constructor.
/// </summary>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
public TextToSpeechService(string serviceName) : this(serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {}
/// <summary>
/// TextToSpeechService constructor.
/// </summary>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
/// <param name="authenticator">The service authenticator.</param>
public TextToSpeechService(string serviceName, Authenticator authenticator) : base(authenticator, serviceName)
{
Authenticator = authenticator;
if (string.IsNullOrEmpty(GetServiceUrl()))
{
SetServiceUrl(defaultServiceUrl);
}
}
/// <summary>
/// List voices.
///
/// Lists all voices available for use with the service. The information includes the name, language, gender,
/// and other details about the voice. The ordering of the list of voices can change from call to call; do not
/// rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a
/// voice](#getvoice).
///
/// **See also:** [Listing all available
/// voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <returns><see cref="Voices" />Voices</returns>
public bool ListVoices(Callback<Voices> callback)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListVoices`");
RequestObject<Voices> req = new RequestObject<Voices>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "ListVoices"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.OnResponse = OnListVoicesResponse;
Connector.URL = GetServiceUrl() + "/v1/voices";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListVoicesResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<Voices> response = new DetailedResponse<Voices>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<Voices>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnListVoicesResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<Voices>)req).Callback != null)
((RequestObject<Voices>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get a voice.
///
/// Gets information about the specified voice. The information includes the name, language, gender, and other
/// details about the voice. Specify a customization ID to obtain information for a custom model that is defined
/// for the language of the specified voice. To list information about all available voices, use the [List
/// voices](#listvoices) method.
///
/// **See also:** [Listing a specific
/// voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice).
///
/// **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian English, Korean, and
/// Swedish languages and voices are supported only for IBM Cloud; they are deprecated for IBM Cloud Pak for
/// Data. Also, the `ar-AR_OmarVoice` voice is deprecated; use the `ar-MS_OmarVoice` voice instead.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="voice">The voice for which information is to be returned.</param>
/// <param name="customizationId">The customization ID (GUID) of a custom model for which information is to be
/// returned. You must make the request with credentials for the instance of the service that owns the custom
/// model. Omit the parameter to see information about the specified voice with no customization.
/// (optional)</param>
/// <returns><see cref="Voice" />Voice</returns>
public bool GetVoice(Callback<Voice> callback, string voice, string customizationId = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetVoice`");
if (string.IsNullOrEmpty(voice))
throw new ArgumentNullException("`voice` is required for `GetVoice`");
RequestObject<Voice> req = new RequestObject<Voice>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "GetVoice"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(customizationId))
{
req.Parameters["customization_id"] = customizationId;
}
req.OnResponse = OnGetVoiceResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/voices/{0}", voice);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetVoiceResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<Voice> response = new DetailedResponse<Voice>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<Voice>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnGetVoiceResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<Voice>)req).Callback != null)
((RequestObject<Voice>)req).Callback(response, resp.Error);
}
/// <summary>
/// Synthesize audio.
///
/// Synthesizes text to audio that is spoken in the specified voice. The service bases its understanding of the
/// language for the input text on the specified voice. Use a voice that matches the language of the input text.
///
///
/// The method accepts a maximum of 5 KB of input text in the body of the request, and 8 KB for the URL and
/// headers. The 5 KB limit includes any SSML tags that you specify. The service returns the synthesized audio
/// stream as an array of bytes.
///
/// **See also:** [The HTTP
/// interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP).
///
/// **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian English, Korean, and
/// Swedish languages and voices are supported only for IBM Cloud; they are deprecated for IBM Cloud Pak for
/// Data. Also, the `ar-AR_OmarVoice` voice is deprecated; use the `ar-MS_OmarVoice` voice instead.
///
/// ### Audio formats (accept types)
///
/// The service can return audio in the following formats (MIME types).
/// * Where indicated, you can optionally specify the sampling rate (`rate`) of the audio. You must specify a
/// sampling rate for the `audio/l16` and `audio/mulaw` formats. A specified sampling rate must lie in the range
/// of 8 kHz to 192 kHz. Some formats restrict the sampling rate to certain values, as noted.
/// * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio:
/// `endianness=big-endian` or `endianness=little-endian`.
///
/// Use the `Accept` header or the `accept` parameter to specify the requested format of the response audio. If
/// you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec
/// (`audio/ogg;codecs=opus`). The service always returns single-channel audio.
/// * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz.
/// * `audio/flac` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
/// * `audio/l16` - You must specify the `rate` of the audio. You can optionally specify the `endianness` of the
/// audio. The default endianness is `little-endian`.
/// * `audio/mp3` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
/// * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
/// * `audio/mulaw` - You must specify the `rate` of the audio.
/// * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can optionally specify the `rate`
/// of the audio. The default sampling rate is 22,050 Hz.
/// * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. Only the following values
/// are valid sampling rates: `48000`, `24000`, `16000`, `12000`, or `8000`. If you specify a value other than
/// one of these, the service returns an error. The default sampling rate is 48,000 Hz.
/// * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate
/// is 22,050 Hz.
/// * `audio/wav` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz.
/// * `audio/webm` - The service returns the audio in the `opus` codec. The service returns audio with a
/// sampling rate of 48,000 Hz.
/// * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of 48,000 Hz.
/// * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate
/// is 22,050 Hz.
///
/// For more information about specifying an audio format, including additional details about some of the
/// formats, see [Using audio
/// formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats).
///
/// ### Warning messages
///
/// If a request includes invalid query parameters, the service returns a `Warnings` response header that
/// provides messages about the invalid parameters. The warning includes a descriptive message and a list of
/// invalid argument strings. For example, a message such as `"Unknown arguments:"` or `"Unknown url query
/// arguments:"` followed by a list of the form `"{invalid_arg_1}, {invalid_arg_2}."` The request succeeds
/// despite the warnings.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="text">The text to synthesize.</param>
/// <param name="accept">The requested format (MIME type) of the audio. You can use the `Accept` header or the
/// `accept` parameter to specify the audio format. For more information about specifying an audio format, see
/// **Audio formats (accept types)** in the method description. (optional, default to
/// audio/ogg;codecs=opus)</param>
/// <param name="voice">The voice to use for synthesis. If you omit the `voice` parameter, the service uses a
/// default voice, which depends on the version of the service that you are using:
/// * _For IBM Cloud,_ the service always uses the US English `en-US_MichaelV3Voice` by default.
/// * _For IBM Cloud Pak for Data,_ the default voice depends on the voices that you installed. If you installed
/// the _enhanced neural voices_, the service uses the US English `en-US_MichaelV3Voice` by default; if that
/// voice is not installed, you must specify a voice. If you installed the _neural voices_, the service always
/// uses the Australian English `en-AU_MadisonVoice` by default.
///
/// **See also:** See also [Using languages and
/// voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). (optional, default to
/// en-US_MichaelV3Voice)</param>
/// <param name="customizationId">The customization ID (GUID) of a custom model to use for the synthesis. If a
/// custom model is specified, it works only if it matches the language of the indicated voice. You must make
/// the request with credentials for the instance of the service that owns the custom model. Omit the parameter
/// to use the specified voice with no customization. (optional)</param>
/// <returns><see cref="byte[]" />byte[]</returns>
public bool Synthesize(Callback<byte[]> callback, string text, string accept = null, string voice = null, string customizationId = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `Synthesize`");
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException("`text` is required for `Synthesize`");
RequestObject<byte[]> req = new RequestObject<byte[]>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "Synthesize"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(voice))
{
req.Parameters["voice"] = voice;
}
if (!string.IsNullOrEmpty(customizationId))
{
req.Parameters["customization_id"] = customizationId;
}
req.Headers["Content-Type"] = "application/json";
req.Headers["Accept"] = "audio/basic";
if (!string.IsNullOrEmpty(accept))
{
req.Headers["Accept"] = accept;
}
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(text))
bodyObject["text"] = text;
req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));
req.OnResponse = OnSynthesizeResponse;
Connector.URL = GetServiceUrl() + "/v1/synthesize";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnSynthesizeResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<byte[]> response = new DetailedResponse<byte[]>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
response.Result = resp.Data;
if (((RequestObject<byte[]>)req).Callback != null)
((RequestObject<byte[]>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get pronunciation.
///
/// 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.
///
/// **See also:** [Querying a word from a
/// language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage).
///
/// **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian English, Korean, and
/// Swedish languages and voices are supported only for IBM Cloud; they are deprecated for IBM Cloud Pak for
/// Data. Also, the `ar-AR_OmarVoice` voice is deprecated; use the `ar-MS_OmarVoice` voice instead.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="text">The word for which the pronunciation is requested.</param>
/// <param name="voice">A voice that specifies the language in which the pronunciation is to be returned. All
/// voices for the same language (for example, `en-US`) return the same translation. (optional, default to
/// en-US_MichaelV3Voice)</param>
/// <param name="format">The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch,
/// Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation in
/// the default format. (optional, default to ipa)</param>
/// <param name="customizationId">The customization ID (GUID) of a custom model for which the pronunciation is
/// to be returned. The language of a specified custom model must match the language of the specified voice. If
/// the word is not defined in the specified custom model, the service returns the default translation for the
/// custom model's language. You must make the request with credentials for the instance of the service that
/// owns the custom model. Omit the parameter to see the translation for the specified voice with no
/// customization. (optional)</param>
/// <returns><see cref="Pronunciation" />Pronunciation</returns>
public bool GetPronunciation(Callback<Pronunciation> callback, string text, string voice = null, string format = null, string customizationId = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetPronunciation`");
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException("`text` is required for `GetPronunciation`");
RequestObject<Pronunciation> req = new RequestObject<Pronunciation>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "GetPronunciation"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(text))
{
req.Parameters["text"] = text;
}
if (!string.IsNullOrEmpty(voice))
{
req.Parameters["voice"] = voice;
}
if (!string.IsNullOrEmpty(format))
{
req.Parameters["format"] = format;
}
if (!string.IsNullOrEmpty(customizationId))
{
req.Parameters["customization_id"] = customizationId;
}
req.OnResponse = OnGetPronunciationResponse;
Connector.URL = GetServiceUrl() + "/v1/pronunciation";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetPronunciationResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<Pronunciation> response = new DetailedResponse<Pronunciation>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<Pronunciation>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnGetPronunciationResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<Pronunciation>)req).Callback != null)
((RequestObject<Pronunciation>)req).Callback(response, resp.Error);
}
/// <summary>
/// Create a custom model.
///
/// Creates a new empty custom model. You must specify a name for the new custom model. You can optionally
/// specify the language and a description for the new model. The model is owned by the instance of the service
/// whose credentials are used to create it.
///
/// **See also:** [Creating a custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate).
///
/// **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian English, Korean, and
/// Swedish languages and voices are supported only for IBM Cloud; they are deprecated for IBM Cloud Pak for
/// Data. Also, the `ar-AR` language identifier cannot be used to create a custom model; use the `ar-MS`
/// identifier instead.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="name">The name of the new custom model.</param>
/// <param name="language">The language of the new custom model. You create a custom model for a specific
/// language, not for a specific voice. A custom model can be used with any voice for its specified language.
/// Omit the parameter to use the the default language, `en-US`.
///
/// **Important:** If you are using the service on IBM Cloud Pak for Data _and_ you install the neural voices,
/// the `language`parameter is required. You must specify the language for the custom model in the indicated
/// format (for example, `en-AU` for Australian English). The request fails if you do not specify a language.
/// (optional, default to en-US)</param>
/// <param name="description">A description of the new custom model. Specifying a description is recommended.
/// (optional)</param>
/// <returns><see cref="CustomModel" />CustomModel</returns>
public bool CreateCustomModel(Callback<CustomModel> callback, string name, string language = null, string description = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `CreateCustomModel`");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("`name` is required for `CreateCustomModel`");
RequestObject<CustomModel> req = new RequestObject<CustomModel>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "CreateCustomModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Headers["Content-Type"] = "application/json";
req.Headers["Accept"] = "application/json";
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
bodyObject["name"] = name;
if (!string.IsNullOrEmpty(language))
bodyObject["language"] = language;
if (!string.IsNullOrEmpty(description))
bodyObject["description"] = description;
req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));
req.OnResponse = OnCreateCustomModelResponse;
Connector.URL = GetServiceUrl() + "/v1/customizations";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnCreateCustomModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<CustomModel> response = new DetailedResponse<CustomModel>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<CustomModel>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnCreateCustomModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<CustomModel>)req).Callback != null)
((RequestObject<CustomModel>)req).Callback(response, resp.Error);
}
/// <summary>
/// List custom models.
///
/// Lists metadata such as the name and description for all custom models that are owned by an instance of the
/// service. Specify a language to list the custom models for that language only. To see the words and prompts
/// in addition to the metadata for a specific custom model, use the [Get a custom model](#getcustommodel)
/// method. You must use credentials for the instance of the service that owns a model to list information about
/// it.
///
/// **See also:** [Querying all custom
/// models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="language">The language for which custom models that are owned by the requesting credentials are
/// to be returned. Omit the parameter to see all custom models that are owned by the requester.
/// (optional)</param>
/// <returns><see cref="CustomModels" />CustomModels</returns>
public bool ListCustomModels(Callback<CustomModels> callback, string language = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListCustomModels`");
RequestObject<CustomModels> req = new RequestObject<CustomModels>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "ListCustomModels"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(language))
{
req.Parameters["language"] = language;
}
req.OnResponse = OnListCustomModelsResponse;
Connector.URL = GetServiceUrl() + "/v1/customizations";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListCustomModelsResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<CustomModels> response = new DetailedResponse<CustomModels>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<CustomModels>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnListCustomModelsResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<CustomModels>)req).Callback != null)
((RequestObject<CustomModels>)req).Callback(response, resp.Error);
}
/// <summary>
/// Update a custom model.
///
/// Updates information for the specified custom model. You can update metadata such as the name and description
/// of the model. You can also update the words in the model and their translations. Adding a new translation
/// for a word that already exists in a custom model overwrites the word's existing translation. A custom model
/// can contain no more than 20,000 entries. You must use credentials for the instance of the service that owns
/// a model to update it.
///
/// You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or
/// more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme
/// format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA)
/// representation
///
/// <code><phoneme alphabet="ipa" ph="təmˈɑto"></phoneme></code>
///
/// or in the proprietary IBM Symbolic Phonetic Representation (SPR)
///
/// <code><phoneme alphabet="ibm" ph="1gAstroEntxrYFXs"></phoneme></code>
///
/// **See also:**
/// * [Updating a custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsUpdate)
/// * [Adding words to a Japanese custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd)
/// * [Understanding
/// customization](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="customizationId">The customization ID (GUID) of the custom model. You must make the request
/// with credentials for the instance of the service that owns the custom model.</param>
/// <param name="name">A new name for the custom model. (optional)</param>
/// <param name="description">A new description for the custom model. (optional)</param>
/// <param name="words">An array of `Word` objects that provides the words and their translations that are to be
/// added or updated for the custom model. Pass an empty array to make no additions or updates.
/// (optional)</param>
/// <returns><see cref="object" />object</returns>
public bool UpdateCustomModel(Callback<object> callback, string customizationId, string name = null, string description = null, List<Word> words = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `UpdateCustomModel`");
if (string.IsNullOrEmpty(customizationId))
throw new ArgumentNullException("`customizationId` is required for `UpdateCustomModel`");
RequestObject<object> req = new RequestObject<object>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "UpdateCustomModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Headers["Content-Type"] = "application/json";
req.Headers["Accept"] = "application/json";
JObject bodyObject = new JObject();
if (!string.IsNullOrEmpty(name))
bodyObject["name"] = name;
if (!string.IsNullOrEmpty(description))
bodyObject["description"] = description;
if (words != null && words.Count > 0)
bodyObject["words"] = JToken.FromObject(words);
req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));
req.OnResponse = OnUpdateCustomModelResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/customizations/{0}", customizationId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnUpdateCustomModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<object> response = new DetailedResponse<object>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<object>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnUpdateCustomModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<object>)req).Callback != null)
((RequestObject<object>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get a custom model.
///
/// Gets all information about a specified custom model. In addition to metadata such as the name and
/// description of the custom model, the output includes the words and their translations that are defined for
/// the model, as well as any prompts that are defined for the model. To see just the metadata for a model, use
/// the [List custom models](#listcustommodels) method.
///
/// **See also:** [Querying a custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="customizationId">The customization ID (GUID) of the custom model. You must make the request
/// with credentials for the instance of the service that owns the custom model.</param>
/// <returns><see cref="CustomModel" />CustomModel</returns>
public bool GetCustomModel(Callback<CustomModel> callback, string customizationId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetCustomModel`");
if (string.IsNullOrEmpty(customizationId))
throw new ArgumentNullException("`customizationId` is required for `GetCustomModel`");
RequestObject<CustomModel> req = new RequestObject<CustomModel>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "GetCustomModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.OnResponse = OnGetCustomModelResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/customizations/{0}", customizationId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetCustomModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<CustomModel> response = new DetailedResponse<CustomModel>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<CustomModel>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnGetCustomModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<CustomModel>)req).Callback != null)
((RequestObject<CustomModel>)req).Callback(response, resp.Error);
}
/// <summary>
/// Delete a custom model.
///
/// Deletes the specified custom model. You must use credentials for the instance of the service that owns a
/// model to delete it.
///
/// **See also:** [Deleting a custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsDelete).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="customizationId">The customization ID (GUID) of the custom model. You must make the request
/// with credentials for the instance of the service that owns the custom model.</param>
/// <returns><see cref="object" />object</returns>
public bool DeleteCustomModel(Callback<object> callback, string customizationId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `DeleteCustomModel`");
if (string.IsNullOrEmpty(customizationId))
throw new ArgumentNullException("`customizationId` is required for `DeleteCustomModel`");
RequestObject<object> req = new RequestObject<object>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbDELETE,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "DeleteCustomModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.OnResponse = OnDeleteCustomModelResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/customizations/{0}", customizationId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnDeleteCustomModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<object> response = new DetailedResponse<object>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<object>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("TextToSpeechService.OnDeleteCustomModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<object>)req).Callback != null)
((RequestObject<object>)req).Callback(response, resp.Error);
}
/// <summary>
/// Add custom words.
///
/// Adds one or more words and their translations to the specified custom model. Adding a new translation for a
/// word that already exists in a custom model overwrites the word's existing translation. A custom model can
/// contain no more than 20,000 entries. You must use credentials for the instance of the service that owns a
/// model to add words to it.
///
/// You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or
/// more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme
/// format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA)
/// representation
///
/// <code><phoneme alphabet="ipa" ph="təmˈɑto"></phoneme></code>
///
/// or in the proprietary IBM Symbolic Phonetic Representation (SPR)
///
/// <code><phoneme alphabet="ibm" ph="1gAstroEntxrYFXs"></phoneme></code>
///
/// **See also:**
/// * [Adding multiple words to a custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsAdd)
/// * [Adding words to a Japanese custom
/// model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuJapaneseAdd)
/// * [Understanding
/// customization](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="customizationId">The customization ID (GUID) of the custom model. You must make the request
/// with credentials for the instance of the service that owns the custom model.</param>
/// <param name="words">The [Add custom words](#addwords) method accepts an array of `Word` objects. Each object
/// provides a word that is to be added or updated for the custom model and the word's translation.
///
/// The [List custom words](#listwords) method returns an array of `Word` objects. Each object shows a word and
/// its translation from the custom model. The words are listed in alphabetical order, with uppercase letters
/// listed before lowercase letters. The array is empty if the custom model contains no words.</param>
/// <returns><see cref="object" />object</returns>
public bool AddWords(Callback<object> callback, string customizationId, List<Word> words)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `AddWords`");
if (string.IsNullOrEmpty(customizationId))
throw new ArgumentNullException("`customizationId` is required for `AddWords`");
if (words == null)
throw new ArgumentNullException("`words` is required for `AddWords`");
RequestObject<object> req = new RequestObject<object>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("text_to_speech", "V1", "AddWords"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}