├── README.md ├── chatbot_model.h5 ├── chatgui.py ├── classes.pkl ├── intents.json ├── train_chatbot.py └── words.pkl /README.md: -------------------------------------------------------------------------------- 1 | # Chatbot-using-Python 2 | Build a chatbot using deep learning techniques. The chatbot will be trained on the dataset which contains categories (intents), pattern and responses. We use a special recurrent neural network (LSTM) to classify which category the user’s message belongs to and then we will give a random response from the list of responses. 3 | 4 | :white_check_mark: ## Getting Started 5 | 6 | - [x] Download all the files 7 | 8 | - [x] Open Command Prompt 9 | 10 | - [x] Get the control to the folder where your files are present 11 | 12 | - [x] Make sure your system has the following modules installed - 13 | tensorflow, keras, nltk, pickle. If not, then install the modules using the command - {pip install module_name}. If your system already has the module, it will show "Requirement already satisfied". 14 | 15 | - [x] Now we have to train and create the model. Hence execute the "train_chatbot.py" file using the following command - {python train_chatbot.py}. If the training is successful it will show model created. 16 | 17 | - [x] To open the GUI window and start conversation with the chatbot execute the "chatgui.py" file using the following command - {python chatgui.py}. It will open the GUI window. 18 | 19 | - [x] Write your text in the section on the right to the send button and click on "Send". Enjoy the responses ! 20 | 21 | 22 | !!! ERROR GUIDE !!! 23 | 24 | While executing the file "train_chatbot.py" if you get some error like - "ImportError: cannot import name 'tf_utils'", uninstall keras using the command - {pip uninstall keras}, then reinstall keras using the command - {pip install keras==2.2.0}. Try executing the file, i hope it works properly ! 25 | -------------------------------------------------------------------------------- /chatbot_model.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tridibsamanta/Chatbot-using-Python/5567c0847306ca345a3f49c54bb833a457bcc00c/chatbot_model.h5 -------------------------------------------------------------------------------- /chatgui.py: -------------------------------------------------------------------------------- 1 | #https://github.com/tridibsamanta/Chatbot-using-Python 2 | 3 | import nltk 4 | from nltk.stem import WordNetLemmatizer 5 | lemmatizer = WordNetLemmatizer() 6 | import pickle 7 | import numpy as np 8 | 9 | from keras.models import load_model 10 | model = load_model('chatbot_model.h5') 11 | import json 12 | import random 13 | intents = json.loads(open('intents.json').read()) 14 | words = pickle.load(open('words.pkl','rb')) 15 | classes = pickle.load(open('classes.pkl','rb')) 16 | 17 | 18 | def clean_up_sentence(sentence): 19 | # tokenize the pattern - split words into array 20 | sentence_words = nltk.word_tokenize(sentence) 21 | # stem each word - create short form for word 22 | sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] 23 | return sentence_words 24 | 25 | # return bag of words array: 0 or 1 for each word in the bag that exists in the sentence 26 | 27 | def bow(sentence, words, show_details=True): 28 | # tokenize the pattern 29 | sentence_words = clean_up_sentence(sentence) 30 | # bag of words - matrix of N words, vocabulary matrix 31 | bag = [0]*len(words) 32 | for s in sentence_words: 33 | for i,w in enumerate(words): 34 | if w == s: 35 | # assign 1 if current word is in the vocabulary position 36 | bag[i] = 1 37 | if show_details: 38 | print ("found in bag: %s" % w) 39 | return(np.array(bag)) 40 | 41 | def predict_class(sentence, model): 42 | # filter out predictions below a threshold 43 | p = bow(sentence, words,show_details=False) 44 | res = model.predict(np.array([p]))[0] 45 | ERROR_THRESHOLD = 0.25 46 | results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD] 47 | # sort by strength of probability 48 | results.sort(key=lambda x: x[1], reverse=True) 49 | return_list = [] 50 | for r in results: 51 | return_list.append({"intent": classes[r[0]], "probability": str(r[1])}) 52 | return return_list 53 | 54 | def getResponse(ints, intents_json): 55 | tag = ints[0]['intent'] 56 | list_of_intents = intents_json['intents'] 57 | for i in list_of_intents: 58 | if(i['tag']== tag): 59 | result = random.choice(i['responses']) 60 | break 61 | return result 62 | 63 | def chatbot_response(msg): 64 | ints = predict_class(msg, model) 65 | res = getResponse(ints, intents) 66 | return res 67 | 68 | 69 | #Creating GUI with tkinter 70 | import tkinter 71 | from tkinter import * 72 | 73 | 74 | def send(): 75 | msg = EntryBox.get("1.0",'end-1c').strip() 76 | EntryBox.delete("0.0",END) 77 | 78 | if msg != '': 79 | ChatLog.config(state=NORMAL) 80 | ChatLog.insert(END, "You: " + msg + '\n\n') 81 | ChatLog.config(foreground="#442265", font=("Verdana", 12 )) 82 | 83 | res = chatbot_response(msg) 84 | ChatLog.insert(END, "Bot: " + res + '\n\n') 85 | 86 | ChatLog.config(state=DISABLED) 87 | ChatLog.yview(END) 88 | 89 | 90 | base = Tk() 91 | base.title("Hello") 92 | base.geometry("400x500") 93 | base.resizable(width=FALSE, height=FALSE) 94 | 95 | #Create Chat window 96 | ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",) 97 | 98 | ChatLog.config(state=DISABLED) 99 | 100 | #Bind scrollbar to Chat window 101 | scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart") 102 | ChatLog['yscrollcommand'] = scrollbar.set 103 | 104 | #Create Button to send message 105 | SendButton = Button(base, font=("Verdana",12,'bold'), text="Send", width="12", height=5, 106 | bd=0, bg="#32de97", activebackground="#3c9d9b",fg='#ffffff', 107 | command= send ) 108 | 109 | #Create the box to enter message 110 | EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial") 111 | #EntryBox.bind("", send) 112 | 113 | 114 | #Place all components on the screen 115 | scrollbar.place(x=376,y=6, height=386) 116 | ChatLog.place(x=6,y=6, height=386, width=370) 117 | EntryBox.place(x=128, y=401, height=90, width=265) 118 | SendButton.place(x=6, y=401, height=90) 119 | 120 | base.mainloop() 121 | -------------------------------------------------------------------------------- /classes.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tridibsamanta/Chatbot-using-Python/5567c0847306ca345a3f49c54bb833a457bcc00c/classes.pkl -------------------------------------------------------------------------------- /intents.json: -------------------------------------------------------------------------------- 1 | {"intents": [ 2 | {"tag": "greeting", 3 | "patterns": ["Hi there", "How are you", "Is anyone there?","Hey","Hola", "Hello", "Good day"], 4 | "responses": ["Hello, thanks for asking", "Good to see you again", "Hi there, how can I help?"], 5 | "context": [""] 6 | }, 7 | {"tag": "goodbye", 8 | "patterns": ["Bye", "See you later", "Goodbye", "Nice chatting to you, bye", "Till next time"], 9 | "responses": ["See you!", "Have a nice day", "Bye! Come back again soon."], 10 | "context": [""] 11 | }, 12 | {"tag": "thanks", 13 | "patterns": ["Thanks", "Thank you", "That's helpful", "Awesome, thanks", "Thanks for helping me"], 14 | "responses": ["Happy to help!", "Any time!", "My pleasure"], 15 | "context": [""] 16 | }, 17 | {"tag": "noanswer", 18 | "patterns": [], 19 | "responses": ["Sorry, can't understand you", "Please give me more info", "Not sure I understand"], 20 | "context": [""] 21 | }, 22 | {"tag": "options", 23 | "patterns": ["How you could help me?", "What you can do?", "What help you provide?", "How you can be helpful?", "What support is offered"], 24 | "responses": ["I can guide you through Adverse drug reaction list, Blood pressure tracking, Hospitals and Pharmacies", "Offering support for Adverse drug reaction, Blood pressure, Hospitals and Pharmacies"], 25 | "context": [""] 26 | }, 27 | {"tag": "adverse_drug", 28 | "patterns": ["How to check Adverse drug reaction?", "Open adverse drugs module", "Give me a list of drugs causing adverse behavior", "List all drugs suitable for patient with adverse reaction", "Which drugs dont have adverse reaction?" ], 29 | "responses": ["Navigating to Adverse drug reaction module"], 30 | "context": [""] 31 | }, 32 | {"tag": "blood_pressure", 33 | "patterns": ["Open blood pressure module", "Task related to blood pressure", "Blood pressure data entry", "I want to log blood pressure results", "Blood pressure data management" ], 34 | "responses": ["Navigating to Blood Pressure module"], 35 | "context": [""] 36 | }, 37 | {"tag": "blood_pressure_search", 38 | "patterns": ["I want to search for blood pressure result history", "Blood pressure for patient", "Load patient blood pressure result", "Show blood pressure results for patient", "Find blood pressure results by ID" ], 39 | "responses": ["Please provide Patient ID", "Patient ID?"], 40 | "context": ["search_blood_pressure_by_patient_id"] 41 | }, 42 | {"tag": "search_blood_pressure_by_patient_id", 43 | "patterns": [], 44 | "responses": ["Loading Blood pressure result for Patient"], 45 | "context": [""] 46 | }, 47 | {"tag": "pharmacy_search", 48 | "patterns": ["Find me a pharmacy", "Find pharmacy", "List of pharmacies nearby", "Locate pharmacy", "Search pharmacy" ], 49 | "responses": ["Please provide pharmacy name"], 50 | "context": ["search_pharmacy_by_name"] 51 | }, 52 | {"tag": "search_pharmacy_by_name", 53 | "patterns": [], 54 | "responses": ["Loading pharmacy details"], 55 | "context": [""] 56 | }, 57 | {"tag": "hospital_search", 58 | "patterns": ["Lookup for hospital", "Searching for hospital to transfer patient", "I want to search hospital data", "Hospital lookup for patient", "Looking up hospital details" ], 59 | "responses": ["Please provide hospital name or location"], 60 | "context": ["search_hospital_by_params"] 61 | }, 62 | {"tag": "search_hospital_by_params", 63 | "patterns": [], 64 | "responses": ["Please provide hospital type"], 65 | "context": ["search_hospital_by_type"] 66 | }, 67 | {"tag": "search_hospital_by_type", 68 | "patterns": [], 69 | "responses": ["Loading hospital details"], 70 | "context": [""] 71 | } 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /train_chatbot.py: -------------------------------------------------------------------------------- 1 | #https://github.com/tridibsamanta/Chatbot-using-Python 2 | 3 | import nltk 4 | from nltk.stem import WordNetLemmatizer 5 | lemmatizer = WordNetLemmatizer() 6 | import json 7 | import pickle 8 | 9 | import numpy as np 10 | from keras.models import Sequential 11 | from keras.layers import Dense, Activation, Dropout 12 | from keras.optimizers import SGD 13 | import random 14 | 15 | words=[] 16 | classes = [] 17 | documents = [] 18 | ignore_words = ['?', '!'] 19 | data_file = open('intents.json').read() 20 | intents = json.loads(data_file) 21 | 22 | 23 | for intent in intents['intents']: 24 | for pattern in intent['patterns']: 25 | 26 | #tokenize each word 27 | w = nltk.word_tokenize(pattern) 28 | words.extend(w) 29 | #add documents in the corpus 30 | documents.append((w, intent['tag'])) 31 | 32 | # add to our classes list 33 | if intent['tag'] not in classes: 34 | classes.append(intent['tag']) 35 | 36 | # lemmaztize and lower each word and remove duplicates 37 | words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words] 38 | words = sorted(list(set(words))) 39 | # sort classes 40 | classes = sorted(list(set(classes))) 41 | # documents = combination between patterns and intents 42 | print (len(documents), "documents") 43 | # classes = intents 44 | print (len(classes), "classes", classes) 45 | # words = all words, vocabulary 46 | print (len(words), "unique lemmatized words", words) 47 | 48 | 49 | pickle.dump(words,open('words.pkl','wb')) 50 | pickle.dump(classes,open('classes.pkl','wb')) 51 | 52 | # create our training data 53 | training = [] 54 | # create an empty array for our output 55 | output_empty = [0] * len(classes) 56 | # training set, bag of words for each sentence 57 | for doc in documents: 58 | # initialize our bag of words 59 | bag = [] 60 | # list of tokenized words for the pattern 61 | pattern_words = doc[0] 62 | # lemmatize each word - create base word, in attempt to represent related words 63 | pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words] 64 | # create our bag of words array with 1, if word match found in current pattern 65 | for w in words: 66 | bag.append(1) if w in pattern_words else bag.append(0) 67 | 68 | # output is a '0' for each tag and '1' for current tag (for each pattern) 69 | output_row = list(output_empty) 70 | output_row[classes.index(doc[1])] = 1 71 | 72 | training.append([bag, output_row]) 73 | # shuffle our features and turn into np.array 74 | random.shuffle(training) 75 | training = np.array(training) 76 | # create train and test lists. X - patterns, Y - intents 77 | train_x = list(training[:,0]) 78 | train_y = list(training[:,1]) 79 | print("Training data created") 80 | 81 | 82 | # Create model - 3 layers. First layer 128 neurons, second layer 64 neurons and 3rd output layer contains number of neurons 83 | # equal to number of intents to predict output intent with softmax 84 | model = Sequential() 85 | model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu')) 86 | model.add(Dropout(0.5)) 87 | model.add(Dense(64, activation='relu')) 88 | model.add(Dropout(0.5)) 89 | model.add(Dense(len(train_y[0]), activation='softmax')) 90 | 91 | # Compile model. Stochastic gradient descent with Nesterov accelerated gradient gives good results for this model 92 | sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) 93 | model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 94 | 95 | #fitting and saving the model 96 | hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1) 97 | model.save('chatbot_model.h5', hist) 98 | 99 | print("model created") 100 | -------------------------------------------------------------------------------- /words.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tridibsamanta/Chatbot-using-Python/5567c0847306ca345a3f49c54bb833a457bcc00c/words.pkl --------------------------------------------------------------------------------