# 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")