-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
232 lines (198 loc) · 7.75 KB
/
bot.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
import nltk
from nltk.stem.lancaster import LancasterStemmer
import numpy as np
import tflearn
import random
import pickle
import json
import re
import os
TRAINING_DATA = "bot/training_data"
INTENT_JSON = 'intents.json'
class Bot(object):
def __init__(self, intents, path):
self.path = path
if not path:
self.path = os.path.abspath(os.path.dirname(__file__))
self.stemmer = LancasterStemmer()
self.intents = intents
self.create_dataset()
self.data = pickle.load(open(os.path.join(self.path, TRAINING_DATA), "rb"))
self.words = self.data['words']
self.classes = self.data['classes']
self.train_x = self.data['train_x']
self.train_y = self.data['train_y']
self.last_response = None
self.model = None
def create_model(self):
net = tflearn.input_data(shape=[None, len(self.train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(self.train_y[0]), activation='softmax')
net = tflearn.regression(net)
self.model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
def create_dataset(self):
words, classes, documents = self.parse_intents()
train_x, train_y = self.training_data(words, classes, documents)
self.pickle_data(words, classes, train_x, train_y)
def train_model(self):
self.model.fit(self.train_x, self.train_y, n_epoch=1000, batch_size=8, show_metric=True)
model_path = os.path.join(self.path, 'bot/model.tflearn')
self.model.save(model_path)
def load_model(self):
model_path = os.path.join(self.path, 'bot/model.tflearn')
self.model.load(model_path)
def pickle_data(self, words, classes, train_x, train_y):
print('Pickling data')
train_data_path = os.path.join(self.path, 'bot/trainin_data')
try:
pickle.dump({
'words': words, 'classes': classes, 'train_x': train_x, 'train_y': train_y
}, open(train_data_path, "wb"))
except:
print('Couldnt pickle data')
def clean_sentence(self, sentence):
# tokenize pattern
sentence_words = nltk.word_tokenize(sentence)
# stem words
sentence_words = [self.stemmer.stem(word.lower()) for word in sentence_words]
return sentence_words
def bow(self, sentence, words):
"""Returns a bag of words array containing
0 or 1 for each word in the bag that exists in the sentence.
Returns:
array(int)
"""
# tokenize the pattern
sentence_words = self.clean_sentence(sentence)
# bag of words
bag = [0] * len(words)
for s in sentence_words:
for i, word in enumerate(words):
if word == s:
bag[i] = 1
return (np.array(bag))
def classify(self, query):
"""Classify a query/sentence.
Returns:
tuple (intent, probability)
"""
error_threshold = 0.25
# get probabilities from model
results = self.model.predict([self.bow(query, self.words)])[0]
# filter out predictions below threshold
results = [[i, r] for i, r in enumerate(results) if r > error_threshold]
results.sort(key=lambda x: x[1], reverse=True)
classified = []
for r in results:
classified.append((self.classes[r[0]], r[1]))
return classified
def get_emoji(self, query):
"""Retrieve an emoji from a string.
Returns:
unicode str representation of emoji.
"""
emoji = None
try:
emoji = re.findall(r'[^\w\s,]', query)[0]
except:
pass
return emoji
def response(self, query):
"""Retrieve and return response from the NL bot.
Returns:
triple of (str, str, str) -> (tag, response, emoji)
"""
query = query.replace('?', '')
results = self.classify(query)
# if we have a classification then find the matching intent tag
if not results:
return
emoji = self.get_emoji(query)
while results:
for i in self.intents['intents']:
# find a tag matching the first result
if i['tag'] == results[0][0]:
# a random response from the intent
response = random.choice(i['responses'])
return i['tag'], response, emoji
def parse_intents(self):
"""Parse intents from provided json intent file containing intents, patterns, tags.
Returns:
triple of (array, array, array) -> (words, classes, documents)
"""
words = []
classes = []
documents = []
ignore_words = ['?']
# loop through each sentence in our intents patterns
for intent in self.intents['intents']:
for pattern in intent['patterns']:
# tokenize each word in the sentence
w = nltk.word_tokenize(pattern)
# add to our words list
words.extend(w)
# add to documents in our corpus
documents.append((w, intent['tag']))
# add to our classes list
if intent['tag'] not in classes:
classes.append(intent['tag'])
# stem and lower each word and remove duplicates
words = [self.stemmer.stem(w.lower()) for w in words if w not in ignore_words]
words = sorted(list(set(words)))
# remove duplicates
classes = sorted(list(set(classes)))
print(len(documents), "documents")
print(len(classes), "classes", classes)
print(len(words), "unique stemmed words", words)
return words, classes, documents
def training_data(self, words, classes, documents):
"""Generate training data for the model to train on.
Returns:
tuple (np.array, np.array) -> train_x, train_y
"""
# create our training data
training = []
# create an empty array for our output
output_empty = [0] * len(classes)
# training set, bag of words for each sentence
for doc in documents:
# initialize our bag of words
bag = []
# list of tokenized words for the pattern
pattern_words = doc[0]
# stem each word
pattern_words = [self.stemmer.stem(word.lower()) for word in pattern_words]
# create our bag of words array
for w in words:
bag.append(1) if w in pattern_words else bag.append(0)
# output is a '0' for each tag and '1' for current tag
output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1
training.append([bag, output_row])
# shuffle our features and turn into np.array
random.shuffle(training)
training = np.array(training)
# create train and test lists
train_x = list(training[:, 0])
train_y = list(training[:, 1])
return train_x, train_y
def load_intents():
with open(INTENT_JSON) as json_data:
return json.load(json_data)
def main():
basedir = os.path.abspath(os.path.dirname(__file__))
intents = load_intents()
bot = Bot(intents, basedir)
bot.create_model()
bot.train_model()
# Test intents
print(bot.response('im feeling pretty happy'))
print(bot.response('im so sad'))
print(bot.response('im feeling eager'))
print(bot.response('lol im shookt'))
print(bot.response('im feeling very tired and sleepy'))
print(bot.response('my favourite emoji 👺'))
print(bot.response('what is my favourite'))
if __name__ == '__main__':
main()