science_ie / science_ie.py
phucdev's picture
Update science_ie.py
b6a41b0
raw
history blame
18.6 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 pathlib import Path
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"
}
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.0.0")
BUILDER_CONFIGS = [
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 = "ner"
def _info(self):
if 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)
word_splitter = English()
word_splitter.add_pipe('sentencizer')
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()
doc = word_splitter(text)
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)
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
})
# 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"