File size: 18,056 Bytes
458cdb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2020 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.
"""DiMB-RE (Diet-MicroBiome dataset for Relation Extraction) is a corpus of 165 nutrition and microbiome-related publications"""
import json
import datasets

from pathlib import Path

# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@misc{hong2024dimbreminingscientificliterature,
      title={DiMB-RE: Mining the Scientific Literature for Diet-Microbiome Associations}, 
      author={Gibong Hong and Veronica Hindle and Nadine M. Veasley and Hannah D. Holscher and Halil Kilicoglu},
      year={2024},
      eprint={2409.19581},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2409.19581}, 
}
"""

# You can copy an official description
_DESCRIPTION = """\
DiMB-RE is a corpus of 165 nutrition and microbiome-related publications, and we validate its usefulness with state-of-the-art pretrained language models. Specifically, we make the following contributions:

1. We annotated titles and abstracts of 165 publications with 15 entity types and 13 relation types that hold between them. To our knowledge, DiMB-RE is the largest and most diverse corpus focusing on this domain in terms of the number of entities and relations it contains.
2. In addition to titles and abstracts, we annotated Results sections of 30 articles (out of 165) to assess the impact of the information from full text.
3. To ground and contextualize relations, we annotated relation triggers and certainty information, which were previously included only in the biological event extraction corpora.
4. We normalized entity mentions to standard database identifiers (e.g., MeSH, CheBI, FoodOn) to allow aggregation for further study.
5. We trained and evaluated NER and RE models based on the state-of-the-art pretrained language models to establish robust baselines for this corpus.

