POLRAMBORA commited on
Commit
5dadbe6
·
verified ·
1 Parent(s): f89484d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -48
app.py CHANGED
@@ -10,7 +10,7 @@ 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):
@@ -25,8 +25,6 @@ def render_avatars(userid):
25
  return response_json["avatar"]["link"]
26
  except Exception:
27
  return None
28
- except requests.exceptions.Timeout:
29
- return None
30
 
31
  def authorize(user, api_key, system_message):
32
  test_data = {"user": user, "key": api_key}
@@ -36,17 +34,16 @@ def authorize(user, api_key, system_message):
36
  json=test_data,
37
  )
38
  if response.status_code == 200:
39
- response_json = response.json()
40
  avatar = render_avatars(user) or USER_PIC_PATH
41
  if api_key not in sessions:
42
  sessions[api_key] = {
43
- "history": [],
44
- "headers": {
45
  "authorization": api_key,
46
  "Content-Type": 'application/json'
47
  },
48
  "avatar": avatar,
49
- "system_message": system_message
50
  }
51
  return True
52
  elif response.status_code == 403:
@@ -89,18 +86,15 @@ def respond(message, api_key, max_tokens, top_p, temperature):
89
  "input": message
90
  }
91
 
92
- response = requests.post(API_URL, headers=headers, data=json.dumps(data), stream=True)
93
- if response.status_code == 200:
94
- assistant_reply = ""
95
- for chunk in response.iter_content(chunk_size=1024):
96
- if chunk:
97
- assistant_reply += chunk.decode()
98
- yield assistant_reply
99
- history.append((message, assistant_reply, "You", "P-ALPLE", sessions[api_key]["avatar"], ASSISTANT_PIC_PATH))
100
- sessions[api_key]["history"] = history
101
- yield history, assistant_reply
102
- else:
103
- yield history, "Error: " + response.json().get("error", "Unknown error occurred.")
104
 
105
  def render_message(history):
106
  messages_html = """
@@ -128,6 +122,12 @@ def render_message(history):
128
 
129
  return messages_html
130
 
 
 
 
 
 
 
131
  def escape_html(unsafe_text):
132
  return (
133
  unsafe_text.replace("&", "&")
@@ -144,56 +144,49 @@ css = """
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.")
148
  api_user_input = gr.Textbox(placeholder="snowflake", label="UserID", type='email')
149
  api_key_input = gr.Textbox(placeholder="Enter your API key", label="Token", type='password')
150
  auth_button = gr.Button("Authorize")
151
  auth_status = gr.Textbox(label="Authorization Status", interactive=False)
152
 
153
  with gr.Column(visible=False) as chat_view:
154
- gr.HTML("""
155
- <script type="text/javascript" id="MathJax-script" async
156
- src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js">
157
- </script>
158
- """)
159
  gr.Markdown("## P-MSQ Chat Interface")
160
  chatbot_output = gr.HTML(elem_id="chatbox-container")
161
- gr.Markdown(elem_id="chatbox-container")
162
- msg_input = gr.Text(
163
- show_label=False,
164
- placeholder="Type your message and press Shift+Enter...",
165
- lines=2,
166
- elem_id="input-text"
167
- )
168
  send_btn = gr.Button("Send")
169
  regen_btn = gr.Button("Clear")
170
- system_instructions_input = gr.Textbox(placeholder="Enter custom instructions (optional)",
171
- label="Custom System Instructions",
172
- lines=2)
173
- save_instructions_btn = gr.Button("Save Instructions")
174
- gr.Markdown("### Settings")
175
  max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
176
  top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P")
177
  temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature")
178
-
179
- history_state = gr.State([])
180
- last_message_state = gr.State("")
181
 
182
  msg_input.submit(
183
- respond,
184
- inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
185
  outputs=[chatbot_output, history_state, msg_input],
186
  )
187
  send_btn.click(
188
- respond,
189
- inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature],
190
  outputs=[chatbot_output, history_state, msg_input],
191
  )
192
- regen_btn.click(lambda x: ("", []), inputs=[api_key_input], outputs=[chatbot_output, history_state])
193
-
194
- auth_button.click(authorize, inputs=[api_user_input, api_key_input], outputs=[auth_view, chat_view])
195
 
196
- demo.launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
197
 
198
  if __name__ == "__main__":
199
  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
 
16
  def render_avatars(userid):
 
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}
 
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:
 
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
 
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("&", "&amp;")
 
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.")
148
  api_user_input = gr.Textbox(placeholder="snowflake", label="UserID", type='email')
149
  api_key_input = gr.Textbox(placeholder="Enter your API key", label="Token", type='password')
150
  auth_button = gr.Button("Authorize")
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: (authorize(user, key, PRIMARY_SYSTEM_INSTRUCTIONS), ""),
181
+ inputs=[api_user_input, api_key_input],
182
+ outputs=[chat_view, auth_status],
183
+ )
184
+ save_instructions_btn.click(
185
+ lambda key, instructions: ("", ""),
186
+ inputs=[api_key_input, system_instructions_input],
187
+ outputs=[auth_status],
188
+ )
189
+ demo.launch(show_api=False)
190
 
191
  if __name__ == "__main__":
192
  demo.queue = False