Ai Chatbot Using Python Report

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

A SIMPLE CHATBOT IN PYTHON USING

ARTIFICIAL INTELLIGENCE

A MINI PROJECT REPORT

Submitted by

ASWATHI S 212220040020

in partial fulfilment for the award of the degree of

BACHELOR OF ENGINEERING
in
COMPUTER SCIENCE AND ENGINEERING

SAVEETHA ENGINEERING COLLEGE


ANNA UNIVERSITY: CHENNAI- 600 025
NOVEMBER 2022

1
ANNA UNIVERSITY, CHENNAI

BONAFIDE CERTIFICATE

Certified that this Mini Project report “A SIMPLE CHATBOT IN


PYTHON USING ARTIFICIAL INTELLIGENCE” is the bonafide work of
ASWATHI S (212220040020), who carried out the mini project work under
my supervision.

SIGNATURE SIGNATURE
Dr. V. Loganathan, M.E., Ph.D. Dr. G. Nagappan, M.E., PhD
Associate Professor Professor
SUPERVISOR HEAD OF THE DEPARTMENT
Dept of Computer Science and Dept of Computer Science
Engineering, and Engineering,
Saveetha Engineering College, Saveetha Engineering College,
Thandalam, Chennai 602105. Thandalam, Chennai 602105.

DATE OF THE VIVA VOCE EXAMINATION: ……………………..

INTERNAL EXAMINER EXTERNAL EXAMINER


.

2
ACKNOWLEDGEMENT

I express my deep sense of gratitude to our honourable and beloved Founder President

Dr. N. M. Veeraiyan, our President Dr. Saveetha Rajesh, our Director Dr. S. Rajesh and other

management members for providing the infrastructure needed.

I express my wholehearted gratitude to our principal, Dr. N. Duraipandian, for his

wholehearted encouragement in completing this project.

I convey my thanks to Dr. G. Nagappan, Professor and Head of the Department of

Computer Science and Engineering, Saveetha Engineering College, for his kind support and

for providing necessary facilities to carry out the project work.

I would like to express my sincere thanks and deep sense of gratitude to my Supervisor

Dr. V. Loganathan, Associate Professor, Department of Computer Science and Engineering,

Saveetha Engineering College, for his valuable guidance, suggestions and constant

encouragement that paved the way for the successful completion of the project work and for

providing me necessary support and details at the right time and during the progressive

reviews.

I owe my thanks to all the members of my college, faculty, staff and technicians for their

kind and valuable cooperation during the course of the project. I am pleased to acknowledge

my sincere thanks to my beloved parents, friends and well-wishers who encouraged me to

complete this project successfully.

3
ABSTRACT

A chatbot is a computer program that simulates and processes human conversation allowing

humans to interact with digital devices as if they were communicating with a real person.

Chatbots can be as simple as rudimentary programs that answer a simple query with a single-

line response, or as sophisticated as digital assistants that learn and evolve to deliver

increasing levels of personalization as they gather and process information.

Chatbots help in customer support, generating information, user navigation etc.,

Organizations looking to increase sales or service productivity may adopt chatbots for time

savings and efficiency, as artificial intelligence (AI) chatbots can converse with users and

answer recurring questions. As consumers move away from traditional forms of

communication, many experts expect chat-based communication methods to rise.

Organizations increasingly use chatbot-based virtual assistants to handle simple tasks,

allowing human agents to focus on other responsibilities.

In this project we will use Python to build a simple chatbot that can interact with users. Here

we make use of AI and Natural Language Processing in Python to create and train a chatbot

to respond appropriately to an user requests.

Natural Language Processing (NLP) makes it possible for computers to understand the

human language. Behind the scenes, NLP analyzes the grammatical structure of sentences

and the individual meaning of words, then uses algorithms to extract meaning and deliver

outputs. In other words, it makes sense of human language so that it can automatically

perform different tasks. A well-known application of NLP is chatbots. They help support

teams solve issues by understanding common language requests and responding

automatically.

4
Table of Contents

Chapter Title Page Number


Number
Abstract

1 Introduction 7
1.1 Overview of the Project 7
1.2 Scope and Objective 7

2. Literature Survey 8
2.1 Introduction 8
2.2 Literature Survey 8

