Create a simple chatbot with Python's NLTK library.

The beauty of a chatbot is how fantastic it is to communicate with someone by asking questions, sharing personal information, and not feeling judged at all. A chatbot is an AI-based program that uses natural language processing to interact with people and respond to their individual requests without human intervention.

Introduction to ChatBot

A chatbot is a smart application that helps an organization solve basic customer queries. Today, most companies and businesses from various sectors use chatbots in various ways to respond to their customers as quickly as possible. Chatbots also aid in increasing site traffic, which is the primary reason for businesses to use chatbots.

Customers' basic information such as name, email address, and query are requested by the chatbot. If a query is simple, such as a product fault, a booking error, or a need for information, it can be solved automatically; if the problem is complex, it passes the details to the human head and allows the customer to easily connect with the organization's manager.  And most of the customers like to deal and talk with a chatbot.

Why do we require Chatbots?

  • Humans cannot be active on-site 24/7, but chatbots can, and their response time is much faster than that of humans.
  • Low development costs As technology advances, many tools are being developed to aid in the development and integration of chatbots with little investment.
  • Human Resources Today, chatbots can communicate using text-to-speech technology, giving the impression that a human is speaking on the other end.
  • Business Branding Businesses are changing as a result of technological advancements, and chatbots are one of them. Chatbots also aid in the advertising and branding of an organization's products and services, as well as providing users with daily updates.

Different Types of ChatBot:-

Chatbots are classified into two types.

  1. Rule Based ChatBot:- As the name implies, there are some ground rules under which the chatbot operates. We train the chatbots on user intents and relevant responses, and based on these intents, the chatbot identifies the new user's intent and responds to him.                                                                 
  2. Self-Learning chatbots - Self-learning bots are extremely efficient because they can automatically detect and identify the user's intent. They are built with advanced Machine Learning, Deep Learning, and Natural Language Processing tools and techniques. Self-learning bots are further classified into two types.
    • Chatbots that use retrieval: Retrieval-based is similar to Rule-based in that predefined input patterns and responses are embedded.
    • Chatbots that are generated: It is based on the same phenomenon as Machine Translation, which is built using a neural network with two sequences.
The majority of organizations use self-learning chatbots in conjunction with the embedding of some rules, resulting in a hybrid version of both methods that makes the chatbot powerful enough to handle any situation that may arise during a conversation with a customer.

Let's create one ChatBot using Python:-

We now have a thorough understanding of the theory of chatbots and their future advancement. Let's get our hands dirty and create a simple rule-based chatbot in Python for ourselves.

Using the Python Tkinter module, we will create a text box and a button to submit user intent, and on the action, we will build a function that will match the user intent and respond to him on his intent. If you do not already have the Tkinter module installed, use the pip command to install it.

pip install tkinter
from tkinter import *
root = Tk()
root.title("Chatbot")
def send():
    send = "You -> "+e.get()
    txt.insert(END, "n"+send)
    user = e.get().lower()
    if(user == "hello"):
        txt.insert(END, "n" + "Bot -> Hi")
    elif(user == "hi" or user == "hii" or user == "hiiii"):
        txt.insert(END, "n" + "Bot -> Hello")
    elif(e.get() == "how are you"):
        txt.insert(END, "n" + "Bot -> fine! and you")
    elif(user == "fine" or user == "i am good" or user == "i am doing good"):
        txt.insert(END, "n" + "Bot -> Great! how can I help you.")
    else:
        txt.insert(END, "n" + "Bot -> Sorry! I dind't got you")
    e.delete(0, END)
txt = Text(root)
txt.grid(row=0, column=0, columnspan=2)
e = Entry(root, width=100)
e.grid(row=1, column=0)
send = Button(root, text="Send", command=send).grid(row=1, column=1)
root.mainloop()

Explanation: First, we created a blank window. Next, we added a text field using the entry method and a Button widget that, when triggered, calls the function to send and receive the chatbot response. To create a simple rule-based chatbot, we used a simple If-else control statement. You can also interact with the chatbot by running the application from the interface, as shown in the figure below.


Using the Python NLTK Library to Implement a Chatbot

NLTK stands for Natural language toolkit, which is used to deal with NLP applications such as chatbots. We will now use the NLTK library to advance our Rule-based chatbots. Please install the NLTK library first before working using the pip command.

pip instal nltk
The first step is to import the library and classes that we will be using.

