Murli-V1.6-Code / data /dataset.py
ViuAI's picture
Murli V1.6 Audited Release (6/6 tests passing): EMA, FP32 CFM mask, F0 autocorr fix, cache & resume hardening
42e63f8 verified
Raw History Blame Contribute Delete
20.8 kB
"""
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"]]