Chatbots, an intelligent assistants which/who can interact with opposite parties and address the concerns or respond to simple questions or questions that are generic or non-generic in nature where we can put pre-determined answers and actions, widely popular in lot of industries especially in customer care support to do some mundane stuff like providing information, redirecting customer requests to respective teams and also call out actions to respond to customer query on behalf of support teams.
I will be writing a series of posts how to create your own chatbots (as I practice) and do some operational stuff we do as DBA.
General Architecture of Chatbot
In this post, I will be explaining how to create a simple chatbot with python script using interactive text and speech way.
Requirements
- Install Python 3+ on your machine
- Install pycharm
- Install ChatterBot , PyAudi0, SpeechRecognition, chatterbot-corpus, chatterbot-voice using PIP
Once installed, run a simple snippet below, before that we need to train our bot with set of questions, look at this chats.txt file some random sample questions and answers we have created.
ChatBot : Interactive Text
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
bot = ChatBot('MyChatBot')
bot.set_trainer(ListTrainer)
conversation = open('chats.txt', 'r').readlines()
bot.train(conversation)
while True: message = input('You:')
if message.strip() != 'Bye':
reply = bot.get_response(message)
print('ChatBot:', reply)
if message.strip() == 'Bye':
print('ChatBot:Bye')
break
Let me explain,
- Lines in red, to call out chatterbot module given name for my chat as MyChatBot and put that in bot variable.
- Lines in blue, Train our chatbot using the pre determined Questions & Answers and train the conversation bot.train.
- Lines in gree, some logic section
- Lines in purple, message input i.e customer, bot will respond to our message.
- Once received Bye from us the chat will terminate. Simple isnt it.
Chatbot: Speech Recognition
import speech_recognition as sr # import the library r = sr.Recognizer() # initialize recognizer
with sr.Microphone() as source: # mention source it will be either Microphone or audio
files. print("Speak Anything :")
audio = r.listen(source) # listen to the source
try:
text = r.recognize_google(audio) # use recognizer to convert our audio into text
part. print("You said : {}".format(text))
except: print("Sorry could not recognize your voice") # In case of voice not recognized clearly
Let me explain,
- Lines in red, to call out speech recognition module and initialize it.
- Lines in green, some logic to loop into the interaction.
- Lines in Purple, listen your voice and respond/print the same in the chat window.
Watch out the chatbot actions in this videos.
Simple isn't it, but not that simple there's too much to learn and do, I will write more posts as series as I progress.
Hope you enjoyed it.
-Suresh
Follow Me!!!