Mistral Pixtral-12B 모델로 이미지 추론하기
Mistral Pixtral-12B 모델로 이미지 추론하기 (Multi-Modal LLM)
LlamaIndex에서 MistralAI Multi-Modal LLM 추상화를 사용해 이미지 이해/추론을 하는 방법을 보여주는 노트북이에요. Pixtral 멀티모달 LLM이 지원하는 complete 계열 함수들을 동기·비동기, 스트리밍 방식으로 모두 다루며, URL과 로컬 파일에서 이미지를 로드하는 방법도 살펴봅니다.
출처: 문서
본문
Pixtral 멀티모달 LLM이 지원하는 함수는 다음과 같아요.
complete(동기·비동기): 단일 프롬프트와 이미지 목록 처리stream complete(동기·비동기):complete의 스트리밍 출력
필요한 패키지를 설치하고 API 키를 설정합니다.
%pip install llama-index-multi-modal-llms-mistralai
%pip install matplotlib
import os
from IPython.display import Markdown, display
os.environ[
"MISTRAL_API_KEY"
] = "<YOUR API KEY>" # Your MistralAI API token here
MistralAIMultiModal 초기화
from llama_index.multi_modal_llms.mistralai import MistralAIMultiModal
mistralai_mm_llm = MistralAIMultiModal(
model="pixtral-12b-2409", max_new_tokens=300
)
URL에서 이미지 로드하기
from llama_index.core.multi_modal_llms.generic_utils import load_image_urls
image_urls = [
"https://tripfixers.com/wp-content/uploads/2019/11/eiffel-tower-with-snow.jpeg",
"https://cdn.statcdn.com/Infographic/images/normal/30322.jpeg",
]
image_documents = load_image_urls(image_urls)
첫 번째 이미지를 확인해 봅니다.
from PIL import Image
import requests
from io import BytesIO
import matplotlib.pyplot as plt
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
img_response = requests.get(image_urls[0], headers=headers)
print(image_urls[0])
img = Image.open(BytesIO(img_response.content))
plt.imshow(img)
두 번째 이미지도 확인합니다.
img_response = requests.get(image_urls[1], headers=headers)
print(image_urls[1])
img = Image.open(BytesIO(img_response.content))
plt.imshow(img)
이미지 여러 장을 담은 프롬프트 완성하기
complete_response = mistralai_mm_llm.complete(
prompt="Describe the images as an alternative text in a few words",
image_documents=image_documents,
)
display(Markdown(f"{complete_response}"))
여러 이미지의 프롬프트 스트림 완성하기 (Stream Complete)
stream_complete_response = mistralai_mm_llm.stream_complete(
prompt="give me more context for this images in a few words",
image_documents=image_documents,
)
for r in stream_complete_response:
print(r.delta, end="")
비동기 완성 (Async Complete)
response_acomplete = await mistralai_mm_llm.acomplete(
prompt="Describe the images as an alternative text in a few words",
image_documents=image_documents,
)
display(Markdown(f"{response_acomplete}"))
비동기 스트림 완성 (Async Steam Complete)
response_astream_complete = await mistralai_mm_llm.astream_complete(
prompt="Describe the images as an alternative text in a few words",
image_documents=image_documents,
)
async for delta in response_astream_complete:
print(delta.delta, end="")
두 개의 이미지로 완성하기
두 이미지를 비교하는 프롬프트를 실행해 봅니다.
image_urls = [
"https://tripfixers.com/wp-content/uploads/2019/11/eiffel-tower-with-snow.jpeg",
"https://assets.visitorscoverage.com/production/wp-content/uploads/2024/04/AdobeStock_626542468-min-1024x683.jpeg",
]
img_response = requests.get(image_urls[0], headers=headers)
print(image_urls[0])
img = Image.open(BytesIO(img_response.content))
plt.imshow(img)
image_documents_compare = load_image_urls(image_urls)
response_multi = mistralai_mm_llm.complete(
prompt="What are the differences between two images?",
image_documents=image_documents_compare,
)
display(Markdown(f"{response_multi}"))
로컬 파일에서 이미지 로드하기
로컬에 있는 영수증 이미지를 내려받아 불러오고 텍스트를 추출합니다.
!wget 'https://www.boredpanda.com/blog/wp-content/uploads/2022/11/interesting-receipts-102-6364c8d181c6a__700.jpg' -O 'receipt.jpg'
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open("./receipt.jpg")
plt.imshow(img)
from llama_index.core import SimpleDirectoryReader
# put your local directore here
image_documents = SimpleDirectoryReader(
input_files=["./receipt.jpg"]
).load_data()
response = mistralai_mm_llm.complete(
prompt="Transcribe the text in the image",
image_documents=image_documents,
)
display(Markdown(f"{response}"))
더 알아보기 (Learn more)
- LlamaIndex Multi-Modal LLM 문서 — 멀티모달 LLM 통합 가이드
MistralAIMultiModal— LlamaIndex의 Mistral 멀티모달 LLM 추상화pixtral-12b-2409— 이 예제에서 사용한 Pixtral 비전 모델load_image_urls— URL에서 이미지 문서를 생성하는 헬퍼