Download narrate.py from ViuAI/Murli-V1.5-Code: direct link, hf CLI and curl.
- Browser
- Download file 5.62 kB
-
https://huggingface.co/ViuAI/Murli-V1.5-Code/resolve/main/narrate.py
- Command line
-
hf download hf://ViuAI/Murli-V1.5-Code/narrate.py
-
curl -L -o narrate.py https://huggingface.co/ViuAI/Murli-V1.5-Code/resolve/main/narrate.py
5.62 kB
| """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 | |
| 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("<i2", copy=False) | |
| wav.writeframesraw(pcm_gap.tobytes()) | |
| pcm = samples.clamp(-1, 1).mul(32767).round().short().numpy().astype("<i2", copy=False) | |
| wav.writeframesraw(pcm.tobytes()) | |
| pause = next_pause | |
| rendered += 1 | |
| if not rendered: | |
| raise ValueError("Script contains no speakable text") | |
| os.replace(temporary, destination) | |
| finally: | |
| Path(temporary).unlink(missing_ok=True) | |
| if was_training: | |
| model.train() | |
| def render(checkpoint, text, destination, emotion="neutral", speed=None): | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| state = torch.load(checkpoint, map_location="cpu", weights_only=True) | |
| cfg = MurliV15Config() | |
| if "model_config" in state: | |
| cfg.model = ModelConfig(**state["model_config"]) | |
| emotion_id = EMOTION_TO_ID[emotion] | |
| if emotion_id and "emotion_counts" in state and not state["emotion_counts"].get(emotion_id): | |
| raise ValueError(f"This checkpoint has no training examples for {emotion!r}. Use a trained style.") | |
| model = MurliV15Engine(cfg) | |
| model.load_state_dict(state["model"]) | |
| del state | |
| model.to(device).eval() | |
| tokenizer = BilingualTextTokenizer(use_g2p_en=False) | |
| vocoder = MurliVocoder() | |
| render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion=emotion, speed=speed) | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", required=True) | |
| source = parser.add_mutually_exclusive_group(required=True) | |
| source.add_argument("--text") | |
| source.add_argument("--text_file", type=Path, help="UTF-8 script") | |
| parser.add_argument("--output", required=True) | |
| parser.add_argument("--emotion", choices=EMOTION_TO_ID, default="neutral") | |
| parser.add_argument("--speed", type=float) | |
| args = parser.parse_args() | |
| text = args.text_file.read_text(encoding="utf-8-sig") if args.text_file else args.text | |
| render(args.checkpoint, text, args.output, args.emotion, args.speed) | |