harrylee1900 commited on
Commit
1c68161
·
verified ·
1 Parent(s): b5b9394

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +52 -0
  2. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+
4
+ # 加载 DialoGPT 模型和 Tokenizer
5
+ model_name = "microsoft/DialoGPT-medium"
6
+ model = AutoModelForCausalLM.from_pretrained(model_name)
7
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
8
+
9
+ # 存储对话历史
10
+ conversation_history = []
11
+
12
+
13
+ # 对话生成函数
14
+ def respond_to_input(user_input):
15
+ global conversation_history
16
+
17
+ # 编码用户输入并将其附加到对话历史
18
+ conversation_history.append(f"User: {user_input}")
19
+
20
+ # 将历史对话作为模型输入
21
+ input_text = " ".join(conversation_history[-5:]) # 只传递最近的5条对话,避免过长
22
+ input_ids = tokenizer.encode(input_text + tokenizer.eos_token, return_tensors="pt")
23
+
24
+ # 生成对话的响应
25
+ response_ids = model.generate(input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
26
+
27
+ # 解码模型生成的响应
28
+ bot_response = tokenizer.decode(response_ids[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
29
+
30
+ # 将机器人响应添加到对话历史
31
+ conversation_history.append(f"Bot: {bot_response}")
32
+
33
+ # 返回更新后的对话历史
34
+ chat_history = "\n".join(conversation_history[-10:]) # 显示最近的10条对话
35
+ return chat_history, "" # 更新对话历史并清空输入框
36
+
37
+
38
+ # 创建 Gradio 界面
39
+ iface = gr.Interface(
40
+ fn=respond_to_input,
41
+ inputs=gr.Textbox(label="", placeholder="Type here...", lines=1, scale=2),
42
+ outputs=[gr.Textbox(label="Conversation History", lines=15, interactive=False), gr.Textbox()],
43
+ title="ChatGPT-like Chatbot",
44
+ description="Chat with a bot powered by DialoGPT. Type your question below!",
45
+ theme="default", # 使用默认的主题
46
+ live=True,
47
+ allow_flagging="never", # 禁用标记按钮
48
+ css=".output-textbox { height: 400px; }" # 自定义输出框高度
49
+ )
50
+
51
+ # 启动应用
52
+ iface.launch()
requirements.txt ADDED
File without changes