File size: 11,427 Bytes
6293d43
acb6ed9
 
 
6895902
e298683
105e133
3340b1c
50587b1
6b03e9a
40c33c8
acb6ed9
3340b1c
 
50587b1
879e7eb
a2a58e7
e298683
a5501b7
 
d388d30
aa18bae
3340b1c
6debdfd
9ff5f83
3340b1c
6c9f8ba
acb6ed9
1e9c143
3340b1c
 
 
bc0f75e
879e7eb
acb6ed9
3340b1c
acb6ed9
3340b1c
acb6ed9
bc0f75e
9a485d3
bc0f75e
 
35c1a65
fbfe5d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08860c0
 
 
a5501b7
6293d43
 
 
 
 
a674ac1
6293d43
 
 
50587b1
bc0f75e
 
 
 
 
 
 
 
fbfe5d9
50587b1
6b03e9a
6293d43
 
 
 
a201f43
 
 
 
 
 
 
 
 
6293d43
ed21e94
a5501b7
bc0f75e
3340b1c
 
 
 
 
 
9a485d3
6b03e9a
40c33c8
e298683
 
 
 
 
 
 
 
 
 
ed21e94
3340b1c
35c1a65
9a485d3
5910af2
 
6b03e9a
3340b1c
 
 
 
 
 
 
 
9a485d3
3340b1c
 
9a485d3
3340b1c
9a485d3
73dbfa8
50587b1
 
 
 
8910a27
 
9a485d3
6b03e9a
a5501b7
9fa3a58
d388d30
 
 
 
6293d43
1d11933
 
 
 
 
 
 
 
aa18bae
6293d43
 
9a485d3
6b03e9a
a5501b7
9a485d3
6b03e9a
5910af2
 
9a485d3
fbfe5d9
 
 
 
 
bda1f51
6293d43
bc0f75e
e298683
 
 
 
 
 
 
 
 
 
 
879e7eb
 
 
 
 
 
 
 
bc0f75e
879e7eb
bc0f75e
 
a5501b7
9fa3a58
d388d30
 
 
 
bc0f75e
879e7eb
bc0f75e
 
 
 
 
 
 
 
8910a27
bc0f75e
73dbfa8
bc0f75e
 
73dbfa8
bc0f75e
 
879e7eb
bc0f75e
d388d30
9f4a9e1
bc0f75e
 
 
 
 
 
 
6895902
bc0f75e
 
 
 
3bac2a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc0f75e
 
3bac2a0
 
 
 
 
 
bc0f75e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5501b7
 
3340b1c
6293d43
e298683
40c33c8
879e7eb
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import uvicorn
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt_tab')
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
from tqdm import tqdm
from tqdm.keras import TqdmCallback

import json
import pickle
import random
import asyncio
import concurrent.futures
import multiprocessing
import io
import os
import tempfile

import numpy as np
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout, Input
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.models import load_model, save_model

import redis
import os
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

load_dotenv()

app = FastAPI()

lemmatizer = WordNetLemmatizer()

redis_password = os.getenv("REDIS_PASSWORD")
r = redis.Redis(host=os.getenv("REDIS_HOST"), port=int(os.getenv("REDIS_PORT")), password=redis_password)

# Load existing data from files if they exist and upload to Redis
def load_data_to_redis():
    files_to_load = {
        'intents.json': 'intents',
        'classes.pkl': 'classes',
        'words.pkl': 'words',
        'chatbot_model.h5': 'chatbot_model'
    }

    for file_name, redis_key in files_to_load.items():
        if os.path.exists(file_name) and not r.exists(redis_key):
            print(f"Loading {file_name} to Redis...")
            if file_name.endswith('.json'):
                with open(file_name) as f:
                    data = json.load(f)
                r.set(redis_key, json.dumps(data))
            elif file_name.endswith('.h5'):
                with open(file_name, 'rb') as f:
                    r.set(redis_key, f.read())
            else:
                with open(file_name, 'rb') as f:
                    r.set(redis_key, pickle.dumps(pickle.load(f)))

# Ensure directories exist
if not os.path.exists('models'):
    os.makedirs('models')

def initialize_redis():
    global r
    try:
        r.ping()
        print("Redis connection successful.")
        load_data_to_redis()
    except redis.exceptions.ConnectionError:
        print("Error connecting to Redis. Exiting.")
        exit(1)

