LangChain实战:图片结构化技巧排行榜
在之前的文章中,我们已详细探讨了Langchain框架下如何高效调用大语言模型(LLM)以及设计精准的Prompt模板。这次直接进入实战:拿一张入职说明图片,完整走通图片文本提取、结构化处理,最终构建一个能理解上下文的智能问答系统。整套流程在普通配置的PC上就能运行,无需上云,跟一遍就能快速掌握实操技巧。
环境配置
实践所需依赖包如下:
langchain==0.2.9
torch
html2text
paddlepaddle
paddleocr
文本提取
图片中的文字和表格如何抽取?这里选用PaddleOCR的表格识别模块,它不仅能识别文字,还能保留表格的结构信息。核心代码如下:
import cv2
from paddleocr import PPStructure
table_engine = PPStructure(show_log=True, use_gpu=False, lang='ch')
img_path = r'./2.jpg'
img = cv2.imread(img_path)
result = table_engine(img)
html = result[0]['res']['html']
print(len(html))
# 2723
输出是一段HTML格式的文本,其中混杂了大量样式标签,长度2723字符。如果直接喂给模型,会浪费大量token。利用html2text将其转换为Markdown格式,体积瞬间压缩到1051字符,信息更加紧凑:
import html2text
markdown = html2text.html2text(html)
print(len(markdown))
# 1051
模型定义
模型选型非常灵活。如果你持有OpenAI的API key,直接按以下方式构建:
from langchain_openai import ChatOpenAI
chat_model = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.0)
偏好本地部署的话,也可以加载自己的模型。参照之前RAG文章中的方法,用HuggingFace Pipeline封装即可:
from langchain_huggingface import HuggingFacePipeline
from langchain_huggingface import ChatHuggingFace
llm = HuggingFacePipeline.from_model_id(
model_id="./Qwen/Qwen2-0.5B-Instruct",
task="text-generation",
pipeline_kwargs=dict(
max_new_tokens=512,
do_sample=False,
),
)
chat_model = ChatHuggingFace(llm=llm)
模型配置完成后,后续流程可按需切换,扩展性很强。
要素提取
接下来演示用Qwen2-0.5B搭建一个简单的问答流水线。模型虽小,但在单字段要素提取任务上表现稳定。先定义Prompt模板:
from langchain_core.prompts import ChatPromptTemplate
chat_prompt_template = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("user", "根据表格内容回答下面问题:\n表格内容:\n{context}\nQuestion: {question}\nAnswer:")
])
chain = chat_prompt_template | chat_model.bind(skip_prompt=True)
res = chain.invoke({"context": markdown, "question": "姓名是什么?"})
# res.content # 赵开心
res = chain.invoke({"context": markdown, "question": "婚姻状况?"})
# res.content # 婚姻状况为未婚。
单字段问答非常稳定,但若需要一次性提取多个字段,0.5B模型就会有些吃力。下篇文章将专门讲解如何优化Prompt实现一次性结构化提取,并给出对应的写法技巧。
