File size: 27,345 Bytes
5330bda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import json
import random
import re
import unicodedata
from typing import Tuple

import gradio as gr
import spacy
import torch
import torch.nn as nn
import torch.nn.functional as F

nlp = spacy.load('en_core_web_sm')

def greet(name):
    return "Hello " + name + "!!"

# read word2idx and idx2word from json file

with open('vocab/word2idx.json', 'r') as f:
    word2idx = json.load(f)
with open('vocab/idx2word.json', 'r') as f:
    idx2word = json.load(f)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def unicodetoascii(text):
    """

    Turn a Unicode string to plain ASCII



    :param text: text to be converted

    :return: text in ascii format

    """
    normalized_text = unicodedata.normalize('NFKD', str(text))
    ascii_text = ''.join(char for char in normalized_text if unicodedata.category(char) != 'Mn')
    return ascii_text

def preprocess_text(text, fn=unicodetoascii):

    text = fn(text)
    text = text.lower()
    text = re.sub(r'http\S+', '', text)
    text = re.sub(r'[^\x00-\x7F]+', "", text) # Remove non-ASCII characters
    text = re.sub(r"(\w)[!?]+(\w)", r'\1\2', text) # Remove !? between words
    text = re.sub(r"\s\s+", r" ", text).strip() # Remove extra spaces
    return text

def tokenize(text, nlp=nlp):
    """

    Tokenize text

    :param text: text to be tokenized

    :return: list of tokens

    """
    return [tok.text for tok in nlp.tokenizer(text)]

def lookup_words(idx2word, indices):
    """

    Lookup words from indices

    :param idx2word: index to word mapping

    :param indices: indices to be converted

    :return: list of words

    """
    return [idx2word[str(idx)] for idx in indices]


class Encoder(nn.Module):
    """

    GRU RNN Encoder

    """
    def __init__(self,

                 input_dim: int,

                 emb_dim: int,

                 enc_hid_dim: int,

                 dec_hid_dim: int,

                 dropout: float = 0):
        super(Encoder, self).__init__()

        # dimension of imput
        self.input_dim = input_dim
        # dimension of embedding layer
        self.emb_dim = emb_dim
        # dimension of encoding hidden layer
        self.enc_hid_dim = enc_hid_dim
        # dimension of decoding hidden layer
        self.dec_hid_dim = dec_hid_dim

        # create embedding layer use to train embedding representations of the corpus
        self.embedding = nn.Embedding(input_dim, emb_dim)

        # use GRU for RNN
        self.rnn = nn.GRU(emb_dim, enc_hid_dim, bidirectional=True, batch_first=False, num_layers=1)
        self.fc = nn.Linear(enc_hid_dim * 2, dec_hid_dim)
        # create dropout layer which will help produce a more generalisable model
        self.dropout = nn.Dropout(dropout)

    def forward(self, src: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
        # apply dropout to the embedding layer
        embedded = self.dropout(self.embedding(src))
        # generate an output and hidden layer from the rnn
        outputs, hidden = self.rnn(embedded)
        hidden = torch.tanh(self.fc(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)))
        return outputs, hidden


class Attention(nn.Module):
    """

    Luong attention

    """
    def __init__(self,

                 enc_hid_dim: int,

                 dec_hid_dim: int,

                 attn_dim: int):
        super(Attention, self).__init__()

        # dimension of encoding hidden layer
        self.enc_hid_dim = enc_hid_dim
        # dimension of decoding hidden layer
        self.dec_hid_dim = dec_hid_dim
        self.attn_in = (enc_hid_dim * 2) + dec_hid_dim

        self.attn = nn.Linear(self.attn_in, attn_dim)

    def forward(self,

                decoder_hidden: torch.Tensor,

                encoder_outputs: torch.Tensor) -> torch.Tensor:

        src_len = encoder_outputs.shape[0]
        repeated_decoder_hidden = decoder_hidden.unsqueeze(1).repeat(1, src_len, 1)
        encoder_outputs = encoder_outputs.permute(1, 0, 2)
        # Luong attention
        energy = torch.tanh(self.attn(torch.cat((repeated_decoder_hidden, encoder_outputs), dim=2)))
        attention = torch.sum(energy, dim=2)

        return F.softmax(attention, dim=1)


