import os import tempfile from pathlib import Path from typing import Iterable, Tuple, List 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" def tokens_with_tags_to_spans(tags: Iterable[str], tokens: Iterable[str]) -> List[ Tuple[str, int, int]]: """ Convert a list of tokens and tags to a list of spans for BIOSE/BIOLU schemes tags. Args: tags: list of entities tags tokens: list of tokens Note that the end index returned by this function is exclusive. No, need to increment the end by 1. Returns: list of {span, start, end, entity, start_char, end_char} where span is a phrase/tokens, start and end are the indices of the span, entity is the entity type, and start_char and end_char are the start and end characters of the span. """ entities = [] start = None start_char = None words = [] curr_pos = 0 for i, (tag, token) in enumerate(zip(tags, tokens)): if tag is None or tag.startswith("-"): if start is not None: start = None start_char = None words = [] else: end_pos = curr_pos + len(token) words.append(token) entities.append({ "entity": "", "span": " ".join(words), "start": i, "end": i + 1, "start_char": curr_pos, "end_char": end_pos }) elif tag.startswith("O"): pass elif tag.startswith("I"): words.append(token) if start is None: raise ValueError( "Invalid BILUO tag sequence: Got a tag starting with {start} " "without a preceding 'B' (beginning of an entity). " "Tag sequence:\n{tags}".format(start="I", tags=list(tags)[: i + 1]) ) elif tag.startswith("U") or tag.startswith("S"): end_pos = curr_pos + len(token) entities.append({ "entity": tag[2:], "span": token, "start": i, "end": i + 1, "start_char": curr_pos, "end_char": end_pos }) elif tag.startswith("B"): start = i start_char = curr_pos words.append(token) elif tag.startswith("L") or tag.startswith("E"): if start is None: raise ValueError( "Invalid BILUO tag sequence: Got a tag starting with {start} " "without a preceding 'B' (beginning of an entity). " "Tag sequence:\n{tags}".format(start="L", tags=list(tags)[: i + 1]) ) end_pos = curr_pos + len(token) words.append(token) entities.append({ "entity": tag[2:], "span": " ".join(words), "start": start, "end": i + 1, "start_char": start_char, "end_char": end_pos }) start = None start_char = None words = [] else: raise ValueError("Invalid BILUO tag: '{}'.".format(tag)) curr_pos += len(token) + len(" ") return entities class NemoCorpusConfig(datasets.BuilderConfig): """BuilderConfig for NemoCorpus""" def __init__(self, name): """BuilderConfig for flat Nemo corpus. Args: **kwargs: keyword arguments forwarded to super. """ version = datasets.Version("1.0.0") description = "Nemo corpus dataset" self.name = name self.dataset_type = name.split("-")[-1] self.is_nested = False super(NemoCorpusConfig, self).__init__(version=version, description=description, name=name) self.features = datasets.Features( { "id": datasets.Value("string"), "tokens": datasets.Sequence(datasets.Value("string")), "sentence": datasets.Value("string"), "raw_tags": 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'] ) ), # "spans": datasets.Sequence({ # "span": datasets.Value("string"), # "start": datasets.Value("int32"), # "end": datasets.Value("int32"), # "entity": datasets.Value("string"), # "start_char": datasets.Value("int32"), # "end_char": datasets.Value("int32"), # }) } ) def get_datafiles(self, folder): data_prefix = "morph" if self.dataset_type == "morph" else "token-single" return { "train": folder / f"{data_prefix}_gold_train.bmes", "validation": folder / f"{data_prefix}_gold_dev.bmes", "test": folder / f"{data_prefix}_gold_test.bmes", } def _generate_examples(self, filepath, sep=" "): logger.info("⏳ Generating examples from = %s", filepath) with open(filepath, encoding="utf-8") as f: guid = 0 tokens = [] ner_tags = [] raw_tags = [] for line in f: line = line.strip() if line.startswith("-DOCSTART-") or line == "" or line == "\n": if tokens: yield guid, { "id": str(guid), "sentence": " ".join(tokens), "tokens": tokens, "raw_tags": raw_tags, "ner_tags": ner_tags, # "spans": tokens_with_tags_to_spans(ner_tags, tokens) } guid += 1 tokens = [] ner_tags = [] raw_tags = [] else: splits = line.split(sep) # token-single contains errors in the data, so need to split it a bit differently rather than just space tag = splits[-1].rstrip() token = line[:-len(tag)].strip() tokens.append(token) raw_tags.append(tag) ner_tags.append(tag) if tokens: yield guid, { "id": str(guid), "sentence": " ".join(tokens), "tokens": tokens, "raw_tags": raw_tags, "ner_tags": ner_tags, # "spans": tokens_with_tags_to_spans(ner_tags, tokens) } class NemoCorpusNestedConfig(datasets.BuilderConfig): """BuilderConfig for NemoCorpus""" def __init__(self, name): """BuilderConfig for nested NemoCorpus. Args: **kwargs: keyword arguments forwarded to super. """ version = datasets.Version("1.0.0") description = "Nemo corpus dataset" self.name = name self.dataset_type = name.split("-")[-1] self.is_nested = True 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)), } ) def get_datafiles(self, folder): data_prefix = "morph" if self.dataset_type == "morph" else "token-single" folder = folder / "nested" return { "train": folder / f"{data_prefix}_gold_train.bmes", "validation": folder / f"{data_prefix}_gold_dev.bmes", "test": folder / f"{data_prefix}_gold_test.bmes" } def _generate_examples(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) tags_line = splits[-4:] token_line = line[:-len(sep.join(tags_line))].strip() tokens.append(token_line) tag1, tag2, tag3, tag4 = tags_line ner_tags.append(tag1.rstrip()) ner_tags_2.append(tag2.rstrip()) ner_tags_3.append(tag3.rstrip()) ner_tags_4.append(tag4.rstrip()) 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, } class NemoCorpus(datasets.GeneratorBasedBuilder): """NemoCorpus dataset.""" DEFAULT_CONFIG_NAME = "flat_token" BUILDER_CONFIGS = [ NemoCorpusConfig("flat_token"), NemoCorpusNestedConfig("nested_token"), NemoCorpusConfig("flat_morph"), NemoCorpusNestedConfig("nested_morph") ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # dirname = tempfile.TemporaryDirectory().name # os.makedirs(dirname, exist_ok=True) # os.system(f"cd {dirname} && git clone --depth=1 {URL}") # self.repo_folder = Path(dirname) / "NEMO-Corpus" / "data" / "spmrl" / "gold" self.repo_folder = Path("data") / "spmrl" / "gold" 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.""" data_files = self.config.get_datafiles(self.repo_folder) data_files = dl_manager.download_and_extract(data_files) 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=" "): yield from self.config._generate_examples(filepath, sep)