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|
|
|
| 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 gradio_client import Client
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
client_messages = []
|
| 14 |
+
server_responses = []
|
| 15 |
+
messages = []
|
| 16 |
+
used_ports = []
|
| 17 |
+
|
| 18 |
+
websocket_server = None
|
| 19 |
+
stop = asyncio.Future()
|
| 20 |
+
|
| 21 |
+
# Global variables to store references to the textboxes
|
| 22 |
+
messageTextbox = None
|
| 23 |
+
serverMessageTextbox = None
|
| 24 |
+
|
| 25 |
+
# Set up the HTTP server
|
| 26 |
+
class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
| 27 |
+
def do_GET(self):
|
| 28 |
+
if self.path == '/':
|
| 29 |
+
self.send_response(200)
|
| 30 |
+
self.send_header('Content-type', 'text/html')
|
| 31 |
+
self.end_headers()
|
| 32 |
+
with open('index.html', 'rb') as file:
|
| 33 |
+
self.wfile.write(file.read())
|
| 34 |
+
else:
|
| 35 |
+
self.send_response(404)
|
| 36 |
+
self.end_headers()
|
| 37 |
+
|
| 38 |
+
# Set up the SQLite database
|
| 39 |
+
db = sqlite3.connect('chat-hub.db')
|
| 40 |
+
cursor = db.cursor()
|
| 41 |
+
cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
|
| 42 |
+
db.commit()
|
| 43 |
+
|
| 44 |
+
# Define the function for sending an error message
|
| 45 |
+
def sendErrorMessage(ws, errorMessage):
|
| 46 |
+
errorResponse = {'error': errorMessage}
|
| 47 |
+
ws.send(json.dumps(errorResponse))
|
| 48 |
+
|
| 49 |
+
# Function to send a question to the chatbot and get the response
|
| 50 |
+
async def askQuestion(question):
|
| 51 |
+
try:
|
| 52 |
+
response = requests.post(
|
| 53 |
+
"https://flowiseai-flowise.hf.space/api/v1/prediction/522afa32-484c-471e-9ba5-4d6d2edfb89b",
|
| 54 |
+
headers={"Content-Type": "application/json"},
|
| 55 |
+
json={"question": message},
|
| 56 |
+
)
|
| 57 |
+
response_content = response.content.decode('utf-8')
|
| 58 |
+
|
| 59 |
+
return response_content
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(e)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
async def listen_for_messages():
|
| 65 |
+
while True:
|
| 66 |
+
if len(client_messages) > 0:
|
| 67 |
+
# Get the latest client message
|
| 68 |
+
client_message = client_messages[-1]
|
| 69 |
+
try:
|
| 70 |
+
server_message = server_responses[-1]
|
| 71 |
+
except IndexError:
|
| 72 |
+
# Handle the case when there are no server responses yet
|
| 73 |
+
server_message = "connected successfully"
|
| 74 |
+
|
| 75 |
+
return client_message, server_message
|
| 76 |
+
else:
|
| 77 |
+
# Handle the case when there are no client messages yet
|
| 78 |
+
client_message = "connected successfully"
|
| 79 |
+
server_message = "connected successfully"
|
| 80 |
+
|
| 81 |
+
return client_message, server_message
|
| 82 |
+
|
| 83 |
+
async def handleWebSocket(ws):
|
| 84 |
+
print('New connection')
|
| 85 |
+
await ws.send('Hello! You are now entering a chat room for AI agents working as instances of NeuralGPT. Keep in mind that you are speaking with another chatbot')
|
| 86 |
+
while True:
|
| 87 |
+
message = await ws.recv()
|
| 88 |
+
message_copy = message
|
| 89 |
+
client_messages.append(message_copy)
|
| 90 |
+
print(f'Received message: {message}')
|
| 91 |
+
parsedMessage = json.loads(message)
|
| 92 |
+
messageText = message
|
| 93 |
+
messages.append(message)
|
| 94 |
+
timestamp = datetime.datetime.now().isoformat()
|
| 95 |
+
sender = 'client'
|
| 96 |
+
db = sqlite3.connect('chat-hub.db')
|
| 97 |
+
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
| 98 |
+
(sender, messageText, timestamp))
|
| 99 |
+
db.commit()
|
| 100 |
+
try:
|
| 101 |
+
message = messages[-1]
|
| 102 |
+
answer = await askQuestion(message) # Use the message directly
|
| 103 |
+
response = {'answer': answer}
|
| 104 |
+
serverMessageText = response.get('answer', '')
|
| 105 |
+
await ws.send(json.dumps(response))
|
| 106 |
+
# Append the server response to the server_responses list
|
| 107 |
+
server_responses.append(serverMessageText)
|
| 108 |
+
serverSender = 'server'
|
| 109 |
+
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)',
|
| 110 |
+
(serverSender, serverMessageText, timestamp))
|
| 111 |
+
db.commit()
|
| 112 |
+
|
| 113 |
+
except websockets.exceptions.ConnectionClosedError as e:
|
| 114 |
+
print(f"Connection closed: {e}")
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"Error: {e}")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# Function to stop the WebSocket server
|
| 121 |
+
def stop_websockets():
|
| 122 |
+
global websocket_server
|
| 123 |
+
if websocket_server:
|
| 124 |
+
cursor.close()
|
| 125 |
+
db.close()
|
| 126 |
+
websocket_server.close()
|
| 127 |
+
print("WebSocket server stopped.")
|
| 128 |
+
else:
|
| 129 |
+
print("WebSocket server is not running.")
|
| 130 |
+
|
| 131 |
+
# Start the WebSocket server
|
| 132 |
+
async def start_websockets(websocketPort):
|
| 133 |
+
global messageTextbox, serverMessageTextbox, websocket_server
|
| 134 |
+
# Create a WebSocket client that connects to the server
|
| 135 |
+
|
| 136 |
+
await(websockets.serve(handleWebSocket, 'localhost', websocketPort))
|
| 137 |
+
used_ports.append(websocketPort)
|
| 138 |
+
print(f"Starting WebSocket server on port {websocketPort}...")
|
| 139 |
+
return "Used ports:\n" + '\n'.join(map(str, used_ports))
|
| 140 |
+
|
| 141 |
+
with gr.Blocks() as demo:
|
| 142 |
+
|
| 143 |
+
with gr.Column(scale=1, min_width=600):
|
| 144 |
+
with gr.Row():
|
| 145 |
+
# Use the client_messages list to update the messageTextbox
|
| 146 |
+
client_message = gr.Textbox(lines=15, max_lines=130, label="Client inputs")
|
| 147 |
+
# Use the server_responses list to update the serverMessageTextbox
|
| 148 |
+
server_message = gr.Textbox(lines=15, max_lines=130, label="Server responses")
|
| 149 |
+
with gr.Row():
|
| 150 |
+
websocketPort = gr.Slider(minimum=1000, maximum=9999, label="Websocket server port", interactive=True, randomize=False)
|
| 151 |
+
startWebsockets = gr.Button("Start WebSocket Server")
|
| 152 |
+
stopWebsockets = gr.Button("Stop WebSocket Server")
|
| 153 |
+
with gr.Row():
|
| 154 |
+
gui = gr.Button("connect interface")
|
| 155 |
+
with gr.Row():
|
| 156 |
+
port = gr.Textbox()
|
| 157 |
+
startWebsockets.click(start_websockets, inputs=websocketPort, outputs=port)
|
| 158 |
+
gui.click(listen_for_messages, inputs=None, outputs={client_message, server_message})
|
| 159 |
+
stopWebsockets.click(stop_websockets)
|
| 160 |
+
|
| 161 |
+
demo.queue()
|
| 162 |
+
demo.launch(share=True)
|