Download narrate.py from ViuAI/Murli-V1.6-Code: direct link, hf CLI and curl.
- Browser
- Download file 9.2 kB
-
https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/narrate.py
- Command line
-
hf download hf://ViuAI/Murli-V1.6-Code/narrate.py
-
curl -L -o narrate.py https://huggingface.co/ViuAI/Murli-V1.6-Code/resolve/main/narrate.py
9.2 kB
| """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 | |
| 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("<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, speaker="0", emotion="neutral", speed=None, language="hi", use_ema=True, steps=None, cfg_scale=None, temperature=None): | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| state = torch.load(checkpoint, map_location="cpu", weights_only=True) | |
| cfg = MurliV16Config() | |
| if "model_config" in state: | |
| cfg.model = ModelConfig(**state["model_config"]) | |
| if "audio_config" in state: | |
| cfg.audio = AudioConfig(**state["audio_config"]) | |
| spk_map = state.get("speaker_to_id") or {} | |
| if str(speaker) in spk_map: | |
| speaker_id = int(spk_map[str(speaker)]) | |
| else: | |
| speaker_id = resolve_speaker_id(speaker) | |
| if spk_map and speaker_id not in set(int(v) for v in spk_map.values()): | |
| raise ValueError( | |
| f"Speaker {speaker!r} (id={speaker_id}) is not trained in this checkpoint. " | |
| f"Available speakers: {spk_map}" | |
| ) | |
| model = MurliV16Engine(cfg) | |
| weights = (state.get("ema_model") or state["model"]) if use_ema else state["model"] | |
| model.load_state_dict(weights) | |
| del state | |
| model.to(device).eval() | |
| tokenizer = BilingualTextTokenizer(use_g2p_en=False) | |
| vocoder = MurliVocoder(repo_id=cfg.model.vocoder_repo) | |
| render_with_model( | |
| model, tokenizer, vocoder, cfg, text, destination, | |
| speaker_id=speaker_id, emotion=emotion, speed=speed, language=language, | |
| steps=steps, cfg_scale=cfg_scale, temperature=temperature, | |
| ) | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--checkpoint", required=True) | |
| p.add_argument("--output", required=True) | |
| p.add_argument("--speaker", default="0", help="Speaker ID (default 0=syspin_male_01) or alias") | |
| p.add_argument("--emotion", choices=sorted(EMOTION_TO_ID), default="neutral") | |
| p.add_argument("--speed", type=float) | |
| p.add_argument("--steps", type=int) | |
| p.add_argument("--cfg_scale", type=float) | |
| p.add_argument("--temperature", type=float) | |
| p.add_argument("--language", choices=["hi", "en", "auto"], default="hi") | |
| p.add_argument("--no_ema", action="store_true", help="Use raw model weights instead of EMA weights") | |
| text_group = p.add_mutually_exclusive_group(required=True) | |
| text_group.add_argument("--text") | |
| text_group.add_argument("--text_file") | |
| args = p.parse_args() | |
| text = Path(args.text_file).read_text(encoding="utf-8") if args.text_file else args.text | |
| render( | |
| args.checkpoint, text, args.output, args.speaker, args.emotion, args.speed, | |
| args.language, use_ema=not args.no_ema, steps=args.steps, cfg_scale=args.cfg_scale, temperature=args.temperature, | |
| ) | |