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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
import pandas as pd
import numpy as np
import random
import torch
import torch.nn as nn
import torch.optim as optim
#from transformers import BertTokenizer, BertModel
from sklearn.metrics import accuracy_score, f1_score, classification_report
import sklearn_crfsuite
from sklearn_crfsuite import metrics
from sklearn.metrics.pairwise import cosine_similarity
from gensim.models import Word2Vec
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelEncoder 
from torch.utils.data import Dataset, DataLoader 
from torch.nn.utils.rnn import pad_sequence
from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer



EMBEDDING_DIM = 100
PAD_VALUE= -1
MAX_LENGTH = 376
EMBEDDING_DIM = 100
BATCH_SIZE = 16

class preprocess_sentences():
    def __init__(self):
        pass

    def fit(self, X, y=None):
        print('PREPROCESSING')
        return self
    
    def transform(self, X):
        # X = train['tokens'], y = 
        sentences = X.apply(lambda x: x.tolist()).tolist()
        print('--> Preprocessing complete \n', flush=True)
        return sentences
    


class Word2VecTransformer():
    def __init__(self, vector_size = 100, window = 5, min_count = 1, workers = 1, embedding_dim=EMBEDDING_DIM):
        self.model = None
        self.vector_size = vector_size
        self.window = window
        self.min_count = min_count
        self.workers = workers
        self.embedding_dim = embedding_dim

    def fit(self, X, y):
        # https://stackoverflow.com/questions/17242456/python-print-sys-stdout-write-not-visible-when-using-logging
        # https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function
        print('WORD2VEC:', flush=True)
        # This fits the word2vec model
        self.model = Word2Vec(sentences = X, vector_size=self.vector_size, window=self.window
                              , min_count=self.min_count, workers=self.workers)
        print('--> Word2Vec Fitted', flush=True)
        return self
    
    def transform(self, X):
        # This bit should transform the sentences
        embedded_sentences = []

        for sentence in X:
            sentence_vectors = []

            for word in sentence:
                if word in self.model.wv:
                    vec = self.model.wv[word]
                else:
                    vec = np.random.normal(scale=0.6, size=(self.embedding_dim,))
                
                sentence_vectors.append(vec)

            embedded_sentences.append(torch.tensor(sentence_vectors, dtype=torch.float32))
        print('--> Embeddings Complete \n', flush=True)

        return embedded_sentences
    
class Word2VecTransformer_CRF():
    def __init__(self, vector_size = 100, window = 5, min_count = 1, workers = 1, embedding_dim=EMBEDDING_DIM):
        self.model = None
        self.vector_size = vector_size
        self.window = window
        self.min_count = min_count
        self.workers = workers
        self.embedding_dim = embedding_dim

    def fit(self, X, y):
        # https://stackoverflow.com/questions/17242456/python-print-sys-stdout-write-not-visible-when-using-logging
        # https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function
        print('WORD2VEC:', flush=True)
        # This fits the word2vec model
        self.model = Word2Vec(sentences = X, vector_size=self.vector_size, window=self.window
                              , min_count=self.min_count, workers=self.workers)
        print('--> Word2Vec Fitted', flush=True)
        return self
    
    def transform(self, X):
        # This bit should transform the sentences
        embedded_sentences = []

        for sentence in X:
            sentence_vectors = []

            for word in sentence:
                features = {
                    'bias': 1.0,
                    'word.lower()': word.lower(),
                    'word[-3:]': word[-3:],
                    'word[-2:]': word[-2:],
                    'word.isupper()': word.isupper(),
                    'word.istitle()': word.istitle(),
                    'word.isdigit()': word.isdigit(),
                }
                if word in self.model.wv:
                    vec = self.model.wv[word]
                else:
                    vec = np.random.normal(scale=0.6, size=(self.embedding_dim,))

                # https://stackoverflow.com/questions/58736548/how-to-use-word-embedding-as-features-for-crf-sklearn-crfsuite-model-training
                for index in range(len(vec)):
                    features[f"embedding_{index}"] = vec[index]
                
                sentence_vectors.append(features)

            embedded_sentences.append(sentence_vectors)
        print('--> Embeddings Complete \n', flush=True)

        return embedded_sentences
    

