RomZay commited on
Commit
653b1c0
·
verified ·
1 Parent(s): 0f46d61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -116
app.py CHANGED
@@ -4,38 +4,28 @@ import json
4
  import os
5
 
6
  API_URL = "https://host.palple.polrambora.com/pmsq"
7
- AUTH_FILE = "auth_key.json"
8
- CONVO_FILE = "conversation_history.json"
9
- API_TOKEN = os.getenv("POLLY")
10
-
11
- ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png"
12
- USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png"
13
 
14
  headers = {
15
- "Authorization": f"{API_TOKEN}",
16
  "Content-Type": "application/json",
17
  }
18
 
19
- def check_auth(key):
20
- if not os.path.exists(AUTH_FILE):
21
- return False
22
- with open(AUTH_FILE, 'r') as f:
23
- saved_key = f.read().strip()
24
- return key == saved_key
25
-
26
- def save_auth(key):
27
- with open(AUTH_FILE, 'w') as f:
28
- f.write(key)
29
-
30
- def load_conversation():
31
- if os.path.exists(CONVO_FILE):
32
- with open(CONVO_FILE, 'r') as f:
33
- return json.load(f)
34
- return []
35
 
36
- def save_conversation(history):
37
- with open(CONVO_FILE, 'w') as f:
38
- json.dump(history, f)
 
 
 
 
 
 
 
 
 
39
 
40
  def respond(message, history, system_message, max_tokens, top_p, temperature):
41
  messages = []
@@ -72,11 +62,21 @@ def respond(message, history, system_message, max_tokens, top_p, temperature):
72
  response_json = response.json()
73
  assistant_reply = response_json["msq"]["message"][0]
74
  history.append((message, assistant_reply, "You", "P-ALPLE", USER_PIC_PATH, ASSISTANT_PIC_PATH))
75
- save_conversation(history)
76
  return history, assistant_reply
77
  else:
78
  return history, "Error: " + response.json().get("error", "Unknown error occurred.")
79
 
 
 
 
 
 
 
 
 
 
 
 
80
  def render_message(history):
81
  messages_html = ""
82
  for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history:
@@ -95,112 +95,73 @@ def render_message(history):
95
  return messages_html
96
 
97
  with gr.Blocks(css=".chatbox {height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9;}") as demo:
98
- def auth_and_load(auth_key):
99
- if check_auth(auth_key):
100
- history = load_conversation()
101
- return render_message(history), gr.update(visible=True), gr.update(visible=False)
102
- return "", gr.update(visible=False), gr.update(visible=True)
103
 
104
- def authorize_and_proceed(auth_key):
105
- save_auth(auth_key)
106
- return auth_and_load(auth_key)
 
107
 
108
- gr.Markdown("## P-MSQ Chat Interface")
 
109
 
110
- chatbot_output = gr.HTML(elem_id="chatbox", visible=False)
111
 
112
- msg_input = gr.Textbox(
113
- show_label=False,
114
- placeholder="Type your message and press Enter...",
115
- lines=2,
116
- elem_id="input-text",
117
- visible=False
118
- )
119
 
120
- send_btn = gr.Button("Send", visible=False)
121
- regen_btn = gr.Button("Clear", visible=False)
122
 
123
- auth_key_input = gr.Textbox(label="Enter your auth key:", type="password", visible=True)
124
- auth_btn = gr.Button("Authorize", visible=True)
 
 
 
 
 
125
 
126
- system_message = gr.Textbox(value="You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations.", label="System message", visible=False)
127
-
128
- gr.Markdown("### Settings", visible=False)
129
-
130
- max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens", visible=False)
131
- top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P", visible=False)
132
- temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature", visible=False)
133
 
134
- history_state = gr.State([])
135
- last_message_state = gr.State("")
136
 
137
- def user_interaction(message, history, system_message, max_tokens, top_p, temperature):
138
- history, assistant_reply = respond(message, history, system_message, max_tokens, top_p, temperature)
139
- return render_message(history), history, "", message
140
 
141
- def regenerate_response(history, last_message, system_message, max_tokens, top_p, temperature):
142
- return "", []
143
 
144
- msg_input.submit(user_interaction,
145
- inputs=[msg_input, history_state, system_message, max_tokens, top_p, temperature],
146
- outputs=[chatbot_output, history_state, msg_input, last_message_state])
147
 
148
- send_btn.click(user_interaction,
149
- inputs=[msg_input, history_state, system_message, max_tokens, top_p, temperature],
150
- outputs=[chatbot_output, history_state, msg_input, last_message_state])
151
 
152
- regen_btn.click(regenerate_response,
153
- inputs=[history_state, last_message_state, system_message, max_tokens, top_p, temperature],
154
- outputs=[chatbot_output, history_state])
155
 
156
- auth_btn.click(auth_and_load, inputs=auth_key_input, outputs=[chatbot_output, chatbot_output, auth_btn])
 
 
157
 
158
- auth_key_input.submit(authorize_and_proceed, inputs=auth_key_input, outputs=[chatbot_output, chatbot_output, auth_btn])
 
 
159
 
160
- with gr.Row(visible=False):
161
- send_btn
162
- regen_btn
163
-
164
- gr.HTML("""
165
- <style>
166
- #chatbox {
167
- max-height: 400px;
168
- overflow-y: auto;
169
- border: 1px solid #ccc;
170
- background-color: #242424;
171
- padding: 10px;
172
- }
173
-
174
- #input-text {
175
- width: 100%;
176
- box-sizing: border-box;
177
- }
178
-
179
- .gr-button {
180
- margin: 5px;
181
- padding: 8px 16px;
182
- font-size: 14px;
183
- }
184
-
185
- .gr-row {
186
- justify-content: flex-end;
187
- }
188
-
189
- </style>
190
- <script>
191
- const chatbox = document.getElementById('chatbox');
192
-
193
- function scrollToBottom() {
194
- chatbox.scrollTop = chatbox.scrollHeight;
195
- }
196
-
197
- function handleNewMessage() {
198
- setTimeout(scrollToBottom, 50);
199
- }
200
 
201
- window.addEventListener('message', handleNewMessage);
202
- </script>
203
- """)
204
 
