-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreprocessing.py
executable file
·352 lines (288 loc) · 12.3 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
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
import json
import os
import re
import shutil
from deep_translator import GoogleTranslator
from tqdm import tqdm
from transformers import pipeline
######### CONFIG #########
med_output_path = "data/med"
os.makedirs(med_output_path, exist_ok=True)
cacm_output_path = "data/cacm"
os.makedirs(cacm_output_path, exist_ok=True)
npl_output_path = "data/npl"
os.makedirs(npl_output_path, exist_ok=True)
translator = GoogleTranslator(source="en", target="de")
summarizer = pipeline("summarization")
TRANSLATE_DOCS = False
TRANSLATE_QUERIES = True
SUMMARIZE_DOCS = True
######### MEDLINE #########
print("Preprocessing Medline...")
with open("download/med/MED.ALL") as f, \
open(os.path.join(med_output_path, "med.json"), "w") as g, \
open(os.path.join(med_output_path, "ger_med.json"), "w") as h, \
open(os.path.join(med_output_path, "partly_summarized_med.json"), "w") as k:
lines = ""
for l in f.readlines():
lines += "\n" + l.strip() if l.startswith(".") else " " + l.strip()
lines = lines.lstrip("\n").split("\n")
count = 0
doc_dict = {}
with tqdm(total=1033) as pbar:
for l in lines:
# id
if l.startswith(".I"):
doc_id = l.split(" ")[1].strip()
doc_dict["DOCID"] = doc_id
# text content
elif l.startswith(".W"):
text = l.strip()[3:]
doc_dict["TEXT"] = text
json.dump(doc_dict, g) # write doc record to file
g.write("\n")
if TRANSLATE_DOCS:
ger_doc_dict = {
"DOCID" : doc_id,
"TEXT" : translator.translate(text=text)
}
json.dump(ger_doc_dict, h, ensure_ascii=False)
h.write("\n")
if SUMMARIZE_DOCS:
summarized_doc_dict = {
"DOCID" : doc_id,
"TEXT" : summarizer(text)[0]["summary_text"] if len(text) > 700 else text
}
json.dump(summarized_doc_dict, k, ensure_ascii=False)
k.write("\n")
count += 1
doc_dict = {} # reset record
pbar.update()
print(f"Wrote {count} records to disk")
if SUMMARIZE_DOCS:
# do full summarize of med.json
os.system(f"python3 full_summarize.py med")
# remove quotes from summarized files to have a valid json format
os.system(f"python3 remove_quotes.py ./data/med/partly_summarized_med.json")
os.system(f"python3 remove_quotes.py ./data/med/full_summarized_med.json")
with open("download/med/MED.QRY") as f, \
open(os.path.join(med_output_path, "queries.json"), "w") as g, \
open(os.path.join(med_output_path, "ger_queries.json"), "w") as h:
lines = ""
for l in f.readlines():
lines += "\n" + l.strip() if l.startswith(".") else " " + l.strip()
lines = lines.lstrip("\n").split("\n")
queries = []
ger_queries = []
query_dict = {}
with tqdm(total=30) as pbar:
for l in lines:
# id
if l.startswith(".I"):
query_id = l.split(" ")[1].strip()
query_dict["QUERYID"] = query_id
# query text
elif l.startswith(".W"):
query = l.strip()[3:]
query_dict["QUERY"] = query
queries.append(query_dict) # add record to queries list
if TRANSLATE_QUERIES:
ger_query_dict = {
"QUERYID" : query_id,
"QUERY" : translator.translate(text=query)
}
ger_queries.append(ger_query_dict)
query_dict = {} # reset record
pbar.update()
# write queries list to file
dictionary = {"QUERIES": queries}
json.dump(dictionary, g)
ger_dictionary = {"QUERIES": ger_queries}
json.dump(ger_dictionary, h, ensure_ascii=False)
print(f"Wrote {len(queries)} queries to disk")
# relevance judgements already in trec_eval format, just copy
shutil.copyfile("download/med/MED.REL", os.path.join(med_output_path, "qrels-treceval.txt"))
######### CACM #########
print("Preprocessing CACM...")
with open("download/cacm/cacm.all") as f, \
open(os.path.join(cacm_output_path, "cacm.json"), "w") as g, \
open(os.path.join(cacm_output_path, "ger_cacm.json"), "w") as h, \
open(os.path.join(cacm_output_path, "partly_summarized_cacm.json"), "w") as k:
lines = ""
for l in f.readlines():
lines += "\n" + l.strip() if l.startswith(".") else " " + l.strip()
lines = lines.lstrip("\n").split("\n")
count = 0
doc_dict = {}
with tqdm(total=3204) as pbar:
for l in lines:
# id
if l.startswith(".I"):
doc_id = l.split(" ")[1].strip()
doc_dict["DOCID"] = doc_id
# title
elif l.startswith(".T"):
title = l.strip()[3:]
doc_dict["TEXT"] = title
# abstract
elif l.startswith(".W"):
abstract = l.strip()[3:]
doc_dict["TEXT"] += ": " + abstract
# last attribute (a doc is a sequence of lines .I, .T, .W, .B, .A, .N, .X)
elif l.startswith(".X"):
json.dump(doc_dict, g) # write doc record to file
g.write("\n")
if TRANSLATE_DOCS:
ger_doc_dict = {
"DOCID" : doc_id,
"TEXT" : translator.translate(text=doc_dict["TEXT"])
}
json.dump(ger_doc_dict, h, ensure_ascii=False)
h.write("\n")
text = doc_dict["TEXT"]
if SUMMARIZE_DOCS:
summarized_doc_dict = {
"DOCID" : doc_id,
"TEXT" : summarizer(text)[0]["summary_text"] if len(text) > 700 else text
}
json.dump(summarized_doc_dict, k, ensure_ascii=False)
k.write("\n")
count += 1
doc_dict = {} # reset record
pbar.update()
print(f"Wrote {count} records to disk")
if SUMMARIZE_DOCS:
# do full summarize of cacm.json
os.system(f"python3 full_summarize.py cacm")
# remove quotes from summarized files to have a valid json format
os.system(f"python3 remove_quotes.py ./data/cacm/partly_summarized_cacm.json")
os.system(f"python3 remove_quotes.py ./data/cacm/full_summarized_cacm.json")
with open("download/cacm/query.text") as f, \
open(os.path.join(cacm_output_path, "queries.json"), "w") as g, \
open(os.path.join(cacm_output_path, "ger_queries.json"), "w") as h:
lines = ""
for l in f.readlines():
lines += "\n" + l.strip() if l.startswith(".") else " " + l.strip()
lines = lines.lstrip("\n").split("\n")
queries = []
ger_queries = []
query_dict = {}
with tqdm(total=64) as pbar:
for l in lines:
# id
if l.startswith(".I"):
query_id = l.split(" ")[1].strip()
query_dict["QUERYID"] = query_id
# query text and last useful attribute
elif l.startswith(".W"):
query = l.strip()[3:]
query_dict["QUERY"] = query
queries.append(query_dict) # add record to queries list
if TRANSLATE_QUERIES:
ger_query_dict = {
"QUERYID" : query_id,
"QUERY" : translator.translate(text=query)
}
ger_queries.append(ger_query_dict)
query_dict = {} # reset record
pbar.update()
# write queries list to file
dictionary = {"QUERIES": queries}
json.dump(dictionary, g)
ger_dictionary = {"QUERIES": ger_queries}
json.dump(ger_dictionary, h, ensure_ascii=False)
print(f"Wrote {len(queries)} queries to disk")
with open("download/cacm/qrels.text") as f, open(os.path.join(cacm_output_path, "qrels-treceval.txt"), "w") as g:
lines = f.readlines()
for l in lines:
query_id, doc_id, _, _ = l.split()
# write in trec_eval format
g.write(f"{int(query_id)} 0 {doc_id} 1\n")
######### NPL #########
print("Preprocessing NPL...")
pattern = r"(\d+)\n(.*?)\n /"
with open("download/npl/doc-text") as f, \
open(os.path.join(npl_output_path, "npl.json"), "w") as g, \
open(os.path.join(npl_output_path, "ger_npl.json"), "w") as h, \
open(os.path.join(npl_output_path, "partly_summarized_npl.json"), "w") as k:
document = f.read()
count = 0
with tqdm(total=11429) as pbar:
for match in re.findall(pattern, document, re.DOTALL):
doc_id = match[0]
text = re.sub(r" +", " ", match[1].replace("\n", ' ')) # remove new lines and double spaces
doc_dict = {
"DOCID": doc_id,
"TEXT": text
}
json.dump(doc_dict, g)
g.write("\n")
if TRANSLATE_DOCS:
ger_doc_dict = {
"DOCID": doc_id,
"TEXT": translator.translate(text=text)
}
json.dump(ger_doc_dict, h, ensure_ascii=False)
h.write("\n")
if SUMMARIZE_DOCS:
summarized_doc_dict = {
"DOCID" : doc_id,
"TEXT" : summarizer(text)[0]["summary_text"] if len(text) > 700 else text
}
json.dump(summarized_doc_dict, k, ensure_ascii=False)
k.write("\n")
count += 1
pbar.update()
print(f"Wrote {count} records to disk")
if SUMMARIZE_DOCS:
# do full summarize of npl.json
os.system(f"python3 full_summarize.py npl")
# remove quotes from summarized files to have a valid json format
os.system(f"python3 remove_quotes.py ./data/npl/partly_summarized_npl.json")
os.system(f"python3 remove_quotes.py ./data/npl/full_summarized_npl.json")
pattern = r"(\d+)\n(.*?)\n/"
with open("download/npl/query-text") as f, \
open(os.path.join(npl_output_path, "queries.json"), "w") as g, \
open(os.path.join(npl_output_path, "ger_queries.json"), "w") as h:
document = f.read()
queries = []
ger_queries = []
with tqdm(total=93) as pbar:
for match in re.findall(pattern, document, re.DOTALL):
query_id = match[0]
query = match[1].lower()
query_dict = {
"QUERYID": query_id,
"QUERY": query
}
queries.append(query_dict)
if TRANSLATE_QUERIES:
ger_query_dict = {
"QUERYID": query_id,
"QUERY": translator.translate(text=query)
}
ger_queries.append(ger_query_dict)
pbar.update()
json.dump({"QUERIES": queries}, g)
json.dump({"QUERIES": ger_queries}, h, ensure_ascii=False)
print(f"Wrote {len(queries)} queries to disk")
pattern = r"(\d+)\n(.*?)\n /"
with open("download/npl/rlv-ass") as f, open(os.path.join(npl_output_path, "qrels-treceval.txt"), "w") as g:
document = f.read()
for match in re.findall(pattern, document, re.DOTALL):
query_id = match[0]
for doc_id in match[1].split():
g.write(f"{query_id} 0 {doc_id} 1\n")
######### REMOVE FILES #########
if not TRANSLATE_DOCS:
os.remove(os.path.join(med_output_path, "ger_med.json"))
os.remove(os.path.join(cacm_output_path, "ger_cacm.json"))
os.remove(os.path.join(npl_output_path, "ger_npl.json"))
if not TRANSLATE_QUERIES:
os.remove(os.path.join(med_output_path, "ger_queries.json"))
os.remove(os.path.join(cacm_output_path, "ger_queries.json"))
os.remove(os.path.join(npl_output_path, "ger_queries.json"))
if not SUMMARIZE_DOCS:
os.remove(os.path.join(med_output_path, "partly_summarized_med.json"))
os.remove(os.path.join(cacm_output_path, "partly_summarized_cacm.json"))
os.remove(os.path.join(npl_output_path, "partly_summarized_npl.json"))