File size: 12,781 Bytes
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75b9352
 
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75b9352
 
94b1951
 
 
 
 
75b9352
 
 
 
 
 
 
 
 
 
 
 
94b1951
 
75b9352
 
94b1951
 
75b9352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75b9352
 
94b1951
75b9352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1951
75b9352
94b1951
 
75b9352
94b1951
 
 
75b9352
 
 
 
94b1951
 
 
 
 
75b9352
 
 
 
 
94b1951
75b9352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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.
"""ScienceIE is a dataset for the SemEval task of extracting key phrases and relations between them from scientific documents"""


import glob
import datasets

from itertools import permutations
from spacy.lang.en import English

# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{DBLP:journals/corr/AugensteinDRVM17,
  author    = {Isabelle Augenstein and
               Mrinal Das and
               Sebastian Riedel and
               Lakshmi Vikraman and
               Andrew McCallum},
  title     = {SemEval 2017 Task 10: ScienceIE - Extracting Keyphrases and Relations
               from Scientific Publications},
  journal   = {CoRR},
  volume    = {abs/1704.02853},
  year      = {2017},
  url       = {http://arxiv.org/abs/1704.02853},
  eprinttype = {arXiv},
  eprint    = {1704.02853},
  timestamp = {Mon, 13 Aug 2018 16:46:36 +0200},
  biburl    = {https://dblp.org/rec/journals/corr/AugensteinDRVM17.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""

# You can copy an official description
_DESCRIPTION = """\
ScienceIE is a dataset for the SemEval task of extracting key phrases and relations between them from scientific documents.
A corpus for the task was built from ScienceDirect open access publications and was available freely for participants, without the need to sign a copyright agreement. Each data instance consists of one paragraph of text, drawn from a scientific paper.
Publications were provided in plain text, in addition to xml format, which included the full text of the publication as well as additional metadata. 500 paragraphs from journal articles evenly distributed among the domains Computer Science, Material Sciences and Physics were selected.
The training data part of the corpus consists of 350 documents, 50 for development and 100 for testing. This is similar to the pilot task described in Section 5, for which 144 articles were used for training, 40 for development and for 100 testing.

The dataset has three labels: Material, Process, Task
"""

_HOMEPAGE = "https://scienceie.github.io/resources.html"

# 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/ScienceIE/scienceie.github.io/raw/master/resources/scienceie2017_train.zip",
    "validation": "https://github.com/ScienceIE/scienceie.github.io/raw/master/resources/scienceie2017_dev.zip",
    "test": "https://github.com/ScienceIE/scienceie.github.io/raw/master/resources/semeval_articles_test.zip"
}


class ScienceIE(datasets.GeneratorBasedBuilder):
    """ScienceIE is a dataset for the task of extracting key phrases and relations between them from scientific documents"""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="ner", version=VERSION, description="NER part of ScienceIE"),
        datasets.BuilderConfig(name="re", version=VERSION, description="Relation extraction part of ScienceIE"),
    ]

    DEFAULT_CONFIG_NAME = "ner"

    def _info(self):
        if self.config.name == "re":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Value("string"),
                    "arg1_start": datasets.Value("int32"),
                    "arg1_end": datasets.Value("int32"),
                    "arg1_type": datasets.Value("string"),
                    "arg2_start": datasets.Value("int32"),
                    "arg2_end": datasets.Value("int32"),
                    "arg2_type": datasets.Value("string"),
                    "relation": datasets.features.ClassLabel(
                        names=[
                            "O",
                            "Synonym-of",
                            "Hyponym-of"
                        ]
                    )
                }
            )
        else:
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "ner_tags": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=[
                                "O",
                                "B-Process",
                                "I-Process",
                                "B-Task",
                                "I-Task",
                                "B-Material",
                                "I-Material"
                            ]
                        )
                    )
                }
            )
        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 two 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={"dir_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, dir_path):
        # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
        annotation_files = glob.glob(dir_path + "/**/*.ann", recursive=True)
        word_splitter = English()
        key = 0
        for f_anno_path in annotation_files:
            f_text_path = f_anno_path.replace(".ann", ".txt")
            with open(f_anno_path, mode="r", encoding="utf8") as f_anno, \
                    open(f_text_path, mode="r", encoding="utf8") as f_text:
                text = f_text.read()
                entities = []
                synonym_groups = []
                hyponyms = []
                for line in f_anno:
                    split_line = line.strip("\n").split("\t")
                    identifier = split_line[0]
                    annotation = split_line[1].split(" ")
                    key_type = annotation[0]
                    if key_type == "Synonym-of":
                        synonym_ids = annotation[1:]
                        synonym_groups.append(synonym_ids)
                    else:
                        if len(annotation) == 3:
                            _, start, end = annotation
                        else:
                            _, start, _, end = annotation
                        if key_type == "Hyponym-of":
                            assert start.startswith("Arg1:") and end.startswith("Arg2:")
                            hyponyms.append({
                                "id": identifier,
                                "arg1_id": start[5:],
                                "arg2_id": end[5:]
                            })
                        else:
                            # NER annotation
                            # look up span in text and print error message if it doesn't match the .ann span text
                            keyphr_text_lookup = text[int(start):int(end)]
                            keyphr_ann = split_line[2]
                            if keyphr_text_lookup != keyphr_ann:
                                print("Spans don't match for anno " + line.strip() + " in file " + f_anno_path)
                            entities.append({
                                "id": identifier,
                                "char_start": int(start),
                                "char_end": int(end),
                                "type": key_type
                            })
                doc = word_splitter(text)
                tokens = [token.text for token in doc]
                ner_tags = ["O" for _ in tokens]
                for entity in entities:
                    entity_span = doc.char_span(entity["char_start"], entity["char_end"], alignment_mode="expand")
                    entity["start"] = entity_span.start
                    entity["end"] = entity_span.end
                    ner_tags[entity["start"]] = "B-" + entity["type"]
                    for i in range(entity["start"] + 1, entity["end"]):
                        ner_tags[i] = "I-" + entity["type"]

                if self.config.name == "re":
                    entity_pairs = list(permutations([entity["id"] for entity in entities], 2))
                    relations = []

                    def add_relation(_arg1_id, _arg2_id, _relation):
                        arg1 = None
                        arg2 = None
                        for e in entities:
                            if e["id"] == _arg1_id:
                                arg1 = e
                            elif e["id"] == _arg2_id:
                                arg2 = e
                        assert arg1 is not None and arg2 is not None
                        relations.append({
                            "arg1_start": arg1["start"],
                            "arg1_end": arg1["end"],
                            "arg1_type": arg1["type"],
                            "arg2_start": arg2["start"],
                            "arg2_end": arg2["end"],
                            "arg2_type": arg2["type"],
                            "relation": _relation
                        })
                        # noinspection PyTypeChecker
                        entity_pairs.remove((_arg1_id, _arg2_id))

                    for synonym_group in synonym_groups:
                        for arg1_id, arg2_id in permutations(synonym_group, 2):
                            add_relation(arg1_id, arg2_id, _relation="Synonym-of")
                    for hyponym in hyponyms:
                        add_relation(hyponym["arg1_id"], hyponym["arg2_id"], _relation="Hyponym-of")
                    for arg1_id, arg2_id in entity_pairs:
                        add_relation(arg1_id, arg2_id, _relation="O")
                    for relation in relations:
                        key += 1
                        # Yields examples as (key, example) tuples
                        example = {
                            "id": str(key),
                            "tokens": tokens
                        }
                        for k, v in relation.items():
                            example[k] = v
                        yield key, example
                else:
                    key += 1
                    # Yields examples as (key, example) tuples
                    yield key, {
                        "id": str(key),
                        "tokens": tokens,
                        "ner_tags": ner_tags
                    }