@aws-amplify/predictions 5.5.6-api-v6-models.b3abc9b.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +3 -0
  2. package/lib/Predictions.d.ts +11 -45
  3. package/lib/Predictions.js +24 -132
  4. package/lib/errors/PredictionsError.d.ts +4 -0
  5. package/lib/errors/PredictionsError.js +15 -0
  6. package/lib/errors/types/validation.d.ts +14 -0
  7. package/lib/errors/types/validation.js +50 -0
  8. package/lib/errors/utils/assertValidationError.d.ts +2 -0
  9. package/lib/errors/utils/assertValidationError.js +14 -0
  10. package/lib/index.d.ts +2 -4
  11. package/lib/index.js +2 -9
  12. package/{lib-esm/Providers → lib/providers}/AmazonAIConvertPredictionsProvider.d.ts +6 -7
  13. package/lib/providers/AmazonAIConvertPredictionsProvider.js +307 -0
  14. package/lib/{Providers → providers}/AmazonAIIdentifyPredictionsProvider.d.ts +5 -6
  15. package/lib/providers/AmazonAIIdentifyPredictionsProvider.js +334 -0
  16. package/lib/{Providers → providers}/AmazonAIInterpretPredictionsProvider.d.ts +3 -4
  17. package/lib/providers/AmazonAIInterpretPredictionsProvider.js +208 -0
  18. package/lib/providers/IdentifyTextUtils.d.ts +16 -0
  19. package/lib/{Providers → providers}/IdentifyTextUtils.js +97 -148
  20. package/lib/{Providers → providers}/Utils.d.ts +2 -2
  21. package/lib/{Providers → providers}/Utils.js +11 -12
  22. package/lib/{Providers → providers}/index.d.ts +1 -2
  23. package/lib/providers/index.js +11 -0
  24. package/lib/tsconfig.tsbuildinfo +1 -0
  25. package/lib/types/AWSTypes.d.ts +8 -9
  26. package/lib/types/AWSTypes.js +0 -1
  27. package/lib/types/Predictions.d.ts +63 -59
  28. package/lib/types/Predictions.js +41 -28
  29. package/lib/types/index.js +1 -2
  30. package/lib-esm/Predictions.d.ts +11 -45
  31. package/lib-esm/Predictions.js +23 -133
  32. package/lib-esm/errors/PredictionsError.d.ts +4 -0
  33. package/lib-esm/errors/PredictionsError.js +11 -0
  34. package/lib-esm/errors/types/validation.d.ts +14 -0
  35. package/lib-esm/errors/types/validation.js +47 -0
  36. package/lib-esm/errors/utils/assertValidationError.d.ts +2 -0
  37. package/lib-esm/errors/utils/assertValidationError.js +10 -0
  38. package/lib-esm/index.d.ts +2 -4
  39. package/lib-esm/index.js +1 -5
  40. package/{lib/Providers → lib-esm/providers}/AmazonAIConvertPredictionsProvider.d.ts +6 -7
  41. package/lib-esm/providers/AmazonAIConvertPredictionsProvider.js +303 -0
  42. package/lib-esm/{Providers → providers}/AmazonAIIdentifyPredictionsProvider.d.ts +5 -6
  43. package/lib-esm/providers/AmazonAIIdentifyPredictionsProvider.js +330 -0
  44. package/lib-esm/{Providers → providers}/AmazonAIInterpretPredictionsProvider.d.ts +3 -4
  45. package/lib-esm/providers/AmazonAIInterpretPredictionsProvider.js +204 -0
  46. package/lib-esm/providers/IdentifyTextUtils.d.ts +16 -0
  47. package/lib-esm/providers/IdentifyTextUtils.js +264 -0
  48. package/lib-esm/{Providers → providers}/Utils.d.ts +2 -2
  49. package/lib-esm/{Providers → providers}/Utils.js +10 -12
  50. package/lib-esm/{Providers → providers}/index.d.ts +1 -2
  51. package/lib-esm/{Providers → providers}/index.js +1 -3
  52. package/lib-esm/tsconfig.tsbuildinfo +1 -0
  53. package/lib-esm/types/AWSTypes.d.ts +8 -9
  54. package/lib-esm/types/AWSTypes.js +1 -1
  55. package/lib-esm/types/Predictions.d.ts +63 -59
  56. package/lib-esm/types/Predictions.js +34 -27
  57. package/lib-esm/types/index.js +0 -1
  58. package/package.json +39 -48
  59. package/src/Predictions.ts +33 -220
  60. package/src/errors/PredictionsError.ts +16 -0
  61. package/src/errors/types/validation.ts +51 -0
  62. package/src/errors/utils/assertValidationError.ts +18 -0
  63. package/src/index.ts +16 -16
  64. package/src/{Providers → providers}/AmazonAIConvertPredictionsProvider.ts +210 -171
  65. package/src/{Providers → providers}/AmazonAIIdentifyPredictionsProvider.ts +244 -246
  66. package/src/providers/AmazonAIInterpretPredictionsProvider.ts +293 -0
  67. package/src/{Providers → providers}/IdentifyTextUtils.ts +69 -52
  68. package/src/{Providers → providers}/Utils.ts +2 -2
  69. package/src/{Providers → providers}/index.ts +0 -2
  70. package/src/types/AWSTypes.ts +5 -6
  71. package/src/types/Predictions.ts +107 -62
  72. package/lib/.tsbuildinfo +0 -3
  73. package/lib/Predictions.js.map +0 -1
  74. package/lib/Providers/AmazonAIConvertPredictionsProvider.js +0 -377
  75. package/lib/Providers/AmazonAIConvertPredictionsProvider.js.map +0 -1
  76. package/lib/Providers/AmazonAIIdentifyPredictionsProvider.js +0 -441
  77. package/lib/Providers/AmazonAIIdentifyPredictionsProvider.js.map +0 -1
  78. package/lib/Providers/AmazonAIInterpretPredictionsProvider.js +0 -321
  79. package/lib/Providers/AmazonAIInterpretPredictionsProvider.js.map +0 -1
  80. package/lib/Providers/AmazonAIPredictionsProvider.d.ts +0 -14
  81. package/lib/Providers/AmazonAIPredictionsProvider.js +0 -43
  82. package/lib/Providers/AmazonAIPredictionsProvider.js.map +0 -1
  83. package/lib/Providers/IdentifyTextUtils.d.ts +0 -40
  84. package/lib/Providers/IdentifyTextUtils.js.map +0 -1
  85. package/lib/Providers/Utils.js.map +0 -1
  86. package/lib/Providers/index.js +0 -13
  87. package/lib/Providers/index.js.map +0 -1
  88. package/lib/index.js.map +0 -1
  89. package/lib/types/AWSTypes.js.map +0 -1
  90. package/lib/types/Predictions.js.map +0 -1
  91. package/lib/types/Providers/AbstractConvertPredictionsProvider.d.ts +0 -9
  92. package/lib/types/Providers/AbstractConvertPredictionsProvider.js +0 -44
  93. package/lib/types/Providers/AbstractConvertPredictionsProvider.js.map +0 -1
  94. package/lib/types/Providers/AbstractIdentifyPredictionsProvider.d.ts +0 -9
  95. package/lib/types/Providers/AbstractIdentifyPredictionsProvider.js +0 -44
  96. package/lib/types/Providers/AbstractIdentifyPredictionsProvider.js.map +0 -1
  97. package/lib/types/Providers/AbstractInterpretPredictionsProvider.d.ts +0 -7
  98. package/lib/types/Providers/AbstractInterpretPredictionsProvider.js +0 -27
  99. package/lib/types/Providers/AbstractInterpretPredictionsProvider.js.map +0 -1
  100. package/lib/types/Providers/AbstractPredictionsProvider.d.ts +0 -7
  101. package/lib/types/Providers/AbstractPredictionsProvider.js +0 -16
  102. package/lib/types/Providers/AbstractPredictionsProvider.js.map +0 -1
  103. package/lib/types/Providers/index.d.ts +0 -4
  104. package/lib/types/Providers/index.js +0 -10
  105. package/lib/types/Providers/index.js.map +0 -1
  106. package/lib/types/index.js.map +0 -1
  107. package/lib-esm/.tsbuildinfo +0 -3
  108. package/lib-esm/Predictions.js.map +0 -1
  109. package/lib-esm/Providers/AmazonAIConvertPredictionsProvider.js +0 -375
  110. package/lib-esm/Providers/AmazonAIConvertPredictionsProvider.js.map +0 -1
  111. package/lib-esm/Providers/AmazonAIIdentifyPredictionsProvider.js +0 -439
  112. package/lib-esm/Providers/AmazonAIIdentifyPredictionsProvider.js.map +0 -1
  113. package/lib-esm/Providers/AmazonAIInterpretPredictionsProvider.js +0 -319
  114. package/lib-esm/Providers/AmazonAIInterpretPredictionsProvider.js.map +0 -1
  115. package/lib-esm/Providers/AmazonAIPredictionsProvider.d.ts +0 -14
  116. package/lib-esm/Providers/AmazonAIPredictionsProvider.js +0 -41
  117. package/lib-esm/Providers/AmazonAIPredictionsProvider.js.map +0 -1
  118. package/lib-esm/Providers/IdentifyTextUtils.d.ts +0 -40
  119. package/lib-esm/Providers/IdentifyTextUtils.js +0 -313
  120. package/lib-esm/Providers/IdentifyTextUtils.js.map +0 -1
  121. package/lib-esm/Providers/Utils.js.map +0 -1
  122. package/lib-esm/Providers/index.js.map +0 -1
  123. package/lib-esm/index.js.map +0 -1
  124. package/lib-esm/types/AWSTypes.js.map +0 -1
  125. package/lib-esm/types/Predictions.js.map +0 -1
  126. package/lib-esm/types/Providers/AbstractConvertPredictionsProvider.d.ts +0 -9
  127. package/lib-esm/types/Providers/AbstractConvertPredictionsProvider.js +0 -42
  128. package/lib-esm/types/Providers/AbstractConvertPredictionsProvider.js.map +0 -1
  129. package/lib-esm/types/Providers/AbstractIdentifyPredictionsProvider.d.ts +0 -9
  130. package/lib-esm/types/Providers/AbstractIdentifyPredictionsProvider.js +0 -42
  131. package/lib-esm/types/Providers/AbstractIdentifyPredictionsProvider.js.map +0 -1
  132. package/lib-esm/types/Providers/AbstractInterpretPredictionsProvider.d.ts +0 -7
  133. package/lib-esm/types/Providers/AbstractInterpretPredictionsProvider.js +0 -25
  134. package/lib-esm/types/Providers/AbstractInterpretPredictionsProvider.js.map +0 -1
  135. package/lib-esm/types/Providers/AbstractPredictionsProvider.d.ts +0 -7
  136. package/lib-esm/types/Providers/AbstractPredictionsProvider.js +0 -14
  137. package/lib-esm/types/Providers/AbstractPredictionsProvider.js.map +0 -1
  138. package/lib-esm/types/Providers/index.d.ts +0 -4
  139. package/lib-esm/types/Providers/index.js +0 -7
  140. package/lib-esm/types/Providers/index.js.map +0 -1
  141. package/lib-esm/types/index.js.map +0 -1
  142. package/src/Providers/AmazonAIInterpretPredictionsProvider.ts +0 -281
  143. package/src/Providers/AmazonAIPredictionsProvider.ts +0 -69
  144. package/src/types/Providers/AbstractConvertPredictionsProvider.ts +0 -55
  145. package/src/types/Providers/AbstractIdentifyPredictionsProvider.ts +0 -57
  146. package/src/types/Providers/AbstractInterpretPredictionsProvider.ts +0 -26
  147. package/src/types/Providers/AbstractPredictionsProvider.ts +0 -20
  148. package/src/types/Providers/index.ts +0 -6
