Building A Machine learning chat-bot with flask framework and python

Creating a chatbot or adding chatbot features in your web apps is always nice it makes your apps look more friendly to your users you can achieve this in different ways with python with libraries like NLTK, Tensorflow but here I will be explaining how we can do this with a library called chatterbot . 
ChatterBot is a Python library that makes it easy to generate automated responses to a user’s input. With chatterbot we will create our chatbot app with python in our console, then we migrate the code to python web base using flask.

  • First type pip install chatterbot to install chatterbot
  • Create a main.py file or any file name of your choice

we need to import some couples of things from chatterbot and our operating system

from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
  • we need to create dataset for our chatbot to learn from since it will be a machine learning chatbot
  • Create folder called base
  • inside base we will have a txt file called dataset.txt

you can add your chat history you want your chatbot to learn from you can add

hi 
hello
how you doing
what up
hey
am good
lol
funny
yes it is funny

save it with dataset.txt

  • Add the following code to your main.py
bot = ChatBot('Friend') #create the bot
bot.set_trainer(ListTrainer) # Teacher
#bot.train(conv) # teacher train the bot
for knowledeg in os.listdir('base'):
BotMemory = open('base/'+ knowledeg, 'r').readlines()
bot.train(BotMemory)

This code will loop through our folder called base, it look for any file inside it since we are having a txt file it will read them line by line then our chatbot will learn one after the other we need to upgrade our code and relate it to flask

app = Flask(__name__)
@app.route('/home')
def index():
return render_template('index.html')
@app.route('/process',methods=['POST'])
def process():
user_input=request.form['user_input']
	bot_response=bot.get_response(user_input)
bot_response=str(bot_response)
print("Friend: "+bot_response)
return render_template('index.html',user_input=user_input,
bot_response=bot_response
)

if __name__=='__main__':
app.run(debug=True,port=5002)

the index route is to render the index.html to the screen and then you will be able to display the html content to the screen. the process route is to receive user input from the html form and send it to the bot the will receive it and bring out an output

  • Create a new folder name it templates in the same directory you save your main.py

add the following html code and save it as index.html inside the templates folder

< html >
< head>
< title>Friend Chatbot
< link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
< script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">< /script>
< script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
< script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
< body>
< div class="container">
< div class="alert alert-primary" role="alert">
User: {{user_input}}
< div class="alert alert-dark" role="alert">
Freind: {{bot_response}}
< /div>
< form  action="/process" method="POST">
< div class="form-group">
< label for="exampleInputEmail1">Friend Chatbot
< input type="text" name="user_input" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Talk to my friend">
  < button type="submit" class="btn btn-primary">Send
< /form>
< /div>
< /body>
< /html>

full code

from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
import os
bot = ChatBot('Friend') #create the bot
bot.set_trainer(ListTrainer) # Teacher
#bot.train(conv) # teacher train the bot
for knowledeg in os.listdir('base'):
BotMemory = open('base/'+ knowledeg, 'r').readlines()
bot.train(BotMemory)
app = Flask(__name__)
@app.route('/home')
def index():
return render_template('index.html')
@app.route('/process',methods=['POST'])
def process():
user_input=request.form['user_input']
bot_response=bot.get_response(user_input)
bot_response=str(bot_response)
print("Friend: "+bot_response)
return render_template('index.html',user_input=user_input,
bot_response=bot_response
)
if __name__=='__main__':
app.run(debug=True,port=5002)

source code: https://github.com/Abdulkereem/flask-machine-learning-chatbot

Video Tutorial

https://www.youtube.com/watch?v=ZEHSqhZYPZA&list=PLH_WdPqEuqE7eEcSqCFl9_3CcQ7-qEVmM