File size: 8,273 Bytes
a3a45e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Speak text with a fixed-shape tiny-voca LiteRT model at 24 kHz."""

# Sentence handling is adapted from src/tiny_voca/infer.py of
# https://github.com/n4ze3m/tiny-voca at commit b4603fc4e2baf08b1f91ea3d6ce8591e8eacffe7
# (Apache-2.0).

import argparse
import json
import math
from pathlib import Path
import re

from ai_edge_litert.compiled_model import CompiledModel
from ai_edge_litert.hardware_accelerator import HardwareAccelerator
import dizione
import numpy as np
import soundfile as sf


VOICES = ("F2", "M2")
HOP = 256
SAMPLE_RATE = 24000
PEAK = 0.99
SPACE = re.compile("[\\s" + chr(0xFEFF) + "]+")
SENTENCE_END = re.compile(r"""(?:(?<=[.!?…])|(?<=[.!?…]["')\]]))\s+(?=["'(\[]?[A-Z0-9])""")
NOT_AN_END = re.compile(
    r"(?:\b(?:mr|mrs|ms|dr|prof|sr|jr|st|vs|etc|no|inc|ltd|co|e\.g|i\.e|a\.m|p\.m)|\b[A-Z])\.$",
    re.IGNORECASE | re.ASCII,
)
CLAUSE_END = re.compile(r"(?<=[,;:—])\s+")
TEXT_END = re.compile("[\\s" + chr(0xFEFF) + "]+$")
CLOSING = "\"'”’)]»"


class UtteranceTooLong(ValueError):
    pass


def sentences(text):
    parts, current = [], ""
    for piece in SENTENCE_END.split(SPACE.sub(" ", text).strip()):
        current = f"{current} {piece}" if current else piece
        if not NOT_AN_END.search(current):
            parts.append(current)
            current = ""
    if current:
        parts.append(current)
    return [part for part in parts if any(char.isalnum() for char in part)]


def finished(text):
    body = TEXT_END.sub("", text)
    if not body:
        return text
    last = SPACE.split(body)[-1]
    if any(char.isalnum() for char in last):
        marked = last.rstrip(CLOSING)[-1:] in tuple(".!?…,;:")
    else:
        marked = any(char in ".!?…" for char in last) or last in (",", ";", ":")
    return text if marked else body + "."


def shorter(text):
    pieces = CLAUSE_END.split(text)
    if len(pieces) > 1:
        return pieces
    words = text.split(" ")
    if len(words) < 2:
        return []
    half = (len(words) + 1) // 2
    return [" ".join(words[:half]), " ".join(words[half:])]


def case_noise(seed):
    return np.random.default_rng(seed).standard_normal(3000 * HOP).astype(np.float32)


class Speaker:
    def __init__(self, path):
        self.model = CompiledModel.from_file(str(path), hardware_accel=HardwareAccelerator.CPU)
        self.signature = "serving_default"
        inputs = self.model.get_input_tensor_details(self.signature)
        self.max_tokens = int(inputs["tokens"]["shape"][-1])
        self.max_samples = int(inputs["noise"]["shape"][-1])
        if self.max_samples % HOP:
            raise ValueError("Noise input size must be a multiple of 256 samples.")
        outputs = self.model.get_output_tensor_details(self.signature)
        self.inputs = {
            name: self.model.create_input_buffer_by_name(self.signature, name) for name in inputs
        }
        self.outputs = {
            name: self.model.create_output_buffer_by_name(self.signature, name) for name in outputs
        }

    def speak_ids(self, ids, stress, voice, speed, pitch_shift, pitch_range, noise):
        if len(ids) != len(stress) or not len(ids):
            raise ValueError("Expected matching nonempty ids and stress.")
        if len(ids) > self.max_tokens:
            raise UtteranceTooLong("Utterance exceeds the graph token limit.")
        if not (0.25 <= speed <= 4 and math.isfinite(pitch_shift) and 0 <= pitch_range <= 3):
            raise ValueError("Speed must be 0.25 to 4, pitch shift finite and pitch range 0 to 3.")
        if noise.shape != (self.max_samples,) or noise.dtype != np.float32:
            raise ValueError(f"Expected {self.max_samples} noise samples in float32.")
        pad = (0, self.max_tokens - len(ids))
        feed = {
            "tokens": np.pad(np.asarray(ids, dtype=np.int32), pad)[None],
            "stress": np.pad(np.asarray(stress, dtype=np.int32), pad)[None],
            "voice": np.array([VOICES.index(voice)], dtype=np.int32),
            "speed": np.array([speed], dtype=np.float32),
            "pitch_shift": np.array([pitch_shift], dtype=np.float32),
            "pitch_range": np.array([pitch_range], dtype=np.float32),
            "noise": noise[None],
        }
        for name, value in feed.items():
            self.inputs[name].write(value)
        self.model.run_by_name(self.signature, self.inputs, self.outputs)
        total = int(self.outputs["total_frames"].read(1, np.int32)[0])
        durations = self.outputs["durations"].read(self.max_tokens, np.int32)
        if (durations < 0).any() or durations[len(ids):].any() or int(durations.sum()) != total:
            raise RuntimeError("The graph returned inconsistent durations.")
        samples = total * HOP
        if samples > self.max_samples:
            raise UtteranceTooLong("Utterance exceeds the graph frame limit.")
        if samples == 0:
            raise RuntimeError("The graph produced no frames.")
        audio = self.outputs["audio"].read(self.max_samples, np.float32)[:samples].copy()
        if not np.isfinite(audio).all():
            raise RuntimeError("The graph produced non-finite audio.")
        return audio, durations[:len(ids)].copy()

    def speak_text(self, text, voice, speed, pitch_shift, pitch_range, seed):
        waves, utterances = [], []

        def read(piece):
            try:
                phones = dizione.phonemize(piece)
            except ValueError as exc:
                if str(exc) == "the text has nothing to pronounce":
                    return
                raise
            if len(phones.ids) <= self.max_tokens - 12:
                try:
                    wave, durations = self.speak_ids(
                        phones.ids, phones.stress, voice, speed, pitch_shift, pitch_range,
                        case_noise(seed + len(waves))[:self.max_samples],
                    )
                except UtteranceTooLong:
                    pass
                else:
                    waves.append(wave)
                    utterances.append({"text": piece, "durations": durations.tolist(), "samples": wave.size})
                    return
            parts = shorter(piece)
            if not parts:
                raise UtteranceTooLong(f"One word is too long to speak: {piece[:40]!r}")
            for part in parts:
                read(part)

        for piece in sentences(finished(text)):
            read(piece)
        if not waves:
            raise ValueError("Nothing in the text could be read. Tiny-voca only reads English for now.")
        raw = np.concatenate(waves)
        raw_peak = float(np.abs(raw).max())
        limited = raw * (PEAK / raw_peak) if raw_peak > PEAK else raw
        return limited, utterances, raw_peak


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--model", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--text")
    source.add_argument("--text-file", type=Path)
    parser.add_argument("--voice", choices=VOICES, default="F2")
    parser.add_argument("--speed", type=float, default=1.0)
    parser.add_argument("--pitch-shift", type=float, default=0.0)
    parser.add_argument("--pitch-range", type=float, default=1.0)
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    if args.seed < 0:
        parser.error("Seed must be nonnegative.")
    text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8")
    try:
        speaker = Speaker(args.model)
        audio, utterances, raw_peak = speaker.speak_text(
            text, args.voice, args.speed, args.pitch_shift, args.pitch_range, args.seed
        )
    except ValueError as exc:
        parser.exit(1, f"{exc}\n")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    sf.write(args.output, audio, SAMPLE_RATE, subtype="FLOAT")
    print(json.dumps({
        "file": str(args.output), "voice": args.voice, "sample_rate_hz": SAMPLE_RATE,
        "samples": audio.size, "raw_peak": raw_peak, "written_peak": float(np.abs(audio).max()),
        "utterances": utterances,
    }))


if __name__ == "__main__":
    main()