-
Notifications
You must be signed in to change notification settings - Fork 27
/
simulate_bot_GAN.py
247 lines (193 loc) · 10.5 KB
/
simulate_bot_GAN.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
# -*- coding: utf-8 -*-
__author__ = 'Oswaldo Ludwig'
__version__ = '1.01'
from keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Dropout, merge
from keras.optimizers import Adam
from keras.models import Model
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.preprocessing import sequence
import keras.backend as K
import numpy as np
np.random.seed(1234) # for reproducibility
import cPickle
import theano
import os.path
import sys
import nltk
import re
import time
from keras.utils import plot_model
word_embedding_size = 100
sentence_embedding_size = 300
dictionary_size = 7000
maxlen_input = 50
maxlen_input_consist = 40
dense_size = 1500
questions_file = 'context_simple'
vocabulary_file = 'vocabulary_movie'
weights_file = 'my_model_weights_bot.h5'
unknown_token = 'something'
file_generated_context = 'generated_context'
file_generated_answer = 'generated_answer'
name_of_computer = 'john'
name = 'john'
depth_of_thinking = 2
threshold_max = 0.65
threshold_min = 0.50
pressure = 4.
bidirec = 0
def greedy_decoder(input):
flag = 0
prob = 1
ans_partial = np.zeros((1,maxlen_input))
ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence)
for k in range(maxlen_input - 1):
ye = model2.predict([input, ans_partial])
yel = ye[0,:]
p = np.max(yel)
mp = np.argmax(ye)
ans_partial[0, 0:-1] = ans_partial[0, 1:]
ans_partial[0, -1] = mp
if mp == 3: # the index of the symbol EOS (end of sentence)
flag = 1
if flag == 0:
prob = prob * p * 1.05
text = ''
for k in ans_partial[0]:
k = k.astype(int)
if k < (dictionary_size-2):
w = vocabulary[k]
text = text + w[0] + ' '
return(text, prob)
def preprocess(raw_word, name):
if raw_word == '':
return ' . '
l1 = ['won’t','won\'t','wouldn’t','wouldn\'t','’m', '’re', '’ve', '’ll', '’s','’d', 'n’t', '\'m', '\'re', '\'ve', '\'ll', '\'s', '\'d', 'can\'t', 'n\'t', 'B: ', 'A: ', ',', ';', '.', '?', '!', ':', '. ?', ', .', '. ,', 'EOS', 'BOS', 'eos', 'bos']
l2 = ['will not','will not','would not','would not',' am', ' are', ' have', ' will', ' is', ' had', ' not', ' am', ' are', ' have', ' will', ' is', ' had', 'can not', ' not', '', '', ' ,', ' ;', ' .', ' ?', ' !', ' :', '? ', '.', ',', '', '', '', '']
l3 = ['-', '_', ' *', ' /', '* ', '/ ', '\"', ' \\"', '\\ ', '--', '...', '. . .']
l4 = ['jeffrey','fred','benjamin','paula','walter','rachel','andy','helen','harrington','kathy','ronnie','carl','annie','cole','ike','milo','cole','rick','johnny','loretta','cornelius','claire','romeo','casey','johnson','rudy','stanzi','cosgrove','wolfi','kevin','paulie','cindy','paulie','enzo','mikey','i\97','davis','jeffrey','norman','johnson','dolores','tom','brian','bruce','john','laurie','stella','dignan','elaine','jack','christ','george','frank','mary','amon','david','tom','joe','paul','sam','charlie','bob','marry','walter','james','jimmy','michael','rose','jim','peter','nick','eddie','johnny','jake','ted','mike','billy','louis','ed','jerry','alex','charles','tommy','bobby','betty','sid','dave','jeffrey','jeff','marty','richard','otis','gale','fred','bill','jones','smith','mickey']
raw_word = raw_word.lower()
raw_word = raw_word.replace(', ' + name_of_computer, '')
raw_word = raw_word.replace(name_of_computer + ' ,', '')
for j, term in enumerate(l1):
raw_word = raw_word.replace(term,l2[j])
for term in l3:
raw_word = raw_word.replace(term,' ')
for term in l4:
raw_word = raw_word.replace(', ' + term, ', ' + name)
raw_word = raw_word.replace(' ' + term + ' ,' ,' ' + name + ' ,')
raw_word = raw_word.replace('i am ' + term, 'i am ' + name_of_computer)
raw_word = raw_word.replace('my name is' + term, 'my name is ' + name_of_computer)
for j in range(30):
raw_word = raw_word.replace('. .', '')
raw_word = raw_word.replace('. .', '')
raw_word = raw_word.replace('..', '')
for j in range(5):
raw_word = raw_word.replace(' ', ' ')
if raw_word[-1] <> '!' and raw_word[-1] <> '?' and raw_word[-1] <> '.' and raw_word[-2:] <> '! ' and raw_word[-2:] <> '? ' and raw_word[-2:] <> '. ':
raw_word = raw_word + ' .'
if raw_word == ' !' or raw_word == ' ?' or raw_word == ' .' or raw_word == ' ! ' or raw_word == ' ? ' or raw_word == ' . ':
raw_word = 'what ?'
return raw_word
def tokenize(sentences):
# Tokenizing the sentences into words:
tokenized_sentences = nltk.word_tokenize(sentences.decode('utf-8'))
index_to_word = [x[0] for x in vocabulary]
word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])
tokenized_sentences = [w if w in word_to_index else unknown_token for w in tokenized_sentences]
X = np.asarray([word_to_index[w] for w in tokenized_sentences])
s = X.size
Q = np.zeros((1,maxlen_input))
if s < (maxlen_input + 1):
Q[0,- s:] = X
else:
Q[0,:] = X[- maxlen_input:]
return Q
# Open files to save the conversation for further training:
qf = open(file_generated_context, 'w')
af = open(file_generated_answer, 'w')
print('Starting the model...')
# *******************************************************************
# Keras model of the chatbot + discriminator:
# *******************************************************************
ad = Adam(lr=0.00005)
input_context = Input(shape=(maxlen_input,), dtype='int32', name='input context')
input_answer = Input(shape=(maxlen_input,), dtype='int32', name='input answer')
if bidirec == 1:
LSTM_encoder_bot = Bidirectional(LSTM(sentence_embedding_size, init= 'lecun_uniform', name = 'encoder bot'))
else:
LSTM_encoder_bot = LSTM(sentence_embedding_size, init= 'lecun_uniform', name = 'encoder bot')
LSTM_decoder_bot = LSTM(sentence_embedding_size, init= 'lecun_uniform', name = 'decoder bot')
if bidirec == 1:
LSTM_encoder_discriminator = Bidirectional(LSTM(sentence_embedding_size, init= 'lecun_uniform'), trainable=False, name = 'encoder discriminator')
else:
LSTM_encoder_discriminator = LSTM(sentence_embedding_size, init= 'lecun_uniform', trainable=False, name = 'encoder discriminator')
LSTM_decoder_discriminator = LSTM(sentence_embedding_size, init= 'lecun_uniform', trainable=False, name = 'decoder discriminator')
if os.path.isfile(weights_file):
Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, trainable=False, name = 'shared')
else:
Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, weights=[embedding_matrix], input_length=maxlen_input, trainable=False, name = 'shared')
word_embedding_context = Shared_Embedding(input_context)
context_embedding_bot = LSTM_encoder_bot(word_embedding_context)
word_embedding_answer = Shared_Embedding(input_answer)
answer_embedding_bot = LSTM_decoder_bot(word_embedding_answer)
context_embedding_discriminator = LSTM_encoder_discriminator(word_embedding_context)
answer_embedding_discriminator = LSTM_decoder_discriminator(word_embedding_answer)
merge_layer = merge([context_embedding_bot, answer_embedding_bot], mode='concat', concat_axis=1, name = 'concatenation bot')
out = Dense(dictionary_size/2, activation="relu", name = 'bot')(merge_layer)
out = Dense(dictionary_size, activation="softmax", name = 'decision bot')(out)
loss = merge([context_embedding_discriminator, answer_embedding_discriminator, out], mode='concat', concat_axis=1, name = 'concatenation discriminator')
loss = Dense(1, activation="sigmoid", trainable=False, name = 'discriminator output')(loss)
model = Model(input=[input_context, input_answer], output = [loss])
if os.path.isfile(weights_file):
print('loading the bot weights...')
model.load_weights(weights_file)
# *******************************************************************
# Only the model of the chatbot:
# *******************************************************************
input_context2 = Input(shape=(maxlen_input,), dtype='int32', name='input context')
input_answer2 = Input(shape=(maxlen_input,), dtype='int32', name='input answer')
if bidirec == 1:
LSTM_encoder_bot2 = Bidirectional(LSTM(sentence_embedding_size, init= 'lecun_uniform', weights=model.layers[3].get_weights(), name = 'encoder bot'))
else:
LSTM_encoder_bot2 = LSTM(sentence_embedding_size, init= 'lecun_uniform', weights=model.layers[3].get_weights(), name = 'encoder bot')
LSTM_decoder_bot2 = LSTM(sentence_embedding_size, init= 'lecun_uniform', weights=model.layers[4].get_weights(), name = 'decoder bot')
Shared_Embedding2 = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, trainable=False, weights=model.layers[2].get_weights(), name = 'shared')
word_embedding_context2 = Shared_Embedding2(input_context2)
context_embedding_bot2 = LSTM_encoder_bot2(word_embedding_context2)
word_embedding_answer2 = Shared_Embedding2(input_answer2)
answer_embedding_bot2 = LSTM_decoder_bot2(word_embedding_answer2)
merge_layer2 = merge([context_embedding_bot2, answer_embedding_bot2], mode='concat', concat_axis=1, name = 'concatenation bot')
out2 = Dense(dictionary_size/2, activation="relu", weights=model.layers[6].get_weights(), name = 'bot')(merge_layer2)
out2 = Dense(dictionary_size, activation="softmax", weights=model.layers[9].get_weights(), name = 'decision bot')(out2)
model2 = Model(input=[input_context2, input_answer2], output = [out2])
# Loading the data:
vocabulary = cPickle.load(open(vocabulary_file, 'rb'))
index_to_word = [x[0] for x in vocabulary]
word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)])
# Loading the context file:
print ("Reading the context data...")
q = open(questions_file, 'r')
questions = q.read()
questions = [p for p in questions.split('\n')]
print(questions[0])
for text in questions:
que = preprocess(text, name_of_computer)
Q = tokenize(que)
predout, prob = greedy_decoder(Q[0:1])
start_index = predout.find('EOS')
text_context = preprocess(predout[0:start_index], name)
# append generated text_context:
qf.write(text_context + ' \n')
print('context: %s'%text_context)
que = preprocess(text_context, name_of_computer)
Q = tokenize(que)
predout, prob = greedy_decoder(Q[0:1])
start_index = predout.find('EOS')
text_answer = preprocess(predout[0:start_index], name)
# append generated answer:
af.write(text_answer + ' \n')
print('answer: %s'%text_answer)
qf.close()
af.close()