Jayesh13 PBJ commited on
Commit
96091b1
·
0 Parent(s):

Duplicate from PBJ/Toxic-Comment-Classification

Browse files

Co-authored-by: Prabhanjan Jadhav <PBJ@users.noreply.huggingface.co>

Files changed (5) hide show
  1. .gitattributes +34 -0
  2. README.md +14 -0
  3. app.py +137 -0
  4. dsbert_toxic_balanced.pt +3 -0
  5. requirements.txt +7 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Toxic Comment Classification
3
+ emoji: 🌖
4
+ colorFrom: indigo
5
+ colorTo: pink
6
+ sdk: streamlit
7
+ sdk_version: 1.15.2
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: PBJ/Toxic-Comment-Classification
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing necessary libraries
2
+ import streamlit as st
3
+ import os
4
+ import numpy as np
5
+ import pandas as pd
6
+ import matplotlib.pyplot as plt
7
+ import re
8
+
9
+ st.title('Toxic Comment Classification')
10
+ comment = st.text_area("Enter Your Text", "Type Here")
11
+
12
+ comment_input = []
13
+ comment_input.append(comment)
14
+ test_df = pd.DataFrame()
15
+ test_df['comment_text'] = comment_input
16
+ cols = {'toxic':[0], 'severe_toxic':[0], 'obscene':[0], 'threat':[0], 'insult':[0], 'identity_hate':[0], 'non_toxic': [0]}
17
+ for key in cols.keys():
18
+ test_df[key] = cols[key]
19
+ test_df = test_df.reset_index()
20
+ test_df.drop(columns=["index"], inplace=True)
21
+
22
+ # Data Cleaning and Preprocessing
23
+ # creating copy of data for data cleaning and preprocessing
24
+ cleaned_data = test_df.copy()
25
+
26
+ # Removing Hyperlinks from text
27
+ cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"https?://\S+|www\.\S+","",x) )
28
+
29
+ # Removing emojis from text
30
+ cleaned_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
40
+ cleaned_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
43
+ cleaned_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"
46
+ cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\"\"", "\"",x)) # replacing "" with "
47
+ cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"^\"", "",x)) # removing quotation from start and the end of the string
48
+ cleaned_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
51
+ cleaned_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
54
+ cleaned_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 text
57
+ cleaned_data["comment_text"] = cleaned_data["comment_text"].map(lambda x: re.sub(r"\s\s+", " ",x))
58
+
59
+ Final_data = cleaned_data.copy()
60
+
61
+ # Model Building
62
+ from transformers import DistilBertTokenizer
63
+ import torch
64
+ import torch.nn as nn
65
+ from torch.utils.data import DataLoader, Dataset
66
+
67
+ # Using Pretrained DistilBertTokenizer
68
+ tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
69
+
70
+ # Creating Dataset class for Toxic comments and Labels
71
+ class 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, label
86
+
87
+ X_test = pd.DataFrame(test_df.iloc[:, 0])
88
+ Y_test = test_df.iloc[:, 1:]
89
+ Test_data = Toxic_Dataset(X_test, Y_test)
90
+ Test_Loader = DataLoader(Test_data, shuffle=False)
91
+
92
+ # Loading pre-trained weights of DistilBert model for sequence classification
93
+ # and changing classifiers output to 7 because we have 7 labels to classify.
94
+ # DistilBERT
95
+
96
+ from transformers import DistilBertForSequenceClassification
97
+
98
+ Distil_bert = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
99
+
100
+ Distil_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 weights
107
+ model = Distil_bert
108
+ model.to('cpu')
109
+ model = torch.load('dsbert_toxic_balanced.pt', map_location=torch.device('cpu'))
110
+
111
+ # Making Predictions
112
+ for 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.logits
120
+
121
+ res = []
122
+ for i in range(7):
123
+ res.append(op[0, i])
124
+ # print(res)
125
+
126
+ preds = []
127
+
128
+ for i in range(len(res)):
129
+ preds.append(res[i].tolist())
130
+
131
+ classes = ['Toxic', 'Severe Toxic', 'Obscene', 'Threat', 'Insult', 'Identity Hate', 'Non Toxic']
132
+
133
+ if 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
+
dsbert_toxic_balanced.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3bb55eaba141c4c5582838e502074b3c9bcff689321d85b3a3eff211b274c93
3
+ size 267889455
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ numpy
3
+ pandas
4
+ matplotlib
5
+ matplotlib-venn
6
+ torch
7
+ transformers