/
main.py
311 lines (262 loc) · 9.73 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
# things we need for NLP
import nltk
from nltk.stem.lancaster import LancasterStemmer
from tensorflow.python.framework import ops
import directory
import wordCorrection
# things we need for Tensorflow
import numpy as np
import tflearn
import tensorflow as tf
import random
import requests
from io import BytesIO
import PyPDF2
# import our chat-bot intents file
import json
#=====================================Loading the intents and training the model=============================
stemmer = LancasterStemmer()
with open('intents.json') as json_data:
intents = json.load(json_data)
words = []
labels = []
documents = []
ignore_words = ['?']
# loop through each sentence in our intents patterns
for intent in 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 labels list
if intent['tag'] not in labels:
labels.append(intent['tag'])
# stem and lower each word and remove duplicates
words = [stemmer.stem(w.lower()) for w in words if w not in ignore_words]
words = sorted(list(set(words)))
# remove duplicates
labels = sorted(list(set(labels)))
# print (len(docs_x), "documents")
# print (len(labels), "labels", labels)
# print (len(words), "unique stemmed words", words)
# create our training data
training = []
output = []
# create an empty array for our output
output_empty = [0] * len(labels)
# 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 = [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[labels.index(doc[1])] = 1
training.append([bag, output_row])
# shuffle our features and turn into np.array
random.shuffle(training)
training = np.array(training,dtype=object)
# create train and test lists
train_x = list(training[:,0])
train_y = list(training[:,1])
# reset underlying graph data
ops.reset_default_graph()
# Build neural network
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)
# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
# Start training (apply gradient descent algorithm)
model.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True)
model.save('model.tflearn')
def bag_of_words(s,words):
bag = [0 for _ in range(len(words))]
s_words = nltk.word_tokenize(s)
s_words = [stemmer.stem(word.lower()) for word in s_words]
for se in s_words:
for i,w in enumerate(words):
if w ==se:
bag[i] = 1
return np.array(bag)
#===========================fetching professor's details===================================
def read_pdf(url):
response = requests.get(url)
pdf_file = BytesIO(response.content)
pdf_reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text += page.extract_text()
return text
# url = "https://www.pvamu.edu/sites/hb2504/cvs/All/amahmed.pdf"
def get_professor_details(url):
text = read_pdf(url)
# def getOffice_info(text):
with open('repository.txt','w') as repo:
repo.write(text)
with open('repository.txt','r') as repo:
for line in repo:
if "Office Location" in line:
return line
#================================Run the chatbot=============================================
def to_camel_case(text):
words = text.lower().split()
return words[0] + ''.join(word.capitalize() for word in words[1:])
# def correctSentence(inp):
# corr_inp = wordCorrection.autocorrect_sentence(inp)
# if corr_inp==inp:
# results = model.predict([bag_of_words(inp,words)])
# result_index = np.argmax(results)
# tag = labels[result_index]
# return tag
# else:
# print (f'do you mean "{corr_inp}" ?')
# res = input("You: ")
# if res[0].lower()=='y':
# results = model.predict([bag_of_words(corr_inp,words)])
# result_index = np.argmax(results)
# tag = labels[result_index]
# return tag
# else:
# print ("please ask your question again")
# inp= input("You: ")
# return correctSentence(inp)
# def response_tag(tag):
# for tg in intents['intents']:
# if tg['tag']==tag:
# responses = tg['responses']
# return random.choice(responses)
import tkinter as tk
def correctSentence(inp):
corr_inp = wordCorrection.autocorrect_sentence(inp)
if corr_inp==inp:
results = model.predict([bag_of_words(inp,words)])
result_index = np.argmax(results)
tag = labels[result_index]
return tag
else:
# print (f'do you mean "{corr_inp}" ?')
chat_window.config(state=tk.NORMAL)
chat_window.insert(tk.END, f'do you mean "{corr_inp}" ?' + "\n\n")
res = entry_box.get()
if res[0].lower()=='y':
results = model.predict([bag_of_words(corr_inp,words)])
result_index = np.argmax(results)
tag = labels[result_index]
return tag
else:
# print ("please ask your question again")
chat_window.config(state=tk.NORMAL)
chat_window.insert(tk.END, "please ask your question again" + "\n\n")
inp = entry_box.get()
correctSentence(inp)
# def chat():
# print ("Hello, how may i help you today?")
# while True:
# inp = input("You: ")
# if inp.lower() == 'quit':
# break
# tag = correctSentence(inp)
# # if corr_inp==inp:
# # results = model.predict([bag_of_words(inp,words)])
# # result_index = np.argmax(results)
# # tag = labels[result_index]
# # else:
# # print (f'do you mean "{corr_inp}" ?')
# # res = input("You: ")
# # if res[0].lower()=='y':
# # results = model.predict([bag_of_words(corr_inp,words)])
# # result_index = np.argmax(results)
# # tag = labels[result_index]
# # else:
# # print ("please ask your question again")
# # inp= input("You: ")
# # correctSentence(inp,corr_inp)
# # results = model.predict([bag_of_words(inp,words)])
# # result_index = np.argmax(results)
# # tag = labels[result_index]
# # print (response_tag(tag))
# #===========
# for tg in intents['intents']:
# if tg['tag']==tag:
# responses = tg['responses']
# print (random.choice(responses))
# # return random.choice(responses)
# chat()
def send_message(event=None):
# get user input
user_message = entry_box.get()
# clear input box
entry_box.delete(0, tk.END)
# display user message in chat window
chat_window.config(state=tk.NORMAL)
chat_window.insert(tk.END, "You: " + user_message + "\n\n")
tag = correctSentence(user_message)
responses = ""
for tg in intents['intents']:
if tg['tag']==tag:
responses = tg['responses']
chatbot_response = (random.choice(responses))
chat_window.config(state=tk.DISABLED)
# get chatbot response
chatbot_message = chatbot_response
# display chatbot response in chat window
chat_window.config(state=tk.NORMAL)
chat_window.insert(tk.END, "PantherBot: " + chatbot_message + "\n\n")
chat_window.config(state=tk.DISABLED)
# scroll chat window to bottom
chat_window.see(tk.END)
# def send_message(event=None):
# # get user input
# user_message = entry_box.get()
# # clear input box
# entry_box.delete(0, tk.END)
# # display user message in chat window
# chat_window.config(state=tk.NORMAL)
# chat_window.insert(tk.END, "You: " + user_message + "\n\n")
# tag = correctSentence(user_message)
# for tg in intents['intents']:
# if tg['tag']==tag:
# responses = tg['responses']
# chatbot_response = (random.choice(responses))
# chat_window.config(state=tk.DISABLED)
# # get chatbot response
# chatbot_message = chatbot_response
# # display chatbot response in chat window
# chat_window.config(state=tk.NORMAL)
# chat_window.insert(tk.END, "PantherBot: " + chatbot_message + "\n\n")
# chat_window.config(state=tk.DISABLED)
# # scroll chat window to bottom
# chat_window.see(tk.END)
# create tkinter window
window = tk.Tk()
window.title("Chatbot")
# create chat window
chat_window = tk.Text(window, height=20, width=50)
chat_window.pack(fill=tk.BOTH, expand=True)
chat_window.config(state=tk.DISABLED)
chat_window.pack()
chat_window.config(state=tk.NORMAL)
chat_window.insert(tk.END, "PantherBot: Hi, I'm PantherBot, your assistance. How can I help you today?" + "\n\n")
chat_window.config(state=tk.DISABLED)
# create entry box for user input
entry_box = tk.Entry(window)
entry_box.bind("<Return>", send_message)
entry_box.pack()
# create send button
send_button = tk.Button(window, text="Send", command=send_message)
send_button.pack()
# start tkinter event loop
window.mainloop()