Надеюсь, у вас все хорошо, у меня есть чат-бот, использующий TensorFlow, tflearn, NumPy и nltk. Предполагается, что он будет официантом в «Красти Краб», который должен принять ваш заказ и доставить его в ресторан. НЛП (обработка естественного языка). Мне было интересно, смогу ли я как-то реализовать это в приложении или на сайте? Таким образом, пользователь может получить к нему доступ в любое время на любом устройстве. Любая помощь будет оценена. Вот код Спасибо!
import nltk
from nltk.stem.Lancaster import LancasterStemmer
from nltk.corpus import wordnet
stemmer = LancasterStemmer()
import NumPy
import tflearn
import TensorFlow
import random
import JSON
import pickle
with open("intents.json") as file:
data = json.load(file)
try:
with open("data.pickle", "rb") as f:
words, labels, training, output = pickle.load(f)
except:
words = []
labels = []
docs_x = []
docs_y = []
for intent in data["intents"]:
for pattern in intent["patterns"]:
wrds = nltk.word_tokenize(pattern)
words.extend(wrds)
docs_x.append(wrds)
docs_y.append(intent["tag"])
if intent["tag"] not in labels:
labels.append(intent["tag"])
words = [stemmer.stem(w.lower()) for w in words if w != "?"]
words = sorted(list(set(words)))
labels = sorted(labels)
training = []
output = []
out_empty = [0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
bag = []
wrds = [stemmer.stem(w.lower()) for w in doc]
for w in words:
if w in wrds:
bag.append(1)
else:
bag.append(0)
output_row = out_empty[:]
output_row[labels.index(docs_y[x])] = 1
training.append(bag)
output.append(output_row)
training = numpy.array(training)
output = numpy.array(output)
with open("data.pickle", "wb") as f:
pickle.dump((words, labels, training, output), f)
tensorflow.reset_default_graph()
net = tflearn.input_data(shape=[None, len(training[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
net = tflearn.regression(net)
model = tflearn.DNN(net)
model.load("model.tflearn")
#model.fit(training, output, n_epoch=2000, batch_size=8, show_metric=True)
#model.save("model.tflearn")
def bag_of_words(s, words):
bag = [0 for _ in range(len(words))]
s_words = nltk.word_tokenize(s)
s_words = [stemmer.stem(word.lower()) 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)
def chat():
print()
print()
while True:
print("Bot: Welcome to the Krusty Krab, how are you today?")
inp = input("You: ")
if inp.lower() == "quit":
break
gsynonyms = []
for syn in wordnet.synsets("good"):
for l in syn.lemmas():
gsynonyms.append(l.name())
bsynonyms = []
for syn in wordnet.synsets("bad"):
for l in syn.lemmas():
bsynonyms.append(l.name())
results = model.predict([bag_of_words(inp, words)])[0]
results_index = numpy.argmax(results)
tag = labels[results_index]
if results[results_index] > 0.7:
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
print(random.choice(responses))
break
else:
if inp in gsynonyms:
print("Bot: That's good to hear!")
elif inp in bsynonyms:
print("Bot: Sorry to hear that.")
else:
print("Bot: I'm sorry, I don't understand.")
chat()
while True:
print("Bot: (Please answer Yes/No) Do you have an allergy to Kelp, Coral, or Krab meat?")
allergyconfirm = input("You: ")
if allergyconfirm.lower() == "yes":
print("Bot: What are you allergic to?")
allergy = input("You: ")
if allergy.lower() != "kelp" or allergy.lower() != "coral" or allergy.lower() != "krab" or allergy.lower() != "krab meat" or allergy.lower() != "meat":
print("Bot: I'm sorry, I don't understand. Since you typed an allergy which doesn't interfere with our menu, I will automatically assume that our menu will be fine for you.")
allergyconfirm = "no"
break
elif allergyconfirm.lower() == "no":
print("Bot: All right!")
break
else:
print("Bot: I'm sorry, I don't understand.")
ordersize = {}
totalcost = 0
def noallergy():
print("Bot: What would you like to order? We have Kelp shakes, Coral bits, and our world-famous Krabby Patties.")
def kelpallergy():
print("Bot: What would you like to order? We have Coral bits and our world-famous Krabby Patties.")
def coralallergy():
print("Bot: What would you like to order? We have Kelp shakes and our world famous Krabby Patties.")
def kraballergy():
print("Bot: What would you like to order? We have Kelp shakes and Coral bits.")
while True:
if allergyconfirm.lower() == "no":
noallergy()
elif allergy.lower() == "kelp":
kelpallergy()
elif allergy.lower() == "coral":
coralallergy()
elif allergy.lower() == "krab" or allergy.lower() == "krab meat" or allergy.lower() == "meat":
kraballergy()
order = input("You: ")
for i in range(0, len(order) - 6):
if order[i:i+7].lower() == "nothing":
print("Okay!")
break
if order.lower() == "kelp shake" or order.lower() == "coral bits":
print("Bot: What size? We have small, medium, and large.")
size = input("You: ")
ordersize[order] = size
elif order.lower() == "krabby patty":
print("Bot: What size/version? We have single, double, and triple.")
size = input("You: ")
ordersize[order] = size
if order.lower() == "kelp shake" and size.lower() == "small":
totalcost += 1.00
elif order.lower() == "kelp shake" and size.lower() == "medium":
totalcost += 1.25
elif order.lower() == "kelp shake" and size.lower() == "large":
totalcost += 1.50
elif order.lower() == "coral bits" and size.lower() == "small":
totalcost += 1.00
elif order.lower() == "coral bits" and size.lower() == "medium":
totalcost += 1.25
elif order.lower() == "coral bits" and size.lower() == "large":
totalcost += 1.50
elif order.lower() == "krabby patty" and size.lower() == "single":
totalcost += 1.25
elif order.lower() == "krabby patty" and size.lower() == "double":
totalcost += 2.00
elif order.lower() == "krabby patty" and size.lower() == "triple":
totalcost += 3.00
else:
print("Bot: I'm sorry, I don't understand.")
print("Bot: (Please answer Yes/No) Would you like anything else?")
wouldlike = input("You: ")
if wouldlike.lower() == "no":
break
elif wouldlike.lower() == "yes":
print("Bot: All right!")
else:
print("Bot: I'm sorry, I don't understand.")
print("Bot: Okay, you ordered:")
for i in ordersize:
print("Bot:", i, "-", ordersize[i])
if ordersize == {}:
print("Bot: Nothing")
print("Bot: Your total cost is: $",totalcost)