พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร
ดึงข้อความ ตาราง และโครงสร้างจากภาพเอกสาร
พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
LLM ในฐานะเครื่องอ่านเอกสาร
เดิมที OCR (การรู้จำอักขระด้วยแสง) จำเป็นต้องใช้ซอฟต์แวร์เฉพาะทางเพื่อดึงข้อความจากภาพ ปัจจุบัน LLM ด้านการมองเห็นสามารถอ่านข้อความจากภาพและยัง เข้าใจ เนื้อหาได้ด้วย — ไม่ใช่เพียงดึงอักขระออกมา แต่ยังวิเคราะห์โครงสร้าง ตาราง ลายมือ และบริบทได้
งานวิเคราะห์เอกสารที่พบบ่อย:
- ดึงข้อความจากเอกสารที่สแกน
- อ่านใบเสร็จ ใบแจ้งหนี้ และแบบฟอร์ม
- วิเคราะห์ตารางและแผนภูมิ
- ถอดความบันทึกที่เขียนด้วยลายมือ
- อ่านฉลากและป้ายที่พิมพ์ไว้
พรอมต์ดึงข้อความพื้นฐาน
สำหรับการดึงข้อความอย่างง่ายจากภาพเอกสาร:
import anthropic, base64
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
def extract_text(image_path, extraction_prompt):
with open(image_path, 'rb') as f:
img_b64 = base64.standard_b64encode(f.read()).decode('utf-8')
r = client.messages.create(
model='claude-opus-4-5', max_tokens=1000,
messages=[{'role': 'user', 'content': [
{'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/jpeg', 'data': img_b64}},
{'type': 'text', 'text': extraction_prompt}
]}]
)
return r.content[0].text
# Basic extraction
basic_prompt = 'Extract all text from this document image exactly as it appears. Preserve line breaks.'
# Structure-preserving extraction
structured_prompt = 'Extract all text from this document image. Preserve: paragraph structure, line breaks, and any visible formatting. Do not add any text not present in the image.'
print('Text extraction functions defined.')การคงโครงสร้างตาราง
เมื่อเอกสารมีตาราง การดึงออกมาเป็นข้อความธรรมดาจะทำให้โครงสร้างสูญหาย ให้ใช้พรอมต์ที่ระบุอย่างชัดเจนว่าต้องคงรูปแบบตารางไว้:
table_prompt = '''
Extract all text from this document image.
If the document contains any tables, preserve the table structure using markdown table format:
| Column 1 | Column 2 | Column 3 |
|----------|----------|----------|
| Value | Value | Value |
For any text outside tables, use plain text preserving paragraph structure.
Do not invent or infer any data not visible in the image.
'''
# For structured output:
table_json_prompt = '''
Extract the table from this image.
Return JSON:
{
"headers": ["column name"],
"rows": [["cell value", "cell value"]],
"caption": "table caption if present or null"
}
If a cell is empty or illegible, use null.
'''
print('Table extraction prompts defined.')การแยกรายการในใบเสร็จ
ใบเสร็จมีโครงสร้างเฉพาะ ได้แก่ ส่วนหัว (ร้านค้า) รายการสินค้า และยอดรวม พรอมต์เฉพาะสำหรับใบเสร็จจะดึงโครงสร้างนี้ได้อย่างน่าเชื่อถือ:
import json
receipt_prompt = '''
Extract all information from this receipt image.
Return JSON:
{
"merchant": {
"name": str,
"address": str or null,
"phone": str or null
},
"transaction": {
"date": "YYYY-MM-DD or as written",
"time": "HH:MM or as written or null",
"receipt_number": str or null,
"payment_method": str or null
},
"items": [
{"description": str, "quantity": number or null, "unit_price": number or null, "total": number}
],
"subtotal": number or null,
"tax": number or null,
"tip": number or null,
"total": number,
"currency": "3-letter ISO code"
}
For any field not visible, use null. For numbers, use numeric type (not string).
'''
def extract_receipt(image_path):
text = extract_text(image_path, receipt_prompt)
return json.loads(text)
print('Receipt extraction function defined.')การถอดความบันทึกที่เขียนด้วยลายมือ
การถอดความเนื้อหาที่เขียนด้วยลายมือต้องใช้พรอมต์ที่ยอมรับความท้าทายต่าง ๆ เช่น คำที่อ่านไม่ออก ข้อความที่ขีดฆ่า และคำย่อ:
handwriting_prompt = '''
Transcribe the handwritten text in this image as accurately as possible.
Handling rules:
- If a word is illegible, write [ILLEGIBLE]
- If a word is partially legible, write [PARTIAL: best_guess]
- If text is crossed out, include it with strikethrough notation: ~~crossed out text~~
- Preserve line breaks as they appear
- If there are arrows, circles, or annotations, note them in brackets: [arrow pointing right]
- Do not correct spelling or grammar
After transcription, estimate overall legibility: high (>90% readable) | medium (70-90%) | low (<70%)
Format:
TRANSCRIPTION:
[transcribed text here]
LEGIBILITY: [rating]
'''
print(handwriting_prompt)การดึงข้อมูลจากช่องแบบฟอร์ม
แบบฟอร์มที่พิมพ์ไว้มีช่องที่มีป้ายกำกับและค่าที่กรอก พรอมต์ดึงข้อมูลจากแบบฟอร์มจะจับคู่ป้ายกำกับกับค่า:
form_prompt = '''
Extract all form fields and their values from this document image.
For each field:
- Field label: the printed label (e.g., "First Name:", "Date of Birth:")
- Field value: the filled-in value (handwritten or typed)
- Filled: whether the field has been filled in (true/false)
Return JSON:
{
"form_title": str or null,
"fields": [
{
"label": str,
"value": str or null,
"filled": true | false
}
],
"signature_present": true | false,
"date_signed": str or null
}
If the value is illegible, use "[ILLEGIBLE]".
If the field is blank, value should be null and filled should be false.
'''
print('Form field extraction prompt defined.')
print('Handles: printed forms, questionnaires, applications.')การจัดประเภทเอกสารก่อนดึงข้อมูล
เชื่อมขั้นตอนการจัดประเภทไว้ก่อนขั้นตอนการดึงข้อมูล เพื่อใช้รูปแบบข้อมูลสำหรับการดึงข้อมูลที่ถูกต้องกับเอกสารแต่ละประเภท:
import json
DOC_SCHEMAS = {
'receipt': receipt_prompt,
'form': form_prompt,
'table': table_json_prompt,
'letter': 'Extract all text preserving paragraph structure. Identify: sender, recipient, date, subject, body.',
'label': 'Extract all text from this label. Include: product name, ingredients/contents, weight, expiry date, barcode numbers.'
}
def classify_and_extract(image_path):
# Step 1: Classify document type
classify_prompt = 'What type of document is this? Return JSON: {"type": "receipt|form|table|letter|label|other", "confidence": "high|medium|low"}'
classification_text = extract_text(image_path, classify_prompt)
doc_type = json.loads(classification_text)['type']
# Step 2: Apply correct schema
schema = DOC_SCHEMAS.get(doc_type, 'Extract all visible text from this document.')
extracted = extract_text(image_path, schema)
return {'type': doc_type, 'data': extracted}
print('Document classify-then-extract pipeline defined.')การจัดการภาพคุณภาพต่ำ
ภาพเอกสารไม่ได้ชัดเจนทุกภาพ พรอมต์ควรจัดการกับภาพที่เสื่อมคุณภาพได้อย่างเหมาะสม:
low_quality_prompt = '''
Extract text from this document image. The image may be low quality, blurry, or poorly lit.
Extraction guidelines:
- Extract all text you can read with reasonable confidence
- For unclear sections, use [UNCLEAR] as a placeholder
- For completely unreadable sections, use [UNREADABLE: approximately N words]
- Do not guess or hallucinate words you cannot see clearly
- Note image quality issues at the end: "Image quality: [good/fair/poor]. Issues: [description]"
Be conservative — it is better to mark something as unclear than to guess incorrectly.
'''
print(low_quality_prompt)
print('\nConservative approach: unclear beats hallucinated.')สรุปเอกสารหลายหน้า
สำหรับเอกสารหลายหน้าที่ส่งเป็นภาพหลายภาพ ให้รวมการดึงข้อมูลทีละหน้ากับขั้นตอนการสังเคราะห์เนื้อหา:
def extract_multi_page_document(image_paths):
# Step 1: Extract text from each page
page_texts = []
for i, path in enumerate(image_paths):
page_text = extract_text(path, f'Extract all text from page {i+1} of this document. Preserve structure.')
page_texts.append(f'=== PAGE {i+1} ===\n{page_text}')
full_text = '\n\n'.join(page_texts)
# Step 2: Synthesize summary and key information
r = client.messages.create(
model='claude-opus-4-5', max_tokens=500,
messages=[{'role': 'user', 'content': f'''
Here is the extracted text from a {len(image_paths)}-page document:\n\n{full_text}\n\n
Provide:
1. Document type and title
2. 3-sentence summary
3. Key data points extracted
Return JSON: {{"type": str, "title": str, "summary": str, "key_data": [str]}}
'''}]
)
return json.loads(r.content[0].text)
print('Multi-page document pipeline defined.')การตรวจสอบหลังการดึงข้อมูลด้วย OCR
ต้องตรวจสอบผลลัพธ์จาก OCR ก่อนนำไปใช้ในระบบถัดไป การตรวจสอบที่พบบ่อยมีดังนี้:
import re
from datetime import datetime
def validate_receipt_extraction(data):
errors = []
# Validate total is present and numeric
if data.get('total') is None:
errors.append('total is missing')
elif not isinstance(data['total'], (int, float)):
errors.append(f'total is not numeric: {data["total"]}')
# Validate date format
if data.get('transaction', {}).get('date'):
date_str = data['transaction']['date']
try:
datetime.strptime(date_str, '%Y-%m-%d')
except ValueError:
errors.append(f'date format invalid: {date_str}')
# Validate line items total approximately equals subtotal
if data.get('items') and data.get('subtotal'):
items_total = sum(item.get('total', 0) for item in data['items'] if item.get('total'))
if abs(items_total - data['subtotal']) > 0.05:
errors.append(f'Items total {items_total} does not match subtotal {data["subtotal"]}')
return errors
print('Receipt validation function defined.')การดึงข้อมูลแบบมีโครงสร้างจากแผนภูมิและกราฟ
แผนภูมิและกราฟในภาพเอกสารมีข้อมูลที่ OCR แบบเดิมมองไม่เห็น แต่ LLM ด้านการมองเห็นสามารถอ่านได้ พรอมต์ดึงข้อมูลจากแผนภูมิจะขอให้โมเดลอ่านค่าข้อมูลที่อยู่เบื้องหลัง:
chart_prompt = '''
Extract the data from this chart or graph image.
Identify:
1. Chart type (bar, line, pie, scatter, table)
2. Title and axis labels
3. All data series names
4. All data points with their labels/values
5. Any notable trend or pattern
Return JSON:
{
"chart_type": str,
"title": str or null,
"x_axis_label": str or null,
"y_axis_label": str or null,
"data_series": [
{"name": str, "values": [{"label": str, "value": number}]}
],
"key_insight": str
}
If exact values are not readable, provide best estimates with a note.
'''
print(chart_prompt)ตรวจสอบความเข้าใจ
เมื่อถอดความเนื้อหาที่เขียนด้วยลายมือจากภาพ ควรใช้แนวทางใดกับคำที่อ่านไม่ออก
OCR และการวิเคราะห์เอกสาร — ประเด็นสำคัญ
LLM ด้านการมองเห็นช่วยให้วิเคราะห์เอกสารได้อย่างยืดหยุ่นและก้าวไกลกว่าการรู้จำอักขระ:
- การดึงข้อมูลพื้นฐาน: คงการขึ้นบรรทัดใหม่และโครงสร้างย่อหน้าไว้ โดยระบุเรื่องนี้อย่างชัดเจน
- ตาราง: ใช้รูปแบบตารางมาร์กดาวน์หรือรูปแบบข้อมูลแถว/ส่วนหัวแบบเจสันเพื่อคงโครงสร้าง
- ใบเสร็จ: ใช้รูปแบบข้อมูลเฉพาะที่มีช่องร้านค้า รายการสินค้า และยอดรวม
- ลายมือ: กำหนดให้ใช้ [ILLEGIBLE] สำหรับข้อความที่อ่านไม่ออก และ [PARTIAL] สำหรับข้อความที่อ่านได้เพียงบางส่วน — ห้ามเดาโดยเด็ดขาด
- แบบฟอร์ม: จับคู่ป้ายกำกับกับค่า และระบุสถานะกรอกแล้ว/ยังไม่ได้กรอกของแต่ละช่อง
- จัดประเภทเอกสารก่อน จากนั้นจึงใช้รูปแบบข้อมูลสำหรับการดึงข้อมูลที่เหมาะสม
- ตรวจสอบข้อมูลที่ดึงออกมาด้วยโปรแกรม: ช่องที่จำเป็น ชนิดข้อมูลตัวเลข รูปแบบวันที่ และการตรวจสอบทางคณิตศาสตร์
- ภาพคุณภาพต่ำ: การดึงข้อมูลอย่างระมัดระวังย่อมดีกว่าการสร้างข้อมูลที่ผิดขึ้นมาอย่างมั่นใจ
เรียนรู้ AI Prompt Engineering ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 53
- บทเรียน
- 199
คำถามที่พบบ่อย
บทเรียน “พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร”
ดึงข้อความ ตาราง และโครงสร้างจากภาพเอกสาร คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม
ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พรอมป์ตสำหรับการบรรยายและใส่คำบรรยายภาพ
- การตอบคำถามด้วยภาพ
- พรอมป์ตสำหรับเปรียบเทียบหลายภาพ
- พรอมป์ตสำหรับ OCR และการวิเคราะห์เอกสาร