File size: 9,199 Bytes
870eedf
 
 
 
 
 
 
 
 
 
 
42e63f8
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e63f8
 
 
 
870a8cd
42e63f8
870eedf
42e63f8
 
 
 
 
 
 
 
 
 
 
 
870eedf
42e63f8
870eedf
 
42e63f8
 
 
 
 
 
870eedf
 
 
870a8cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850083c
870a8cd
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870a8cd
870eedf
870a8cd
850083c
870eedf
 
 
 
 
 
 
870a8cd
 
 
870eedf
 
 
 
870a8cd
 
 
870eedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870a8cd
870eedf
 
 
 
 
42e63f8
 
870eedf
 
 
 
 
42e63f8
 
 
 
 
870eedf
42e63f8
 
870eedf
 
 
8d10455
42e63f8
 
 
870a8cd
42e63f8
870eedf
 
 
 
 
 
42e63f8
870eedf
 
870a8cd
 
 
42e63f8
 
870eedf
 
 
 
 
870a8cd
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""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


@torch.inference_mode()
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()


@torch.inference_mode()
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,
    )