Skip to content

Commit

Permalink
chore(predictions): run yarn lint:fix
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF committed Mar 11, 2024
1 parent 5ecf8f2 commit 690338e
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 73 deletions.
2 changes: 2 additions & 0 deletions packages/predictions/src/Predictions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { ConsoleLogger } from '@aws-amplify/core';

import {
AmazonAIConvertPredictionsProvider,
AmazonAIIdentifyPredictionsProvider,
Expand Down Expand Up @@ -52,6 +53,7 @@ export class PredictionsClass {
public identify(
input: IdentifyEntitiesInput,
): Promise<IdentifyEntitiesOutput>;

public identify(
input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput,
): Promise<
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { Buffer } from 'buffer';

import { Amplify, ConsoleLogger, fetchAuthSession } from '@aws-amplify/core';
import {
AWSCredentials,
Expand All @@ -18,7 +20,7 @@ import {
MessageHeaderValue,
} from '@smithy/eventstream-codec';
import { fromUtf8, toUtf8 } from '@smithy/util-utf8';
import { Buffer } from 'buffer';

import { PredictionsValidationErrorCode } from '../errors/types/validation';
import { assertValidationError } from '../errors/utils/assertValidationError';
import {
Expand Down Expand Up @@ -59,12 +61,15 @@ export class AmazonAIConvertPredictionsProvider {

if (isTranslateTextInput(input)) {
logger.debug('translateText');

return this.translateText(input);
} else if (isTextToSpeechInput(input)) {
logger.debug('textToSpeech');

return this.convertTextToSpeech(input);
} else {
logger.debug('textToSpeech');

return this.convertSpeechToText(input);
}
}
Expand Down Expand Up @@ -116,6 +121,7 @@ export class AmazonAIConvertPredictionsProvider {
Text: input.translateText?.source?.text,
});
const data = await this.translateClient.send(translateTextCommand);

return {
text: data.TranslatedText,
language: data.TargetLanguageCode,
Expand Down Expand Up @@ -161,7 +167,6 @@ export class AmazonAIConvertPredictionsProvider {
VoiceId: voiceId,
TextType: 'text',
SampleRate: '24000',
// tslint:disable-next-line: align
});
const data = await this.pollyClient.send(synthesizeSpeechCommand);
const response = new Response(data.AudioStream as ReadableStream);
Expand All @@ -170,6 +175,7 @@ export class AmazonAIConvertPredictionsProvider {
type: data.ContentType,
});
const url = URL.createObjectURL(blob);

return {
speech: { url },
audioStream: arrayBuffer,
Expand Down Expand Up @@ -218,6 +224,7 @@ export class AmazonAIConvertPredictionsProvider {
raw: source.bytes,
languageCode: language,
});

return {
transcription: {
fullText,
Expand Down Expand Up @@ -261,6 +268,7 @@ export class AmazonAIConvertPredictionsProvider {
}
}
}

return decodedMessage;
}

Expand Down Expand Up @@ -293,7 +301,8 @@ export class AmazonAIConvertPredictionsProvider {

connection.onclose = closeEvent => {
logger.debug({ closeEvent });
return res(fullText.trim());

res(fullText.trim());
};

logger.debug({ raw });
Expand Down Expand Up @@ -366,6 +375,7 @@ export class AmazonAIConvertPredictionsProvider {
const s = Math.max(-1, Math.min(1, input[i]));
view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
}

return buffer;
}

Expand Down Expand Up @@ -393,8 +403,8 @@ export class AmazonAIConvertPredictionsProvider {
let offsetBuffer = 0;
while (offsetResult < result.length) {
const nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
let accum = 0,
count = 0;
let accum = 0;
let count = 0;
for (
let i = offsetBuffer;
i < nextOffsetBuffer && i < buffer.length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
DetectDocumentTextCommandInput,
TextractClient,
} from '@aws-sdk/client-textract';

import { PredictionsValidationErrorCode } from '../errors/types/validation';
import { assertValidationError } from '../errors/utils/assertValidationError';
import {
Expand Down Expand Up @@ -56,6 +57,7 @@ import {
Image,
TextDetectionList,
} from '../types/AWSTypes';

import {
categorizeRekognitionBlocks,
categorizeTextractBlocks,
Expand Down Expand Up @@ -84,12 +86,15 @@ export class AmazonAIIdentifyPredictionsProvider {

if (isIdentifyTextInput(input)) {
logger.debug('identifyText');

return this.identifyText(input);
} else if (isIdentifyLabelsInput(input)) {
logger.debug('identifyLabels');

return this.identifyLabels(input);
} else {
logger.debug('identifyEntities');

return this.identifyEntities(input);
}
}
Expand Down Expand Up @@ -122,21 +127,27 @@ export class AmazonAIIdentifyPredictionsProvider {
},
});
})
.catch(err => rej(err));
.catch(err => {
rej(err);
});
} else if (isFileSource(source)) {
blobToArrayBuffer(source.file)
.then(buffer => {
res({ Bytes: new Uint8Array(buffer) });
})
.catch(err => rej(err));
.catch(err => {
rej(err);
});
} else if (isIdentifyBytesSource(source)) {
const bytes = source.bytes;
const { bytes } = source;
if (bytes instanceof Blob) {
blobToArrayBuffer(bytes)
.then(buffer => {
res({ Bytes: new Uint8Array(buffer) });
})
.catch(err => rej(err));
.catch(err => {
rej(err);
});
}
if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) {
res({ Bytes: new Uint8Array(bytes) } as Image);
Expand Down Expand Up @@ -237,6 +248,7 @@ export class AmazonAIIdentifyPredictionsProvider {

const analyzeDocumentCommand = new AnalyzeDocumentCommand(param);
const { Blocks } = await this.textractClient.send(analyzeDocumentCommand);

return categorizeTextractBlocks(Blocks as BlockList);
}
}
Expand Down Expand Up @@ -285,6 +297,7 @@ export class AmazonAIIdentifyPredictionsProvider {
data.forEach(val => {
identifyResult = { ...identifyResult, ...val };
});

return identifyResult;
});
}
Expand All @@ -306,6 +319,7 @@ export class AmazonAIIdentifyPredictionsProvider {
instance =>
makeCamelCase(instance.BoundingBox) as BoundingBox | undefined,
) || [];

