Etapa 1 de 6 - Cerca de 45 min
Lab 01 - Vision: Rekognition and Textract
Image analysis and document text extraction with Amazon Rekognition and Amazon Textract.
Time: about 45 minutes.
Overview
This lab covers two managed computer vision services:
- Amazon Rekognition detects labels (objects, scenes, activities), faces, and text in images, and stores face vectors in a collection for search.
- Amazon Textract extracts printed and handwritten text, forms, and tables from documents. You run it synchronously for one page and asynchronously (with an SNS notification) for multi-page documents.
Neither service needs model training. You send an image or document and get JSON back.
What gets created
<account-id> is your 12-digit AWS account ID.
| Component | Resources |
|---|---|
s3-bucket |
Bucket ai-01-vision-test-vision-data-<account-id> with input/images/, input/documents/, output/rekognition/, output/textract/ |
iam-role |
Role ai-01-vision-test-vision-services (trusted by Lambda) with Rekognition, Textract, S3, and CloudWatch Logs policies |
rekognition |
Collection ai-01-vision-test-rekognition, SNS topic ai-01-vision-test-rekognition-notifications, role ai-01-vision-test-rekognition-rekognition-sns |
textract |
SNS topic ai-01-vision-test-textract-notifications, role ai-01-vision-test-textract-textract-role, SQS queue ai-01-vision-test-textract-results subscribed to the topic |
The IAM role from iam-role is not used by the CLI steps below (those run as
you). It shows how to build a least-privilege role for an application; Lab 06
attaches the same kind of role to a Lambda function.
Architecture
+---------------------------------------------------------------+
| S3 bucket |
| input/images/ input/documents/ |
+--------+--------------------------------------+---------------+
| |
v v
+------------------+ +-----------------------------+
| Rekognition | | Textract |
| - DetectLabels | | - DetectDocumentText (sync) |
| - DetectFaces | | - StartDocumentAnalysis |
| - DetectText | | (async, multi-page) |
| - IndexFaces / | +--------------+--------------+
| SearchFaces | |
+--------+---------+ v
| +-----------------------+
v | SNS topic -> SQS queue|
+------------------+ | (job completion) |
| Collection | +-----------------------+
| (face vectors) |
+------------------+Before you start
- Complete the Prerequisites in the README.
- Have a few test files in the lab folder:
sample-image.jpg- any photo (JPEG or PNG)sign-image.jpg- a photo that contains text, such as a street signface-image.jpgandsearch-face.jpg- two photos of the same person (use your own photos or images you have the rights to use)sample-document.pdf- a document, ideally with a table or a form
Deploy
The stack for this lab is stacks/labs/01-vision/test.yaml. It
imports the shared defaults, the
region and stage mixins, and the
component defaults from the catalog,
then sets this lab's variables. Atmos
names the stack lab-01-vision-test from the name_template in
atmos.yaml (lab-{{ .vars.lab }}-{{ .vars.stage }}; see
Stack Names).
iam-role reads the bucket ARN from s3-bucket with the
!terraform.output
YAML function, so apply s3-bucket first. Destroy in the reverse order.
cd atmos-aws-ai-infra # the lab folder
# Check the stack (YAML functions off: nothing is applied yet)
atmos validate stacks
atmos list stacks
atmos describe stacks -s lab-01-vision-test --process-functions=false
# Apply in order: iam-role reads the bucket ARN from s3-bucket
atmos terraform apply s3-bucket -s lab-01-vision-test
atmos terraform apply iam-role -s lab-01-vision-test
atmos terraform apply rekognition -s lab-01-vision-test
atmos terraform apply textract -s lab-01-vision-testatmos validate stacks
checks the stack files,
atmos list stacks shows the
six lab stacks, and
atmos describe stacks
shows the merged configuration. --process-functions=false leaves
!terraform.output unevaluated, because nothing is applied yet.
Each atmos terraform apply
shows the plan and asks you to type yes. Atmos runs terraform init and
selects a Terraform workspace
named after the stack, so the same component folder can hold the state of
several labs.
Set shell variables
The commands below read outputs with
atmos terraform output.
--skip-init keeps the terraform init messages out of the variable, and
everything after -- goes to Terraform unchanged (-raw prints the bare
value).
STACK=lab-01-vision-test
BUCKET=$(atmos terraform output s3-bucket -s $STACK --skip-init -- -raw bucket_id)
COLLECTION_ID=$(atmos terraform output rekognition -s $STACK --skip-init -- -raw collection_id)
TOPIC_ARN=$(atmos terraform output textract -s $STACK --skip-init -- -raw sns_topic_arn)
TEXTRACT_ROLE_ARN=$(atmos terraform output textract -s $STACK --skip-init -- -raw textract_role_arn)
QUEUE_URL=$(atmos terraform output textract -s $STACK --skip-init -- -raw sqs_queue_url)
echo "$BUCKET $COLLECTION_ID"Test Rekognition
Detect labels
aws s3 cp sample-image.jpg "s3://$BUCKET/input/images/"
aws rekognition detect-labels \
--image "S3Object={Bucket=$BUCKET,Name=input/images/sample-image.jpg}" \
--max-labels 10 \
--region us-east-1 \
--query 'Labels[].[Name,Confidence]' --output tableExample output (your labels and scores depend on the image):
---------------------------------
| DetectLabels |
+-------------+-----------------+
| Person | 99.2 |
| Outdoors | 87.5 |
+-------------+-----------------+Rekognition reads the object from S3 with your credentials, so the bucket
must be in the same region as the Rekognition endpoint (us-east-1 here).
Detect faces
aws rekognition detect-faces \
--image "S3Object={Bucket=$BUCKET,Name=input/images/sample-image.jpg}" \
--attributes ALL \
--region us-east-1 \
--query 'FaceDetails[].{Age:AgeRange,Smile:Smile.Value,Emotion:Emotions[0].Type}'--attributes ALL adds age range, emotions, and other facial attributes.
Rekognition estimates these from appearance; they are not facts about the
person. Treat them with care (see Exam connection below).
Detect text in an image
aws s3 cp sign-image.jpg "s3://$BUCKET/input/images/"
aws rekognition detect-text \
--image "S3Object={Bucket=$BUCKET,Name=input/images/sign-image.jpg}" \
--region us-east-1 \
--query "TextDetections[?Type=='LINE'].DetectedText"Face collection: index and search
aws s3 cp face-image.jpg "s3://$BUCKET/input/images/"
aws s3 cp search-face.jpg "s3://$BUCKET/input/images/"
# Store the face from one photo in the collection
aws rekognition index-faces \
--collection-id "$COLLECTION_ID" \
--image "S3Object={Bucket=$BUCKET,Name=input/images/face-image.jpg}" \
--external-image-id "person-001" \
--region us-east-1 \
--query 'FaceRecords[].Face.FaceId'
# Search the collection with the other photo
aws rekognition search-faces-by-image \
--collection-id "$COLLECTION_ID" \
--image "S3Object={Bucket=$BUCKET,Name=input/images/search-face.jpg}" \
--region us-east-1 \
--query 'FaceMatches[].{Id:Face.ExternalImageId,Similarity:Similarity}'The collection stores face vectors, not the images. destroy deletes the
collection and every face in it.
Test Textract
Synchronous text detection (one page)
aws s3 cp sample-document.pdf "s3://$BUCKET/input/documents/"
aws textract detect-document-text \
--document "S3Object={Bucket=$BUCKET,Name=input/documents/sample-document.pdf}" \
--region us-east-1 \
--query "Blocks[?BlockType=='LINE'].Text"The synchronous API accepts JPEG, PNG, TIFF, and single-page PDF files. For a multi-page PDF it returns an error; use the asynchronous API below.
Asynchronous analysis with an SNS notification
This uses the SNS topic, role, and SQS queue that the textract component
created. Textract assumes the role to publish "job finished" to the topic,
and the queue receives a copy.
JOB_ID=$(aws textract start-document-analysis \
--document-location "S3Object={Bucket=$BUCKET,Name=input/documents/sample-document.pdf}" \
--feature-types TABLES FORMS \
--notification-channel "SNSTopicArn=$TOPIC_ARN,RoleArn=$TEXTRACT_ROLE_ARN" \
--region us-east-1 \
--query JobId --output text)
echo "$JOB_ID"
# Wait for the completion message (repeat if it prints nothing yet)
aws sqs receive-message \
--queue-url "$QUEUE_URL" \
--wait-time-seconds 20 \
--region us-east-1 \
--query 'Messages[0].Body' --output text | jq -Rs 'fromjson? | .Message | fromjson | {JobId, Status}'
# Read the results
aws textract get-document-analysis \
--job-id "$JOB_ID" \
--region us-east-1 \
--query '{Status:JobStatus,Pages:DocumentMetadata.Pages,Tables:length(Blocks[?BlockType==`TABLE`])}'The SQS message body is the SNS envelope; its Message field holds the
Textract notification. get-document-analysis returns results in pages; pass
--next-token to read large documents in full.
Console testing (optional)
- Amazon Rekognition console: open Label detection and upload an image to see labels and bounding boxes.
- Amazon Textract console: open Analyze Document, upload a document, and compare the Raw text, Forms, and Tables tabs.
Cleanup
Destroy in the reverse order of the apply:
atmos terraform destroy textract -s lab-01-vision-test
atmos terraform destroy rekognition -s lab-01-vision-test
atmos terraform destroy iam-role -s lab-01-vision-test
atmos terraform destroy s3-bucket -s lab-01-vision-testThe bucket uses force_destroy, so the uploaded files are deleted with it.
Delete the local test files you no longer need.
Troubleshooting
- AccessDenied - the CLI commands run as your own AWS identity, not as
the lab IAM role. Your identity needs the Rekognition or Textract action
and
s3:GetObjecton the bucket. Check who you are withaws sts get-caller-identity. - InvalidS3ObjectException - check the key with
aws s3 ls "s3://$BUCKET/input/" --recursive, and make sure the bucket is inus-east-1. - InvalidImageFormatException (Rekognition) - use a JPEG or PNG image.
- UnsupportedDocumentException (Textract) - use JPEG, PNG, TIFF, or PDF (a single page for the synchronous API).
- No SQS message - the job may still be running. Check with
aws textract get-document-analysis --job-id "$JOB_ID" --region us-east-1 --query JobStatus.
Cost
Rekognition bills per image analyzed and per face vector stored in a collection each month. Textract bills per page, and AnalyzeDocument with tables and forms costs more per page than DetectDocumentText. SNS, SQS, and S3 cost little at this scale. See Rekognition pricing and Textract pricing. Free Tier terms depend on your account; see AWS Free Tier.
Next steps
- Next: Lab 02 - Language: Comprehend and Translate - sentiment, entities, PII, and translation.
- Back to the lab overview.
- Try
aws textract analyze-document --feature-types QUERIESto ask a question of a document, ordetect-moderation-labelsin Rekognition.
Atmos docs
- Stack Names - how
name_templateturnslabandstageintolab-01-vision-test. - Import Stack Configurations - how the lab stack pulls in
_defaults, the catalog, and the mixins. - Stack Catalogs - the component defaults in
stacks/catalog/. - Using !terraform.output - why
iam-roleneedss3-bucketapplied first. - atmos terraform - the apply, output, and destroy commands used here.
- Workspaces - one Terraform workspace per stack.
Exam connection
This lab practices:
- AIF-C01, Fundamentals of AI and ML - computer vision use cases and the managed AWS services for them: Rekognition for images and faces, Textract for documents (and how Textract differs from Rekognition DetectText).
- AIF-C01, Security, Compliance, and Governance for AI Solutions - least-privilege IAM roles, S3 Block Public Access and encryption, and service roles that let Textract publish to SNS.
- AIF-C01, Guidelines for Responsible AI - face analysis attributes are estimates; consider privacy and consent before you index faces.
- MLA-C01, ML Model Development - choosing a pre-trained AI service instead of training a custom model.
- Terraform Associate (004), Use the Core Terraform Workflow - the
init, plan, apply, and destroy cycle, run for you by
atmos terraform. - Terraform Associate (004), Read, Generate, and Modify Configuration -
countfor optional resources, outputs, and passing one component's output into another component's variables.
Related certification pages: AIF-C01, MLA-C01, Terraform Associate (004).
Practice exam-style questions on these topics on CertLabPro: on the web at https://certlabpro.com/cert/aws-aif-c01, or in the app: https://certlabpro.com/mobile.