async def train_and_save_model():
    global lemmatizer, r
    while True:
        words = []
        classes = []
        documents = []
        ignore_words = ['?', '!']

        intents = json.loads(r.get('intents'))

        print("Loading user questions from Redis...")
        if not r.exists('user_questions_loaded'):
            user_questions = r.lrange('user_questions', 0, -1)
            for question in user_questions:
                question = question.decode('utf-8')
                try:
                    existing_tag = r.get(f"tag:{question}").decode('utf-8')
                    documents.append((nltk.word_tokenize(question), existing_tag))
                    if existing_tag not in classes:
                        classes.append(existing_tag)
                except AttributeError:
                    documents.append((nltk.word_tokenize(question), "unknown"))
                    if "unknown" not in classes:
                        classes.append("unknown")
            r.set('user_questions_loaded', 1)

        print("Processing intents from Redis...")
        for intent in intents['intents']:
            for pattern in intent['patterns']:
                w = nltk.word_tokenize(pattern)
                words.extend(w)
                documents.append((w, intent['tag']))
                if intent['tag'] not in classes:
                    classes.append(intent['tag'])

            print(f"Generating synonyms for intent '{intent['tag']}'...")
            with multiprocessing.Pool() as pool:
                results = []
                for _ in tqdm(range(100000), desc="Generating synonyms", leave=False):
                    if not intent['patterns']:
                        break
                    results.append(pool.apply_async(generate_synonym_pattern, (intent['patterns'],)))

                for result in results:
                    new_pattern = result.get()
                    if new_pattern:
                        intent['patterns'].append(new_pattern)

        words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]
        words = sorted(list(set(words)))

        classes = sorted(list(set(classes)))

        print("Creating training data...")
        training = []
        output_empty = [0] * len(classes)
        for doc in documents:
            bag = []
            pattern_words = doc[0]
            pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]
            for w in words:
                bag.append(1) if w in pattern_words else bag.append(0)

            output_row = list(output_empty)
            output_row[classes.index(doc[1])] = 1

            training.append([bag, output_row])

        if not training:
            print("No training data yet. Waiting...")
            await asyncio.sleep(60)
            continue

        train_x = np.array([row[0] for row in training])
        train_y = np.array([row[1] for row in training])

        print("Loading or creating model...")
        if r.exists('chatbot_model'):
            with tempfile.NamedTemporaryFile(delete=False, suffix='.h5') as temp_file:
                temp_file.write(r.get('chatbot_model'))
                temp_file_name = temp_file.name
            model = load_model(temp_file_name)
            os.remove(temp_file_name)
        else:
            input_layer = Input(shape=(len(train_x[0]),)) 
            layer1 = Dense(128, activation='relu')(input_layer)
            layer2 = Dropout(0.5)(layer1)
            layer3 = Dense(64, activation='relu')(layer2)
            layer4 = Dropout(0.5)(layer3)
            output_layer = Dense(len(classes), activation='softmax')(layer4)

            model = Sequential(layers=[input_layer, layer1, layer2, layer3, layer4, output_layer])

            sgd = SGD(learning_rate=0.01, momentum=0.9, nesterov=True)
            model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

        print("Training the model...")
        model.fit(train_x, train_y, epochs=1, batch_size=len(train_x), verbose=0, callbacks=[TqdmCallback(verbose=2)])

        print("Saving data to Redis...")
        r.set('words', pickle.dumps(words))
        r.set('classes', pickle.dumps(classes))

        with tempfile.NamedTemporaryFile(delete=False, suffix='.h5') as temp_file:
            save_model(model, temp_file.name)
            with open(temp_file.name, 'rb') as f:
                r.set('chatbot_model', f.read())
            os.remove(temp_file.name)

        print("Data and model saved. Re-training...")

def generate_synonym_pattern(patterns):
    new_pattern = []
    for word in random.choice(patterns).split():
        synonyms = wordnet.synsets(word)
        if synonyms:
            synonym = random.choice(synonyms[0].lemmas()).name()
            new_pattern.append(synonym)
        else:
            new_pattern.append(word)
    return " ".join(new_pattern)

def start_training_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(train_and_save_model())

class ChatMessage(BaseModel):
    message: str

@app.post("/chat")
async def chat(message: ChatMessage):
    words = pickle.loads(r.get('words'))
    classes = pickle.loads(r.get('classes'))
    with io.BytesIO(r.get('chatbot_model')) as f:
        with tempfile.NamedTemporaryFile(delete=False, suffix='.h5') as temp_file:
            temp_file.write(f.read())
            temp_file_name = temp_file.name
        model = load_model(temp_file_name)
        os.remove(temp_file_name)

    sentence_words = nltk.word_tokenize(message.message)
    sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]

    bag = [0] * len(words)
    for s in sentence_words:
        for i, w in enumerate(words):
            if w == s:
                bag[i] = 1

    p = model.predict(np.array([bag]))[0]
    ERROR_THRESHOLD = 0.25
    results = [[i, p] for i, p in enumerate(p) if p > ERROR_THRESHOLD]
    results.sort(key=lambda x: x[1], reverse=True)
    return_list = []
    for i, p in results:
        return_list.append({"intent": classes[i], "probability": str(p)})

    r.rpush('user_questions', message.message)

    asyncio.create_task(train_and_save_model())

    return return_list

@app.post("/tag")
async def tag_question(question: str, tag: str):
    r.set(f"tag:{question}", tag)
    return {"message": "Tag saved"}

html_code = """
<!DOCTYPE html>
<html>
<head>
    <title>Chatbot</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        #container {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            padding: 30px;
            width: 80%;
            max-width: 600px;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #333;
        }

        #chatbox {
            height: 300px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        #chatbox p {
            margin: 5px 0;
        }

        #user_input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="container">
        <h1>Chatbot</h1>
        <div id="chatbox"></div>
        <input type="text" id="user_input" placeholder="Type your message...">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>
    function sendMessage() {
        let userInput = document.getElementById('user_input').value;
        document.getElementById('user_input').value = '';

        fetch('/chat', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({"message": userInput})
        })
        .then(response => response.json())
        .then(data => {
            let chatbox = document.getElementById('chatbox');
            chatbox.innerHTML += '<p><b>You:</b> ' + userInput + '</p>';
            data.forEach(item => {
              chatbox.innerHTML += '<p><b>Bot:</b> ' + item.intent + ' (Probability: ' + item.probability + ')</p>';
            });
        });
      }
    </script>

</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def root():
    return html_code

if __name__ == "__main__":
    initialize_redis()
    training_process = multiprocessing.Process(target=start_training_loop)
    training_process.start()
    uvicorn.run(app, host="0.0.0.0", port=7860)