Skip to content

Commit c8a7212

Browse files
author
Bruno Lira
committed
feat: first commit
0 parents  commit c8a7212

9 files changed

+3074
-0
lines changed

.gitignore

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# package directories
2+
node_modules
3+
jspm_packages
4+
5+
# Serverless directories
6+
.serverless
7+
8+
# Webpack directories
9+
.webpack

handler.ts

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
"use strict";
2+
import axios from "axios";
3+
import { APIGatewayProxyEvent } from "aws-lambda";
4+
import * as aws from "aws-sdk";
5+
import "source-map-support/register";
6+
7+
class Handler {
8+
private rekoSvc: aws.Rekognition;
9+
private translatorSvc: aws.Translate;
10+
constructor({ rekoSvc, translatorSvc }) {
11+
this.rekoSvc = rekoSvc;
12+
this.translatorSvc = translatorSvc;
13+
}
14+
15+
async detectImageLabels(buffer: Buffer) {
16+
const result = await this.rekoSvc
17+
.detectLabels({
18+
Image: {
19+
Bytes: buffer,
20+
},
21+
})
22+
.promise();
23+
24+
const workingItems = result.Labels.filter(
25+
({ Confidence }) => Confidence > 80
26+
);
27+
28+
const names = workingItems.map(({ Name }) => Name).join(" | ");
29+
30+
return { names, workingItems };
31+
}
32+
33+
async translateText(text: string) {
34+
const params = {
35+
SourceLanguageCode: "en",
36+
TargetLanguageCode: "pt",
37+
Text: text,
38+
};
39+
const { TranslatedText } = await this.translatorSvc
40+
.translateText(params)
41+
.promise();
42+
return TranslatedText.split(" | ");
43+
}
44+
45+
formatFinalText({ translatedNames, workingItems }) {
46+
const finalText = [];
47+
for (const index in workingItems) {
48+
const nameInPortuguese = translatedNames[index];
49+
const currentItemConfidence = workingItems[index].Confidence;
50+
finalText.push(
51+
`${currentItemConfidence.toFixed(
52+
2
53+
)}% de chance de conter ${nameInPortuguese}`
54+
);
55+
}
56+
return finalText;
57+
}
58+
59+
async getImageBuffer(imageUrl: string) {
60+
const response = await axios.get(imageUrl, {
61+
responseType: "arraybuffer",
62+
});
63+
const buffer = Buffer.from(response.data, "base64");
64+
return buffer;
65+
}
66+
67+
async main(event: APIGatewayProxyEvent) {
68+
try {
69+
const { imageUrl } = event.queryStringParameters;
70+
console.log("Fetching image buffer...");
71+
const imageBuffer = await this.getImageBuffer(imageUrl);
72+
console.log("Detecting labels...");
73+
const { names, workingItems } = await this.detectImageLabels(imageBuffer);
74+
75+
console.log("Translating to portuguese...");
76+
const translatedNames = await this.translateText(names);
77+
78+
console.log("Handling final text...");
79+
const finalText = this.formatFinalText({
80+
translatedNames,
81+
workingItems,
82+
});
83+
return {
84+
statusCode: 200,
85+
body: JSON.stringify(finalText),
86+
};
87+
} catch (e) {
88+
console.log("ERROR***", e);
89+
return {
90+
statusCode: 500,
91+
body: "Internal server error!",
92+
};
93+
}
94+
}
95+
}
96+
97+
const trantranslate = new aws.Translate();
98+
const reko = new aws.Rekognition();
99+
100+
const handler = new Handler({
101+
rekoSvc: reko,
102+
translatorSvc: trantranslate,
103+
});
104+
105+
export const main = handler.main.bind(handler);

package.json

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "image-analysis-ts",
3+
"version": "1.0.0",
4+
"description": "Serverless webpack example using Typescript",
5+
"main": "handler.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"dependencies": {
10+
"source-map-support": "^0.5.10",
11+
"aws-sdk": "^2.729.0",
12+
"axios": "^0.19.2"
13+
},
14+
"devDependencies": {
15+
"@types/aws-lambda": "^8.10.17",
16+
"@types/node": "^10.12.18",
17+
"@types/serverless": "^1.72.5",
18+
"fork-ts-checker-webpack-plugin": "^3.0.1",
19+
"serverless-webpack": "^5.2.0",
20+
"ts-loader": "^5.3.3",
21+
"ts-node": "^8.10.2",
22+
"typescript": "^3.2.4",
23+
"webpack": "^4.29.0",
24+
"webpack-node-externals": "^1.7.2"
25+
},
26+
"author": "The serverless webpack authors (https://github.com/elastic-coders/serverless-webpack)",
27+
"license": "MIT"
28+
}

