Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Natural Language Processing using Python/ChatBot.ipynb
3074 views
Kernel: Python 3 (ipykernel)

What is ChatBot?

  • A chatbot, short for chat robot or chatterbot, is a computer program or artificial intelligence (AI) application designed to conduct a conversation with human users through natural language processing. It simulates human conversation and interaction, providing responses to the user's input or questions in a manner that is often indistinguishable from communication with a real person.

  • Chatbots can be integrated into various platforms, such as websites, messaging apps, social media platforms, and customer service systems.

image.png

Real time use and Applications

  • Customer support: Chatbots can handle frequently asked questions and provide instant assistance to customers, reducing the need for human intervention in basic inquiries.

  • Information retrieval: They can fetch data from databases, websites, or other sources to provide users with relevant information.

  • Virtual assistants: Chatbots can help users with tasks like setting reminders, scheduling appointments, and managing to-do lists.

  • Entertainment: Some chatbots are designed purely for entertainment purposes, engaging users in fun conversations or games.

  • Language learning: Chatbots can help users practice and improve their language skills through interactive conversations.

  • E-commerce: Chatbots can assist customers in finding products, making recommendations, and facilitating the purchasing process.

  • Education: Chatbots can be used in educational settings to support learning, answer questions, and provide explanations.

Chatbots can range from simple rule-based systems that follow predefined scripts to more advanced AI-based models that use machine learning techniques to understand and generate human-like responses. The evolution of natural language processing and machine learning technologies has significantly improved the capabilities and effectiveness of chatbots, making them increasingly prevalent in various industries and applications

Chat – Chat is a class that contains complete logic for processing the text data which the chatbot receives and find useful information out of it

reflections – is a dictionary containing basic input and corresponding outputs. You can also create your own dictionary with more responses you want.

import nltk from nltk.chat.util import Chat, reflections import warnings #warnings.filterwaring("ignore")
reflections = { "hello" : "Hi", "i want" : "you want", "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" }

Pairs are framed conversations. You can create it according to your applications

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 suyashi. my nick name is Ashi!",] ], [ r"how are you ?", ["I'm doing great and what about You ?",] ], [ r"sorry (.*)", ["Its alright","Its OK, never mind",] ], [ r"I am fine", ["I am also always fine. you need some help?",] ], [ r"i'm (.*) doing good", ["Nice to hear that","How can I help you any issues that i can solve for you?)",] ], [ r"(.*) age?", ["I am always sweet 16?",] ], [ r"what (.*) want ?", ["talk to me for any help",] ], [ r"(.*) created ?", ["Suyashi created me using Python's NLTK library ","Now you also know it and create one for yourself ;)",] ], [ r"(.*) you love ?", ['Talking Talking Talking and you?',] ], [ r"You know Python (.*)?", ["Yes","This is silly Question","I know it so i can talk",] ], [ r"i work in (.*)?", ["i am looking for job do you have any thing for me kidding!!!.",] ], [ r"(.*)raining in (.*)", ["No rain since last week here in %2","Damn its raining too much here in %2"] ], [ r"ok", ["Any help needed form me ",] ], [ r"(.*) (sports|game) ?", ["I'm a very big fan of cricket",] ], [ r"who (.*) sportsperson ?", ["Virat","Sachin",] ], [ r"what do you do ?", ["I am virtual Assistant"] ], [ 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", ["By take care. See you soon :) ","It was nice talking to you. See you soon :)"] ], ]
def chatBot(): print("Hi! I will talk to you i am Ashi") chatBot = Chat(pairs, reflections) chatBot.converse() #initiate the conversation if __name__ == "__main__": chatBot()
Hi! I will talk to you i am Ashi >Hi Hey there >hello Hello >What is your name? I am a bot created by suyashi. my nick name is Ashi! >what do you do? I am virtual Assistant >ok Any help needed form me >bye None >quir None >quit By take care. See you soon :)

Example to create Tech support ChatBot Tk interface and more interactive