205
  if __name__ == "__main__":
206
  demo.launch()
 
4
  import os
5
 
6
  API_URL = "https://host.palple.polrambora.com/pmsq"
7
+ API_TOKEN = os.getenv("POLLY")
 
 
 
 
 
8
 
9
  headers = {
10
+ "Authorization": "",
11
  "Content-Type": "application/json",
12
  }
13
 
14
+ ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png"
15
+ USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ def authorize(api_key):
18
+ test_data = {"test": "auth"}
19
+ test_headers = {
20
+ "Authorization": f"{api_key}",
21
+ "Content-Type": "application/json",
22
+ }
23
+ response = requests.post("https://", headers=test_headers, data=json.dumps(test_data))
24
+ if response.status_code == 200:
25
+ headers["Authorization"] = f"{api_key}"
26
+ return True
27
+ else:
28
+ return False
29
 
30
  def respond(message, history, system_message, max_tokens, top_p, temperature):
31
  messages = []
 
62
  response_json = response.json()
63
  assistant_reply = response_json["msq"]["message"][0]
64
  history.append((message, assistant_reply, "You", "P-ALPLE", USER_PIC_PATH, ASSISTANT_PIC_PATH))
 
65
  return history, assistant_reply
66
  else:
67
  return history, "Error: " + response.json().get("error", "Unknown error occurred.")
68
 
69
+ def load_conversation_from_file(json_file):
70
+ with open(json_file, 'r') as file:
71
+ data = json.load(file)
72
+ history = []
73
+ for msg in data['conversation']:
74
+ user_message = msg.get('user_message', "")
75
+ assistant_message = msg.get('assistant_message', "")
76
+ history.append((user_message, assistant_message, "You", "P-ALPLE", USER_PIC_PATH, ASSISTANT_PIC_PATH))
77
+ return history
78
+
79
+ # Message rendering
80
  def render_message(history):
81
  messages_html = ""
82
  for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history:
 
95
  return messages_html
96
 
97
  with gr.Blocks(css=".chatbox {height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9;}") as demo:
 
 
 
 
 
98
 
99
+ with gr.Column(visible=True) as auth_view:
100
+ gr.Markdown("## P-MSQ Authorization")
101
+ api_key_input = gr.Textbox(placeholder="Enter your API key", label="API Key")
102
+ auth_button = gr.Button("Authorize")
103
 
104
+ with gr.Column(visible=False) as chat_view:
105
+ gr.Markdown("## P-MSQ Chat Interface")
106
 
107
+ chatbot_output = gr.HTML(elem_id="chatbox")
108
 
109
+ msg_input = gr.Textbox(
110
+ show_label=False,
111
+ placeholder="Type your message and press Enter...",
112
+ lines=2,
113
+ elem_id="input-text"
114
+ )
 
115
 
116
+ send_btn = gr.Button("Send")
117
+ regen_btn = gr.Button("Clear")
118
 
119
+ system_message = gr.Textbox(value="You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations.", label="System message")
120
+
121
+ gr.Markdown("### Settings")
122
+
123
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens")
124
+ top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P")
125
+ temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature")
126
 
127
+ history_state = gr.State([])
128
+ last_message_state = gr.State("")
 
 
 
 
 
129
 
130
+ load_btn = gr.Button("Load Conversation")
131
+ json_file_input = gr.Textbox(placeholder="Path to .json file", label="JSON File Path")
132
 
133
+ def load_conversation(file_path):
134
+ history = load_conversation_from_file(file_path)
135
+ return render_message(history), history
136
 
137
+ load_btn.click(load_conversation, inputs=json_file_input, outputs=[chatbot_output, history_state])
 
138
 
139
+ def user_interaction(message, history, system_message, max_tokens, top_p, temperature):
140
+ history, assistant_reply = respond(message, history, system_message, max_tokens, top_p, temperature)
141
+ return render_message(history), history, "", message
142
 
143
+ def regenerate_response(history, last_message, system_message, max_tokens, top_p, temperature):
144
+ return "", []
 
145
 
146
+ msg_input.submit(user_interaction,
147
+ inputs=[msg_input, history_state, system_message, max_tokens, top_p, temperature],
148
+ outputs=[chatbot_output, history_state, msg_input, last_message_state])
149
 
150
+ send_btn.click(user_interaction,
151
+ inputs=[msg_input, history_state, system_message, max_tokens, top_p, temperature],
152
+ outputs=[chatbot_output, history_state, msg_input, last_message_state])
153
 
154
+ regen_btn.click(regenerate_response,
155
+ inputs=[history_state, last_message_state, system_message, max_tokens, top_p, temperature],
156
+ outputs=[chatbot_output, history_state])
157
 
158
+ def authorize_and_proceed(api_key):
159
+ if authorize(api_key):
160
+ return gr.update(visible=False), gr.update(visible=True)
161
+ else:
162
+ return gr.update(visible=True), gr.update(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ auth_button.click(authorize_and_proceed, inputs=api_key_input, outputs=[auth_view, chat_view])
 
 
165
 
166
  if __name__ == "__main__":
167
  demo.launch()