# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
"""
Just a quick demo to test torchtext lib and my first experience with NLP.
"""
text = pd.read_csv('/kaggle/input/jigsaw-toxic-severity-rating/comments_to_score.csv')
labels = pd.read_csv('/kaggle/input/jigsaw-toxic-severity-rating/validation_data.csv')
new_labels = np.concatenate((np.zeros(len(labels['less_toxic'])), 
                             np.ones(len(labels['more_toxic']))))
new_comments = np.concatenate((labels['less_toxic'].values, 
                               labels['more_toxic'].values))

dataset = np.stack((new_comments, new_labels), axis=1)

dataset
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator

tokenizer = get_tokenizer('basic_english')

def yield_tokens(data_iter):
    for text, _ in data_iter:
        yield tokenizer(text)
        
vocab = build_vocab_from_iterator(yield_tokens(dataset))
vocab.set_default_index(1)
print(vocab.get_default_index())
text_pipeline = lambda x: vocab(tokenizer(x))
label_pipeline = lambda x: float(x)

text_pipeline('Hello world')
import torch
from torch.utils.data import DataLoader
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

def collate_batch(batch):
    label_list, text_list, offsets = [], [], [0]
    for (_text, _label) in batch:
        label_list.append(_label)
        processed_text = torch.tensor(text_pipeline(_text), dtype=torch.int64)
        text_list.append(processed_text)
        offsets.append(processed_text.size(0))
    label_list = torch.tensor(label_list, dtype=torch.float)
    offsets = torch.tensor(offsets[:-1]).cumsum(dim=0)
    text_list = torch.cat(text_list)
    return label_list.unsqueeze(1).to(device), text_list.to(device), offsets.to(device)

dataloader = DataLoader(dataset, batch_size=4, shuffle=True, collate_fn=collate_batch)

next(iter(dataloader))
import time

def train(dataloader):
    model.train()
    total_acc, total_count = 0, 0
    log_interval = 500
    start_time = time.time()

    for idx, (label, text, offsets) in enumerate(dataloader):
        optimizer.zero_grad()
        predicted_label = model(text, offsets)
        loss = criterion(predicted_label, label)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1)
        optimizer.step()
        total_acc += ((predicted_label > 0.5).float() == label).sum().item()
        total_count += label.size(0)
        if idx % log_interval == 0 and idx > 0:
            elapsed = time.time() - start_time
            print('| epoch {:3d} | {:5d}/{:5d} batches '
                  '| accuracy {:8.3f}'.format(epoch, idx, len(dataloader),
                                              total_acc/total_count))
            total_acc, total_count = 0, 0
            start_time = time.time()

def evaluate(dataloader):
    model.eval()
    total_acc, total_count = 0, 0

    with torch.no_grad():
        for idx, (label, text, offsets) in enumerate(dataloader):
            predicted_label = model(text, offsets)
            loss = criterion(predicted_label, label)
            total_acc += ((predicted_label > 0.5).float() == label).sum().item()
            total_count += label.size(0)
    return total_acc/total_count
from torch import nn

class CustomModel(nn.Module):
    def __init__(self, vocab_size, embed_dim):
        super(CustomModel, self).__init__()
        self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)
        self.fc_1 = nn.Linear(embed_dim, 32)
        self.relu = nn.ReLU()
        self.fc_2 = nn.Linear(32, 1)
        self.init_weights()
        
    def init_weights(self):
        initrange = 0.5
        self.embedding.weight.data.uniform_(-initrange, initrange)
        self.fc_1.weight.data.uniform_(-initrange,initrange)
        self.fc_1.bias.data.zero_()
        self.fc_2.weight.data.uniform_(-initrange,initrange)
        self.fc_2.bias.data.zero_()
        
    def forward(self, text, offsets):
        embedded = self.embedding(text, offsets)
        embedded = self.fc_1(embedded)
        embedded = self.relu(embedded)
        return torch.sigmoid(self.fc_2(embedded))
    
vocab_size = len(vocab)
emsize = 128
model = CustomModel(vocab_size, emsize).to(device)
from torch.utils.data.dataset import random_split
from torchtext.data.functional import to_map_style_dataset
from sklearn.model_selection import train_test_split

EPOCHS = 10 
LR = 1.
BATCH_SIZE = 64 
  
criterion = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=LR)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, .01, gamma=0.1)
total_accu = None
train_iter, test_iter = train_test_split(dataset, test_size=0.1, train_size=0.9, random_state=42)
train_dataset = to_map_style_dataset(train_iter)
test_dataset = to_map_style_dataset(test_iter)

train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE,
                              shuffle=True, collate_fn=collate_batch)
valid_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE,
                              shuffle=True, collate_fn=collate_batch)

for epoch in range(1, EPOCHS + 1):
    epoch_start_time = time.time()
    train(train_dataloader)
    accu_val = evaluate(valid_dataloader)
    if total_accu is not None and total_accu > accu_val:
        scheduler.step()
    else:
        total_accu = accu_val
    
    print('| end of epoch {:3d} | time: {:5.2f}s | valid accuracy {:8.3f} '
          .format(epoch, time.time() - epoch_start_time, accu_val))
def predict(text, text_pipeline):
    with torch.no_grad():
        text = torch.tensor(text_pipeline(text), dtype=torch.int64).to(device)
        offsets = [0]
        offsets.append(text.size(0))
        offsets = torch.tensor(offsets[:-1]).cumsum(dim=0).to(device)
        
        output = model(text, offsets)
        return output

text.text=text.text.astype(str)
    
for index, i in enumerate(text['text']):
    item = predict(i, text_pipeline).item()
    text.at[index, 'score'] = item
    
text.head()
sub_cv = text.drop('text', axis=1)
sub_cv.to_csv('submission.csv', index=False)
"""
If you liked it or found useful - plz UV ;) 

PS: I would like to learn more about NLP, so please share some wisdom or guidance.
"""