-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc_builder.py
157 lines (136 loc) · 5.53 KB
/
doc_builder.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
import json
import nltk
import spacy
from pred_ner import Predictor
from typing import Dict, Any, List, Optional
class DocBuilder:
def __init__(self,
tokenizer,
trainer,
_id: int,
spacy_dir: str,
save_path_dir: str,
mode: str="tokenized"
):
"""
Formats a given document (passed by path to get_doc).
Extracts the abstract and text passages of CORD-19 dataset.
Retrieves the BioNER tags of a document in tag_document.
:param tokenizer: The BERT word tokenizer to be passed to the predictor
:param trainer: The huggingface trainer used for inference to be passed to the predictor
:param _id: The ID of this process to save progress accordingly
:param mode: The mode we expect our DocBuilder to format the data
"""
self.sent_tokenizer = nltk.sent_tokenize
self.word_tokenizer = spacy.load(spacy_dir)
self.pred = Predictor(tokenizer, trainer)
self._id = _id
self.mode = mode
self.save_path = save_path_dir + str(self._id)
def get_saved_point(self):
"""Loads progress of current DocBuilder."""
try:
with open(self.save_path, 'r', encoding="utf-8") as file:
return int(file.readline())
except FileNotFoundError:
self.save(0)
return 0
def save(self, i: int):
"""Saves progress of current DocBuilder progress."""
with open(self.save_path, 'w', encoding="utf-8") as file:
file.write(str(i))
return i
def get_doc(self, path: str) -> (Dict[str: Any],
Dict[str: Any]
):
"""
Annotates a given document (path).
:param path: The path to file
:return: The tuple of old data and new data
"""
with open(path) as file:
data = json.load(file)
tok_abs = self.get_abstract_of(data)
tok_txt = self.get_text_of(data)
tgd_doc = self.tag_document(tok_abs, tok_txt)
amt_tags = self.count_tags(tgd_doc)
amt_words = self.count_words(tok_abs, tok_txt)
ratio = self.calc_ratio(amt_tags, amt_words)
doc = {
"tokenized_abstract": tok_abs,
"tokenized_text": tok_txt,
"tagged_document": tgd_doc,
"amount_of_tags": amt_tags,
"amount_of_words": amt_words,
"gene_to_word_ratio": ratio
}
return data, doc
@staticmethod
def count_tags(tgd_doc: List[List[str]]) -> int:
"""Counts how many gene tags are in a tagged list."""
return sum([x.count("B") for x in tgd_doc])
@staticmethod
def count_words(tok_abs: List[List[str]],
tok_txt: List[List[str]]
) -> int:
"""Counts how many gene tags are in a tagged list."""
return sum(map(len, tok_abs + tok_txt))
@staticmethod
def calc_ratio(amt_tags: int, amt_words: int) -> float:
"""Calculates the percentage of genetags in a document."""
return float(amt_tags/amt_words)
@staticmethod
def write_doc(path: str,
data: Dict[str: Any],
doc: Dict[str: Any]
):
"""Concatenates original data and new data and writes to file."""
with open(path, 'w', encoding="utf-8") as f:
json.dump({**data, **doc}, f)
def tag_document(self,
tok_abs: List[List[str]],
tok_txt: List[List[str]]
) -> List[List[str]]:
"""Sets the data, predicts and returns list of tags.
The structure of the tag list corresponds 1-to-1 to the structure
of the concatenated tokenized abstract and text.
"""
self.pred.set_data(tok_abs + tok_txt)
tags = self.pred.predict()
return tags
def get_text_of(self, data: Dict[str: Any]
) -> Optional[str, List[str], List[List[str]]]:
"""Formats the text of a CORD-19 JSON"""
# raw text string
ps = [p["text"] for p in data["body_text"]]
raw_text = " ".join(ps)
if self.mode == "raw_string":
return raw_text
# list of sentences
sents = self.sent_tokenizer(raw_text)
if self.mode == "sentence_list":
return sents
# list of tokenized sentences
sents = [self.word_tokenizer(sent) for sent in sents]
tokenized = [[str(word) for word in sent] for sent in sents]
if self.mode == "tokenized":
return tokenized
def get_abstract_of(self, data: Dict[str: Any]
) -> Optional[str, List[str], List[List[str]]]:
"""Formats the abstract of a CORD-19 JSON"""
raw_abst = data["abstract"]
abstract = [raw_abst[i]["text"] for i, _ in enumerate(raw_abst)]
if len(abstract) == 0: return [] # some have no abstract
# raw abstract string
abstract = abstract[0]
if self.mode == "raw_string":
return abstract
# list of sentences
sents = self.sent_tokenizer(abstract)
if self.mode == "sentence_list":
return sents
# list of tokenized sentences
sents = [self.word_tokenizer(sent) for sent in sents]
tokenized = [[str(word) for word in sent] for sent in sents]
if self.mode == "tokenized":
return tokenized