/
preprocessing.py
199 lines (167 loc) · 6.24 KB
/
preprocessing.py
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
import argparse
import os
from os.path import join as fjoin
import tqdm
import random
from bs4 import BeautifulSoup
import email
import spacy
from elasticsearch import Elasticsearch
import pickle
nlp = spacy.load("en_core_web_sm")
VOCAB = spacy.load("en_core_web_md").vocab.strings
def create_index(index, es):
print("inside creating index")
if es.indices.exists(index):
print("Index already exists")
else:
request_body = {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1,
"max_result_window": "85000",
},
"mappings": {
"properties": {
"subject": {
"type": "text",
"fielddata": True,
"index_options": "positions"
},
"text": {
"type": "text",
"fielddata": True,
"index_options": "positions"
},
"spam": {
"type": "text",
"fielddata": True,
"store": True
},
"split": {
"type": "text",
"fielddata": True,
"store": True
}
}
}
}
print("index created")
es.indices.create(index=index, body=request_body, ignore=400)
def store_in_ES(index, data, labels, train, test, es):
for key in tqdm.tqdm(data):
subject, content = data[key][0], data[key][1]
if key in labels['spam']:
spam = 'yes'
else:
spam = 'no'
if key in train['spam'] or key in train['ham']:
split = 'train'
if key in test['spam'] or key in test['ham']:
split = 'test'
doc = {
'head': subject,
'text': content,
'spam': spam,
'split': split
}
es.index(index=index, id=key, body=doc)
def post_process(text):
doc = nlp(text, disable=["parser", "tagger", "ner"])
clean_text = [token.orth_ for token in doc if not token.is_punct | token.is_space | token.is_stop]
clean_text = [token.lower() for token in clean_text if token.lower() in VOCAB]
return " ".join(clean_text)
def get_text_from_html(text):
html_text = str(text)
bs = BeautifulSoup(html_text, 'html.parser')
text = bs.get_text().strip()
text = text.replace("\n", " ")
return text
def get_text_from_email(text):
body = email.message_from_string(text)
subject = ''
if body['subject'] is not None:
subject = body['subject']
body_text = ''
if body.is_multipart():
for part in body.walk():
content_type = part.get_content_type()
content_disposition = str(part.get('Content-Disposition'))
if content_type == 'text/plain' and 'attachment' not in content_disposition:
body_text += part.get_payload()
elif content_type =='text/html' and 'attachment' not in content_disposition:
html_text = part.get_payload()
parsed_text = get_text_from_html(html_text)
body_text += parsed_text
else:
content_type = body.get_content_type()
content_disposition = str(body.get('Content-Disposition'))
if content_type == 'text/plain' and 'attachment' not in content_disposition:
body_text += body.get_payload()
elif content_type == 'text/html' and 'attachment' not in content_disposition:
html_text = body.get_payload()
parsed_text = get_text_from_html(html_text)
body_text += parsed_text
subject = post_process(subject)
body_text = post_process(body_text)
return subject, body_text
def read_labels(fname):
'''
spam ../data/inmail.179
'''
labels = {}
with open(fname, 'r') as f:
for line in f:
line = line.strip().split("/")
label = line[0].split(" ")[0]
file = line[2]
if label in labels:
labels[label].append(file)
else:
labels[label] = [file]
return labels
def read_data(dir, savepath=''):
data = {}
if os.path.isfile(savepath):
with open(savepath, "rb") as handle:
data = pickle.load(handle)
return data
files = os.listdir(dir)
for file in tqdm.tqdm(files):
path = fjoin(dir, file)
text = open(path, 'r', encoding='ISO-8859-1').read()
subject, body_text = get_text_from_email(text)
data[file] = [subject, body_text]
with open(savepath, 'wb') as handle:
pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
return data
def main(args):
random.seed(args.seed)
print("starting to read the data")
data = read_data(args.dirpath, args.savepath) # {mail.1 : <content>, mail.2 : <content>}
print("read the data")
labels = read_labels(args.labels) # {spam : [mail.1, mail.2], ham:[mail.3]}
print("read the labels")
train, test = {}, {} #train -> {spam : [], ham:[]}, test -> {spam : [], ham:[]}
for key in labels:
ratio = int(0.8 * len(labels[key]))
random.shuffle(labels[key])
train[key] = labels[key][:ratio]
test[key] = labels[key][ratio:]
print("train and test done")
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
if es.indices.exists(args.index):
print("Index and data already exists on ES")
else:
create_index(args.index, es)
print("data is getting stored on ES")
store_in_ES(args.index, data, labels, train, test, es)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Arguments')
parser.add_argument("--dirpath", type=str, default="data/trec/data/", help="")
parser.add_argument("--labels", type=str, default="data/trec/full/index", help="")
parser.add_argument("--savepath", type=str, default="data/data.pickle", help="")
parser.add_argument("--index", type=str, default="spam_data", help="")
parser.add_argument("--seed", type=int, default=4, help="")
args = parser.parse_args()
main(args)