File size: 20,810 Bytes
870eedf 42e63f8 870eedf e3176d6 870eedf e3176d6 870eedf 42e63f8 870eedf 88e817e e3176d6 870eedf 42e63f8 870eedf 42e63f8 870eedf 850083c 42e63f8 870eedf 42e63f8 870eedf 850083c 870eedf 850083c 870eedf 42e63f8 870eedf 42e63f8 870eedf 42e63f8 870eedf 42e63f8 870eedf 1896ee9 870eedf 1896ee9 870eedf 850083c 42e63f8 870eedf 42e63f8 870eedf 42e63f8 870eedf 88e817e 42e63f8 88e817e e3176d6 88e817e 850083c 88e817e 42e63f8 88e817e e3176d6 88e817e 42e63f8 88e817e 42e63f8 88e817e 42e63f8 88e817e 42e63f8 88e817e e3176d6 42e63f8 88e817e e3176d6 88e817e 42e63f8 88e817e 42e63f8 88e817e 850083c 88e817e 42e63f8 88e817e 42e63f8 e3176d6 88e817e 42e63f8 88e817e e3176d6 88e817e e3176d6 42e63f8 e3176d6 42e63f8 88e817e e3176d6 42e63f8 88e817e | 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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | """
Murli V1.6 Single-Speaker (syspin_male_01, 49.28h) & Optional Multi-Speaker Parquet Dataset Pipeline.
Includes metadata-only row indexing, sequential shard warmup, transcript-disjoint split, and versioned caching.
"""
import gc
import hashlib
import json
import math
import multiprocessing as mp
import os
import pickle
import warnings
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import copy
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
import torch
from torch.utils.data import Dataset
from config import EMOTION_TO_ID, SPEAKER_TO_ID, AudioConfig
from data.audio_processor import AudioProcessor, read_audio_bytes
from data.text_cleaner import BilingualTextTokenizer
from utils.checkpoint import atomic_save
def _extract_clip(raw, text, proc, tokenizer, language):
if not isinstance(raw, (bytes, bytearray, memoryview)) or not raw:
raise ValueError("Missing audio bytes")
try:
wav, sr = read_audio_bytes(raw)
except (ValueError, OSError, RuntimeError, EOFError) as exc:
raise ValueError(f"Undecodable audio: {exc}") from exc
if sr <= 0 or not 0.8 <= wav.shape[-1] / sr <= 18.0:
raise ValueError("Decoded duration outside 0.8 to 18 seconds")
mel, f0, energy = proc.extract_features(proc.normalize_waveform(wav, sr))
tokens = tokenizer.text_to_ids(text, language=language)
if not tokens.numel() or mel.size(1) < tokens.numel():
raise ValueError("Empty transcript or too few mel frames for alignment")
return tokens, (mel - proc.cfg.mel_mean) / proc.cfg.mel_std, f0, energy
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 MurliV16Dataset(Dataset):
"""Studio-grade Hindi Parquet dataset (defaults to Single-Speaker syspin_male_01)."""
def __init__(
self,
parquet_paths: Optional[List[str]] = None,
hf_dataset_name: Optional[str] = None,
data_subdirs: Optional[List[str]] = None,
target_speakers: Optional[List[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,
language: Optional[str] = "hi",
target_language: Optional[str] = None,
):
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.target_language = target_language
self.skip_invalid = skip_invalid
self.language = language if language in ("hi", "en") else None
self.speaker_to_id: Dict[str, int] = dict(SPEAKER_TO_ID)
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())
signature.update(f"|lang={self.language or 'auto'}".encode())
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)
allowed: Optional[Set[str]] = set(target_speakers) if target_speakers else None
self.rows: List[Dict[str, Any]] = []
if parquet_paths:
self._load_local_parquets(parquet_paths, allowed_speakers=allowed, 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"],
allowed_speakers=allowed,
target_gender=target_gender,
max_samples=max_samples,
)
self.rows = self.partition_rows(partition)
def _resolve_speaker_num(self, spk_name: str) -> int:
if spk_name not in self.speaker_to_id:
self.speaker_to_id[spk_name] = len(self.speaker_to_id)
return self.speaker_to_id[spk_name]
def partition_rows(self, partition: str):
if partition == "all":
return self.rows
if partition not in {"train", "validation"}:
raise ValueError(f"Unknown partition {partition}")
keys = sorted({r["split_key"] for r in self.rows})
count = min(max(0, len(keys) - 1), max(1, math.ceil(len(keys) / 50)))
speakers_by_key = defaultdict(set)
for row in self.rows:
speakers_by_key[row["split_key"]].add(row["speaker_id"])
remaining = defaultdict(int)
for speakers in speakers_by_key.values():
for speaker in speakers:
remaining[speaker] += 1
held_out = set()
for key in keys:
if len(held_out) == count:
break
speakers = speakers_by_key[key]
if all(remaining[speaker] > 1 for speaker in speakers):
held_out.add(key)
for speaker in speakers:
remaining[speaker] -= 1
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], allowed_speakers: Optional[Set[str]], target_gender: Optional[str]) -> bool:
text = str(row.get("text", "") or "").strip()
if not text:
return False
label = str(row.get("language") or "").strip().casefold().replace("_", "-").split("-")[0]
label = {"hindi": "hi", "hin": "hi", "english": "en", "eng": "en"}.get(label, label)
if self.target_language and label and label != self.target_language:
return False
spk = str(row.get("speaker_id") or row.get("speaker") or "").strip()
if allowed_speakers is not None and spk not in allowed_speakers:
return False
if target_gender is not None:
gen = str(row.get("gender", "") or "").strip().lower()
if gen != target_gender.strip().lower():
return False
try:
dur = float(row.get("duration_s", row.get("duration", 0.0)) or 0.0)
except (TypeError, ValueError) as exc:
if self.skip_invalid:
return False
raise ValueError(f"Invalid duration for {text!r}") from exc
if not math.isfinite(dur) or dur < 0 or (dur and not 0.8 <= dur <= 18.0):
return False
return True
def _load_local_parquets(
self,
paths: List[str],
allowed_speakers: Optional[Set[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", "language"})
# Hugging Face LFS blob filenames already carry the SHA-256 of the bytes.
if path.parent.name == "blobs" and len(path.name) == 64 and all(c in "0123456789abcdef" for c in path.name):
identity = path.name
else:
digest = hashlib.sha256()
with path.open("rb") as shard:
for block in iter(lambda: shard.read(4 * 1024 * 1024), b""):
digest.update(block)
identity = digest.hexdigest()
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, allowed_speakers, target_gender):
continue
text = str(row["text"]).strip()
spk_name = str(row.get("speaker_id") or row.get("speaker") or "unknown").strip()
spk_num = self._resolve_speaker_num(spk_name)
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": spk_name,
"speaker_num": spk_num,
})
if max_samples and len(self.rows) >= max_samples:
return
def _audio_bytes(self, row):
import pyarrow as pa
import pyarrow.parquet as pq
key = (row["path"], row["group"])
if self._audio_group != key:
self._audio_group = self._audio_column = None
pa.default_memory_pool().release_unused()
table = pq.ParquetFile(row["path"]).read_row_group(
row["group"], columns=[row["audio_column"]], use_threads=False
)
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],
allowed_speakers: Optional[Set[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], allowed_speakers, 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:
if os.path.exists(cache_path + ".bad"):
raise ValueError("Cached invalid clip")
if os.path.exists(cache_path):
try:
cached = torch.load(cache_path, map_location="cpu", weights_only=True)
return cached["tokens"], cached["mel"], cached["f0"], cached["energy"]
except (EOFError, pickle.UnpicklingError, RuntimeError, KeyError, IndexError, TypeError):
# A broken feature file can be rebuilt from the authoritative audio.
pass
features = _extract_clip(self._audio_bytes(row), row["text"], self.proc, self.tokenizer, self.language)
tokens, mel, f0, energy = features
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)
if not -n <= idx < n:
raise IndexError(idx)
for offset in range(n):
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,
"speaker_id": torch.tensor(int(row["speaker_num"]), dtype=torch.long),
"emotion_id": torch.tensor(_map_emotion(row.get("emotion")), dtype=torch.long),
}
except ValueError 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 v16_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)
speaker_ids = torch.zeros((bsz,), dtype=torch.long)
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"]
speaker_ids[i] = item["speaker_id"]
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,
"speaker_ids": speaker_ids,
"emotion_ids": emotion_ids,
}
def _warm_shard_worker(task: Tuple[str, List[Dict[str, Any]], AudioConfig, str, str, Optional[str]]) -> Tuple[str, int, int, Dict[str, float]]:
"""Decode and cache all uncached rows of ONE Parquet shard sequentially (1.0x disk read)."""
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")
import pyarrow as pa
import pyarrow.parquet as pq
shard_path, entries, audio_cfg, cache_dir, feature_version, language = task
proc = AudioProcessor(audio_cfg)
tokenizer = BilingualTextTokenizer(use_g2p_en=False)
by_group: Dict[int, List[Dict[str, Any]]] = defaultdict(list)
for r in entries:
cache_path = os.path.join(cache_dir, f"{r['uid']}-{feature_version}.pt")
if not os.path.exists(cache_path) and not os.path.exists(cache_path + ".bad"):
by_group[r["group"]].append(r)
shard_name = os.path.basename(shard_path)
if not by_group:
return shard_name, 0, 0, {}
pf = pq.ParquetFile(shard_path)
done = skipped = 0
durations: Dict[str, float] = {}
frame_sec = audio_cfg.hop_length / float(audio_cfg.sample_rate)
for group_idx in sorted(by_group):
group_rows = by_group[group_idx]
audio_col = group_rows[0]["audio_column"]
col = pf.read_row_group(group_idx, columns=[audio_col], use_threads=False).column(0)
for r in group_rows:
cache_path = os.path.join(cache_dir, f"{r['uid']}-{feature_version}.pt")
try:
val = col[r["offset"]].as_py()
raw_bytes = val.get("bytes") if isinstance(val, dict) else val
tokens, mel, f0, energy = _extract_clip(raw_bytes, r["text"], proc, tokenizer, language)
except ValueError as exc:
Path(cache_path + ".bad").write_text(str(exc), encoding="utf-8")
skipped += 1
continue
atomic_save({"tokens": tokens, "mel": mel, "f0": f0, "energy": energy}, cache_path)
if r.get("duration", 0.0) <= 0.0:
durations[r["uid"]] = round(mel.size(1) * frame_sec, 3)
done += 1
del col
pa.default_memory_pool().release_unused()
del pf
gc.collect()
return shard_name, done, skipped, durations
def warm_cache_by_shard(dataset: MurliV16Dataset, num_workers: int = 2) -> None:
"""Pre-build Mel/F0/Energy cache sequentially per Parquet shard using spawn workers (no fork deadlock)."""
if not dataset.cache_dir or not dataset.rows:
return
os.makedirs(dataset.cache_dir, exist_ok=True)
by_shard: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
missing = 0
for r in dataset.rows:
p = os.path.join(dataset.cache_dir, f"{r['uid']}-{dataset.feature_version}.pt")
if not os.path.exists(p) and not os.path.exists(p + ".bad"):
by_shard[r["path"]].append(r)
missing += 1
if missing == 0:
print(f"[Cache Ready] All {len(dataset.rows)} rows have cache entries or invalid-clip markers", flush=True)
return
tasks = [
(shard_path, rows, dataset.audio_cfg, dataset.cache_dir, dataset.feature_version, dataset.language)
for shard_path, rows in sorted(by_shard.items())
]
workers = min(len(tasks), 4, max(1, num_workers), os.cpu_count() or 2)
print(f"[Cache Warmup] Extracting {missing} clips across {len(tasks)} shards ({workers} workers)...", flush=True)
total_done = total_skip = 0
durations_all: Dict[str, float] = {}
if workers <= 1:
for idx, t in enumerate(tasks, 1):
name, d, s, durs = _warm_shard_worker(t)
durations_all.update(durs)
total_done += d
total_skip += s
print(f"[Cache {idx}/{len(tasks)}] {name}: +{d} (skip {s}) | Total {total_done}/{missing}", flush=True)
else:
ctx = mp.get_context("spawn")
with ProcessPoolExecutor(max_workers=workers, mp_context=ctx, initializer=torch.set_num_threads, initargs=(1,)) as ex:
futures = [ex.submit(_warm_shard_worker, t) for t in tasks]
for idx, fut in enumerate(as_completed(futures), 1):
name, d, s, durs = fut.result()
durations_all.update(durs)
total_done += d
total_skip += s
print(f"[Cache {idx}/{len(tasks)}] {name}: +{d} (skip {s}) | Total {total_done}/{missing}", flush=True)
if durations_all:
for r in dataset.rows:
if r.get("duration", 0.0) <= 0.0 and r["uid"] in durations_all:
r["duration"] = durations_all[r["uid"]]
|