class AttnDecoder(nn.Module):
    """

    GRU RNN Decoder with attention

    """
    def __init__(self,

                 output_dim: int,

                 emb_dim: int,

                 enc_hid_dim: int,

                 dec_hid_dim: int,

                 attention: nn.Module,

                 dropout: float = 0):
        super(AttnDecoder, self).__init__()

        # dimention of output layer
        self.output_dim = output_dim
        # dimention of embedding layer
        self.emb_dim = emb_dim
        # dimention of encoding hidden layer
        self.enc_hid_dim = enc_hid_dim
        # dimention of decoding hidden layer
        self.dec_hid_dim = dec_hid_dim
        # drouput rate
        self.dropout = dropout
        # attention layer
        self.attention = attention

        # create embedding layer use to train embedding representations of the corpus
        self.embedding = nn.Embedding(output_dim, emb_dim)
        # use GRU for RNN
        self.rnn = nn.GRU((enc_hid_dim * 2) + emb_dim, dec_hid_dim, batch_first=False, num_layers=1)
        self.out = nn.Linear(self.attention.attn_in + emb_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def encode_attention(self,

                              decoder_hidden: torch.Tensor,

                              encoder_outputs: torch.Tensor) -> torch.Tensor:

        a = self.attention(decoder_hidden, encoder_outputs)
        a = a.unsqueeze(1)
        encoder_outputs = encoder_outputs.permute(1, 0, 2)
        weighted_encoder_rep = torch.bmm(a, encoder_outputs)
        weighted_encoder_rep = weighted_encoder_rep.permute(1, 0, 2)
        return weighted_encoder_rep

    def forward(self,

                input: torch.Tensor,

                decoder_hidden: torch.Tensor,

                encoder_outputs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:

        input = input.unsqueeze(0)
        # apply dropout to embedding layer
        embedded = self.dropout(self.embedding(input))
        weighted_encoder = self.encode_attention(decoder_hidden, encoder_outputs)
        
        # generate an output and hidden layer from the rnn
        rnn_input = torch.cat((embedded, weighted_encoder), dim=2)
        output, decoder_hidden = self.rnn(rnn_input, decoder_hidden.unsqueeze(0))

        embedded = embedded.squeeze(0)
        output = output.squeeze(0)
        weighted_encoder = weighted_encoder.squeeze(0)
        output = self.out(torch.cat((output, weighted_encoder, embedded), dim=1))
        return output, decoder_hidden.squeeze(0)

class Decoder(nn.Module):
    """

    GRU RNN Decoder without attention

    """
    def __init__(self,

                 output_dim: int,

                 emb_dim: int,

                 enc_hid_dim: int,

                 dec_hid_dim: int,

                 dropout: float = 0):
        super(Decoder, self).__init__()

        # dimention of output layer
        self.output_dim = output_dim
        # dimention of embedding layer
        self.emb_dim = emb_dim
        # dimention of encoding hidden layer
        self.enc_hid_dim = enc_hid_dim
        # dimention of decoding hidden layer
        self.dec_hid_dim = dec_hid_dim
        # drouput rate
        self.dropout = dropout

        # create embedding layer use to train embedding representations of the corpus
        self.embedding = nn.Embedding(output_dim, emb_dim)
        # GRU RNN
        self.rnn = nn.GRU((enc_hid_dim * 2) + emb_dim, dec_hid_dim, batch_first=False, num_layers=1)
        self.out = nn.Linear((enc_hid_dim * 2) + dec_hid_dim + emb_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self,

                input: torch.Tensor,

                decoder_hidden: torch.Tensor,

                encoder_outputs: torch.Tensor) -> Tuple[torch.Tensor
                                                        , torch.Tensor]:
        
        input = input.unsqueeze(0)
        # apply dropout to embedding layer
        embedded = self.dropout(self.embedding(input))
        context = encoder_outputs[-1,:,:]
        context = context.repeat(embedded.shape[0], 1, 1)
        embs_and_context = torch.cat((embedded, context), -1)
        # generate an output and hidden layer from the rnn
        output, decoder_hidden = self.rnn(embs_and_context, decoder_hidden.unsqueeze(0))
        embedded = embedded.squeeze(0)
        output = output.squeeze(0)
        context = context.squeeze(0)
        output = self.out(torch.cat((output, embedded, context), -1))
        return output, decoder_hidden.squeeze(0)

class Seq2Seq(nn.Module):
    """

    Seq-2-Seq model combining RNN encoder and RNN decoder

    """
    def __init__(self,

                 encoder: nn.Module,

                 decoder: nn.Module,

                 device: torch.device):
        super(Seq2Seq, self).__init__()

        self.encoder = encoder
        self.decoder = decoder
        self.device = device

    def forward(self,

                src: torch.Tensor,

                trg: torch.Tensor,

                teacher_forcing_ratio: float = 0.5) -> torch.Tensor:
        src = src.transpose(0, 1) # (max_len, batch_size)
        trg = trg.transpose(0, 1) # (max_len, batch_size)
        batch_size = src.shape[1]
        max_len = trg.shape[0]
        trg_vocab_size = self.decoder.output_dim

        outputs = torch.zeros(max_len, batch_size, trg_vocab_size).to(self.device)
        encoder_outputs, hidden = self.encoder(src)

        # first input to the decoder is the <sos> token
        output = trg[0,:]

        for t in range(1, max_len):
            output, hidden = self.decoder(output, hidden, encoder_outputs)
            outputs[t] = output
            teacher_force = random.random() < teacher_forcing_ratio
            top1 = output.max(1)[1]
            output = trg[t] if teacher_force else top1

        return outputs

params = {'input_dim': len(word2idx),
            'emb_dim': 128,
            'enc_hid_dim': 256,
            'dec_hid_dim': 256,
            'dropout': 0.5,
            'attn_dim': 32,
            'teacher_forcing_ratio': 0.5,
            'epochs': 35}

enc = Encoder(input_dim=params['input_dim'], emb_dim=params['emb_dim'], enc_hid_dim=params['enc_hid_dim'], dec_hid_dim=params['dec_hid_dim'], dropout=params['dropout'])
attn = Attention(enc_hid_dim=params['enc_hid_dim'], dec_hid_dim=params['dec_hid_dim'], attn_dim=params['attn_dim'])
dec = AttnDecoder(output_dim=params['input_dim'], emb_dim=params['emb_dim'], enc_hid_dim=params['enc_hid_dim'], dec_hid_dim=params['dec_hid_dim'], attention=attn, dropout=params['dropout'])
attn_model = Seq2Seq(encoder=enc, decoder=dec, device=device)
attn_model.load_state_dict(torch.load('AttnSeq2Seq-188M_epoch35.pt', map_location=torch.device('cpu')))
attn_model.to(device)

enc = Encoder(input_dim=params['input_dim'], emb_dim=params['emb_dim'], enc_hid_dim=params['enc_hid_dim'], dec_hid_dim=params['dec_hid_dim'], dropout=params['dropout'])
dec = Decoder(output_dim=params['input_dim'], emb_dim=params['emb_dim'], enc_hid_dim=params['enc_hid_dim'], dec_hid_dim=params['dec_hid_dim'], dropout=params['dropout'])
norm_model = Seq2Seq(encoder=enc, decoder=dec, device=device)
norm_model.load_state_dict(torch.load('NormSeq2Seq-188M_epoch35.pt', map_location=torch.device('cpu')))
norm_model.to(device)

with open('vocab219/word2idx.json', 'r') as f:
    word2idx2 = json.load(f)
with open('vocab219/idx2word.json', 'r') as f:
    idx2word2 = json.load(f)

params219 = {'input_dim': len(word2idx2),
            'emb_dim': 192,
            'enc_hid_dim': 256,
            'dec_hid_dim': 256,
            'dropout': 0.5,
            'attn_dim': 64,
            'teacher_forcing_ratio': 0.5,
            'epochs': 35}

enc = Encoder(input_dim=params219['input_dim'], emb_dim=params219['emb_dim'],
              enc_hid_dim=params219['enc_hid_dim'], dec_hid_dim=params219['dec_hid_dim'],
              dropout=params219['dropout'])
attn = Attention(enc_hid_dim=params219['enc_hid_dim'], dec_hid_dim=params219['dec_hid_dim'],
                 attn_dim=params219['attn_dim'])
dec = AttnDecoder(output_dim=params219['input_dim'], emb_dim=params219['emb_dim'],
                  enc_hid_dim=params219['enc_hid_dim'], dec_hid_dim=params219['dec_hid_dim'],
                  attention=attn, dropout=params219['dropout'])
attn_model219 = Seq2Seq(encoder=enc, decoder=dec, device=device)
attn_model219.load_state_dict(torch.load('AttnSeq2Seq-219M_epoch35.pt',
                              map_location=torch.device('cpu')))
attn_model219.to(device)

enc = Encoder(input_dim=params219['input_dim'], emb_dim=params219['emb_dim'],
              enc_hid_dim=params219['enc_hid_dim'],
              dec_hid_dim=params219['dec_hid_dim'], dropout=params219['dropout'])
dec = Decoder(output_dim=params219['input_dim'], emb_dim=params219['emb_dim'],
              enc_hid_dim=params219['enc_hid_dim'],
              dec_hid_dim=params219['dec_hid_dim'],
              dropout=params219['dropout'])
norm_model219 = Seq2Seq(encoder=enc, decoder=dec, device=device)
norm_model219.load_state_dict(torch.load('NormSeq2Seq-219M_epoch35.pt',
                              map_location=torch.device('cpu')))
norm_model219.to(device)

with open('vocab219SW/word2idx.json', 'r') as f:
    word2idx3 = json.load(f)
with open('vocab219SW/idx2word.json', 'r') as f:
    idx2word3 = json.load(f)

params219SW = {'input_dim': len(word2idx3),
            'emb_dim': 192,
            'enc_hid_dim': 256,
            'dec_hid_dim': 256,
            'dropout': 0.5,
            'attn_dim': 64,
            'teacher_forcing_ratio': 0.5,
            'epochs': 35}

enc = Encoder(input_dim=params219SW['input_dim'], emb_dim=params219SW['emb_dim'],
              enc_hid_dim=params219SW['enc_hid_dim'], dec_hid_dim=params219SW['dec_hid_dim'],
              dropout=params219SW['dropout'])
attn = Attention(enc_hid_dim=params219SW['enc_hid_dim'], dec_hid_dim=params219SW['dec_hid_dim'],
                 attn_dim=params219SW['attn_dim'])
dec = AttnDecoder(output_dim=params219SW['input_dim'], emb_dim=params219['emb_dim'],
                  enc_hid_dim=params219SW['enc_hid_dim'], dec_hid_dim=params219SW['dec_hid_dim'],
                  attention=attn, dropout=params219SW['dropout'])
attn_model219SW = Seq2Seq(encoder=enc, decoder=dec, device=device)
attn_model219SW.load_state_dict(torch.load('AttnSeq2Seq-219M-SW_epoch35.pt',
                              map_location=torch.device('cpu')))
attn_model219SW.to(device)

enc = Encoder(input_dim=params219SW['input_dim'], emb_dim=params219SW['emb_dim'],
              enc_hid_dim=params219SW['enc_hid_dim'],
              dec_hid_dim=params219SW['dec_hid_dim'], dropout=params219SW['dropout'])
dec = Decoder(output_dim=params219SW['input_dim'], emb_dim=params219SW['emb_dim'],
              enc_hid_dim=params219SW['enc_hid_dim'],
              dec_hid_dim=params219SW['dec_hid_dim'],
              dropout=params219SW['dropout'])
norm_model219SW = Seq2Seq(encoder=enc, decoder=dec, device=device)
norm_model219SW.load_state_dict(torch.load('NormSeq2Seq-219M-SW_epoch35.pt',
                              map_location=torch.device('cpu')))
norm_model219SW.to(device)

nlp = spacy.load('en_core_web_sm')

models_dict = {'AttentionSeq2Seq-188M': attn_model, 'NormalSeq2Seq-188M': norm_model,
               'AttentionSeq2Seq-219M': attn_model219,
               'NormalSeq2Seq-219M': norm_model219,
               'AttentionSeq2Seq-219M-SW': attn_model219SW,
               'NormalSeq2Seq-219M-SW': norm_model219SW}

def generateAttn188(sentence, history, max_len=12,

             word2idx=word2idx, idx2word=idx2word,

             device=device, tokenize=tokenize, preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['AttentionSeq2Seq-188M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

def generateNorm188(sentence, history, max_len=12,

             word2idx=word2idx, idx2word=idx2word,

             device=device, tokenize=tokenize, preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['NormalSeq2Seq-188M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

def generateAttn219(sentence, history, max_len=12,

             word2idx=word2idx2, idx2word=idx2word2,

             device=device, tokenize=tokenize, preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['AttentionSeq2Seq-219M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

def generateNorm219(sentence, history, max_len=12,

             word2idx=word2idx2, idx2word=idx2word2,

             device=device, tokenize=tokenize, preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['NormalSeq2Seq-219M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

def tokenize_context(text, nlp=nlp):
    """

    Tokenize text and remove stop words

    :param text: text to be tokenized

    :return: list of tokens

    """
    return [tok.text for tok in nlp.tokenizer(text) if not tok.is_stop]

def generateAttn219SW(sentence, history, max_len=12,

             word2idx=word2idx3, idx2word=idx2word3,

             device=device, tokenize_context=tokenize_context,

             preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['AttentionSeq2Seq-219M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize_context(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

def generateNorm219SW(sentence, history, max_len=12,

             word2idx=word2idx3, idx2word=idx2word3,

             device=device, tokenize_context=tokenize_context, preprocess_text=preprocess_text,

             lookup_words=lookup_words, models_dict=models_dict):
    """

    Generate response

    :param model: model

    :param sentence: sentence

    :param max_len: maximum length of sequence

    :param word2idx: word to index mapping

    :param idx2word: index to word mapping

    :return: response

    """
    history = history
    model = models_dict['NormalSeq2Seq-219M']
    model.eval()
    sentence = preprocess_text(sentence)
    tokens = tokenize_context(sentence)
    tokens = [word2idx[token] if token in word2idx else word2idx['<unk>'] for token in tokens]
    tokens = [word2idx['<bos>']] + tokens + [word2idx['<eos>']]
    tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(1).to(device)
    outputs = [word2idx['<bos>']]
    with torch.no_grad():
        encoder_outputs, hidden = model.encoder(tokens)
    for t in range(max_len):
        output, hidden = model.decoder(torch.tensor([outputs[-1]], dtype=torch.long).to(device), hidden, encoder_outputs)
        top1 = output.max(1)[1]
        outputs.append(top1.item())
        if top1.item() == word2idx['<eos>']:
            break
    response = lookup_words(idx2word, outputs)
    return ' '.join(response).replace('<bos>', '').replace('<eos>', '').strip()

norm188 = gr.ChatInterface(generateNorm188,
                     title="NormalSeq2Seq-188M",
description="""Seq2Seq Generative Chatbot without Attention.



188,204,500 trainable parameters""")
norm219 = gr.ChatInterface(generateNorm219,
                     title="NormalSeq2Seq-219M",
description="""Seq2Seq Generative Chatbot without Attention.



219,456,724 trainable parameters""")
norm219sw = gr.ChatInterface(generateNorm219SW,
                        title="NormalSeq2Seq-219M-SW",
description="""Seq2Seq Generative Chatbot without Attention.



219,451,344 trainable parameters



Trained with stop words removed for context (input) and more data.""")

attn188 = gr.ChatInterface(generateAttn188,
                     title="AttentionSeq2Seq-188M",
description="""Seq2Seq Generative Chatbot with Attention.



188,229,108 trainable parameters""")
attn219 = gr.ChatInterface(generateAttn219,
                     title="AttentionSeq2Seq-219M",
description="""Seq2Seq Generative Chatbot with Attention.



219,505,940 trainable parameters

                     """)
attn219sw = gr.ChatInterface(generateAttn219SW,
                        title="AttentionSeq2Seq-219M-SW",
description="""Seq2Seq Generative Chatbot with Attention.



219,500,560 trainable parameters



Trained with stop words removed for context (input) and more data""")

with gr.Blocks() as demo:
    gr.Markdown(""" > This chatbot is created as part of the Group Project Practical Assessment for University of Liverpool's CSCK507 Natural Language Processing and Understanding (June 2023)

    

    > Disclaimer: Please be advised that this chatbot is an AI language model designed to generate responses based on patterns in data it has been trained on (Ubuntu Dialogue Dataset).

    While efforts have been made to ensure that the responses generated are appropriate and respectful, there is a possibility that the chatbot may occasionally produce content that could be offensive, vulgar, or inappropriate.""")
    gr.TabbedInterface([norm188, norm219, norm219sw], ["188M", "219M", "219M-SW"])
    gr.TabbedInterface([attn188, attn219, attn219sw], ["188M", "219M", "219M-SW"])

if __name__ == "__main__":
    demo.launch()