class tfidf(BaseEstimator, TransformerMixin):
    def __init__(self):
        self.model = None
        self.embedding_dim = None
        self.idf = None
        self.vocab_size = None
        self.vocab = None
        pass

    def fit(self, X, y = None):
        print('TFIDF:', flush=True)
        joined_sentences = [' '.join(tokens) for tokens in X]
        self.model = TfidfVectorizer()
        self.model.fit(joined_sentences)
        self.vocab = self.model.vocabulary_
        self.idf = self.model.idf_
        self.vocab_size = len(self.vocab)
        self.embedding_dim = self.vocab_size
        print('--> TFIDF Fitted', flush=True)
        return self

    def transform(self, X):

        embedded = []
        for sentence in X:
            sent_vecs = []
            token_counts = {}
            for word in sentence:
                token_counts[word] = token_counts.get(word, 0) + 1

            sent_len = len(sentence)
            for word in sentence:
                vec = np.zeros(self.vocab_size)
                if word in self.vocab:
                    tf = token_counts[word] / sent_len
                    token_idx = self.vocab[word]
                    vec[token_idx] = tf * self.idf[token_idx]
                sent_vecs.append(vec)
            embedded.append(torch.tensor(sent_vecs, dtype=torch.float32))
        print('--> Embeddings Complete \n', flush=True)
        print(embedded[0][0], flush=True)
        print('Those were the embeddings', flush=True)

        
        return embedded
        

class BiLSTM_NER(nn.Module):
    def __init__(self,input_dim, hidden_dim, tagset_size):
        super(BiLSTM_NER, self).__init__()

        # Embedding layer
        #Freeze= false means that it will fine tune
        #self.embedding = nn.Embedding.from_pretrained(embedding_matrix, freeze = False, padding_idx=-1) 
        
        self.lstm = nn.LSTM(input_dim, hidden_dim, batch_first=True, bidirectional=True)
        self.fc = nn.Linear(hidden_dim*2, tagset_size)
    
    def forward(self, sentences):
        #embeds = self.embedding(sentences)
        lstm_out, _ = self.lstm(sentences)
        tag_scores = self.fc(lstm_out)
        
        return tag_scores
    
# Define the FeedForward NN Model
class FeedForwardNN_NER(nn.Module):
    def __init__(self, embedding_dim, hidden_dim, tagset_size):
        super(FeedForwardNN_NER, self).__init__()
        self.fc1 = nn.Linear(embedding_dim, hidden_dim)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_dim, tagset_size)
    
    def forward(self, x):
        # x: (batch_size, seq_length, embedding_dim)
        x = self.fc1(x)             # (batch_size, seq_length, hidden_dim)
        x = self.relu(x)
        logits = self.fc2(x)        # (batch_size, seq_length, tagset_size)
        return logits
    

def pad(batch):
        # batch is a list of (X, y) pairs
        X_batch, y_batch = zip(*batch)

        # Convert to tensors
        X_batch = [torch.tensor(seq, dtype=torch.float32) for seq in X_batch]
        y_batch = [torch.tensor(seq, dtype=torch.long) for seq in y_batch]

        # Pad sequences
        X_padded = pad_sequence(X_batch, batch_first=True, padding_value=PAD_VALUE)
        y_padded = pad_sequence(y_batch, batch_first=True, padding_value=PAD_VALUE)

        return X_padded, y_padded

def pred_pad(batch):
    X_batch = [torch.tensor(seq, dtype=torch.float32) for seq in batch]
    X_padded = pad_sequence(X_batch, batch_first=True, padding_value=PAD_VALUE)
    return X_padded


