File size: 12,435 Bytes
5b19c86 |
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 |
# Some code referenced from https://huggingface.co/datasets/Babelscape/SREDFM/blob/main/SREDFM.py
from pathlib import Path
from typing import Dict, List, Tuple
import datasets
import jsonlines
from seacrowd.utils import schemas
from seacrowd.utils.configs import SEACrowdConfig
from seacrowd.utils.constants import Licenses, Tasks
_CITATION = """\
@inproceedings{huguet-cabot-et-al-2023-redfm-dataset,
title = "RED$^{\rm FM}$: a Filtered and Multilingual Relation Extraction Dataset",
author = "Huguet Cabot, Pere-Lluís and Tedeschi, Simone and Ngonga Ngomo, Axel-Cyrille and
Navigli, Roberto",
booktitle = "Proc. of the 61st Annual Meeting of the Association for Computational Linguistics: ACL 2023",
month = jul,
year = "2023",
address = "Toronto, Canada",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/2306.09802",
}
"""
_DATASETNAME = "sredfm"
_DESCRIPTION = """\
SREDFM is an automatically annotated dataset for relation extraction task covering 18 languages, 400 relation types, 13 entity types, totaling more than 40 million triplet instances. SREDFM includes Vietnamnese.
"""
_HOMEPAGE = "https://github.com/babelscape/rebel"
_LANGUAGES = ["vie"]
_LICENSE = Licenses.CC_BY_SA_4_0.value
_LOCAL = False
_URLS = {
"train": "https://huggingface.co/datasets/Babelscape/SREDFM/resolve/main/data/train.vi.jsonl",
"dev": "https://huggingface.co/datasets/Babelscape/SREDFM/resolve/main/data/dev.vi.jsonl",
"test": "https://huggingface.co/datasets/Babelscape/SREDFM/resolve/main/data/test.vi.jsonl",
"relations_url": "https://huggingface.co/datasets/Babelscape/SREDFM/raw/main/relations.tsv",
}
_SUPPORTED_TASKS = [Tasks.RELATION_EXTRACTION]
_SOURCE_VERSION = "1.0.0"
_SEACROWD_VERSION = "2024.06.20"
class SREDFMDataset(datasets.GeneratorBasedBuilder):
"""SREDFM is an automatically annotated dataset for relation extraction task.
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. SREDFM covers 400 relation types, 13 entity types,
totaling more than 40 million triplet instances."""
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
BUILDER_CONFIGS = [
SEACrowdConfig(
name=f"{_DATASETNAME}_source",
version=SOURCE_VERSION,
description=f"{_DATASETNAME} source schema",
schema="source",
subset_id=f"{_DATASETNAME}",
),
SEACrowdConfig(
name=f"{_DATASETNAME}_seacrowd_kb",
version=SEACROWD_VERSION,
description=f"{_DATASETNAME} SEACrowd schema",
schema="seacrowd_kb",
subset_id=f"{_DATASETNAME}",
),
]
DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_source"
def _info(self) -> datasets.DatasetInfo:
if self.config.schema == "source":
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"),
}
],
}
)
elif self.config.schema == "seacrowd_kb":
features = schemas.kb_features
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
"""Returns SplitGenerators."""
data_dir = dl_manager.download_and_extract(_URLS)
relation_names = dict()
relation_path = data_dir["relations_url"]
with open(relation_path, encoding="utf-8") as f:
for row in f:
rel_code, rel_name, _, _ = row.strip().split("\t")
relation_names[rel_code] = rel_name
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepath": data_dir["train"], "relation_names": relation_names},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"filepath": data_dir["test"], "relation_names": relation_names},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"filepath": data_dir["dev"], "relation_names": relation_names},
),
]
def _generate_examples(self, filepath: Path, relation_names: dict) -> Tuple[int, Dict]:
"""Yields examples as (key, example) tuples."""
if self.config.schema == "source":
with jsonlines.open(filepath) as f:
skip = set()
for example in f.iter():
if example["docid"] in skip:
continue
skip.add(example["docid"])
entities = []
for entity in example["entities"]:
entities.append(
{
"uri": entity["uri"],
"surfaceform": entity["surfaceform"],
"start": entity["boundaries"][0],
"end": entity["boundaries"][1],
"type": entity["type"],
}
)
relations = []
for relation in example["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 example["docid"], {
"docid": example["docid"],
"title": example["title"],
"uri": example["uri"],
"text": example["text"],
"entities": entities,
"relations": relations,
}
elif self.config.schema == "seacrowd_kb":
with jsonlines.open(filepath) as f:
skip = set()
i = 0
for example in f.iter():
if example["docid"] in skip:
continue
skip.add(example["docid"])
i += 1
processed_text = example["text"].replace("\n", " ")
passages = [
{
"id": f"{i}-{example['uri']}",
"type": "text",
"text": [processed_text],
"offsets": [[0, len(processed_text)]],
}
]
entities = []
for entity in example["entities"]:
entities.append(
{
"id": entity["uri"],
"type": entity["type"],
"text": [entity["surfaceform"]],
"offsets": [entity["boundaries"]],
"normalized": {"db_name": "", "db_id": ""},
}
)
relations = []
for relation in example["relations"]:
if relation["predicate"]["uri"] not in relation_names or relation["confidence"] <= 0.75:
continue
i += 1
sub = relation["subject"]
pred = relation["predicate"]
obj = relation["object"]
relations.append(
{
"id": f"{i}-{sub['uri']}-{pred['uri']}-{obj['uri']}",
"type": relation_names[pred["uri"]],
"arg1_id": str(
entities.index(
{
"id": sub["uri"],
"type": sub["type"],
"text": [sub["surfaceform"]],
"offsets": [sub["boundaries"]],
"normalized": {"db_name": "", "db_id": ""},
}
)
),
"arg2_id": str(
entities.index(
{
"id": obj["uri"],
"type": obj["type"],
"text": [obj["surfaceform"]],
"offsets": [obj["boundaries"]],
"normalized": {"db_name": "", "db_id": ""},
}
)
),
"normalized": {"db_name": "", "db_id": ""},
}
)
for entity in entities:
i += 1
entity["id"] = f"{i}-{entity['id']}"
if len(relations) == 0:
continue
yield example["docid"], {
"id": example["docid"],
"passages": passages,
"entities": entities,
"relations": relations,
"events": [],
"coreferences": [],
}
|