Datasets:
File size: 13,155 Bytes
c3db668 |
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 |
# 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": datasets.Sequence(feature={'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": datasets.Sequence(feature={'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": datasets.Sequence(feature={'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": datasets.Sequence(feature={'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"],
}),
})
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"],
}),
})
yield data["docid"], {
"docid": data["docid"],
"title": data["title"],
"uri": data["uri"],
"text": data["text"],
"entities": entities,
"relations": relations,
} |