<jupyter_start><jupyter_text>We’ll build a simple state-machine to handle responses, using our intents model (from the previous step) as our classifier. [That’s how chatbots work](https://medium.freecodecamp.com/how-chat-bots-work-dfff656a35e2).> A contextual chatbot framework is a classifier within a state-machine.- we’ll un-pickle our model and documents as well as reload our intents file-  Remember our chatbot framework is separate from our model build — you don’t need to rebuild your model unless the intent patterns change- With several hundred intents and thousands of patterns the model could take several minutes to build<jupyter_code># restore all of our data structures
import pickle
data = pickle.load(open("training_data", "rb"))
words = data['words']
classes = data['classes']
train_x = data['train_x']
train_y = data['train_y']

# import our chat-bot intents file
import json
with open('Mop intents.json') as json_data:
    intents = json.load(json_data)
"""""input = keras.input(shape=[len(intent_train_x[0])]) 
intent_net = input
intent_net = layers.Dense(8)(intent_net) 
intent_net = layers.Dense(8)(intent_net) 
intent_net = layers.Dense(len(intent_train_y[0], activation='softmax')(intent_net) 
intent_model = keras.Model(inputs=[input], outputs=[output])
intent_model.load('model1') """""
# Build neural network
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)

# Define model and setup tensorboard
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')<jupyter_output>WARNING:tensorflow:From C:\Users\POOJA\anaconda\lib\site-packages\tflearn\initializations.py:164: calling TruncatedNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor<jupyter_text>Util functions<jupyter_code>def clean_up_sentence(sentence):
    # tokenize the pattern
    sentence_words = nltk.word_tokenize(sentence)
    # stem each word
    sentence_words = [stemmer.stem(word.lower()) for word in sentence_words]
    return sentence_words

# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence


def bow(sentence, words, show_details=False):
    # tokenize the pattern
    sentence_words = clean_up_sentence(sentence)
    # bag of words
    bag = [0]*len(words)
    for s in sentence_words:
        for i, w in enumerate(words):
            if w == s:
                bag[i] = 1
                if show_details:
                    print("found in bag: %s" % w)

    return(np.array(bag))
p1 = bow("what is mopedo?", words)
print (p1)
print (classes)
# load our saved model
model.load('./model.tflearn')<jupyter_output>INFO:tensorflow:Restoring parameters from C:\Users\POOJA\Mopybot\model.tflearn<jupyter_text>Checking that our model gives the same result as in the previous step<jupyter_code>def get_predicted_intent(predictions):
    return classes[np.argmax(predictions)]


assert 'Mopedo' == get_predicted_intent(model.predict([p1]))<jupyter_output><empty_output><jupyter_text>Response processor<jupyter_code># data structure to hold user context
context = {}

ERROR_THRESHOLD = 0.25


def classify(sentence):
    # generate probabilities from the model
    results = model.predict([bow(sentence, words)])[0]

    # filter out predictions below a threshold
    results = [[i, r] for i, r in enumerate(results) if r > ERROR_THRESHOLD]

    # sort by strength of probability
    results.sort(key=lambda x: x[1], reverse=True)
    return_list = []

    for r in results:
        return_list.append((classes[r[0]], r[1]))

    # return tuple of intent and probability
    return return_list


def response(sentence, userID='123', show_details=False):
    results = classify(sentence)
    if results:
        for i in intents['intents']:
            if i['tag'] == results[0][0]:
                result = (random.choice(i['responses']))
                return result
    else:
        return ("info@")
        
classify("Mopedo")
response('Mopedo')
response('what services does mopedo provide?')
classify("safety and maintenance")
response('How safe is mopedo?')
response('payments?')
response('can I book ride for others?')
response('Mopedo city boundaries?')
response("how are they charged?")
response("Any technical help")
response(" help")
response("..")
response("ha")
response("puja")
response(".")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11226028873087697, 'fraction_numerical': 0.007972419737125619, 'mean_word_length': 4.667887667887668, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '488056', 'license': 'MIT', 'n_tokens_mistral': 1469, 'n_tokens_neox': 1412, 'n_words': 421, 'path': 'Chatbot2.ipynb', 'repo_name': 'Poojakottae/Chatbot', 'size': '4641'}