Download data/dataset.py from ViuAI/TTS_10M: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/ViuAI/TTS_10M/resolve/main/data/dataset.py
- Command line
-
hf download hf://ViuAI/TTS_10M/data/dataset.py
-
curl -L -o dataset.py https://huggingface.co/ViuAI/TTS_10M/resolve/main/data/dataset.py
10.4 kB
| """ | |
| 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, | |
| } | |