class Ner_Dataset(Dataset):
        def __init__(self, X, y):
            self.X = X
            self.y = y
    
        def __len__(self):
            return len(self.X)
    
        def __getitem__(self, idx):
            return self.X[idx], self.y[idx]
        



class LSTM(BaseEstimator, ClassifierMixin):
    def __init__(self, embedding_dim = None, hidden_dim = 128, epochs = 5, learning_rate = 0.001, tag2idx = None):
        self.embedding_dim = embedding_dim
        self.hidden_dim = hidden_dim
        self.epochs = epochs
        self.learning_rate = learning_rate
        self.tag2idx = tag2idx



    def fit(self, embedded, encoded_tags):
        print('LSTM:', flush=True)
        data = Ner_Dataset(embedded, encoded_tags)
        train_loader = DataLoader(data, batch_size=BATCH_SIZE, shuffle=True, collate_fn=pad)

        self.model = self.train_LSTM(train_loader)
        print('--> LSTM trained', flush=True)
        return self
    
    def predict(self, X): 
    # Switch to evaluation mode

        test_loader = DataLoader(X, batch_size=1, shuffle=False, collate_fn=pred_pad)

        self.model.eval()
        predictions = []

        # Iterate through test data
        with torch.no_grad():
            for X_batch in test_loader:
                X_batch = X_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
                
                tag_scores = self.model(X_batch)
                _, predicted_tags = torch.max(tag_scores, dim=2)

                # Flatten the tensors to compare word-by-word
                flattened_pred = predicted_tags.view(-1)
                predictions.append(flattened_pred.cpu().numpy())

        predictions = np.concatenate(predictions)
        return predictions


    def train_LSTM(self, train_loader, input_dim=None, hidden_dim=128, epochs=5, learning_rate=0.001): 

        input_dim = self.embedding_dim
        # Instantiate the lstm_model
        lstm_model = BiLSTM_NER(input_dim, hidden_dim=hidden_dim, tagset_size=len(self.tag2idx))
        lstm_model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

        # Loss function and optimizer
        loss_function = nn.CrossEntropyLoss(ignore_index=PAD_VALUE)  # Ignore padding
        optimizer = optim.Adam(lstm_model.parameters(), lr=learning_rate)
        print('--> Training LSTM')

        # Training loop
        for epoch in range(epochs):
            total_loss = 0
            total_correct = 0
            total_words = 0
            lstm_model.train()  # Set model to training mode
            
            for batch_idx, (X_batch, y_batch) in enumerate(train_loader):
                X_batch, y_batch = X_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')), y_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

                # Zero gradients
                optimizer.zero_grad()

                # Forward pass
                tag_scores = lstm_model(X_batch)

                # Reshape and compute loss (ignore padded values)
                loss = loss_function(tag_scores.view(-1, len(self.tag2idx)), y_batch.view(-1))
                
                # Backward pass and optimization
                loss.backward()
                optimizer.step()

                total_loss += loss.item()

                # Compute accuracy for this batch
                # Get the predicted tags (index of max score)
                _, predicted_tags = torch.max(tag_scores, dim=2)

                # Flatten the tensors to compare word-by-word
                flattened_pred = predicted_tags.view(-1)
                flattened_true = y_batch.view(-1)

                # Exclude padding tokens from the accuracy calculation
                mask = flattened_true != PAD_VALUE
                correct = (flattened_pred[mask] == flattened_true[mask]).sum().item()

                # Count the total words in the batch (ignoring padding)
                total_words_batch = mask.sum().item()

                # Update total correct and total words
                total_correct += correct
                total_words += total_words_batch

            avg_loss = total_loss / len(train_loader)
            avg_accuracy = total_correct / total_words * 100  # Accuracy in percentage

            print(f'    ==> Epoch {epoch + 1}/{epochs}, Loss: {avg_loss:.4f}, Accuracy: {avg_accuracy:.2f}%')

        return lstm_model


