gugebing commited on
Commit
5974fc9
1 Parent(s): c1ba8d9

Upload 2 files

Browse files
Files changed (2) hide show
  1. main.py +290 -0
  2. preview.png +0 -0
main.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # encoding=utf-8
2
+ import asyncio
3
+ import random
4
+ import re
5
+ from functools import partial
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import httpcore
10
+ from EdgeGPT import Chatbot, ConversationStyle
11
+ from utils import postprocess
12
+
13
+ cookiePath = r"./cookiePath" # 填写存放Bing的cookies目录
14
+ cookieList = [_ for _ in Path(cookiePath).iterdir()]
15
+ cookieDict = {} # {IP: [bot, Bing]}
16
+ IP = ""
17
+ QUESTION = []
18
+ NumUserMessagesInConversation = [] # [max,Num]
19
+ gr.Chatbot.postprocess = postprocess
20
+ # 读取css文件
21
+ with open("./static/main.css", "r", encoding="utf-8") as f:
22
+ my_css = f.read()
23
+
24
+
25
+ async def get_message(message):
26
+ """
27
+ 从Bing请求数据.
28
+ """
29
+ global QUESTION, NumUserMessagesInConversation
30
+ try:
31
+ rs = await cookieDict[IP][1](prompt=message)
32
+ except httpcore.ConnectTimeout as exc:
33
+ return "请求失败,请重试……"
34
+ except Exception as exc:
35
+ return "请求失败,请重试……"
36
+ try:
37
+ QUESTION = [_["text"] for _ in rs["item"]["messages"][1]["suggestedResponses"]]
38
+ except KeyError:
39
+ QUESTION = []
40
+ except IndexError:
41
+ QUESTION = []
42
+ try:
43
+ quotes = rs["item"]["messages"][1]["adaptiveCards"][0]["body"]
44
+ except KeyError:
45
+ quotes = []
46
+ except IndexError:
47
+ quotes = []
48
+
49
+ if quotes.__len__() == 1:
50
+ body, quotes = quotes[0]["text"], []
51
+ elif quotes.__len__() > 1:
52
+ quotes = quotes[0]["text"]
53
+ split = quotes.find("\n\n")
54
+ body = quotes[split + 2 :]
55
+ quotes = quotes[:split]
56
+ quotes_ = []
57
+ quotes = quotes.split("\n")
58
+ count = 1
59
+ for quote in quotes:
60
+ quote = quote[quote.find(": ") + 2 :]
61
+ s = quote.find(" ")
62
+ # quotes_.append({"url": quote[:s], "title": quote[s + 2 : -1]})
63
+ quotes_.append(
64
+ f"""<a href={quote[:s]} target="_blank">[{count}]: {quote[s+2:-1]}</a>"""
65
+ )
66
+ count += 1
67
+ quotes = "<br>".join(quotes_)
68
+ body += "\n<br>了解详细信息:<br>" + quotes
69
+ else:
70
+ body = ""
71
+ body = re.sub(r"\[\^(\d+)\^\]", "", body)
72
+ NumUserMessagesInConversation = [
73
+ rs["item"]["throttling"]["maxNumUserMessagesInConversation"],
74
+ rs["item"]["throttling"]["numUserMessagesInConversation"],
75
+ ]
76
+ return body
77
+
78
+
79
+ # 创建一个 Gradio Blocks 对象
80
+ with gr.Blocks(css=my_css) as demo:
81
+ # 创建一个Radio用于选择聊天风格
82
+ with gr.Accordion(label="点这里切换Ai风格", open=False):
83
+ chat_style = gr.Radio(
84
+ ["🥳更有创造性", "😊两者间平衡", "🤓更有精确性"],
85
+ value="😊两者间平衡",
86
+ show_label=False,
87
+ elem_id="style_select",
88
+ )
89
+ # 创建一个聊天机器人
90
+ chatbot = gr.Chatbot(show_label=False, elem_id="chat_window")
91
+ chatbot.style(height="100%")
92
+ # 创建三个备选项
93
+ with gr.Row():
94
+ question1 = gr.Button("你好,Bing。你可以帮我做什么?").style(size="sm")
95
+ question2 = gr.Button("你好,Bing。请随便写一首诗。").style(size="sm")
96
+ question3 = gr.Button("你好,Bing。帮我搜索最近的新闻。").style(size="sm")
97
+
98
+ # 创建一个文本框
99
+ msg = gr.Textbox(show_label=False, elem_id="user_input", placeholder="有问题尽管问我……")
100
+
101
+ with gr.Row():
102
+ # 创建一个清除按钮
103
+ clear = gr.Button("🧹打扫干净屋子再请客🤖").style(size="sm")
104
+ # 创建一个提交按钮
105
+ btn = gr.Button(value="⬆️把消息告诉Bing🅱️").style(size="sm")
106
+
107
+ # chat_style改变时的事件
108
+ def change_style(choice, history, request: gr.Request):
109
+ global cookieList, cookieDict, IP
110
+ IP = request.client.host
111
+ cookieDict[IP] = [Chatbot(random.choice(cookieList)), None]
112
+ if choice == "🥳更有创造性":
113
+ cookieDict[IP][1] = partial(
114
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.creative
115
+ )
116
+ return history + [[None, "好的我会更有创造性,让我们重新开始"]]
117
+ elif choice == "😊两者间平衡":
118
+ cookieDict[IP][1] = partial(
119
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.balanced
120
+ )
121
+ return history + [[None, "好的我会尽量保持平衡,让我们重新开始"]]
122
+ else:
123
+ cookieDict[IP][1] = partial(
124
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.precise
125
+ )
126
+ return history + [[None, "好的我会更有精确性,让我们重新开始"]]
127
+
128
+ # 绑定chat_style选择时的事件
129
+ chat_style.change(fn=change_style, inputs=[chat_style, chatbot], outputs=[chatbot])
130
+
131
+ def bot_login(choice):
132
+ """
133
+ 注册bot
134
+ """
135
+ global cookieList, cookieDict, IP
136
+ cookieDict[IP] = [Chatbot(random.choice(cookieList)), None]
137
+ if choice == "🥳更有创造性":
138
+ cookieDict[IP][1] = partial(
139
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.creative
140
+ )
141
+ elif choice == "😊两者间平衡":
142
+ cookieDict[IP][1] = partial(
143
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.balanced
144
+ )
145
+ else:
146
+ cookieDict[IP][1] = partial(
147
+ cookieDict[IP][0].ask, conversation_style=ConversationStyle.precise
148
+ )
149
+
150
+ # 用户输入的回调函数
151
+ def user(user_message, history, choice, request: gr.Request):
152
+ """
153
+ user 函数的目的是将用户输入添加到历史记录中。history 参数实际上是 chatbot 对象,而不是一个列表。但是,chatbot 对象是一个包含历史记录的列表,第一个返回值作为点击submit后的输入框值。
154
+ """
155
+ global IP
156
+ if user_message == "" or user_message == None:
157
+ return "", history
158
+ IP = request.client.host
159
+ if IP not in cookieDict:
160
+ bot_login(choice)
161
+ return "", history + [[user_message, None]]
162
+
163
+ # 机器人回复的回调函数
164
+ def bing(history):
165
+ if history:
166
+ user_message = history[-1][0]
167
+ # bot_message = random.choice(["# Yes", "## No"])
168
+ # bot_message = [r'<a href="www.baidu.com">百度</a>']
169
+ bot_message = asyncio.run(get_message(user_message))
170
+ # bot_message = ['1', ['1','2','3']]
171
+ history[-1][1] = bot_message
172
+ return history
173
+
174
+ def change_question(choice, history):
175
+ """
176
+ 更改快速选项
177
+ """
178
+ global QUESTION, NumUserMessagesInConversation
179
+ if NumUserMessagesInConversation:
180
+ if NumUserMessagesInConversation[1] >= NumUserMessagesInConversation[0]:
181
+ bot_login(choice)
182
+ return (
183
+ history + [[None, "我们的聊天达到了次数限制,让我们重新开始"]],
184
+ gr.Button.update(value="你好,Bing。你可以帮我做什么?", visible=True),
185
+ gr.Button.update(value="你好,Bing。请随便写一首诗。", visible=True),
186
+ gr.Button.update(value="你好,Bing。帮我搜索最近的新闻。", visible=True),
187
+ )
188
+ match len(QUESTION):
189
+ case 0:
190
+ return (history,
191
+ gr.Button.update(visible=False), gr.Button.update(
192
+ visible=False
193
+ ), gr.Button.update(visible=False))
194
+ case 1:
195
+ return (
196
+ history,
197
+ gr.Button.update(value=QUESTION[0], visible=True),
198
+ gr.Button.update(visible=False),
199
+ gr.Button.update(visible=False),
200
+ )
201
+ case 2:
202
+ return (
203
+ history,
204
+ gr.Button.upda1te(value=QUESTION[0], visible=True),
205
+ gr.Button.update(value=QUESTION[1], visible=True),
206
+ gr.Button.update(visible=False),
207
+ )
208
+ case _:
209
+ return (
210
+ history,
211
+ gr.Button.update(value=QUESTION[0], visible=True),
212
+ gr.Button.update(value=QUESTION[1], visible=True),
213
+ gr.Button.update(value=QUESTION[2], visible=True),
214
+ )
215
+
216
+ # 快速选择时的事件
217
+ question1.click(
218
+ fn=user,
219
+ inputs=[question1, chatbot, chat_style],
220
+ outputs=[msg, chatbot],
221
+ queue=False,
222
+ ).then(fn=bing, inputs=[chatbot], outputs=[chatbot], queue=False).then(
223
+ fn=change_question,
224
+ inputs=[chat_style, chatbot],
225
+ outputs=[chatbot, question1, question2, question3],
226
+ )
227
+ question2.click(
228
+ fn=user,
229
+ inputs=[question2, chatbot, chat_style],
230
+ outputs=[msg, chatbot],
231
+ queue=False,
232
+ ).then(fn=bing, inputs=chatbot, outputs=chatbot, queue=False).then(
233
+ fn=change_question,
234
+ inputs=[chat_style, chatbot],
235
+ outputs=[chatbot, question1, question2, question3],
236
+ )
237
+ question3.click(
238
+ fn=user,
239
+ inputs=[question3, chatbot, chat_style],
240
+ outputs=[msg, chatbot],
241
+ queue=False,
242
+ ).then(fn=bing, inputs=chatbot, outputs=chatbot, queue=False).then(
243
+ fn=change_question,
244
+ inputs=[chat_style, chatbot],
245
+ outputs=[chatbot, question1, question2, question3],
246
+ )
247
+
248
+ # 将用户输入和机器人回复绑定到 msg.submit() 方法上
249
+ msg.submit(
250
+ fn=user, inputs=[msg, chatbot, chat_style], outputs=[msg, chatbot], queue=False
251
+ ).then(fn=bing, inputs=chatbot, outputs=chatbot, queue=False).then(
252
+ fn=change_question,
253
+ inputs=[chat_style, chatbot],
254
+ outputs=[chatbot, question1, question2, question3],
255
+ )
256
+
257
+ # 发送按钮的事件
258
+ btn.click(
259
+ fn=user, inputs=[msg, chatbot, chat_style], outputs=[msg, chatbot], queue=False
260
+ ).then(fn=bing, inputs=chatbot, outputs=chatbot, queue=False).then(
261
+ fn=change_question,
262
+ inputs=[chat_style, chatbot],
263
+ outputs=[chatbot, question1, question2, question3],
264
+ )
265
+
266
+ def clean(choice, history):
267
+ if not history:
268
+ return (
269
+ None,
270
+ gr.Button.update(value="你好,Bing。你可以帮我做什么?", visible=True),
271
+ gr.Button.update(value="你好,Bing。请随便写一首诗。", visible=True),
272
+ gr.Button.update(value="你好,Bing。帮我搜索最近的新闻。", visible=True),
273
+ )
274
+ bot_login(choice)
275
+ return (
276
+ [[None, "好的,让我们忘记刚刚聊过的,然后重新开始。"]],
277
+ gr.Button.update(value="你好,Bing。你可以帮我做什么?", visible=True),
278
+ gr.Button.update(value="你好,Bing。请随便写一首诗。", visible=True),
279
+ gr.Button.update(value="你好,Bing。帮我搜索最近的新闻。", visible=True),
280
+ )
281
+
282
+ # 将清除按钮绑定到 clear.click() 方法上
283
+ clear.click(
284
+ fn=clean, inputs=[chat_style, chatbot], outputs=[chatbot, question1, question2, question3]
285
+ )
286
+
287
+ if __name__ == "__main__":
288
+ # demo.queue(concurrency_count=9)
289
+ demo.title = "Bing本地服务"
290
+ demo.launch(server_name="0.0.0.0", server_port=5000)
preview.png ADDED