POLRAMBORA commited on
Commit
ae68c7f
·
verified ·
1 Parent(s): 0646e2a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -45
app.py CHANGED
@@ -10,47 +10,59 @@ API_URL = "https://host.palple.polrambora.com/pmsq"
10
 
11
  sessions = {}
12
  PRIMARY_SYSTEM_INSTRUCTIONS = "You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations"
13
- ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png"
14
  USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png"
15
-
16
  def render_avatars(userid):
17
  try:
18
  response = requests.post(
19
  'https://host.palple.polrambora.com/userexistence',
20
- json={'userid': userid},
 
 
21
  timeout=10
22
  )
 
23
  if response.status_code == 200:
24
  response_json = response.json()
25
  return response_json["avatar"]["link"]
26
- except Exception:
 
 
27
  return None
28
 
 
29
  def authorize(user, api_key, system_message):
30
- test_data = {"user": user, "key": api_key}
 
 
 
 
31
  try:
32
  response = requests.post(
33
  "https://host.palple.polrambora.com/check_key_impv",
34
  json=test_data,
35
  )
 
36
  if response.status_code == 200:
 
37
  avatar = render_avatars(user) or USER_PIC_PATH
 
38
  if api_key not in sessions:
39
  sessions[api_key] = {
40
- "history": [],
41
- "headers": {
42
  "authorization": api_key,
43
  "Content-Type": 'application/json'
44
  },
45
  "avatar": avatar,
46
- "system_message": system_message
47
  }
48
  return True
49
  elif response.status_code == 403:
50
  return 403
51
  else:
52
  return False
53
- except Exception:
54
  return False
55
 
56
  def respond(message, api_key, max_tokens, top_p, temperature):
@@ -59,6 +71,7 @@ def respond(message, api_key, max_tokens, top_p, temperature):
59
  headers = session.get("headers", {})
60
  system_message = session.get("system_message", PRIMARY_SYSTEM_INSTRUCTIONS)
61
  messages = []
 
62
  for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history:
63
  if user_message:
64
  messages.append({
@@ -80,21 +93,38 @@ def respond(message, api_key, max_tokens, top_p, temperature):
80
  "max_char": max_tokens,
81
  "temperature": temperature,
82
  "top_p": top_p,
83
- "system_message": system_message
 
84
  },
85
  "conversation_history": messages,
86
  "input": message
87
  }
88
 
89
- with requests.post(API_URL, headers=headers, data=json.dumps(data), stream=True) as response:
 
 
90
  if response.status_code == 200:
