Create Web Based ChatBot in Python, Django, Flask

Learn how to create Chatbot in Python. I this tutorial, we will use Chatterbot Library for creating the chat bot. We will use Flask Framework for deploying the chatbot on web. This tutorial change be used with Django also.

Chatbot in Python, Flask, Django, Chatterbot

Every Chatbot has a theme. Our chatbot is going to Answer the Questions of User of Coronavirus Disease. It will greet the user, interact with them and give answers of Covid-19.

Installing Chatbot Required Libraries

All the libraries are installed in Virtualenv.

pip install Flask
pip install chatterbot
pip install chatterbot-corpus 

Creating Chatbot in Python

Now we have install chatterbot, we will create a chatbot.py file and paste the bellow code.

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer

# Creating ChatBot Instance
chatbot = ChatBot('CoronaBot')

 # Training with Personal Ques & Ans 
conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great.",
    "That is good to hear",
    "Thank you.",
    "You're welcome."
]

trainer = ListTrainer(chatbot)
trainer.train(conversation)

# Training with English Corpus Data 
trainer_corpus = ChatterBotCorpusTrainer(chatbot)
trainer_corpus.train(
    'chatterbot.corpus.english'
) 

In the above code, we are creating a chatterbot instance. Then we are training our chatbot with ListTrainer with our personal question and answers. Then we are using chatterbot corpus english data to train our chatbot.

Creating Web UI for Chatbot using Flask

As we have installed Flask, we will create a app.py file and paste the bellow code inside it.

from chatbot import chatbot
from flask import Flask, render_template, request

app = Flask(__name__)
app.static_folder = 'static'

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return str(chatbot.get_response(userText))

if __name__ == "__main__":
    app.run() 

In the above code, we are creating routes for our web application. In get_bot_response() we are taking input from html form and after processing chatbot giving response.

HTML Template for ChatBot

Create a folder templates and add this index.html inside it – Download.

Create a folder static, inside it create styles folder and inside it add this file style.cssDownload

The above file path should match like bellow –

D:/chatbot/static/styles/style.css
D:/chatbot/templates/index.html

In index.html file, we have written a script for sending the data which is input to chatbot form and take the response to append it to chatbot window.

Running Chatbot Project

Once the you have setup the project, we need to just run the flask app.

python app.py

If everything goes right, go to – http://localhost:5000/ and enjoy your own personal chatbot.

Note – If you see not see right answer for question, delete the .sqlite3 database file from your folder.

Optimizing and Adding Feature to Chatbot

We have created chatbot successfully, but it as basic example. We need to add more features to our chatbot.

Open your chatbot.py file and do some changes like

Replace

chatbot = ChatBot('CoronaBot',) 

with

chatbot = ChatBot(
    'CoronaBot',
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        'chatterbot.logic.MathematicalEvaluation',
        'chatterbot.logic.TimeLogicAdapter',
        'chatterbot.logic.BestMatch',
        {
            'import_path': 'chatterbot.logic.BestMatch',
            'default_response': 'I am sorry, but I do not understand. I am still learning.',
            'maximum_similarity_threshold': 0.90
        }
    ],
    database_uri='sqlite:///database.sqlite3'
) 

In above replacing, we have added default answer, database and added logic adapter which can answer maths and time questions.

Using file for question and answer

In the above, we have used conversation list. Now we will replace with it a file where question and answer are written inside it are loaded and fed to ListTrainer.

Replace

 # Training with Personal Ques & Ans 
conversation = [
    "Hello",
    "Hi there!",
    "How are you doing?",
    "I'm doing great.",
    "That is good to hear",
    "Thank you.",
    "You're welcome."
]

trainer = ListTrainer(chatbot)
trainer.train(conversation)

with

training_data_quesans = open('training_data/ques_ans.txt').read().splitlines()
training_data_personal = open('training_data/personal_ques.txt').read().splitlines()

training_data = training_data_quesans + training_data_personal

trainer = ListTrainer(chatbot)
trainer.train(training_data)  

We are loading data form training_data/ques_ans.txt and training_data/personal_ques.txt. You can download those files from here.

Project Github

19 Comments

Andrew Murdoch

Hallo Huzaif Sayyed,

I was really interested in creatiing the Chatbot following your instruction. Unfortunately it failed for me. I could not install the Chatterbox. Could it be that I have to use a 64bit version of Python. I am using Python v 3.7.3 (32bit)?

Could you please give advice about what versions you use to create the Chatbot?

Many thanks

Andrew

Reply
Huzaif Sayyed

Are you using VirtualEnv, Because it is very important. It won’t mess up with your core python code.

Reply
sheetal

i cannot install chatterbot-corpus in linux machine
i am getting error no matching distribution found

Reply
Andrew Murdoch

Dear Huzaif,

Yes I was using the VENV virtual environment – and 32 bit version of Python…on a Windows PC.

I want to install Chatterbot on a Raspberry Pi – but first of all to get it working I would install on a set-up that is known to work.

Could you advise what platform you are using – and what versions of OS and Python – this would really be helpful.

Many thanks

Andrew

Reply
Andrew Murdoch

I get a sea of red error messages when running the "pip install chatterbot" command line in the virtual environment.

I ran install setuptools to try & resolve this problem but to no avail.

Any help welcomed.

Reply
Ram Sankar

i have created this one in django,but i cannot get answer to my question
eg: hi
Not Found: /get
"GET /get?msg=hi HTTP/1.1" 404
please say what can i do???

Reply
BK

Hi, I keep getting this message
"GET /favicon.ico HTTP/1.1" 404 –

I placed an icon as well in the same name in the same place as that of app.py, still I am getting this error.

How to make this chat retrieve data from DB instead of just replying Q&A based chat?

Reply
BK

Added this in the HEAD section and the /favicon.ico error went off

<link rel="icon" href="data:,">

Reply
Nachiket

Hello can you plz help me change the background image in the index.html file

Reply
PHILAWON KASAR

hello sir,chatterbot cannot install install within the environment?please help!!

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *