Monday, May 10, 2021

Chatbot

########## Intents.json ##############

{"intents": [

  {"tag": "greetings", 

   "patterns":["hello", "hey", "hi", "good day", "greetings", "what's u?", "howdy"],

   "responses": ["Hello!", "Hey!", "What can I do for you?"]

  },

  {"tag": "goodbye", 

   "patterns":["cya", "see you later", "goodbye", "i am leaving",

               "have a good day", "bye", "ciao", "tata", "farewell"],

   "responses": ["Sad to see you go :(", "Talk to you later", "Goodbye", "So long ..." ]

  },

  {"tag": "age", 

   "patterns":["how old", "how old is binoy", "what is your age", "how old are you", "age?"],

   "responses": ["My owner Binoy is 54 years young!", "54 years", "He has seen 54 summers"]

  },

  {"tag": "name", 

   "patterns":["what is your name?", "what should I call you?", "whats your name?", "who are you?", "can you tell me your name?", "please tell me your name"],

   "responses": ["You can call me Neural", "I'm Neural", "I'm Neural, the assistant to Binoy"]

  },

  {"tag": "shop", 

   "patterns":["I'd like to buy something", "what do you sell?", "what are your products?", "what do you recommend?", "what are you selling", "what's for sale", "what can I buy?"],

   "responses": ["You can buy a snazzy car", "We have cars of all makes and models", "Wanna see our range of cars?"]

  },

  {"tag": "hours", 

   "patterns":["when are you open", "what are your hours", "hours of operation", "timing", "opening time", "closing time", "working hours"],

   "responses": ["24/7"]

  },

  {"tag": "stocks", 

   "patterns":["what stocks do I own?", "how are my shares?", "what companies am I investing in?", "what am I doing with my savings"],

   "responses": ["You own the following shares: RIL & Tata Motors on the BSE and FB, MS & Intel on the NYSE"]

  },

  {"tag": "shutdown", 

   "patterns":["", "", "", "", "", "", ""],

   "responses": ["", "", ""]

  }

]}



############ Chatbot.py ############

import random, json, pickle, nltk, numpy as np
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import load_model

bot_name = "Discoverer"
lemmatizer = WordNetLemmatizer()
intents = json.loads(open("Intents.json").read())

words = pickle.load(open("Words.pkl", "rb"))
classes = pickle.load(open("Classes.pkl", "rb"))
model = load_model("ChatbotModel.h5")

def clean_up_sentence(sentence):
  sentence_words = nltk.word_tokenize(sentence)
  sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
  return sentence_words

def bag_of_words(sentence):
  sentence_words = clean_up_sentence(sentence)
  bag = [0] * len(words)
  for w in sentence_words:
    for i, word in enumerate(words):
      if word == w:
        bag[i] = 1
  return np.array(bag)

def predict_class(sentence):
  bow = bag_of_words(sentence)
  res = model.predict(np.array([bow]))[0]
  ERROR_THRESHOLD = 0.25
  results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]

  results.sort(key=lambda x: x[1], reverse=True)
  return_list = []
  for r in results:
    return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})
  return return_list

def get_response(intents_list, intents_json):
  tag = intents_list[0]['intent']
  list_of_intents = intents_json['intents']
  for i in list_of_intents:
    if i['tag'] == tag:
      result = random.choice(i['responses'])
      break
  return result


############ Training.py ############

# https://youtu.be/1lwddP0KUEg

''' Run the following from the IDLE prompt
>> nltk.download("punkt")
>> nltk.download("wordnet")
'''
import random, json, pickle, numpy as np, nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD

lemmatizer = WordNetLemmatizer()
intents = json.loads(open("Intents.json").read())

words, classes, documents, ignore_letters = [], [], [], ['?', '.', ',', '!']

for intent in intents['intents']:
  for pattern in intent['patterns']:
    word_list = nltk.word_tokenize(pattern)
    words.extend(word_list)
    documents.append((word_list, intent['tag']))
    if intent["tag"] not in classes:
      classes.append(intent['tag'])

words = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(set(words))

ckasses = sorted(set(classes))

pickle.dump(words, open("Words.pkl", "wb"))
pickle.dump(classes, open("Classes.pkl", "wb"))

training = []
output_empty = [0] * len(classes)

for document in documents:
  bag = []
  word_patterns = document[0]
  word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
  for word in words:
    bag.append(1) if word in word_patterns else bag.append(0)

  output_row = list(output_empty)
  output_row[classes.index(document[1])] = 1
  training.append([bag, output_row])

random.shuffle(training)
training = np.array(training, dtype=object)

train_x = list(training[:, 0])
train_y = list(training[:, 1])

model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save("ChatbotModel.h5", hist)
print("Done")



######### UI.py ###########

# https://www.youtube.com/watch?v=RNEcewpVZUQ

from ChatBot import *
from tkinter import *
from random import choice

BG_GRAY, BG_COLOR, TEXT_COLOR = "#ABB2B9", "#17202A", "#EAECEE"
FONT, FONT_BOLD = "Helvetica 14", "Helvetica 13 bold"

win = Tk()
win.geometry("470x550")
win.resizable(0, 0)
win.title("Chat")
win.config(bg=BG_COLOR)

head_label = Label(win, bg=BG_COLOR, fg=TEXT_COLOR, text="Welcome", font=FONT_BOLD, pady=0)
head_label.place(relwidth=1)

line = Label(win, width=450, bg=BG_GRAY)
line.place(relwidth=1, rely=0.045, relheight=0.012)

txt = Text(win, width=20, height=2, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, padx=5, pady=5, bd=3)
txt.place(relheight=0.8, relwidth=1, rely=0.06)
txt.config(cursor="arrow", state=DISABLED)

scrollbar = Scrollbar(txt)
scrollbar.place(relheight=1, relx=0.974)
scrollbar.configure(command=txt.yview)

bottom_label = Label(win, bg=BG_GRAY, height=80)
bottom_label.place(relwidth=1, rely=0.825)

def insert_message(msg, sender):
  if not msg:
    return

  ent.delete(0, END)
  msg1 = f"{sender}: {msg}\n\n"
  txt.config(state=NORMAL)
  txt.insert(END, msg1)
  txt.config(state=DISABLED)

  ints = predict_class(msg)
  res = get_response(ints, intents)
  sorry_responses = ["Sorry, I don't understand", "Pardon me ...", "Can you be more specific?"]
  if res == "":
    res = choice(sorry_responses)
  msg2 = f"{bot_name}: {res}\n\n"
  txt.config(state=NORMAL)
  txt.insert(END, msg2)
  txt.config(state=DISABLED)

  txt.see(END)

def send():
  msg = ent.get().lower()
  insert_message(msg, "You")
  ent.focus()

ent = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
ent.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.0)
ent.focus()

btn = Button(bottom_label, text="SEND", font=FONT_BOLD, command=send)
btn.place(relx=0.77, rely=0.02, relheight=0.04, relwidth=0.22)

win.mainloop()














No comments:

Post a Comment