Pearx commited on
Commit
e0999af
·
1 Parent(s): 609d6b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -136
app.py CHANGED
@@ -4,56 +4,14 @@ import uuid
4
  import copy
5
  import pandas as pd
6
  import openai
7
- import re
8
  from requests.models import ChunkedEncodingError
 
 
9
 
10
  st.set_page_config(page_title='ChatGPT Assistant', layout='wide', page_icon='🤖')
11
-
12
  # 自定义元素样式
13
- # 第一个是减少侧边栏顶部空白,不同版本的st存在区别(此处适用1.19.0)
14
- st.markdown("""
15
- <style>
16
- div.css-da9rnt.e1fqkh3o4 {
17
- padding-top: 1.5rem !important;
18
- }
19
- .avatar {
20
- display: flex;
21
- align-items: center;
22
- gap: 10px;
23
- pointer-events: none;
24
- margin:10px;
25
- }
26
- .avatar svg {
27
- width: 30px;
28
- height: 30px;
29
- }
30
- .avatar h2 {
31
- font-size: 20px;
32
- margin: 0px;
33
- }
34
 
35
- .content-div {
36
- padding: 5px 20px;
37
- margin: 5px;
38
- text-align: left;
39
- border-radius: 10px;
40
- border: none;
41
- line-height: 1.6;
42
- font-size:17px;
43
- }
44
- .content-div p{
45
- padding: 4px;
46
- margin : 2px;
47
- }
48
- #chat-window{
49
- padding: 10px 0px;
50
- text-decoration: none;
51
- }
52
- #chat-window:hover{
53
- color: blue;
54
- }
55
- </style>
56
- """, unsafe_allow_html=True)
57
  if "initial_settings" not in st.session_state:
58
  # 历史聊天窗口
59
  st.session_state["path"] = set_chats_path()
@@ -62,8 +20,8 @@ if "initial_settings" not in st.session_state:
62
  st.session_state['pre_chat'] = None
63
  st.session_state['if_chat_change'] = False
64
  st.session_state['error_info'] = ''
65
- st.session_state['user_input_content'] = ''
66
  st.session_state["current_chat_index"] = 0
 
67
  # 设置完成
68
  st.session_state["initial_settings"] = True
69
 
@@ -83,13 +41,16 @@ with st.sidebar:
83
  st.session_state['if_chat_change'] = True
84
  st.write("---")
85
 
 
86
 
87
- def create_chat_button_callback():
 
88
  st.session_state['history_chats'] = ['New Chat_' + str(uuid.uuid4())] + st.session_state['history_chats']
89
  st.session_state["current_chat_index"] = 0
 
90
 
91
-
92
- def delete_chat_button_callback():
93
  if len(st.session_state['history_chats']) == 1:
94
  chat_init = 'New Chat_' + str(uuid.uuid4())
95
  st.session_state['history_chats'].append(chat_init)
@@ -101,20 +62,17 @@ with st.sidebar:
101
  st.session_state["current_chat_index"] = 0
102
  st.session_state['history_chats'].remove(current_chat)
103
  remove_data(st.session_state["path"], current_chat)
104
-
105
-
106
- c1, c2 = st.columns(2)
107
- create_chat_button = c1.button('新建', use_container_width=True, key='create_chat_button',
108
- on_click=create_chat_button_callback)
109
- delete_chat_button = c2.button('删除', use_container_width=True, key='delete_chat_button',
110
- on_click=delete_chat_button_callback)
111
-
112
- st.write("\n")
113
- st.write("\n")
114
- # 此处href与下文的st.header内容相对应,跳转锚点
115
- st.markdown("<a href='#chatgpt-assistant' id='chat-window'>➡️ 直达输入区</a>",unsafe_allow_html=True)
116
-
117
-
118
  # 加载数据
119
  if ("history" + current_chat not in st.session_state) or (st.session_state['if_chat_change']):
120
  for key, value in load_data(st.session_state["path"], current_chat).items():
