AWS Builder Center
Turn Any Document Into Speech on AWS with Textract, Polly, and Lambda

Turn Any Document Into Speech on AWS with Textract, Polly, and Lambda

Build a serverless pipeline that OCRs a scanned image with Amazon Textract and synthesizes the extracted text into natural MP3 audio with Amazon Polly, all orchestrated by a single Python Lambda function. Includes step-by-step Console and CLI instructions, the IAM policy, a cost breakdown, and cleanup commands.

Software Development Engineer

1. The Problem

Scanned documents — JPEGs, PNGs, PDFs of receipts, letters, medical records, ID cards — are silent and inaccessible. The text inside them can't be searched, copied, or read aloud. For visually impaired users, for people who prefer audio, or for content that needs to be consumed on the go, that content is effectively locked away.
In this walkthrough we'll build a small serverless pipeline that:
  1. Reads a document image from Amazon S3
  1. Extracts its text with Amazon Textract
  1. Converts that text to natural-sounding speech with Amazon Polly
  1. Writes the resulting MP3 back to S3
No machine learning expertise required. Three managed services and roughly 40 lines of Python.



2. Architecture

Source code & Architecture —  Source Code 

Stage
Service
What happens
1. Input
S3
Source document textract_sample.jpeg is stored in a bucket
2. Orchestration
Lambda
A Python function is triggered and coordinates the flow
3. OCR
Textract
detect_document_text() reads text from the image
4. Synthesis
Polly
start_speech_synthesis_task() turns text into an MP3
5. Output
S3
The MP3 is written to s3://<bucket>/output/<taskId>.mp3



3. Prerequisites

Before you start, make sure you have:
  • An AWS account (the free tier is enough to try this once or twice)
  • Python 3.9+ installed locally (only needed to package the Lambda)
  • Either:
  • AWS Management Console access, or
  • AWS CLI v2 installed and configured ( aws configure  with an access key that has admin rights, or at least permissions for S3, IAM, Lambda, Textract, and Polly)
Pick the region closest to you — Textract and Polly are available in most (e.g.,  us-east-1 ,  eu-west-1 ). We'll use  us-east-1  in the commands below; substitute your own.



4. Step 1 — Create the S3 Bucket & Upload a Sample

You need a sample image containing text. Any scanned page or screenshot of text works. Save it locally as  textract_sample.jpeg  (the function looks for this exact key).

Console

  1. Open S3 → Create bucket
  1. Bucket name:  doc-handling-<your-initials>-001  (must be globally unique)
  1. Leave defaults (Block All Public Access = ON), Create
  1. Open the bucket → Upload → add  textract_sample.jpeg  → Upload

CLI

# Create the bucket
aws s3 mb s3://doc-handling-yourname-001 --region us-east-1

# Upload your sample image
aws s3 cp textract_sample.jpeg s3://doc-handling-yourname-001/textract_sample.jpeg

Remember your bucket name — you'll set it as the  BUCKET_NAME  environment variable in Step 4.



5. Step 2 — Create the IAM Execution Role

Lambda needs a role it can assume that grants permission to read/write S3, call Textract, and call Polly.

Console

  1. IAM → Roles → Create role
  1. Trusted entity: AWS service → Lambda
  1. Permissions: attach  AmazonS3ReadOnlyAccess ,  AmazonTextractFullAccess ,  AmazonPollyFullAccess  (fine for a learning exercise)
  1. Role name:  lambda-doc-handler-role  → Create role

CLI

Create a trust policy file first:
// trust-policy.json
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole"
}]
}

Create the role and attach a permissions policy:
# Create the role
aws iam create-role \
--role-name lambda-doc-handler-role \
--assume-role-policy-document file://trust-policy.json

# Attach the three managed policies
aws iam attach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
aws iam attach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonTextractFullAccess
aws iam attach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonPollyFullAccess

