├── data.pickle
├── img
├── bot.png
└── gui.png
├── requirements.txt
├── models
├── chatbot-model.tflearn.index
├── chatbot-model.tflearn.meta
├── chatbot-model.tflearn.data-00000-of-00001
└── checkpoint
├── PyAudio-0.2.11-cp37-cp37m-win_amd64.whl
├── dataset
└── dataset.json
├── README.md
├── chatbot.py
├── trainModel.py
├── gui.py
├── textChatbot.py
└── voiceBot.py
/data.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/data.pickle
--------------------------------------------------------------------------------
/img/bot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/img/bot.png
--------------------------------------------------------------------------------
/img/gui.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/img/gui.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | nltk==3.5
2 | numpy==1.18.1
3 | tflearn==0.3.2
4 | tensorflow==1.15.2
--------------------------------------------------------------------------------
/models/chatbot-model.tflearn.index:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/models/chatbot-model.tflearn.index
--------------------------------------------------------------------------------
/models/chatbot-model.tflearn.meta:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/models/chatbot-model.tflearn.meta
--------------------------------------------------------------------------------
/PyAudio-0.2.11-cp37-cp37m-win_amd64.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/PyAudio-0.2.11-cp37-cp37m-win_amd64.whl
--------------------------------------------------------------------------------
/models/chatbot-model.tflearn.data-00000-of-00001:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/amolikvivian/AI-NLP-Chatbot/HEAD/models/chatbot-model.tflearn.data-00000-of-00001
--------------------------------------------------------------------------------
/models/checkpoint:
--------------------------------------------------------------------------------
1 | model_checkpoint_path: "C:\\Users\\Asus\\Desktop\\nlp\\main\\models\\chatbot-model.tflearn"
2 | all_model_checkpoint_paths: "C:\\Users\\Asus\\Desktop\\nlp\\main\\models\\chatbot-model.tflearn"
3 |
--------------------------------------------------------------------------------
/dataset/dataset.json:
--------------------------------------------------------------------------------
1 | {"intents": [
2 | {"tag": "greeting",
3 | "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day", "Whats up"],
4 | "responses": ["Hi there, how can I help?"],
5 | "context_set": ""
6 | },
7 | {"tag": "goodbye",
8 | "patterns": ["bye", "See you later", "Goodbye", "I am Leaving", "Have a Good day"],
9 | "responses": ["Farewell, hope I was of help! :)"],
10 | "context_set": ""
11 | },
12 | {"tag": "identity",
13 | "patterns": ["who are you?", "what are you", ""],
14 | "responses": ["I am an AI Chatbot for O2i, my work is to talk to you after analyzing what you have asked me and give you information about us."],
15 | "context_set": ""
16 | },
17 | {"tag": "information",
18 | "patterns": ["what is Oxygen to Innovation?", "what do you do at Oxygen to Innovation", "what is done at this company?"],
19 | "responses": ["I am an AI Chatbot, my work is to talk to you after analyzing what you have asked me. I can be programmed."],
20 | "context_set": ""
21 | },
22 | {"tag": "time",
23 | "patterns": ["what are your timings?", "when are you open?"],
24 | "responses": ["The visiting and meeting hours for the office space are from 9 AM to 6 PM"],
25 | "context_set": ""
26 | }
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AI-NLP-Chatbot
2 |
3 | An NLP based Chatbot over a simple fully connected neural network architecture using Tensorflow and tflearn. Trained over a custom dataset specified in the JSON file.
4 |
5 | ## Prerequisites
6 |
7 | Run **`pip install -r requirements.txt`** in your terminal to install all required libraries
8 |
9 | ## Dataset
10 |
11 | The **`dataset.json`** contains the intents on which the model is trained. Each pattern (sentence) and response is given a particular tag. The model classifies each input sentence under a tag and gives out a random answer corresponding to that tag. The json file can be formatted according to the user's requirements.
12 |
13 | ## PyAudio
14 |
15 | In Python versions above 3.6 PyAudio is not a supported library and installing PyAudio directly using
`pip install pyaudio` fails and needs to be installed separately.
16 |
17 | * Windows
18 | For that, individually install the wheel file given (this is for Python 3.7, find suitable wheel files [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio)) writing the following line in your terminal.
19 | **`pip install <.wh file name>`**
20 |
21 | * Ubuntu/Linux
22 | **`$ sudo apt-get install python3-pyaudio`**
23 |
24 | ## Execute Code
25 |
26 | * Run **`trainModel.py`** to train the Fully Connected Network on the dataset. You can change the number of epochs or layers accordingly, the current architecture gave good results with a ~95% accuracy on predicting tags.
27 |
28 | * Run **`textChatbot.py`** for text based chatbot with GUI incorporated
29 | * Run **`voiceBot.py`** for voice recognition based chatbot
30 |
31 | ## GUI Snippet
32 |
33 |
34 |
--------------------------------------------------------------------------------
/chatbot.py:
--------------------------------------------------------------------------------
1 | import json
2 | import nltk
3 | import random
4 | import pickle
5 | import tflearn
6 | import numpy as np
7 | import tensorflow as tf
8 | from nltk.stem.lancaster import LancasterStemmer
9 |
10 | #Initializing Lancaster Stemmer
11 | stemmer = LancasterStemmer()
12 |
13 | #Loading dataset
14 | with open('dataset/dataset.json') as file:
15 | data = json.load(file)
16 |
17 | with open('data.pickle', 'rb') as f:
18 | words, labels, train, output = pickle.load(f)
19 |
20 |
21 | #Building network
22 | net = tflearn.input_data(shape = [None, len(train[0])])
23 | net = tflearn.fully_connected(net, 8)
24 | net = tflearn.fully_connected(net, 8)
25 | net = tflearn.fully_connected(net, len(output[0]), activation = 'softmax')
26 | net = tflearn.regression(net)
27 |
28 | model = tflearn.DNN(net)
29 |
30 | #Loading Model
31 | model.load('models/chatbot-model.tflearn')
32 |
33 |
34 | def bag_of_words(s, words):
35 |
36 | bag = [0 for _ in range(len(words))]
37 |
38 | s_words = nltk.word_tokenize(s)
39 | s_words = [stemmer.stem(word.lower()) for word in s_words]
40 |
41 | for se in s_words:
42 | for i, w in enumerate(words):
43 | if(w == se):
44 | bag[i] = 1
45 |
46 | return np.array(bag)
47 |
48 |
49 | def chat(inputText):
50 |
51 | print('[INFO] Start talking...(type quit to exit)')
52 |
53 | while True:
54 |
55 | inp = inputText
56 |
57 | #Type quit to exit
58 | if inp.lower() == 'quit':
59 | break
60 |
61 | #Predicting input sentence tag
62 | predict = model.predict([bag_of_words(inp, words)])
63 | predictions = np.argmax(predict)
64 |
65 | tag = labels[predictions]
66 | #Printing response
67 | for t in data['intents']:
68 | #print(t['tag'])
69 | if t['tag'] == tag:
70 | responses = t['responses']
71 |
72 | outputText = random.choice(responses)
73 | return outputText
74 |
--------------------------------------------------------------------------------
/trainModel.py:
--------------------------------------------------------------------------------
1 | import json
2 | import nltk
3 | import random
4 | import pickle
5 | import tflearn
6 | import numpy as np
7 | import tensorflow as tf
8 | from nltk.stem.lancaster import LancasterStemmer
9 |
10 | #Initializing Lancaster Stemmer
11 | stemmer = LancasterStemmer()
12 |
13 | #Loading dataset
14 | with open('dataset/dataset.json') as f:
15 | data = json.load(f)
16 |
17 | try:
18 | with open('data.pickle', 'rb') as file:
19 | words, labels, train, output = pickle.load(file)
20 |
21 | except:
22 |
23 | words = []
24 | x_docs = [] #Patterns - Sentences
25 | y_docs = [] #Tags for patterns
26 | labels = []
27 |
28 | #Looping over all data in json file as dictionaries
29 | for intent in data['intents']:
30 |
31 | #Looping over the patterns - input sentences
32 | for pattern in intent['patterns']:
33 |
34 | #Tokenizing each word in each pattern sentences
35 | tokenizedWords = nltk.word_tokenize(pattern)
36 |
37 | #Extending words list with lists of tokens
38 | words.extend(tokenizedWords)
39 |
40 | #Appending docs lists with sentence and respective tag
41 | x_docs.append(tokenizedWords)
42 | y_docs.append(intent['tag'])
43 |
44 | #Appending labels list with tags
45 | if(intent['tag'] not in labels):
46 | labels.append(intent['tag'])
47 |
48 | #Sorting labels
49 | labels = sorted(labels)
50 |
51 | #Stemming words and sorting - Stemming refers to findin the root of every word
52 | words = [stemmer.stem(w.lower()) for w in words if w not in '?']
53 | words = sorted(list(set(words)))
54 |
55 | train = []
56 | output = []
57 |
58 | #Creating a Bag of Words - One Hot Encoding
59 | out_empty = [0 for _ in range(len(labels))]
60 | for x, doc in enumerate(x_docs):
61 | bag = []
62 | stemmedWords = [stemmer.stem(w) for w in doc]
63 |
64 | #Marking word index as 1
65 | for w in words:
66 | if w in stemmedWords:
67 | bag.append(1)
68 | else:
69 | bag.append(0)
70 |
71 | outputRow = out_empty[:]
72 | outputRow[labels.index(y_docs[x])] = 1
73 |
74 | train.append(bag)
75 | output.append(outputRow)
76 |
77 | #Converting data into numpy array
78 | train = np.array(train)
79 | output = np.array(output)
80 |
81 | #Saving data
82 | with open('data.pickle', 'wb') as f:
83 | pickle.dump((words, labels, train, output), f)
84 |
85 | #Building network
86 | net = tflearn.input_data(shape = [None, len(train[0])])
87 | net = tflearn.fully_connected(net, 8)
88 | net = tflearn.fully_connected(net, 8)
89 | net = tflearn.fully_connected(net, len(output[0]), activation = 'softmax')
90 | net = tflearn.regression(net)
91 |
92 | model = tflearn.DNN(net)
93 |
94 | print('[INFO] Training Model...')
95 |
96 | #Training model
97 | model.fit(train, output, n_epoch = 400, batch_size = 8, show_metric = True)
98 |
99 | #Saving model weights
100 | model.save('models/chatbot-model.tflearn')
101 |
102 | print('[INFO] Model successfully trained')
103 |
104 | '''
105 | def bag_of_words(s, words):
106 |
107 | bag = [0 for _ in range(len(words))]
108 |
109 | s_words = nltk.word_tokenize(s)
110 | s_words = [stemmer.stem(word.lower()) for word in s_words]
111 |
112 | for se in s_words:
113 | for i, w in enumerate(words):
114 | if(w == se):
115 | bag[i] = 1
116 |
117 | return np.array(bag)
118 |
119 | def chat():
120 | print('[INFO] Start talking...(type quit to exit)')
121 | while True:
122 | inp = input('You: ')
123 |
124 | #Type quit to exit
125 | if inp.lower() == 'quit':
126 | break
127 |
128 | #Predicting input sentence tag
129 | predict = model.predict([bag_of_words(inp, words)])
130 | predictions = np.argmax(predict)
131 |
132 | tag = labels[predictions]
133 | #Printing response
134 | for t in data['intents']:
135 | #print(t['tag'])
136 | if t['tag'] == tag:
137 | responses = t['responses']
138 |
139 | outputText = random.choice(responses)
140 | print (outputText)
141 |
142 | chat()
143 | '''
144 |
--------------------------------------------------------------------------------
/gui.py:
--------------------------------------------------------------------------------
1 | import time
2 | import tkinter.messagebox
3 | from tkinter import *
4 |
5 | DIMS="500x500"
6 |
7 | class ChatInterface(Frame):
8 |
9 | def __init__(self, master=None):
10 | Frame.__init__(self, master)
11 | self.master = master
12 |
13 | #Default background setting
14 | self.tl_bg = "#EEEEEE"
15 | self.tl_bg2 = "#EEEEEE"
16 | self.tl_fg = "#000000"
17 | self.font = "Verdana 10"
18 |
19 | #Menu bar
20 | menu = Menu(self.master)
21 | self.master.config(menu=menu, bd=5)
22 |
23 | #File
24 | file = Menu(menu, tearoff=0)
25 | menu.add_cascade(label="File", menu=file)
26 |
27 | #Clear chat option
28 | file.add_command(label="Clear Chat", command=self.clear_chat)
29 |
30 | #Exit chatbot option
31 | file.add_command(label="Exit",command=self.chatexit)
32 |
33 | #Preferences option
34 | options = Menu(menu, tearoff=0)
35 | menu.add_cascade(label="Preferences", menu=options)
36 |
37 | #Fonts
38 | font = Menu(options, tearoff=0)
39 | options.add_cascade(label="Font", menu=font)
40 | font.add_command(label="Default",command=self.font_change_default)
41 | font.add_command(label="System",command=self.font_change_system)
42 |
43 | #Theme
44 | color_theme = Menu(options, tearoff=0)
45 | options.add_cascade(label="Theme", menu=color_theme)
46 | color_theme.add_command(label="Default",command=self.color_theme_default)
47 | color_theme.add_command(label="Blue",command=self.color_theme_dark_blue)
48 | color_theme.add_command(label="Hacker",command=self.color_theme_hacker)
49 |
50 | help_option = Menu(menu, tearoff=0)
51 | menu.add_cascade(label="About", menu=help_option)
52 | help_option.add_command(label="About Chatbot", command=self.msg)
53 |
54 | self.text_frame = Frame(self.master, bd=6)
55 | self.text_frame.pack(expand=True, fill=BOTH)
56 |
57 | #Scrollbar for text box
58 | self.text_box_scrollbar = Scrollbar(self.text_frame, bd=0)
59 | self.text_box_scrollbar.pack(fill=Y, side=RIGHT)
60 |
61 | #Contains messages
62 | self.text_box = Text(self.text_frame, yscrollcommand=self.text_box_scrollbar.set, state=DISABLED,
63 | bd=1, padx=6, pady=6, spacing3=8, wrap=WORD, bg=None, font="Verdana 10", relief=GROOVE,
64 | width=10, height=1)
65 | self.text_box.pack(expand=True, fill=BOTH)
66 | self.text_box_scrollbar.config(command=self.text_box.yview)
67 |
68 | #Frame containing user entry field
69 | self.entry_frame = Frame(self.master, bd=1)
70 | self.entry_frame.pack(side=LEFT, fill=BOTH, expand=True)
71 |
72 | #Entry field
73 | self.entry_field = Entry(self.entry_frame, bd=1, justify=LEFT)
74 | self.entry_field.pack(fill=X, padx=6, pady=6, ipady=3)
75 | #self.users_message = self.entry_field.get()
76 |
77 | #Frame containing send button and emoji button
78 | self.send_button_frame = Frame(self.master, bd=0)
79 | self.send_button_frame.pack(fill=BOTH)
80 |
81 | #Send button
82 | self.send_button = Button(self.send_button_frame, text="Send", width=5, relief=GROOVE, bg='white',
83 | bd=1, command=lambda: self.send_message_insert(None), activebackground="#FFFFFF",
84 | activeforeground="#000000")
85 | self.send_button.pack(side=LEFT, ipady=8)
86 | self.master.bind("", self.send_message_insert)
87 |
88 | self.last_sent_label(date="No messages sent.")
89 | #t2 = threading.Thread(target=self.send_message_insert(, name='t1')
90 | #t2.start()
91 |
92 |
93 | def last_sent_label(self, date):
94 |
95 | try:
96 | self.sent_label.destroy()
97 | except AttributeError:
98 | pass
99 |
100 | self.sent_label = Label(self.entry_frame, font="Verdana 7", text=date, bg=self.tl_bg2, fg=self.tl_fg)
101 | self.sent_label.pack(side=LEFT, fill=X, padx=3)
102 |
103 | def clear_chat(self):
104 | self.text_box.config(state=NORMAL)
105 | self.last_sent_label(date="No messages sent.")
106 | self.text_box.delete(1.0, END)
107 | self.text_box.delete(1.0, END)
108 | self.text_box.config(state=DISABLED)
109 |
110 | def chatexit(self):
111 | exit()
112 |
113 | def msg(self):
114 | tkinter.messagebox.showinfo("NLP - Neural Network based chatbot")
115 |
116 | def about(self):
117 | tkinter.messagebox.showinfo("Chatbot by AI")
118 |
119 | def send_message_insert(self, message):
120 |
121 | user_input = self.entry_field.get()
122 | pr1 = "Human : " + user_input + "\n"
123 |
124 | self.text_box.configure(state=NORMAL)
125 | self.text_box.insert(END, pr1)
126 | self.text_box.configure(state=DISABLED)
127 | self.text_box.see(END)
128 |
129 | response = "Hello"
130 | #ob = chat(user_input)
131 | pr = "Bot : " + response + "\n"
132 |
133 | self.text_box.configure(state=NORMAL)
134 | self.text_box.insert(END, pr)
135 | self.text_box.configure(state=DISABLED)
136 | self.text_box.see(END)
137 | self.last_sent_label(str(time.strftime( "Last message sent: " + '%B %d, %Y' + ' at ' + '%I:%M %p')))
138 | self.entry_field.delete(0,END)
139 |
140 |
141 | def font_change_default(self):
142 | self.text_box.config(font="Verdana 10")
143 | self.entry_field.config(font="Verdana 10")
144 | self.font = "Verdana 10"
145 |
146 | def font_change_system(self):
147 | self.text_box.config(font="System")
148 | self.entry_field.config(font="System")
149 | self.font = "System"
150 |
151 | def font_change_fixedsys(self):
152 | self.text_box.config(font="fixedsys")
153 | self.entry_field.config(font="fixedsys")
154 | self.font = "fixedsys"
155 |
156 | def color_theme_default(self):
157 | self.master.config(bg="#EEEEEE")
158 | self.text_frame.config(bg="#EEEEEE")
159 | self.entry_frame.config(bg="#EEEEEE")
160 | self.text_box.config(bg="#FFFFFF", fg="#000000")
161 | self.entry_field.config(bg="#FFFFFF", fg="#000000", insertbackground="#000000")
162 | self.send_button_frame.config(bg="#EEEEEE")
163 | self.send_button.config(bg="#FFFFFF", fg="#000000", activebackground="#FFFFFF", activeforeground="#000000")
164 | self.sent_label.config(bg="#EEEEEE", fg="#000000")
165 |
166 | self.tl_bg = "#FFFFFF"
167 | self.tl_bg2 = "#EEEEEE"
168 | self.tl_fg = "#000000"
169 |
170 | #Dark
171 | def color_theme_dark(self):
172 | self.master.config(bg="#2a2b2d")
173 | self.text_frame.config(bg="#2a2b2d")
174 | self.text_box.config(bg="#212121", fg="#FFFFFF")
175 | self.entry_frame.config(bg="#2a2b2d")
176 | self.entry_field.config(bg="#212121", fg="#FFFFFF", insertbackground="#FFFFFF")
177 | self.send_button_frame.config(bg="#2a2b2d")
178 | self.send_button.config(bg="#212121", fg="#FFFFFF", activebackground="#212121", activeforeground="#FFFFFF")
179 | self.sent_label.config(bg="#2a2b2d", fg="#FFFFFF")
180 |
181 | self.tl_bg = "#212121"
182 | self.tl_bg2 = "#2a2b2d"
183 | self.tl_fg = "#FFFFFF"
184 |
185 | #Blue
186 | def color_theme_dark_blue(self):
187 | self.master.config(bg="#263b54")
188 | self.text_frame.config(bg="#263b54")
189 | self.text_box.config(bg="#1c2e44", fg="#FFFFFF")
190 | self.entry_frame.config(bg="#263b54")
191 | self.entry_field.config(bg="#1c2e44", fg="#FFFFFF", insertbackground="#FFFFFF")
192 | self.send_button_frame.config(bg="#263b54")
193 | self.send_button.config(bg="#1c2e44", fg="#FFFFFF", activebackground="#1c2e44", activeforeground="#FFFFFF")
194 | self.sent_label.config(bg="#263b54", fg="#FFFFFF")
195 |
196 | self.tl_bg = "#1c2e44"
197 | self.tl_bg2 = "#263b54"
198 | self.tl_fg = "#FFFFFF"
199 |
200 | #Hacker
201 | def color_theme_hacker(self):
202 | self.master.config(bg="#0F0F0F")
203 | self.text_frame.config(bg="#0F0F0F")
204 | self.entry_frame.config(bg="#0F0F0F")
205 | self.text_box.config(bg="#0F0F0F", fg="#33FF33")
206 | self.entry_field.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
207 | self.send_button_frame.config(bg="#0F0F0F")
208 | self.send_button.config(bg="#0F0F0F", fg="#FFFFFF", activebackground="#0F0F0F", activeforeground="#FFFFFF")
209 | self.sent_label.config(bg="#0F0F0F", fg="#33FF33")
210 |
211 | self.tl_bg = "#0F0F0F"
212 | self.tl_bg2 = "#0F0F0F"
213 | self.tl_fg = "#33FF33"
214 |
215 | #Default font and color theme
216 | def default_format(self):
217 | self.font_change_default()
218 | self.color_theme_default()
219 |
220 |
221 | root=Tk()
222 |
223 |
224 | ob = ChatInterface(root)
225 | root.geometry(DIMS)
226 | root.title("Chatbot-NLP")
227 | root.mainloop()
228 |
229 |
--------------------------------------------------------------------------------
/textChatbot.py:
--------------------------------------------------------------------------------
1 |
2 | import time
3 | import tkinter.messagebox
4 |
5 | from tkinter import *
6 | from chatbot import chat
7 |
8 | DIMS="500x500"
9 |
10 | class ChatInterface(Frame):
11 |
12 | def __init__(self, master=None):
13 | Frame.__init__(self, master)
14 | self.master = master
15 |
16 | #Default background setting
17 | self.tl_bg = "#EEEEEE"
18 | self.tl_bg2 = "#EEEEEE"
19 | self.tl_fg = "#000000"
20 | self.font = "Verdana 10"
21 |
22 | #Menu bar
23 | menu = Menu(self.master)
24 | self.master.config(menu=menu, bd=5)
25 |
26 | #File
27 | file = Menu(menu, tearoff=0)
28 | menu.add_cascade(label="File", menu=file)
29 |
30 | #Clear chat option
31 | file.add_command(label="Clear Chat", command=self.clear_chat)
32 |
33 | #Exit chatbot option
34 | file.add_command(label="Exit",command=self.chatexit)
35 |
36 | #Preferences option
37 | options = Menu(menu, tearoff=0)
38 | menu.add_cascade(label="Preferences", menu=options)
39 |
40 | #Fonts
41 | font = Menu(options, tearoff=0)
42 | options.add_cascade(label="Font", menu=font)
43 | font.add_command(label="Default",command=self.font_change_default)
44 | font.add_command(label="System",command=self.font_change_system)
45 |
46 | #Theme
47 | color_theme = Menu(options, tearoff=0)
48 | options.add_cascade(label="Theme", menu=color_theme)
49 | color_theme.add_command(label="Default",command=self.color_theme_default)
50 | color_theme.add_command(label="Blue",command=self.color_theme_dark_blue)
51 | color_theme.add_command(label="Hacker",command=self.color_theme_hacker)
52 |
53 | help_option = Menu(menu, tearoff=0)
54 | menu.add_cascade(label="About", menu=help_option)
55 | help_option.add_command(label="About Chatbot", command=self.msg)
56 |
57 | self.text_frame = Frame(self.master, bd=6)
58 | self.text_frame.pack(expand=True, fill=BOTH)
59 |
60 | #Scrollbar for text box
61 | self.text_box_scrollbar = Scrollbar(self.text_frame, bd=0)
62 | self.text_box_scrollbar.pack(fill=Y, side=RIGHT)
63 |
64 | #Contains messages
65 | self.text_box = Text(self.text_frame, yscrollcommand=self.text_box_scrollbar.set, state=DISABLED,
66 | bd=1, padx=6, pady=6, spacing3=8, wrap=WORD, bg=None, font="Verdana 10", relief=GROOVE,
67 | width=10, height=1)
68 | self.text_box.pack(expand=True, fill=BOTH)
69 | self.text_box_scrollbar.config(command=self.text_box.yview)
70 |
71 | #Frame containing user entry field
72 | self.entry_frame = Frame(self.master, bd=1)
73 | self.entry_frame.pack(side=LEFT, fill=BOTH, expand=True)
74 |
75 | #Entry field
76 | self.entry_field = Entry(self.entry_frame, bd=1, justify=LEFT)
77 | self.entry_field.pack(fill=X, padx=6, pady=6, ipady=3)
78 | #self.users_message = self.entry_field.get()
79 |
80 | #Frame containing send button and emoji button
81 | self.send_button_frame = Frame(self.master, bd=0)
82 | self.send_button_frame.pack(fill=BOTH)
83 |
84 | #Send button
85 | self.send_button = Button(self.send_button_frame, text="Send", width=5, relief=GROOVE, bg='white',
86 | bd=1, command=lambda: self.send_message_insert(None), activebackground="#FFFFFF",
87 | activeforeground="#000000")
88 | self.send_button.pack(side=LEFT, ipady=8)
89 | self.master.bind("", self.send_message_insert)
90 |
91 | self.last_sent_label(date="No messages sent.")
92 | #t2 = threading.Thread(target=self.send_message_insert(, name='t1')
93 | #t2.start()
94 |
95 |
96 | def last_sent_label(self, date):
97 |
98 | try:
99 | self.sent_label.destroy()
100 | except AttributeError:
101 | pass
102 |
103 | self.sent_label = Label(self.entry_frame, font="Verdana 7", text=date, bg=self.tl_bg2, fg=self.tl_fg)
104 | self.sent_label.pack(side=LEFT, fill=X, padx=3)
105 |
106 | def clear_chat(self):
107 | self.text_box.config(state=NORMAL)
108 | self.last_sent_label(date="No messages sent.")
109 | self.text_box.delete(1.0, END)
110 | self.text_box.delete(1.0, END)
111 | self.text_box.config(state=DISABLED)
112 |
113 | def chatexit(self):
114 | exit()
115 |
116 | def msg(self):
117 | tkinter.messagebox.showinfo("NLP - Neural Network based chatbot")
118 |
119 | def about(self):
120 | tkinter.messagebox.showinfo("Chatbot by AI")
121 |
122 | def send_message_insert(self, message):
123 |
124 | user_input = self.entry_field.get()
125 | pr1 = "You : " + user_input + "\n"
126 |
127 | self.text_box.configure(state=NORMAL)
128 | self.text_box.insert(END, pr1)
129 | self.text_box.configure(state=DISABLED)
130 | self.text_box.see(END)
131 |
132 | response = chat(user_input)
133 | pr = "Bot : " + response + "\n"
134 |
135 | self.text_box.configure(state=NORMAL)
136 | self.text_box.insert(END, pr)
137 | self.text_box.configure(state=DISABLED)
138 | self.text_box.see(END)
139 | self.last_sent_label(str(time.strftime( "Last message sent: " + '%B %d, %Y' + ' at ' + '%I:%M %p')))
140 | self.entry_field.delete(0,END)
141 |
142 | def font_change_default(self):
143 | self.text_box.config(font="Verdana 10")
144 | self.entry_field.config(font="Verdana 10")
145 | self.font = "Verdana 10"
146 |
147 | def font_change_system(self):
148 | self.text_box.config(font="System")
149 | self.entry_field.config(font="System")
150 | self.font = "System"
151 |
152 | def font_change_fixedsys(self):
153 | self.text_box.config(font="fixedsys")
154 | self.entry_field.config(font="fixedsys")
155 | self.font = "fixedsys"
156 |
157 | def color_theme_default(self):
158 | self.master.config(bg="#EEEEEE")
159 | self.text_frame.config(bg="#EEEEEE")
160 | self.entry_frame.config(bg="#EEEEEE")
161 | self.text_box.config(bg="#FFFFFF", fg="#000000")
162 | self.entry_field.config(bg="#FFFFFF", fg="#000000", insertbackground="#000000")
163 | self.send_button_frame.config(bg="#EEEEEE")
164 | self.send_button.config(bg="#FFFFFF", fg="#000000", activebackground="#FFFsFFF", activeforeground="#000000")
165 | self.sent_label.config(bg="#EEEEEE", fg="#000000")
166 |
167 | self.tl_bg = "#FFFFFF"
168 | self.tl_bg2 = "#EEEEEE"
169 | self.tl_fg = "#000000"
170 |
171 | #Dark
172 | def color_theme_dark(self):
173 | self.master.config(bg="#2a2b2d")
174 | self.text_frame.config(bg="#2a2b2d")
175 | self.text_box.config(bg="#212121", fg="#FFFFFF")
176 | self.entry_frame.config(bg="#2a2b2d")
177 | self.entry_field.config(bg="#212121", fg="#FFFFFF", insertbackground="#FFFFFF")
178 | self.send_button_frame.config(bg="#2a2b2d")
179 | self.send_button.config(bg="#212121", fg="#FFFFFF", activebackground="#212121", activeforeground="#FFFFFF")
180 | self.sent_label.config(bg="#2a2b2d", fg="#FFFFFF")
181 |
182 | self.tl_bg = "#212121"
183 | self.tl_bg2 = "#2a2b2d"
184 | self.tl_fg = "#FFFFFF"
185 |
186 | #Blue
187 | def color_theme_dark_blue(self):
188 | self.master.config(bg="#263b54")
189 | self.text_frame.config(bg="#263b54")
190 | self.text_box.config(bg="#1c2e44", fg="#FFFFFF")
191 | self.entry_frame.config(bg="#263b54")
192 | self.entry_field.config(bg="#1c2e44", fg="#FFFFFF", insertbackground="#FFFFFF")
193 | self.send_button_frame.config(bg="#263b54")
194 | self.send_button.config(bg="#1c2e44", fg="#FFFFFF", activebackground="#1c2e44", activeforeground="#FFFFFF")
195 | self.sent_label.config(bg="#263b54", fg="#FFFFFF")
196 |
197 | self.tl_bg = "#1c2e44"
198 | self.tl_bg2 = "#263b54"
199 | self.tl_fg = "#FFFFFF"
200 |
201 | #Hacker
202 | def color_theme_hacker(self):
203 | self.master.config(bg="#0F0F0F")
204 | self.text_frame.config(bg="#0F0F0F")
205 | self.entry_frame.config(bg="#0F0F0F")
206 | self.text_box.config(bg="#0F0F0F", fg="#33FF33")
207 | self.entry_field.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
208 | self.send_button_frame.config(bg="#0F0F0F")
209 | self.send_button.config(bg="#0F0F0F", fg="#FFFFFF", activebackground="#0F0F0F", activeforeground="#FFFFFF")
210 | self.sent_label.config(bg="#0F0F0F", fg="#33FF33")
211 |
212 | self.tl_bg = "#0F0F0F"
213 | self.tl_bg2 = "#0F0F0F"
214 | self.tl_fg = "#33FF33"
215 |
216 | #Default font and color theme
217 | def default_format(self):
218 | self.font_change_default()
219 | self.color_theme_default()
220 |
221 |
222 | root=Tk()
223 | ob = ChatInterface(root)
224 | root.geometry(DIMS)
225 | root.title("Chatbot-NLP")
226 |
227 | img = PhotoImage(file = 'img/bot.png')
228 | root.iconphoto(False, img)
229 |
230 | root.mainloop()
231 |
232 |
--------------------------------------------------------------------------------
/voiceBot.py:
--------------------------------------------------------------------------------
1 | import time
2 | import tkinter.messagebox
3 | import speech_recognition as sr
4 |
5 | import threading
6 |
7 | from tkinter import *
8 | from chatbot import chat
9 |
10 | DIMS="500x500"
11 |
12 | class ChatInterface(Frame):
13 |
14 | def __init__(self, master=None):
15 | Frame.__init__(self, master)
16 | self.master = master
17 |
18 | #Default background setting
19 | self.tl_bg = "#EEEEEE"
20 | self.tl_bg2 = "#EEEEEE"
21 | self.tl_fg = "#000000"
22 | self.font = "Verdana 10"
23 |
24 | #Menu bar
25 | menu = Menu(self.master)
26 | self.master.config(menu=menu, bd=5)
27 |
28 | #File
29 | file = Menu(menu, tearoff=0)
30 | menu.add_cascade(label="File", menu=file)
31 |
32 | #Clear chat option
33 | file.add_command(label="Clear Chat", command=self.clear_chat)
34 |
35 | #Exit chatbot option
36 | file.add_command(label="Exit",command=self.chatexit)
37 |
38 | #Preferences option
39 | options = Menu(menu, tearoff=0)
40 | menu.add_cascade(label="Preferences", menu=options)
41 |
42 | #Fonts
43 | font = Menu(options, tearoff=0)
44 | options.add_cascade(label="Font", menu=font)
45 | font.add_command(label="Default",command=self.font_change_default)
46 | font.add_command(label="System",command=self.font_change_system)
47 |
48 | #Theme
49 | color_theme = Menu(options, tearoff=0)
50 | options.add_cascade(label="Theme", menu=color_theme)
51 | color_theme.add_command(label="Default",command=self.color_theme_default)
52 | color_theme.add_command(label="Blue",command=self.color_theme_dark_blue)
53 | color_theme.add_command(label="Hacker",command=self.color_theme_hacker)
54 |
55 | help_option = Menu(menu, tearoff=0)
56 | menu.add_cascade(label="About", menu=help_option)
57 | help_option.add_command(label="About Chatbot", command=self.msg)
58 |
59 | self.text_frame = Frame(self.master, bd=6)
60 | self.text_frame.pack(expand=True, fill=BOTH)
61 |
62 | #Scrollbar for text box
63 | self.text_box_scrollbar = Scrollbar(self.text_frame, bd=0)
64 | self.text_box_scrollbar.pack(fill=Y, side=RIGHT)
65 |
66 | #Contains messages
67 | self.text_box = Text(self.text_frame, yscrollcommand=self.text_box_scrollbar.set, state=DISABLED,
68 | bd=1, padx=6, pady=6, spacing3=8, wrap=WORD, bg=None, font="Verdana 10", relief=GROOVE,
69 | width=10, height=1)
70 | self.text_box.pack(expand=True, fill=BOTH)
71 | self.text_box_scrollbar.config(command=self.text_box.yview)
72 |
73 | #Frame containing user entry field
74 | self.entry_frame = Frame(self.master, bd=1)
75 | self.entry_frame.pack(side=LEFT, fill=BOTH, expand=True)
76 |
77 | #Entry field
78 | self.entry_field = Entry(self.entry_frame, bd=1, justify=LEFT)
79 | self.entry_field.pack(fill=X, padx=6, pady=6, ipady=3)
80 | #self.users_message = self.entry_field.get()
81 |
82 | #Frame containing send button and emoji button
83 | self.send_button_frame = Frame(self.master, bd=0)
84 | self.send_button_frame.pack(fill=BOTH)
85 |
86 | #Send button
87 | self.send_button = Button(self.send_button_frame, text="Speak", width=5, relief=GROOVE, bg='white',
88 | bd=1, command=lambda: self.send_message_insert(None), activebackground="#FFFFFF",
89 | activeforeground="#000000")
90 | self.send_button.pack(side=LEFT, ipady=8)
91 | self.master.bind("", self.send_message_insert)
92 |
93 |
94 | self.last_sent_label(date="No messages sent.")
95 |
96 | t2 = threading.Thread(target=self.speechToText)
97 | t2.start()
98 |
99 |
100 | def speechToText(self):
101 | r = sr.Recognizer()
102 |
103 | while(True):
104 |
105 | with sr.Microphone() as source:
106 | print('Listenting...')
107 | try:
108 | inputAudio = r.listen(source)
109 | inputText = r.recognize_google(inputAudio)
110 |
111 | print(inputText.lower())
112 | return inputText.lower()
113 |
114 | except:
115 | print("Not")
116 |
117 | def last_sent_label(self, date):
118 |
119 | try:
120 | self.sent_label.destroy()
121 | except AttributeError:
122 | pass
123 |
124 | self.sent_label = Label(self.entry_frame, font="Verdana 7", text=date, bg=self.tl_bg2, fg=self.tl_fg)
125 | self.sent_label.pack(side=LEFT, fill=X, padx=3)
126 |
127 | def clear_chat(self):
128 | self.text_box.config(state=NORMAL)
129 | self.last_sent_label(date="No messages sent.")
130 | self.text_box.delete(1.0, END)
131 | self.text_box.delete(1.0, END)
132 | self.text_box.config(state=DISABLED)
133 |
134 | def chatexit(self):
135 | exit()
136 |
137 | def msg(self):
138 | tkinter.messagebox.showinfo("NLP - Neural Network based chatbot")
139 |
140 | def about(self):
141 | tkinter.messagebox.showinfo("Chatbot by AI")
142 |
143 | def send_message_insert(self, message):
144 |
145 | user_input = self.speechToText()
146 |
147 | print("I heard: " + user_input)
148 | pr1 = "You : " + user_input + "\n"
149 |
150 | self.text_box.configure(state=NORMAL)
151 | self.text_box.insert(END, pr1)
152 | self.text_box.configure(state=DISABLED)
153 | self.text_box.see(END)
154 |
155 | response = chat(user_input)
156 | pr = "Bot : " + response + "\n"
157 |
158 | self.text_box.configure(state=NORMAL)
159 | self.text_box.insert(END, pr)
160 | self.text_box.configure(state=DISABLED)
161 | self.text_box.see(END)
162 | self.last_sent_label(str(time.strftime( "Last message sent: " + '%B %d, %Y' + ' at ' + '%I:%M %p')))
163 | self.entry_field.delete(0,END)
164 |
165 | def font_change_default(self):
166 | self.text_box.config(font="Verdana 10")
167 | self.entry_field.config(font="Verdana 10")
168 | self.font = "Verdana 10"
169 |
170 | def font_change_system(self):
171 | self.text_box.config(font="System")
172 | self.entry_field.config(font="System")
173 | self.font = "System"
174 |
175 | def font_change_fixedsys(self):
176 | self.text_box.config(font="fixedsys")
177 | self.entry_field.config(font="fixedsys")
178 | self.font = "fixedsys"
179 |
180 | def color_theme_default(self):
181 | self.master.config(bg="#EEEEEE")
182 | self.text_frame.config(bg="#EEEEEE")
183 | self.entry_frame.config(bg="#EEEEEE")
184 | self.text_box.config(bg="#FFFFFF", fg="#000000")
185 | self.entry_field.config(bg="#FFFFFF", fg="#000000", insertbackground="#000000")
186 | self.send_button_frame.config(bg="#EEEEEE")
187 | self.send_button.config(bg="#FFFFFF", fg="#000000", activebackground="#FFFsFFF", activeforeground="#000000")
188 | self.sent_label.config(bg="#EEEEEE", fg="#000000")
189 |
190 | self.tl_bg = "#FFFFFF"
191 | self.tl_bg2 = "#EEEEEE"
192 | self.tl_fg = "#000000"
193 |
194 | #Dark
195 | def color_theme_dark(self):
196 | self.master.config(bg="#2a2b2d")
197 | self.text_frame.config(bg="#2a2b2d")
198 | self.text_box.config(bg="#212121", fg="#FFFFFF")
199 | self.entry_frame.config(bg="#2a2b2d")
200 | self.entry_field.config(bg="#212121", fg="#FFFFFF", insertbackground="#FFFFFF")
201 | self.send_button_frame.config(bg="#2a2b2d")
202 | self.send_button.config(bg="#212121", fg="#FFFFFF", activebackground="#212121", activeforeground="#FFFFFF")
203 | self.sent_label.config(bg="#2a2b2d", fg="#FFFFFF")
204 |
205 | self.tl_bg = "#212121"
206 | self.tl_bg2 = "#2a2b2d"
207 | self.tl_fg = "#FFFFFF"
208 |
209 | #Blue
210 | def color_theme_dark_blue(self):
211 | self.master.config(bg="#263b54")
212 | self.text_frame.config(bg="#263b54")
213 | self.text_box.config(bg="#1c2e44", fg="#FFFFFF")
214 | self.entry_frame.config(bg="#263b54")
215 | self.entry_field.config(bg="#1c2e44", fg="#FFFFFF", insertbackground="#FFFFFF")
216 | self.send_button_frame.config(bg="#263b54")
217 | self.send_button.config(bg="#1c2e44", fg="#FFFFFF", activebackground="#1c2e44", activeforeground="#FFFFFF")
218 | self.sent_label.config(bg="#263b54", fg="#FFFFFF")
219 |
220 | self.tl_bg = "#1c2e44"
221 | self.tl_bg2 = "#263b54"
222 | self.tl_fg = "#FFFFFF"
223 |
224 | #Hacker
225 | def color_theme_hacker(self):
226 | self.master.config(bg="#0F0F0F")
227 | self.text_frame.config(bg="#0F0F0F")
228 | self.entry_frame.config(bg="#0F0F0F")
229 | self.text_box.config(bg="#0F0F0F", fg="#33FF33")
230 | self.entry_field.config(bg="#0F0F0F", fg="#33FF33", insertbackground="#33FF33")
231 | self.send_button_frame.config(bg="#0F0F0F")
232 | self.send_button.config(bg="#0F0F0F", fg="#FFFFFF", activebackground="#0F0F0F", activeforeground="#FFFFFF")
233 | self.sent_label.config(bg="#0F0F0F", fg="#33FF33")
234 |
235 | self.tl_bg = "#0F0F0F"
236 | self.tl_bg2 = "#0F0F0F"
237 | self.tl_fg = "#33FF33"
238 |
239 | #Default font and color theme
240 | def default_format(self):
241 | self.font_change_default()
242 | self.color_theme_default()
243 |
244 | root=Tk()
245 | ob = ChatInterface(root)
246 | root.geometry(DIMS)
247 | root.title("Chatbot-NLP")
248 |
249 | img = PhotoImage(file = 'img/bot.png')
250 | root.iconphoto(False, img)
251 |
252 | root.mainloop()
253 |
254 |
--------------------------------------------------------------------------------