-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_ChatAPI.py
72 lines (54 loc) · 1.84 KB
/
test_ChatAPI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import json
from pickle import TRUE
from train import all_words, dataset, intents
import torch
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize
import random
class ChatAPIs():
def chat (self, sentence):
#if GPU available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#Load sentiment data
with open('intents.json', 'r') as f:
intents = json.load(f)
#Load saved model
FILE = "trained.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).to(device)
model.load_state_dict(model_state)
model.eval()
bot_name = "Ghost"
sentence = tokenize(sentence)
X = bag_of_words(sentence, all_words)
X = X.reshape(1, X.shape[0])
X = torch.from_numpy(X).to(device)
output = model(X)
_, predicted = torch.max(output, dim=1)
tag = tags[predicted.item()]
probs = torch.softmax(output, dim=1)
prob = probs[0][predicted.item()]
#print (prob.item())
if prob.item() > 0.40: #We found a match with over 70% probability
for intent in intents["intents"]:
if tag == intent["tag"]:
out = (f"{random.choice(intent['responses'])}")
else:
out = ("Nothing matched...")
return out
#def chat( sentence):
# return sentence
def tchat(text):
api = ChatAPIs()
print(api.chat(text))
#tchat("hello") # This works now
def test_module():
assert (TRUE)
def test_chat():
assert tchat("Hello") != ""