File size: 12,350 Bytes
bbbdde0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os
from typing import List

import datasets
import xml.etree.ElementTree as ET
import uuid
import html

from .bigbiohub import kb_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks

_LANGUAGES = ['English']
_PUBMED = True
_LOCAL = False
_CITATION = """\
@article{Wei2015,
  title        = {
    {GNormPlus}: An Integrative Approach for Tagging Genes,  Gene Families,
    and Protein Domains
  },
  author       = {Chih-Hsuan Wei and Hung-Yu Kao and Zhiyong Lu},
  year         = 2015,
  journal      = {{BioMed} Research International},
  publisher    = {Hindawi Limited},
  volume       = 2015,
  pages        = {1--7},
  doi          = {10.1155/2015/918710},
  url          = {https://doi.org/10.1155/2015/918710}
}
"""

_DATASETNAME = "citation_gia_test_collection"
_DISPLAYNAME = "Citation GIA Test Collection"

_DESCRIPTION = """\
The Citation GIA Test Collection was recently created for gene indexing at the
NLM and includes 151 PubMed abstracts with both mention-level and document-level
annotations. They are selected because both have a focus on human genes.
"""

_HOMEPAGE = "https://www.ncbi.nlm.nih.gov/research/bionlp/Tools/gnormplus/"

_LICENSE = 'License information unavailable'

_URLS = {
    _DATASETNAME: [
        "https://www.ncbi.nlm.nih.gov/CBBresearch/Lu/Demo/tmTools/download/GNormPlus/GNormPlusCorpus.zip"
    ]
}

_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.NAMED_ENTITY_DISAMBIGUATION]

_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"


