ctrltokyo commited on
Commit
0da08c4
·
verified ·
1 Parent(s): af8303a

eeh-1-1: looped stacks, local attention, int8 weights

Browse files
.gitattributes CHANGED
@@ -33,3 +33,22 @@ 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
+ bin/linux-aarch64/eeh filter=lfs diff=lfs merge=lfs -text
37
+ bin/linux-x86_64/eeh filter=lfs diff=lfs merge=lfs -text
38
+ bin/macos-arm64/eeh filter=lfs diff=lfs merge=lfs -text
39
+ lib/linux-aarch64/libeeh_ffi.so filter=lfs diff=lfs merge=lfs -text
40
+ lib/linux-x86_64/libeeh_ffi.so filter=lfs diff=lfs merge=lfs -text
41
+ lib/macos-arm64/libeeh_ffi.dylib filter=lfs diff=lfs merge=lfs -text
42
+ python/eeh-0.2.0-py3-none-macosx_11_0_arm64.whl filter=lfs diff=lfs merge=lfs -text
43
+ python/eeh-0.2.0-py3-none-manylinux_2_28_aarch64.whl filter=lfs diff=lfs merge=lfs -text
44
+ python/eeh-0.2.0-py3-none-manylinux_2_28_x86_64.whl filter=lfs diff=lfs merge=lfs -text
45
+ samples/F1-hello.wav filter=lfs diff=lfs merge=lfs -text
46
+ samples/F1-numbers.wav filter=lfs diff=lfs merge=lfs -text
47
+ samples/F1-polite.wav filter=lfs diff=lfs merge=lfs -text
48
+ samples/F1-question.wav filter=lfs diff=lfs merge=lfs -text
49
+ samples/F1-story.wav filter=lfs diff=lfs merge=lfs -text
50
+ samples/M1-hello.wav filter=lfs diff=lfs merge=lfs -text
51
+ samples/M1-numbers.wav filter=lfs diff=lfs merge=lfs -text
52
+ samples/M1-polite.wav filter=lfs diff=lfs merge=lfs -text
53
+ samples/M1-question.wav filter=lfs diff=lfs merge=lfs -text
54
+ 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,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: ja
3
+ license: apache-2.0
4
+ pipeline_tag: text-to-speech
5
+ library_name: eeh
6
+ base_model: ctrltokyo/eeh-1
7
+ tags:
8
+ - text-to-speech
9
+ - japanese
10
+ - rust
11
+ - webassembly
12
+ - tiny
13
+ - looped-transformer
14
+ - streaming
15
+ ---
16
+
17
+ # eeh-1-1
18
+
19
+ **A tiny Japanese voice that fits in a browser tab.** eeh is a Japanese
20
+ text-to-speech model with two voices and 3.3 million parameters, waveform
21
+ generator included. It reads kanji, numbers and Tokyo pitch accent, and runs on
22
+ a CPU or fully inside a browser, with nothing sent anywhere.
23
+
24
+ There is no neural vocoder. A transformer reads OpenJTalk's phonemes with their
25
+ pitch-accent tones, predicts how long each one lasts, then predicts pitch,
26
+ loudness and the settings of a small source-filter synthesizer, which makes the
27
+ waveform from a pulse train and noise. It was trained from scratch on 18.6
28
+ hours of speech by
29
+ [Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi).
30
+
31
+ **What changed since [eeh-1](https://huggingface.co/ctrltokyo/eeh-1).**
32
+ eeh-1-1 is eeh-1 with **looped** transformer stacks (shared weights, same
33
+ depth) and **local attention** on the frame-level stacks, fine-tuned from
34
+ eeh-1 for 20,000 steps. It has 26% fewer parameters, ships as 4.0 MB of int8
35
+ weights, streams audio within a sentence (first sound in about 3 ms on a CPU),
36
+ and scores the same as or better than eeh-1 on every metric.
37
+
38
+ <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-hello.wav"></audio>
39
+
40
+ | | |
41
+ |---|---|
42
+ | Parameters | 3,343,824 (eeh-1: 4,534,219) |
43
+ | Weights | 4.0 MB int8 (`eeh.safetensors`), 13.4 MB float32 (`eeh-f32.safetensors`) |
44
+ | Voices | F1 (female, late 20s, calm and clear), M1 (male, early 30s, warm), Tokyo Japanese |
45
+ | Output | 24 kHz mono |
46
+ | Input | Japanese text (kanji, kana, numbers), read with OpenJTalk |
47
+ | Speed | 14 s sentence in 35 ms on one CPU thread (400x real time, Apple M4 Max, Accelerate); about 60x in a browser tab |
48
+ | First sound | 3 ms for a short sentence, 11 ms for a 14 s one (one CPU thread, streamed); 13–50 ms in a browser |
49
+ | Pretrained weights in the model | None (initialised from eeh-1, itself trained from scratch) |
50
+ | License | Apache-2.0 |
51
+
52
+ ## Samples
53
+
54
+ | Text | F1 | M1 |
55
+ |---|---|---|
56
+ | こんにちは!これは、ノートパソコンでも動く小さな音声合成モデルです。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-hello.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/M1-hello.wav"></audio> |
57
+ | 会議は三月十四日の午後三時半に変わったので、あと四十五分ほどあります。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-numbers.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/M1-numbers.wav"></audio> |
58
+ | 本当に、あなたの誕生日を忘れると思ったの? | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-question.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/M1-question.wav"></audio> |
59
+ | 彼女は海を見たことがなかった。しばらくの間、何も言わずに波打ち際に立っていた。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-story.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/M1-story.wav"></audio> |
60
+ | 恐れ入りますが、お名前とご連絡先をこちらにご記入いただけますか。 | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-polite.wav"></audio> | <audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/M1-polite.wav"></audio> |
61
+
62
+ ## Files
63
+
64
+ | Path | Contents |
65
+ |---|---|
66
+ | `eeh.safetensors` | Weights, int8 linear layers with a float32 scale per row (4.0 MB); the default |
67
+ | `eeh-f32.safetensors` | The same weights in float32 (13.4 MB), e.g. for fine-tuning |
68
+ | `eeh-dict.bin` | The Japanese dictionary the front end reads (36 MB) |
69
+ | `python/` | Python wheels for macOS (arm64) and Linux (aarch64, x86_64) |
70
+ | `bin/<platform>/eeh` | Command-line program |
71
+ | `lib/<platform>/`, `include/eeh.h` | C library and header, for any language with a C FFI |
72
+ | `demo/` | The browser demo: the whole engine compiled to WebAssembly, the weights and the dictionary |
73
+ | `samples/` | The audio on this page |
74
+ | `eval/report.json`, `eval/metrics.jsonl` | Evaluation report (int8 weights) and the fine-tuning log |
75
+ | `looped.png` | The diagram below |
76
+ | `LICENSE` | Apache-2.0 |
77
+
78
+ ## Usage
79
+
80
+ eeh runs on its own engine, written in Rust: a Japanese front end that reads
81
+ text exactly as OpenJTalk does (identical on more than 500,000 test texts) and
82
+ the model. The same engine is behind the Python package, the command-line
83
+ program, the C library and the browser demo. Both weight files load the same
84
+ way; int8 is dequantised at load, so speed is identical.
85
+
86
+ ```bash
87
+ hf download ctrltokyo/eeh-1-1 --local-dir eeh
88
+ cd eeh
89
+ ```
90
+
91
+ ### Python
92
+
93
+ ```bash
94
+ pip install python/eeh-0.2.0-py3-none-<your platform>.whl
95
+ ```
96
+
97
+ ```python
98
+ import eeh, soundfile
99
+
100
+ synth = eeh.Synthesizer("eeh.safetensors", "eeh-dict.bin")
101
+ audio = synth.speak("こんにちは。今日はいい天気ですね。", voice="F1") # float32 array, 24 kHz
102
+ soundfile.write("hello.wav", audio, synth.sample_rate)
103
+
104
+ # Streaming within a sentence: chunks arrive as soon as their samples are final.
105
+ synth.speak_stream("長い文章も、最初の音はすぐに届きます。", lambda text, chunk, index: play(chunk), voice="M1")
106
+ ```
107
+
108
+ `speak` takes `voice` (`F1` or `M1`), `speed` (1.0), `pitch_shift` (0; 0.058
109
+ is about one semitone), `pitch_range` (1.0) and `seed`. `speak_stream(text,
110
+ callback)` hands over chunks of audio (`first_frames=12`, then
111
+ `chunk_frames=48`, 10.7 ms per frame); joined, they equal `speak`'s audio.
112
+ `speak_each(text, callback)` hands over whole sentences. The package has no
113
+ dependencies; it returns a NumPy array when NumPy is installed. The
114
+ synthesizer can be shared between threads.
115
+
116
+ ### Command line
117
+
118
+ ```bash
119
+ chmod +x bin/macos-arm64/eeh # the Hub does not keep the executable bit
120
+ bin/macos-arm64/eeh speak --weights eeh.safetensors --dictionary eeh-dict.bin \
121
+ --voice M1 --text "こんにちは。今日はいい天気ですね。" --out hello.wav [--stream]
122
+ ```
123
+
124
+ ### C and other languages
125
+
126
+ `lib/<platform>/libeeh_ffi` with `include/eeh.h`: `eeh_synthesizer_new` takes
127
+ the weights and dictionary as bytes, `eeh_speak` returns the audio,
128
+ `eeh_speak_each` streams it sentence by sentence and `eeh_speak_stream` chunk
129
+ by chunk. Errors come back as status codes, never as crashes. Go, Node, Java,
130
+ Ruby and Swift can call it through their C FFI (all five are tested).
131
+
132
+ Text of any length works. It is split into sentences at 。!? and read one
133
+ sentence at a time; a quote followed by と or って stays with its sentence, and
134
+ a sentence too long for one call is cut after 、. A text without a final mark
135
+ gets 。. The audio never peaks above 0.99.
136
+
137
+ ### In a browser
138
+
139
+ ```bash
140
+ python -m http.server --directory demo 8000
141
+ ```
142
+
143
+ Then open `http://localhost:8000`. The engine runs in a Web Worker and plays
144
+ audio chunk by chunk as it is made. The first visit downloads about 13 MB
145
+ (gzip): 3.7 MB of weights, 9 MB of dictionary and 0.4 MB of program, all kept
146
+ by the browser afterwards.
147
+
148
+ ## How it works
149
+
150
+ **Front end.** eeh's own Rust front end reads the text the way OpenJTalk does
151
+ with the NAIST Japanese Dictionary: it splits it into words, picks each kanji's
152
+ reading, expands numbers, joins words into accent phrases and assigns their
153
+ accent types. It turns the result into tokens:
154
+
155
+ - one token per phoneme (`k`, `sh`, `a`, `N` for ん, `cl` for っ);
156
+ a long vowel is two tokens, one per mora;
157
+ - devoiced vowels (the u of です, the i of した) are their own tokens `A I U E O`;
158
+ - `<sp>` marks a boundary between accent phrases, and punctuation is kept;
159
+ - each token carries the Tokyo pitch-accent tone of its mora, low or high,
160
+ computed from the phrase's accent type and the mora's position.
161
+
162
+ The 8,650 training sentences (11.8 hours of speech) are read in 0.29 s on one
163
+ CPU thread (0.03 ms per sentence, about 150,000x real time), 5.5x faster than
164
+ pyopenjtalk. The dictionary loads in 3 ms.
165
+
166
+ **Model.** All blocks are pre-norm transformer blocks with 192 channels, 4
167
+ heads and rotary position embeddings. Their feed-forward is a depthwise
168
+ convolution (kernel 7) followed by a GELU MLP (192 → 640 → 192).
169
+
170
+ | Stage | Blocks stored / applied | Attention | Output |
171
+ |---|---|---|---|
172
+ | Text encoder | 3 / 4 (looped, 2 core passes) | global | token states |
173
+ | Duration and pause predictor | conv | – | frames per token |
174
+ | Frame transformer A | 2 / 2 | local, ±32 frames (±341 ms) | log F0, voicing, energy |
175
+ | Frame transformer B | 3 / 5 (looped, 3 core passes) | local, ±16 frames (±171 ms) | synthesizer settings per frame |
176
+ | Source-filter head | – | – | band-limited pulse train at F0 plus noise, each shaped by a per-frame filter (256 samples, 10.7 ms) |
177
+
178
+ | Component | Parameters | eeh-1 |
179
+ |---|---:|---:|
180
+ | Embeddings (token, tone, voice) | 13,632 | 13,632 |
181
+ | Text encoder | 1,192,130 | 1,588,864 |
182
+ | Duration and pause predictor | 123,906 | 123,906 |
183
+ | Frame transformer A, pitch/voicing/energy head | 795,971 | 795,971 |
184
+ | Frame transformer B | 1,192,323 | 1,985,984 |
185
+ | Source-filter waveform head | 25,862 | 25,862 |
186
+ | Total | 3,343,824 | 4,534,219 |
187
+
188
+ ## Looped stacks
189
+
190
+ ![Looped stack: the prelude runs once, the core block runs three times with shared weights, the coda runs once](https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/looped.png)
191
+
192
+ A looped stack stores *prelude → core → coda* and applies the core `L` times
193
+ with tied weights. Depth (block applications) is unchanged from eeh-1;
194
+ parameters are not.
195
+
196
+ ```
197
+ h0 = prelude(x)
198
+ h = h0
199
+ for k in 1..L:
200
+ h = (h + e_k + tanh(g_k) · h0) ⊙ mask # per-pass embedding, gated input injection
201
+ h = core(h)
202
+ y = norm(coda(h))
203
+ ```
204
+
205
+ - **`e_k`** (`[L, 192]`): learned pass embedding, so the shared core can tell
206
+ passes apart (a depth embedding, as in Universal Transformers).
207
+ - **`tanh(g_k) · h0`**: learned scalar gate re-injecting the prelude output
208
+ before every pass, which keeps later passes anchored to the input and keeps
209
+ gradients short.
210
+ - **Zero init**: `e_k = 0`, `g_k = 0`, so an untrained loop is exactly a
211
+ repeated block. That makes branching from a non-looped checkpoint stable.
212
+ - **Cost**: `L·192 + L` extra parameters per stack (386 for the encoder, 579 for B). In the Rust engine the core's
213
+ packed weights are reused across passes while a tile of frames is in cache.
214
+
215
+ | Stack | eeh-1 | eeh-1-1 | Mapping from eeh-1 |
216
+ |---|---|---|---|
217
+ | Text encoder | 4 blocks | prelude + core ×2 + coda | blocks 0, 1, 3 (2 dropped) |
218
+ | Frame transformer B | 5 blocks | prelude + core ×3 + coda | blocks 0, 2, 4 (1, 3 dropped) |
219
+
220
+ **Local attention and streaming.** Frame transformers A and B attend within a
221
+ band (`|i − j| ≤ W`), computed as a band in `O(T·W)` time and memory instead of
222
+ `O(T²)`. The receptive field of transformer B is 5 × (16 + 3) = 95 frames
223
+ (about 1.0 s) each side, so the engine streams. It computes the encoder,
224
+ durations and prosody for the whole sentence, then runs transformer B and the
225
+ source-filter head as a wavefront over frames, emitting a chunk once its
226
+ samples can no longer change. The first chunk is final after 95 + 12 frames
227
+ are fed. Nothing is computed twice, and the joined chunks equal one-shot
228
+ synthesis to within 1e-5.
229
+
230
+ **Ablation.** All variants were branched from eeh-1 and fine-tuned for 20,000
231
+ steps under identical settings. Scores are on 300 validation clips and 16
232
+ novel sentences.
233
+
234
+ | Variant | Params | Reading error | Accent | UTMOS | UTMOS, novel |
235
+ |---|---:|---:|---:|---:|---:|
236
+ | eeh-1 (no fine-tune) | 4.53M | 1.03% | 0.706 | 2.94 | 2.88 |
237
+ | Pruned to 3.7M (blocks deleted) | 3.74M | 1.09% | 0.704 | 2.91 | 2.91 |
238
+ | Looped B, global attention | 3.74M | 1.08% | 0.702 | 2.90 | 2.90 |
239
+ | Looped B, local ±64/±32 | 3.74M | 1.10% | 0.705 | 3.00 | 3.04 |
240
+ | Looped B, local ±32/±16 | 3.74M | 1.07% | 0.700 | 2.99 | 3.04 |
241
+ | Looped encoder + B, ±64/±32 | 3.34M | 1.10% | 0.702 | 2.98 | 2.99 |
242
+ | **Looped encoder + B, ±32/±16 (eeh-1-1)** | **3.34M** | 1.12% | 0.703 | 2.99 | 2.98 |
243
+
244
+ At equal size, looping matches deleting blocks. Local attention adds about
245
+ 0.09 UTMOS on validation and 0.14 on novel sentences. Looping the encoder removes 0.4M more parameters with no
246
+ measurable loss. Training for 40,000 steps instead of 20,000 did not help
247
+ (validation loss flat from step 116,000).
248
+
249
+ **int8 weights.** Each 2-D linear weight (33 matrices, about 90% of the
250
+ parameters) is quantised symmetrically per output row (`q = round(w / s)`,
251
+ `s = max|w_row| / 127`) and stored as I8 plus an F32 scale; everything else
252
+ stays float32. The engine dequantises at load (about 1 ms). Durations match
253
+ float32 exactly. The mean log-mel difference from float32 is 0.17–0.20, and
254
+ every evaluation score is within ±0.004 on accent and ±0.03 on UTMOS (see
255
+ below).
256
+
257
+ ## Training data
258
+
259
+ The speech is synthetic. Two voices were designed once from Japanese
260
+ descriptions with Irodori-TTS v4.1 Small (`落ち着いた20代後半の女性。明瞭で自然な東京の話し言葉。`
261
+ and `30代前半の男性。温かく親しみやすい、自然な東京の話し言葉。`), then every
262
+ sentence was read by [Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi)
263
+ (MIT) cloning those two references. No recording of a real speaker is involved.
264
+
265
+ On the 300 test sentences in both voices, the teacher's speech has 1.2% kana
266
+ reading error, 0.69 pitch-accent agreement and a UTMOS of 3.38.
267
+
268
+ The 8,650 sentences (8,000 train, 350 validation, 300 test, split by sentence)
269
+ were chosen to cover as many morae and mora pairs as possible; 25% are
270
+ questions and 10% exclamations.
271
+
272
+ Every clip was screened before training:
273
+
274
+ - **Reading.** [kana-whisper](https://huggingface.co/sbintuitions/kana-whisper)
275
+ transcribed it to katakana, compared with OpenJTalk's reading; more than 10%
276
+ kana error was rejected.
277
+ - **Alignment.** Phoneme durations come from forced alignment with
278
+ `facebook/wav2vec2-lv-60-espeak-cv-ft`, used only to label the data. Its
279
+ labels were recalibrated on the teacher's audio, and clips it aligned with
280
+ low confidence were rejected.
281
+ - **Speaking rate and length.**
282
+
283
+ | | Clips | Hours |
284
+ |---|---:|---:|
285
+ | Generated (sentences x voices) | 17,300 | |
286
+ | Passed screening | 15,684 | |
287
+ | Used for training (F1 7,301, M1 6,783) | 14,084 | 18.6 |
288
+ | Validation / test | 614 / 527 | 1.3 / 1.0 |
289
+
290
+ ## Training
291
+
292
+ | | eeh-1 (from scratch) | eeh-1-1 (fine-tune) |
293
+ |---|---|---|
294
+ | Steps | 0 → 104,000 | 104,000 → 124,000 |
295
+ | Initialisation | random | eeh-1 blocks mapped as above; zero-init loop parameters; fresh optimizer |
296
+ | Batches | about 9,000 frames (96 s of audio) per step | same |
297
+ | Losses | Multi-resolution spectral losses; adversarial loss with multi-period and multi-resolution discriminators after step 8,000 | same, adversarial throughout |
298
+ | Hardware | One NVIDIA GB10 (Lenovo ThinkStation PGX) | One NVIDIA H100 |
299
+ | Time | 11.5 hours | 46 minutes (7.2 steps/s) |
300
+
301
+ The adversarial step computes the discriminators' gradient at the waveform once
302
+ instead of twice, and runs their convolutions in bfloat16 with autotuned
303
+ kernels on batches padded to a few fixed shapes. That is twice as fast, with
304
+ the same gradients.
305
+
306
+ ## Evaluation
307
+
308
+ Speech from the released weights was scored the same way as the teacher's
309
+ recordings of the same sentences. kana-whisper transcribes it to katakana
310
+ (reading error against OpenJTalk's reading), a pitch tracker checks each
311
+ expected rise and fall of the pitch accent, and UTMOS rates naturalness. The
312
+ spectral distance is the mean log-mel distance from the teacher's recording
313
+ after DTW.
314
+
315
+ | Sentences | Clips | Model | Reading error | Pitch-accent agreement | UTMOS | Spectral distance |
316
+ |---|---:|---|---:|---:|---:|---:|
317
+ | Test | 300 | eeh-1-1 int8 | **0.82%** | 0.705 | **2.97** | **0.662** |
318
+ | | | eeh-1-1 float32 | 0.84% | **0.710** | **2.97** | **0.662** |
319
+ | | | eeh-1 | 0.84% | 0.696 | 2.94 | 0.671 |
320
+ | | | teacher | 1.23% | 0.692 | 3.38 | |
321
+ | Validation | 300 | eeh-1-1 int8 | 1.11% | 0.703 | 2.98 | 0.701 |
322
+ | | | eeh-1-1 float32 | 1.12% | 0.703 | 2.99 | 0.701 |
323
+ | | | eeh-1 | 1.03% | 0.706 | 2.94 | 0.708 |
324
+ | | | teacher | 1.70% | 0.677 | 3.34 | |
325
+ | New sentences, not in the dataset | 16 | eeh-1-1 int8 | 0.0% | 0.702 | 3.01 | |
326
+ | | | eeh-1 | 0.0% | 0.689 | 2.88 | |
327
+
328
+ eeh-1-1 reads and accents as well as the teacher it learned from. It sounds
329
+ less natural than the teacher (UTMOS about 0.4 lower), which is the cost of
330
+ the small synthesizer. Differences from eeh-1 are within noise on reading and
331
+ accent and slightly favour eeh-1-1 on UTMOS and spectral distance. No formal
332
+ listening test has been run; informal side-by-side listening found eeh-1,
333
+ eeh-1-1 and the other variants indistinguishable.
334
+
335
+ **Speed** (Apple M4 Max, one thread, Rust engine):
336
+
337
+ | | eeh-1 | eeh-1-1 |
338
+ |---|---:|---:|
339
+ | 14 s sentence, portable build | 195 ms | 99 ms |
340
+ | 14 s sentence, Accelerate | 55 ms | 35 ms |
341
+ | First sound, 14 s sentence (Accelerate, streamed) | 55 ms | 11 ms |
342
+ | First sound, 3 s sentence (Accelerate, streamed) | 7.4 ms | 3.0 ms |
343
+ | Browser tab (Chromium), real time | about 50x | about 60x |
344
+
345
+ The gain grows with sentence length: attention cost is linear in the band
346
+ width instead of quadratic. On short sentences throughput is the same as
347
+ eeh-1, and the gain is in first sound.
348
+
349
+ ## Limitations
350
+
351
+ - Japanese only, two fixed voices, no voice cloning.
352
+ - Readings come from OpenJTalk's dictionary. Rare kanji readings, names and
353
+ new words can be read wrong, and the accent of compound phrases is predicted
354
+ by rules. Whatever OpenJTalk gets wrong, eeh says wrong.
355
+ - Latin letters are spelled out one by one (`eeh` is read イー・イー・エイチ).
356
+ - The same text is always read the same way.
357
+ - Prosody (frame transformer A) is computed for the whole sentence before the
358
+ first chunk, so first sound grows slowly with sentence length (11 ms for a
359
+ 14 s sentence on one thread).
360
+ - The training data is synthetic, so eeh cannot sound more natural than the
361
+ teacher; the small source-filter synthesizer sounds more buzzy than it.
362
+
363
+ ## License
364
+
365
+ Apache-2.0 for the weights and code.
366
+
367
+ ## Citation
368
+
369
+ ```bibtex
370
+ @software{nicholson2026eeh,
371
+ author = {Nicholson, Alexander},
372
+ title = {eeh: a 3.3M-parameter two-voice Japanese text-to-speech model},
373
+ year = {2026},
374
+ url = {https://huggingface.co/ctrltokyo/eeh-1-1}
375
+ }
376
+ ```
377
+
378
+ ## Acknowledgements
379
+
380
+ 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/).
bin/linux-aarch64/eeh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:369b7c2ae276dbac19a399e6d053cf0722800de801375ee9000095dbcb1f9fc5
3
+ size 1866288
bin/linux-x86_64/eeh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82543b1343023377235111dbdc78d6327f851c020fb31908bc05b9734a19ef96
3
+ size 2666136
bin/macos-arm64/eeh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac7b2f6a51669012b28e4f10c62bc56049205b0ab64a17fad76a45288dd6bc60
3
+ size 1972864
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 3.3M-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>3.3M-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>3,343,824</b><span>parameters, waveform generator included</span></div>
113
+ <div><b>3.7 MB</b><span>model file (int8 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 13 MB (gzip): the model (3.7 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:bd043d25a2cc4ef2ac0ece7668a83a9d3f21fc34c90804f818fe1963d930f0f2
3
+ size 3657567
demo/pkg/eeh_wasm.js ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ * Streaming within a sentence: `callback(sentenceText, Float32Array, sentenceIndex)` is called with each chunk as
81
+ * soon as its samples are final (the first one after about `firstFrames` frames) and stops the rest by returning
82
+ * `false`. A model with global acoustic attention sends one chunk per sentence. The peak limit follows the loudest
83
+ * sample heard so far (see `Synthesizer::speak_stream` of the `eeh` crate).
84
+ *
85
+ * # Errors
86
+ * As `speak`, and whatever the callback throws.
87
+ * @param {string} text
88
+ * @param {string} voice
89
+ * @param {any} options
90
+ * @param {Function} callback
91
+ */
92
+ speakStream(text, voice, options, callback) {
93
+ let ptr0, len0, ptr1, len1;
94
+ try {
95
+ ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
96
+ len0 = WASM_VECTOR_LEN;
97
+ ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
98
+ len1 = WASM_VECTOR_LEN;
99
+ } catch (e) {
100
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
101
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
102
+ throw e;
103
+ }
104
+ const ret = wasm.synthesizer_speakStream(this.__wbg_ptr, ptr0, len0, ptr1, len1, options, callback);
105
+ if (ret[1]) {
106
+ throw takeFromExternrefTable0(ret[0]);
107
+ }
108
+ }
109
+ /**
110
+ * The whole text as one waveform, peak-limited as a whole.
111
+ *
112
+ * # Errors
113
+ * A message for an unknown voice, a text with nothing readable in it, or a failure of the model.
114
+ * @param {string} text
115
+ * @param {string} voice
116
+ * @param {any} options
117
+ * @returns {Float32Array}
118
+ */
119
+ speak(text, voice, options) {
120
+ let ptr0, len0, ptr1, len1;
121
+ try {
122
+ ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
123
+ len0 = WASM_VECTOR_LEN;
124
+ ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
125
+ len1 = WASM_VECTOR_LEN;
126
+ } catch (e) {
127
+ if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); }
128
+ if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); }
129
+ throw e;
130
+ }
131
+ const ret = wasm.synthesizer_speak(this.__wbg_ptr, ptr0, len0, ptr1, len1, options);
132
+ if (ret[3]) {
133
+ throw takeFromExternrefTable0(ret[2]);
134
+ }
135
+ var v3 = getArrayF32FromWasm0(ret[0], ret[1]).slice();
136
+ wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
137
+ return v3;
138
+ }
139
+ /**
140
+ * The voices of the model, e.g. `["F1", "M1"]`.
141
+ * @returns {string[]}
142
+ */
143
+ voices() {
144
+ const ret = wasm.synthesizer_voices(this.__wbg_ptr);
145
+ var v1 = getArrayJsValueFromWasm0(ret[0], ret[1]);
146
+ wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
147
+ return v1;
148
+ }
149
+ }
150
+ if (Symbol.dispose) Synthesizer.prototype[Symbol.dispose] = Synthesizer.prototype.free;
151
+ function __wbg_get_imports() {
152
+ const import0 = {
153
+ __proto__: null,
154
+ __wbg_Error_208446807d0d1e30: function(arg0, arg1) {
155
+ const ret = Error(getStringFromWasm0(arg0, arg1));
156
+ return ret;
157
+ },
158
+ __wbg___wbindgen_boolean_get_4f1baf9a00be3c74: function(arg0) {
159
+ const v = arg0;
160
+ const ret = typeof(v) === 'boolean' ? v : undefined;
161
+ return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
162
+ },
163
+ __wbg___wbindgen_is_null_c22311b1cc228e3a: function(arg0) {
164
+ const ret = arg0 === null;
165
+ return ret;
166
+ },
167
+ __wbg___wbindgen_is_object_8b968c3ab8e96595: function(arg0) {
168
+ const val = arg0;
169
+ const ret = typeof(val) === 'object' && val !== null;
170
+ return ret;
171
+ },
172
+ __wbg___wbindgen_number_get_934b640d0889af78: function(arg0, arg1) {
173
+ const obj = arg1;
174
+ const ret = typeof(obj) === 'number' ? obj : undefined;
175
+ getDataViewMemory0().setFloat64((arg0 >>> 0) + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
176
+ getDataViewMemory0().setInt32((arg0 >>> 0) + 4 * 0, !isLikeNone(ret), true);
177
+ },
178
+ __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
179
+ throw new Error(getStringFromWasm0(arg0, arg1));
180
+ },
181
+ __wbg_call_275b78b3b6520b92: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
182
+ const ret = arg0.call(arg1, arg2, arg3, arg4);
183
+ return ret;
184
+ }, arguments); },
185
+ __wbg_call_fc92fee6137d452d: function() { return handleError(function (arg0, arg1, arg2, arg3) {
186
+ const ret = arg0.call(arg1, arg2, arg3);
187
+ return ret;
188
+ }, arguments); },
189
+ __wbg_get_2080c49015e35254: function() { return handleError(function (arg0, arg1) {
190
+ const ret = Reflect.get(arg0, arg1);
191
+ return ret;
192
+ }, arguments); },
193
+ __wbg_new_from_slice_355c10c5d8f2addb: function(arg0, arg1) {
194
+ const ret = new Float32Array(getArrayF32FromWasm0(arg0, arg1));
195
+ return ret;
196
+ },
197
+ __wbindgen_generic_0000000000000001: function(arg0) {
198
+ // Cast intrinsic for `F64 -> Externref`.
199
+ const ret = arg0;
200
+ return ret;
201
+ },
202
+ __wbindgen_generic_0000000000000002: function(arg0, arg1) {
203
+ // Cast intrinsic for `Ref(String) -> Externref`.
204
+ const ret = getStringFromWasm0(arg0, arg1);
205
+ return ret;
206
+ },
207
+ __wbindgen_init_externref_table: function() {
208
+ const table = wasm.__wbindgen_externrefs;
209
+ table.set(0, undefined);
210
+ table.set(1024, undefined);
211
+ table.set(1025, null);
212
+ table.set(1026, true);
213
+ table.set(1027, false);
214
+ },
215
+ };
216
+ return {
217
+ __proto__: null,
218
+ "./eeh_wasm_bg.js": import0,
219
+ };
220
+ }
221
+
222
+ const SynthesizerFinalization = (typeof FinalizationRegistry === 'undefined')
223
+ ? { register: () => {}, unregister: () => {} }
224
+ : new FinalizationRegistry(ptr => wasm.__wbg_synthesizer_free(ptr, 1));
225
+
226
+ function addToExternrefTable0(obj) {
227
+ const idx = wasm.__externref_table_alloc();
228
+ wasm.__wbindgen_externrefs.set(idx, obj);
229
+ return idx;
230
+ }
231
+
232
+ function getArrayF32FromWasm0(ptr, len) {
233
+ ptr = ptr >>> 0;
234
+ return getFloat32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);
235
+ }
236
+
237
+ function getArrayJsValueFromWasm0(ptr, len) {
238
+ ptr = ptr >>> 0;
239
+ const mem = getDataViewMemory0();
240
+ const result = [];
241
+ for (let i = ptr; i < ptr + 4 * len; i += 4) {
242
+ result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true)));
243
+ }
244
+ wasm.__externref_drop_slice(ptr, len);
245
+ return result;
246
+ }
247
+
248
+ let cachedDataViewMemory0 = null;
249
+ function getDataViewMemory0() {
250
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
251
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
252
+ }
253
+ return cachedDataViewMemory0;
254
+ }
255
+
256
+ let cachedFloat32ArrayMemory0 = null;
257
+ function getFloat32ArrayMemory0() {
258
+ if (cachedFloat32ArrayMemory0 === null || cachedFloat32ArrayMemory0.byteLength === 0) {
259
+ cachedFloat32ArrayMemory0 = new Float32Array(wasm.memory.buffer);
260
+ }
261
+ return cachedFloat32ArrayMemory0;
262
+ }
263
+
264
+ function getStringFromWasm0(ptr, len) {
265
+ ptr = ptr >>> 0;
266
+ return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
267
+ }
268
+
269
+ let cachedUint8ArrayMemory0 = null;
270
+ function getUint8ArrayMemory0() {
271
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
272
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
273
+ }
274
+ return cachedUint8ArrayMemory0;
275
+ }
276
+
277
+ function handleError(f, args) {
278
+ try {
279
+ return f.apply(this, args);
280
+ } catch (e) {
281
+ const idx = addToExternrefTable0(e);
282
+ wasm.__wbindgen_exn_store(idx);
283
+ }
284
+ }
285
+
286
+ function isLikeNone(x) {
287
+ return x === undefined || x === null;
288
+ }
289
+
290
+ function passArray8ToWasm0(arg, malloc) {
291
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
292
+ getUint8ArrayMemory0().set(arg, ptr / 1);
293
+ WASM_VECTOR_LEN = arg.length;
294
+ return ptr;
295
+ }
296
+
297
+ function passStringToWasm0(arg, malloc, realloc) {
298
+ if (realloc === undefined) {
299
+ const buf = cachedTextEncoder.encode(arg);
300
+ const ptr = malloc(buf.length, 1) >>> 0;
301
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
302
+ WASM_VECTOR_LEN = buf.length;
303
+ return ptr;
304
+ }
305
+
306
+ let len = arg.length;
307
+ let ptr = malloc(len, 1) >>> 0;
308
+
309
+ const mem = getUint8ArrayMemory0();
310
+
311
+ let offset = 0;
312
+
313
+ for (; offset < len; offset++) {
314
+ const code = arg.charCodeAt(offset);
315
+ if (code > 0x7F) break;
316
+ mem[ptr + offset] = code;
317
+ }
318
+ if (offset !== len) {
319
+ if (offset !== 0) {
320
+ arg = arg.slice(offset);
321
+ }
322
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
323
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
324
+ const ret = cachedTextEncoder.encodeInto(arg, view);
325
+
326
+ offset += ret.written;
327
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
328
+ }
329
+
330
+ WASM_VECTOR_LEN = offset;
331
+ return ptr;
332
+ }
333
+
334
+ function takeFromExternrefTable0(idx) {
335
+ const value = wasm.__wbindgen_externrefs.get(idx);
336
+ wasm.__externref_table_dealloc(idx);
337
+ return value;
338
+ }
339
+
340
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
341
+ cachedTextDecoder.decode();
342
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
343
+ let numBytesDecoded = 0;
344
+ function decodeText(bytes) {
345
+ numBytesDecoded += bytes.length;
346
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
347
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });
348
+ cachedTextDecoder.decode();
349
+ numBytesDecoded = bytes.length;
350
+ }
351
+ return cachedTextDecoder.decode(bytes);
352
+ }
353
+
354
+ const cachedTextEncoder = new TextEncoder();
355
+
356
+ if (!('encodeInto' in cachedTextEncoder)) {
357
+ cachedTextEncoder.encodeInto = function (arg, view) {
358
+ const buf = cachedTextEncoder.encode(arg);
359
+ view.set(buf);
360
+ return {
361
+ read: arg.length,
362
+ written: buf.length
363
+ };
364
+ };
365
+ }
366
+
367
+ let WASM_VECTOR_LEN = 0;
368
+
369
+ let wasmModule, wasmInstance, wasm;
370
+ function __wbg_finalize_init(instance, module) {
371
+ wasmInstance = instance;
372
+ wasm = instance.exports;
373
+ wasmModule = module;
374
+ cachedDataViewMemory0 = null;
375
+ cachedFloat32ArrayMemory0 = null;
376
+ cachedUint8ArrayMemory0 = null;
377
+ wasm.__wbindgen_start();
378
+ return wasm;
379
+ }
380
+
381
+ async function __wbg_load(module, imports) {
382
+ if (typeof Response === 'function' && module instanceof Response) {
383
+ if (!module.ok) {
384
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
385
+ }
386
+
387
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
388
+ try {
389
+ return await WebAssembly.instantiateStreaming(module, imports);
390
+ } catch (e) {
391
+ const validResponse = expectedResponseType(module.type);
392
+
393
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
394
+ 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);
395
+
396
+ } else { throw e; }
397
+ }
398
+ }
399
+
400
+ const bytes = await module.arrayBuffer();
401
+ return await WebAssembly.instantiate(bytes, imports);
402
+ } else {
403
+ const instance = await WebAssembly.instantiate(module, imports);
404
+
405
+ if (instance instanceof WebAssembly.Instance) {
406
+ return { instance, module };
407
+ } else {
408
+ return instance;
409
+ }
410
+ }
411
+
412
+ function expectedResponseType(type) {
413
+ switch (type) {
414
+ case 'basic': case 'cors': case 'default': return true;
415
+ }
416
+ return false;
417
+ }
418
+ }
419
+
420
+ function initSync(module) {
421
+ if (wasm !== undefined) return wasm;
422
+
423
+
424
+ if (module !== undefined) {
425
+ if (Object.getPrototypeOf(module) === Object.prototype) {
426
+ ({module} = module)
427
+ } else {
428
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
429
+ }
430
+ }
431
+
432
+ const imports = __wbg_get_imports();
433
+ if (!(module instanceof WebAssembly.Module)) {
434
+ module = new WebAssembly.Module(module);
435
+ }
436
+ const instance = new WebAssembly.Instance(module, imports);
437
+ return __wbg_finalize_init(instance, module);
438
+ }
439
+
440
+ let __wbg_init_promise;
441
+ async function __wbg_init(module_or_path) {
442
+ if (wasm !== undefined) return wasm;
443
+ if (__wbg_init_promise === undefined) {
444
+ __wbg_init_promise = __wbg_init_once(module_or_path);
445
+ __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; });
446
+ }
447
+ return __wbg_init_promise;
448
+ }
449
+
450
+ async function __wbg_init_once(module_or_path) {
451
+
452
+ if (module_or_path !== undefined) {
453
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
454
+ ({module_or_path} = module_or_path)
455
+ } else {
456
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
457
+ }
458
+ }
459
+
460
+ if (module_or_path === undefined) {
461
+ module_or_path = new URL('eeh_wasm_bg.wasm', import.meta.url);
462
+ }
463
+ const imports = __wbg_get_imports();
464
+
465
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
466
+ module_or_path = fetch(module_or_path);
467
+ }
468
+
469
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
470
+
471
+ return __wbg_finalize_init(instance, module);
472
+ }
473
+
474
+ 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:d6db8c0d21d8e2343dfb8d455f14cff147df0d1b5100ff187e2747f63e35c767
3
+ size 969700
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,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (a chunk of a sentence's audio, as soon as it is final), 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 chunk that is played before the rest is made is scaled by a gain that follows the loudest
94
+ // sample heard so far (down only), since the loudest sample of the clip is not known yet.
95
+ const PEAK = 0.99;
96
+ function limitPeak(samples) {
97
+ let loudest = 0;
98
+ for (let i = 0; i < samples.length; i++) loudest = Math.max(loudest, Math.abs(samples[i]));
99
+ if (loudest > PEAK) for (let i = 0; i < samples.length; i++) samples[i] *= PEAK / loudest;
100
+ }
101
+
102
+ // Shown when no sentence of a text could be read.
103
+ const JAPANESE_ONLY = "eeh only reads Japanese for now.";
104
+
105
+ function speak({ id, text, voice, speed }) {
106
+ const started = performance.now();
107
+ const chunks = [];
108
+ let index = -1, firstAudio = 0, loudest = 0;
109
+ try {
110
+ // speakStream hands over chunks of a sentence as soon as they are final (a model with local acoustic attention
111
+ // sends the first one long before the sentence is done; one with global attention sends the sentence at once).
112
+ synth.speakStream(text, voice, { speed, peak: null }, (sentence, audio, sentenceIndex) => {
113
+ chunks.push(audio);
114
+ if (!firstAudio) firstAudio = performance.now() - started;
115
+ // The page plays this chunk at once: a copy under the running gain; the clip keeps the original.
116
+ const heard = audio.slice();
117
+ for (let i = 0; i < heard.length; i++) {
118
+ loudest = Math.max(loudest, Math.abs(heard[i]));
119
+ if (loudest > PEAK) heard[i] *= PEAK / loudest;
120
+ }
121
+ // The sentence text goes with its first chunk only (the page counts the characters spoken).
122
+ const first = sentenceIndex !== index;
123
+ index = sentenceIndex;
124
+ postMessage({ type: "sentence", id, index, text: first ? sentence : "", audio: heard, sampleRate: synth.sampleRate(),
125
+ time: performance.now() - started }, [heard.buffer]);
126
+ return true;
127
+ });
128
+ } catch (error) {
129
+ const message = String(error && error.message || error);
130
+ postMessage({ type: "error", id, message: message.startsWith("nothing in the text could be read") ? JAPANESE_ONLY : message,
131
+ plain: message.startsWith("nothing in the text could be read") });
132
+ return;
133
+ }
134
+ const audio = new Float32Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
135
+ let offset = 0;
136
+ for (const chunk of chunks) { audio.set(chunk, offset); offset += chunk.length; }
137
+ limitPeak(audio);
138
+ postMessage({ type: "done", id, audio, sampleRate: synth.sampleRate(), sentences: index + 1, firstAudio,
139
+ totalTime: performance.now() - started }, [audio.buffer]);
140
+ }
141
+
142
+ onmessage = async ({ data }) => {
143
+ try {
144
+ if (data.type === "load") await load(data);
145
+ else if (data.type === "speak") speak(data);
146
+ } catch (error) {
147
+ postMessage({ type: "error", id: data.id, message: String(error && error.message || error) });
148
+ }
149
+ };
eeh-dict.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2d480c8806b230b113a37a28756748736b975c3aed37d5b27a3e8de7e32c6af
3
+ size 35927036
eeh-f32.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b26ae787c81fd0b8cf71d29c3c0d1c43ab7f99632d658e00c174bd1b4b6e174d
3
+ size 13395864
eeh.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:212d59411ad667431bcd9ab4df4dfee88e37cb745e826a76aaa21e0a2342d6c6
3
+ size 3956896
eval/metrics.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval/report.json ADDED
The diff for this file is too large to render. See raw diff
 
include/eeh.h ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* eeh C API. Generated by cbindgen from rust/crates/eeh-ffi (generate-header.sh); do not edit. */
2
+
3
+ #ifndef EEH_H
4
+ #define EEH_H
5
+
6
+ #include <stdbool.h>
7
+ #include <stddef.h>
8
+ #include <stdint.h>
9
+
10
+ /**
11
+ * Result of a call. `EEH_STATUS_OK` is 0.
12
+ */
13
+ typedef enum {
14
+ /**
15
+ * Success.
16
+ */
17
+ EEH_STATUS_OK = 0,
18
+ /**
19
+ * A pointer was null or a string was not UTF-8.
20
+ */
21
+ EEH_STATUS_INVALID_ARGUMENT = 1,
22
+ /**
23
+ * No sentence of the text could be read (eeh only reads Japanese for now).
24
+ */
25
+ EEH_STATUS_NOTHING_TO_PRONOUNCE = 2,
26
+ /**
27
+ * The voice is not one of the model's.
28
+ */
29
+ EEH_STATUS_UNKNOWN_VOICE = 3,
30
+ /**
31
+ * The dictionary is malformed, or the text could not be analysed.
32
+ */
33
+ EEH_STATUS_FRONTEND = 4,
34
+ /**
35
+ * The weights are malformed or an option is out of range.
36
+ */
37
+ EEH_STATUS_MODEL = 5,
38
+ /**
39
+ * Anything else, e.g. a word too long to speak or non-finite audio.
40
+ */
41
+ EEH_STATUS_OTHER = 6,
42
+ /**
43
+ * An internal panic was caught; the call had no effect.
44
+ */
45
+ EEH_STATUS_PANIC = 7,
46
+ } EehStatus;
47
+
48
+ /**
49
+ * An error: a code and a message. Opaque to C; read it with `eeh_error_code` and `eeh_error_message`.
50
+ */
51
+ typedef struct EehError EehError;
52
+
53
+ /**
54
+ * A synthesizer and the voice names as C strings.
55
+ */
56
+ typedef struct EehSynthesizer EehSynthesizer;
57
+
58
+ /**
59
+ * Options of a call; `NULL` for all defaults (see `eeh_options_default`).
60
+ */
61
+ typedef struct {
62
+ /**
63
+ * Speaking rate, 0.25 to 4 (1 = as predicted, larger is faster).
64
+ */
65
+ float speed;
66
+ /**
67
+ * Added to log F0 (0.058 is about one semitone).
68
+ */
69
+ float pitch_shift;
70
+ /**
71
+ * Scales the pitch movement, 0 to 3 (1 = as predicted).
72
+ */
73
+ float pitch_range;
74
+ /**
75
+ * Seed of the noise; sentence `i` uses `seed + i`.
76
+ */
77
+ uint64_t seed;
78
+ /**
79
+ * The loudest sample of the audio: louder audio is scaled down to it. Zero or less (or NaN) leaves
80
+ * the model's output as it is. In `eeh_speak_each` each sentence is limited on its own.
81
+ */
82
+ float peak;
83
+ } EehOptions;
84
+
85
+ /**
86
+ * Called by `eeh_speak_each` for each sentence: its text (NUL-terminated UTF-8) and `len` samples at
87
+ * `audio`, both valid only during the call. Return `false` to stop.
88
+ */
89
+ typedef bool (*EehUtteranceCallback)(const char *text,
90
+ const float *audio,
91
+ size_t len,
92
+ void *user_data);
93
+
94
+ /**
95
+ * Called by `eeh_speak_stream` for each chunk of audio: the text of the sentence it belongs to
96
+ * (NUL-terminated UTF-8), the index of that sentence (from 0) and `len` samples at `audio`, both
97
+ * pointers valid only during the call. Return `false` to stop.
98
+ */
99
+ typedef bool (*EehChunkCallback)(const char *text,
100
+ size_t index,
101
+ const float *audio,
102
+ size_t len,
103
+ void *user_data);
104
+
105
+ #ifdef __cplusplus
106
+ extern "C" {
107
+ #endif // __cplusplus
108
+
109
+ /**
110
+ * The version of the library, e.g. `"0.1.0"`. Static; never freed.
111
+ */
112
+ const char *eeh_version(void);
113
+
114
+ /**
115
+ * Writes the default options (speed 1, no pitch change, seed 0, peak 0.99) to `*options`.
116
+ *
117
+ * # Safety
118
+ * `options` is null or points to writable memory for an `EehOptions`.
119
+ */
120
+ void eeh_options_default(EehOptions *options);
121
+
122
+ /**
123
+ * Loads a synthesizer from the bytes of the weights file (safetensors) and of the packed dictionary
124
+ * (both are copied or parsed during the call; the buffers may be freed afterwards).
125
+ *
126
+ * Returns `NULL` on failure, with `*err` set when `err` is not `NULL`. Free the result with
127
+ * `eeh_synthesizer_free` and the error with `eeh_error_free`. A synthesizer can be used from
128
+ * several threads at once.
129
+ *
130
+ * # Safety
131
+ * Each buffer is `NULL` or has that many readable bytes; `err` is `NULL` or points to a writable `EehError*`.
132
+ */
133
+ EehSynthesizer *eeh_synthesizer_new(const uint8_t *weights,
134
+ size_t weights_len,
135
+ const uint8_t *dictionary,
136
+ size_t dictionary_len,
137
+ EehError **err);
138
+
139
+ /**
140
+ * Frees a synthesizer. `NULL` is fine. No other call may use it at the same time or after.
141
+ *
142
+ * # Safety
143
+ * `synth` is `NULL` or came from `eeh_synthesizer_new` and is not freed twice.
144
+ */
145
+ void eeh_synthesizer_free(EehSynthesizer *synth);
146
+
147
+ /**
148
+ * Sample rate of the audio in Hz; 0 when `synth` is `NULL`.
149
+ *
150
+ * # Safety
151
+ * `synth` is `NULL` or a live synthesizer.
152
+ */
153
+ uint32_t eeh_sample_rate(const EehSynthesizer *synth);
154
+
155
+ /**
156
+ * Number of voices of the model; 0 when `synth` is `NULL`.
157
+ *
158
+ * # Safety
159
+ * `synth` is `NULL` or a live synthesizer.
160
+ */
161
+ size_t eeh_voice_count(const EehSynthesizer *synth);
162
+
163
+ /**
164
+ * Name of voice `index` (e.g. `"F1"`), valid until the synthesizer is freed; `NULL` when out of range.
165
+ *
166
+ * # Safety
167
+ * `synth` is `NULL` or a live synthesizer.
168
+ */
169
+ const char *eeh_voice_name(const EehSynthesizer *synth,
170
+ size_t index);
171
+
172
+ /**
173
+ * Speaks `utf8` (NUL-terminated) in `voice` and returns all the audio.
174
+ *
175
+ * On success `*audio` points to `*len` samples (mono, `eeh_sample_rate` Hz, `float`) that the caller frees with `eeh_audio_free(*audio, *len)`.
176
+ * `options` may be `NULL`. Returns `EEH_STATUS_OK` or an error code, with `*err` set when `err` is not
177
+ * `NULL` (free it with `eeh_error_free`); `*audio` is `NULL` and `*len` 0 on failure.
178
+ *
179
+ * # Safety
180
+ * `synth` is live; `utf8` and `voice` are NUL-terminated strings; `options` is `NULL` or readable;
181
+ * `audio` and `len` are writable; `err` is `NULL` or points to a writable `EehError*`.
182
+ */
183
+ EehStatus eeh_speak(const EehSynthesizer *synth,
184
+ const char *utf8,
185
+ const char *voice,
186
+ const EehOptions *options,
187
+ float **audio,
188
+ size_t *len,
189
+ EehError **err);
190
+
191
+ /**
192
+ * Like `eeh_speak`, but hands each sentence to `callback` as soon as it is made (streaming).
193
+ *
194
+ * The audio is only valid during the callback. The callback returns `false` to stop early (the result is then
195
+ * still `EEH_STATUS_OK`). It runs on the calling thread and must not call back into the same
196
+ * synthesizer's `eeh_synthesizer_free`.
197
+ *
198
+ * # Safety
199
+ * As `eeh_speak`; `callback` is a valid function and `user_data` whatever it expects.
200
+ */
201
+ EehStatus eeh_speak_each(const EehSynthesizer *synth,
202
+ const char *utf8,
203
+ const char *voice,
204
+ const EehOptions *options,
205
+ EehUtteranceCallback callback,
206
+ void *user_data,
207
+ EehError **err);
208
+
209
+ /**
210
+ * Like `eeh_speak_each`, but hands each sentence to `callback` in chunks, each as soon as its samples
211
+ * are final (streaming within a sentence: the first sound comes before the sentence is finished).
212
+ *
213
+ * With a model whose acoustic attention is local the first chunk holds about `first_frames` frames of
214
+ * audio (one frame is `hop` = 256 samples, 10.7 ms) and each later one `chunk_frames`; 0 selects the
215
+ * defaults (12 and 48). With global attention (eeh-1) a sentence is one chunk. The chunks of a
216
+ * sentence joined equal the audio `eeh_speak_each` delivers for it (within 1e-5), except that the
217
+ * peak limit (`options->peak`) is applied as a gain that follows the loudest sample heard so far.
218
+ * The callback returns `false` to stop (the result is then still `EEH_STATUS_OK`); it runs on the
219
+ * calling thread and must not call `eeh_synthesizer_free` on the same synthesizer.
220
+ *
221
+ * # Safety
222
+ * As `eeh_speak_each`.
223
+ */
224
+ EehStatus eeh_speak_stream(const EehSynthesizer *synth,
225
+ const char *utf8,
226
+ const char *voice,
227
+ const EehOptions *options,
228
+ size_t first_frames,
229
+ size_t chunk_frames,
230
+ EehChunkCallback callback,
231
+ void *user_data,
232
+ EehError **err);
233
+
234
+ /**
235
+ * Frees audio from `eeh_speak`; `len` is the length it returned. `NULL` is fine.
236
+ *
237
+ * # Safety
238
+ * `audio` is `NULL` or the pointer and `len` the length `eeh_speak` returned, not freed twice.
239
+ */
240
+ void eeh_audio_free(float *audio, size_t len);
241
+
242
+ /**
243
+ * The message of an error (NUL-terminated UTF-8), valid until `eeh_error_free`; `""` for `NULL`.
244
+ *
245
+ * # Safety
246
+ * `error` is `NULL` or a live error.
247
+ */
248
+ const char *eeh_error_message(const EehError *error);
249
+
250
+ /**
251
+ * The status code of an error; `EEH_STATUS_INVALID_ARGUMENT` for `NULL`.
252
+ *
253
+ * # Safety
254
+ * `error` is `NULL` or a live error.
255
+ */
256
+ EehStatus eeh_error_code(const EehError *error);
257
+
258
+ /**
259
+ * Frees an error. `NULL` is fine.
260
+ *
261
+ * # Safety
262
+ * `error` is `NULL` or came from this library and is not freed twice.
263
+ */
264
+ void eeh_error_free(EehError *error);
265
+
266
+ #ifdef __cplusplus
267
+ } // extern "C"
268
+ #endif // __cplusplus
269
+
270
+ #endif /* EEH_H */
lib/linux-aarch64/libeeh_ffi.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5a930c71e308ce805396c7a903ddd4356c87403a81e10c0b02a246115b831f2
3
+ size 1724800
lib/linux-x86_64/libeeh_ffi.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2dd6fc91879325bc85a50103574f19fda7f9a4063ebb2fb86f8f6dc6cd00aa39
3
+ size 2487600
lib/macos-arm64/libeeh_ffi.dylib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2cfb558d5bff705bc49f4b7f5f0d67da797c88d8f16a1f48bc19136220c67040
3
+ size 1943760
looped.png ADDED
python/eeh-0.2.0-py3-none-macosx_11_0_arm64.whl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b17a8d80932369f43f8515dd1a4ebc2ad9809ad21c1c462ef3e27f2fbf60e0d2
3
+ size 809626
python/eeh-0.2.0-py3-none-manylinux_2_28_aarch64.whl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00c85da47dcdeb79f8e36e22985ee19735f0568939b4bf393cf96917ec0a87ad
3
+ size 799857
python/eeh-0.2.0-py3-none-manylinux_2_28_x86_64.whl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d89f2ae27d62d3b2f98dcb15b3112eb2232eee2e20d6cc5d948c96150c7a5131
3
+ size 1067247
samples/F1-hello.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdfa7f0370950eaa85f4c41f6e6434b5b2aace2d2990f391f9283aff0bc4e600
3
+ size 658476
samples/F1-numbers.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3ed37b9007cd375224da29171c212d0746e3863fe0b920465f57ff2c3bea7df
3
+ size 676908
samples/F1-polite.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09df9e5c1a703baef390c0d4de1a3ad3a70ec352b22d03b4ab08e83ae36abb6e
3
+ size 553004
samples/F1-question.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ab122a1fa0b3511bd07eb053c2d36bef84de3fddab9ce661eb546f8d91b1777
3
+ size 404524
samples/F1-story.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:213eb33c084abdf2146f347b3f219d8161437b4029143593af469dc7c617c058
3
+ size 741420
samples/M1-hello.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb809dffdcf50c72c93263032315148516fecf65bf5f825dbf63e110192a4dab
3
+ size 632876
samples/M1-numbers.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2074d1bea6bdc2893318908fd1a6fcbbeda8797212a19a3ff278be3eab0df5a6
3
+ size 677932
samples/M1-polite.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2feef3b52a109014ad5fd285659ec1ef89876b1cb461cd2deeb111bd05f60609
3
+ size 544812
samples/M1-question.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c6bae1809a5bc337d9f39c433586da0c0283d2610f0f01f366f821fba4520afd
3
+ size 402476
samples/M1-story.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcfce563d7a10826e7e8805ed9878498c67903026bb5235cab9757b3b772fdd4
3
+ size 702508