Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
gabrielaltay commited on
Commit
949eaa3
1 Parent(s): 0038745

upload hubscripts/genia_term_corpus_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. genia_term_corpus.py +313 -0
genia_term_corpus.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ The identification of linguistic expressions referring to entities of interest in molecular biology such as proteins,
18
+ genes and cells is a fundamental task in biomolecular text mining. The GENIA technical term annotation covers the
19
+ identification of physical biological entities as well as other important terms. The corpus annotation covers the full
20
+ 1,999 abstracts of the primary GENIA corpus.
21
+ """
22
+
23
+ import xml.etree.ElementTree as ET
24
+ from itertools import count
25
+ from typing import Dict, List, Tuple
26
+
27
+ import datasets
28
+
29
+ from .bigbiohub import kb_features
30
+ from .bigbiohub import BigBioConfig
31
+ from .bigbiohub import Tasks
32
+
33
+ _LANGUAGES = ['English']
34
+ _PUBMED = True
35
+ _LOCAL = False
36
+ _CITATION = """\
37
+ @inproceedings{10.5555/1289189.1289260,
38
+ author = {Ohta, Tomoko and Tateisi, Yuka and Kim, Jin-Dong},
39
+ title = {The GENIA Corpus: An Annotated Research Abstract Corpus in Molecular Biology Domain},
40
+ year = {2002},
41
+ publisher = {Morgan Kaufmann Publishers Inc.},
42
+ address = {San Francisco, CA, USA},
43
+ booktitle = {Proceedings of the Second International Conference on Human Language Technology Research},
44
+ pages = {82–86},
45
+ numpages = {5},
46
+ location = {San Diego, California},
47
+ series = {HLT '02}
48
+ }
49
+
50
+ @article{Kim2003GENIAC,
51
+ title={GENIA corpus - a semantically annotated corpus for bio-textmining},
52
+ author={Jin-Dong Kim and Tomoko Ohta and Yuka Tateisi and Junichi Tsujii},
53
+ journal={Bioinformatics},
54
+ year={2003},
55
+ volume={19 Suppl 1},
56
+ pages={
57
+ i180-2
58
+ }
59
+ }
60
+
61
+ @inproceedings{10.5555/1567594.1567610,
62
+ author = {Kim, Jin-Dong and Ohta, Tomoko and Tsuruoka, Yoshimasa and Tateisi, Yuka and Collier, Nigel},
63
+ title = {Introduction to the Bio-Entity Recognition Task at JNLPBA},
64
+ year = {2004},
65
+ publisher = {Association for Computational Linguistics},
66
+ address = {USA},
67
+ booktitle = {Proceedings of the International Joint Workshop on Natural Language Processing in Biomedicine and Its
68
+ Applications},
69
+ pages = {70–75},
70
+ numpages = {6},
71
+ location = {Geneva, Switzerland},
72
+ series = {JNLPBA '04}
73
+ }
74
+ """
75
+
76
+ _DATASETNAME = "genia_term_corpus"
77
+ _DISPLAYNAME = "GENIA Term Corpus"
78
+
79
+ _DESCRIPTION = """\
80
+ The identification of linguistic expressions referring to entities of interest in molecular biology such as proteins,
81
+ genes and cells is a fundamental task in biomolecular text mining. The GENIA technical term annotation covers the
82
+ identification of physical biological entities as well as other important terms. The corpus annotation covers the full
83
+ 1,999 abstracts of the primary GENIA corpus.
84
+ """
85
+
86
+ _HOMEPAGE = "http://www.geniaproject.org/genia-corpus/term-corpus"
87
+
88
+ _LICENSE = 'GENIA Project License for Annotated Corpora'
89
+
90
+ _URLS = {
91
+ _DATASETNAME: "http://www.nactem.ac.uk/GENIA/current/GENIA-corpus/Term/GENIAcorpus3.02.tgz",
92
+ }
93
+
94
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
95
+
96
+ _SOURCE_VERSION = "3.0.2"
97
+
98
+ _BIGBIO_VERSION = "1.0.0"
99
+
100
+
101
+ class GeniaTermCorpusDataset(datasets.GeneratorBasedBuilder):
102
+ """TODO: Short description of my dataset."""
103
+
104
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
105
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
106
+
107
+ BUILDER_CONFIGS = [
108
+ BigBioConfig(
109
+ name="genia_term_corpus_source",
110
+ version=SOURCE_VERSION,
111
+ description="genia_term_corpus source schema",
112
+ schema="source",
113
+ subset_id="genia_term_corpus",
114
+ ),
115
+ BigBioConfig(
116
+ name="genia_term_corpus_bigbio_kb",
117
+ version=BIGBIO_VERSION,
118
+ description="genia_term_corpus BigBio schema",
119
+ schema="bigbio_kb",
120
+ subset_id="genia_term_corpus",
121
+ ),
122
+ ]
123
+
124
+ DEFAULT_CONFIG_NAME = "genia_term_corpus_source"
125
+
126
+ def _info(self) -> datasets.DatasetInfo:
127
+ if self.config.schema == "source":
128
+ features = datasets.Features(
129
+ {
130
+ "document_id": datasets.Value("string"),
131
+ "title": [
132
+ {
133
+ "text": datasets.Value("string"),
134
+ "entities": [
135
+ {
136
+ "text": datasets.Value("string"),
137
+ "lex": datasets.Value("string"),
138
+ "sem": datasets.Value("string"),
139
+ }
140
+ ],
141
+ }
142
+ ],
143
+ "abstract": [
144
+ {
145
+ "text": datasets.Value("string"),
146
+ "entities": [
147
+ {
148
+ "text": datasets.Value("string"),
149
+ "lex": datasets.Value("string"),
150
+ "sem": datasets.Value("string"),
151
+ }
152
+ ],
153
+ }
154
+ ],
155
+ }
156
+ )
157
+
158
+ elif self.config.schema == "bigbio_kb":
159
+ features = kb_features
160
+
161
+ return datasets.DatasetInfo(
162
+ description=_DESCRIPTION,
163
+ features=features,
164
+ homepage=_HOMEPAGE,
165
+ license=str(_LICENSE),
166
+ citation=_CITATION,
167
+ )
168
+
169
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
170
+ """Returns SplitGenerators."""
171
+ urls = _URLS[_DATASETNAME]
172
+ data_dir = dl_manager.download(urls)
173
+ return [
174
+ datasets.SplitGenerator(
175
+ name=datasets.Split.TRAIN,
176
+ gen_kwargs={
177
+ "archive": dl_manager.iter_archive(data_dir),
178
+ "data_path": "GENIA_term_3.02/GENIAcorpus3.02.xml",
179
+ },
180
+ ),
181
+ ]
182
+
183
+ def _generate_examples(self, archive, data_path) -> Tuple[int, Dict]:
184
+ """Yields examples as (key, example) tuples."""
185
+ uid = count(0)
186
+ for path, file in archive:
187
+ if path == data_path:
188
+ for key, example in enumerate(iterparse_genia(file)):
189
+ if self.config.schema == "source":
190
+ yield key, example
191
+
192
+ elif self.config.schema == "bigbio_kb":
193
+ yield key, parse_genia_to_bigbio(example, uid)
194
+
195
+
196
+ def iterparse_genia(file):
197
+ # ontology = None
198
+ for _, element in ET.iterparse(file):
199
+ # if element.tag == "import":
200
+ # ontology = {"name": element.get("resource"), "prefix": element.get("prefix")}
201
+ if element.tag == "article":
202
+ bibliomisc = element.find("articleinfo/bibliomisc").text
203
+ document_id = parse_genia_bibliomisc(bibliomisc)
204
+ title = element.find("title")
205
+ title_sentences = parse_genia_sentences(title)
206
+ abstract = element.find("abstract")
207
+ abstract_sentences = parse_genia_sentences(abstract)
208
+ yield {
209
+ "document_id": document_id,
210
+ "title": title_sentences,
211
+ "abstract": abstract_sentences,
212
+ }
213
+
214
+
215
+ def parse_genia_sentences(passage):
216
+ sentences = []
217
+ for sentence in passage.iter(tag="sentence"):
218
+ text = "".join(sentence.itertext())
219
+ entities = []
220
+ for entity in sentence.iter(tag="cons"): # constituent
221
+ entity_lex = entity.get("lex", "")
222
+ entity_sem = parse_genia_sem(entity.get("sem", ""))
223
+ entity_text = "".join(entity.itertext())
224
+ entities.append({"text": entity_text, "lex": entity_lex, "sem": entity_sem})
225
+ sentences.append(
226
+ {
227
+ "text": text,
228
+ "entities": entities,
229
+ }
230
+ )
231
+ return sentences
232
+
233
+
234
+ def parse_genia_bibliomisc(bibliomisc):
235
+ """Remove 'MEDLINE:' from 'MEDLINE:96055286'."""
236
+ return bibliomisc.replace("MEDLINE:", "") if ":" in bibliomisc else bibliomisc
237
+
238
+
239
+ def parse_genia_sem(sem):
240
+ return sem.replace("G#", "") if "G#" in sem else sem
241
+
242
+
243
+ def parse_genia_to_bigbio(example, uid):
244
+ document = {
245
+ "id": next(uid),
246
+ "document_id": example["document_id"],
247
+ "passages": list(generate_bigbio_passages(example, uid)),
248
+ "entities": list(generate_bigbio_entities(example, uid)),
249
+ "events": [],
250
+ "coreferences": [],
251
+ "relations": [],
252
+ }
253
+ return document
254
+
255
+
256
+ def parse_genia_to_bigbio_passage(passage, uid, type="", offset=0):
257
+ text = " ".join(sentence["text"] for sentence in passage)
258
+ new_offset = offset + len(text)
259
+ return {
260
+ "id": next(uid),
261
+ "type": type,
262
+ "text": [text],
263
+ "offsets": [[offset, new_offset]],
264
+ }, new_offset + 1
265
+
266
+
267
+ def generate_bigbio_passages(example, uid):
268
+ offset = 0
269
+ for type in ["title", "abstract"]:
270
+ passage, offset = parse_genia_to_bigbio_passage(
271
+ example[type], uid, type=type, offset=offset
272
+ )
273
+ yield passage
274
+
275
+
276
+ def parse_genia_to_bigbio_entity(entity, uid, text="", relative_offset=0, offset=0):
277
+ try:
278
+ relative_offset = text.index(entity["text"], relative_offset)
279
+ except ValueError:
280
+ # Skip duplicated annotations:
281
+ # <cons lex="tumour_cell" sem="G#cell_type"><cons lex="tumour_cell" sem="G#cell_type">tumour cells</cons></cons>
282
+ return None, None
283
+ new_relative_offset = relative_offset + len(entity["text"])
284
+ return {
285
+ "id": next(uid),
286
+ "offsets": [[offset + relative_offset, offset + new_relative_offset]],
287
+ "text": [entity["text"]],
288
+ "type": entity["sem"],
289
+ "normalized": [],
290
+ }, new_relative_offset
291
+
292
+
293
+ def generate_bigbio_entities(example, uid):
294
+ sentence_offset = 0
295
+ for type in ["title", "abstract"]:
296
+ for sentence in example[type]:
297
+ relative_offsets = {}
298
+ for entity in sentence["entities"]:
299
+ bigbio_entity, new_relative_offset = parse_genia_to_bigbio_entity(
300
+ entity,
301
+ uid,
302
+ text=sentence["text"],
303
+ relative_offset=relative_offsets.get(
304
+ (entity["text"], entity["lex"], entity["sem"]), 0
305
+ ),
306
+ offset=sentence_offset,
307
+ )
308
+ if bigbio_entity:
309
+ relative_offsets[
310
+ (entity["text"], entity["lex"], entity["sem"])
311
+ ] = new_relative_offset
312
+ yield bigbio_entity
313
+ sentence_offset += len(sentence["text"]) + 1