File size: 22,360 Bytes
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75b9352
3ac9938
75b9352
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1951
3ac9938
 
94b1951
2f8afd8
94b1951
 
2f8afd8
3ac9938
 
 
 
 
 
 
 
75b9352
 
94b1951
 
2f8afd8
94b1951
 
2f8afd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75b9352
 
 
 
 
 
 
 
 
 
3ac9938
75b9352
 
 
 
 
 
 
3ac9938
75b9352
 
 
3ac9938
 
75b9352
 
 
3ac9938
75b9352
 
 
 
 
94b1951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f8afd8
 
 
 
 
 
3ac9938
 
 
 
 
94b1951
 
b6a41b0
2f8afd8
 
 
 
94b1951
75b9352
 
94b1951
75b9352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1951
75b9352
94b1951
 
75b9352
94b1951
3ac9938
 
 
2f8afd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9938
2f8afd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9938
2f8afd8
 
75b9352
2f8afd8
 
 
 
 
3ac9938
2f8afd8
3ac9938
 
 
2f8afd8
3ac9938
2f8afd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac9938
 
 
 
 
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# 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 pathlib import Path
from itertools import permutations

# 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"
}


def generate_relation(entities, arg1_id, arg2_id, relation, offset=0):
    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, \
        f"Did not find corresponding entities {arg1_id} & {arg2_id} in {entities}"
    return {
        "arg1_start": arg1["start"] - offset,
        "arg1_end": arg1["end"] - offset,
        "arg1_type": arg1["type"],
        "arg2_start": arg2["start"] - offset,
        "arg2_end": arg2["end"] - offset,
        "arg2_type": arg2["type"],
        "relation": relation
    }


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.1.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="science_ie", version=VERSION, description="Full ScienceIE dataset"),
        datasets.BuilderConfig(name="subtask_a", version=VERSION,
                               description="Subtask A of ScienceIE for tokens being outside, at the beginning, "
                                           "or inside a key phrase"),
        datasets.BuilderConfig(name="subtask_b", version=VERSION,
                               description="Subtask B of ScienceIE for tokens being outside, or part of a material, "
                                           "process or task"),
        datasets.BuilderConfig(name="subtask_c", version=VERSION,
                               description="Subtask C of ScienceIE for Synonym-of and Hyponym-of relations"),
        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 = "science_ie"

    def _info(self):
        if self.config.name == "science_ie":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "keyphrases": [
                        {
                            "id": datasets.Value("string"),
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32"),
                            "type": datasets.features.ClassLabel(
                                names=[
                                    "Material",
                                    "Process",
                                    "Task"
                                ]
                            ),
                            "type_": datasets.Value("string")
                        }
                    ],
                    "relations": [
                        {
                            "arg1": datasets.Value("string"),
                            "arg2": datasets.Value("string"),
                            "relation": datasets.features.ClassLabel(names=["O", "Synonym-of", "Hyponym-of"]),
                            "relation_": datasets.Value("string")
                        }
                    ]
                }
            )
        elif self.config.name == "subtask_a":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "tags": datasets.Sequence(datasets.features.ClassLabel(names=["O", "B", "I"]))
                }
            )
        elif self.config.name == "subtask_b":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "tags": datasets.Sequence(datasets.features.ClassLabel(names=["O", "M", "P", "T"]))
                }
            )
        elif self.config.name == "subtask_c":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "tags": datasets.Sequence(datasets.Sequence(datasets.features.ClassLabel(names=["O", "S", "H"])))
                }
            )
        elif 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")),
                    "tags": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=[
                                "O",
                                "B-Material",
                                "I-Material",
                                "B-Process",
                                "I-Process",
                                "B-Task",
                                "I-Task"
                            ]
                        )
                    )
                }
            )
        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)
        if self.config.name != "science_ie":
            from spacy.lang.en import English
            word_splitter = English()
            word_splitter.add_pipe('sentencizer')
        else:
            word_splitter = None
        for f_anno_file in annotation_files:
            doc_example_idx = 0
            f_anno_path = Path(f_anno_file)
            f_text_path = f_anno_path.with_suffix(".txt")
            doc_id = f_anno_path.stem
            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().strip()
                if word_splitter:
                    doc = word_splitter(text)
                else:
                    doc = None
                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_file)
                            char_start = int(start)
                            char_end = int(end)
                            if doc:
                                entity_span = doc.char_span(char_start, char_end, alignment_mode="expand")
                                start = entity_span.start
                                end = entity_span.end
                                entities.append({
                                    "id": identifier,
                                    "start": start,
                                    "end": end,
                                    "char_start": char_start,
                                    "char_end": char_end,
                                    "type": key_type,
                                    "type_": key_type
                                })
                            else:
                                entities.append({
                                    "id": identifier,
                                    "start": char_start,
                                    "end": char_end,
                                    "type": key_type,
                                    "type_": key_type
                                })
                if self.config.name == "science_ie":
                    # just to pass the assertion at the end of the method, check is not relevant for this config
                    synonym_groups_used = [True for _ in synonym_groups]
                    hyponyms_used = [True for _ in hyponyms]
                    gen_relations = []
                    for idx, synonym_group in enumerate(synonym_groups):
                        for arg1_id, arg2_id in permutations(synonym_group, 2):
                            gen_relations.append(dict(arg1=arg1_id, arg2=arg2_id, relation="Synonym-of",
                                                      relation_="Synonym-of"))
                    for hyponym in hyponyms:
                        gen_relations.append(dict(arg1=hyponym["arg1_id"], arg2=hyponym["arg2_id"],
                                                  relation="Hyponym-of", relation_="Hyponym-of"))
                    yield doc_id, {
                        "id": doc_id,
                        "text": text,
                        "keyphrases": entities,
                        "relations": gen_relations
                    }
                else:
                    # check if any annotation is lost during sentence splitting
                    synonym_groups_used = [False for _ in synonym_groups]
                    hyponyms_used = [False for _ in hyponyms]
                    for sent in doc.sents:
                        token_offset = sent.start
                        tokens = [token.text for token in sent]
                        tags = ["O" for _ in tokens]
                        sent_entities = []
                        sent_entity_ids = []
                        for entity in entities:
                            if entity["start"] >= sent.start and entity["end"] <= sent.end:
                                sent_entity = {k: v for k, v in entity.items()}
                                sent_entity["start"] -= token_offset
                                sent_entity["end"] -= token_offset
                                sent_entities.append(sent_entity)
                                sent_entity_ids.append(entity["id"])
                        for entity in sent_entities:
                            tags[entity["start"]] = "B-" + entity["type"]
                            for i in range(entity["start"] + 1, entity["end"]):
                                tags[i] = "I-" + entity["type"]

                        relations = []
                        entity_pairs_in_relation = []
                        for idx, synonym_group in enumerate(synonym_groups):
                            if all(entity_id in sent_entity_ids for entity_id in synonym_group):
                                synonym_groups_used[idx] = True
                                for arg1_id, arg2_id in permutations(synonym_group, 2):
                                    relations.append(
                                        generate_relation(sent_entities, arg1_id, arg2_id, relation="Synonym-of"))
                                    entity_pairs_in_relation.append((arg1_id, arg2_id))
                        for idx, hyponym in enumerate(hyponyms):
                            if hyponym["arg1_id"] in sent_entity_ids and hyponym["arg2_id"] in sent_entity_ids:
                                hyponyms_used[idx] = True
                                relations.append(
                                    generate_relation(sent_entities, hyponym["arg1_id"], hyponym["arg2_id"],
                                                      relation="Hyponym-of"))

                                entity_pairs_in_relation.append((arg1_id, arg2_id))
                        entity_pairs = [(arg1["id"], arg2["id"]) for arg1, arg2 in permutations(sent_entities, 2)
                                        if (arg1["id"], arg2["id"]) not in entity_pairs_in_relation]
                        for arg1_id, arg2_id in entity_pairs:
                            relations.append(generate_relation(sent_entities, arg1_id, arg2_id, relation="O"))

                        if self.config.name == "subtask_a":
                            doc_example_idx += 1
                            key = f"{doc_id}_{doc_example_idx}"
                            # Yields examples as (key, example) tuples
                            yield key, {
                                "id": key,
                                "tokens": tokens,
                                "tags": [tag[0] for tag in tags]
                            }
                        elif self.config.name == "subtask_b":
                            doc_example_idx += 1
                            key = f"{doc_id}_{doc_example_idx}"
                            # Yields examples as (key, example) tuples
                            key_phrase_tags = []
                            for tag in tags:
                                if tag == "O":
                                    key_phrase_tags.append(tag)
                                else:
                                    # use first letter of key phrase type
                                    key_phrase_tags.append(tag[2])
                            yield key, {
                                "id": key,
                                "tokens": tokens,
                                "tags": key_phrase_tags
                            }
                        elif self.config.name == "subtask_c":
                            doc_example_idx += 1
                            key = f"{doc_id}_{doc_example_idx}"
                            tag_vectors = [["O" for _ in tokens] for _ in tokens]
                            for relation in relations:
                                tag = relation["relation"][0]
                                if tag != "O":
                                    tag_vectors[relation["arg1_start"]][relation["arg2_start"]] = tag
                            # Yields examples as (key, example) tuples
                            yield key, {
                                "id": key,
                                "tokens": tokens,
                                "tags": tag_vectors
                            }
                        elif self.config.name == "re":
                            for relation in relations:
                                doc_example_idx += 1
                                key = f"{doc_id}_{doc_example_idx}"
                                # Yields examples as (key, example) tuples
                                example = {
                                    "id": key,
                                    "tokens": tokens
                                }
                                for k, v in relation.items():
                                    example[k] = v
                                yield key, example
                        else:  # NER config
                            doc_example_idx += 1
                            key = f"{doc_id}_{doc_example_idx}"
                            # Yields examples as (key, example) tuples
                            yield key, {
                                "id": key,
                                "tokens": tokens,
                                "tags": tags
                            }

        assert all(synonym_groups_used) and all(hyponyms_used), \
            f"Annotations were lost: {len([e for e in synonym_groups_used if e])} synonym annotations," \
            f"{len([e for e in hyponyms_used if e])} synonym annotations"