@aws-amplify/predictions 6.0.22 → 6.0.23

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 (41) hide show
  1. package/dist/cjs/Predictions.js +2 -4
  2. package/dist/cjs/Predictions.js.map +1 -1
  3. package/dist/cjs/providers/AmazonAIConvertPredictionsProvider.js +9 -9
  4. package/dist/cjs/providers/AmazonAIConvertPredictionsProvider.js.map +1 -1
  5. package/dist/cjs/providers/AmazonAIIdentifyPredictionsProvider.js +25 -20
  6. package/dist/cjs/providers/AmazonAIIdentifyPredictionsProvider.js.map +1 -1
  7. package/dist/cjs/providers/AmazonAIInterpretPredictionsProvider.js +7 -7
  8. package/dist/cjs/providers/AmazonAIInterpretPredictionsProvider.js.map +1 -1
  9. package/dist/cjs/providers/IdentifyTextUtils.js +9 -9
  10. package/dist/cjs/providers/IdentifyTextUtils.js.map +1 -1
  11. package/dist/cjs/providers/Utils.js +6 -6
  12. package/dist/cjs/providers/Utils.js.map +1 -1
  13. package/dist/cjs/types/Predictions.js +15 -14
  14. package/dist/cjs/types/Predictions.js.map +1 -1
  15. package/dist/esm/Predictions.mjs +0 -2
  16. package/dist/esm/Predictions.mjs.map +1 -1
  17. package/dist/esm/providers/AmazonAIConvertPredictionsProvider.mjs +9 -9
  18. package/dist/esm/providers/AmazonAIConvertPredictionsProvider.mjs.map +1 -1
  19. package/dist/esm/providers/AmazonAIIdentifyPredictionsProvider.d.ts +6 -6
  20. package/dist/esm/providers/AmazonAIIdentifyPredictionsProvider.mjs +25 -20
  21. package/dist/esm/providers/AmazonAIIdentifyPredictionsProvider.mjs.map +1 -1
  22. package/dist/esm/providers/AmazonAIInterpretPredictionsProvider.mjs +7 -7
  23. package/dist/esm/providers/AmazonAIInterpretPredictionsProvider.mjs.map +1 -1
  24. package/dist/esm/providers/IdentifyTextUtils.mjs +9 -9
  25. package/dist/esm/providers/IdentifyTextUtils.mjs.map +1 -1
  26. package/dist/esm/providers/Utils.mjs +6 -6
  27. package/dist/esm/providers/Utils.mjs.map +1 -1
  28. package/dist/esm/types/AWSTypes.d.ts +2 -2
  29. package/dist/esm/types/Predictions.d.ts +30 -30
  30. package/dist/esm/types/Predictions.mjs +15 -14
  31. package/dist/esm/types/Predictions.mjs.map +1 -1
  32. package/package.json +6 -5
  33. package/src/Predictions.ts +2 -3
  34. package/src/providers/AmazonAIConvertPredictionsProvider.ts +20 -10
  35. package/src/providers/AmazonAIIdentifyPredictionsProvider.ts +41 -26
  36. package/src/providers/AmazonAIInterpretPredictionsProvider.ts +22 -18
  37. package/src/providers/IdentifyTextUtils.ts +25 -22
  38. package/src/providers/Utils.ts +8 -6
  39. package/src/providers/index.ts +1 -0
  40. package/src/types/AWSTypes.ts +2 -3
  41. package/src/types/Predictions.ts +60 -44
