Download utils/long_form.py from ViuAI/TTS_10M: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/ViuAI/TTS_10M/resolve/main/utils/long_form.py
- Command line
-
hf download hf://ViuAI/TTS_10M/utils/long_form.py
-
curl -L -o long_form.py https://huggingface.co/ViuAI/TTS_10M/resolve/main/utils/long_form.py
5.22 kB
| """ | |
| 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 | |
| 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) | |