Update app.py
Browse files
app.py
CHANGED
|
@@ -1,2 +1,64 @@
|
|
| 1 |
import json
|
| 2 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import os
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import base64
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
|
| 8 |
+
def base64_to_image(
|
| 9 |
+
base64_str: str,
|
| 10 |
+
remove_prefix: bool = True,
|
| 11 |
+
convert_mode: Optional[str] = "RGB"
|
| 12 |
+
) -> Union[Image.Image, None]:
|
| 13 |
+
"""
|
| 14 |
+
将Base64编码的图片字符串转换为PIL Image对象
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
base64_str: Base64编码的图片字符串(可带data:前缀)
|
| 18 |
+
remove_prefix: 是否自动去除"data:image/..."前缀(默认True)
|
| 19 |
+
convert_mode: 转换为指定模式(如"RGB"/"RGBA",None表示不转换)
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
PIL.Image.Image 对象,解码失败时返回None
|
| 23 |
+
|
| 24 |
+
Examples:
|
| 25 |
+
>>> img = base64_to_image("data:image/png;base64,iVBORw0KGg...")
|
| 26 |
+
>>> img = base64_to_image("iVBORw0KGg...", remove_prefix=False)
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
# 1. 处理Base64前缀
|
| 30 |
+
if remove_prefix and "," in base64_str:
|
| 31 |
+
base64_str = base64_str.split(",")[1]
|
| 32 |
+
|
| 33 |
+
# 2. 解码Base64
|
| 34 |
+
image_data = base64.b64decode(base64_str)
|
| 35 |
+
|
| 36 |
+
# 3. 转换为PIL Image
|
| 37 |
+
image = Image.open(BytesIO(image_data))
|
| 38 |
+
|
| 39 |
+
# 4. 可选模式转换
|
| 40 |
+
if convert_mode:
|
| 41 |
+
image = image.convert(convert_mode)
|
| 42 |
+
|
| 43 |
+
return image
|
| 44 |
+
|
| 45 |
+
except (base64.binascii.Error, OSError, Exception) as e:
|
| 46 |
+
print(f"Base64解码失败: {str(e)}")
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
file_path = "./test_message_gpt.json"
|
| 51 |
+
messages = json.load(open(file_path, "r", encoding="utf-8"))
|
| 52 |
+
|
| 53 |
+
for message_item in messages:
|
| 54 |
+
role = message_item['role']
|
| 55 |
+
content = message_item['content']
|
| 56 |
+
|
| 57 |
+
for content_item in content:
|
| 58 |
+
content_type = content_item['type']
|
| 59 |
+
if content_type == "text":
|
| 60 |
+
content_value = content_item['text']
|
| 61 |
+
elif conent_type == "image_url":
|
| 62 |
+
content_value = content_item['image_url']['url']
|
| 63 |
+
image = base64_to_image(content_value)
|
| 64 |
+
|