| 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" |
| |
| 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) |
| |
| |
| if start > last_end: |
| text_part = text[last_end:start] |
| if text_part: |
| content_list.append({"type": "text", "text": text_part}) |
| |
| |
| try: |
| if os.path.exists(image_path): |
| image = Image.open(image_path).convert("RGB") |
| |
| 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 |
|
|