AI Prompt Engineering · 강의

OCR 및 문서 분석 프롬프트

문서 이미지에서 텍스트, 표 및 구조를 추출합니다.

레슨 4/413개 단계

OCR 및 문서 분석 프롬프트은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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은 문자 인식을 넘어 유연한 문서 분석을 제공합니다.

  • 기본 추출: 줄바꿈과 단락 구조를 보존하도록 명시합니다.
  • 표: 구조를 보존하기 위해 마크다운 표 형식 또는 JSON 행/머리글 스키마를 사용합니다.
  • 영수증: 판매자, 항목, 합계 필드가 포함된 전용 스키마를 사용합니다.
  • 손글씨: 읽을 수 없는 부분에는 [ILLEGIBLE], 부분적으로 읽을 수 있는 부분에는 [PARTIAL]을 사용하도록 지시합니다 — 절대 추측하지 않습니다.
  • 양식: 라벨과 값의 쌍을 매핑하고 각 필드에 입력 여부 상태를 포함합니다.
  • 먼저 문서 유형을 분류한 다음 적절한 추출 스키마를 적용합니다.
  • 필수 필드, 수치형, 날짜 형식, 산술 검사를 통해 추출한 데이터를 프로그래밍 방식으로 검증합니다.
  • 저품질 이미지에서는 확신에 찬 환각 생성보다 보수적인 추출이 낫습니다.
무료로 시작

AI 튜터와 함께 AI Prompt Engineering을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
53
레슨
199

자주 묻는 질문

“OCR 및 문서 분석 프롬프트” 강의는 무료인가요?

네 — “OCR 및 문서 분석 프롬프트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“OCR 및 문서 분석 프롬프트”에서 뭘 배우나요?

문서 이미지에서 텍스트, 표 및 구조를 추출합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 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(으)로 돌아가기