-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.py
64 lines (54 loc) · 2.16 KB
/
process.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
import json
import random
import string
import pickle
import numpy as np
import tensorflow as tf
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow import keras
from tensorflow.keras.preprocessing.sequence import pad_sequences
class ChatBot:
def __init__(self):
self.input_shape = 8
self.responses = {}
self.lemmatizer = WordNetLemmatizer()
self.tokenizer, self.le, self.model = None, None, None
self.load_resources()
self.prepare_model()
def load_resources(self):
with open('dataset/chatbot.json') as content:
data = json.load(content)
for intent in data['intents']:
self.responses[intent['tag']] = intent['responses']
nltk.download('punkt', quiet=True)
nltk.download('wordnet', quiet=True)
nltk.download('omw-1.4', quiet=True)
def prepare_model(self):
self.tokenizer = pickle.load(open('model/tokenizers.pkl', 'rb'))
self.le = pickle.load(open('model/le.pkl', 'rb'))
self.model = keras.models.load_model('model/chat_model.h5')
def remove_punctuation(self, text):
text = ''.join([letters.lower() for letters in text if letters not in string.punctuation])
return [text]
def vectorize_text(self, text):
texts_p = self.remove_punctuation(text)
vector = self.tokenizer.texts_to_sequences(texts_p)
vector = np.array(vector).reshape(-1)
vector = pad_sequences([vector], self.input_shape)
return vector
def predict(self, text):
vector = self.vectorize_text(text)
output = self.model.predict(vector)
response_tag = self.le.inverse_transform([output.argmax()])[0]
response = random.choice(self.responses[response_tag])
if isinstance(response, dict):
return response['text'], response.get('links', [])
else:
return response, []
def generate_response(self, text):
response_text, links = self.predict(text)
if links:
return f"{response_text} Link: {links[0]}"
else:
return response_text