return {
name: label.Name,
boundingBoxes: boxes,
Expand All @@ -315,6 +329,7 @@ export class AmazonAIIdentifyPredictionsProvider {
},
};
});

return { labels: detectLabelData };
}

Expand Down Expand Up @@ -401,6 +416,7 @@ export class AmazonAIIdentifyPredictionsProvider {
},
}) as IdentifyEntity,
) ?? [];

return { entities: faces };
} else if (
isIdentifyFromCollection(input.entities) &&
Expand All @@ -425,6 +441,7 @@ export class AmazonAIIdentifyPredictionsProvider {
const externalImageId = match.Face?.ExternalImageId
? this.decodeExternalImageId(match.Face.ExternalImageId)
: undefined;

return {
boundingBox: makeCamelCase(match.Face?.BoundingBox),
metadata: {
Expand All @@ -433,6 +450,7 @@ export class AmazonAIIdentifyPredictionsProvider {
},
} as IdentifyEntity;
}) ?? [];

return { entities: faces };
} else {
const detectFacesCommand = new DetectFacesCommand(param);
Expand All @@ -458,6 +476,7 @@ export class AmazonAIIdentifyPredictionsProvider {
faceAttributes.emotions = detail.Emotions?.map(
emotion => emotion.Type,
);

return {
boundingBox: makeCamelCase(detail.BoundingBox),
landmarks: makeCamelCaseArray(detail.Landmarks),
Expand All @@ -469,6 +488,7 @@ export class AmazonAIIdentifyPredictionsProvider {
},
} as IdentifyEntity;
}) ?? [];

return { entities: faces };
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
PredictionsAction,
getAmplifyUserAgentObject,
} from '@aws-amplify/core/internals/utils';