91
- response_json = response.json()
92
- assistant_reply = response_json["msq"]["message"][0]
 
 
 
 
 
 
 
 
 
 
93
  history.append((message, assistant_reply, "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH))
94
  sessions[api_key]["history"] = history
95
- return history, assistant_reply
96
  else:
97
- return history, "Error: " + response.json().get("error", "Unknown error occurred.")
 
 
 
 
 
98
 
99
  def render_message(history):
100
  messages_html = """
@@ -122,12 +152,6 @@ def render_message(history):
122
 
123
  return messages_html
124
 
125
- def user_interaction(message, history, api_key, max_tokens, top_p, temperature):
126
- loading_message = history + [(message, "Loading...", "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH)]
127
- yield render_message(loading_message), loading_message, ""
128
- history, assistant_reply = respond(message, api_key, max_tokens, top_p, temperature)
129
- yield render_message(history), history, ""
130
-
131
  def escape_html(unsafe_text):
132
  return (
133
  unsafe_text.replace("&", "&")
@@ -137,11 +161,12 @@ def escape_html(unsafe_text):
137
  .replace("'", "'")
138
  )
139
 
140
- css = """
141
  .chatbox {height: 400px; overflow: auto; border: 1px solid #262626; padding: 10px; background-color: #171717; display: flex; flex-direction: column-reverse;}
142
  """
143
-
144
  with gr.Blocks(css=css) as demo:
 
 
145
  with gr.Column(visible=True) as auth_view:
146
  gr.Markdown("## P-MSQ Authorization")
147
  gr.Markdown("P-MSQ is in closed alpha test! The model, api and more are subject to change.")
@@ -151,43 +176,122 @@ with gr.Blocks(css=css) as demo:
151
  auth_status = gr.Textbox(label="Authorization Status", interactive=False)
152
 
153
  with gr.Column(visible=False) as chat_view:
 
 
 
 
 
154
  gr.Markdown("## P-MSQ Chat Interface")
155
  chatbot_output = gr.HTML(elem_id="chatbox-container")
156
- msg_input = gr.Text(show_label=False, placeholder="Type your message and press Shift+Enter...", lines=2)
 
 
 
 
 
 
 
157
  send_btn = gr.Button("Send")
158
  regen_btn = gr.Button("Clear")
159
- system_instructions_input = gr.Textbox(placeholder="Enter custom instructions (optional)", label="Custom System Instructions", lines=2)
160
- save_instructions_btn = gr.Button("Save Instructions")
 
 
 
 
 
161
  max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
162
  top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P")
163
  temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature")
164
- history_state = gr.State([])
165
- last_message_state = gr.State("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  msg_input.submit(
168
- user_interaction,
169
- inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
170
  outputs=[chatbot_output, history_state, msg_input],
171
  )
 
172
  send_btn.click(
173
- user_interaction,
174
- inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
175
  outputs=[chatbot_output, history_state, msg_input],
176
  )
177
- regen_btn.click(lambda _: ("", []), outputs=[chatbot_output, history_state])
178
 
179
- auth_button.click(
180
- lambda user, key: ("Authorized" if authorize(user, key, PRIMARY_SYSTEM_INSTRUCTIONS) else "Authorization Failed"),
181
- inputs=[api_user_input, api_key_input],
182
- outputs=[auth_status],
183
- )
184
 
185
- save_instructions_btn.click(
186
- lambda key, instructions: ("", ""),
187
- inputs=[api_key_input, system_instructions_input],
188
- outputs=[auth_status],
189
- )
190
- demo.launch(show_api=False)
 
 
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  if __name__ == "__main__":
193
- demo.queue = False
 
10
 
11
  sessions = {}
12
  PRIMARY_SYSTEM_INSTRUCTIONS = "You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations"
13
+ ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png"
14
  USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png"
 
15
  def render_avatars(userid):
16
  try:
17
  response = requests.post(
18
  'https://host.palple.polrambora.com/userexistence',
19
+ json={
20
+ 'userid': userid
21
+ },
22
  timeout=10
23
  )
24
+
25
  if response.status_code == 200:
26
  response_json = response.json()
27
  return response_json["avatar"]["link"]
28
+ except Exception as e:
29
+ return None
30
+ except requests.exceptions.Timeout:
31
  return None
32
 
33
+
34
  def authorize(user, api_key, system_message):
35
+ test_data = {
36
+ "user": user,
37
+ "key": api_key
38
+ }
39
+
40
  try:
41
  response = requests.post(
42
  "https://host.palple.polrambora.com/check_key_impv",
43
  json=test_data,
44
  )
45
+
46
  if response.status_code == 200:
47
+ response_json = response.json()
48
  avatar = render_avatars(user) or USER_PIC_PATH
49
+
50
  if api_key not in sessions:
51
  sessions[api_key] = {
52
+ "history": [],
53
+ "headers": {
54
  "authorization": api_key,
55
  "Content-Type": 'application/json'
56
  },
57
  "avatar": avatar,
58
+ "system_message": system_message
59
  }
60
  return True
61
  elif response.status_code == 403:
62
  return 403
63
  else:
64
  return False
65
+ except Exception as e:
66
  return False
67
 
68
  def respond(message, api_key, max_tokens, top_p, temperature):
 
71
  headers = session.get("headers", {})
72
  system_message = session.get("system_message", PRIMARY_SYSTEM_INSTRUCTIONS)
73
  messages = []
74
+
75
  for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history:
76
  if user_message:
77
  messages.append({
 
93
  "max_char": max_tokens,
94
  "temperature": temperature,
95
  "top_p": top_p,
96
+ "system_message": system_message,
97
+ "stream": True
98
  },
99
  "conversation_history": messages,
100
  "input": message
101
  }
102
 
103
+ try:
104
+ response = requests.post(API_URL, headers=headers, data=json.dumps(data), stream=True)
105
+
106
  if response.status_code == 200:
107
+ assistant_reply = ""
108
+ for line in response.iter_lines(decode_unicode=True):
109
+ if line:
110
+ try:
111
+ chunk = json.loads(line)
112
+ chunk_message = chunk.get("chunk", {}).get("content", "")
113
+ assistant_reply += chunk_message
114
+
115
+ yield assistant_reply
116
+ except Exception as e:
117
+ print(f"Stream chunk error: {e}")
118
+
119
  history.append((message, assistant_reply, "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH))
120
  sessions[api_key]["history"] = history
 
121
  else:
122
+ yield f"Error: {response.status_code} - {response.text}"
123
+ except Exception as e:
124
+ yield f"Error: {str(e)}"
125
+
126
+
127
+
128
 
129
  def render_message(history):
130
  messages_html = """
 
152
 
153
  return messages_html
154
 
 
 
 
 
 
 
155
  def escape_html(unsafe_text):
156
  return (
157
  unsafe_text.replace("&", "&")
 
161
  .replace("'", "'")
162
  )
163
 
164
+ css="""
165
  .chatbox {height: 400px; overflow: auto; border: 1px solid #262626; padding: 10px; background-color: #171717; display: flex; flex-direction: column-reverse;}
166
  """
 
167
  with gr.Blocks(css=css) as demo:
168
+
169
+
170
  with gr.Column(visible=True) as auth_view:
171
  gr.Markdown("## P-MSQ Authorization")
172
  gr.Markdown("P-MSQ is in closed alpha test! The model, api and more are subject to change.")
 
176
  auth_status = gr.Textbox(label="Authorization Status", interactive=False)
177
 
178
  with gr.Column(visible=False) as chat_view:
179
+ gr.HTML("""
180
+ <script type="text/javascript" id="MathJax-script" async
181
+ src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js">
182
+ </script>
183
+ """)
184
  gr.Markdown("## P-MSQ Chat Interface")
185
  chatbot_output = gr.HTML(elem_id="chatbox-container")
186
+ gr.Markdown(elem_id="chatbox-container")
187
+ msg_input = gr.Text(
188
+ show_label=False,
189
+ placeholder="Type your message and press Shift+Enter...",
190
+ lines=2,
191
+ elem_id="input-text"
192
+ )
193
+
194
  send_btn = gr.Button("Send")
195
  regen_btn = gr.Button("Clear")
196
+
197
+ system_instructions_input = gr.Textbox(placeholder="Enter custom instructions (optional)",
198
+ label="Custom System Instructions",
199
+ lines=2)
200
+ save_instructions_btn = gr.Button("Save Instructions")
201
+ gr.Markdown("### Settings")
202
+
203
  max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
204
  top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P")
205
  temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature")
206
+
207
+ history_state = gr.State([])
208
+ last_message_state = gr.State("")
209
+
210
+ def user_interaction(message, history, api_key, max_tokens, top_p, temperature):
211
+ loading_message = history + [(message, "Loading...", "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH)]
212
+ yield render_message(loading_message), loading_message, ""
213
+
214
+ assistant_reply = ""
215
+ for partial_reply in respond(message, api_key, max_tokens, top_p, temperature):
216
+ partial_history = history + [(message, partial_reply, "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH)]
217
+ yield render_message(partial_history), partial_history, ""
218
+
219
+ history, assistant_reply = partial_history, partial_reply
220
+ yield render_message(history), history, ""
221
+
222
+ def regenerate_response(history, last_message, max_tokens, top_p, temperature):
223
+ return "", []
224
+
225
+ def clear_history(api_key):
226
+ if api_key in sessions:
227
+ sessions[api_key]["history"] = []
228
+ return "", []
229
+
230
+ def load_conversation(api_key):
231
+ session = sessions.get(api_key, {})
232
+ history = session.get("history", [])
233
+ return render_message(history), history
234
 
235
  msg_input.submit(
236
+ user_interaction,
237
+ inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
238
  outputs=[chatbot_output, history_state, msg_input],
239
  )
240
+
241
  send_btn.click(
242
+ user_interaction,
243
+ inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
244
  outputs=[chatbot_output, history_state, msg_input],
245
  )
 
246
 
247
+ regen_btn.click(clear_history,
248
+ inputs=[api_key_input],
249
+ outputs=[chatbot_output, history_state])
 
 
250
 
251
+ with gr.Column(visible=False) as blacklist_view:
252
+ gr.Markdown("## P-MSQ Authorization")
253
+ gr.Markdown("Your linked ID appears to be blacklisted, and your API Key is pending on removal, if you believe this is a mistake, please try reaching us out.")
254
+
255
+
256
+ def authorize_and_proceed(user, api_key):
257
+ if authorize(user, api_key, PRIMARY_SYSTEM_INSTRUCTIONS):
258
+ gr.Info("Loading, please wait.")
259
+ messages_html, history = load_conversation(api_key)
260
 
261
+ return (
262
+ gr.update(visible=False),
263
+ gr.update(visible=True),
264
+ messages_html,
265
+ history
266
+ )
267
+ elif authorize(user, api_key, PRIMARY_SYSTEM_INSTRUCTIONS) == 403:
268
+ return (
269
+ gr.update(visible=False),
270
+ gr.update(visible=False),
271
+ gr.update(visible=True),
272
+ )
273
+ else:
274
+ gr.Warning("Incorrect userid/token")
275
+ return (
276
+ gr.update(visible=True),
277
+ gr.update(visible=False),
278
+ auth_status.update(value="Invalid userid/token")
279
+ )
280
+
281
+ def save_custom_instructions(api_key, custom_instructions):
282
+ if api_key in sessions:
283
+ gr.Info("Instructions updated, we recommend to start the new conversation to make it more efficient.")
284
+ sessions[api_key]["system_message"] = custom_instructions
285
+ return "Instructions updated!", gr.update(value="")
286
+ else:
287
+ gr.Warning("Your session has been expired, please refresh the page and login again.")
288
+ return "Session not found.", gr.update(value="")
289
+
290
+
291
+
292
+
293
+ auth_button.click(authorize_and_proceed, inputs=[api_user_input, api_key_input], outputs=[auth_view, chat_view, chatbot_output, history_state])
294
+ save_instructions_btn.click(save_custom_instructions, inputs=[api_key_input, system_instructions_input], outputs=auth_status)
295
+ demo.launch(show_api=False)
296
  if __name__ == "__main__":
297
+ demo.queue = False