Spaces:
Running
on
Zero
Running
on
Zero
Upload folder using huggingface_hub
Browse files- app.py +114 -158
- requirements.txt +9 -9
app.py
CHANGED
|
@@ -81,56 +81,26 @@ class ModelHandler:
|
|
| 81 |
print(f"❌ Model loading failed: {e}")
|
| 82 |
raise e
|
| 83 |
|
| 84 |
-
def predict(self,
|
| 85 |
-
|
| 86 |
-
files = message_dict.get("files", [])
|
| 87 |
-
|
| 88 |
-
messages = []
|
| 89 |
-
|
| 90 |
-
if history:
|
| 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 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
text_prompt = self.processor.apply_chat_template(
|
| 136 |
messages, tokenize=False, add_generation_prompt=True
|
|
@@ -155,37 +125,17 @@ class ModelHandler:
|
|
| 155 |
do_sample=True if temperature > 0 else False,
|
| 156 |
)
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
generated_ids,
|
| 170 |
-
skip_special_tokens=True
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
print(f"Generation completed. Output length: {len(generated_text)}, Content preview: {repr(generated_text[:200])}")
|
| 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 |
-
warning_msg = "⚠️ No output generated. The model may not have produced any response."
|
| 180 |
-
print(warning_msg)
|
| 181 |
-
yield warning_msg
|
| 182 |
-
|
| 183 |
-
except Exception as e:
|
| 184 |
-
import traceback
|
| 185 |
-
error_details = traceback.format_exc()
|
| 186 |
-
print(f"Error in model.generate: {error_details}")
|
| 187 |
-
yield f"❌ Generation error: {str(e)}"
|
| 188 |
-
return
|
| 189 |
|
| 190 |
model_handler = None
|
| 191 |
|
|
@@ -197,113 +147,120 @@ 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 |
-
|
| 214 |
-
|
| 215 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
user_msg:
|
| 251 |
-
history:
|
| 252 |
"""
|
|
|
|
|
|
|
| 253 |
|
| 254 |
-
# 1.
|
| 255 |
-
|
| 256 |
|
| 257 |
-
#
|
| 258 |
-
|
| 259 |
-
for
|
| 260 |
-
|
| 261 |
|
| 262 |
-
#
|
| 263 |
-
text = user_msg.get("text", "")
|
| 264 |
if text:
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
# 调用 predict (注意:这里直接传 history 即可,因为 history 已经是完整的上下文)
|
| 286 |
-
# 我们传入 history 的深拷贝以防修改影响 UI,或者直接传引用如果 predict 内部做了处理
|
| 287 |
-
# 这里为了安全,我们只把 history 传进去,predict 内部会处理 sys_prompt 的追加逻辑
|
| 288 |
-
import copy
|
| 289 |
-
messages_payload = copy.deepcopy(history[:-1]) # 去掉刚才加的空 assistant
|
| 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 |
-
if history and history[-1][
|
| 301 |
-
history[-1][
|
| 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():
|
|
@@ -324,7 +281,6 @@ def create_chat_ui():
|
|
| 324 |
label="Chat",
|
| 325 |
avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=Qwen"),
|
| 326 |
height=650,
|
| 327 |
-
type="messages"
|
| 328 |
)
|
| 329 |
|
| 330 |
chat_input = gr.MultimodalTextbox(
|
|
|
|
| 81 |
print(f"❌ Model loading failed: {e}")
|
| 82 |
raise e
|
| 83 |
|
| 84 |
+
def predict(self, messages, temperature, max_tokens):
|
| 85 |
+
# 这里的 messages 已经是处理好的标准 OpenAI 格式列表
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
+
# 将 sys_prompt 注入到最后一条用户消息中
|
| 88 |
+
if messages and messages[-1]["role"] == "user":
|
| 89 |
+
content = messages[-1]["content"]
|
| 90 |
+
sys_prompt_fmt = "\n" + " ".join(sys_prompt.split())
|
| 91 |
+
|
| 92 |
+
if isinstance(content, str):
|
| 93 |
+
messages[-1]["content"] += sys_prompt_fmt
|
| 94 |
+
elif isinstance(content, list):
|
| 95 |
+
# 查找文本部分并追加,如果没有则添加
|
| 96 |
+
text_found = False
|
| 97 |
+
for item in content:
|
| 98 |
+
if item.get("type") == "text":
|
| 99 |
+
item["text"] += sys_prompt_fmt
|
| 100 |
+
text_found = True
|
| 101 |
+
break
|
| 102 |
+
if not text_found:
|
| 103 |
+
content.append({"type": "text", "text": sys_prompt_fmt})
|
| 104 |
|
| 105 |
text_prompt = self.processor.apply_chat_template(
|
| 106 |
messages, tokenize=False, add_generation_prompt=True
|
|
|
|
| 125 |
do_sample=True if temperature > 0 else False,
|
| 126 |
)
|
| 127 |
|
| 128 |
+
with torch.no_grad():
|
| 129 |
+
generated_ids = self.model.generate(**generation_kwargs)
|
| 130 |
+
|
| 131 |
+
input_length = inputs['input_ids'].shape[1]
|
| 132 |
+
generated_ids = generated_ids[0][input_length:]
|
| 133 |
+
|
| 134 |
+
generated_text = self.processor.tokenizer.decode(
|
| 135 |
+
generated_ids, skip_special_tokens=True
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
yield generated_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
model_handler = None
|
| 141 |
|
|
|
|
| 147 |
model_handler = ModelHandler(MODEL_PATH)
|
| 148 |
return model_handler
|
| 149 |
|
| 150 |
+
def _history_to_messages(history):
|
| 151 |
+
"""
|
| 152 |
+
将 Gradio 的 Tuple 历史 [[user, bot], ...] 转换为 OpenAI 格式的消息列表。
|
| 153 |
+
以便发送给模型。
|
| 154 |
+
"""
|
| 155 |
messages = []
|
| 156 |
+
|
| 157 |
for pair in history:
|
| 158 |
+
user_msg, bot_msg = pair
|
| 159 |
+
|
| 160 |
+
# --- 处理用户消息 ---
|
| 161 |
+
if user_msg:
|
| 162 |
+
# 检查是否是文件路径(图片)
|
| 163 |
+
# Gradio 中图片通常是临时路径,或者 http 链接
|
| 164 |
+
is_image = False
|
| 165 |
if isinstance(user_msg, str):
|
| 166 |
+
if os.path.exists(user_msg) or user_msg.startswith("http"):
|
| 167 |
+
# 简单的判断:如果是现有路径或者是URL,且看起来像图片
|
| 168 |
+
lower_msg = user_msg.lower()
|
| 169 |
+
if any(lower_msg.endswith(ext) for ext in ['.jpg', '.png', '.jpeg', '.webp', '.bmp']):
|
| 170 |
+
is_image = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# 构建 User Content
|
| 173 |
+
if is_image:
|
| 174 |
+
# 这是一个独立的图片消息
|
| 175 |
+
# 注意:为了模型效果,最好将图片和紧接着的文本合并。
|
| 176 |
+
# 但为了代码简单,我们先作为独立消息,大多数 VLM 也能处理。
|
| 177 |
+
messages.append({
|
| 178 |
+
"role": "user",
|
| 179 |
+
"content": [{"type": "image", "image": user_msg}]
|
| 180 |
+
})
|
| 181 |
+
else:
|
| 182 |
+
# 这是一个文本消息
|
| 183 |
+
# 如果上一条也是 user 且是 image,尝试合并(可选,这里简单起见直接 append)
|
| 184 |
+
messages.append({
|
| 185 |
+
"role": "user",
|
| 186 |
+
"content": [{"type": "text", "text": str(user_msg)}]
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
# --- 处理机器人消息 ---
|
| 190 |
+
if bot_msg:
|
| 191 |
+
messages.append({
|
| 192 |
+
"role": "assistant",
|
| 193 |
+
"content": [{"type": "text", "text": str(bot_msg)}]
|
| 194 |
+
})
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
return messages
|
| 197 |
|
| 198 |
+
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
@gpu_decorator
|
| 200 |
def respond(user_msg, history, temp, tokens):
|
| 201 |
"""
|
| 202 |
+
user_msg: {'text': '...', 'files': ['...']}
|
| 203 |
+
history: List[List[str | None]] <- 这是旧版格式
|
| 204 |
"""
|
| 205 |
+
files = user_msg.get("files", [])
|
| 206 |
+
text = user_msg.get("text", "")
|
| 207 |
|
| 208 |
+
# 1. 更新 UI History (先让用户在界面上看到自己的输入)
|
| 209 |
+
# -------------------------------------------------
|
| 210 |
|
| 211 |
+
# 先处理图片:每张图片作为一个单独的 (path, None) 元组添加到历史
|
| 212 |
+
# Gradio Chatbot 会自动识别路径并显示图片
|
| 213 |
+
for f in files:
|
| 214 |
+
history.append([f, None])
|
| 215 |
|
| 216 |
+
# 再处理文本
|
|
|
|
| 217 |
if text:
|
| 218 |
+
# 如果有文本,添加 (text, None),准备让机器人回复这一条
|
| 219 |
+
history.append([text, None])
|
| 220 |
+
elif not text and files:
|
| 221 |
+
# 如果只有图片没文本,添加一个空的占位符,让机器人回复图片
|
| 222 |
+
# 注意:这里我们用 (None, None) 可能会报错,用 ("(image uploaded)", None) 或者
|
| 223 |
+
# 更常见的做法是:最后一项的 user 部分必须非空才能看起来正常,
|
| 224 |
+
# 但我们可以在下面立即生成回复填补 bot 部分。
|
| 225 |
+
pass
|
| 226 |
|
| 227 |
+
# 此时 history 已经更新了用户的输入
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
yield history, gr.MultimodalTextbox(value=None, interactive=False)
|
| 229 |
|
| 230 |
+
# 2. 调用模型
|
| 231 |
+
# -------------------------------------------------
|
| 232 |
try:
|
| 233 |
handler = get_model_handler()
|
| 234 |
|
| 235 |
+
# 将 Tuple 历史转换为模型能懂的 Messages 列表
|
| 236 |
+
# 注意:我们需要把刚才加入的“只有用户部分”的消息也转进去
|
| 237 |
+
messages = _history_to_messages(history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
# 在界面上为机器人的回复预留位置
|
| 240 |
+
# 如果最后一条是 [user_content, None],我们把它改成 [user_content, ""]
|
| 241 |
+
if history and history[-1][1] is None:
|
| 242 |
+
history[-1][1] = ""
|
| 243 |
+
else:
|
| 244 |
+
# 如果万一没有对应行,加一行
|
| 245 |
+
history.append([None, ""])
|
| 246 |
+
|
| 247 |
+
# 流式生成
|
| 248 |
+
full_response = ""
|
| 249 |
+
for chunk in handler.predict(messages, temp, tokens):
|
| 250 |
+
full_response += chunk
|
| 251 |
+
history[-1][1] = full_response # 更新最后一行机器人的回复
|
| 252 |
yield history, gr.MultimodalTextbox(interactive=False)
|
| 253 |
|
| 254 |
except Exception as e:
|
| 255 |
import traceback
|
| 256 |
traceback.print_exc()
|
| 257 |
+
err_msg = f"❌ Error: {str(e)}"
|
| 258 |
+
if history and history[-1][1] is None:
|
| 259 |
+
history[-1][1] = err_msg
|
| 260 |
else:
|
| 261 |
+
history.append([None, err_msg])
|
| 262 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 263 |
|
|
|
|
| 264 |
yield history, gr.MultimodalTextbox(interactive=True)
|
| 265 |
|
| 266 |
def create_chat_ui():
|
|
|
|
| 281 |
label="Chat",
|
| 282 |
avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=Qwen"),
|
| 283 |
height=650,
|
|
|
|
| 284 |
)
|
| 285 |
|
| 286 |
chat_input = gr.MultimodalTextbox(
|
requirements.txt
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
gradio>=6.0.0
|
| 2 |
-
torch>=2.0.0
|
| 3 |
-
torchvision>=0.15.0
|
| 4 |
-
transformers>=4.37.0
|
| 5 |
-
qwen-vl-utils
|
| 6 |
-
accelerate
|
| 7 |
-
sentencepiece
|
| 8 |
-
protobuf
|
| 9 |
-
pillow
|
| 10 |
einops
|
|
|
|
| 1 |
+
gradio>=6.0.0
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
torchvision>=0.15.0
|
| 4 |
+
transformers>=4.37.0
|
| 5 |
+
qwen-vl-utils
|
| 6 |
+
accelerate
|
| 7 |
+
sentencepiece
|
| 8 |
+
protobuf
|
| 9 |
+
pillow
|
| 10 |
einops
|