MistralOCRDocumentConverter

MistralOCRDocumentConverter

Mistral의 OCR API로 문서에서 텍스트를 추출하는 컴포넌트예요. 개별 이미지 영역과 전체 문서에 대한 선택적 구조화 주석(annotation)을 지원해요. 로컬 파일, URL, Mistral 파일 ID 등 다양한 입력 형식을 지원해요.

출처: MistralOCRDocumentConverter

본문

개요

MistralOCRDocumentConverter는 문서 소스 목록을 받아 Mistral의 OCR API로 이미지와 PDF에서 텍스트를 추출해요. 여러 입력 형식을 지원해요.

  • 로컬 파일: 파일 경로(str 또는 Path)나 ByteStream 객체
  • 원격 리소스: Mistral의 DocumentURLChunk와 ImageURLChunk를 사용한 문서 URL, 이미지 URL
  • Mistral 저장소: 이전에 Mistral에 업로드한 파일의 FileChunk를 사용한 파일 ID

컴포넌트는 소스당 Haystack Document 하나를 반환하며, 모든 페이지는 폼 피드 문자(\f)를 구분자로 연결돼요. 이 형식은 Haystack의 DocumentSplitter와의 호환성을 보장해서 정확한 페이지별 분할과 오버랩 처리를 가능하게 해요. 내용은 markdown 형식으로 반환되며 이미지는 ![img-id](img-id) 태그로 표현돼요.

기본적으로 컴포넌트는 인증에 MISTRAL_API_KEY 환경 변수를 사용해요. 초기화 때 api_key를 전달할 수도 있어요. 로컬 파일은 처리를 위해 Mistral 저장소에 자동 업로드된 뒤 삭제돼요(cleanup_uploaded_files로 구성 가능).

컴포넌트를 초기화할 때 처리할 페이지를 지정하거나, 이미지 추출 제한을 설정하거나, 최소 이미지 크기를 구성하거나, 응답에 base64 인코딩 이미지를 포함할 수도 있어요. 기본 모델은 "mistral-ocr-4-1"이에요. 사용 가능한 모델은 Mistral 모델 문서를 참고하세요.

구조화 주석

MistralOCRDocumentConverter의 독특한 기능은 Pydantic 스키마를 사용한 구조화 주석 지원이에요.

  • 바운딩 박스 주석(bbox_annotation_schema): 개별 이미지 영역에 구조화 데이터로 주석을 답니다(예: 이미지 타입, 설명, 요약). 이 주석들은 markdown 내용의 해당 이미지 태그 뒤에 인라인으로 삽입돼요.
  • 문서 주석(document_annotation_schema): 전체 문서에 구조화 데이터로 주석을 답니다(예: 언어, 장 제목, URL). 이 주석들은 source_ 접두사와 함께 문서의 메타데이터로 풀려요(예: source_language, source_chapter_titles).

주석 스키마를 제공하면 OCR 모델이 먼저 텍스트와 구조를 추출하고, 다음으로 Vision LLM이 내용을 분석해 정의한 Pydantic 스키마에 따라 구조화 주석을 생성해요. 문서 주석은 최대 8페이지로 제한된다는 점을 기억하세요. 자세한 내용은 Mistral의 주석 문서를 참고하세요.

참고: 이 컴포넌트는 Markdown 내용을 반환해요. 기본 설정의 DocumentCleaner()에 통과시키지 않는 게 좋아요. remove_extra_whitespaces=True와 remove_empty_lines=True가 줄바꿈을 붕괴시키고 헤딩·테이블·이미지 태그를 평탄화할 수 있기 때문이에요. 페이지 인식 청킹을 하려면 컨버터를 DocumentSplitter에 직접 연결하거나, 커스텀 정리가 필요하면 해당 옵션을 비활성화하세요.

사용법

MistralOCRDocumentConverter를 쓰려면 mistral-haystack 통합을 설치해야 해요.

pip install mistral-haystack

단독 사용 — 로컬 파일 기본 사용:

from pathlib import Path
from haystack.utils import Secret
from haystack_integrations.components.converters.mistral import (
    MistralOCRDocumentConverter,
)

converter = MistralOCRDocumentConverter(
    api_key=Secret.from_env_var("MISTRAL_API_KEY"),
)

result = converter.run(sources=[Path("my_document.pdf")])
documents = result["documents"]

여러 소스, 다양한 타입 처리:

from pathlib import Path
from haystack.utils import Secret
from haystack_integrations.components.converters.mistral import (
    MistralOCRDocumentConverter,
)
from mistralai.client.models import DocumentURLChunk, ImageURLChunk

converter = MistralOCRDocumentConverter(
    api_key=Secret.from_env_var("MISTRAL_API_KEY"),
)

sources = [
    Path("local_document.pdf"),
    DocumentURLChunk(document_url="https://example.com/document.pdf"),
    ImageURLChunk(image_url="https://example.com/receipt.jpg"),
]

result = converter.run(sources=sources)
documents = result["documents"] # List of 3 Documents
raw_responses = result["raw_mistral_response"] # List of 3 raw responses

구조화 주석 사용:

from pathlib import Path
from typing import List
from pydantic import BaseModel, Field
from haystack.utils import Secret
from haystack_integrations.components.converters.mistral import (
    MistralOCRDocumentConverter,
)
from mistralai.client.models import DocumentURLChunk

# Define schema for image region annotations
class ImageAnnotation(BaseModel):
    image_type: str = Field(..., description="The type of image content")
    short_description: str = Field(
        ...,
        description="Short natural-language description",
    )
    summary: str = Field(..., description="Detailed summary of the image content")

# Define schema for document-level annotations
class DocumentAnnotation(BaseModel):
    language: str = Field(..., description="Primary language of the document")
    chapter_titles: List[str] = Field(
        ...,
        description="Detected chapter or section titles",
    )
    urls: List[str] = Field(..., description="URLs found in the text")

converter = MistralOCRDocumentConverter(
    api_key=Secret.from_env_var("MISTRAL_API_KEY"),
)

sources = [DocumentURLChunk(document_url="https://example.com/report.pdf")]
result = converter.run(
    sources=sources,
    bbox_annotation_schema=ImageAnnotation,
    document_annotation_schema=DocumentAnnotation,
)

documents = result["documents"]
# Document metadata will include:
# - source_language: extracted from DocumentAnnotation
# - source_chapter_titles: extracted from DocumentAnnotation
# - source_urls: extracted from DocumentAnnotation
# Document content will include inline image annotations

파이프라인 안에서:

아래는 PDF를 OCR로 처리하고 Document Store에 작성하는 인덱싱 파이프라인 예시예요.

from haystack import Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.preprocessors import DocumentSplitter
from haystack.components.writers import DocumentWriter
from haystack.utils import Secret
from haystack_integrations.components.converters.mistral import (
    MistralOCRDocumentConverter,
)

document_store = InMemoryDocumentStore()

pipeline = Pipeline()
pipeline.add_component(
    "converter",
    MistralOCRDocumentConverter(
        api_key=Secret.from_env_var("MISTRAL_API_KEY"),
    ),
)
pipeline.add_component("splitter", DocumentSplitter(split_by="page", split_length=1))
pipeline.add_component("writer", DocumentWriter(document_store=document_store))

pipeline.connect("converter", "splitter")
pipeline.connect("splitter", "writer")

file_paths = ["invoice.pdf", "receipt.jpg", "contract.pdf"]
pipeline.run({"converter": {"sources": file_paths}})

더 알아보기 (Learn more)