## Import lib import tkinter as tk from tkinter import scrolledtext from nltk.chat.util import Chat, reflections
# Tech support responses tech_support_responses = [ (r"Hello/hi", ["Hi, How can i support you?"]), (r"my PC not turning ON", ["Have you checked if it's plugged in?"]), (r"Yes", ["restart and connet to internet"]), (r"No", ["Please explain in detail"]), (r"I can't connect to the internet", ["Have you tried restarting your router?"]), (r"my PC is running slow", ["Try clearing your browser cache."]), (r"OK", ["It worked?"]), (r"how do I reset my password\?", ["You can reset your password by visiting our website and following the instructions."]), (r".*", ["Sorry, I cannot answer this."]), (r" thank you", ["Bye! hope your issue is solved" ]) ]
# Create a chatbot chatbot = Chat(tech_support_responses, reflections) # Function to handle sending a message and getting a response def send_message(): message = user_input.get() user_input.delete(0, tk.END) response = chatbot.respond(message) chat_history.config(state=tk.NORMAL) chat_history.insert(tk.END, "You: " + message + "\n", "user") chat_history.insert(tk.END, "Bot: " + response + "\n", "bot") chat_history.config(state=tk.DISABLED) chat_history.see(tk.END) # Create the main window root = tk.Tk() root.title("ITHub Support Chatbot") # Create widgets chat_history = scrolledtext.ScrolledText(root, wrap=tk.WORD) user_input = tk.Entry(root) send_button = tk.Button(root, text="Send", command=send_message) # Configure chat history chat_history.config(state=tk.DISABLED) chat_history.tag_config("user", foreground="blue") chat_history.tag_config("bot", foreground="red") # Place widgets on the grid chat_history.grid(row=0, column=0, columnspan=2, padx=5, pady=5) user_input.grid(row=1, column=0, padx=5, pady=5, sticky="ew") send_button.grid(row=1, column=1, padx=5, pady=5, sticky="e") # Start the main loop root.mainloop()

More Dynamic with selection

import tkinter as tk from tkinter import scrolledtext from nltk.chat.util import Chat, reflections import time ## Tech support responses tech_support_responses = [ (r"Hello", ["Hi, How can i support you?"]), (r"my PC not turning ON", ["Have you checked if it's plugged in?"]), (r"Yes", ["restart and connet to internet"]), (r"No", ["Please explain in detail"]), (r"I can't connect to the internet", ["Have you tried restarting your router?"]), (r"my PC is running slow", ["Try clearing your browser cache"]), (r"OK", ["It worked?"]), (r"how do I reset my password\?", ["You can reset your password by visiting our website and following the instructions"]) , (r".*", ["Sorry, I cannot answer this."]), (r" Thanks", ["Bye! hope your issue is solved" ]) ] # Responses for the counselling assistant counselling_responses = [ (r"Hello", ["Hi, How are you feeling today?"]), (r"I feel (.*)", ["Why do you feel {0}?", "I'm sorry to hear that. Can you tell me more about why you feel {0}?"]), (r"(.*) (depressed|sad|unhappy|lonely|dying)", ["I'm here to listen. What's been bothering you?", "It's okay to feel down sometimes. What's been on your mind?"]), (r"I need someone to talk to", ["I'm here to listen. You can share anything with me"]), (r".*", ["Sorry, I cannot help you in this"]), (r"Thanks and Bye", ["Bye! hope your issue is solved" ]) , ] # Create chatbots tech_support_chatbot = Chat(tech_support_responses, reflections) counselling_chatbot = Chat(counselling_responses, reflections) # Function to handle sending a message and getting a response def send_message(): message = user_input.get() user_input.delete(0, tk.END) chat_history.config(state=tk.NORMAL) chat_history.insert(tk.END, "You: " + message + "\n", "user") chat_history.config(state=tk.DISABLED) chat_history.see(tk.END) # Show typing indicator chat_history.config(state=tk.NORMAL) chat_history.insert(tk.END, "Bot is typing...", "bot_typing") chat_history.see(tk.END) chat_history.config(state=tk.DISABLED) root.update_idletasks() # Force GUI update to show the typing indicator # Simulate bot response delay time.sleep(1) # Get bot response if chat_mode.get() == "Tech Support": response = tech_support_chatbot.respond(message) else: response = counselling_chatbot.respond(message) # Remove typing indicator and display bot response chat_history.config(state=tk.NORMAL) chat_history.delete("bot_typing.first", "bot_typing.last") # Remove typing indicator chat_history.insert(tk.END, "Bot: " + response + "\n", "bot") chat_history.config(state=tk.DISABLED) chat_history.see(tk.END) # Create the main window root = tk.Tk() root.title("Chatbot Counselling & Tech Support") # Create widgets chat_history = scrolledtext.ScrolledText(root, wrap=tk.WORD) user_input = tk.Entry(root) send_button = tk.Button(root, text="Send", command=send_message) chat_mode = tk.StringVar(value="Tech Support") mode_selector = tk.Radiobutton(root, text="Tech Support", variable=chat_mode, value="Tech Support") mode_selector2 = tk.Radiobutton(root, text="Counselling", variable=chat_mode, value="Counselling") # Configure chat history chat_history.config(state=tk.DISABLED) chat_history.tag_config("user", foreground="blue") chat_history.tag_config("bot", foreground="red") # Place widgets on the grid chat_history.grid(row=0, column=0, columnspan=2, padx=5, pady=5) user_input.grid(row=1, column=0, padx=5, pady=5, sticky="ew") send_button.grid(row=1, column=1, padx=5, pady=5, sticky="e") mode_selector.grid(row=2, column=0, padx=5, pady=5, sticky="w") mode_selector2.grid(row=2, column=1, padx=5, pady=5, sticky="w") # Start the main loop root.mainloop()