File size: 12,153 Bytes
e072fcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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 Dict, List, Tuple

import datasets
from bioc import biocxml

from .bigbiohub import BigBioConfig, Tasks, kb_features

_LOCAL = True
_CITATION = """\
@article{10.1093/jamiaopen/ooab025,
    author = {Kittner, Madeleine and Lamping, Mario and Rieke, Damian T and Götze, Julian and Bajwa, Bariya and
    Jelas, Ivan and Rüter, Gina and Hautow, Hanjo and Sänger, Mario and Habibi, Maryam and Zettwitz, Marit and
    Bortoli, Till de and Ostermann, Leonie and Ševa, Jurica and Starlinger, Johannes and Kohlbacher, Oliver and
    Malek, Nisar P and Keilholz, Ulrich and Leser, Ulf},
    title = "{Annotation and initial evaluation of a large annotated German oncological corpus}",
    journal = {JAMIA Open},
    volume = {4},
    number = {2},
    year = {2021},
    month = {04},
    issn = {2574-2531},
    doi = {10.1093/jamiaopen/ooab025},
    url = {https://doi.org/10.1093/jamiaopen/ooab025},
    note = {ooab025},
    eprint = {https://academic.oup.com/jamiaopen/article-pdf/4/2/ooab025/38830128/ooab025.pdf},
}
"""
_DESCRIPTION = """\
BRONCO150 is a corpus containing selected sentences of 150 German discharge summaries of cancer patients (hepatocelluar
carcinoma or melanoma) treated at Charite Universitaetsmedizin Berlin or Universitaetsklinikum Tuebingen. All discharge
summaries were manually anonymized. The original documents were scrambled at the sentence level to make reconstruction
of individual reports impossible.
"""
_HOMEPAGE = "https://www2.informatik.hu-berlin.de/~leser/bronco/index.html"
_LICENSE = "DUA"
_URLS = {}
_PUBMED = False
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.NAMED_ENTITY_DISAMBIGUATION]
_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"
_DATASETNAME = "bronco"
_DISPLAYNAME = "BRONCO"
_LANGUAGES = ["German"]


