0Pricing
AI Prompt Engineering · レッスン

OCR とドキュメント分析のプロンプト

文書画像からテキスト、表、構造を抽出します。

「OCR とドキュメント分析のプロンプト」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。

ドキュメントリーダーとしてのLLM

OCR(光学文字認識)では従来、画像からテキストを抽出するために専用ソフトウェアが必要でした。現在ではVision 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では見えないものの、Vision 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とドキュメント分析 — 要点

Vision LLMは、文字認識を超えた柔軟なドキュメント分析を提供します。

  • 基本的な抽出:改行と段落構造を保持し、そのことを明示的に指定します
  • 表:構造を保持するため、Markdownの表形式またはJSONの行/ヘッダースキーマを使用します
  • レシート:店舗、項目、合計のフィールドを含む専用スキーマを使用します
  • 手書き文字:読めない部分には[ILLEGIBLE]、部分的に読める部分には[PARTIAL]を使用し、決して推測しないよう指示します
  • フォーム:ラベルと値のペアを対応付け、各フィールドに入力済み/未入力の状態を含めます
  • まずドキュメントの種類を分類し、その後で適切な抽出スキーマを適用します
  • 必須フィールド、数値型、日付形式、計算結果などをプログラムで確認し、抽出データを検証します
  • 低品質画像では、自信ありげなハルシネーションよりも保守的な抽出を優先します

よくある質問

「OCR とドキュメント分析のプロンプト」レッスンは無料ですか?

はい。「OCR とドキュメント分析のプロンプト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。

「OCR とドキュメント分析のプロンプト」で何を学びますか?

文書画像からテキスト、表、構造を抽出します。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Prompt Engineeringを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「OCR とドキュメント分析のプロンプト」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Prompt Engineeringレッスンでコードを書いて実行できますか?

はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 画像説明とキャプション作成のプロンプト
  2. 画像に関する質問応答
  3. 複数画像の比較プロンプト
  4. OCR とドキュメント分析のプロンプト
← AI Prompt Engineeringに戻る