@@ -1,77 +1,110 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { AbstractConvertPredictionsProvider } from '../types/Providers/AbstractConvertPredictionsProvider';
3
+ import {
4
+ Amplify,
5
+ ConsoleLogger as Logger,
6
+ fetchAuthSession,
7
+ } from '@aws-amplify/core';
8
+ import {
9
+ AWSCredentials,
10
+ Category,
11
+ PredictionsAction,
12
+ Signer,
13
+ getAmplifyUserAgentObject,
14
+ } from '@aws-amplify/core/internals/utils';
15
+ import { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';
4
16
  import {
5
17
  TranslateClient,
6
18
  TranslateTextCommand,
7
19
  } from '@aws-sdk/client-translate';
8
- import { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';
9
20
  import {
10
- TranslateTextInput,
11
- TextToSpeechInput,
21
+ EventStreamCodec,
22
+ MessageHeaderValue,
23
+ } from '@smithy/eventstream-codec';
24
+ import { fromUtf8, toUtf8 } from '@smithy/util-utf8';
25
+ import { Buffer } from 'buffer';
26
+ import { PredictionsValidationErrorCode } from '../errors/types/validation';
27
+ import { assertValidationError } from '../errors/utils/assertValidationError';
28
+ import {
29
+ ConvertBytes,
12
30
  SpeechToTextInput,
13
- TranslateTextOutput,
14
- TextToSpeechOutput,
15
31
  SpeechToTextOutput,
16
- isBytesSource,
32
+ TextToSpeechInput,
33
+ TextToSpeechOutput,
34
+ TranscribeData,
35
+ TranslateTextInput,
36
+ TranslateTextOutput,
37
+ isConvertBytesSource,
38
+ isTextToSpeechInput,
39
+ isTranslateTextInput,
40
+ isValidConvertInput,
17
41
  } from '../types';
18
- import {
19
- Credentials,
20
- ConsoleLogger as Logger,
21
- Signer,
22
- getAmplifyUserAgentObject,
23
- Category,
24
- PredictionsAction,
25
- } from '@aws-amplify/core';
26
- import {
27
- EventStreamMarshaller,
28
- MessageHeaderValue,
29
- } from '@aws-sdk/eventstream-marshaller';
30
- import { fromUtf8, toUtf8 } from '@aws-sdk/util-utf8-node';
31
- import { Buffer } from 'buffer';
32
42
 
33
43
  const logger = new Logger('AmazonAIConvertPredictionsProvider');
34
- const eventBuilder = new EventStreamMarshaller(toUtf8, fromUtf8);
44
+ const eventBuilder = new EventStreamCodec(toUtf8, fromUtf8);
35
45
 
36
46
  const LANGUAGES_CODE_IN_8KHZ = ['fr-FR', 'en-AU', 'en-GB', 'fr-CA'];
37
47
 
38
- export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictionsProvider {
39
- private translateClient: TranslateClient;
40
- private pollyClient: PollyClient;
41
- constructor() {
42
- super();
43
- }
48
+ export class AmazonAIConvertPredictionsProvider {
49
+ private translateClient?: TranslateClient;
50
+ private pollyClient?: PollyClient;
44
51
 
45
52
  getProviderName() {
46
53
  return 'AmazonAIConvertPredictionsProvider';
47
54
  }
48
55
 
56
+ convert(
57
+ input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput
58
+ ): Promise<TextToSpeechOutput | TranslateTextOutput | SpeechToTextOutput> {
59
+ assertValidationError(
60
+ isValidConvertInput(input),
61
+ PredictionsValidationErrorCode.InvalidInput
62
+ );
63
+
64
+ if (isTranslateTextInput(input)) {
65
+ logger.debug('translateText');
66
+ return this.translateText(input);
67
+ } else if (isTextToSpeechInput(input)) {
68
+ logger.debug('textToSpeech');
69
+ return this.convertTextToSpeech(input);
70
+ } else {
71
+ logger.debug('textToSpeech');
72
+ return this.convertSpeechToText(input);
73
+ }
74
+ }
75
+
49
76
  protected async translateText(
50
77
  input: TranslateTextInput
51
78
  ): Promise<TranslateTextOutput> {
52
79
  logger.debug('Starting translation');
53
- const {
54
- translateText: {
55
- defaults: { sourceLanguage = '', targetLanguage = '' } = {},
56
- region = '',
57
- } = {},
58
- } = this._config;
59
-
60
- if (!region) {
61
- return Promise.reject('region not configured for transcription');
62
- }
63
80
 
64
- const credentials = await Credentials.get();
65
- if (!credentials) {
66
- return Promise.reject('No credentials');
67
- }
81
+ const { translateText = {} } =
82
+ Amplify.getConfig().Predictions?.convert ?? {};
83
+ assertValidationError(
84
+ !!translateText.region,
85
+ PredictionsValidationErrorCode.NoRegion
86
+ );
87
+ const { defaults = {}, region } = translateText;
88
+
89
+ const { credentials } = await fetchAuthSession();
90
+ assertValidationError(
91
+ !!credentials,
92
+ PredictionsValidationErrorCode.NoCredentials
93
+ );
94
+
95
+ const { sourceLanguage, targetLanguage } = defaults;
68
96
  const sourceLanguageCode =
69
- input.translateText.source.language || sourceLanguage;
97
+ input.translateText?.source?.language ?? sourceLanguage;
70
98
  const targetLanguageCode =
71
- input.translateText.targetLanguage || targetLanguage;
72
- if (!sourceLanguageCode || !targetLanguageCode) {
73
- return Promise.reject('Please provide both source and target language');
74
- }
99
+ input.translateText?.targetLanguage ?? targetLanguage;
100
+ assertValidationError(
101
+ !!sourceLanguageCode,
102
+ PredictionsValidationErrorCode.NoSourceLanguage
103
+ );
104
+ assertValidationError(
105
+ !!targetLanguageCode,
106
+ PredictionsValidationErrorCode.NoTargetLanguage
107
+ );
75
108
 
76
109
  this.translateClient = new TranslateClient({
77
110
  region,
@@ -84,43 +117,39 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
84
117
  const translateTextCommand = new TranslateTextCommand({
85
118
  SourceLanguageCode: sourceLanguageCode,
86
119
  TargetLanguageCode: targetLanguageCode,
87
- Text: input.translateText.source.text,
120
+ Text: input.translateText?.source?.text,
88
121
  });
89
- try {
90
- const data = await this.translateClient.send(translateTextCommand);
91
- return {
92
- text: data.TranslatedText,
93
- language: data.TargetLanguageCode,
94
- } as TranslateTextOutput;
95
- } catch (err) {
96
- return Promise.reject(err);
97
- }
122
+ const data = await this.translateClient.send(translateTextCommand);
123
+ return {
124
+ text: data.TranslatedText,
125
+ language: data.TargetLanguageCode,
126
+ } as TranslateTextOutput;
98
127
  }
99
128
 
100
129
  protected async convertTextToSpeech(
101
130
  input: TextToSpeechInput
102
131
  ): Promise<TextToSpeechOutput> {
103
- const credentials = await Credentials.get();
104
- if (!credentials) {
105
- return Promise.reject('No credentials');
106
- }
107
- const {
108
- speechGenerator: { defaults: { VoiceId = '' } = {}, region = '' } = {},
109
- } = this._config;
132
+ const { credentials } = await fetchAuthSession();
133
+ assertValidationError(
134
+ !!credentials,
135
+ PredictionsValidationErrorCode.NoCredentials
136
+ );
137
+ assertValidationError(
138
+ !!input.textToSpeech?.source,
139
+ PredictionsValidationErrorCode.NoSource
140
+ );
110
141
 
111
- if (!input.textToSpeech.source) {
112
- return Promise.reject('Source needs to be provided in the input');
113
- }
114
- const voiceId = input.textToSpeech.voiceId || VoiceId;
115
- if (!region) {
116
- return Promise.reject(
117
- 'Region was undefined. Did you enable speech generator using amplify CLI?'
118
- );
119
- }
142
+ const { speechGenerator } = Amplify.getConfig().Predictions?.convert ?? {};
143
+ assertValidationError(
144
+ !!speechGenerator?.region,
145
+ PredictionsValidationErrorCode.NoRegion
146
+ );
120
147
 
121
- if (!voiceId) {
122
- return Promise.reject('VoiceId was undefined.');
123
- }
148
+ const { defaults = {}, region } = speechGenerator;
149
+
150
+ const { voiceId: defaultVoiceId } = defaults;
151
+ const voiceId = input.textToSpeech?.voiceId ?? defaultVoiceId;
152
+ assertValidationError(!!voiceId, PredictionsValidationErrorCode.NoVoiceId);
124
153
 
125
154
  this.pollyClient = new PollyClient({
126
155
  region,
@@ -132,93 +161,77 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
132
161
  });
133
162
  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
134
163
  OutputFormat: 'mp3',
135
- Text: input.textToSpeech.source.text,
164
+ Text: input.textToSpeech?.source?.text,
136
165
  VoiceId: voiceId,
137
166
  TextType: 'text',
138
167
  SampleRate: '24000',
139
168
  // tslint:disable-next-line: align
140
169
  });
141
- try {
142
- const data = await this.pollyClient.send(synthesizeSpeechCommand);
143
- const response = new Response(data.AudioStream as ReadableStream);
144
- const arrayBuffer = await response.arrayBuffer();
145
- const blob = new Blob([arrayBuffer], {
146
- type: data.ContentType,
147
- });
148
- const url = URL.createObjectURL(blob);
149
- return {
150
- speech: { url },
151
- audioStream: arrayBuffer,
152
- text: input.textToSpeech.source.text,
153
- } as TextToSpeechOutput;
154
- } catch (err) {
155
- return Promise.reject(err);
156
- }
170
+ const data = await this.pollyClient.send(synthesizeSpeechCommand);
171
+ const response = new Response(data.AudioStream as ReadableStream);
172
+ const arrayBuffer = await response.arrayBuffer();
173
+ const blob = new Blob([arrayBuffer], {
174
+ type: data.ContentType,
175
+ });
176
+ const url = URL.createObjectURL(blob);
177
+ return {
178
+ speech: { url },
179
+ audioStream: arrayBuffer,
180
+ text: input.textToSpeech?.source?.text,
181
+ } as TextToSpeechOutput;
157
182
  }
158
183
 
159
184
  protected async convertSpeechToText(
160
185
  input: SpeechToTextInput
161
186
  ): Promise<SpeechToTextOutput> {
162
- try {
163
- logger.debug('starting transcription..');
164
- const credentials = await Credentials.get();
165
- if (!credentials) {
166
- return Promise.reject('No credentials');
167
- }
168
- const {
169
- transcription: {
170
- defaults: { language: languageCode = '' } = {},
171
- region = '',
172
- } = {},
173
- } = this._config;
174
- if (!region) {
175
- return Promise.reject('region not configured for transcription');
176
- }
177
- if (!languageCode) {
178
- return Promise.reject(
179
- 'languageCode not configured or provided for transcription'
180
- );
181
- }
182
- const {
183
- transcription: { source, language = languageCode },
184
- } = input;
187
+ logger.debug('starting transcription..');
188
+ const { credentials } = await fetchAuthSession();
189
+ assertValidationError(
190
+ !!credentials,
191
+ PredictionsValidationErrorCode.NoCredentials
192
+ );
185
193
 
186
- if (isBytesSource(source)) {
187
- const connection = await this.openConnectionWithTranscribe({
188
- credentials,
189
- region,
190
- languageCode: language,
191
- });
194
+ const { transcription } = Amplify.getConfig().Predictions?.convert ?? {};
195
+ assertValidationError(
196
+ !!transcription?.region,
197
+ PredictionsValidationErrorCode.NoRegion
198
+ );
192
199
 
193
- try {
194
- const fullText = await this.sendDataToTranscribe({
195
- connection,
196
- raw: source.bytes,
197
- languageCode: language,
198
- });
199
- return {
200
- transcription: {
201
- fullText,
202
- },
203
- };
204
- } catch (err) {
205
- return Promise.reject(err);
206
- }
207
- }
200
+ const { defaults, region } = transcription;
201
+ const language = input.transcription?.language ?? defaults?.language;
208
202
 
209
- return Promise.reject(
210
- 'Source types other than byte source are not supported.'
211
- );
212
- } catch (err) {
213
- return Promise.reject(err.name + ': ' + err.message);
214
- }
203
+ assertValidationError(
204
+ !!language,
205
+ PredictionsValidationErrorCode.NoLanguage
206
+ );
207
+
208
+ const source = input.transcription?.source;
209
+ assertValidationError(
210
+ isConvertBytesSource(source),
211
+ PredictionsValidationErrorCode.InvalidSource
212
+ );
213
+
214
+ const connection = await this.openConnectionWithTranscribe({
215
+ credentials,
216
+ region,
217
+ languageCode: language,
218
+ });
219
+
220
+ const fullText = await this.sendDataToTranscribe({
221
+ connection,
222
+ raw: source.bytes,
223
+ languageCode: language,
224
+ });
225
+ return {
226
+ transcription: {
227
+ fullText,
228
+ },
229
+ };
215
230
  }
216
231
 
217
- public static serializeDataFromTranscribe(message) {
232
+ public static serializeDataFromTranscribe(message: MessageEvent) {
218
233
  let decodedMessage = '';
219
- const transcribeMessage = eventBuilder.unmarshall(
220
- Buffer.from(message.data)
221
- );
234
+ const transcribeMessage = eventBuilder.decode(Buffer.from(message.data));
222
235
  const transcribeMessageJson = JSON.parse(toUtf8(transcribeMessage.body));
223
236
  if (transcribeMessage.headers[':message-type'].value === 'exception') {
224
237
  logger.debug(
@@ -259,7 +272,7 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
259
272
  connection,
260
273
  raw,
261
274
  languageCode,
262
- }): Promise<string> {
275
+ }: TranscribeData): Promise<string> {
263
276
  return new Promise((res, rej) => {
264
277
  let fullText = '';
265
278
  connection.onmessage = message => {
@@ -271,9 +284,9 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
271
284
  if (decodedMessage) {
272
285
  fullText += decodedMessage + ' ';
273
286
  }
274
- } catch (err) {
287
+ } catch (err: unknown) {
275
288
  logger.debug(err);
276
- rej(err.message);
289
+ rej(err);
277
290
  }
278
291
  };
279
292
 
@@ -301,27 +314,32 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
301
314
 
302
315
  // sending end frame
303
316
  const endFrameEventMessage = this.getAudioEventMessage(Buffer.from([]));
304
- const endFrameBinary = eventBuilder.marshall(endFrameEventMessage);
317
+ const endFrameBinary = eventBuilder.encode(endFrameEventMessage);
305
318
  connection.send(endFrameBinary);
306
319
  });
307
320
  }
308
321
 
309
- private sendEncodedDataToTranscribe(connection, data, languageCode) {
322
+ private sendEncodedDataToTranscribe(
323
+ connection: WebSocket,
324
+ data: ConvertBytes | any[],
325
+ languageCode: string
326
+ ) {
310
327
  const downsampledBuffer = this.downsampleBuffer({
311
328
  buffer: data,
312
329
  outputSampleRate: LANGUAGES_CODE_IN_8KHZ.includes(languageCode)
313
330
  ? 8000
314
331
  : 16000,
315
332
  });
333
+
316
334
  const pcmEncodedBuffer = this.pcmEncode(downsampledBuffer);
317
335
  const audioEventMessage = this.getAudioEventMessage(
318
336
  Buffer.from(pcmEncodedBuffer)
319
337
  );
320
- const binary = eventBuilder.marshall(audioEventMessage);
338
+ const binary = eventBuilder.encode(audioEventMessage);
321
339
  connection.send(binary);
322
340
  }
323
341
 
324
- private getAudioEventMessage(buffer) {
342
+ private getAudioEventMessage(buffer: Buffer) {
325
343
  const audioEventMessage = {
326
344
  body: buffer as Uint8Array,
327
345
  headers: {
@@ -339,8 +357,13 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
339
357
  return audioEventMessage;
340
358
  }
341
359
 
342
- private pcmEncode(input) {
360
+ private pcmEncode(input: Float32Array | ConvertBytes | any[]) {
343
361
  let offset = 0;
362
+ // ArrayBuffer cannot be processed using length property
363
+ if (input instanceof ArrayBuffer) {
364
+ return input;
365
+ }
366
+
344
367
  const buffer = new ArrayBuffer(input.length * 2);
345
368
  const view = new DataView(buffer);
346
369
  for (let i = 0; i < input.length; i++, offset += 2) {
@@ -352,8 +375,18 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
352
375
 
353
376
  private inputSampleRate = 44100;
354
377
 
355
- private downsampleBuffer({ buffer, outputSampleRate = 16000 }) {
356
- if (outputSampleRate === this.inputSampleRate) {
378
+ private downsampleBuffer({
379
+ buffer,
380
+ outputSampleRate = 16000,
381
+ }: {
382
+ buffer: ConvertBytes | any[];
383
+ outputSampleRate: number;
384
+ }) {
385
+ // Cannot process ArrayBuffer using length property
386
+ if (
387
+ outputSampleRate === this.inputSampleRate ||
388
+ buffer instanceof ArrayBuffer
389
+ ) {
357
390
  return buffer;
358
391
  }
359
392
 
@@ -383,23 +416,15 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
383
416
  }
384
417
 
385
418
  private openConnectionWithTranscribe({
386
- credentials: userCredentials,
419
+ credentials,
387
420
  region,
388
421
  languageCode,
422
+ }: {
423
+ credentials: AWSCredentials;
424
+ region: string;
425
+ languageCode: string;
389
426
  }): Promise<WebSocket> {
390
427
  return new Promise(async (res, rej) => {
391
- const {
392
- accessKeyId: access_key,
393
- secretAccessKey: secret_key,
394
- sessionToken: session_token,
395
- } = userCredentials;
396
-
397
- const credentials = {
398
- access_key,
399
- secret_key,
400
- session_token,
401
- };
402
-
403
428
  const signedUrl = this.generateTranscribeUrl({
404
429
  credentials,
405
430
  region,
@@ -417,7 +442,21 @@ export class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictio
417
442
  });
418
443
  }
419
444
 
420
- private generateTranscribeUrl({ credentials, region, languageCode }): string {
445
+ private generateTranscribeUrl({
446
+ credentials: { accessKeyId, secretAccessKey, sessionToken },
447
+ region,
448
+ languageCode,
449
+ }: {
450
+ credentials: AWSCredentials;
451
+ region: string;
452
+ languageCode: string;
453
+ }): string {
454
+ const credentials = {
455
+ access_key: accessKeyId,
456
+ secret_key: secretAccessKey,
457
+ session_token: sessionToken,
458
+ };
459
+
421
460
  const url = [
422
461
  `wss://transcribestreaming.${region}.amazonaws.com:8443`,
423
462
  '/stream-transcription-websocket?',