-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
94 lines (77 loc) · 2.18 KB
/
handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const { get } = require('axios')
class Handler {
constructor({ rekoSvc, translateSvc }) {
this.rekoSvc = rekoSvc
this.translateSvc = translateSvc
}
async detectImageLabels (buffer) {
const result = await this.rekoSvc.detectLabels({
Image: {
Bytes: buffer
}
}).promise()
const workingItems = result.Labels
.filter(({ Confidence }) => Confidence > 80);
const names = workingItems
.map(({ Name }) => Name)
.join(' and ')
return { names, workingItems }
}
async translateText (text) {
const params = {
SourceLanguageCode: 'en',
TargetLanguageCode: 'pt',
Text: text
}
const { TranslatedText } = await this.translateSvc
.translateText(params)
.promise()
return TranslatedText.split(' e ')
}
async formatTextResults (texts, workingItems) {
const finalText = []
for (const indexText in texts) {
const nameInPortuguese = texts[indexText]
const confidence = workingItems[indexText].Confidence
finalText.push(
`${confidence.toFixed(2)}% de ser do tipo ${nameInPortuguese}`
)
}
return finalText.join('\n')
}
async getImageBuffer (imageUrl) {
const response = await get(imageUrl, {
responseType: 'arraybuffer'
})
const buffer = Buffer.from(response.data, 'base64')
return buffer
}
async main (event) {
try {
const { imageUrl } = event.queryStringParameters
const buffer = await this.getImageBuffer(imageUrl)
const { names, workingItems } = await this.detectImageLabels(buffer)
const texts = await this.translateText(names)
const finalText = await this.formatTextResults(texts, workingItems)
return {
statusCode: 200,
body: `A imagem tem \n`.concat(finalText)
}
} catch (error) {
console.log('Error**', error.stack)
return {
statusCode: 500,
body: 'Internal server error!'
}
}
}
}
const aws = require('aws-sdk')
const reko = new aws.Rekognition()
const translate = new aws.Translate()
const handler = new Handler({
rekoSvc: reko,
translateSvc: translate
})
module.exports.main = handler.main.bind(handler);