File size: 13,026 Bytes
1ea004e
 
 
 
 
 
 
 
 
 
a2a5bf1
1ea004e
 
 
81c31e0
1ea004e
 
 
 
 
 
 
 
898401c
 
81c31e0
1d975f5
40c9827
898401c
81c31e0
 
 
 
1ea004e
 
 
898401c
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c31e0
1ea004e
 
898401c
 
1ea004e
 
898401c
1ea004e
 
 
 
898401c
1ea004e
 
 
 
81c31e0
1ea004e
81c31e0
 
 
1ea004e
81c31e0
 
 
 
1ea004e
898401c
 
1ea004e
 
898401c
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c31e0
1ea004e
 
 
 
 
 
898401c
1ea004e
 
 
 
 
 
 
 
 
 
81c31e0
 
1ea004e
 
 
81c31e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ea004e
 
 
 
 
 
81c31e0
 
 
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c31e0
1ea004e
 
93891ff
81c31e0
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c31e0
 
 
1ea004e
1d975f5
 
 
 
1ea004e
 
93891ff
1ea004e
 
 
 
1d975f5
 
 
1ea004e
 
81c31e0
 
 
 
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81c31e0
1ea004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c9827
1ea004e
 
 
 
 
 
 
 
 
 
 
81c31e0
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""LibriTTS dataset with forced alignments."""

import os
from pathlib import Path
import hashlib
import pickle

import datasets
import pandas as pd
import numpy as np
from alignments.datasets.librispeech import LibrittsDataset
from tqdm.contrib.concurrent import process_map
from tqdm.auto import tqdm
from multiprocessing import cpu_count
import multiprocessing as mp
from phones.convert import Converter
import torchaudio
import torchaudio.transforms as AT

logger = datasets.logging.get_logger(__name__)

_PHONESET = "arpabet"

_VERBOSE = os.environ.get("LIBRITTS_VERBOSE", True)
_MAX_WORKERS = os.environ.get("LIBRITTS_MAX_WORKERS", cpu_count())
_MAX_WORKERS = int(_MAX_WORKERS)
_NO_MP = _MAX_WORKERS <= 1
_MAX_PHONES = os.environ.get("LIBRITTS_MAX_PHONES", 512)
_PATH = os.environ.get("LIBRITTS_PATH", os.environ.get("HF_DATASETS_CACHE", None))
_DOWNLOAD_SPLITS = os.environ.get(
    "LIBRITTS_DOWNLOAD_SPLITS",
    "train-clean-100,train-clean-360,train-other-500,dev-clean,dev-other,test-clean,test-other",
).split(",")
if _PATH is not None and not os.path.exists(_PATH):
    os.makedirs(_PATH)

_VERSION = "1.0.1"

_CITATION = """\
@article{zen2019libritts,
  title={LibriTTS: A Corpus Derived from LibriSpeech for Text-to-Speech},
  author={Zen, Heiga and Dang, Viet and Clark, Rob and Zhang, Yu and Weiss, Ron J and Jia, Ye and Chen, Zhifeng and Wu, Yonghui},
  journal={Interspeech},
  year={2019}
}
@article{https://doi.org/10.48550/arxiv.2211.16049,
  author = {Minixhofer, Christoph and Klejch, Ondřej and Bell, Peter},
  title = {Evaluating and reducing the distance between synthetic and real speech distributions},
  year = {2022}
}
"""

_DESCRIPTION = """\
Dataset used for loading TTS spectrograms and waveform audio with alignments and a number of configurable "measures", which are extracted from the raw audio.
"""

_URL = "https://www.openslr.org/resources/60/"
_URLS = {
    "dev-clean": _URL + "dev-clean.tar.gz",
    "dev-other": _URL + "dev-other.tar.gz",
    "test-clean": _URL + "test-clean.tar.gz",
    "test-other": _URL + "test-other.tar.gz",
    "train-clean-100": _URL + "train-clean-100.tar.gz",
    "train-clean-360": _URL + "train-clean-360.tar.gz",
    "train-other-500": _URL + "train-other-500.tar.gz",
}
_URLS = {k: v for k, v in _URLS.items() if k in _DOWNLOAD_SPLITS}


class LibriTTSAlignConfig(datasets.BuilderConfig):
    """BuilderConfig for LibriTTSAlign."""

    def __init__(self, sampling_rate=22050, hop_length=256, win_length=1024, **kwargs):
        """BuilderConfig for LibriTTSAlign.

        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(LibriTTSAlignConfig, self).__init__(**kwargs)

        self.sampling_rate = sampling_rate
        self.hop_length = hop_length
        self.win_length = win_length

        if _PATH is None:
            raise ValueError(
                "Please set the environment variable LIBRITTS_PATH to point to the LibriTTS dataset directory."
            )
        elif _PATH == os.environ.get("HF_DATASETS_CACHE", None):
            logger.warning(
                "Please set the environment variable LIBRITTS_PATH to point to the LibriTTS dataset directory. Using HF_DATASETS_CACHE as a fallback."
            )


