You are on page 1of 29

ChatBot

A PROJECT REPORT

Submitted by

Abhishek Verma(00414902018)
Archit Kr. Singh(01414902018)
Jatin Bagga(03814902018)

in partial fulfillment for the award of the degree

of

BACHELOR OF COMPUTER APPLICATION

MAHARAJA SURAJMAL INSTITUTE

C-4, JANAK PURI,


NEW DELHI - 110058

1|ChatBot
MAHARAJA SURAJMAL INSTITUTE

BONAFIDE CERTIFICATE

Certified that this project report ChatBot is the bonafide work of ABHISHEK

VERMA, ARCHIT KR. SINGH, JATIN BAGGA who carried out the project work

under my supervision.

SIGNATURE

Dr. RHYTHM CHAUDHARY


SUPERVISOR

Assistant Professor

Computer Application Department


Maharaja Surajmal Institute
C-4 Janakpuri, New Delhi, 110058

2|ChatBot
3|ChatBot
Abstract
A chatbot is a computer software program that conducts a conversation via auditory or textual
methods. This software is used to perform tasks such as quickly responding to users, informing
them, helping to purchase products and providing better service to customers. Chatbots are programs
that work on Artificial Intelligence (AI) & Machine Learning Platform. Chatbot has become more
popular in business groups right now as it can reduce customer service costs and handles multiple
users at a time. But yet to accomplish many tasks there is a need to make chatbots as efficient as
possible. In this project, we provide the design of a chatbot, which provides a genuine and accurate
answer for any query using Artificial Intelligence Markup Language (AIML) and Latent Semantic
Analysis (LSA) with python platform.

4|ChatBot
TABLE OF CONTENTS

Serial no. Content Page no.


1. INTRODUCTION 5
2. METHODOLOGY 6
3. PYTHON LIBRARIES USED 7~8
4. SYSTEM MODULE DIAGRAM 9
5. CODE 10~19
6. ChatBot DEMO 20
7. SCREENSHOTS 21~22
8. ADVANTAGES 23
9. LIMITATIONS 24
10. FUTURE SCOPES 25
11. CONCLUSION 26
12. REFERENCES 27

5|ChatBot
INTRODUCTION
Chatbots are software applications that use artificial intelligence & natural language processing to
understand what a human wants, and guides them to their desired outcome with as little work for the
end user as possible. Like a virtual assistant for your customer experience touchpoints.

A well designed & built chatbot will:

1. Use existing conversation data (if available) to understand the type of questions people ask.
2. Analyze correct answers to those questions through a ‘training’ period.
3. Use machine learning & NLP to learn context, and continually get better at answering those
questions in the future.

The adoption of chatbots was accelerated in 2016 when Facebook opened up its developer platform
and showed the world what is possible with chatbots through their Messenger app. Google also got
in the game soon after with Google Assistant. Since then there have been a tremendous amount of
chatbot apps built on websites, in applications, on social media, for customer support, and countless
other examples.

There are basically two types of ChatBot:

1. Rules-Based Chatbots – These chatbots follow pre-designed rules, often built using a
graphical user interface where a bot builder will design paths using a decision tree.
2. AI Chatbots – AI chatbots will automatically learn after an initial training period by a bot
developer.

6|ChatBot
METHODOLOGY

7|ChatBot
PYTHON LIBRARIES USED
In this Project we have used Python Programming Language (Version 3.7) along with HTML, CSS,
Machine Learning and Artificial Intelligence. We have also utilized a number of python modules to
implement various features and functionalities. These modules and libraries include the following:

NLTK (Natural Language Toolkit):


NLTK is a leading platform for building Python programs to work with human language data. It
provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along
with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing,
and semantic reasoning, wrappers for industrial-strength NLP libraries, and an active discussion
forum.

TensorFlow:
TensorFlow 2 is an end-to-end, open-source machine learning platform. You can think of it as an
infrastructure layer for differentiable programming. It combines four key abilities:
 Efficiently executing low-level tensor operations on CPU, GPU, or TPU.
 Computing the gradient of arbitrary differentiable expressions.
 Scaling computation to many devices, such as clusters of hundreds of GPUs.
 Exporting programs ("graphs") to external runtimes such as servers, browsers, mobile and
