[fix] 一定程度修复图片生成的问题

This commit is contained in:
Wizerd
2023-12-14 18:11:36 +08:00
parent ab3d4e6d8d
commit ac8068bc23
3 changed files with 45 additions and 16 deletions

View File

@@ -8,6 +8,11 @@
# 更新日志 # 更新日志
### 0.0.7
- 一定程度上修复图片无法正常生成的问题
- 注意:`docker-compsoe.yml`有更新
### 0.0.6 ### 0.0.6
- 修复接入ChatGPT-Next-Web后回复会携带上次的回复的Bug - 修复接入ChatGPT-Next-Web后回复会携带上次的回复的Bug

View File

@@ -2,7 +2,7 @@ version: '3'
services: services:
backend-to-api: backend-to-api:
image: wizerd/pandora-to-api:0.0.6 image: wizerd/pandora-to-api:0.0.7
restart: always restart: always
ports: ports:
- "50011:33333" - "50011:33333"
@@ -12,9 +12,11 @@ services:
- UPLOAD_BASE_URL=<Uploader 容器可以访问到的地址http://127.0.0.1:50012> - UPLOAD_BASE_URL=<Uploader 容器可以访问到的地址http://127.0.0.1:50012>
volumes: volumes:
- ./log:/app/log - ./log:/app/log
- ./images:/app/images
uploader: uploader:
image: wizerd/pandora-to-api:0.0.6 image: wizerd/pandora-to-api:0.0.7
restart: always restart: always
entrypoint: ["python3", "/app/upload.py"] entrypoint: ["python3", "/app/upload.py"]
volumes: volumes:

50
main.py
View File

@@ -198,20 +198,27 @@ def delete_conversation(conversation_id, api_key):
from PIL import Image from PIL import Image
import io import io
def save_image(image_data, path='./images'): def save_image(image_data, path='images'):
if not os.path.exists(path): try:
os.makedirs(path) # print(f"image_data: {image_data}")
current_time = datetime.now().strftime('%Y%m%d%H%M%S') if not os.path.exists(path):
filename = f'image_{current_time}.png' os.makedirs(path)
print(f"filename: {filename}") current_time = datetime.now().strftime('%Y%m%d%H%M%S')
# 使用 PIL 打开图像数据 filename = f'image_{current_time}.png'
with Image.open(io.BytesIO(image_data)) as image: full_path = os.path.join(path, filename)
# 保存为 PNG 格式 print(f"完整的文件路径: {full_path}") # 打印完整路径
image.save(os.path.join(path, filename), 'PNG') # print(f"filename: {filename}")
# 使用 PIL 打开图像数据
with Image.open(io.BytesIO(image_data)) as image:
# 保存为 PNG 格式
image.save(os.path.join(path, filename), 'PNG')
print(f"保存图片成功: {filename}") print(f"保存图片成功: {filename}")
return os.path.join(path, filename)
except Exception as e:
print(f"保存图片时出现异常: {e}")
return os.path.join(path, filename)
def unicode_to_chinese(unicode_string): def unicode_to_chinese(unicode_string):
@@ -327,12 +334,25 @@ def chat_completions():
for chunk in upstream_response.iter_content(chunk_size=1024): for chunk in upstream_response.iter_content(chunk_size=1024):
if chunk: if chunk:
buffer += chunk.decode('utf-8') buffer += chunk.decode('utf-8')
# 检查是否存在 "event: ping",如果存在,则只保留 "data:" 后面的内容
if "event: ping" in buffer:
if "data:" in buffer:
buffer = buffer.split("data:", 1)[1]
buffer = "data:" + buffer
# 使用正则表达式移除特定格式的字符串
# print("应用正则表达式之前的 buffer:", buffer.replace('\n', '\\n'))
buffer = re.sub(r'data: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}(\r\n|\r|\n){2}', '', buffer)
# print("应用正则表达式之后的 buffer:", buffer.replace('\n', '\\n'))
while 'data:' in buffer and '\n\n' in buffer: while 'data:' in buffer and '\n\n' in buffer:
end_index = buffer.index('\n\n') + 2 end_index = buffer.index('\n\n') + 2
complete_data, buffer = buffer[:end_index], buffer[end_index:] complete_data, buffer = buffer[:end_index], buffer[end_index:]
# 解析 data 块 # 解析 data 块
try: try:
data_json = json.loads(complete_data.replace('data: ', '')) data_json = json.loads(complete_data.replace('data: ', ''))
# print(f"data_json: {data_json}")
message = data_json.get("message", {}) message = data_json.get("message", {})
message_status = message.get("status") message_status = message.get("status")
content = message.get("content", {}) content = message.get("content", {})
@@ -349,7 +369,7 @@ def chat_completions():
except: except:
pass pass
name = message.get("author", {}).get("name") name = message.get("author", {}).get("name")
if role == "user" or message_status == "finished_successfully" or role == "system": if (role == "user" or message_status == "finished_successfully" or role == "system") and role != "tool":
# 如果是用户发来的消息,直接舍弃 # 如果是用户发来的消息,直接舍弃
continue continue
try: try:
@@ -363,8 +383,10 @@ def chat_completions():
parts = content.get("parts", []) parts = content.get("parts", [])
for part in parts: for part in parts:
try: try:
# print(f"part: {part}")
# print(f"part type: {part.get('content_type')}")
if part.get('content_type') == 'image_asset_pointer': if part.get('content_type') == 'image_asset_pointer':
print(f"content_type: {content_type}") print(f"find img message~")
is_img_message = True is_img_message = True
asset_pointer = part.get('asset_pointer').replace('file-service://', '') asset_pointer = part.get('asset_pointer').replace('file-service://', '')
print(f"asset_pointer: {asset_pointer}") print(f"asset_pointer: {asset_pointer}")