Datasets:
File size: 17,310 Bytes
ea34fa8 |
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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
# coding=utf-8
# Copyright 2022 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.
"""The KnowledgeNet dataset for automatically populating a knowledge base"""
import json
import re
import datasets
_CITATION = """\
@inproceedings{mesquita-etal-2019-knowledgenet,
title = "{K}nowledge{N}et: A Benchmark Dataset for Knowledge Base Population",
author = "Mesquita, Filipe and
Cannaviccio, Matteo and
Schmidek, Jordan and
Mirza, Paramita and
Barbosa, Denilson",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing and the 9th International Joint Conference on Natural Language Processing (EMNLP-IJCNLP)",
month = nov,
year = "2019",
address = "Hong Kong, China",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/D19-1069",
doi = "10.18653/v1/D19-1069",
pages = "749--758",}
"""
_DESCRIPTION = """\
KnowledgeNet is a benchmark dataset for the task of automatically populating a knowledge base (Wikidata) with facts
expressed in natural language text on the web. KnowledgeNet provides text exhaustively annotated with facts, thus
enabling the holistic end-to-end evaluation of knowledge base population systems as a whole, unlike previous benchmarks
that are more suitable for the evaluation of individual subcomponents (e.g., entity linking, relation extraction).
For instance, the dataset contains text expressing the fact (Gennaro Basile; RESIDENCE; Moravia), in the passage:
"Gennaro Basile was an Italian painter, born in Naples but active in the German-speaking countries. He settled at Brünn,
in Moravia, and lived about 1756..."
For a description of the dataset and baseline systems, please refer to their
[EMNLP paper](https://github.com/diffbot/knowledge-net/blob/master/knowledgenet-emnlp-cameraready.pdf).
Note: This Datasetreader currently only supports the `train` split and does not contain negative examples
"""
_HOMEPAGE = "https://github.com/diffbot/knowledge-net"
_LICENSE = ""
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
_URLS = {
"train": "https://raw.githubusercontent.com/diffbot/knowledge-net/master/dataset/train.json",
"test": "https://raw.githubusercontent.com/diffbot/knowledge-net/master/dataset/test-no-facts.json"
}
_VERSION = datasets.Version("1.1.0")
_CLASS_LABELS = [
"NO_RELATION",
"DATE_OF_BIRTH",
"DATE_OF_DEATH",
"PLACE_OF_RESIDENCE",
"PLACE_OF_BIRTH",
"NATIONALITY",
"EMPLOYEE_OR_MEMBER_OF",
"EDUCATED_AT",
"POLITICAL_AFFILIATION",
"CHILD_OF",
"SPOUSE",
"DATE_FOUNDED",
"HEADQUARTERS",
"SUBSIDIARY_OF",
"FOUNDED_BY",
"CEO"
]
_NER_CLASS_LABELS = [
"O",
"PER",
"ORG",
"LOC",
"DATE"
]
def get_entity_types_from_relation(relation_label):
if relation_label == "DATE_OF_BIRTH":
subj_type = "PER"
obj_type = "DATE"
elif relation_label == "DATE_OF_DEATH":
subj_type = "PER"
obj_type = "DATE"
elif relation_label == "PLACE_OF_RESIDENCE":
subj_type = "PER"
obj_type = "LOC"
elif relation_label == "PLACE_OF_BIRTH":
subj_type = "PER"
obj_type = "LOC"
elif relation_label == "NATIONALITY":
subj_type = "PER"
obj_type = "LOC"
elif relation_label == "EMPLOYEE_OR_MEMBER_OF":
subj_type = "PER"
obj_type = "ORG"
elif relation_label == "EDUCATED_AT":
subj_type = "PER"
obj_type = "ORG"
elif relation_label == "POLITICAL_AFFILIATION":
subj_type = "PER"
obj_type = "ORG"
elif relation_label == "CHILD_OF":
subj_type = "PER"
obj_type = "PER"
elif relation_label == "SPOUSE":
subj_type = "PER"
obj_type = "PER"
elif relation_label == "DATE_FOUNDED":
subj_type = "ORG"
obj_type = "DATE"
elif relation_label == "HEADQUARTERS":
subj_type = "ORG"
obj_type = "LOC"
elif relation_label == "SUBSIDIARY_OF":
subj_type = "ORG"
obj_type = "ORG"
elif relation_label == "FOUNDED_BY":
subj_type = "ORG"
obj_type = "PER"
elif relation_label == "CEO":
subj_type = "ORG"
obj_type = "PER"
else:
raise ValueError(f"Unknown relation label: {relation_label}")
return subj_type, obj_type
def remove_contiguous_whitespaces(text):
# +1 to account for regular whitespace at the beginning
contiguous_whitespaces_indices = [(m.start(0) + 1, m.end(0)) for m in re.finditer(' +', text)]
cleaned_text = re.sub(" +", " ", text)
return cleaned_text, contiguous_whitespaces_indices
def fix_char_index(char_index, contiguous_whitespaces_indices):
new_char_index = char_index
offset = 0
for ws_start, ws_end in contiguous_whitespaces_indices:
if char_index >= ws_end:
offset = offset + (ws_end - ws_start)
new_char_index -= offset
return new_char_index
class KnowledgeNet(datasets.GeneratorBasedBuilder):
"""The KnowledgeNet dataset for automatically populating a knowledge base"""
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="knet", version=_VERSION, description="The original KnowledgeNet formatted for RE."
),
datasets.BuilderConfig(
name="knet_re", version=_VERSION, description="The original KnowledgeNet formatted for RE."
),
datasets.BuilderConfig(
name="knet_tokenized", version=_VERSION, description="KnowledgeNet tokenized and reformatted."
),
]
DEFAULT_CONFIG_NAME = "knet" # type: ignore
def _info(self):
if self.config.name == "knet_tokenized":
features = datasets.Features(
{
"doc_id": datasets.Value("string"),
"passage_id": datasets.Value("string"),
"fact_id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"subj_start": datasets.Value("int32"),
"subj_end": datasets.Value("int32"),
"subj_type": datasets.ClassLabel(names=_NER_CLASS_LABELS),
"subj_uri": datasets.Value("string"),
"obj_start": datasets.Value("int32"),
"obj_end": datasets.Value("int32"),
"obj_type": datasets.ClassLabel(names=_NER_CLASS_LABELS),
"obj_uri": datasets.Value("string"),
"relation": datasets.ClassLabel(names=_CLASS_LABELS),
}
)
elif self.config.name == "knet_re":
features = datasets.Features(
{
"documentId": datasets.Value("string"),
"passageId": datasets.Value("string"),
"factId": datasets.Value("string"),
"passageText": datasets.Value("string"),
"humanReadable": datasets.Value("string"),
"annotatedPassage": datasets.Value("string"),
"subjectStart": datasets.Value("int32"),
"subjectEnd": datasets.Value("int32"),
"subjectText": datasets.Value("string"),
"subjectType": datasets.ClassLabel(names=_NER_CLASS_LABELS),
"subjectUri": datasets.Value("string"),
"objectStart": datasets.Value("int32"),
"objectEnd": datasets.Value("int32"),
"objectText": datasets.Value("string"),
"objectType": datasets.ClassLabel(names=_NER_CLASS_LABELS),
"objectUri": datasets.Value("string"),
"relation": datasets.ClassLabel(names=_CLASS_LABELS),
}
)
else:
features = datasets.Features(
{
"fold": datasets.Value("int32"),
"documentId": datasets.Value("string"),
"source": datasets.Value("string"),
"documentText": datasets.Value("string"),
"passages": [{
"passageId": datasets.Value("string"),
"passageStart": datasets.Value("int32"),
"passageEnd": datasets.Value("int32"),
"passageText": datasets.Value("string"),
"exhaustivelyAnnotatedProperties": [{
"propertyId": datasets.Value("string"),
"propertyName": datasets.Value("string"),
"propertyDescription": datasets.Value("string"),
}],
"facts": [{
"factId": datasets.Value("string"),
"propertyId": datasets.Value("string"),
"humanReadable": datasets.Value("string"),
"annotatedPassage": datasets.Value("string"),
"subjectStart": datasets.Value("int32"),
"subjectEnd": datasets.Value("int32"),
"subjectText": datasets.Value("string"),
"subjectUri": datasets.Value("string"),
"objectStart": datasets.Value("int32"),
"objectEnd": datasets.Value("int32"),
"objectText": datasets.Value("string"),
"objectUri": datasets.Value("string"),
}],
}],
}
)
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,
# specify them here. They'll be used if as_supervised=True in
# builder.as_dataset.
supervised_keys=None,
# 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):
"""Returns SplitGenerators."""
# 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)
# splits = [datasets.Split.TRAIN, datasets.Split.TEST]
splits = [datasets.Split.TRAIN]
return [datasets.SplitGenerator(name=i, gen_kwargs={"filepath": downloaded_files[str(i)], "split": i})
for i in splits]
def _generate_examples(self, filepath, split):
"""Yields examples."""
# This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method.
# It is in charge of opening the given file and yielding (key, example) tuples from the dataset
# The key is not important, it's more here for legacy reason (legacy from tfds)
if self.config.name == "knet_tokenized":
from spacy.lang.en import English
word_splitter = English()
else:
word_splitter = None
with open(filepath, encoding="utf-8") as f:
for line in f:
doc = json.loads(line)
if self.config.name == "knet":
yield doc["documentId"], doc
else:
for passage in doc["passages"]:
# Skip passages without facts right away
if len(passage["facts"]) == 0:
continue
text = passage["passageText"]
passage_start = passage["passageStart"]
if self.config.name == "knet_tokenized":
cleaned_text, contiguous_ws_indices = remove_contiguous_whitespaces(text)
spacy_doc = word_splitter(cleaned_text)
word_tokens = [t.text for t in spacy_doc]
for fact in passage["facts"]:
subj_start = fix_char_index(fact["subjectStart"] - passage_start, contiguous_ws_indices)
subj_end = fix_char_index(fact["subjectEnd"] - passage_start, contiguous_ws_indices)
obj_start = fix_char_index(fact["objectStart"] - passage_start, contiguous_ws_indices)
obj_end = fix_char_index(fact["objectEnd"] - passage_start, contiguous_ws_indices)
# Get exclusive token spans from char spans
subj_span = spacy_doc.char_span(subj_start, subj_end, alignment_mode="expand")
obj_span = spacy_doc.char_span(obj_start, obj_end, alignment_mode="expand")
relation_label = fact["humanReadable"].split(">")[1][2:]
subj_type, obj_type = get_entity_types_from_relation(relation_label)
id_ = fact["factId"]
yield id_, {
"doc_id": doc["documentId"],
"passage_id": passage["passageId"],
"fact_id": id_,
"tokens": word_tokens,
"subj_start": subj_span.start,
"subj_end": subj_span.end,
"subj_type": subj_type,
"subj_uri": fact["subjectUri"],
"obj_start": obj_span.start,
"obj_end": obj_span.end,
"obj_type": obj_type,
"obj_uri": fact["objectUri"],
"relation": relation_label
}
else:
for fact in passage["facts"]:
relation_label = fact["humanReadable"].split(">")[1][2:]
subj_type, obj_type = get_entity_types_from_relation(relation_label)
id_ = fact["factId"]
yield id_, {
"documentId": doc["documentId"],
"passageId": passage["passageId"],
"passageText": passage["passageText"],
"factId": id_,
"humanReadable": fact["humanReadable"],
"annotatedPassage": fact["annotatedPassage"],
"subjectStart": fact["subjectStart"] - passage_start,
"subjectEnd": fact["subjectEnd"] - passage_start,
"subjectText": fact["subjectText"],
"subjectType": subj_type,
"subjectUri": fact["subjectUri"],
"objectStart": fact["objectStart"] - passage_start,
"objectEnd": fact["objectEnd"] - passage_start,
"objectText": fact["objectText"],
"objectType": obj_type,
"objectUri": fact["objectUri"],
"relation": relation_label
}
|