embedded devices.

8|ChatBot
Keras:
Keras is the high-level neural networks API for Python: an approachable, highly-productive
interface for solving machine learning problems, with a focus on modern deep learning. It provides
essential abstractions and building blocks for developing and shipping machine learning solutions
with high iteration velocity.

Numpy:
NumPy is a library for the Python programming language, adding support for large, multi-
dimensional arrays and matrices, along with a large collection of high-level mathematical functions
to operate on these arrays.

Flask:
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick
and easy, with the ability to scale up to complex applications. It began as a simple wrapper around
Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

9|ChatBot
SYSTEM MODULE DIAGRAM

10 | C h a t B o t
11 | C h a t B o t
CODE

Train_chatbot.py

import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import json
import pickle

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import random

words=[]
classes = []
documents = []
ignore_words = ['?', '!']
data_file = open('intents.json').read()
intents = json.loads(data_file)

for intent in intents['intents']:


for pattern in intent['patterns']:

#tokenize each word


w = nltk.word_tokenize(pattern)
words.extend(w)
#add documents in the corpus
12 | C h a t B o t
documents.append((w, intent['tag']))

# add to our classes list


if intent['tag'] not in classes:
classes.append(intent['tag'])

# lemmaztize and lower each word and remove duplicates


words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]
words = sorted(list(set(words)))
# sort classes
classes = sorted(list(set(classes)))
# documents = combination between patterns and intents
print (len(documents), "documents")
# classes = intents
print (len(classes), "classes", classes)
# words = all words, vocabulary
print (len(words), "unique lemmatized words", words)

pickle.dump(words,open('words.pkl','wb'))
pickle.dump(classes,open('classes.pkl','wb'))

# 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]
13 | C h a t B o t
# lemmatize each word - create base word, in attempt to represent related words
pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]
# create our bag of words array with 1, if word match found in current pattern
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 (for each pattern)
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. X - patterns, Y - intents
train_x = list(training[:,0])
train_y = list(training[:,1])
print("Training data created")

# Create model - 3 layers. First layer 128 neurons, second layer 64 neurons and 3rd output layer
contains number of neurons
# equal to number of intents to predict output intent with softmax
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))

# Compile model. Stochastic gradient descent with Nesterov accelerated gradient gives good results
for this model
14 | C h a t B o t
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

#fitting and saving the model


hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('chatbot_model.h5', hist)

print("model created")

chatgui.py

import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np

from keras.models import load_model


model = load_model('chatbot_model.h5')
import json
import random
intents = json.loads(open('intents.json').read())
words = pickle.load(open('words.pkl', 'rb'))
classes = pickle.load(open('classes.pkl', 'rb'))

def clean_up_sentence(sentence):
# tokenize the pattern - split words into array
sentence_words = nltk.word_tokenize(sentence)
# stem each word - create short form for word
15 | C h a t B o t
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
return sentence_words

# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence

def bow(sentence, words, show_details=True):


# tokenize the pattern
sentence_words = clean_up_sentence(sentence)
# bag of words - matrix of N words, vocabulary matrix
bag = [0]*len(words)
for s in sentence_words:
for i, w in enumerate(words):
if w == s:
# assign 1 if current word is in the vocabulary position
bag[i] = 1
if show_details:
print("found in bag: %s" % w)
return(np.array(bag))

def predict_class(sentence, model):


