Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,29 @@
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
generator = pipeline("text-generation", model="
|
|
|
|
| 6 |
|
| 7 |
-
def chat_fn(
|
| 8 |
history = history or []
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
-
gr.ChatInterface(chat_fn).launch()
|
|
|
|
| 1 |
from transformers import pipeline
|
| 2 |
import gradio as gr
|
| 3 |
|
| 4 |
+
# 使用開放的中文 GPT-2 模型
|
| 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 |
+
# 取出 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 |
+
return history, history
|
| 20 |
|
| 21 |
+
with gr.Blocks() as demo:
|
| 22 |
+
chatbot = gr.Chatbot()
|
| 23 |
+
state = gr.State([])
|
| 24 |
+
textbox = gr.Textbox(show_label=False, placeholder="請輸入訊息").style(container=False)
|
| 25 |
|
| 26 |
+
textbox.submit(chat_fn, [textbox, state], [chatbot, state])
|
| 27 |
+
textbox.submit(lambda: "", None, textbox) # 清空輸入框
|
| 28 |
|
| 29 |
+
demo.launch()
|
|
|