import nltk
from nltk.chat.util import Chat, reflections
Chat - Chat is a class that contains complete logic for processing text data received by the chatbot and extracting useful information from it.
reflections - We also imported reflections, which is a dictionary with basic input and corresponding outputs. You can also make your own dictionary with additional responses. If you print reflections, they will look like this.

reflections = {
  "i am"       : "you are",
  "i was"      : "you were",
  "i"          : "you",
  "i'm"        : "you are",
  "i'd"        : "you would",
  "i've"       : "you have",
  "i'll"       : "you will",
  "my"         : "your",
  "you are"    : "I am",
  "you were"   : "I was",
  "you've"     : "I have",
  "you'll"     : "I will",
  "your"       : "my",
  "yours"      : "mine",
  "you"        : "me",
  "me"         : "you"
}

Let's get started on the logic for the NLTK chatbot.

After importing the libraries, we must first create rules. The following lines of code generate a simple set of rules. The first line describes the user input, which we took as raw string input, and the following line is our chatbot response. You can change the questions and answers in these pairs.

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, How are you today ?",]
    ],
    [
        r"hi|hey|hello",
        ["Hello", "Hey there",]
    ], 
    [
        r"what is your name ?",
        ["I am a bot created by CodeITronics. you can call me crazy!",]
    ],
    [
        r"how are you ?",
        ["I'm doing goodnHow about You ?",]
    ],
    [
        r"sorry (.*)",
        ["Its alright","Its OK, never mind",]
    ],
    [
        r"I am fine",
        ["Great to hear that, How can I help you?",]
    ],
    [
        r"i'm (.*) doing good",
        ["Nice to hear that","How can I help you?:)",]
    ],
    [
        r"(.*) age?",
        ["I'm a computer program dudenSeriously you are asking me this?",]
    ],
    [
        r"what (.*) want ?",
        ["Make me an offer I can't refuse",]
    ],
    [
        r"(.*) created ?",
        ["Raghav created me using Python's NLTK library ","top secret ;)",]
    ],
    [
        r"(.*) (location|city) ?",
        ['Indore, Madhya Pradesh',]
    ],
    [
        r"how is weather in (.*)?",
        ["Weather in %1 is awesome like always","Too hot man here in %1","Too cold man here in %1","Never even heard about %1"]
    ],
    [
        r"i work in (.*)?",
        ["%1 is an Amazing company, I have heard about it. But they are in huge loss these days.",]
    ],
    [
        r"(.*)raining in (.*)",
        ["No rain since last week here in %2","Damn its raining too much here in %2"]
    ],
    [
        r"how (.*) health(.*)",
        ["I'm a computer program, so I'm always healthy ",]
    ],
    [
        r"(.*) (sports|game) ?",
        ["I'm a very big fan of Football",]
    ],
    [
        r"who (.*) sportsperson ?",
        ["Messy","Ronaldo","Roony"]
    ],
    [
        r"who (.*) (moviestar|actor)?",
        ["Brad Pitt"]
    ],
    [
        r"i am looking for online guides and courses to learn data science, can you suggest?",
        ["Crazy_Tech has many great articles with each step explanation along with code, you can explore"]
    ],
    [
        r"quit",
        ["BBye take care. See you soon :) ","It was nice talking to you. See you soon :)"]
    ],
]

Following the creation of rule pairs, we will define a function to start the chat process. The function is very simple, greeting the user and asking for assistance. And the conversation begins by invoking a Chat class and passing it on to pairs and reflections.

def chat():
    print("Hi! My name is A.V.N.I. I am a chatbot.")
    chat = Chat(pairs, reflections)
    chat.converse()
#initiate the conversation
if __name__ == "__main__":
    chat()

We created an amazing Rule-based chatbot using only Python and the NLTK library. The nltk.chat works on various regex patterns present in user Intent and displays the output to the user. Let's run the app and chat with your custom chatbot.

Output


Hi! My name is A.V.N.I. I am a chatbot.
>Hello
Hello
>How are you
I'm doing goodnHow about You ?
>I am good too
None
>Tell me something
None
>

Notes at the End

Chatbots are the most popular Natural Language Processing application, and they are now simple to create and integrate with various social media handles and websites. Most Chatbots are now built with tools like Dialogflow, RASA, and others. This was a brief overview of chatbots to provide an understanding of how businesses are transforming through the use of data science and artificial intelligence.

Thank you for reading all the way through. If you have any questions, please leave them in the comments section.






Comments

Popular posts from this blog

Brief info on Feature Engineering

Learn Data Structure and Algorithms for Competitive Programming in 30 Days

Quick Guide on Quantum Computing