#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile from pathlib import Path import datasets logger = datasets.logging.get_logger(__name__) _CITATION = """@article{10.1162/tacl_a_00404, author = {Bareket, Dan and Tsarfaty, Reut}, title = "{Neural Modeling for Named Entities and Morphology (NEMO2)}", journal = {Transactions of the Association for Computational Linguistics}, volume = {9}, pages = {909-928}, year = {2021}, month = {09}, abstract = "{Named Entity Recognition (NER) is a fundamental NLP task, commonly formulated as classification over a sequence of tokens. Morphologically rich languages (MRLs) pose a challenge to this basic formulation, as the boundaries of named entities do not necessarily coincide with token boundaries, rather, they respect morphological boundaries. To address NER in MRLs we then need to answer two fundamental questions, namely, what are the basic units to be labeled, and how can these units be detected and classified in realistic settings (i.e., where no gold morphology is available). We empirically investigate these questions on a novel NER benchmark, with parallel token- level and morpheme-level NER annotations, which we develop for Modern Hebrew, a morphologically rich-and-ambiguous language. Our results show that explicitly modeling morphological boundaries leads to improved NER performance, and that a novel hybrid architecture, in which NER precedes and prunes morphological decomposition, greatly outperforms the standard pipeline, where morphological decomposition strictly precedes NER, setting a new performance bar for both Hebrew NER and Hebrew morphological decomposition tasks.}", issn = {2307-387X}, doi = {10.1162/tacl_a_00404}, url = {https://doi.org/10.1162/tacl\_a\_00404}, eprint = {https://direct.mit.edu/tacl/article-pdf/doi/10.1162/tacl\_a\_00404/1962472/tacl\_a\_00404.pdf}, } """ _DESCRIPTION = """\ """ URL = "https://github.com/OnlpLab/NEMO-Corpus" class NemoCorpusConfig(datasets.BuilderConfig): """BuilderConfig for NemoCorpus""" def __init__(self): """BuilderConfig for flat Nemo corpus. Args: **kwargs: keyword arguments forwarded to super. """ version = datasets.Version("1.0.0") description = "Nemo corpus dataset" name = "flat" super(NemoCorpusConfig, self).__init__(version=version, description=description, name=name) self.features = datasets.Features( { "id": datasets.Value("string"), "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel( names=['S-ANG', 'B-ANG', 'I-ANG', 'E-ANG', 'S-DUC', 'B-DUC', 'I-DUC', 'E-DUC', 'B-EVE', 'E-EVE', 'S-EVE', 'I-EVE', 'S-FAC', 'B-FAC', 'E-FAC', 'I-FAC', 'S-GPE', 'B-GPE', 'E-GPE', 'I-GPE', 'S-LOC', 'B-LOC', 'E-LOC', 'I-LOC', 'O', 'S-ORG', 'B-ORG', 'E-ORG', 'I-ORG', 'B-PER', 'I-PER', 'E-PER', 'S-PER', 'B-WOA', 'E-WOA', 'I-WOA', 'S-WOA'] ) ), } ) class NemoCorpusNestedConfig(datasets.BuilderConfig): """BuilderConfig for NemoCorpus""" def __init__(self): """BuilderConfig for nested NemoCorpus. Args: **kwargs: keyword arguments forwarded to super. """ version = datasets.Version("1.0.0") description = "Nemo corpus dataset" name = "nested" super(NemoCorpusNestedConfig, self).__init__(version=version, description=description, name=name) self.classes = ['S-ANG', 'B-ANG', 'I-ANG', 'E-ANG', 'S-DUC', 'B-DUC', 'I-DUC', 'E-DUC', 'B-EVE', 'E-EVE', 'S-EVE', 'I-EVE', 'S-FAC', 'B-FAC', 'E-FAC', 'I-FAC', 'S-GPE', 'B-GPE', 'E-GPE', 'I-GPE', 'S-LOC', 'B-LOC', 'E-LOC', 'I-LOC', 'O', 'S-ORG', 'B-ORG', 'E-ORG', 'I-ORG', 'B-PER', 'I-PER', 'E-PER', 'S-PER', 'B-WOA', 'E-WOA', 'I-WOA', 'S-WOA'] self.features = datasets.Features( { "id": datasets.Value("string"), "tokens": datasets.Sequence(datasets.Value("string")), "ner_tags": datasets.Sequence( datasets.features.ClassLabel(names=self.classes)), "ner_tags_2": datasets.Sequence( datasets.features.ClassLabel(names=self.classes)), "ner_tags_3": datasets.Sequence( datasets.features.ClassLabel(names=self.classes)), "ner_tags_4": datasets.Sequence( datasets.features.ClassLabel(names=self.classes)), } ) class NemoCorpus(datasets.GeneratorBasedBuilder): """NemoCorpus dataset.""" DEFAULT_CONFIG_NAME = "flat" BUILDER_CONFIGS = [ NemoCorpusConfig(), NemoCorpusNestedConfig() ] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=self.config.features, supervised_keys=None, homepage="https://www.cs.bgu.ac.il/~elhadad/nlpproj/naama/", citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" dirname = tempfile.TemporaryDirectory().name os.makedirs(dirname, exist_ok=True) os.system(f"cd {dirname} && git clone --depth=1 {URL} ;") folder = Path(dirname) / "NEMO-Corpus" / "data" / "spmrl" / "gold" if self.config.name == "nested": folder = folder / "nested" data_files = { "train": dl_manager.download(folder / "morph_gold_train.bmes"), "validation": dl_manager.download(folder / "morph_gold_dev.bmes"), "test": dl_manager.download(folder / "morph_gold_test.bmes"), } return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": data_files["train"]}), datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": data_files["validation"]}), datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": data_files["test"]}), ] def _generate_examples(self, filepath, sep=" "): if self.config.name == "nested": yield from self._generate_examples_nested(filepath, sep) else: yield from self._generate_examples_flat(filepath, sep) def _generate_examples_flat(self, filepath, sep=" "): logger.info("⏳ Generating examples from = %s", filepath) with open(filepath, encoding="utf-8") as f: guid = 0 tokens = [] ner_tags = [] for line in f: if line.startswith("-DOCSTART-") or line == "" or line == "\n": if tokens: yield guid, { "id": str(guid), "tokens": tokens, "ner_tags": ner_tags, } guid += 1 tokens = [] ner_tags = [] else: splits = line.split(sep) tokens.append(splits[0]) ner_tags.append(splits[1].rstrip()) # last example yield guid, { "id": str(guid), "tokens": tokens, "ner_tags": ner_tags, } def _generate_examples_nested(self, filepath, sep=" "): logger.info("⏳ Generating examples from = %s", filepath) with open(filepath, encoding="utf-8") as f: guid = 0 tokens = [] ner_tags = [] ner_tags_2 = [] ner_tags_3 = [] ner_tags_4 = [] for line in f: if line.startswith("-DOCSTART-") or line == "" or line == "\n": if tokens: yield guid, { "id": str(guid), "tokens": tokens, "ner_tags": ner_tags, "ner_tags_2": ner_tags_2, "ner_tags_3": ner_tags_3, "ner_tags_4": ner_tags_4, } guid += 1 tokens = [] ner_tags = [] ner_tags_2 = [] ner_tags_3 = [] ner_tags_4 = [] else: splits = line.split(sep) tokens.append(splits[0]) ner_tags.append(splits[1].rstrip()) ner_tags_2.append(splits[2].rstrip()) ner_tags_3.append(splits[3].rstrip()) ner_tags_4.append(splits[4].rstrip()) # last example yield guid, { "id": str(guid), "tokens": tokens, "ner_tags": ner_tags, "ner_tags_2": ner_tags_2, "ner_tags_3": ner_tags_3, "ner_tags_4": ner_tags_4, }