Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
-
#
|
| 5 |
generator = pipeline("text-generation", model="ckiplab/gpt2-base-chinese",
|
| 6 |
tokenizer="ckiplab/gpt2-base-chinese")
|
| 7 |
|
|
@@ -10,18 +10,19 @@ def chat_fn(message, history):
|
|
| 10 |
input_text = "\n".join(history + [f"你: {message}", "AI:"])
|
| 11 |
|
| 12 |
output = generator(input_text, max_new_tokens=80, pad_token_id=0)[0]["generated_text"]
|
| 13 |
-
# 取出 AI 回應部分
|
| 14 |
response = output.split("AI:")[-1].strip().split("你:")[0].strip()
|
| 15 |
|
| 16 |
history.append(f"你: {message}")
|
| 17 |
history.append(f"AI: {response}")
|
| 18 |
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
with gr.Blocks() as demo:
|
| 22 |
-
chatbot = gr.Chatbot()
|
| 23 |
state = gr.State([])
|
| 24 |
-
textbox = gr.Textbox(
|
| 25 |
|
| 26 |
textbox.submit(chat_fn, [textbox, state], [chatbot, state])
|
| 27 |
textbox.submit(lambda: "", None, textbox) # 清空輸入框
|
|
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
+
# 使用公開支援中文的 GPT2 模型
|
| 5 |
generator = pipeline("text-generation", model="ckiplab/gpt2-base-chinese",
|
| 6 |
tokenizer="ckiplab/gpt2-base-chinese")
|
| 7 |
|
|
|
|
| 10 |
input_text = "\n".join(history + [f"你: {message}", "AI:"])
|
| 11 |
|
| 12 |
output = generator(input_text, max_new_tokens=80, pad_token_id=0)[0]["generated_text"]
|
|
|
|
| 13 |
response = output.split("AI:")[-1].strip().split("你:")[0].strip()
|
| 14 |
|
| 15 |
history.append(f"你: {message}")
|
| 16 |
history.append(f"AI: {response}")
|
| 17 |
|
| 18 |
+
# 將歷史轉換成 [(user, bot), ...] 格式
|
| 19 |
+
messages = [(history[i], history[i+1]) for i in range(0, len(history)-1, 2)]
|
| 20 |
+
return messages, history
|
| 21 |
|
| 22 |
with gr.Blocks() as demo:
|
| 23 |
+
chatbot = gr.Chatbot(label="中文聊天機器人", type="chatbot") # 預設 tuple 格式,不報錯
|
| 24 |
state = gr.State([])
|
| 25 |
+
textbox = gr.Textbox(placeholder="請輸入訊息")
|
| 26 |
|
| 27 |
textbox.submit(chat_fn, [textbox, state], [chatbot, state])
|
| 28 |
textbox.submit(lambda: "", None, textbox) # 清空輸入框
|