/ocr
/ocr (광학 문자 인식)
LiteLLM의 OCR(광학 문자 인식) 엔드포인트를 소개할게요. 문서·이미지에서 텍스트를 추출하는 OCR 호출을 지원하며, Mistral의 OCR API 스펙을 따릅니다. 지원 프로바이더는 mistral, azure_ai, vertex_ai, cohere예요.
| 기능 | 지원 여부 |
|---|---|
| 비용 추적 (Cost Tracking) | ✅ |
| 로깅 (Logging) | ✅ (기본 로깅은 미지원) |
| 로드 밸런싱 (Load Balancing) | ✅ |
| 지원 프로바이더 | mistral, azure_ai, vertex_ai, cohere |
출처: 문서
본문
LiteLLM Python SDK 사용법
빠른 시작 (Quick Start)
from litellm import ocr
import os
os.environ["MISTRAL_API_KEY"] = "sk-.."
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
}
)
# Access extracted text
for page in response.pages:
print(f"Page {page.index}:")
print(page.markdown)
비동기 사용법 (Async Usage)
from litellm import aocr
import os, asyncio
os.environ["MISTRAL_API_KEY"] = "sk-.."
async def test_async_ocr():
response = await aocr(
model="mistral/mistral-ocr-latest",
document={
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
}
)
# Access extracted text
for page in response.pages:
print(f"Page {page.index}:")
print(page.markdown)
asyncio.run(test_async_ocr())
로컬 파일 사용하기 (Using Local Files)
LiteLLM은 수동 base64 인코딩 없이 로컬 파일을 직접 읽을 수 있어요.
from litellm import ocr
# OCR with a local PDF file path
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "file",
"file": "/path/to/document.pdf"
}
)
# OCR with a file object
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "file",
"file": open("document.pdf", "rb")
}
)
# OCR with raw bytes
with open("document.pdf", "rb") as f:
pdf_bytes = f.read()
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "file",
"file": pdf_bytes,
"mime_type": "application/pdf" # recommended for raw bytes (auto-detected from extension for file paths)
}
)
file 필드는 다음 값을 받아요:
- 파일 경로 (
str또는pathlib.Path): LiteLLM이 파일을 읽고 확장자에서 MIME 타입을 감지해요. - 파일 객체 (바이너리 파일 유사 객체): 예:
open("doc.pdf", "rb") - 원시 바이트 (
bytes):mime_type으로 콘텐츠 타입을 지정해요.
LiteLLM은 내부적으로 파일 입력을 base64 데이터 URI로 자동 변환하므로, 모든 프로바이더가 추가 처리 없이 동작해요.
base64 인코딩 문서 사용하기
import base64
from litellm import ocr
# Encode PDF to base64
with open("document.pdf", "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "document_url",
"document_url": f"data:application/pdf;base64,{base64_pdf}"
}
)
선택 파라미터 (Optional Parameters)
response = ocr(
model="mistral/mistral-ocr-latest",
document={
"type": "document_url",
"document_url": "https://example.com/doc.pdf"
},
# Optional Mistral parameters
pages=[0, 1, 2], # Only process specific pages
include_image_base64=True, # Include extracted images
image_limit=10, # Max images to return
image_min_size=100 # Min image size to include
)
LiteLLM 프록시 사용법
LiteLLM은 Mistral API 호환 /ocr 엔드포인트를 OCR 호출용으로 제공해요.
설정 (Setup)
config.yaml에 다음을 추가해요.
model_list:
- model_name: mistral-ocr
litellm_params:
model: mistral/mistral-ocr-latest
api_key: os.environ/MISTRAL_API_KEY
litellm을 시작해요.
litellm --config /path/to/config.yaml
# RUNNING on http://0.0.0.0:4000
JSON 본문 요청 테스트
curl http://0.0.0.0:4000/v1/ocr \
-H "Authorization: Bearer $LITELLM_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mistral-ocr",
"document": {
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
}
}'
multipart 파일 업로드 테스트
multipart 폼 데이터로 파일을 직접 업로드할 수 있어요. 직접 base64 인코딩할 필요가 없어요.
curl http://0.0.0.0:4000/v1/ocr \
-H "Authorization: Bearer $LITELLM_API_KEY" \
-F "model=mistral-ocr" \
-F "file=@/path/to/document.pdf"
선택 파라미터를 추가 폼 필드로도 전달할 수 있어요.
curl http://0.0.0.0:4000/v1/ocr \
-H "Authorization: Bearer $LITELLM_API_KEY" \
-F "model=mistral-ocr" \
-F "[email protected]" \
-F 'pages=[0,1,2]' \
-F "include_image_base64=true"
요청/응답 형식 (Request/Response Format)
LiteLLM은 Mistral OCR API 스펙을 따릅니다. 전체 상세 내용은 공식 Mistral OCR 문서를 참고해 주세요.
예시 요청 (Example Request)
{
"model": "mistral/mistral-ocr-latest",
"document": {
"type": "document_url",
"document_url": "https://arxiv.org/pdf/2201.04234"
},
"pages": [0, 1, 2], # Optional: specific pages to process
"include_image_base64": True, # Optional: include extracted images
"image_limit": 10, # Optional: max images to return
"image_min_size": 100 # Optional: min image size in pixels
}
요청 파라미터 (Request Parameters)
| 파라미터 | 타입 | 필수 | 설명 |
|---|---|---|---|
model |
string | 예 | 사용할 OCR 모델 (예: "mistral/mistral-ocr-latest") |
document |
object | 예 | 처리할 문서. type과 해당 필드를 반드시 포함 |
document.type |
string | 예 | PDF/문서는 "document_url", 이미지는 "image_url", 로컬 파일은 "file" |
document.document_url |
string | 조건부 | 문서의 URL 또는 data URI (type이 "document_url"일 때 필수) |
document.image_url |
string | 조건부 | 이미지의 URL 또는 data URI (type이 "image_url"일 때 필수) |
document.file |
string/bytes/file | 조건부 | 파일 경로, 바이트, 파일 유사 객체 (type이 "file"일 때 필수) |
document.mime_type |
string | 아니요 | 파일 입력의 MIME 타입 명시 (미제공 시 확장자에서 자동 감지) |
pages |
array | 아니요 | 처리할 특정 페이지 인덱스 목록 (0부터 시작) |
include_image_base64 |
boolean | 아니요 | 추출된 이미지를 base64 문자열로 포함할지 여부 |
image_limit |
integer | 아니요 | 반환할 최대 이미지 수 |
image_min_size |
integer | 아니요 | 포함할 이미지의 최소 크기(픽셀) |
문서 형식 예시 (Document Format Examples)
PDF/문서 (URL):
{
"type": "document_url",
"document_url": "https://example.com/document.pdf"
}
이미지 (URL):
{
"type": "image_url",
"image_url": "https://example.com/image.png"
}
base64 인코딩 콘텐츠:
{
"type": "document_url",
"document_url": "data:application/pdf;base64,JVBERi0xLjQKJ..."
}
로컬 파일 (SDK):
{"type": "file", "file": "/path/to/document.pdf"}
{"type": "file", "file": open("image.png", "rb")}
{"type": "file", "file": pdf_bytes, "mime_type": "application/pdf"}
파일 업로드 (Proxy, multipart form):
curl http://0.0.0.0:4000/v1/ocr \
-H "Authorization: Bearer $LITELLM_API_KEY" \
-F "model=mistral-ocr" \
-F "[email protected]"
응답 형식 (Response Format)
응답은 Mistral의 OCR 형식을 따르며 구조는 다음과 같아요.
{
"pages": [
{
"index": 0,
"markdown": "# Document Title\n\nExtracted text content...",
"dimensions": {
"dpi": 200,
"height": 2200,
"width": 1700
},
"images": [
{
"image_base64": "base64string...",
"bbox": {
"x": 100,
"y": 200,
"width": 300,
"height": 400
}
}
]
}
],
"model": "mistral-ocr-2505-completion",
"usage_info": {
"pages_processed": 29,
"doc_size_bytes": 3002783
},
"document_annotation": null,
"object": "ocr"
}
응답 필드 (Response Fields)
| 필드 | 타입 | 설명 |
|---|---|---|
pages |
array | 추출된 콘텐츠가 있는 처리된 페이지 목록 |
pages[].index |
integer | 페이지 번호 (0부터 시작) |
pages[].markdown |
string | Markdown 형식으로 추출된 텍스트 |
pages[].dimensions |
object | 페이지 치수 (dpi, height, width in pixels) |
pages[].images |
array | 페이지에서 추출된 이미지 (include_image_base64=true일 때) |
model |
string | OCR 처리에 사용된 모델 |
usage_info |
object | 처리 통계 (처리된 페이지 수, 문서 크기) |
document_annotation |
object | 선택적인 문서 수준 어노테이션 |
object |
string | OCR 응답에서는 항상 "ocr" |
배치 OCR (Batch OCR)
Mistral OCR은 배치 API로도 동작해요. 각 라인이 /v1/ocr을 가리키는 JSONL 파일을 업로드하고, "endpoint": "/v1/ocr"로 배치를 만든 뒤, 완료되면 출력 파일을 다운로드하면 돼요. 배치에서 처리된 페이지는 해당 모델의 ocr_cost_per_page_batches 요율로 청구됩니다. 전체 흐름과 비용 키는 Mistral files and batches를 참고해 주세요.
지원 프로바이더 (Supported Providers)
| 프로바이더 | 사용 방법 링크 |
|---|---|
| Mistral AI | 사용법, 배치 OCR |
| Azure AI (Mistral, Cohere Parse) | 사용법 |
| Vertex AI | 사용법 |
| Cohere Parse | 사용법 |