-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
82 lines (66 loc) · 1.56 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
'use strict';
const AWS = require('aws-sdk');
const rekognition = new AWS.Rekognition();
const s3 = new AWS.S3();
module.exports.validateImage = async (event) => {
const s3Record = event.Records[0].s3;
const bucket = s3Record.bucket.name;
const key = s3Record.object.key;
console.log(`A file named ${key} was put in a bucket ${bucket}`);
// Detect the labels
return detectLabels(bucket, key).then(labels => {
console.log(labels);
const isAHuman = checkIsHuman(labels);
console.log(isAHuman);
if (!isAHuman) {
return removeImage(bucket, key).then(() => {
console.log('The image was not a human and was removed');
return;
});
}
}).catch(error => {
return error;
})
};
//function part
function checkIsHuman(labels){
return labels
.map(label => {
return label.Name === 'Human' ? true : false
}).some( val => {
return val === true;
});
}
function detectLabels(bucket, key) {
const params = {
Image: {
S3Object: {
Bucket: bucket,
Name: key
}
},
MaxLabels: 5,
MinConfidence: 85
};
return rekognition.detectLabels(params).promise().then(data => {
return data.Labels;
}).catch(error => {
console.log(error);
return error;
});
}
function checkIsACat(labels) {
return labels
.map(label => {
return label.Name === 'Cat' ? true : false
}).some( val => {
return val === true;
});
}
function removeImage(bucket, key) {
const params = {
Bucket: bucket,
Key: key
};
return s3.deleteObject(params).promise();
}