File size: 10,398 Bytes
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d9a0d
79b2661
 
 
 
 
67d9a0d
 
 
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d9a0d
 
 
 
 
 
 
 
 
 
 
 
 
79b2661
 
 
 
 
 
67d9a0d
 
 
 
 
 
 
 
 
 
 
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67d9a0d
 
 
 
 
79b2661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

PyTorch Dataset and Dynamic Batch Collator for 10M TTS.

Supports local audio/text files and direct Hugging Face Datasets.

"""

import os
from pathlib import Path, PurePosixPath, PureWindowsPath
import math
import torch
from torch.utils.data import Dataset
from typing import List, Dict, Optional

from .audio_processor import AudioProcessor
from .text_cleaner import TextTokenizer
from config import AudioConfig
from .metadata import read_manifest, TEXT_COLUMNS


class TTSDataset(Dataset):
    def __init__(

        self,

        metadata_path: Optional[str] = None,

        hf_dataset_name: Optional[str] = None,

        language: Optional[str] = None,

        speaker: Optional[str] = None,

        data_list: Optional[List[Dict[str, str]]] = None,

        audio_processor: Optional[AudioProcessor] = None,

        tokenizer: Optional[TextTokenizer] = None,

        cache_dir: Optional[str] = None,

    ):
        self.processor = audio_processor or AudioProcessor()
        self.tokenizer = tokenizer or TextTokenizer()
        self.items: List[Dict[str, str]] = []
        self.hf_dataset = None
        self.cache_dir = Path(cache_dir) if cache_dir else None
        if self.cache_dir is not None:
            self.cache_dir.mkdir(parents=True, exist_ok=True)

        self.manifest_repo = None
        self.manifest_revision = None

        if hf_dataset_name:
            self._load_from_hf(hf_dataset_name, language=language, speaker=speaker)
        elif data_list is not None:
            self.items = data_list
        elif metadata_path:
            self._load_metadata(metadata_path, language=language, speaker=speaker)

    def _load_from_hf(self, repo_id: str, language: Optional[str] = None, speaker: Optional[str] = None):
        from datasets import load_dataset, Audio
        print(f"Loading Hugging Face Dataset: {repo_id}...")
        from huggingface_hub import hf_hub_download
        from huggingface_hub.errors import EntryNotFoundError
        try:
            manifest = hf_hub_download(repo_id, "metadata.csv", repo_type="dataset")
        except EntryNotFoundError:
            manifest = None
        if manifest:
            # The project curator publishes raw audio paths beside a delimited root manifest.
            with open(manifest, encoding="utf-8-sig") as f:
                header = f.readline().strip().lower()
            if "audio_file" in header or "audio_filename" in header:
                self.items = list(read_manifest(manifest, language=language, speaker=speaker))
                self.manifest_repo = repo_id
                parent = Path(manifest).parent
                self.manifest_revision = parent.name if parent.parent.name == "snapshots" else None
                return
        ds = load_dataset(repo_id, split="train")

        lang_col = "language" if "language" in ds.column_names else ("lang" if "lang" in ds.column_names else None)
        if language and not lang_col:
            raise ValueError("Dataset has no language column to filter.")
        if language:
            ds = ds.filter(lambda value: value == language, input_columns=lang_col)
            print(f"Filtered by {lang_col}='{language}': {len(ds)} samples remain.")

        spk_col = "speaker" if "speaker" in ds.column_names else ("speaker_id" if "speaker_id" in ds.column_names else None)
        if speaker and not spk_col:
            raise ValueError("Dataset has no speaker column to filter.")
        if speaker:
            ds = ds.filter(lambda value: value == speaker, input_columns=spk_col)
            print(f"Filtered by {spk_col}='{speaker}': {len(ds)} samples remain.")

        if "audio" in ds.column_names:
            ds = ds.cast_column("audio", Audio(decode=False))

        self.hf_dataset = ds

    def _load_metadata(self, path, **filters):
        base = Path(path).parent
        missing = 0
        for row in read_manifest(path, **filters):
            audio = base / row["audio_path"]
            if audio.is_file():
                self.items.append({"audio_path": str(audio), "text": row["text"]})
            else:
                missing += 1
        if missing:
            print(f"Skipped {missing} manifest rows with missing audio files.")

    def get_approx_lengths(self) -> List[float]:
        """Returns approximate sample durations/lengths for fast length-bucketed batching."""
        if self.hf_dataset is not None:
            if "duration" in self.hf_dataset.column_names:
                return [float(d) for d in self.hf_dataset["duration"]]
            if "duration_s" in self.hf_dataset.column_names:
                return [float(d) for d in self.hf_dataset["duration_s"]]
            text_col = next((c for c in TEXT_COLUMNS if c in self.hf_dataset.column_names), None)
            if text_col:
                return [float(len(t or "")) for t in self.hf_dataset[text_col]]
            return [1.0] * len(self.hf_dataset)
        return [float(len(it.get("text", ""))) for it in self.items]

    def __len__(self) -> int:
        if self.hf_dataset is not None:
            return len(self.hf_dataset)
        return len(self.items)

    def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
        cache_path = (self.cache_dir / f"{idx}.pt") if self.cache_dir is not None else None
        if cache_path is not None and cache_path.is_file():
            cached = torch.load(cache_path, map_location="cpu", weights_only=True)
            mel = cached["mel"].float()
            text_ids = cached["text_ids"]
            return {
                "text_ids": text_ids,
                "mel": mel,
                "text_len": len(text_ids),
                "mel_len": mel.shape[-1],
            }
        if self.hf_dataset is not None:
            row = self.hf_dataset[idx]
            text = next((row[k] for k in TEXT_COLUMNS if row.get(k)), "")

            if "audio" in row and row["audio"] is not None:
                audio_info = row["audio"]
                if isinstance(audio_info, dict) and audio_info.get("bytes") is not None:
                    wav = self.processor.load_audio_bytes(audio_info["bytes"])
                    orig_sr = self.processor.config.sample_rate
                elif isinstance(audio_info, dict) and "array" in audio_info:
                    audio_arr = audio_info["array"]
                    orig_sr = audio_info["sampling_rate"]
                    wav = torch.as_tensor(audio_arr, dtype=torch.float32)
                elif isinstance(audio_info, dict) and audio_info.get("path"):
                    wav = self.processor.load_audio(audio_info["path"])
                    orig_sr = self.processor.config.sample_rate
                elif hasattr(audio_info, "get_all_samples"):
                    samples = audio_info.get_all_samples()
                    wav = samples.data.float()
                    orig_sr = samples.sample_rate
                else:
                    raise ValueError(f"Unsupported audio format in HF dataset: {type(audio_info)}")
                wav = self.processor.normalize_waveform(wav, orig_sr)
            elif "audio_file" in row:
                wav = self.processor.load_audio(row["audio_file"])
            else:
                raise ValueError("Dataset row must contain 'audio' or 'audio_file'")
        else:
            item = self.items[idx]
            text = item["text"]
            audio_path = item["audio_path"]
            if self.manifest_repo:
                from huggingface_hub import hf_hub_download
                rel = PurePosixPath(audio_path)
                if PureWindowsPath(audio_path).anchor or ".." in rel.parts or chr(92) in audio_path:
                    raise ValueError(f"Expected a repository-relative audio path: {audio_path}")
                audio_path = hf_hub_download(self.manifest_repo, str(rel), repo_type="dataset",
                                             revision=self.manifest_revision)
            wav = self.processor.load_audio(audio_path)

        if wav.numel() == 0 or wav.amax() == wav.amin():
            raise ValueError(f"Sample {idx} has no varying audio signal for its transcript.")
        mel = self.processor.wav_to_mel(wav)  # (n_mels, T_mel)
        text_ids = self.tokenizer.text_to_ids(text)  # (T_text,)
        if len(text_ids) == 0:
            raise ValueError(f"Sample at index {idx} produced empty text tokens.")

        if len(text_ids) > mel.shape[-1]:
            raise ValueError(f"Sample {idx} has {len(text_ids)} tokens but only {mel.shape[-1]} frames.")

        if cache_path is not None:
            tmp_path = cache_path.with_name(f".{idx}.{os.getpid()}.tmp")
            torch.save({"text_ids": text_ids, "mel": mel.half()}, tmp_path)
            os.replace(tmp_path, cache_path)

        return {
            "text_ids": text_ids,
            "mel": mel,
            "text_len": len(text_ids),
            "mel_len": mel.shape[-1],
        }


def collate_tts_fn(

    batch: List[Dict[str, torch.Tensor]],

    mel_pad_value: Optional[float] = None,

) -> Dict[str, torch.Tensor]:
    """

    Collates a batch of variable-length text and mel spectrograms with padding.

    """
    if mel_pad_value is None:
        mel_pad_value = math.log(AudioConfig.mel_min_clip)

    B = len(batch)
    text_lens = torch.tensor([item["text_len"] for item in batch], dtype=torch.long)
    mel_lens = torch.tensor([item["mel_len"] for item in batch], dtype=torch.long)

    max_text_len = max(item["text_len"] for item in batch)
    max_mel_len = max(item["mel_len"] for item in batch)

    # Pad text with 0 (<pad>)
    padded_texts = torch.zeros(B, max_text_len, dtype=torch.long)
    for i, item in enumerate(batch):
        padded_texts[i, :item["text_len"]] = item["text_ids"]

    # Pad mel with log(mel_min_clip) (Vocos silence floor)
    mel_dim = batch[0]["mel"].shape[0]
    padded_mels = torch.full((B, mel_dim, max_mel_len), mel_pad_value, dtype=torch.float32)
    for i, item in enumerate(batch):
        padded_mels[i, :, :item["mel_len"]] = item["mel"]

    return {
        "text_ids": padded_texts,
        "text_lengths": text_lens,
        "mel_gt": padded_mels,
        "mel_lengths": mel_lens,
    }