File size: 4,355 Bytes
a1cd84e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | """
Murli V2.0 Bilingual Long-Form Synthesis (Hindi + English + Hinglish).
Splits multi-paragraph stories cleanly across `।`, `॥`, `.`, `!`, `?` boundaries,
preserves Zero-Shot voice cloning reference `ref_mel` across chunks, and stitches
clauses with smooth fade edges and natural pauses.
"""
import re
from typing import List, Optional, Tuple
import numpy as np
import torch
def split_bilingual_clauses(paragraph: str, max_clause_words: int = 16) -> List[Tuple[str, str]]:
"""Split a bilingual paragraph into `(clause_text, pause_type)` pairs."""
if max_clause_words < 1:
raise ValueError("max_clause_words must be >= 1")
sentences = re.split(r"(?<=[।॥.!?])(?![।॥.!?])\s+", paragraph.strip())
clauses: List[Tuple[str, str]] = []
for sent in filter(None, sentences):
words = sent.split()
while len(words) > max_clause_words:
cut = next(
(i for i in range(max_clause_words, 0, -1) if words[i - 1].endswith((",", ";", ":"))),
max_clause_words,
)
clauses.append((" ".join(words[:cut]), "comma"))
words = words[cut:]
if words:
clauses.append((" ".join(words), "sentence"))
return clauses
@torch.no_grad()
def synthesize_bilingual_long_text(
model,
tokenizer,
text: str,
device: torch.device,
ref_mel: Optional[torch.Tensor] = None,
ref_mask: Optional[torch.Tensor] = None,
sample_rate: int = 24000,
language: Optional[str] = None,
num_steps: int = 32,
method: str = "midpoint",
speed: float = 1.0,
cfg_scale: float = 1.8,
temperature: float = 0.65,
sway_sampling_coef: float = -1.0,
pitch_shift: float = 0.0,
energy_scale: float = 1.0,
min_frames: int = 2,
seed: int = 42,
) -> np.ndarray:
"""Synthesize arbitrarily long bilingual Hindi/English stories cleanly."""
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text.strip()) if p.strip()]
if not paragraphs:
raise ValueError("Input text is empty.")
fade = int(0.012 * sample_rate)
comma_pause = np.zeros(int(0.15 * sample_rate), dtype=np.float32)
sent_pause = np.zeros(int(0.35 * sample_rate), dtype=np.float32)
para_pause = np.zeros(int(0.70 * sample_rate), dtype=np.float32)
chunks: List[np.ndarray] = []
gen = torch.Generator(device=device).manual_seed(seed) if seed is not None else None
for para in paragraphs:
paragraph_start = len(chunks)
clauses = split_bilingual_clauses(para)
for c_idx, (clause, pause_type) in enumerate(clauses):
ids = tokenizer.text_to_ids(clause, language=language)
if ids.numel() == 0:
continue
out = model.synthesize(
ids.unsqueeze(0).to(device),
ref_mel=ref_mel,
ref_mask=ref_mask,
num_steps=num_steps,
method=method,
speed=speed,
cfg_scale=cfg_scale,
temperature=temperature,
sway_sampling_coef=sway_sampling_coef,
pitch_shift=pitch_shift,
energy_scale=energy_scale,
min_frames=min_frames,
return_waveform=True,
generator=gen,
)
wav = out["waveform"].squeeze(0).cpu().numpy().astype(np.float32)
if wav.size == 0 or not np.isfinite(wav).all():
raise ValueError(f"Empty or non-finite waveform on clause: {clause!r}")
peak = float(np.max(np.abs(wav)))
if peak > 1e-4:
wav = wav / peak * 0.90
if len(wav) > 2 * fade:
wav[:fade] *= np.linspace(0.0, 1.0, fade, dtype=np.float32)
wav[-fade:] *= np.linspace(1.0, 0.0, fade, dtype=np.float32)
if paragraph_start and len(chunks) == paragraph_start:
chunks.append(para_pause)
chunks.append(wav)
if c_idx < len(clauses) - 1:
chunks.append(sent_pause if pause_type == "sentence" else comma_pause)
if not chunks:
raise ValueError("No valid audio synthesized from input text.")
return np.concatenate(chunks)
|