Datasets:

Modalities:
Text
ArXiv:
Libraries:
Datasets
License:
SREDFM / SREDFM.py
PereLluis13's picture
update and add README
568ffc1
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# 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.
# Lint as: python3
"""REDFM: a Filtered and Multilingual Relation Extraction Dataset."""
import collections
import json
import os
from contextlib import ExitStack
import logging
import datasets
_CITATION = """\
@InProceedings{REDFM2023,
author = {Huguet Cabot, Pere-Lluis
and Tedeschi, Simone
and Ngonga Ngomo, Axel-Cyrille
and Navigli, Roberto},
title = {RED\textsuperscript{FM}: a Filtered and Multilingual Relation Extraction Dataset},
booktitle = {Proceedings of the 2023 Conference on Association for Computational Linguistics},
year = {2023},
publisher = {Association for Computational Linguistics},
location = {Toronto, Canada},
}"""
_DESCRIPTION = """\
Relation Extraction (RE) is a task that identifies relationships between entities in a text, enabling the acquisition of relational facts and bridging the gap between natural language and structured knowledge. However, current RE models often rely on small datasets with low coverage of relation types, particularly when working with languages other than English. \\
In this paper, we address the above issue and provide two new resources that enable the training and evaluation of multilingual RE systems.
First, we present SRED\textsuperscript{FM}, an automatically annotated dataset covering 18 languages, 400 relation types, 13 entity types, totaling more than 40 million triplet instances. Second, we propose RED\textsuperscript{FM}, a smaller, human-revised dataset for seven languages that allows for the evaluation of multilingual RE systems.
To demonstrate the utility of these novel datasets, we experiment with the first end-to-end multilingual RE model, mREBEL,
that extracts triplets, including entity types, in multiple languages. We release our resources and model checkpoints at \href{https://www.github.com/babelscape/rebel}{https://www.github.com/babelscape/rebel}.
"""
DEFAULT_CONFIG_NAME = "all_languages"
_LANGUAGES = ("ar", "ca", "de", "el", "en", "es", "fr", "hi", "it", "ja", "ko", "nl", "pl", "pt", "ru", "sv", "vi", "zh")
_URL_train = f"data/train."
_URL_dev = f"data/dev."
_URL_test = f"data/test."
class SREDFMConfig(datasets.BuilderConfig):
"""BuilderConfig for SREDFM."""
def __init__(self, language: str, languages=None, **kwargs):
"""BuilderConfig for SREDFM.
Args:
language: One of ar,de,en,es,fr,it,zh, or all_languages
**kwargs: keyword arguments forwarded to super.
"""
super(SREDFMConfig, self).__init__(**kwargs)
self.language = language
if language != "all_languages":
self.languages = [language]
else:
self.languages = languages if languages is not None else _LANGUAGES
class SREDFM(datasets.GeneratorBasedBuilder):
"""SREDFM: a Filtered and Multilingual Relation Extraction Dataset. Version 1.0.0"""
VERSION = datasets.Version("1.0.0", "")
BUILDER_CONFIG_CLASS = SREDFMConfig
BUILDER_CONFIGS = [
SREDFMConfig(
name=lang,
language=lang,
version=datasets.Version("1.0.0", ""),
description=f"Plain text import of SREDFM for the {lang} language",
)
for lang in _LANGUAGES
] + [
SREDFMConfig(
name="all_languages",
language="all_languages",
version=datasets.Version("1.0.0", ""),
description="Plain text import of SREDFM for all languages",
)
]
def _info(self):
if self.config.language == "all_languages":
features = datasets.Features(
{
"docid": datasets.Value("string"),
"title": datasets.Value("string"),
"uri": datasets.Value("string"),
"lan": datasets.Value("string"),
"text": datasets.Value("string"),
"entities": [{'uri': datasets.Value(dtype='string'), 'surfaceform': datasets.Value(dtype='string'), 'type': datasets.Value(dtype='string'), 'start': datasets.Value(dtype='int32'), 'end': datasets.Value(dtype='int32')}],
"relations": [{'subject': datasets.Value(dtype='int32'),
'predicate': datasets.Value(dtype='string'),
'object': datasets.Value(dtype='int32')}],
}
)
else:
features = datasets.Features(
{
"docid": datasets.Value("string"),
"title": datasets.Value("string"),
"uri": datasets.Value("string"),
"text": datasets.Value("string"),
"entities": [{'uri': datasets.Value(dtype='string'), 'surfaceform': datasets.Value(dtype='string'), 'type': datasets.Value(dtype='string'), 'start': datasets.Value(dtype='int32'), 'end': datasets.Value(dtype='int32')}],
"relations": [{'subject': datasets.Value(dtype='int32'),
'predicate': datasets.Value(dtype='string'),
'object': datasets.Value(dtype='int32')}],
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
# No default supervised_keys (as we have to pass both premise
# and hypothesis as input).
supervised_keys=None,
homepage="https://www.github.com/babelscape/rebel",
citation=_CITATION,
)
def _split_generators(self, dl_manager):
data_dir = dl_manager.download(
{
"train": [f"{_URL_train}{lang}.jsonl" for lang in self.config.languages],
"dev": [f"{_URL_dev}{lang}.jsonl" for lang in self.config.languages],
"test": [f"{_URL_test}{lang}.jsonl" for lang in self.config.languages],
"relations": "relations.tsv",
}
)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepaths": data_dir["train"],
"relations": data_dir["relations"],
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepaths": data_dir["test"],
"relations": data_dir["relations"],
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepaths": data_dir["dev"],
"relations": data_dir["relations"],
},
),
]
def _generate_examples(self, relations, filepaths):
"""This function returns the examples in the raw (text) form."""
logging.info("generating examples from = %s", filepaths)
relation_names = dict()
with open(relations, encoding="utf-8") as f:
for row in f:
rel_code, rel_name, rel_alt_names, rel_description = row.strip().split("\t")
relation_names[rel_code] = rel_name
if self.config.language == "all_languages":
for filepath in filepaths:
with open(filepath, encoding="utf-8") as f:
for idx, row in enumerate(f):
data = json.loads(row)
entities = []
for entity in data["entities"]:
entities.append({
"uri": entity["uri"],
"surfaceform": entity["surfaceform"],
"start": entity["boundaries"][0],
"end": entity["boundaries"][1],
"type": entity["type"],
})
relations = []
for relation in data["relations"]:
if relation["predicate"]["uri"] not in relation_names or relation['confidence']<=0.75:
continue
relations.append({
"subject": entities.index({
"uri": relation["subject"]["uri"],
"surfaceform": relation["subject"]["surfaceform"],
"start": relation["subject"]["boundaries"][0],
"end": relation["subject"]["boundaries"][1],
"type": relation["subject"]["type"],
}),
"predicate": relation_names[relation["predicate"]["uri"]],
"object": entities.index({
"uri": relation["object"]["uri"],
"surfaceform": relation["object"]["surfaceform"],
"start": relation["object"]["boundaries"][0],
"end": relation["object"]["boundaries"][1],
"type": relation["object"]["type"],
}),
})
if len(relations) == 0:
continue
yield data["docid"]+ '-' + data["lan"], {
"docid": data["docid"],
"title": data["title"],
"uri": data["uri"],
"lan": data["lan"],
"text": data["text"],
"entities": entities,
"relations": relations,
}
else:
for filepath in filepaths:
with open(filepath, encoding="utf-8") as f:
for idx, row in enumerate(f):
data = json.loads(row)
entities = []
for entity in data["entities"]:
entities.append({
"uri": entity["uri"],
"surfaceform": entity["surfaceform"],
"start": entity["boundaries"][0],
"end": entity["boundaries"][1],
"type": entity["type"],
})
relations = []
for relation in data["relations"]:
if relation["predicate"]["uri"] not in relation_names or relation['confidence']<=0.75:
continue
relations.append({
"subject": entities.index({
"uri": relation["subject"]["uri"],
"surfaceform": relation["subject"]["surfaceform"],
"start": relation["subject"]["boundaries"][0],
"end": relation["subject"]["boundaries"][1],
"type": relation["subject"]["type"],
}),
"predicate": relation_names[relation["predicate"]["uri"]],
"object": entities.index({
"uri": relation["object"]["uri"],
"surfaceform": relation["object"]["surfaceform"],
"start": relation["object"]["boundaries"][0],
"end": relation["object"]["boundaries"][1],
"type": relation["object"]["type"],
}),
})
if len(relations) == 0:
continue
yield data["docid"], {
"docid": data["docid"],
"title": data["title"],
"uri": data["uri"],
"text": data["text"],
"entities": entities,
"relations": relations,
}