ygorg commited on
Commit
1f7ec3b
·
1 Parent(s): 45bc25f

Keep original files for reproduction.

Browse files
Files changed (1) hide show
  1. _attic/E3C.py +296 -0
_attic/E3C.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pip install bs4 syntok
2
+
3
+ import os
4
+ import random
5
+
6
+ import datasets
7
+
8
+ import numpy as np
9
+ from bs4 import BeautifulSoup, ResultSet
10
+ from syntok.tokenizer import Tokenizer
11
+
12
+ tokenizer = Tokenizer()
13
+
14
+ _CITATION = """\
15
+ @report{Magnini2021, \
16
+ author = {Bernardo Magnini and Begoña Altuna and Alberto Lavelli and Manuela Speranza \
17
+ and Roberto Zanoli and Fondazione Bruno Kessler}, \
18
+ keywords = {Clinical data,clinical enti-ties,corpus,multilingual,temporal information}, \
19
+ title = {The E3C Project: \
20
+ European Clinical Case Corpus El proyecto E3C: European Clinical Case Corpus}, \
21
+ url = {https://uts.nlm.nih.gov/uts/umls/home}, \
22
+ year = {2021}, \
23
+ }
24
+ """
25
+
26
+ _DESCRIPTION = """\
27
+ E3C is a freely available multilingual corpus (English, French, Italian, Spanish, and Basque) \
28
+ of semantically annotated clinical narratives to allow for the linguistic analysis, benchmarking, \
29
+ and training of information extraction systems. It consists of two types of annotations: \
30
+ (i) clinical entities (e.g., pathologies), (ii) temporal information and factuality (e.g., events). \
31
+ Researchers can use the benchmark training and test splits of our corpus to develop and test \
32
+ their own models.
33
+ """
34
+
35
+ _URL = "https://github.com/hltfbk/E3C-Corpus/archive/refs/tags/v2.0.0.zip"
36
+
37
+ _LANGUAGES = ["English","Spanish","Basque","French","Italian"]
38
+
39
+ class E3C(datasets.GeneratorBasedBuilder):
40
+
41
+ BUILDER_CONFIGS = [
42
+ datasets.BuilderConfig(name=f"{lang}_clinical", version="1.0.0", description=f"The {lang} subset of the E3C corpus") for lang in _LANGUAGES
43
+ ]
44
+
45
+ BUILDER_CONFIGS += [
46
+ datasets.BuilderConfig(name=f"{lang}_temporal", version="1.0.0", description=f"The {lang} subset of the E3C corpus") for lang in _LANGUAGES
47
+ ]
48
+
49
+ DEFAULT_CONFIG_NAME = "French_clinical"
50
+
51
+ def _info(self):
52
+
53
+ if self.config.name == "default":
54
+ self.config.name = self.DEFAULT_CONFIG_NAME
55
+
56
+ if self.config.name.find("clinical") != -1:
57
+ names = ["O","B-CLINENTITY","I-CLINENTITY"]
58
+ elif self.config.name.find("temporal") != -1:
59
+ names = ["O", "B-EVENT", "B-ACTOR", "B-BODYPART", "B-TIMEX3", "B-RML", "I-EVENT", "I-ACTOR", "I-BODYPART", "I-TIMEX3", "I-RML"]
60
+
61
+ features = datasets.Features(
62
+ {
63
+ "id": datasets.Value("string"),
64
+ "text": datasets.Value("string"),
65
+ "tokens": datasets.Sequence(datasets.Value("string")),
66
+ "ner_tags": datasets.Sequence(
67
+ datasets.features.ClassLabel(
68
+ names=names,
69
+ ),
70
+ ),
71
+ }
72
+ )
73
+
74
+ return datasets.DatasetInfo(
75
+ description=_DESCRIPTION,
76
+ features=features,
77
+ citation=_CITATION,
78
+ supervised_keys=None,
79
+ )
80
+
81
+ def _split_generators(self, dl_manager):
82
+
83
+ data_dir = dl_manager.download_and_extract(_URL)
84
+
85
+ if self.config.name.find("clinical") != -1:
86
+
87
+ return [
88
+ datasets.SplitGenerator(
89
+ name=datasets.Split.TRAIN,
90
+ gen_kwargs={
91
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_clinical",""), "layer2"),
92
+ "split": "train",
93
+ },
94
+ ),
95
+ datasets.SplitGenerator(
96
+ name=datasets.Split.VALIDATION,
97
+ gen_kwargs={
98
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_clinical",""), "layer2"),
99
+ "split": "validation",
100
+ },
101
+ ),
102
+ datasets.SplitGenerator(
103
+ name=datasets.Split.TEST,
104
+ gen_kwargs={
105
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_clinical",""), "layer1"),
106
+ "split": "test",
107
+ },
108
+ ),
109
+ ]
110
+
111
+ elif self.config.name.find("temporal") != -1:
112
+
113
+ return [
114
+ datasets.SplitGenerator(
115
+ name=datasets.Split.TRAIN,
116
+ gen_kwargs={
117
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_temporal",""), "layer1"),
118
+ "split": "train",
119
+ },
120
+ ),
121
+ datasets.SplitGenerator(
122
+ name=datasets.Split.VALIDATION,
123
+ gen_kwargs={
124
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_temporal",""), "layer1"),
125
+ "split": "validation",
126
+ },
127
+ ),
128
+ datasets.SplitGenerator(
129
+ name=datasets.Split.TEST,
130
+ gen_kwargs={
131
+ "filepath": os.path.join(data_dir, "E3C-Corpus-2.0.0/data_annotation", self.config.name.replace("_temporal",""), "layer1"),
132
+ "split": "test",
133
+ },
134
+ ),
135
+ ]
136
+
137
+ @staticmethod
138
+ def get_annotations(entities: ResultSet, text: str) -> list:
139
+
140
+ return [[
141
+ int(entity.get("begin")),
142
+ int(entity.get("end")),
143
+ text[int(entity.get("begin")) : int(entity.get("end"))],
144
+ ] for entity in entities]
145
+
146
+ def get_clinical_annotations(self, entities: ResultSet, text: str) -> list:
147
+
148
+ return [[
149
+ int(entity.get("begin")),
150
+ int(entity.get("end")),
151
+ text[int(entity.get("begin")) : int(entity.get("end"))],
152
+ entity.get("entityID"),
153
+ ] for entity in entities]
154
+
155
+ def get_parsed_data(self, filepath: str):
156
+
157
+ for root, _, files in os.walk(filepath):
158
+
159
+ for file in files:
160
+
161
+ with open(f"{root}/{file}") as soup_file:
162
+
163
+ soup = BeautifulSoup(soup_file, "xml")
164
+ text = soup.find("cas:Sofa").get("sofaString")
165
+
166
+ yield {
167
+ "CLINENTITY": self.get_clinical_annotations(soup.find_all("custom:CLINENTITY"), text),
168
+ "EVENT": self.get_annotations(soup.find_all("custom:EVENT"), text),
169
+ "ACTOR": self.get_annotations(soup.find_all("custom:ACTOR"), text),
170
+ "BODYPART": self.get_annotations(soup.find_all("custom:BODYPART"), text),
171
+ "TIMEX3": self.get_annotations(soup.find_all("custom:TIMEX3"), text),
172
+ "RML": self.get_annotations(soup.find_all("custom:RML"), text),
173
+ "SENTENCE": self.get_annotations(soup.find_all("type4:Sentence"), text),
174
+ "TOKENS": self.get_annotations(soup.find_all("type4:Token"), text),
175
+ }
176
+
177
+ def _generate_examples(self, filepath, split):
178
+
179
+ all_res = []
180
+
181
+ key = 0
182
+
183
+ parsed_content = self.get_parsed_data(filepath)
184
+
185
+ for content in parsed_content:
186
+
187
+ for sentence in content["SENTENCE"]:
188
+
189
+ tokens = [(
190
+ token.offset + sentence[0],
191
+ token.offset + sentence[0] + len(token.value),
192
+ token.value,
193
+ ) for token in list(tokenizer.tokenize(sentence[-1]))]
194
+
195
+ filtered_tokens = list(
196
+ filter(
197
+ lambda token: token[0] >= sentence[0] and token[1] <= sentence[1],
198
+ tokens,
199
+ )
200
+ )
201
+
202
+ tokens_offsets = [
203
+ [token[0] - sentence[0], token[1] - sentence[0]] for token in filtered_tokens
204
+ ]
205
+
206
+ clinical_labels = ["O"] * len(filtered_tokens)
207
+ clinical_cuid = ["CUI_LESS"] * len(filtered_tokens)
208
+ temporal_information_labels = ["O"] * len(filtered_tokens)
209
+
210
+ for entity_type in ["CLINENTITY","EVENT","ACTOR","BODYPART","TIMEX3","RML"]:
211
+
212
+ if len(content[entity_type]) != 0:
213
+
214
+ for entities in list(content[entity_type]):
215
+
216
+ annotated_tokens = [
217
+ idx_token
218
+ for idx_token, token in enumerate(filtered_tokens)
219
+ if token[0] >= entities[0] and token[1] <= entities[1]
220
+ ]
221
+
222
+ for idx_token in annotated_tokens:
223
+
224
+ if entity_type == "CLINENTITY":
225
+ if idx_token == annotated_tokens[0]:
226
+ clinical_labels[idx_token] = f"B-{entity_type}"
227
+ else:
228
+ clinical_labels[idx_token] = f"I-{entity_type}"
229
+ clinical_cuid[idx_token] = entities[-1]
230
+ else:
231
+ if idx_token == annotated_tokens[0]:
232
+ temporal_information_labels[idx_token] = f"B-{entity_type}"
233
+ else:
234
+ temporal_information_labels[idx_token] = f"I-{entity_type}"
235
+
236
+ if self.config.name.find("clinical") != -1:
237
+ _labels = clinical_labels
238
+ elif self.config.name.find("temporal") != -1:
239
+ _labels = temporal_information_labels
240
+
241
+ all_res.append({
242
+ "id": key,
243
+ "text": sentence[-1],
244
+ "tokens": list(map(lambda token: token[2], filtered_tokens)),
245
+ "ner_tags": _labels,
246
+ })
247
+
248
+ key += 1
249
+
250
+ if self.config.name.find("clinical") != -1:
251
+
252
+ if split != "test":
253
+
254
+ ids = [r["id"] for r in all_res]
255
+
256
+ random.seed(4)
257
+ random.shuffle(ids)
258
+ random.shuffle(ids)
259
+ random.shuffle(ids)
260
+
261
+ train, validation = np.split(ids, [int(len(ids)*0.8738)])
262
+
263
+ if split == "train":
264
+ allowed_ids = list(train)
265
+ elif split == "validation":
266
+ allowed_ids = list(validation)
267
+
268
+ for r in all_res:
269
+ if r["id"] in allowed_ids:
270
+ yield r["id"], r
271
+ else:
272
+
273
+ for r in all_res:
274
+ yield r["id"], r
275
+
276
+ elif self.config.name.find("temporal") != -1:
277
+
278
+ ids = [r["id"] for r in all_res]
279
+
280
+ random.seed(4)
281
+ random.shuffle(ids)
282
+ random.shuffle(ids)
283
+ random.shuffle(ids)
284
+
285
+ train, validation, test = np.split(ids, [int(len(ids)*0.70), int(len(ids)*0.80)])
286
+
287
+ if split == "train":
288
+ allowed_ids = list(train)
289
+ elif split == "validation":
290
+ allowed_ids = list(validation)
291
+ elif split == "test":
292
+ allowed_ids = list(test)
293
+
294
+ for r in all_res:
295
+ if r["id"] in allowed_ids:
296
+ yield r["id"], r