Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
File size: 11,245 Bytes
e188596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a0d6b8
c2f6702
1a0d6b8
e188596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a0d6b8
e188596
 
 
 
 
 
 
 
 
 
1a0d6b8
c2f6702
e188596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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.
"""
AnEM corpus is a domain- and species-independent resource manually annotated for anatomical
entity mentions using a fine-grained classification system. The corpus consists of 500 documents
(over 90,000 words) selected randomly from citation abstracts and full-text papers with
the aim of making the corpus representative of the entire available biomedical scientific
literature. The corpus annotation covers mentions of both healthy and pathological anatomical
entities and contains over 3,000 annotated mentions.
"""

from pathlib import Path
from typing import Dict, List, Tuple

import datasets

from .bigbiohub import kb_features
from .bigbiohub import BigBioConfig
from .bigbiohub import Tasks
from .bigbiohub import parse_brat_file
from .bigbiohub import brat_parse_to_bigbio_kb


_LANGUAGES = ['English']
_PUBMED = True
_LOCAL = False
_CITATION = """\
@inproceedings{ohta-etal-2012-open,
  author    = {Ohta, Tomoko and Pyysalo, Sampo and Tsujii, Jun{'}ichi and Ananiadou, Sophia},
  title     = {Open-domain Anatomical Entity Mention Detection},
  journal   = {},
  volume    = {W12-43},
  year      = {2012},
  url       = {https://aclanthology.org/W12-4304},
  doi       = {},
  biburl    = {},
  bibsource = {},
  publisher = {Association for Computational Linguistics}
}
"""

_DATASETNAME = "an_em"
_DISPLAYNAME = "AnEM"

_DESCRIPTION = """\
AnEM corpus is a domain- and species-independent resource manually annotated for anatomical
entity mentions using a fine-grained classification system. The corpus consists of 500 documents
(over 90,000 words) selected randomly from citation abstracts and full-text papers with
the aim of making the corpus representative of the entire available biomedical scientific
literature. The corpus annotation covers mentions of both healthy and pathological anatomical
entities and contains over 3,000 annotated mentions.
"""


_HOMEPAGE = "http://www.nactem.ac.uk/anatomy/"

_LICENSE = 'Creative Commons Attribution Share Alike 3.0 Unported'

_URLS = {
    _DATASETNAME: "http://www.nactem.ac.uk/anatomy/data/AnEM-1.0.4.tar.gz",
}

_SUPPORTED_TASKS = [
    Tasks.NAMED_ENTITY_RECOGNITION,
    Tasks.COREFERENCE_RESOLUTION,
    Tasks.RELATION_EXTRACTION,
]

_SOURCE_VERSION = "1.0.4"
_BIGBIO_VERSION = "1.0.0"


