-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.py
52 lines (38 loc) · 1.5 KB
/
chat.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
import json
import numpy as np
from tensorflow import keras
from sklearn.preprocessing import LabelEncoder
import tensorflowjs as tfjs
import colorama
colorama.init()
from colorama import Fore, Style, Back
import random
import pickle
with open("intents.json") as file:
data = json.load(file)
def chat():
# load trained model
model = keras.models.load_model('chat_model')
# load tokenizer object
with open('tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
# load label encoder object
with open('label_encoder.pickle', 'rb') as enc:
lbl_encoder = pickle.load(enc)
# parameters
max_len = 20
while True:
print(Fore.LIGHTBLUE_EX + "User: " + Style.RESET_ALL, end="")
inp = input()
if inp.lower() == "quit":
break
result = model.predict(keras.preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences([inp]),
truncating='post', maxlen=max_len))
tag = lbl_encoder.inverse_transform([np.argmax(result)])
for i in data['intents']:
if i['tag'] == tag:
print(Fore.GREEN + "ChatBot:" + Style.RESET_ALL , np.random.choice(i['responses']))
# print(Fore.GREEN + "ChatBot:" + Style.RESET_ALL,random.choice(responses))
tfjs.converters.save_keras_model(model, 'C:/Users/hp/Documents/Python_Chatbot')
print(Fore.YELLOW + "Start messaging with the bot (type quit to stop)!" + Style.RESET_ALL)
chat()