-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
371 lines (315 loc) · 11.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from model import llama, loadLlama, TTS
from flask import (
Flask,
render_template,
request,
Response,
session,
redirect,
url_for,
jsonify,
)
import json
# import mysql.connector as mc
import re
import threading
import asyncio
from db import DataBase
import os
app = Flask(__name__)
loadEvent = threading.Event()
infEvent = threading.Event()
# @app.before_request
# loadLlama()
def backgroundtasks():
# app.before_request_funcs[None].remove(backgroundtasks)
start_background_tasks()
def start_background_tasks():
loop = asyncio.new_event_loop()
t = threading.Thread(target=load_model_background, args=(loop,))
t.start()
def load_model_background(loop):
asyncio.set_event_loop(loop)
loop.run_until_complete(loadLlama())
global loadEvent
loadEvent.set()
backgroundtasks()
app.secret_key = "#chatbotproject###$$$"
app.config["UPLOAD_FOLDER"] = os.path.join(app.static_folder, "uploads")
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = "admin"
app.config["MYSQL_DB"] = "chatbot"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
db = DataBase(app)
@app.route("/")
def index():
if "loggedin" in session:
return redirect("/newchat")
return redirect(url_for("login"))
@app.route("/login", methods=["GET", "POST"])
def login():
msg = ""
if (
request.method == "POST"
and "username" in request.form
and "password" in request.form
):
username = request.form["username"]
password = request.form["password"]
account = db.selectOne(
"*", "users", ["name = %s and password = %s", (username, password)]
)
if account:
session["loggedin"] = True
session["id"] = account["id"]
session["username"] = account["name"]
msg = "Logged in successfully !"
return redirect("/")
else:
msg = "Incorrect username / password !"
return render_template("login.html", msg=msg)
@app.route("/logout")
def logout():
session.pop("loggedin", None)
session.pop("id", None)
session.pop("username", None)
return redirect(url_for("login"))
@app.route("/register", methods=["GET", "POST"])
def register():
msg = ""
if (
request.method == "POST"
and "username" in request.form
and "password" in request.form
):
username = request.form["username"]
password = request.form["password"]
account = db.selectOne("*", "users", ["name = %s", (username,)])
if account:
msg = "Account already exists !"
elif not re.match(r"[A-Za-z0-9]+", username):
msg = "name must contain only characters and numbers !"
else:
db.insert("users", ['name','password'], [username, password])
msg = 'You have successfully registered ! <a href="/login"> Login here </a>'
elif request.method == "POST":
msg = "Please fill out the form !"
return render_template("register.html", msg=msg)
@app.route("/createchat", methods=["GET"])
def createChat():
chat_id = session.get("chat_id")
if chat_id is not None:
session.pop("chat_id", None)
return redirect("/newchat")
else:
return redirect("newchat")
@app.route("/newchat", methods=["POST", "GET"])
def newchat():
chat_id = session.get("chat_id")
username = session["username"]
if request.method == "GET":
#maybe handle if id is not in db
names = db.select(
["name", "id"], "history", ["usrid = {}".format(session["id"]), False]
)
chatlist = list()
for i in names:
chatlist.append(i)
if chat_id is not None:
return redirect('/chat?chat_id='+str(chat_id))
return render_template("new_chat.html", chatlist=chatlist)
if request.method == "POST":
if "message" not in request.get_json():
return redirect("/newchat")
data = request.get_json()
usermsg = data["message"]
if chat_id is not None:
lastmsgs = db.select(
["body"],
"history",
["usrid = {} and id = {}".format(session["id"], chat_id), False],
)[0]["body"]
lastmsg = "\n".join(lastmsgs.split("####|msgsep|####")[-5:])
prompt = (
"Here is the last conversation between user and assistant : \n"
+ lastmsg
+ "\nRespond to this latest message :\n"
+ session["username"]
+ ": "
+ usermsg
)
f = open("prompt.txt", "r")
sysmsg = f.read()
loadEvent.wait()
response = llama(prompt=prompt, sys_prompt=sysmsg)
message = (
response[0]["generated_text"]
.split("<|eot_id|><|start_header_id|>assistant<|end_header_id|>")[1]
.strip()
)
usermsgformatted = (
session["username"] + ": " + usermsg + "\n" + "Assistant: " + message
)
db.update(
"history",
"body",
lastmsgs + "\n####|msgsep|####\n" + usermsgformatted,
["id=%s", chat_id],
)
# audio = TTS(message, "static/uploads")
# audioURL = request.url_root + "/" + audio
message = {"message": message, "newchat": False}
return app.response_class(
response=json.dumps(message), status=200, mimetype="application/json"
)
else:
prompt = (
"Here is a conversation between user and assistant\nRespond to this message :\n"
+ session["username"]
+ ": "
+ usermsg
)
f = open("prompt.txt", "r")
sysmsg = f.read()
loadEvent.wait()
response = llama(prompt=prompt, sys_prompt=sysmsg)
message = (
response[0]["generated_text"]
.split("<|eot_id|><|start_header_id|>assistant<|end_header_id|>")[1]
.strip()
)
usermsgformatted = (
session["username"] + ": " + usermsg + "\n" + "Assistant: " + message
)
chatName = (
llama(
usermsgformatted,
sys_prompt="You are good at giving names for a chatsummary.Give clear and consice short names for a given chat. The chat will be given to you. You should return only a suitable name for the chat nothing else. The name should match the chattopic. Now give a name for the following chat.",
)[0]["generated_text"]
.split("<|eot_id|><|start_header_id|>assistant<|end_header_id|>")[1]
.strip()
)
db.insert(
"history",
["body", "usrid", "name"],
[usermsgformatted, session["id"], chatName],
)
chat_id = db.getInsertedId()
session["chat_id"] = str(chat_id)
message = {
"message": message,
"chat_id": chat_id,
"name": chatName,
"newchat": True,
}
return app.response_class(
response=json.dumps(message), status=200, mimetype="application/json"
)
@app.route("/chat", methods=["POST", "GET"])
def chat():
if request.method == "GET":
chat_id = request.args.get("chat_id")
if chat_id is None:
return redirect("/newchat")
names = db.select(
["name", "id"], "history", ["usrid = {}".format(session["id"]), False]
)
chatlist = list()
chatName=''
for i in names:
if str(i['id'])==chat_id:
chatName = i['name']
chatlist.append(i)
data = db.select("*", "history", ["id = {}".format(chat_id), False])[0]
if(len(data)<=0):
return render_template('404.html',chatlist=chatlist)
lastChats = data["body"].split("####|msgsep|####")
chats = []
for lc in lastChats:
msglist = lc.split("Assistant: ")
msg = [msglist[0][msglist[0].find(":") + 1 :].strip(), msglist[1].strip()]
chats.append({"user": msg[0], "assistant": msg[1]})
data = {"chats": chats, "chat_id": chat_id, "chatlist": chatlist,"chatName":chatName}
return render_template("chat.html", data=data)
if request.method == "POST":
data = request.get_json()
usermsg = data["message"]
chat_id = data["chat_id"]
lastmsgs = db.select(
["body"],
"history",
["usrid = {} and id = {}".format(session["id"], chat_id), False],
)[0]["body"]
lastmsg = "\n".join(lastmsgs.split("####|newmsg|####")[-5:])
prompt = (
"Here is the last conversation between user and assistant : \n"
+ lastmsg
+ "\nRespond to this latest message :\n"
+ session["username"]
+ ": "
+ usermsg
)
f = open("prompt.txt", "r")
sysmsg = f.read()
loadEvent.wait()
# maybe set a timeout
response = llama(prompt=prompt, sys_prompt=sysmsg)
message = response[0]["generated_text"].split(
"<|eot_id|><|start_header_id|>assistant<|end_header_id|>"
)[1]
usermsgformatted = (
session["username"] + ": " + usermsg + "\n" + "Assistant: " + message
)
db.update(
"history",
"body",
lastmsgs + "\n####|msgsep|####\n" + usermsgformatted,
["id=%s", chat_id],
)
message = {"message": message}
return app.response_class(
response=json.dumps(message), status=200, mimetype="application/json"
)
@app.route('/speak',methods=['POST'])
def speak():
data = request.get_json()
text = data['text']
print(text)
if text!= None:
audio = TTS(text,'static/uploads')
audioURL = request.url_root + "/" + audio
response = {'audio':audioURL}
return app.response_class(
response=json.dumps(response), status=200, mimetype="application/json"
)
else:
return app.response_class(
response=json.dumps({"error":"No text provided"}), status=404, mimetype="application/json"
)
@app.route('/delete', methods=['POST'])
def delete():
data = request.get_json()
chat_id = data['chat_id']
context = data['context']
db.delete('history', ["id=%s",(chat_id,)])
if str(session.get('chat_id'))==chat_id:
session.pop("chat_id", None)
if context == "inPage":
return redirect('/newchat')
elif context == "notinPage":
return app.response_class(
response=json.dumps({"chat_id":chat_id}), status=200, mimetype="application/json"
)
@app.route('/edit',methods=['POST'])
def edit():
data = request.get_json()
chat_id = data['chat_id']
context = data['context']
newName = data['name']
db.update('history','name',newName,["id=%s",(chat_id)])
return app.response_class(
response=json.dumps({'chatName':newName})
)
if __name__ == "__main__":
app.run(debug=False)