Extracting Data from Documents with Amazon Textract and Amazon Bedrock
Learn how to extract data from invoices with Amazon Textract and Amazon Bedrock. Read fields and line items, check the arithmetic in code, tidy the data with a model, flag uncertain documents for review and measure what slips through.
Series: Amazon Bedrock (18 articles)
Read invoices with Amazon Textract, check the numbers in code, use a model to tidy the fields, and send anything doubtful to a person.
Somewhere in most businesses there's a pile of documents that people retype into a system: invoices, receipts, forms. It's slow, and typos creep in. Amazon Textract can read these documents and pull out the fields. Amazon Bedrock can then tidy and classify what it finds. In between, a few plain lines of code can catch the mistakes that matter.
This article walks through that pipeline using invoices as the example: upload a document to S3, extract it with Textract, check the totals, normalise the fields with a model and flag the uncertain ones for human review.
What you need
- The setup from the earlier articles: Python, boto3, and an S3 bucket in your chosen Region
- A small set of sample invoices or receipts you're allowed to use, as PNG, JPEG or PDF files. Start with ten to twenty, and use samples without real customer data if you can.
- Access to a Bedrock text model, with its ID from the model's documentation
- About ninety minutes
Invoices often contain bank details, names and addresses. Use test data where possible, restrict the bucket's access, and read the privacy notes near the end before you use real documents.
How the pipeline fits together
- Upload the document to S3.
- Extract the fields and line items with Textract's invoice and receipt analysis.
- Check the numbers in code. Do the line items add up to the total?
- Normalise with a Bedrock model: consistent date format, a category, a clean vendor name.
- Decide: if confidence is high and the checks pass, accept it. Otherwise, send it to a person.
The important design choice is in step 3. We'll let code do the arithmetic and a model do the tidying. Models are good at language and unreliable at sums, as we saw in the reasoning prompts article on Medium.
Step 1: Upload a sample
aws s3 cp ./sample-invoice.png s3://my-ai-project-dev/raw/invoices/sample-invoice.pngUse the bucket layout from the S3 article, and keep invoices under their own prefix. Textract needs permission to read the object, so the identity you run the code as must be able to read it.
Step 2: Extract with Textract
Textract has several operations. For invoices and receipts, the specialised one is
AnalyzeExpense . It's built to find the fields you'd expect, such as vendor name, date and total, and the individual line items, without you needing to describe the layout.import boto3
REGION = "us-east-1"BUCKET = "my-ai-project-dev"KEY = "raw/invoices/sample-invoice.png"
textract = boto3.client("textract", region_name=REGION)
response = textract.analyze_expense( Document={"S3Object": {"Bucket": BUCKET, "Name": KEY}})This is a synchronous call, which suits single images and short documents. For longer, multi-page documents, Textract has asynchronous versions that start a job and let you collect the result when it's done. Check the current Textract documentation for which file types and page counts each operation supports.
The response contains
ExpenseDocuments . Each one has two parts:- SummaryFields: information found outside of a table, such as the vendor, invoice number, date and totals
- LineItemGroups: the rows of the items table
Each field has a
Type , which says what Textract thinks it is (for example VENDOR_NAME ), and a ValueDetection , which holds the text it read and a confidence score. Fields it can't classify come back with the type OTHER , along with a label, such as "Cashier", which is often still useful.Step 3: Turn the response into something usable
The raw response is verbose. This function flattens it into the fields and line items you care about, keeping the confidence scores:
def parse_expense(response): documents = [] for doc in response.get("ExpenseDocuments", []): fields = {} for field in doc.get("SummaryFields", []): field_type = field.get("Type", {}).get("Text") value = field.get("ValueDetection", {}) if field_type and field_type != "OTHER" and field_type not in fields: fields[field_type] = { "value": value.get("Text"), "confidence": value.get("Confidence", 0), }
line_items = [] for group in doc.get("LineItemGroups", []): for line in group.get("LineItems", []): item = {} for line_field in line.get("LineItemExpenseFields", []): name = line_field.get("Type", {}).get("Text") item[name] = line_field.get("ValueDetection", {}).get("Text") line_items.append(item)
documents.append({"fields": fields, "line_items": line_items}) return documents
invoice = parse_expense(response)[0]for name, field in invoice["fields"].items(): print(name, field["value"], round(field["confidence"]))Run it on a few of your samples and look at what comes back. You'll quickly learn which fields Textract finds reliably on your documents and which it struggles with. The exact field types you get depend on the document, so print them rather than assuming.
Step 4: Check the numbers in code
Now the safety net. If the line items are supposed to add up to the total, check that with ordinary code. A mismatch is one of the best signals that something was misread.
Invoices can include tax, shipping and discounts, so a simple sum of the line items often won't equal the total. A better check is to test the relationships the invoice itself states. If it shows a subtotal, tax and total, check that subtotal plus tax equals the total:
def arithmetic_ok(invoice, tolerance=Decimal("0.05")): f = invoice["fields"] subtotal = to_amount(f.get("SUBTOTAL", {}).get("value")) tax = to_amount(f.get("TAX", {}).get("value")) total = to_amount(f.get("TOTAL", {}).get("value")) if None in (subtotal, tax, total): return None # not enough information to check return abs((subtotal + tax) - total) <= toleranceThe lesson is to be honest about what you can check. If a check can't run, record "unknown" and treat it as a reason for review, not as a pass. Which relationships hold depends on your invoices, so adapt this to the documents you really handle.
Pay attention to money handling. Use
Decimal , not floating-point numbers, for amounts, and be careful with currency symbols and with the comma and full stop conventions that differ between countries.Step 5: Tidy the fields with Bedrock
Textract gives you the text as printed. A model is useful for the clean-up that follows: converting dates to one format, picking a category, tidying a vendor name. We'll ask for strict JSON and validate it, as in the structured output article on Medium.
import json
bedrock = boto3.client("bedrock-runtime", region_name=REGION)MODEL_ID = "YOUR_MODEL_ID"
CATEGORIES = ["office supplies", "travel", "software", "utilities", "meals", "other"]
def normalise(invoice): values = {name: f["value"] for name, f in invoice["fields"].items()} prompt = ( "You are cleaning up data extracted from an invoice. Use only the " "fields provided. Do not invent or change any amounts.\n\n" f"<fields>\n{json.dumps(values)}\n</fields>\n\n" "Return only a JSON object with:\n" "- vendor: the vendor name, tidied\n" "- invoice_date: in YYYY-MM-DD format, or null if unclear\n" f"- category: one of {CATEGORIES}\n" "- notes: anything unusual, or null\n" ) response = bedrock.converse( modelId=MODEL_ID, messages=[{"role": "user", "content": [{"text": prompt}]}], inferenceConfig={"maxTokens": 300, "temperature": 0}, ) raw = response["output"]["message"]["content"][0]["text"].strip() raw = raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip() return json.loads(raw) # validate properly in real useTwo deliberate choices. The prompt tells the model not to touch the amounts, and the amounts never go through it at all, since we keep them from Textract and check them in code. And the date is requested in a fixed format, with a way to say "unclear" instead of guessing.
In real use, validate the JSON against a schema and retry once on failure, as in the structured output article.
Step 6: Decide what needs a person
Now tie it together. Accept a result only if everything looks right. Otherwise flag it.
MIN_CONFIDENCE = 85 # an example threshold; tune it using your own samplesKEY_FIELDS = ["VENDOR_NAME", "TOTAL", "INVOICE_RECEIPT_DATE"]
def needs_review(invoice): reasons = [] for name in KEY_FIELDS: field = invoice["fields"].get(name) if not field: reasons.append(f"missing {name}") elif field["confidence"] < MIN_CONFIDENCE: reasons.append(f"low confidence on {name}") check = arithmetic_ok(invoice) if check is False: reasons.append("totals do not add up") elif check is None: reasons.append("could not check totals") return reasonsThe function returns a list of reasons, and an empty list means it can go straight through. Keeping the reasons is valuable: the person doing the review sees why the item was flagged, and you can count which reasons are common.
The field names above, such as
INVOICE_RECEIPT_DATE , come from Textract's usual output for invoices. Print your own results and use the names you actually see.Step 7: Store the result
Save accepted invoices, and the review queue, somewhere your systems can use them. DynamoDB, from the earlier article, is a good fit: one item per invoice, with the file's S3 key, the cleaned fields, the confidence scores, the review reasons and a status such as
accepted or needs_review . Keep the original file and keep a link to it, so a reviewer can always compare the data with the source.If you want it to run automatically when a file lands in the bucket, the EventBridge and Step Functions article shows how to trigger a workflow on a new upload.
Test it properly
A pipeline like this needs an honest test, in the spirit of the prompt testing article.
- Collect 20 or more documents, including bad ones: blurry scans, rotated pages, handwritten notes, unusual layouts, other languages and a document with no totals.
- Write down the correct values for the key fields by hand, before you run anything.
- Run the pipeline and compare, field by field.
- Count three things: how many fields were right, how many documents went through automatically, and, most important, how many wrong results went through without being flagged.
That last number is the one that matters. A pipeline that flags too much costs you some time. One that passes wrong totals costs you money.
My results
[Add your own results here once you've run it: the number of documents, field-level accuracy for the key fields, how many went through automatically, how many were flagged, the most common reasons for review, anything that surprised you and roughly what it cost. I haven't run this pipeline, so these numbers need to be yours.]
Privacy and safety
- Invoices hold sensitive details, such as bank accounts, addresses and names. Limit who can read the bucket and the table, encrypt them and set retention.
- Don't log full documents or extracted fields unless you have to.
- Think before sending data to a model. Here, only the extracted fields go to the model, not the document. Consider whether even those need masking, using the PII article that follows.
- Keep a person in the loop for anything that moves money.
- Keep an audit trail, with the original file, the extracted data, the checks and who approved what.
What it costs
Textract is priced per page, and different features, such as invoice analysis, have different rates. The Bedrock step costs tokens, which here are small. S3 and DynamoDB add a little. Check the current pricing pages, run your sample set, and multiply by your expected monthly volume.
Common mistakes
- Trusting every field. Always use the confidence scores.
- Letting the model do arithmetic. Use code.
- Treating "can't check" as "passed."
- Using floating-point numbers for money.
- Assuming one layout. Test on the messy documents.
- Skipping the human review path.
- Never measuring wrong results that slipped through.
Clean up
Delete the test files and any table you created, and check your bill after a day or two.
A checklist
- Have you tested on messy documents, not just clean ones?
- Do you check the arithmetic in code, using
Decimal?
- Is "couldn't check" treated as a reason for review?
- Do you use the confidence scores, with a threshold tuned on your own samples?
- Do amounts bypass the model?
- Does a person review the flagged items, with the reasons shown?
- Do you measure wrong results that passed without review?
- Is the bucket and table locked down?
Where we go next
Next, we'll turn audio into text and then into a summary, with Amazon Transcribe and Amazon Bedrock.
Textract operations, field types, limits and pricing change often. Check the current Amazon Textract documentation before you follow any step here, and test everything in a non-production account first.
Series: Amazon Bedrock (18 articles)
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article