Spaces:
Runtime error
Runtime error
| import http.server | |
| import asyncio | |
| import json | |
| import random | |
| import datetime | |
| import sqlite3 | |
| import time | |
| import websockets | |
| import gradio as gr | |
| client_messages = [] # List to store client messages | |
| server_responses = [] # List to store server responses | |
| messages = [] # List to store all messages | |
| used_ports = [] # List to store used WebSocket ports | |
| # Set up the SQLite database | |
| db = sqlite3.connect('chat-hub.db') | |
| cursor = db.cursor() | |
| cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)') | |
| db.commit() | |
| websocket_server = None | |
| stop = asyncio.Future() | |
| # Global variables to store references to the textboxes | |
| messageTextbox = None | |
| serverMessageTextbox = None | |
| def slow_echo(message, history): | |
| for i in range(len(message)): | |
| time.sleep(0.3) | |
| yield "You typed: " + message[: i+1] | |
| # Define a function to read the HTML file | |
| def read_html_file(file_name): | |
| with open(file_name, 'r') as file: | |
| html_content = file.read() | |
| return html_content | |
| # Set up the HTTP server | |
| class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler): | |
| def do_GET(self): | |
| if self.path == '/': | |
| self.send_response(200) | |
| self.send_header('Content-type', 'text/html') | |
| self.end_headers() | |
| with open('index.html', 'rb') as file: | |
| self.wfile.write(file.read()) | |
| else: | |
| self.send_response(404) | |
| self.end_headers() | |
| # Set up the SQLite database | |
| db = sqlite3.connect('chat-hub.db') | |
| cursor = db.cursor() | |
| cursor.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)') | |
| db.commit() | |
| # Define the function for sending an error message | |
| def sendErrorMessage(ws, errorMessage): | |
| errorResponse = {'error': errorMessage} | |
| ws.send(json.dumps(errorResponse)) | |
| async def handle_message(client_responses, user_input, user_message, history): | |
| client_responses.append(user_input) | |
| # Provide a response to the user | |
| return "You typed: " + user_message, history + [[user_message, None]] | |
| async def ask_question(agent_responses, user_input, user_message): | |
| agent_responses.append(user_input) | |
| bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"]) | |
| return bot_message | |
| # Define the WebSocket server handler | |
| async def websocket_server(ws, path): | |
| async for message in ws: | |
| # Handle incoming WebSocket messages using the handle_message function | |
| response, _ = await handle_message(client_messages, message, message, []) | |
| await ws.send(response) | |
| async def handleWebSocket(ws): | |
| print('New connection') | |
| 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') | |
| while True: | |
| message = await ws.recv() | |
| message_copy = message | |
| client_messages.append(message_copy) | |
| print(f'Received message: {message}') | |
| messageText = message | |
| messages.append(message) | |
| timestamp = datetime.datetime.now().isoformat() | |
| sender = 'client' | |
| db = sqlite3.connect('chat-hub.db') | |
| db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
| (sender, messageText, timestamp)) | |
| db.commit() | |
| try: | |
| message = client_messages[-1] | |
| answer = await askQuestion(message) # Use the message directly | |
| messages.append(answer) | |
| response = {'answer': answer} | |
| serverMessageText = response.get('answer', '') | |
| await ws.send(json.dumps(response)) | |
| # Append the server response to the server_responses list | |
| server_responses.append(serverMessageText) | |
| serverSender = 'server' | |
| db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', | |
| (serverSender, serverMessageText, timestamp)) | |
| db.commit() | |
| except websockets.exceptions.ConnectionClosedError as e: | |
| print(f"Connection closed: {e}") | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| # Function to stop the WebSocket server | |
| def stop_websockets(): | |
| global websocket_server | |
| if websocket_server: | |
| cursor.close() | |
| db.close() | |
| websocket_server.close() | |
| print("WebSocket server stopped.") | |
| else: | |
| print("WebSocket server is not running.") | |
| # Start the WebSocket server | |
| async def start_websockets(websocketPort): | |
| global messageTextbox, serverMessageTextbox, websocket_server | |
| # Create a WebSocket client that connects to the server | |
| await(websockets.serve(handleWebSocket, 'localhost', websocketPort)) | |
| used_ports.append(websocketPort) | |
| print(f"Starting WebSocket server on port {websocketPort}...") | |
| return "Used ports:\n" + '\n'.join(map(str, used_ports)) | |
| async def start_client(): | |
| async with websockets.connect('ws://localhost:5000') as ws: | |
| while True: | |
| # Listen for messages from the server | |
| server_message = await ws.recv() | |
| server_responses.append(server_message) | |
| messages.append(server_message) | |
| client_response = await askQuestion2(server_message) | |
| client_messages.append(client_response) | |
| await ws.send(client_response) | |
| return server_message | |
| await asyncio.sleep(0.1) | |
| async def start_websocket_server(): | |
| server = await websockets.serve(websocket_server, "localhost", 8765) # Set your desired WebSocket server parameters | |
| await server.wait_closed() | |
| if __name__ == "__main__": | |
| demo = gr.Interface( | |
| fn=handle_message, | |
| inputs="text", # Change this to the appropriate input type | |
| outputs="text", # Change this to the appropriate output type | |
| live=False, | |
| title="Chatbot Interface", | |
| description="Enter your message and get a response.", | |
| ) | |
| demo.launch(server_name="0.0.0.0", server_port=8765) | |
| asyncio.run(start_websocket_server()) |