Skip to content

03 Rekognition

JP Barbosa edited this page Sep 24, 2022 · 13 revisions

Rekognition

Diagram

Rekognition

Create function to process images

code ./services/functions/process.ts
import {
  S3ObjectCreatedNotificationEvent,
  S3ObjectCreatedNotificationEventDetail,
  SQSHandler,
} from "aws-lambda";
import { AWSError, Rekognition, S3 } from "aws-sdk";

const rekognition = new Rekognition();

const s3 = new S3();

const getLabels = async ({
  bucket,
  object,
}: S3ObjectCreatedNotificationEventDetail) => {
  const labels = await rekognition
    .detectLabels({
      Image: {
        S3Object: {
          Bucket: bucket.name,
          Name: object.key,
        },
      },
    })
    .promise();
  console.log("Image has been processed", object.key);
  return labels;
};

const deleteImage = async ({
  bucket,
  object,
}: S3ObjectCreatedNotificationEventDetail) => {
  try {
    await s3
      .deleteObject({
        Bucket: bucket.name,
        Key: object.key,
      })
      .promise();
    console.log("Image has been deleted");
  } catch (error) {
    console.log(error);
  }
};

export const handler: SQSHandler = async (sqsEvent) => {
  sqsEvent.Records.forEach(async (record) => {
    const { detail }: S3ObjectCreatedNotificationEvent = JSON.parse(
      record.body
    );
    const { key } = detail.object;
    try {
      const labels = await getLabels(detail);
      console.log(labels);
    } catch (error) {
      const awsError = error as AWSError;
      console.log(awsError);
    } finally {
      await deleteImage(detail);
    }
  });
};

Deploy infrastructure

The first start should take several minutes as many AWS resources need to be created (it has taken 10 minutes for me). Make sure to insert AWS credentials alias correctly according to your ~/.aws/credentials file.

npm start

Test on SST Console

open https://console.sst.dev/sst-rekognition/sst-jp/local
image image

Commit

git add .
git commit -m "Rekognition"

Next step

Dynamo DB

Clone this wiki locally