
import random
import json

import torch

from model import NeuralNet
from nltk_utilis import bag_of_word, tokenized_word

with open('intent.json', 'r') as json_data:
    intents = json.load(json_data)

FILE = "data.pth"
data = torch.load(FILE)

input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data['all_words']
tags = data['tags']
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size)
model.load_state_dict(model_state)
model.eval()

bot_name = "GMU"
print("Let's chat!")
while True:
    
    sentence = input("You: ")
    s = sentence

    sentence = tokenized_word(sentence)
    X = bag_of_word(sentence, all_words)
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X)

    output = model(X)
    _, predicted = torch.max(output, dim=1)

    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]
    if prob.item() > 0.75:
        for intent in intents['intents']:
            if tag == intent["tag"]:
                intent["patterns"].append(s)
                print(f"{bot_name}: {random.choice(intent['responses'])}")
        
        with open('intent.json', 'w') as outfile:
            json.dump(intents, outfile)
    else:
        print(f"{bot_name}: I do not understand...")
    
    if tag == 'goodbye':
        break