Azure Document Intelligence OCR

Azure Document Intelligence OCR

Azure Document Intelligence(구 Form Recognizer)의 강력한 사전 구축 모델로 텍스트를 추출하고 문서 구조를 분석해요. LiteLLM의 azure_ai/doc-intelligence/ 라우트로 통합 OCR 기능을 제공해요.

출처: 문서

본문

개요 (Overview)

속성 설명
설명 Azure Document Intelligence(구 Form Recognizer)는 텍스트 추출, 레이아웃 분석, 구조 인식 등 고급 문서 분석 기능을 제공해요
LiteLLM 라우트 azure_ai/doc-intelligence/
지원 작업 /ocr
공급자 문서 Azure Document Intelligence

빠른 시작 (Quick Start)

LiteLLM SDK:

import litellm
import os

# Set environment variables
os.environ["AZURE_DOCUMENT_INTELLIGENCE_API_KEY"] = "your-api-key"
os.environ["AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT"] = "https://your-resource.cognitiveservices.azure.com"

# OCR with PDF URL
response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={
        "type": "document_url",
        "document_url": "https://example.com/document.pdf"
    }
)

# Access extracted text
for page in response.pages:
    print(f"Page {page.index}:")
    print(page.markdown)

LiteLLM Proxy (proxy_config.yaml):

model_list:
  - model_name: azure-doc-intel
    litellm_params:
      model: azure_ai/doc-intelligence/prebuilt-layout
      api_key: os.environ/AZURE_DOCUMENT_INTELLIGENCE_API_KEY
      api_base: os.environ/AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
      model_info:
        mode: ocr

Proxy 시작 후 호출:

litellm --config proxy_config.yaml
curl -X POST http://localhost:4000/ocr \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ***" \
  -d '{
    "model": "azure-doc-intel",
    "document": {
      "type": "document_url",
      "document_url": "https://arxiv.org/pdf/2201.04234"
    }
  }'

동작 방식 (How It Works)

Azure Document Intelligence는 비동기 API 패턴을 사용해요. LiteLLM AI Gateway가 요청/응답 변환과 폴링을 자동으로 처리해요.

LiteLLM이 해주는 일:

  • 요청 변환: Mistral OCR 형식 → Azure Document Intelligence 형식
  • 문서 제출: 변환된 요청을 Azure DI API로 전송
  • 202 응답 처리: 응답 헤더에서 Operation-Location URL 캡처
  • 자동 폴링:
    • retry-after 헤더(기본 2초)가 지정한 간격으로 operation URL을 폴링
    • 상태가 succeeded 또는 failed가 될 때까지 계속
    • Azure의 rate limiting을 retry-after 헤더로 준수
  • 응답 변환: Azure DI 형식 → Mistral OCR 형식
  • 결과 반환: 통합된 Mistral 형식 응답을 클라이언트로 전송

폴링 설정:

  • 기본 타임아웃: 120초
  • AZURE_OPERATION_POLLING_TIMEOUT 환경 변수로 설정 가능
  • 호출 유형에 따라 동기(time.sleep()) 또는 비동기(await asyncio.sleep()) 사용

일반적인 처리 시간: 문서 크기와 복잡도에 따라 2~10초

지원 모델 (Supported Models)

Azure Document Intelligence는 용도별로 최적화된 여러 사전 구축 모델을 제공해요.

prebuilt-layout (권장)

일반 문서 OCR에 구조 보존과 함께 가장 적합해요.

SDK:

import litellm
import os

os.environ["AZURE_DOCUMENT_INTELLIGENCE_API_KEY"] = "your-api-key"
os.environ["AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT"] = "https://your-resource.cognitiveservices.azure.com"

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={
        "type": "document_url",
        "document_url": "https://example.com/document.pdf"
    }
)

Proxy Config:

model_list:
  - model_name: azure-layout
    litellm_params:
      model: azure_ai/doc-intelligence/prebuilt-layout
      api_key: os.environ/AZURE_DOCUMENT_INTELLIGENCE_API_KEY
      api_base: os.environ/AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
      model_info:
        mode: ocr

cURL:

curl -X POST http://localhost:4000/ocr \
  -H "Authorization: Bearer ***" \
  -d '{"model": "azure-layout", "document": {"type": "document_url", "document_url": "https://example.com/doc.pdf"}}'

