Chatbot / chatbot.py
cellanet's picture
Update chatbot.py
9379df1
raw
history blame
2.97 kB
from machine_learning import model, words, labels, ans_data, nlp
import datetime
import random
import numpy
def bag_of_words(s, words):
bag = [0 for _ in range(len(words))]
s_words = nlp(s.lower())
s_words = [word.lemma_ for word in s_words]
for se in s_words:
for i, w in enumerate(words):
if w == se:
bag[i] = 1
return numpy.array(bag)
unknown = ["I'm afraid I don't follow; could you perhaps give more detail?",
"I'm sorry, but I need you to elaborate a little bit more.", "I don't understand, can you try another question?"]
def chat():
print("Start talking with the bot (type quit to stop)!")
print("\n---------------------------------------------\nCellanet: Hello there!")
while True:
inp = input("You: ")
if inp.lower() == "quit":
break
results = model.predict([bag_of_words(inp, words)])
# print(f"Predict: {results}\n")
results_index = numpy.argmax(results)
max_result = numpy.max(results)
# print(f"max: {max_result}")
if max_result < 0.65:
tag = 'unknown'
else:
tag = labels[results_index]
responses = []
print(f"({tag})")
if tag in ans_data:
if tag == 'what time':
responses.append(f"Now is {datetime.datetime.now()}.")
else:
for x in ans_data[tag]:
for z in x:
responses.append(z)
else:
for x in unknown:
responses.append(x)
print('Cellanet:', random.choice(responses))
# return f"Cellanet: {random.choice(responses)}."
def onlineChat(inp):
print("\n---------------------------------------------\n")
while True:
# inp = input("You: ")
if inp.lower() == "quit":
break
results = model.predict([bag_of_words(inp, words)])
# print(f"Predict: {results}\n")
results_index = numpy.argmax(results)
max_result = numpy.max(results)
# print(f"max: {max_result}")
if max_result < 0.45:
tag = 'unknown'
else:
tag = labels[results_index]
responses = []
print(f"({tag})")
if tag in ans_data:
if tag == 'what time':
responses.append(f"Now is {datetime.datetime.now()}.")
else:
for x in ans_data[tag]:
for z in x:
responses.append(z)
else:
for x in unknown:
responses.append(f"*********** {x} ***********")
f = open('question and answer.txt', 'a')
f.write(f"- - {inp}\n - {random.choice(responses)}.\n\n\n")
f.close()
return f"Cellanet: {random.choice(responses)}"
# chat()