Sprint 1: Hinglish 3-tier G2P router, cross-utterance ref sampling + SpecAugment self-crop, IndicTTS-English source
Browse filesFiles changed (6)
- data/dataset.py+87-5
- data/text_cleaner.py+235-83
- kaggle_data_collector.py+13-4
- models/tts_engine.py+37-12
- tests/test_v2.py+114
- train.py+4
5 unmodified lines67891011101213141517 unmodified lines33343536373839404142434445464748493 unmodified lines53545556575859606144 unmodified lines1061071081091109911111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016118 unmodified lines18018118212918318418518618718818919019119219319413319519619719819920020120220320420585 unmodified lines2912922932252942952962971 unmodified line2993003013023033043053063073083093103113123133145 unmodified lines
import os
import hashlib
import random
import tempfile
from collections import defaultdict
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Tuple
import torch
from torch.utils.data import Dataset
17 unmodified lines 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)3 unmodified lines
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:44 unmodified lines 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(len(self.rows))
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,18 unmodified lines
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
if not self.skip_invalid:
return self._load_item(idx)
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:
return self._load_item((idx + attempt) % len(self.rows))
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}")85 unmodified lines energy_target[b, :ty] = item["energy"]
mel_mask[b, :ty] = True
return {
out = {
"token_ids": token_ids,
"text_mask": text_mask,
"mel_target": mel_target,1 unmodified line "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 out12345645678910111246 unmodified lines596061596263626465666667686914 unmodified lines8485868787888914 unmodified lines1041051061071081091101111121131141151161171181141191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771787 unmodified lines1861871881281291301891901911921341931941951961391971981992003 unmodified lines2042052061491501511521531541551562072081581592092102112122131651662141681691701711721732152161751762172182192203 unmodified lines2242252261862272282292301911922312322331951961971981992002342352362372384 unmodified lines2432442452112122132142152462472482492172502512522534 unmodified lines2582592602282612622312322332632642362652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043 unmodified lines30830931024631131231311 unmodified lines32532632726432832933016 unmodified lines34734834928735035135235335424 unmodified lines37938038131831932032132232332432532632732832933038238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347414 unmodified lines4894904913514924933533543554944954964974984995005015025035043573585055065073623635085095105115125135143693703715155165175185195205215225235245253735265273765285295305311 unmodified line533534535384536537538539"""Murli V2.0 — 2026 Bilingual Hindi + English / Hinglish G2P & Unified IPA Tokenizer.
Solves V1's character-level errors (schwa deletion, contextual Anusvara, ड़/ढ़ retroflexes,and unknown Latin words) by translating BOTH Devanagari Hindi and English/Hinglish text intoa single shared phonetic IPA + prosody token sequence.Supports: - Pure Devanagari Hindi (`<hi>`): schwa rules, contextual Anusvara, Chandrabindu, ड़/ढ़ retroflexes - Pure English (`<en>`): EN_LEXICON + optional g2p_en + deterministic English G2P rules - Romanized Hinglish (`<hi>` + `<en>`): 3-tier word router (orthographic normalizer, Roman-Hindi lexicon & suffix heuristics, clause-level homograph context voting), deterministic Roman-Hindi -> unified IPA mapper, and context-aware digit expansion."""
import re46 unmodified lines "प": ["p"], "फ": ["pʰ"], "ब": ["b"], "भ": ["bʰ"], "म": ["m"], "य": ["j"], "र": ["ɾ"], "ल": ["l"], "व": ["ʋ"], "श": ["ʃ"], "ष": ["ʃ"], "स": ["s"], "ह": ["ɦ"], # Nukta variants (including retroflex flaps ड़, ढ़!) "क़": ["q"], "ख़": ["x"], "ग़": ["ɣ"], "ज़": ["z"], "ड़": ["ɽ"], "ढ़": ["ɽʰ"], "फ़": ["f"], "य़": ["j"], # Pre-composed conjuncts "क्ष": ["k", "ʃ"], "त्र": ["t̪", "ɾ"], "ज्ञ": ["g", "j"], "श्र": ["ʃ", "ɾ"],}
# Anusvara nasal assimilation by varga of following consonantVARGA_NASAL: Dict[str, str] = { "क": "ŋ", "ख": "ŋ", "ग": "ŋ", "घ": "ŋ", "ङ": "ŋ", "च": "ɲ", "छ": "ɲ", "ज": "ɲ", "झ": "ɲ", "ञ": "ɲ",14 unmodified lines "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine",}
# Common high-frequency English & Hinglish technical words mapped directly to clean IPAEN_LEXICON: Dict[str, List[str]] = { "a": ["ə"], "an": ["æ", "n"], "the": ["ð", "ə"], "and": ["æ", "n", "d"], "is": ["ɪ", "z"], "are": ["ɑː", "r"], "was": ["w", "ɒ", "z"], "in": ["ɪ", "n"],14 unmodified lines "today": ["t", "ə", "d", "eɪ"], "friend": ["f", "r", "ɛ", "n", "d"], "server": ["s", "ɜː", "r", "v", "ə", "r"], "gpu": ["dʒ", "iː", "p", "iː", "uː"], "murli": ["m", "ʊ", "ɾ", "l", "iː"], "version": ["v", "ɜː", "r", "ʒ", "ə", "n"], "meeting": ["m", "iː", "t", "ɪ", "ŋ"], "pm": ["p", "iː", "ɛ", "m"], "am": ["eɪ", "ɛ", "m"], "office": ["ɒ", "f", "ɪ", "s"], "project": ["p", "r", "ɒ", "dʒ", "ɛ", "k", "t"], "call": ["k", "ɔː", "l"], "train": ["t", "r", "eɪ", "n"], "launch": ["l", "ɔː", "n", "tʃ"], "file": ["f", "aɪ", "l"], "download": ["d", "aʊ", "n", "l", "oʊ", "d"], "two": ["t", "uː"], "one": ["w", "ʌ", "n"], "three": ["θ", "r", "iː"], "four": ["f", "ɔː", "r"], "five": ["f", "aɪ", "v"], "six": ["s", "ɪ", "k", "s"], "seven": ["s", "ɛ", "v", "ə", "n"], "eight": ["eɪ", "t"], "nine": ["n", "aɪ", "n"], "zero": ["z", "ɪə", "r", "oʊ"], "don't": ["d", "oʊ", "n", "t"], "can't": ["k", "æ", "n", "t"], "won't": ["w", "oʊ", "n", "t"], "it's": ["ɪ", "t", "s"], "i'm": ["aɪ", "m"], "you're": ["j", "ʊ", "r"], "that's": ["ð", "æ", "t", "s"], "didn't": ["d", "ɪ", "d", "ə", "n", "t"], "isn't": ["ɪ", "z", "ə", "n", "t"],}
# ARPAbet (g2p_en) -> Unified IPA mapping when optional g2p_en is installed# Roman-Hindi Orthographic Variants -> Canonical FormROMAN_HINDI_VARIANTS: Dict[str, str] = { "achha": "accha", "acha": "accha", "achcha": "accha", "acchha": "accha", "bohot": "bahut", "bhaut": "bahut", "bohut": "bahut", "nahin": "nahi", "nahee": "nahi", "naheen": "nahi", "nhi": "nahi", "kyaa": "kya", "kyun": "kyu", "kyon": "kyu", "ku": "kyu", "hoon": "hu", "hun": "hu", "hain": "hai", "he": "hai", "mein": "me", "mai": "main", "mera": "mera", "meri": "meri", "mere": "mere", "tumhara": "tumhara", "aapka": "aapka", "apna": "apna", "kaam": "kaam", "kam": "kaam", "samay": "samay", "waqt": "waqt", "kal": "kal", "aaj": "aaj", "abhi": "abhi", "phir": "phir", "fir": "phir", "bhi": "bhi", "toh": "to", "lekin": "lekin", "magar": "magar", "aur": "aur", "yaa": "ya", "kyunki": "kyunki", "isliye": "isliye", "karo": "karo", "kro": "karo", "krna": "karna", "karna": "karna", "bolo": "bolo", "batao": "batao", "btao": "batao", "sunao": "sunao", "baat": "baat", "bat": "baat", "subah": "subah", "shaam": "shaam", "raat": "raat", "dost": "dost", "bhai": "bhai", "yaar": "yaar", "log": "log", "paisa": "paisa", "ghar": "ghar", "gaao": "gaon", "gaon": "gaon", "theek": "thik", "thik": "thik", "shukriya": "shukriya", "dhanyavaad": "dhanyavaad", "namaste": "namaste", "namaskar": "namaskar",}
# Curated Roman-Hindi IPA Lexicon (canonical forms -> unified IPA)ROMAN_HINDI_LEXICON: Dict[str, List[str]] = { "aaj": ["aː", "dʒ"], "kal": ["k", "ə", "l"], "abhi": ["ə", "bʰ", "iː"], "mausam": ["m", "ɔː", "s", "ə", "m"], "bahut": ["b", "ə", "ɦ", "ʊ", "t̪"], "accha": ["ə", "tʃ", "tʃʰ", "aː"], "acchi": ["ə", "tʃ", "tʃʰ", "iː"], "acche": ["ə", "tʃ", "tʃʰ", "eː"], "hai": ["ɦ", "ɛː"], "hu": ["ɦ", "uː"], "tha": ["t̪ʰ", "aː"], "thi": ["t̪ʰ", "iː"], "the": ["t̪ʰ", "eː"], "baje": ["b", "ə", "dʒ", "eː"], "kya": ["k", "j", "aː"], "kyu": ["k", "j", "uː"], "nahi": ["n̪", "ə", "ɦ", "iː"], "haan": ["ɦ", "aː", "̃"], "main": ["m", "ɛː", "̃"], "me": ["m", "eː", "̃"], "hum": ["ɦ", "ə", "m"], "tum": ["t̪", "ʊ", "m"], "aap": ["aː", "p"], "ka": ["k", "aː"], "ki": ["k", "iː"], "ke": ["k", "eː"], "ko": ["k", "oː"], "se": ["s", "eː"], "aur": ["ɔː", "ɾ"], "par": ["p", "ə", "ɾ"], "ya": ["j", "aː"], "bhi": ["bʰ", "iː"], "ye": ["j", "eː"], "yeh": ["j", "eː"], "wo": ["ʋ", "oː"], "woh": ["ʋ", "oː"], "naam": ["n̪", "aː", "m"], "kaam": ["k", "aː", "m"], "samay": ["s", "ə", "m", "ə", "j"], "subah": ["s", "ʊ", "b", "ə", "ɦ"], "shaam": ["ʃ", "aː", "m"], "raat": ["ɾ", "aː", "t̪"], "ghar": ["gʰ", "ə", "ɾ"], "dost": ["d̪", "oː", "s", "t̪"], "bhai": ["bʰ", "aː", "iː"], "yaar": ["j", "aː", "ɾ"], "namaste": ["n̪", "ə", "m", "ə", "s", "t̪", "eː"], "namaskar": ["n̪", "ə", "m", "ə", "s", "k", "aː", "ɾ"], "shukriya": ["ʃ", "ʊ", "k", "ɾ", "ɪ", "j", "aː"], "dhanyavaad": ["d̪ʰ", "ə", "n̪", "j", "ə", "ʋ", "aː", "d̪"], "thik": ["ʈʰ", "iː", "k"], "chalo": ["tʃ", "ə", "l", "oː"], "karo": ["k", "ə", "ɾ", "oː"], "karna": ["k", "ə", "ɾ", "n̪", "aː"], "raha": ["ɾ", "ə", "ɦ", "aː"], "rahi": ["ɾ", "ə", "ɦ", "iː"], "rahe": ["ɾ", "ə", "ɦ", "eː"], "batao": ["b", "ə", "t̪", "aː", "oː"], "bolo": ["b", "oː", "l", "oː"], "jaana": ["dʒ", "aː", "n̪", "aː"], "aana": ["aː", "n̪", "aː"], "khana": ["kʰ", "aː", "n̪", "aː"], "paani": ["p", "aː", "n̪", "iː"], "bus": ["b", "ə", "s"], "din": ["d̪", "ɪ", "n̪"], "raasta": ["ɾ", "aː", "s", "t̪", "aː"], "lekin": ["l", "eː", "k", "ɪ", "n̪"], "phir": ["pʰ", "ɪ", "ɾ"], "isliye": ["ɪ", "s", "l", "ɪ", "j", "eː"], "baat": ["b", "aː", "t̪"], "log": ["l", "oː", "g"], "sab": ["s", "ə", "b"], "kuch": ["k", "ʊ", "tʃʰ"], "mera": ["m", "eː", "ɾ", "aː"], "meri": ["m", "eː", "ɾ", "iː"], "mere": ["m", "eː", "ɾ", "eː"], "aapka": ["aː", "p", "k", "aː"], "ek": ["eː", "k"], "do": ["d̪", "oː"], "teen": ["t̪", "iː", "n̪"], "chaar": ["tʃ", "aː", "ɾ"], "paanch": ["p", "aː", "n̪", "tʃ"],}
# Words that exist in BOTH English and Roman-Hindi (disambiguated by clause context voting)AMBIGUOUS_HOMOGRAPHS = {"main", "me", "bus", "in", "on", "to", "is", "are", "he", "do", "din", "man", "bar", "per", "kal"}ROMAN_HINDI_SUFFIXES = ("waala", "wala", "wali", "wale", "raha", "rahi", "rahe", "kar", "naa", "ega", "egi", "oge")
ARPABET_TO_IPA: Dict[str, List[str]] = { "AA": ["ɑː"], "AE": ["æ"], "AH": ["ʌ"], "AH0": ["ə"], "AO": ["ɔː"], "AW": ["aʊ"], "AY": ["aɪ"], "B": ["b"], "CH": ["tʃ"], "D": ["d"],7 unmodified lines
def _strip_stress(arpabet_tok: str) -> str: if arpabet_tok == "AH0": return "AH0" return re.sub(r"[012]$", "", arpabet_tok) return "AH0" if arpabet_tok == "AH0" else re.sub(r"[012]$", "", arpabet_tok)
def _split_devanagari_units(word: str) -> List[str]: """Merge consonant+nukta base pairs into atomic grapheme units.""" chars = list(word) units: List[str] = [] i = 0 while i < len(chars): if i + 1 < len(chars) and chars[i + 1] == "\u093c": # Nukta if i + 1 < len(chars) and chars[i + 1] == "\u093c": units.append(chars[i] + chars[i + 1]) i += 2 else:3 unmodified lines
def hindi_word_to_ipa(word: str) -> List[str]: """ Rule-based Hindi G2P converting a Devanagari word into unified IPA tokens. Handles: - Intrinsic schwa (`अ`) retention vs word-final / medial schwa deletion - Contextual Anusvara (`ं`) assimilation (`ईंधन -> iː n̪ d̪ʰ ə n̪`) - Chandrabindu (`ँ`) nasalization - Retroflexes (`ड़ -> ɽ`, `ढ़ -> ɽʰ`) and aspirated stops """ """Rule-based Hindi G2P converting a Devanagari word into unified IPA tokens.""" units = _split_devanagari_units(word) syllables: List[Tuple[str, List[str], Optional[str]]] = [] # (type, onset/nucleus, nasal)
out: List[str] = [] n = len(units) i = 0 while i < n: u = units[i]
# Independent vowel if u in HI_INDEP_VOWELS: v = HI_INDEP_VOWELS[u] if u == "ऋ": out.extend(["ɾ", "ɪ"]) else: out.append(v) # Check trailing anusvara / chandrabindu out.extend(["ɾ", "ɪ"] if u == "ऋ" else [HI_INDEP_VOWELS[u]]) if i + 1 < n and units[i + 1] in ("ं", "ँ"): mark = units[i + 1] if mark == "ँ": if units[i + 1] == "ँ": out.append("̃") else: next_c = units[i + 2] if i + 2 < n else ""3 unmodified lines i += 1 continue
# Consonant if u in HI_CONSONANTS: cons = HI_CONSONANTS[u] out.extend(cons) nxt = units[i + 1] if i + 1 < n else None
if nxt == "्": # Halant -> suppress inherent schwa if nxt == "्": i += 2 continue elif nxt in HI_MATRAS: # Explicit vowel matra m = HI_MATRAS[nxt] if nxt == "ृ": out.extend(["ɾ", "ɪ"]) else: out.append(m) elif nxt in HI_MATRAS: out.extend(["ɾ", "ɪ"] if nxt == "ृ" else [HI_MATRAS[nxt]]) i += 2 if i < n and units[i] in ("ं", "ँ"): if units[i] == "ँ":4 unmodified lines i += 1 continue else: # Inherent schwa decision: # Suppress word-final schwa on polysyllabic words unless preceded by conjunct has_more_cons = any(units[k] in HI_CONSONANTS or units[k] in HI_INDEP_VOWELS for k in range(i + 1, n)) has_trailing_nasal = nxt in ("ं", "ँ") if has_more_cons or has_trailing_nasal or len(out) <= len(cons): has_more = any(units[k] in HI_CONSONANTS or units[k] in HI_INDEP_VOWELS for k in range(i + 1, n)) has_nasal = nxt in ("ं", "ँ") if has_more or has_nasal or len(out) <= len(cons): out.append("ə") if has_trailing_nasal: if has_nasal: if nxt == "ँ": out.append("̃") else:4 unmodified lines i += 1 continue
# Visarga if u == "ः": out.append("ɦ") i += 1 continue
i += 1
# Collapse redundant doubled identical vowels if any & filter to vocab return [tok for tok in out if tok in TOKEN_TO_ID]
def roman_hindi_to_ipa(word: str) -> List[str]: """Deterministic Romanized Hindi -> Unified IPA mapper.""" w = ROMAN_HINDI_VARIANTS.get(word.lower(), word.lower()) if w in ROMAN_HINDI_LEXICON: return list(ROMAN_HINDI_LEXICON[w])
digraphs = [ ("chh", ["tʃʰ"]), ("ksh", ["k", "ʃ"]), ("kh", ["kʰ"]), ("gh", ["gʰ"]), ("ch", ["tʃ"]), ("jh", ["dʒʰ"]), ("th", ["t̪ʰ"]), ("dh", ["d̪ʰ"]), ("ph", ["pʰ"]), ("bh", ["bʰ"]), ("sh", ["ʃ"]), ("ng", ["ŋ"]), ("aa", ["aː"]), ("ee", ["iː"]), ("ii", ["iː"]), ("oo", ["uː"]), ("uu", ["uː"]), ("ai", ["ɛː"]), ("au", ["ɔː"]), ("ei", ["eː"]), ] singles = { "a": ["ə"], "b": ["b"], "c": ["k"], "d": ["d̪"], "e": ["eː"], "f": ["f"], "g": ["g"], "h": ["ɦ"], "i": ["ɪ"], "j": ["dʒ"], "k": ["k"], "l": ["l"], "m": ["m"], "n": ["n̪"], "o": ["oː"], "p": ["p"], "q": ["q"], "r": ["ɾ"], "s": ["s"], "t": ["t̪"], "u": ["ʊ"], "v": ["ʋ"], "w": ["ʋ"], "x": ["k", "s"], "y": ["j"], "z": ["z"], } out: List[str] = [] i = 0 while i < len(w): matched = False for pat, ipa in digraphs: if w.startswith(pat, i): out.extend(ipa) i += len(pat) matched = True break if not matched: out.extend(singles.get(w[i], [])) i += 1 return [tok for tok in out if tok in TOKEN_TO_ID]
3 unmodified lines if w in EN_LEXICON: return list(EN_LEXICON[w])
# Digraph-first greedy scan digraphs = [ ("tion", ["ʃ", "ə", "n"]), ("sion", ["ʒ", "ə", "n"]), ("igh", ["aɪ"]), ("eigh", ["eɪ"]), ("tch", ["tʃ"]), ("dge", ["dʒ"]),11 unmodified lines "p": ["p"], "q": ["k"], "r": ["r"], "s": ["s"], "t": ["t"], "u": ["ʌ"], "v": ["v"], "w": ["w"], "x": ["k", "s"], "y": ["j"], "z": ["z"], } # Silent final -e lengthens single-syllable simple words lightly if len(w) > 3 and w.endswith("e") and not w.endswith(("ee", "le")): w = w[:-1]
16 unmodified linesclass BilingualTextTokenizer: """ Unified Hindi + English / Hinglish IPA Tokenizer for Murli V2.0. Produces `<bos> [<hi>|<en> phonemes <sp> ...] <eos>` sequences inside vocab_size=256. Includes 3-tier Hinglish word routing, Roman-Hindi variant normalization, context-aware homograph resolution, and context-aware digit expansion. """
def __init__(self, use_g2p_en: bool = True):24 unmodified lines return text
@staticmethod def _detect_chunk_lang(token: str) -> str: if any("\u0900" <= ch <= "\u097f" for ch in token): return "hi" if any("a" <= ch.lower() <= "z" for ch in token): return "en" return "punct"
def _expand_digits(self, text: str, prefer_lang: str) -> str: def repl(match): digits = match.group(0) table = HI_DIGITS if prefer_lang == "hi" else EN_DIGITS return " ".join(table.get(d, d) for d in digits) return re.sub(r"[0-9०-९]+", repl, text) def _is_devanagari(token: str) -> bool: return any("\u0900" <= ch <= "\u097f" for ch in token)
@staticmethod def _is_latin(token: str) -> bool: return any("a" <= ch.lower() <= "z" for ch in token)
@staticmethod def _is_unambiguous_roman_hindi(low: str) -> bool: if low in AMBIGUOUS_HOMOGRAPHS: return False canon = ROMAN_HINDI_VARIANTS.get(low, low) if canon in ROMAN_HINDI_LEXICON and canon not in EN_LEXICON: return True if len(canon) > 4 and canon.endswith(ROMAN_HINDI_SUFFIXES) and canon not in EN_LEXICON: return True return False
def _classify_latin_tokens(self, chunks: List[str], force_lang: Optional[str]) -> List[str]: """3-tier router: unambiguous lexicon/variants -> English lexicon -> clause context vote.""" if force_lang in ("hi", "en"): return [ "hi" if self._is_devanagari(c) else ("en" if self._is_latin(c) and force_lang == "en" else ("hi_roman" if self._is_latin(c) else "punct")) for c in chunks ]
# First pass: score unambiguous Hindi vs English cues per clause raw_kinds: List[str] = [] hi_votes = 0 en_votes = 0 for c in chunks: if self._is_devanagari(c): raw_kinds.append("hi") hi_votes += 2 elif self._is_latin(c): low = c.lower() if self._is_unambiguous_roman_hindi(low): raw_kinds.append("hi_roman") hi_votes += 1 elif low in AMBIGUOUS_HOMOGRAPHS: raw_kinds.append("ambig") elif low in EN_LEXICON: raw_kinds.append("en") en_votes += 1 elif self._g2p_en is not None and low in getattr(self._g2p_en, "cmu", {}): raw_kinds.append("en") en_votes += 1 else: # Unknown Latin word: lean with English unless Hindi suffixes match raw_kinds.append("en") else: raw_kinds.append("punct")
# Second pass: resolve ambiguous homographs by clause context vote resolved: List[str] = [] for idx, k in enumerate(raw_kinds): if k != "ambig": resolved.append(k) continue # Local window vote (+-2 tokens) with clause-level tiebreaker win_hi = sum(1 for j in range(max(0, idx - 2), min(len(raw_kinds), idx + 3)) if raw_kinds[j] in ("hi", "hi_roman")) win_en = sum(1 for j in range(max(0, idx - 2), min(len(raw_kinds), idx + 3)) if raw_kinds[j] == "en") if win_hi != win_en: resolved.append("hi_roman" if win_hi > win_en else "en") else: resolved.append("hi_roman" if hi_votes >= en_votes else "en") return resolved
def _expand_digits_in_context(self, chunks: List[str], default_lang: str) -> List[str]: """Expand digits to Hindi or English words based on neighboring tokens.""" out: List[str] = [] for i, c in enumerate(chunks): if not re.fullmatch(r"[0-9०-९]+", c): out.append(c) continue # Check Devanagari digits or adjacent Hindi/English context cues if any("\u0966" <= ch <= "\u096f" for ch in c): lang = "hi" else: nxt = chunks[i + 1].lower() if i + 1 < len(chunks) else "" prv = chunks[i - 1].lower() if i > 0 else "" if nxt in ("am", "pm", "percent", "hours", "days") or nxt in EN_LEXICON: lang = "en" elif self._is_devanagari(nxt) or self._is_devanagari(prv) or self._is_unambiguous_roman_hindi(nxt) or self._is_unambiguous_roman_hindi(prv): lang = "hi" else: lang = default_lang table = HI_DIGITS if lang == "hi" else EN_DIGITS out.extend(table[d] for d in c if d in table) return out
def english_word_to_ipa(self, word: str) -> List[str]: low = word.lower()14 unmodified lines return _english_rules_to_ipa(word)
def text_to_phonemes(self, text: str, language: Optional[str] = None) -> List[str]: """Convert bilingual Hindi/English/Hinglish text into unified IPA token strings.""" """Convert pure Hindi, English, or mixed/Romanized Hinglish text into unified IPA tokens.""" cleaned = self.clean_text(text) has_devanagari = any("\u0900" <= c <= "\u097f" for c in cleaned) default_lang = language if language in ("hi", "en") else ("hi" if has_devanagari else "en") cleaned = self._expand_digits(cleaned, default_lang) has_dev = any("\u0900" <= c <= "\u097f" for c in cleaned) raw_chunks = re.findall(r"[\u0900-\u097f]+|[A-Za-z]+(?:'[A-Za-z]+)*|[0-9०-९]+|[.,!?;:\-]", cleaned)
# Estimate clause default language before expanding digits hi_cues = sum(1 for c in raw_chunks if self._is_devanagari(c) or self._is_unambiguous_roman_hindi(c.lower())) en_cues = sum(1 for c in raw_chunks if self._is_latin(c) and not self._is_unambiguous_roman_hindi(c.lower()) and c.lower() in EN_LEXICON) default_lang = language if language in ("hi", "en") else ("hi" if (has_dev or hi_cues >= en_cues) else "en")
chunks = self._expand_digits_in_context(raw_chunks, default_lang=default_lang) kinds = self._classify_latin_tokens(chunks, force_lang=language)
# Split into word / Devanagari / Latin (with apostrophe contractions) / punctuation chunks chunks = re.findall(r"[\u0900-\u097f]+|[A-Za-z]+(?:'[A-Za-z]+)*|[.,!?;:\-]", cleaned) tokens: List[str] = ["<bos>"] active_lang: Optional[str] = None
for idx, chunk in enumerate(chunks): kind = self._detect_chunk_lang(chunk) for idx, (chunk, kind) in enumerate(zip(chunks, kinds)): if kind == "punct": if chunk in TOKEN_TO_ID: tokens.append(chunk) continue
target_tag = "<hi>" if kind in ("hi", "hi_roman") else "<en>" if kind != active_lang: tokens.append("<hi>" if kind == "hi" else "<en>") active_lang = kind if target_tag != active_lang: tokens.append(target_tag) active_lang = target_tag
if kind == "hi": phonemes = hindi_word_to_ipa(chunk) elif kind == "hi_roman": phonemes = roman_hindi_to_ipa(chunk) else: phonemes = self.english_word_to_ipa(chunk)
phonemes = hindi_word_to_ipa(chunk) if kind == "hi" else self.english_word_to_ipa(chunk) if phonemes: tokens.extend(phonemes) if idx + 1 < len(chunks) and self._detect_chunk_lang(chunks[idx + 1]) != "punct": if idx + 1 < len(chunks) and kinds[idx + 1] != "punct": tokens.append("<sp>")
tokens.append("<eos>")1 unmodified line
def text_to_ids(self, text: str, language: Optional[str] = None) -> torch.Tensor: phonemes = self.text_to_phonemes(text, language=language) if len(phonemes) <= 2: # Only <bos> and <eos> if len(phonemes) <= 2: return torch.empty(0, dtype=torch.long) ids = [TOKEN_TO_ID.get(p, self.unk_id) for p in phonemes] return torch.tensor(ids, dtype=torch.long)62 unmodified lines63646566676869495 unmodified lines56556656756756856957057157257357457557657457757857958027 unmodified lines6086096106116126136146156126166176186191 unmodified line62162262362062462562662762862963063163262 unmodified lines Source("hindi_female_ivr_18_30", "SayantanJoker/IndicVoices_Hindi_audio_44100_18_30_female", "hi", 100),
Source("hindi_female_ivr_30_45", "SayantanJoker/IndicVoices_Hindi_audio_44100_30_45_female", "hi", 100),
Source("hindi_indicvoices", "ai4bharat/IndicVoices", "hi", config="hindi", audio="audio_filepath"),
Source("english_indictts", "SPRINGLab/IndicTTS-English", "en", 100),
Source("english_libritts_r_100", "parler-tts/libritts_r_filtered", "en", 100, "clean", "train.clean.100"),
Source("english_libritts_r_360", "parler-tts/libritts_r_filtered", "en", 360, "clean", "train.clean.360"),
Source("english_mls", "parler-tts/mls_eng", "en"),495 unmodified lines
def run(curator, goals, only):
def run(curator, goals, only, cap_overrides=None):
failed = []
cap_overrides = cap_overrides or {}
for src in SOURCES:
if only and src.name != only:
continue
committed = sum(curator.states[s.name]["curated_hours"] for s in SOURCES if s.lang == src.lang)
state = curator.states[src.name]
eff_cap = cap_overrides.get(src.name, src.cap)
target = min(src.cap, state["curated_hours"] + max(0, goals[src.lang] - committed))
target = min(eff_cap, state["curated_hours"] + max(0, goals[src.lang] - committed))
if state["curated_hours"] >= target:
continue
try:27 unmodified lines parser.add_argument("--migrate_50h", action="store_true", help="Copy the separate V1 baseline")
parser.add_argument("--hindi_hours", type=float, default=400)
parser.add_argument("--english_hours", type=float, default=650)
parser.add_argument("--indictts_en_hours", type=float, default=100.0, help="Target hours for SPRINGLab/IndicTTS-English (e.g., 20 for smoke test)")
parser.add_argument("--shard_mb", type=float, default=350, help="Buffered WAV payload per shard in MiB")
parser.add_argument("--only", choices=[s.name for s in SOURCES])
parser.add_argument("--token")
args = parser.parse_args()
if any(not math.isfinite(x) or x < 0 for x in (args.hindi_hours, args.english_hours)):
if any(not math.isfinite(x) or x < 0 for x in (args.hindi_hours, args.english_hours, args.indictts_en_hours)):
parser.error("Hour targets must be finite and nonnegative")
if not math.isfinite(args.shard_mb) or args.shard_mb <= 0:
parser.error("Shard size must be finite and positive")1 unmodified line curator.initialize()
if args.migrate_50h:
curator.migrate_50h_to_subfolder()
return run(curator, {"hi": args.hindi_hours, "en": args.english_hours}, args.only)
return run(
curator,
{"hi": args.hindi_hours, "en": args.english_hours},
args.only,
cap_overrides={"english_indictts": args.indictts_en_hours},
)
if __name__ == "__main__":106 unmodified lines107108109110111112110111112113114115116117118119120121122123115124125117126127128129130131132133134120121122123124125126135136137138139140141142143144145146147148149150151152153154155106 unmodified lines
text_feats = self.text_encoder(token_ids, text_mask=text_mask)
# Zero-shot reference style conditioning: crop a random sub-window during training # so Perceiver extracts timbre/style without memorizing exact target timing. if ref_mel is not None: # Zero-shot reference style conditioning: # Use cross-utterance ref_mel where available; for single-clip/unknown rows (or ref_mel=None) # fall back to a 25%-50% random sub-window self-crop with light freq/time masking. has_valid_ref = ( ref_mel is not None and (ref_mask is None or bool(ref_mask.any().item())) ) all_rows_have_ref = ( ref_mel is not None and (ref_mask is None or bool(ref_mask.any(dim=1).all().item())) ) if all_rows_have_ref: style_tokens, style_global = self.style_encoder(ref_mel, ref_mask=ref_mask) elif self.training and mel_target.shape[-1] > 32: t_max = mel_target.shape[-1] t_max = max(mel_target.shape[-1], ref_mel.shape[-1] if ref_mel is not None else 0) crop_mel = mel_target.new_zeros(bsz, mel_target.shape[1], t_max) crop_mask = torch.zeros_like(mel_mask) crop_mask = torch.zeros(bsz, t_max, dtype=torch.bool, device=device) lengths = mel_mask.sum(dim=1) for b in range(bsz): row_has_ref = has_valid_ref and (ref_mask is None or bool(ref_mask[b].any().item())) if row_has_ref: rl = int(ref_mask[b].sum().item()) if ref_mask is not None else ref_mel.shape[-1] crop_mel[b, :, :rl] = ref_mel[b, :, :rl] crop_mask[b, :rl] = True else: v_len = max(16, int(lengths[b].item())) w_len = max(16, min(v_len, int(v_len * (0.25 + 0.25 * torch.rand(()).item())))) max_start = max(0, v_len - w_len) st = int(torch.randint(0, max_start + 1, ()).item()) if max_start > 0 else 0 crop_mel[b, :, :w_len] = mel_target[b, :, st : st + w_len] crop_mask[b, :w_len] = True max_w = int(crop_mask.sum(dim=1).max().item()) v_len = max(16, int(lengths[b].item())) w_len = max(16, min(v_len, int(v_len * (0.25 + 0.25 * torch.rand(()).item())))) max_start = max(0, v_len - w_len) st = int(torch.randint(0, max_start + 1, ()).item()) if max_start > 0 else 0 seg = mel_target[b, :, st : st + w_len].clone() # Light SpecAugment-style frequency (<=12 bins) & time (<=15% frames) masking on self-crop f_w = int(torch.randint(1, min(13, seg.shape[0] + 1), ()).item()) f_s = int(torch.randint(0, max(1, seg.shape[0] - f_w + 1), ()).item()) seg[f_s : f_s + f_w, :] = 0.0 t_w = max(1, int(w_len * 0.15 * torch.rand(()).item())) t_s = int(torch.randint(0, max(1, w_len - t_w + 1), ()).item()) seg[:, t_s : t_s + t_w] = 0.0 crop_mel[b, :, :w_len] = seg crop_mask[b, :w_len] = True max_w = max(16, int(crop_mask.sum(dim=1).max().item())) style_tokens, style_global = self.style_encoder(crop_mel[:, :, :max_w], ref_mask=crop_mask[:, :max_w]) elif has_valid_ref: style_tokens, style_global = self.style_encoder(ref_mel, ref_mask=ref_mask) else: style_tokens, style_global = self.style_encoder(mel_target, ref_mask=mel_mask)
180 unmodified lines181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300180 unmodified lines wav2 = synthesize_bilingual_long_text(mock_model, tok, text, torch.device("cpu"), ref_mel=ref, seed=7) np.testing.assert_array_equal(wav1, wav2)
def test_20_sentence_hinglish_suite(self): tok = BilingualTextTokenizer(use_g2p_en=False) sentences = [ # Pure Devanagari Hindi (4) "नमस्ते, आज मौसम बहुत अच्छा है।", "ईंधन और कंबल की जरूरत है।", "बढ़ई ने सुंदर लकड़ी की मेज बनाई।", "कल सुबह पांच बजे मिलते हैं।", # Pure English (4) "Hello friend, please download the audio file.", "We didn't expect the GPU server to finish today.", "The meeting is scheduled in the office at 5 PM.", "That's a good voice model for speech synthesis.", # Roman Hinglish + orthographic variants (5) "Aaj mausam bohot achha hai, lekin kal barish hogi.", "Kyaa aapka kaam abhi nahi hua hai?", "Namaste bhai, shaam ko ghar aana naheen bhoolna.", "Yeh kahani bahut accha aur pyara hai.", "Chalo dost, subah 6 baje walk par chalte hain.", # Mixed Devanagari + Roman code-switching (3) "नमस्ते friend, आज AI model launch हो रहा है!", "मेरा phone और server दोनों fast काम कर रहे हैं।", "आज office में project meeting बहुत good रही।", # Homographs + context numbers (4) "Main aaj 5 baje office me jaunga.", "I am in the main bus on my way to work.", "Bus karo yaar, ab ghar chalo!", "Meet me at 5 PM in the main conference hall.", ] self.assertEqual(len(sentences), 20) for s in sentences: ids = tok.text_to_ids(s) self.assertGreater(ids.numel(), 4, f"Empty/short tokens for: {s}") self.assertLess(int(ids.max().item()), tok.vocab_size)
# Verify homograph routing: "5 baje" -> Hindi paanch (<hi>), "5 PM" -> English five (<en>) hi_num = tok.text_to_phonemes("Main aaj 5 baje jaunga.") en_num = tok.text_to_phonemes("Meet me at 5 PM in the main hall.") self.assertIn("<hi>", hi_num) self.assertIn("p", hi_num) self.assertIn("<en>", en_num) self.assertIn("f", en_num)
# Verify orthographic variants collapse identically self.assertEqual(tok.text_to_phonemes("bohot achha naheen kyaa"), tok.text_to_phonemes("bahut accha nahi kya"))
# Print 5 sample IPA tokenizations for Sprint 1 report print("\n[Sample Hinglish G2P Outputs]") for sample in [sentences[0], sentences[6], sentences[8], sentences[13], sentences[16]]: print(f" TEXT: {sample}") print(f" IPA : {' '.join(tok.text_to_phonemes(sample))}")
def test_cross_utterance_ref_sampling_and_indictts_source(self): import io import tempfile import pyarrow as pa import pyarrow.parquet as pq from scipy.io import wavfile from data.dataset import MurliV2Dataset, v2_collate_fn import kaggle_data_collector as kdc
# Verify SPRINGLab/IndicTTS-English source registration en_src = next(s for s in kdc.SOURCES if s.name == "english_indictts") self.assertEqual(en_src.repo, "SPRINGLab/IndicTTS-English") self.assertEqual(en_src.lang, "en")
buf1, buf2 = io.BytesIO(), io.BytesIO() t = torch.linspace(0.0, 2.0, 48000) wavfile.write(buf1, 24000, (0.3 * torch.sin(2.0 * math.pi * 180.0 * t).numpy() * 32767.0).astype("int16")) wavfile.write(buf2, 24000, (0.4 * torch.sin(2.0 * math.pi * 240.0 * t).numpy() * 32767.0).astype("int16"))
with tempfile.TemporaryDirectory() as tmp: p = Path(tmp) / "shard-00000.parquet" tbl = pa.table({ "audio": [ {"bytes": buf1.getvalue(), "path": "a1.wav"}, {"bytes": buf2.getvalue(), "path": "a2.wav"}, {"bytes": buf1.getvalue(), "path": "u1.wav"}, ], "text": ["नमस्ते दोस्त!", "यह अच्छा दिन है।", "Hello friend!"], "speaker_id": ["spk_known_1", "spk_known_1", "indictts_en_unknown"], "lang": ["hi", "hi", "en"], }) pq.write_table(tbl, p) ds = MurliV2Dataset(parquet_dir=tmp, cross_utterance_ref=True, min_ref_frames=60, max_ref_frames=120) s_known = ds[0] s_unknown = ds[2] self.assertIn("ref_mel", s_known) self.assertLessEqual(s_known["ref_mel"].shape[-1], 120) self.assertNotIn("ref_mel", s_unknown) batch = v2_collate_fn([s_known, s_unknown]) self.assertTrue(bool(batch["ref_mask"][0].any().item())) self.assertFalse(bool(batch["ref_mask"][1].any().item()))
# Mixed-batch training forward (row 0 uses cross-utterance ref, row 1 uses SpecAugment self-crop) cfg = MurliV2Config() cfg.model.dit_layers = 2 cfg.model.text_layers = 2 cfg.model.style_layers = 1 cfg.model.prosody_layers = 2 engine = MurliV2Engine(cfg.model, cfg.training).train() out = engine( token_ids=batch["token_ids"], text_mask=batch["text_mask"], mel_target=batch["mel_target"], mel_mask=batch["mel_mask"], ref_mel=batch["ref_mel"], ref_mask=batch["ref_mask"], f0_target=batch["f0_target"], energy_target=batch["energy_target"], ) self.assertTrue(torch.isfinite(out["loss"])) out["loss"].backward()
if __name__ == "__main__": unittest.main()86 unmodified lines8788899091929394218 unmodified lines31331431531631731831932086 unmodified lines text_mask=batch["text_mask"],
mel_target=batch["mel_target"],
mel_mask=batch["mel_mask"],
ref_mel=batch.get("ref_mel"),
ref_mask=batch.get("ref_mask"),
f0_target=batch["f0_target"],
energy_target=batch["energy_target"],
)218 unmodified lines text_mask=batch["text_mask"],
mel_target=batch["mel_target"],
mel_mask=batch["mel_mask"],
ref_mel=batch.get("ref_mel"),
ref_mask=batch.get("ref_mask"),
f0_target=batch["f0_target"],
energy_target=batch["energy_target"],
)data/dataset.py+87-5
data/text_cleaner.py+235-83
kaggle_data_collector.py+13-4
models/tts_engine.py+37-12
tests/test_v2.py+114
train.py+4