PDFToImageContent

PDFToImageContent

PDFToImageContent는 로컬 PDF 파일을 읽어 ImageContent 객체로 변환하는 컴포넌트예요. 이미지 캡셔닝, 시각 QA, 프롬프트 기반 생성 같은 멀티모달 AI 파이프라인에 바로 쓸 수 있는 형태죠.

출처: 문서

본문

항목 내용
파이프라인에서 가장 흔한 위치 쿼리 파이프라인의 ChatPromptBuilder 앞
필수 run 변수 sources: PDF 파일 경로 또는 ByteStream 목록
출력 변수 image_contents: ImageContent 객체 목록
API reference Image Converters
GitHub 링크 pdf_to_image.py
패키지 이름 haystack-ai

개요

PDFToImageContent는 PDF 소스 목록을 처리해 페이지마다 하나씩 ImageContent 객체로 변환해요. base64로 인코딩된 이미지 입력이 필요한 멀티모달 파이프라인에서 쓸 수 있죠.

각 소스는 다음 중 하나가 될 수 있어요:

  • 파일 경로(문자열 또는 Path), 또는
  • ByteStream 객체.

선택적으로 meta 파라미터로 메타데이터를 제공할 수 있어요. 이 값은 모든 이미지에 적용되는 단일 딕셔너리이거나, sources 길이에 맞는 목록일 수 있어요.

size 파라미터를 사용하면 종횡비를 유지하면서 이미지를 리사이즈할 수 있어요. 메모리 사용량과 전송 크기를 줄여주기 때문에, 원격 모델이나 리소스가 제한된 환경에서 작업할 때 유용하죠.

이 컴포넌트는 보통 쿼리 파이프라인에서 ChatPromptBuilder 바로 앞에 사용해요.

사용법

단독으로 사용하기

from haystack.components.converters.image import PDFToImageContent

converter = PDFToImageContent()

sources = ["file.pdf", "another_file.pdf"]
image_contents = converter.run(sources=sources)["image_contents"]

print(image_contents)
# [ImageContent(base64_image='...',
#  mime_type='image/jpeg',
#  detail=None,
#  meta={'file_path': 'file.pdf', 'page_number': 1}),
#  ...]

파이프라인에서 사용하기

PDFToImageContent로 페이지 이미지를 ChatPromptBuilder에 공급해 LLM으로 멀티모달 QA나 캡셔닝을 수행해요.

from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.converters.image import PDFToImageContent

# Query pipeline
pipeline = Pipeline()
pipeline.add_component("image_converter", PDFToImageContent(detail="auto"))
pipeline.add_component(
    "chat_prompt_builder",
    ChatPromptBuilder(
        required_variables=["question"],
        template="""{% message role="system" %}You are a helpful assistant that answers questions using the provided images.{% endmessage %}{% message role="user" %}Question: {{ question }}{% 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")

sources = ["flan_paper.pdf"]
result = pipeline.run(
    data={
        "image_converter": {"sources": ["flan_paper.pdf"], "page_range": "9"},
        "chat_prompt_builder": {"question": "What is the main takeaway of Figure 6?"},
    },
)
print(result["llm"]["replies"][0].text)
# ('The main takeaway of Figure 6 is that Flan-PaLM demonstrates improved '
#  'performance in zero-shot reasoning tasks when utilizing chain-of-thought '
#  '(CoT) reasoning, as indicated by higher accuracy across different model '
#  'sizes compared to PaLM without finetuning. This highlights the importance of '
#  'instruction finetuning combined with CoT for enhancing reasoning '
#  'capabilities in models.')

추가 참고 자료

🧑‍🍳 Cookbook: Introduction to Multimodality

더 알아보기 (Learn more)