@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
@@ -0,0 +1,2 @@
1
+ import { PredictionsValidationErrorCode } from '../types/validation';
2
+ export declare function assertValidationError(assertion: boolean, name: PredictionsValidationErrorCode): asserts assertion;
@@ -0,0 +1,10 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { PredictionsError } from '../PredictionsError';
4
+ import { validationErrorMap, } from '../types/validation';
5
+ export function assertValidationError(assertion, name) {
6
+ if (!assertion) {
7
+ const { message, recoverySuggestion } = validationErrorMap[name];
8
+ throw new PredictionsError({ name, message, recoverySuggestion });
9
+ }
10
+ }
@@ -1,4 +1,2 @@
1
- import { Predictions } from './Predictions';
2
- import { AmazonAIConvertPredictionsProvider, AmazonAIIdentifyPredictionsProvider, AmazonAIPredictionsProvider, AmazonAIInterpretPredictionsProvider } from './Providers';
3
- export * from './types';
4
- export { Predictions, AmazonAIIdentifyPredictionsProvider, AmazonAIConvertPredictionsProvider, AmazonAIPredictionsProvider, AmazonAIInterpretPredictionsProvider, };
1
+ export { Predictions } from './Predictions';
2
+ export { IdentifyEntitiesInput, IdentifyEntitiesOutput, IdentifyLabelsInput, IdentifyLabelsOutput, IdentifyTextInput, IdentifyTextOutput, InterpretTextInput, InterpretTextOutput, SpeechToTextInput, SpeechToTextOutput, TextToSpeechInput, TextToSpeechOutput, TranslateTextInput, TranslateTextOutput, } from './types';
package/lib-esm/index.js CHANGED
@@ -1,7 +1,3 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { Predictions } from './Predictions';
4
- import { AmazonAIConvertPredictionsProvider, AmazonAIIdentifyPredictionsProvider, AmazonAIPredictionsProvider, AmazonAIInterpretPredictionsProvider, } from './Providers';
5
- export * from './types';
6
- export { Predictions, AmazonAIIdentifyPredictionsProvider, AmazonAIConvertPredictionsProvider, AmazonAIPredictionsProvider, AmazonAIInterpretPredictionsProvider, };
7
- //# sourceMappingURL=index.js.map
3
+ export { Predictions } from './Predictions';
@@ -1,14 +1,13 @@
1
- import { AbstractConvertPredictionsProvider } from '../types/Providers/AbstractConvertPredictionsProvider';
2
- import { TranslateTextInput, TextToSpeechInput, SpeechToTextInput, TranslateTextOutput, TextToSpeechOutput, SpeechToTextOutput } from '../types';
3
- export declare class AmazonAIConvertPredictionsProvider extends AbstractConvertPredictionsProvider {
4
- private translateClient;
5
- private pollyClient;
6
- constructor();
1
+ import { SpeechToTextInput, SpeechToTextOutput, TextToSpeechInput, TextToSpeechOutput, TranslateTextInput, TranslateTextOutput } from '../types';
2
+ export declare class AmazonAIConvertPredictionsProvider {
3
+ private translateClient?;
4
+ private pollyClient?;
7
5
  getProviderName(): string;
6
+ convert(input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput): Promise<TextToSpeechOutput | TranslateTextOutput | SpeechToTextOutput>;
8
7
  protected translateText(input: TranslateTextInput): Promise<TranslateTextOutput>;
9
8
  protected convertTextToSpeech(input: TextToSpeechInput): Promise<TextToSpeechOutput>;
10
9
  protected convertSpeechToText(input: SpeechToTextInput): Promise<SpeechToTextOutput>;
11
- static serializeDataFromTranscribe(message: any): string;
10
+ static serializeDataFromTranscribe(message: MessageEvent): string;
12
11
  private sendDataToTranscribe;
13
12
  private sendEncodedDataToTranscribe;
14
13
  private getAudioEventMessage;
@@ -0,0 +1,303 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Amplify, ConsoleLogger as Logger, fetchAuthSession, } from '@aws-amplify/core';
4
+ import { Category, PredictionsAction, Signer, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';
5
+ import { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';
6
+ import { TranslateClient, TranslateTextCommand, } from '@aws-sdk/client-translate';
7
+ import { EventStreamCodec, } from '@smithy/eventstream-codec';
8
+ import { fromUtf8, toUtf8 } from '@smithy/util-utf8';
9
+ import { Buffer } from 'buffer';
10
+ import { PredictionsValidationErrorCode } from '../errors/types/validation';
11
+ import { assertValidationError } from '../errors/utils/assertValidationError';
12
+ import { isConvertBytesSource, isTextToSpeechInput, isTranslateTextInput, isValidConvertInput, } from '../types';
13
+ const logger = new Logger('AmazonAIConvertPredictionsProvider');
14
+ const eventBuilder = new EventStreamCodec(toUtf8, fromUtf8);
15
+ const LANGUAGES_CODE_IN_8KHZ = ['fr-FR', 'en-AU', 'en-GB', 'fr-CA'];
16
+ export class AmazonAIConvertPredictionsProvider {
17
+ constructor() {
18
+ this.inputSampleRate = 44100;
19
+ }
20
+ getProviderName() {
21
+ return 'AmazonAIConvertPredictionsProvider';
22
+ }
23
+ convert(input) {
24
+ assertValidationError(isValidConvertInput(input), PredictionsValidationErrorCode.InvalidInput);
25
+ if (isTranslateTextInput(input)) {
26
+ logger.debug('translateText');
27
+ return this.translateText(input);
28
+ }
29
+ else if (isTextToSpeechInput(input)) {
30
+ logger.debug('textToSpeech');
31
+ return this.convertTextToSpeech(input);
32
+ }
33
+ else {
34
+ logger.debug('textToSpeech');
35
+ return this.convertSpeechToText(input);
36
+ }
37
+ }
38
+ async translateText(input) {
39
+ logger.debug('Starting translation');
40
+ const { translateText = {} } = Amplify.getConfig().Predictions?.convert ?? {};
41
+ assertValidationError(!!translateText.region, PredictionsValidationErrorCode.NoRegion);
42
+ const { defaults = {}, region } = translateText;
43
+ const { credentials } = await fetchAuthSession();
44
+ assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);
45
+ const { sourceLanguage, targetLanguage } = defaults;
46
+ const sourceLanguageCode = input.translateText?.source?.language ?? sourceLanguage;
47
+ const targetLanguageCode = input.translateText?.targetLanguage ?? targetLanguage;
48
+ assertValidationError(!!sourceLanguageCode, PredictionsValidationErrorCode.NoSourceLanguage);
49
+ assertValidationError(!!targetLanguageCode, PredictionsValidationErrorCode.NoTargetLanguage);
50
+ this.translateClient = new TranslateClient({
51
+ region,
52
+ credentials,
53
+ customUserAgent: getAmplifyUserAgentObject({
54
+ category: Category.Predictions,
55
+ action: PredictionsAction.Convert,
56
+ }),
57
+ });
58
+ const translateTextCommand = new TranslateTextCommand({
59
+ SourceLanguageCode: sourceLanguageCode,
60
+ TargetLanguageCode: targetLanguageCode,
61
+ Text: input.translateText?.source?.text,
62
+ });
63
+ const data = await this.translateClient.send(translateTextCommand);
64
+ return {
65
+ text: data.TranslatedText,
66
+ language: data.TargetLanguageCode,
67
+ };
68
+ }
69
+ async convertTextToSpeech(input) {
70
+ const { credentials } = await fetchAuthSession();
71
+ assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);
72
+ assertValidationError(!!input.textToSpeech?.source, PredictionsValidationErrorCode.NoSource);
73
+ const { speechGenerator } = Amplify.getConfig().Predictions?.convert ?? {};
74
+ assertValidationError(!!speechGenerator?.region, PredictionsValidationErrorCode.NoRegion);
75
+ const { defaults = {}, region } = speechGenerator;
76
+ const { voiceId: defaultVoiceId } = defaults;
77
+ const voiceId = input.textToSpeech?.voiceId ?? defaultVoiceId;
78
+ assertValidationError(!!voiceId, PredictionsValidationErrorCode.NoVoiceId);
79
+ this.pollyClient = new PollyClient({
80
+ region,
81
+ credentials,
82
+ customUserAgent: getAmplifyUserAgentObject({
83
+ category: Category.Predictions,
84
+ action: PredictionsAction.Convert,
85
+ }),
86
+ });
87
+ const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
88
+ OutputFormat: 'mp3',
89
+ Text: input.textToSpeech?.source?.text,
90
+ VoiceId: voiceId,
91
+ TextType: 'text',
92
+ SampleRate: '24000',
93
+ // tslint:disable-next-line: align
94
+ });
95
+ const data = await this.pollyClient.send(synthesizeSpeechCommand);
96
+ const response = new Response(data.AudioStream);
97
+ const arrayBuffer = await response.arrayBuffer();
98
+ const blob = new Blob([arrayBuffer], {
99
+ type: data.ContentType,
100
+ });
101
+ const url = URL.createObjectURL(blob);
102
+ return {
103
+ speech: { url },
104
+ audioStream: arrayBuffer,
105
+ text: input.textToSpeech?.source?.text,
106
+ };
107
+ }
108
+ async convertSpeechToText(input) {
109
+ logger.debug('starting transcription..');
110
+ const { credentials } = await fetchAuthSession();
111
+ assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);
112
+ const { transcription } = Amplify.getConfig().Predictions?.convert ?? {};
113
+ assertValidationError(!!transcription?.region, PredictionsValidationErrorCode.NoRegion);
114
+ const { defaults, region } = transcription;
115
+ const language = input.transcription?.language ?? defaults?.language;
116
+ assertValidationError(!!language, PredictionsValidationErrorCode.NoLanguage);
117
+ const source = input.transcription?.source;
118
+ assertValidationError(isConvertBytesSource(source), PredictionsValidationErrorCode.InvalidSource);
119
+ const connection = await this.openConnectionWithTranscribe({
120
+ credentials,
121
+ region,
122
+ languageCode: language,
123
+ });
124
+ const fullText = await this.sendDataToTranscribe({
125
+ connection,
126
+ raw: source.bytes,
127
+ languageCode: language,
128
+ });
129
+ return {
130
+ transcription: {
131
+ fullText,
132
+ },
133
+ };
134
+ }
135
+ static serializeDataFromTranscribe(message) {
136
+ let decodedMessage = '';
137
+ const transcribeMessage = eventBuilder.decode(Buffer.from(message.data));
138
+ const transcribeMessageJson = JSON.parse(toUtf8(transcribeMessage.body));
139
+ if (transcribeMessage.headers[':message-type'].value === 'exception') {
140
+ logger.debug('exception', JSON.stringify(transcribeMessageJson.Message, null, 2));
141
+ throw new Error(transcribeMessageJson.Message);
142
+ }
143
+ else if (transcribeMessage.headers[':message-type'].value === 'event') {
144
+ if (transcribeMessageJson.Transcript.Results.length > 0) {
145
+ if (transcribeMessageJson.Transcript.Results[0].Alternatives.length > 0) {
146
+ if (transcribeMessageJson.Transcript.Results[0].Alternatives[0]
147
+ .Transcript.length > 0) {
148
+ if (transcribeMessageJson.Transcript.Results[0].IsPartial === false) {
149
+ decodedMessage =
150
+ transcribeMessageJson.Transcript.Results[0].Alternatives[0]
151
+ .Transcript + '\n';
152
+ logger.debug({ decodedMessage });
153
+ }
154
+ else {
155
+ logger.debug({
156
+ transcript: transcribeMessageJson.Transcript.Results[0].Alternatives[0],
157
+ });
158
+ }
159
+ }
160
+ }
161
+ }
162
+ }
163
+ return decodedMessage;
164
+ }
165
+ sendDataToTranscribe({ connection, raw, languageCode, }) {
166
+ return new Promise((res, rej) => {
167
+ let fullText = '';
168
+ connection.onmessage = message => {
169
+ try {
170
+ const decodedMessage = AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe(message);
171
+ if (decodedMessage) {
172
+ fullText += decodedMessage + ' ';
173
+ }
174
+ }
175
+ catch (err) {
176
+ logger.debug(err);
177
+ rej(err);
178
+ }
179
+ };
180
+ connection.onerror = errorEvent => {
181
+ logger.debug({ errorEvent });
182
+ rej('failed to transcribe, network error');
183
+ };
184
+ connection.onclose = closeEvent => {
185
+ logger.debug({ closeEvent });
186
+ return res(fullText.trim());
187
+ };
188
+ logger.debug({ raw });
189
+ if (Array.isArray(raw)) {
190
+ for (let i = 0; i < raw.length - 1023; i += 1024) {
191
+ const data = raw.slice(i, i + 1024);
192
+ this.sendEncodedDataToTranscribe(connection, data, languageCode);
193
+ }
194
+ }
195
+ else {
196
+ // If Buffer
197
+ this.sendEncodedDataToTranscribe(connection, raw, languageCode);
198
+ }
199
+ // sending end frame
200
+ const endFrameEventMessage = this.getAudioEventMessage(Buffer.from([]));
201
+ const endFrameBinary = eventBuilder.encode(endFrameEventMessage);
202
+ connection.send(endFrameBinary);
203
+ });
204
+ }
205
+ sendEncodedDataToTranscribe(connection, data, languageCode) {
206
+ const downsampledBuffer = this.downsampleBuffer({
207
+ buffer: data,
208
+ outputSampleRate: LANGUAGES_CODE_IN_8KHZ.includes(languageCode)
209
+ ? 8000
210
+ : 16000,
211
+ });
212
+ const pcmEncodedBuffer = this.pcmEncode(downsampledBuffer);
213
+ const audioEventMessage = this.getAudioEventMessage(Buffer.from(pcmEncodedBuffer));
214
+ const binary = eventBuilder.encode(audioEventMessage);
215
+ connection.send(binary);
216
+ }
217
+ getAudioEventMessage(buffer) {
218
+ const audioEventMessage = {
219
+ body: buffer,
220
+ headers: {
221
+ ':message-type': {
222
+ type: 'string',
223
+ value: 'event',
224
+ },
225
+ ':event-type': {
226
+ type: 'string',
227
+ value: 'AudioEvent',
228
+ },
229
+ },
230
+ };
231
+ return audioEventMessage;
232
+ }
233
+ pcmEncode(input) {
234
+ let offset = 0;
235
+ // ArrayBuffer cannot be processed using length property
236
+ if (input instanceof ArrayBuffer) {
237
+ return input;
238
+ }
239
+ const buffer = new ArrayBuffer(input.length * 2);
240
+ const view = new DataView(buffer);
241
+ for (let i = 0; i < input.length; i++, offset += 2) {
242
+ const s = Math.max(-1, Math.min(1, input[i]));
243
+ view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
244
+ }
245
+ return buffer;
246
+ }
247
+ downsampleBuffer({ buffer, outputSampleRate = 16000, }) {
248
+ // Cannot process ArrayBuffer using length property
249
+ if (outputSampleRate === this.inputSampleRate ||
250
+ buffer instanceof ArrayBuffer) {
251
+ return buffer;
252
+ }
253
+ const sampleRateRatio = this.inputSampleRate / outputSampleRate;
254
+ const newLength = Math.round(buffer.length / sampleRateRatio);
255
+ const result = new Float32Array(newLength);
256
+ let offsetResult = 0;
257
+ let offsetBuffer = 0;
258
+ while (offsetResult < result.length) {
259
+ const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
260
+ let accum = 0, count = 0;
261
+ for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
262
+ accum += buffer[i];
263
+ count++;
264
+ }
265
+ result[offsetResult] = accum / count;
266
+ offsetResult++;
267
+ offsetBuffer = nextOffsetBuffer;
268
+ }
269
+ return result;
270
+ }
271
+ openConnectionWithTranscribe({ credentials, region, languageCode, }) {
272
+ return new Promise(async (res, rej) => {
273
+ const signedUrl = this.generateTranscribeUrl({
274
+ credentials,
275
+ region,
276
+ languageCode,
277
+ });
278
+ logger.debug('connecting...');
279
+ const connection = new WebSocket(signedUrl);
280
+ connection.binaryType = 'arraybuffer';
281
+ connection.onopen = () => {
282
+ logger.debug('connected');
283
+ res(connection);
284
+ };
285
+ });
286
+ }
287
+ generateTranscribeUrl({ credentials: { accessKeyId, secretAccessKey, sessionToken }, region, languageCode, }) {
288
+ const credentials = {
289
+ access_key: accessKeyId,
290
+ secret_key: secretAccessKey,
291
+ session_token: sessionToken,
292
+ };
293
+ const url = [
294
+ `wss://transcribestreaming.${region}.amazonaws.com:8443`,
295
+ '/stream-transcription-websocket?',
296
+ `media-encoding=pcm&`,
297
+ `sample-rate=${LANGUAGES_CODE_IN_8KHZ.includes(languageCode) ? '8000' : '16000'}&`,
298
+ `language-code=${languageCode}`,
299
+ ].join('');
300
+ const signedUrl = Signer.signUrl(url, credentials, { region, service: 'transcribe' }, 300);
301
+ return signedUrl;
302
+ }
303
+ }
@@ -1,10 +1,9 @@
1
- import { AbstractIdentifyPredictionsProvider } from '../types/Providers';
2
- import { IdentifyLabelsInput, IdentifyLabelsOutput, IdentifyEntitiesInput, IdentifyEntitiesOutput, IdentifyTextInput, IdentifyTextOutput } from '../types';
3
- export declare class AmazonAIIdentifyPredictionsProvider extends AbstractIdentifyPredictionsProvider {
4
- private rekognitionClient;
5
- private textractClient;
6
- constructor();
1
+ import { IdentifyEntitiesInput, IdentifyEntitiesOutput, IdentifyLabelsInput, IdentifyLabelsOutput, IdentifyTextInput, IdentifyTextOutput } from '../types';
2
+ export declare class AmazonAIIdentifyPredictionsProvider {
3
+ private rekognitionClient?;
4
+ private textractClient?;
7
5
  getProviderName(): string;
6
+ identify(input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput): Promise<IdentifyTextOutput | IdentifyLabelsOutput | IdentifyEntitiesOutput>;
8
7
  /**
9
8
  * Verify user input source and converts it into source object readable by Rekognition and Textract.
10
9
  * Note that Rekognition and Textract use the same source interface, so we need not worry about types.