-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
110 lines (77 loc) · 2.62 KB
/
api.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
import datetime
import json
from difflib import SequenceMatcher
from db import db
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
class quiz:
@staticmethod
def get_default_data():
questions = json.loads(open('questions.json').read())
return questions
@staticmethod
def begin_start(user_id):
quiz.save_user(user_id, quiz.get_default_data())
return
@staticmethod
def get_user(user_id):
user = db.get_user(user_id)
if user is None:
user = quiz.save_user(user_id, quiz.get_default_data())
user['questions'] = json.loads(user['questions'])
return user
@staticmethod
def save_user(user_id, data):
d = data
d['questions'] = json.dumps(data['questions'], ensure_ascii=False)
user = db.save_user(user_id, data)
return user
@staticmethod
def answer_success(user_id):
user = quiz.get_user(user_id)
if user['step'] in user['questions']:
user['step'] = str(int(user['step'])+1)
user['errors'] = '0'
quiz.save_user(user_id, user)
return
@staticmethod
def answer_error(user_id):
user = quiz.get_user(user_id)
user['errors'] = int(user['errors'])+1
helps = user['questions'][user['step']]['help']
if user['errors'] >= len(helps):
user['errors'] = len(helps)
user['errors'] = str(user['errors'])
quiz.save_user(user_id, user)
return
@staticmethod
def next_step(user_id, success=False):
user = quiz.get_user(user_id)
next_text = ''
video = None
if success:
if user['step'] in user['questions']:
next_step = next_text = user['questions'][user['step']]
next_text = next_step['question']
if 'video' in next_step:
video = next_step['video']
else:
next_text = user['final']
else:
helps = user['questions'][user['step']]['help']
for i in range(0, int(user['errors'])):
next_text += helps[i]+'\n'
return next_text, video
@staticmethod
def check_answer(user_id, answer):
user = quiz.get_user(user_id)
answer = answer.lower()
is_good = False
if user['step'] in user['questions']:
good_answer = user['questions'][user['step']]['answer']
good_answer = good_answer.lower()
if similar(answer, good_answer) > 0.65:
is_good = True
else:
is_good = True
return is_good