Spaces:
Build error
Build error
| import gradio as gr | |
| import requests | |
| import json | |
| import os | |
| API_URL = "https://host.palple.polrambora.com/pmsq" | |
| sessions = {} | |
| PRIMARY_SYSTEM_INSTRUCTIONS = "You are P-MSQ (Messaging Service Query), a friendly AI Chatbot that can help in any situations" | |
| ASSISTANT_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/API.png" | |
| USER_PIC_PATH = "https://huggingface.co/spaces/PLRMB/P-MSQ-API-PREVIEW/resolve/main/usr.png" | |
| def authorize(user, api_key, system_message): | |
| test_data = { | |
| "user": user, | |
| "key": api_key | |
| } | |
| try: | |
| response = requests.post( | |
| "https://host.palple.polrambora.com/check_key_impv", | |
| json=test_data, | |
| ) | |
| if response.status_code == 200: | |
| response_json = response.json() | |
| if api_key not in sessions: | |
| sessions[api_key] = { | |
| "history": [], | |
| "headers": { | |
| "authorization": api_key, | |
| "Content-Type": 'application/json' | |
| }, | |
| "system_message": system_message | |
| } | |
| return True | |
| else: | |
| return False | |
| except Exception as e: | |
| return False | |
| def respond(message, api_key, max_tokens, top_p, temperature): | |
| session = sessions.get(api_key, {}) | |
| history = session.get("history", []) | |
| headers = session.get("headers", {}) | |
| system_message = session.get("system_message", PRIMARY_SYSTEM_INSTRUCTIONS) | |
| messages = [] | |
| for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history: | |
| if user_message: | |
| messages.append({ | |
| "role": "user", | |
| "content": user_message, | |
| "profile": user_profile, | |
| "picture": user_pic | |
| }) | |
| if assistant_message: | |
| messages.append({ | |
| "role": "assistant", | |
| "content": assistant_message, | |
| "profile": assistant_profile, | |
| "picture": assistant_pic | |
| }) | |
| data = { | |
| "preferences": { | |
| "max_char": max_tokens, | |
| "temperature": temperature, | |
| "top_p": top_p, | |
| "system_message": system_message | |
| }, | |
| "conversation_history": messages, | |
| "input": message | |
| } | |
| response = requests.post(API_URL, headers=headers, data=json.dumps(data)) | |
| if response.status_code == 200: | |
| response_json = response.json() | |
| assistant_reply = response_json["msq"]["message"][0] | |
| history.append((message, assistant_reply, "You", "P-ALPLE", USER_PIC_PATH, ASSISTANT_PIC_PATH)) | |
| sessions[api_key]["history"] = history | |
| return history, assistant_reply | |
| else: | |
| return history, "Error: " + response.json().get("error", "Unknown error occurred.") | |
| js = """ | |
| function Scrolldown() { | |
| const messagesContainer = document.getElementById('chatbox-container'); | |
| if (!messagesContainer) { | |
| console.error('Messages container not found!'); | |
| return; | |
| } | |
| const observer = new MutationObserver((mutationsList, observer) => { | |
| for (const mutation of mutationsList) { | |
| if (mutation.type === 'childList') { | |
| const chatboxContainer = document.getElementById('chatbox-container'); | |
| if (chatboxContainer) { | |
| chatboxContainer.scrollTop = chatboxContainer.scrollHeight; | |
| } | |
| } | |
| } | |
| }); | |
| const config = { childList: true }; | |
| observer.observe(messagesContainer, config); | |
| console.log('Observing'); | |
| } | |
| """ | |
| with gr.Blocks(css=".chatbox {height: 400px; overflow: auto; border: 1px solid #262626; padding: 10px; background-color: #171717; display: flex; flex-direction: column-reverse;}", js=js) as demo: | |
| with gr.Column(visible=True) as auth_view: | |
| gr.Markdown("## P-MSQ Authorization") | |
| gr.Markdown("P-MSQ is in closed alpha test! The model, api and more are subject to change.") | |
| api_user_input = gr.Textbox(placeholder="snowflake", label="UserID", type='email') | |
| api_key_input = gr.Textbox(placeholder="Enter your API key", label="Token", type='password') | |
| auth_button = gr.Button("Authorize") | |
| auth_status = gr.Textbox(label="Authorization Status", interactive=False) | |
| with gr.Column(visible=False) as chat_view: | |
| gr.Markdown("## P-MSQ Chat Interface") | |
| chatbot_output = gr.HTML(elem_id="chatbox-container") | |
| msg_input = gr.Textbox( | |
| show_label=False, | |
| placeholder="Type your message and press Shift+Enter...", | |
| lines=2, | |
| elem_id="input-text" | |
| ) | |
| send_btn = gr.Button("Send") | |
| regen_btn = gr.Button("Clear") | |
| system_instructions_input = gr.Textbox(placeholder="Enter custom instructions (optional)", | |
| label="Custom System Instructions", | |
| lines=2) | |
| save_instructions_btn = gr.Button("Save Instructions") | |
| gr.Markdown("### Settings") | |
| max_tokens = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens") | |
| top_p = gr.Slider(minimum=0, maximum=2, value=0.8, step=0.1, label="Top P") | |
| temperature = gr.Slider(minimum=0.1, maximum=1, value=0.7, step=0.1, label="Temperature") | |
| history_state = gr.State([]) | |
| last_message_state = gr.State("") | |
| def user_interaction(message, history, api_key, max_tokens, top_p, temperature): | |
| history, assistant_reply = respond(message, api_key, max_tokens, top_p, temperature) | |
| for user_message, assistant_message, user_profile, assistant_profile, user_pic, assistant_pic in history: | |
| with chatbot_output: | |
| if user_message: | |
| with gr.Row(): | |
| gr.Image(value=user_pic, label=user_profile, width=40, height=40) | |
| gr.Markdown(f"**{user_profile}:** {user_message}") | |
| if assistant_message: | |
| with gr.Row(): | |
| gr.Image(value=assistant_pic, label=assistant_profile, width=40, height=40) | |
| gr.Markdown(f"**{assistant_profile}:** {assistant_message}") | |
| return history, "" | |
| def regenerate_response(history, last_message, max_tokens, top_p, temperature): | |
| return "", [] | |
| def clear_history(api_key): | |
| if api_key in sessions: | |
| sessions[api_key]["history"] = [] | |
| return "", [] | |
| def load_conversation(api_key): | |
| session = sessions.get(api_key, {}) | |
| history = session.get("history", []) | |
| return render_message(history), history | |
| msg_input.submit( | |
| user_interaction, | |
| inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature], | |
| outputs=[chatbot_output, history_state, msg_input], | |
| ) | |
| send_btn.click( | |
| user_interaction, | |
| inputs=[msg_input, history_state, api_key_input, max_tokens, top_p, temperature], | |
| outputs=[chatbot_output, history_state, msg_input], | |
| ) | |
| regen_btn.click(clear_history, | |
| inputs=[api_key_input], | |
| outputs=[chatbot_output, history_state]) | |
| def authorize_and_proceed(user, api_key): | |
| if authorize(user, api_key, PRIMARY_SYSTEM_INSTRUCTIONS): | |
| gr.Info("Loading, please wait.") | |
| messages_html, history = load_conversation(api_key) | |
| return ( | |
| gr.update(visible=False), | |
| gr.update(visible=True), | |
| messages_html, | |
| history | |
| ) | |
| else: | |
| gr.Warning("Incorrect userid/token") | |
| return ( | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| auth_status.update(value="Invalid userid/token") | |
| ) | |
| def save_custom_instructions(api_key, custom_instructions): | |
| if api_key in sessions: | |
| gr.Info("Instructions updated, we recommend to start the new conversation to make it more efficient.") | |
| sessions[api_key]["system_message"] = custom_instructions | |
| return "Instructions updated!", gr.update(value="") | |
| else: | |
| gr.Warning("Your session has been expired, please refresh the page and login again.") | |
| return "Session not found.", gr.update(value="") | |
| auth_button.click(authorize_and_proceed, inputs=[api_user_input, api_key_input], outputs=[auth_view, chat_view, chatbot_output, history_state]) | |
| save_instructions_btn.click(save_custom_instructions, inputs=[api_key_input, system_instructions_input], outputs=auth_status) | |
| demo.launch() | |
| if __name__ == "__main__": | |
| demo.queue = False | |