-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
565 lines (390 loc) · 20.1 KB
/
main.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
import os
from flask import Flask, render_template, redirect, request, session
import json
import os
from datetime import datetime
from base64 import b64encode
import simplejson as json
app = Flask(__name__)
# VARIABLES
amount_place = 2
id = 0
key = ''
secret_key = '=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD, =EF=BF=BD=EF=BF=BD =EF=BF==BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF==BD =EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD =EF=BF=BD=EF==BF=BD =EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD=EF==BF=BD=EF=BF=BD=EF=BF=BD=EF=BF=BD'
app.config['SECRET_KEY'] = os.urandom(32)
# Функции для back-end
def top(users_data):
points_list = list()
dict_users = {
# user: points
}
for user in users_data:
dict_users[users_data[user]["username"]] = users_data[user]["points"]
points_list.append(users_data[user]["points"])
top_place = list()
# количество мест
for i in range(len(users_data)):
# Наивысшее место
the_most_place = max(points_list)
points_list.remove(the_most_place)
for user in dict_users:
if dict_users[user] == the_most_place:
name_1st = user
top_place.append(name_1st)
del dict_users[user]
break
print("top_places", top_place)
return top_place
def save_intent(example, responce):
try:
# Добавление опыта пользователю
print("Experience")
with open('Data-Bases/Data-users.json', 'r', encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
user_data = data_all_users["users"]
user_data[id]["points"] += 3
with open('Data-Bases/Data-users.json', 'w', encoding='utf-8') as file:
data = {
"users": user_data
}
json.dump(data, file, sort_keys = True)
print("INTENT")
# Добавление предложенных пользователем intent и responce
with open("Data-Bases/Data_Base.json", "r", encoding='utf-8') as file:
data = json.load(file)
data_intents = data["intents"]
name_topic = f"{id}_{str(user_data[id]['points'])}"
data_intents[name_topic] = {}
data_intents[name_topic]["examples"] = example.split("/")
data_intents[name_topic]["responses"] = responce.split("/")
print(data_intents[name_topic])
with open('Data-Bases/Data_Base.json', 'w', encoding='utf-8') as file:
data = {
"intents": data_intents
}
json.dump(data, file, sort_keys = True)
print("END INTENT")
except Exception as _Ex:
print("Warning in saving", _Ex)
return False
return True
# Функции для браузера
# main
@app.route("/<int:id>", methods=["GET"])
@app.route("/", methods=["GET"])
def main_page(id=0):
if not session.modified:
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
session.modified = True
print("ID", id)
try:
with open('Data-Bases/Data-Amount.json', 'r', encoding='utf-8') as file:
data_amount = json.load(file)["months"]
for month in data_amount:
print(f"{month} - {data_amount[month]['users']} users - {data_amount[month]['messages']} messages - {data_amount[month]['intents']} intents")
except:
print("WARNING IN OPEN Data-Bases/Data-Amount.json")
return render_template("main.html",data_month=data_amount, id=id, verificat_key=session["verificat_key"])
# Logging
@app.route("/logging/<key>", methods=["GET", "POST"])
def logging_page(key=''):
global top_user
print(f"{key} - {session['verificat_key']}")
if session["verificat_key"] == key:
if not session.modified:
session.modified = True
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
print(f"Logging: Incorrect verificate key\nKey is {key} - {session['verificat_key']}")
if request.method == "POST":
# login-пользователя
login = request.form["login"]
# password-пользователя
password = request.form["password"]
print("Login",login,"\nPASSWORD",password)
try:
# открытие словаря со всеми данными пользователей
with open("Data-Bases/Data-users.json", "r", encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
users_data = data_all_users["users"]
for id in users_data:
if login == users_data[id]["username"]:
if users_data[id]["password"] == password:
# data = users_data[id]
# Вычисление топа
top_user = top(users_data)
print("ID", id)
return redirect(f'/{id}')
return render_template("logging.html", success=False, verificat_key=session["verificat_key"])
except Exception as _Ex:
print("Warning in logging:\n", _Ex)
return render_template("logging.html", success=True, verificat_key=session["verificat_key"])
print(f"Logging: Incorrect verificate key\nKey is {key} - {session['verificat_key']}")
try:
return redirect(f'/{id}')
except:
return redirect(f'/{0}')
# Global Page
@app.route("//create/<key>", methods=["GET","POST"])
@app.route("/<int:id>/create/<key>", methods=["GET","POST"])
def form(id=0, key=''):
print("ID", id)
print(f"{key} - {session['verificat_key']}")
if session["verificat_key"] == key:
if not session.modified:
session.modified = True
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
if id == 0:
return redirect(f'/logging/{session["verificat_key"]}')
# открытие словаря со вsсеми данными пользователей
try:
if request.method == "POST":
topic = request.form["topic"]
example = request.form["example"]
responce = request.form["responce"]
print("TOPIC", topic,"\nEXAMPLE", example,"\nRESPONCE", responce)
if topic != '' and example != '' and responce != '':
#
try:
# Добавление опыта пользователю
print("Experience")
with open('Data-Bases/Data-users.json', 'r', encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
user_data = data_all_users["users"]
user_data[str(id)]["points"] += 3
with open('Data-Bases/Data-users.json', 'w', encoding='utf-8') as file:
data = {
"users": user_data
}
json.dump(data, file, sort_keys = True)
print("INTENT")
# Добавление предложенных пользователем intent и responce
with open("Data-Bases/Data_Base.json", "r", encoding='utf-8') as file:
data = json.load(file)
data_intents = data["intents"]
name_topic = f"{str(id)}_{str(user_data[str(id)]['points'])}"
data_intents[name_topic] = {}
data_intents[name_topic]["examples"] = example
data_intents[name_topic]["responses"] = responce
print(data_intents[name_topic])
with open('Data-Bases/Data_Base.json', 'w', encoding='utf-8') as file:
data = {
"intents": data_intents
}
json.dump(data, file, sort_keys = True)
# Добавление интентов за день
print("Add Intent Count")
with open("Data-Bases/Data-day.json", "r", encoding='utf-8') as file:
data_day = json.load(file)
if f'{datetime.now().strftime("%m%d")}' not in data_day:
data_day[f'{datetime.now().strftime("%m%d")}'] = {}
data_day[f'{datetime.now().strftime("%m%d")}']["intents"] = 0
data_day[f'{datetime.now().strftime("%m%d")}']["users"] = 0
data_day[f'{datetime.now().strftime("%m%d")}']["messages"] = 0
data_day[f'{datetime.now().strftime("%m%d")}']["intents"] += 3
with open('Data-Bases/Data-day.json', 'w', encoding='utf-8') as file:
json.dump(data_day, file, sort_keys = True)
# Добавление интента в data-amount
with open("Data-Bases/Data-Amount.json", "r", encoding='utf-8') as file:
data_day = json.load(file)["months"]
print("Month", datetime.now().strftime("%m"))
print("Data", data_day[f'{datetime.now().strftime("%m")}'])
data_day[f'{datetime.now().strftime("%m")}']["intents"] += 3
with open("Data-Bases/Data-Amount.json", "w", encoding='utf-8') as file:
data = {"months": data_day}
json.dump(data, file, sort_keys = True)
print("END INTENT")
except Exception as _Ex:
print("Warning in saving", _Ex)
return render_template("index.html",id=id, verificat_key=session["verificat_key"])
return redirect(f'/{id}')
return render_template("index.html",id=id, verificat_key=session["verificat_key"])
return render_template("index.html",id=id, verificat_key=session["verificat_key"])
except Exception as _Ex:
print("Warning in Save Intent", _Ex)
return render_template("index.html",id=id, data_user=data,verificat_key=session["verificat_key"])
print(f"Create: Incorrect verificate key\nKey is{key} - {session['verificat_key']}")
return redirect(f'/{id}')
@app.route("//profile/<key>", methods=["GET","POST"])
@app.route("/<int:id>/profile/<key>", methods=["GET"])
def show_profile(id=0, key=''):
print("ID", id)
if session["verificat_key"] == key:
if not session.modified:
session.modified = True
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
if id == 0:
return redirect(f'/logging/{session["verificat_key"]}')
with open("Data-Bases/Data-users.json", "r", encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
users_data = data_all_users["users"]
data = users_data[str(id)]
with open("Data-Bases/Data-users.json", "r", encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
users_data = data_all_users["users"]
top_user = top(users_data)
counter = 0
for user in top_user:
counter += 1
if user == users_data[str(id)]["username"]:
break
return render_template("profile.html",id=id, data_user=data, top_user=top_user[:amount_place], place_num=counter, verificat_key=session["verificat_key"])
print(f"Profile: Incorrect verificate key\nKey is{key} - {session['verificat_key']}")
return redirect(f'/{id}')
@app.route("//about", methods=["GET","POST"])
@app.route("/<int:id>/about", methods=["GET"])
def show_about(id=0):
if not session.modified:
session.modified = True
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
with open("Data-Bases/Data-day.json", "r", encoding='utf-8') as file:
# Весь
data_day = json.load(file)
# Даты нет в словаре
if f'{datetime.now().strftime("%m%d")}' not in data_day:
data_day[f'{datetime.now().strftime("%m%d")}'] = {}
data_day[f'{datetime.now().strftime("%m%d")}']["intents"] = 0
data_day[f'{datetime.now().strftime("%m%d")}']["users"] = 0
data_day[f'{datetime.now().strftime("%m%d")}']["messages"] = 0
if f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}' not in data_day:
data_day[f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}'] = {}
data_day[f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}']["intents"] = 0
data_day[f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}']["users"] = 0
data_day[f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}']["messages"] = 0
with open('Data-Bases/Data-day.json', 'w', encoding='utf-8') as file:
json.dump(data_day, file, sort_keys = True)
current_data = data_day[f'{datetime.now().strftime("%m%d")}']
yesterday_data = data_day[f'{datetime.now().strftime("%m")+str(int(datetime.now().strftime("%d"))-1)}']
print("data_day", current_data)
print("yestaerday_data", yesterday_data)
# Выбираем значки
sign_list = list()
if current_data["messages"] > yesterday_data["messages"]:
sign_list.append("img/uparrow_78484.png")
elif current_data["messages"] < yesterday_data["messages"]:
sign_list.append("img/arrowdown_flech_1539.png")
else:
sign_list.append("img/calculate_equals_icon_194844.png")
if current_data["users"] > yesterday_data["users"]:
sign_list.append("img/uparrow_78484.png")
elif current_data["users"] < yesterday_data["users"]:
sign_list.append("img/arrowdown_flech_1539.png")
else:
sign_list.append("img/calculate_equals_icon_194844.png")
if current_data["intents"] > yesterday_data["intents"]:
sign_list.append("img/uparrow_78484.png")
elif current_data["intents"] < yesterday_data["intents"]:
sign_list.append("img/arrowdown_flech_1539.png")
else:
sign_list.append("img/calculate_equals_icon_194844.png")
with open("Data-Bases/Data-Amount.json", "r", encoding='utf-8') as file:
amount_users = 0
amount_messages = 0
amount_intents = 0
data_months = json.load(file)["months"]
for month in data_months:
amount_users += data_months[month]["users"]
amount_messages += data_months[month]["messages"]
amount_intents += data_months[month]["intents"]
return render_template("about.html",sign_list=sign_list, id=id, amount_intents=amount_intents, amount_users=amount_users, amount_messages=amount_messages, current_data=current_data, yesterday_data=yesterday_data, verificat_key=session["verificat_key"] )
@app.route("//support", methods=["GET","POST"])
@app.route("/<int:id>/support", methods=["GET"])
def show_support(id=0):
if not session.modified:
session.modified = True
session["verificat_key"] = b64encode(os.urandom(1)).decode('utf-8')
return render_template("support.html", id=id, verificat_key=session["verificat_key"])
# Возвращают словари
# Словарь ИНТЕНТОВ
@app.route("/get/Data_Base/<string:key>/", methods=["GET"])
def Get_Data_Base(key):
print("KEY", key)
if key == secret_key:
if request.method == "GET":
try:
with open("Data-Bases/Data_Base.json", "r", encoding="utf-8") as file:
BOT_CONFIG = json.load(file)
return BOT_CONFIG
except Exception as _EX:
return("WARNING ⚠\n"+str(_EX) )
# Словарь Данных Пользователей
@app.route("/get/Data_Users/<string:key>/", methods=["GET", "POST"])
def Get_Data_Users(key):
global data_all_users
print("KEY", key)
if key == secret_key:
if request.method == "POST":
try:
json_file = json.loads(request.get_json())['json']
print("Success get json")
print("REQUEST", json_file)
with open('Data-Bases/Data-users.json', 'w', encoding='utf-8') as file:
json.dump(json_file, file, sort_keys = True)
print("Success save json")
return render_template("json_get.html", data=data_all_users,)
except Exception as _EX:
return "FAIL \n" + str(_EX)
elif request.method == "GET":
try:
with open('Data-Bases/Data-users.json', 'r', encoding='utf-8') as file:
# Весь
data_all_users = json.load(file)
return data_all_users
except Exception as _EX:
return("WARNING ⚠\n"+str(_EX) )
# Словарь Данных за День
@app.route("/get/Data_Day/<string:key>/", methods=["GET", "POST"])
def Get_Data_Day(key):
global data_day
print("KEY", key)
if key == secret_key:
if request.method == "POST":
try:
json_file = json.loads(request.get_json())['json']
print("REQUEST", json_file)
with open("Data-Bases/Data-day.json", "w", encoding='utf-8') as file:
json.dump(json_file, file, sort_keys = True)
return render_template("json_get.html",data=data_day,)
except Exception as _EX:
return "FAIL \n" + str(_EX)
elif request.method == "GET":
try:
with open("Data-Bases/Data-day.json", "r", encoding='utf-8') as file:
data_day = json.load(file)
return data_day
except Exception as _EX:
return("WARNING ⚠\n"+str(_EX) )
# Словарь Данных за Весь период
@app.route("/get/Data_Amount/<string:key>/", methods=["GET", "POST"])
def Get_Data_Amount(key):
global data_amount
print("KEY", key)
if key == secret_key:
if request.method == "POST":
try:
# получаем json-file
# print("1st", type(request.form['json']))
# print("2nd", type(json.loads(request.form['json'])))
json_file = json.loads(request.get_json())['json']
print("REQUEST", json_file)
with open("Data-Bases/Data-Amount.json", "w", encoding='utf-8') as file:
json.dump(json_file, file, sort_keys = True)
return render_template("json_get.html",data=data_amount,)
except Exception as _EX:
return "FAIL \n" + str(_EX)
elif request.method == "GET":
try:
with open("Data-Bases/Data-Amount.json", "r", encoding='utf-8') as file:
data_amount = json.load(file)["months"]
return data_amount
except Exception as _EX:
return("WARNING ⚠\n"+str(_EX) )
# if __name__ == '__main__':
# app.run(debug=True)
if __name__ == "__main__":
print("MAIN")
app.run(host='0.0.0.0', port=80)