Minimal inline policy (alternative). If you prefer least-privilege over the broad managed policies above, attach this inline policy instead. It grants only what the function actually uses:__PRE_PLACEHOLDER_3__
Save your Account ID — you'll need the role's full ARN in Step 4:  arn:aws:iam::<ACCOUNT_ID>:role/lambda-doc-handler-role 



6. Step 3 — Package the Function

The Lambda needs  boto3  bundled into the deployment package (the runtime includes it by default, but packaging your own version is safest). From the project directory containing  document_handler.py :
# Install boto3 into the current folder
pip install boto3 -t .

# Zip everything up
zip -r document-handler.zip .

This produces  document-handler.zip , which you'll upload in the next step.
Console-only path: if you'd rather not package locally, you can paste the code directly into the Lambda console's inline editor and let AWS handle the runtime —  boto3  is included in the Python 3.9 runtime, so no zip is needed. Skip to Step 4's Console path.



7. Step 4 — Create the Lambda Function

Console

  1. Lambda → Create function → Author from scratch
  1. Function name:  document-handler 
  1. Runtime: Python 3.9
  1. Architecture: x86_64
  1. Execution role: Use an existing role → pick  lambda-doc-handler-role 
  1. Create function
  1. Scroll to Code source, paste the contents of  document_handler.py , Deploy
  1. Go to Configuration → Environment variables → add:
  • Key:  BUCKET_NAME 
  • Value:  doc-handling-yourname-001 
  1. Go to Configuration → General → Edit timeout → set to 1 minute (Textract + Polly can take a few seconds)
  1. Save

CLI

aws lambda create-function \
--function-name document-handler \
--runtime python3.9 \
--role arn:aws:iam::<ACCOUNT_ID>:role/lambda-doc-handler-role \
--handler document_handler.lambda_handler \
--zip-file fileb://document-handler.zip \
--timeout 60 \
--environment Variables={BUCKET_NAME=doc-handling-yourname-001} \
--region us-east-1




8. Step 5 — Invoke the Function & Verify

Invoke

aws lambda invoke \
--function-name document-handler \
--payload '{}' \
--region us-east-1 \
response.json

The payload is empty  {}  because the function reads its inputs from the environment variable and a hardcoded key — it doesn't need event data.

Read the response

cat response.json
# {"taskId": "abc123def456..."}

Polly's  start_speech_synthesis_task  is asynchronous — it returns a  taskId  immediately and writes the MP3 to S3 in the background once synthesis finishes (usually a few seconds for a single page).

Fetch the MP3

# List the output folder
aws s3 ls s3://doc-handling-yourname-001/output/

# Download the file
aws s3 cp s3://doc-handling-yourname-001/output/<taskId>.mp3 ./output.mp3

# Play it
xdg-open output.mp3 # Linux
open output.mp3 # macOS
start output.mp3 # Windows

You should hear the document's text spoken aloud. That's it — you've turned a scanned image into audio.



9. How It Works — Code Walkthrough

Here's the entire function, annotated:
import boto3
import os

# Read the target bucket from the environment variable set in Step 4
s3_bucket = os.environ['BUCKET_NAME']
sample_file = 'textract_sample.jpeg' # hardcoded input key

def lambda_handler(event, context):

textract_client = boto3.client('textract')
text2speech = ''

# 1. OCR — send the S3 object to Textract
textract_response = textract_client.detect_document_text(
Document={
'S3Object': {
'Bucket': s3_bucket,
'Name': sample_file
}
})

# 2. Textract returns a list of "Blocks". Each block has a BlockType
# (LINE, WORD, PAGE, etc.). We keep only LINE blocks and join their
# Text fields into one continuous string.
for item in textract_response["Blocks"]:
if item["BlockType"] == "LINE":
text2speech = text2speech + ' ' + item["Text"]

print(text2speech) # visible in CloudWatch Logs