class FeedforwardNN(BaseEstimator, ClassifierMixin):
    def __init__(self, embedding_dim = None, hidden_dim = 128, epochs = 5, learning_rate = 0.001, tag2idx = None):
        self.embedding_dim = embedding_dim
        self.hidden_dim = hidden_dim
        self.epochs = epochs
        self.learning_rate = learning_rate
        self.tag2idx = tag2idx



    def fit(self, embedded, encoded_tags):
        print('Feed Forward NN: ', flush=True)
        data = Ner_Dataset(embedded, encoded_tags)
        train_loader = DataLoader(data, batch_size=BATCH_SIZE, shuffle=True, collate_fn=pad)

        self.model = self.train_FF(train_loader)
        print('--> Feed Forward trained', flush=True)
        return self
    
    def predict(self, X): 
    # Switch to evaluation mode

        test_loader = DataLoader(X, batch_size=1, shuffle=False, collate_fn=pred_pad)

        self.model.eval()
        predictions = []

        # Iterate through test data
        with torch.no_grad():
            for X_batch in test_loader:
                X_batch = X_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))
                
                tag_scores = self.model(X_batch)
                _, predicted_tags = torch.max(tag_scores, dim=2)

                # Flatten the tensors to compare word-by-word
                flattened_pred = predicted_tags.view(-1)
                predictions.append(flattened_pred.cpu().numpy())

        predictions = np.concatenate(predictions)
        return predictions


    def train_FF(self, train_loader, input_dim=None, hidden_dim=128, epochs=5, learning_rate=0.001): 

        input_dim = self.embedding_dim
        # Instantiate the lstm_model
        ff_model = FeedForwardNN_NER(self.embedding_dim, hidden_dim=hidden_dim, tagset_size=len(self.tag2idx))
        ff_model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

        # Loss function and optimizer
        loss_function = nn.CrossEntropyLoss(ignore_index=PAD_VALUE)  # Ignore padding
        optimizer = optim.Adam(ff_model.parameters(), lr=learning_rate)
        print('--> Training FF')

        # Training loop
        for epoch in range(epochs):
            total_loss = 0
            total_correct = 0
            total_words = 0
            ff_model.train()  # Set model to training mode
            
            for batch_idx, (X_batch, y_batch) in enumerate(train_loader):
                X_batch, y_batch = X_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')), y_batch.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

                # Zero gradients
                optimizer.zero_grad()

                # Forward pass
                tag_scores = ff_model(X_batch)

                # Reshape and compute loss (ignore padded values)
                loss = loss_function(tag_scores.view(-1, len(self.tag2idx)), y_batch.view(-1))
                
                # Backward pass and optimization
                loss.backward()
                optimizer.step()

                total_loss += loss.item()

                # Compute accuracy for this batch
                # Get the predicted tags (index of max score)
                _, predicted_tags = torch.max(tag_scores, dim=2)

                # Flatten the tensors to compare word-by-word
                flattened_pred = predicted_tags.view(-1)
                flattened_true = y_batch.view(-1)

                # Exclude padding tokens from the accuracy calculation
                mask = flattened_true != PAD_VALUE
                correct = (flattened_pred[mask] == flattened_true[mask]).sum().item()

                # Count the total words in the batch (ignoring padding)
                total_words_batch = mask.sum().item()

                # Update total correct and total words
                total_correct += correct
                total_words += total_words_batch

            avg_loss = total_loss / len(train_loader)
            avg_accuracy = total_correct / total_words * 100  # Accuracy in percentage

            print(f'    ==> Epoch {epoch + 1}/{epochs}, Loss: {avg_loss:.4f}, Accuracy: {avg_accuracy:.2f}%')

        return ff_model
        
crf = sklearn_crfsuite.CRF(
    algorithm='lbfgs',
    c1=0.1,
    c2=0.1,
    max_iterations=100,
    all_possible_transitions=True)