Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
gabrielaltay commited on
Commit
7017766
·
1 Parent(s): c41d790

upload hubscripts/progene_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. progene.py +354 -0
progene.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import itertools
17
+ import os
18
+ import pathlib
19
+ from typing import Dict, Iterable, Iterator, List, Tuple
20
+
21
+ import datasets
22
+
23
+ from .bigbiohub import kb_features
24
+ from .bigbiohub import BigBioConfig
25
+ from .bigbiohub import Tasks
26
+
27
+ _LANGUAGES = ['English']
28
+ _PUBMED = True
29
+ _LOCAL = False
30
+ _CITATION = """\
31
+ @inproceedings{faessler-etal-2020-progene,
32
+ title = "{P}ro{G}ene - A Large-scale, High-Quality Protein-Gene Annotated Benchmark Corpus",
33
+ author = "Faessler, Erik and
34
+ Modersohn, Luise and
35
+ Lohr, Christina and
36
+ Hahn, Udo",
37
+ booktitle = "Proceedings of the 12th Language Resources and Evaluation Conference",
38
+ month = may,
39
+ year = "2020",
40
+ address = "Marseille, France",
41
+ publisher = "European Language Resources Association",
42
+ url = "https://aclanthology.org/2020.lrec-1.564",
43
+ pages = "4585--4596",
44
+ abstract = "Genes and proteins constitute the fundamental entities of molecular genetics. We here introduce ProGene (formerly called FSU-PRGE), a corpus that reflects our efforts to cope with this important class of named entities within the framework of a long-lasting large-scale annotation campaign at the Jena University Language {\&} Information Engineering (JULIE) Lab. We assembled the entire corpus from 11 subcorpora covering various biological domains to achieve an overall subdomain-independent corpus. It consists of 3,308 MEDLINE abstracts with over 36k sentences and more than 960k tokens annotated with nearly 60k named entity mentions. Two annotators strove for carefully assigning entity mentions to classes of genes/proteins as well as families/groups, complexes, variants and enumerations of those where genes and proteins are represented by a single class. The main purpose of the corpus is to provide a large body of consistent and reliable annotations for supervised training and evaluation of machine learning algorithms in this relevant domain. Furthermore, we provide an evaluation of two state-of-the-art baseline systems {---} BioBert and flair {---} on the ProGene corpus. We make the evaluation datasets and the trained models available to encourage comparable evaluations of new methods in the future.",
45
+ language = "English",
46
+ ISBN = "979-10-95546-34-4",
47
+ }
48
+ """
49
+
50
+ _DATASETNAME = "progene"
51
+ _DISPLAYNAME = "ProGene"
52
+
53
+ _DESCRIPTION = """\
54
+ The Protein/Gene corpus was developed at the JULIE Lab Jena under supervision of Prof. Udo Hahn.
55
+ The executing scientist was Dr. Joachim Wermter.
56
+ The main annotator was Dr. Rico Pusch who is an expert in biology.
57
+ The corpus was developed in the context of the StemNet project (http://www.stemnet.de/).
58
+ """
59
+
60
+ _HOMEPAGE = "https://zenodo.org/record/3698568#.YlVHqdNBxeg"
61
+
62
+ _LICENSE = 'Creative Commons Attribution 4.0 International'
63
+
64
+ # using custom url: original distribution includes trained models (>25GB) and original dataset license allow for redistribution
65
+ _URLS = "https://huggingface.co/datasets/bigscience-biomedical/progene/resolve/main/crossvalidation_data.zip"
66
+
67
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
68
+
69
+ _SOURCE_VERSION = "1.1.0"
70
+
71
+ _BIGBIO_VERSION = "1.0.0"
72
+
73
+
74
+ class ProgeneDataset(datasets.GeneratorBasedBuilder):
75
+ """ProgeneDataset"""
76
+
77
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
78
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
79
+
80
+ BUILDER_CONFIGS = [
81
+ BigBioConfig(
82
+ name="progene_source",
83
+ version=SOURCE_VERSION,
84
+ description="PROGENE source schema",
85
+ schema="source",
86
+ subset_id="progene",
87
+ ),
88
+ BigBioConfig(
89
+ name="progene_bigbio_kb",
90
+ version=BIGBIO_VERSION,
91
+ description="PROGENE BigBio schema",
92
+ schema="bigbio_kb",
93
+ subset_id="progene",
94
+ ),
95
+ ]
96
+
97
+ DEFAULT_CONFIG_NAME = "progene_source"
98
+
99
+ def _info(self) -> datasets.DatasetInfo:
100
+
101
+ if self.config.schema == "source":
102
+ # This follows something similar to CONLL dataset that is in the IOB Format as well
103
+ features = datasets.Features(
104
+ {
105
+ "id": datasets.Value("string"),
106
+ "tokens": datasets.Sequence(datasets.Value("string")),
107
+ "tags": datasets.Sequence(datasets.Value("string")),
108
+ }
109
+ )
110
+
111
+ elif self.config.schema == "bigbio_kb":
112
+ features = kb_features
113
+ else:
114
+ raise ValueError(
115
+ "config schema is one of source or bigbio_kb for Progene Dataset"
116
+ )
117
+
118
+ return datasets.DatasetInfo(
119
+ description=_DESCRIPTION,
120
+ features=features,
121
+ homepage=_HOMEPAGE,
122
+ license=str(_LICENSE),
123
+ citation=_CITATION,
124
+ )
125
+
126
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
127
+ """Returns SplitGenerators."""
128
+ urls = _URLS
129
+ dl_dir = dl_manager.download_and_extract(urls)
130
+ dataset_dir = os.path.join(dl_dir, "crossvalidation_data")
131
+ dataset_dir = pathlib.Path(dataset_dir)
132
+ splits = []
133
+ for split_num in range(0, 10):
134
+ for file in dataset_dir.joinpath(f"flairSplit{split_num}").iterdir():
135
+ if file.name == "train.txt":
136
+ split_id = f"split_{split_num}_{datasets.Split.TRAIN}"
137
+ elif file.name == "dev.txt":
138
+ split_id = f"split_{split_num}_{datasets.Split.VALIDATION}"
139
+ else:
140
+ split_id = f"split_{split_num}_{datasets.Split.TEST}"
141
+
142
+ splits.append(
143
+ datasets.SplitGenerator(
144
+ name=split_id,
145
+ gen_kwargs={"filepath": file, "split_id": split_id},
146
+ )
147
+ )
148
+
149
+ return splits
150
+
151
+ def _generate_examples(self, filepath, split_id: str) -> Tuple[int, Dict]:
152
+ """Yields examples as (key, example) tuples."""
153
+
154
+ with open(filepath, "r") as fp:
155
+ guid = 0
156
+ tokens = []
157
+ ner_tags = []
158
+ entity_ids = 0
159
+ for line in fp:
160
+ if line == "" or line == "\n":
161
+ if tokens:
162
+ entities = self.iob_tags_to_entities(tokens, ner_tags)
163
+ entity_dicts = []
164
+
165
+ for entity in entities:
166
+ entity_text = [str(entity[0])]
167
+ entity_offset = [entity[1]]
168
+ entity_dict = {
169
+ "id": f"{split_id}_{entity_ids}_entity",
170
+ "type": "progene_text",
171
+ "text": entity_text,
172
+ "offsets": entity_offset,
173
+ "normalized": [],
174
+ }
175
+ entity_ids += 1
176
+ entity_dicts.append(entity_dict)
177
+
178
+ if self.config.schema == "source":
179
+ yield f"{split_id}_{guid}", {
180
+ "id": f"{split_id}_{guid}",
181
+ "tokens": tokens,
182
+ "tags": ner_tags,
183
+ }
184
+ elif self.config.schema == "bigbio_kb":
185
+ yield f"{split_id}_{guid}", {
186
+ "id": f"{split_id}_{guid}",
187
+ "document_id": f"{split_id}_{guid}",
188
+ "passages": [
189
+ {
190
+ "id": f"{split_id}_{guid}_passage",
191
+ "type": "progene_text",
192
+ "text": [" ".join(tokens)],
193
+ "offsets": [[0, len(" ".join(tokens))]],
194
+ }
195
+ ],
196
+ "entities": entity_dicts,
197
+ "events": [],
198
+ "coreferences": [],
199
+ "relations": [],
200
+ }
201
+ guid += 1
202
+ tokens = []
203
+ ner_tags = []
204
+ else:
205
+ text_tags = line.split("\t")
206
+ token = text_tags[0].strip()
207
+ ner_tag = text_tags[1].strip()
208
+ tokens.append(token)
209
+ ner_tags.append(ner_tag)
210
+
211
+ # residual tokens and tags at the end of the file
212
+ entities = self.iob_tags_to_entities(tokens, ner_tags)
213
+ entity_dicts = []
214
+ for entity in entities:
215
+ entity_text = [str(entity[0])]
216
+ entity_offset = [entity[1]]
217
+ entity_dict = {
218
+ "id": f"{split_id}_{entity_ids}_entity",
219
+ "type": "progene_text",
220
+ "text": entity_text,
221
+ "offsets": entity_offset,
222
+ "normalized": [],
223
+ }
224
+ entity_ids += 1
225
+ entity_dicts.append(entity_dict)
226
+
227
+ if self.config.schema == "source":
228
+ yield f"{split_id}_{guid}", {
229
+ "id": f"{split_id}_{guid}",
230
+ "tokens": tokens,
231
+ "tags": ner_tags,
232
+ }
233
+ elif self.config.schema == "bigbio_kb":
234
+ yield f"{split_id}_{guid}", {
235
+ "id": f"{split_id}_{guid}",
236
+ "document_id": f"{split_id}_{guid}",
237
+ "passages": [
238
+ {
239
+ "id": f"{split_id}_{guid}_passage",
240
+ "type": "progene_text",
241
+ "text": [" ".join(tokens)],
242
+ "offsets": [[0, len(" ".join(tokens))]],
243
+ }
244
+ ],
245
+ "entities": entity_dicts,
246
+ "events": [],
247
+ "coreferences": [],
248
+ "relations": [],
249
+ }
250
+
251
+ def iob_to_biluo(self, tags: Iterable[str]) -> List[str]:
252
+ """Converts IOB tags to BILUO tags. This is taken from spacy.training.iob_utils"""
253
+ out: List[str] = []
254
+ tags = list(tags)
255
+ while tags:
256
+ out.extend(self._consume_os(tags))
257
+ out.extend(self._consume_ent(tags))
258
+ return out
259
+
260
+ def _consume_os(self, tags: List[str]) -> Iterator[str]:
261
+ while tags and tags[0] == "O":
262
+ yield tags.pop(0)
263
+
264
+ def _consume_ent(self, tags: List[str]) -> List[str]:
265
+ if not tags:
266
+ return []
267
+ tag = tags.pop(0)
268
+ target_in = "I" + tag[1:]
269
+ target_last = "L" + tag[1:]
270
+ length = 1
271
+ while tags and tags[0] in {target_in, target_last}:
272
+ length += 1
273
+ tags.pop(0)
274
+ label = tag[2:]
275
+ if length == 1:
276
+ if len(label) == 0:
277
+ raise ValueError("Error parsing iob")
278
+ return ["U-" + label]
279
+ else:
280
+ start = "B-" + label
281
+ end = "L-" + label
282
+ middle = [f"I-{label}" for _ in range(1, length - 1)]
283
+ return [start] + middle + [end]
284
+
285
+ def tags_to_entities(self, tags: Iterable[str]) -> List[Tuple[str, int, int]]:
286
+ """This has been taken from spacy.training.iob_utils
287
+ Note that the end index returned by this function is inclusive.
288
+ To use it for Span creation, increment the end by 1."""
289
+ entities = []
290
+ start = None
291
+ for i, tag in enumerate(tags):
292
+ if tag is None or tag.startswith("-"):
293
+ # TODO: We shouldn't be getting these malformed inputs. Fix this.
294
+ if start is not None:
295
+ start = None
296
+ else:
297
+ entities.append(("", i, i))
298
+ elif tag.startswith("O"):
299
+ pass
300
+ elif tag.startswith("I"):
301
+ if start is None:
302
+ raise ValueError("Error converting tags to entities")
303
+ elif tag.startswith("U"):
304
+ entities.append((tag[2:], i, i))
305
+ elif tag.startswith("B"):
306
+ start = i
307
+ elif tag.startswith("L"):
308
+ if start is None:
309
+ raise ValueError("Error converting tags to entities")
310
+ entities.append((tag[2:], start, i))
311
+ start = None
312
+ else:
313
+ raise ValueError("Error converting tags to entities")
314
+ return entities
315
+
316
+ def iob_tags_to_entities(self, text: List[str], tags: List[str]):
317
+ """Converts IOB Tags to a set of entities
318
+ text: List[str] - A list of tokens
319
+ tags: List[str] - A list of corresponding tags
320
+ """
321
+
322
+ assert len(text) == len(tags)
323
+
324
+ biluo_tags = self.iob_to_biluo(tags)
325
+ entity_offsets = self.tags_to_entities(biluo_tags)
326
+ spans = self.get_span_offsets(" ".join(text))
327
+ entities = []
328
+ text_string = " ".join(text)
329
+ for entity, start_word, end_word in entity_offsets:
330
+ start_char = spans[start_word][0]
331
+ end_char = (
332
+ spans[end_word][1] - 1
333
+ ) # The offsets include the space in the text
334
+ entity_text = text_string[start_char:end_char]
335
+ entity_offsets = [start_char, end_char]
336
+ entities.append((entity_text, entity_offsets))
337
+
338
+ return entities
339
+
340
+ def get_span_offsets(self, text):
341
+ """Returns the character offsets for every word in the text.
342
+ We assume that every word ends in a space for this function
343
+ """
344
+ words = text.split()
345
+ len_words = list(map(lambda word: len(word) + 1, words))
346
+ offsets = [0] + len_words
347
+ offsets = itertools.accumulate(offsets)
348
+ offsets = list(offsets)
349
+ offsets = list(zip(offsets, offsets[1:]))
350
+ return offsets
351
+
352
+
353
+ if __name__ == "__main__":
354
+ datasets.load_dataset(__file__, name="progene_bigbio_kb")