【手把手教程】PyCharm本地部署阿里Qwen2.5-VL:零基础玩转顶级AI视觉模型
·
阿里云开源的Qwen2.5-VL凭借其强大的图像理解、文本识别和复杂布局解析能力,已成为AI视觉领域的明星模型。本文从零开始教你用PyCharm实现本地部署,全程避坑指南+代码可复制,小白也能轻松搞定!
📦 准备工作(必装工具)
-
Anaconda
>> 官网下载地址
用于管理Python环境,避免依赖冲突 -
PyCharm
>> 专业版下载
推荐使用专业版,社区版也可运行 -
Git
>> 下载地址
用于克隆开源代码仓库🛠️ 本地部署全流程(含镜像加速)
步骤1:创建虚拟环境
# 创建名为qwen-vl的Python3.11环境
conda create -n qwen-vl python=3.11 -y
# 激活环境
conda activate qwen-vl
步骤2:安装依赖(国内镜像加速)
# 使用清华镜像加速安装!
pip install torch torchvision -i https://pypi.tuna.tsinghua.edu.cn/simple
# 关键依赖(必须安装)
pip install transformers accelerate -i https://pypi.tuna.tsinghua.edu.cn/simple
# 模型管理工具
pip install modelscope qwen-tools
步骤3:克隆代码仓库
git clone https://github.com/QwenLM/Qwen2.5-VL.git
cd Qwen2.5-VL # 进入项目目录
⚡ PyCharm配置指南
1. 关联虚拟环境
- 打开PyCharm -> 点击右下角Python解释器
- 选择添加新解释器 -> Conda环境
- 选择已存在的环境:qwen-vl
2. 修改核心代码
import base64
from modelscope import snapshot_download
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
from test_aliyun import image_base64
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# 下载模型
model_dir = snapshot_download("Qwen/Qwen2.5-VL-3B-Instruct")
# 加载模型和处理器
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model_dir,
torch_dtype="auto",
device_map="auto"
)
processor = AutoProcessor.from_pretrained(model_dir, max_pixels=1280*28*28)
# 图像路径
image_path = r"H:\test_aliyun\picture\test.png"
image_base64 = image_to_base64(image_path)
# 定义符合 Qwen 格式的对话历史
my_messages = [
{
"role": "system",
"content": "You are an OCR expert. Extract ALL text and return a JSON array with 'text'",
},
{
"role": "user",
"content": "Extract text from this image in JSON format.",
"image": f"data:image/png;base64,{image_base64}" # ✅ 正确 base64 格式
}
]
# 处理视觉输入(自动加载图像)
text = processor.apply_chat_template(
my_messages,
tokenize=False,
add_generation_prompt=True
)
image_inputs, _ = process_vision_info(my_messages) # 忽略视频输入
# 模型推理
inputs = processor(
text=[text],
images=image_inputs,
padding=True,
return_tensors="pt"
).to(model.device)
generated_ids = model.generate(**inputs, max_new_tokens=512) # 增加 token 长度
output_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(output_text)
🚀运行与测试
- 右键运行demo.py
- 首次运行会自动下载模型(约3GB)
- 查看控制台输出示例:
更多推荐
所有评论(0)