"""Render a Hindi, English or Hinglish script to a mono 24 kHz PCM WAV using Murli V1.6.""" import argparse import math import os import re import tempfile import wave from pathlib import Path import torch from config import EMOTION_TO_ID, SPEAKER_ALIASES, AudioConfig, ModelConfig, MurliV16Config from data.text_cleaner import BilingualTextTokenizer from models.tts_engine import MurliV16Engine from models.vocoder import MurliVocoder def resolve_speaker_id(raw_speaker) -> int: if isinstance(raw_speaker, int): return raw_speaker s = str(raw_speaker).strip() if s.isdigit(): return int(s) if s in SPEAKER_ALIASES: return SPEAKER_ALIASES[s] if s.lower() in SPEAKER_ALIASES: return SPEAKER_ALIASES[s.lower()] raise ValueError(f"Unknown speaker {raw_speaker!r}. Valid options: {sorted(SPEAKER_ALIASES)}") _ABBREV_RE = re.compile(r"\b(?:Dr|Mr|Mrs|Ms|Prof|Sr|Jr|St|vs|etc|e\.g|i\.e)\.$", re.IGNORECASE) _SENTENCE_RE = re.compile(r".+?(?:[।॥!?]+[\"'”’)]*(?=\s|\Z)|\.[\"'”’)]*(?=\s+\S|\Z)|\Z)") def script_chunks(text, tokenizer, limit=220, language="hi", merge_short=False): lang_arg = None if language == "auto" else language for paragraph in re.split(r"\n\s*\n", text.strip()): para = paragraph.strip() if not para: continue sentences = [] for match in _SENTENCE_RE.finditer(para): s = match.group(0).strip() if not s: continue if sentences and _ABBREV_RE.search(sentences[-1]): sentences[-1] = f"{sentences[-1]} {s}" else: sentences.append(s) parts = [] for sentence in sentences: words = [] for word in sentence.split(): candidate = " ".join([*words, word]) if tokenizer.text_to_ids(candidate, language=lang_arg).numel() > limit: if not words or tokenizer.text_to_ids(word, language=lang_arg).numel() > limit: raise ValueError("A single word exceeds the model chunk limit") parts.append((" ".join(words), 70)) words = [] words.append(word) if words: parts.append((" ".join(words), 120)) if merge_short and len(parts) > 1: merged = [] i = 0 while i < len(parts): txt, gap = parts[i] if len(txt.split()) <= 3 and i + 1 < len(parts): nxt_txt, nxt_gap = parts[i + 1] combined = f"{txt} {nxt_txt}" if tokenizer.text_to_ids(combined, language=lang_arg).numel() <= limit: merged.append((combined, nxt_gap)) i += 2 continue merged.append((txt, gap)) i += 1 parts = merged if parts: parts[-1] = (parts[-1][0], 260) yield from parts @torch.inference_mode() def render_with_model( model, tokenizer, vocoder, cfg, text, destination, speaker_id=0, emotion="neutral", speed=None, seed=42, language="hi", steps=None, cfg_scale=None, temperature=None, ): device = next(model.parameters()).device emotion_id = EMOTION_TO_ID[emotion] destination = Path(destination) destination.parent.mkdir(parents=True, exist_ok=True) if speed is not None and (not math.isfinite(speed) or speed <= 0): raise ValueError("Speed must be finite and positive") was_training = model.training model.eval() devices = [device.index or 0] if device.type == "cuda" else [] with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as f: temporary = f.name try: with torch.random.fork_rng(devices=devices): if seed is not None: torch.manual_seed(int(seed)) if device.type == "cuda": torch.cuda.manual_seed(int(seed)) with wave.open(temporary, "wb") as wav: wav.setparams((1, 2, cfg.audio.sample_rate, 0, "NONE", "not compressed")) pause = 150 rendered = 0 for chunk, next_pause in script_chunks(text, tokenizer, language=language, merge_short=True): ids = tokenizer.text_to_ids(chunk, language=(None if language == "auto" else language)) if not ids.numel(): continue mel = model.synthesize( ids[None].to(device), speaker_id=int(speaker_id), emotion_id=emotion_id, speed=speed, steps=steps, cfg_scale=cfg_scale, temperature=temperature, ) samples = vocoder.decode(mel)[0].float().cpu().flatten() if not samples.numel() or not torch.isfinite(samples).all(): raise ValueError("Vocoder returned invalid audio") peak = float(samples.abs().max()) if peak > 0.95: samples = samples * (0.95 / peak) fade = min(samples.numel() // 2, cfg.audio.sample_rate // 200) if fade: ramp = torch.linspace(0, 1, fade) samples[:fade] *= ramp samples[-fade:] *= ramp.flip(0) if pause > 0: n_gap = round(cfg.audio.sample_rate * pause / 1000) room = (torch.randn(n_gap) * 1.5e-4).clamp(-0.002, 0.002) pcm_gap = room.mul(32767).round().short().numpy().astype("