class AnEMDataset(datasets.GeneratorBasedBuilder):
    """Anatomical Entity Mention (AnEM) corpus"""

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

    BUILDER_CONFIGS = [
        BigBioConfig(
            name="an_em_source",
            version=SOURCE_VERSION,
            description="AnEM source schema",
            schema="source",
            subset_id="an_em",
        ),
        BigBioConfig(
            name="an_em_bigbio_kb",
            version=BIGBIO_VERSION,
            description="AnEM BigBio schema",
            schema="bigbio_kb",
            subset_id="an_em",
        ),
    ]

    DEFAULT_CONFIG_NAME = "an_em_source"

    def _info(self) -> datasets.DatasetInfo:
        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "document_id": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "document_type": datasets.Value("string"),
                    "text_type": datasets.Value("string"),
                    "entities": [
                        {
                            "offsets": datasets.Sequence([datasets.Value("int32")]),
                            "text": datasets.Value("string"),
                            "type": datasets.Value("string"),
                            "entity_id": datasets.Value("string"),
                        }
                    ],
                    "equivalences": [
                        {
                            "entity_id": datasets.Value("string"),
                            "ref_ids": datasets.Sequence(datasets.Value("string")),
                        }
                    ],
                    "relations": [
                        {
                            "id": datasets.Value("string"),
                            "head": {
                                "ref_id": datasets.Value("string"),
                                "role": datasets.Value("string"),
                            },
                            "tail": {
                                "ref_id": datasets.Value("string"),
                                "role": datasets.Value("string"),
                            },
                            "type": 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]:
        """Returns SplitGenerators."""
        urls = _URLS[_DATASETNAME]
        data_dir = Path(dl_manager.download_and_extract(urls))
        all_data = data_dir / "AnEM-1.0.4" / "standoff"

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": all_data,
                    "split_path": data_dir
                    / "AnEM-1.0.4"
                    / "development"
                    / "train-files.list",
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepath": all_data,
                    "split_path": data_dir / "AnEM-1.0.4" / "test" / "test-files.list",
                    "split": "test",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "filepath": all_data,
                    "split_path": data_dir
                    / "AnEM-1.0.4"
                    / "development"
                    / "test-files.list",
                    "split": "dev",
                },
            ),
        ]

    def _generate_examples(self, filepath, split_path, split: str) -> Tuple[int, Dict]:
        """Yields examples as (key, example) tuples."""

        with open(split_path, "r") as sp:
            split_list = [line.rstrip() for line in sp]

        if self.config.schema == "source":
            for file in filepath.iterdir():

                # Use brat text files and consider files in the provided split list
                if (file.suffix != ".txt") or (file.stem not in split_list):
                    continue
                brat_parsed = parse_brat_file(file)
                source_example = self._brat_to_source(file, brat_parsed)

                yield source_example["document_id"], source_example

        elif self.config.schema == "bigbio_kb":
            for file in filepath.iterdir():

                # Use brat text files and consider files in the provided split list
                if (file.suffix != ".txt") or (file.stem not in split_list):
                    continue
                brat_parsed = parse_brat_file(file)
                bigbio_kb_example = brat_parse_to_bigbio_kb(brat_parsed)

                bigbio_kb_example["id"] = bigbio_kb_example["document_id"]

                doc_type, text_type = self.get_document_type_and_text_type(file)
                bigbio_kb_example["passages"][0]["type"] = text_type

                yield bigbio_kb_example["id"], bigbio_kb_example

    def _brat_to_source(self, filepath, brat_example):
        """
        Converts parsed brat example to source schema example
        """
        document_type, text_type = self.get_document_type_and_text_type(filepath)

        source_example = {
            "document_id": brat_example["document_id"],
            "text": brat_example["text"],
            "document_type": document_type,
            "text_type": text_type,
            "entities": [
                {
                    "offsets": brat_entity["offsets"],
                    "text": brat_entity["text"],
                    "type": brat_entity["type"],
                    "entity_id": f"{brat_example['document_id']}_{brat_entity['id']}",
                }
                for brat_entity in brat_example["text_bound_annotations"]
            ],
            "equivalences": [
                {
                    "entity_id": brat_entity["id"],
                    "ref_ids": [
                        f"{brat_example['document_id']}_{ids}"
                        for ids in brat_entity["ref_ids"]
                    ],
                }
                for brat_entity in brat_example["equivalences"]
            ],
            "relations": [
                {
                    "id": f"{brat_example['document_id']}_{brat_entity['id']}",
                    "head": {
                        "ref_id": f"{brat_example['document_id']}_{brat_entity['head']['ref_id']}",
                        "role": brat_entity["head"]["role"],
                    },
                    "tail": {
                        "ref_id": f"{brat_example['document_id']}_{brat_entity['tail']['ref_id']}",
                        "role": brat_entity["tail"]["role"],
                    },
                    "type": brat_entity["type"],
                }
                for brat_entity in brat_example["relations"]
            ],
        }

        return source_example

    def get_document_type_and_text_type(self, input_file: Path) -> Tuple[str, str]:
        """
        Implementation used from
        https://github.com/bigscience-workshop/biomedical/blob/master/biodatasets/anat_em/anat_em.py

        Extracts the document type (PubMed(PM) or PubMedCentral (PMC)) and the respective
        text type (abstract for PM and sec or caption for (PMC) from the name of the given
        file, e.g.:

        PMID-9778569.txt -> ("PM", "abstract")

        PMC-1274342-sec-02.txt -> ("PMC", "sec")

        PMC-1592597-caption-02.ann -> ("PMC", "caption")

        """
        name_parts = str(input_file.stem).split("-")

        if name_parts[0] == "PMID":
            return "PM", "abstract"

        elif name_parts[0] == "PMC":
            return "PMC", name_parts[2]
        else:
            raise AssertionError(f"Unexpected file prefix {name_parts[0]}")