File size: 7,742 Bytes
a2c2ee7
 
f82bbf7
 
a2c2ee7
 
 
c4c06ef
a2c2ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed267f2
 
a2c2ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
040862e
 
 
 
 
 
 
a2c2ee7
 
 
 
 
 
 
 
 
 
 
ed267f2
a2c2ee7
 
 
 
 
c4c06ef
f82bbf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2c2ee7
ed267f2
 
a2c2ee7
 
ed267f2
 
 
c4c06ef
 
ed267f2
 
 
 
 
 
a2c2ee7
 
 
 
 
ed267f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2c2ee7
 
ed267f2
a2c2ee7
 
 
 
 
 
ed267f2
 
 
 
 
 
 
 
 
 
 
 
 
040862e
 
 
ed267f2
 
 
 
 
 
 
a2c2ee7
 
 
 
 
 
 
 
 
 
 
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
import json
import gzip
import os
from pathlib import Path

import datasets
import numpy as np
from tqdm import tqdm

logger = datasets.logging.get_logger(__name__)

_DESCRIPTION = """\
Libriheavy is a labeled version of Librilight.
This (unofficial) huggingface dataset contains the medium (4500 hours) split of the Libriheavy dataset with alignments and mel spectrograms.
"""

_URL = """\
https://github.com/k2-fsa/libriheavy
"""

_CITATION = """\
@article{kang2023libriheavy,
  title={Libriheavy: a 50,000 hours asr corpus with punctuation casing and context},
  author={Kang, Wei and Yang, Xiaoyu and Yao, Zengwei and Kuang, Fangjun and Yang, Yifan and Guo, Liyong and Lin, Long and Povey, Daniel},
  journal={arXiv preprint arXiv:2309.08105},
  year={2023}
}
"""

PATH = "./medium_data"

class LibriheavyConfig(datasets.BuilderConfig):
    """BuilderConfig for Libriheavy."""

    def __init__(self, **kwargs):
        """BuilderConfig for Libriheavy.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(LibriheavyConfig, self).__init__(**kwargs)


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

    BUILDER_CONFIGS = [
        LibriheavyConfig(name="libriheavy", version=datasets.Version("1.0.0"), description="Libriheavy dataset."),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "speaker_id": datasets.Value("string"),
                    "audio": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "word_segments": datasets.Sequence(
                        {
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32"),
                            "word": datasets.Value("string"),
                        }
                    ),
                    "phone_segments": datasets.Sequence(
                        {
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32"),
                            "phone": datasets.Value("string"),
                        }
                    ),
                    "mel_spectrogram": datasets.Sequence(datasets.Sequence(datasets.Value("float32"))),
                }
            ),
            supervised_keys=None,
            homepage=_URL,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # first, we load speaker_list.json
        speaker_list = f"{PATH}/speaker_list.json"
        speaker_list = dl_manager.download_and_extract(speaker_list)
        with open(speaker_list, "r") as f:
            speaker_list = json.load(f)
        # now we load the individual speaker metadata
        speaker_metadata = {}
        for speaker_id, metadata_path in tqdm(speaker_list.items()):
            hf_home = os.environ.get("HF_HOME", "~/.cache/huggingface")
            metadata_cache = f"hf_home/libriheavy_metadata"
            # we always cache the speaker metadata, as it is small
            if os.path.exists(f"{metadata_cache}/{speaker_id}.json"):
                with open(f"{metadata_cache}/{speaker_id}.json", "r") as f:
                    speaker_metadata[speaker_id] = json.load(f)
            else:
                Path(metadata_cache).mkdir(parents=True, exist_ok=True)
                metadata_path = f"{PATH}/{speaker_id}/{metadata_path}"
                metadata_path = dl_manager.download_and_extract(metadata_path)
                with open(metadata_path, "r") as f:
                    speaker_metadata[speaker_id] = json.load(f)
                with open(f"{metadata_cache}/{speaker_id}.json", "w") as f:
                    json.dump(speaker_metadata[speaker_id], f)

        speaker_chunks = []
        even_speaker_chunks = []
        odd_speaker_chunks = []
        for speaker_id, metadata in speaker_metadata.items():
            for chunk_id, chunk in metadata["chunks"].items():
                chunk_dict = {
                    "speaker_id": speaker_id,
                    "id": f"{speaker_id}_{chunk_id}",
                    "audio": dl_manager.download(f"{PATH}/{speaker_id}/{chunk['npz'].replace('.gz', '')}"),
                    "text": dl_manager.download(f"{PATH}/{speaker_id}/{chunk['json']}"),
                }
                speaker_chunks.append(chunk_dict)
                if int(chunk_id) % 2 == 0:
                    even_speaker_chunks.append(chunk_dict)
                else:
                    odd_speaker_chunks.append(chunk_dict)
        # shuffle the chunks
        np.random.seed(42)
        np.random.shuffle(speaker_chunks)
        return [
            datasets.SplitGenerator(
                name="train",
                gen_kwargs={"speaker_chunks": speaker_chunks, "split": "train"}
            ),
            datasets.SplitGenerator(
                name="validation",
                gen_kwargs={"speaker_chunks": speaker_chunks, "split": "validation"}
            ),
            datasets.SplitGenerator(
                name="even",
                gen_kwargs={"speaker_chunks": even_speaker_chunks, "split": "even"}
            ),
            datasets.SplitGenerator(
                name="odd",
                gen_kwargs={"speaker_chunks": odd_speaker_chunks, "split": "odd"}
            ),
        ]

    def _generate_examples(self, speaker_chunks, split):
        """Yields examples."""
        for chunk in speaker_chunks:
            npz = dict(np.load(chunk["audio"], allow_pickle=True))
            utterances = npz.keys()
            with gzip.open(chunk["text"], "rt") as f:
                text = json.load(f)
            if split in ["train", "even", "odd"]:
                for utterance_id, utterance in text.items():
                    # skip the last utterance
                    if utterance_id == sorted(list(text.keys()))[-1]:
                        continue
                    result =  {
                        "id": chunk["speaker_id"] + "_" + utterance_id,
                        "speaker_id": chunk["speaker_id"],
                        "audio": chunk["audio"],
                        "text": chunk["text"],
                        "word_segments": [
                            {"start": segment[0], "end": segment[1], "word": segment[2]} for segment in utterance["word_segments"]
                        ],
                        "phone_segments": [
                            {"start": segment[0], "end": segment[1], "word": segment[2]} for segment in utterance["phone_segments"]
                        ],
                        "mel_spectrogram": npz[str(utterance_id)].item()["mel"][0][0],
                    }
                    yield chunk["speaker_id"] + "_" + utterance_id, result
            else:
                # only use the last utterance
                utterance_id = sorted(list(text.keys()))[-1]
                utterance = text[utterance_id]
                result =  {
                    "id": chunk["speaker_id"] + "_" + utterance_id,
                    "speaker_id": chunk["speaker_id"],
                    "audio": chunk["audio"],
                    "text": chunk["text"],
                    "word_segments": [
                        {"start": segment[0], "end": segment[1], "word": segment[2]} for segment in utterance["word_segments"]
                    ],
                    "mel_spectrogram": npz[str(utterance_id)].item()["mel"][0][0],
                }
                yield chunk["speaker_id"] + "_" + utterance_id, result