Jenny991 commited on
Commit
aa665ef
·
verified ·
1 Parent(s): 131598f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -15
app.py CHANGED
@@ -1,24 +1,29 @@
1
  from transformers import pipeline
2
  import gradio as gr
3
 
4
- # 中文 GPT2 模型
5
- generator = pipeline("text-generation", model="IDEA-CCNL/Wenzhong2.0-GPT2-110M")
 
6
 
7
- def chat_fn(user_input, history):
8
  history = history or []
 
9
 
10
- # 建立 prompt
11
- prompt = ""
12
- for user_msg, bot_msg in history:
13
- prompt += f"用戶:{user_msg}\n機器人:{bot_msg}\n"
14
- prompt += f"用戶:{user_input}\n機器人:"
 
 
 
15
 
16
- # 模型生成
17
- output = generator(prompt, max_new_tokens=100, pad_token_id=50256)[0]["generated_text"]
18
- reply = output.split("機器人:")[-1].strip()
 
19
 
20
- history.append((user_input, reply))
21
- return history, history
22
 
23
- # ✅ 用 gr.ChatInterface() 就會自動長得像聊天室
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()