Add run_murli.py standalone Murli V1.0 runner (CLI, interactive, and streaming 10k-word story mode)
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""Murli V1.0 Runner Program (`ViuAI/Murli-V1.0`).Supports: 1. Single text synthesis: python run_murli.py --text "नमस्ते!" 2. Long story (.txt) mode: python run_murli.py --text_file story.txt --output story.wav (Streams paragraph-by-paragraph to WAV with minimal RAM, tested for 10,000+ word stories) 3. Interactive prompt loop: python run_murli.py
Automatically downloads `model.safetensors` from `ViuAI/Murli-V1.0` if no local checkpoint is passed."""
import argparseimport osimport reimport timeimport wavefrom typing import Optional
import numpy as npimport torchfrom huggingface_hub import hf_hub_download
from config import TTS10MConfigfrom data.text_cleaner import TextTokenizerfrom models.tts_engine import TTS10MEnginefrom utils.audio_sanity import save_audiofrom utils.checkpoint import find_checkpoint, load_checkpointfrom utils.long_form import synthesize_long_text
def resolve_device(requested: Optional[str] = None) -> torch.device: """Resolve explicit device or pick CUDA automatically when available.""" if requested: return torch.device(requested) return torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_murli_v1( checkpoint_path: Optional[str] = None, repo_id: str = "ViuAI/Murli-V1.0", device: Optional[torch.device] = None,): """Load Murli V1.0 acoustic weights from local checkpoint or Hugging Face Hub.""" cfg = TTS10MConfig() target_device = device or resolve_device()
resolved_ckpt = checkpoint_path or find_checkpoint() if not resolved_ckpt: print(f"Downloading Murli V1.0 weights from Hugging Face Hub ({repo_id})...") resolved_ckpt = hf_hub_download(repo_id=repo_id, filename="model.safetensors")
model = TTS10MEngine(cfg.model, cfg.training).to(target_device) model = load_checkpoint(model, resolved_ckpt, device=str(target_device)) model.eval() return model, TextTokenizer(), cfg, target_device
def synthesize_file_streaming( model, tokenizer: TextTokenizer, cfg: TTS10MConfig, device: torch.device, text_file: str, output_wav: str, num_steps: int = 48, speed: float = 0.92, cfg_scale: float = 1.5, temperature: float = 0.667, sway: float = -1.0, seed: int = 42,) -> float: """Stream long Hindi text files (10,000+ words) paragraph-by-paragraph into a 24kHz PCM WAV file.""" if not os.path.isfile(text_file): raise FileNotFoundError(f"Story text file not found: {text_file}")
with open(text_file, "r", encoding="utf-8") as f: raw_text = f.read().strip() if not raw_text: raise ValueError(f"Story text file is empty: {text_file}")
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", raw_text) if p.strip()] total_words = len(raw_text.split()) para_silence = np.zeros(int(0.70 * cfg.audio.sample_rate), dtype=np.int16)
out_dir = os.path.dirname(os.path.abspath(output_wav)) if out_dir: os.makedirs(out_dir, exist_ok=True)
print(f"\nStreaming {len(paragraphs)} paragraphs (~{total_words:,} words) -> {output_wav}") t0 = time.perf_counter() total_samples = 0
with wave.open(output_wav, "wb") as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(cfg.audio.sample_rate)
for idx, para in enumerate(paragraphs, 1): wav_f32 = synthesize_long_text( model=model, tokenizer=tokenizer, text=para, device=device, sample_rate=cfg.audio.sample_rate, num_steps=num_steps, speed=speed, cfg_scale=cfg_scale, temperature=temperature, sway_sampling_coef=sway, min_frames=2, seed=seed + idx if seed is not None else None, ) pcm16 = np.clip(wav_f32 * 32767.0, -32768, 32767).astype(np.int16) wf.writeframes(pcm16.tobytes()) total_samples += len(pcm16)
if idx < len(paragraphs): wf.writeframes(para_silence.tobytes()) total_samples += len(para_silence)
elapsed = time.perf_counter() - t0 audio_sec = total_samples / float(cfg.audio.sample_rate) rtf = elapsed / max(audio_sec, 1e-6) if idx % 5 == 0 or idx == len(paragraphs): print( f" [{idx}/{len(paragraphs)}] Audio: {audio_sec / 60.0:.2f} min | " f"Elapsed: {elapsed:.1f}s | RTF: {rtf:.3f}x" )
return total_samples / float(cfg.audio.sample_rate)
def interactive_loop( model, tokenizer: TextTokenizer, cfg: TTS10MConfig, device: torch.device, out_dir: str, num_steps: int, speed: float, cfg_scale: float, temperature: float, sway: float, seed: int,) -> None: """Interactive Hindi terminal prompt loop for quick testing.""" os.makedirs(out_dir, exist_ok=True) print("\nMurli V1.0 Interactive Mode (type Hindi text, or 'exit' to quit)") clip_idx = 1 while True: try: line = input("\nHindi Text > ").strip() except (EOFError, KeyboardInterrupt): print("\nExiting.") break if not line: continue if line.lower() in {"exit", "quit", "q"}: break
out_path = os.path.join(out_dir, f"murli_{clip_idx:03d}.wav") t0 = time.perf_counter() wav = synthesize_long_text( model=model, tokenizer=tokenizer, text=line, device=device, sample_rate=cfg.audio.sample_rate, num_steps=num_steps, speed=speed, cfg_scale=cfg_scale, temperature=temperature, sway_sampling_coef=sway, min_frames=2, seed=seed, ) save_audio(out_path, torch.from_numpy(wav), cfg.audio.sample_rate) dur = len(wav) / float(cfg.audio.sample_rate) print(f"Saved {out_path} ({dur:.2f}s audio in {time.perf_counter() - t0:.2f}s)") clip_idx += 1
def main() -> None: parser = argparse.ArgumentParser(description="Run Murli V1.0 Hindi TTS (short text, 10k-word story file, or interactive CLI)") parser.add_argument("--text", type=str, default=None, help="Hindi text to synthesize directly") parser.add_argument("--text_file", type=str, default=None, help="Path to UTF-8 .txt story file (streams long stories)") parser.add_argument("--output", type=str, default="murli_output.wav", help="Output .wav file path") parser.add_argument("--out_dir", type=str, default="outputs", help="Output directory for interactive mode") parser.add_argument("--checkpoint", type=str, default=None, help="Optional local .safetensors checkpoint") parser.add_argument("--repo_id", type=str, default="ViuAI/Murli-V1.0", help="HF model repository") parser.add_argument("--device", type=str, default=None, help="Device override (cuda or cpu; auto-detected by default)") parser.add_argument("--steps", type=int, default=48, help="ODE Euler steps (default: 48)") parser.add_argument("--speed", type=float, default=0.92, help="Speech rate multiplier (default: 0.92)") parser.add_argument("--cfg_scale", type=float, default=1.5, help="Classifier-Free Guidance scale (default: 1.5)") parser.add_argument("--temperature", type=float, default=0.667, help="Prior noise temperature (default: 0.667)") parser.add_argument("--sway", type=float, default=-1.0, help="Sway sampling coefficient (default: -1.0)") parser.add_argument("--seed", type=int, default=42, help="Random seed") args = parser.parse_args()
device = resolve_device(args.device) print(f"Loading Murli V1.0 on {device}...") model, tokenizer, cfg, device = load_murli_v1( checkpoint_path=args.checkpoint, repo_id=args.repo_id, device=device, )
if args.text_file: dur_s = synthesize_file_streaming( model=model, tokenizer=tokenizer, cfg=cfg, device=device, text_file=args.text_file, output_wav=args.output, num_steps=args.steps, speed=args.speed, cfg_scale=args.cfg_scale, temperature=args.temperature, sway=args.sway, seed=args.seed, ) print(f"Finished story -> {os.path.abspath(args.output)} ({dur_s / 60.0:.2f} min audio)") elif args.text: t0 = time.perf_counter() wav = synthesize_long_text( model=model, tokenizer=tokenizer, text=args.text, device=device, sample_rate=cfg.audio.sample_rate, num_steps=args.steps, speed=args.speed, cfg_scale=args.cfg_scale, temperature=args.temperature, sway_sampling_coef=args.sway, min_frames=2, seed=args.seed, ) save_audio(args.output, torch.from_numpy(wav), cfg.audio.sample_rate) dur_s = len(wav) / float(cfg.audio.sample_rate) print(f"Saved {os.path.abspath(args.output)} ({dur_s:.2f}s audio in {time.perf_counter() - t0:.2f}s)") else: interactive_loop( model=model, tokenizer=tokenizer, cfg=cfg, device=device, out_dir=args.out_dir, num_steps=args.steps, speed=args.speed, cfg_scale=args.cfg_scale, temperature=args.temperature, sway=args.sway, seed=args.seed, )
if __name__ == "__main__": main()run_murli.pyAdded+260