science_ie / science_ie.py
phucdev's picture
Add RE configuration to science_ie.py
75b9352
raw
history blame
12.8 kB
# 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
}