-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatbot.py
More file actions
70 lines (55 loc) · 1.8 KB
/
chatbot.py
File metadata and controls
70 lines (55 loc) · 1.8 KB
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
import torch
import nltk
import pickle
from nltk.stem.lancaster import LancasterStemmer
from pathlib import Path
import numpy as np
import random
import json
from model import ChatBot
stemmer = LancasterStemmer()
with open("data\intents.json") as file:
data = json.load(file)
RES_SAVE_PATH = Path("resources\data.pickle")
MODEL_PATH = Path("models\model.pth")
try:
with open(RES_SAVE_PATH, "rb") as f:
words, labels, training, output = pickle.load(f)
print(f"Loaded data from pickle file. Vocabulary size: {len(words)}")
except Exception as e:
print(f"This the error geting when loading the data: -->{e}")
def bag_of_words(s, words):
bag = torch.zeros(len(words))
s_words = nltk.word_tokenize(s)
s_words = [stemmer.stem(word.lower()) for word in s_words]
indices = [i for i, w in enumerate(words) if w in s_words]
bag[indices] = 1
out = torch.Tensor(bag)
return torch.unsqueeze(out, 0)
out =bag_of_words(s="hai", words=words)
print(out.shape)
model = ChatBot(input_size=len(words), hidden_size=8, output_size=38)
model.load_state_dict(torch.load(f=MODEL_PATH))
def chat():
print("Start chatting with the bot \n")
while True:
inp = input("You: ")
if inp.lower() == "q":
break
user_input=bag_of_words(inp, words)
model.eval()
with torch.inference_mode():
result = model(user_input)
result_index = torch.argmax(result)
test=result[0,result_index.item()]
print(test)
tag = labels[result_index]
for intent in data["intents"]:
if intent['tag'] == tag:
responses = intent['responses']
if test.item() > 9.0:
print(random.choice(responses))
print(test.item())
else:
print("Sorry")
chat()