File size: 6,640 Bytes
d195bbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import csv
import os
import json

import datasets
from datasets.utils.py_utils import size_str
from tqdm import tqdm

from .languages import LANGUAGES



_CITATION = """\
@inproceedings{khadka2023tts,
    title={Nepali Text-to-Speech Synthesis using Tacotron2 for Melspectrogram Generation},
    author={Khadka, Supriya and G.C., Ranju and Paudel, Prabin and Shah, Rahul and Joshi, Basanta},
    booktitle={SIGUL 2023, 2nd Annual Meeting of the Special Interest Group on Under-resourced Languages: a Satellite Workshop of Interspeech 2023},
    year={2023}
    }
"""

_HOMEPAGE = "https://https://www.openslr.org/143/"

_LICENSE = "Attribution-ShareAlike 4.0 (CC BY-NC-SA 4.0)"



_AUDIO_URL = "https://huggingface.co./datasets/SonishMaharjan/asr_nepali_0/resolve/main/audio/{lang}/{split}/{lang}_{split}_{shard_idx}.tar"

_TRANSCRIPT_URL = "https://huggingface.co./datasets/SonishMaharjan/asr_nepali_0/raw/main/transcript/{lang}/{split}.tsv"

_N_SHARDS_URL = "https://huggingface.co./datasets/SonishMaharjan/asr_nepali_0/raw/main/n_shards.json"


class CommonVoiceConfig(datasets.BuilderConfig):
    """BuilderConfig for CommonVoice."""

    def __init__(self, name, version, **kwargs):
        self.language = kwargs.pop("language", None)
        self.release_date = kwargs.pop("release_date", None)
        self.num_clips = kwargs.pop("num_clips", None)
        self.num_speakers = kwargs.pop("num_speakers", None)
        self.validated_hr = kwargs.pop("validated_hr", None)
        self.total_hr = kwargs.pop("total_hr", None)
        self.size_bytes = kwargs.pop("size_bytes", None)
        self.size_human = size_str(self.size_bytes)
        description = (
            f"Common Voice speech to text dataset in {self.language} released on {self.release_date}. "
            f"The dataset comprises {self.validated_hr} hours of validated transcribed speech data "
            f"out of {self.total_hr} hours in total from {self.num_speakers} speakers. "
            f"The dataset contains {self.num_clips} audio clips and has a size of {self.size_human}."
        )
        super(CommonVoiceConfig, self).__init__(
            name=name,
            version=datasets.Version(version),
            description=description,
            **kwargs,
        )


class CommonVoice(datasets.GeneratorBasedBuilder):
    DEFAULT_WRITER_BATCH_SIZE = 1000

    BUILDER_CONFIGS = [
        CommonVoiceConfig(
            name="asr_nepali",
            version="0.0.01",
            language="asr_nepali",
            release_date="22nov2023",
        )
    ]

    def _info(self):
        description = (
            "This dataset comprises text and speech data in Nepali, featuring both female and male voices. The dataset includes .wav files and two separate .tsv files for male and female audio. Each .tsv file contains audio_id and corresponding sentences, aligning with the audio filenames. The dataset underwent manual quality checks, although the possibility of errors remains. It was recorded to facilitate Nepali Text-to-Speech Synthesis research during the fine-tuning phase. "
        )
        features = datasets.Features(
            {
                
                "path": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=48_000),
                "transcription": datasets.Value("string"),
                
            }
        )

        return datasets.DatasetInfo(
            description=description,
            features=features,
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
            version=self.config.version,
        )

    def _split_generators(self, dl_manager):
        lang = self.config.name
        n_shards_path = dl_manager.download_and_extract(_N_SHARDS_URL)
        with open(n_shards_path, encoding="utf-8") as f:
            n_shards = json.load(f)
        audio_urls = {}
        splits = ("train", "test")
        for split in splits:
            audio_urls[split] = [
                _AUDIO_URL.format(lang=lang, split=split, shard_idx=i) for i in range(n_shards[lang][split])
            ]
        archive_paths = dl_manager.download(audio_urls)
        local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}

        meta_urls = {split: _TRANSCRIPT_URL.format(lang=lang, split=split) for split in splits}
        meta_paths = dl_manager.download_and_extract(meta_urls)

        split_generators = []
        split_names = {
            "train": datasets.Split.TRAIN,
            "test": datasets.Split.TEST,
        }
        for split in splits:
            split_generators.append(
                datasets.SplitGenerator(
                    name=split_names.get(split, split),
                    gen_kwargs={
                        "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
                        "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
                        "meta_path": meta_paths[split],
                    },
                ),
            )

        return split_generators

    def _generate_examples(self, local_extracted_archive_paths, archives, meta_path):
        data_fields = list(self._info().features.keys())
        metadata = {}
        with open(meta_path, encoding="utf-8") as f:
            reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
            for row in tqdm(reader, desc="Reading metadata..."):
                if not row["path"].endswith(".flac"):
                    row["path"] += ".flac"
                # accent -> accents in CV 8.0
                if "accents" in row:
                    row["accent"] = row["accents"]
                    del row["accents"]
                # if data is incomplete, fill with empty values
                for field in data_fields:
                    if field not in row:
                        row[field] = ""
                metadata[row["path"]] = row

        for i, audio_archive in enumerate(archives):
            for path, file in audio_archive:
                _, filename = os.path.split(path)
                if filename in metadata:
                    result = dict(metadata[filename])
                    # set the audio feature and the path to the extracted file
                    path = os.path.join(local_extracted_archive_paths[i], path) if local_extracted_archive_paths else path
                    result["audio"] = {"path": path, "bytes": file.read()}
                    result["path"] = path
                    yield path, result