# coding=utf-8 # Copyright 2020 HuggingFace Datasets Authors. # # 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. # Lint as: python3 """MasakhaNER-X: Named Entity Recognition for African Languages""" import datasets import json logger = datasets.logging.get_logger(__name__) _CITATION = """\ @inproceedings{adelani-etal-2022-masakhaner, title = "{M}asakha{NER} 2.0: {A}frica-centric Transfer Learning for Named Entity Recognition", author = "Adelani, David and Neubig, Graham and Ruder, Sebastian and Rijhwani, Shruti and Beukman, Michael and Palen-Michel, Chester and Lignos, Constantine and Alabi, Jesujoba and Muhammad, Shamsuddeen and Nabende, Peter and Dione, Cheikh M. Bamba and Bukula, Andiswa and Mabuya, Rooweither and Dossou, Bonaventure F. P. and Sibanda, Blessing and Buzaaba, Happy and Mukiibi, Jonathan and Kalipe, Godson and Mbaye, Derguene and Taylor, Amelia and Kabore, Fatoumata and Emezue, Chris Chinenye and Aremu, Anuoluwapo and Ogayo, Perez and Gitau, Catherine and Munkoh-Buabeng, Edwin and Memdjokam Koagne, Victoire and Tapo, Allahsera Auguste and Macucwa, Tebogo and Marivate, Vukosi and Elvis, Mboning Tchiaze and Gwadabe, Tajuddeen and Adewumi, Tosin and Ahia, Orevaoghene and Nakatumba-Nabende, Joyce and Mokono, Neo Lerato and Ezeani, Ignatius and Chukwuneke, Chiamaka and Oluwaseun Adeyemi, Mofetoluwa and Hacheme, Gilles Quentin and Abdulmumin, Idris and Ogundepo, Odunayo and Yousuf, Oreen and Moteu, Tatiana and Klakow, Dietrich", booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing", month = dec, year = "2022", address = "Abu Dhabi, United Arab Emirates", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/2022.emnlp-main.298", pages = "4488--4508", abstract = "African languages are spoken by over a billion people, but they are under-represented in NLP research and development. Multiple challenges exist, including the limited availability of annotated training and evaluation datasets as well as the lack of understanding of which settings, languages, and recently proposed methods like cross-lingual transfer will be effective. In this paper, we aim to move towards solutions for these challenges, focusing on the task of named entity recognition (NER). We present the creation of the largest to-date human-annotated NER dataset for 20 African languages. We study the behaviour of state-of-the-art cross-lingual transfer methods in an Africa-centric setting, empirically demonstrating that the choice of source transfer language significantly affects performance. While much previous work defaults to using English as the source language, our results show that choosing the best transfer language improves zero-shot F1 scores by an average of 14{\%} over 20 languages as compared to using English.", } """ _DESCRIPTION = """\ MasakhaNER-X is an aggregation of MasakhaNER 1.0 and MasakhaNER 2.0 datasets for 20 African languages. The dataset is not in CoNLL format. The input is the original raw text while the output is byte-level span annotations. Example: {"example_id": "test-00015916", "language": "pcm", "text": "By Bashir Ibrahim Hassan", "spans": [{"start_byte": 3, "limit_byte": 24, "label": "PER"}], "target": "PER: Bashir Ibrahim Hassan"} MasakhaNER-X is a named entity dataset consisting of PER, ORG, LOC, and DATE entities annotated by Masakhane for twenty African languages: - Amharic - Ghomala - Bambara - Ewe - Hausa - Igbo - Kinyarwanda - Luganda - Luo - Mossi - Chichewa - Nigerian-Pidgin - chiShona - Swahili - Setswana - Twi - Wolof - Xhosa - Yoruba - Zulu The train/validation/test sets are available for all the twenty languages. For more details see https://aclanthology.org/2022.emnlp-main.298 """ _URL = "https://raw.githubusercontent.com/masakhane-io/masakhane-ner/main/xtreme-up/MasakhaNER-X/" _TRAINING_DIR = "train" _DEV_DIR = "validation" _TEST_DIR = "test" class MasakhanerConfig(datasets.BuilderConfig): """BuilderConfig for MasakhaNER-X""" def __init__(self, **kwargs): """BuilderConfig for MasakhaNER-X. Args: **kwargs: keyword arguments forwarded to super. """ super(MasakhanerConfig, self).__init__(**kwargs) class Masakhaner(datasets.GeneratorBasedBuilder): """MasakhaNER-X dataset.""" BUILDER_CONFIGS = [ MasakhanerConfig(name="am", version=datasets.Version("1.0.0"), description="MasakhaNER-X Amharic dataset"), MasakhanerConfig(name="bbj", version=datasets.Version("1.0.0"), description="MasakhaNER-X Ghomala dataset"), MasakhanerConfig(name="bm", version=datasets.Version("1.0.0"), description="MasakhaNER-X Bambara dataset"), MasakhanerConfig(name="ee", version=datasets.Version("1.0.0"), description="MasakhaNER-X Ewe dataset"), MasakhanerConfig(name="ha", version=datasets.Version("1.0.0"), description="MasakhaNER-X Hausa dataset"), MasakhanerConfig(name="ig", version=datasets.Version("1.0.0"), description="MasakhaNER-X Igbo dataset"), MasakhanerConfig(name="lg", version=datasets.Version("1.0.0"), description="MasakhaNER-X Luganda dataset"), MasakhanerConfig(name="luo", version=datasets.Version("1.0.0"), description="MasakhaNER-X Luo dataset"), MasakhanerConfig(name="mos", version=datasets.Version("1.0.0"), description="MasakhaNER-X Mossi dataset"), MasakhanerConfig(name="ny", version=datasets.Version("1.0.0"), description="MasakhaNER-X Chichewa dataset"), MasakhanerConfig( name="pcm", version=datasets.Version("1.0.0"), description="MasakhaNER-X Nigerian-Pidgin dataset" ), MasakhanerConfig(name="rw", version=datasets.Version("1.0.0"), description="MasakhaNER-X Kinyarwanda dataset"), MasakhanerConfig(name="sn", version=datasets.Version("1.0.0"), description="MasakhaNER-X chiShona dataset"), MasakhanerConfig(name="sw", version=datasets.Version("1.0.0"), description="MasakhaNER-X Swahili dataset"), MasakhanerConfig(name="tn", version=datasets.Version("1.0.0"), description="MasakhaNER-X Setswana dataset"), MasakhanerConfig(name="tw", version=datasets.Version("1.0.0"), description="MasakhaNER-X Twi dataset"), MasakhanerConfig(name="wo", version=datasets.Version("1.0.0"), description="MasakhaNER-X Wolof dataset"), MasakhanerConfig(name="xh", version=datasets.Version("1.0.0"), description="MasakhaNER-X Xhosa dataset"), MasakhanerConfig(name="yo", version=datasets.Version("1.0.0"), description="MasakhaNER-X Yoruba dataset"), MasakhanerConfig(name="zu", version=datasets.Version("1.0.0"), description="MasakhaNER-X Zulu dataset"), ] def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { "id": datasets.Value("string", id="id"), "text": datasets.Value("string", id="text"), "spans": datasets.Sequence(datasets.Value("string"), id="spans"), "target": datasets.Value("string", id="target") } ), supervised_keys=None, homepage="https://aclanthology.org/2022.emnlp-main.298", citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" urls_to_download = { "train": f"{_URL}/{_TRAINING_DIR}/{self.config.name}.jsonl", "validation": f"{_URL}/{_DEV_DIR}/{self.config.name}.jsonl", "test": f"{_URL}/{_TEST_DIR}/{self.config.name}.jsonl", } downloaded_files = dl_manager.download_and_extract(urls_to_download) return [ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}), datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["validation"]}), datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}), ] def _generate_examples(self, filepath): logger.info("⏳ Generating examples from = %s", filepath) guid = 0 # Open the JSONL file with open(filepath, encoding="utf-8") as f: for line in f: # Read each line as a JSON object data = json.loads(line.strip()) # Extract relevant fields: text, span, and target text = data.get("text", []) spans = data.get("spans", []) target = data.get("target", []) # Yield the example with the unique identifier yield guid, { "id": str(guid), "text": text, "spans": spans, "target": target, } # Increment the identifier for the next example guid += 1