fleurs / fleurs.py
cahya's picture
rm some features
0dbeda6
# coding=utf-8
# Copyright 2022 The Google and 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.
import os
from collections import OrderedDict
# from text_processor.text_processor import TextProcessor
import datasets
logger = datasets.logging.get_logger(__name__)
""" FLEURS Dataset"""
_FLEURS_LANG_TO_ID = OrderedDict([("Afrikaans", "af"), ("Amharic", "am"), ("Arabic", "ar"), ("Armenian", "hy"), ("Assamese", "as"), ("Asturian", "ast"), ("Azerbaijani", "az"), ("Belarusian", "be"), ("Bengali", "bn"), ("Bosnian", "bs"), ("Bulgarian", "bg"), ("Burmese", "my"), ("Catalan", "ca"), ("Cebuano", "ceb"), ("Mandarin Chinese", "cmn_hans"), ("Cantonese Chinese", "yue_hant"), ("Croatian", "hr"), ("Czech", "cs"), ("Danish", "da"), ("Dutch", "nl"), ("English", "en"), ("Estonian", "et"), ("Filipino", "fil"), ("Finnish", "fi"), ("French", "fr"), ("Fula", "ff"), ("Galician", "gl"), ("Ganda", "lg"), ("Georgian", "ka"), ("German", "de"), ("Greek", "el"), ("Gujarati", "gu"), ("Hausa", "ha"), ("Hebrew", "he"), ("Hindi", "hi"), ("Hungarian", "hu"), ("Icelandic", "is"), ("Igbo", "ig"), ("Indonesian", "id"), ("Irish", "ga"), ("Italian", "it"), ("Japanese", "ja"), ("Javanese", "jv"), ("Kabuverdianu", "kea"), ("Kamba", "kam"), ("Kannada", "kn"), ("Kazakh", "kk"), ("Khmer", "km"), ("Korean", "ko"), ("Kyrgyz", "ky"), ("Lao", "lo"), ("Latvian", "lv"), ("Lingala", "ln"), ("Lithuanian", "lt"), ("Luo", "luo"), ("Luxembourgish", "lb"), ("Macedonian", "mk"), ("Malay", "ms"), ("Malayalam", "ml"), ("Maltese", "mt"), ("Maori", "mi"), ("Marathi", "mr"), ("Mongolian", "mn"), ("Nepali", "ne"), ("Northern-Sotho", "nso"), ("Norwegian", "nb"), ("Nyanja", "ny"), ("Occitan", "oc"), ("Oriya", "or"), ("Oromo", "om"), ("Pashto", "ps"), ("Persian", "fa"), ("Polish", "pl"), ("Portuguese", "pt"), ("Punjabi", "pa"), ("Romanian", "ro"), ("Russian", "ru"), ("Serbian", "sr"), ("Shona", "sn"), ("Sindhi", "sd"), ("Slovak", "sk"), ("Slovenian", "sl"), ("Somali", "so"), ("Sorani-Kurdish", "ckb"), ("Spanish", "es"), ("Swahili", "sw"), ("Swedish", "sv"), ("Tajik", "tg"), ("Tamil", "ta"), ("Telugu", "te"), ("Thai", "th"), ("Turkish", "tr"), ("Ukrainian", "uk"), ("Umbundu", "umb"), ("Urdu", "ur"), ("Uzbek", "uz"), ("Vietnamese", "vi"), ("Welsh", "cy"), ("Wolof", "wo"), ("Xhosa", "xh"), ("Yoruba", "yo"), ("Zulu", "zu")])
_FLEURS_LANG_SHORT_TO_LONG = {v: k for k, v in _FLEURS_LANG_TO_ID.items()}
_FLEURS_LANG = sorted(["af_za", "am_et", "ar_eg", "as_in", "ast_es", "az_az", "be_by", "bn_in", "bs_ba", "ca_es", "ceb_ph", "cmn_hans_cn", "yue_hant_hk", "cs_cz", "cy_gb", "da_dk", "de_de", "el_gr", "en_us", "es_419", "et_ee", "fa_ir", "ff_sn", "fi_fi", "fil_ph", "fr_fr", "ga_ie", "gl_es", "gu_in", "ha_ng", "he_il", "hi_in", "hr_hr", "hu_hu", "hy_am", "id_id", "ig_ng", "is_is", "it_it", "ja_jp", "jv_id", "ka_ge", "kam_ke", "kea_cv", "kk_kz", "km_kh", "kn_in", "ko_kr", "ckb_iq", "ky_kg", "lb_lu", "lg_ug", "ln_cd", "lo_la", "lt_lt", "luo_ke", "lv_lv", "mi_nz", "mk_mk", "ml_in", "mn_mn", "mr_in", "ms_my", "mt_mt", "my_mm", "nb_no", "ne_np", "nl_nl", "nso_za", "ny_mw", "oc_fr", "om_et", "or_in", "pa_in", "pl_pl", "ps_af", "pt_br", "ro_ro", "ru_ru", "bg_bg", "sd_in", "sk_sk", "sl_si", "sn_zw", "so_so", "sr_rs", "sv_se", "sw_ke", "ta_in", "te_in", "tg_tj", "th_th", "tr_tr", "uk_ua", "umb_ao", "ur_pk", "uz_uz", "vi_vn", "wo_sn", "xh_za", "yo_ng", "zu_za"])
_FLEURS_LONG_TO_LANG = {_FLEURS_LANG_SHORT_TO_LONG["_".join(k.split("_")[:-1]) or k]: k for k in _FLEURS_LANG}
_FLEURS_LANG_TO_LONG = {v: k for k, v in _FLEURS_LONG_TO_LANG.items()}
_FLEURS_GROUP_TO_LONG = OrderedDict({
"western_european_we": ["Asturian", "Bosnian", "Catalan", "Croatian", "Danish", "Dutch", "English", "Finnish", "French", "Galician", "German", "Greek", "Hungarian", "Icelandic", "Irish", "Italian", "Kabuverdianu", "Luxembourgish", "Maltese", "Norwegian", "Occitan", "Portuguese", "Spanish", "Swedish", "Welsh"],
"eastern_european_ee": ["Armenian", "Belarusian", "Bulgarian", "Czech", "Estonian", "Georgian", "Latvian", "Lithuanian", "Macedonian", "Polish", "Romanian", "Russian", "Serbian", "Slovak", "Slovenian", "Ukrainian"],
"central_asia_middle_north_african_cmn": ["Arabic", "Azerbaijani", "Hebrew", "Kazakh", "Kyrgyz", "Mongolian", "Pashto", "Persian", "Sorani-Kurdish", "Tajik", "Turkish", "Uzbek"],
"sub_saharan_african_ssa": ["Afrikaans", "Amharic", "Fula", "Ganda", "Hausa", "Igbo", "Kamba", "Lingala", "Luo", "Northern-Sotho", "Nyanja", "Oromo", "Shona", "Somali", "Swahili", "Umbundu", "Wolof", "Xhosa", "Yoruba", "Zulu"],
"south_asian_sa": ["Assamese", "Bengali", "Gujarati", "Hindi", "Kannada", "Malayalam", "Marathi", "Nepali", "Oriya", "Punjabi", "Sindhi", "Tamil", "Telugu", "Urdu"],
"south_east_asian_sea": ["Burmese", "Cebuano", "Filipino", "Indonesian", "Javanese", "Khmer", "Lao", "Malay", "Maori", "Thai", "Vietnamese"],
"chinese_japanase_korean_cjk": ["Mandarin Chinese", "Cantonese Chinese", "Japanese", "Korean"],
})
_FLEURS_LONG_TO_GROUP = {a: k for k, v in _FLEURS_GROUP_TO_LONG.items() for a in v}
_FLEURS_LANG_TO_GROUP = {_FLEURS_LONG_TO_LANG[k]: v for k, v in _FLEURS_LONG_TO_GROUP.items()}
_ALL_LANG = _FLEURS_LANG
_ALL_CONFIGS = []
for langs in _FLEURS_LANG:
_ALL_CONFIGS.append(langs)
_ALL_CONFIGS.append("all")
# TODO(FLEURS)
_DESCRIPTION = "4.FLEURS is the speech version of the FLORES machine translation benchmark, covering 2000 n-way parallel sentences in n=102 languages."
_CITATION = ""
_HOMEPAGE_URL = ""
_DATA_URL = "https://storage.googleapis.com/xtreme_translations/FLEURS102/{}.tar.gz"
_METADATA_URL = "data/metadata.zip"
class FleursConfig(datasets.BuilderConfig):
"""BuilderConfig for xtreme-s"""
def __init__(
self, name, description, citation, homepage, data_url
):
super(FleursConfig, self).__init__(
name=self.name,
version=datasets.Version("2.0.0", ""),
description=self.description,
)
self.name = name
self.description = description
self.citation = citation
self.homepage = homepage
self.data_url = data_url
def _build_config(name):
return FleursConfig(
name=name,
description=_DESCRIPTION,
citation=_CITATION,
homepage=_HOMEPAGE_URL,
data_url=_DATA_URL,
)
class Fleurs(datasets.GeneratorBasedBuilder):
DEFAULT_WRITER_BATCH_SIZE = 1000
BUILDER_CONFIGS = [_build_config(name) for name in _ALL_CONFIGS]
def _info(self):
task_templates = None
langs = _ALL_CONFIGS
features = datasets.Features(
{
"path": datasets.Value("string"),
"audio": datasets.features.Audio(sampling_rate=48_000),
"sentence": datasets.Value("string"),
}
)
return datasets.DatasetInfo(
description=self.config.description + "\n" + _DESCRIPTION,
features=features,
supervised_keys=("audio", "transcription"),
homepage=self.config.homepage,
citation=self.config.citation + "\n" + _CITATION,
task_templates=task_templates,
)
# Fleurs
def _split_generators(self, dl_manager):
data_url_format = self.config.data_url
metadata_path = dl_manager.download_and_extract(_METADATA_URL)
if self.config.name == "all":
data_urls = {l: data_url_format.format(l) for l in _FLEURS_LANG}
else:
data_urls = {
self.config.name: data_url_format.format(self.config.name)
}
archive_path = dl_manager.download(data_urls)
local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else None
archive_iters = {l: dl_manager.iter_archive(v) for l,v in archive_path.items()}
audio_path = {l: os.path.join(l, "audio") for l in archive_path.keys()}
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"local_extracted_archive": local_extracted_archive,
"archive_iters": archive_iters,
"audio_path": {
l: os.path.join(v, "train") for l, v in audio_path.items()
},
"text_path": {
l: os.path.join(metadata_path, "metadata", l, "train.tsv") for l in archive_path.keys()
},
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"local_extracted_archive": local_extracted_archive,
"archive_iters": archive_iters,
"audio_path": {
l: os.path.join(v, "dev") for l, v in audio_path.items()
},
"text_path": {
l: os.path.join(metadata_path, "metadata", l, "dev.tsv") for l in archive_path.keys()
},
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"local_extracted_archive": local_extracted_archive,
"archive_iters": archive_iters,
"audio_path": {
l: os.path.join(v, "test") for l, v in audio_path.items()
},
"text_path": {
l: os.path.join(metadata_path, "metadata", l, "test.tsv") for l in archive_path.keys()
},
},
),
]
def _get_data(self, lines, lang_id):
# tp = TextProcessor()
data = {}
for line in lines:
if isinstance(line, bytes):
line = line.decode("utf-8")
(
_id,
file_name,
raw_transcription,
transcription,
_,
num_samples,
gender,
) = line.strip().split("\t")
lang_group = _FLEURS_LANG_TO_GROUP[lang_id]
data[file_name] = {
"sentence": raw_transcription,
}
return data
def _generate_examples(self, local_extracted_archive, archive_iters, audio_path, text_path):
key = 0
for lang_id, archive_iter in archive_iters.items():
with open(text_path[lang_id], encoding="utf-8") as f:
lines = f.readlines()
data = self._get_data(lines, lang_id)
for path, f in archive_iter:
path = path.split("/")[-1]
if path not in data.keys():
continue
result = data[path]
extracted_audio_path = (
os.path.join(local_extracted_archive[lang_id], audio_path[lang_id])
if local_extracted_archive is not None
else None
)
extracted_audio_path = os.path.join(extracted_audio_path, path) if extracted_audio_path else path
result["path"] = extracted_audio_path if extracted_audio_path is not None else None
result["audio"] = {"path": path, "bytes": f.read()}
yield key, result
key += 1