import {
ComprehendClient,
DetectDominantLanguageCommand,
Expand All @@ -17,6 +16,7 @@ import {
Entity,
SyntaxToken,
} from '@aws-sdk/client-comprehend';

import { PredictionsValidationErrorCode } from '../errors/types/validation';
import { assertValidationError } from '../errors/utils/assertValidationError';
import {
Expand Down Expand Up @@ -87,7 +87,7 @@ export class AmazonAIInterpretPredictionsProvider {
languageCode = await this.detectLanguage(languageDetectionParams);
}

let entitiesPromise: Promise<Array<TextEntities>> | undefined;
let entitiesPromise: Promise<TextEntities[]> | undefined;
if (doAll || type === 'entities') {
assertValidationError(
!!languageCode,
Expand All @@ -113,7 +113,7 @@ export class AmazonAIInterpretPredictionsProvider {
sentimentPromise = this.detectSentiment(sentimentParams);
}

let syntaxPromise: Promise<Array<TextSyntax>> | undefined;
let syntaxPromise: Promise<TextSyntax[]> | undefined;
if (doAll || type === 'syntax') {
assertValidationError(
!!languageCode,
Expand Down Expand Up @@ -145,6 +145,7 @@ export class AmazonAIInterpretPredictionsProvider {
syntaxPromise,
keyPhrasesPromise,
]);

return {
textInterpretation: {
keyPhrases,
Expand All @@ -161,6 +162,7 @@ export class AmazonAIInterpretPredictionsProvider {
const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params);
const data = await this.comprehendClient!.send(detectKeyPhrasesCommand);
const { KeyPhrases = [] } = data || {};

return KeyPhrases.map(({ Text: text }) => {
return { text };
});
Expand All @@ -176,11 +178,12 @@ export class AmazonAIInterpretPredictionsProvider {
}
}

private async detectSyntax(params: DetectParams): Promise<Array<TextSyntax>> {
private async detectSyntax(params: DetectParams): Promise<TextSyntax[]> {
try {
const detectSyntaxCommand = new DetectSyntaxCommand(params);
const data = await this.comprehendClient!.send(detectSyntaxCommand);
const { SyntaxTokens = [] } = data || {};

return this.serializeSyntaxFromComprehend(SyntaxTokens);
} catch (err: any) {
if (err.code === 'AccessDeniedException') {
Expand All @@ -194,9 +197,7 @@ export class AmazonAIInterpretPredictionsProvider {
}
}

private serializeSyntaxFromComprehend(
tokens: SyntaxToken[],
): Array<TextSyntax> {
private serializeSyntaxFromComprehend(tokens: SyntaxToken[]): TextSyntax[] {
let response: TextSyntax[] = [];
if (tokens && Array.isArray(tokens)) {
response = tokens.map(
Expand All @@ -205,6 +206,7 @@ export class AmazonAIInterpretPredictionsProvider {
},
);
}

return response;
}

Expand All @@ -221,6 +223,7 @@ export class AmazonAIInterpretPredictionsProvider {
Mixed: mixed = 0,
} = {},
} = ({} = data);

return { predominant, positive, negative, neutral, mixed };
} catch (err: any) {
if (err.code === 'AccessDeniedException') {
Expand All @@ -234,13 +237,12 @@ export class AmazonAIInterpretPredictionsProvider {
}
}

private async detectEntities(
params: DetectParams,
): Promise<Array<TextEntities>> {
private async detectEntities(params: DetectParams): Promise<TextEntities[]> {
try {
const detectEntitiesCommand = new DetectEntitiesCommand(params);
const data = await this.comprehendClient!.send(detectEntitiesCommand);
const { Entities = [] } = data || {};

return this.serializeEntitiesFromComprehend(Entities);
} catch (err: any) {
if (err.code === 'AccessDeniedException') {
Expand All @@ -254,13 +256,14 @@ export class AmazonAIInterpretPredictionsProvider {
}
}

private serializeEntitiesFromComprehend(data: Entity[]): Array<TextEntities> {
private serializeEntitiesFromComprehend(data: Entity[]): TextEntities[] {
let response: TextEntities[] = [];
if (data && Array.isArray(data)) {
response = data.map(({ Type: type, Text: text }) => {
return { type, text };
});
}

return response;
}

Expand Down
Loading

0 comments on commit 690338e

Please sign in to comment.