3. System Design 15
3.1 Natural Language Processing 15
3.2 Advantage of Natural Language Processing 16
3.3 Disadvantage of Natural Language Processing 16
3.4 Architecture Diagram 17
3.5 Hardware Requirement 17
3.6 Software Requirement 17

4. Implementation and Analysis 18


4.1 Python Library 18
4.2 Data 20
4.3.Software Description 20
4.3.1. Python 20
4.3.2. Pycharm 21
4.4 Sample Coding 22
4.5 Sample Output 25

5. Conclusion 27

5
Reference 28

LIST OF FIGURES
3.1 Architecture Diagram 17

4.1 Chatbot 25

4.2 User request and response 1 25

4.3 User request and response 2 26

4.4 User request and response 3 26

6
Chapter 1. INTRODUCTION

1.1 OVERVIEW OF THE PROJECT

A chatbot is a way of solving a user’s by interacting with a computer program. Chatbots and

other virtual methods of communication are becoming more popular as people turn away

from more conventional forms of communication. Chatbots provide a way for people to get

their queries answered virtually without having to correspond to emails or talk on the phone

with a customer service person. Chatbots can be adopted by an organization to increase their

time efficiency as AI-based chatbots can answer customers recurring questions easily.

1.2 SCOPE AND OBJECTIVE

SCOPE
The goal of the chatbot is to respond as precisely as possible to client questions. The

consumer should be able to receive the clearest possible responses to their inquiries.

OBJECTIVE

The main aim of the project is to provide the users with a platform to get their questions and

queries answered in a easy and simple way. This helps users avoid having to wait on a call or

wait for an E-mail to get their queries resolved. This chatbot is a way for users to get their

queries answered without having to go through a customer service call or having to talk to an

automated recording to get their concerns cleared. Here we train the chatbot to recognize

multiple types of words and phrases related to a particular question in order to provide as

proper answers to the users question as possible.

7
Chapter 2
Literature Survey

2.1. INTRODUCTION
A literature survey or a literature review in a project report is that section which shows

various analysis and research made in the field of your interest and the results already

published, taking into account the various parameters of the project and the extent of project.

Once the programmers start building the tool programmers need a lot of external support.

This support can be obtained from senior programmers, books or from the websites. It is the

most important part of your report as it gives you a direction in the area of your research. It

helps you set a goal for your analysis - thus giving you your problem of statement. Literature

survey is the most important sector in the software development process. Before developing

the tools and the associated designing the software it is necessary to determine the survey the

time factor, resource requirement etc., The consumer needs regarding online customer service

differs from person to person. The needs are also based off each persons personal needs. We

need to identify and anticipate these needs in order to completely and accurately meet them.

2.2.Literature Survey

1 .An Overview of Chatbot Technology


Eleni Adamopoulou and Lefteris Moussiades. 2020. An Overview of Chatbot Technology. An
Overview of Chatbot Technology | SpringerLink. Retrieved November 28, 2022 from
https://link.springer.com/chapter/10.1007/978-3-030-49186-4_31

Artificial Intelligence (ΑΙ) increasingly integrates our daily lives with the creation and

analysis of intelligent software and hardware, called intelligent agents. Intelligent agents can

do a variety of tasks ranging from labor work to sophisticated operations. A chatbot is a

typical example of an AI system and one of the most elementary and widespread examples of

8
intelligent Human-Computer Interaction (HCI) [1]. It is a computer program, which responds

like a smart entity when conversed with through text or voice and understands one or more

human languages by Natural Language Processing (NLP) [2]. In the lexicon, a chatbot is

defined as “A computer program designed to simulate conversation with human users,

especially over the Internet” [3]. Chatbots are also known as smart bots, interactive agents,

digital assistants, or artificial conversation entities.

Chatbots can mimic human conversation and entertain users but they are not built only for

this. They are useful in applications such as education, information retrieval, business, and e-

commerce [4]. They became so popular because there are many advantages of chatbots for

users and developers too. Most implementations are platform-independent and instantly

available to users without needed installations. Contact to the chatbot is spread through a

user’s social graph without leaving the messaging app the chatbot lives in, which provides

and guarantees the user’s identity. Moreover, payment services are integrated into the

messaging system and can be used safely and reliably and a notification system re-engages

inactive users. Chatbots are integrated with group conversations or shared just like any other