request.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"queryStringParameters": {
3+
"imageUrl": "https://saude.abril.com.br/wp-content/uploads/2018/12/cachorro-livro.png"
4+
}
5+
}

serverless.ts

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { Serverless } from "serverless/aws";
2+
3+
const serverlessConfiguration: Serverless = {
4+
service: {
5+
name: "image-analysis-ts",
6+
// app and org for use with dashboard.serverless.com
7+
// app: your-app-name,
8+
// org: your-org-name,
9+
},
10+
frameworkVersion: ">=1.72.0",
11+
custom: {
12+
webpack: {
13+
webpackConfig: "./webpack.config.js",
14+
includeModules: true,
15+
},
16+
},
17+
// Add the serverless-webpack plugin
18+
plugins: ["serverless-webpack"],
19+
provider: {
20+
name: "aws",
21+
runtime: "nodejs12.x",
22+
apiGateway: {
23+
minimumCompressionSize: 1024,
24+
},
25+
environment: {
26+
AWS_NODEJS_CONNECTION_REUSE_ENABLED: "1",
27+
},
28+
iamRoleStatements: [
29+
{
30+
Effect: "Allow",
31+
Action: "rekognition:DetectLabels",
32+
Resource: "*",
33+
},
34+
{
35+
Effect: "Allow",
36+
Action: "translate:TranslateText",
37+
Resource: "*",
38+
},
39+
],
40+
},
41+
functions: {
42+
analyseImage: {
43+
handler: "handler.main",
44+
events: [
45+
{
46+
http: {
47+
method: "get",
48+
path: "analyse",
49+
},
50+
},
51+
],
52+
},
53+
},
54+
};
55+
56+
module.exports = serverlessConfiguration;

tsconfig.json

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"compilerOptions": {
3+
"lib": ["es2017"],
4+
"removeComments": true,
5+
"moduleResolution": "node",
6+
"noUnusedLocals": true,
7+
"noUnusedParameters": true,
8+
"sourceMap": true,
9+
"target": "es2017",
10+
"outDir": "lib"
11+
},
12+
"include": ["./**/*.ts"],
13+
"exclude": [
14+
"node_modules/**/*",
15+
".serverless/**/*",
16+
".webpack/**/*",
17+
"_warmup/**/*",
18+
".vscode/**/*"
19+
]
20+
}

vscode/launch.json

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"configurations": [
3+
{
4+
"name": "Lambda",
5+
"type": "node",
6+
"request": "launch",
7+
"runtimeArgs": ["--inspect", "--debug-port=9229"],
8+
"program": "${workspaceFolder}/node_modules/serverless/bin/serverless",
9+
"args": ["offline"],
10+
"port": 9229,
11+
"console": "integratedTerminal"
12+
}
13+
]
14+
}

webpack.config.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const path = require('path');
2+
const slsw = require('serverless-webpack');
3+
const nodeExternals = require('webpack-node-externals');
4+
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
5+
6+
module.exports = {
7+
context: __dirname,
8+
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
9+
entry: slsw.lib.entries,
10+
devtool: slsw.lib.webpack.isLocal ? 'cheap-module-eval-source-map' : 'source-map',
11+
resolve: {
12+
extensions: ['.mjs', '.json', '.ts'],
13+
symlinks: false,
14+
cacheWithContext: false,
15+
},
16+
output: {
17+
libraryTarget: 'commonjs',
18+
path: path.join(__dirname, '.webpack'),
19+
filename: '[name].js',
20+
},
21+
target: 'node',
22+
externals: [nodeExternals()],
23+
module: {
24+
rules: [
25+
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
26+
{
27+
test: /\.(tsx?)$/,
28+
loader: 'ts-loader',
29+
exclude: [
30+
[
31+
path.resolve(__dirname, 'node_modules'),
32+
path.resolve(__dirname, '.serverless'),
33+
path.resolve(__dirname, '.webpack'),
34+
],
35+
],
36+
options: {
37+
transpileOnly: true,
38+
experimentalWatchApi: true,
39+
},
40+
},
41+
],
42+
},
43+
plugins: [
44+
// new ForkTsCheckerWebpackPlugin({
45+
// eslint: true,
46+
// eslintOptions: {
47+
// cache: true
48+
// }
49+
// })
50+
],
51+
};

0 commit comments

Comments
 (0)