1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
| """ 使用 LM Studio API 给图片打标 支持单张图片测试和批量文件夹处理 """
import base64 import requests import json import argparse import os import shutil import hashlib from pathlib import Path from datetime import datetime from typing import Optional, List, Tuple
DEFAULT_API_URL = "http://localhost:1234/v1/chat/completions" DEFAULT_MODEL = "qwen/qwen3-vl-8b" TIMEOUT = 30
DEFAULT_PROMPT = """请详细描述这张图片中的内容,包括主体、动作、背景、风格等。 只需返回描述文本,不要使用markdown符号,不要任何额外说明。 首先进行整体描述,例如:人物、镜头、动作/表情、场景类别等。 之后进行详细描述。""" DEFAULT_PREFIX = "" DEFAULT_SUFFIX = ""
MAX_TOKENS = 2048 TEMPERATURE = 0.7
SUPPORTED_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
def calculate_md5(file_path: str) -> str: """计算文件的 MD5 hash""" md5_hash = hashlib.md5() with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): md5_hash.update(chunk) return md5_hash.hexdigest()
def encode_image(image_path: str) -> str: """将图片转换为 base64 编码""" with open(image_path, "rb") as img_file: encoded_string = base64.b64encode(img_file.read()).decode("utf-8") return encoded_string
def call_lm_studio_api( image_base64: str, prompt: str, prefix: str = "", suffix: str = "", api_url: str = DEFAULT_API_URL, model: str = DEFAULT_MODEL, ) -> Optional[str]: """ 调用 LM Studio API 进行图片打标
参数: image_base64: 图片的 base64 编码 prompt: 主要提示词 prefix: 前缀提示词(如触发词) suffix: 后缀提示词 api_url: API 地址 model: 模型名称
返回: 成功: 返回标签文本 失败: 返回 None """ full_prompt = f"{prefix}{prompt}{suffix}".strip() payload = { "model": model, "messages": [ { "role": "user", "content": [ {"type": "text", "text": full_prompt}, { "type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}, }, ], } ], "max_tokens": MAX_TOKENS, "temperature": TEMPERATURE, }
try: response = requests.post(api_url, json=payload, timeout=TIMEOUT) response.raise_for_status()
result = response.json() caption = result["choices"][0]["message"]["content"] return caption.strip()
except requests.Timeout: print(f" ⚠ 超时 (>{TIMEOUT}s)") return None except requests.ConnectionError: print(f" ❌ 连接失败:无法连接到 LM Studio API ({api_url})") print(" 请确保:") print(" 1. LM Studio 已启动") print(f" 2. 已加载 {model} 模型") print(" 3. API 服务已开启(Developer → Start Server)") return None except KeyError: print(f" ❌ API 返回格式错误") return None except Exception as e: print(f" ❌ API 错误: {str(e)}") return None
def tag_single_image( image_path: str, prompt: str = DEFAULT_PROMPT, prefix: str = DEFAULT_PREFIX, suffix: str = DEFAULT_SUFFIX, api_url: str = DEFAULT_API_URL, model: str = DEFAULT_MODEL, ) -> Optional[str]: """ 单张图片打标(测试模式)
返回: 成功: 返回标签文本 失败: 返回 None """ if not os.path.exists(image_path): print(f"❌ 图片不存在: {image_path}") return None
print(f"📷 处理图片: {image_path}") print(f"🔄 正在调用 API...")
full_prompt = f"{prefix}{prompt}{suffix}".strip() print(f"📝 完整 Prompt: {full_prompt}")
try: image_base64 = encode_image(image_path) caption = call_lm_studio_api( image_base64, prompt, prefix, suffix, api_url, model ) return caption except Exception as e: print(f"❌ 编码图片失败: {str(e)}") return None
def collect_images(input_dir: str) -> List[str]: """ 递归收集所有支持的图片文件
返回: 图片路径列表 """ images = [] input_path = Path(input_dir)
if not input_path.exists(): print(f"❌ 输入目录不存在: {input_dir}") return images
for file_path in input_path.rglob("*"): if file_path.is_file() and file_path.suffix.lower() in SUPPORTED_EXTS: images.append(str(file_path))
return sorted(images)
def save_caption(txt_path: str, caption: str): """保存标签到文本文件""" with open(txt_path, "w", encoding="utf-8") as f: f.write(caption)
def log_error(log_file: str, image_path: str, error_msg: str): """记录失败日志""" timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(log_file, "a", encoding="utf-8") as f: f.write(f"{timestamp} | {image_path} | {error_msg}\n")
def batch_tag_folder( input_dir: str, output_dir: str, prompt: str = DEFAULT_PROMPT, prefix: str = DEFAULT_PREFIX, suffix: str = DEFAULT_SUFFIX, api_url: str = DEFAULT_API_URL, model: str = DEFAULT_MODEL, overwrite: bool = False, ): """ 批量处理文件夹
参数: input_dir: 输入目录(递归处理) output_dir: 输出目录(扁平化,使用 MD5 命名) prompt: 打标提示词 prefix: 前缀提示词(如触发词) suffix: 后缀提示词 api_url: LM Studio API 地址 model: 模型名称 overwrite: 是否覆盖已有标签 """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True)
print(f"📁 扫描输入目录: {input_dir}") images = collect_images(input_dir)
if not images: print("❌ 未找到任何图片文件") return
full_prompt = f"{prefix}{prompt}{suffix}".strip()
print(f"✓ 找到 {len(images)} 张图片") print(f"📂 输出目录: {output_dir}") print(f"🤖 模型: {model}") print(f"📝 完整 Prompt: {full_prompt}") print("-" * 60)
log_file = output_path / "failed.log"
success_count = 0 skipped_count = 0 failed_count = 0
processed_hashes = set()
for idx, image_path in enumerate(images, 1): print(f"[{idx}/{len(images)}] {Path(image_path).name}")
try: file_hash = calculate_md5(image_path)
if file_hash in processed_hashes: print(f" ⊘ 跳过(重复文件,MD5: {file_hash[:8]}...)") skipped_count += 1 continue
ext = Path(image_path).suffix.lower()
output_image_name = f"{file_hash}{ext}" output_txt_name = f"{file_hash}.txt"
output_image_path = output_path / output_image_name output_txt_path = output_path / output_txt_name
if output_txt_path.exists() and not overwrite: print(f" ⊘ 跳过(已存在标签文件)") processed_hashes.add(file_hash) skipped_count += 1 continue
image_base64 = encode_image(image_path)
caption = call_lm_studio_api( image_base64, prompt, prefix, suffix, api_url, model )
if caption is None: failed_count += 1 log_error(str(log_file), image_path, "API 调用失败或超时") continue
if not output_image_path.exists(): shutil.copy2(image_path, output_image_path)
save_caption(str(output_txt_path), caption)
print(f" ✓ 已保存: {output_txt_name}") processed_hashes.add(file_hash) success_count += 1
except Exception as e: print(f" ❌ 处理失败: {str(e)}") failed_count += 1 log_error(str(log_file), image_path, str(e))
print("-" * 60) print(f"✅ 成功: {success_count}") print(f"⊘ 跳过: {skipped_count}") print(f"❌ 失败: {failed_count}")
if failed_count > 0: print(f"📋 失败日志: {log_file}")
def main(): parser = argparse.ArgumentParser( description="使用 LM Studio API 给图片打标", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" 示例用法: # 单张图片测试 python tagger.py --image "D:\\test\\sample.jpg" # 批量处理文件夹 python tagger.py --input "D:\\dataset\\images" --output "D:\\dataset\\tagged" # 强制覆盖已有标签 python tagger.py --input "..." --output "..." --overwrite # 自定义 API 地址和模型 python tagger.py --input "..." --output "..." --api-url "http://192.168.1.100:1234" --model "qwen/qwen2-vl-72b" """, )
mode_group = parser.add_mutually_exclusive_group(required=True) mode_group.add_argument("--image", type=str, help="单张图片路径(测试模式)") mode_group.add_argument("--input", type=str, help="输入目录(批量处理模式)")
parser.add_argument("--output", type=str, help="输出目录(批量模式必需)")
parser.add_argument( "--prompt", type=str, default=DEFAULT_PROMPT, help=f'打标提示词(默认: "{DEFAULT_PROMPT}")', ) parser.add_argument( "--prefix", type=str, default=DEFAULT_PREFIX, help='前缀提示词(如触发词),示例: "sks woman, "', ) parser.add_argument( "--suffix", type=str, default=DEFAULT_SUFFIX, help='后缀提示词,示例: ", high quality, masterpiece"', ) parser.add_argument( "--api-url", type=str, default=DEFAULT_API_URL, help=f"LM Studio API 地址(默认: {DEFAULT_API_URL})", ) parser.add_argument( "--model", type=str, default=DEFAULT_MODEL, help=f"模型名称(默认: {DEFAULT_MODEL})", ) parser.add_argument("--overwrite", action="store_true", help="覆盖已有标签文件")
args = parser.parse_args()
if args.image: caption = tag_single_image( args.image, prompt=args.prompt, prefix=args.prefix, suffix=args.suffix, api_url=args.api_url, model=args.model, )
if caption: print("\n" + "=" * 60) print("📝 打标结果:") print("=" * 60) print(caption) print("=" * 60) else: print("\n❌ 打标失败")
elif args.input: if not args.output: parser.error("批量模式需要指定 --output 参数")
batch_tag_folder( input_dir=args.input, output_dir=args.output, prompt=args.prompt, prefix=args.prefix, suffix=args.suffix, api_url=args.api_url, model=args.model, overwrite=args.overwrite, )
if __name__ == "__main__": main()
|