gabrielaltay commited on
Commit
8e78222
1 Parent(s): a8c1391

upload hubscripts/pico_extraction_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. pico_extraction.py +291 -0
pico_extraction.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ This dataset contains annotations for Participants, Interventions, and Outcomes (referred to as PICO task).
18
+ For 423 sentences, annotations collected by 3 medical experts are available.
19
+ To get the final annotations, we perform the majority voting.
20
+ The script loads dataset in bigbio schema (using knowledgebase schema: schemas/kb) AND/OR source (default) schema
21
+ """
22
+ import json
23
+ from typing import Dict, List, Tuple, Union
24
+
25
+ import datasets
26
+ import numpy as np
27
+
28
+ from .bigbiohub import kb_features
29
+ from .bigbiohub import BigBioConfig
30
+ from .bigbiohub import Tasks
31
+
32
+ _LANGUAGES = ['English']
33
+ _PUBMED = True
34
+ _LOCAL = False
35
+ _CITATION = """\
36
+ @inproceedings{zlabinger-etal-2020-effective,
37
+ title = "Effective Crowd-Annotation of Participants, Interventions, and Outcomes in the Text of Clinical Trial Reports",
38
+ author = {Zlabinger, Markus and
39
+ Sabou, Marta and
40
+ Hofst{\"a}tter, Sebastian and
41
+ Hanbury, Allan},
42
+ booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2020",
43
+ month = nov,
44
+ year = "2020",
45
+ address = "Online",
46
+ publisher = "Association for Computational Linguistics",
47
+ url = "https://aclanthology.org/2020.findings-emnlp.274",
48
+ doi = "10.18653/v1/2020.findings-emnlp.274",
49
+ pages = "3064--3074",
50
+ }
51
+ """
52
+
53
+ _DATASETNAME = "pico_extraction"
54
+ _DISPLAYNAME = "PICO Annotation"
55
+
56
+
57
+ _DESCRIPTION = """\
58
+ This dataset contains annotations for Participants, Interventions, and Outcomes (referred to as PICO task).
59
+ For 423 sentences, annotations collected by 3 medical experts are available.
60
+ To get the final annotations, we perform the majority voting.
61
+ """
62
+
63
+ _HOMEPAGE = "https://github.com/Markus-Zlabinger/pico-annotation"
64
+
65
+ _LICENSE = 'License information unavailable'
66
+
67
+ _DATA_PATH = (
68
+ "https://raw.githubusercontent.com/Markus-Zlabinger/pico-annotation/master/data"
69
+ )
70
+ _URLS = {
71
+ _DATASETNAME: {
72
+ "sentence_file": f"{_DATA_PATH}/sentences.json",
73
+ "annotation_files": {
74
+ "intervention": f"{_DATA_PATH}/annotations/interventions_expert.json",
75
+ "outcome": f"{_DATA_PATH}/annotations/outcomes_expert.json",
76
+ "participant": f"{_DATA_PATH}/annotations/participants_expert.json",
77
+ },
78
+ }
79
+ }
80
+
81
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
82
+ _SOURCE_VERSION = "1.0.0"
83
+ _BIGBIO_VERSION = "1.0.0"
84
+
85
+
86
+ def _pico_extraction_data_loader(
87
+ sentence_file: str, annotation_files: Dict[str, str]
88
+ ) -> Tuple[Dict[str, str], Dict[str, Dict[str, Dict[str, List[int]]]]]:
89
+ """Loads four files with PICO extraction dataset:
90
+ - one json file with sentences
91
+ - three json files with annotations for PIO
92
+ """
93
+ # load sentences
94
+ with open(sentence_file) as fp:
95
+ sentences = json.load(fp)
96
+
97
+ # load annotations
98
+ annotation_dict = {}
99
+ for annotation_type, _file in annotation_files.items():
100
+ with open(_file) as fp:
101
+ annotations = json.load(fp)
102
+ annotation_dict[annotation_type] = annotations
103
+
104
+ return sentences, annotation_dict
105
+
106
+
107
+ def _get_entities_pico(
108
+ annotation_dict: Dict[str, Dict[str, Dict[str, List[int]]]],
109
+ sentence: str,
110
+ sentence_id: str,
111
+ ) -> List[Dict[str, Union[int, str]]]:
112
+ """extract entities from sentences using annotation_dict"""
113
+
114
+ def _partition(alist, indices):
115
+ return [alist[i:j] for i, j in zip([0] + indices, indices + [None])]
116
+
117
+ ents = []
118
+ for annotation_type, annotations in annotation_dict.items():
119
+ # get indices from three annotators by majority voting
120
+ indices = np.where(
121
+ np.round(np.mean(annotations[sentence_id]["annotations"], axis=0)) == 1
122
+ )[0]
123
+
124
+ if len(indices) > 0: # if annotations exist for this sentence
125
+ split_indices = []
126
+ # if there are two annotations of one type in one sentence
127
+ for item_index, item in enumerate(indices):
128
+ if item_index + 1 == len(indices):
129
+ break
130
+ if indices[item_index] + 1 != indices[item_index + 1]:
131
+ split_indices.append(item_index + 1)
132
+ multiple_indices = _partition(indices, split_indices)
133
+
134
+ for _indices in multiple_indices:
135
+
136
+ annotation_text = " ".join([sentence.split()[ind] for ind in _indices])
137
+
138
+ char_start = sentence.find(annotation_text)
139
+ char_end = char_start + len(annotation_text)
140
+
141
+ ent = {
142
+ "annotation_text": annotation_text,
143
+ "annotation_type": annotation_type,
144
+ "char_start": char_start,
145
+ "char_end": char_end,
146
+ }
147
+
148
+ ents.append(ent)
149
+ return ents
150
+
151
+
152
+ class PicoExtractionDataset(datasets.GeneratorBasedBuilder):
153
+ """PICO Extraction dataset with annotations for
154
+ Participants, Interventions, and Outcomes."""
155
+
156
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
157
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
158
+
159
+ BUILDER_CONFIGS = [
160
+ BigBioConfig(
161
+ name="pico_extraction_source",
162
+ version=SOURCE_VERSION,
163
+ description="pico_extraction source schema",
164
+ schema="source",
165
+ subset_id="pico_extraction",
166
+ ),
167
+ BigBioConfig(
168
+ name="pico_extraction_bigbio_kb",
169
+ version=BIGBIO_VERSION,
170
+ description="pico_extraction BigBio schema",
171
+ schema="bigbio_kb",
172
+ subset_id="pico_extraction",
173
+ ),
174
+ ]
175
+
176
+ DEFAULT_CONFIG_NAME = "pico_extraction_source"
177
+
178
+ def _info(self) -> datasets.DatasetInfo:
179
+
180
+ if self.config.schema == "source":
181
+ features = datasets.Features(
182
+ {
183
+ "doc_id": datasets.Value("string"),
184
+ "text": datasets.Value("string"),
185
+ "entities": [
186
+ {
187
+ "text": datasets.Value("string"),
188
+ "type": datasets.Value("string"),
189
+ "start": datasets.Value("int64"),
190
+ "end": datasets.Value("int64"),
191
+ }
192
+ ],
193
+ }
194
+ )
195
+
196
+ elif self.config.schema == "bigbio_kb":
197
+ features = kb_features
198
+
199
+ return datasets.DatasetInfo(
200
+ description=_DESCRIPTION,
201
+ features=features,
202
+ homepage=_HOMEPAGE,
203
+ license=str(_LICENSE),
204
+ citation=_CITATION,
205
+ )
206
+
207
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
208
+ """Returns SplitGenerators."""
209
+
210
+ urls = _URLS[_DATASETNAME]
211
+ data_dir = dl_manager.download_and_extract(urls)
212
+
213
+ return [
214
+ datasets.SplitGenerator(
215
+ name=datasets.Split.TRAIN,
216
+ gen_kwargs={
217
+ "split": "train",
218
+ "sentence_file": data_dir["sentence_file"],
219
+ "annotation_files": data_dir["annotation_files"],
220
+ },
221
+ ),
222
+ ]
223
+
224
+ def _generate_examples(self, split, sentence_file, annotation_files):
225
+ """Yields examples as (key, example) tuples."""
226
+
227
+ sentences, annotation_dict = _pico_extraction_data_loader(
228
+ sentence_file=sentence_file, annotation_files=annotation_files
229
+ )
230
+
231
+ if self.config.schema == "source":
232
+ for uid, sentence_tuple in enumerate(sentences.items()):
233
+ sentence_id, sentence = sentence_tuple
234
+ ents = _get_entities_pico(annotation_dict, sentence, sentence_id)
235
+
236
+ data = {
237
+ "doc_id": sentence_id,
238
+ "text": sentence,
239
+ "entities": [
240
+ {
241
+ "text": ent["annotation_text"],
242
+ "type": ent["annotation_type"],
243
+ "start": ent["char_start"],
244
+ "end": ent["char_end"],
245
+ }
246
+ for ent in ents
247
+ ],
248
+ }
249
+ yield uid, data
250
+
251
+ elif self.config.schema == "bigbio_kb":
252
+ uid = 0
253
+ for id_, sentence_tuple in enumerate(sentences.items()):
254
+ if id_ < 2:
255
+ continue
256
+ sentence_id, sentence = sentence_tuple
257
+ ents = _get_entities_pico(annotation_dict, sentence, sentence_id)
258
+
259
+ data = {
260
+ "id": str(uid),
261
+ "document_id": sentence_id,
262
+ "passages": [],
263
+ "entities": [],
264
+ "relations": [],
265
+ "events": [],
266
+ "coreferences": [],
267
+ }
268
+ uid += 1
269
+
270
+ data["passages"] = [
271
+ {
272
+ "id": str(uid),
273
+ "type": "sentence",
274
+ "text": [sentence],
275
+ "offsets": [[0, len(sentence)]],
276
+ }
277
+ ]
278
+ uid += 1
279
+
280
+ for ent in ents:
281
+ entity = {
282
+ "id": uid,
283
+ "type": ent["annotation_type"],
284
+ "text": [ent["annotation_text"]],
285
+ "offsets": [[ent["char_start"], ent["char_end"]]],
286
+ "normalized": [],
287
+ }
288
+ data["entities"].append(entity)
289
+ uid += 1
290
+
291
+ yield uid, data