contact, while multiple conversations can be carried forward in parallel. Knowledge in the

use of one chatbot is easily transferred to the usage of other chatbots, and there are limited

data requirements. Communication reliability, fast and uncomplicated development

iterations, lack of version fragmentation, and limited design efforts for the interface are some

of the advantages for developers too.

2. AI-based Chatbot Service for Financial Industry - Takuma Okuda ,


Sanae Shoda

Introducing automation through the use of a chatbot makes it possible to respond to customer

inquiries 24/7. For example, applying a chatbot to a business in which operators make up a

9
big percentage of human resources as in a call center has the potential of making business

operations vastly more efficient. However, automating by chatbots has not yet reached a

point at which all requests can be handled, so there is a need to establish and apply

technology that can satisfy service requirements. With this in mind, Fujitsu has undertaken

the development of a hybrid chatbot that is capable of combining technologies such as

rulebased scenarios, FAQ searching, and text mining with machine learning. This paper

describes trends and examples surrounding the business application of chatbots and presents

the features of a chatbot product developed by Fujitsu for the financial industry.

3. Rule-Based Chatbot Integration into Software Engineering Course

Binkis, Mikas, et al. “Rule-Based Chatbot Integration Into Software Engineering Course.” Rule-
Based Chatbot Integration Into Software Engineering Course | SpringerLink, 7 Oct. 2021,
link.springer.com/chapter/10.1007/978-3-030-88304-1_29.

A Chatbot refers to software that can perform services based on commands or answers given

by a user during an online conversation. Chatbots are applied in different areas ranging from

pure entertainment solutions to learning support systems. In this article, we investigate

Chatbot systems as a way to support learners during educational video sessions. We propose

a rule-based Chatbot system that uses speech recognition and synthesized answers for

increased immersiveness and for supporting the learners with different sensual perceptions.

We introduce the design methodology we followed while creating a Chatbot system, explain

the Chatbot behavior from learner and teacher perspectives and describe the system structure.

The system was validated using the System Usability Scales (SUS) methodology. It shows

that the current implementation has an average usability score; therefore, it needs

improvement. On the other hand, the survey shows a positive learners attitude towards the

proposed system.

10
4. An overview of artificial intelligence based chatbots and an example

chatbot application

N. Albayrak, A. Özdemir and E. Zeydan, "An overview of artificial intelligence based


chatbots and an example chatbot application," 2018 26th Signal Processing and
Communications Applications Conference (SIU), 2018, pp. 1-4, doi:
10.1109/SIU.2018.8404430.

ChatBot can be described as software that can chat with people using artificial intelligence.

These software are used to perform tasks such as quickly responding to users, informing

them, helping to purchase products and providing better service to customers. In this paper,

we present the general working principle and the basic concepts of artificial intelligence

based chatbots and related concepts as well as their applications in various sectors such as

telecommunication, banking, health, customer call centers and e-commerce. Additionally, the

results of an example chabbot for donation service developed for telecommunication service

provider are presented using the proposed architecture.

5. AI-based chatbots in customer service and their effects on user

compliance

Adam, Martin, et al. “AI-based Chatbots in Customer Service and Their Effects on User Compliance
- Electronic Markets.” SpringerLink, 17 Mar. 2020, link.springer.com/article/10.1007/s12525-020-
00414-7.
Communicating with customers through live chat interfaces has become an increasingly

popular means to provide real-time customer service in many e-commerce settings. Today,

human chat service agents are frequently replaced by conversational software agents or

chatbots, which are systems designed to communicate with human users by means of natural

language often based on artificial intelligence (AI). Though cost- and time-saving

opportunities triggered a widespread implementation of AI-based chatbots, they still

11
frequently fail to meet customer expectations, potentially resulting in users being less

inclined to comply with requests made by the chatbot. Drawing on social response and

commitment-consistency theory, we empirically examine through a randomized online

experiment how verbal anthropomorphic design cues and the foot-in-the-door technique

affect user request compliance. Our results demonstrate that both anthropomorphism as well

as the need to stay consistent significantly increase the likelihood that users comply with a

chatbot’s request for service feedback. Moreover, the results show that social presence

mediates the effect of anthropomorphic design cues on user compliance.

Communicating with customers through live chat interfaces has become an increasingly

