"""Render a Hindi, English or Hinglish script to a mono 24 kHz PCM WAV.""" import argparse import math import os import re import tempfile import wave from pathlib import Path import torch from config import EMOTION_TO_ID, ModelConfig, MurliV15Config from data.text_cleaner import BilingualTextTokenizer from models.tts_engine import MurliV15Engine from models.vocoder import MurliVocoder def script_chunks(text, tokenizer, limit=220): for paragraph in re.split(r"\n\s*\n", text.strip()): sentences = re.split(r"(?<=[редрее!?])\s*|(?<=\.)\s+(?=\S)", paragraph.strip()) parts = [] for sentence in filter(str.strip, sentences): words = [] for word in sentence.split(): if words and tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit: parts.append((" ".join(words), 70)) words = [] if tokenizer.text_to_ids(word).numel() > limit: raise ValueError("A single word exceeds the model chunk limit") words.append(word) if words: parts.append((" ".join(words), 120)) if parts: parts[-1] = (parts[-1][0], 260) yield from parts @torch.inference_mode() def render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion="neutral", speed=None, seed=42): 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 = 0 rendered = 0 for chunk, next_pause in script_chunks(text, tokenizer): ids = tokenizer.text_to_ids(chunk) if not ids.numel(): continue mel = model.synthesize(ids[None].to(device), emotion_id=emotion_id, speed=speed) samples = vocoder.decode(mel)[0].float().cpu().flatten() if not samples.numel() or not torch.isfinite(samples).all(): raise ValueError("Vocoder returned invalid audio") 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("