Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files
app.py
CHANGED
|
@@ -81,56 +81,30 @@ class ModelHandler:
|
|
| 81 |
print(f"❌ Model loading failed: {e}")
|
| 82 |
raise e
|
| 83 |
|
| 84 |
-
def predict(self, message_dict, history, temperature, max_tokens):
|
| 85 |
-
text = message_dict.get("text", "")
|
| 86 |
-
files = message_dict.get("files", [])
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
print(f"Processing {len(history)} previous messages from history")
|
| 92 |
-
for msg in history:
|
| 93 |
-
role = msg.get("role", "")
|
| 94 |
-
content = msg.get("content", "")
|
| 95 |
-
|
| 96 |
-
if role == "user":
|
| 97 |
-
user_content = []
|
| 98 |
-
|
| 99 |
-
if isinstance(content, list):
|
| 100 |
-
for item in content:
|
| 101 |
-
if isinstance(item, str):
|
| 102 |
-
if os.path.exists(item) or any(item.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']):
|
| 103 |
-
user_content.append({"type": "image", "image": item})
|
| 104 |
-
else:
|
| 105 |
-
user_content.append({"type": "text", "text": item})
|
| 106 |
-
elif isinstance(item, dict):
|
| 107 |
-
user_content.append(item)
|
| 108 |
-
elif isinstance(content, str):
|
| 109 |
-
if content:
|
| 110 |
-
user_content.append({"type": "text", "text": content})
|
| 111 |
-
|
| 112 |
-
if user_content:
|
| 113 |
-
messages.append({"role": "user", "content": user_content})
|
| 114 |
-
|
| 115 |
-
elif role == "assistant":
|
| 116 |
-
if isinstance(content, str) and content:
|
| 117 |
-
messages.append({"role": "assistant", "content": content})
|
| 118 |
-
|
| 119 |
-
current_content = []
|
| 120 |
-
if files:
|
| 121 |
-
for file_path in files:
|
| 122 |
-
current_content.append({"type": "image", "image": file_path})
|
| 123 |
-
|
| 124 |
-
if text:
|
| 125 |
-
sys_prompt_formatted = " ".join(sys_prompt.split())
|
| 126 |
-
full_text = f"{text}\n{sys_prompt_formatted}"
|
| 127 |
-
current_content.append({"type": "text", "text": full_text})
|
| 128 |
-
|
| 129 |
-
if current_content:
|
| 130 |
-
messages.append({"role": "user", "content": current_content})
|
| 131 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
print(f"Total messages for model: {len(messages)}")
|
| 133 |
-
print(f"Message roles: {[m['role'] for m in messages]}")
|
| 134 |
|
| 135 |
text_prompt = self.processor.apply_chat_template(
|
| 136 |
messages, tokenize=False, add_generation_prompt=True
|
|
@@ -163,22 +137,15 @@ class ModelHandler:
|
|
| 163 |
input_length = inputs['input_ids'].shape[1]
|
| 164 |
generated_ids = generated_ids[0][input_length:]
|
| 165 |
|
| 166 |
-
print(f"Input length: {input_length}, Generated token count: {len(generated_ids)}")
|
| 167 |
-
|
| 168 |
generated_text = self.processor.tokenizer.decode(
|
| 169 |
generated_ids,
|
| 170 |
skip_special_tokens=True
|
| 171 |
)
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
if generated_text and generated_text.strip():
|
| 176 |
-
print(f"Yielding generated text: {generated_text[:100]}...")
|
| 177 |
yield generated_text
|
| 178 |
else:
|
| 179 |
-
|
| 180 |
-
print(warning_msg)
|
| 181 |
-
yield warning_msg
|
| 182 |
|
| 183 |
except Exception as e:
|
| 184 |
import traceback
|
|
@@ -197,113 +164,109 @@ def get_model_handler():
|
|
| 197 |
model_handler = ModelHandler(MODEL_PATH)
|
| 198 |
return model_handler
|
| 199 |
|
| 200 |
-
def
|
| 201 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
messages = []
|
|
|
|
| 203 |
for pair in history:
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
#
|
| 209 |
-
|
| 210 |
if isinstance(user_msg, str):
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# 旧格式可能是 (text, image) 或 (image, text)
|
| 214 |
-
for item in user_msg:
|
| 215 |
-
if isinstance(item, str):
|
| 216 |
-
if os.path.exists(item) or any(item.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']):
|
| 217 |
-
user_content.append({"type": "image", "image": item})
|
| 218 |
-
else:
|
| 219 |
-
user_content.append({"type": "text", "text": item})
|
| 220 |
-
elif isinstance(user_msg, list):
|
| 221 |
-
# 可能是新格式的内容列表
|
| 222 |
-
user_content = user_msg
|
| 223 |
|
| 224 |
-
if
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
# 处理助手消息
|
| 228 |
-
if assistant_msg and isinstance(assistant_msg, str):
|
| 229 |
-
messages.append({"role": "assistant", "content": assistant_msg})
|
| 230 |
-
elif isinstance(pair, dict):
|
| 231 |
-
# 如果已经是新格式,直接使用
|
| 232 |
-
messages.append(pair)
|
| 233 |
return messages
|
| 234 |
|
| 235 |
-
def _format_user_input_for_chatbot(text, files):
|
| 236 |
-
"""格式化用户输入为 Chatbot 可显示的格式"""
|
| 237 |
-
if files and text:
|
| 238 |
-
# 有图片和文本,返回元组格式
|
| 239 |
-
return (text, *files)
|
| 240 |
-
elif files:
|
| 241 |
-
# 只有图片
|
| 242 |
-
return files[0] if len(files) == 1 else tuple(files)
|
| 243 |
-
else:
|
| 244 |
-
# 只有文本
|
| 245 |
-
return text
|
| 246 |
-
|
| 247 |
@gpu_decorator
|
| 248 |
def respond(user_msg, history, temp, tokens):
|
| 249 |
"""
|
| 250 |
-
|
| 251 |
-
|
| 252 |
"""
|
| 253 |
|
| 254 |
-
# 1.
|
| 255 |
-
user_content = []
|
| 256 |
-
|
| 257 |
-
# 处理图片文件
|
| 258 |
files = user_msg.get("files", [])
|
| 259 |
-
for file_path in files:
|
| 260 |
-
user_content.append({"type": "image", "image": file_path})
|
| 261 |
-
|
| 262 |
-
# 处理文本
|
| 263 |
text = user_msg.get("text", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
if text:
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
return
|
| 270 |
|
| 271 |
-
#
|
| 272 |
-
new_message = {"role": "user", "content": user_content}
|
| 273 |
-
history.append(new_message)
|
| 274 |
-
|
| 275 |
-
# 3. 立即 yield 更新 UI(显示用户消息),同时清空输入框
|
| 276 |
yield history, gr.MultimodalTextbox(value=None, interactive=False)
|
| 277 |
|
| 278 |
-
#
|
|
|
|
| 279 |
try:
|
| 280 |
handler = get_model_handler()
|
| 281 |
|
| 282 |
-
#
|
| 283 |
-
|
| 284 |
|
| 285 |
-
#
|
| 286 |
-
#
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
yield history, gr.MultimodalTextbox(interactive=False)
|
| 295 |
|
| 296 |
except Exception as e:
|
| 297 |
import traceback
|
| 298 |
traceback.print_exc()
|
| 299 |
-
#
|
| 300 |
-
|
| 301 |
-
|
|
|
|
| 302 |
else:
|
| 303 |
-
history.append(
|
| 304 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 305 |
|
| 306 |
-
#
|
| 307 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 308 |
|
| 309 |
def create_chat_ui():
|
|
|
|
| 81 |
print(f"❌ Model loading failed: {e}")
|
| 82 |
raise e
|
| 83 |
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
def predict(self, messages, temperature, max_tokens):
|
| 86 |
+
# 【修复3】简化 predict 逻辑
|
| 87 |
+
# 不要在函数内部重新解析 history,而是直接接收处理好的标准 messages 列表
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# 将 system prompt 拼接到最后一条用户消息中
|
| 90 |
+
if messages and messages[-1]["role"] == "user":
|
| 91 |
+
content = messages[-1]["content"]
|
| 92 |
+
sys_prompt_fmt = "\n" + " ".join(sys_prompt.split())
|
| 93 |
+
|
| 94 |
+
if isinstance(content, str):
|
| 95 |
+
messages[-1]["content"] += sys_prompt_fmt
|
| 96 |
+
elif isinstance(content, list):
|
| 97 |
+
# 如果是多模态列表,找到 text 部分追加
|
| 98 |
+
text_found = False
|
| 99 |
+
for item in content:
|
| 100 |
+
if item.get("type") == "text":
|
| 101 |
+
item["text"] += sys_prompt_fmt
|
| 102 |
+
text_found = True
|
| 103 |
+
break
|
| 104 |
+
if not text_found:
|
| 105 |
+
content.append({"type": "text", "text": sys_prompt_fmt})
|
| 106 |
+
|
| 107 |
print(f"Total messages for model: {len(messages)}")
|
|
|
|
| 108 |
|
| 109 |
text_prompt = self.processor.apply_chat_template(
|
| 110 |
messages, tokenize=False, add_generation_prompt=True
|
|
|
|
| 137 |
input_length = inputs['input_ids'].shape[1]
|
| 138 |
generated_ids = generated_ids[0][input_length:]
|
| 139 |
|
|
|
|
|
|
|
| 140 |
generated_text = self.processor.tokenizer.decode(
|
| 141 |
generated_ids,
|
| 142 |
skip_special_tokens=True
|
| 143 |
)
|
| 144 |
|
| 145 |
+
if generated_text:
|
|
|
|
|
|
|
|
|
|
| 146 |
yield generated_text
|
| 147 |
else:
|
| 148 |
+
yield "⚠️ No output generated."
|
|
|
|
|
|
|
| 149 |
|
| 150 |
except Exception as e:
|
| 151 |
import traceback
|
|
|
|
| 164 |
model_handler = ModelHandler(MODEL_PATH)
|
| 165 |
return model_handler
|
| 166 |
|
| 167 |
+
def _history_to_messages(history):
|
| 168 |
+
"""
|
| 169 |
+
【新增辅助函数��学习参考代码的逻辑:
|
| 170 |
+
将 Gradio 的 Tuple 历史 [[user_msg, bot_msg], ...]
|
| 171 |
+
转换为 Model 需要的 OpenAI 格式 [{'role': 'user', ...}, ...]
|
| 172 |
+
"""
|
| 173 |
messages = []
|
| 174 |
+
|
| 175 |
for pair in history:
|
| 176 |
+
user_msg, bot_msg = pair
|
| 177 |
+
|
| 178 |
+
# --- 1. 处理用户消息 ---
|
| 179 |
+
if user_msg:
|
| 180 |
+
# 判断是否为图片路径(简单判断)
|
| 181 |
+
is_image = False
|
| 182 |
if isinstance(user_msg, str):
|
| 183 |
+
if os.path.exists(user_msg) or any(user_msg.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp']):
|
| 184 |
+
is_image = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
if is_image:
|
| 187 |
+
# 图片消息
|
| 188 |
+
messages.append({
|
| 189 |
+
"role": "user",
|
| 190 |
+
"content": [{"type": "image", "image": user_msg}]
|
| 191 |
+
})
|
| 192 |
+
else:
|
| 193 |
+
# 文本消息
|
| 194 |
+
messages.append({
|
| 195 |
+
"role": "user",
|
| 196 |
+
"content": [{"type": "text", "text": str(user_msg)}]
|
| 197 |
+
})
|
| 198 |
+
|
| 199 |
+
# --- 2. 处理机器人消息 ---
|
| 200 |
+
if bot_msg:
|
| 201 |
+
messages.append({
|
| 202 |
+
"role": "assistant",
|
| 203 |
+
"content": [{"type": "text", "text": str(bot_msg)}]
|
| 204 |
+
})
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
return messages
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
@gpu_decorator
|
| 209 |
def respond(user_msg, history, temp, tokens):
|
| 210 |
"""
|
| 211 |
+
【修复4】完全重写 respond 函数
|
| 212 |
+
解决 UI (Tuple) 和 Model (Dict) 格式不兼容的问题
|
| 213 |
"""
|
| 214 |
|
| 215 |
+
# 1. 解析 Gradio MultimodalTextbox 的输入
|
|
|
|
|
|
|
|
|
|
| 216 |
files = user_msg.get("files", [])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
text = user_msg.get("text", "")
|
| 218 |
+
|
| 219 |
+
# 2. 更新 UI 历史 (Tuple 格式)
|
| 220 |
+
# -------------------------------------------------
|
| 221 |
+
# 先把图片加进历史
|
| 222 |
+
for f in files:
|
| 223 |
+
history.append([f, None])
|
| 224 |
+
|
| 225 |
+
# 再把文本加进历史
|
| 226 |
if text:
|
| 227 |
+
history.append([text, None])
|
| 228 |
+
elif not text and files:
|
| 229 |
+
# 如果只有图没字,也需要触发回复,不做操作,history 已经有了图片项
|
| 230 |
+
pass
|
|
|
|
| 231 |
|
| 232 |
+
# 立即 yield,让用户先看到自己的输入
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
yield history, gr.MultimodalTextbox(value=None, interactive=False)
|
| 234 |
|
| 235 |
+
# 3. 准备模型输入 (Dict 格式)
|
| 236 |
+
# -------------------------------------------------
|
| 237 |
try:
|
| 238 |
handler = get_model_handler()
|
| 239 |
|
| 240 |
+
# 将当前的 Tuple 历史转换为 Model 能读懂的 Messages 列表
|
| 241 |
+
messages = _history_to_messages(history)
|
| 242 |
|
| 243 |
+
# 在 UI 历史上预留一个空位给机器人回复
|
| 244 |
+
# 如果最后一条只有 User 内容 (例如 [text, None]),我们填充它
|
| 245 |
+
if history and history[-1][1] is None:
|
| 246 |
+
history[-1][1] = ""
|
| 247 |
+
else:
|
| 248 |
+
history.append([None, ""]) # 万一没对应上,追加一个空回复
|
| 249 |
+
|
| 250 |
+
# 4. 调用模型流式生成
|
| 251 |
+
full_response = ""
|
| 252 |
+
for chunk in handler.predict(messages, temp, tokens):
|
| 253 |
+
full_response += chunk
|
| 254 |
+
# 实时更新 UI 历史的最后一条
|
| 255 |
+
history[-1][1] = full_response
|
| 256 |
yield history, gr.MultimodalTextbox(interactive=False)
|
| 257 |
|
| 258 |
except Exception as e:
|
| 259 |
import traceback
|
| 260 |
traceback.print_exc()
|
| 261 |
+
# 错误处理
|
| 262 |
+
err_msg = f"❌ Error: {str(e)}"
|
| 263 |
+
if history and history[-1][1] is None:
|
| 264 |
+
history[-1][1] = err_msg
|
| 265 |
else:
|
| 266 |
+
history.append([None, err_msg])
|
| 267 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 268 |
|
| 269 |
+
# 恢复输入框
|
| 270 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 271 |
|
| 272 |
def create_chat_ui():
|