popular means to provide real-time customer service in e-commerce settings. Customers use

these chat services to obtain information (e.g., product details) or assistance (e.g., solving

technical problems). The real-time nature of chat services has transformed customer service

into a two-way communication with significant effects on trust, satisfaction, and repurchase

as well as WOM intentions (Mero 2018). Over the last decade, chat services have become the

preferred option to obtain customer support (Charlton 2013). More recently, and fueled by

technological advances in artificial intelligence (AI), human chat service agents are

frequently replaced by conversational software agents (CAs) such as chatbots, which are

systems such as chatbots designed to communicate with human users by means of natural

language (e.g., Gnewuch et al. 2017; Pavlikova et al. 2003; Pfeuffer et al. 2019a). Though

rudimentary CAs emerged as early as the 1960s (Weizenbaum 1966), the “second wave of

artificial intelligence” (Launchbury 2018) has renewed the interest and strengthened the

commitment to this technology, because it has paved the way for systems that are capable of

more human-like interactions (e.g., Gnewuch et al. 2017; Maedche et al. 2019; Pfeuffer et al.

2019b). However, despite the technical advances, customers continue to have unsatisfactory

encounters with CAs that are based on AI. CAs may, for instance, provide unsuitable

12
responses to the user requests, leading to a gap between the user’s expectation and the

system’s performance (Luger and Sellen 2016; Orlowski 2017). With AI-based CAs

displacing human chat service agents, the question arises whether live chat services will

continue to be effective, as skepticism and resistance against the technology might obstruct

task completion and inhibit successful service encounters. Interactions with these systems

might thus trigger unwanted behaviors in customers such as a noncompliance that can

negatively affect both the service providers as well as users (Bowman et al. 2004). However,

if customers choose not to conform with or adapt to the recommendations and requests given

by the CAs this calls into question the raison d’être of this self-service technology (Cialdini

and Goldstein 2004).

To address this challenge, we employ an experimental design based on an AI-based chatbot

(hereafter simply “chatbot”), which is a particular type of CAs that is designed for turn-by-

turn conversations with human users based on textual input. More specifically, we explore

what characteristics of the chatbot increase the likelihood that users comply with a chatbot’s

request for service feedback through a customer service survey. We have chosen this scenario

to test the user’s compliance because a customer’s assessment of service quality is important

and a universally applicable predictor for customer retention (Gustafsson et al. 2005).

6. A Review of AI Based Medical Assistant Chatbot


Chetan Bulla, Chinmay Parushetti, Akshata Teli, Samiksha Aski, Sachin
Koppad
This is now the age of smart computer. Machines have started to impersonate as human, with

the advent of artificial intelligence, machine learning, and deep learning. Chatbot is

classified as conversational software agents enabled by natural language processing, and is

an excellent example of such system. A Chatbot is a program which allows the user to start a

13
conversation with the machine. This is a platform focused on Artificial Intelligence (AI),

which can be developed as messaging applications, web applications, or smartphone

applications. A chatbot represents machine that answers questions using Natural Language

Processing (NLP). Formulating natural language answers to the questions. Chatbots create a

difference in the world of nursing and provide a simple way to handle people from

professional organizations. Health chatbots are capable of running one-on-one patient

communications and of reviewing specific patient queries. This program aims to investigate

the existing e healthcare structure involving a complex interaction with human machines and

proposes an alternate method: a chat interface designed and configured to act and interact

with patients like a human being.

14
Chapter 3. System Design

3.1. Natural Language Processing (NLP)

Natural language processing (NLP) refers to the branch of computer science—and more

specifically, the branch of artificial intelligence or AI—concerned with giving computers the

ability to understand text and spoken words in much the same way human beings can.

NLP combines computational linguistics—rule-based modeling of human language—with

statistical, machine learning, and deep learning models. Together, these technologies enable

computers to process human language in the form of text or voice data and to ‘understand’ its

full meaning, complete with the speaker or writer’s intent and sentiment.

Natural language processing strives to build machines that understand and respond to text or

voice data—and respond with text or speech of their own—in much the same way humans

do.

Python and the Natural Language Toolkit (NLTK)

The Python programming language provides a wide range of tools and libraries for attacking

specific NLP tasks. Many of these are found in the Natural Language Toolkit, or NLTK, an