@@ -1 +1 @@
1
- {"version":3,"file":"AmazonAIConvertPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIConvertPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, Signer, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';\nimport { TranslateClient, TranslateTextCommand, } from '@aws-sdk/client-translate';\nimport { EventStreamCodec, } from '@smithy/eventstream-codec';\nimport { fromUtf8, toUtf8 } from '@smithy/util-utf8';\nimport { Buffer } from 'buffer';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isConvertBytesSource, isTextToSpeechInput, isTranslateTextInput, isValidConvertInput, } from '../types';\nconst logger = new ConsoleLogger('AmazonAIConvertPredictionsProvider');\nconst eventBuilder = new EventStreamCodec(toUtf8, fromUtf8);\nconst LANGUAGES_CODE_IN_8KHZ = ['fr-FR', 'en-AU', 'en-GB', 'fr-CA'];\nexport class AmazonAIConvertPredictionsProvider {\n constructor() {\n this.inputSampleRate = 44100;\n }\n getProviderName() {\n return 'AmazonAIConvertPredictionsProvider';\n }\n convert(input) {\n assertValidationError(isValidConvertInput(input), PredictionsValidationErrorCode.InvalidInput);\n if (isTranslateTextInput(input)) {\n logger.debug('translateText');\n return this.translateText(input);\n }\n else if (isTextToSpeechInput(input)) {\n logger.debug('textToSpeech');\n return this.convertTextToSpeech(input);\n }\n else {\n logger.debug('textToSpeech');\n return this.convertSpeechToText(input);\n }\n }\n async translateText(input) {\n logger.debug('Starting translation');\n const { translateText = {} } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!translateText.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults = {}, region } = translateText;\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { sourceLanguage, targetLanguage } = defaults;\n const sourceLanguageCode = input.translateText?.source?.language ?? sourceLanguage;\n const targetLanguageCode = input.translateText?.targetLanguage ?? targetLanguage;\n assertValidationError(!!sourceLanguageCode, PredictionsValidationErrorCode.NoSourceLanguage);\n assertValidationError(!!targetLanguageCode, PredictionsValidationErrorCode.NoTargetLanguage);\n this.translateClient = new TranslateClient({\n region,\n credentials,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Convert,\n }),\n });\n const translateTextCommand = new TranslateTextCommand({\n SourceLanguageCode: sourceLanguageCode,\n TargetLanguageCode: targetLanguageCode,\n Text: input.translateText?.source?.text,\n });\n const data = await this.translateClient.send(translateTextCommand);\n return {\n text: data.TranslatedText,\n language: data.TargetLanguageCode,\n };\n }\n async convertTextToSpeech(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n assertValidationError(!!input.textToSpeech?.source, PredictionsValidationErrorCode.NoSource);\n const { speechGenerator } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!speechGenerator?.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults = {}, region } = speechGenerator;\n const { voiceId: defaultVoiceId } = defaults;\n const voiceId = input.textToSpeech?.voiceId ?? defaultVoiceId;\n assertValidationError(!!voiceId, PredictionsValidationErrorCode.NoVoiceId);\n this.pollyClient = new PollyClient({\n region,\n credentials,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Convert,\n }),\n });\n const synthesizeSpeechCommand = new SynthesizeSpeechCommand({\n OutputFormat: 'mp3',\n Text: input.textToSpeech?.source?.text,\n VoiceId: voiceId,\n TextType: 'text',\n SampleRate: '24000',\n // tslint:disable-next-line: align\n });\n const data = await this.pollyClient.send(synthesizeSpeechCommand);\n const response = new Response(data.AudioStream);\n const arrayBuffer = await response.arrayBuffer();\n const blob = new Blob([arrayBuffer], {\n type: data.ContentType,\n });\n const url = URL.createObjectURL(blob);\n return {\n speech: { url },\n audioStream: arrayBuffer,\n text: input.textToSpeech?.source?.text,\n };\n }\n async convertSpeechToText(input) {\n logger.debug('starting transcription..');\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { transcription } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!transcription?.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults, region } = transcription;\n const language = input.transcription?.language ?? defaults?.language;\n assertValidationError(!!language, PredictionsValidationErrorCode.NoLanguage);\n const source = input.transcription?.source;\n assertValidationError(isConvertBytesSource(source), PredictionsValidationErrorCode.InvalidSource);\n const connection = await this.openConnectionWithTranscribe({\n credentials,\n region,\n languageCode: language,\n });\n const fullText = await this.sendDataToTranscribe({\n connection,\n raw: source.bytes,\n languageCode: language,\n });\n return {\n transcription: {\n fullText,\n },\n };\n }\n static serializeDataFromTranscribe(message) {\n let decodedMessage = '';\n const transcribeMessage = eventBuilder.decode(Buffer.from(message.data));\n const transcribeMessageJson = JSON.parse(toUtf8(transcribeMessage.body));\n if (transcribeMessage.headers[':message-type'].value === 'exception') {\n logger.debug('exception', JSON.stringify(transcribeMessageJson.Message, null, 2));\n throw new Error(transcribeMessageJson.Message);\n }\n else if (transcribeMessage.headers[':message-type'].value === 'event') {\n if (transcribeMessageJson.Transcript.Results.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].Alternatives.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].Alternatives[0]\n .Transcript.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].IsPartial === false) {\n decodedMessage =\n transcribeMessageJson.Transcript.Results[0].Alternatives[0]\n .Transcript + '\\n';\n logger.debug({ decodedMessage });\n }\n else {\n logger.debug({\n transcript: transcribeMessageJson.Transcript.Results[0].Alternatives[0],\n });\n }\n }\n }\n }\n }\n return decodedMessage;\n }\n sendDataToTranscribe({ connection, raw, languageCode, }) {\n return new Promise((res, rej) => {\n let fullText = '';\n connection.onmessage = message => {\n try {\n const decodedMessage = AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe(message);\n if (decodedMessage) {\n fullText += decodedMessage + ' ';\n }\n }\n catch (err) {\n logger.debug(err);\n rej(err);\n }\n };\n connection.onerror = errorEvent => {\n logger.debug({ errorEvent });\n rej('failed to transcribe, network error');\n };\n connection.onclose = closeEvent => {\n logger.debug({ closeEvent });\n return res(fullText.trim());\n };\n logger.debug({ raw });\n if (Array.isArray(raw)) {\n for (let i = 0; i < raw.length - 1023; i += 1024) {\n const data = raw.slice(i, i + 1024);\n this.sendEncodedDataToTranscribe(connection, data, languageCode);\n }\n }\n else {\n // If Buffer\n this.sendEncodedDataToTranscribe(connection, raw, languageCode);\n }\n // sending end frame\n const endFrameEventMessage = this.getAudioEventMessage(Buffer.from([]));\n const endFrameBinary = eventBuilder.encode(endFrameEventMessage);\n connection.send(endFrameBinary);\n });\n }\n sendEncodedDataToTranscribe(connection, data, languageCode) {\n const downsampledBuffer = this.downsampleBuffer({\n buffer: data,\n outputSampleRate: LANGUAGES_CODE_IN_8KHZ.includes(languageCode)\n ? 8000\n : 16000,\n });\n const pcmEncodedBuffer = this.pcmEncode(downsampledBuffer);\n const audioEventMessage = this.getAudioEventMessage(Buffer.from(pcmEncodedBuffer));\n const binary = eventBuilder.encode(audioEventMessage);\n connection.send(binary);\n }\n getAudioEventMessage(buffer) {\n const audioEventMessage = {\n body: buffer,\n headers: {\n ':message-type': {\n type: 'string',\n value: 'event',\n },\n ':event-type': {\n type: 'string',\n value: 'AudioEvent',\n },\n },\n };\n return audioEventMessage;\n }\n pcmEncode(input) {\n let offset = 0;\n // ArrayBuffer cannot be processed using length property\n if (input instanceof ArrayBuffer) {\n return input;\n }\n const buffer = new ArrayBuffer(input.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < input.length; i++, offset += 2) {\n const s = Math.max(-1, Math.min(1, input[i]));\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n downsampleBuffer({ buffer, outputSampleRate = 16000, }) {\n // Cannot process ArrayBuffer using length property\n if (outputSampleRate === this.inputSampleRate ||\n buffer instanceof ArrayBuffer) {\n return buffer;\n }\n const sampleRateRatio = this.inputSampleRate / outputSampleRate;\n const newLength = Math.round(buffer.length / sampleRateRatio);\n const result = new Float32Array(newLength);\n let offsetResult = 0;\n let offsetBuffer = 0;\n while (offsetResult < result.length) {\n const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);\n let accum = 0, count = 0;\n for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {\n accum += buffer[i];\n count++;\n }\n result[offsetResult] = accum / count;\n offsetResult++;\n offsetBuffer = nextOffsetBuffer;\n }\n return result;\n }\n openConnectionWithTranscribe({ credentials, region, languageCode, }) {\n return new Promise(async (res, rej) => {\n const signedUrl = this.generateTranscribeUrl({\n credentials,\n region,\n languageCode,\n });\n logger.debug('connecting...');\n const connection = new WebSocket(signedUrl);\n connection.binaryType = 'arraybuffer';\n connection.onopen = () => {\n logger.debug('connected');\n res(connection);\n };\n });\n }\n generateTranscribeUrl({ credentials: { accessKeyId, secretAccessKey, sessionToken }, region, languageCode, }) {\n const credentials = {\n access_key: accessKeyId,\n secret_key: secretAccessKey,\n session_token: sessionToken,\n };\n const url = [\n `wss://transcribestreaming.${region}.amazonaws.com:8443`,\n '/stream-transcription-websocket?',\n `media-encoding=pcm&`,\n `sample-rate=${LANGUAGES_CODE_IN_8KHZ.includes(languageCode) ? '8000' : '16000'}&`,\n `language-code=${languageCode}`,\n ].join('');\n const signedUrl = Signer.signUrl(url, credentials, { region, service: 'transcribe' }, 300);\n return signedUrl;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AAWA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,oCAAoC,CAAC,CAAC;AACvE,MAAM,YAAY,GAAG,IAAI,gBAAgB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5D,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC7D,MAAM,kCAAkC,CAAC;AAChD,IAAI,WAAW,GAAG;AAClB,QAAQ,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;AACrC,KAAK;AACL,IAAI,eAAe,GAAG;AACtB,QAAQ,OAAO,oCAAoC,CAAC;AACpD,KAAK;AACL,IAAI,OAAO,CAAC,KAAK,EAAE;AACnB,QAAQ,qBAAqB,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAE,8BAA8B,CAAC,YAAY,CAAC,CAAC;AACvG,QAAQ,IAAI,oBAAoB,CAAC,KAAK,CAAC,EAAE;AACzC,YAAY,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;AAC1C,YAAY,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AAC7C,SAAS;AACT,aAAa,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;AAC7C,YAAY,MAAM,CAAC,KAAK,CAAC,cAA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AM;AACtC,gBAAgB,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;AAC1C,gBAAgB,GAAG,CAAC,UAAU,CAAC,CAAC;AAChC,aAAa,CAAC;AACd,SAAS,CAAC,CAAC;AACX,KAAK;AACL,IAAI,qBAAqB,CAAC,EAAE,WAAW,EAAE,EAAE,WAAW,EAAE,eAAe,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,YAAY,GAAG,EAAE;AAClH,QAAQ,MAAM,WAAW,GAAG;AAC5B,YAAY,UAAU,EAAE,WAAW;AACnC,YAAY,UAAU,EAAE,eAAe;AACvC,YAAY,aAAa,EAAE,YAAY;AACvC,SAAS,CAAC;AACV,QAAQ,MAAM,GAAG,GAAG;AACpB,YAAY,CAAC,0BAA0B,EAAE,MAAM,CAAC,mBAAmB,CAAC;AACpE,YAAY,kCAAkC;AAC9C,YAAY,CAAC,mBAAmB,CAAC;AACjC,YAAY,CAAC,YAAY,EAAE,sBAAsB,CAAC,QAAQ,CAAC,YAAY,CAAC,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC;AAC9F,YAAY,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;AAC3C,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACnB,QAAQ,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,GAAG,CAAC,CAAC;AACnG,QAAQ,OAAO,SAAS,CAAC;AACzB,KAAK;AACL;;;;"}
1
+ {"version":3,"file":"AmazonAIConvertPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIConvertPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Buffer } from 'buffer';\nimport { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, Signer, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { PollyClient, SynthesizeSpeechCommand } from '@aws-sdk/client-polly';\nimport { TranslateClient, TranslateTextCommand, } from '@aws-sdk/client-translate';\nimport { EventStreamCodec, } from '@smithy/eventstream-codec';\nimport { fromUtf8, toUtf8 } from '@smithy/util-utf8';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isConvertBytesSource, isTextToSpeechInput, isTranslateTextInput, isValidConvertInput, } from '../types';\nconst logger = new ConsoleLogger('AmazonAIConvertPredictionsProvider');\nconst eventBuilder = new EventStreamCodec(toUtf8, fromUtf8);\nconst LANGUAGES_CODE_IN_8KHZ = ['fr-FR', 'en-AU', 'en-GB', 'fr-CA'];\nexport class AmazonAIConvertPredictionsProvider {\n constructor() {\n this.inputSampleRate = 44100;\n }\n getProviderName() {\n return 'AmazonAIConvertPredictionsProvider';\n }\n convert(input) {\n assertValidationError(isValidConvertInput(input), PredictionsValidationErrorCode.InvalidInput);\n if (isTranslateTextInput(input)) {\n logger.debug('translateText');\n return this.translateText(input);\n }\n else if (isTextToSpeechInput(input)) {\n logger.debug('textToSpeech');\n return this.convertTextToSpeech(input);\n }\n else {\n logger.debug('textToSpeech');\n return this.convertSpeechToText(input);\n }\n }\n async translateText(input) {\n logger.debug('Starting translation');\n const { translateText = {} } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!translateText.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults = {}, region } = translateText;\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { sourceLanguage, targetLanguage } = defaults;\n const sourceLanguageCode = input.translateText?.source?.language ?? sourceLanguage;\n const targetLanguageCode = input.translateText?.targetLanguage ?? targetLanguage;\n assertValidationError(!!sourceLanguageCode, PredictionsValidationErrorCode.NoSourceLanguage);\n assertValidationError(!!targetLanguageCode, PredictionsValidationErrorCode.NoTargetLanguage);\n this.translateClient = new TranslateClient({\n region,\n credentials,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Convert,\n }),\n });\n const translateTextCommand = new TranslateTextCommand({\n SourceLanguageCode: sourceLanguageCode,\n TargetLanguageCode: targetLanguageCode,\n Text: input.translateText?.source?.text,\n });\n const data = await this.translateClient.send(translateTextCommand);\n return {\n text: data.TranslatedText,\n language: data.TargetLanguageCode,\n };\n }\n async convertTextToSpeech(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n assertValidationError(!!input.textToSpeech?.source, PredictionsValidationErrorCode.NoSource);\n const { speechGenerator } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!speechGenerator?.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults = {}, region } = speechGenerator;\n const { voiceId: defaultVoiceId } = defaults;\n const voiceId = input.textToSpeech?.voiceId ?? defaultVoiceId;\n assertValidationError(!!voiceId, PredictionsValidationErrorCode.NoVoiceId);\n this.pollyClient = new PollyClient({\n region,\n credentials,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Convert,\n }),\n });\n const synthesizeSpeechCommand = new SynthesizeSpeechCommand({\n OutputFormat: 'mp3',\n Text: input.textToSpeech?.source?.text,\n VoiceId: voiceId,\n TextType: 'text',\n SampleRate: '24000',\n });\n const data = await this.pollyClient.send(synthesizeSpeechCommand);\n const response = new Response(data.AudioStream);\n const arrayBuffer = await response.arrayBuffer();\n const blob = new Blob([arrayBuffer], {\n type: data.ContentType,\n });\n const url = URL.createObjectURL(blob);\n return {\n speech: { url },\n audioStream: arrayBuffer,\n text: input.textToSpeech?.source?.text,\n };\n }\n async convertSpeechToText(input) {\n logger.debug('starting transcription..');\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { transcription } = Amplify.getConfig().Predictions?.convert ?? {};\n assertValidationError(!!transcription?.region, PredictionsValidationErrorCode.NoRegion);\n const { defaults, region } = transcription;\n const language = input.transcription?.language ?? defaults?.language;\n assertValidationError(!!language, PredictionsValidationErrorCode.NoLanguage);\n const source = input.transcription?.source;\n assertValidationError(isConvertBytesSource(source), PredictionsValidationErrorCode.InvalidSource);\n const connection = await this.openConnectionWithTranscribe({\n credentials,\n region,\n languageCode: language,\n });\n const fullText = await this.sendDataToTranscribe({\n connection,\n raw: source.bytes,\n languageCode: language,\n });\n return {\n transcription: {\n fullText,\n },\n };\n }\n static serializeDataFromTranscribe(message) {\n let decodedMessage = '';\n const transcribeMessage = eventBuilder.decode(Buffer.from(message.data));\n const transcribeMessageJson = JSON.parse(toUtf8(transcribeMessage.body));\n if (transcribeMessage.headers[':message-type'].value === 'exception') {\n logger.debug('exception', JSON.stringify(transcribeMessageJson.Message, null, 2));\n throw new Error(transcribeMessageJson.Message);\n }\n else if (transcribeMessage.headers[':message-type'].value === 'event') {\n if (transcribeMessageJson.Transcript.Results.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].Alternatives.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].Alternatives[0]\n .Transcript.length > 0) {\n if (transcribeMessageJson.Transcript.Results[0].IsPartial === false) {\n decodedMessage =\n transcribeMessageJson.Transcript.Results[0].Alternatives[0]\n .Transcript + '\\n';\n logger.debug({ decodedMessage });\n }\n else {\n logger.debug({\n transcript: transcribeMessageJson.Transcript.Results[0].Alternatives[0],\n });\n }\n }\n }\n }\n }\n return decodedMessage;\n }\n sendDataToTranscribe({ connection, raw, languageCode, }) {\n return new Promise((resolve, reject) => {\n let fullText = '';\n connection.onmessage = message => {\n try {\n const decodedMessage = AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe(message);\n if (decodedMessage) {\n fullText += decodedMessage + ' ';\n }\n }\n catch (err) {\n logger.debug(err);\n reject(err);\n }\n };\n connection.onerror = errorEvent => {\n logger.debug({ errorEvent });\n reject(new Error('failed to transcribe, network error'));\n };\n connection.onclose = closeEvent => {\n logger.debug({ closeEvent });\n resolve(fullText.trim());\n };\n logger.debug({ raw });\n if (Array.isArray(raw)) {\n for (let i = 0; i < raw.length - 1023; i += 1024) {\n const data = raw.slice(i, i + 1024);\n this.sendEncodedDataToTranscribe(connection, data, languageCode);\n }\n }\n else {\n // If Buffer\n this.sendEncodedDataToTranscribe(connection, raw, languageCode);\n }\n // sending end frame\n const endFrameEventMessage = this.getAudioEventMessage(Buffer.from([]));\n const endFrameBinary = eventBuilder.encode(endFrameEventMessage);\n connection.send(endFrameBinary);\n });\n }\n sendEncodedDataToTranscribe(connection, data, languageCode) {\n const downsampledBuffer = this.downsampleBuffer({\n buffer: data,\n outputSampleRate: LANGUAGES_CODE_IN_8KHZ.includes(languageCode)\n ? 8000\n : 16000,\n });\n const pcmEncodedBuffer = this.pcmEncode(downsampledBuffer);\n const audioEventMessage = this.getAudioEventMessage(Buffer.from(pcmEncodedBuffer));\n const binary = eventBuilder.encode(audioEventMessage);\n connection.send(binary);\n }\n getAudioEventMessage(buffer) {\n const audioEventMessage = {\n body: buffer,\n headers: {\n ':message-type': {\n type: 'string',\n value: 'event',\n },\n ':event-type': {\n type: 'string',\n value: 'AudioEvent',\n },\n },\n };\n return audioEventMessage;\n }\n pcmEncode(input) {\n let offset = 0;\n // ArrayBuffer cannot be processed using length property\n if (input instanceof ArrayBuffer) {\n return input;\n }\n const buffer = new ArrayBuffer(input.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < input.length; i++, offset += 2) {\n const s = Math.max(-1, Math.min(1, input[i]));\n view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n downsampleBuffer({ buffer, outputSampleRate = 16000, }) {\n // Cannot process ArrayBuffer using length property\n if (outputSampleRate === this.inputSampleRate ||\n buffer instanceof ArrayBuffer) {\n return buffer;\n }\n const sampleRateRatio = this.inputSampleRate / outputSampleRate;\n const newLength = Math.round(buffer.length / sampleRateRatio);\n const result = new Float32Array(newLength);\n let offsetResult = 0;\n let offsetBuffer = 0;\n while (offsetResult < result.length) {\n const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);\n let accum = 0;\n let count = 0;\n for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {\n accum += buffer[i];\n count++;\n }\n result[offsetResult] = accum / count;\n offsetResult++;\n offsetBuffer = nextOffsetBuffer;\n }\n return result;\n }\n openConnectionWithTranscribe({ credentials, region, languageCode, }) {\n return new Promise((resolve, _reject) => {\n const signedUrl = this.generateTranscribeUrl({\n credentials,\n region,\n languageCode,\n });\n logger.debug('connecting...');\n const connection = new WebSocket(signedUrl);\n connection.binaryType = 'arraybuffer';\n connection.onopen = () => {\n logger.debug('connected');\n resolve(connection);\n };\n });\n }\n generateTranscribeUrl({ credentials: { accessKeyId, secretAccessKey, sessionToken }, region, languageCode, }) {\n const credentials = {\n access_key: accessKeyId,\n secret_key: secretAccessKey,\n session_token: sessionToken,\n };\n const url = [\n `wss://transcribestreaming.${region}.amazonaws.com:8443`,\n '/stream-transcription-websocket?',\n `media-encoding=pcm&`,\n `sample-rate=${LANGUAGES_CODE_IN_8KHZ.includes(languageCode) ? '8000' : '16000'}&`,\n `language-code=${languageCode}`,\n ].join('');\n const signedUrl = Signer.signUrl(url, credentials, { region, service: 'transcribe' }, 300);\n return signedUrl;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AAWA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,oCAAoC,CAAC,CAAC;AACvE,MAAM,YAAY,GAAG,IAAI,gBAAgB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC5D,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAC7D,MAAM,kCAAkC,CAAC;AAChD,IAAI,WAAW,GAAG;AAClB,QAAQ,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;AACrC,KAAK;AACL,IA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IAAI,CAAC,EAAE,CAAC,CAAC;AACnB,QAAQ,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,WAAW,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,GAAG,CAAC,CAAC;AACnG,QAAQ,OAAO,SAAS,CAAC;AACzB,KAAK;AACL;;;;"}
@@ -27,21 +27,21 @@ export declare class AmazonAIIdentifyPredictionsProvider {
27
27
  protected identifyLabels(input: IdentifyLabelsInput): Promise<IdentifyLabelsOutput>;
28
28
  /**
29
29
  * Calls Rekognition.detectLabels and organizes the returned data.
30
- * @param {DetectLabelsInput} param - parameter to be passed onto Rekognition
31
- * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectLabels response.
30
+ * @param param - parameters as {@link DetectLabelsCommandInput} to be passed onto Rekognition
31
+ * @return a promise resolving to organized detectLabels response as {@link IdentifyLabelsOutput}.
32
32
  */
33
33
  private detectLabels;
34
34
  /**
35
35
  * Calls Rekognition.detectModerationLabels and organizes the returned data.
36
- * @param {Rekognition.DetectLabelsRequest} param - Parameter to be passed onto Rekognition
37
- * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectModerationLabels response.
36
+ * @param param parameter to be passed onto Rekognition as {@link DetectModerationLabelsCommandInput}
37
+ * @return a promise resolving to organized detectModerationLabels response as {@link IdentifyLabelsOutput}.
38
38
  */
39
39
  private detectModerationLabels;
40
40
  /**
41
41
  * Identify faces within an image that is provided as input, and match faces from a collection
42
42
  * or identify celebrities.
43
- * @param {IdentifyEntityInput} input - object containing the source image and face match options.
44
- * @return {Promise<IdentifyEntityOutput>} Promise resolving to identify results.
43
+ * @param input - object of {@link IdentifyEntitiesInput} containing the source image and face match options.
44
+ * @return a promise resolving to identify results as {@link IdentifyEntitiesOutput}.
45
45
  */
46
46
  protected identifyEntities(input: IdentifyEntitiesInput): Promise<IdentifyEntitiesOutput>;
47
47
  private decodeExternalImageId;
@@ -39,7 +39,7 @@ class AmazonAIIdentifyPredictionsProvider {
39
39
  * @return {Promise<Image>} - Promise resolving to the converted source object.
40
40
  */
41
41
  configureSource(source) {
42
- return new Promise((res, rej) => {
42
+ return new Promise((resolve, reject) => {
43
43
  if (isStorageSource(source)) {
44
44
  const storageConfig = {
45
45
  accessLevel: source.level,
@@ -50,40 +50,46 @@ class AmazonAIIdentifyPredictionsProvider {
50
50
  const parser = /https:\/\/([a-zA-Z0-9%\-_.]+)\.s3\.[A-Za-z0-9%\-._~]+\/([a-zA-Z0-9%\-._~/]+)\?/;
51
51
  const parsedURL = value.url.toString().match(parser) ?? '';
52
52
  if (parsedURL.length < 3)
53
- rej('Invalid S3 key was given.');
54
- res({
53
+ reject(new Error('Invalid S3 key was given.'));
54
+ resolve({
55
55
  S3Object: {
56
56
  Bucket: parsedURL[1],
57
57
  Name: decodeURIComponent(parsedURL[2]),
58
58
  },
59
59
  });
60
60
  })
61
- .catch(err => rej(err));
61
+ .catch(err => {
62
+ reject(err);
63
+ });
62
64
  }
63
65
  else if (isFileSource(source)) {
64
66
  blobToArrayBuffer(source.file)
65
67
  .then(buffer => {
66
- res({ Bytes: new Uint8Array(buffer) });
68
+ resolve({ Bytes: new Uint8Array(buffer) });
67
69
  })
68
- .catch(err => rej(err));
70
+ .catch(err => {
71
+ reject(err);
72
+ });
69
73
  }
70
74
  else if (isIdentifyBytesSource(source)) {
71
- const bytes = source.bytes;
75
+ const { bytes } = source;
72
76
  if (bytes instanceof Blob) {
73
77
  blobToArrayBuffer(bytes)
74
78
  .then(buffer => {
75
- res({ Bytes: new Uint8Array(buffer) });
79
+ resolve({ Bytes: new Uint8Array(buffer) });
76
80
  })
77
- .catch(err => rej(err));
81
+ .catch(err => {
82
+ reject(err);
83
+ });
78
84
  }
79
85
  if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) {
80
- res({ Bytes: new Uint8Array(bytes) });
86
+ resolve({ Bytes: new Uint8Array(bytes) });
81
87
  }
82
88
  // everything else can be directly passed to Rekognition / Textract.
83
- res({ Bytes: bytes });
89
+ resolve({ Bytes: bytes });
84
90
  }
85
91
  else {
86
- rej('Input source is not configured correctly.');
92
+ reject(new Error('Input source is not configured correctly.'));
87
93
  }
88
94
  });
89
95
  }
@@ -109,8 +115,7 @@ class AmazonAIIdentifyPredictionsProvider {
109
115
  credentials,
110
116
  customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),
111
117
  });
112
- let inputDocument;
113
- inputDocument = await this.configureSource(input.text?.source);
118
+ const inputDocument = await this.configureSource(input.text?.source);
114
119
  // get default value if format isn't specified in the input.
115
120
  const format = input.text?.format ?? configFormat;
116
121
  const featureTypes = []; // structures we want to analyze (e.g. [TABLES, FORMS]).
@@ -192,8 +197,8 @@ class AmazonAIIdentifyPredictionsProvider {
192
197
  }
193
198
  /**
194
199
  * Calls Rekognition.detectLabels and organizes the returned data.
195
- * @param {DetectLabelsInput} param - parameter to be passed onto Rekognition
196
- * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectLabels response.
200
+ * @param param - parameters as {@link DetectLabelsCommandInput} to be passed onto Rekognition
201
+ * @return a promise resolving to organized detectLabels response as {@link IdentifyLabelsOutput}.
197
202
  */
198
203
  async detectLabels(param) {
199
204
  const detectLabelsCommand = new DetectLabelsCommand(param);
@@ -215,8 +220,8 @@ class AmazonAIIdentifyPredictionsProvider {
215
220
  }
216
221
  /**
217
222
  * Calls Rekognition.detectModerationLabels and organizes the returned data.
218
- * @param {Rekognition.DetectLabelsRequest} param - Parameter to be passed onto Rekognition
219
- * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectModerationLabels response.
223
+ * @param param parameter to be passed onto Rekognition as {@link DetectModerationLabelsCommandInput}
224
+ * @return a promise resolving to organized detectModerationLabels response as {@link IdentifyLabelsOutput}.
220
225
  */
221
226
  async detectModerationLabels(param) {
222
227
  const detectModerationLabelsCommand = new DetectModerationLabelsCommand(param);
@@ -231,8 +236,8 @@ class AmazonAIIdentifyPredictionsProvider {
231
236
  /**
232
237
  * Identify faces within an image that is provided as input, and match faces from a collection
233
238
  * or identify celebrities.
234
- * @param {IdentifyEntityInput} input - object containing the source image and face match options.
235
- * @return {Promise<IdentifyEntityOutput>} Promise resolving to identify results.
239
+ * @param input - object of {@link IdentifyEntitiesInput} containing the source image and face match options.
240
+ * @return a promise resolving to identify results as {@link IdentifyEntitiesOutput}.
236
241
  */
237
242
  async identifyEntities(input) {
238
243
  const { credentials } = await fetchAuthSession();
@@ -1 +1 @@
1
- {"version":3,"file":"AmazonAIIdentifyPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIIdentifyPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { getUrl } from '@aws-amplify/storage';\nimport { DetectFacesCommand, DetectLabelsCommand, DetectModerationLabelsCommand, DetectTextCommand, RecognizeCelebritiesCommand, RekognitionClient, SearchFacesByImageCommand, } from '@aws-sdk/client-rekognition';\nimport { AnalyzeDocumentCommand, DetectDocumentTextCommand, TextractClient, } from '@aws-sdk/client-textract';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isFileSource, isIdentifyBytesSource, isIdentifyCelebrities, isIdentifyFromCollection, isIdentifyLabelsInput, isIdentifyTextInput, isStorageSource, isValidIdentifyInput, } from '../types';\nimport { categorizeRekognitionBlocks, categorizeTextractBlocks, } from './IdentifyTextUtils';\nimport { blobToArrayBuffer, makeCamelCase, makeCamelCaseArray } from './Utils';\nconst logger = new ConsoleLogger('AmazonAIIdentifyPredictionsProvider');\nexport class AmazonAIIdentifyPredictionsProvider {\n getProviderName() {\n return 'AmazonAIIdentifyPredictionsProvider';\n }\n identify(input) {\n assertValidationError(isValidIdentifyInput(input), PredictionsValidationErrorCode.InvalidInput);\n if (isIdentifyTextInput(input)) {\n logger.debug('identifyText');\n return this.identifyText(input);\n }\n else if (isIdentifyLabelsInput(input)) {\n logger.debug('identifyLabels');\n return this.identifyLabels(input);\n }\n else {\n logger.debug('identifyEntities');\n return this.identifyEntities(input);\n }\n }\n /**\n * Verify user input source and converts it into source object readable by Rekognition and Textract.\n * Note that Rekognition and Textract use the same source interface, so we need not worry about types.\n * @param {IdentifySource} source - User input source that directs to the object user wants\n * to identify (storage, file, or bytes).\n * @return {Promise<Image>} - Promise resolving to the converted source object.\n */\n configureSource(source) {\n return new Promise((res, rej) => {\n if (isStorageSource(source)) {\n const storageConfig = {\n accessLevel: source.level,\n targetIdentityId: source.identityId,\n };\n getUrl({ key: source.key, options: storageConfig })\n .then(value => {\n const parser = /https:\\/\\/([a-zA-Z0-9%\\-_.]+)\\.s3\\.[A-Za-z0-9%\\-._~]+\\/([a-zA-Z0-9%\\-._~/]+)\\?/;\n const parsedURL = value.url.toString().match(parser) ?? '';\n if (parsedURL.length < 3)\n rej('Invalid S3 key was given.');\n res({\n S3Object: {\n Bucket: parsedURL[1],\n Name: decodeURIComponent(parsedURL[2]),\n },\n });\n })\n .catch(err => rej(err));\n }\n else if (isFileSource(source)) {\n blobToArrayBuffer(source.file)\n .then(buffer => {\n res({ Bytes: new Uint8Array(buffer) });\n })\n .catch(err => rej(err));\n }\n else if (isIdentifyBytesSource(source)) {\n const bytes = source.bytes;\n if (bytes instanceof Blob) {\n blobToArrayBuffer(bytes)\n .then(buffer => {\n res({ Bytes: new Uint8Array(buffer) });\n })\n .catch(err => rej(err));\n }\n if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) {\n res({ Bytes: new Uint8Array(bytes) });\n }\n // everything else can be directly passed to Rekognition / Textract.\n res({ Bytes: bytes });\n }\n else {\n rej('Input source is not configured correctly.');\n }\n });\n }\n /**\n * Recognize text from real-world images and documents (plain text, forms and tables). Detects text in the input\n * image and converts it into machine-readable text.\n * @param {IdentifySource} source - Object containing the source image and feature types to analyze.\n * @return {Promise<IdentifyTextOutput>} - Promise resolving to object containing identified texts.\n */\n async identifyText(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyText = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', defaults = {} } = identifyText;\n const { format: configFormat = 'PLAIN' } = defaults;\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n this.textractClient = new TextractClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n let inputDocument;\n inputDocument = await this.configureSource(input.text?.source);\n // get default value if format isn't specified in the input.\n const format = input.text?.format ?? configFormat;\n const featureTypes = []; // structures we want to analyze (e.g. [TABLES, FORMS]).\n if (format === 'FORM' || format === 'ALL')\n featureTypes.push('FORMS');\n if (format === 'TABLE' || format === 'ALL')\n featureTypes.push('TABLES');\n if (featureTypes.length === 0) {\n /**\n * Empty featureTypes indicates that we will identify plain text. We will use rekognition (suitable\n * for everyday images but has 50 word limit) first and see if reaches its word limit. If it does, then\n * we call textract and use the data that identify more words.\n */\n const textractParam = {\n Document: inputDocument,\n };\n const rekognitionParam = {\n Image: inputDocument,\n };\n const detectTextCommand = new DetectTextCommand(rekognitionParam);\n const rekognitionData = await this.rekognitionClient.send(detectTextCommand);\n const rekognitionResponse = categorizeRekognitionBlocks(rekognitionData.TextDetections);\n if (rekognitionResponse.text.words.length < 50) {\n // did not hit the word limit, return the data\n return rekognitionResponse;\n }\n const detectDocumentTextCommand = new DetectDocumentTextCommand(textractParam);\n const { Blocks } = await this.textractClient.send(detectDocumentTextCommand);\n if ((rekognitionData.TextDetections?.length ?? 0) > (Blocks?.length ?? 0)) {\n return rekognitionResponse;\n }\n return categorizeTextractBlocks(Blocks);\n }\n else {\n const param = {\n Document: inputDocument,\n FeatureTypes: featureTypes,\n };\n const analyzeDocumentCommand = new AnalyzeDocumentCommand(param);\n const { Blocks } = await this.textractClient.send(analyzeDocumentCommand);\n return categorizeTextractBlocks(Blocks);\n }\n }\n /**\n * Identify instances of real world entities from an image and if it contains unsafe content.\n * @param {IdentifyLabelsInput} input - Object containing the source image and entity type to identify.\n * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to an array of identified entities.\n */\n async identifyLabels(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyLabels = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', defaults = {} } = identifyLabels;\n const { type = 'LABELS' } = defaults;\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n const inputImage = await this.configureSource(input.labels?.source);\n const param = { Image: inputImage };\n const servicePromises = [];\n // get default argument\n const entityType = input.labels?.type ?? type;\n if (entityType === 'LABELS' || entityType === 'ALL') {\n servicePromises.push(this.detectLabels(param));\n }\n if (entityType === 'UNSAFE' || entityType === 'ALL') {\n servicePromises.push(this.detectModerationLabels(param));\n }\n return Promise.all(servicePromises).then(data => {\n let identifyResult = {};\n // concatenate resolved promises to a single object\n data.forEach(val => {\n identifyResult = { ...identifyResult, ...val };\n });\n return identifyResult;\n });\n }\n /**\n * Calls Rekognition.detectLabels and organizes the returned data.\n * @param {DetectLabelsInput} param - parameter to be passed onto Rekognition\n * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectLabels response.\n */\n async detectLabels(param) {\n const detectLabelsCommand = new DetectLabelsCommand(param);\n const data = await this.rekognitionClient.send(detectLabelsCommand);\n if (!data.Labels)\n return {}; // no image was detected\n const detectLabelData = data.Labels.map(label => {\n const boxes = label.Instances?.map(instance => makeCamelCase(instance.BoundingBox)) || [];\n return {\n name: label.Name,\n boundingBoxes: boxes,\n metadata: {\n confidence: label.Confidence,\n parents: makeCamelCaseArray(label.Parents),\n },\n };\n });\n return { labels: detectLabelData };\n }\n /**\n * Calls Rekognition.detectModerationLabels and organizes the returned data.\n * @param {Rekognition.DetectLabelsRequest} param - Parameter to be passed onto Rekognition\n * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectModerationLabels response.\n */\n async detectModerationLabels(param) {\n const detectModerationLabelsCommand = new DetectModerationLabelsCommand(param);\n const data = await this.rekognitionClient.send(detectModerationLabelsCommand);\n if (data.ModerationLabels?.length !== 0) {\n return { unsafe: 'YES' };\n }\n else {\n return { unsafe: 'NO' };\n }\n }\n /**\n * Identify faces within an image that is provided as input, and match faces from a collection\n * or identify celebrities.\n * @param {IdentifyEntityInput} input - object containing the source image and face match options.\n * @return {Promise<IdentifyEntityOutput>} Promise resolving to identify results.\n */\n async identifyEntities(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyEntities = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', celebrityDetectionEnabled = false, defaults = {}, } = identifyEntities;\n const { collectionId: collectionIdConfig = '', maxEntities: maxFacesConfig = 50, } = defaults;\n // default arguments\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n const inputImage = await this.configureSource(input.entities?.source);\n const param = { Attributes: ['ALL'], Image: inputImage };\n if (isIdentifyCelebrities(input.entities) &&\n input.entities.celebrityDetection) {\n assertValidationError(celebrityDetectionEnabled, PredictionsValidationErrorCode.CelebrityDetectionNotEnabled);\n const recognizeCelebritiesCommand = new RecognizeCelebritiesCommand(param);\n const data = await this.rekognitionClient.send(recognizeCelebritiesCommand);\n const faces = data.CelebrityFaces?.map(celebrity => ({\n boundingBox: makeCamelCase(celebrity.Face?.BoundingBox),\n landmarks: makeCamelCaseArray(celebrity.Face?.Landmarks),\n metadata: {\n ...makeCamelCase(celebrity, ['Id', 'Name', 'Urls']),\n pose: makeCamelCase(celebrity.Face?.Pose),\n },\n })) ?? [];\n return { entities: faces };\n }\n else if (isIdentifyFromCollection(input.entities) &&\n input.entities.collection) {\n const { collectionId = collectionIdConfig, maxEntities: maxFaces = maxFacesConfig, } = input.entities;\n // Concatenate additional parameters\n const updatedParam = {\n ...param,\n CollectionId: collectionId,\n MaxFaces: maxFaces,\n };\n const searchFacesByImageCommand = new SearchFacesByImageCommand(updatedParam);\n const data = await this.rekognitionClient.send(searchFacesByImageCommand);\n const faces = data.FaceMatches?.map(match => {\n const externalImageId = match.Face?.ExternalImageId\n ? this.decodeExternalImageId(match.Face.ExternalImageId)\n : undefined;\n return {\n boundingBox: makeCamelCase(match.Face?.BoundingBox),\n metadata: {\n externalImageId,\n similarity: match.Similarity,\n },\n };\n }) ?? [];\n return { entities: faces };\n }\n else {\n const detectFacesCommand = new DetectFacesCommand(param);\n const data = await this.rekognitionClient.send(detectFacesCommand);\n const faces = data.FaceDetails?.map(detail => {\n // face attributes keys we want to extract from Rekognition's response\n const attributeKeys = [\n 'Smile',\n 'Eyeglasses',\n 'Sunglasses',\n 'Gender',\n 'Beard',\n 'Mustache',\n 'EyesOpen',\n 'MouthOpen',\n ];\n const faceAttributes = makeCamelCase(detail, attributeKeys);\n faceAttributes.emotions = detail.Emotions?.map(emotion => emotion.Type);\n return {\n boundingBox: makeCamelCase(detail.BoundingBox),\n landmarks: makeCamelCaseArray(detail.Landmarks),\n ageRange: makeCamelCase(detail.AgeRange),\n attributes: faceAttributes,\n metadata: {\n confidence: detail.Confidence,\n pose: makeCamelCase(detail.Pose),\n },\n };\n }) ?? [];\n return { entities: faces };\n }\n }\n decodeExternalImageId(externalImageId) {\n return ('' + externalImageId).replace(/::/g, '/');\n }\n}\nfunction _getPredictionsIdentifyAmplifyUserAgent() {\n return getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Identify,\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AAWA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,qCAAqC,CAAC,CAAC;A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CAAC;AACxF,gBAAgB,OAAO;AACvB,oBAAoB,WAAW,EAAE,aAAa,CAAC,MAAM,CAAC,WAAW,CAAC;AAClE,oBAAoB,SAAS,EAAE,kBAAkB,CAAC,MAAM,CAAC,SAAS,CAAC;AACnE,oBAAoB,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,QAAQ,CAAC;AAC5D,oBAAoB,UAAU,EAAE,cAAc;AAC9C,oBAAoB,QAAQ,EAAE;AAC9B,wBAAwB,UAAU,EAAE,MAAM,CAAC,UAAU;AACrD,wBAAwB,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC;AACxD,qBAAqB;AACrB,iBAAiB,CAAC;AAClB,aAAa,CAAC,IAAI,EAAE,CAAC;AACrB,YAAY,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACvC,SAAS;AACT,KAAK;AACL,IAAI,qBAAqB,CAAC,eAAe,EAAE;AAC3C,QAAQ,OAAO,CAAC,EAAE,GAAG,eAAe,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC1D,KAAK;AACL,CAAC;AACD,SAAS,uCAAuC,GAAG;AACnD,IAAI,OAAO,yBAAyB,CAAC;AACrC,QAAQ,QAAQ,EAAE,QAAQ,CAAC,WAAW;AACtC,QAAQ,MAAM,EAAE,iBAAiB,CAAC,QAAQ;AAC1C,KAAK,CAAC,CAAC;AACP;;;;"}
1
+ {"version":3,"file":"AmazonAIIdentifyPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIIdentifyPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { getUrl } from '@aws-amplify/storage';\nimport { DetectFacesCommand, DetectLabelsCommand, DetectModerationLabelsCommand, DetectTextCommand, RecognizeCelebritiesCommand, RekognitionClient, SearchFacesByImageCommand, } from '@aws-sdk/client-rekognition';\nimport { AnalyzeDocumentCommand, DetectDocumentTextCommand, TextractClient, } from '@aws-sdk/client-textract';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isFileSource, isIdentifyBytesSource, isIdentifyCelebrities, isIdentifyFromCollection, isIdentifyLabelsInput, isIdentifyTextInput, isStorageSource, isValidIdentifyInput, } from '../types';\nimport { categorizeRekognitionBlocks, categorizeTextractBlocks, } from './IdentifyTextUtils';\nimport { blobToArrayBuffer, makeCamelCase, makeCamelCaseArray } from './Utils';\nconst logger = new ConsoleLogger('AmazonAIIdentifyPredictionsProvider');\nexport class AmazonAIIdentifyPredictionsProvider {\n getProviderName() {\n return 'AmazonAIIdentifyPredictionsProvider';\n }\n identify(input) {\n assertValidationError(isValidIdentifyInput(input), PredictionsValidationErrorCode.InvalidInput);\n if (isIdentifyTextInput(input)) {\n logger.debug('identifyText');\n return this.identifyText(input);\n }\n else if (isIdentifyLabelsInput(input)) {\n logger.debug('identifyLabels');\n return this.identifyLabels(input);\n }\n else {\n logger.debug('identifyEntities');\n return this.identifyEntities(input);\n }\n }\n /**\n * Verify user input source and converts it into source object readable by Rekognition and Textract.\n * Note that Rekognition and Textract use the same source interface, so we need not worry about types.\n * @param {IdentifySource} source - User input source that directs to the object user wants\n * to identify (storage, file, or bytes).\n * @return {Promise<Image>} - Promise resolving to the converted source object.\n */\n configureSource(source) {\n return new Promise((resolve, reject) => {\n if (isStorageSource(source)) {\n const storageConfig = {\n accessLevel: source.level,\n targetIdentityId: source.identityId,\n };\n getUrl({ key: source.key, options: storageConfig })\n .then(value => {\n const parser = /https:\\/\\/([a-zA-Z0-9%\\-_.]+)\\.s3\\.[A-Za-z0-9%\\-._~]+\\/([a-zA-Z0-9%\\-._~/]+)\\?/;\n const parsedURL = value.url.toString().match(parser) ?? '';\n if (parsedURL.length < 3)\n reject(new Error('Invalid S3 key was given.'));\n resolve({\n S3Object: {\n Bucket: parsedURL[1],\n Name: decodeURIComponent(parsedURL[2]),\n },\n });\n })\n .catch(err => {\n reject(err);\n });\n }\n else if (isFileSource(source)) {\n blobToArrayBuffer(source.file)\n .then(buffer => {\n resolve({ Bytes: new Uint8Array(buffer) });\n })\n .catch(err => {\n reject(err);\n });\n }\n else if (isIdentifyBytesSource(source)) {\n const { bytes } = source;\n if (bytes instanceof Blob) {\n blobToArrayBuffer(bytes)\n .then(buffer => {\n resolve({ Bytes: new Uint8Array(buffer) });\n })\n .catch(err => {\n reject(err);\n });\n }\n if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) {\n resolve({ Bytes: new Uint8Array(bytes) });\n }\n // everything else can be directly passed to Rekognition / Textract.\n resolve({ Bytes: bytes });\n }\n else {\n reject(new Error('Input source is not configured correctly.'));\n }\n });\n }\n /**\n * Recognize text from real-world images and documents (plain text, forms and tables). Detects text in the input\n * image and converts it into machine-readable text.\n * @param {IdentifySource} source - Object containing the source image and feature types to analyze.\n * @return {Promise<IdentifyTextOutput>} - Promise resolving to object containing identified texts.\n */\n async identifyText(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyText = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', defaults = {} } = identifyText;\n const { format: configFormat = 'PLAIN' } = defaults;\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n this.textractClient = new TextractClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n const inputDocument = await this.configureSource(input.text?.source);\n // get default value if format isn't specified in the input.\n const format = input.text?.format ?? configFormat;\n const featureTypes = []; // structures we want to analyze (e.g. [TABLES, FORMS]).\n if (format === 'FORM' || format === 'ALL')\n featureTypes.push('FORMS');\n if (format === 'TABLE' || format === 'ALL')\n featureTypes.push('TABLES');\n if (featureTypes.length === 0) {\n /**\n * Empty featureTypes indicates that we will identify plain text. We will use rekognition (suitable\n * for everyday images but has 50 word limit) first and see if reaches its word limit. If it does, then\n * we call textract and use the data that identify more words.\n */\n const textractParam = {\n Document: inputDocument,\n };\n const rekognitionParam = {\n Image: inputDocument,\n };\n const detectTextCommand = new DetectTextCommand(rekognitionParam);\n const rekognitionData = await this.rekognitionClient.send(detectTextCommand);\n const rekognitionResponse = categorizeRekognitionBlocks(rekognitionData.TextDetections);\n if (rekognitionResponse.text.words.length < 50) {\n // did not hit the word limit, return the data\n return rekognitionResponse;\n }\n const detectDocumentTextCommand = new DetectDocumentTextCommand(textractParam);\n const { Blocks } = await this.textractClient.send(detectDocumentTextCommand);\n if ((rekognitionData.TextDetections?.length ?? 0) > (Blocks?.length ?? 0)) {\n return rekognitionResponse;\n }\n return categorizeTextractBlocks(Blocks);\n }\n else {\n const param = {\n Document: inputDocument,\n FeatureTypes: featureTypes,\n };\n const analyzeDocumentCommand = new AnalyzeDocumentCommand(param);\n const { Blocks } = await this.textractClient.send(analyzeDocumentCommand);\n return categorizeTextractBlocks(Blocks);\n }\n }\n /**\n * Identify instances of real world entities from an image and if it contains unsafe content.\n * @param {IdentifyLabelsInput} input - Object containing the source image and entity type to identify.\n * @return {Promise<IdentifyLabelsOutput>} - Promise resolving to an array of identified entities.\n */\n async identifyLabels(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyLabels = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', defaults = {} } = identifyLabels;\n const { type = 'LABELS' } = defaults;\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n const inputImage = await this.configureSource(input.labels?.source);\n const param = { Image: inputImage };\n const servicePromises = [];\n // get default argument\n const entityType = input.labels?.type ?? type;\n if (entityType === 'LABELS' || entityType === 'ALL') {\n servicePromises.push(this.detectLabels(param));\n }\n if (entityType === 'UNSAFE' || entityType === 'ALL') {\n servicePromises.push(this.detectModerationLabels(param));\n }\n return Promise.all(servicePromises).then(data => {\n let identifyResult = {};\n // concatenate resolved promises to a single object\n data.forEach(val => {\n identifyResult = { ...identifyResult, ...val };\n });\n return identifyResult;\n });\n }\n /**\n * Calls Rekognition.detectLabels and organizes the returned data.\n * @param param - parameters as {@link DetectLabelsCommandInput} to be passed onto Rekognition\n * @return a promise resolving to organized detectLabels response as {@link IdentifyLabelsOutput}.\n */\n async detectLabels(param) {\n const detectLabelsCommand = new DetectLabelsCommand(param);\n const data = await this.rekognitionClient.send(detectLabelsCommand);\n if (!data.Labels)\n return {}; // no image was detected\n const detectLabelData = data.Labels.map(label => {\n const boxes = label.Instances?.map(instance => makeCamelCase(instance.BoundingBox)) || [];\n return {\n name: label.Name,\n boundingBoxes: boxes,\n metadata: {\n confidence: label.Confidence,\n parents: makeCamelCaseArray(label.Parents),\n },\n };\n });\n return { labels: detectLabelData };\n }\n /**\n * Calls Rekognition.detectModerationLabels and organizes the returned data.\n * @param param parameter to be passed onto Rekognition as {@link DetectModerationLabelsCommandInput}\n * @return a promise resolving to organized detectModerationLabels response as {@link IdentifyLabelsOutput}.\n */\n async detectModerationLabels(param) {\n const detectModerationLabelsCommand = new DetectModerationLabelsCommand(param);\n const data = await this.rekognitionClient.send(detectModerationLabelsCommand);\n if (data.ModerationLabels?.length !== 0) {\n return { unsafe: 'YES' };\n }\n else {\n return { unsafe: 'NO' };\n }\n }\n /**\n * Identify faces within an image that is provided as input, and match faces from a collection\n * or identify celebrities.\n * @param input - object of {@link IdentifyEntitiesInput} containing the source image and face match options.\n * @return a promise resolving to identify results as {@link IdentifyEntitiesOutput}.\n */\n async identifyEntities(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { identifyEntities = {} } = Amplify.getConfig().Predictions?.identify ?? {};\n const { region = '', celebrityDetectionEnabled = false, defaults = {}, } = identifyEntities;\n const { collectionId: collectionIdConfig = '', maxEntities: maxFacesConfig = 50, } = defaults;\n // default arguments\n this.rekognitionClient = new RekognitionClient({\n region,\n credentials,\n customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),\n });\n const inputImage = await this.configureSource(input.entities?.source);\n const param = { Attributes: ['ALL'], Image: inputImage };\n if (isIdentifyCelebrities(input.entities) &&\n input.entities.celebrityDetection) {\n assertValidationError(celebrityDetectionEnabled, PredictionsValidationErrorCode.CelebrityDetectionNotEnabled);\n const recognizeCelebritiesCommand = new RecognizeCelebritiesCommand(param);\n const data = await this.rekognitionClient.send(recognizeCelebritiesCommand);\n const faces = data.CelebrityFaces?.map(celebrity => ({\n boundingBox: makeCamelCase(celebrity.Face?.BoundingBox),\n landmarks: makeCamelCaseArray(celebrity.Face?.Landmarks),\n metadata: {\n ...makeCamelCase(celebrity, ['Id', 'Name', 'Urls']),\n pose: makeCamelCase(celebrity.Face?.Pose),\n },\n })) ?? [];\n return { entities: faces };\n }\n else if (isIdentifyFromCollection(input.entities) &&\n input.entities.collection) {\n const { collectionId = collectionIdConfig, maxEntities: maxFaces = maxFacesConfig, } = input.entities;\n // Concatenate additional parameters\n const updatedParam = {\n ...param,\n CollectionId: collectionId,\n MaxFaces: maxFaces,\n };\n const searchFacesByImageCommand = new SearchFacesByImageCommand(updatedParam);\n const data = await this.rekognitionClient.send(searchFacesByImageCommand);\n const faces = data.FaceMatches?.map(match => {\n const externalImageId = match.Face?.ExternalImageId\n ? this.decodeExternalImageId(match.Face.ExternalImageId)\n : undefined;\n return {\n boundingBox: makeCamelCase(match.Face?.BoundingBox),\n metadata: {\n externalImageId,\n similarity: match.Similarity,\n },\n };\n }) ?? [];\n return { entities: faces };\n }\n else {\n const detectFacesCommand = new DetectFacesCommand(param);\n const data = await this.rekognitionClient.send(detectFacesCommand);\n const faces = data.FaceDetails?.map(detail => {\n // face attributes keys we want to extract from Rekognition's response\n const attributeKeys = [\n 'Smile',\n 'Eyeglasses',\n 'Sunglasses',\n 'Gender',\n 'Beard',\n 'Mustache',\n 'EyesOpen',\n 'MouthOpen',\n ];\n const faceAttributes = makeCamelCase(detail, attributeKeys);\n faceAttributes.emotions = detail.Emotions?.map(emotion => emotion.Type);\n return {\n boundingBox: makeCamelCase(detail.BoundingBox),\n landmarks: makeCamelCaseArray(detail.Landmarks),\n ageRange: makeCamelCase(detail.AgeRange),\n attributes: faceAttributes,\n metadata: {\n confidence: detail.Confidence,\n pose: makeCamelCase(detail.Pose),\n },\n };\n }) ?? [];\n return { entities: faces };\n }\n }\n decodeExternalImageId(externalImageId) {\n return ('' + externalImageId).replace(/::/g, '/');\n }\n}\nfunction _getPredictionsIdentifyAmplifyUserAgent() {\n return getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Identify,\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AAWA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,qCAAqC,CAAC,CAAC;AACjE,MAAM,mCAAmC,CAAC;AACjD,IAAI,eAAe,GAAG;AACtB,QAAQ,OAAO,qCAAqC,CAAC;AACrD,KAAK;AACL,IAAI,QAAQ,CAAC,KAAK,EAAE;AACpB,QAAQ,qBAAqB,CAAC,oBAAoB,CAAC,KAAK,CAAC,EAAE,8BAA8B,CAAC,YAAY,CAAC,CAAC;AACxG,QAAQ,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;AACxC,YAAY,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;AACzC,YAAY,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;AAC5C,SAAS;AACT,aAAa,IAAI,qBAAqB,CAAC,KAAK,CAAC,EAAE;AAC/C,YAAY,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;AAC3C,YAAY,OAAO,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;AAC9C,SAAS;AACT,aAAa;AACb,YA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O,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACvC,SAAS;AACT,KAAK;AACL,IAAI,qBAAqB,CAAC,eAAe,EAAE;AAC3C,QAAQ,OAAO,CAAC,EAAE,GAAG,eAAe,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC1D,KAAK;AACL,CAAC;AACD,SAAS,uCAAuC,GAAG;AACnD,IAAI,OAAO,yBAAyB,CAAC;AACrC,QAAQ,QAAQ,EAAE,QAAQ,CAAC,WAAW;AACtC,QAAQ,MAAM,EAAE,iBAAiB,CAAC,QAAQ;AAC1C,KAAK,CAAC,CAAC;AACP;;;;"}
@@ -24,9 +24,9 @@ class AmazonAIInterpretPredictionsProvider {
24
24
  const { text: textSource } = input;
25
25
  const { source, type = defaultType } = textSource;
26
26
  const { text } = source;
27
- let language;
27
+ let sourceLanguage;
28
28
  if (isInterpretTextOthers(textSource)) {
29
- language = textSource.source.language;
29
+ sourceLanguage = textSource.source.language;
30
30
  }
31
31
  this.comprehendClient = new ComprehendClient({
32
32
  credentials,
@@ -37,7 +37,7 @@ class AmazonAIInterpretPredictionsProvider {
37
37
  }),
38
38
  });
39
39
  const doAll = type === 'all';
40
- let languageCode = language;
40
+ let languageCode = sourceLanguage;
41
41
  if (doAll || type === 'language') {
42
42
  const languageDetectionParams = {
43
43
  Text: text,
@@ -100,8 +100,8 @@ class AmazonAIInterpretPredictionsProvider {
100
100
  try {
101
101
  const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params);
102
102
  const data = await this.comprehendClient.send(detectKeyPhrasesCommand);
103
- const { KeyPhrases = [] } = data || {};
104
- return KeyPhrases.map(({ Text: text }) => {
103
+ const { KeyPhrases: keyPhrases = [] } = data || {};
104
+ return keyPhrases.map(({ Text: text }) => {
105
105
  return { text };
106
106
  });
107
107
  }
@@ -145,7 +145,7 @@ class AmazonAIInterpretPredictionsProvider {
145
145
  try {
146
146
  const detectSentimentCommand = new DetectSentimentCommand(params);
147
147
  const data = await this.comprehendClient.send(detectSentimentCommand);
148
- const { Sentiment: predominant = '', SentimentScore: { Positive: positive = 0, Negative: negative = 0, Neutral: neutral = 0, Mixed: mixed = 0, } = {}, } = ({} = data);
148
+ const { Sentiment: predominant = '', SentimentScore: { Positive: positive = 0, Negative: negative = 0, Neutral: neutral = 0, Mixed: mixed = 0, } = {}, } = data ?? {};
149
149
  return { predominant, positive, negative, neutral, mixed };
150
150
  }
151
151
  catch (err) {
@@ -188,7 +188,7 @@ class AmazonAIInterpretPredictionsProvider {
188
188
  try {
189
189
  const detectDominantLanguageCommand = new DetectDominantLanguageCommand(params);
190
190
  const data = await this.comprehendClient.send(detectDominantLanguageCommand);
191
- const { Languages: [{ LanguageCode }] = [{}] } = ({} = data || {});
191
+ const { Languages: [{ LanguageCode }] = [{ LanguageCode: undefined }] } = data ?? {};
192
192
  assertValidationError(!!LanguageCode, PredictionsValidationErrorCode.NoLanguage);
193
193
  return LanguageCode;
194
194
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AmazonAIInterpretPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIInterpretPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { ComprehendClient, DetectDominantLanguageCommand, DetectEntitiesCommand, DetectKeyPhrasesCommand, DetectSentimentCommand, DetectSyntaxCommand, } from '@aws-sdk/client-comprehend';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isInterpretTextOthers, isValidInterpretInput, } from '../types';\nexport class AmazonAIInterpretPredictionsProvider {\n getProviderName() {\n return 'AmazonAIInterpretPredictionsProvider';\n }\n interpret(input) {\n assertValidationError(isValidInterpretInput(input), PredictionsValidationErrorCode.InvalidInput);\n return this.interpretText(input);\n }\n async interpretText(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { interpretText = {} } = Amplify.getConfig().Predictions?.interpret ?? {};\n const { region = '', defaults = {} } = interpretText;\n const { type: defaultType = '' } = defaults;\n const { text: textSource } = input;\n const { source, type = defaultType } = textSource;\n const { text } = source;\n let language;\n if (isInterpretTextOthers(textSource)) {\n language = textSource.source.language;\n }\n this.comprehendClient = new ComprehendClient({\n credentials,\n region,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Interpret,\n }),\n });\n const doAll = type === 'all';\n let languageCode = language;\n if (doAll || type === 'language') {\n const languageDetectionParams = {\n Text: text,\n };\n languageCode = await this.detectLanguage(languageDetectionParams);\n }\n let entitiesPromise;\n if (doAll || type === 'entities') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const entitiesDetectionParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n entitiesPromise = this.detectEntities(entitiesDetectionParams);\n }\n let sentimentPromise;\n if (doAll || type === 'sentiment') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const sentimentParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n sentimentPromise = this.detectSentiment(sentimentParams);\n }\n let syntaxPromise;\n if (doAll || type === 'syntax') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const syntaxParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n syntaxPromise = this.detectSyntax(syntaxParams);\n }\n let keyPhrasesPromise;\n if (doAll || type === 'keyPhrases') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const keyPhrasesParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n keyPhrasesPromise = this.detectKeyPhrases(keyPhrasesParams);\n }\n const [textEntities, sentiment, syntax, keyPhrases] = await Promise.all([\n entitiesPromise,\n sentimentPromise,\n syntaxPromise,\n keyPhrasesPromise,\n ]);\n return {\n textInterpretation: {\n keyPhrases,\n language: languageCode,\n sentiment,\n syntax,\n textEntities,\n },\n };\n }\n async detectKeyPhrases(params) {\n try {\n const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params);\n const data = await this.comprehendClient.send(detectKeyPhrasesCommand);\n const { KeyPhrases = [] } = data || {};\n return KeyPhrases.map(({ Text: text }) => {\n return { text };\n });\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n async detectSyntax(params) {\n try {\n const detectSyntaxCommand = new DetectSyntaxCommand(params);\n const data = await this.comprehendClient.send(detectSyntaxCommand);\n const { SyntaxTokens = [] } = data || {};\n return this.serializeSyntaxFromComprehend(SyntaxTokens);\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n serializeSyntaxFromComprehend(tokens) {\n let response = [];\n if (tokens && Array.isArray(tokens)) {\n response = tokens.map(({ Text: text = '', PartOfSpeech: { Tag: syntax = '' } = {} }) => {\n return { text, syntax };\n });\n }\n return response;\n }\n async detectSentiment(params) {\n try {\n const detectSentimentCommand = new DetectSentimentCommand(params);\n const data = await this.comprehendClient.send(detectSentimentCommand);\n const { Sentiment: predominant = '', SentimentScore: { Positive: positive = 0, Negative: negative = 0, Neutral: neutral = 0, Mixed: mixed = 0, } = {}, } = ({} = data);\n return { predominant, positive, negative, neutral, mixed };\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n async detectEntities(params) {\n try {\n const detectEntitiesCommand = new DetectEntitiesCommand(params);\n const data = await this.comprehendClient.send(detectEntitiesCommand);\n const { Entities = [] } = data || {};\n return this.serializeEntitiesFromComprehend(Entities);\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n serializeEntitiesFromComprehend(data) {\n let response = [];\n if (data && Array.isArray(data)) {\n response = data.map(({ Type: type, Text: text }) => {\n return { type, text };\n });\n }\n return response;\n }\n async detectLanguage(params) {\n try {\n const detectDominantLanguageCommand = new DetectDominantLanguageCommand(params);\n const data = await this.comprehendClient.send(detectDominantLanguageCommand);\n const { Languages: [{ LanguageCode }] = [{}] } = ({} = data || {});\n assertValidationError(!!LanguageCode, PredictionsValidationErrorCode.NoLanguage);\n return LanguageCode;\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;AACA;AAOO,MAAM,oCAAoC,CAAC;AAClD,IAAI,eAAe,GAAG;AACtB,QAAQ,OAAO,sCAAsC,CAAC;AACtD,KAAK;AACL,IAAI,SAAS,CAAC,KAAK,EAAE;AACrB,QAAQ,qBAAqB,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAAE,8BAA8B,CAAC,YAAY,CAAC,CAAC;AACzG,QAAQ,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AACzC,KAAK;AACL,IAAI,MAAM,aAAa,CAAC,KAAK,EAAE;AAC/B,QAAQ,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,gBAAgB,EAAE,CAAC;AACzD,QAAQ,qBAAqB,CAAC,CAAC,CAAC,WAAW,EAAE,8BAA8B,CAAC,aAAa,CAAC,CAAC;AAC3F,QAAQ,MAAM,EAAE,aAAa,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,WAAW,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AG,CAAC,IAAI,KAAK,uBAAuB,EAAE;AACtD,gBAAgB,MAAM,IAAI,KAAK,CAAC,0FAA0F;AAC1H,oBAAoB,yBAAyB,CAAC,CAAC;AAC/C,aAAa;AACb,iBAAiB;AACjB,gBAAgB,MAAM,GAAG,CAAC;AAC1B,aAAa;AACb,SAAS;AACT,KAAK;AACL;;;;"}
1
+ {"version":3,"file":"AmazonAIInterpretPredictionsProvider.mjs","sources":["../../../src/providers/AmazonAIInterpretPredictionsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { Category, PredictionsAction, getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils';\nimport { ComprehendClient, DetectDominantLanguageCommand, DetectEntitiesCommand, DetectKeyPhrasesCommand, DetectSentimentCommand, DetectSyntaxCommand, } from '@aws-sdk/client-comprehend';\nimport { PredictionsValidationErrorCode } from '../errors/types/validation';\nimport { assertValidationError } from '../errors/utils/assertValidationError';\nimport { isInterpretTextOthers, isValidInterpretInput, } from '../types';\nexport class AmazonAIInterpretPredictionsProvider {\n getProviderName() {\n return 'AmazonAIInterpretPredictionsProvider';\n }\n interpret(input) {\n assertValidationError(isValidInterpretInput(input), PredictionsValidationErrorCode.InvalidInput);\n return this.interpretText(input);\n }\n async interpretText(input) {\n const { credentials } = await fetchAuthSession();\n assertValidationError(!!credentials, PredictionsValidationErrorCode.NoCredentials);\n const { interpretText = {} } = Amplify.getConfig().Predictions?.interpret ?? {};\n const { region = '', defaults = {} } = interpretText;\n const { type: defaultType = '' } = defaults;\n const { text: textSource } = input;\n const { source, type = defaultType } = textSource;\n const { text } = source;\n let sourceLanguage;\n if (isInterpretTextOthers(textSource)) {\n sourceLanguage = textSource.source.language;\n }\n this.comprehendClient = new ComprehendClient({\n credentials,\n region,\n customUserAgent: getAmplifyUserAgentObject({\n category: Category.Predictions,\n action: PredictionsAction.Interpret,\n }),\n });\n const doAll = type === 'all';\n let languageCode = sourceLanguage;\n if (doAll || type === 'language') {\n const languageDetectionParams = {\n Text: text,\n };\n languageCode = await this.detectLanguage(languageDetectionParams);\n }\n let entitiesPromise;\n if (doAll || type === 'entities') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const entitiesDetectionParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n entitiesPromise = this.detectEntities(entitiesDetectionParams);\n }\n let sentimentPromise;\n if (doAll || type === 'sentiment') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const sentimentParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n sentimentPromise = this.detectSentiment(sentimentParams);\n }\n let syntaxPromise;\n if (doAll || type === 'syntax') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const syntaxParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n syntaxPromise = this.detectSyntax(syntaxParams);\n }\n let keyPhrasesPromise;\n if (doAll || type === 'keyPhrases') {\n assertValidationError(!!languageCode, PredictionsValidationErrorCode.NoLanguage);\n const keyPhrasesParams = {\n Text: text,\n LanguageCode: languageCode,\n };\n keyPhrasesPromise = this.detectKeyPhrases(keyPhrasesParams);\n }\n const [textEntities, sentiment, syntax, keyPhrases] = await Promise.all([\n entitiesPromise,\n sentimentPromise,\n syntaxPromise,\n keyPhrasesPromise,\n ]);\n return {\n textInterpretation: {\n keyPhrases,\n language: languageCode,\n sentiment,\n syntax,\n textEntities,\n },\n };\n }\n async detectKeyPhrases(params) {\n try {\n const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params);\n const data = await this.comprehendClient.send(detectKeyPhrasesCommand);\n const { KeyPhrases: keyPhrases = [] } = data || {};\n return keyPhrases.map(({ Text: text }) => {\n return { text };\n });\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n async detectSyntax(params) {\n try {\n const detectSyntaxCommand = new DetectSyntaxCommand(params);\n const data = await this.comprehendClient.send(detectSyntaxCommand);\n const { SyntaxTokens = [] } = data || {};\n return this.serializeSyntaxFromComprehend(SyntaxTokens);\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n serializeSyntaxFromComprehend(tokens) {\n let response = [];\n if (tokens && Array.isArray(tokens)) {\n response = tokens.map(({ Text: text = '', PartOfSpeech: { Tag: syntax = '' } = {} }) => {\n return { text, syntax };\n });\n }\n return response;\n }\n async detectSentiment(params) {\n try {\n const detectSentimentCommand = new DetectSentimentCommand(params);\n const data = await this.comprehendClient.send(detectSentimentCommand);\n const { Sentiment: predominant = '', SentimentScore: { Positive: positive = 0, Negative: negative = 0, Neutral: neutral = 0, Mixed: mixed = 0, } = {}, } = data ?? {};\n return { predominant, positive, negative, neutral, mixed };\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n async detectEntities(params) {\n try {\n const detectEntitiesCommand = new DetectEntitiesCommand(params);\n const data = await this.comprehendClient.send(detectEntitiesCommand);\n const { Entities = [] } = data || {};\n return this.serializeEntitiesFromComprehend(Entities);\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n serializeEntitiesFromComprehend(data) {\n let response = [];\n if (data && Array.isArray(data)) {\n response = data.map(({ Type: type, Text: text }) => {\n return { type, text };\n });\n }\n return response;\n }\n async detectLanguage(params) {\n try {\n const detectDominantLanguageCommand = new DetectDominantLanguageCommand(params);\n const data = await this.comprehendClient.send(detectDominantLanguageCommand);\n const { Languages: [{ LanguageCode }] = [{ LanguageCode: undefined }] } = data ?? {};\n assertValidationError(!!LanguageCode, PredictionsValidationErrorCode.NoLanguage);\n return LanguageCode;\n }\n catch (err) {\n if (err.code === 'AccessDeniedException') {\n throw new Error('Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' +\n 'amplify predictions add');\n }\n else {\n throw err;\n }\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;AACA;AAOO,MAAM,oCAAoC,CAAC;AAClD,IAAI,eAAe,GAAG;AACtB,QAAQ,OAAO,sCAAsC,CAAC;AACtD,KAAK;AACL,IAAI,SAAS,CAAC,KAAK,EAAE;AACrB,QAAQ,qBAAqB,CAAC,qBAAqB,CAAC,KAAK,CAAC,EAAE,8BAA8B,CAAC,YAAY,CAAC,CAAC;AACzG,QAAQ,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AACzC,KAAK;AACL,IAAI,MAAM,aAAa,CAAC,KAAK,EAAE;AAC/B,QAAQ,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,gBAAgB,EAAE,CAAC;AACzD,QAAQ,qBAAqB,CAAC,CAAC,CAAC,WAAW,EAAE,8BAA8B,CAAC,aAAa,CAAC,CAAC;AAC3F,QAAQ,MAAM,EAAE,aAAa,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,WAAW,EAAE,SAAS,IAAI,EAAE,CAAC;AACxF,QAAQ,MAAM,EAAE,MAAM,GAAG,EAAE,EAAE,QAAQ,GAAG,EAAE,EAAE,GAAG,aAAa,CAAC;AAC7D,QAAQ,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,QAAQ,CAAC;AACpD,QAAQ,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;AAC3C,QAAQ,MAAM,EAAE,MAAM,EAAE,IAAI,GAAG,WAAW,EAAE,GAAG,UAAU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GAAG,EAAE,CAAC;AAC1B,QAAQ,IAAI,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;AACzC,YAAY,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK;AAChE,gBAAgB,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;AACtC,aAAa,CAAC,CAAC;AACf,SAAS;AACT,QAAQ,OAAO,QAAQ,CAAC;AACxB,KAAK;AACL,IAAI,MAAM,cAAc,CAAC,MAAM,EAAE;AACjC,QAAQ,IAAI;AACZ,YAAY,MAAM,6BAA6B,GAAG,IAAI,6BAA6B,CAAC,MAAM,CAAC,CAAC;AAC5F,YAAY,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;AACzF,YAAY,MAAM,EAAE,SAAS,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,GAAG,CAAC,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC,EAAE,GAAG,IAAI,IAAI,EAAE,CAAC;AACjG,YAAY,qBAAqB,CAAC,CAAC,CAAC,YAAY,EAAE,8BAA8B,CAAC,UAAU,CAAC,CAAC;AAC7F,YAAY,OAAO,YAAY,CAAC;AAChC,SAAS;AACT,QAAQ,OAAO,GAAG,EAAE;AACpB,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,uBAAuB,EAAE;AACtD,gBAAgB,MAAM,IAAI,KAAK,CAAC,0FAA0F;AAC1H,oBAAoB,yBAAyB,CAAC,CAAC;AAC/C,aAAa;AACb,iBAAiB;AACjB,gBAAgB,MAAM,GAAG,CAAC;AAC1B,aAAa;AACb,SAAS;AACT,KAAK;AACL;;;;"}
@@ -81,8 +81,8 @@ function categorizeTextractBlocks(blocks) {
81
81
  * Note that we do not map `WORD` and `TABLE` in `blockMap` because they will not be referenced by any other
82
82
  * block except the Page block.
83
83
  */
84
- const tableBlocks = Array();
85
- const keyValueBlocks = Array();
84
+ const tableBlocks = [];
85
+ const keyValueBlocks = [];
86
86
  const blockMap = {};
87
87
  blocks.forEach(block => {
88
88
  switch (block.BlockType) {
@@ -108,8 +108,8 @@ function categorizeTextractBlocks(blocks) {
108
108
  blockMap[block.Id] = block;
109
109
  }
110
110
  break;
111
- case 'SELECTION_ELEMENT':
112
- const selectionStatus = block.SelectionStatus === 'SELECTED' ? true : false;
111
+ case 'SELECTION_ELEMENT': {
112
+ const selectionStatus = block.SelectionStatus === 'SELECTED';
113
113
  if (!response.text.selections)
114
114
  response.text.selections = [];
115
115
  response.text.selections.push({
@@ -121,6 +121,7 @@ function categorizeTextractBlocks(blocks) {
121
121
  blockMap[block.Id] = block;
122
122
  }
123
123
  break;
124
+ }
124
125
  case 'TABLE':
125
126
  tableBlocks.push(block);
126
127
  break;
@@ -140,14 +141,14 @@ function categorizeTextractBlocks(blocks) {
140
141
  response.text.fullText = response.text.fullText.substr(0, response.text.fullText.length - 1);
141
142
  // Post-process complex structures if they exist.
142
143
  if (tableBlocks.length !== 0) {
143
- const tableResponse = Array();
144
+ const tableResponse = [];
144
145
  tableBlocks.forEach(table => {
145
146
  tableResponse.push(constructTable(table, blockMap));
146
147
  });
147
148
  response.text.tables = tableResponse;
148
149
  }
149
150
  if (keyValueBlocks.length !== 0) {
150
- const keyValueResponse = Array();
151
+ const keyValueResponse = [];
151
152
  keyValueBlocks.forEach(keyValue => {
152
153
  // We need the KeyValue blocks of EntityType = `KEY`, which has both key and value references.
153
154
  if (keyValue.EntityTypes) {
@@ -167,8 +168,7 @@ function categorizeTextractBlocks(blocks) {
167
168
  * @param {[id: string]: Block} blockMap - Maps block Ids to blocks.
168
169
  */
169
170
  function constructTable(table, blockMap) {
170
- let tableMatrix;
171
- tableMatrix = [];
171
+ const tableMatrix = [];
172
172
  // visit each of the cell associated with the table's relationship.
173
173
  for (const tableRelation of table.Relationships ?? []) {
174
174
  for (const cellId of tableRelation.Ids ?? []) {
@@ -256,7 +256,7 @@ function extractContentsFromBlock(block, blockMap) {
256
256
  words += contentBlock.Text + ' ';
257
257
  }
258
258
  else if (contentBlock.BlockType === 'SELECTION_ELEMENT') {
259
- isSelected = contentBlock.SelectionStatus === 'SELECTED' ? true : false;
259
+ isSelected = contentBlock.SelectionStatus === 'SELECTED';
260
260
  }
261
261
  }
262
262
  }