DocumentToImageContent

DocumentToImageContent

DocumentToImageContent는 이미지 또는 PDF 파일 기반 문서에서 시각 데이터를 추출해 ImageContent 객체로 변환해요. 이렇게 만들어진 객체는 이미지 질의응답, 캡셔닝 같은 멀티모달 AI 파이프라인에서 바로 사용할 수 있어요.

출처: 문서

본문

  • 파이프라인에서의 일반적인 위치: 쿼리 파이프라인에서 ChatPromptBuilder 앞에 사용해요.
  • 필수 실행 변수: documents(처리할 문서 리스트. 각 문서의 메타데이터에 최소한 file_path_meta_field 키가 있어야 해요. PDF 문서는 변환할 페이지를 지정하기 위해 page_number 키가 추가로 필요해요.)
  • 출력 변수: image_contents(ImageContent 객체 리스트)

개요 (Overview)

DocumentToImageContent는 이미지 또는 PDF 파일 경로를 담은 문서 리스트를 처리해 ImageContent 객체로 변환해요.

  • 이미지의 경우 파일을 직접 읽고 인코딩해요.
  • PDF의 경우 메타데이터의 page_number로 지정된 페이지를 추출해 이미지로 변환해요.

기본적으로 파일 경로를 file_path 메타데이터 필드에서 찾아요. file_path_meta_field 파라미터로 이 필드를 바꿀 수 있어요. root_path는 파일 해석을 위한 공통 기본 디렉터리를 지정할 수 있게 해줘요.

이 컴포넌트는 보통 쿼리 파이프라인에서 사용자 프롬프트에 이미지를 추가하고 싶을 때 ChatPromptBuilder 바로 앞에 배치해요.

size를 지정하면 비율을 유지하면서 이미지 크기가 조정돼요. 이렇게 하면 파일 크기, 메모리 사용량, 처리 시간이 줄어들어요. 해상도 제약이 있는 모델을 다루거나 원격 서비스로 이미지를 전송할 때 유용하죠.

단독 사용 (On its own)

from haystack import Document
from haystack.components.converters.image.document_to_image import (
    DocumentToImageContent,
)

converter = DocumentToImageContent(
    file_path_meta_field="file_path",
    root_path="/data/documents",
    detail="high",
    size=(800, 600),
)

documents = [
    Document(content="Photo of a mountain", meta={"file_path": "mountain.jpg"}),
    Document(
        content="First page of a report",
        meta={"file_path": "report.pdf", "page_number": 1},
    ),
]

result = converter.run(documents)
image_contents = result["image_contents"]
print(image_contents)

# [
# ImageContent(
# base64_image="/9j/4A...", mime_type="image/jpeg", detail="high",
# meta={"file_path": "mountain.jpg"}
# ),
# ImageContent(
# base64_image="/9j/4A...", mime_type="image/jpeg", detail="high",
# meta={"file_path": "report.pdf", "page_number": 1}
# )
# ]

파이프라인에서 사용 (In a pipeline)

DocumentToImageContent는 멀티모달 인덱싱 파이프라인에서 Embedder나 캡셔닝 모델에 넘기기 전에 사용할 수 있어요.

from haystack import Document, Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.converters.image.document_to_image import (
    DocumentToImageContent,
)

# Query pipeline
pipeline = Pipeline()
pipeline.add_component("image_converter", DocumentToImageContent(detail="auto"))
pipeline.add_component(
    "chat_prompt_builder",
    ChatPromptBuilder(
        required_variables=["question"],
        template="""{% message role="system" %}
You are a friendly assistant that answers questions based on provided images.
{% endmessage %}

{%- message role="user" -%}
Only provide an answer to the question using the images provided.

Question: {{ question }}
Answer:

{%- for img in image_contents -%}
  {{ img | templatize_part }}
{%- endfor -%}
{%- endmessage -%}
""",
    ),
)
pipeline.add_component("llm", OpenAIChatGenerator(model="gpt-4o-mini"))

pipeline.connect("image_converter", "chat_prompt_builder.image_contents")
pipeline.connect("chat_prompt_builder", "llm")

documents = [
    Document(content="Cat image", meta={"file_path": "cat.jpg"}),
    Document(content="Doc intro", meta={"file_path": "paper.pdf", "page_number": 1}),
]

result = pipeline.run(
    data={
        "image_converter": {"documents": documents},
        "chat_prompt_builder": {"question": "What color is the cat?"},
    },
)
print(result)

# {
# "llm": {
# "replies": [
# ChatMessage(
# _role=<ChatRole.ASSISTANT: 'assistant'>,
# _content=[TextContent(text="The cat is orange with some black.")],
# _name=None,
# _meta={
# "model": "gpt-4o-mini-2024-07-18",
# "index": 0,
# "finish_reason": "stop",
# "usage": {...},
# },
# )
# ]
# }
# }

추가 자료 (Additional References)

🧑🍳 Cookbook: Introduction to Multimodality

더 알아보기 (Learn more)