class LibriTTSAlign(datasets.GeneratorBasedBuilder):
    """LibriTTSAlign dataset."""

    BUILDER_CONFIGS = [
        LibriTTSAlignConfig(
            name="libritts",
            version=datasets.Version(_VERSION, ""),
        ),
    ]

    def _info(self):
        features = {
            "id": datasets.Value("string"),
            "speaker": datasets.Value("string"),
            "text": datasets.Value("string"),
            "start": datasets.Value("float32"),
            "end": datasets.Value("float32"),
            # phone features
            "phones": datasets.Sequence(datasets.Value("string")),
            "phone_durations": datasets.Sequence(datasets.Value("int32")),
            # audio feature
            "audio": datasets.Value("string"),
        }

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(features),
            supervised_keys=None,
            homepage="https://github.com/MiniXC/MeasureCollator",
            citation=_CITATION,
            task_templates=None,
        )

    def _split_generators(self, dl_manager):
        ds_dict = {}
        for name, url in _URLS.items():
            ds_dict[name] = self._create_alignments_ds(name, url)
        splits = [
            datasets.SplitGenerator(
                name=key.replace("-", "."), gen_kwargs={"ds": self._create_data(value)}
            )
            for key, value in ds_dict.items()
        ]
        # dataframe with all data
        data_train, data_dev, data_test, data_all = None, None, None, None
        if (
            "train-clean-100" in _URLS
            and "train-clean-360" in _URLS
            and "train-other-500" in _URLS
        ):
            data_train = self._create_data(
                [
                    ds_dict["train-clean-100"],
                    ds_dict["train-clean-360"],
                    ds_dict["train-other-500"],
                ]
            )
        if "dev-clean" in _URLS and "dev-other" in _URLS:
            data_dev = self._create_data([ds_dict["dev-clean"], ds_dict["dev-other"]])
        if "test-clean" in _URLS and "test-other" in _URLS:
            data_test = self._create_data(
                [ds_dict["test-clean"], ds_dict["test-other"]]
            )
        if (
            "train-clean-100" in _URLS
            and "train-clean-360" in _URLS
            and "train-other-500" in _URLS
            and "dev-clean" in _URLS
            and "dev-other" in _URLS
            and "test-clean" in _URLS
            and "test-other" in _URLS
        ):
            data_all = pd.concat([data_train, data_dev, data_test])
        if data_all is not None:
            splits.append(
                datasets.SplitGenerator(
                    name="train.all",
                    gen_kwargs={
                        "ds": data_all,
                    },
                )
            )
        if data_dev is not None:
            splits.append(
                datasets.SplitGenerator(
                    name="dev.all",
                    gen_kwargs={
                        "ds": data_dev,
                    },
                )
            )
        if data_test is not None:
            splits.append(
                datasets.SplitGenerator(
                    name="test.all",
                    gen_kwargs={
                        "ds": data_test,
                    },
                )
            )
        if data_dev is not None and data_all is not None:
            # move last row for each speaker from data_all to dev dataframe
            data_dev = data_all.copy()
            data_dev = data_dev.sort_values(by=["speaker", "audio"])
            data_dev = data_dev.groupby("speaker").tail(1)
            data_dev = data_dev.reset_index()
            # remove last row for each speaker from data_all
            data_all = data_all[~data_all["audio"].isin(data_dev["audio"])]
            splits += [
                datasets.SplitGenerator(
                    name="train",
                    gen_kwargs={
                        "ds": data_all,
                    },
                ),
                datasets.SplitGenerator(
                    name="dev",
                    gen_kwargs={
                        "ds": data_dev,
                    },
                ),
            ]
        self.alignments_ds = None
        self.data = None
        return splits

    def _create_alignments_ds(self, name, url):
        self.empty_textgrids = 0
        ds_hash = hashlib.md5(
            os.path.join(_PATH, f"{name}-alignments").encode()
        ).hexdigest()
        pkl_path = os.path.join(_PATH, f"{ds_hash}.pkl")
        if os.path.exists(pkl_path):
            ds = pickle.load(open(pkl_path, "rb"))
        else:
            tgt_dir = os.path.join(_PATH, f"{name}-alignments")
            src_dir = os.path.join(_PATH, f"{name}-data")
            if os.path.exists(tgt_dir):
                src_dir = None
                url = None
            if os.path.exists(src_dir):
                url = None
            ds = LibrittsDataset(
                target_directory=tgt_dir,
                source_directory=src_dir,
                source_url=url,
                textgrid_url=f"https://huggingface.co/datasets/cdminix/libritts-aligned/resolve/main/data/{name.replace('-', '_')}.tar.gz",
                verbose=_VERBOSE,
                tmp_directory=os.path.join(_PATH, f"{name}-tmp"),
                chunk_size=100,
                n_workers=_MAX_WORKERS,
            )
            pickle.dump(ds, open(pkl_path, "wb"))
        return ds, ds_hash

    def _create_data(self, data):
        entries = []
        self.phone_cache = {}
        self.phone_converter = Converter()
        if not isinstance(data, list):
            data = [data]
        hashes = [ds_hash for ds, ds_hash in data]
        ds = [ds for ds, ds_hash in data]
        self.ds = ds
        del data
        for i, ds in enumerate(ds):
            if os.path.exists(os.path.join(_PATH, f"{hashes[i]}-entries.pkl")):
                add_entries = pickle.load(
                    open(os.path.join(_PATH, f"{hashes[i]}-entries.pkl"), "rb")
                )
            else:
                if _NO_MP:
                    _entries = [self._create_entry(x) for x in tqdm(zip([i] * len(ds), np.arange(len(ds))), desc=f"processing dataset {hashes[i]}")]
                else:
                    _entries = process_map(
                        self._create_entry,
                        zip([i] * len(ds), np.arange(len(ds))),
                        chunksize=100,
                        max_workers=_MAX_WORKERS,
                        desc=f"processing dataset {hashes[i]}",
                        tqdm_class=tqdm,
                    )
                add_entries = [
                    entry
                    for entry in _entries
                    if entry is not None
                ]
                pickle.dump(
                    add_entries,
                    open(os.path.join(_PATH, f"{hashes[i]}-entries.pkl"), "wb"),
                )
            entries += add_entries
        if self.empty_textgrids > 0:
            logger.warning(f"Found {self.empty_textgrids} empty textgrids")
        return pd.DataFrame(
            entries,
            columns=[
                "phones",
                "duration",
                "start",
                "end",
                "audio",
                "speaker",
                "text",
                "basename",
            ],
        )
        del self.ds, self.phone_cache, self.phone_converter

    def _create_entry(self, dsi_idx):
        dsi, idx = dsi_idx
        item = self.ds[dsi][idx]
        start, end = item["phones"][0][0], item["phones"][-1][1]

        phones = []
        durations = []

        for i, p in enumerate(item["phones"]):
            s, e, phone = p
            phone.replace("ˌ", "")
            r_phone = phone.replace("0", "").replace("1", "")
            if len(r_phone) > 0:
                phone = r_phone
            if "[" not in phone:
                o_phone = phone
                if o_phone not in self.phone_cache:
                    phone = self.phone_converter(phone, _PHONESET, lang=None)[0]
                    self.phone_cache[o_phone] = phone
                phone = self.phone_cache[o_phone]
            phones.append(phone)
            durations.append(
                int(
                    np.round(e * self.config.sampling_rate / self.config.hop_length)
                    - np.round(s * self.config.sampling_rate / self.config.hop_length)
                )
            )

        if start >= end:
            self.empty_textgrids += 1
            return None

        return (
            phones,
            durations,
            start,
            end,
            item["wav"],
            str(item["speaker"]).split("/")[-1],
            item["transcript"],
            Path(item["wav"]).name,
        )

    def _generate_examples(self, ds):
        j = 0
        for i, row in ds.iterrows():
            # 10kB is the minimum size of a wav file for our purposes
            if Path(row["audio"]).stat().st_size >= 10_000:
                if len(row["phones"]) < _MAX_PHONES:
                    result = {
                        "id": row["basename"],
                        "speaker": row["speaker"],
                        "text": row["text"],
                        "start": row["start"],
                        "end": row["end"],
                        "phones": row["phones"],
                        "phone_durations": row["duration"],
                        "audio": str(row["audio"]),
                    }
                    yield j, result
                    j += 1