# filter out predictions below a threshold
p = bow(sentence, words,show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
# sort by strength of probability
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
return return_list
16 | C h a t B o t
def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result

def chatbot_response(msg):
ints = predict_class(msg, model)
res = getResponse(ints, intents)
return res

#Creating GUI with tkinter


import tkinter
from tkinter import *

def send():
msg = EntryBox.get("1.0",'end-1c').strip()
EntryBox.delete("0.0",END)

if msg != '':
ChatLog.config(state=NORMAL)
ChatLog.insert(END, "You: " + msg + '\n\n')
ChatLog.config(foreground="#442265", font=("Verdana", 12 ))

res = chatbot_response(msg)
ChatLog.insert(END, "Bot: " + res + '\n\n')
17 | C h a t B o t
ChatLog.config(state=DISABLED)
ChatLog.yview(END)

base = Tk()
base.title("Hello")
base.geometry("400x500")
base.resizable(width=FALSE, height=FALSE)

#Create Chat window


ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",)

ChatLog.config(state=DISABLED)

#Bind scrollbar to Chat window


scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set

#Create Button to send message


SendButton = Button(base, font=("Verdana",12,'bold'), text="Send", width="12", height=5,
bd=0, bg="#32de97", activebackground="#3c9d9b",fg='#ffffff',
command= send )

#Create the box to enter message


EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
#EntryBox.bind("<Return>", send)

#Place all components on the screen


scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
18 | C h a t B o t
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)

base.mainloop()

intents.json