@@ -127,27 +85,29 @@ if ("history" + current_chat not in st.session_state) or (st.session_state['if_c
127
 
128
 
129
  # 一键复制按钮
130
- st.markdown('<center><a href="https://huggingface.co/spaces/Pearx/ChatGPT-Assistant?duplicate=true">'
131
- '<img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><center>', unsafe_allow_html=True)
132
  # 对话展示
133
  show_messages(st.session_state["history" + current_chat])
134
 
135
 
136
  # 数据写入文件
137
  def write_data(new_chat_name=current_chat):
138
- st.session_state["paras"] = {
139
- "temperature": st.session_state["temperature" + current_chat],
140
- "top_p": st.session_state["top_p" + current_chat],
141
- "presence_penalty": st.session_state["presence_penalty" + current_chat],
142
- "frequency_penalty": st.session_state["frequency_penalty" + current_chat],
143
- }
144
- st.session_state["contexts"] = {
145
- "context_select": st.session_state["context_select" + current_chat],
146
- "context_input": st.session_state["context_input" + current_chat],
147
- "context_level": st.session_state["context_level" + current_chat],
148
- }
149
- save_data(st.session_state["path"], new_chat_name, st.session_state["history" + current_chat],
150
- st.session_state["paras"], st.session_state["contexts"])
 
 
151
 
152
 
153
  # 输入内容展示
@@ -159,7 +119,6 @@ area_gpt_content = st.empty()
159
  # 报错展示
160
  area_error = st.empty()
161
 
162
- st.write("\n")
163
  st.header('ChatGPT Assistant')
164
  tap_input, tap_context, tap_set = st.tabs(['💬 聊天', '🗒️ 预设', '⚙️ 设置'])
165
 
@@ -169,23 +128,27 @@ with tap_context:
169
  st.selectbox(label='选择上下文', options=set_context_list, key='context_select' + current_chat,
170
  index=context_select_index, on_change=write_data)
171
  st.caption(set_context_all[st.session_state['context_select' + current_chat]])
172
- st.text_area(label='补充或自定义上下文:', key="context_input" + current_chat,
173
- value=st.session_state['context_input' + current_chat + "default"],
174
- on_change=write_data)
 
175
 
176
  with tap_set:
177
  def clear_button_callback():
178
  st.session_state['history' + current_chat] = copy.deepcopy(initial_content_history)
179
  write_data()
180
 
 
181
  st.button("清空聊天记录", use_container_width=True, on_click=clear_button_callback)
182
 
183
  st.markdown("OpenAI API Key (可选)")
184
  st.text_input("OpenAI API Key (可选)", type='password', key='apikey_input', label_visibility='collapsed')
185
- st.caption("此Key仅在当前网页有效,且优先级高于Secrets中的配置,仅自己可用,他人无法共享。[官网获取](https://platform.openai.com/account/api-keys)")
 
186
 
187
  st.markdown("包含对话次数:")
188
- st.slider("Context Level", 0, 10, st.session_state['context_level' + current_chat + "default"], 1, on_change=write_data,
 
189
  key='context_level' + current_chat, help="表示每次会话中包含的历史对话次数,预设内容不计算在内。")
190
 
191
  st.markdown("模型参数:")
@@ -208,57 +171,34 @@ with tap_set:
208
  st.caption("[官网参数说明](https://platform.openai.com/docs/api-reference/completions/create)")
209
 
210
  with tap_input:
211
- def get_history_input(history, level):
212
- df_history = pd.DataFrame(history)
213
- df_system = df_history.query('role=="system"')
214
- df_input = df_history.query('role!="system"')
215
- df_input = df_input[-level * 2:]
216
- res = pd.concat([df_system, df_input], ignore_index=True).to_dict('records')
217
- return res
218
-
219
-
220
- def remove_hashtag_space(text):
221
- res = re.sub(r"(#+)\s*", r"\1", text)
222
- return res
223
-
224
-
225
- def extract_chars(text, num):
226
- char_num = 0
227
- chars = ''
228
- for char in text:
229
- # 汉字算两个字符
230
- if '\u4e00' <= char <= '\u9fff':
231
- char_num += 2
232
- else:
233
- char_num += 1
234
- chars += char
235
- if char_num >= num:
236
- break
237
- return chars
238
-
239
-
240
- def user_input_area_callback():
241
- # 清空输入框
242
- st.session_state['user_input_content'] = (remove_hashtag_space(st.session_state['user_input_area'])
243
- .replace('\n', '\n\n'))
244
- st.session_state['user_input_area'] = ''
245
-
246
- # 修改窗口名称
247
- user_input_content = st.session_state['user_input_content']
248
- df_history = pd.DataFrame(st.session_state["history" + current_chat])
249
- if len(df_history.query('role!="system"')) == 0:
250
- remove_data(st.session_state["path"], current_chat)
251
- current_chat_index = st.session_state['history_chats'].index(current_chat)
252
- new_name = extract_chars(user_input_content, 18) + '_' + str(uuid.uuid4())
253
- st.session_state['history_chats'][current_chat_index] = new_name
254
- st.session_state["current_chat_index"] = current_chat_index
255
- # 写入新文件
256
- write_data(new_name)
257
-
258
-
259
- st.text_area("**输入:**", key="user_input_area", on_change=user_input_area_callback)
260
- if st.session_state['user_input_content'].strip() != '':
261
- st.session_state['pre_user_input_content'] = st.session_state['user_input_content']
262
  st.session_state['user_input_content'] = ''
263
  show_each_message(st.session_state['pre_user_input_content'], 'user',
264
  [area_user_svg.markdown, area_user_content.markdown])
@@ -328,4 +268,7 @@ if ("r" in st.session_state) and (current_chat == st.session_state["chat_of_r"])
328
  if current_chat + 'report' in st.session_state:
329
  st.session_state.pop(current_chat + 'report')
330
  if 'r' in st.session_state:
331
- st.session_state.pop("r")
 
 
 
 
4
  import copy
5
  import pandas as pd
6
  import openai
 
7
  from requests.models import ChunkedEncodingError
8
+ from streamlit.components import v1
9
+ from custom import css_code, js_code, set_context_all
10
 
11
  st.set_page_config(page_title='ChatGPT Assistant', layout='wide', page_icon='🤖')
 
12
  # 自定义元素样式
13
+ st.markdown(css_code, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  if "initial_settings" not in st.session_state:
16
  # 历史聊天窗口
17
  st.session_state["path"] = set_chats_path()
 
20
  st.session_state['pre_chat'] = None
21
  st.session_state['if_chat_change'] = False
22
  st.session_state['error_info'] = ''
 
23
  st.session_state["current_chat_index"] = 0
24
+ st.session_state['user_input_content'] = ''
25
  # 设置完成
26
  st.session_state["initial_settings"] = True
27
 
 
41
  st.session_state['if_chat_change'] = True
42
  st.write("---")
43
 
44
+ c1, c2 = st.columns(2)
45
 
46
+ create_chat_button = c1.button('新建', use_container_width=True, key='create_chat_button')
47
+ if create_chat_button:
48
  st.session_state['history_chats'] = ['New Chat_' + str(uuid.uuid4())] + st.session_state['history_chats']
49
  st.session_state["current_chat_index"] = 0
50
+ st.experimental_rerun()
51
 
52
+ delete_chat_button = c2.button('删除', use_container_width=True, key='delete_chat_button')
53
+ if delete_chat_button:
54
  if len(st.session_state['history_chats']) == 1:
55
  chat_init = 'New Chat_' + str(uuid.uuid4())
56
  st.session_state['history_chats'].append(chat_init)
 
62
  st.session_state["current_chat_index"] = 0
63
  st.session_state['history_chats'].remove(current_chat)
64
  remove_data(st.session_state["path"], current_chat)
65
+ st.experimental_rerun()
66
+
67
+ for i in range(5):
68
+ st.write("\n")
69
+ st.caption("""
70
+ - 双击页面可直接定位输入栏
71
+ - Ctrl + Enter 可快捷提交问题
72
+ """)
73
+ st.markdown('<a href="https://github.com/PierXuY/ChatGPT-Assistant" target="_blank" rel="ChatGPT-Assistant">'
74
+ '<img src="https://badgen.net/badge/icon/GitHub?icon=github&amp;label=ChatGPT Assistant" alt="GitHub">'
75
+ '</a>', unsafe_allow_html=True)
 
 
 
76
  # 加载数据
77
  if ("history" + current_chat not in st.session_state) or (st.session_state['if_chat_change']):
78
  for key, value in load_data(st.session_state["path"], current_chat).items():
 
85
 
86
 
87
  # 一键复制按钮
88
+ st.markdown('<center>< a href="https://huggingface.co/spaces/Pearx/ChatGPT-Assistant?duplicate=true">'
89
+ '<img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></ a><center>', unsafe_allow_html=True)
90
  # 对话展示
91
  show_messages(st.session_state["history" + current_chat])
92
 
93
 
94
  # 数据写入文件
95
  def write_data(new_chat_name=current_chat):
96
+ # 防止高频创建时组件尚未渲染完成,不影响正常写入
97
+ if "frequency_penalty" + current_chat in st.session_state:
98
+ st.session_state["paras"] = {
99
+ "temperature": st.session_state["temperature" + current_chat],
100
+ "top_p": st.session_state["top_p" + current_chat],
101
+ "presence_penalty": st.session_state["presence_penalty" + current_chat],
102
+ "frequency_penalty": st.session_state["frequency_penalty" + current_chat],
103
+ }
104
+ st.session_state["contexts"] = {
105
+ "context_select": st.session_state["context_select" + current_chat],
106
+ "context_input": st.session_state["context_input" + current_chat],
107
+ "context_level": st.session_state["context_level" + current_chat],
108
+ }
109
+ save_data(st.session_state["path"], new_chat_name, st.session_state["history" + current_chat],
110
+ st.session_state["paras"], st.session_state["contexts"])
111
 
112
 
113
  # 输入内容展示
 
119
  # 报错展示
120
  area_error = st.empty()
121
 
 
122
  st.header('ChatGPT Assistant')
123
  tap_input, tap_context, tap_set = st.tabs(['💬 聊天', '🗒️ 预设', '⚙️ 设置'])
124
 
 
128
  st.selectbox(label='选择上下文', options=set_context_list, key='context_select' + current_chat,
129
  index=context_select_index, on_change=write_data)
130
  st.caption(set_context_all[st.session_state['context_select' + current_chat]])
131
+ context_input = st.text_area(label='补充或自定义上下文:', key="context_input" + current_chat,
132
+ value=st.session_state['context_input' + current_chat + "default"],
133
+ on_change=write_data)
134
+ st.caption(context_input)
135
 
136
  with tap_set:
137
  def clear_button_callback():
138
  st.session_state['history' + current_chat] = copy.deepcopy(initial_content_history)
139
  write_data()
140
 
141
+
142
  st.button("清空聊天记录", use_container_width=True, on_click=clear_button_callback)
143
 
144
  st.markdown("OpenAI API Key (可选)")
145
  st.text_input("OpenAI API Key (可选)", type='password', key='apikey_input', label_visibility='collapsed')
146
+ st.caption(
147
+ "此Key仅在当前网页有效,且优先级高于Secrets中的配置,仅自己可用,他人无法共享。[官网获取](https://platform.openai.com/account/api-keys)")
148
 
149
  st.markdown("包含对话次数:")
150
+ st.slider("Context Level", 0, 10, st.session_state['context_level' + current_chat + "default"], 1,
151
+ on_change=write_data,
152
  key='context_level' + current_chat, help="表示每次会话中包含的历史对话次数,预设内容不计算在内。")
153
 
154
  st.markdown("模型参数:")
 
171
  st.caption("[官网参数说明](https://platform.openai.com/docs/api-reference/completions/create)")
172
 
173
  with tap_input:
174
+ def input_callback():
175
+ if st.session_state['user_input_area'] != "":
176
+ # 修改窗口名称
177
+ user_input_content = st.session_state['user_input_area']
178
+ df_history = pd.DataFrame(st.session_state["history" + current_chat])
179
+ if len(df_history.query('role!="system"')) == 0:
180
+ remove_data(st.session_state["path"], current_chat)
181
+ current_chat_index = st.session_state['history_chats'].index(current_chat)
182
+ new_name = extract_chars(user_input_content, 18) + '_' + str(uuid.uuid4())
183
+ st.session_state['history_chats'][current_chat_index] = new_name
184
+ st.session_state["current_chat_index"] = current_chat_index
185
+ # 写入新文件
186
+ write_data(new_name)
187
+
188
+
189
+
190
+ with st.form("input_form", clear_on_submit=True):
191
+ user_input = st.text_area("**输入:**", key="user_input_area")
192
+ submitted = st.form_submit_button("确认提交", use_container_width=True, on_click=input_callback)
193
+ if submitted:
194
+ st.session_state['user_input_content'] = user_input
195
+
196
+ if st.session_state['user_input_content'] != '':
197
+ if 'r' in st.session_state:
198
+ st.session_state.pop("r")
199
+ st.session_state[current_chat + 'report'] = ""
200
+ st.session_state['pre_user_input_content'] = (remove_hashtag_right__space(st.session_state['user_input_content']
201
+ .replace('\n', '\n\n')))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  st.session_state['user_input_content'] = ''
203
  show_each_message(st.session_state['pre_user_input_content'], 'user',
204
  [area_user_svg.markdown, area_user_content.markdown])
 
268
  if current_chat + 'report' in st.session_state:
269
  st.session_state.pop(current_chat + 'report')
270
  if 'r' in st.session_state:
271
+ st.session_state.pop("r")
272
+
273
+ # 添加事件监听
274
+ v1.html(js_code, height=0)