Datasets:

ArXiv:
License:
IN22-Gen / IN22-Gen.py
jaygala24's picture
Upload IN22-Gen.py with huggingface_hub
1924d9e
raw
history blame
7.63 kB
# coding=utf-8
"""The IN-22 Gen Evaluation Benchmark for evaluation of Machine Translation for Indic Languages."""
import os
import sys
import datasets
from typing import Union, List, Optional
_CITATION = """
@article{ai4bharat2023indictrans2,
title = {IndicTrans2: Towards High-Quality and Accessible Machine Translation Models for all 22 Scheduled Indian Languages},
author = {AI4Bharat and Jay Gala and Pranjal A. Chitale and Raghavan AK and Sumanth Doddapaneni and Varun Gumma and Aswanth Kumar and Janki Nawale and Anupama Sujatha and Ratish Puduppully and Vivek Raghavan and Pratyush Kumar and Mitesh M. Khapra and Raj Dabre and Anoop Kunchukuttan},
year = {2023},
journal = {arXiv preprint arXiv: 2305.16307}
}
"""
_DESCRIPTION = """\
IN-22 is a newly created comprehensive benchmark for evaluating machine translation performance in multi-domain, n-way parallel contexts across 22 Indic languages.
IN22-Gen is a general-purpose multi-domain evaluation subset of IN22. It has been created from two sources: Wikipedia and Web Sources offering diverse content spanning news, entertainment, culture, legal, and India-centric topics.
"""
_HOMEPAGE = "https://github.com/AI4Bharat/IndicTrans2"
_LICENSE = "CC-BY-4.0"
_LANGUAGES = [
"asm_Beng", "ben_Beng", "brx_Deva",
"doi_Deva", "eng_Latn", "gom_Deva",
"guj_Gujr", "hin_Deva", "kan_Knda",
"kas_Arab", "mai_Deva", "mal_Mlym",
"mar_Deva", "mni_Beng", "mni_Mtei",
"npi_Deva", "ory_Orya", "pan_Guru",
"san_Deva", "sat_Olck", "snd_Arab",
"snd_Deva", "tam_Taml", "tel_Telu",
"urd_Arab"
]
_URL = "https://indictrans2-public.objectstore.e2enetworks.net/IN22_benchmark.tar.gz"
_SPLITS = ["gen"]
_SENTENCES_PATHS = {
lang: {
split: os.path.join("IN22_benchmark", split, f"test.{lang}")
for split in _SPLITS
} for lang in _LANGUAGES
}
_METADATA_PATHS = {
split: os.path.join("IN22_benchmark", f"metadata_{split}.tsv")
for split in _SPLITS
}
from itertools import permutations
def _pairings(iterable, r=2):
previous = tuple()
for p in permutations(sorted(iterable), r):
if p > previous:
previous = p
yield p
class IN22GenConfig(datasets.BuilderConfig):
"""BuilderConfig for the IN-22 Gen evaluation subset."""
def __init__(self, lang: str, lang2: str = None, **kwargs):
"""
Args:
**kwargs: keyword arguments forwarded to super.
"""
super().__init__(version=datasets.Version("1.0.0"), **kwargs)
self.lang = lang
self.lang2 = lang2
class IN22Gen(datasets.GeneratorBasedBuilder):
"""IN-22 Gen evaluation subset."""
BUILDER_CONFIGS = [
IN22GenConfig(
name=lang,
description=f"IN-22: {lang} subset.",
lang=lang
)
for lang in _LANGUAGES
] + [
IN22GenConfig(
name="all",
description=f"IN-22: all language pairs",
lang=None
)
] + [
IN22GenConfig(
name=f"{l1}-{l2}",
description=f"IN-22: {l1}-{l2} aligned subset.",
lang=l1,
lang2=l2
) for (l1,l2) in _pairings(_LANGUAGES)
]
def _info(self):
features = {
"id": datasets.Value("int32"),
"context": datasets.Value("string"),
"source": datasets.Value("string"),
"url": datasets.Value("string"),
"domain": datasets.Value("string"),
"num_words": datasets.Value("int32"),
"bucket": datasets.Value("string")
}
if self.config.name != "all" and "-" not in self.config.name:
features["sentence"] = datasets.Value("string")
elif "-" in self.config.name:
for lang in [self.config.lang, self.config.lang2]:
features[f"sentence_{lang}"] = datasets.Value("string")
else:
for lang in _LANGUAGES:
features[f"sentence_{lang}"] = datasets.Value("string")
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(features),
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
dl_dir = dl_manager.download_and_extract(_URL)
def _get_sentence_paths(split):
if isinstance(self.config.lang, str) and isinstance(self.config.lang2, str):
sentence_paths = [os.path.join(dl_dir, _SENTENCES_PATHS[lang][split]) for lang in (self.config.lang, self.config.lang2)]
elif isinstance(self.config.lang, str):
sentence_paths = os.path.join(dl_dir, _SENTENCES_PATHS[self.config.lang][split])
else:
sentence_paths = [os.path.join(dl_dir, _SENTENCES_PATHS[lang][split]) for lang in _LANGUAGES]
return sentence_paths
return [
datasets.SplitGenerator(
name=split,
gen_kwargs={
"sentence_paths": _get_sentence_paths(split),
"metadata_path": os.path.join(dl_dir, _METADATA_PATHS[split]),
}
) for split in _SPLITS
]
def _generate_examples(self, sentence_paths: Union[str, List[str]], metadata_path: str, langs: Optional[List[str]] = None):
"""Yields examples as (key, example) tuples."""
if isinstance(sentence_paths, str):
with open(sentence_paths, "r") as sentences_file:
with open(metadata_path, "r") as metadata_file:
metadata_lines = [l.strip() for l in metadata_file.readlines()[1:]]
for id_, (sentence, metadata) in enumerate(
zip(sentences_file, metadata_lines)
):
sentence = sentence.strip()
metadata = metadata.split("\t")
yield id_, {
"id": id_ + 1,
"sentence": sentence,
"context": metadata[0],
"source": metadata[1],
"url": metadata[2],
"domain": metadata[3],
"num_words": metadata[4],
"bucket": metadata[5]
}
else:
sentences = {}
if len(sentence_paths) == len(_LANGUAGES):
langs = _LANGUAGES
else:
langs = [self.config.lang, self.config.lang2]
for path, lang in zip(sentence_paths, langs):
with open(path, "r") as sent_file:
sentences[lang] = [l.strip() for l in sent_file.readlines()]
with open(metadata_path, "r") as metadata_file:
metadata_lines = [l.strip() for l in metadata_file.readlines()[1:]]
for id_, metadata in enumerate(metadata_lines):
metadata = metadata.split("\t")
yield id_, {
**{
"id": id_ + 1,
"context": metadata[0],
"source": metadata[1],
"url": metadata[2],
"domain": metadata[3],
"num_words": metadata[4],
"bucket": metadata[5]
}, **{
f"sentence_{lang}": sentences[lang][id_]
for lang in langs
}
}