File size: 3,197 Bytes
60fde3b | 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 | import base64
import mimetypes
import os
import re
from PIL import Image
def encode_image_to_base64(image_path):
"""读取图片并转换为 data:image/jpeg;base64,xxx 格式"""
if not os.path.exists(image_path):
raise FileNotFoundError(f"Image not found: {image_path}")
mime_type, _ = mimetypes.guess_type(image_path)
if not mime_type:
mime_type = "image/jpeg" # 默认 fallback
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
def parse_multimodal_text(text: str) -> list:
"""
【API 模式】解析文本,图片转 Base64。
"""
pattern = r"<image_start>\[(.*?)\]<image_end>"
content_list = []
last_end = 0
for match in re.finditer(pattern, text):
start, end = match.span()
image_path = match.group(1)
if start > last_end:
text_part = text[last_end:start]
if text_part:
content_list.append({"type": "text", "text": text_part})
try:
base64_url = encode_image_to_base64(image_path)
content_list.append({
"type": "image_url",
"image_url": {"url": base64_url}
})
except Exception as e:
print(f"Error encoding image {image_path}: {e}")
content_list.append({"type": "text", "text": f"[Image Missing: {image_path}]"})
last_end = end
if last_end < len(text):
content_list.append({"type": "text", "text": text[last_end:]})
return content_list
def parse_multimodal_text_for_vllm(text: str) -> list:
"""
【本地 vLLM 模式】解析文本,图片直接加载为 PIL 对象。
避免 Base64 编解码的开销。
"""
pattern = r"<image_start>\[(.*?)\]<image_end>"
content_list = []
last_end = 0
for match in re.finditer(pattern, text):
start, end = match.span()
image_path = match.group(1)
# 1. 文本部分
if start > last_end:
text_part = text[last_end:start]
if text_part:
content_list.append({"type": "text", "text": text_part})
# 2. 图片部分 (直接加载 PIL)
try:
if os.path.exists(image_path):
image = Image.open(image_path).convert("RGB")
# 使用自定义类型 "pil_image" 区别于 API 的 "image_url"
content_list.append({
"type": "pil_image",
"image": image
})
else:
print(f"Image not found: {image_path}")
content_list.append({"type": "text", "text": f"[Image Missing: {image_path}]"})
except Exception as e:
print(f"Error loading image {image_path}: {e}")
content_list.append({"type": "text", "text": f"[Image Error]"})
last_end = end
if last_end < len(text):
content_list.append({"type": "text", "text": text[last_end:]})
return content_list
|