# 3. Synthesis — send the text to Polly as an async batch task
polly_client = boto3.client('polly')
response = polly_client.start_speech_synthesis_task(
VoiceId='Ruth', # a natural generative voice
OutputFormat='mp3',
OutputS3BucketName=s3_bucket, # where to write the MP3
OutputS3KeyPrefix='output', # prefix/folder inside the bucket
Text=text2speech,
Engine='generative') # higher-quality neural engine

taskId = response['SynthesisTask']['TaskId']

return { 'taskId': taskId }


Key concepts

  •  detect_document_text  is Textract's synchronous OCR API. It returns blocks of type  PAGE ,  BLOCK ,  LINE , and  WORD . Filtering to  LINE  gives you readable sentences without duplicate word-level fragments.
  •  start_speech_synthesis_task  is Polly's asynchronous API — it's meant for longer text and writes the audio file directly to S3, so the Lambda doesn't have to stream the audio back as a response payload. The trade-off: you get a  taskId , not the audio itself, and you poll or just check S3 once it's done.
  •  Engine='generative'  uses Polly's newer high-quality voices.  Ruth  is one of the generative voices; others include  Lupe ,  Aria ,  Justin , etc. Swap  VoiceId  to experiment.
  • The function reads its inputs from the environment ( BUCKET_NAME ) and a hardcoded key ( textract_sample.jpeg ). In a production system you'd parameterize the key from the event, but for a learning demo this keeps things minimal.



10. Cost Breakdown

This pipeline is cheap to experiment with. Rough per-invocation costs:
Service
Charge
Example (1 page, ~500 chars)
Textract
$0.0015 per page (DetectDocumentText API)
$0.0015
Polly
~$0.0004 per character (standard) / $0.0015 per char (generative)
~$0.75 for 500 chars on generative*
Lambda
$0.0000002 per request + compute time
negligible
S3
Storage ($0.023/GB-month) + request fees
cents
*Polly generative-engine pricing is higher than standard — for a quick test this is fine; check the  Polly pricing page  for the latest numbers. A single one-page demo typically costs well under a dollar.



11. Troubleshooting

Symptom
Likely cause
Fix
AccessDeniedException from Textract/Polly
Role missing policies
Re-verify the role has Textract + Polly permissions (Step 2)
NoSuchKey on textract_sample.jpeg
Wrong bucket name or key
Confirm the env var BUCKET_NAME matches your bucket, and the file is uploaded with the exact key textract_sample.jpeg
Task timed out after 3s
Default Lambda timeout is 3s
Raise the timeout to 60s (Step 4, item 9)
MP3 not in output/ yet
Polly async task still running
Wait ~10s and re-list the prefix
Empty audio / silence
Textract found no LINE blocks
Check the document is legible text, not a photo with no text



12. Cleanup

To avoid ongoing charges, tear down what you created:
# Empty and delete the bucket
aws s3 rm s3://doc-handling-yourname-001 --recursive
aws s3 rb s3://doc-handling-yourname-001

# Delete the Lambda function
aws lambda delete-function --function-name document-handler

# (Optional) Delete the IAM role
aws iam detach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
aws iam detach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonTextractFullAccess
aws iam detach-role-policy --role-name lambda-doc-handler-role \
--policy-arn arn:aws:iam::aws:policy/AmazonPollyFullAccess
aws iam delete-role --role-name lambda-doc-handler-role

Or in the Console: delete the Lambda, empty + delete the bucket, and remove the role under IAM → Roles.



Recap

You built a fully serverless document-to-audio pipeline using three AWS services and a single Python function:
  • S3 held the input and output
  • Textract did the OCR
  • Polly did the text-to-speech
  • Lambda glued it together
From here, interesting extensions to try next (out of scope for this demo): trigger the Lambda automatically when a new file lands in S3 (S3 Event Notifications), parameterize the input key from the event, add a DynamoDB table to track synthesis jobs, or swap Polly's voice by language.
Happy building.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article