Skip to content

Commit

Permalink
chore(predictions): manual fix of linter reported errors
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF committed Mar 11, 2024
1 parent 690338e commit 5c7e2b5
Show file tree
Hide file tree
Showing 8 changed files with 73 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,9 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch(
expect(predictionsProvider.identify(detectLabelInput)).rejects.toThrow(
'error',
);
});
Expand All @@ -448,11 +448,11 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(
predictionsProvider.identify(detectModerationInput),
).rejects.toMatch('error');
).rejects.toThrow('error');
});
});

Expand Down Expand Up @@ -480,11 +480,11 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(
predictionsProvider.identify(detectModerationInput),
).rejects.toMatch('error');
).rejects.toThrow('error');
});
});
});
Expand Down Expand Up @@ -532,9 +532,9 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(predictionsProvider.identify(detectFacesInput)).rejects.toMatch(
expect(predictionsProvider.identify(detectFacesInput)).rejects.toThrow(
'error',
);
});
Expand All @@ -561,11 +561,11 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(
predictionsProvider.identify(recognizeCelebritiesInput),
).rejects.toMatch('error');
).rejects.toThrow('error');
});
});

Expand All @@ -592,11 +592,11 @@ describe('Predictions identify provider test', () => {
jest
.spyOn(RekognitionClient.prototype, 'send')
.mockImplementationOnce(() => {
return Promise.reject('error');
return Promise.reject(new Error('error'));
});
expect(
predictionsProvider.identify(searchByFacesInput),
).rejects.toMatch('error');
).rejects.toThrow('error');
});
});
});
Expand Down Expand Up @@ -718,7 +718,7 @@ describe('Predictions identify provider test', () => {
const detectLabelInput = {
labels: { source: null, type: 'LABELS' },
};
expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch(
expect(predictionsProvider.identify(detectLabelInput)).rejects.toThrow(
'not configured correctly',
);
});
Expand Down
3 changes: 0 additions & 3 deletions packages/predictions/src/Predictions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { ConsoleLogger } from '@aws-amplify/core';

import {
AmazonAIConvertPredictionsProvider,
Expand All @@ -24,8 +23,6 @@ import {
TranslateTextOutput,
} from './types';

const logger = new ConsoleLogger('Predictions');

export class PredictionsClass {
private convertProvider = new AmazonAIConvertPredictionsProvider();
private identifyProvider = new AmazonAIIdentifyPredictionsProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ export class AmazonAIConvertPredictionsProvider {
raw,
languageCode,
}: TranscribeData): Promise<string> {
return new Promise((res, rej) => {
return new Promise((resolve, reject) => {
let fullText = '';
connection.onmessage = message => {
try {
Expand All @@ -290,19 +290,19 @@ export class AmazonAIConvertPredictionsProvider {
}
} catch (err: unknown) {
logger.debug(err);
rej(err);
reject(err);
}
};

connection.onerror = errorEvent => {
logger.debug({ errorEvent });
rej('failed to transcribe, network error');
reject(new Error('failed to transcribe, network error'));
};

connection.onclose = closeEvent => {
logger.debug({ closeEvent });

res(fullText.trim());
resolve(fullText.trim());
};

logger.debug({ raw });
Expand Down Expand Up @@ -430,7 +430,7 @@ export class AmazonAIConvertPredictionsProvider {
region: string;
languageCode: string;
}): Promise<WebSocket> {
return new Promise(async (res, rej) => {
return new Promise((resolve, _reject) => {
const signedUrl = this.generateTranscribeUrl({
credentials,
region,
Expand All @@ -443,7 +443,7 @@ export class AmazonAIConvertPredictionsProvider {
connection.binaryType = 'arraybuffer';
connection.onopen = () => {
logger.debug('connected');
res(connection);
resolve(connection);
};
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,7 @@ import {
isStorageSource,
isValidIdentifyInput,
} from '../types';
import {
BlockList,
Document,
Image,
TextDetectionList,
} from '../types/AWSTypes';
import { BlockList, Image, TextDetectionList } from '../types/AWSTypes';

import {
categorizeRekognitionBlocks,
Expand Down Expand Up @@ -107,7 +102,7 @@ export class AmazonAIIdentifyPredictionsProvider {
* @return {Promise<Image>} - Promise resolving to the converted source object.
*/
private configureSource(source: IdentifySource): Promise<Image> {
return new Promise((res, rej) => {
return new Promise((resolve, reject) => {
if (isStorageSource(source)) {
const storageConfig = {
accessLevel: source.level,
Expand All @@ -119,43 +114,44 @@ export class AmazonAIIdentifyPredictionsProvider {
const parser =
/https:\/\/([a-zA-Z0-9%\-_.]+)\.s3\.[A-Za-z0-9%\-._~]+\/([a-zA-Z0-9%\-._~/]+)\?/;
const parsedURL = value.url.toString().match(parser) ?? '';
if (parsedURL.length < 3) rej('Invalid S3 key was given.');
res({
if (parsedURL.length < 3)
reject(new Error('Invalid S3 key was given.'));
resolve({
S3Object: {
Bucket: parsedURL[1],
Name: decodeURIComponent(parsedURL[2]),
},
});
})
.catch(err => {
rej(err);
reject(err);
});
} else if (isFileSource(source)) {
blobToArrayBuffer(source.file)
.then(buffer => {
res({ Bytes: new Uint8Array(buffer) });
resolve({ Bytes: new Uint8Array(buffer) });
})
.catch(err => {
rej(err);
reject(err);
});
} else if (isIdentifyBytesSource(source)) {
const { bytes } = source;
if (bytes instanceof Blob) {
blobToArrayBuffer(bytes)
.then(buffer => {
res({ Bytes: new Uint8Array(buffer) });
resolve({ Bytes: new Uint8Array(buffer) });
})
.catch(err => {
rej(err);
reject(err);
});
}
if (bytes instanceof ArrayBuffer || bytes instanceof Buffer) {
res({ Bytes: new Uint8Array(bytes) } as Image);
resolve({ Bytes: new Uint8Array(bytes) } as Image);
}
// everything else can be directly passed to Rekognition / Textract.
res({ Bytes: bytes } as Image);
resolve({ Bytes: bytes } as Image);
} else {
rej('Input source is not configured correctly.');
reject(new Error('Input source is not configured correctly.'));
}
});
}
Expand Down Expand Up @@ -190,9 +186,8 @@ export class AmazonAIIdentifyPredictionsProvider {
credentials,
customUserAgent: _getPredictionsIdentifyAmplifyUserAgent(),
});
let inputDocument: Document;

inputDocument = await this.configureSource(input.text?.source);
const inputDocument = await this.configureSource(input.text?.source);

// get default value if format isn't specified in the input.
const format = input.text?.format ?? configFormat;
Expand Down Expand Up @@ -304,8 +299,8 @@ export class AmazonAIIdentifyPredictionsProvider {

/**
* Calls Rekognition.detectLabels and organizes the returned data.
* @param {DetectLabelsInput} param - parameter to be passed onto Rekognition
* @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectLabels response.
* @param param - parameters as {@link DetectLabelsCommandInput} to be passed onto Rekognition
* @return a promise resolving to organized detectLabels response as {@link IdentifyLabelsOutput}.
*/
private async detectLabels(
param: DetectLabelsCommandInput,
Expand Down Expand Up @@ -335,8 +330,8 @@ export class AmazonAIIdentifyPredictionsProvider {

/**
* Calls Rekognition.detectModerationLabels and organizes the returned data.
* @param {Rekognition.DetectLabelsRequest} param - Parameter to be passed onto Rekognition
* @return {Promise<IdentifyLabelsOutput>} - Promise resolving to organized detectModerationLabels response.
* @param param parameter to be passed onto Rekognition as {@link DetectModerationLabelsCommandInput}
* @return a promise resolving to organized detectModerationLabels response as {@link IdentifyLabelsOutput}.
*/
private async detectModerationLabels(
param: DetectModerationLabelsCommandInput,
Expand All @@ -357,8 +352,8 @@ export class AmazonAIIdentifyPredictionsProvider {
/**
* Identify faces within an image that is provided as input, and match faces from a collection
* or identify celebrities.
* @param {IdentifyEntityInput} input - object containing the source image and face match options.
* @return {Promise<IdentifyEntityOutput>} Promise resolving to identify results.
* @param input - object of {@link IdentifyEntitiesInput} containing the source image and face match options.
* @return a promise resolving to identify results as {@link IdentifyEntitiesOutput}.
*/
protected async identifyEntities(
input: IdentifyEntitiesInput,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ export class AmazonAIInterpretPredictionsProvider {
const { text: textSource } = input;
const { source, type = defaultType } = textSource;
const { text } = source;
let language;
let sourceLanguage;
if (isInterpretTextOthers(textSource)) {
language = (textSource as InterpretTextOthers).source.language;
sourceLanguage = (textSource as InterpretTextOthers).source.language;
}

this.comprehendClient = new ComprehendClient({
Expand All @@ -79,7 +79,7 @@ export class AmazonAIInterpretPredictionsProvider {

const doAll = type === 'all';

let languageCode = language;
let languageCode = sourceLanguage;
if (doAll || type === 'language') {
const languageDetectionParams = {
Text: text,
Expand Down Expand Up @@ -161,9 +161,9 @@ export class AmazonAIInterpretPredictionsProvider {
try {
const detectKeyPhrasesCommand = new DetectKeyPhrasesCommand(params);
const data = await this.comprehendClient!.send(detectKeyPhrasesCommand);
const { KeyPhrases = [] } = data || {};
const { KeyPhrases: keyPhrases = [] } = data || {};

return KeyPhrases.map(({ Text: text }) => {
return keyPhrases.map(({ Text: text }) => {
return { text };
});
} catch (err: any) {
Expand Down Expand Up @@ -222,7 +222,7 @@ export class AmazonAIInterpretPredictionsProvider {
Neutral: neutral = 0,
Mixed: mixed = 0,
} = {},
} = ({} = data);
} = data ?? {};

return { predominant, positive, negative, neutral, mixed };
} catch (err: any) {
Expand Down Expand Up @@ -275,7 +275,8 @@ export class AmazonAIInterpretPredictionsProvider {
const data = await this.comprehendClient!.send(
detectDominantLanguageCommand,
);
const { Languages: [{ LanguageCode }] = [{}] } = ({} = data || {});
const { Languages: [{ LanguageCode }] = [{ LanguageCode: undefined }] } =
data ?? {};
assertValidationError(
!!LanguageCode,
PredictionsValidationErrorCode.NoLanguage,
Expand Down
6 changes: 3 additions & 3 deletions packages/predictions/src/providers/IdentifyTextUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export function categorizeTextractBlocks(
blockMap[block.Id] = block;
}
break;
case 'SELECTION_ELEMENT':
case 'SELECTION_ELEMENT': {
const selectionStatus = block.SelectionStatus === 'SELECTED';
if (!response.text.selections) response.text.selections = [];
response.text.selections.push({
Expand All @@ -145,6 +145,7 @@ export function categorizeTextractBlocks(
blockMap[block.Id] = block;
}
break;
}
case 'TABLE':
tableBlocks.push(block);
break;
Expand Down Expand Up @@ -197,8 +198,7 @@ export function categorizeTextractBlocks(
* @param {[id: string]: Block} blockMap - Maps block Ids to blocks.
*/
function constructTable(table: Block, blockMap: Record<string, Block>): Table {
let tableMatrix: TableCell[][];
tableMatrix = [];
const tableMatrix: TableCell[][] = [];
// visit each of the cell associated with the table's relationship.
for (const tableRelation of table.Relationships ?? []) {
for (const cellId of tableRelation.Ids ?? []) {
Expand Down
10 changes: 5 additions & 5 deletions packages/predictions/src/providers/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function makeCamelCase(obj?: any, keys?: string[]) {
const newObj = {};
const keysToRename = keys || Object.keys(obj);
keysToRename.forEach(key => {
if (obj.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
// change the key to camelcase.
const camelCaseKey = key.charAt(0).toLowerCase() + key.substr(1);
Object.assign(newObj, { [camelCaseKey]: obj[key] });
Expand All @@ -32,18 +32,18 @@ export function makeCamelCaseArray(objArr?: object[], keys?: string[]) {
* Converts blob to array buffer
*/
export function blobToArrayBuffer(blob: Blob): Promise<Uint8Array> {
return new Promise((res, rej) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = _event => {
res(reader.result as Uint8Array);
resolve(reader.result as Uint8Array);
};
reader.onerror = err => {
rej(err);
reject(err);
};
try {
reader.readAsArrayBuffer(blob);
} catch (err) {
rej(err); // in case user gives invalid type
reject(err); // in case user gives invalid type
}
});
}
Loading

0 comments on commit 5c7e2b5

Please sign in to comment.