Tonic commited on
Commit
15b5332
·
1 Parent(s): 1241577

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -68
app.py CHANGED
@@ -1,20 +1,23 @@
1
- import requests
2
- import datetime
3
  import http.server
4
- import websockets
5
- import websocket
6
  import asyncio
7
- import sqlite3
8
  import json
9
- import gradio as gr
10
- from bs4 import BeautifulSoup
11
- from gradio_client import Client
12
  import time
 
 
13
 
14
- client_messages = []
15
- server_responses = []
16
- messages = []
17
- used_ports = []
 
 
 
 
 
 
18
 
19
  websocket_server = None
20
  stop = asyncio.Future()
@@ -58,39 +61,23 @@ def sendErrorMessage(ws, errorMessage):
58
  errorResponse = {'error': errorMessage}
59
  ws.send(json.dumps(errorResponse))
60
 
61
- # Define a function to ask a question to the chatbot and display the response
62
- async def askQuestion(question):
63
- try:
64
- response = requests.post(
65
- "https://flowiseai-flowise.hf.space/api/v1/prediction/8fd03bee-7752-484f-844f-bdae1e4cb4fe",
66
- headers={"Content-Type": "application/json"},
67
- json={"question": question},
68
- )
69
- response_content = response.content.decode('utf-8')
70
- client_messages.append(response_content)
71
- return response_content
72
- except Exception as e:
73
- print(e)
74
-
75
- # Define a function to ask a question to the chatbot and display the response
76
- async def askQuestion2(question):
77
- try:
78
- message = server_responses[-1]
79
- url = "https://api.chaindesk.ai/datastores/query/clka5g9zc000drg6mxl671ekv"
80
- payload = {"query": message,
81
- "topK":2
82
- }
83
- headers = {
84
- "Authorization": "Bearer 5315cd7b-bb79-49bc-bca2-8bcc7b243504",
85
- "Content-Type": "application/json"
86
- }
87
-
88
- response = requests.request("POST", url, json=payload, headers=headers)
89
-
90
- print(response.text)
91
- return response.text
92
- except Exception as e:
93
- print(e)
94
 
95
  async def handleWebSocket(ws):
96
  print('New connection')
@@ -163,27 +150,52 @@ async def start_client():
163
  return server_message
164
  await asyncio.sleep(0.1)
165
 
 
 
 
166
  with gr.Blocks() as demo:
167
- with gr.Tabs(elem_classes="tab-buttons") as tabs:
168
- with gr.TabItem("Websocket Server", elem_id="websocket_server", id=0):
169
- with gr.Column(scale=1, min_width=600):
170
- with gr.Row():
171
- # Use the client_messages list to update the messageTextbox
172
- client_msg = gr.Textbox(lines=15, max_lines=130, label="Client inputs")
173
- # Use the server_responses list to update the serverMessageTextbox
174
- server_msg = gr.Textbox(lines=15, max_lines=130, label="Server responses")
175
- with gr.Row():
176
- websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
177
- startWebsockets = gr.Button("Start WebSocket Server")
178
- stopWebsockets = gr.Button("Stop WebSocket Server")
179
- with gr.Row():
180
- Bot1 = gr.Button("Bot 1")
181
- with gr.Row():
182
- gui = gr.Button("connect interface")
183
- with gr.Row():
184
- port = gr.Textbox()
185
- startWebsockets.click(start_websockets, inputs=websocketPort, outputs=port)
186
- Bot1.click(askQuestion, inputs=client_msg, outputs=server_msg)
187
-
188
- demo.queue()
189
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import http.server
 
 
2
  import asyncio
 
3
  import json
4
+ import random
5
+ import datetime
6
+ import sqlite3
7
  import time
8
+ import websockets
9
+ import gradio as gr
10
 
11
+ client_messages = [] # List to store client messages
12
+ server_responses = [] # List to store server responses
13
+ messages = [] # List to store all messages
14
+ used_ports = [] # List to store used WebSocket ports
15
+
16
+ # Set up the SQLite database
17
+ db = sqlite3.connect('chat-hub.db')
18
+ cursor = db.cursor()
19
+ cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
20
+ db.commit()
21
 
22
  websocket_server = None
23
  stop = asyncio.Future()
 
61
  errorResponse = {'error': errorMessage}
62
  ws.send(json.dumps(errorResponse))
63
 
64
+
65
+ async def handle_message(client_responses, user_input, user_message, history):
66
+ client_responses.append(user_input)
67
+ # Provide a response to the user
68
+ return "You typed: " + user_message, history + [[user_message, None]]
69
+
70
+ async def ask_question(agent_responses, user_input, user_message):
71
+ agent_responses.append(user_input)
72
+ bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
73
+ return bot_message
74
+
75
+ # Define the WebSocket server handler
76
+ async def websocket_server(ws, path):
77
+ async for message in ws:
78
+ # Handle incoming WebSocket messages using the handle_message function
79
+ response, _ = await handle_message(client_messages, message, message, [])
80
+ await ws.send(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  async def handleWebSocket(ws):
83
  print('New connection')
 
150
  return server_message
151
  await asyncio.sleep(0.1)
152
 
153
+ # Start the WebSocket server
154
+ start_server = websockets.serve(websocket_server, "localhost", 8765)
155
+
156
  with gr.Blocks() as demo:
157
+ with gr.Column(scale=1, min_width=600):
158
+ with gr.Row():
159
+ input_msg1 = gr.Textbox(lines=15, max_lines=130, label="inputs", interactive=False)
160
+ response_msg1 = gr.Textbox(lines=15, max_lines=130, label="Client responses", interactive=False)
161
+ with gr.Row():
162
+ user_input1 = gr.Textbox(label="User Input")
163
+ with gr.Row():
164
+ bot1 = gr.Button("Ask Agent1")
165
+ bot2 = gr.Button("Ask Agent2")
166
+ with gr.Row():
167
+ websocket_port = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
168
+ start_client = gr.Button("Start WebSocket client")
169
+ stop_client = gr.Button("Stop WebSocket client")
170
+ with gr.Row():
171
+ port_in_use = gr.Textbox()
172
+ with gr.Row():
173
+ chat = gr.ChatInterface(handle_message, inputs=input_msg1, outputs=[response_msg1])
174
+ start_client.click(start_client, inputs=websocket_port, outputs=[port_in_use]).then(handle_message, inputs=None, outputs=chat)
175
+ bot1.click(ask_question, inputs=user_input1, outputs=response_msg1)
176
+
177
+ chatbot = gr.Chatbot()
178
+ msg = gr.Textbox()
179
+ clear = gr.Button("Clear")
180
+
181
+ def user(user_message, history):
182
+ return "", history + [[user_message, None]]
183
+
184
+ def bot(history):
185
+ bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
186
+ history[-1][1] = ""
187
+ for character in bot_message:
188
+ history[-1][1] += character
189
+ time.sleep(0.05)
190
+ yield history
191
+
192
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
193
+ bot, chatbot, chatbot
194
+ )
195
+ clear.click(lambda: None, None, chatbot, queue=False)
196
+
197
+ server = await websockets.serve(websocket_server, "localhost", 8765) # Set your desired WebSocket server parameters
198
+ await server.wait_closed()
199
+
200
+ demo.queue()
201
+ demo.launch(share=True, server_name="0.0.0.0", server_port=8765)