はじめに
画像からテキストを抽出するのにLangChainの必要性はあまりありません。ただ、LangChainを使うとスクリプトが非常にシンプルになります。
Pythonスクリプト
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import base64
from typer import Typer, Option
def encode_image(image_path :str) -> dict[str, str]:
with open(image_path, "rb") as image_file:
return {"base64_image": base64.b64encode(image_file.read()).decode('utf-8')}
app = Typer()
@app.command()
def main(
image_path: str=Option("D:\\langchain\\sample.jpg", "--image", "-I", help="image path")
):
prompt_template = ChatPromptTemplate.from_messages(
[
("system", "あなたは優秀なAIアシスタントです。"),
("human",[
{"type": "text", "text":"画像からテキストを抽出して下さい。"},
{
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64,{base64_image}"}
}
])
]
)
'''
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model = "gemma-3-12b-it-4bit",
api_key="EMPTY",
base_url="http://localhost:8000/v1",
temperature=0
)
'''
from langchain.chat_models import init_chat_model
model = init_chat_model(
model="openai:gemma-3-12b-it-4bit",
api_key="EMPTY",
base_url="http://localhost:8000/v1",
temperature=0
)
chain = (
encode_image
| prompt_template
| model
| StrOutputParser()
)
for chunk in chain.stream(image_path):
print(chunk, end="", flush=True)
if __name__=="__main__":
app()