AWS Machine Learning Use Case using Serverless…

So now as you are familiar with the services let's start our project implementation for a better understanding of these services…

service: cat-rekognationframeworkVersion: '3'provider:
name: aws
runtime: nodejs14.x
iamRoleStatements:
- Effect: Allow
Action:
- s3:ListBucket
- s3:GetObject
- s3:DeleteObject
Resource: arn:aws:s3:::cat-rekognation/*
- Effect: Allow
Action:
- rekognition:DetectLabels
Resource: "*"
functions:
validateImage:
handler: handler.validateImage
events:
- s3:
bucket: cat-rekognation
event: s3:ObjectCreated:*
destinations:
onSuccess: arn:aws:sns:us-east-1:247513377090:success
'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 isACat = checkIsACat(labels);
console.log(isACat);
if (!isACat) {
return removeImage(bucket, key).then(() => {
console.log('The image was not a cat and was removed');
return;
});
}
}).catch(error => {
return error;
})
};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(); }

It's time to upload the image in S3……

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Dependency Injection in iPlayer Android

4 Best Time Series Databases To Watch in 2019

DynamoDb Incremental Backups

Apache: Redirect HTTP to HTTPS

How to Solve Sudoku with Depth-first Search Algorithm (DFS) in Python

Adding Flutter to the development of RappiBank — Introduction

The Paradox of Effort

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parinati Rajput

Parinati Rajput

More from Medium

AWS Learning — Simple API using API Gateway and Lambda with CloudFormation (Part 1)

AWS Lambda Use Cases

5 Steps To Install Python Packages To AWS lambda From Windows OS

What is AWS Lambda Function