apptor commited on
Commit
c898fdb
·
verified ·
1 Parent(s): b5c6ae8

No eSpeak NG needed: own G2P model, Vocos as ONNX, new speak.py

Browse files
README.md CHANGED
@@ -23,9 +23,15 @@ It is built on **[tiny-voca](https://github.com/n4ze3m/tiny-voca) by n4ze3m**: s
23
  recipe, retrained from scratch for German. This is **not an official tiny-voca release**. Thanks to n4ze3m for the
24
  model and the idea.
25
 
26
- An optional second stage, a [Vocos](https://github.com/gemelo-ai/vocos) vocoder fine-tuned on the two voices
27
- (13.5M parameters, 54 MB), re-synthesises the waveform and removes most of the buzzy sound of the tiny built-in
28
- generator. It is still real time on the CPU (~20x).
 
 
 
 
 
 
29
 
30
  Listen: `samples/demo.wav` (with Vocos) and `samples/demo-without-vocos.wav`.
31
 
@@ -35,22 +41,27 @@ Listen: `samples/demo.wav` (with Vocos) and `samples/demo-without-vocos.wav`.
35
  |---|---|---|
36
  | `apptor-tiny-tts-de.onnx` | the TTS model (text tokens -> 24 kHz audio) | Apache-2.0 |
37
  | `apptor-tiny-tts-de.json` | sample rate, voices, phoneme symbols, limits | Apache-2.0 |
38
- | `apptor-tiny-tts-vocos-de.pt` | optional: Vocos state dict, fine-tuned from `charactr/vocos-mel-24khz` | MIT |
39
- | `tinyvoca/` | German text front end (eSpeak NG phonemes, number normalisation), from tiny-voca | Apache-2.0 |
40
- | `speak.py` | minimal example | Apache-2.0 |
 
 
41
 
42
  ## Use
43
 
44
- Needs the `espeak-ng` program (`apt install espeak-ng`; GPL-3.0, called as a separate process) and
45
- `pip install onnxruntime numpy soundfile num2words`.
46
-
47
  ```bash
 
48
  python speak.py "Am 3. Mai um 18:30 Uhr kostet das Ticket 12,50 Euro." --voice M2 --out test.wav
49
- # with the Vocos second stage (pip install torch vocos):
50
- python speak.py "Hallo, wie geht es dir?" --voice F2 --vocos --out test.wav
 
 
 
 
 
51
  ```
52
 
53
- ONNX inputs: `tokens` and `stress` (int64 [1, N], from `tinyvoca.text.phonemize`), `voice` (int64 [1], index into
54
  `voices`), `speed`, `pitch_shift`, `pitch_range` (float32 [1]; 1.0 / 0.0 / 1.0 for normal). Outputs: `audio`
55
  (float32 [1, samples]) and `durations`. At most 512 phoneme tokens per call; split longer text into sentences.
56
 
@@ -63,8 +74,9 @@ CC BY-NC 4.0 (non-commercial only).
63
  - **Data:** about 12 hours of synthetic German speech, ~15,000 utterances, made with
64
  [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) 1.7B Base (Apache-2.0) with two of its built-in voices. Texts:
65
  Mozilla Common Voice German sentences (CC0). Utterances were screened with Whisper.
66
- - **Front end:** eSpeak NG `de`, 67 phoneme symbols (the English inventory of tiny-voca replaced by a German one),
67
- German number/date/time normalisation.
 
68
  - **Model:** tiny-voca recipe, 82k steps on one RTX 3090 (about 10 hours).
69
  - **Vocoder:** Vocos fine-tuned for about 60k steps on an RTX 5060 Ti: input is tiny-voca's own teacher-forced
70
  waveform, target the recording.
@@ -82,7 +94,8 @@ CC BY-NC 4.0 (non-commercial only).
82
  ## Deutsch
83
 
84
  Ein winziges deutsches TTS-Modell für die CPU (4,5M Parameter, 21 MB ONNX), auf Basis von tiny-voca von n4ze3m
85
- nachtrainiert, mit optionalem Vocos-Vocoder. Gewichte und Code unter Apache 2.0, also auch kommerziell nutzbar,
 
86
  der Vocoder unter MIT. Keine offizielle tiny-voca-Version.
87
 
88
  ## Credits
@@ -91,4 +104,5 @@ der Vocoder unter MIT. Keine offizielle tiny-voca-Version.
91
  - [Vocos](https://github.com/gemelo-ai/vocos), `charactr/vocos-mel-24khz` (MIT)
92
  - [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) (Apache-2.0): training speech
93
  - [Mozilla Common Voice](https://commonvoice.mozilla.org) German (CC0): texts
94
- - [eSpeak NG](https://github.com/espeak-ng/espeak-ng) (GPL-3.0, not included), num2words (LGPL-2.1)
 
 
23
  recipe, retrained from scratch for German. This is **not an official tiny-voca release**. Thanks to n4ze3m for the
24
  model and the idea.
25
 
26
+ A second stage, a [Vocos](https://github.com/gemelo-ai/vocos) vocoder fine-tuned on the two voices, re-synthesises
27
+ the waveform and removes most of the buzzy sound of the tiny built-in generator. Since November 2026 it ships as an
28
+ int8 ONNX file (17 MB), so no PyTorch is needed, and it is on by default.
29
+
30
+ **New (2026-11-19): no eSpeak NG needed any more.** A small letter-to-sound model (`apptor-g2p-de.onnx`, Apache-2.0)
31
+ replaces the eSpeak NG program, so the whole thing needs only `onnxruntime`, `numpy` and `num2words`, and it also
32
+ runs in the browser. There is also an Austrian-accented version with an accent slider:
33
+ [apptor-tiny-tts-at](https://huggingface.co/apptor/apptor-tiny-tts-at), demo at
34
+ [tiny-tts.apptor.at](https://tiny-tts.apptor.at).
35
 
36
  Listen: `samples/demo.wav` (with Vocos) and `samples/demo-without-vocos.wav`.
37
 
 
41
  |---|---|---|
42
  | `apptor-tiny-tts-de.onnx` | the TTS model (text tokens -> 24 kHz audio) | Apache-2.0 |
43
  | `apptor-tiny-tts-de.json` | sample rate, voices, phoneme symbols, limits | Apache-2.0 |
44
+ | `apptor-g2p-de.onnx` / `.json` | letters -> phonemes (conv + BiGRU + CTC, 12 MB), replaces eSpeak NG | Apache-2.0 |
45
+ | `apptor-vocos-de.int8.onnx` | sound filter: Vocos fine-tuned on the two voices, as ONNX (int8) | MIT |
46
+ | `apptor-tiny-tts-vocos-de.pt` | the same Vocos as PyTorch state dict (for `vocos` + torch users) | MIT |
47
+ | `tinyvoca/` | German text front end: number normalisation, tokens, G2P wrapper with a list of first names | Apache-2.0 |
48
+ | `speak.py` | Python example and small library | Apache-2.0 |
49
 
50
  ## Use
51
 
 
 
 
52
  ```bash
53
+ pip install onnxruntime numpy num2words
54
  python speak.py "Am 3. Mai um 18:30 Uhr kostet das Ticket 12,50 Euro." --voice M2 --out test.wav
55
+ python speak.py "Hallo, wie geht es dir?" --voice F2 --no-vocos --out test.wav # without the sound filter
56
+ ```
57
+
58
+ ```python
59
+ from speak import Speaker
60
+ s = Speaker() # finds the models next to speak.py
61
+ audio = s.speak("Hallo!", voice="F2") # float32 numpy array, 24 kHz
62
  ```
63
 
64
+ ONNX inputs: `tokens` and `stress` (int64 [1, N], from `tinyvoca.g2p_de.phonemize`), `voice` (int64 [1], index into
65
  `voices`), `speed`, `pitch_shift`, `pitch_range` (float32 [1]; 1.0 / 0.0 / 1.0 for normal). Outputs: `audio`
66
  (float32 [1, samples]) and `durations`. At most 512 phoneme tokens per call; split longer text into sentences.
67
 
 
74
  - **Data:** about 12 hours of synthetic German speech, ~15,000 utterances, made with
75
  [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) 1.7B Base (Apache-2.0) with two of its built-in voices. Texts:
76
  Mozilla Common Voice German sentences (CC0). Utterances were screened with Whisper.
77
+ - **Front end:** trained on eSpeak NG `de` phonemes, 67 phoneme symbols (the English inventory of tiny-voca replaced by a German one),
78
+ German number/date/time normalisation. At run time the G2P model produces the same phonemes: it learned the
79
+ eSpeak readings of ~480,000 words from the Common Voice sentences (98% of held-out words identical).
80
  - **Model:** tiny-voca recipe, 82k steps on one RTX 3090 (about 10 hours).
81
  - **Vocoder:** Vocos fine-tuned for about 60k steps on an RTX 5060 Ti: input is tiny-voca's own teacher-forced
82
  waveform, target the recording.
 
94
  ## Deutsch
95
 
96
  Ein winziges deutsches TTS-Modell für die CPU (4,5M Parameter, 21 MB ONNX), auf Basis von tiny-voca von n4ze3m
97
+ nachtrainiert, mit Vocos-Klangfilter. Seit 19.11.2026 ohne eSpeak NG: nur onnxruntime, numpy und num2words, läuft
98
+ auch im Browser. Österreichische Variante: [apptor-tiny-tts-at](https://huggingface.co/apptor/apptor-tiny-tts-at). Gewichte und Code unter Apache 2.0, also auch kommerziell nutzbar,
99
  der Vocoder unter MIT. Keine offizielle tiny-voca-Version.
100
 
101
  ## Credits
 
104
  - [Vocos](https://github.com/gemelo-ai/vocos), `charactr/vocos-mel-24khz` (MIT)
105
  - [Qwen3-TTS](https://github.com/QwenLM/Qwen3-TTS) (Apache-2.0): training speech
106
  - [Mozilla Common Voice](https://commonvoice.mozilla.org) German (CC0): texts
107
+ - [eSpeak NG](https://github.com/espeak-ng/espeak-ng) (GPL-3.0): phonemes for training and for teaching the G2P model; not
108
+ included and not needed at run time. num2words (LGPL-2.1, installed separately)
apptor-g2p-de.json ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chars": [
3
+ "<pad>",
4
+ "<unk>",
5
+ "'",
6
+ "-",
7
+ ".",
8
+ "A",
9
+ "B",
10
+ "C",
11
+ "D",
12
+ "E",
13
+ "F",
14
+ "G",
15
+ "H",
16
+ "I",
17
+ "J",
18
+ "K",
19
+ "L",
20
+ "M",
21
+ "N",
22
+ "O",
23
+ "P",
24
+ "Q",
25
+ "R",
26
+ "S",
27
+ "T",
28
+ "U",
29
+ "V",
30
+ "W",
31
+ "X",
32
+ "Y",
33
+ "Z",
34
+ "a",
35
+ "b",
36
+ "c",
37
+ "d",
38
+ "e",
39
+ "f",
40
+ "g",
41
+ "h",
42
+ "i",
43
+ "j",
44
+ "k",
45
+ "l",
46
+ "m",
47
+ "n",
48
+ "o",
49
+ "p",
50
+ "q",
51
+ "r",
52
+ "s",
53
+ "t",
54
+ "u",
55
+ "v",
56
+ "w",
57
+ "x",
58
+ "y",
59
+ "z",
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
+ "units": [
159
+ "1",
160
+ "??",
161
+ "??ˈ",
162
+ "??ˌ",
163
+ "a",
164
+ "aɪ",
165
+ "aɪə",
166
+ "aɪəˈ",
167
+ "aɪəˌ",
168
+ "aɪˈ",
169
+ "aɪˌ",
170
+ "aʊ",
171
+ "aʊˈ",
172
+ "aʊˌ",
173
+ "aˈ",
174
+ "aˌ",
175
+ "b",
176
+ "bʲ",
177
+ "d",
178
+ "dʑ",
179
+ "dʒ",
180
+ "dʲ",
181
+ "e",
182
+ "eə",
183
+ "eəˈ",
184
+ "eəˌ",
185
+ "eɪ",
186
+ "eɪˈ",
187
+ "eɪˌ",
188
+ "eˈ",
189
+ "eː",
190
+ "eːˈ",
191
+ "eːˌ",
192
+ "f",
193
+ "fʲ",
194
+ "h",
195
+ "i",
196
+ "iə",
197
+ "iəˈ",
198
+ "iəˌ",
199
+ "iʊ",
200
+ "iˈ",
201
+ "iˌ",
202
+ "iː",
203
+ "iːˈ",
204
+ "iːˌ",
205
+ "j",
206
+ "k",
207
+ "kʲ",
208
+ "l",
209
+ "m",
210
+ "mʲ",
211
+ "n",
212
+ "o",
213
+ "oɪˈ",
214
+ "oˈ",
215
+ "oˌ",
216
+ "oː",
217
+ "oːˈ",
218
+ "oːˌ",
219
+ "p",
220
+ "pf",
221
+ "q",
222
+ "r",
223
+ "s",
224
+ "t",
225
+ "ts",
226
+ "tɕ",
227
+ "tʃ",
228
+ "tʲ",
229
+ "u",
230
+ "uˈ",
231
+ "uˌ",
232
+ "uː",
233
+ "uːˈ",
234
+ "uːˌ",
235
+ "v",
236
+ "vʲ",
237
+ "w",
238
+ "w-ˈ",
239
+ "x",
240
+ "y",
241
+ "yˈ",
242
+ "yˌ",
243
+ "yː",
244
+ "yːˈ",
245
+ "yːˌ",
246
+ "z",
247
+ "ç",
248
+ "ð",
249
+ "øː",
250
+ "øːˈ",
251
+ "øːˌ",
252
+ "ŋ",
253
+ "œ",
254
+ "œˈ",
255
+ "œˌ",
256
+ "œ̃ˈ",
257
+ "ɐ",
258
+ "ɐˈ",
259
+ "ɑ",
260
+ "ɑˈ",
261
+ "ɑˌ",
262
+ "ɑː",
263
+ "ɑːˈ",
264
+ "ɑːˌ",
265
+ "ɑ̃",
266
+ "ɑ̃ˈ",
267
+ "ɑ̃ˌ",
268
+ "ɒ",
269
+ "ɒˈ",
270
+ "ɒˌ",
271
+ "ɔ",
272
+ "ɔø",
273
+ "ɔøˈ",
274
+ "ɔøˌ",
275
+ "ɔɪ",
276
+ "ɔɪˈ",
277
+ "ɔɪˌ",
278
+ "ɔˈ",
279
+ "ɔˌ",
280
+ "ɔː",
281
+ "ɔːˈ",
282
+ "ɔːˌ",
283
+ "ɔ̃ˈ",
284
+ "ɔ̃ˌ",
285
+ "ɕ",
286
+ "ə",
287
+ "əl",
288
+ "əʊ",
289
+ "əʊˈ",
290
+ "əʊˌ",
291
+ "əˈ",
292
+ "əˌ",
293
+ "ɛ",
294
+ "ɛɪ",
295
+ "ɛɪˈ",
296
+ "ɛɪˌ",
297
+ "ɛˈ",
298
+ "ɛˌ",
299
+ "ɛː",
300
+ "ɛːˈ",
301
+ "ɛːˌ",
302
+ "ɛ̃ˌ",
303
+ "ɜ",
304
+ "ɜˈ",
305
+ "ɜˌ",
306
+ "ɜː",
307
+ "ɜːˈ",
308
+ "ɜːˌ",
309
+ "ɡ",
310
+ "ɡʲ",
311
+ "ɨ",
312
+ "ɨˈ",
313
+ "ɪ",
314
+ "ɪˈ",
315
+ "ɪˌ",
316
+ "ɫ",
317
+ "ɯ",
318
+ "ɯˈ",
319
+ "ɯˌ",
320
+ "ɲ",
321
+ "ɹ",
322
+ "ɾ",
323
+ "ʃ",
324
+ "ʊ",
325
+ "ʊə",
326
+ "ʊəˈ",
327
+ "ʊəˌ",
328
+ "ʊˈ",
329
+ "ʊˌ",
330
+ "ʌ",
331
+ "ʌˈ",
332
+ "ʌˌ",
333
+ "ʑ",
334
+ "ʒ",
335
+ "ʔ",
336
+ "θ"
337
+ ],
338
+ "up": 3,
339
+ "max_len": 40,
340
+ "blank": 178,
341
+ "inputs": [
342
+ "chars"
343
+ ],
344
+ "outputs": [
345
+ "logp"
346
+ ]
347
+ }
apptor-g2p-de.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d981694e7a03030b2169be46b2094775dde4ec5a3e9406c92a3fc8f1ed8bbec3
3
+ size 12364141
apptor-vocos-de.int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:417f2413163d666b23a89dd73b1829a34ac316fb524a02cc6a4120660a40e6eb
3
+ size 16655451
speak.py CHANGED
@@ -1,65 +1,147 @@
1
- """apptor-tiny-tts: German text -> WAV on the CPU.
2
 
3
- python speak.py "Hallo, wie geht es dir?" --voice F2 --out hallo.wav [--vocos] [--speed 1.0]
4
- Needs espeak-ng, onnxruntime, numpy, soundfile, num2words; --vocos also torch and vocos.
 
 
 
 
 
5
  """
6
  import argparse
7
  import json
 
8
  import re
 
9
  from pathlib import Path
10
 
11
  import numpy as np
12
  import onnxruntime as ort
13
- import soundfile as sf
14
-
15
- from tinyvoca.text import phonemize
16
 
17
  HERE = Path(__file__).resolve().parent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
 
20
  def main():
21
- ap = argparse.ArgumentParser()
22
  ap.add_argument("text")
23
- ap.add_argument("--voice", default="F2", choices=["F2", "M2"])
24
- ap.add_argument("--out", default="out.wav")
25
  ap.add_argument("--speed", type=float, default=1.0)
26
- ap.add_argument("--vocos", action="store_true", help="second stage: fine-tuned Vocos (cleaner sound)")
 
 
27
  ap.add_argument("--threads", type=int, default=4)
28
  a = ap.parse_args()
29
-
30
- meta = json.loads((HERE / "apptor-tiny-tts-de.json").read_text(encoding="utf-8"))
31
- opts = ort.SessionOptions()
32
- opts.intra_op_num_threads = a.threads
33
- session = ort.InferenceSession(str(HERE / "apptor-tiny-tts-de.onnx"), opts, providers=["CPUExecutionProvider"])
34
- voice = meta["voices"].index(a.voice)
35
-
36
- pieces = []
37
- for sentence in re.split(r"(?<=[.!?…])\s+", a.text.strip()): # one sentence per call (<= 512 tokens)
38
- if not sentence:
39
- continue
40
- p = phonemize(sentence)
41
- audio, _ = session.run(None, {
42
- "tokens": np.array([p.ids], np.int64), "stress": np.array([p.stress], np.int64),
43
- "voice": np.array([voice], np.int64), "speed": np.array([a.speed], np.float32),
44
- "pitch_shift": np.array([0.0], np.float32), "pitch_range": np.array([1.0], np.float32)})
45
- pieces += [audio[0].astype(np.float32), np.zeros(int(0.12 * meta["sample_rate"]), np.float32)]
46
- audio = np.concatenate(pieces)
47
-
48
- if a.vocos:
49
- import torch
50
- from vocos import Vocos
51
- torch.set_num_threads(a.threads)
52
- voc = Vocos.from_pretrained("charactr/vocos-mel-24khz").eval()
53
- voc.load_state_dict(torch.load(HERE / "apptor-tiny-tts-vocos-de.pt", map_location="cpu", weights_only=True))
54
- with torch.inference_mode():
55
- x = torch.from_numpy(audio)[None]
56
- audio = voc.decode(voc.feature_extractor(x))[0, :len(audio)].numpy()
57
-
58
- peak = float(np.abs(audio).max())
59
- if peak > 0.95:
60
- audio = audio * (0.95 / peak)
61
- sf.write(a.out, audio, meta["sample_rate"])
62
- print(f"wrote {a.out} ({len(audio) / meta['sample_rate']:.1f} s)")
63
 
64
 
65
  if __name__ == "__main__":
 
1
+ """apptor-tiny-tts: German text -> WAV on the CPU. No eSpeak NG, no torch, no GPU.
2
 
3
+ pip install onnxruntime numpy num2words
4
+ python speak.py "Servus, wie geht's dir?" --voice M2 --out servus.wav
5
+ python speak.py "Servus, wie geht's dir?" --accent 0 # Austrian model: Hochdeutsch
6
+ python speak.py "Servus, wie geht's dir?" --accent 1.6 # Austrian model: strongest usable accent
7
+
8
+ Uses the files next to this script: the speech model (apptor-tiny-tts-at.onnx, else apptor-tiny-tts-de.onnx), the
9
+ letter-to-sound model apptor-g2p-de.onnx and, unless --no-vocos, the sound filter apptor-vocos-de.int8.onnx.
10
  """
11
  import argparse
12
  import json
13
+ import os
14
  import re
15
+ import wave
16
  from pathlib import Path
17
 
18
  import numpy as np
19
  import onnxruntime as ort
 
 
 
20
 
21
  HERE = Path(__file__).resolve().parent
22
+ os.environ.setdefault("APPTOR_G2P_MODEL", str(HERE / "apptor-g2p-de.onnx"))
23
+ from tinyvoca.g2p_de import phonemize # noqa: E402
24
+
25
+
26
+ def session(path, threads):
27
+ options = ort.SessionOptions()
28
+ options.intra_op_num_threads = threads
29
+ return ort.InferenceSession(str(path), options, providers=["CPUExecutionProvider"])
30
+
31
+
32
+ def vocos_kernels(n_fft=1024):
33
+ """Fixed STFT / inverse STFT kernels of the Vocos ONNX model (periodic Hann window)."""
34
+ n = np.arange(n_fft)
35
+ k = np.arange(n_fft // 2 + 1)[:, None]
36
+ w = 0.5 - 0.5 * np.cos(2 * np.pi * n / n_fft)
37
+ ang = 2 * np.pi * k * n / n_fft
38
+ c = np.where((k == 0) | (k == n_fft // 2), 1.0, 2.0) / n_fft
39
+ return {"a_real": (w * np.cos(ang))[:, None].astype(np.float32),
40
+ "a_imag": (-w * np.sin(ang))[:, None].astype(np.float32),
41
+ "synth": np.concatenate((c * np.cos(ang) * w, -c * np.sin(ang) * w))[:, None].astype(np.float32)}
42
+
43
+
44
+ def trim_tail(audio, sr, floor_db=-30.0, fade_ms=40.0):
45
+ """Cut the breathy noise after the last sound: keep up to the last 10 ms frame within 30 dB of the loudest one,
46
+ then fade out over 40 ms."""
47
+ hop = sr // 100
48
+ n = len(audio) // hop
49
+ if n == 0:
50
+ return audio
51
+ e = (audio[:n * hop].reshape(n, hop) ** 2).sum(1)
52
+ if e.max() <= 0:
53
+ return audio
54
+ last = int(np.nonzero(e >= e.max() * 10 ** (floor_db / 10))[0][-1])
55
+ fade = int(fade_ms * sr / 1000)
56
+ end = (last + 1) * hop + fade
57
+ if end >= len(audio):
58
+ return audio
59
+ out = audio[:end].copy()
60
+ out[-fade:] *= 0.5 + 0.5 * np.cos(np.pi * np.arange(1, fade + 1) / fade)
61
+ return out
62
+
63
+
64
+ class Speaker:
65
+ def __init__(self, model=None, vocos=True, threads=4):
66
+ model = Path(model) if model else next(p for p in (HERE / "apptor-tiny-tts-at.onnx", HERE / "apptor-tiny-tts-de.onnx")
67
+ if p.is_file())
68
+ self.meta = json.loads(model.with_suffix(".json").read_text(encoding="utf-8"))
69
+ self.tts = session(model, threads)
70
+ self.inputs = {i.name for i in self.tts.get_inputs()}
71
+ self.max_tokens = self.meta.get("max_tokens", 512)
72
+ self.vocos = session(HERE / "apptor-vocos-de.int8.onnx", threads) if vocos else None
73
+ self.kernels = vocos_kernels() if vocos else None
74
+
75
+ @property
76
+ def voices(self):
77
+ return [v for v in self.meta["voices"] if v != "AT"]
78
+
79
+ def _pieces(self, text, austrian):
80
+ """Sentences, then clauses or halves, so that no piece exceeds the model's token limit."""
81
+ for sentence in re.split(r"(?<=[.!?…])\s+", text.strip()):
82
+ if not sentence:
83
+ continue
84
+ p = phonemize(sentence, austrian=austrian)
85
+ if len(p.ids) <= self.max_tokens:
86
+ yield p
87
+ continue
88
+ parts = re.split(r"(?<=[,;:—])\s+", sentence)
89
+ if len(parts) == 1:
90
+ words = sentence.split()
91
+ parts = [" ".join(words[:len(words) // 2]), " ".join(words[len(words) // 2:])]
92
+ for part in parts:
93
+ yield from self._pieces(part, austrian)
94
+
95
+ def speak(self, text, voice="M2", accent=1.0, speed=1.0, gap=0.12):
96
+ """-> float32 audio at meta["sample_rate"]. accent: 0 = Hochdeutsch, 1.0 = Austrian, up to 1.6 (AT model only)."""
97
+ sr = self.meta["sample_rate"]
98
+ has_accent = "accent" in self.inputs
99
+ out = []
100
+ for p in self._pieces(text, austrian=has_accent and accent >= 0.5):
101
+ feeds = {"tokens": np.array([p.ids], np.int64), "stress": np.array([p.stress], np.int64),
102
+ "voice": np.array([self.meta["voices"].index(voice)], np.int64),
103
+ "speed": np.array([speed], np.float32), "pitch_shift": np.array([0.0], np.float32),
104
+ "pitch_range": np.array([1.0], np.float32)}
105
+ if has_accent:
106
+ feeds["accent"] = np.array([accent], np.float32)
107
+ audio = self.tts.run(["audio"], feeds)[0][0].astype(np.float32)
108
+ if self.vocos is not None:
109
+ y = self.vocos.run(None, {"audio": audio[None], **self.kernels})[0][0]
110
+ audio = y[:len(audio)]
111
+ audio = trim_tail(audio, sr)
112
+ peak = float(np.abs(audio).max()) if len(audio) else 0.0
113
+ if peak > 0.95:
114
+ audio = audio * (0.95 / peak)
115
+ if out:
116
+ out.append(np.zeros(int(gap * sr), np.float32))
117
+ out.append(audio)
118
+ return np.concatenate(out) if out else np.zeros(0, np.float32)
119
+
120
+
121
+ def write_wav(path, audio, sr):
122
+ """float audio -> 16-bit mono WAV."""
123
+ with wave.open(str(path), "wb") as w:
124
+ w.setnchannels(1)
125
+ w.setsampwidth(2)
126
+ w.setframerate(sr)
127
+ w.writeframes((np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes())
128
 
129
 
130
  def main():
131
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
132
  ap.add_argument("text")
133
+ ap.add_argument("--voice", default="M2", choices=["M2", "F2"])
134
+ ap.add_argument("--accent", type=float, default=1.0, help="Austrian model: 0 Hochdeutsch, 1.0 Austrian, up to 1.6")
135
  ap.add_argument("--speed", type=float, default=1.0)
136
+ ap.add_argument("--out", default="out.wav")
137
+ ap.add_argument("--model", help="speech model .onnx (default: the one next to this script)")
138
+ ap.add_argument("--no-vocos", action="store_true", help="skip the sound filter (faster, more buzzy)")
139
  ap.add_argument("--threads", type=int, default=4)
140
  a = ap.parse_args()
141
+ s = Speaker(a.model, vocos=not a.no_vocos, threads=a.threads)
142
+ audio = s.speak(a.text, voice=a.voice, accent=a.accent, speed=a.speed)
143
+ write_wav(a.out, audio, s.meta["sample_rate"])
144
+ print(f"wrote {a.out} ({len(audio) / s.meta['sample_rate']:.1f} s)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
 
147
  if __name__ == "__main__":
tinyvoca/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
- """Text front end of tiny-voca (https://github.com/n4ze3m/tiny-voca, Apache 2.0), German fork:
2
- text.py (eSpeak NG "de", German phone inventory) and normalize_de.py, copied unchanged from the German training
3
- code so the server makes exactly the tokens the model was trained on. Needs the espeak-ng program and num2words."""
 
1
+ """German text front end of apptor-tiny-tts, based on tiny-voca (https://github.com/n4ze3m/tiny-voca, Apache 2.0):
2
+ text.py (phone inventory, tokens), normalize_de.py (numbers, dates, times; needs num2words) and g2p_de.py (letters
3
+ to phones with the small apptor-g2p-de model, so no eSpeak NG is needed)."""
tinyvoca/g2p_de.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """apptor-tiny-tts German letter-to-sound front end without eSpeak NG (Apache 2.0).
2
+
3
+ A small model (convolutions + bidirectional GRU, CTC, ~3 MB ONNX) turns each written word into phones with stress,
4
+ in the same inventory and conventions as eSpeak NG "de", which the speech models were trained on. It was trained
5
+ on the eSpeak readings of ~480,000 words from the Common Voice German sentences, so it reproduces those readings
6
+ without needing the eSpeak program (GPL-3.0) at run time. A small hand-written list (EXCEPTIONS) wins over the model.
7
+
8
+ words(piece) -> [[(phone, stress), ...], ...] # drop-in for tiny_voca.text.espeak_words
9
+ """
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ HERE = Path(__file__).resolve().parent
17
+ MODEL = Path(os.environ.get("APPTOR_G2P_MODEL", HERE / "apptor-g2p-de.onnx"))
18
+ MARKS = {"ˈ": 1, "ˌ": 2}
19
+
20
+ # Hand-written readings (word -> phones with stress marks, space separated), used before the model: mostly first
21
+ # names, where the eSpeak readings (and so the model) put the stress on the wrong syllable.
22
+ EXCEPTIONS = {
23
+ "Helene": "h eː l eːˈ n ə",
24
+ "Diana": "d i aˈ n ɑː",
25
+ "Dianna": "d i aˈ n ɑː",
26
+ "Daniela": "d a n i eːˈ l ɑː",
27
+ "Melanie": "m eːˈ l a n iː",
28
+ "Valentina": "v a l ɛ n t iːˈ n ɑː",
29
+ "Theresa": "t eː r eːˈ z ɑː",
30
+ "Elisabeth": "eː l iːˈ z a b ɛ t",
31
+ "Alexander": "a l ɛ k s aˈ n d ɜ",
32
+ "Andreas": "a n d r eːˈ a s",
33
+ "Matthias": "m a t iːˈ a s",
34
+ "Tobias": "t oː b iːˈ a s",
35
+ "Florian": "f l oːˈ r i a n",
36
+ "Sebastian": "z eː b aˈ s t i a n",
37
+ "Stefanie": "ʃ t eːˈ f a n iː",
38
+ "Christina": "k r ɪ s t iːˈ n ɑː",
39
+ "Magdalena": "m a k d a l eːˈ n ɑː",
40
+ "Veronika": "v eː r oːˈ n i k ɑː",
41
+ "Monika": "m oːˈ n i k ɑː",
42
+ "Angelika": "a ŋ ɡ eːˈ l i k ɑː",
43
+ "Leonie": "l eː oːˈ n iː",
44
+ "Emilia": "eː m iːˈ l i ɑː",
45
+ "David": "d ɑːˈ v ɪ t",
46
+ "Raphael": "r ɑːˈ f a eː l",
47
+ "Michael": "m ɪˈ ç a eː l",
48
+ "Manuel": "m ɑːˈ n uː ɛ l",
49
+ "Maximilian": "m a k s i m iːˈ l i ɑː n",
50
+ "Julia": "j uːˈ l i ɑː",
51
+ "Sarah": "z ɑːˈ r ɑː",
52
+ "Barbara": "b aˈ ɾ b a r ɑː",
53
+ "Gabriele": "ɡ a b r i eːˈ l ə",
54
+ "Ursula": "ʊˈ ɾ z uː l ɑː",
55
+ "Irene": "iː r eːˈ n ə",
56
+ "Miriam": "m iːˈ r i a m",
57
+ "Marlene": "m a ɾ l eːˈ n ə",
58
+ "Helena": "h eːˈ l eː n ɑː",
59
+ "Elena": "eːˈ l eː n ɑː",
60
+ "Selina": "z eː l iːˈ n ɑː",
61
+ "Martina": "m a ɾ t iːˈ n ɑː",
62
+ "Claudia": "k l aʊˈ d i ɑː",
63
+ "Ingrid": "ɪˈ ŋ ɡ r ɪ t",
64
+ "Leopold": "l eːˈ oː p ɔ l t",
65
+ "Ferdinand": "f ɛˈ ɾ d i n a n t",
66
+ "Dominik": "d oːˈ m i n ɪ k",
67
+ "Fabian": "f ɑːˈ b i a n",
68
+ "Kilian": "k iːˈ l i a n",
69
+ "Elias": "eː l iːˈ a s",
70
+ "Noah": "n oːˈ a",
71
+ "Anton": "aˈ n t oː n",
72
+ "Dorothea": "d oː r oː t eːˈ ɑː",
73
+ "Cornelia": "k ɔ ɾ n eːˈ l i ɑː",
74
+ "Philomena": "f i l oː m eːˈ n ɑː",
75
+ "Aurelia": "aʊ r eːˈ l i ɑː",
76
+ "Antonia": "a n t oːˈ n i ɑː",
77
+ "Paulina": "p aʊ l iːˈ n ɑː",
78
+ "Juliana": "j uː l i ɑːˈ n ɑː",
79
+ "Liliana": "l i l i ɑːˈ n ɑː",
80
+ "Adriana": "a d r i ɑːˈ n ɑː",
81
+ "Tatjana": "t a t j ɑːˈ n ɑː",
82
+ "Svetlana": "s v ɛ t l ɑːˈ n ɑː",
83
+ "Milena": "m i l eːˈ n ɑː",
84
+ "Daria": "d ɑːˈ r i ɑː",
85
+ "Mariana": "m a r i ɑːˈ n ɑː",
86
+ "Ariana": "a r i ɑːˈ n ɑː",
87
+ }
88
+
89
+ # Austrian standard pronunciation (Österreichisches Wörterbuch) where the German German reading differs: used only
90
+ # when the Austrian accent is on (austrian=True), so the Hochdeutsch voices keep the German reading.
91
+ AUSTRIAN = {
92
+ "Kaffee": "k a f eːˈ", "Kaffees": "k a f eːˈ s", "Kaffeehaus": "k a f eːˈ h aʊˌ s",
93
+ "Kaffeehäuser": "k a f eːˈ h ɔøˌ z ɜ", "Tabak": "t a b aˈ k", "Mathematik": "m a t eːˈ m a t ɪ k",
94
+ "Chemie": "k eː m iːˈ", "Chemiker": "k eːˈ m ɪ k ɜ", "Chemikalien": "k eːˌ m iː k ɑˈ l ɪ ə n",
95
+ "chemisch": "k eːˈ m ɪ ʃ", "chemische": "k eːˈ m ɪ ʃ ə", "chemischen": "k eːˈ m ɪ ʃ ə n",
96
+ "China": "k iːˈ n ɑː", "Chinese": "k iː n eːˈ z ə", "Chinesen": "k iː n eːˈ z ə n",
97
+ "chinesisch": "k iː n eːˈ z ɪ ʃ", "chinesische": "k iː n eːˈ z ɪ ʃ ə", "Chirurg": "k iː r ??ˈ k",
98
+ "Motor": "m oː t oːˈ ɾ", "Platin": "p l a t iːˈ n", "Billard": "b ɪ j ɑːˈ ɾ", "Garage": "ɡ a r ɑːˈ ʃ",
99
+ # western-Austrian "scht" crept into the accent here; lenis d (as said in Vienna) keeps a clean s
100
+ "Donnerstag": "d ɔˈ n ɐ s d ɑː k", "Donnerstags": "d ɔˈ n ɐ s d ɑː k s",
101
+ }
102
+
103
+ _state = {}
104
+
105
+
106
+ def _load():
107
+ if "session" not in _state:
108
+ import onnxruntime as ort
109
+ meta = json.loads(MODEL.with_suffix(".json").read_text(encoding="utf-8"))
110
+ options = ort.SessionOptions()
111
+ options.intra_op_num_threads = 1
112
+ options.inter_op_num_threads = 1
113
+ _state["session"] = ort.InferenceSession(str(MODEL), options, providers=["CPUExecutionProvider"])
114
+ _state["chars"] = {c: i for i, c in enumerate(meta["chars"])}
115
+ _state["units"] = meta["units"]
116
+ _state["up"] = meta["up"]
117
+ _state["max_len"] = meta["max_len"]
118
+ _state["cache"] = {}
119
+ return _state
120
+
121
+
122
+ def _units(text):
123
+ out = []
124
+ for unit in text.split():
125
+ stress = 0
126
+ for mark, level in MARKS.items():
127
+ if mark in unit:
128
+ stress = stress or level
129
+ unit = unit.replace(mark, "")
130
+ if unit:
131
+ out.append((unit, stress))
132
+ return out
133
+
134
+
135
+ def word(w, austrian=False):
136
+ """One written word -> [(phone, stress), ...]."""
137
+ if austrian and w in AUSTRIAN:
138
+ return _units(AUSTRIAN[w])
139
+ if w in EXCEPTIONS:
140
+ return _units(EXCEPTIONS[w])
141
+ s = _load()
142
+ cache = s["cache"]
143
+ if w in cache:
144
+ return cache[w]
145
+ if len(w) > s["max_len"]: # very long compound: read it in parts
146
+ half = len(w) // 2
147
+ result = word(w[:half]) + word(w[half:])
148
+ else:
149
+ ids = np.array([[s["chars"].get(c, 1) for c in w]], dtype=np.int64)
150
+ logp = s["session"].run(None, {"chars": ids})[0][0]
151
+ blank = len(s["units"])
152
+ best = logp.argmax(-1)
153
+ units, prev = [], None
154
+ for b in best:
155
+ if b != prev and b != blank:
156
+ units.append(s["units"][b])
157
+ prev = b
158
+ result = _units(" ".join(units))
159
+ if len(cache) < 100000:
160
+ cache[w] = result
161
+ return result
162
+
163
+
164
+ def words(piece, austrian=False):
165
+ """A text piece (normalized, no punctuation) -> words as lists of (phone, stress), like espeak_words."""
166
+ return [u for u in (word(w, austrian) for w in piece.split()) if u]
167
+
168
+
169
+ def phonemize(text, austrian=False):
170
+ """Text -> tokens like tiny_voca.text.phonemize, with this model instead of eSpeak NG. ``austrian``: use the
171
+ Austrian readings (AUSTRIAN) - for the accent switch of apptor-tiny-tts-at."""
172
+ try:
173
+ from tiny_voca.normalize_de import normalize as normalize_german
174
+ from tiny_voca.text import chunks, normalize_text, tokenize
175
+ except ImportError: # flash-voice vendors the front end as "tinyvoca"
176
+ from tinyvoca.normalize_de import normalize as normalize_german
177
+ from tinyvoca.text import chunks, normalize_text, tokenize
178
+ if not isinstance(text, str) or not text.strip():
179
+ raise ValueError("text must not be empty")
180
+ pieces = [(True, p) if punct else (False, words(p, austrian))
181
+ for punct, p in chunks(normalize_text(normalize_german(normalize_text(text))))]
182
+ return tokenize(pieces)
tinyvoca/normalize_de.py CHANGED
@@ -61,5 +61,6 @@ def normalize(text):
61
  text = re.sub(r"(?<![\w-])-(\d+)", lambda m: "minus " + m[1], text)
62
  if _n2w is not None:
63
  text = re.sub(r"\d+", lambda m: _num(m[0]), text)
 
64
  text = re.sub(r"\bein(hundert|tausend)", r"\1", text)
65
  return re.sub(r"\s+", " ", text).strip()
 
61
  text = re.sub(r"(?<![\w-])-(\d+)", lambda m: "minus " + m[1], text)
62
  if _n2w is not None:
63
  text = re.sub(r"\d+", lambda m: _num(m[0]), text)
64
+ text = text.replace("einstausend", "eintausend") # num2words: 101000 -> einhunderteinstausend
65
  text = re.sub(r"\bein(hundert|tausend)", r"\1", text)
66
  return re.sub(r"\s+", " ", text).strip()