open source collection of libraries, programs, and education resources for building NLP

programs.

The NLTK includes libraries for many of the NLP tasks plus libraries for subtasks, such as

sentence parsing, word segmentation, stemming and lemmatization (methods of trimming

15
words down to their roots), and tokenization (for breaking phrases, sentences, paragraphs and

passages into tokens that help the computer better understand the text). It also includes

libraries for implementing capabilities such as semantic reasoning, the ability to reach logical

conclusions based on facts extracted from text.

3.2. Advantages of Natural Language Processing

 The accuracy of the answer increases with the amount of relevant information

provided in the questions.

 Structuring a high unstructured data source.

 Users can ask questions about any subject and get a direct response in seconds.

 It is easy to implement.

 Using a program is less costly than hiring a person. A person can take two or three

times longer than a machine to execute the tasks mentioned.

 NLP system provides answers to the questions in natural language.

 Allow you to perform more language-based data compares to a human being without

fatigue and in an unbiased and consistent way.

 NLP process help computer communicate with a human in their language and scales

other language-related tasks.

 It is a faster customer service response time.

3.3. Disadvantage of Natural Language Processing

 If it is necessary to develop a model with a new one without using a pre-trained

model, it can take a week to achieve a good performance depending o the amount of

data.

 The system is built for a single and specific task only, it is unable to adapt to new

domains and problems because of limited functions.

16
 In complex query language, the system may not be able to provide the correct answer

it a question that is poorly worded or ambiguous.

 It is not 100% reliable, It is never 100% dependable. There is the possibility of error

in its prediction and results.

3.4. Architecture Diagram

3.1 ARCHITECTURE DIAGRAM

3.5. Hardware Requirements

• Modern Operating System

 Windows 7 or 10

 Mac OS X 10.11 or higher, 64-bit

 Linux: RHEL 6/7, 64-bit

• X86 64-bit CPU

• 32 GB RAM

• 3 GB Storage

3.6. Software Requirements

• Programming Language - Python 3.9

17
• IDE - Pycharm

• Nltk module

• Tensorflow module

Chapter 4. Implementation and Analysis

4.1. Python Library

A Python library is a collection of related modules. It contains bundles of code that can be

used repeatedly in different programs. It makes Python Programming simpler and convenient

for the programmer. As we don’t need to write the same code again and again for different

programs. Python libraries play a very vital role in fields of Machine Learning, Data Science,

Data Visualization, etc.

Python libraries that are used in the project are:

 Nltk

 Tensorflow

 Numpy

 Random

 Pickle

Nltk:

The Natural Language Toolkit (NLTK) is a platform used for building Python programs that

work with human language data for applying in statistical natural language processing (NLP).

It contains text processing libraries for tokenization, parsing, classification, stemming,

tagging and semantic reasoning. It also includes graphical demonstrations and sample data

18
sets as well as accompanied by a cook book and a book which explains the principles behind

the underlying language processing tasks that NLTK supports.

It comes with a hands-on guide that introduces topics in computational linguistics as well as

programming fundamentals for Python which makes it suitable for linguists who have no

deep knowledge in programming, engineers and researchers that need to delve into

computational linguistics, students and educators.

Tensorflow:

TensorFlow is a high-performance numerical calculation library that is open source. It is also

employed in deep learning algorithms and machine learning algorithms. It was created by the

Google Brain team researchers within the Google AI organization and is currently widely

utilized by math, physics, and machine learning researchers for complicated mathematical

computations. TensorFlow is designed to be fast, and it employs techniques such as XLA

(XLA or Accelerated Linear Algebra is a domain-specific compiler for linear algebra that can

accelerate TensorFlow models with potentially no source code changes.) to do speedy linear

algebra computations.

NumPy:

NumPy is one of the most widely used open-source Python libraries, focusing on scientific

computation. It features built-in mathematical functions for quick computation and supports

big matrices and multidimensional data. “Numerical Python” is defined by the term

“NumPy.” It can be used in linear algebra, as a multi-dimensional container for generic data,

and as a random number generator, among other things. Some of the important functions in

NumPy are arcsin(), arccos(), tan(), radians(), etc. NumPy Array is a Python object which

defines an N-dimensional array with rows and columns. In Python, NumPy Array is preferred

