File size: 5,217 Bytes
79b2661 5d91cb9 79b2661 5d91cb9 79b2661 5d91cb9 79b2661 5d91cb9 79b2661 | 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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | """
Long-Form Story & Clause-Level Synthesis Engine (Phase 1 Inference Patch).
Reduces syllable dropping, edge truncation, and boundary merging via:
1. Clause-level chunking (sentences + long comma clauses)
2. Start/end boundary space padding
3. Minimum frame floor (min_frames=2) & gentle pacing (speed=0.92)
4. Natural inter-clause (150ms), inter-sentence (350ms), and inter-paragraph (700ms) pauses
"""
import re
import numpy as np
import torch
from typing import Callable, List, Optional, Tuple
from .audio_sanity import debuzz_waveform
def split_into_clauses(paragraph: str, max_clause_words: int = 12) -> List[Tuple[str, str]]:
"""
Splits a paragraph into (clause_text, pause_type) tuples.
pause_type is 'comma' (150ms) or 'sentence' (350ms).
"""
if max_clause_words < 1:
raise ValueError("max_clause_words must be positive.")
sentences = re.split(r"(?<=[।॥!?])(?![।॥!?])\s*|(?<=\.)\s+", paragraph.strip())
clauses = []
for sentence in filter(None, sentences):
words = sentence.split()
while len(words) > max_clause_words:
# Prefer the last comma within the budget, otherwise use a word boundary.
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_long_text(
model,
tokenizer,
text: str,
device: torch.device,
sample_rate: int = 24000,
num_steps: int = 48,
speed: float = 0.92,
cfg_scale: float = 1.5,
temperature: float = 0.667,
sway_sampling_coef: float = -1.0,
min_frames: int = 2,
seed: int = 42,
normalize_hindi: bool = True,
debuzz: bool = True,
progress_cb: Optional[Callable[[int, int, float], None]] = None,
) -> np.ndarray:
"""
Synthesizes multi-sentence / long story Hindi text cleanly without truncation or clicks.
Returns 1D float32 numpy waveform in [-1.0, 1.0].
"""
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.")
all_para_clauses = [split_into_clauses(p) for p in paragraphs]
total_clauses = sum(len(c) for c in all_para_clauses)
fade_samples = int(0.012 * sample_rate) # 12ms fade in/out
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)
audio_chunks: List[np.ndarray] = []
done = 0
space = torch.tensor([tokenizer.ASCII_START], dtype=torch.long)
generator = torch.Generator(device=device).manual_seed(seed) if seed is not None else None
for p_idx, clauses in enumerate(all_para_clauses):
for c_idx, (clause, pause_type) in enumerate(clauses):
done += 1
if normalize_hindi and hasattr(tokenizer, "normalize_hindi_pronunciation"):
clause = tokenizer.normalize_hindi_pronunciation(clause)
ids = tokenizer.text_to_ids(clause)
if ids.numel() > 2046:
raise ValueError("A clause exceeds 2046 tokens. Add word boundaries or shorten the text.")
ids = torch.cat((space, ids, space)).unsqueeze(0).to(device)
out = model.synthesize(
ids,
num_steps=num_steps,
speed=speed,
cfg_scale=cfg_scale,
temperature=temperature,
sway_sampling_coef=sway_sampling_coef,
min_frames=min_frames,
return_waveform=True,
generator=generator,
)
wav = out["waveform"].squeeze(0).cpu().numpy().astype(np.float32)
if wav.size == 0 or not np.isfinite(wav).all():
raise ValueError(f"Clause {done} produced an empty or non-finite waveform.")
if debuzz:
wav = debuzz_waveform(wav, sample_rate=sample_rate)
peak = np.max(np.abs(wav))
if peak > 1e-4:
wav = wav / peak * 0.90
if len(wav) > 2 * fade_samples:
wav[:fade_samples] *= np.linspace(0.0, 1.0, fade_samples, dtype=np.float32)
wav[-fade_samples:] *= np.linspace(1.0, 0.0, fade_samples, dtype=np.float32)
audio_chunks.append(wav)
is_last_clause_in_para = (c_idx == len(clauses) - 1)
if not is_last_clause_in_para:
audio_chunks.append(sent_pause if pause_type == "sentence" else comma_pause)
if progress_cb is not None:
cur_dur = sum(len(ch) for ch in audio_chunks) / float(sample_rate)
progress_cb(done, total_clauses, cur_dur)
if p_idx < len(all_para_clauses) - 1:
audio_chunks.append(para_pause)
return np.concatenate(audio_chunks)
|