{"intents": [
{"tag": "greeting",
"patterns": ["Hi there", "How are you", "Is anyone there?","Hey","Hola", "Hello", "Good day"],
"responses": ["Hello, thanks for asking", "Good to see you again", "Hi there, how can I help?"],
"context": [""]
},
{"tag": "goodbye",
"patterns": ["Bye", "See you later", "Goodbye", "Nice chatting to you, bye", "Till next time"],
"responses": ["See you!", "Have a nice day", "Bye! Come back again soon."],
"context": [""]
},
{"tag": "thanks",
"patterns": ["Thanks", "Thank you", "That's helpful", "Awesome, thanks", "Thanks for helping me"],
"responses": ["Happy to help!", "Any time!", "My pleasure"],
"context": [""]
},
{"tag": "noanswer",
"patterns": [],
"responses": ["Sorry, can't understand you", "Please give me more info", "Not sure I understand"],
"context": [""]
},
{"tag": "options",

19 | C h a t B o t
"patterns": ["How you could help me?", "What you can do?", "What help you provide?", "How you
can be helpful?", "What support is offered"],
"responses": ["I can guide you through Adverse drug reaction list, Blood pressure tracking, Hospitals
and Pharmacies", "Offering support for Adverse drug reaction, Blood pressure, Hospitals and
Pharmacies"],
"context": [""]
},
{"tag": "adverse_drug",
"patterns": ["How to check Adverse drug reaction?", "Open adverse drugs module", "Give me a list
of drugs causing adverse behavior", "List all drugs suitable for patient with adverse reaction",
"Which drugs dont have adverse reaction?" ],
"responses": ["Navigating to Adverse drug reaction module"],
"context": [""]
},
{"tag": "blood_pressure",
"patterns": ["Open blood pressure module", "Task related to blood pressure", "Blood pressure data
entry", "I want to log blood pressure results", "Blood pressure data management" ],
"responses": ["Navigating to Blood Pressure module"],
"context": [""]
},
{"tag": "blood_pressure_search",
"patterns": ["I want to search for blood pressure result history", "Blood pressure for patient", "Load
patient blood pressure result", "Show blood pressure results for patient", "Find blood pressure results
by ID" ],
"responses": ["Please provide Patient ID", "Patient ID?"],
"context": ["search_blood_pressure_by_patient_id"]
},
{"tag": "search_blood_pressure_by_patient_id",
"patterns": [],
"responses": ["Loading Blood pressure result for Patient"],
"context": [""]
},
20 | C h a t B o t
{"tag": "pharmacy_search",
"patterns": ["Find me a pharmacy", "Find pharmacy", "List of pharmacies nearby", "Locate
pharmacy", "Search pharmacy" ],
"responses": ["Please provide pharmacy name"],
"context": ["search_pharmacy_by_name"]
},
{"tag": "search_pharmacy_by_name",
"patterns": [],
"responses": ["Loading pharmacy details"],
"context": [""]
},
{"tag": "hospital_search",
"patterns": ["Lookup for hospital", "Searching for hospital to transfer patient", "I want to search
hospital data", "Hospital lookup for patient", "Looking up hospital details" ],
"responses": ["Please provide hospital name or location"],
"context": ["search_hospital_by_params"]
},
{"tag": "search_hospital_by_params",
"patterns": [],
"responses": ["Please provide hospital type"],
"context": ["search_hospital_by_type"]
},
{"tag": "search_hospital_by_type",
"patterns": [],
"responses": ["Loading hospital details"],
"context": [""]
}
]
}

21 | C h a t B o t
ChatBot- DEMO

22 | C h a t B o t
SCREENSHOTS

23 | C h a t B o t
24 | C h a t B o t
ADVANTAGES

There are many advantages of chatbots; from receptionists to salespersons and online assistants, they
can do almost anything that can help you satisfy your customers while generating more revenue.

1. Chatbots Can Enhance Sales


It is seen that the customer experience gets even better when they have an assisting agent with them.
Your chatbot can assist the clients in shopping while resolving their queries on the go.

2. Chatbots Can Manage Accounts


Managing accounts requires one to be precise about the data and the information. And you can use a
chatbot to manage accounts and retrieve details whenever needed.

3. Chatbots are Customer Executives


Most of the websites render online chat options due to their ease and convenience. Chatbots are
perfect for deploying as customer executives because they are available around the clock and
seamlessly resolve customer issues.

25 | C h a t B o t
LIMITATIONS

There are some limitations of chatbots that have stopped various organizations from deploying
chatbots on their applications and websites.

1. Chatbots Don’t Understand Human Context.


It is one of the significant limitations of chatbots. These chatbots are programmed in a way that they
only know what they are taught.

2. They Can’t Make Decisions.


Another limitation of chatbots is that they lack decision-making. They don’t have the right know-
how to differentiate between the good and the bad.

3. Exorbitant Installation
Yes, chatbots save a lot of money in the long run, but their installation cost can break the bank. You
need to hire professionals who have rightly programmed chatbots to match the integrity of your
business.

4. Chatbots Have the Same Answer for a Query


Most customers don’t proceed with the chat when they know they are chatting with a chatbot.
Chatbots are easily identifiable because they have the same answer for multiple queries.

5. They Have Zero Research Skills


The harsh reality of chatbots is that they have zero research skills. These bots only have the answers
to the available queries; they cannot research new topics on the web.

6. Chatbots Have No Emotions


Lastly, chatbots have no emotions, and they cannot relate to any low situation. Having no emotions
means a chatbot can never establish a connection with the customer, which is crucial for any
business’s growth.

26 | C h a t B o t
FUTURE SCOPE

As future work, we can make a chatbot that is based on AIML and LSA. This technology will enable
a client to interact with a chatbot in a more natural fashion. We can enhance the discussion by
including and changing patterns and templates for general client queries using AIML and the right
response are given more often than LSA.

Chatbot Technology is Embracing with Each Day.

27 | C h a t B o t
CONCLUSION

In this project, we have introduced a chatbot that is able to interact with users. This chatbot can
answer queries in the textual user input. For this purpose, AIML with program-o has been used. The
chatbot can answer only those questions which he has the answer in its AIML dataset. So, to
increase the knowledge of the chatbot, we can add the APIs of Wikipedia, Weather Forecasting
Department, Sports, News, Government and a lot more. In such cases, the user will be able to talk
and interact with the chatbot in any kind of domain. Using APIs like Weather, Sports, News and
Government Services, the chatbot will be able to answer the questions outside of its dataset and
which are currently happening in the real world.

The next step towards building chatbots involves helping people to facilitate their work and interact
with computers using natural language or using their set of rules. Future Such chatbots, backed by
machine-learning technology, will be able to remember past conversations and learn from them to
answer new ones. The challenge would be conversing with the various multiple bot users and
multiple users.

28 | C h a t B o t
REFERENCES

https://docs.python.org/3/
https://keras.io/
https://www.tensorflow.org/
https://numpy.org/doc/stable/
https://www.drift.com/learn/chatbot/
https://www.smatbot.com/blog/what-are-the-limitations-of-chatbots

29 | C h a t B o t

You might also like