기능:

  • 마크다운 서식의 텍스트 추출
  • 표 감지 및 추출
  • 문서 구조 분석
  • 문단 및 섹션 인식

가격: 1,000페이지당 $10

prebuilt-read

문서에서 텍스트를 읽기에 최적화 — 가장 빠르고 비용 효율적이에요.

SDK:

import litellm
import os

os.environ["AZURE_DOCUMENT_INTELLIGENCE_API_KEY"] = "your-api-key"
os.environ["AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT"] = "https://your-resource.cognitiveservices.azure.com"

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-read",
    document={
        "type": "document_url",
        "document_url": "https://example.com/document.pdf"
    }
)

Proxy Config:

model_list:
  - model_name: azure-read
    litellm_params:
      model: azure_ai/doc-intelligence/prebuilt-read
      api_key: os.environ/AZURE_DOCUMENT_INTELLIGENCE_API_KEY
      api_base: os.environ/AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
      model_info:
        mode: ocr

cURL:

curl -X POST http://localhost:4000/ocr \
  -H "Authorization: Bearer ***" \
  -d '{"model": "azure-read", "document": {"type": "document_url", "document_url": "https://example.com/doc.pdf"}}'

기능:

  • 빠른 텍스트 추출
  • 읽기 중심 문서에 최적화
  • 기본 구조 인식

가격: 1,000페이지당 $1.50

prebuilt-document

키-값 쌍이 있는 일반 목적 문서 분석이에요.

SDK:

import litellm
import os

os.environ["AZURE_DOCUMENT_INTELLIGENCE_API_KEY"] = "your-api-key"
os.environ["AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT"] = "https://your-resource.cognitiveservices.azure.com"

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-document",
    document={
        "type": "document_url",
        "document_url": "https://example.com/document.pdf"
    }
)

Proxy Config:

model_list:
  - model_name: azure-document
    litellm_params:
      model: azure_ai/doc-intelligence/prebuilt-document
      api_key: os.environ/AZURE_DOCUMENT_INTELLIGENCE_API_KEY
      api_base: os.environ/AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
      model_info:
        mode: ocr

cURL:

curl -X POST http://localhost:4000/ocr \
  -H "Authorization: Bearer ***" \
  -d '{"model": "azure-document", "document": {"type": "document_url", "document_url": "https://example.com/doc.pdf"}}'

가격: 1,000페이지당 $10

문서 유형 (Document Types)

Azure Document Intelligence는 다양한 문서 형식을 지원해요.

PDF 문서

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={
        "type": "document_url",
        "document_url": "https://example.com/document.pdf"
    }
)

이미지 문서

지원 이미지 형식: JPEG, PNG, BMP, TIFF

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={
        "type": "image_url",
        "image_url": "https://example.com/image.png"
    }
)

Base64 인코딩 문서

import base64

# Read and encode PDF
with open("document.pdf", "rb") as f:
    pdf_base64 = base64.b64encode(f.read()).decode()

response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={
        "type": "document_url",
        "document_url": f"data:application/pdf;base64,{pdf_base64}"
    }
)

응답 형식 (Response Format)

# Response has the following structure
response.pages          # List of pages with extracted text
response.model          # Model used
response.object         # "ocr"
response.usage_info     # Token usage information

# Access page content
for page in response.pages:
    print(f"Page {page.index}:")
    print(page.markdown)
    # Page dimensions (in pixels)
    if page.dimensions:
        print(f"Width: {page.dimensions.width}px")
        print(f"Height: {page.dimensions.height}px")

비동기 지원 (Async Support)

import litellm
import asyncio

async def process_document():
    response = await litellm.aocr(
        model="azure_ai/doc-intelligence/prebuilt-layout",
        document={
            "type": "document_url",
            "document_url": "https://example.com/document.pdf"
        }
    )
    return response

# Run async function
response = asyncio.run(process_document())

비용 추적 (Cost Tracking)

LiteLLM이 Azure Document Intelligence OCR 비용을 자동 추적해요.

모델 1,000페이지당 비용
prebuilt-read $1.50
prebuilt-layout $10.00
prebuilt-document $10.00
response = litellm.ocr(
    model="azure_ai/doc-intelligence/prebuilt-layout",
    document={"type": "document_url", "document_url": "https://..."}
)

# Access cost information
print(f"Cost: ${response._hidden_params.get('response_cost', 0)}")

더 알아보기 (Learn more)