PBJ/Toxic-Comment-Classification
2
1# Importing necessary libraries2import streamlit as st3import os4import numpy as np5import pandas as pd6import matplotlib.pyplot as plt7import re8 9st.title('Toxic Comment Classification')10comment = st.text_area("Enter Your Text", "Type Here")11 12comment_input = []13comment_input.append(comment)14test_df = pd.DataFrame()15test_df['comment_text'] = comment_input16cols = {'toxic':[0], 'severe_toxic':[0], 'obscene':[0], 'threat':[0], 'insult':[0], 'identity_hate':[0], 'non_toxic': [0]}17for key in cols.keys():18 test_df[key] = cols[key]19test_df = test_df.reset_index()20test_df.drop(columns=["index"], inplace=True)21 22# Data Cleaning and Preprocessing23# creating copy of data for data cleaning and preprocessing24cleaned_data = test_df.copy()25 26# Removing Hyperlinks from text27cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"https?://\S+|www\.\S+","",x) )28 29# Removing emojis from text30cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub("["31 u"\U0001F600-\U0001F64F"32 u"\U0001F300-\U0001F5FF" 33 u"\U0001F680-\U0001F6FF" 34 u"\U0001F1E0-\U0001F1FF" 35 u"\U00002702-\U000027B0"36 u"\U000024C2-\U0001F251"37 "]+","", x, flags=re.UNICODE))38 39# Removing IP addresses from text 40cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}","",x))41 42# Removing html tags from text 43cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"<.*?>","",x))44 45# There are some comments which contain double quoted words like --> ""words"" we will convert these to --> "words" 46cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\"\"", "\"",x)) # replacing "" with "47cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"^\"", "",x)) # removing quotation from start and the end of the string48cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\"$", "",x))49 50# Removing Punctuation / Special characters (;:'".?@!%&*+) which appears more than twice in the text 51cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"[^a-zA-Z0-9\s][^a-zA-Z0-9\s]+", " ",x))52 53# Removing Special characters 54cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"[^a-zA-Z0-9\s\"\',:;?!.()]", " ",x))55 56# Removing extra spaces in text57cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\s\s+", " ",x))58 59Final_data = cleaned_data.copy()60 61# Model Building62from transformers import DistilBertTokenizer63import torch64import torch.nn as nn65from torch.utils.data import DataLoader, Dataset66 67# Using Pretrained DistilBertTokenizer68tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")69 70# Creating Dataset class for Toxic comments and Labels 71class Toxic_Dataset(Dataset):72 def __init__(self, Comments_, Labels_):73 self.comments = Comments_.copy()74 self.labels = Labels_.copy()75 76 self.comments["comment_text"] = self.comments["comment_text"].map(lambda x: tokenizer(x, padding="max_length", truncation=True, return_tensors="pt"))77 78 def __len__(self):79 return len(self.labels)80 81 def __getitem__(self, idx):82 comment = self.comments.loc[idx,"comment_text"]83 label = np.array(self.labels.loc[idx,:])84 85 return comment, label86 87X_test = pd.DataFrame(test_df.iloc[:, 0])88Y_test = test_df.iloc[:, 1:]89Test_data = Toxic_Dataset(X_test, Y_test)90Test_Loader = DataLoader(Test_data, shuffle=False)91 92# Loading pre-trained weights of DistilBert model for sequence classification93# and changing classifiers output to 7 because we have 7 labels to classify.94# DistilBERT95 96from transformers import DistilBertForSequenceClassification97 98Distil_bert = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")99 100Distil_bert.classifier = nn.Sequential(101 nn.Linear(768,7),102 nn.Sigmoid()103 )104# print(Distil_bert)105 106# Instantiating the model and loading the weights107model = Distil_bert108model.to('cpu')109model = torch.load('dsbert_toxic_balanced.pt', map_location=torch.device('cpu'))110 111# Making Predictions112for comments, labels in Test_Loader:113 labels = labels.to('cpu')114 labels = labels.float()115 masks = comments['attention_mask'].squeeze(1).to('cpu')116 input_ids = comments['input_ids'].squeeze(1).to('cpu')117 118 output = model(input_ids, masks)119 op = output.logits120 121 res = []122 for i in range(7):123 res.append(op[0, i])124 # print(res)125 126preds = []127 128for i in range(len(res)):129 preds.append(res[i].tolist())130 131classes = ['Toxic', 'Severe Toxic', 'Obscene', 'Threat', 'Insult', 'Identity Hate', 'Non Toxic']132 133if st.button('Classify'):134 for i in range(len(res)):135 st.write(f"{classes[i]} : {round(preds[i], 2)}\n")136 st.success('These are the outputs')137 138 