Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 3 |
+
|
| 4 |
+
# 设置模型名称
|
| 5 |
+
model_id = "Qwen/Qwen3-1.7B-GGUF"
|
| 6 |
+
|
| 7 |
+
# 从 Hugging Face 加载模型和分词器
|
| 8 |
+
# 使用 `device_map="cpu"` 强制在 CPU 上运行,`torch_dtype=torch.float16` 可以节省内存
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 10 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 11 |
+
model_id,
|
| 12 |
+
device_map="auto", # 如果是 CPU 环境,会自动 fallback 到 CPU
|
| 13 |
+
trust_remote_code=True # Qwen 模型需要此选项
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# 创建文本生成管道
|
| 17 |
+
pipe = pipeline(
|
| 18 |
+
"text-generation",
|
| 19 |
+
model=model,
|
| 20 |
+
tokenizer=tokenizer,
|
| 21 |
+
max_new_tokens=512, # 生成的最大token数
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# 定义聊天函数
|
| 25 |
+
def predict(message, history):
|
| 26 |
+
"""
|
| 27 |
+
history 格式: [(用户消息1, 助手回复1), (用户消息2, 助手回复2), ...]
|
| 28 |
+
"""
|
| 29 |
+
# 1. 将对话历史格式化为 Qwen 所需的聊天格式
|
| 30 |
+
conversation = []
|
| 31 |
+
for human, assistant in history:
|
| 32 |
+
conversation.append({"role": "user", "content": human})
|
| 33 |
+
conversation.append({"role": "assistant", "content": assistant})
|
| 34 |
+
# 2. 加入当前用户的新消息
|
| 35 |
+
conversation.append({"role": "user", "content": message})
|
| 36 |
+
|
| 37 |
+
# 3. 应用聊天模板
|
| 38 |
+
prompt = tokenizer.apply_chat_template(
|
| 39 |
+
conversation,
|
| 40 |
+
tokenize=False,
|
| 41 |
+
add_generation_prompt=True # 添加让模型开始回复的提示
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# 4. 生成回复
|
| 45 |
+
outputs = pipe(prompt)
|
| 46 |
+
response = outputs[0]['generated_text'][len(prompt):].strip() # 只提取新生成的部分
|
| 47 |
+
|
| 48 |
+
return response
|
| 49 |
+
|
| 50 |
+
# 创建 Gradio 聊天界面
|
| 51 |
+
gr.ChatInterface(
|
| 52 |
+
fn=predict,
|
| 53 |
+
title="Qwen3-1.7B-GGUF 模型的LLM",
|
| 54 |
+
description="这是一个基于 Qwen/Qwen3-1.7B-GGUF 模型的LLM。",
|
| 55 |
+
).launch(server_name="0.0.0.0", server_port=7860) # 在 Space 环境中必须这样设置
|