Skip to main content

Amazon Textract

Amazon Textract คือบริการที่ใช้ Machine Learning ในการสกัดข้อความและข้อมูลจากเอกสารสแกน รูปภาพ และ PDF โดยอัตโนมัติ ต่างจาก OCR ทั่วไปที่อ่านได้แค่ข้อความ Textract เข้าใจโครงสร้างของเอกสาร สามารถระบุ key-value pairs ในฟอร์ม ข้อมูลในตาราง และตอบคำถามเฉพาะเจาะจงจากเอกสารได้ ทำให้ได้ structured data พร้อมใช้งานทันที

บริการนี้ยังมี specialized API สำหรับเอกสารเฉพาะประเภท เช่น ใบเสร็จ/ใบแจ้งหนี้ (Analyze Expense) เอกสารระบุตัวตน (Analyze ID) และเอกสารสินเชื่อ (Analyze Lending) ซึ่งให้ผลลัพธ์ที่มีความแม่นยำสูงกว่าการใช้ general OCR อีกทั้งยังรองรับ Human Review ผ่าน Amazon Augmented AI สำหรับเอกสารที่มีความสำคัญสูง

AWS Docs: https://docs.aws.amazon.com/textract/latest/dg/what-is.html

สถาปัตยกรรม


ฟีเจอร์หลัก

Text Detection (DetectDocumentText)

อ่านข้อความทั้งหมดจากเอกสาร รองรับทั้ง printed text และ handwritten text พร้อมข้อมูลตำแหน่ง (bounding box) และ confidence score ของแต่ละ word และ line เหมาะสำหรับเอกสารที่ต้องการแค่ข้อความดิบ

Form Extraction (AnalyzeDocument - FORMS)

สกัด key-value pairs จากฟอร์มอัตโนมัติ เช่น "ชื่อ: สมชาย ใจดี" หรือ "วันเกิด: 01/01/2530" ระบบระบุ field label และค่าที่สอดคล้องได้โดยอัตโนมัติ ไม่ต้องสร้าง template ล่วงหน้า

Table Extraction (AnalyzeDocument - TABLES)

สกัดข้อมูลจากตารางในเอกสาร รักษาโครงสร้าง row และ column ได้อย่างถูกต้อง รองรับตารางที่มี merged cells และ nested tables เหมาะสำหรับสกัดข้อมูลจากรายงานทางการเงิน ตารางราคา และ spreadsheet ที่สแกนมา

Query-Based Extraction (AnalyzeDocument - QUERIES)

ถามคำถามเฉพาะเจาะจงเกี่ยวกับเอกสาร เช่น "What is the total amount?" หรือ "What is the customer name?" ระบบจะค้นหาและตอบคำถามโดยไม่ต้องสกัดข้อมูลทั้งหมดก่อน เหมาะสำหรับเอกสารที่มีรูปแบบหลากหลาย

Signature Detection

ตรวจจับว่ามีลายเซ็นในเอกสารหรือไม่ และระบุตำแหน่ง เหมาะสำหรับการตรวจสอบว่าสัญญาหรือเอกสารได้รับการลงนามแล้วหรือยัง

Analyze Expense (ใบเสร็จและใบแจ้งหนี้)

API เฉพาะสำหรับสกัดข้อมูลจากใบเสร็จรับเงิน ใบแจ้งหนี้ และ receipts สามารถระบุ vendor name, invoice date, invoice number, line items, amounts, tax และ total โดยอัตโนมัติ รองรับรูปแบบใบแจ้งหนี้หลายหลายแบบ

Analyze ID (เอกสารระบุตัวตน)

สกัดข้อมูลจาก passport, driver's license, national ID และเอกสารยืนยันตัวตนอื่นๆ ระบบรู้จักโครงสร้างของเอกสารประเภทนี้และสามารถระบุ field ต่างๆ เช่น ชื่อ เลขที่เอกสาร วันหมดอายุ ได้อัตโนมัติ

Analyze Lending (เอกสารสินเชื่อ)

API เฉพาะสำหรับประมวลผลเอกสารในกระบวนการ mortgage lending เช่น W-2 forms, 1003 loan applications, bank statements, pay stubs และ tax returns ระบบจำแนกประเภทเอกสารโดยอัตโนมัติและสกัดข้อมูลที่ต้องการตาม schema มาตรฐาน