class Bronco(datasets.GeneratorBasedBuilder):
    SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
    BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
    DEFAULT_CONFIG_NAME = "bronco_bigbio_kb"
    BUILDER_CONFIGS = [
        BigBioConfig(
            name="bronco_source",
            version=SOURCE_VERSION,
            description="BRONCO source schema",
            schema="source",
            subset_id="bronco",
        ),
        BigBioConfig(
            name="bronco_bigbio_kb",
            version=BIGBIO_VERSION,
            description="BRONCO BigBio schema",
            schema="bigbio_kb",
            subset_id="bronco",
        ),
    ]

    def _info(self) -> datasets.DatasetInfo:
        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "passage": {
                        "offset": datasets.Value("int32"),
                        "text": datasets.Value("string"),
                        "annotation": [
                            {
                                "id": datasets.Value("string"),
                                "infon": {
                                    "file": datasets.Value("string"),
                                    "type": datasets.Value("string"),
                                },
                                "location": [
                                    {
                                        "offset": datasets.Value("int32"),
                                        "length": datasets.Value("int32"),
                                    }
                                ],
                                "text": datasets.Value("string"),
                            }
                        ],
                        "relation": [
                            {
                                "id": datasets.Value("string"),
                                "infon": {
                                    "file": datasets.Value("string"),
                                    "type": datasets.Value("string"),
                                    "norm/atr": datasets.Value("string"),
                                    "string": datasets.Value("string"),
                                },
                                "node": [
                                    {
                                        "refid": datasets.Value("string"),
                                        "role": datasets.Value("string"),
                                    }
                                ],
                            }
                        ],
                    },
                }
            )

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

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

    def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
        """Returns SplitGenerators."""
        if self.config.data_dir is None:
            raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
        else:
            data_dir = self.config.data_dir

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": os.path.join(data_dir, "bioCFiles", "BRONCO150.xml"),
                    "split": "train",
                },
            ),
        ]

    def _generate_examples(self, filepath, split: str) -> Tuple[int, Dict]:
        """Yields examples as (key, example) tuples."""
        with open(filepath, "r") as fp:
            data = biocxml.load(fp).documents

            if self.config.schema == "source":
                for uid, doc in enumerate(data):
                    out = {
                        "id": doc.id,
                        "passage": {
                            "offset": doc.passages[0].offset,
                            "text": doc.passages[0].text,
                            "annotation": [],
                            "relation": [],
                        },
                    }

                    # handle entities
                    for annotation in doc.passages[0].annotations:
                        anno = {
                            "id": annotation.id,
                            "infon": annotation.infons,
                            "text": annotation.text,
                            "location": [],
                        }
                        for location in annotation.locations:
                            anno["location"].append(
                                {
                                    "offset": location.offset,
                                    "length": location.length,
                                }
                            )
                        out["passage"]["annotation"].append(anno)

                    # handle relations
                    for relation in doc.passages[0].relations:
                        rel = {
                            "id": relation.id,
                            "node": [],
                        }

                        # relation.infons has different keys depending on the relation type
                        # these must be unified to comply with a fixed schema
                        if relation.infons["type"] == "Normalization":
                            rel["infon"] = {
                                "file": relation.infons["file"],
                                "type": relation.infons["type"],
                                "norm/atr": relation.infons["normalization type"],
                                "string": relation.infons["string"],
                            }
                        else:
                            rel["infon"] = {
                                "file": relation.infons["file"],
                                "type": relation.infons["type"],
                                "norm/atr": relation.infons["attribute type"],
                                "string": "",
                            }

                        for node in relation.nodes:
                            rel["node"].append(
                                {
                                    "refid": node.refid,
                                    "role": node.role,
                                }
                            )

                        out["passage"]["relation"].append(rel)

                    yield uid, out

            elif self.config.schema == "bigbio_kb":
                # reorder the documents so they appear in increasing order
                ordered_data = [data[2], data[4], data[0], data[3], data[1]]
                for uid, doc in enumerate(ordered_data):
                    out = {
                        "id": uid,
                        "document_id": doc.id,
                        "passages": [],
                        "entities": [],
                        "events": [],
                        "coreferences": [],
                        "relations": [],
                    }

                    # catch all normalized entities for lookup
                    norm_map = {}
                    for rel in doc.passages[0].relations:
                        if rel.infons["type"] == "Normalization":
                            norm_map[rel.nodes[0].role] = rel.nodes[0].refid

                    # handle passages - split text into sentences
                    for i, passage in enumerate(doc.passages[0].text.split("\n")):
                        # match the offsets on the text after removing \n
                        if i == 0:
                            marker = 0
                        else:
                            marker = out["passages"][-1]["offsets"][-1][-1] + 1

                        out["passages"].append(
                            {
                                "id": f"{uid}-{i}",
                                "text": [passage],
                                "type": "sentence",
                                "offsets": [[marker, marker + len(passage)]],
                            }
                        )

                    # handle entities
                    for ent in doc.passages[0].annotations:
                        offsets = []
                        text_s = []
                        for loc in ent.locations:
                            offsets.append([loc.offset, loc.offset + loc.length])
                            text_s.append(doc.passages[0].text[loc.offset: loc.offset + loc.length])

                        out["entities"].append(
                            {
                                "id": f"{uid}-{ent.id}",
                                "type": ent.infons["type"],
                                "text": text_s,
                                "offsets": offsets,
                                "normalized": [
                                    {
                                        "db_name": norm_map.get(ent.id, ":").split(":")[0],
                                        # replace faulty connectors in db_ids
                                        "db_id": norm_map.get(ent.id, ":")
                                        .split(":")[1]
                                        .replace(",", ".")
                                        .replace("+", ""),
                                    }
                                ],
                            }
                        )

                    yield uid, out