Further details regarding this study are available in our paper: https://arxiv.org/pdf/2409.19581.pdf
"""

_HOMEPAGE = "https://github.com/ScienceNLP-Lab/DiMB-RE"

# TODO: Add the licence for the dataset here if you can find it
_LICENSE = ""

# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
    "train": "https://github.com/ScienceNLP-Lab/DiMB-RE/raw/refs/heads/master/data/DiMB-RE/ner_reduced_v6.1_trg_abs_result/train.json",
    "validation": "https://github.com/ScienceNLP-Lab/DiMB-RE/raw/refs/heads/master/data/DiMB-RE/ner_reduced_v6.1_trg_abs_result/dev.json",
    "test": "https://github.com/ScienceNLP-Lab/DiMB-RE/raw/refs/heads/master/data/DiMB-RE/ner_reduced_v6.1_trg_abs_result/test.json"
}


class DiMB_RE(datasets.GeneratorBasedBuilder):
    """DiMB-RE (Diet-MicroBiome dataset for Relation Extraction) a comprehensive corpus annotated with 15 entity
    types (e.g., Nutrient, Microorganism) and 13 relation types (e.g., INCREASES, IMPROVES) capturing
    diet-microbiome associations"""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="default", version=VERSION, description="Default configuration"),
        datasets.BuilderConfig(name="ner", version=VERSION,
                               description="Configuration for Named Entity Recognition (NER)"),
        datasets.BuilderConfig(name="re", version=VERSION,
                                 description="Configuration for Relation Extraction (RE)"),
        datasets.BuilderConfig(name="sentence_level", version=VERSION,
                                 description="Configuration for sentence-level processing"),
    ]

    DEFAULT_CONFIG_NAME = "default"

    def _info(self):
        ner = [
            {
                "start": datasets.Value("int32"),
                "end": datasets.Value("int32"),
                "type": datasets.Value("string")
            }
        ]
        triggers = [
            {
                "start": datasets.Value("int32"),
                "end": datasets.Value("int32"),
                "type": datasets.Value("string")
            }
        ]
        relations = [
            {
                "head": datasets.Value("int32"),
                "head_start": datasets.Value("int32"),
                "head_end": datasets.Value("int32"),
                "head_type": datasets.Value("string"),
                "tail": datasets.Value("int32"),
                "tail_start": datasets.Value("int32"),
                "tail_end": datasets.Value("int32"),
                "tail_type": datasets.Value("string"),
                "type": datasets.Value("string"),
                "factuality": datasets.Value("string")
            }
        ]
        triplets = [
            {
                "head_start": datasets.Value("int32"),
                "head_end": datasets.Value("int32"),
                "tail_start": datasets.Value("int32"),
                "tail_end": datasets.Value("int32"),
                "trigger_start": datasets.Value("int32"),
                "trigger_end": datasets.Value("int32"),
                "relation": datasets.Value("string")
            }
        ]
        if self.config.name == "sentence_level":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "doc_key": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "ner": ner,
                    "ner_tags": datasets.Sequence(datasets.Value("string")),
                    "triggers": triggers,
                    "relations": relations,
                    "triplets": triplets
                }
            )
        else:
            features = datasets.Features(
                {
                    "doc_key": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "sentences": [
                        {
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32")
                        }
                    ],
                    "ner": ner,
                    "ner_tags": datasets.Sequence(datasets.Value("string")),
                    "triggers": triggers,
                    "relations": relations,
                    "triplets": triplets
                }
            )
        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the configurations
            # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
            # specify them. They'll be used if as_supervised=True in builder.as_dataset.
            # supervised_keys=("sentence", "label"),
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        downloaded_files = dl_manager.download_and_extract(_URLS)

        return [datasets.SplitGenerator(name=i, gen_kwargs={"file_path": downloaded_files[str(i)]})
                for i in [datasets.Split.TRAIN, datasets.Split.VALIDATION, datasets.Split.TEST]]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, file_path):
        # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.

        with open(file_path, "r", encoding="utf-8") as f:
            for line in f:
                loaded_doc = json.loads(line)
                doc_key = loaded_doc["doc_key"]
                tokens = []
                sentences = []
                offset = 0
                for sentence in loaded_doc["sentences"]:
                    start = offset
                    end = offset + len(sentence)
                    sentences.append({"start": start, "end": end})
                    offset = end
                    tokens.extend(sentence)
                entities = []
                for sent_entities in loaded_doc["ner"]:
                    for entity in sent_entities:
                        # Each entity is a tuple (start, end, type)
                        entities.append({"start": entity[0], "end": entity[1] + 1, "type": entity[2]})
                ner_tags = process_ner(entities, tokens)
                triggers = []
                for sent_triggers in loaded_doc["triggers"]:
                    for trigger in sent_triggers:
                        # Each trigger is a tuple (start, end, type)
                        triggers.append({"start": trigger[0], "end": trigger[1] + 1, "type": trigger[2]})
                relations = []
                for sent_idx, rels in enumerate(loaded_doc["relations"]):
                    for rel in rels:
                        # Each relation (head_start, head_end, tail_start, tail_end, relation_type, factuality)
                        head_start = rel[0]
                        head_end = rel[1] + 1
                        head_idx = -1
                        tail_start = rel[2]
                        tail_end = rel[3] + 1
                        tail_idx = -1
                        for idx, entity in enumerate(entities):
                            if entity["start"] == head_start and entity["end"] == head_end:
                                head_idx = idx
                            elif entity["start"] == tail_start and entity["end"] == tail_end:
                                tail_idx = idx
                        if head_idx == -1 or tail_idx == -1:
                            print(f"Warning: Relation {rel} in document {doc_key} has invalid entity indices.")
                            continue
                        relation_type = rel[4]
                        factuality = rel[5]
                        relations.append({
                            "head": head_idx,
                            "head_start": head_start,
                            "head_end": head_end,
                            "head_type": entities[head_idx]["type"],
                            "tail": tail_idx,
                            "tail_start": tail_start,
                            "tail_end": tail_end,
                            "tail_type": entities[tail_idx]["type"],
                            "type": relation_type,
                            "factuality": factuality
                        })
                triplets = []
                for sent_triplets in loaded_doc["triplets"]:
                    for triplet in sent_triplets:
                        # Each triplet is a tuple (head_start, head_end, tail_start, tail_end, relation_type)
                        head_start = triplet[0]
                        head_end = triplet[1] + 1
                        tail_start = triplet[2]
                        tail_end = triplet[3] + 1
                        trigger_start = triplet[4]
                        trigger_end = triplet[5] + 1
                        relation_type = triplet[4]
                        triplets.append({
                            "head_start": head_start,
                            "head_end": head_end,
                            "tail_start": tail_start,
                            "tail_end": tail_end,
                            "trigger_start": trigger_start,
                            "trigger_end": trigger_end,
                            "relation": relation_type
                        })
                doc = {
                    "doc_key": doc_key,
                    "tokens": tokens,
                    "sentences": sentences,
                    "ner": entities,
                    "triggers": triggers,
                    "relations": relations,
                    "triplets": triplets,
                    "ner_tags": ner_tags
                }
                if self.config.name == "sentence_level":
                    # Convert all document-level information to sentence-level, fix spans
                    for sent_idx, sent in enumerate(sentences):
                        sentence = {
                            "id": f"{doc_key}_sent_{sent_idx}",
                            "doc_key": doc_key,
                            "tokens": doc["tokens"][sent["start"]:sent["end"]],
                            "ner": [
                                {
                                    "start": entity["start"] - sent["start"],
                                    "end": entity["end"] - sent["start"],
                                    "type": entity["type"]
                                } for entity in entities
                                if entity["start"] >= sent["start"] and entity["end"] <= sent["end"]
                            ],
                            "ner_tags": ner_tags[sent["start"]:sent["end"]],
                            "triggers": [
                                {
                                    "start": entity["start"] - sent["start"],
                                    "end": entity["end"] - sent["start"],
                                    "type": entity["type"]
                                } for trigger in triggers
                                if trigger["start"] >= sent["start"] and trigger["end"] <= sent["end"]
                            ],
                            "relations": [
                                {
                                    "head": rel["head"],
                                    "head_start": rel["head_start"] - sent["start"],
                                    "head_end": rel["head_end"] - sent["start"],
                                    "head_type": rel["head_type"],
                                    "tail": rel["tail"],
                                    "tail_start": rel["tail_start"] - sent["start"],
                                    "tail_end": rel["tail_end"] - sent["start"],
                                    "tail_type": rel["tail_type"],
                                    "type": rel["type"],
                                    "factuality": rel["factuality"]
                                } for rel in relations
                                if (rel["head_start"] >= sent["start"] and rel["head_end"] <= sent["end"]) and
                                   (rel["tail_start"] >= sent["start"] and rel["tail_end"] <= sent["end"])
                            ],
                            "triplets": [
                                {
                                    "head_start": triplet["head_start"] - sent["start"],
                                    "head_end": triplet["head_end"] - sent["start"],
                                    "tail_start": triplet["tail_start"] - sent["start"],
                                    "tail_end": triplet["tail_end"] - sent["start"],
                                    "trigger_start": triplet["trigger_start"] - sent["start"],
                                    "trigger_end": triplet["trigger_end"] - sent["start"],
                                    "relation": triplet["relation"]
                                } for triplet in triplets
                                if (triplet["head_start"] >= sent["start"] and triplet["head_end"] <= sent["end"]) and
                                   (triplet["tail_start"] >= sent["start"] and triplet["tail_end"] <= sent["end"])
                            ]}
                        yield sentence["id"], sentence
                else:
                    # Yields examples as (key, example) tuples
                    yield doc_key, doc


def process_ner(entities, tokens):
    """Converts entities to BIO tags for NER"""
    bio_tags = ["O"] * len(tokens)

    # Iterate through each entity to apply B- and I- tags.
    for entity in entities:
        start_index = entity["start"]
        end_index = entity["end"]
        entity_type = entity["type"]

        # Ensure the entity indices are within the bounds of the token list.
        if start_index >= len(tokens) or end_index > len(tokens):
            print(f"Warning: Entity {entity} is out of bounds. Skipping.")
            continue

        # Mark the beginning of the entity.
        if start_index < len(tokens):
            bio_tags[start_index] = f"B-{entity_type}"

        # Mark the inside of the entity for all subsequent tokens.
        for i in range(start_index + 1, end_index):
            if i < len(tokens):
                bio_tags[i] = f"I-{entity_type}"
    return bio_tags