ctrltokyo commited on
Commit
a42c72e
·
verified ·
1 Parent(s): c8899b6

eeh-1: 4.5M-parameter Japanese TTS, weights, ONNX, Rust/WASM demo

Browse files
.gitattributes CHANGED
@@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ eval/metrics.jsonl filter=lfs diff=lfs merge=lfs -text
37
+ samples/F1-hello.wav filter=lfs diff=lfs merge=lfs -text
38
+ samples/F1-numbers.wav filter=lfs diff=lfs merge=lfs -text
39
+ samples/F1-polite.wav filter=lfs diff=lfs merge=lfs -text
40
+ samples/F1-question.wav filter=lfs diff=lfs merge=lfs -text
41
+ samples/F1-story.wav filter=lfs diff=lfs merge=lfs -text
42
+ samples/M1-hello.wav filter=lfs diff=lfs merge=lfs -text
43
+ samples/M1-numbers.wav filter=lfs diff=lfs merge=lfs -text
44
+ samples/M1-polite.wav filter=lfs diff=lfs merge=lfs -text
45
+ samples/M1-question.wav filter=lfs diff=lfs merge=lfs -text
46
+ samples/M1-story.wav filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: apache-2.0
4
+ pipeline_tag: text-to-speech
5
+ library_name: pytorch
6
+ tags:
7
+ - text-to-speech
8
+ - japanese
9
+ - onnx
10
+ - tiny
11
+ ---
12
+
13
+ # eeh
14
+
15
+ **A tiny Japanese voice that fits in a browser tab.** eeh is a Japanese
16
+ text-to-speech model with two voices and 4.5 million parameters, waveform
17
+ generator included. It reads kanji, numbers and Tokyo pitch accent, and runs on
18
+ a CPU or fully inside a browser, with nothing sent anywhere.
19
+
20
+ There is no neural vocoder. A transformer reads OpenJTalk's phonemes with their
21
+ pitch-accent tones, predicts how long each one lasts, then predicts pitch,
22
+ loudness and the settings of a small source-filter synthesizer, which makes the
23
+ waveform from a pulse train and noise. That is why it is small and fast. It was
24
+ trained from scratch on 18.6 hours of speech by
25
+ [Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi).
26
+
27
+ <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-hello.wav"></audio>
28
+
29
+ | | |
30
+ |---|---|
31
+ | Parameters | 4,534,219 |
32
+ | Voices | F1 (female, late 20s, calm and clear), M1 (male, early 30s, warm), Tokyo Japanese |
33
+ | Output | 24 kHz mono |
34
+ | Input | Japanese text (kanji, kana, numbers), read with OpenJTalk |
35
+ | Speed | About 50x real time in a browser tab on one thread, first audio in under 0.1 s (Apple M4 Max) |
36
+ | Pretrained weights in the model | None |
37
+ | License | Apache-2.0 |
38
+
39
+ ## Samples
40
+
41
+ | Text | F1 | M1 |
42
+ |---|---|---|
43
+ | こんにちは!これは、ノートパソコンでも動く小さな音声合成モデルです。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-hello.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/M1-hello.wav"></audio> |
44
+ | 会議は三月十四日の午後三時半に変わったので、あと四十五分ほどあります。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-numbers.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/M1-numbers.wav"></audio> |
45
+ | 本当に、あなたの誕生日を忘れると思ったの? | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-question.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/M1-question.wav"></audio> |
46
+ | 彼女は海を見たことがなかった。しばらくの間、何も言わずに波打ち際に立っていた。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-story.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/M1-story.wav"></audio> |
47
+ | 恐れ入りますが、お名前とご連絡先をこちらにご記入いただけますか。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/F1-polite.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1/resolve/main/samples/M1-polite.wav"></audio> |
48
+
49
+ ## Files
50
+
51
+ | Path | Contents |
52
+ |---|---|
53
+ | `eeh.pt` | PyTorch weights, float32 (18.2 MB) |
54
+ | `eeh.safetensors` | The same weights for the Rust/WebAssembly engine |
55
+ | `onnx/model.onnx`, `onnx/config.json` | ONNX export, float32, opset 17 (21.4 MB); symbols, voices, inputs and outputs |
56
+ | `tiny_voca/` | The Python package for inference: front end, model, `infer` |
57
+ | `demo/` | The browser demo: the whole engine compiled from Rust to WebAssembly, the weights and the dictionary |
58
+ | `samples/` | The audio on this page |
59
+ | `eval/report.json`, `eval/metrics.jsonl` | Evaluation report and the training log |
60
+ | `LICENSE` | Apache-2.0 |
61
+
62
+ ## Usage
63
+
64
+ ### Python
65
+
66
+ ```bash
67
+ pip install torch numpy soundfile "pyopenjtalk>=0.4,<0.5"
68
+ hf download ctrltokyo/eeh-1 --local-dir eeh
69
+ cd eeh
70
+
71
+ python -m tiny_voca.infer \
72
+ --checkpoint eeh.pt \
73
+ --voice F1 \
74
+ --text "こんにちは。今日はいい天気ですね。" \
75
+ --output hello.wav
76
+ ```
77
+
78
+ | Option | Default | Meaning |
79
+ |---|---|---|
80
+ | `--text-file` | | Read the text from a UTF-8 file instead of `--text` |
81
+ | `--voice` | `F1` | `F1` or `M1` |
82
+ | `--speed` | 1.0 | Speaking rate |
83
+ | `--pitch-shift` | 0 | Added to log F0. 0.058 is about one semitone. |
84
+ | `--pitch-range` | 1.0 | Scales pitch movement around the utterance mean |
85
+
86
+ Text of any length works. It is split into sentences at 。!? and read one
87
+ sentence at a time; a quote followed by と or って stays with its sentence, and
88
+ a sentence too long for one call is cut after 、. A text without a final mark
89
+ gets 。. The saved audio never peaks above 0.99. In Python,
90
+ `tiny_voca.infer.speak_text` does the same.
91
+
92
+ ### In a browser
93
+
94
+ ```bash
95
+ hf download ctrltokyo/eeh-1 --local-dir eeh
96
+ python -m http.server --directory eeh/demo 8000
97
+ ```
98
+
99
+ Then open `http://localhost:8000`. The page runs eeh's own engine, written in
100
+ Rust and compiled to WebAssembly: a Japanese front end that reads text exactly
101
+ as OpenJTalk does (identical on more than 500,000 test texts), and the model.
102
+ It runs in a Web Worker and plays long text sentence by sentence as it is made;
103
+ the first sentence starts in under 0.1 s. The first visit downloads about 26 MB
104
+ (gzip): 17 MB of weights, 9 MB of dictionary and 0.4 MB of program, all kept by
105
+ the browser afterwards.
106
+
107
+ ### ONNX
108
+
109
+ The graph takes phoneme ids and tone values and returns the waveform. Text is
110
+ converted outside the graph with `tiny_voca.text.phonemize`.
111
+
112
+ ```python
113
+ import numpy as np
114
+ import onnxruntime as ort
115
+ import soundfile as sf
116
+ from tiny_voca.text import phonemize
117
+
118
+ phones = phonemize("こんにちは。")
119
+ one = lambda value: np.array([value], dtype=np.float32)
120
+ session = ort.InferenceSession("onnx/model.onnx")
121
+ audio, durations = session.run(None, {
122
+ "tokens": np.array([phones.ids], dtype=np.int64),
123
+ "stress": np.array([phones.stress], dtype=np.int64), # pitch-accent tone per token
124
+ "voice": np.array([0], dtype=np.int64), # 0 = F1, 1 = M1
125
+ "speed": one(1.0), "pitch_shift": one(0.0), "pitch_range": one(1.0),
126
+ })
127
+ audio = audio[0] * min(1.0, 0.99 / np.abs(audio[0]).max())
128
+ sf.write("hello.wav", audio, 24000)
129
+ ```
130
+
131
+ | Input | Type | Shape | Meaning |
132
+ |---|---|---|---|
133
+ | `tokens` | int64 | [1, N] | Symbol ids (`symbols` in `onnx/config.json`), with the start and end tokens |
134
+ | `stress` | int64 | [1, N] | Tokyo pitch-accent tone of the token's mora: 0 not a phone, 1 low, 2 high |
135
+ | `voice` | int64 | [1] | 0 = F1, 1 = M1 |
136
+ | `speed`, `pitch_shift`, `pitch_range` | float32 | [1] | As in the Python options |
137
+
138
+ | Output | Type | Shape | Meaning |
139
+ |---|---|---|---|
140
+ | `audio` | float32 | [1, samples] | Waveform at 24 kHz |
141
+ | `durations` | int64 | [1, N] | Length of each token in frames of 256 samples |
142
+
143
+ One call reads one utterance, up to 512 tokens and 3,000 frames (32 s).
144
+
145
+ ## How it works
146
+
147
+ **Front end.** [OpenJTalk](https://open-jtalk.sourceforge.net/) with the NAIST
148
+ Japanese Dictionary (the build in [pyopenjtalk](https://github.com/r9y9/pyopenjtalk)
149
+ 0.4) reads the text: it splits it into words, picks each kanji's reading,
150
+ expands numbers, joins words into accent phrases and assigns their accent types.
151
+ eeh turns its labels into tokens:
152
+
153
+ - one token per OpenJTalk phoneme (`k`, `sh`, `a`, `N` for ん, `cl` for っ);
154
+ a long vowel is two tokens, one per mora;
155
+ - devoiced vowels (the u of です, the i of した) are their own tokens `A I U E O`;
156
+ - `<sp>` marks a boundary between accent phrases, and punctuation is kept;
157
+ - each token carries the Tokyo pitch-accent tone of its mora, low or high,
158
+ computed from the phrase's accent type and the mora's position.
159
+
160
+ **Model.** A transformer encoder (4 blocks) reads the tokens and tones, a
161
+ predictor gives each token a length in frames, and two frame-level transformers
162
+ (2 and 5 blocks) predict pitch, voicing and loudness and then the settings of
163
+ the synthesizer: a band-limited pulse train at the predicted pitch plus noise,
164
+ each shaped by a filter predicted every frame (256 samples, 10.7 ms). All blocks
165
+ use 192 channels, 4 heads and rotary position embeddings.
166
+
167
+ | Component | Parameters |
168
+ |---|---:|
169
+ | Embeddings (token, tone, voice) | 13,632 |
170
+ | Text encoder | 1,588,864 |
171
+ | Duration and pause predictor | 123,906 |
172
+ | Frame transformer A, pitch/voicing/energy head | 795,971 |
173
+ | Frame transformer B | 1,985,984 |
174
+ | Source-filter waveform head | 25,862 |
175
+ | Total | 4,534,219 |
176
+
177
+ ## Training data
178
+
179
+ The speech is synthetic. Two voices were designed once from Japanese
180
+ descriptions with Irodori-TTS v4.1 Small (`落ち着いた20代後半の女性。明瞭で自然な東京の話し言葉。`
181
+ and `30代前半の男性。温かく親しみやすい、自然な東京の話し言葉。`), then every
182
+ sentence was read by [Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi)
183
+ (MIT) cloning those two references. No recording of a real speaker is involved.
184
+
185
+ On the 300 test sentences in both voices, the teacher's speech has 1.7% kana
186
+ reading error, 0.70 pitch-accent agreement and a UTMOS of 3.38.
187
+
188
+ The 8,650 sentences (8,000 train, 350 validation, 300 test, split by sentence)
189
+ were chosen to cover as many morae and mora pairs as possible; 25% are
190
+ questions and 10% exclamations.
191
+
192
+ Every clip was screened before training:
193
+
194
+ - **Reading.** [kana-whisper](https://huggingface.co/sbintuitions/kana-whisper)
195
+ transcribed it to katakana, compared with OpenJTalk's reading; more than 10%
196
+ kana error was rejected.
197
+ - **Alignment.** Phoneme durations come from forced alignment with
198
+ `facebook/wav2vec2-lv-60-espeak-cv-ft`, used only to label the data. Its
199
+ labels were recalibrated on the teacher's audio, and clips it aligned with
200
+ low confidence were rejected.
201
+ - **Speaking rate and length.**
202
+
203
+ | | Clips | Hours |
204
+ |---|---:|---:|
205
+ | Generated (sentences x voices) | 17,300 | |
206
+ | Passed screening | 15,684 | |
207
+ | Used for training (F1 7,301, M1 6,783) | 14,084 | 18.6 |
208
+ | Validation / test | 614 / 527 | 1.3 / 1.0 |
209
+
210
+ ## Training
211
+
212
+ | | |
213
+ |---|---|
214
+ | Steps | 104,000 |
215
+ | Batches | about 9,000 frames (96 s of audio) per step |
216
+ | Losses | Multi-resolution spectral losses; adversarial loss with multi-period and multi-resolution discriminators after step 8,000 |
217
+ | Hardware | One NVIDIA GB10 (Lenovo ThinkStation PGX) for training; an Apple M4 Max MacBook generated and scored half of the corpus |
218
+ | Time | 11.5 hours of training; 5.7 hours to generate the corpus on both machines |
219
+
220
+ Two changes to the training step made the adversarial phase twice as fast
221
+ without changing the gradients: the discriminators' gradient at the waveform is
222
+ computed once instead of twice, and their convolutions run in bfloat16 with
223
+ autotuned kernels, on batches padded to a few fixed shapes.
224
+
225
+ ## Evaluation
226
+
227
+ Speech from the final checkpoint was scored the same way as the teacher's
228
+ recordings of the same sentences: kana-whisper transcribes it to katakana
229
+ (reading error against OpenJTalk's reading), the pitch tracker checks each
230
+ expected rise and fall of the pitch accent, and UTMOS rates naturalness.
231
+
232
+ | Sentences | Clips | Reading error, eeh | Reading error, teacher | Pitch-accent agreement, eeh | Pitch-accent agreement, teacher | UTMOS, eeh | UTMOS, teacher |
233
+ |---|---:|---:|---:|---:|---:|---:|---:|
234
+ | Test | 300 | 0.8% | 1.2% | 0.70 | 0.69 | 2.94 | 3.38 |
235
+ | Validation | 300 | 1.0% | 1.7% | 0.71 | 0.68 | 2.94 | 3.34 |
236
+ | New sentences, not in the dataset | 16 | 0.0% | | 0.69 | | 2.88 | |
237
+
238
+ eeh reads and accents as well as the teacher it learned from; it sounds less
239
+ natural (UTMOS about 0.4 lower), which is the cost of the small synthesizer. No
240
+ listening test has been run.
241
+
242
+ ## Limitations
243
+
244
+ - Japanese only, two fixed voices, no voice cloning.
245
+ - Readings come from OpenJTalk's dictionary. Rare kanji readings, names and
246
+ new words can be read wrong, and the accent of compound phrases is predicted
247
+ by rules. Whatever OpenJTalk gets wrong, eeh says wrong.
248
+ - Latin letters are spelled out one by one (`eeh` is read イー・イー・エイチ).
249
+ - The same text is always read the same way.
250
+ - The training data is synthetic, so eeh cannot sound more natural than the
251
+ teacher; the small source-filter synthesizer sounds more buzzy than it.
252
+
253
+ ## License
254
+
255
+ Apache-2.0 for the weights and code.
256
+
257
+ ## Citation
258
+
259
+ ```bibtex
260
+ @software{nicholson2026eeh,
261
+ author = {Nicholson, Alexander},
262
+ title = {eeh: a 4.5M-parameter two-voice Japanese text-to-speech model},
263
+ year = {2026},
264
+ url = {https://huggingface.co/ctrltokyo/eeh-1}
265
+ }
266
+ ```
267
+
268
+ ## Acknowledgements
269
+
270
+ Inspired by [tiny-voca](https://github.com/n4ze3m/tiny-voca), trained on speech from [Irodori-TTS](https://github.com/Aratako/Irodori-TTS), and reading Japanese with [OpenJTalk](https://open-jtalk.sourceforge.net/).
demo/404.html ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <meta charset="utf-8">
3
+ <meta name="viewport" content="width=device-width, initial-scale=1">
4
+ <title>Not found – eeh</title>
5
+ <body style="font: 17px/1.5 system-ui, sans-serif; max-width: 40em; margin: 15vh auto; padding: 0 20px">
6
+ <h1>Not found</h1>
7
+ <p><a href="/">Back to the eeh demo</a></p>
8
+ </body>
demo/index.html ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>eeh</title>
7
+ <meta name="description" content="eeh is a 4.5M-parameter Japanese text-to-speech model. This page runs it in your browser.">
8
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%23171512'/%3E%3Cpath d='M8 13v6M12 9v14M16 12v8M20 7v18M24 13v6' stroke='%23f4efe6' stroke-width='2.4' stroke-linecap='round'/%3E%3C/svg%3E">
9
+ <style>
10
+ :root {
11
+ --paper: #f6f2ea; --ink: #1b1915; --muted: #6d665b; --line: #d9d2c4; --panel: #fffdf8;
12
+ --accent: #b4421f; --accent-ink: #fff; --ok: #2f6b3c;
13
+ --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
14
+ --sans: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
15
+ --ui: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
16
+ }
17
+ @media (prefers-color-scheme: dark) {
18
+ :root { --paper: #151412; --ink: #ece6da; --muted: #9a9284; --line: #35312a; --panel: #1d1b18; --accent: #e0703f; --accent-ink: #151412; --ok: #7fbf8c; }
19
+ }
20
+ * { box-sizing: border-box; }
21
+ body { margin: 0; background: var(--paper); color: var(--ink); font: 17px/1.55 var(--ui); }
22
+ main { max-width: 760px; margin: 0 auto; padding: 56px 20px 72px; }
23
+ header h1 { font: 600 44px/1.05 var(--sans); letter-spacing: -0.01em; margin: 0 0 14px; }
24
+ header p { margin: 0; color: var(--muted); max-width: 56ch; }
25
+ header p strong { color: var(--ink); font-weight: 600; }
26
+ .panel { margin-top: 36px; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 18px; }
27
+ textarea { width: 100%; min-height: 150px; resize: vertical; border: 0; outline: 0; background: transparent; color: inherit;
28
+ font: 20px/1.5 var(--sans); padding: 4px; }
29
+ .examples { display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0 2px; }
30
+ .examples button { font: 13px var(--ui); color: var(--muted); background: transparent; border: 1px solid var(--line);
31
+ border-radius: 999px; padding: 5px 11px; cursor: pointer; }
32
+ .examples button:hover { color: var(--ink); border-color: var(--muted); }
33
+ .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 14px 22px; border-top: 1px solid var(--line); margin-top: 14px; padding-top: 14px; }
34
+ .voices { display: inline-flex; border: 1px solid var(--line); border-radius: 9px; overflow: hidden; }
35
+ .voices label { padding: 7px 14px; font-size: 14px; cursor: pointer; color: var(--muted); }
36
+ .voices input { position: absolute; opacity: 0; pointer-events: none; }
37
+ .voices input:checked + span { color: var(--ink); font-weight: 600; }
38
+ .voices label:has(input:checked) { background: var(--paper); }
39
+ .voices label:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: -2px; }
40
+ .speed { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--muted); }
41
+ .speed input { width: 130px; accent-color: var(--accent); }
42
+ .speed output { font: 13px var(--mono); color: var(--ink); min-width: 4ch; }
43
+ #speak { margin-left: auto; min-width: 6em; font: 600 16px var(--ui); color: var(--accent-ink); background: var(--accent); border: 0;
44
+ border-radius: 10px; padding: 11px 22px; cursor: pointer; }
45
+ #speak:disabled { opacity: 0.45; cursor: default; }
46
+ #speak:focus-visible, textarea:focus-visible, .examples button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
47
+ .status { margin-top: 16px; font-size: 14px; color: var(--muted); min-height: 22px; }
48
+ .bar { height: 3px; background: var(--line); border-radius: 2px; margin-top: 8px; overflow: hidden; }
49
+ .bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width 0.15s; }
50
+ .bar[hidden] { display: none; }
51
+ .result[hidden] { display: none; }
52
+ .result { margin-top: 22px; }
53
+ audio { width: 100%; }
54
+ dl { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 16px 0 0; }
55
+ dl div { border-top: 1px solid var(--line); padding-top: 8px; }
56
+ dt { font-size: 12px; color: var(--muted); }
57
+ dd { margin: 2px 0 0; font: 15px var(--mono); }
58
+ #download { display: inline-block; margin-top: 8px; font-size: 14px; color: var(--ink); text-underline-offset: 3px; }
59
+ #download[hidden] { display: none; }
60
+ details { margin-top: 16px; font-size: 14px; color: var(--muted); }
61
+ details pre { white-space: pre-wrap; word-break: break-word; font: 13px/1.6 var(--mono); color: var(--ink); margin: 8px 0 0; }
62
+ .facts { margin-top: 44px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; border-top: 1px solid var(--line); }
63
+ .facts div { padding: 16px 12px 16px 0; border-bottom: 1px solid var(--line); }
64
+ .facts b { display: block; font: 600 22px var(--sans); }
65
+ .facts span { font-size: 13px; color: var(--muted); }
66
+ footer { margin-top: 36px; font-size: 14px; color: var(--muted); }
67
+ footer a { color: var(--ink); text-underline-offset: 3px; margin-right: 16px; }
68
+ footer p { margin: 14px 0 0; max-width: 62ch; }
69
+ @media (max-width: 560px) {
70
+ header h1 { font-size: 34px; } main { padding-top: 36px; }
71
+ dl { grid-template-columns: repeat(2, 1fr); } .facts { grid-template-columns: repeat(2, 1fr); }
72
+ #speak { margin-left: 0; width: 100%; }
73
+ }
74
+ </style>
75
+ </head>
76
+ <body>
77
+ <main>
78
+ <header>
79
+ <h1>eeh</h1>
80
+ <p>A <strong>4.5M-parameter</strong> Japanese text-to-speech model with two voices, trained from scratch.
81
+ This page runs it in your browser: nothing you type leaves your device.</p>
82
+ </header>
83
+
84
+ <section class="panel">
85
+ <textarea id="text" spellcheck="false" aria-label="Text to speak" lang="ja">こんにちは!これは、ブラウザの中だけで動く、小さな音声合成モデルです。</textarea>
86
+ <div class="examples" id="examples"></div>
87
+ <div class="controls">
88
+ <div class="voices" role="radiogroup" aria-label="Voice">
89
+ <label><input type="radio" name="voice" value="F1"><span>F1</span></label>
90
+ <label><input type="radio" name="voice" value="M1" checked><span>M1</span></label>
91
+ </div>
92
+ <label class="speed">Speed <input id="speed" type="range" min="0.7" max="1.4" step="0.05" value="1"><output id="speed-value">1.00</output></label>
93
+ <button id="speak" disabled>Speak</button>
94
+ </div>
95
+ </section>
96
+
97
+ <div class="status" id="status" role="status">Loading…</div>
98
+ <div class="bar" id="bar"><i></i></div>
99
+
100
+ <section class="result" id="result" hidden>
101
+ <audio id="audio" controls></audio>
102
+ <a id="download" download="eeh.wav" hidden>Download WAV</a>
103
+ <dl>
104
+ <div><dt>Audio</dt><dd id="m-audio">–</dd></div>
105
+ <div><dt>Time to generate</dt><dd id="m-time">–</dd></div>
106
+ <div><dt>Speed</dt><dd id="m-speed">–</dd></div>
107
+ <div><dt>To first audio</dt><dd id="m-first">–</dd></div>
108
+ </dl>
109
+ </section>
110
+
111
+ <section class="facts">
112
+ <div><b>4,534,219</b><span>parameters, waveform generator included</span></div>
113
+ <div><b>17 MB</b><span>model file (float32 safetensors, gzip)</span></div>
114
+ <div><b>24 kHz</b><span>mono output</span></div>
115
+ <div><b>2 voices</b><span>F1 and M1, Japanese</span></div>
116
+ <div><b>Rust</b><span>reads kanji, numbers and pitch accent; the whole stack is WebAssembly</span></div>
117
+ <div><b>Apache-2.0</b><span>code</span></div>
118
+ </section>
119
+
120
+ <footer>
121
+ <a href="https://github.com/n4ze3m/tiny-voca">tiny-voca (architecture)</a>
122
+ <a href="https://github.com/r9y9/pyopenjtalk">OpenJTalk (pyopenjtalk) dictionary</a>
123
+ <p>The first visit downloads about 26 MB (gzip): the model (17 MB), the dictionary (9 MB) and the program (0.4 MB), all kept
124
+ by the browser afterwards. Japanese only. Rare names and unusual readings are sometimes read wrongly.</p>
125
+ </footer>
126
+ </main>
127
+
128
+ <script src="player.js"></script>
129
+ <script>
130
+ const EXAMPLES = [
131
+ ["挨拶", "こんにちは!これは、ブラウザの中だけで動く、小さな音声合成モデルです。"],
132
+ ["数字", "会議は3月14日の午後3時半に変更になりました。料金は4250円です。"],
133
+ ["質問", "本当に私の誕生日を忘れていたの?もう九時半なの?そろそろ出かけないと間に合わないよ!"],
134
+ ["物語", "彼女は海を見たことがなかったので、長いあいだ水際に立ったまま、ひとことも話さずに波を見つめていた。"],
135
+ ["早口", "東京特許許可局の局長は、今日も急遽休暇を取った。"],
136
+ ];
137
+ const $ = (id) => document.getElementById(id);
138
+ const worker = new Worker("worker.js", { type: "module" });
139
+ // The model is loaded from ./model/eeh.safetensors.gz and ./model/eeh-dict.bin.gz; ?model=URL and ?dictionary=URL load others
140
+ // (a ".gz" address is gunzipped, any other is used as it is).
141
+ const params = new URLSearchParams(location.search);
142
+ const weightsUrl = new URL(params.get("model") || "model/eeh.safetensors.gz", location.href);
143
+ const dictionaryUrl = new URL(params.get("dictionary") || "model/eeh-dict.bin.gz", location.href);
144
+ let ready = false, busy = false, request = 0, url = null, rate = 0, live = null;
145
+
146
+ for (const [label, text] of EXAMPLES) {
147
+ const button = document.createElement("button");
148
+ button.textContent = label;
149
+ button.onclick = () => { $("text").value = text; $("text").focus(); };
150
+ $("examples").append(button);
151
+ }
152
+ $("speed").oninput = () => { $("speed-value").textContent = Number($("speed").value).toFixed(2); };
153
+
154
+ function setStatus(text, progress) {
155
+ $("status").textContent = text;
156
+ $("bar").hidden = progress == null;
157
+ if (progress != null) $("bar").firstElementChild.style.width = Math.round(progress * 100) + "%";
158
+ }
159
+ // While the sentences are playing, the button stops them.
160
+ function update() {
161
+ const playing = live !== null && live.playing;
162
+ $("speak").textContent = playing ? "Stop" : "Speak";
163
+ $("speak").disabled = !playing && (!ready || busy || !$("text").value.trim());
164
+ }
165
+ $("text").oninput = update;
166
+
167
+ function wav(samples, rate) {
168
+ const buffer = new ArrayBuffer(44 + samples.length * 2);
169
+ const view = new DataView(buffer);
170
+ const text = (offset, value) => { for (let i = 0; i < value.length; i++) view.setUint8(offset + i, value.charCodeAt(i)); };
171
+ text(0, "RIFF"); view.setUint32(4, 36 + samples.length * 2, true); text(8, "WAVEfmt ");
172
+ view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
173
+ view.setUint32(24, rate, true); view.setUint32(28, rate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
174
+ text(36, "data"); view.setUint32(40, samples.length * 2, true);
175
+ for (let i = 0; i < samples.length; i++) view.setInt16(44 + i * 2, Math.max(-1, Math.min(1, samples[i])) * 32767, true);
176
+ return new Blob([buffer], { type: "audio/wav" });
177
+ }
178
+
179
+ // The worker splits the text itself, so how far it is is told by the characters spoken of the characters sent.
180
+ let spoken = 0, total = 1;
181
+ worker.onmessage = ({ data }) => {
182
+ if (data.type === "status") setStatus(data.text, data.progress);
183
+ else if (data.type === "ready") {
184
+ ready = true; rate = data.sampleRate; setStatus("Ready."); update();
185
+ console.info("eeh ready", JSON.stringify(data.times));
186
+ } else if (data.type === "sentence" && data.id === request) {
187
+ if (live && data.audio) live.add(data.audio, data.sampleRate);
188
+ spoken += [...data.text.replace(/\s+/g, "")].length;
189
+ setStatus(`Speaking sentence ${data.index + 1}`, Math.min(1, spoken / total));
190
+ } else if (data.type === "done" && data.id === request) {
191
+ busy = false; update();
192
+ const seconds = data.audio.length / data.sampleRate;
193
+ if (url) URL.revokeObjectURL(url);
194
+ url = URL.createObjectURL(wav(data.audio, data.sampleRate));
195
+ $("audio").src = url;
196
+ $("download").href = url;
197
+ $("download").hidden = false;
198
+ // The sentences have been playing since the first one was made, so the whole clip only waits in the player.
199
+ // Where they could not be heard, it plays now.
200
+ if (!live || !live.end()) $("audio").play().catch(() => {});
201
+ $("m-audio").textContent = seconds.toFixed(1) + " s";
202
+ $("m-time").textContent = (data.totalTime / 1000).toFixed(2) + " s";
203
+ $("m-speed").textContent = (seconds / (data.totalTime / 1000)).toFixed(1) + "× real time";
204
+ $("m-first").textContent = Math.round(data.firstAudio) + " ms";
205
+ $("result").hidden = false;
206
+ setStatus("Done.");
207
+ } else if (data.type === "error") {
208
+ busy = false;
209
+ if (live) live.end();
210
+ update();
211
+ setStatus(data.plain ? data.message : "Something went wrong: " + data.message);
212
+ }
213
+ };
214
+ worker.onerror = (event) => setStatus("Could not start: " + event.message);
215
+
216
+ // Sound has to start inside a click, so the player is made here and not when the first sentence arrives.
217
+ function listen() {
218
+ const Context = window.AudioContext || window.webkitAudioContext;
219
+ if (!live && Context) {
220
+ let context = null;
221
+ try { context = new Context({ sampleRate: rate }); } catch (error) { try { context = new Context(); } catch (failed) {} }
222
+ if (context) live = livePlayer(context, update);
223
+ }
224
+ $("audio").pause();
225
+ if (live) live.begin();
226
+ }
227
+ $("audio").onplay = () => { if (live) live.stop(); };
228
+
229
+ $("speak").onclick = () => {
230
+ if (live && live.playing) { live.stop(); return; }
231
+ busy = true; spoken = 0; total = [...$("text").value.replace(/\s+/g, "")].length || 1;
232
+ request += 1;
233
+ listen();
234
+ update();
235
+ setStatus("Speaking…", 0);
236
+ worker.postMessage({ type: "speak", id: request, text: $("text").value,
237
+ voice: document.querySelector("input[name=voice]:checked").value, speed: Number($("speed").value) });
238
+ };
239
+ $("text").addEventListener("keydown", (event) => {
240
+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !$("speak").disabled) $("speak").click();
241
+ });
242
+
243
+ setStatus("Loading the model and the dictionary…");
244
+ worker.postMessage({ type: "load", weights: weightsUrl.href, dictionary: dictionaryUrl.href });
245
+ </script>
246
+ </body>
247
+ </html>
demo/model/eeh-dict.bin.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0934c6a66014bc0c55b3e12c3319c431cf9d2345bcb982ebbbe2db5f6cb3a507
3
+ size 9006746
demo/model/eeh.safetensors.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f54d6ed09ca4810757f07283966a2fd278fb595c3863c0cb891310fe17bead7f
3
+ size 16831065
demo/pkg/eeh_wasm.js ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * The eeh model and front end, loaded once and used for any number of texts.
3
+ */
4
+ export class Synthesizer {
5
+ __destroy_into_raw() {
6
+ const ptr = this.__wbg_ptr;
7
+ this.__wbg_ptr = 0;
8
+ SynthesizerFinalization.unregister(this);
9
+ return ptr;
10
+ }
11
+ free() {
12
+ const ptr = this.__destroy_into_raw();
13
+ wasm.__wbg_synthesizer_free(ptr, 0);
14
+ }
15
+ /**
16
+ * Loads the weights (`eeh.safetensors`) and the packed dictionary (`eeh-dict.bin`).
17
+ *
18
+ * # Errors
19
+ * A message when either file is malformed.
20
+ * @param {Uint8Array | number[]} weights
21
+ * @param {Uint8Array | number[]} dictionary
22
+ */
23
+ constructor(weights, dictionary) {
24
+ let ptr0, len0, ptr1, len1;
25
+ try {
26
+ ptr0 = passArray8ToWasm0(weights, wasm.__wbindgen_malloc);
27
+ len0 = WASM_VECTOR_LEN;
28
+ ptr1 = passArray8ToWasm0(dictionary, wasm.__wbindgen_malloc);
29
+ len1 = WASM_VECTOR_LEN;
30
+ } catch (e) {
31
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
32
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
33
+ throw e;
34
+ }
35
+ const ret = wasm.synthesizer_new(ptr0, len0, ptr1, len1);
36
+ if (ret[2]) {
37
+ throw takeFromExternrefTable0(ret[1]);
38
+ }
39
+ this.__wbg_ptr = ret[0];
40
+ SynthesizerFinalization.register(this, this.__wbg_ptr, this);
41
+ return this;
42
+ }
43
+ /**
44
+ * Sample rate of the audio, in Hz.
45
+ * @returns {number}
46
+ */
47
+ sampleRate() {
48
+ const ret = wasm.synthesizer_sampleRate(this.__wbg_ptr);
49
+ return ret >>> 0;
50
+ }
51
+ /**
52
+ * Speaks the text sentence by sentence: `callback(sentenceText, Float32Array)` is called as each is made
53
+ * and stops the rest by returning `false`. Each sentence is peak-limited on its own.
54
+ *
55
+ * # Errors
56
+ * As `speak`, and whatever the callback throws.
57
+ * @param {string} text
58
+ * @param {string} voice
59
+ * @param {any} options
60
+ * @param {Function} callback
61
+ */
62
+ speakEach(text, voice, options, callback) {
63
+ let ptr0, len0, ptr1, len1;
64
+ try {
65
+ ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
66
+ len0 = WASM_VECTOR_LEN;
67
+ ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
68
+ len1 = WASM_VECTOR_LEN;
69
+ } catch (e) {
70
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
71
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
72
+ throw e;
73
+ }
74
+ const ret = wasm.synthesizer_speakEach(this.__wbg_ptr, ptr0, len0, ptr1, len1, options, callback);
75
+ if (ret[1]) {
76
+ throw takeFromExternrefTable0(ret[0]);
77
+ }
78
+ }
79
+ /**
80
+ * The whole text as one waveform, peak-limited as a whole.
81
+ *
82
+ * # Errors
83
+ * A message for an unknown voice, a text with nothing readable in it, or a failure of the model.
84
+ * @param {string} text
85
+ * @param {string} voice
86
+ * @param {any} options
87
+ * @returns {Float32Array}
88
+ */
89
+ speak(text, voice, options) {
90
+ let ptr0, len0, ptr1, len1;
91
+ try {
92
+ ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
93
+ len0 = WASM_VECTOR_LEN;
94
+ ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
95
+ len1 = WASM_VECTOR_LEN;
96
+ } catch (e) {
97
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
98
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
99
+ throw e;
100
+ }
101
+ const ret = wasm.synthesizer_speak(this.__wbg_ptr, ptr0, len0, ptr1, len1, options);
102
+ if (ret[3]) {
103
+ throw takeFromExternrefTable0(ret[2]);
104
+ }
105
+ var v3 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
106
+ wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
107
+ return v3;
108
+ }
109
+ /**
110
+ * The voices of the model, e.g. `["F1", "M1"]`.
111
+ * @returns {string[]}
112
+ */
113
+ voices() {
114
+ const ret = wasm.synthesizer_voices(this.__wbg_ptr);
115
+ var v1 = getArrayJsValueFromWasm0(ret[0], ret[1]);
116
+ wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
117
+ return v1;
118
+ }
119
+ }
120
+ if (Symbol.dispose) Synthesizer.prototype[Symbol.dispose] = Synthesizer.prototype.free;
121
+ function __wbg_get_imports() {
122
+ const import0 = {
123
+ __proto__: null,
124
+ __wbg_Error_208446807d0d1e30: function(arg0, arg1) {
125
+ const ret = Error(getStringFromWasm0(arg0, arg1));
126
+ return ret;
127
+ },
128
+ __wbg___wbindgen_boolean_get_4f1baf9a00be3c74: function(arg0) {
129
+ const v = arg0;
130
+ const ret = typeof(v) === 'boolean' ? v : undefined;
131
+ return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
132
+ },
133
+ __wbg___wbindgen_is_null_c22311b1cc228e3a: function(arg0) {
134
+ const ret = arg0 === null;
135
+ return ret;
136
+ },
137
+ __wbg___wbindgen_is_object_8b968c3ab8e96595: function(arg0) {
138
+ const val = arg0;
139
+ const ret = typeof(val) === 'object' && val !== null;
140
+ return ret;
141
+ },
142
+ __wbg___wbindgen_number_get_934b640d0889af78: function(arg0, arg1) {
143
+ const obj = arg1;
144
+ const ret = typeof(obj) === 'number' ? obj : undefined;
145
+ getDataViewMemory0().setFloat64((arg0 >>> 0) + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
146
+ getDataViewMemory0().setInt32((arg0 >>> 0) + 4 * 0, !isLikeNone(ret), true);
147
+ },
148
+ __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
149
+ throw new Error(getStringFromWasm0(arg0, arg1));
150
+ },
151
+ __wbg_call_fc92fee6137d452d: function() { return handleError(function (arg0, arg1, arg2, arg3) {
152
+ const ret = arg0.call(arg1, arg2, arg3);
153
+ return ret;
154
+ }, arguments); },
155
+ __wbg_get_2080c49015e35254: function() { return handleError(function (arg0, arg1) {
156
+ const ret = Reflect.get(arg0, arg1);
157
+ return ret;
158
+ }, arguments); },
159
+ __wbg_new_from_slice_355c10c5d8f2addb: function(arg0, arg1) {
160
+ const ret = new Float32Array(getArrayF32FromWasm0(arg0, arg1));
161
+ return ret;
162
+ },
163
+ __wbindgen_generic_0000000000000001: function(arg0, arg1) {
164
+ // Cast intrinsic for `Ref(String) -> Externref`.
165
+ const ret = getStringFromWasm0(arg0, arg1);
166
+ return ret;
167
+ },
168
+ __wbindgen_init_externref_table: function() {
169
+ const table = wasm.__wbindgen_externrefs;
170
+ table.set(0, undefined);
171
+ table.set(1024, undefined);
172
+ table.set(1025, null);
173
+ table.set(1026, true);
174
+ table.set(1027, false);
175
+ },
176
+ };
177
+ return {
178
+ __proto__: null,
179
+ "./eeh_wasm_bg.js": import0,
180
+ };
181
+ }
182
+
183
+ const SynthesizerFinalization = (typeof FinalizationRegistry === 'undefined')
184
+ ? { register: () => {}, unregister: () => {} }
185
+ : new FinalizationRegistry(ptr => wasm.__wbg_synthesizer_free(ptr, 1));
186
+
187
+ function addToExternrefTable0(obj) {
188
+ const idx = wasm.__externref_table_alloc();
189
+ wasm.__wbindgen_externrefs.set(idx, obj);
190
+ return idx;
191
+ }
192
+
193
+ function getArrayF32FromWasm0(ptr, len) {
194
+ ptr = ptr >>> 0;
195
+ return getFloat32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
196
+ }
197
+
198
+ function getArrayJsValueFromWasm0(ptr, len) {
199
+ ptr = ptr >>> 0;
200
+ const mem = getDataViewMemory0();
201
+ const result = [];
202
+ for (let i = ptr; i < ptr + 4 * len; i += 4) {
203
+ result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true)));
204
+ }
205
+ wasm.__externref_drop_slice(ptr, len);
206
+ return result;
207
+ }
208
+
209
+ let cachedDataViewMemory0 = null;
210
+ function getDataViewMemory0() {
211
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
212
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
213
+ }
214
+ return cachedDataViewMemory0;
215
+ }
216
+
217
+ let cachedFloat32ArrayMemory0 = null;
218
+ function getFloat32ArrayMemory0() {
219
+ if (cachedFloat32ArrayMemory0 === null || cachedFloat32ArrayMemory0.byteLength === 0) {
220
+ cachedFloat32ArrayMemory0 = new Float32Array(wasm.memory.buffer);
221
+ }
222
+ return cachedFloat32ArrayMemory0;
223
+ }
224
+
225
+ function getStringFromWasm0(ptr, len) {
226
+ ptr = ptr >>> 0;
227
+ return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
228
+ }
229
+
230
+ let cachedUint8ArrayMemory0 = null;
231
+ function getUint8ArrayMemory0() {
232
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
233
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
234
+ }
235
+ return cachedUint8ArrayMemory0;
236
+ }
237
+
238
+ function handleError(f, args) {
239
+ try {
240
+ return f.apply(this, args);
241
+ } catch (e) {
242
+ const idx = addToExternrefTable0(e);
243
+ wasm.__wbindgen_exn_store(idx);
244
+ }
245
+ }
246
+
247
+ function isLikeNone(x) {
248
+ return x === undefined || x === null;
249
+ }
250
+
251
+ function passArray8ToWasm0(arg, malloc) {
252
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
253
+ getUint8ArrayMemory0().set(arg, ptr / 1);
254
+ WASM_VECTOR_LEN = arg.length;
255
+ return ptr;
256
+ }
257
+
258
+ function passStringToWasm0(arg, malloc, realloc) {
259
+ if (realloc === undefined) {
260
+ const buf = cachedTextEncoder.encode(arg);
261
+ const ptr = malloc(buf.length, 1) >>> 0;
262
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
263
+ WASM_VECTOR_LEN = buf.length;
264
+ return ptr;
265
+ }
266
+
267
+ let len = arg.length;
268
+ let ptr = malloc(len, 1) >>> 0;
269
+
270
+ const mem = getUint8ArrayMemory0();
271
+
272
+ let offset = 0;
273
+
274
+ for (; offset < len; offset++) {
275
+ const code = arg.charCodeAt(offset);
276
+ if (code > 0x7F) break;
277
+ mem[ptr + offset] = code;
278
+ }
279
+ if (offset !== len) {
280
+ if (offset !== 0) {
281
+ arg = arg.slice(offset);
282
+ }
283
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
284
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
285
+ const ret = cachedTextEncoder.encodeInto(arg, view);
286
+
287
+ offset += ret.written;
288
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
289
+ }
290
+
291
+ WASM_VECTOR_LEN = offset;
292
+ return ptr;
293
+ }
294
+
295
+ function takeFromExternrefTable0(idx) {
296
+ const value = wasm.__wbindgen_externrefs.get(idx);
297
+ wasm.__externref_table_dealloc(idx);
298
+ return value;
299
+ }
300
+
301
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
302
+ cachedTextDecoder.decode();
303
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
304
+ let numBytesDecoded = 0;
305
+ function decodeText(bytes) {
306
+ numBytesDecoded += bytes.length;
307
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
308
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
309
+ cachedTextDecoder.decode();
310
+ numBytesDecoded = bytes.length;
311
+ }
312
+ return cachedTextDecoder.decode(bytes);
313
+ }
314
+
315
+ const cachedTextEncoder = new TextEncoder();
316
+
317
+ if (!('encodeInto' in cachedTextEncoder)) {
318
+ cachedTextEncoder.encodeInto = function (arg, view) {
319
+ const buf = cachedTextEncoder.encode(arg);
320
+ view.set(buf);
321
+ return {
322
+ read: arg.length,
323
+ written: buf.length
324
+ };
325
+ };
326
+ }
327
+
328
+ let WASM_VECTOR_LEN = 0;
329
+
330
+ let wasmModule, wasmInstance, wasm;
331
+ function __wbg_finalize_init(instance, module) {
332
+ wasmInstance = instance;
333
+ wasm = instance.exports;
334
+ wasmModule = module;
335
+ cachedDataViewMemory0 = null;
336
+ cachedFloat32ArrayMemory0 = null;
337
+ cachedUint8ArrayMemory0 = null;
338
+ wasm.__wbindgen_start();
339
+ return wasm;
340
+ }
341
+
342
+ async function __wbg_load(module, imports) {
343
+ if (typeof Response === 'function' && module instanceof Response) {
344
+ if (!module.ok) {
345
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
346
+ }
347
+
348
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
349
+ try {
350
+ return await WebAssembly.instantiateStreaming(module, imports);
351
+ } catch (e) {
352
+ const validResponse = expectedResponseType(module.type);
353
+
354
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
355
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
356
+
357
+ } else { throw e; }
358
+ }
359
+ }
360
+
361
+ const bytes = await module.arrayBuffer();
362
+ return await WebAssembly.instantiate(bytes, imports);
363
+ } else {
364
+ const instance = await WebAssembly.instantiate(module, imports);
365
+
366
+ if (instance instanceof WebAssembly.Instance) {
367
+ return { instance, module };
368
+ } else {
369
+ return instance;
370
+ }
371
+ }
372
+
373
+ function expectedResponseType(type) {
374
+ switch (type) {
375
+ case 'basic': case 'cors': case 'default': return true;
376
+ }
377
+ return false;
378
+ }
379
+ }
380
+
381
+ function initSync(module) {
382
+ if (wasm !== undefined) return wasm;
383
+
384
+
385
+ if (module !== undefined) {
386
+ if (Object.getPrototypeOf(module) === Object.prototype) {
387
+ ({module} = module)
388
+ } else {
389
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
390
+ }
391
+ }
392
+
393
+ const imports = __wbg_get_imports();
394
+ if (!(module instanceof WebAssembly.Module)) {
395
+ module = new WebAssembly.Module(module);
396
+ }
397
+ const instance = new WebAssembly.Instance(module, imports);
398
+ return __wbg_finalize_init(instance, module);
399
+ }
400
+
401
+ let __wbg_init_promise;
402
+ async function __wbg_init(module_or_path) {
403
+ if (wasm !== undefined) return wasm;
404
+ if (__wbg_init_promise === undefined) {
405
+ __wbg_init_promise = __wbg_init_once(module_or_path);
406
+ __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; });
407
+ }
408
+ return __wbg_init_promise;
409
+ }
410
+
411
+ async function __wbg_init_once(module_or_path) {
412
+
413
+ if (module_or_path !== undefined) {
414
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
415
+ ({module_or_path} = module_or_path)
416
+ } else {
417
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
418
+ }
419
+ }
420
+
421
+ if (module_or_path === undefined) {
422
+ module_or_path = new URL('eeh_wasm_bg.wasm', import.meta.url);
423
+ }
424
+ const imports = __wbg_get_imports();
425
+
426
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
427
+ module_or_path = fetch(module_or_path);
428
+ }
429
+
430
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
431
+
432
+ return __wbg_finalize_init(instance, module);
433
+ }
434
+
435
+ export { initSync, __wbg_init as default };
demo/pkg/eeh_wasm_bg.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:858d115d0a40af27e871d7c570cd834c77f841f7733a146f7fed4e48584fb66f
3
+ size 951094
demo/player.js ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Plays the sentences of one request as they arrive. Each one starts on the sample where the one before it
2
+ // ends, so there is no gap between them. `context` is an AudioContext; changed() is called whenever `playing`
3
+ // may have changed.
4
+ function livePlayer(context, changed = () => {}) {
5
+ // A sentence with nothing before it to follow starts this many seconds from now, not at once: the browser then
6
+ // has it in hand before its first sample is due. Asked to start at once, it can start a few milliseconds late
7
+ // (measured in Firefox: up to 21 ms), and the next sentence would begin before it has ended.
8
+ const LEAD = 0.05;
9
+ const sources = new Set();
10
+ let open = false; // more sentences of this request may still come
11
+ let muted = false; // the listener stopped this request: its later sentences stay silent
12
+ let refused = false; // the browser said no when asked to start the sound
13
+ let queued = 0; // sentences of this request handed to the browser
14
+ let next = 0; // the context time at which the next sentence starts
15
+
16
+ function silence() {
17
+ for (const source of sources) {
18
+ source.onended = null;
19
+ try { source.stop(); } catch (error) { /* an old browser, and the sentence had already ended */ }
20
+ }
21
+ sources.clear();
22
+ }
23
+
24
+ return {
25
+ get playing() { return !muted && (open || sources.size > 0); },
26
+
27
+ // A new request. Call it from a click or a key press: browsers let a page start sound only there.
28
+ begin() {
29
+ silence();
30
+ open = true; muted = false; refused = false; queued = 0; next = 0;
31
+ if (context.state !== "running") Promise.resolve(context.resume()).catch(() => { refused = true; });
32
+ changed();
33
+ },
34
+
35
+ // Queue one sentence. It starts when the one before it ends, or right away when that moment has passed.
36
+ add(samples, rate) {
37
+ if (muted || !samples.length) return;
38
+ const buffer = context.createBuffer(1, samples.length, rate);
39
+ buffer.getChannelData(0).set(samples);
40
+ const source = context.createBufferSource();
41
+ source.buffer = buffer;
42
+ source.connect(context.destination);
43
+ source.onended = () => { sources.delete(source); changed(); };
44
+ const when = Math.max(next, context.currentTime + LEAD);
45
+ source.start(when);
46
+ next = when + samples.length / rate;
47
+ sources.add(source);
48
+ queued += 1;
49
+ },
50
+
51
+ // No more sentences will come; the queued ones play to the end. False when there is nothing to hear (no
52
+ // sentence came, or the browser refused the sound): the caller then plays the whole clip itself. A context
53
+ // that is only slow to start is not a refusal: a short text can be done before the sound is running, and
54
+ // its sentences play as soon as it is.
55
+ end() {
56
+ open = false;
57
+ const played = muted || (queued > 0 && !(refused && context.state !== "running"));
58
+ if (!played) silence();
59
+ changed();
60
+ return played;
61
+ },
62
+
63
+ stop() {
64
+ muted = true; open = false;
65
+ silence();
66
+ changed();
67
+ },
68
+ };
69
+ }
demo/worker.js ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Runs eeh (crates/eeh-wasm: the Rust front end and model in WebAssembly) off the main thread. A module worker.
2
+ // Messages in: {type: "load", weights, dictionary} urls; ".gz" ones are gunzipped
3
+ // {type: "speak", id, text, voice, speed}
4
+ // Messages out: status, ready, sentence (with its audio, as soon as it is made), done (with the whole clip),
5
+ // error (plain: true when the message is meant for the reader as it is).
6
+ // The text is split into sentences in Rust (eeh-frontend), so nothing here knows about Japanese.
7
+
8
+ import init, { Synthesizer } from "./pkg/eeh_wasm.js";
9
+
10
+ let synth;
11
+
12
+ const status = (text, progress) => postMessage({ type: "status", text, progress });
13
+
14
+ // Bump when the format of the cached files changes.
15
+ const STORE = "eeh-rust-1";
16
+
17
+ // The body of a response, reporting how much of it has come (as a fraction of content-length, when it has one).
18
+ function watched(response, label) {
19
+ const total = Number(response.headers.get("content-length")) || 0;
20
+ if (!response.body || !total) return response.body;
21
+ let received = 0;
22
+ return response.body.pipeThrough(new TransformStream({
23
+ transform(chunk, controller) {
24
+ received += chunk.length;
25
+ status(label, Math.min(1, received / total));
26
+ controller.enqueue(chunk);
27
+ },
28
+ }));
29
+ }
30
+
31
+ // A file of the demo as bytes. Gzipped files (the 36 MB dictionary is 9 MB that way; a host needs no compression
32
+ // settings) are gunzipped here, and the plain bytes are kept in Cache Storage with the validators of the response:
33
+ // the next visit asks the server only "has it changed?" (a 304 costs no body) and starts from the stored bytes.
34
+ // Another origin is not asked (that would need a CORS preflight): its file stays until the address changes.
35
+ async function asset(address, label) {
36
+ const url = new URL(address, self.location.href);
37
+ const key = url.href;
38
+ let store = null, kept = null;
39
+ try {
40
+ store = await caches.open(STORE);
41
+ kept = await store.match(key);
42
+ } catch (error) { store = null; }
43
+
44
+ const headers = {};
45
+ if (kept && url.origin === self.location.origin) {
46
+ const etag = kept.headers.get("x-etag"), modified = kept.headers.get("x-last-modified");
47
+ if (etag) headers["If-None-Match"] = etag;
48
+ if (modified) headers["If-Modified-Since"] = modified;
49
+ }
50
+ let response = null;
51
+ if (!kept || Object.keys(headers).length) {
52
+ try {
53
+ response = await fetch(key, { headers });
54
+ } catch (error) {
55
+ if (!kept) throw error; // offline, and kept: use what is stored
56
+ }
57
+ }
58
+ if (kept && (!response || response.status === 304 || (!response.ok && !Object.keys(headers).length))) {
59
+ return new Uint8Array(await kept.arrayBuffer());
60
+ }
61
+ if (!response.ok) throw new Error(`${key}: ${response.status}`);
62
+
63
+ let body = watched(response, label);
64
+ // A host that gzips on its own has been undone by the browser already (content-encoding is set then).
65
+ if (url.pathname.endsWith(".gz") && !response.headers.get("content-encoding")) {
66
+ body = body.pipeThrough(new DecompressionStream("gzip"));
67
+ }
68
+ const bytes = new Uint8Array(await new Response(body).arrayBuffer());
69
+ if (store) {
70
+ const info = { "x-etag": response.headers.get("etag") || "", "x-last-modified": response.headers.get("last-modified") || "" };
71
+ store.put(key, new Response(bytes, { headers: info })).catch(() => {});
72
+ }
73
+ return bytes;
74
+ }
75
+
76
+ async function load({ weights, dictionary }) {
77
+ const started = performance.now();
78
+ status("Loading the model and the dictionary", 0);
79
+ const [files] = await Promise.all([
80
+ Promise.all([asset(weights, "Loading the model"), asset(dictionary, "Loading the dictionary")]),
81
+ init(),
82
+ ]);
83
+ const fetched = performance.now();
84
+ synth = new Synthesizer(files[0], files[1]);
85
+ const built = performance.now();
86
+ synth.speak("こんにちは。", synth.voices()[0], {}); // warm up
87
+ const warm = performance.now();
88
+ postMessage({ type: "ready", voices: synth.voices(), sampleRate: synth.sampleRate(),
89
+ times: { files: fetched - started, synthesizer: built - fetched, warmup: warm - built, total: warm - started } });
90
+ }
91
+
92
+ // The model sometimes peaks above 1.0, which would clip in a 16-bit file: a clip is scaled down as a whole to PEAK, as
93
+ // Synthesizer.speak does. A sentence that is played before the rest is made is scaled on its own.
94
+ const PEAK = 0.99;
95
+ function limitPeak(samples) {
96
+ let loudest = 0;
97
+ for (let i = 0; i < samples.length; i++) loudest = Math.max(loudest, Math.abs(samples[i]));
98
+ if (loudest > PEAK) for (let i = 0; i < samples.length; i++) samples[i] *= PEAK / loudest;
99
+ }
100
+
101
+ // Shown when no sentence of a text could be read.
102
+ const JAPANESE_ONLY = "eeh only reads Japanese for now.";
103
+
104
+ function speak({ id, text, voice, speed }) {
105
+ const started = performance.now();
106
+ const chunks = [];
107
+ let index = 0, firstAudio = 0;
108
+ try {
109
+ synth.speakEach(text, voice, { speed, peak: null }, (sentence, audio) => {
110
+ chunks.push(audio);
111
+ if (!firstAudio) firstAudio = performance.now() - started;
112
+ // The page plays this sentence at once, before the whole clip is known: a copy, kept below full scale by itself; the clip keeps the original.
113
+ const heard = audio.slice();
114
+ limitPeak(heard);
115
+ postMessage({ type: "sentence", id, index: index++, text: sentence, audio: heard, sampleRate: synth.sampleRate(),
116
+ time: performance.now() - started }, [heard.buffer]);
117
+ return true;
118
+ });
119
+ } catch (error) {
120
+ const message = String(error && error.message || error);
121
+ postMessage({ type: "error", id, message: message.startsWith("nothing in the text could be read") ? JAPANESE_ONLY : message,
122
+ plain: message.startsWith("nothing in the text could be read") });
123
+ return;
124
+ }
125
+ const audio = new Float32Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
126
+ let offset = 0;
127
+ for (const chunk of chunks) { audio.set(chunk, offset); offset += chunk.length; }
128
+ limitPeak(audio);
129
+ postMessage({ type: "done", id, audio, sampleRate: synth.sampleRate(), sentences: index, firstAudio,
130
+ totalTime: performance.now() - started }, [audio.buffer]);
131
+ }
132
+
133
+ onmessage = async ({ data }) => {
134
+ try {
135
+ if (data.type === "load") await load(data);
136
+ else if (data.type === "speak") speak(data);
137
+ } catch (error) {
138
+ postMessage({ type: "error", id: data.id, message: String(error && error.message || error) });
139
+ }
140
+ };
eeh.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0426a98e9f6755b9f26f55dc460b288c9b297eb28859142c7e20e90889a8d633
3
+ size 18196805
eeh.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06df86fc0444ef7fc8158cc63f5e537d02c0e7518d1904b909cf8a28e9bf91b4
3
+ size 18161348
eval/metrics.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f1b09e4fbdc7cbc3a2715d172f9e8bc98766474e3920f633af67666525f1e7d
3
+ size 11021960
eval/report.json ADDED
The diff for this file is too large to render. See raw diff
 
