mobie / mobie.py
phucdev's picture
Fix doc with faulty spans and add more information to example
7188b32
raw
history blame
26.7 kB
# 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
def find_concept_mention_token_offsets(sentence, concept_mention):
arg_char_start = concept_mention["span"]["start"]
arg_char_end = concept_mention["span"]["end"]
arg_start = -1
arg_end = -1
for idx, token in enumerate(sentence["tokens"]):
if token["span"]["start"] == arg_char_start:
arg_start = idx
if token["span"]["end"] == arg_char_end:
arg_end = idx+1
assert arg_start != -1 and arg_end != -1, f"Could not find token offsets for {concept_mention['id']}"
return arg_start, arg_end
def fix_doc(doc):
"""Fix document with faulty spans. REMOVE IF FIXED IN DATASET!"""
if doc["id"] == "1111185208647274501":
offset = 0
# Fix token spans
tokens = doc["tokens"]["array"]
for idx, token in enumerate(tokens):
if idx == 6:
offset += 1
token["span"]["start"] -= offset
if idx == 3:
offset += 1
token["span"]["end"] -= offset
# Fix concept mentions and relation mentions
offset = 0
concept_mentions = doc["conceptMentions"]["array"]
for idx, cm in enumerate(concept_mentions):
if idx == 1 or idx == 2:
offset += 1
cm["span"]["start"] -= offset
cm["span"]["end"] -= offset
rm = doc["relationMentions"]["array"][0]
rm["span"]["start"] -= 1
rm["span"]["end"] -= 2
rm["args"]["array"][0]["conceptMention"]["span"]["start"] -= 1
rm["args"]["array"][0]["conceptMention"]["span"]["end"] -= 1
rm["args"]["array"][1]["conceptMention"]["span"]["start"] -= 2
rm["args"]["array"][1]["conceptMention"]["span"]["end"] -= 2
doc["tokens"]["array"] = tokens
doc["sentences"]["array"][0]["span"]["end"] -= 2
doc["sentences"]["array"][0]["tokens"]["array"] = tokens[:20]
doc["sentences"]["array"][0]["conceptMentions"]["array"] = concept_mentions[:-1]
doc["sentences"]["array"][0]["relationMentions"]["array"] = [rm]
doc["sentences"]["array"][1]["span"]["start"] -= 2
doc["sentences"]["array"][1]["span"]["end"] -= 2
doc["sentences"]["array"][1]["tokens"]["array"] = tokens[20:]
doc["sentences"]["array"][1]["conceptMentions"]["array"] = [concept_mentions[-1]]
print("Fixed spans")
return doc
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")
}
]
}
]
prefixes = ["B", "I"]
ner_tags = ["O"] + [f"{prefix}-{label}" for prefix in prefixes for label in labels]
if self.config.name == "ner":
features = datasets.Features(
{
"id": datasets.Value("string"),
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=ner_tags
)
),
}
)
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"
]
),
}
],
"tokens": datasets.Sequence(datasets.Value("string")),
"pos_tags": datasets.Sequence(datasets.Value("string")),
"lemma": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(datasets.features.ClassLabel(names=ner_tags))
}
)
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):
if doc["id"] == "1111185208647274501":
doc = fix_doc(doc)
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)
if doc["id"] == "1111185208647274501":
doc = fix_doc(doc)
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:
char_start = cm["span"]["start"]
char_end = cm["span"]["end"]
# Find token offsets for entity mentions
start, end = find_concept_mention_token_offsets(sentence, cm)
cm_text = text[char_start:char_end]
entity_id = "NIL"
for refid in cm["refids"]:
if refid["key"] == "osm_id":
entity_id = refid["value"]
break
entity_mentions.append({
"text": cm_text,
"start": start,
"end": end,
"char_start": char_start - sentence_start,
"char_end": char_end - sentence_start,
"type": cm["type"],
"entity_id": entity_id,
"refids": [
{
"key": refid["key"],
"value": refid["value"]
} for refid in cm["refids"]
] if "refids" in cm and cm["refids"] else []
})
tokens = []
lemmas = []
ner_tags = []
pos_tags = []
for token in sentence["tokens"]:
token_text = text[token["span"]["start"]:token["span"]["end"]]
tokens.append(token_text)
lemmas.append(token["lemma"])
ner_tags.append(token["ner"])
pos_tags.append(token["posTag"])
if self.config.name == "el":
yield sentence_id, {
"id": sentence_id,
"text": text,
"tokens": tokens,
"entity_mentions": entity_mentions
}
elif self.config.name == "re":
mobie_rms = sentence["relationMentions"]
if not mobie_rms:
continue
entities = []
entity_types = []
entity_ids = []
for cm in entity_mentions:
entities.append([cm["start"], cm["end"]])
entity_types.append(cm["type"])
entity_ids.append(cm["entity_id"])
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 positions
cm = arg["conceptMention"]
start, end = find_concept_mention_token_offsets(sentence, cm)
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_char_start = trigger["conceptMention"]["span"]["start"]
trigger_char_end = trigger["conceptMention"]["span"]["end"]
trigger_start, trigger_end = find_concept_mention_token_offsets(sentence, trigger["conceptMention"])
trigger_text = text[trigger_char_start:trigger_char_end]
args = []
for arg in rm["args"]:
if arg["role"] == "trigger":
continue
arg_char_start = arg["conceptMention"]["span"]["start"]
arg_char_end = arg["conceptMention"]["span"]["end"]
arg_start = -1
arg_end = -1
for idx, token in enumerate(sentence["tokens"]):
if token["span"]["start"] == arg_char_start:
arg_start = idx
if token["span"]["end"] == arg_char_end:
arg_end = idx+1
assert arg_start != -1 and arg_end != -1, f"Could not find token offsets for {arg['conceptMention']['id']}"
arg_text = text[arg_char_start:arg_char_end]
args.append({
"id": arg["conceptMention"]["id"],
"text": arg_text,
"start": arg_start,
"end": arg_end,
"char_start": arg_char_start - sentence_start,
"char_end": arg_char_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,
"end": trigger_end,
"char_start": trigger_char_start - sentence_start,
"char_end": trigger_char_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,
"tokens": tokens,
"pos_tags": pos_tags,
"lemma": lemmas,
"ner_tags": ner_tags
}
else:
raise ValueError("Invalid configuration name")