Update app.py
Browse files
app.py
CHANGED
@@ -1,30 +1,25 @@
|
|
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 |
|
8 |
def chat_fn(message, history):
|
9 |
history = history or []
|
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="
|
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)
|
29 |
|
30 |
demo.launch()
|
|
|
1 |
from transformers import pipeline
|
2 |
import gradio as gr
|
3 |
|
|
|
4 |
generator = pipeline("text-generation", model="ckiplab/gpt2-base-chinese",
|
5 |
tokenizer="ckiplab/gpt2-base-chinese")
|
6 |
|
7 |
def chat_fn(message, history):
|
8 |
history = history or []
|
9 |
input_text = "\n".join(history + [f"你: {message}", "AI:"])
|
|
|
10 |
output = generator(input_text, max_new_tokens=80, pad_token_id=0)[0]["generated_text"]
|
11 |
response = output.split("AI:")[-1].strip().split("你:")[0].strip()
|
|
|
12 |
history.append(f"你: {message}")
|
13 |
history.append(f"AI: {response}")
|
|
|
|
|
14 |
messages = [(history[i], history[i+1]) for i in range(0, len(history)-1, 2)]
|
15 |
return messages, history
|
16 |
|
17 |
with gr.Blocks() as demo:
|
18 |
+
chatbot = gr.Chatbot(label="中文聊天機器人", type="tuples")
|
19 |
state = gr.State([])
|
20 |
textbox = gr.Textbox(placeholder="請輸入訊息")
|
21 |
|
22 |
textbox.submit(chat_fn, [textbox, state], [chatbot, state])
|
23 |
+
textbox.submit(lambda: "", None, textbox)
|
24 |
|
25 |
demo.launch()
|