File size: 5,621 Bytes
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41ba478
cc5e704
41ba478
 
 
 
 
 
 
 
 
 
 
cc5e704
41ba478
cc5e704
 
 
 
fad5e83
ff2327f
cc5e704
 
 
 
 
ff2327f
 
fad5e83
cc5e704
 
 
fad5e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5e704
 
 
ff2327f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5e704
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Render a Hindi, English or Hinglish script to a mono 24 kHz PCM WAV."""
import argparse
import math
import os
import re
import tempfile
import wave
from pathlib import Path

import torch

from config import EMOTION_TO_ID, ModelConfig, MurliV15Config
from data.text_cleaner import BilingualTextTokenizer
from models.tts_engine import MurliV15Engine
from models.vocoder import MurliVocoder


def script_chunks(text, tokenizer, limit=220):
    for paragraph in re.split(r"\n\s*\n", text.strip()):
        sentences = re.split(r"(?<=[।॥!?])\s*|(?<=\.)\s+(?=\S)", paragraph.strip())
        parts = []
        for sentence in filter(str.strip, sentences):
            words = []
            for word in sentence.split():
                if words and tokenizer.text_to_ids(" ".join(words + [word])).numel() > limit:
                    parts.append((" ".join(words), 70))
                    words = []
                if tokenizer.text_to_ids(word).numel() > limit:
                    raise ValueError("A single word exceeds the model chunk limit")
                words.append(word)
            if words:
                parts.append((" ".join(words), 120))
        if parts:
            parts[-1] = (parts[-1][0], 260)
            yield from parts


@torch.inference_mode()
def render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion="neutral", speed=None, seed=42):
    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 = 0
                rendered = 0
                for chunk, next_pause in script_chunks(text, tokenizer):
                    ids = tokenizer.text_to_ids(chunk)
                    if not ids.numel():
                        continue
                    mel = model.synthesize(ids[None].to(device), emotion_id=emotion_id, speed=speed)
                    samples = vocoder.decode(mel)[0].float().cpu().flatten()
                    if not samples.numel() or not torch.isfinite(samples).all():
                        raise ValueError("Vocoder returned invalid audio")
                    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, emotion="neutral", speed=None):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    state = torch.load(checkpoint, map_location="cpu", weights_only=True)
    cfg = MurliV15Config()
    if "model_config" in state:
        cfg.model = ModelConfig(**state["model_config"])
    emotion_id = EMOTION_TO_ID[emotion]
    if emotion_id and "emotion_counts" in state and not state["emotion_counts"].get(emotion_id):
        raise ValueError(f"This checkpoint has no training examples for {emotion!r}. Use a trained style.")
    model = MurliV15Engine(cfg)
    model.load_state_dict(state["model"])
    del state
    model.to(device).eval()
    tokenizer = BilingualTextTokenizer(use_g2p_en=False)
    vocoder = MurliVocoder()
    render_with_model(model, tokenizer, vocoder, cfg, text, destination, emotion=emotion, speed=speed)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--checkpoint", required=True)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--text")
    source.add_argument("--text_file", type=Path, help="UTF-8 script")
    parser.add_argument("--output", required=True)
    parser.add_argument("--emotion", choices=EMOTION_TO_ID, default="neutral")
    parser.add_argument("--speed", type=float)
    args = parser.parse_args()
    text = args.text_file.read_text(encoding="utf-8-sig") if args.text_file else args.text
    render(args.checkpoint, text, args.output, args.emotion, args.speed)