Building a Serverless Image Moderation System Using AWS

Listen to this Post

In this article, we explore how to build a serverless image moderation system using AWS services such as AWS Lambda, Step Functions, and Amazon Rekognition. This system automates the process of checking uploaded images for inappropriate content and resizing them, all without the need for managing servers or infrastructure.

You Should Know:

To implement this serverless image moderation system, follow these steps:

1. Set Up AWS Lambda Functions:

  • Create a Lambda function that triggers when an image is uploaded to an S3 bucket.
  • Use the following code to initialize the Lambda function:
import boto3
import json

def lambda_handler(event, context):
s3 = boto3.client('s3')
rekognition = boto3.client('rekognition')

<h1>Get the bucket and object key from the event</h1>

bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']

<h1>Call Amazon Rekognition to detect inappropriate content</h1>

response = rekognition.detect_moderation_labels(
Image={
'S3Object': {
'Bucket': bucket,
'Name': key
}
}
)

<h1>Check if any inappropriate content is detected</h1>

for label in response['ModerationLabels']:
if label['Confidence'] > 90: # Adjust confidence threshold as needed
print(f"Inappropriate content detected: {label['Name']}")

<h1>Optionally, move the image to a quarantined bucket</h1>

s3.copy_object(
Bucket='quarantined-bucket',
CopySource={'Bucket': bucket, 'Key': key},
Key=key
)
s3.delete_object(Bucket=bucket, Key=key)
break

return {
'statusCode': 200,
'body': json.dumps('Image processed successfully')
}

2. Configure AWS Step Functions:

  • Create a state machine in AWS Step Functions to orchestrate the workflow.
  • Define states for image upload, content moderation, and resizing.
  • Use the following JSON template to define the state machine:
{
"Comment": "Image Moderation Workflow",
"StartAt": "CheckImageContent",
"States": {
"CheckImageContent": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:CheckImageContent",
"Next": "ResizeImage"
},
"ResizeImage": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ResizeImage",
"End": true
}
}
}

3. Resize Images Using AWS Lambda:

  • Create another Lambda function to resize the images using the Python Imaging Library (PIL).
  • Use the following code to resize the image:
from PIL import Image
import boto3
import io

def lambda_handler(event, context):
s3 = boto3.client('s3')
bucket = event['bucket']
key = event['key']

<h1>Download the image from S3</h1>

response = s3.get_object(Bucket=bucket, Key=key)
image = Image.open(io.BytesIO(response['Body'].read()))

<h1>Resize the image</h1>

resized_image = image.resize((500, 500))

<h1>Save the resized image to a buffer</h1>

buffer = io.BytesIO()
resized_image.save(buffer, 'JPEG')
buffer.seek(0)

<h1>Upload the resized image back to S3</h1>

s3.put_object(Bucket=bucket, Key=f"resized/{key}", Body=buffer)

return {
'statusCode': 200,
'body': 'Image resized and uploaded successfully'
}

4. Deploy and Test:

  • Deploy the Lambda functions and Step Functions state machine.
  • Upload an image to the S3 bucket and monitor the workflow execution in the AWS Management Console.

What Undercode Say:

Building a serverless image moderation system using AWS services like Lambda, Step Functions, and Rekognition is a powerful way to automate image processing tasks without the need for managing servers. This approach not only reduces operational overhead but also scales seamlessly with the number of images processed. By following the steps and code examples provided, you can quickly set up a robust image moderation system that ensures only appropriate content is stored and displayed.

Expected Output:

  • A fully automated serverless image moderation system.
  • Images are checked for inappropriate content using Amazon Rekognition.
  • Images are resized and stored in an S3 bucket.
  • The entire workflow is managed by AWS Step Functions.

URLs:

References:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image