门户 网站 asp,国外产品推广是怎么做的,天津市住房和城乡建设局网站,用网站做淘宝客的人多吗概述
随着人工智能技术的迅猛发展#xff0c;多模态模型在各类应用场景中展现出强大的潜力和广泛的适用性。Qwen2-VL 作为最新一代的多模态大模型#xff0c;融合了视觉与语言处理能力#xff0c;旨在提升复杂任务的执行效率和准确性。本指南聚焦于 Qwen2-VL 在三个关键领域…
概述
随着人工智能技术的迅猛发展多模态模型在各类应用场景中展现出强大的潜力和广泛的适用性。Qwen2-VL 作为最新一代的多模态大模型融合了视觉与语言处理能力旨在提升复杂任务的执行效率和准确性。本指南聚焦于 Qwen2-VL 在三个关键领域的实践应用发票数据提取、视频聊天以及基于 PDF 文档的多模态检索增强生成RAG, Retrieval-Augmented Generation。
多模态 RAG 的重要性
传统的生成模型主要依赖于文本数据而多模态 RAG 则通过结合视觉信息实现对复杂数据的更深入理解和处理。这一方法不仅提高了生成内容的相关性和准确性还扩展了模型在实际应用中的适用范围。Qwen2-VL 通过整合图像、视频和文本数据能够在多种场景下提供智能化的解决方案满足企业和个人用户日益增长的需求。
发票数据提取
在财务和会计领域发票作为重要的交易凭证其数据的准确提取和处理对于企业的运营至关重要。传统的方法往往依赖人工录入效率低下且易出错。Qwen2-VL 利用其强大的视觉识别和自然语言理解能力能够自动识别发票中的关键信息如金额、日期和供应商信息实现高效、准确的数据提取大幅提升工作效率并降低人为错误的风险。
视频聊天
随着远程办公和在线交流的普及视频聊天已成为日常工作和社交的重要工具。Qwen2-VL 在视频聊天应用中通过结合视觉和语言模型实现智能化的实时翻译、情感分析和内容摘要等功能。此举不仅提升了沟通的便捷性和效果还为用户提供了更加个性化和高效的交流体验。
基于 PDF 的多模态 RAG
PDF 作为一种广泛使用的文档格式涵盖了文本、图表和图像等多种信息形式。Qwen2-VL 通过解析和理解 PDF 文档中的多模态内容能够实现智能检索和生成。例如在科研、法律和教育等领域用户可以通过自然语言查询快速获取相关信息并生成简洁明了的总结报告。这不仅提高了信息获取的效率还促进了知识的传播和应用。
Qwen2-VL 架构
下面这张图就是Qwen2-VL的架构图。 到目前为止已知的是 Qwen2-VL 使用带有 Vision Transformer 的 Qwen2-LM — 能够处理图像和视频。此外Qwen2-VL 还推出了新颖的多模态旋转位置嵌入 s M-ROPE 。这是 ROPE 嵌入的一种变体它将位置嵌入分解为多个部分 。 Qwen2-VL 支持多种语言包括大多数欧洲语言、日语、韩语、中文和阿拉伯语。更多细节参考官方文档。
项目 1将发票数据提取为 JSON 格式
在这个小型项目中我们将从下面的发票中提取财务和个人信息 — JSON 格式 首先安装必要的库
pip install githttps://github.com/huggingface/transformers accelerate
pip install qwen-vl-utils接下来我们下载我们的文件:
import urllib.request# 发票图片地址
url http://cwb.stdusfc.edu.cn/images/2015/cw112701.png
# 下载发票
file_name url.split(/)[-1]
urllib.request.urlretrieve(url, file_name)
print(fDownloaded file name: {file_name})
# Downloaded file name: cw112701.png然后我们将安装 Qwen2-VL-7B-Instruct 。
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import jsonmodel_name Qwen/Qwen2-VL-7B-Instruct
model Qwen2VLForConditionalGeneration.from_pretrained(model_name,torch_dtypeauto,device_mapauto
)
processor AutoProcessor.from_pretrained(model_name
)
在模型下载并放入内存后我们可以发送我们的请求。一些额外提示
至少使用原始图像尺寸 确保至少使用图像的原始尺寸以获得最佳效果resized_height resized_width arguments参数较大的尺寸 在质量较差的图像中尺寸稍大可以提高准确性但会增加 VRAM 的使用量。相应地调整
我们将使用 Qwen2-VL 的聊天模板并提示如下 检索项目内容金额付款单位时间发票代码发票号码。响应必须是 JSON 格式messages [{role: user,content: [{type: image,image: file_name,resized_height: 696,resized_width: 943,},{type: text,text: 检索项目内容金额付款单位时间发票代码发票号码。响应必须是 JSON 格式}]}
]text processor.apply_chat_template(messages, tokenizeFalse, add_generation_promptTrue
)
image_inputs, video_inputs process_vision_info(messages)
inputs processor(text[text],imagesimage_inputs,videosvideo_inputs,paddingTrue,return_tensorspt,
)
inputs inputs.to(cuda)
generated_ids model.generate(**inputs, max_new_tokens512)
generated_ids_trimmed [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text processor.batch_decode(generated_ids_trimmed, skip_special_tokensTrue, clean_up_tokenization_spacesTrue)
output_text我们得到以下输出
[json\\n{\\n 项目内容: [\\n 钢尺 30 x11.5,\\n 美工刀 60 x2,\\n 腊线 30 x14\\n ],\\n 金额: [\\n 345.00,\\n 200.00,\\n 420.00\\n ],\\n 付款单位: 石家庄铁道大学四方学院,\\n 时间: 2015年5月11日,\\n 发票代码: 113001464131,\\n 发票号码: 09404611\\n}\\n]
你可以使用以下代码来修复潜在错误并设置模型的 JSON 输出格式
json_string output_text[0]
json_string json_string.strip([])
json_string json_string.replace(json\\n, ).replace(\\n, )
json_string json_string.replace(, )
try:formatted_json json.loads(json_string)print(json.dumps(formatted_json, indent3, ensure_asciiFalse))
except json.JSONDecodeError as e:print(Not valid JSON format:, e)通过将结果与上述发票进行比较我们注意到
该模型的输出准确率非常高 — 它准确地提取了所有相关信息尽管图像质量很差并且表格中嵌入了数据较小的 Qwen2-VL 在这里表现良好但对于更复杂的图像或手写文本你可能需要更大的模型例如 Qwen2-VL-72B .
项目 2通过视频聊天
Qwen2-VL 还可以提取信息并与视频交互。
在这个项目中我们将使用一个简短的 B站 视频 —《这一段毫无表演痕迹 堪称经典》
## 下载B站视频
pip install yt-dlp按如下方式下载
import yt_dlp
import osdef download_bilibili_video(url, download_pathdownloads, fmt10004730280, cookiefileNone):# 创建下载目录如果不存在if not os.path.exists(download_path):os.makedirs(download_path)ydl_opts {outtmpl: os.path.join(download_path, %(title)s.%(ext)s),format: fmt, # 指定视频和音频的格式IDnoplaylist: True,merge_output_format: mp4, # 合并为mp4格式}if cookiefile:ydl_opts[cookiefile] cookiefilewith yt_dlp.YoutubeDL(ydl_opts) as ydl:ydl.download([url])video_url https://www.bilibili.com/video/BV1us41eBERp # 替换为你要下载的视频URL
download_directory ./downloads # 替换为你希望保存视频的目录# 如果需要使用Cookies进行认证取消下行注释并提供Cookies文件路径# cookies_path path_to_cookies.txt# download_bilibili_video(video_url, download_directory, fmt10004730280, cookiefilecookies_path)# 如果不需要认证使用以下行
download_bilibili_video(video_url, download_directory, fmt10004630280)file_name ./downloads/这一段毫无表演痕迹 堪称经典.mp4我们将再次使用Qwen2-VL-7B因为它的资源密集度较低。
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessormodel_name Qwen/Qwen2-VL-7B-Instructmodel Qwen2VLForConditionalGeneration.from_pretrained(model_name,torch_dtypeauto,##attn_implementationflash_attention_2, #use flash-attention2 if your gpu card supports it (Free Colabs T4 does not support it)device_mapauto,
)
processor AutoProcessor.from_pretrained(model_name
)我们定义函数 chat_with_video 它接受调整后的视频尺寸、每秒帧数和我们将向 Qwen 询问的文本消息
def chat_with_video(file_name, query, video_width, video_height, fps1.0):messages [{role: user,content: [{type: video,video: file_name,max_pixels: video_width * video_height,fps: 1.0,},{type: text, text: query},],}]text processor.apply_chat_template(messages, tokenizeFalse, add_generation_promptTrue)image_inputs, video_inputs process_vision_info(messages)inputs processor(text[text],imagesimage_inputs,videosvideo_inputs,paddingTrue,return_tensorspt,)inputs inputs.to(cuda)generated_ids model.generate(**inputs, max_new_tokens150)generated_ids_trimmed [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_text processor.batch_decode(generated_ids_trimmed, skip_special_tokensTrue, clean_up_tokenization_spacesFalse)return output_text
让我们问一下模型 output_text chat_with_video(file_name, 这个视频展示了什么?, 360, 360,fps0.5)
[这个视频展示了两个人在餐馆里吃饭的场景。其中一个人穿着蓝色衣服戴着帽子另一个人穿着棕色外套。他们用筷子夹着食物喝着汤看起来非常享受。]还有另一个问题
output_text chat_with_video(file_name, 谁付的钱?, 360, 360,fps0.5)
[根据视频内容最后是穿棕色大衣的男子付了钱。]耗费gpu资源情况 令人惊讶的是该模型准确地回答了这两个问题
一些额外的说明
增加视频的高度、宽度和帧速率 fps 通常会提高准确性但需要更多的 GPU VRAM。Qwen2-VL 可以处理超过 20 分钟的视频但是GPU资源需求很大。从我的实验来看Qwen2-VL-7B 在准确性和资源需求 GPU VRAM 之间提供了最佳平衡。
项目 3多模态 RAG
在本项目中我们将 Qwen2-VL 与另一个模型 ColPali 相结合以对 PDF 执行 RAG。ColPali 是一个文档检索模型包含一个 PaliGemma-3B 模型也是 VLM和一个 Gemma-2B。ColPali 的作用是执行文档检索部分并创建一个多向量文档存储 在我们的例子中流程如下将每个 PDF 页面转换为图像。将图像推送到 ColPali 中以存储每个页面的多向量表示。向 ColPali 提交文本查询以检索相关图像。将文本查询和相关图像提交给 Qwen2-VL 以获取答案。
我们将使用 Byaldi 库创建图像向量存储。Byaldi 加载 ColPali以及使用 API 的类似模型。我们还将使用 pdf2image 将 PDF 转换为图像
让我们从安装必要的库开始
#pip install --upgrade byaldi
pip install byaldi0.0.5
pip install -q githttps://github.com/huggingface/transformers.git qwen-vl-utils pdf2image## pdf2image 必要的工具
!sudo apt-get install -y poppler-utils我们将为此项目下载一个 1 页的 PDF — 一个用于节省 VRAM 的小文件。
import urllib.request# We will use this pdf:
url http://ep.ycwb.com/epaper/ycwb/resfile/2020-01-28/A08/ycwb20200128A08.pdf
# Download the file
pdf_filepath url.split(/)[-1]
urllib.request.urlretrieve(url, pdf_filepath)
print(fDownloaded file name: {pdf_filepath})由于模型处理的是图像而不是 PDF 文件因此我们将每个页面转换为图像。如果要在 Jupyter/Colab 中可视化图像请运行以下代码
from PIL import Image as PILImage
from pdf2image import convert_from_path
from IPython.display import displayimages convert_from_path(pdf_filepath)
for page_number, page in enumerate(images):resized_image page.resize((600, 800), PILImage.Resampling.LANCZOS)print(fPage {page_number 1}:)display(resized_image)以下是我们 PDF 中的一张图片 接下来我们加载 ColPali 并构建我们的索引存储
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import torchvlm_name Qwen/Qwen2-VL-7B-Instruct
model Qwen2VLForConditionalGeneration.from_pretrained(vlm_name,torch_dtypeauto,device_mapauto)
processor AutoProcessor.from_pretrained(vlm_name)该函数extract_answer_from_pdf执行以下操作
给定一个文本查询我们要求 Colpali 检索最相关的图像 k1。该图像表示一个 PDF 页面。给定文本查询和相关图像我们要求 Qwen-VL-7B 执行图像识别并提供文本查询的答案该函数返回答案 output_text、包含答案的页码以及相关的图像/页面
def extract_answer_from_pdf(text_query):results RAG.search(text_query, k1)print(results)image_index results[0][page_num] - 1messages [{role: user,content: [{type: image,image: images[image_index], ## 包含检索到的 pdf 页面作为图像resized_height: 527,resized_width: 522,},{type: text, text: text_query},],}]text processor.apply_chat_template(messages, tokenizeFalse, add_generation_promptTrue)image_inputs, video_inputs process_vision_info(messages)inputs processor(text[text],imagesimage_inputs,videosvideo_inputs,paddingTrue,return_tensorspt,)inputs inputs.to(device)generated_ids model.generate(**inputs, max_new_tokens50)## 从答案中删除提示generated_ids_trimmed [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]output_text processor.batch_decode(generated_ids_trimmed, skip_special_tokensTrue, clean_up_tokenization_spacesFalse)return output_text, results[0].page_num , images[image_index]
让我们问问我们的模型
text_query 这篇报道的时间是什么?
output_text, page_number, image extract_answer_from_pdf(text_query)print(\\n\\n)
print(output_text)
[2020-01-28]模型是正确的报道的时间是2020-01-28。让我们再问一个问题
text_query 科比的直升机坠机地点在哪?
output_text, page_number, image extract_answer_from_pdf(text_query)print(\\n\\n)
print(output_text)
[T事故发生在美国加利福尼亚州卡拉巴萨斯市在洛杉矶以西大约 30 公里.]我们可以使用多个 PDF 吗
是的只需将多个 PDF 放在访问的RAG.index()文件夹中即可。
我们可以检索多张图像吗
是的。在这种情况下我们只检索了最相关的图像 k1。你可以通过设置 k2 来检索更多图像然后将两张图像都传递给 Qwen 进行处理。
chat_template [{role: user,content: [{type: image,image: image[0],},{type: image,image: image[1],}{type: text, text: text_query},],}
]但是添加更多 PDF 或检索多个页面需要更多的资源。
结束语
本文探讨了 Qwen2-VL 在图像、视频和文档检索任务中的应用。
对于更复杂的情况你可以选择模型的更大版本或量化版本——这些版本的大小更小质量损失最小。