over lists because it takes up less memory and is faster and more convenient to use.

Random:

19
Python Random module is an in-built module of Python which is used to generate random

numbers. These are pseudo-random numbers means these are not truly random. This module

can be used to perform random actions such as generating random numbers, print random a

value for a list or string, etc.

Pickle:

Pickle in Python is primarily used in serializing and deserializing a Python object structure.

In other words, it’s the process of converting a Python object into a byte stream to store it in a

file/database, maintain program state across sessions, or transport data over the network. The

pickled byte stream can be used to re-create the original object hierarchy by unpickling the

stream.

4.2. Data

The crucial element in artificial intelligence tasks is the data. The results will be highly

influenced by the data that are given, how are they formatted, their consistency, their

relevance to the subject at hand and so on. At this step, many questions should be answered

in order to guarantee that the results will be accurate and relevant. The data that is used

should be clearly stated, in this case, with proper patterns and responses

4.3. Software Description

4.3.1. Python

Python is an interpreted, object-oriented, high-level programming language with dynamic

semantics. Its high-level built in data structures, combined with dynamic typing and dynamic

binding, make it very attractive for Rapid Application Development, as well as for use as a

scripting or glue language to connect existing components together. Python's simple, easy to

learn syntax emphasizes readability and therefore reduces the cost of program maintenance.

20
Python supports modules and packages, which encourages program modularity and code

reuse. The Python interpreter and the extensive standard library are available in source or

binary form without charge for all major platforms, and can be freely distributed.

Python is the simplest language of all the programming languages, and in reality, is one-fifth

when compared with other OOP languages. This is why it is currently among the most well-

known languages in the marketplace.

Python comes with Prebuilt Libraries such as Numpy to perform scientific calculations, Scipy

for advanced computing, and Pybrain for machine learning (Python Machine Learning),

making it among the top languages for AI.

Python developers all over the globe offer extensive support and assistance through tutorials

and forums, helping the programmer much easier than another popular language.

Python is platform-independent and therefore is among the most adaptable and well-known

options for various platforms and technologies, with minimal modifications to the basics of

coding.

Python has the greatest flexibility among other programs, with the option of choosing among

OOPs method and scripting. Additionally, you can use the IDE to search for all codes and be

a blessing to developers struggling with different algorithms.

4.3.2. Pycharm

PyCharm is an Integrated Development Environment (IDE) used for programming in Python.

It provides code analysis, a graphical debugger, an integrated unit tester, integration with

version control systems (VCSes), and supports web development with Django. PyCharm is

developed by the Czech company JetBrains.

21
It is cross-platform working on Windows, Mac OS X and Linux. PyCharm has a Professional

Edition, released under a proprietary license and a Community Edition released under the

Apache License. PyCharm Community Edition is less extensive than the Professional

Edition.

4.4. Sample Coding

training.py:
import nltk
from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()
import json
import pickle

import numpy as np
from tensorflow import keras
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']:
w = nltk.word_tokenize(pattern)
words.extend(w)
documents.append((w, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])

words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in


ignore_words]
words = sorted(list(set(words)))
classes = sorted(list(set(classes)))
print(len(documents), "documents")
print(len(classes), "classes", classes)
print(len(words), "unique lemmatized words", words)

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


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

training = []
output_empty = [0] * len(classes)
for doc in documents:

22
bag = []
pattern_words = doc[0]
pattern_words = [lemmatizer.lemmatize(word.lower()) for word in
pattern_words]

for w in words:
bag.append(1) if w in pattern_words else bag.append(0)
output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1

training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)

train_x = list(training[:, 0])


train_y = list(training[:, 1])
print("Training data created")

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'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)


model.compile(loss='categorical_crossentropy', optimizer=sgd,
metrics=['accuracy'])

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")

chatbot.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):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word.lower()) for word in
sentence_words]

23
return sentence_words

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


sentence_words = clean_up_sentence(sentence)
bag = [0] * len(words)
for s in sentence_words:
for i, w in enumerate(words):
if w == s:
bag[i] = 1
if show_details:
print("found in bag: %s" % w)
return (np.array(bag))

def predict_class(sentence, model):


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]
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

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['response'])
break
return result

def chatbot_response(msg):
ints = predict_class(msg, model)
res = getResponse(ints, intents)
return res
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')

