Update app.py
Browse files
app.py
CHANGED
|
@@ -4,23 +4,22 @@ import gradio as gr
|
|
| 4 |
from openai import OpenAI
|
| 5 |
|
| 6 |
def encode_image(image_path):
|
| 7 |
-
"""将
|
| 8 |
with open(image_path, "rb") as image_file:
|
| 9 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 10 |
|
| 11 |
def predict(message, history):
|
| 12 |
api_key = os.getenv("SILICONFLOW_API_KEY", "")
|
| 13 |
if not api_key:
|
| 14 |
-
yield "❌ 未检测到 API Key!请先在 Space Settings -> Secrets 中
|
| 15 |
return
|
| 16 |
|
| 17 |
try:
|
| 18 |
-
# 初始化 OpenAI 客户端连接硅基流动
|
| 19 |
client = OpenAI(
|
| 20 |
api_key=api_key.strip(),
|
| 21 |
base_url="https://api.siliconflow.cn/v1"
|
| 22 |
)
|
| 23 |
-
|
| 24 |
text_content = ""
|
| 25 |
files = []
|
| 26 |
|
|
@@ -32,7 +31,7 @@ def predict(message, history):
|
|
| 32 |
|
| 33 |
user_content = []
|
| 34 |
|
| 35 |
-
# 1.
|
| 36 |
for f in files:
|
| 37 |
file_path = f.get("path") if isinstance(f, dict) else f
|
| 38 |
if file_path:
|
|
@@ -42,17 +41,18 @@ def predict(message, history):
|
|
| 42 |
"type": "image_url",
|
| 43 |
"image_url": {"url": f"data:image/jpeg;base64,{base64_img}"}
|
| 44 |
})
|
| 45 |
-
except Exception:
|
| 46 |
-
|
| 47 |
|
| 48 |
-
# 2.
|
| 49 |
if text_content:
|
| 50 |
user_content.append({"type": "text", "text": text_content})
|
| 51 |
|
| 52 |
if not user_content:
|
| 53 |
-
yield "请输入
|
| 54 |
return
|
| 55 |
|
|
|
|
| 56 |
messages = []
|
| 57 |
for msg in history:
|
| 58 |
role = "user" if msg.get("role") == "user" else "assistant"
|
|
@@ -60,16 +60,35 @@ def predict(message, history):
|
|
| 60 |
if isinstance(content_val, dict):
|
| 61 |
content_val = content_val.get("text", "")
|
| 62 |
messages.append({"role": role, "content": str(content_val)})
|
| 63 |
-
|
| 64 |
messages.append({"role": "user", "content": user_content})
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
|
|
|
| 73 |
partial_text = ""
|
| 74 |
for chunk in response:
|
| 75 |
if chunk.choices and chunk.choices[0].delta.content:
|
|
@@ -79,13 +98,13 @@ def predict(message, history):
|
|
| 79 |
except Exception as e:
|
| 80 |
yield f"❌ 请求失败: {str(e)}"
|
| 81 |
|
| 82 |
-
#
|
| 83 |
demo = gr.ChatInterface(
|
| 84 |
fn=predict,
|
| 85 |
title="🌱 AI 植物与通用多模态识别助手",
|
| 86 |
-
description="基于 SiliconFlow
|
| 87 |
multimodal=True
|
| 88 |
)
|
| 89 |
|
| 90 |
if __name__ == "__main__":
|
| 91 |
-
demo.launch(ssr_mode=False)
|
|
|
|
| 4 |
from openai import OpenAI
|
| 5 |
|
| 6 |
def encode_image(image_path):
|
| 7 |
+
"""将本地图片文件转换为 Base64 编码"""
|
| 8 |
with open(image_path, "rb") as image_file:
|
| 9 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 10 |
|
| 11 |
def predict(message, history):
|
| 12 |
api_key = os.getenv("SILICONFLOW_API_KEY", "")
|
| 13 |
if not api_key:
|
| 14 |
+
yield "❌ 未检测到 API Key!请先在 Space Settings -> Secrets 中添加 SILICONFLOW_API_KEY!"
|
| 15 |
return
|
| 16 |
|
| 17 |
try:
|
|
|
|
| 18 |
client = OpenAI(
|
| 19 |
api_key=api_key.strip(),
|
| 20 |
base_url="https://api.siliconflow.cn/v1"
|
| 21 |
)
|
| 22 |
+
|
| 23 |
text_content = ""
|
| 24 |
files = []
|
| 25 |
|
|
|
|
| 31 |
|
| 32 |
user_content = []
|
| 33 |
|
| 34 |
+
# 1. 处理上传的图片/文件
|
| 35 |
for f in files:
|
| 36 |
file_path = f.get("path") if isinstance(f, dict) else f
|
| 37 |
if file_path:
|
|
|
|
| 41 |
"type": "image_url",
|
| 42 |
"image_url": {"url": f"data:image/jpeg;base64,{base64_img}"}
|
| 43 |
})
|
| 44 |
+
except Exception as img_err:
|
| 45 |
+
print(f"图片读取失败: {img_err}")
|
| 46 |
|
| 47 |
+
# 2. 处理输入的文本
|
| 48 |
if text_content:
|
| 49 |
user_content.append({"type": "text", "text": text_content})
|
| 50 |
|
| 51 |
if not user_content:
|
| 52 |
+
yield "请输入问题或上传图片!"
|
| 53 |
return
|
| 54 |
|
| 55 |
+
# 3. 构造历史对话上下文
|
| 56 |
messages = []
|
| 57 |
for msg in history:
|
| 58 |
role = "user" if msg.get("role") == "user" else "assistant"
|
|
|
|
| 60 |
if isinstance(content_val, dict):
|
| 61 |
content_val = content_val.get("text", "")
|
| 62 |
messages.append({"role": role, "content": str(content_val)})
|
| 63 |
+
|
| 64 |
messages.append({"role": "user", "content": user_content})
|
| 65 |
|
| 66 |
+
# 4. 尝试请求硅基流动模型(带备选模型降级逻辑)
|
| 67 |
+
candidate_models = [
|
| 68 |
+
"Pro/Qwen/Qwen2.5-VL-7B-Instruct",
|
| 69 |
+
"Qwen/Qwen2-VL-72B-Instruct",
|
| 70 |
+
"deepseek-ai/deepseek-vl2"
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
response = None
|
| 74 |
+
last_exception = None
|
| 75 |
+
|
| 76 |
+
for model_name in candidate_models:
|
| 77 |
+
try:
|
| 78 |
+
response = client.chat.completions.create(
|
| 79 |
+
model=model_name,
|
| 80 |
+
messages=messages,
|
| 81 |
+
stream=True
|
| 82 |
+
)
|
| 83 |
+
break # 调用成功,跳出循环
|
| 84 |
+
except Exception as err:
|
| 85 |
+
last_exception = err
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
if response is None:
|
| 89 |
+
raise last_exception
|
| 90 |
|
| 91 |
+
# 5. 流式输出结果
|
| 92 |
partial_text = ""
|
| 93 |
for chunk in response:
|
| 94 |
if chunk.choices and chunk.choices[0].delta.content:
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
yield f"❌ 请求失败: {str(e)}"
|
| 100 |
|
| 101 |
+
# 创建 Gradio 界面
|
| 102 |
demo = gr.ChatInterface(
|
| 103 |
fn=predict,
|
| 104 |
title="🌱 AI 植物与通用多模态识别助手",
|
| 105 |
+
description="基于 SiliconFlow 多模态大模型驱动,支持照片识别与流畅对话",
|
| 106 |
multimodal=True
|
| 107 |
)
|
| 108 |
|
| 109 |
if __name__ == "__main__":
|
| 110 |
+
demo.launch(ssr_mode=False) # 关闭 SSR 避免 Gradio 6 探测报错
|