mibaiyou's picture
Update app.py
febc3b1 verified
import gradio as gr
import os
import requests
from http import HTTPStatus
from dashscope import Application
import io
import PIL.Image
import time
# 配置参数
API_KEY = os.getenv("DASHSCOPE_API_KEY1")
APP_ID = 'caa8ee1c0ac7419888ab59b942326385'
CHEVERETO_API_KEY = "chv_SNduL_12ffd9b01310d168e4f2a89ae8a839276a8366746c24c620b687b67b362c65ab5f3d1c6fe4683abe8d94abc3c2e18008aa8faadbeb8c5a9895f52663609316d5"
CHEVERETO_API_URL = "https://www.picgo.net/api/1/upload" # 替换为你的Chevereto图床API地址
if not API_KEY:
raise ValueError("请先在环境变量中设置 DASHSCOPE_API_KEY1")
def upload_to_chevereto(image):
# 压缩图片:最大边不超过1024,JPEG质量85
max_size = (1024, 1024)
image = image.copy()
image.thumbnail(max_size)
buffered = io.BytesIO()
img_format = image.format if image.format in ["JPEG", "JPG", "PNG", "GIF", "BMP", "WEBP"] else "JPEG"
save_kwargs = {}
if img_format in ["JPEG", "JPG"]:
save_kwargs["quality"] = 85
image.save(buffered, format=img_format, **save_kwargs)
buffered.seek(0)
files = {
"source": buffered
}
headers = {
"X-API-Key": CHEVERETO_API_KEY
}
response = requests.post(CHEVERETO_API_URL, files=files, headers=headers)
if response.status_code == 200:
res_json = response.json()
if res_json.get("status_code") == 200:
return res_json['image']['url']
else:
raise Exception(f"上传失败:{res_json.get('status_txt')}")
else:
raise Exception(f"HTTP错误:{response.status_code}")
def chat_with_ai(message, chat_history, session_id, image):
try:
image_url = None
if image is not None and isinstance(image, PIL.Image.Image):
image_url = upload_to_chevereto(image)
# 构建 messages 传给大模型(只文本)
messages = []
for msg in chat_history:
if msg["role"] == "user":
# 去掉markdown图片,只保留文本
user_text = msg["content"].split("![](")[0].strip()
messages.append({"role": "user", "content": user_text})
elif msg["role"] == "assistant":
messages.append({"role": "assistant", "content": msg["content"]})
# 新一轮用户输入
user_content = message
messages.append({"role": "user", "content": user_content})
# 构建 inputs
inputs = {"messages": messages}
if image_url:
inputs["image_list"] = [image_url]
print("=== 调用大模型 inputs ===")
print(inputs)
time.sleep(1)
response = Application.call(
api_key=API_KEY,
app_id=APP_ID,
messages=inputs["messages"],
image_list=inputs["image_list"] if "image_list" in inputs else None,
)
print("=== 大模型 response ===")
print(response)
if response.status_code != HTTPStatus.OK:
error_msg = f"⚠️ API错误 ({response.status_code}): {getattr(response, 'message', '无详细信息')}"
if image_url:
chat_history.append({"role": "user", "content": f"{message}\n![]({image_url})"})
else:
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": error_msg})
return chat_history, session_id
new_session_id = getattr(response.output, 'session_id', session_id)
ai_response = getattr(response.output, 'text', '')
if image_url:
chat_history.append({"role": "user", "content": f"{message}\n![]({image_url})"})
else:
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": ai_response})
return chat_history, new_session_id
except Exception as e:
error_msg = f"⚠️ 系统错误: {str(e)}"
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": error_msg})
return chat_history, session_id
# 以下界面部分与1.py一致
with gr.Blocks(theme=gr.themes.Soft()) as demo:
session_state = gr.State(value=None)
gr.Markdown(
"""
<div style="text-align:center;">
<span style="font-size:2.5em;font-weight:bold;">智能搭配师</span><br>
<span style="font-size:1em;color:gray;">by:好醋酿十年</span>
</div>
""",
elem_id="title"
)
with gr.Row():
chatbot = gr.Chatbot(
height=600,
avatar_images=(
"user.png",
"ai.png"
),
render_markdown=True,
type="messages"
)
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(label="上传图片", type="pil", sources=["upload"])
with gr.Column(scale=4):
text_input = gr.Textbox(
placeholder="输入文字消息...",
lines=1,
container=False
)
submit_btn = gr.Button("发送", variant="primary")
def clear_inputs():
return "", None
submit_btn.click(
fn=chat_with_ai,
inputs=[text_input, chatbot, session_state, image_input],
outputs=[chatbot, session_state],
show_progress="hidden"
).then(
fn=clear_inputs,
outputs=[text_input, image_input]
)
text_input.submit(
fn=chat_with_ai,
inputs=[text_input, chatbot, session_state, image_input],
outputs=[chatbot, session_state],
show_progress="hidden"
).then(
fn=clear_inputs,
outputs=[text_input, image_input]
)
if __name__ == "__main__":
demo.launch()