Async Processing

ประมวลผลเอกสารหลายหน้าหรือขนาดใหญ่แบบ asynchronous ผ่าน StartDocumentAnalysis และ GetDocumentAnalysis ระบบจะแจ้งเมื่อเสร็จผ่าน SNS notification รองรับ PDF สูงสุด 3,000 หน้า

Human Review (Amazon Augmented AI)

ผสานรวมกับ A2I เพื่อให้มนุษย์ review ผลลัพธ์ที่มี confidence ต่ำ เหมาะสำหรับเอกสารที่มีความสำคัญสูงและต้องการความแม่นยำสมบูรณ์


การติดตั้งและการตั้งค่า

1. เปิดใช้งานผ่าน AWS Console

  1. เข้า AWS Console และค้นหา "Amazon Textract"
  2. บริการพร้อมใช้งานทันที ไม่ต้องสร้าง resources
  3. อัปโหลดรูปภาพหรือ PDF ทดสอบในหน้า Textract Demo ก่อนเขียนโค้ด

2. ติดตั้ง boto3 และ dependencies

pip install boto3 Pillow pdf2image

3. IAM Permissions ที่จำเป็น

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"textract:DetectDocumentText",
"textract:AnalyzeDocument",
"textract:AnalyzeExpense",
"textract:AnalyzeID",
"textract:StartDocumentAnalysis",
"textract:GetDocumentAnalysis",
"textract:StartDocumentTextDetection",
"textract:GetDocumentTextDetection"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-documents-bucket/*"
}
]
}

4. ตัวอย่างการตั้งค่า boto3

import boto3

textract = boto3.client(
service_name='textract',
region_name='ap-southeast-1'
)

วิธีใช้งาน

Text Detection จากรูปภาพ

import boto3

textract = boto3.client('textract', region_name='ap-southeast-1')

# อ่านข้อความจากรูปภาพที่เก็บใน S3
response = textract.detect_document_text(
Document={
'S3Object': {
'Bucket': 'my-documents',
'Name': 'scanned-document.jpg'
}
}
)

# รวบรวมข้อความทั้งหมด
full_text = []
for block in response['Blocks']:
if block['BlockType'] == 'LINE':
full_text.append(block['Text'])
print(f"Line: {block['Text']} (Confidence: {block['Confidence']:.1f}%)")

print("\nFull Text:")
print('\n'.join(full_text))

Form Extraction (Key-Value Pairs)

# สกัด key-value pairs จากฟอร์ม
response = textract.analyze_document(
Document={
'S3Object': {'Bucket': 'my-docs', 'Name': 'application-form.pdf'}
},
FeatureTypes=['FORMS']
)

# Parse key-value pairs
key_map = {}
value_map = {}
block_map = {}

for block in response['Blocks']:
block_id = block['Id']
block_map[block_id] = block

if block['BlockType'] == 'KEY_VALUE_SET':
if 'KEY' in block.get('EntityTypes', []):
key_map[block_id] = block
else:
value_map[block_id] = block

def get_text(result, blocks):
text = ''
if result.get('Relationships'):
for rel in result['Relationships']:
if rel['Type'] == 'CHILD':
for child_id in rel['Ids']:
word = blocks[child_id]
if word['BlockType'] == 'WORD':
text += word['Text'] + ' '
return text.strip()

print("Form Fields:")
for key_id, key_block in key_map.items():
value_block = None
if key_block.get('Relationships'):
for rel in key_block['Relationships']:
if rel['Type'] == 'VALUE':
for val_id in rel['Ids']:
value_block = value_map.get(val_id)

key_text = get_text(key_block, block_map)
val_text = get_text(value_block, block_map) if value_block else ''
print(f" {key_text}: {val_text}")

Analyze Expense (ใบแจ้งหนี้)

# สกัดข้อมูลจากใบแจ้งหนี้/ใบเสร็จ
response = textract.analyze_expense(
Document={
'S3Object': {'Bucket': 'invoices', 'Name': 'invoice_2024.pdf'}
}
)

for expense_doc in response['ExpenseDocuments']:
print("Summary Fields:")
for field in expense_doc.get('SummaryFields', []):
field_type = field.get('Type', {}).get('Text', 'Unknown')
value = field.get('ValueDetection', {}).get('Text', '')
print(f" {field_type}: {value}")

print("\nLine Items:")
for group in expense_doc.get('LineItemGroups', []):
for item in group.get('LineItems', []):
for field in item.get('LineItemExpenseFields', []):
field_type = field.get('Type', {}).get('Text', '')
value = field.get('ValueDetection', {}).get('Text', '')
print(f" {field_type}: {value}")

Analyze ID (บัตรประชาชน / พาสปอร์ต)

# สกัดข้อมูลจากเอกสารระบุตัวตน
response = textract.analyze_id(
DocumentPages=[
{
'S3Object': {'Bucket': 'kyc-docs', 'Name': 'passport.jpg'}
}
]
)

for id_doc in response['IdentityDocuments']:
print("ID Document Fields:")
for field in id_doc.get('IdentityDocumentFields', []):
field_type = field.get('Type', {}).get('Text', '')
value = field.get('ValueDetection', {}).get('Text', '')
confidence = field.get('ValueDetection', {}).get('Confidence', 0)
print(f" {field_type}: {value} ({confidence:.1f}%)")
# FIRST_NAME: SOMCHAI (99.2%)
# LAST_NAME: JAIDEE (98.8%)
# DATE_OF_BIRTH: 01-01-1990 (99.5%)
# DOCUMENT_NUMBER: AB1234567 (99.9%)
# EXPIRATION_DATE: 31-12-2030 (99.7%)

Query-Based Extraction

# ถามคำถามเฉพาะเจาะจงจากเอกสาร
response = textract.analyze_document(
Document={
'S3Object': {'Bucket': 'contracts', 'Name': 'service-agreement.pdf'}
},
FeatureTypes=['QUERIES'],
QueriesConfig={
'Queries': [
{'Text': 'What is the contract start date?', 'Alias': 'START_DATE'},
{'Text': 'What is the total contract value?', 'Alias': 'CONTRACT_VALUE'},
{'Text': 'Who is the service provider?', 'Alias': 'PROVIDER'}
]
}
)

for block in response['Blocks']:
if block['BlockType'] == 'QUERY_RESULT':
print(f"Answer: {block.get('Text', 'Not found')}")
print(f"Confidence: {block.get('Confidence', 0):.1f}%")

Async Processing สำหรับ PDF หลายหน้า

import time

# เริ่ม async job
response = textract.start_document_analysis(
DocumentLocation={
'S3Object': {'Bucket': 'large-docs', 'Name': 'annual-report-100pages.pdf'}
},
FeatureTypes=['FORMS', 'TABLES'],
NotificationChannel={
'SNSTopicArn': 'arn:aws:sns:ap-southeast-1:123456789:textract-done',
'RoleArn': 'arn:aws:iam::123456789:role/TextractRole'
}
)

job_id = response['JobId']
print(f"Job started: {job_id}")

# ตรวจสอบสถานะ
while True:
result = textract.get_document_analysis(JobId=job_id)
status = result['JobStatus']
print(f"Status: {status}")

if status in ['SUCCEEDED', 'FAILED']:
break
time.sleep(5)

ราคา (ประมาณการในบาท)

อัตราแลกเปลี่ยน: 1 USD = 35 บาท

ฟีเจอร์ราคา (USD)ราคา (บาท)
Text Detection$0.0015/page0.053 บาท/หน้า
Forms + Tables Analysis$0.015/page0.53 บาท/หน้า
Queries$0.0035/query0.12 บาท/query
Analyze Expense$0.05/page1.75 บาท/หน้า
Analyze ID$0.05/page1.75 บาท/หน้า
Analyze Lending$0.05/page1.75 บาท/หน้า
Signature Detectionรวมกับ FORMS-

Free Tier:

  • 1,000 หน้า/เดือน สำหรับ Text Detection (3 เดือนแรก)
  • 100 หน้า/เดือน สำหรับ Forms, Tables, Queries (3 เดือนแรก)

ตัวอย่างการคำนวณ:

  • ประมวลผลใบแจ้งหนี้ 10,000 ใบ (1 หน้า/ใบ) ด้วย Analyze Expense

  • ค่าใช้จ่าย = 10,000 × $0.05 = $500 (~17,500 บาท)

  • ประมวลผลแบบฟอร์มสมัครสินเชื่อ 1,000 ชุด (5 หน้า/ชุด) ด้วย Forms + Tables

  • ค่าใช้จ่าย = 5,000 × $0.015 = $75 (~2,625 บาท)


เหมาะสำหรับ

  • ธนาคารและสถาบันการเงิน ที่ต้องการประมวลผลเอกสารสินเชื่อ bank statement และ KYC documents
  • บริษัทประกัน สำหรับ automated claims processing และ policy document extraction
  • โรงพยาบาล ที่ต้องการ digitize เวชระเบียนเก่าและแบบฟอร์มทางการแพทย์
  • ฝ่าย Accounts Payable ที่ต้องการ automate การประมวลผลใบแจ้งหนี้และใบเสร็จ
  • หน่วยงานรัฐ ที่ต้องการสกัดข้อมูลจากแบบฟอร์มกระดาษจำนวนมาก
  • บริษัท Logistics สำหรับ shipping documents, customs forms และ delivery receipts

ใช้ร่วมกับ AWS Services

AWS Serviceการผสานรวม
Amazon S3เก็บเอกสาร input และผลลัพธ์ที่สกัดได้
AWS Lambdaประมวลผล Textract แบบ event-driven
Amazon Comprehendวิเคราะห์ข้อความที่สกัดมาเพิ่มเติม
Amazon Comprehend Medicalวิเคราะห์ medical text จากเวชระเบียน
Amazon Augmented AI (A2I)Human review สำหรับ low-confidence results
Amazon DynamoDB / RDSเก็บ structured data ที่สกัดได้
AWS Step Functionsสร้าง document processing workflow
Amazon SNSรับ notification เมื่อ async job เสร็จ

Use Case ตัวอย่าง

1. ระบบประมวลผลสินเชื่ออัตโนมัติ

ธนาคารแห่งหนึ่งใช้ Textract ประมวลผลเอกสารสมัครสินเชื่อที่ลูกค้าอัปโหลดผ่านแอป เอกสารแต่ละชุดประกอบด้วย สลิปเงินเดือน bank statement 3 เดือน และบัตรประชาชน Textract Analyze ID สกัดข้อมูลจากบัตรประชาชนโดยอัตโนมัติ Forms API สกัดข้อมูลรายได้จากสลิป และ Tables API สกัดรายการเดินบัญชี ข้อมูลทั้งหมดถูกส่งเข้าระบบ core banking โดยตรง ลดเวลาอนุมัติสินเชื่อจาก 3 วันเหลือเพียง 4 ชั่วโมง และลด manual data entry errors ลง 99%

2. ระบบประมวลผลใบแจ้งหนี้อัตโนมัติ

บริษัทขนาดใหญ่ที่มี supplier กว่า 500 ราย ได้รับใบแจ้งหนี้กว่า 5,000 ใบต่อเดือนในรูปแบบ PDF ที่หลากหลาย ระบบ S3 trigger Lambda ทุกครั้งที่ใบแจ้งหนี้ถูกอัปโหลด Textract Analyze Expense สกัด vendor name, invoice number, line items และ total amount ระบบตรวจสอบข้อมูลกับ PO ในระบบ ERP โดยอัตโนมัติ และอนุมัติการจ่ายเงินสำหรับ invoices ที่ match โดยไม่ต้องมีมนุษย์ review ลดต้นทุนการประมวลผลต่อใบจาก 150 บาทเหลือเพียง 5 บาท

3. ระบบ Digitize เวชระเบียนโรงพยาบาล

โรงพยาบาลขนาดใหญ่มีเวชระเบียนกระดาษสะสมอยู่กว่า 2 ล้านฉบับ ต้องการแปลงให้เป็นดิจิทัลเพื่อใช้ analytics และ research ระบบ batch processing ส่งเอกสารสแกนเข้า Textract ผ่าน async API สกัดข้อมูลผู้ป่วย การวินิจฉัย การรักษา และยาที่ใช้ จากนั้น Comprehend Medical วิเคราะห์เนื้อหาทางการแพทย์และ map กับ ICD-10 codes ข้อมูลที่ได้ถูกเก็บใน AWS HealthLake เพื่อใช้ในการวิจัยและวางแผนรักษาผู้ป่วย โครงการที่เคยประเมินว่าต้องใช้เวลา 5 ปีด้วยแรงงานมนุษย์ สำเร็จในเวลาเพียง 3 เดือน