Nyanfa commited on
Commit
ad5eacd
·
verified ·
1 Parent(s): af771fa

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +367 -0
app.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import streamlit as st
3
+ from streamlit.components.v1 import html
4
+ from streamlit_extras.stylable_container import stylable_container
5
+ import re
6
+ import urllib.parse
7
+ import traceback
8
+ import tiktoken
9
+
10
+ st.title("Nvidia Chat UI")
11
+
12
+ if "api_key" not in st.session_state:
13
+ api_key = st.text_input("Enter your API Key", type="password")
14
+ if api_key:
15
+ if api_key.isascii():
16
+ st.session_state.api_key = api_key
17
+ client = openai.OpenAI(base_url = "https://integrate.api.nvidia.com/v1",
18
+ api_key=api_key)
19
+ st.rerun()
20
+ else:
21
+ st.warning("Please enter your API key correctly.")
22
+ st.stop()
23
+ else:
24
+ st.warning("Please enter your API key to use the app. You can obtain your API key from here: https://build.nvidia.com/nvidia/nemotron-4-340b-instruct")
25
+ st.stop()
26
+ else:
27
+ client = openai.OpenAI(base_url = "https://integrate.api.nvidia.com/v1",
28
+ api_key=st.session_state.api_key)
29
+
30
+ if "messages" not in st.session_state:
31
+ st.session_state.messages = []
32
+
33
+ encoding = tiktoken.get_encoding("cl100k_base")
34
+
35
+ def num_tokens_from_string(string):
36
+ num_tokens = len(encoding.encode(string))
37
+ return num_tokens
38
+
39
+ def get_ai_response(prompt, chat_history):
40
+ st.session_state.is_streaming = True
41
+ st.session_state.response = ""
42
+
43
+ chat_history.insert(0, {"role": "system", "content": system_prompt})
44
+ chat_history.append({"role": "user", "content": prompt})
45
+
46
+ system_tokens = num_tokens_from_string(system_message["content"])
47
+ user_tokens = num_tokens_from_string(user_message["content"])
48
+
49
+ # Maximum allowed tokens
50
+ context_length = 4096 - max_tokens
51
+ available_tokens = context_length - system_tokens - user_tokens
52
+
53
+ # Trim chat history if necessary
54
+ trimmed_history = []
55
+ total_tokens = 0
56
+
57
+ for message in reversed(chat_history):
58
+ message_tokens = num_tokens_from_string(message["content"])
59
+ if total_tokens + message_tokens <= available_tokens:
60
+ trimmed_history.insert(0, message)
61
+ total_tokens += message_tokens
62
+ else:
63
+ break
64
+
65
+ # Construct final message list
66
+ final_messages = [system_message] + trimmed_history + [user_message]
67
+
68
+ try:
69
+ with st.chat_message("assistant", avatar=st.session_state.assistant_avatar):
70
+ stream = client.chat.completions.create(
71
+ model=model,
72
+ messages=chat_history,
73
+ temperature=temperature,
74
+ top_p=top_p,
75
+ max_tokens=max_tokens,
76
+ stream=True,
77
+ )
78
+
79
+ placeholder = st.empty()
80
+
81
+ with stylable_container(
82
+ key="stop_generating",
83
+ css_styles="""
84
+ button {
85
+ position: fixed;
86
+ bottom: 100px;
87
+ left: 50%;
88
+ transform: translateX(-50%);
89
+ z-index: 1;
90
+ }
91
+ """,
92
+ ):
93
+ st.button("Stop generating")
94
+
95
+ shown_message = ""
96
+
97
+ for chunk in stream:
98
+ if chunk.choices[0].delta.content is not None:
99
+ content = chunk.choices[0].delta.content
100
+ st.session_state.response += content
101
+ shown_message += content.replace("\n", " \n")\
102
+ .replace("<", "\\<")\
103
+ .replace(">", "\\>")
104
+ placeholder.markdown(shown_message)
105
+
106
+ except:
107
+ st.session_state.response += "\n!Exception\n" + traceback.format_exc()
108
+
109
+ st.session_state.is_streaming = False
110
+ return st.session_state.response
111
+
112
+ def normalize_code_block(match):
113
+ return match.group(0).replace(" \n", "\n")\
114
+ .replace("\\<", "<")\
115
+ .replace("\\>", ">")
116
+
117
+ def normalize_inline(match):
118
+ return match.group(0).replace("\\<", "<")\
119
+ .replace("\\>", ">")
120
+
121
+ code_block_pattern = r"(```.*?```)"
122
+ inline_pattern = r"`([^`\n]+?)`"
123
+
124
+ def display_messages():
125
+ for i, message in enumerate(st.session_state.messages):
126
+ avatar = st.session_state.user_avatar if message["role"] == "user" else st.session_state.assistant_avatar
127
+ with st.chat_message(message["role"], avatar=avatar):
128
+ shown_message = message["content"].replace("\n", " \n")\
129
+ .replace("<", "\\<")\
130
+ .replace(">", "\\>")
131
+ if "```" in shown_message:
132
+ # Replace " \n" with "\n" within code blocks
133
+ shown_message = re.sub(code_block_pattern, normalize_code_block, shown_message, flags=re.DOTALL)
134
+ if "`" in shown_message:
135
+ shown_message = re.sub(inline_pattern, normalize_inline, shown_message)
136
+ st.markdown(shown_message)
137
+
138
+ col1, col2, col3, col4 = st.columns([1, 1, 1, 1])
139
+ with col1:
140
+ if st.button("Edit", key=f"edit_{i}_{len(st.session_state.messages)}"):
141
+ st.session_state.edit_index = i
142
+ st.rerun()
143
+ with col2:
144
+ if st.session_state.is_delete_mode and st.button("Delete", key=f"delete_{i}_{len(st.session_state.messages)}"):
145
+ del st.session_state.messages[i]
146
+ st.rerun()
147
+ with col3:
148
+ text_to_copy = message["content"]
149
+ # Encode the string to escape
150
+ text_to_copy_escaped = urllib.parse.quote(text_to_copy)
151
+
152
+ copy_button_html = f"""
153
+ <button id="copy-msg-btn-{i}" style='font-size: 1em; padding: 0.5em;' onclick='copyMessage("{i}")'>Copy</button>
154
+
155
+ <script>
156
+ function copyMessage(index) {{
157
+ navigator.clipboard.writeText(decodeURIComponent("{text_to_copy_escaped}"));
158
+ let copyBtn = document.getElementById("copy-msg-btn-" + index);
159
+ copyBtn.innerHTML = "Copied!";
160
+ setTimeout(function(){{ copyBtn.innerHTML = "Copy"; }}, 2000);
161
+ }}
162
+ </script>
163
+ """
164
+ html(copy_button_html, height=50)
165
+
166
+ if i == len(st.session_state.messages) - 1 and message["role"] == "CHATBOT":
167
+ with col4:
168
+ if st.button("Retry", key=f"retry_{i}_{len(st.session_state.messages)}"):
169
+ if len(st.session_state.messages) >= 2:
170
+ del st.session_state.messages[-1]
171
+ st.session_state.retry_flag = True
172
+ st.rerun()
173
+
174
+ if "edit_index" in st.session_state and st.session_state.edit_index == i:
175
+ with st.form(key=f"edit_form_{i}_{len(st.session_state.messages)}"):
176
+ new_content = st.text_area("Edit message", height=200, value=st.session_state.messages[i]["content"])
177
+ col1, col2 = st.columns([1, 1])
178
+ with col1:
179
+ if st.form_submit_button("Save"):
180
+ st.session_state.messages[i]["content"] = new_content
181
+ del st.session_state.edit_index
182
+ st.rerun()
183
+ with col2:
184
+ if st.form_submit_button("Cancel"):
185
+ del st.session_state.edit_index
186
+ st.rerun()
187
+
188
+ # Add sidebar for advanced settings
189
+ with st.sidebar:
190
+ settings_tab, appearance_tab = st.tabs(["Settings", "Appearance"])
191
+
192
+ with settings_tab:
193
+ st.markdown("Help (Japanese): https://rentry.org/9hgneofz")
194
+
195
+ # Copy Conversation History button
196
+ log_text = ""
197
+ for message in st.session_state.messages:
198
+ if message["role"] == "user":
199
+ log_text += "<USER>\n"
200
+ log_text += message["content"] + "\n\n"
201
+ else:
202
+ log_text += "<ASSISTANT>\n"
203
+ log_text += message["content"] + "\n\n"
204
+ log_text = log_text.rstrip("\n")
205
+
206
+ # Encode the string to escape
207
+ log_text_escaped = urllib.parse.quote(log_text)
208
+
209
+ copy_log_button_html = f"""
210
+ <button id="copy-log-btn" style='font-size: 1em; padding: 0.5em;' onclick='copyLog()'>Copy Conversation History</button>
211
+
212
+ <script>
213
+ function copyLog() {{
214
+ navigator.clipboard.writeText(decodeURIComponent("{log_text_escaped}"));
215
+ let copyBtn = document.getElementById("copy-log-btn");
216
+ copyBtn.innerHTML = "Copied!";
217
+ setTimeout(function(){{ copyBtn.innerHTML = "Copy Conversation History"; }}, 2000);
218
+ }}
219
+ </script>
220
+ """
221
+ html(copy_log_button_html, height=50)
222
+
223
+ if st.session_state.get("is_history_shown") != True:
224
+ if st.button("Display History as Code Block"):
225
+ st.session_state.is_history_shown = True
226
+ st.rerun()
227
+ else:
228
+ if st.button("Hide History"):
229
+ st.session_state.is_history_shown = False
230
+ st.rerun()
231
+ st.code(log_text)
232
+
233
+ st.session_state.is_delete_mode = st.toggle("Enable Delete button")
234
+
235
+ st.header("Advanced Settings")
236
+ model = st.selectbox("Model", options=["nvidia/nemotron-4-340b-instruct"], index=0)
237
+ system_prompt = st.text_area("System Prompt", height=200)
238
+ temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.3, step=0.1)
239
+ top_p = st.slider("Top-P", min_value=0.01, max_value=1.00, value=1.00, step=0.01)
240
+ max_tokens = st.slider("Max Tokens (Output)", min_value=1, max_value=1024, value=1024, step=1)
241
+ st.header("Restore History")
242
+ history_input = st.text_area("Paste conversation history:", height=200)
243
+ if st.button("Restore History"):
244
+ st.session_state.messages = []
245
+ messages = re.split(r"^(<USER>|<ASSISTANT>)\n", history_input, flags=re.MULTILINE)
246
+ role = None
247
+ text = ""
248
+ for message in messages:
249
+ if message.strip() in ["<USER>", "<ASSISTANT>"]:
250
+ if role and text:
251
+ st.session_state.messages.append({"role": role, "content": text.strip()})
252
+ text = ""
253
+ role = "user" if message.strip() == "<USER>" else "assistant"
254
+ else:
255
+ text += message
256
+ if role and text:
257
+ st.session_state.messages.append({"role": role, "content": text.strip()})
258
+ st.rerun()
259
+
260
+ st.header("Clear History")
261
+ if st.button("Clear Chat History"):
262
+ st.session_state.messages = []
263
+ st.rerun()
264
+
265
+ st.header("Change API Key")
266
+ new_api_key = st.text_input("Enter new API Key", type="password")
267
+ if st.button("Update API Key"):
268
+ if new_api_key and new_api_key.isascii():
269
+ st.session_state.api_key = new_api_key
270
+ client = openai.OpenAI(api_key=new_api_key)
271
+ st.success("API Key updated successfully!")
272
+ else:
273
+ st.warning("Please enter a valid API Key.")
274
+
275
+ with appearance_tab:
276
+ st.header("Font Selection")
277
+ font_options = {
278
+ "Zen Maru Gothic": "Zen Maru Gothic",
279
+ "Noto Sans JP": "Noto Sans JP",
280
+ "Sawarabi Mincho": "Sawarabi Mincho"
281
+ }
282
+ selected_font = st.selectbox("Choose a font", ["Default"] + list(font_options.keys()))
283
+
284
+ st.header("Change the font size")
285
+ st.session_state.font_size = st.slider("Font size", min_value=16.0, max_value=50.0, value=16.0, step=1.0)
286
+
287
+ st.header("Change the user's icon")
288
+ st.session_state.user_avatar = st.file_uploader("Choose an image", type=["png", "jpg", "jpeg", "webp", "gif", "bmp", "svg",], key="user_avatar_uploader")
289
+
290
+ st.header("Change the assistant's icon")
291
+ st.session_state.assistant_avatar = st.file_uploader("Choose an image", type=["png", "jpg", "jpeg", "webp", "gif", "bmp", "svg",], key="assistant_avatar_uploader")
292
+
293
+ st.header("Change the icon size")
294
+ st.session_state.avatar_size = st.slider("Icon size", min_value=2.0, max_value=20.0, value=2.0, step=0.2)
295
+
296
+
297
+ # After Stop generating
298
+ if st.session_state.get("is_streaming"):
299
+ st.session_state.messages.append({"role": "assistant", "content": st.session_state.response})
300
+ st.session_state.is_streaming = False
301
+ if "retry_flag" in st.session_state and st.session_state.retry_flag:
302
+ st.session_state.retry_flag = False
303
+ st.rerun()
304
+
305
+ if selected_font != "Default":
306
+ with open("style.css") as css:
307
+ st.markdown(f'<style>{css.read()}</style>', unsafe_allow_html=True)
308
+ st.markdown(f'<style>body * {{ font-family: "{font_options[selected_font]}", serif !important; }}</style>', unsafe_allow_html=True)
309
+
310
+ # Change font size
311
+ st.markdown(f'<style>[data-testid="stChatMessageContent"] .st-emotion-cache-cnbvxy p{{font-size: {st.session_state.font_size}px;}}</style>', unsafe_allow_html=True)
312
+
313
+ # Change icon size
314
+ # (CSS element names may be subject to change.)
315
+ # (Contributor: ★31 >>538)
316
+ AVATAR_SIZE_STYLE = f"""
317
+ <style>
318
+ [data-testid="chatAvatarIcon-user"] {{
319
+ width: {st.session_state.avatar_size}rem;
320
+ height: {st.session_state.avatar_size}rem;
321
+ }}
322
+ [data-testid="chatAvatarIcon-assistant"] {{
323
+ width: {st.session_state.avatar_size}rem;
324
+ height: {st.session_state.avatar_size}rem;
325
+ }}
326
+ [data-testid="stChatMessage"] .st-emotion-cache-1pbsqtx {{
327
+ width: {st.session_state.avatar_size / 1.6}rem;
328
+ height: {st.session_state.avatar_size / 1.6}rem;
329
+ }}
330
+ [data-testid="stChatMessage"] .st-emotion-cache-p4micv {{
331
+ width: {st.session_state.avatar_size}rem;
332
+ height: {st.session_state.avatar_size}rem;
333
+ }}
334
+ </style>
335
+ """
336
+ st.markdown(AVATAR_SIZE_STYLE, unsafe_allow_html=True)
337
+
338
+ display_messages()
339
+
340
+ # After Retry
341
+ if st.session_state.get("retry_flag"):
342
+ if len(st.session_state.messages) > 0:
343
+ prompt = st.session_state.messages[-1]["content"]
344
+ messages = st.session_state.messages[:-1].copy()
345
+ response = get_ai_response(prompt, messages)
346
+ st.session_state.messages.append({"role": "assistant", "content": response})
347
+ st.session_state.retry_flag = False
348
+ st.rerun()
349
+ else:
350
+ st.session_state.retry_flag = False
351
+
352
+ if prompt := st.chat_input("Enter your message here..."):
353
+ chat_history = st.session_state.messages.copy()
354
+
355
+ shown_message = prompt.replace("\n", " \n")\
356
+ .replace("<", "\\<")\
357
+ .replace(">", "\\>")
358
+
359
+ with st.chat_message("user", avatar=st.session_state.user_avatar):
360
+ st.write(shown_message)
361
+
362
+ st.session_state.messages.append({"role": "user", "content": prompt})
363
+
364
+ response = get_ai_response(prompt, chat_history)
365
+
366
+ st.session_state.messages.append({"role": "assistant", "content": response})
367
+ st.rerun()