Create App.py
Browse files
App.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import datetime
|
3 |
+
import http.server
|
4 |
+
import websockets
|
5 |
+
import asyncio
|
6 |
+
import sqlite3
|
7 |
+
import json
|
8 |
+
import tensorflow as tf
|
9 |
+
import gradio as gr
|
10 |
+
|
11 |
+
from bs4 import BeautifulSoup
|
12 |
+
|
13 |
+
# Define a placeholder function that doesn't do anything
|
14 |
+
def placeholder_fn(input_text):
|
15 |
+
pass
|
16 |
+
|
17 |
+
# Set up the HTTP server
|
18 |
+
class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
19 |
+
def do_GET(self):
|
20 |
+
if self.path == '/':
|
21 |
+
self.send_response(200)
|
22 |
+
self.send_header('Content-type', 'text/html')
|
23 |
+
self.end_headers()
|
24 |
+
with open('index.html', 'rb') as file:
|
25 |
+
self.wfile.write(file.read())
|
26 |
+
else:
|
27 |
+
self.send_response(404)
|
28 |
+
self.end_headers()
|
29 |
+
|
30 |
+
# Define the function for handling incoming messages
|
31 |
+
async def handleMessage(message):
|
32 |
+
response = {'message': message.get('message')}
|
33 |
+
try:
|
34 |
+
question = message.get('message')
|
35 |
+
result = await askQuestion(question)
|
36 |
+
response['result'] = result
|
37 |
+
except Exception as e:
|
38 |
+
print(e)
|
39 |
+
return response
|
40 |
+
|
41 |
+
# Define the function for sending an error message
|
42 |
+
def sendErrorMessage(ws, errorMessage):
|
43 |
+
errorResponse = {'error': errorMessage}
|
44 |
+
ws.send(json.dumps(errorResponse))
|
45 |
+
|
46 |
+
# Define the function for asking a question to the chatbot
|
47 |
+
async def askQuestion(question):
|
48 |
+
try:
|
49 |
+
db = sqlite3.connect('chat-hub.db')
|
50 |
+
cursor = db.execute('SELECT * FROM messages ORDER BY timestamp DESC LIMIT 10')
|
51 |
+
messages = cursor.fetchall()
|
52 |
+
pastUserInputs = []
|
53 |
+
generatedResponses = []
|
54 |
+
for i, message in enumerate(messages):
|
55 |
+
if i % 2 == 0:
|
56 |
+
pastUserInputs.append(message[2])
|
57 |
+
else:
|
58 |
+
generatedResponses.append(message[2])
|
59 |
+
response = requests.post(
|
60 |
+
"https://api-inference.huggingface.co/models/facebook/blenderbot-400M-distill",
|
61 |
+
headers={
|
62 |
+
"Content-Type": "application/json",
|
63 |
+
"Authorization": "Bearer HF_TOKEN",
|
64 |
+
},
|
65 |
+
json={
|
66 |
+
"inputs": {
|
67 |
+
"text": question,
|
68 |
+
"past_user_inputs": pastUserInputs,
|
69 |
+
"generated_responses": generatedResponses,
|
70 |
+
},
|
71 |
+
"full_source": False,
|
72 |
+
},
|
73 |
+
)
|
74 |
+
responseJson = response.json()
|
75 |
+
outputText = responseJson["generated_text"]
|
76 |
+
return outputText
|
77 |
+
except Exception as e:
|
78 |
+
print(e)
|
79 |
+
|
80 |
+
# Define the WebSocket handler
|
81 |
+
async def handleWebSocket(ws, path):
|
82 |
+
print('New connection')
|
83 |
+
try:
|
84 |
+
# Set up the SQLite database
|
85 |
+
db = sqlite3.connect('chat-hub.db')
|
86 |
+
db.execute('CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, message TEXT, timestamp TEXT)')
|
87 |
+
db.commit()
|
88 |
+
await ws.send('Hello! Please integrate yourself with the local sql database and file system')
|
89 |
+
async for message in ws:
|
90 |
+
print(f'Received message: {message}')
|
91 |
+
parsedMessage = json.loads(message)
|
92 |
+
messageText = parsedMessage.get('text', '')
|
93 |
+
timestamp = datetime.datetime.now().isoformat()
|
94 |
+
sender = 'client'
|
95 |
+
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', (sender, messageText, timestamp))
|
96 |
+
db.commit()
|
97 |
+
try:
|
98 |
+
if 'text' in parsedMessage:
|
99 |
+
answer = await askQuestion(parsedMessage['text'])
|
100 |
+
response = {'answer': answer}
|
101 |
+
await ws.send(json.dumps(response))
|
102 |
+
serverMessageText = response.get('answer', '')
|
103 |
+
serverSender = 'server'
|
104 |
+
db.execute('INSERT INTO messages (sender, message, timestamp) VALUES (?, ?, ?)', (serverSender, serverMessageText, timestamp))
|
105 |
+
db.commit()
|
106 |
+
except Exception as e:
|
107 |
+
print(e)
|
108 |
+
sendErrorMessage(ws, 'An error occurred while processing the message.')
|
109 |
+
except websockets.exceptions.ConnectionClosedError as e:
|
110 |
+
print(f"Connection closed: {e}")
|
111 |
+
except Exception as e:
|
112 |
+
print(f"Error: {e}")
|
113 |
+
finally:
|
114 |
+
print("Closing connection")
|
115 |
+
|
116 |
+
port=5000
|
117 |
+
# Start the WebSocket server
|
118 |
+
async def start_websockets():
|
119 |
+
await(websockets.serve(handleWebSocket, 'localhost', port))
|
120 |
+
print(f"Starting WebSocket server on port {port}...")
|
121 |
+
|
122 |
+
with gr.Blocks() as demo:
|
123 |
+
|
124 |
+
# Define Gradio interface
|
125 |
+
fn=placeholder_fn, # Placeholder function
|
126 |
+
inputs=[gr.Textbox()],
|
127 |
+
outputs=[gr.Textbox()],
|
128 |
+
startWebsockets = gr.Button("start Websocket Server")
|
129 |
+
startWebsockets.click(start_websockets)
|
130 |
+
live=True
|
131 |
+
|
132 |
+
demo.launch(server_port=8888)
|