onnx/config.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sample_rate": 24000,
3
+ "hop": 256,
4
+ "voices": [
5
+ "F1",
6
+ "M1"
7
+ ],
8
+ "symbols": [
9
+ "<pad>",
10
+ "<bos>",
11
+ "<eos>",
12
+ "<sp>",
13
+ "<unk>",
14
+ ",",
15
+ ".",
16
+ "?",
17
+ "!",
18
+ ";",
19
+ ":",
20
+ "\"",
21
+ "(",
22
+ ")",
23
+ "—",
24
+ "…",
25
+ "k",
26
+ "ky",
27
+ "kw",
28
+ "g",
29
+ "gy",
30
+ "gw",
31
+ "s",
32
+ "sh",
33
+ "z",
34
+ "j",
35
+ "t",
36
+ "ty",
37
+ "ch",
38
+ "ts",
39
+ "d",
40
+ "dy",
41
+ "n",
42
+ "ny",
43
+ "h",
44
+ "hy",
45
+ "f",
46
+ "b",
47
+ "by",
48
+ "p",
49
+ "py",
50
+ "m",
51
+ "my",
52
+ "y",
53
+ "r",
54
+ "ry",
55
+ "w",
56
+ "v",
57
+ "N",
58
+ "cl",
59
+ "a",
60
+ "i",
61
+ "u",
62
+ "e",
63
+ "o",
64
+ "A",
65
+ "I",
66
+ "U",
67
+ "E",
68
+ "O"
69
+ ],
70
+ "max_tokens": 512,
71
+ "max_frames": 3000,
72
+ "step": 104000,
73
+ "frontend": "pyopenjtalk",
74
+ "frontend_fingerprint": "785d412fa394ae31d619203871d1b134404e24241c324cab897dddc1d22c8f77",
75
+ "inputs": [
76
+ "tokens",
77
+ "stress",
78
+ "voice",
79
+ "speed",
80
+ "pitch_shift",
81
+ "pitch_range"
82
+ ],
83
+ "outputs": [
84
+ "audio",
85
+ "durations"
86
+ ]
87
+ }
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f31b311a23912933ed4fe515879c7df6a1330d14f085cd90d5328a3245a188f
3
+ size 21374050
samples/F1-hello.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0eaab40e82edcc1e2e7151b5be5d6b1973191a8e4f26714a6e1bd3b325f16b13
3
+ size 334380
samples/F1-numbers.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa38266688a098efbb25f6e9e46d70a105162ff46740e8f28341838e4efca5a4
3
+ size 331820
samples/F1-polite.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14d2fbe0ed3a74c42e71e79eb9fbadd51aa40673b87057250196e4b8f60142c4
3
+ size 276524
samples/F1-question.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48bf72366efeb4ec309f939464e3f71e737fce2ff1e35116d9ebc863e63d8efe
3
+ size 202284
samples/F1-story.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94515f99e2ed274ad5a7ac1f37ffd6f96a1bf0633a74e9c227802c8bb1a08c45
3
+ size 375340
samples/M1-hello.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:240b8da6e672c82bcc03a4e8fddcffa264a4b5b2502b5e00ff7833ba30b3ceaf
3
+ size 323116
samples/M1-numbers.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59bb3d00fb079090bbb100533a8348bc1b057e9d4d68c8f81c27c9d17db0eb43
3
+ size 324652
samples/M1-polite.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ce74a9de6045e85b5b3cf9da337f65abfb8d11f8982a758eadcebcc0721796f
3
+ size 271916
samples/M1-question.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0dbcc359dbad7eb433b52828d92026cfb53e12db787f17dd8adaf0e775ce0bda
3
+ size 197676
samples/M1-story.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0103009d7768ed55273131a4b9c0203272c60aa4ebc44fe2c9aabba40b168a0
3
+ size 354348
tiny_voca/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """tiny-voca: a small two-voice TTS trained from scratch.
2
+
3
+ The speech model loads no pretrained weights. A pretrained phoneme recogniser
4
+ is used only by the annotation step, and an ASR model only by evaluation.
5
+ """
6
+
7
+ from .config import Config
8
+ from .model import TinyVoca
9
+
10
+ __all__ = ["Config", "TinyVoca"]
tiny_voca/config.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+ import hashlib
3
+ import json
4
+
5
+ CHECKPOINT_FORMAT = 4 # 2-3: byte tokens + learned aligner (rejected explicitly).
6
+ ANNOTATION_VERSION = 3
7
+
8
+
9
+ def _digest(value):
10
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Config:
15
+ # Acoustic features (unchanged since feature schema 2; existing files are reused).
16
+ sample_rate: int = 24000
17
+ hop: int = 256
18
+ n_fft: int = 1024
19
+ n_mels: int = 80
20
+ f0_min: float = 50.0
21
+ f0_max: float = 600.0
22
+ speakers: tuple[str, ...] = ("F1", "M1")
23
+ # Phoneme tokens from tiny_voca.text.SYMBOLS (Japanese front end, version 1).
24
+ vocab_size: int = 60
25
+ # Text encoder and frame-level transformer.
26
+ channels: int = 192
27
+ heads: int = 4
28
+ feedforward: int = 640
29
+ kernel: int = 7
30
+ encoder_layers: int = 4
31
+ prosody_layers: int = 2
32
+ acoustic_layers: int = 5
33
+ dropout: float = 0.1
34
+ predictor_channels: int = 128
35
+ # Source-filter waveform head: harmonic branch and noise branch STFT sizes,
36
+ # causal/anticausal complex-cepstrum orders.
37
+ synth_fft: int = 512
38
+ synth_hop: int = 128
39
+ noise_fft: int = 256
40
+ noise_hop: int = 64
41
+ cep_causal: int = 80
42
+ cep_anti: int = 16
43
+ noise_cep: int = 32
44
+ harmonic_limit: float = 0.47
45
+ max_tokens: int = 512
46
+ max_frames: int = 3000
47
+ mel_mean: float = -5.0
48
+ mel_scale: float = 5.0
49
+ energy_mean: float = -4.0
50
+ energy_scale: float = 2.0
51
+ pitch_reference_hz: float = 200.0
52
+
53
+ def __post_init__(self):
54
+ from .text import SYMBOLS
55
+ if self.vocab_size != len(SYMBOLS):
56
+ raise ValueError(f"vocab_size must equal the phoneme inventory size {len(SYMBOLS)}")
57
+ if self.channels % self.heads or (self.channels // self.heads) % 2:
58
+ raise ValueError("channels must be divisible by heads with an even head width")
59
+ if not self.speakers or len(set(self.speakers)) != len(self.speakers):
60
+ raise ValueError("speaker names must be unique and nonempty")
61
+ for fft, hop in ((self.synth_fft, self.synth_hop), (self.noise_fft, self.noise_hop)):
62
+ if fft != 4 * hop or self.hop % hop:
63
+ raise ValueError("synthesis windows need 4x overlap and a hop dividing the acoustic hop")
64
+ if self.cep_causal + self.cep_anti >= self.synth_fft // 2 or self.noise_cep >= self.noise_fft // 2:
65
+ raise ValueError("cepstrum orders must be well below half the synthesis FFT size")
66
+ if min(self.encoder_layers, self.prosody_layers, self.acoustic_layers, self.kernel) < 1 or not self.kernel % 2:
67
+ raise ValueError("layer counts must be positive and the kernel odd")
68
+ if min(self.mel_scale, self.energy_scale) <= 0 or not 0 < self.harmonic_limit < 0.5:
69
+ raise ValueError("invalid normalization scale or harmonic limit")
70
+
71
+ def to_dict(self):
72
+ return asdict(self)
73
+
74
+ @classmethod
75
+ def from_dict(cls, value):
76
+ return cls(**{**value, "speakers": tuple(value["speakers"])})
77
+
78
+ @property
79
+ def fingerprint(self):
80
+ return _digest(self.to_dict())
81
+
82
+ @property
83
+ def acoustic_config(self):
84
+ """Settings that determine stored wave/mel/prosody tensors. Tokens and
85
+ durations are versioned separately by the annotation layer."""
86
+ fields = ("sample_rate", "hop", "n_fft", "n_mels", "f0_min", "f0_max")
87
+ return {**{key: getattr(self, key) for key in fields}, "feature_version": 2,
88
+ "pitch_reference_hz": 200, "log_floor": 1e-5}
89
+
90
+ @property
91
+ def acoustic_fingerprint(self):
92
+ return _digest(self.acoustic_config)
tiny_voca/infer.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ import re
4
+ import torch
5
+ from .config import CHECKPOINT_FORMAT, Config
6
+ from .model import TinyVoca, UtteranceTooLong
7
+ from .text import NothingToPronounce, frontend_fingerprint, phonemize
8
+
9
+ # The loudest sample of the audio that ``speak_text`` and the command return.
10
+ PEAK = 0.99
11
+ # Said when no sentence of a text could be read. The browser demo says the same.
12
+ JAPANESE_ONLY = "eeh only reads Japanese for now"
13
+ _SPACE = re.compile("[\\s" + chr(0xFEFF) + "]+") # JavaScript's \s, which the demo uses, takes U+FEFF too
14
+ # A sentence ends at 。!?… (full or half width) and at a full stop that is not
15
+ # a decimal point; closing quotes and brackets after the mark stay with it. A
16
+ # quotation that goes on with と or って (「行こう。」と言った) is not an end.
17
+ _END_MARKS = "。.!?!?…"
18
+ _CLOSING = "」』))\"'”’】»"
19
+ _END = rf"(?:(?:[{_END_MARKS}]|(?<!\d)\.|\.(?!\d))(?![{_END_MARKS}.]*[{_CLOSING}]+[とっ]))"
20
+ _SENTENCE = re.compile(rf"(?:(?!{_END}).)+(?:{_END})*[{_CLOSING}]*|(?:{_END})+[{_CLOSING}]*", re.S)
21
+ _MARKED = frozenset(_END_MARKS + "、,;:;:.")
22
+ _CLAUSE_END = re.compile(r"(?<=[、,;:;:—])")
23
+ _TEXT_END = re.compile("[\\s" + chr(0xFEFF) + "]+$")
24
+
25
+
26
+ def load_model(path, device="cpu"):
27
+ state = torch.load(path, map_location="cpu", weights_only=True)
28
+ if state.get("format_version") != CHECKPOINT_FORMAT:
29
+ raise ValueError("unsupported checkpoint format: byte-token checkpoints (format 2-3) cannot be used with this code")
30
+ if state["frontend"]["fingerprint"] != frontend_fingerprint():
31
+ raise ValueError("checkpoint was trained with a different phoneme inventory/front end")
32
+ model = TinyVoca(Config.from_dict(state["config"]))
33
+ model.load_state_dict(state["model"], strict=True)
34
+ return model.to(device).eval()
35
+
36
+
37
+ def sentences(text):
38
+ """The sentences of ``text``, never cut inside a number. The browser demo
39
+ splits the same way (``web/public/worker.js``); keep the two alike."""
40
+ parts = (part.strip() for part in _SENTENCE.findall(_SPACE.sub(" ", text).strip()))
41
+ return [part for part in parts if any(char.isalnum() for char in part)]
42
+
43
+
44
+ def finished(text):
45
+ """``text`` with 。 added when it ends without a mark. Before a final mark
46
+ the voice lets the last mora fall; without one the audio breaks off. A
47
+ closing quote or bracket after the mark is fine; an emoji or a sign is no
48
+ mark. The browser demo does the same (``web/public/worker.js``); keep the
49
+ two alike."""
50
+ body = _TEXT_END.sub("", text)
51
+ if not body:
52
+ return text
53
+ core = body.rstrip(_CLOSING)
54
+ return text if core and core[-1] in _MARKED else body + "。"
55
+
56
+
57
+ def shorter(text):
58
+ """``text`` in smaller pieces: cut after 、 and the like if it has any,
59
+ else in two halves, never inside a number. ``[]`` for a single character."""
60
+ pieces = [piece for piece in _CLAUSE_END.split(text) if piece.strip()]
61
+ if len(pieces) > 1:
62
+ return pieces
63
+ if len(text) < 2:
64
+ return []
65
+ cuts = [i for i in range(1, len(text)) if not (text[i - 1].isdigit() and text[i].isdigit())]
66
+ if not cuts:
67
+ return []
68
+ middle = min(cuts, key=lambda i: abs(i - len(text) / 2))
69
+ return [text[:middle], text[middle:]]
70
+
71
+
72
+ def limit_peak(wave, peak=PEAK):
73
+ """``wave`` scaled down as a whole when its loudest sample is above
74
+ ``peak``; quieter audio is returned as it is. The model sometimes peaks
75
+ above 1.0, and that clips when the audio is saved as 16-bit samples."""
76
+ loudest = float(wave.abs().max()) if wave.numel() else 0.0
77
+ return wave * (peak / loudest) if loudest > peak else wave
78
+
79
+
80
+ def _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range):
81
+ """Phonemes -> (float waveform tensor, details): one call of the model."""
82
+ device = next(model.parameters()).device
83
+ tokens = torch.tensor([phones.ids], device=device)
84
+ stress = torch.tensor([phones.stress], device=device)
85
+ speaker = torch.tensor([model.config.speakers.index(voice)], device=device)
86
+ audio, lengths, details = model.synthesize(tokens, stress, torch.tensor([len(phones)], device=device), speaker, speed, pitch_shift, seed, pitch_range)
87
+ if not torch.isfinite(audio).all():
88
+ raise RuntimeError("model produced non-finite audio")
89
+ return audio[0, :int(lengths[0])].cpu(), details
90
+
91
+
92
+ def speak(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0):
93
+ """One utterance: text -> (float waveform tensor, phonemized text, details).
94
+ Same front end as training. The audio is the model's output as it is and
95
+ can peak above 1.0 (see ``limit_peak``). ``speak_text`` reads text of any
96
+ length."""
97
+ phones = phonemize(text)
98
+ if len(phones) > model.config.max_tokens:
99
+ raise ValueError("text is too long for one utterance; speak_text splits it into sentences")
100
+ wave, details = _voice(model, phones, voice, speed, pitch_shift, seed, pitch_range)
101
+ return wave, phones, details
102
+
103
+
104
+ def speak_text(model, text, voice, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, peak=PEAK):
105
+ """Text of any length -> (float waveform tensor, phonemized utterances).
106
+
107
+ The text is read sentence by sentence and the audio is joined. A text that
108
+ ends without a mark gets a full stop (``finished``). A sentence
109
+ too long for one call of the model (``max_tokens`` phonemes or
110
+ ``max_frames`` frames) is cut after commas, then between words. A sentence
111
+ with nothing to pronounce (another script, a face, signs only) is skipped;
112
+ when no sentence could be read, ``NothingToPronounce`` says so. The audio
113
+ is scaled down as a whole when it peaks above ``peak``, so that it can be
114
+ saved as 16-bit samples without clipping; ``peak=None`` returns the
115
+ model's output as it is."""
116
+ limit = model.config.max_tokens - 12
117
+ waves, spoken = [], []
118
+
119
+ def read(piece):
120
+ try:
121
+ phones = phonemize(piece)
122
+ except NothingToPronounce:
123
+ return
124
+ if len(phones) <= limit:
125
+ try:
126
+ wave, _ = _voice(model, phones, voice, speed, pitch_shift, seed + len(waves), pitch_range)
127
+ except UtteranceTooLong:
128
+ pass
129
+ else:
130
+ waves.append(wave)
131
+ spoken.append(phones)
132
+ return
133
+ pieces = shorter(piece)
134
+ if not pieces:
135
+ raise ValueError(f"one word is too long to speak: {piece[:40]!r}")
136
+ for part in pieces:
137
+ read(part)
138
+
139
+ for sentence in sentences(finished(text)):
140
+ read(sentence)
141
+ if not waves:
142
+ raise NothingToPronounce(f"nothing in the text could be read: {JAPANESE_ONLY}")
143
+ wave = torch.cat(waves)
144
+ return (wave if peak is None else limit_peak(wave, peak)), spoken
145
+
146
+
147
+ def main():
148
+ parser = argparse.ArgumentParser(description="Generate speech from a trained tiny-voca inference checkpoint")
149
+ parser.add_argument("--checkpoint", type=Path, required=True)
150
+ source = parser.add_mutually_exclusive_group(required=True)
151
+ source.add_argument("--text", help="Text of any length; it is read sentence by sentence")
152
+ source.add_argument("--text-file", type=Path, help="Read the text from a file (UTF-8)")
153
+ parser.add_argument("--voice", help="A voice of the checkpoint (default: its first, e.g. F1)")
154
+ parser.add_argument("--output", type=Path, required=True)
155
+ parser.add_argument("--speed", type=float, default=1)
156
+ parser.add_argument("--pitch-shift", type=float, default=0, help="Added to log F0 (0.058 is about one semitone)")
157
+ parser.add_argument("--pitch-range", type=float, default=1, help="Scale pitch movement around the utterance mean (1 = as predicted)")
158
+ parser.add_argument("--device", default="cpu")
159
+ args = parser.parse_args()
160
+ import soundfile as sf
161
+ model = load_model(args.checkpoint, args.device)
162
+ voice = args.voice or model.config.speakers[0]
163
+ if voice not in model.config.speakers:
164
+ parser.error(f"--voice must be one of {', '.join(model.config.speakers)}")
165
+ text = args.text if args.text is not None else args.text_file.read_text(encoding="utf-8")
166
+ try:
167
+ raw, spoken = speak_text(model, text, voice, args.speed, args.pitch_shift, pitch_range=args.pitch_range, peak=None)
168
+ except NothingToPronounce:
169
+ parser.exit(1, f"{JAPANESE_ONLY}. Nothing in the text could be read, so no file was written.\n")
170
+ wave = limit_peak(raw)
171
+ args.output.parent.mkdir(parents=True, exist_ok=True)
172
+ # Float samples, never above PEAK: a later conversion to 16-bit does not clip.
173
+ sf.write(args.output, wave.numpy(), model.config.sample_rate, subtype="FLOAT")
174
+ for phones in spoken:
175
+ print(" ".join(phones.symbols))
176
+ loudest = float(raw.abs().max())
177
+ scaled = f", scaled down to {PEAK}" if wave is not raw else ""
178
+ print(f"Saved {len(wave)/model.config.sample_rate:.2f}s in {len(spoken)} utterance{'s' if len(spoken) != 1 else ''}; peak={loudest:.4f}{scaled}")
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
tiny_voca/model.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """tiny-voca v2: feed-forward transformer with a pitch-driven source-filter head.
2
+
3
+ All weights start random. Tensor conventions: hidden [B,T,C], frame features
4
+ [B,T], waveform [B,S]. Acoustic frame i is centred on sample ``i * hop``.
5
+
6
+ phoneme + stress + voice -> transformer encoder -> duration predictor
7
+ -> repeat tokens by duration (supervised durations while training)
8
+ -> frame transformer A -> pitch / voicing / energy
9
+ -> frame transformer B -> filter parameters
10
+ -> harmonic pulse train (from pitch) and noise, each shaped by its
11
+ time-varying filter in the STFT domain -> 24 kHz waveform
12
+
13
+ The waveform head has no neural upsampling network. The oscillator supplies the
14
+ periodicity that a tiny decoder cannot render reliably on its own; the network
15
+ only has to predict slowly varying spectral envelopes (complex cepstra), which
16
+ is what keeps the voice from sounding buzzy or unstable at this size.
17
+ """
18
+
19
+ import math
20
+ import torch
21
+ from torch import nn
22
+ from torch.nn import functional as F
23
+ from .config import Config
24
+ from .text import PHONE_IDS, SYMBOL_TO_ID, VOWELS
25
+
26
+
27
+ class UtteranceTooLong(ValueError):
28
+ """The utterance needs more frames than ``max_frames``: split the input."""
29
+
30
+
31
+ def length_mask(lengths, size=None):
32
+ size = int(lengths.max()) if size is None else size
33
+ return torch.arange(size, device=lengths.device)[None, :] < lengths[:, None]
34
+
35
+
36
+ def rotary_table(size, width, device):
37
+ inverse = 1.0 / (10000 ** (torch.arange(0, width, 2, device=device, dtype=torch.float32) / width))
38
+ angle = torch.arange(size, device=device, dtype=torch.float32)[:, None] * inverse[None]
39
+ return angle.cos(), angle.sin()
40
+
41
+
42
+ def rotate(x, table):
43
+ cos, sin = table[0].to(x.dtype), table[1].to(x.dtype)
44
+ a, b = x[..., 0::2], x[..., 1::2]
45
+ return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)
46
+
47
+
48
+ class Attention(nn.Module):
49
+ """Self-attention with rotary (relative) positions: no absolute position
50
+ table, so utterances longer than those seen in training stay in range."""
51
+
52
+ def __init__(self, channels, heads, dropout):
53
+ super().__init__()
54
+ self.heads, self.dropout = heads, dropout
55
+ self.qkv = nn.Linear(channels, 3 * channels)
56
+ self.out = nn.Linear(channels, channels)
57
+
58
+ def forward(self, x, mask, table):
59
+ b, t, c = x.shape
60
+ q, k, v = self.qkv(x).view(b, t, 3, self.heads, c // self.heads).permute(2, 0, 3, 1, 4)
61
+ y = F.scaled_dot_product_attention(rotate(q, table), rotate(k, table), v, attn_mask=mask[:, None, None, :],
62
+ dropout_p=self.dropout if self.training else 0.0)
63
+ return self.out(y.transpose(1, 2).reshape(b, t, c))
64
+
65
+
66
+ class Block(nn.Module):
67
+ def __init__(self, c):
68
+ super().__init__()
69
+ self.norm1 = nn.LayerNorm(c.channels)
70
+ self.attention = Attention(c.channels, c.heads, c.dropout)
71
+ self.norm2 = nn.LayerNorm(c.channels)
72
+ self.depthwise = nn.Conv1d(c.channels, c.channels, c.kernel, padding=c.kernel // 2, groups=c.channels)
73
+ self.expand = nn.Linear(c.channels, c.feedforward)
74
+ self.project = nn.Linear(c.feedforward, c.channels)
75
+ self.dropout = nn.Dropout(c.dropout)
76
+
77
+ def forward(self, x, mask, table):
78
+ keep = mask[..., None]
79
+ x = (x + self.dropout(self.attention(self.norm1(x), mask, table))) * keep
80
+ # Mask before the convolution so padded positions cannot leak back in.
81
+ y = self.depthwise((self.norm2(x) * keep).transpose(1, 2)).transpose(1, 2)
82
+ y = self.project(self.dropout(F.gelu(self.expand(y))))
83
+ return (x + self.dropout(y)) * keep
84
+
85
+
86
+ class Stack(nn.Module):
87
+ def __init__(self, c, layers):
88
+ super().__init__()
89
+ self.blocks = nn.ModuleList(Block(c) for _ in range(layers))
90
+ self.norm = nn.LayerNorm(c.channels)
91
+ self.width = c.channels // c.heads
92
+
93
+ def forward(self, x, mask):
94
+ table = rotary_table(x.shape[1], self.width, x.device)
95
+ for block in self.blocks:
96
+ x = block(x, mask, table)
97
+ return self.norm(x) * mask[..., None]
98
+
99
+
100
+ class Predictor(nn.Module):
101
+ def __init__(self, c, outputs):
102
+ super().__init__()
103
+ p = c.predictor_channels
104
+ self.conv1 = nn.Conv1d(c.channels, p, 3, padding=1)
105
+ self.conv2 = nn.Conv1d(p, p, 3, padding=1)
106
+ self.norm1, self.norm2 = nn.LayerNorm(p), nn.LayerNorm(p)
107
+ self.drop = nn.Dropout(c.dropout)
108
+ self.out = nn.Linear(p, outputs)
109
+
110
+ def forward(self, x, mask):
111
+ x = self.conv1((x * mask[..., None]).transpose(1, 2)).transpose(1, 2)
112
+ x = self.drop(self.norm1(F.gelu(x))) * mask[..., None]
113
+ x = self.conv2(x.transpose(1, 2)).transpose(1, 2)
114
+ x = self.drop(self.norm2(F.gelu(x)))
115
+ return self.out(x) * mask[..., None]
116
+
117
+
118
+ def pulse_train(f0, sample_rate, hop, limit=0.47, phase=None):
119
+ """Band-limited pulse train [B, T*hop] with unit power for f0 [B, T] in Hz.
120
+
121
+ Frame values sit at samples i*hop and are interpolated in the log domain.
122
+ The sum of all harmonics below ``limit * sample_rate`` has the closed form
123
+ sin((K+1/2)x) / (2 sin(x/2)) - 1/2; the top harmonic fades in and out so the
124
+ signal stays continuous while the pitch glides. Float64 keeps the phase exact.
125
+ """
126
+ frames = f0.shape[1]
127
+ knots = torch.log(f0.double().clamp_min(1.0))
128
+ knots = torch.cat((knots, knots[:, -1:]), dim=1)
129
+ position = torch.arange(frames * hop, device=f0.device, dtype=torch.float64) / hop
130
+ low = position.floor().long()
131
+ weight = position - low
132
+ frequency = torch.exp(knots[:, low] * (1 - weight) + knots[:, low + 1] * weight)
133
+ theta = 2 * math.pi * torch.cumsum(frequency / sample_rate, dim=1)
134
+ if phase is not None:
135
+ theta = theta + phase.double()[:, None]
136
+ theta = torch.remainder(theta, 2 * math.pi)
137
+ harmonics = (limit * sample_rate / frequency).clamp_min(1.0)
138
+ whole = torch.floor(harmonics)
139
+ denominator = 2 * torch.sin(theta / 2)
140
+ tiny = denominator.abs() < 1e-7
141
+ core = torch.where(tiny, whole, torch.sin((whole + 0.5) * theta) / torch.where(tiny, torch.ones_like(denominator), denominator) - 0.5)
142
+ wave = core + (harmonics - whole) * torch.cos((whole + 1) * theta)
143
+ return (wave * torch.sqrt(2.0 / harmonics)).float()
144
+
145
+
146
+ def filtered(source, response, fft, hop, window):
147
+ """Time-varying filtering: response [B, frames, bins] multiplies the STFT."""
148
+ spectrum = torch.stft(source, fft, hop, window=window, center=True, pad_mode="constant", return_complex=True)
149
+ if spectrum.shape[-1] != response.shape[1]:
150
+ raise ValueError("filter frames do not match the source")
151
+ return torch.istft(spectrum * response.transpose(1, 2), fft, hop, window=window, center=True, length=source.shape[-1])
152
+
153
+
154
+ def cepstrum_response(causal, anticausal, fft):
155
+ """Complex frequency response exp(FFT(cepstrum)). Causal coefficients give a
156
+ minimum-phase filter; anticausal ones add a maximum-phase part (glottal pulse)."""
157
+ buffer = causal.new_zeros(*causal.shape[:-1], fft)
158
+ buffer[..., :causal.shape[-1]] = causal
159
+ if anticausal is not None:
160
+ buffer[..., fft - anticausal.shape[-1]:] = anticausal.flip(-1)
161
+ spectrum = torch.fft.rfft(buffer, dim=-1)
162
+ return torch.polar(torch.exp(spectrum.real.clamp(-14, 6)), spectrum.imag)
163
+
164
+
165
+ class SourceFilter(nn.Module):
166
+ """Harmonic-plus-noise synthesis controlled per frame by two linear heads."""
167
+
168
+ def __init__(self, c):
169
+ super().__init__()
170
+ self.config = c
171
+ self.harmonic_steps, self.noise_steps = c.hop // c.synth_hop, c.hop // c.noise_hop
172
+ self.harmonic = nn.Linear(c.channels, c.cep_causal + c.cep_anti + self.harmonic_steps)
173
+ self.noise = nn.Linear(c.channels, c.noise_cep + self.noise_steps)
174
+ for head, level in ((self.harmonic, -1.5), (self.noise, -2.5)): # start quiet and spectrally flat
175
+ nn.init.zeros_(head.weight)
176
+ nn.init.zeros_(head.bias)
177
+ head.bias.data[0] = level
178
+
179
+ def lifter(size, first):
180
+ scale = 1.0 / (1.0 + torch.arange(first, first + size, dtype=torch.float32) / 4)
181
+ if first == 0:
182
+ scale[0] = 2.0 # coefficient 0 is the log gain and needs range
183
+ return scale
184
+ self.register_buffer("causal_lifter", lifter(c.cep_causal, 0), persistent=False)
185
+ self.register_buffer("anti_lifter", lifter(c.cep_anti, 1), persistent=False)
186
+ self.register_buffer("noise_lifter", lifter(c.noise_cep, 0), persistent=False)
187
+ self.register_buffer("synth_window", torch.hann_window(c.synth_fft), persistent=False)
188
+ self.register_buffer("noise_window", torch.hann_window(c.noise_fft), persistent=False)
189
+
190
+ @staticmethod
191
+ def _take(values, index):
192
+ return values.gather(1, index[..., None].expand(-1, -1, values.shape[-1]))
193
+
194
+ def _subframes(self, frames, lengths, steps):
195
+ """Sub-frame j uses frame j // steps; indices past an utterance's end
196
+ repeat its last sub-frame so padding never changes real audio. Two extra
197
+ sub-frames cover the half window of zeros appended to the source."""
198
+ sub = torch.arange(steps * frames + 3, device=lengths.device)[None].expand(len(lengths), -1)
199
+ return torch.minimum(sub, (steps * lengths - 1).clamp_min(0)[:, None])
200
+
201
+ @staticmethod
202
+ def _shape(source, response, fft, hop, window):
203
+ # Half a window of trailing zeros: the frames around an utterance's end are
204
+ # then the same whether it stands alone or is padded inside a batch.
205
+ return filtered(F.pad(source, (0, fft // 2)), response, fft, hop, window)[:, :source.shape[-1]]
206
+
207
+ def forward(self, hidden, f0, lengths, noise=None, phase=None):
208
+ c = self.config
209
+ frames = hidden.shape[1]
210
+ samples = frames * c.hop
211
+ with torch.autocast(device_type=hidden.device.type, enabled=False):
212
+ hidden = hidden.float()
213
+ audible = length_mask(lengths * c.hop, samples)
214
+ last = (lengths - 1).clamp_min(0)[:, None]
215
+ # Harmonic branch: envelope interpolated between frames, one gain per sub-frame.
216
+ h = self.harmonic(hidden)
217
+ split = c.cep_causal + c.cep_anti
218
+ sub = self._subframes(frames, lengths, self.harmonic_steps)
219
+ here, following = sub // self.harmonic_steps, torch.minimum((sub + 1) // self.harmonic_steps, last)
220
+ causal = 0.5 * (self._take(h[..., :c.cep_causal], here) + self._take(h[..., :c.cep_causal], following)) * self.causal_lifter
221
+ anti = 0.5 * (self._take(h[..., c.cep_causal:split], here) + self._take(h[..., c.cep_causal:split], following)) * self.anti_lifter
222
+ causal = torch.cat((causal[..., :1] + h[..., split:].flatten(1).gather(1, sub)[..., None], causal[..., 1:]), dim=-1)
223
+ harmonic_response = cepstrum_response(causal, anti, c.synth_fft)
224
+ # Noise branch: one envelope per frame, four gains per frame for sharp consonants.
225
+ n = self.noise(hidden)
226
+ sub = self._subframes(frames, lengths, self.noise_steps)
227
+ shape = self._take(n[..., :c.noise_cep], sub // self.noise_steps) * self.noise_lifter
228
+ shape = torch.cat((shape[..., :1] + n[..., c.noise_cep:].flatten(1).gather(1, sub)[..., None], shape[..., 1:]), dim=-1)
229
+ noise_response = cepstrum_response(shape, None, c.noise_fft)
230
+ # Hold the last real pitch value through padding: the pitch glide inside an
231
+ # utterance's final frame must not depend on what the batch was padded with.
232
+ f0 = f0.float().gather(1, torch.minimum(torch.arange(frames, device=f0.device)[None], last))
233
+ pulses = pulse_train(f0, c.sample_rate, c.hop, c.harmonic_limit, phase) * audible
234
+ if noise is None:
235
+ noise = torch.randn(hidden.shape[0], samples, device=hidden.device)
236
+ wave = (self._shape(pulses, harmonic_response, c.synth_fft, c.synth_hop, self.synth_window)
237
+ + self._shape(noise * audible, noise_response, c.noise_fft, c.noise_hop, self.noise_window))
238
+ return wave * audible
239
+
240
+
241
+ class TinyVoca(nn.Module):
242
+ def __init__(self, config=Config()):
243
+ super().__init__()
244
+ self.config = c = config
245
+ self.tokens = nn.Embedding(c.vocab_size, c.channels, padding_idx=0)
246
+ self.stress = nn.Embedding(3, c.channels)
247
+ self.voices = nn.Embedding(len(c.speakers), c.channels)
248
+ self.encoder = Stack(c, c.encoder_layers)
249
+ # Outputs per token: log(1 + frames) and, for pause-capable tokens, a
250
+ # "has frames at all" logit. A pause is absent more often than present, so
251
+ # one regression would average both cases into a pause that is too short.
252
+ self.duration = Predictor(c, 2)
253
+ self.frame_voices = nn.Embedding(len(c.speakers), c.channels)
254
+ self.frame_position = nn.Linear(3, c.channels)
255
+ self.prosody_stack = Stack(c, c.prosody_layers)
256
+ # Outputs: continuous log(F0/reference), voiced logit, normalized log RMS energy.
257
+ self.prosody_head = nn.Linear(c.channels, 3)
258
+ self.prosody_projection = nn.Linear(3, c.channels)
259
+ self.acoustic_stack = Stack(c, c.acoustic_layers)
260
+ self.vocoder = SourceFilter(c)
261
+ phones = torch.zeros(c.vocab_size, dtype=torch.bool)
262
+ phones[sorted(PHONE_IDS)] = True
263
+ self.register_buffer("phone_tokens", phones, persistent=False)
264
+ vowels = torch.zeros(c.vocab_size, dtype=torch.bool)
265
+ vowels[[SYMBOL_TO_ID[v] for v in VOWELS]] = True
266
+ self.register_buffer("vowel_tokens", vowels, persistent=False)
267
+
268
+ def encode(self, tokens, stress, lengths, speakers):
269
+ if tokens.ndim != 2 or stress.shape != tokens.shape or lengths.shape != (tokens.shape[0],) or speakers.shape != lengths.shape:
270
+ raise ValueError("expected tokens[B,N], stress[B,N], lengths[B], speakers[B]")
271
+ if tokens.shape[1] > self.config.max_tokens or bool((lengths < 1).any()) or bool((lengths > tokens.shape[1]).any()):
272
+ raise ValueError("invalid token length")
273
+ mask = length_mask(lengths, tokens.shape[1])
274
+ x = (self.tokens(tokens) + self.stress(stress) + self.voices(speakers)[:, None]) * mask[..., None]
275
+ return self.encoder(x, mask), mask
276
+
277
+ def expand(self, hidden, durations, token_mask, speakers):
278
+ """Repeat token states by integer durations (zero is allowed for pause
279
+ tokens) and add each frame's position inside its token."""
280
+ if durations.shape != token_mask.shape or bool((durations < 0).any()) or bool((durations[~token_mask] != 0).any()):
281
+ raise ValueError("invalid durations")
282
+ lengths = durations.sum(1)
283
+ if bool((lengths < 1).any()):
284
+ raise ValueError("utterance has no frames")
285
+ if bool((lengths > self.config.max_frames).any()):
286
+ raise UtteranceTooLong("utterance exceeds max_frames; split the input")
287
+ size = int(lengths.max())
288
+ ends = durations.cumsum(1)
289
+ frame = torch.arange(size, device=hidden.device)[None].expand(hidden.shape[0], size).contiguous()
290
+ index = torch.searchsorted(ends, frame, right=True).clamp(max=durations.shape[1] - 1)
291
+ owned = durations.gather(1, index).clamp_min(1)
292
+ offset = frame - (ends.gather(1, index) - durations.gather(1, index))
293
+ relative = (offset.to(hidden.dtype) + 0.5) / owned
294
+ features = torch.stack((relative, 1 - relative, torch.log1p(owned.to(hidden.dtype)) / 4), dim=-1)
295
+ mask = frame < lengths[:, None]
296
+ expanded = hidden.gather(1, index[..., None].expand(-1, -1, hidden.shape[-1]))
297
+ expanded = expanded + self.frame_position(features) + self.frame_voices(speakers)[:, None]
298
+ return expanded * mask[..., None], mask, lengths
299
+
300
+ def predict_prosody(self, frames, frame_mask):
301
+ hidden = self.prosody_stack(frames, frame_mask)
302
+ return hidden, self.prosody_head(hidden) * frame_mask[..., None]
303
+
304
+ @staticmethod
305
+ def hard_prosody(prediction):
306
+ """What the decoder is conditioned on when it is not teacher-forced."""
307
+ return torch.stack((prediction[..., 0].clamp(-2.0, 1.5), (prediction[..., 1] > 0).to(prediction.dtype),
308
+ prediction[..., 2].clamp(-4.5, 3.0)), dim=-1)
309
+
310
+ def decode(self, prosody_hidden, condition, frame_mask):
311
+ return self.acoustic_stack((prosody_hidden + self.prosody_projection(condition)) * frame_mask[..., None], frame_mask)
312
+
313
+ def frequency(self, log_f0):
314
+ c = self.config
315
+ return (c.pitch_reference_hz * torch.exp(log_f0.float())).clamp(c.f0_min, c.f0_max)
316
+
317
+ def predict_durations(self, hidden, mask, tokens, speed=1.0):
318
+ output = self.duration(hidden, mask).float()
319
+ frames = torch.round(torch.expm1(output[..., 0].clamp(0, math.log1p(400))) / speed).long().clamp_min(1)
320
+ # Every phoneme is audible for at least one frame. A pause-capable token
321
+ # (edge, punctuation, word boundary) lasts its predicted length when the
322
+ # presence logit says there is a pause, and vanishes otherwise.
323
+ present = self.phone_tokens[tokens] | (output[..., 1] > 0)
324
+ return torch.where(present, frames, torch.zeros_like(frames)) * mask
325
+
326
+ @staticmethod
327
+ def widen_pitch(prosody, frame_mask, pitch_range):
328
+ """Scale the predicted pitch movement around each utterance's voiced mean.
329
+ Regression predicts a flatter contour than the recordings; values above 1
330
+ restore range (1.0 leaves the prediction untouched)."""
331
+ if pitch_range == 1.0:
332
+ return prosody
333
+ voiced = ((prosody[..., 1] > 0) & frame_mask).to(prosody.dtype)
334
+ mean = (prosody[..., 0] * voiced).sum(1, keepdim=True) / voiced.sum(1, keepdim=True).clamp_min(1)
335
+ pitch = mean + (prosody[..., 0] - mean) * pitch_range
336
+ return torch.cat((pitch[..., None], prosody[..., 1:]), dim=-1) * frame_mask[..., None]
337
+
338
+ @staticmethod
339
+ def pitch_wobble(shape, semitones, seed, device):
340
+ """Small random pitch movement for the oscillator only (log-F0 units).
341
+ Recorded pitch has cycle-to-cycle irregularity that a predicted contour
342
+ lacks; two thirds of the wobble is slow drift, one third frame-level."""
343
+ generator = torch.Generator().manual_seed(seed + 7919)
344
+ fast = torch.randn(shape, generator=generator)
345
+ slow = F.avg_pool1d(torch.randn(shape[0], 1, shape[1] + 16, generator=generator), 17, stride=1)[:, 0]
346
+ slow = slow / slow.std().clamp_min(1e-6)
347
+ return ((2 * slow + fast) / 5 ** 0.5 * semitones * math.log(2) / 12).to(device)
348
+
349
+ @torch.inference_mode()
350
+ def synthesize(self, tokens, stress, lengths, speakers, speed=1.0, pitch_shift=0.0, seed=0, pitch_range=1.0, pitch_jitter=0.0,
351
+ voiced_vowels=True):
352
+ """Free-running synthesis: predicted durations, pitch, voicing and energy."""
353
+ if not math.isfinite(speed) or not 0.25 <= speed <= 4 or not math.isfinite(pitch_shift) or not 0 <= pitch_range <= 3:
354
+ raise ValueError("speed must be between 0.25 and 4, pitch_shift finite and pitch_range between 0 and 3")
355
+ hidden, mask = self.encode(tokens, stress, lengths, speakers)
356
+ durations = self.predict_durations(hidden, mask, tokens, speed)
357
+ frames, frame_mask, frame_lengths = self.expand(hidden, durations, mask, speakers)
358
+ prosody_hidden, prosody = self.predict_prosody(frames, frame_mask)
359
+ if voiced_vowels:
360
+ # The pitch tracker missed creaky vowels in the recordings, and the
361
+ # voicing predictor learned to drop whole vowels (heard as a whispered
362
+ # word). A vowel is voiced by definition, so its frames are kept voiced.
363
+ ends = durations.cumsum(1)
364
+ frame = torch.arange(frames.shape[1], device=tokens.device)[None].expand(len(lengths), -1).contiguous()
365
+ owner = torch.searchsorted(ends, frame, right=True).clamp(max=tokens.shape[1] - 1)
366
+ vowel = self.vowel_tokens[tokens].gather(1, owner) & frame_mask
367
+ prosody = torch.cat((prosody[..., :1], torch.where(vowel, prosody[..., 1].clamp_min(2.0), prosody[..., 1])[..., None],
368
+ prosody[..., 2:]), dim=-1)
369
+ prosody = self.widen_pitch(prosody, frame_mask, pitch_range)
370
+ acoustic = self.decode(prosody_hidden, self.hard_prosody(prosody), frame_mask)
371
+ # One noise stream per row, drawn at the row's own length, so batching or
372
+ # padding never changes a row's audio.
373
+ noise = nn.utils.rnn.pad_sequence([torch.randn(int(n) * self.config.hop, generator=torch.Generator().manual_seed(seed + row))
374
+ for row, n in enumerate(frame_lengths)], batch_first=True)
375
+ pitch = prosody[..., 0] + pitch_shift
376
+ if pitch_jitter > 0:
377
+ pitch = pitch + self.pitch_wobble(pitch.shape, pitch_jitter, seed, pitch.device)
378
+ wave = self.vocoder(acoustic, self.frequency(pitch), frame_lengths, noise=noise.to(hidden.device))
379
+ return wave, frame_lengths * self.config.hop, {"durations": durations, "prosody": prosody, "frame_mask": frame_mask}
tiny_voca/text.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Japanese front end: text -> phoneme tokens with a pitch-accent feature.
2
+
3
+ The same code runs during annotation, training-set preparation and inference,
4
+ so tokens can never drift between them.
5
+
6
+ * pyopenjtalk (OpenJTalk with its NAIST-JDIC dictionary) reads the text: kanji
7
+ readings, numbers, and the accent phrases with their accent types.
8
+ * A token is one OpenJTalk phoneme (``k``, ``sh``, ``a``, ``N``, ``cl``, ...).
9
+ A long vowel is two tokens (``o o``), one per mora. Vowels that OpenJTalk
10
+ devoices (``desU``, ``shIta``) are their own tokens, ``A I U E O``: they are
11
+ not voiced, and the voicing rules for vowels must not touch them.
12
+ * The per-token feature that the model calls ``stress`` carries the Tokyo
13
+ pitch-accent tone of the token's mora: 1 low, 2 high, 0 for everything that
14
+ is not a phone. It is derived from the accent type and the mora position in
15
+ the accent phrase (full-context fields F1/F2 and A2).
16
+ * Accent-phrase boundaries are ``<sp>`` tokens, punctuation marks are tokens,
17
+ and so are the utterance edges. They may last zero frames and carry the
18
+ pauses when the recording has them.
19
+ """
20
+
21
+ from dataclasses import dataclass
22
+ import hashlib
23
+ import json
24
+ import re
25
+ import unicodedata
26
+
27
+ FRONTEND_VERSION = 1
28
+
29
+ PAD, BOS, EOS, SP, UNK = "<pad>", "<bos>", "<eos>", "<sp>", "<unk>"
30
+ SPECIALS = (PAD, BOS, EOS, SP, UNK)
31
+ PUNCTUATION = (",", ".", "?", "!", ";", ":", '"', "(", ")", "—", "…")
32
+ CONSONANTS = ("k", "ky", "kw", "g", "gy", "gw", "s", "sh", "z", "j", "t", "ty", "ch", "ts", "d", "dy", "n", "ny",
33
+ "h", "hy", "f", "b", "by", "p", "py", "m", "my", "y", "r", "ry", "w", "v", "N", "cl")
34
+ VOWELS = ("a", "i", "u", "e", "o")
35
+ DEVOICED = ("A", "I", "U", "E", "O")
36
+ PHONES = CONSONANTS + VOWELS + DEVOICED
37
+ # Append-only: changing the order or removing a symbol invalidates checkpoints.
38
+ SYMBOLS = SPECIALS + PUNCTUATION + PHONES
39
+ SYMBOL_TO_ID = {symbol: index for index, symbol in enumerate(SYMBOLS)}
40
+ PHONE_SET = frozenset(PHONES)
41
+ PHONE_IDS = frozenset(SYMBOL_TO_ID[p] for p in PHONES) | {SYMBOL_TO_ID[UNK]}
42
+ VOICELESS = frozenset(("k", "ky", "kw", "s", "sh", "t", "ty", "ch", "ts", "h", "hy", "f", "p", "py", "cl") + DEVOICED)
43
+ VOWEL_SET = frozenset(VOWELS)
44
+ LOW, HIGH = 1, 2
45
+
46
+ # Full-width and typographic marks to the inventory. NFKC already turns
47
+ # full-width ASCII (?!,.:;()) into ASCII.
48
+ _MARKS = str.maketrans({"、": ",", ",": ",", "。": ".", "。": ".", "、": ",", "‥": "…", "―": "—", "–": "—",
49
+ "「": '"', "」": '"', "『": '"', "』": '"', "“": '"', "”": '"', "„": '"', "«": '"', "»": '"',
50
+ "【": "(", "】": ")", "〔": "(", "〕": ")", "[": "(", "]": ")", "[": "(", "]": ")"})
51
+ _PUNCTUATION_CHARS = frozenset(PUNCTUATION)
52
+ # Separate words but say nothing: a boundary between accent phrases.
53
+ _SEPARATORS = frozenset("・ ")
54
+ # The phone, its mora position in the accent phrase (A2), the phrase's mora
55
+ # count and accent type (F1, F2) and its position in the breath group (F5).
56
+ _LABEL = re.compile(r"-(?P<phone>[^+]+)\+.*?/A:(?:-?\d+|xx)\+(?P<a2>\d+|xx)\+.*?/F:(?P<f1>\d+|xx)_(?P<f2>\d+|xx)"
57
+ r"#(?:\d+|xx)_(?:\d+|xx)@(?P<f5>\d+|xx)_")
58
+
59
+
60
+ class NothingToPronounce(ValueError):
61
+ """The text has nothing to say: only marks, emoji and the like."""
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Phonemized:
66
+ symbols: tuple
67
+ ids: tuple
68
+ stress: tuple # pitch-accent tone per token: 0 none, 1 low, 2 high
69
+ unknown: tuple # OpenJTalk phonemes that are not in the inventory
70
+
71
+ def __len__(self):
72
+ return len(self.ids)
73
+
74
+
75
+ def _pyopenjtalk():
76
+ try:
77
+ import pyopenjtalk
78
+ except ImportError as error:
79
+ raise RuntimeError("the Japanese front end needs pyopenjtalk: pip install pyopenjtalk") from error
80
+ return pyopenjtalk
81
+
82
+
83
+ def frontend_identity():
84
+ return {"frontend_version": FRONTEND_VERSION, "phonemizer": "pyopenjtalk", "symbols": list(SYMBOLS),
85
+ "tone": "Tokyo H/L from accent type and mora position"}
86
+
87
+
88
+ def frontend_runtime():
89
+ """What an annotation run records about the program behind its tokens."""
90
+ return {"pyopenjtalk": _pyopenjtalk().__version__}
91
+
92
+
93
+ def frontend_fingerprint():
94
+ return hashlib.sha256(json.dumps(frontend_identity(), sort_keys=True, ensure_ascii=False).encode()).hexdigest()
95
+
96
+
97
+ def normalize_text(text):
98
+ text = unicodedata.normalize("NFKC", text).translate(_MARKS)
99
+ text = re.sub(r"\.{3,}", "…", text)
100
+ text = re.sub(r"-{2,}|\s-\s", "—", text)
101
+ return re.sub(r"\s+", " ", text).strip()
102
+
103
+
104
+ def chunks(text):
105
+ """Yield ``(is_punctuation, piece)`` for normalized text. Decimal points and
106
+ digit-group commas stay inside the text piece for OpenJTalk; a separator
107
+ (space, ・) ends a piece without a token of its own."""
108
+ start = 0
109
+ for i, char in enumerate(text):
110
+ if char in _SEPARATORS:
111
+ if text[start:i].strip():
112
+ yield False, text[start:i].strip()
113
+ start = i + 1
114
+ continue
115
+ if char not in _PUNCTUATION_CHARS:
116
+ continue
117
+ previous = text[i - 1] if i else ""
118
+ following = text[i + 1] if i + 1 < len(text) else ""
119
+ if char in ".,:" and previous.isdigit() and following.isdigit():
120
+ continue
121
+ if text[start:i].strip():
122
+ yield False, text[start:i].strip()
123
+ yield True, char
124
+ start = i + 1
125
+ if text[start:].strip():
126
+ yield False, text[start:].strip()
127
+
128
+
129
+ def tone(mora_position, accent_type):
130
+ """Tokyo pitch accent of a mora: high or low.
131
+
132
+ Type 0 (heiban) rises after the first mora and stays high; type 1 starts
133
+ high and falls; type n > 1 rises after the first mora and falls after the
134
+ n-th."""
135
+ if accent_type == 1:
136
+ return HIGH if mora_position == 1 else LOW
137
+ if mora_position == 1:
138
+ return LOW
139
+ return HIGH if accent_type == 0 or mora_position <= accent_type else LOW
140
+
141
+
142
+ def accent_phrases(labels):
143
+ """OpenJTalk full-context labels -> accent phrases as lists of ``(phone, tone)``.
144
+ A pause inside a piece also ends the phrase."""
145
+ phrases, current, phrase = [], [], None
146
+ for label in labels:
147
+ match = _LABEL.search(label)
148
+ if match is None:
149
+ raise ValueError(f"unexpected OpenJTalk label: {label}")
150
+ if match["phone"] in ("sil", "pau") or match["a2"] == "xx":
151
+ if current:
152
+ phrases.append(current)
153
+ current, phrase = [], None
154
+ continue
155
+ if current and match["f5"] != phrase:
156
+ phrases.append(current)
157
+ current = []
158
+ current.append((match["phone"], tone(int(match["a2"]), int(match["f2"]))))
159
+ phrase = match["f5"]
160
+ if current:
161
+ phrases.append(current)
162
+ return phrases
163
+
164
+
165
+ def tokenize(pieces):
166
+ """Build the token sequence from ``(is_punctuation, value)`` pieces where a
167
+ text piece's value is a list of accent phrases, each a list of
168
+ ``(phone, tone)``. Pure function (testable without OpenJTalk)."""
169
+ symbols, stress, unknown = [BOS], [0], []
170
+ for punctuation, value in pieces:
171
+ if punctuation:
172
+ if symbols[-1] != value: # collapse repeats such as "!!"
173
+ symbols.append(value)
174
+ stress.append(0)
175
+ continue
176
+ for phrase in value:
177
+ if symbols[-1] in PHONE_SET or symbols[-1] == UNK:
178
+ symbols.append(SP)
179
+ stress.append(0)
180
+ for phone, level in phrase:
181
+ if phone not in PHONE_SET:
182
+ unknown.append(phone)
183
+ phone = UNK
184
+ symbols.append(phone)
185
+ stress.append(level)
186
+ symbols.append(EOS)
187
+ stress.append(0)
188
+ if not any(s in PHONE_SET or s == UNK for s in symbols):
189
+ raise NothingToPronounce("the text has nothing to pronounce")
190
+ return Phonemized(tuple(symbols), tuple(SYMBOL_TO_ID[s] for s in symbols), tuple(stress), tuple(unknown))
191
+
192
+
193
+ def phonemize(text):
194
+ if not isinstance(text, str) or not text.strip():
195
+ raise ValueError("text must not be empty")
196
+ openjtalk = _pyopenjtalk()
197
+ pieces = []
198
+ for punctuation, piece in chunks(normalize_text(text)):
199
+ pieces.append((True, piece) if punctuation else (False, accent_phrases(openjtalk.extract_fullcontext(piece))))
200
+ return tokenize(pieces)
201
+
202
+
203
+ def is_phone(token_ids):
204
+ """Boolean list/tensor helper: tokens that must be realised as audio."""
205
+ return [int(i) in PHONE_IDS for i in token_ids]
206
+
207
+
208
+ def morae(symbols):
209
+ """The morae of a token sequence as strings of their phones (``"ky o"``,
210
+ ``"N"``, ``"cl"``). A mora ends with a vowel, a devoiced vowel, ``N`` or
211
+ ``cl``; any other token in between is skipped."""
212
+ result, onset = [], []
213
+ for symbol in symbols:
214
+ if symbol in VOWEL_SET or symbol in DEVOICED or symbol in ("N", "cl"):
215
+ result.append(" ".join(onset + [symbol]))
216
+ onset = []
217
+ elif symbol in PHONE_SET:
218
+ onset.append(symbol)
219
+ return result