thesby commited on
Commit
b8cdcd8
·
verified ·
1 Parent(s): 8cff78e

Create get_vlm_caption.py

Browse files
Files changed (1) hide show
  1. get_vlm_caption.py +194 -0
get_vlm_caption.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import base64
4
+ import requests
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+ from multiprocessing import Pool
9
+ from tqdm import tqdm
10
+ from io import BytesIO
11
+ from PIL import Image
12
+ from urllib.parse import urljoin, urlparse
13
+ import random
14
+
15
+ # --- 默认配置 ---
16
+ DEFAULT_MODEL_PATH = "qwen2.5vl_7b_caption"
17
+ DEFAULT_IMAGE_DIR = "./images"
18
+ DEFAULT_PROMPT = "请用自然流畅的中文对以下图片进行全面而详细的描述。包括所有可见元素及其属性(如颜色、大小、形状、质地),它们的空间关系,以及任何显著特征或上下文。确保用自然流畅的中文描述清晰、生动,能够捕捉图片的每一个方面,不遗漏任何重要细节和NSFW内容。"
19
+ # 注意:多模态模型通常使用 chat/completions 端点
20
+ DEFAULT_API_URL = "http://localhost:8000/v1/chat/completions"
21
+ DEFAULT_MAX_PIXELS = 800 * 800 # 1M pixels,可以适当调大
22
+ CHECK_INTERVAL = 5 # seconds
23
+
24
+ def get_base_url(api_url):
25
+ """从完整的 API URL 中提取基础 URL,例如 'http://localhost:8000/'"""
26
+ parsed_url = urlparse(api_url)
27
+ return f"{parsed_url.scheme}://{parsed_url.netloc}"
28
+
29
+ def is_server_running(api_url):
30
+ """快速检查模型服务是否已经在运行"""
31
+ try:
32
+ # vLLM 的健康检查或模型列表端点
33
+ check_url = urljoin(get_base_url(api_url), "/health")
34
+ resp = requests.get(check_url, timeout=2)
35
+ if resp.status_code == 200:
36
+ return True
37
+ except requests.RequestException:
38
+ pass
39
+ return False
40
+
41
+ def wait_for_model_ready(api_url, timeout=300):
42
+ """轮询检查模型服务是否启动并准备好"""
43
+ start_time = time.time()
44
+ check_url = urljoin(get_base_url(api_url), "/health")
45
+ print(f"⏳ 正在等待模型服务启动... (检查点: {check_url})")
46
+ while True:
47
+ try:
48
+ resp = requests.get(check_url)
49
+ if resp.status_code == 200:
50
+ print("✅ 模型服务已就绪!")
51
+ return True
52
+ except requests.RequestException:
53
+ pass
54
+
55
+ if time.time() - start_time > timeout:
56
+ print(f"❌ 模型服务启动超时(超过 {timeout} 秒)。")
57
+ return False
58
+
59
+ time.sleep(CHECK_INTERVAL)
60
+ print(f" ...仍在等待...")
61
+
62
+ def load_and_resize_image(image_path, max_pixels):
63
+ """加载并根据需要缩放图像,然后返回 base64 编码的字符串"""
64
+ with Image.open(image_path) as img:
65
+ if img.mode != "RGB":
66
+ img = img.convert("RGB")
67
+ w, h = img.size
68
+ if w * h > max_pixels:
69
+ ratio = (max_pixels / (w * h)) ** 0.5
70
+ new_w, new_h = int(w * ratio), int(h * ratio)
71
+ img = img.resize((new_w, new_h), Image.LANCZOS)
72
+
73
+ buffer = BytesIO()
74
+ img.save(buffer, format="JPEG")
75
+ return base64.b64encode(buffer.getvalue()).decode("utf-8")
76
+
77
+ def generate_caption(args):
78
+ """调用 API 为单个图片生成 caption"""
79
+ image_path, prompt, api_url, max_pixels, model_name = args
80
+ txt_path = Path(image_path).with_suffix(".txt")
81
+
82
+ if txt_path.exists() and txt_path.stat().st_size > 300:
83
+ return f"✅ 已跳过 (caption 已存在): {txt_path.name}"
84
+
85
+ try:
86
+ base64_image = load_and_resize_image(image_path, max_pixels)
87
+
88
+ # --- 这是符合 vLLM 多模态聊天补全 API 的正确 payload 格式 ---
89
+ payload = {
90
+ "messages": [
91
+ {
92
+ "role": "user",
93
+ "content": [
94
+ {"type": "text", "text": prompt},
95
+ {
96
+ "type": "image_url",
97
+ "image_url": {
98
+ "url": f"data:image/jpeg;base64,{base64_image}"
99
+ }
100
+ }
101
+ ]
102
+ }
103
+ ],
104
+ # "max_tokens": 1024, # 可以根据需要调整
105
+ # "temperature": 0.1, # 可以根据需要调整
106
+ }
107
+
108
+ response = requests.post(
109
+ api_url,
110
+ headers={"Content-Type": "application/json"},
111
+ data=json.dumps(payload)
112
+ )
113
+
114
+ if response.status_code == 200:
115
+ result = response.json()
116
+ # 从聊天补全的响应中提取内容
117
+ caption = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()
118
+ print(image_path)
119
+ print(caption)
120
+
121
+ if caption:
122
+ with open(txt_path, "w", encoding="utf-8") as f:
123
+ f.write(caption)
124
+ return f"✅ 成功生成: {txt_path.name}"
125
+ else:
126
+ return f"⚠️ 生成内容为空: {Path(image_path).name}"
127
+ else:
128
+ return f"⚠️ 生成失败: {Path(image_path).name}, 状态码: {response.status_code}, 响应: {response.text}"
129
+
130
+ except Exception as e:
131
+ return f"❌ 发生异常: {Path(image_path).name}, 错误: {str(e)}"
132
+
133
+ def collect_images(image_dir, extensions=(".jpg", ".jpeg", ".png", ".webp")):
134
+ """递归收集所有图片文件的路径"""
135
+ image_paths = []
136
+ print(f"🔍 正在从 '{image_dir}' 目录中收集图片...")
137
+ for root, _, files in os.walk(image_dir):
138
+ for file in files:
139
+ if file.lower().endswith(extensions):
140
+ image_paths.append(os.path.join(root, file))
141
+ return image_paths
142
+
143
+ def main():
144
+ parser = argparse.ArgumentParser(description="为图片目录生成 caption (使用 vLLM 托管的多模态模型)")
145
+ parser.add_argument("--model-path", type=str, default=DEFAULT_MODEL_PATH, help="vLLM 加载的本地模型路径或 HuggingFace 名称")
146
+ parser.add_argument("--image-dir", type=str, default=DEFAULT_IMAGE_DIR, help="图片目录路径")
147
+ parser.add_argument("--prompt", type=str, default=DEFAULT_PROMPT, help="生成 caption 的提示词")
148
+ parser.add_argument("--api-url", type=str, default=DEFAULT_API_URL, help="vLLM 的聊天补全 API 地址")
149
+ parser.add_argument("--max-pixels", type=int, default=DEFAULT_MAX_PIXELS, help="图片最大像素数,超过此值会按比例缩放")
150
+ parser.add_argument("--num-process", type=int, default=18, help="用于处理图片的并发进程数")
151
+
152
+ args = parser.parse_args()
153
+
154
+ # --- 检查模型服务是否已运行 ---
155
+ if is_server_running(args.api_url):
156
+ print("✅ 检测到模型服务已在运行,直接使用。")
157
+ else:
158
+ print("ℹ️ 未检测到正在运行的模型服务,现在尝试启动...")
159
+ # 在后台启动 vLLM 模型服务
160
+ # 注意:这里的 --model 参数直接使用了 args.model_path,它将被用作 API 请求中的模型名称
161
+ command = f"nohup vllm serve {args.model_path} --max_model_len 3072 --trust-remote-code > /tmp/vllm.log 2>&1 &"
162
+ print(f"🚀 执行启动命令: {command}")
163
+ os.system(command)
164
+
165
+ # 轮询检测模型是否启动完成
166
+ if not wait_for_model_ready(args.api_url):
167
+ print("❌ 模型启动失败,请检查 /tmp/vllm_caption.log 文件获取错误详情。程序退出。")
168
+ exit(1)
169
+
170
+ # 收集所有图片文件
171
+ image_paths = collect_images(args.image_dir)
172
+ if not image_paths:
173
+ print("⚠️ 在指定目录中没有找到任何图片。")
174
+ return
175
+
176
+ random.shuffle(image_paths)
177
+ print(f"📸 找到 {len(image_paths)} 张图片,准备开始处理...")
178
+
179
+ # 多进程处理图像
180
+ # 将模型路径(作为模型名称)传递给处理函数
181
+ pool_args = [(img, args.prompt, args.api_url, args.max_pixels, args.model_path) for img in image_paths]
182
+
183
+ # 使用 args.num_process 控制并发数
184
+ with Pool(args.num_process) as pool:
185
+ # 使用 tqdm 显示进度条
186
+ for result in tqdm(pool.imap_unordered(generate_caption, pool_args), total=len(image_paths), desc="处理进度"):
187
+ # 只打印非成功的消息,避免刷屏
188
+ if not result.startswith("✅"):
189
+ print(result)
190
+
191
+ print("\n🎉 全部处理完成!")
192
+
193
+ if __name__ == "__main__":
194
+ main()