ChatLog.config(state=DISABLED)
ChatLog.yview(END)

24
base = Tk()
base.title("Welcome to SEC")
base.geometry("400x500")
base.resizable(width=FALSE, height=FALSE)
ChatLog = Text(base, bd=0, bg="white", height="8", width="50",
font="Arial", wrap=WORD)
ChatLog.pack()
ChatLog.config(state=DISABLED)
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set

SendButton = Button(base, font=("Verdana", 12, 'bold'), text="Send",


width="12", height=5, bd=0, bg="#3293de", activebackground="#3c9d9b",
fg='#ffffff', command=send)
EntryBox = Text(base, bd=0, bg="white", width="29", height="5",
font="Arial", wrap=WORD)
EntryBox.pack()scrollbar.place(x=376, y=6, height=386)
ChatLog.place(x=6, y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)

base.mainloop()

4.5.Sample Output

4.1 CHATBOT

25
4.2 USER REQUEST AND RESPONSE 1

4.3 USER REQUEST AND RESPONSE 2

26
4.4 USER REQUEST AND RESPONSE 3

Chapter 5. Conclusion

In conclusion, a method to resolve user queries via a chatbot has been developed. Here we

have used NLP technologies to recognise words and sentences of the user input to further

increase the efficiency and accuracy of the chatbot responses. The chatbot can now read,

recognise and respond appropriately to the user queries so that the users can get their queries

resolved as quickly and efficiently as possible. The artificial intelligence techniques have

been implemented to help facilitate the functioning of this chatbot.

27
References

1. Chatbot Development Using Python by Shreyashkar Sharma from School Of

Computing Science And Engineering, Galgotias University, Greater Noida

https://ijcrt.org/papers/IJCRT2007585.pdf

2. Development Of Chatterbot Using Python by P. Shanmugapriya, and Harini M

https://www.ijcaonline.org/archives/volume176/number21/shanmugapriya-2020-ijca-

920184.pdf

3. Python Chatbot Project – Learn To Build Your First Chatbot Using NLTK & Keras

by Isaac Ikwuegbu from IU International University of Applied Sciences

https://www.researchgate.net/publication/358214948

28
4. An Overview of Chatbot Technology - Eleni Adamopoulou and Lefteris Moussiades.

2020. An Overview of Chatbot Technology. An Overview of Chatbot Technology |

SpringerLink. Retrieved November 28, 2022 from

https://link.springer.com/chapter/10.1007/978-3-030-49186-4_31

5. AI-based Chatbot Service for Financial Industry - Takuma Okuda , Sanae Shoda

6. Rule-Based Chatbot Integration into Software Engineering Course Binkis, Mikas, et

al. “Rule-Based Chatbot Integration Into Software Engineering Course.” Rule-Based

Chatbot Integration Into Software Engineering Course | SpringerLink, 7 Oct. 2021,

link.springer.com/chapter/10.1007/978-3-030-88304-1_29.

7. An overview of artificial intelligence based chatbots and an example chatbot

application - N. Albayrak, A. Özdemir and E. Zeydan, "An overview of artificial

intelligence based chatbots and an example chatbot application," 2018 26th Signal

Processing and Communications Applications Conference (SIU), 2018, pp. 1-4, doi:

10.1109/SIU.2018.8404430.

8. AI-based chatbots in customer service and their effects on user compliance - Adam,

Martin, et al. “AI-based Chatbots in Customer Service and Their Effects on User

Compliance - Electronic Markets.” SpringerLink, 17 Mar. 2020,

link.springer.com/article/10.1007/s12525-020-00414-7.

9. A Review of AI Based Medical Assistant Chatbot - Chetan Bulla, Chinmay

Parushetti, Akshata Teli, Samiksha Aski, Sachin Koppad

10. An intelligent knowledge-based chatbot for customer service

Eric W.T. Ngai, Maggie C.M. Lee, Mei Luo, Patrick S.L. Chan, Tenglu Liang,

An intelligent knowledge-based chatbot for customer service,

https://doi.org/10.1016/j.elerap.2021.101098.

(https://www.sciencedirect.com/science/article/pii/S1567422321000703)

29
11. Application of AI based Chatbot Technology in the Industry – Park, Arum; Lee, Sae

Bom ; Song, Jaemin

30

You might also like