File size: 13,776 Bytes
a1cd84e
 
 
 
 
 
 
 
3ea4cde
a1cd84e
3ea4cde
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
 
 
a1cd84e
 
 
 
 
3ea4cde
 
 
a1cd84e
 
 
 
 
 
 
 
 
3ea4cde
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
a1cd84e
3ea4cde
 
 
 
 
 
a1cd84e
 
 
 
 
3ea4cde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
 
 
 
 
 
 
 
a1cd84e
 
3ea4cde
a1cd84e
3ea4cde
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
a1cd84e
 
 
 
 
 
 
3ea4cde
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Murli V2.0 Parquet-First Bilingual Dataset & Length-Bucketed Collate Pipeline.

Enforces V1 post-mortem rules: Parquet shards only, pre-filtered speaker/language before

decoding bytes, strict MAS feasibility check (T_text <= T_mel), and disk caching.

"""

import os
import hashlib
import random
import tempfile
from collections import defaultdict
from typing import Any, Dict, List, Optional, Tuple
import torch
from torch.utils.data import Dataset

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


class MurliV2Dataset(Dataset):
    """Bilingual (Hindi + English) dataset loading Parquet shards or local manifests."""

    def __init__(

        self,

        parquet_dir: Optional[str] = None,

        hf_dataset_name: Optional[str] = None,

        data_subdir: str = "bilingual_1000h",

        language: Optional[str] = None,

        speaker: Optional[str] = None,

        cache_dir: Optional[str] = None,

        audio_cfg: AudioConfig = AudioConfig(),

        max_samples: Optional[int] = None,

        partition: str = "all",

        skip_invalid: bool = False,

        cross_utterance_ref: bool = True,

        min_ref_frames: int = 280,

        max_ref_frames: int = 750,

    ):
        if partition not in {"all", "train", "validation"}:
            raise ValueError("partition must be all, train or validation")
        self.partition = partition
        self.skip_invalid = skip_invalid
        self.cross_utterance_ref = cross_utterance_ref
        self.min_ref_frames = min_ref_frames
        self.max_ref_frames = max_ref_frames
        self.audio_cfg = audio_cfg
        self.proc = AudioProcessor(audio_cfg)
        self.tokenizer = BilingualTextTokenizer(use_g2p_en=False)
        self.cache_dir = cache_dir
        if cache_dir:
            os.makedirs(cache_dir, exist_ok=True)

        self.rows = []
        self.durations = []
        self.row_speakers: List[str] = []
        self.speaker_to_indices: Dict[str, List[int]] = defaultdict(list)
        self.shard_speaker_to_indices: Dict[Tuple[str, str], List[int]] = defaultdict(list)
        self.validation_indices = []
        self.shard_versions = {}
        if parquet_dir is not None:
            self._load_parquet_dir(parquet_dir, language=language, speaker=speaker, max_samples=max_samples)
        elif hf_dataset_name is not None:
            self._load_hf_parquet(
                hf_dataset_name,
                data_subdir=data_subdir,
                language=language,
                speaker=speaker,
                max_samples=max_samples,
            )

    def _accept_row(self, row: Dict[str, Any], language: Optional[str], speaker: Optional[str]) -> bool:
        if language and row.get("lang", row.get("language")) != language:
            return False
        if speaker and row.get("speaker_id", row.get("speaker")) != speaker:
            return False
        if self.partition != "all" and (self.partition == "validation") != self._held_out(row):
            return False
        return bool(row.get("text") or row.get("transcript"))

    @staticmethod
    def _held_out(row):
        key = row.get("speaker_id")
        if key is None:
            key = row.get("speaker")
        if key is None or str(key).lower() == "unknown" or str(key).endswith("_unknown"):
            return False
        bucket = int.from_bytes(hashlib.sha256(str(key).encode()).digest()[:4], "big") % 100
        return bucket < 5

    def _load_parquet_dir(self, parquet_dir: str, language: Optional[str], speaker: Optional[str], max_samples: Optional[int]):
        import pyarrow.parquet as pq

        files = []
        for root, _, fnames in os.walk(parquet_dir):
            for f in sorted(fnames):
                if f.endswith(".parquet"):
                    files.append(os.path.join(root, f))
        for fpath in sorted(files):
            stat = os.stat(fpath)
            self.shard_versions[fpath] = (os.path.abspath(fpath), stat.st_size, stat.st_mtime_ns)
            with pq.ParquetFile(fpath) as pf:
                columns = [c for c in ("lang", "language", "speaker_id", "speaker", "text", "transcript", "duration_s")
                           if c in pf.schema_arrow.names]
                for group in range(pf.num_row_groups):
                    metadata = pf.read_row_group(group, columns=columns)
                    for offset, item in enumerate(metadata.to_pylist()):
                        if self._accept_row(item, language, speaker):
                            row_idx = len(self.rows)
                            if self._held_out(item):
                                self.validation_indices.append(row_idx)
                            spk = str(item.get("speaker_id") or item.get("speaker") or "unknown")
                            self.row_speakers.append(spk)
                            if self._is_known_speaker(spk):
                                self.speaker_to_indices[spk].append(row_idx)
                                self.shard_speaker_to_indices[(fpath, spk)].append(row_idx)
                            self.durations.append(float(item.get("duration_s") or len(item.get("text") or item["transcript"]) * 0.08))
                            self.rows.append((fpath, group, offset))
                            if max_samples and len(self.rows) >= max_samples:
                                return

    @staticmethod
    def _is_known_speaker(spk: Optional[str]) -> bool:
        if not spk:
            return False
        low = str(spk).strip().lower()
        return low != "unknown" and not low.endswith("_unknown")

    def _sample_ref_idx(self, idx: int) -> Optional[int]:
        if not self.cross_utterance_ref or idx >= len(self.row_speakers):
            return None
        spk = self.row_speakers[idx]
        if not self._is_known_speaker(spk):
            return None
        fpath = self.rows[idx][0]
        # Prefer same-shard utterances first to avoid cross-shard disk thrashing
        shard_pool = self.shard_speaker_to_indices.get((fpath, spk), [])
        if len(shard_pool) >= 2:
            for _ in range(4):
                cand = random.choice(shard_pool)
                if cand != idx:
                    return cand
        global_pool = self.speaker_to_indices.get(spk, [])
        if len(global_pool) >= 2:
            for _ in range(4):
                cand = random.choice(global_pool)
                if cand != idx:
                    return cand
        return None

    def _crop_ref_mel(self, mel: torch.Tensor) -> torch.Tensor:
        t_len = mel.shape[-1]
        if t_len <= self.max_ref_frames:
            return mel
        win = random.randint(min(self.min_ref_frames, self.max_ref_frames), self.max_ref_frames)
        start = random.randint(0, t_len - win)
        return mel[:, start : start + win]

    def _load_hf_parquet(

        self,

        repo_id: str,

        data_subdir: str,

        language: Optional[str],

        speaker: Optional[str],

        max_samples: Optional[int],

    ):
        from huggingface_hub import snapshot_download
        patterns = [f"{data_subdir}/**/*.parquet", f"{data_subdir}/*.parquet"] if data_subdir else ["*.parquet", "**/*.parquet"]
        local_dir = snapshot_download(
            repo_id=repo_id,
            repo_type="dataset",
            allow_patterns=patterns,
            max_workers=16,
        )
        target_dir = os.path.join(local_dir, data_subdir) if data_subdir and os.path.isdir(os.path.join(local_dir, data_subdir)) else local_dir
        self._load_parquet_dir(target_dir, language, speaker, max_samples)

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

    def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
        if not self.skip_invalid:
            sample = self._load_item(idx)
            ref_idx = self._sample_ref_idx(idx)
            if ref_idx is not None:
                try:
                    sample["ref_mel"] = self._crop_ref_mel(self._load_item(ref_idx)["mel"])
                except Exception:
                    pass
            return sample
        last_err = None
        for attempt in range(min(16, len(self.rows))):
            cur_idx = (idx + attempt) % len(self.rows)
            try:
                sample = self._load_item(cur_idx)
                ref_idx = self._sample_ref_idx(cur_idx)
                if ref_idx is not None:
                    try:
                        sample["ref_mel"] = self._crop_ref_mel(self._load_item(ref_idx)["mel"])
                    except Exception:
                        pass
                return sample
            except Exception as exc:
                last_err = exc
        raise RuntimeError(f"Failed to load a valid sample after 16 retries near idx {idx}: {last_err}")

    def _load_item(self, idx: int) -> Dict[str, torch.Tensor]:
        import pyarrow.parquet as pq

        fpath, group, offset = self.rows[idx]
        cache_path = None
        if self.cache_dir:
            identity = (self.shard_versions[fpath], group, offset, self.audio_cfg, "ipa-v2-centered-mel-1")
            key = hashlib.sha256(repr(identity).encode()).hexdigest()
            cache_path = os.path.join(self.cache_dir, key + ".pt")
        if cache_path and os.path.isfile(cache_path):
            return torch.load(cache_path, map_location="cpu", weights_only=True)

        with pq.ParquetFile(fpath) as pf:
            for batch in pf.iter_batches(batch_size=16, row_groups=[group]):
                if offset < batch.num_rows:
                    row = batch.slice(offset, 1).to_pylist()[0]
                    break
                offset -= batch.num_rows
            else:
                raise IndexError(idx)
        def audio_path(path):
            return path if os.path.isabs(path) or os.path.isfile(path) else os.path.join(os.path.dirname(fpath), path)

        text = row.get("text") or row.get("transcript", "")
        lang = row.get("lang") or row.get("language")
        token_ids = self.tokenizer.text_to_ids(text, language=lang)

        if not token_ids.numel():
            raise ValueError(f"No pronounceable tokens in Parquet row {idx}")
        audio_field = row.get("audio")
        if isinstance(audio_field, dict) and audio_field.get("bytes") is not None:
            wav, sr = read_audio_bytes(audio_field["bytes"])
        elif isinstance(audio_field, dict) and audio_field.get("path"):
            wav, sr = read_audio_file(audio_path(audio_field["path"]))
        elif row.get("audio_path"):
            wav, sr = read_audio_file(audio_path(row["audio_path"]))
        else:
            raise ValueError(f"Row {idx} has no readable audio payload.")

        wav = self.proc.normalize_waveform(wav, sr)
        mel, log_f0, energy = self.proc.extract_features(wav)

        if mel.shape[-1] < token_ids.numel():
            raise ValueError(f"Row {idx} has {token_ids.numel()} tokens for only {mel.shape[-1]} audio frames")

        sample = {
            "token_ids": token_ids,
            "mel": mel,
            "f0": log_f0,
            "energy": energy,
        }
        if cache_path:
            with tempfile.NamedTemporaryFile(dir=self.cache_dir, suffix=".pt", delete=False) as tmp:
                tmp_path = tmp.name
            try:
                torch.save(sample, tmp_path)
                os.replace(tmp_path, cache_path)
            finally:
                if os.path.exists(tmp_path):
                    os.unlink(tmp_path)
        return sample


def v2_collate_fn(batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
    """Pad variable-length bilingual phoneme and acoustic sequences cleanly."""
    bsz = len(batch)
    max_t = max(item["token_ids"].numel() for item in batch)
    max_m = max(item["mel"].shape[-1] for item in batch)
    n_mels = batch[0]["mel"].shape[0]

    token_ids = torch.zeros(bsz, max_t, dtype=torch.long)
    text_mask = torch.zeros(bsz, max_t, dtype=torch.bool)
    mel_target = torch.zeros(bsz, n_mels, max_m, dtype=torch.float32)
    f0_target = torch.zeros(bsz, max_m, dtype=torch.float32)
    energy_target = torch.zeros(bsz, max_m, dtype=torch.float32)
    mel_mask = torch.zeros(bsz, max_m, dtype=torch.bool)

    for b, item in enumerate(batch):
        tx = item["token_ids"].numel()
        ty = item["mel"].shape[-1]
        token_ids[b, :tx] = item["token_ids"]
        text_mask[b, :tx] = True
        mel_target[b, :, :ty] = item["mel"]
        f0_target[b, :ty] = item["f0"]
        energy_target[b, :ty] = item["energy"]
        mel_mask[b, :ty] = True

    out = {
        "token_ids": token_ids,
        "text_mask": text_mask,
        "mel_target": mel_target,
        "f0_target": f0_target,
        "energy_target": energy_target,
        "mel_mask": mel_mask,
    }
    if any(item.get("ref_mel") is not None for item in batch):
        max_ref = max(item["ref_mel"].shape[-1] for item in batch if item.get("ref_mel") is not None)
        ref_mel = torch.zeros(bsz, n_mels, max_ref, dtype=torch.float32)
        ref_mask = torch.zeros(bsz, max_ref, dtype=torch.bool)
        for b, item in enumerate(batch):
            rm = item.get("ref_mel")
            if rm is not None:
                rl = rm.shape[-1]
                ref_mel[b, :, :rl] = rm
                ref_mask[b, :rl] = True
        out["ref_mel"] = ref_mel
        out["ref_mask"] = ref_mask
    return out