class CitationGIATestCollection(datasets.GeneratorBasedBuilder):
    """
    The Citation GIA Test Collection was recently created for gene indexing at the
    NLM and includes 151 PubMed abstracts with both mention-level and document-level
    annotations. They are selected because both have a focus on human genes.
    """

    SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
    BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)

    BUILDER_CONFIGS = [
        BigBioConfig(
            name="citation_gia_test_collection_source",
            version=SOURCE_VERSION,
            description="citation_gia_test_collection source schema",
            schema="source",
            subset_id="citation_gia_test_collection",
        ),
        BigBioConfig(
            name="citation_gia_test_collection_bigbio_kb",
            version=BIGBIO_VERSION,
            description="citation_gia_test_collection BigBio schema",
            schema="bigbio_kb",
            subset_id="citation_gia_test_collection",
        ),
    ]

    DEFAULT_CONFIG_NAME = "citation_gia_test_collection_source"

    def _info(self) -> datasets.DatasetInfo:

        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "passages": [
                        {
                            "id": datasets.Value("string"),
                            "type": datasets.Value("string"),
                            "text": datasets.Sequence(datasets.Value("string")),
                            "offsets": datasets.Sequence([datasets.Value("int32")]),
                        }
                    ],
                    "entities": [
                        {
                            "id": datasets.Value("string"),
                            "type": datasets.Value("string"),
                            "text": datasets.Sequence(datasets.Value("string")),
                            "offsets": datasets.Sequence([datasets.Value("int32")]),
                            "normalized": [
                                {
                                    "db_name": datasets.Value("string"),
                                    "db_id": datasets.Value("string"),
                                }
                            ],
                        }
                    ],
                }
            )

        elif self.config.schema == "bigbio_kb":
            features = kb_features

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=str(_LICENSE),
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:

        urls = _URLS[_DATASETNAME]
        data_dir = dl_manager.download_and_extract(urls)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepath": os.path.join(
                        data_dir[0], "GNormPlusCorpus/NLMIAT.BioC.xml"
                    ),
                    "split": "NLMIAT",
                },
            ),
        ]

    def _get_entities(self, annot_d: dict) -> dict:
        """'
        Converts annotation dict to entity dict.
        """
        ent = {
            "id": str(uuid.uuid4()),
            "type": annot_d["type"],
            "text": [annot_d["text"]],
            "offsets": [annot_d["offsets"]],
            "normalized": [
                {
                    "db_name": "NCBI Gene" if annot_d["type"].isdigit() else "",
                    "db_id": annot_d["type"] if annot_d["type"].isdigit() else "",
                }
            ],
        }

        return ent

    def _get_offsets_entities(
        child, parent_text: str, child_text: str, offset: int
    ) -> List[int]:
        """
        Extracts child text offsets from parent text for entities.
        Some offsets that were present in the datset were wrong mainly because of string encodings.
        Also a little fraction of parent strings doesn't contain its respective child strings.
        Hence few assertion errors in the entitity offsets checking test.
        """
        if child_text in parent_text:
            index = parent_text.index(child_text)
            start = index + offset

        else:
            start = offset
        end = start + len(child_text)

        return [start, end]

    def _process_annot(self, annot: ET.Element, passages: dict) -> dict:
        """'
        Converts annotation XML Element to Python dict.
        """
        parent_text = " ".join([p["text"] for p in passages.values()])
        annot_d = dict()
        a_d = {a.tag: a.text for a in annot}

        for a in list(annot):

            if a.tag == "location":
                offset = int(a.attrib["offset"])
                annot_d["offsets"] = self._get_offsets_entities(
                    html.escape(parent_text[offset:]), html.escape(a_d["text"]), offset
                )

            elif a.tag != "infon":
                annot_d[a.tag] = html.escape(a.text)

            else:
                annot_d[a.attrib["key"]] = html.escape(a.text)

        return annot_d

    def _parse_elem(self, elem: ET.Element) -> dict:
        """'
        Converts document XML Element to Python dict.
        """
        elem_d = dict()
        passages = dict()
        annotations = elem.findall(".//annotation")
        elem_d["entities"] = []

        for child in elem:
            elem_d[child.tag] = []

        for child in elem:
            if child.tag == "passage":
                elem_d[child.tag].append(
                    {
                        c.tag: html.escape(
                            " ".join(
                                list(
                                    filter(
                                        lambda item: item,
                                        [t.strip("\n") for t in c.itertext()],
                                    )
                                )
                            )
                        )
                        for c in child
                    }
                )

            elif child.tag == "id":
                elem_d[child.tag] = html.escape(child.text)

        for passage in elem_d["passage"]:
            infon = passage["infon"]
            passage.pop("infon", None)
            passages[infon] = passage

        elem_d["passages"] = passages
        elem_d.pop("passage", None)

        for a in annotations:
            elem_d["entities"].append(self._process_annot(a, elem_d["passages"]))

        return elem_d

    def _generate_examples(self, filepath, split):

        root = ET.parse(filepath).getroot()

        if self.config.schema == "source":
            uid = 0
            for elem in root.findall("document"):
                row = self._parse_elem(elem)
                uid += 1
                passages = row["passages"]
                yield uid, {
                    "id": str(uid),
                    "passages": [
                        {
                            "id": str(uuid.uuid4()),
                            "type": "title",
                            "text": [passages["title"]["text"]],
                            "offsets": [
                                [
                                    int(passages["title"]["offset"]),
                                    int(passages["title"]["offset"])
                                    + len(passages["title"]["text"]),
                                ]
                            ],
                        },
                        {
                            "id": str(uuid.uuid4()),
                            "type": "abstract",
                            "text": [passages["abstract"]["text"]],
                            "offsets": [
                                [
                                    int(passages["abstract"]["offset"]),
                                    int(passages["abstract"]["offset"])
                                    + len(passages["abstract"]["text"]),
                                ]
                            ],
                        },
                    ],
                    "entities": [self._get_entities(a) for a in row["entities"]],
                }

        elif self.config.schema == "bigbio_kb":
            uid = 0
            for elem in root.findall("document"):
                row = self._parse_elem(elem)
                uid += 1
                passages = row["passages"]
                yield uid, {
                    "id": str(uid),
                    "document_id": str(uuid.uuid4()),
                    "passages": [
                        {
                            "id": str(uuid.uuid4()),
                            "type": "title",
                            "text": [passages["title"]["text"]],
                            "offsets": [
                                [
                                    int(passages["title"]["offset"]),
                                    int(passages["title"]["offset"])
                                    + len(passages["title"]["text"]),
                                ]
                            ],
                        },
                        {
                            "id": str(uuid.uuid4()),
                            "type": "abstract",
                            "text": [passages["abstract"]["text"]],
                            "offsets": [
                                [
                                    int(passages["abstract"]["offset"]),
                                    int(passages["abstract"]["offset"])
                                    + len(passages["abstract"]["text"]),
                                ]
                            ],
                        },
                    ],
                    "entities": [self._get_entities(a) for a in row["entities"]],
                    "relations": [],
                    "events": [],
                    "coreferences": [],
                }