Datasets:
File size: 23,175 Bytes
0f218f8 f28bfbf 0f218f8 f28bfbf 15676c8 f28bfbf 0f218f8 f28bfbf 0f218f8 f28bfbf 0f218f8 f28bfbf 15676c8 0f218f8 f28bfbf 0f218f8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 0f218f8 15676c8 0f218f8 f28bfbf 15676c8 f28bfbf 0f218f8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf 15676c8 f28bfbf |
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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 |
# coding=utf-8
# 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.
"""\
MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities. The dataset consists of 3,232 social media texts and traffic reports with 91K tokens, and contains 20.5K annotated entities, 13.1K of which are linked to a knowledge base. A subset of the dataset is human-annotated with seven mobility-related, n-ary relation types, while the remaining documents are annotated using a weakly-supervised labeling approach implemented with the Snorkel framework. The dataset combines annotations for NER, EL and RE, and thus can be used for joint and multi-task learning of these fundamental information extraction tasks."""
import re
import json
from json import JSONDecodeError, JSONDecoder
import datasets
_CITATION = """\
@inproceedings{hennig-etal-2021-mobie,
title = "{M}ob{IE}: A {G}erman Dataset for Named Entity Recognition, Entity Linking and Relation Extraction in the Mobility Domain",
author = "Hennig, Leonhard and
Truong, Phuc Tran and
Gabryszak, Aleksandra",
booktitle = "Proceedings of the 17th Conference on Natural Language Processing (KONVENS 2021)",
month = "6--9 " # sep,
year = "2021",
address = {D{\"u}sseldorf, Germany},
publisher = "KONVENS 2021 Organizers",
url = "https://aclanthology.org/2021.konvens-1.22",
pages = "223--227",
}
"""
_DESCRIPTION = """\
MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities. The dataset consists of 3,232 social media texts and traffic reports with 91K tokens, and contains 20.5K annotated entities, 13.1K of which are linked to a knowledge base. A subset of the dataset is human-annotated with seven mobility-related, n-ary relation types, while the remaining documents are annotated using a weakly-supervised labeling approach implemented with the Snorkel framework. The dataset combines annotations for NER, EL and RE, and thus can be used for joint and multi-task learning of these fundamental information extraction tasks."""
_HOMEPAGE = "https://github.com/dfki-nlp/mobie"
_LICENSE = "CC-BY 4.0"
_URLs = {
"train": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/train.jsonl.gz",
"dev": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/dev.jsonl.gz",
"test": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/test.jsonl.gz",
}
def simplify_dict(d, remove_attribute=True):
"""Simplify nested dictionary by removing unnecessary keys"""
if isinstance(d, dict):
new_dict = {}
for k, v in d.items():
if remove_attribute and k == "attributes":
continue
if isinstance(v, dict) and len(v) == 1:
if "string" in v:
new_dict[k] = v["string"]
elif "map" in v:
new_dict[k] = v["map"]
elif "array" in v:
new_dict[k] = simplify_dict(v["array"])
else:
new_dict[k] = simplify_dict(v)
else:
new_dict[k] = simplify_dict(v)
return new_dict
elif isinstance(d, list):
return [simplify_dict(x) for x in d]
else:
return d
class Mobie(datasets.GeneratorBasedBuilder):
"""MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities"""
VERSION = datasets.Version("1.0.0")
# This is an example of a dataset with multiple configurations.
# If you don't want/need to define several sub-sets in your dataset,
# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
# If you need to make complex sub-parts in the datasets with configurable options
# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
# BUILDER_CONFIG_CLASS = MyBuilderConfig
# You will be able to load one or the other configurations in the following list with
# data = datasets.load_dataset('my_dataset', 'first_domain')
# data = datasets.load_dataset('my_dataset', 'second_domain')
BUILDER_CONFIGS = [
datasets.BuilderConfig(name="ner", version=VERSION, description="MobIE V1 NER"),
datasets.BuilderConfig(name="el", version=VERSION, description="MobIE V1 Entity Linking"),
datasets.BuilderConfig(name="re", version=VERSION, description="MobIE V1 Relation Extraction"),
datasets.BuilderConfig(name="ee", version=VERSION, description="MobIE V1 Event Extraction"),
]
DEFAULT_CONFIG_NAME = "ner"
def _info(self):
labels = [
"date",
"disaster-type",
"distance",
"duration",
"event-cause",
"location",
"location-city",
"location-route",
"location-stop",
"location-street",
"money",
"number",
"organization",
"organization-company",
"org-position",
"percent",
"person",
"set",
"time",
"trigger",
]
entity_mentions = [
{
"id": datasets.Value("string"),
"text": datasets.Value("string"),
"start": datasets.Value("int32"),
"end": datasets.Value("int32"),
"type": datasets.features.ClassLabel(names=labels),
"refids": [
{
"key": datasets.Value("string"),
"value": datasets.Value("string")
}
]
}
]
if self.config.name == "ner":
prefixes = ["B", "I"]
names = ["O"] + [f"{prefix}-{label}" for prefix in prefixes for label in labels]
features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=names
)
),
}
)
elif self.config.name == "el":
features = datasets.Features(
{
"id": datasets.Value("string"),
"text": datasets.Value("string"),
"entity_mentions": entity_mentions
}
)
elif self.config.name == "re":
features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"entities": datasets.Sequence([datasets.Value("int32")]),
"entity_roles": datasets.Sequence(datasets.features.ClassLabel(
names=[
"no_arg", "trigger", "location", "delay", "direction", "start_loc", "end_loc",
"start_date", "end_date", "cause", "jam_length", "route"
]
)),
"entity_types": datasets.Sequence(datasets.features.ClassLabel(
names=labels
)),
"event_type": datasets.features.ClassLabel(
names=[
"O", "Accident", "CanceledRoute", "CanceledStop", "Delay", "Obstruction",
"RailReplacementService", "TrafficJam"
]
),
"entity_ids": datasets.Sequence(datasets.Value("string"))
}
)
elif self.config.name == "ee":
# Inspired by https://github.com/nlpcl-lab/ace2005-preprocessing?tab=readme-ov-file#format
features = datasets.Features(
{
"id": datasets.Value("string"),
"text": datasets.Value("string"),
"entity_mentions": entity_mentions,
"event_mentions": [
{
"id": datasets.Value("string"),
"trigger": {
"id": datasets.Value("string"),
"text": datasets.Value("string"),
"start": datasets.Value("int32"),
"end": datasets.Value("int32"),
},
"arguments": [{
"id": datasets.Value("string"),
"text": datasets.Value("string"),
"start": datasets.Value("int32"),
"end": datasets.Value("int32"),
"role": datasets.features.ClassLabel(
names=[
"no_arg", "location", "delay", "direction", "start_loc", "end_loc",
"start_date", "end_date", "cause", "jam_length", "route"
]
),
"type": datasets.features.ClassLabel(
names=labels
)
}],
"event_type": datasets.features.ClassLabel(
names=[
"O", "Accident", "CanceledRoute", "CanceledStop", "Delay", "Obstruction",
"RailReplacementService", "TrafficJam"
]
),
}
]
}
)
else:
raise ValueError("Invalid configuration name")
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."""
# 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
data_dir = dl_manager.download_and_extract(_URLs)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={"filepath": data_dir["train"], "split": "train"},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={"filepath": data_dir["test"], "split": "test"},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
# These kwargs will be passed to _generate_examples
gen_kwargs={"filepath": data_dir["dev"], "split": "dev"},
),
]
def _generate_examples(self, filepath, split, sentence_level=False):
"""Yields examples."""
if self.config.name == "ner":
NOT_WHITESPACE = re.compile(r"[^\s]")
def decode_stacked(document, pos=0, decoder=JSONDecoder()):
while True:
match = NOT_WHITESPACE.search(document, pos)
if not match:
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except JSONDecodeError:
raise
yield obj
with open(filepath, encoding="utf-8") as f:
raw = f.read()
for doc in decode_stacked(raw):
text = doc["text"]["string"]
iterable = doc["sentences"]["array"] if sentence_level else [doc]
for s in iterable:
toks = []
lbls = []
sid = s["id"]
for x in s["tokens"]["array"]:
toks.append(text[x["span"]["start"]: x["span"]["end"]])
lbls.append(x["ner"]["string"])
yield sid, {
"id": sid,
"tokens": toks,
"ner_tags": lbls,
}
else:
example_idx = 0
with open(filepath, encoding="utf-8") as f:
for line in f:
doc = json.loads(line)
doc = simplify_dict(doc)
text = doc["text"]
iterable = doc["sentences"] if sentence_level else [doc]
for sentence in iterable:
sentence_id = sentence["id"]
sentence_start = sentence["span"]["start"] if "span" in sentence else 0
mobie_cms = sentence["conceptMentions"]
entity_mentions = []
for cm in mobie_cms:
cm_start = cm["span"]["start"]
cm_end = cm["span"]["end"]
cm_text = text[cm_start:cm_end]
entity_mentions.append({
"id": cm["id"],
"text": cm_text,
"start": cm_start - sentence_start,
"end": cm_end - sentence_start,
"type": cm["type"],
"refids": [
{
"key": refid["key"],
"value": refid["value"]
} for refid in cm["refids"]
] if "refids" in cm and cm["refids"] else []
})
if self.config.name == "el":
# TODO use osm_id as entity id?
yield sentence_id, {
"id": sentence_id,
"text": text,
"entity_mentions": entity_mentions
}
elif self.config.name == "re":
mobie_rms = sentence["relationMentions"]
if not mobie_rms:
continue
tokens = [text[token["span"]["start"]:token["span"]["end"]] for token in sentence["tokens"]]
entities = []
entity_types = []
entity_ids = []
for cm in mobie_cms:
# Find token offsets for entity mentions
start = -1
end = -1
for idx, token in enumerate(sentence["tokens"]):
if token["span"]["start"] == cm["span"]["start"]:
start = idx
if token["span"]["end"] == cm["span"]["end"]:
end = idx
assert start != -1 and end != -1, f"Could not find token offsets for {cm['id']}"
entities.append([start, end])
entity_types.append(cm["type"])
found_osm_id = False
for refid in cm["refids"]:
if refid["key"] == "osm_id":
entity_ids.append(refid["value"])
found_osm_id = True
break
if not found_osm_id:
entity_ids.append("NIL")
for rm in mobie_rms:
entity_roles = ["no_arg"] * len(entities)
for arg in rm["args"]:
entity_role = arg["role"]
# Matching via ids does not work, need to match via position
# Find token offsets for entity mentions
start = -1
end = -1
cm = arg["conceptMention"]
for idx, token in enumerate(sentence["tokens"]):
if token["span"]["start"] == cm["span"]["start"]:
start = idx
if token["span"]["end"] == cm["span"]["end"]:
end = idx
assert start != -1 and end != -1, f"Could not find token offsets for {cm['id']}"
entity_idx = -1
for idx, entity in enumerate(entities):
if entity == [start, end]:
entity_idx = idx
break
assert entity_idx != -1, f"Could not find entity for {cm['id']}"
entity_roles[entity_idx] = entity_role
yield f"{sentence_id}_{example_idx}", {
"id": f"{sentence_id}_{example_idx}",
"tokens": tokens,
"entities": entities,
"entity_roles": entity_roles,
"entity_types": entity_types,
"event_type": rm["name"],
"entity_ids": entity_ids
}
example_idx += 1
elif self.config.name == "ee":
mobie_rms = sentence["relationMentions"]
if not mobie_rms:
continue
event_mentions = []
for rm in mobie_rms:
# Find trigger in rm["args"]
trigger = None
for arg in rm["args"]:
if arg["role"] == "trigger":
trigger = arg
break
if trigger is None:
continue
trigger_start = trigger["conceptMention"]["span"]["start"]
trigger_end = trigger["conceptMention"]["span"]["end"]
trigger_text = text[trigger_start:trigger_end]
args = []
for arg in rm["args"]:
if arg["role"] == "trigger":
continue
arg_start = arg["conceptMention"]["span"]["start"]
arg_end = arg["conceptMention"]["span"]["end"]
arg_text = text[arg_start:arg_end]
args.append({
"id": arg["conceptMention"]["id"],
"text": arg_text,
"start": arg_start - sentence_start,
"end": arg_end - sentence_start,
"role": arg["role"],
"type": arg["conceptMention"]["type"]
})
event_mentions.append({
"id": rm["id"],
"trigger": {
"id": trigger["conceptMention"]["id"],
"text": trigger_text,
"start": trigger_start - sentence_start,
"end": trigger_end - sentence_start
},
"arguments": args,
"event_type": rm["name"]
})
yield sentence_id, {
"id": sentence_id,
"text": text,
"entity_mentions": entity_mentions,
"event_mentions": event_mentions
}
else:
raise ValueError("Invalid configuration name")
|