File size: 12,836 Bytes
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672856a
cc5e704
 
672856a
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f28ca4
cc5e704
 
 
 
 
 
2f28ca4
 
 
 
 
 
 
 
 
 
cc5e704
2f28ca4
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Murli V1.5 Single-Speaker Studio-Grade Dataset & Collate Pipeline.

Loads Parquet shards from Hugging Face (`ViuAI/Murli_TTS_Dataset`), optionally filtering to a single

studio speaker_id, extracts & caches 100-bin HTK Mel + Log-F0 + Energy, and enforces MAS feasibility.

"""

import hashlib
import os
import json
import math
import warnings
from copy import copy
from dataclasses import asdict
from pathlib import Path

from utils.checkpoint import atomic_save
from typing import Any, Dict, List, Optional, Tuple

import torch
from torch.utils.data import Dataset

from config import EMOTION_TO_ID, AudioConfig
from data.audio_processor import AudioProcessor, read_audio_bytes
from data.text_cleaner import BilingualTextTokenizer


def _map_emotion(raw_emotion: Optional[str]) -> int:
    if not raw_emotion:
        return 0
    key = str(raw_emotion).strip().lower()
    aliases = {"narration": "story", "storytelling": "story", "anger": "angry",
               "happiness": "happy", "sadness": "sad", "fearful": "fear", "surprised": "surprise"}
    if key in aliases:
        return EMOTION_TO_ID[aliases[key]]
    for name, idx in EMOTION_TO_ID.items():
        if name in key:
            return idx
    return 0


class MurliV15Dataset(Dataset):
    """Single-speaker studio-grade expressive Hindi dataset."""

    def __init__(

        self,

        parquet_paths: Optional[List[str]] = None,

        hf_dataset_name: Optional[str] = None,

        data_subdirs: Optional[List[str]] = None,

        target_speaker: Optional[str] = None,

        target_gender: Optional[str] = None,

        cache_dir: Optional[str] = None,

        audio_cfg: AudioConfig = AudioConfig(),

        max_samples: Optional[int] = None,

        partition: str = "all",

        skip_invalid: bool = True,

    ):
        self.audio_cfg = audio_cfg
        self.proc = AudioProcessor(audio_cfg)
        self.tokenizer = BilingualTextTokenizer(use_g2p_en=False)
        self.cache_dir = cache_dir
        self.partition = partition
        self.skip_invalid = skip_invalid
        # Invalidate cached targets whenever the preprocessing contract changes.
        here = Path(__file__).parent
        signature = hashlib.sha256(json.dumps(asdict(audio_cfg), sort_keys=True).encode())
        for filename in ("audio_processor.py", "text_cleaner.py", "numbers_spoken.py"):
            signature.update((here / filename).read_bytes())
        self.feature_version = signature.hexdigest()[:16]
        self._audio_group = None
        self._audio_column = None
        if max_samples is not None and max_samples < 1:
            raise ValueError("max_samples must be positive")
        if cache_dir:
            os.makedirs(cache_dir, exist_ok=True)

        self.rows: List[Dict[str, Any]] = []
        if parquet_paths:
            self._load_local_parquets(parquet_paths, target_speaker=target_speaker, target_gender=target_gender, max_samples=max_samples)
        elif hf_dataset_name:
            self._load_hf_parquets(
                hf_dataset_name,
                data_subdirs=data_subdirs or ["hindi_50h"],
                target_speaker=target_speaker,
                target_gender=target_gender,
                max_samples=max_samples,
            )

        self.rows = self.partition_rows(partition)

    def partition_rows(self, partition):
        if partition == "all":
            return self.rows
        if partition not in {"train", "validation"}:
            raise ValueError(f"Unknown partition {partition}")
        # Keep repetitions of the same transcript on one side of the split.
        keys = sorted({r["split_key"] for r in self.rows})
        count = min(max(0, len(keys) - 1), max(1, math.ceil(len(keys) / 50)))
        held_out = set(keys[:count])
        return [r for r in self.rows if (r["split_key"] in held_out) == (partition == "validation")]

    def split(self):
        train, validation = copy(self), copy(self)
        train.rows = self.partition_rows("train")
        validation.rows = self.partition_rows("validation")
        return train, validation

    def _accept_row(self, row: Dict[str, Any], target_speaker: Optional[str], target_gender: Optional[str]) -> bool:
        text = str(row.get("text", "") or "").strip()
        if not text:
            return False
        if target_speaker is not None:
            spk = str(row.get("speaker_id") or row.get("speaker") or "").strip()
            if spk != target_speaker:
                return False
        if target_gender is not None:
            gen = str(row.get("gender", "") or "").strip().lower()
            if gen != target_gender.strip().lower():
                return False
        dur = float(row.get("duration_s", row.get("duration", 0.0)) or 0.0)
        if dur > 0.0 and (dur < 0.8 or dur > 18.0):
            return False
        return True

    def _load_local_parquets(self, paths: List[str], target_speaker: Optional[str], target_gender: Optional[str], max_samples: Optional[int]):
        import pyarrow.parquet as pq

        for p in paths:
            path = Path(p).resolve()
            file = pq.ParquetFile(path)
            columns = set(file.schema_arrow.names)
            audio_column = "audio" if "audio" in columns else "audio_bytes"
            if audio_column not in columns or "text" not in columns:
                raise ValueError(f"Missing audio or text column in {path}")
            fields = sorted(columns & {"text", "speaker", "speaker_id", "emotion", "duration",
                                       "duration_s", "gender"})
            stat = path.stat()
            identity = f"{path}|{stat.st_size}|{stat.st_mtime_ns}"
            for group in range(file.num_row_groups):
                metadata = file.read_row_group(group, columns=fields)
                for offset, row in enumerate(metadata.to_pylist()):
                    if not self._accept_row(row, target_speaker, target_gender):
                        continue
                    text = str(row["text"]).strip()
                    split_key = hashlib.sha256(" ".join(text.casefold().split()).encode()).hexdigest()
                    uid = hashlib.sha256(f"{identity}|{group}|{offset}".encode()).hexdigest()
                    dur = float(row.get("duration_s", row.get("duration", 0.0)) or 0.0)
                    self.rows.append({
                        "path": str(path), "group": group, "offset": offset, "audio_column": audio_column,
                        "text": text, "split_key": split_key, "uid": uid, "duration": dur,
                        "emotion": row.get("emotion") or "neutral",
                        "speaker_id": str(row.get("speaker_id") or row.get("speaker") or "unknown").strip(),
                    })
                    if max_samples and len(self.rows) >= max_samples:
                        return

    def _audio_bytes(self, row):
        import pyarrow.parquet as pq

        key = (row["path"], row["group"])
        if self._audio_group != key:
            # Keep at most one decoded Parquet row group per worker.
            self._audio_group = self._audio_column = None
            table = pq.ParquetFile(row["path"]).read_row_group(row["group"], columns=[row["audio_column"]])
            self._audio_column = table.column(0)
            self._audio_group = key
        value = self._audio_column[row["offset"]].as_py()
        return value.get("bytes") if isinstance(value, dict) else value

    def _load_hf_parquets(

        self,

        repo_id: str,

        data_subdirs: List[str],

        target_speaker: Optional[str],

        target_gender: Optional[str],

        max_samples: Optional[int],

    ):
        from huggingface_hub import HfApi, hf_hub_download

        api = HfApi(token=os.getenv("HF_TOKEN"))
        revision = api.dataset_info(repo_id).sha
        all_files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", revision=revision)
        parquet_files = [
            f for f in sorted(all_files)
            if f.endswith(".parquet") and any(f.startswith(sub.rstrip("/") + "/") for sub in data_subdirs)
        ]
        print(f"[Dataset] Found {len(parquet_files)} parquet shards in {repo_id} ({data_subdirs})", flush=True)
        for idx, filename in enumerate(parquet_files, start=1):
            print(f"[Download {idx}/{len(parquet_files)}] Fetching {filename} ...", flush=True)
            path = hf_hub_download(
                repo_id=repo_id,
                filename=filename,
                repo_type="dataset",
                revision=revision,
                token=os.getenv("HF_TOKEN"),
            )
            self._load_local_parquets([path], target_speaker, target_gender, max_samples)
            print(f"[Indexed {idx}/{len(parquet_files)}] Matched clips so far: {len(self.rows)}", flush=True)
            if max_samples and len(self.rows) >= max_samples:
                break

    def __len__(self) -> int:
        return len(self.rows)

    def _load_features(self, row: Dict[str, Any]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        uid = row["uid"]
        cache_path = os.path.join(self.cache_dir, f"{uid}-{self.feature_version}.pt") if self.cache_dir else None
        if cache_path and os.path.exists(cache_path):
            cached = torch.load(cache_path, map_location="cpu", weights_only=True)
            return cached["tokens"], cached["mel"], cached["f0"], cached["energy"]

        wav, sr = read_audio_bytes(self._audio_bytes(row))
        if sr <= 0 or not 0.8 <= wav.shape[-1] / sr <= 18.0:
            raise ValueError("Decoded duration outside 0.8 to 18 seconds")
        wav_norm = self.proc.normalize_waveform(wav, sr)
        mel_raw, f0, energy = self.proc.extract_features(wav_norm)
        mel = (mel_raw - self.audio_cfg.mel_mean) / self.audio_cfg.mel_std
        tokens = self.tokenizer.text_to_ids(row["text"])

        if cache_path:
            atomic_save({"tokens": tokens, "mel": mel, "f0": f0, "energy": energy}, cache_path)
        return tokens, mel, f0, energy

    def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
        n = len(self.rows)
        for offset in range(min(n, 8)):
            cur = (idx + offset) % n
            row = self.rows[cur]
            try:
                tokens, mel, f0, energy = self._load_features(row)
                if tokens.numel() == 0 or mel.shape[1] < tokens.numel():
                    raise ValueError("Empty transcript or too few mel frames for alignment")
                return {
                    "tokens": tokens,
                    "mel": mel,
                    "f0": f0,
                    "energy": energy,
                    "emotion_id": torch.tensor(_map_emotion(row.get("emotion")), dtype=torch.long),
                }
            except (ValueError, OSError, RuntimeError) as exc:
                message = f"{row['path']} group {row['group']} row {row['offset']}: {exc}"
                if not self.skip_invalid:
                    raise ValueError(message) from exc
                warnings.warn(message, RuntimeWarning, stacklevel=2)
        raise RuntimeError(f"Failed to load valid sample starting at idx={idx}")


def v15_collate_fn(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
    bsz = len(batch)
    max_text = max(item["tokens"].shape[0] for item in batch)
    max_mel = max(item["mel"].shape[1] for item in batch)
    n_mels = batch[0]["mel"].shape[0]

    token_ids = torch.zeros((bsz, max_text), dtype=torch.long)
    text_mask = torch.zeros((bsz, max_text), dtype=torch.bool)
    mel_target = torch.zeros((bsz, n_mels, max_mel), dtype=torch.float32)
    mel_mask = torch.zeros((bsz, max_mel), dtype=torch.bool)
    f0_target = torch.zeros((bsz, max_mel), dtype=torch.float32)
    energy_target = torch.zeros((bsz, max_mel), dtype=torch.float32)
    emotion_ids = torch.zeros((bsz,), dtype=torch.long)

    for i, item in enumerate(batch):
        t_len = item["tokens"].shape[0]
        m_len = item["mel"].shape[1]
        token_ids[i, :t_len] = item["tokens"]
        text_mask[i, :t_len] = True
        mel_target[i, :, :m_len] = item["mel"]
        mel_mask[i, :m_len] = True
        f0_target[i, :m_len] = item["f0"]
        energy_target[i, :m_len] = item["energy"]
        emotion_ids[i] = item["emotion_id"]

    return {
        "token_ids": token_ids,
        "text_mask": text_mask,
        "mel_target": mel_target,
        "mel_mask": mel_mask,
        "f0_target": f0_target,
        "energy_target": energy_target,
        "emotion_ids": emotion_ids,
    }