eeh-1-1: looped stacks, local attention, int8 weights
Browse filesFiles changed (37)
- .gitattributes+19
- LICENSEAdded+202
- README.mdAdded+380
- bin/linux-aarch64/eehAdded+3
- bin/linux-x86_64/eehAdded+3
- bin/macos-arm64/eehAdded+3
- demo/404.htmlAdded+8
- demo/index.htmlAdded+247
- demo/model/eeh-dict.bin.gzAdded+3
- demo/model/eeh.safetensors.gzAdded+3
- demo/pkg/eeh_wasm.jsAdded+474
- demo/pkg/eeh_wasm_bg.wasmAdded+3
- demo/player.jsAdded+69
- demo/worker.jsAdded+149
- eeh-dict.binAdded+3
- eeh-f32.safetensorsAdded+3
- eeh.safetensorsAdded+3
- eval/metrics.jsonlAdded
- eval/report.jsonAdded
- include/eeh.hAdded+270
- lib/linux-aarch64/libeeh_ffi.soAdded+3
- lib/linux-x86_64/libeeh_ffi.soAdded+3
- lib/macos-arm64/libeeh_ffi.dylibAdded+3
- looped.pngAdded
- python/eeh-0.2.0-py3-none-macosx_11_0_arm64.whlAdded+3
- python/eeh-0.2.0-py3-none-manylinux_2_28_aarch64.whlAdded+3
- python/eeh-0.2.0-py3-none-manylinux_2_28_x86_64.whlAdded+3
- samples/F1-hello.wavAdded+3
- samples/F1-numbers.wavAdded+3
- samples/F1-polite.wavAdded+3
- samples/F1-question.wavAdded+3
- samples/F1-story.wavAdded+3
- samples/M1-hello.wavAdded+3
- samples/M1-numbers.wavAdded+3
- samples/M1-polite.wavAdded+3
- samples/M1-question.wavAdded+3
- samples/M1-story.wavAdded+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383940414243444546474849505152535432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textbin/linux-aarch64/eeh filter=lfs diff=lfs merge=lfs -textbin/linux-x86_64/eeh filter=lfs diff=lfs merge=lfs -textbin/macos-arm64/eeh filter=lfs diff=lfs merge=lfs -textlib/linux-aarch64/libeeh_ffi.so filter=lfs diff=lfs merge=lfs -textlib/linux-x86_64/libeeh_ffi.so filter=lfs diff=lfs merge=lfs -textlib/macos-arm64/libeeh_ffi.dylib filter=lfs diff=lfs merge=lfs -textpython/eeh-0.2.0-py3-none-macosx_11_0_arm64.whl filter=lfs diff=lfs merge=lfs -textpython/eeh-0.2.0-py3-none-manylinux_2_28_aarch64.whl filter=lfs diff=lfs merge=lfs -textpython/eeh-0.2.0-py3-none-manylinux_2_28_x86_64.whl filter=lfs diff=lfs merge=lfs -textsamples/F1-hello.wav filter=lfs diff=lfs merge=lfs -textsamples/F1-numbers.wav filter=lfs diff=lfs merge=lfs -textsamples/F1-polite.wav filter=lfs diff=lfs merge=lfs -textsamples/F1-question.wav filter=lfs diff=lfs merge=lfs -textsamples/F1-story.wav filter=lfs diff=lfs merge=lfs -textsamples/M1-hello.wav filter=lfs diff=lfs merge=lfs -textsamples/M1-numbers.wav filter=lfs diff=lfs merge=lfs -textsamples/M1-polite.wav filter=lfs diff=lfs merge=lfs -textsamples/M1-question.wav filter=lfs diff=lfs merge=lfs -textsamples/M1-story.wav filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380---language: jalicense: apache-2.0pipeline_tag: text-to-speechlibrary_name: eehbase_model: ctrltokyo/eeh-1tags:- text-to-speech- japanese- rust- webassembly- tiny- looped-transformer- streaming---
# eeh-1-1
**A tiny Japanese voice that fits in a browser tab.** eeh is a Japanesetext-to-speech model with two voices and 3.3 million parameters, waveformgenerator included. It reads kanji, numbers and Tokyo pitch accent, and runs ona CPU or fully inside a browser, with nothing sent anywhere.
There is no neural vocoder. A transformer reads OpenJTalk's phonemes with theirpitch-accent tones, predicts how long each one lasts, then predicts pitch,loudness and the settings of a small source-filter synthesizer, which makes thewaveform from a pulse train and noise. It was trained from scratch on 18.6hours of speech by[Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi).
**What changed since [eeh-1](https://huggingface.co/ctrltokyo/eeh-1).**eeh-1-1 is eeh-1 with **looped** transformer stacks (shared weights, samedepth) and **local attention** on the frame-level stacks, fine-tuned fromeeh-1 for 20,000 steps. It has 26% fewer parameters, ships as 4.0 MB of int8weights, streams audio within a sentence (first sound in about 3 ms on a CPU),and scores the same as or better than eeh-1 on every metric.
<audio controls preload="none" src="https://huggingface.co/ctrltokyo/eeh-1-1/resolve/main/samples/F1-hello.wav"></audio>
| | ||---|---|| Parameters | 3,343,824 (eeh-1: 4,534,219) || Weights | 4.0 MB int8 (`eeh.safetensors`), 13.4 MB float32 (`eeh-f32.safetensors`) || Voices | F1 (female, late 20s, calm and clear), M1 (male, early 30s, warm), Tokyo Japanese || Output | 24 kHz mono || Input | Japanese text (kanji, kana, numbers), read with OpenJTalk || Speed | 14 s sentence in 35 ms on one CPU thread (400x real time, Apple M4 Max, Accelerate); about 60x in a browser tab || 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 || Pretrained weights in the model | None (initialised from eeh-1, itself trained from scratch) || License | Apache-2.0 |
## Samples
| Text | F1 | M1 ||---|---|---|| こんにちは!これは、ノートパソコンでも動く小さな音声合成モデルです。 | <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> || 会議は三月十四日の午後三時半に変わったので、あと四十五分ほどあります。 | <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> || 本当に、あなたの誕生日を忘れると思ったの? | <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> || 彼女は海を見たことがなかった。しばらくの間、何も言わずに波打ち際に立っていた。 | <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> || 恐れ入りますが、お名前とご連絡先をこちらにご記入いただけますか。 | <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> |
## Files
| Path | Contents ||---|---|| `eeh.safetensors` | Weights, int8 linear layers with a float32 scale per row (4.0 MB); the default || `eeh-f32.safetensors` | The same weights in float32 (13.4 MB), e.g. for fine-tuning || `eeh-dict.bin` | The Japanese dictionary the front end reads (36 MB) || `python/` | Python wheels for macOS (arm64) and Linux (aarch64, x86_64) || `bin/<platform>/eeh` | Command-line program || `lib/<platform>/`, `include/eeh.h` | C library and header, for any language with a C FFI || `demo/` | The browser demo: the whole engine compiled to WebAssembly, the weights and the dictionary || `samples/` | The audio on this page || `eval/report.json`, `eval/metrics.jsonl` | Evaluation report (int8 weights) and the fine-tuning log || `looped.png` | The diagram below || `LICENSE` | Apache-2.0 |
## Usage
eeh runs on its own engine, written in Rust: a Japanese front end that readstext exactly as OpenJTalk does (identical on more than 500,000 test texts) andthe model. The same engine is behind the Python package, the command-lineprogram, the C library and the browser demo. Both weight files load the sameway; int8 is dequantised at load, so speed is identical.
```bashhf download ctrltokyo/eeh-1-1 --local-dir eehcd eeh```
### Python
```bashpip install python/eeh-0.2.0-py3-none-<your platform>.whl```
```pythonimport eeh, soundfile
synth = eeh.Synthesizer("eeh.safetensors", "eeh-dict.bin")audio = synth.speak("こんにちは。今日はいい天気ですね。", voice="F1") # float32 array, 24 kHzsoundfile.write("hello.wav", audio, synth.sample_rate)
# Streaming within a sentence: chunks arrive as soon as their samples are final.synth.speak_stream("長い文章も、最初の音はすぐに届きます。", lambda text, chunk, index: play(chunk), voice="M1")```
`speak` takes `voice` (`F1` or `M1`), `speed` (1.0), `pitch_shift` (0; 0.058is about one semitone), `pitch_range` (1.0) and `seed`. `speak_stream(text,callback)` hands over chunks of audio (`first_frames=12`, then`chunk_frames=48`, 10.7 ms per frame); joined, they equal `speak`'s audio.`speak_each(text, callback)` hands over whole sentences. The package has nodependencies; it returns a NumPy array when NumPy is installed. Thesynthesizer can be shared between threads.
### Command line
```bashchmod +x bin/macos-arm64/eeh # the Hub does not keep the executable bitbin/macos-arm64/eeh speak --weights eeh.safetensors --dictionary eeh-dict.bin \ --voice M1 --text "こんにちは。今日はいい天気ですね。" --out hello.wav [--stream]```
### C and other languages
`lib/<platform>/libeeh_ffi` with `include/eeh.h`: `eeh_synthesizer_new` takesthe weights and dictionary as bytes, `eeh_speak` returns the audio,`eeh_speak_each` streams it sentence by sentence and `eeh_speak_stream` chunkby chunk. Errors come back as status codes, never as crashes. Go, Node, Java,Ruby and Swift can call it through their C FFI (all five are tested).
Text of any length works. It is split into sentences at 。!? and read onesentence at a time; a quote followed by と or って stays with its sentence, anda sentence too long for one call is cut after 、. A text without a final markgets 。. The audio never peaks above 0.99.
### In a browser
```bashpython -m http.server --directory demo 8000```
Then open `http://localhost:8000`. The engine runs in a Web Worker and playsaudio chunk by chunk as it is made. The first visit downloads about 13 MB(gzip): 3.7 MB of weights, 9 MB of dictionary and 0.4 MB of program, all keptby the browser afterwards.
## How it works
**Front end.** eeh's own Rust front end reads the text the way OpenJTalk doeswith the NAIST Japanese Dictionary: it splits it into words, picks each kanji'sreading, expands numbers, joins words into accent phrases and assigns theiraccent types. It turns the result into tokens:
- one token per phoneme (`k`, `sh`, `a`, `N` for ん, `cl` for っ); a long vowel is two tokens, one per mora;- devoiced vowels (the u of です, the i of した) are their own tokens `A I U E O`;- `<sp>` marks a boundary between accent phrases, and punctuation is kept;- each token carries the Tokyo pitch-accent tone of its mora, low or high, computed from the phrase's accent type and the mora's position.
The 8,650 training sentences (11.8 hours of speech) are read in 0.29 s on oneCPU thread (0.03 ms per sentence, about 150,000x real time), 5.5x faster thanpyopenjtalk. The dictionary loads in 3 ms.
**Model.** All blocks are pre-norm transformer blocks with 192 channels, 4heads and rotary position embeddings. Their feed-forward is a depthwiseconvolution (kernel 7) followed by a GELU MLP (192 → 640 → 192).
| Stage | Blocks stored / applied | Attention | Output ||---|---|---|---|| Text encoder | 3 / 4 (looped, 2 core passes) | global | token states || Duration and pause predictor | conv | – | frames per token || Frame transformer A | 2 / 2 | local, ±32 frames (±341 ms) | log F0, voicing, energy || Frame transformer B | 3 / 5 (looped, 3 core passes) | local, ±16 frames (±171 ms) | synthesizer settings per frame || Source-filter head | – | – | band-limited pulse train at F0 plus noise, each shaped by a per-frame filter (256 samples, 10.7 ms) |
| Component | Parameters | eeh-1 ||---|---:|---:|| Embeddings (token, tone, voice) | 13,632 | 13,632 || Text encoder | 1,192,130 | 1,588,864 || Duration and pause predictor | 123,906 | 123,906 || Frame transformer A, pitch/voicing/energy head | 795,971 | 795,971 || Frame transformer B | 1,192,323 | 1,985,984 || Source-filter waveform head | 25,862 | 25,862 || Total | 3,343,824 | 4,534,219 |
## Looped stacks

A looped stack stores *prelude → core → coda* and applies the core `L` timeswith tied weights. Depth (block applications) is unchanged from eeh-1;parameters are not.
```h0 = prelude(x)h = h0for k in 1..L: h = (h + e_k + tanh(g_k) · h0) ⊙ mask # per-pass embedding, gated input injection h = core(h)y = norm(coda(h))```
- **`e_k`** (`[L, 192]`): learned pass embedding, so the shared core can tell passes apart (a depth embedding, as in Universal Transformers).- **`tanh(g_k) · h0`**: learned scalar gate re-injecting the prelude output before every pass, which keeps later passes anchored to the input and keeps gradients short.- **Zero init**: `e_k = 0`, `g_k = 0`, so an untrained loop is exactly a repeated block. That makes branching from a non-looped checkpoint stable.- **Cost**: `L·192 + L` extra parameters per stack (386 for the encoder, 579 for B). In the Rust engine the core's packed weights are reused across passes while a tile of frames is in cache.
| Stack | eeh-1 | eeh-1-1 | Mapping from eeh-1 ||---|---|---|---|| Text encoder | 4 blocks | prelude + core ×2 + coda | blocks 0, 1, 3 (2 dropped) || Frame transformer B | 5 blocks | prelude + core ×3 + coda | blocks 0, 2, 4 (1, 3 dropped) |
**Local attention and streaming.** Frame transformers A and B attend within aband (`|i − j| ≤ W`), computed as a band in `O(T·W)` time and memory instead of`O(T²)`. The receptive field of transformer B is 5 × (16 + 3) = 95 frames(about 1.0 s) each side, so the engine streams. It computes the encoder,durations and prosody for the whole sentence, then runs transformer B and thesource-filter head as a wavefront over frames, emitting a chunk once itssamples can no longer change. The first chunk is final after 95 + 12 framesare fed. Nothing is computed twice, and the joined chunks equal one-shotsynthesis to within 1e-5.
**Ablation.** All variants were branched from eeh-1 and fine-tuned for 20,000steps under identical settings. Scores are on 300 validation clips and 16novel sentences.
| Variant | Params | Reading error | Accent | UTMOS | UTMOS, novel ||---|---:|---:|---:|---:|---:|| eeh-1 (no fine-tune) | 4.53M | 1.03% | 0.706 | 2.94 | 2.88 || Pruned to 3.7M (blocks deleted) | 3.74M | 1.09% | 0.704 | 2.91 | 2.91 || Looped B, global attention | 3.74M | 1.08% | 0.702 | 2.90 | 2.90 || Looped B, local ±64/±32 | 3.74M | 1.10% | 0.705 | 3.00 | 3.04 || Looped B, local ±32/±16 | 3.74M | 1.07% | 0.700 | 2.99 | 3.04 || Looped encoder + B, ±64/±32 | 3.34M | 1.10% | 0.702 | 2.98 | 2.99 || **Looped encoder + B, ±32/±16 (eeh-1-1)** | **3.34M** | 1.12% | 0.703 | 2.99 | 2.98 |
At equal size, looping matches deleting blocks. Local attention adds about0.09 UTMOS on validation and 0.14 on novel sentences. Looping the encoder removes 0.4M more parameters with nomeasurable loss. Training for 40,000 steps instead of 20,000 did not help(validation loss flat from step 116,000).
**int8 weights.** Each 2-D linear weight (33 matrices, about 90% of theparameters) is quantised symmetrically per output row (`q = round(w / s)`,`s = max|w_row| / 127`) and stored as I8 plus an F32 scale; everything elsestays float32. The engine dequantises at load (about 1 ms). Durations matchfloat32 exactly. The mean log-mel difference from float32 is 0.17–0.20, andevery evaluation score is within ±0.004 on accent and ±0.03 on UTMOS (seebelow).
## Training data
The speech is synthetic. Two voices were designed once from Japanesedescriptions with Irodori-TTS v4.1 Small (`落ち着いた20代後半の女性。明瞭で自然な東京の話し言葉。`and `30代前半の男性。温かく親しみやすい、自然な東京の話し言葉。`), then everysentence was read by [Irodori-TTS v4.1 Small Yomi](https://huggingface.co/takuma104/Irodori-TTS-v4.1-Small-Yomi)(MIT) cloning those two references. No recording of a real speaker is involved.
On the 300 test sentences in both voices, the teacher's speech has 1.2% kanareading error, 0.69 pitch-accent agreement and a UTMOS of 3.38.
The 8,650 sentences (8,000 train, 350 validation, 300 test, split by sentence)were chosen to cover as many morae and mora pairs as possible; 25% arequestions and 10% exclamations.
Every clip was screened before training:
- **Reading.** [kana-whisper](https://huggingface.co/sbintuitions/kana-whisper) transcribed it to katakana, compared with OpenJTalk's reading; more than 10% kana error was rejected.- **Alignment.** Phoneme durations come from forced alignment with `facebook/wav2vec2-lv-60-espeak-cv-ft`, used only to label the data. Its labels were recalibrated on the teacher's audio, and clips it aligned with low confidence were rejected.- **Speaking rate and length.**
| | Clips | Hours ||---|---:|---:|| Generated (sentences x voices) | 17,300 | || Passed screening | 15,684 | || Used for training (F1 7,301, M1 6,783) | 14,084 | 18.6 || Validation / test | 614 / 527 | 1.3 / 1.0 |
## Training
| | eeh-1 (from scratch) | eeh-1-1 (fine-tune) ||---|---|---|| Steps | 0 → 104,000 | 104,000 → 124,000 || Initialisation | random | eeh-1 blocks mapped as above; zero-init loop parameters; fresh optimizer || Batches | about 9,000 frames (96 s of audio) per step | same || Losses | Multi-resolution spectral losses; adversarial loss with multi-period and multi-resolution discriminators after step 8,000 | same, adversarial throughout || Hardware | One NVIDIA GB10 (Lenovo ThinkStation PGX) | One NVIDIA H100 || Time | 11.5 hours | 46 minutes (7.2 steps/s) |
The adversarial step computes the discriminators' gradient at the waveform onceinstead of twice, and runs their convolutions in bfloat16 with autotunedkernels on batches padded to a few fixed shapes. That is twice as fast, withthe same gradients.
## Evaluation
Speech from the released weights was scored the same way as the teacher'srecordings of the same sentences. kana-whisper transcribes it to katakana(reading error against OpenJTalk's reading), a pitch tracker checks eachexpected rise and fall of the pitch accent, and UTMOS rates naturalness. Thespectral distance is the mean log-mel distance from the teacher's recordingafter DTW.
| Sentences | Clips | Model | Reading error | Pitch-accent agreement | UTMOS | Spectral distance ||---|---:|---|---:|---:|---:|---:|| Test | 300 | eeh-1-1 int8 | **0.82%** | 0.705 | **2.97** | **0.662** || | | eeh-1-1 float32 | 0.84% | **0.710** | **2.97** | **0.662** || | | eeh-1 | 0.84% | 0.696 | 2.94 | 0.671 || | | teacher | 1.23% | 0.692 | 3.38 | || Validation | 300 | eeh-1-1 int8 | 1.11% | 0.703 | 2.98 | 0.701 || | | eeh-1-1 float32 | 1.12% | 0.703 | 2.99 | 0.701 || | | eeh-1 | 1.03% | 0.706 | 2.94 | 0.708 || | | teacher | 1.70% | 0.677 | 3.34 | || New sentences, not in the dataset | 16 | eeh-1-1 int8 | 0.0% | 0.702 | 3.01 | || | | eeh-1 | 0.0% | 0.689 | 2.88 | |
eeh-1-1 reads and accents as well as the teacher it learned from. It soundsless natural than the teacher (UTMOS about 0.4 lower), which is the cost ofthe small synthesizer. Differences from eeh-1 are within noise on reading andaccent and slightly favour eeh-1-1 on UTMOS and spectral distance. No formallistening test has been run; informal side-by-side listening found eeh-1,eeh-1-1 and the other variants indistinguishable.
**Speed** (Apple M4 Max, one thread, Rust engine):
| | eeh-1 | eeh-1-1 ||---|---:|---:|| 14 s sentence, portable build | 195 ms | 99 ms || 14 s sentence, Accelerate | 55 ms | 35 ms || First sound, 14 s sentence (Accelerate, streamed) | 55 ms | 11 ms || First sound, 3 s sentence (Accelerate, streamed) | 7.4 ms | 3.0 ms || Browser tab (Chromium), real time | about 50x | about 60x |
The gain grows with sentence length: attention cost is linear in the bandwidth instead of quadratic. On short sentences throughput is the same aseeh-1, and the gain is in first sound.
## Limitations
- Japanese only, two fixed voices, no voice cloning.- Readings come from OpenJTalk's dictionary. Rare kanji readings, names and new words can be read wrong, and the accent of compound phrases is predicted by rules. Whatever OpenJTalk gets wrong, eeh says wrong.- Latin letters are spelled out one by one (`eeh` is read イー・イー・エイチ).- The same text is always read the same way.- Prosody (frame transformer A) is computed for the whole sentence before the first chunk, so first sound grows slowly with sentence length (11 ms for a 14 s sentence on one thread).- The training data is synthetic, so eeh cannot sound more natural than the teacher; the small source-filter synthesizer sounds more buzzy than it.
## License
Apache-2.0 for the weights and code.
## Citation
```bibtex@software{nicholson2026eeh, author = {Nicholson, Alexander}, title = {eeh: a 3.3M-parameter two-voice Japanese text-to-speech model}, year = {2026}, url = {https://huggingface.co/ctrltokyo/eeh-1-1}}```
## Acknowledgements
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/).123version https://git-lfs.github.com/spec/v1oid sha256:369b7c2ae276dbac19a399e6d053cf0722800de801375ee9000095dbcb1f9fc5size 1866288123version https://git-lfs.github.com/spec/v1oid sha256:82543b1343023377235111dbdc78d6327f851c020fb31908bc05b9734a19ef96size 2666136123version https://git-lfs.github.com/spec/v1oid sha256:ac7b2f6a51669012b28e4f10c62bc56049205b0ab64a17fad76a45288dd6bc60size 197286412345678<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Not found – eeh</title><body style="font: 17px/1.5 system-ui, sans-serif; max-width: 40em; margin: 15vh auto; padding: 0 20px"><h1>Not found</h1><p><a href="/">Back to the eeh demo</a></p></body>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>eeh</title><meta name="description" content="eeh is a 3.3M-parameter Japanese text-to-speech model. This page runs it in your browser."><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"><style> :root { --paper: #f6f2ea; --ink: #1b1915; --muted: #6d665b; --line: #d9d2c4; --panel: #fffdf8; --accent: #b4421f; --accent-ink: #fff; --ok: #2f6b3c; --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; --sans: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; --ui: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } @media (prefers-color-scheme: dark) { :root { --paper: #151412; --ink: #ece6da; --muted: #9a9284; --line: #35312a; --panel: #1d1b18; --accent: #e0703f; --accent-ink: #151412; --ok: #7fbf8c; } } * { box-sizing: border-box; } body { margin: 0; background: var(--paper); color: var(--ink); font: 17px/1.55 var(--ui); } main { max-width: 760px; margin: 0 auto; padding: 56px 20px 72px; } header h1 { font: 600 44px/1.05 var(--sans); letter-spacing: -0.01em; margin: 0 0 14px; } header p { margin: 0; color: var(--muted); max-width: 56ch; } header p strong { color: var(--ink); font-weight: 600; } .panel { margin-top: 36px; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 18px; } textarea { width: 100%; min-height: 150px; resize: vertical; border: 0; outline: 0; background: transparent; color: inherit; font: 20px/1.5 var(--sans); padding: 4px; } .examples { display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0 2px; } .examples button { font: 13px var(--ui); color: var(--muted); background: transparent; border: 1px solid var(--line); border-radius: 999px; padding: 5px 11px; cursor: pointer; } .examples button:hover { color: var(--ink); border-color: var(--muted); } .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 14px 22px; border-top: 1px solid var(--line); margin-top: 14px; padding-top: 14px; } .voices { display: inline-flex; border: 1px solid var(--line); border-radius: 9px; overflow: hidden; } .voices label { padding: 7px 14px; font-size: 14px; cursor: pointer; color: var(--muted); } .voices input { position: absolute; opacity: 0; pointer-events: none; } .voices input:checked + span { color: var(--ink); font-weight: 600; } .voices label:has(input:checked) { background: var(--paper); } .voices label:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: -2px; } .speed { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--muted); } .speed input { width: 130px; accent-color: var(--accent); } .speed output { font: 13px var(--mono); color: var(--ink); min-width: 4ch; } #speak { margin-left: auto; min-width: 6em; font: 600 16px var(--ui); color: var(--accent-ink); background: var(--accent); border: 0; border-radius: 10px; padding: 11px 22px; cursor: pointer; } #speak:disabled { opacity: 0.45; cursor: default; } #speak:focus-visible, textarea:focus-visible, .examples button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .status { margin-top: 16px; font-size: 14px; color: var(--muted); min-height: 22px; } .bar { height: 3px; background: var(--line); border-radius: 2px; margin-top: 8px; overflow: hidden; } .bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width 0.15s; } .bar[hidden] { display: none; } .result[hidden] { display: none; } .result { margin-top: 22px; } audio { width: 100%; } dl { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 16px 0 0; } dl div { border-top: 1px solid var(--line); padding-top: 8px; } dt { font-size: 12px; color: var(--muted); } dd { margin: 2px 0 0; font: 15px var(--mono); } #download { display: inline-block; margin-top: 8px; font-size: 14px; color: var(--ink); text-underline-offset: 3px; } #download[hidden] { display: none; } details { margin-top: 16px; font-size: 14px; color: var(--muted); } details pre { white-space: pre-wrap; word-break: break-word; font: 13px/1.6 var(--mono); color: var(--ink); margin: 8px 0 0; } .facts { margin-top: 44px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; border-top: 1px solid var(--line); } .facts div { padding: 16px 12px 16px 0; border-bottom: 1px solid var(--line); } .facts b { display: block; font: 600 22px var(--sans); } .facts span { font-size: 13px; color: var(--muted); } footer { margin-top: 36px; font-size: 14px; color: var(--muted); } footer a { color: var(--ink); text-underline-offset: 3px; margin-right: 16px; } footer p { margin: 14px 0 0; max-width: 62ch; } @media (max-width: 560px) { header h1 { font-size: 34px; } main { padding-top: 36px; } dl { grid-template-columns: repeat(2, 1fr); } .facts { grid-template-columns: repeat(2, 1fr); } #speak { margin-left: 0; width: 100%; } }</style></head><body><main> <header> <h1>eeh</h1> <p>A <strong>3.3M-parameter</strong> Japanese text-to-speech model with two voices, trained from scratch. This page runs it in your browser: nothing you type leaves your device.</p> </header>
<section class="panel"> <textarea id="text" spellcheck="false" aria-label="Text to speak" lang="ja">こんにちは!これは、ブラウザの中だけで動く、小さな音声合成モデルです。</textarea> <div class="examples" id="examples"></div> <div class="controls"> <div class="voices" role="radiogroup" aria-label="Voice"> <label><input type="radio" name="voice" value="F1"><span>F1</span></label> <label><input type="radio" name="voice" value="M1" checked><span>M1</span></label> </div> <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> <button id="speak" disabled>Speak</button> </div> </section>
<div class="status" id="status" role="status">Loading…</div> <div class="bar" id="bar"><i></i></div>
<section class="result" id="result" hidden> <audio id="audio" controls></audio> <a id="download" download="eeh.wav" hidden>Download WAV</a> <dl> <div><dt>Audio</dt><dd id="m-audio">–</dd></div> <div><dt>Time to generate</dt><dd id="m-time">–</dd></div> <div><dt>Speed</dt><dd id="m-speed">–</dd></div> <div><dt>To first audio</dt><dd id="m-first">–</dd></div> </dl> </section>
<section class="facts"> <div><b>3,343,824</b><span>parameters, waveform generator included</span></div> <div><b>3.7 MB</b><span>model file (int8 safetensors, gzip)</span></div> <div><b>24 kHz</b><span>mono output</span></div> <div><b>2 voices</b><span>F1 and M1, Japanese</span></div> <div><b>Rust</b><span>reads kanji, numbers and pitch accent; the whole stack is WebAssembly</span></div> <div><b>Apache-2.0</b><span>code</span></div> </section>
<footer> <a href="https://github.com/n4ze3m/tiny-voca">tiny-voca (architecture)</a> <a href="https://github.com/r9y9/pyopenjtalk">OpenJTalk (pyopenjtalk) dictionary</a> <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 by the browser afterwards. Japanese only. Rare names and unusual readings are sometimes read wrongly.</p> </footer></main>
<script src="player.js"></script><script>const EXAMPLES = [ ["挨拶", "こんにちは!これは、ブラウザの中だけで動く、小さな音声合成モデルです。"], ["数字", "会議は3月14日の午後3時半に変更になりました。料金は4250円です。"], ["質問", "本当に私の誕生日を忘れていたの?もう九時半なの?そろそろ出かけないと間に合わないよ!"], ["物語", "彼女は海を見たことがなかったので、長いあいだ水際に立ったまま、ひとことも話さずに波を見つめていた。"], ["早口", "東京特許許可局の局長は、今日も急遽休暇を取った。"],];const $ = (id) => document.getElementById(id);const worker = new Worker("worker.js", { type: "module" });// The model is loaded from ./model/eeh.safetensors.gz and ./model/eeh-dict.bin.gz; ?model=URL and ?dictionary=URL load others// (a ".gz" address is gunzipped, any other is used as it is).const params = new URLSearchParams(location.search);const weightsUrl = new URL(params.get("model") || "model/eeh.safetensors.gz", location.href);const dictionaryUrl = new URL(params.get("dictionary") || "model/eeh-dict.bin.gz", location.href);let ready = false, busy = false, request = 0, url = null, rate = 0, live = null;
for (const [label, text] of EXAMPLES) { const button = document.createElement("button"); button.textContent = label; button.onclick = () => { $("text").value = text; $("text").focus(); }; $("examples").append(button);}$("speed").oninput = () => { $("speed-value").textContent = Number($("speed").value).toFixed(2); };
function setStatus(text, progress) { $("status").textContent = text; $("bar").hidden = progress == null; if (progress != null) $("bar").firstElementChild.style.width = Math.round(progress * 100) + "%";}// While the sentences are playing, the button stops them.function update() { const playing = live !== null && live.playing; $("speak").textContent = playing ? "Stop" : "Speak"; $("speak").disabled = !playing && (!ready || busy || !$("text").value.trim());}$("text").oninput = update;
function wav(samples, rate) { const buffer = new ArrayBuffer(44 + samples.length * 2); const view = new DataView(buffer); const text = (offset, value) => { for (let i = 0; i < value.length; i++) view.setUint8(offset + i, value.charCodeAt(i)); }; text(0, "RIFF"); view.setUint32(4, 36 + samples.length * 2, true); text(8, "WAVEfmt "); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true); view.setUint32(24, rate, true); view.setUint32(28, rate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true); text(36, "data"); view.setUint32(40, samples.length * 2, true); for (let i = 0; i < samples.length; i++) view.setInt16(44 + i * 2, Math.max(-1, Math.min(1, samples[i])) * 32767, true); return new Blob([buffer], { type: "audio/wav" });}
// The worker splits the text itself, so how far it is is told by the characters spoken of the characters sent.let spoken = 0, total = 1;worker.onmessage = ({ data }) => { if (data.type === "status") setStatus(data.text, data.progress); else if (data.type === "ready") { ready = true; rate = data.sampleRate; setStatus("Ready."); update(); console.info("eeh ready", JSON.stringify(data.times)); } else if (data.type === "sentence" && data.id === request) { if (live && data.audio) live.add(data.audio, data.sampleRate); spoken += [...data.text.replace(/\s+/g, "")].length; setStatus(`Speaking sentence ${data.index + 1}`, Math.min(1, spoken / total)); } else if (data.type === "done" && data.id === request) { busy = false; update(); const seconds = data.audio.length / data.sampleRate; if (url) URL.revokeObjectURL(url); url = URL.createObjectURL(wav(data.audio, data.sampleRate)); $("audio").src = url; $("download").href = url; $("download").hidden = false; // The sentences have been playing since the first one was made, so the whole clip only waits in the player. // Where they could not be heard, it plays now. if (!live || !live.end()) $("audio").play().catch(() => {}); $("m-audio").textContent = seconds.toFixed(1) + " s"; $("m-time").textContent = (data.totalTime / 1000).toFixed(2) + " s"; $("m-speed").textContent = (seconds / (data.totalTime / 1000)).toFixed(1) + "× real time"; $("m-first").textContent = Math.round(data.firstAudio) + " ms"; $("result").hidden = false; setStatus("Done."); } else if (data.type === "error") { busy = false; if (live) live.end(); update(); setStatus(data.plain ? data.message : "Something went wrong: " + data.message); }};worker.onerror = (event) => setStatus("Could not start: " + event.message);
// Sound has to start inside a click, so the player is made here and not when the first sentence arrives.function listen() { const Context = window.AudioContext || window.webkitAudioContext; if (!live && Context) { let context = null; try { context = new Context({ sampleRate: rate }); } catch (error) { try { context = new Context(); } catch (failed) {} } if (context) live = livePlayer(context, update); } $("audio").pause(); if (live) live.begin();}$("audio").onplay = () => { if (live) live.stop(); };
$("speak").onclick = () => { if (live && live.playing) { live.stop(); return; } busy = true; spoken = 0; total = [...$("text").value.replace(/\s+/g, "")].length || 1; request += 1; listen(); update(); setStatus("Speaking…", 0); worker.postMessage({ type: "speak", id: request, text: $("text").value, voice: document.querySelector("input[name=voice]:checked").value, speed: Number($("speed").value) });};$("text").addEventListener("keydown", (event) => { if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !$("speak").disabled) $("speak").click();});
setStatus("Loading the model and the dictionary…");worker.postMessage({ type: "load", weights: weightsUrl.href, dictionary: dictionaryUrl.href });</script></body></html>123version https://git-lfs.github.com/spec/v1oid sha256:0934c6a66014bc0c55b3e12c3319c431cf9d2345bcb982ebbbe2db5f6cb3a507size 9006746123version https://git-lfs.github.com/spec/v1oid sha256:bd043d25a2cc4ef2ac0ece7668a83a9d3f21fc34c90804f818fe1963d930f0f2size 3657567123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474/** * The eeh model and front end, loaded once and used for any number of texts. */export class Synthesizer { __destroy_into_raw() { const ptr = this.__wbg_ptr; this.__wbg_ptr = 0; SynthesizerFinalization.unregister(this); return ptr; } free() { const ptr = this.__destroy_into_raw(); wasm.__wbg_synthesizer_free(ptr, 0); } /** * Loads the weights (`eeh.safetensors`) and the packed dictionary (`eeh-dict.bin`). * * # Errors * A message when either file is malformed. * @param {Uint8Array | number[]} weights * @param {Uint8Array | number[]} dictionary */ constructor(weights, dictionary) { let ptr0, len0, ptr1, len1; try { ptr0 = passArray8ToWasm0(weights, wasm.__wbindgen_malloc); len0 = WASM_VECTOR_LEN; ptr1 = passArray8ToWasm0(dictionary, wasm.__wbindgen_malloc); len1 = WASM_VECTOR_LEN; } catch (e) { if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); } if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); } throw e; } const ret = wasm.synthesizer_new(ptr0, len0, ptr1, len1); if (ret[2]) { throw takeFromExternrefTable0(ret[1]); } this.__wbg_ptr = ret[0]; SynthesizerFinalization.register(this, this.__wbg_ptr, this); return this; } /** * Sample rate of the audio, in Hz. * @returns {number} */ sampleRate() { const ret = wasm.synthesizer_sampleRate(this.__wbg_ptr); return ret >>> 0; } /** * Speaks the text sentence by sentence: `callback(sentenceText, Float32Array)` is called as each is made * and stops the rest by returning `false`. Each sentence is peak-limited on its own. * * # Errors * As `speak`, and whatever the callback throws. * @param {string} text * @param {string} voice * @param {any} options * @param {Function} callback */ speakEach(text, voice, options, callback) { let ptr0, len0, ptr1, len1; try { ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len0 = WASM_VECTOR_LEN; ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len1 = WASM_VECTOR_LEN; } catch (e) { if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); } if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); } throw e; } const ret = wasm.synthesizer_speakEach(this.__wbg_ptr, ptr0, len0, ptr1, len1, options, callback); if (ret[1]) { throw takeFromExternrefTable0(ret[0]); } } /** * Streaming within a sentence: `callback(sentenceText, Float32Array, sentenceIndex)` is called with each chunk as * soon as its samples are final (the first one after about `firstFrames` frames) and stops the rest by returning * `false`. A model with global acoustic attention sends one chunk per sentence. The peak limit follows the loudest * sample heard so far (see `Synthesizer::speak_stream` of the `eeh` crate). * * # Errors * As `speak`, and whatever the callback throws. * @param {string} text * @param {string} voice * @param {any} options * @param {Function} callback */ speakStream(text, voice, options, callback) { let ptr0, len0, ptr1, len1; try { ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len0 = WASM_VECTOR_LEN; ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len1 = WASM_VECTOR_LEN; } catch (e) { if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); } if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); } throw e; } const ret = wasm.synthesizer_speakStream(this.__wbg_ptr, ptr0, len0, ptr1, len1, options, callback); if (ret[1]) { throw takeFromExternrefTable0(ret[0]); } } /** * The whole text as one waveform, peak-limited as a whole. * * # Errors * A message for an unknown voice, a text with nothing readable in it, or a failure of the model. * @param {string} text * @param {string} voice * @param {any} options * @returns {Float32Array} */ speak(text, voice, options) { let ptr0, len0, ptr1, len1; try { ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len0 = WASM_VECTOR_LEN; ptr1 = passStringToWasm0(voice, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); len1 = WASM_VECTOR_LEN; } catch (e) { if (ptr1) { wasm.__wbindgen_free(ptr1, len1 * 1, 1); } if (ptr0) { wasm.__wbindgen_free(ptr0, len0 * 1, 1); } throw e; } const ret = wasm.synthesizer_speak(this.__wbg_ptr, ptr0, len0, ptr1, len1, options); if (ret[3]) { throw takeFromExternrefTable0(ret[2]); } var v3 = getArrayF32FromWasm0(ret[0], ret[1]).slice(); wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); return v3; } /** * The voices of the model, e.g. `["F1", "M1"]`. * @returns {string[]} */ voices() { const ret = wasm.synthesizer_voices(this.__wbg_ptr); var v1 = getArrayJsValueFromWasm0(ret[0], ret[1]); wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); return v1; }}if (Symbol.dispose) Synthesizer.prototype[Symbol.dispose] = Synthesizer.prototype.free;function __wbg_get_imports() { const import0 = { __proto__: null, __wbg_Error_208446807d0d1e30: function(arg0, arg1) { const ret = Error(getStringFromWasm0(arg0, arg1)); return ret; }, __wbg___wbindgen_boolean_get_4f1baf9a00be3c74: function(arg0) { const v = arg0; const ret = typeof(v) === 'boolean' ? v : undefined; return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0; }, __wbg___wbindgen_is_null_c22311b1cc228e3a: function(arg0) { const ret = arg0 === null; return ret; }, __wbg___wbindgen_is_object_8b968c3ab8e96595: function(arg0) { const val = arg0; const ret = typeof(val) === 'object' && val !== null; return ret; }, __wbg___wbindgen_number_get_934b640d0889af78: function(arg0, arg1) { const obj = arg1; const ret = typeof(obj) === 'number' ? obj : undefined; getDataViewMemory0().setFloat64((arg0 >>> 0) + 8 * 1, isLikeNone(ret) ? 0 : ret, true); getDataViewMemory0().setInt32((arg0 >>> 0) + 4 * 0, !isLikeNone(ret), true); }, __wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) { throw new Error(getStringFromWasm0(arg0, arg1)); }, __wbg_call_275b78b3b6520b92: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { const ret = arg0.call(arg1, arg2, arg3, arg4); return ret; }, arguments); }, __wbg_call_fc92fee6137d452d: function() { return handleError(function (arg0, arg1, arg2, arg3) { const ret = arg0.call(arg1, arg2, arg3); return ret; }, arguments); }, __wbg_get_2080c49015e35254: function() { return handleError(function (arg0, arg1) { const ret = Reflect.get(arg0, arg1); return ret; }, arguments); }, __wbg_new_from_slice_355c10c5d8f2addb: function(arg0, arg1) { const ret = new Float32Array(getArrayF32FromWasm0(arg0, arg1)); return ret; }, __wbindgen_generic_0000000000000001: function(arg0) { // Cast intrinsic for `F64 -> Externref`. const ret = arg0; return ret; }, __wbindgen_generic_0000000000000002: function(arg0, arg1) { // Cast intrinsic for `Ref(String) -> Externref`. const ret = getStringFromWasm0(arg0, arg1); return ret; }, __wbindgen_init_externref_table: function() { const table = wasm.__wbindgen_externrefs; table.set(0, undefined); table.set(1024, undefined); table.set(1025, null); table.set(1026, true); table.set(1027, false); }, }; return { __proto__: null, "./eeh_wasm_bg.js": import0, };}
const SynthesizerFinalization = (typeof FinalizationRegistry === 'undefined') ? { register: () => {}, unregister: () => {} } : new FinalizationRegistry(ptr => wasm.__wbg_synthesizer_free(ptr, 1));
function addToExternrefTable0(obj) { const idx = wasm.__externref_table_alloc(); wasm.__wbindgen_externrefs.set(idx, obj); return idx;}
function getArrayF32FromWasm0(ptr, len) { ptr = ptr >>> 0; return getFloat32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len);}
function getArrayJsValueFromWasm0(ptr, len) { ptr = ptr >>> 0; const mem = getDataViewMemory0(); const result = []; for (let i = ptr; i < ptr + 4 * len; i += 4) { result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true))); } wasm.__externref_drop_slice(ptr, len); return result;}
let cachedDataViewMemory0 = null;function getDataViewMemory0() { if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { cachedDataViewMemory0 = new DataView(wasm.memory.buffer); } return cachedDataViewMemory0;}
let cachedFloat32ArrayMemory0 = null;function getFloat32ArrayMemory0() { if (cachedFloat32ArrayMemory0 === null || cachedFloat32ArrayMemory0.byteLength === 0) { cachedFloat32ArrayMemory0 = new Float32Array(wasm.memory.buffer); } return cachedFloat32ArrayMemory0;}
function getStringFromWasm0(ptr, len) { ptr = ptr >>> 0; return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));}
let cachedUint8ArrayMemory0 = null;function getUint8ArrayMemory0() { if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); } return cachedUint8ArrayMemory0;}
function handleError(f, args) { try { return f.apply(this, args); } catch (e) { const idx = addToExternrefTable0(e); wasm.__wbindgen_exn_store(idx); }}
function isLikeNone(x) { return x === undefined || x === null;}
function passArray8ToWasm0(arg, malloc) { const ptr = malloc(arg.length * 1, 1) >>> 0; getUint8ArrayMemory0().set(arg, ptr / 1); WASM_VECTOR_LEN = arg.length; return ptr;}
function passStringToWasm0(arg, malloc, realloc) { if (realloc === undefined) { const buf = cachedTextEncoder.encode(arg); const ptr = malloc(buf.length, 1) >>> 0; getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); WASM_VECTOR_LEN = buf.length; return ptr; }
let len = arg.length; let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) { const code = arg.charCodeAt(offset); if (code > 0x7F) break; mem[ptr + offset] = code; } if (offset !== len) { if (offset !== 0) { arg = arg.slice(offset); } ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); const ret = cachedTextEncoder.encodeInto(arg, view);
offset += ret.written; ptr = realloc(ptr, len, offset, 1) >>> 0; }
WASM_VECTOR_LEN = offset; return ptr;}
function takeFromExternrefTable0(idx) { const value = wasm.__wbindgen_externrefs.get(idx); wasm.__externref_table_dealloc(idx); return value;}
let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true });cachedTextDecoder.decode();const MAX_SAFARI_DECODE_BYTES = 2146435072;let numBytesDecoded = 0;function decodeText(bytes) { numBytesDecoded += bytes.length; if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true }); cachedTextDecoder.decode(); numBytesDecoded = bytes.length; } return cachedTextDecoder.decode(bytes);}
const cachedTextEncoder = new TextEncoder();
if (!('encodeInto' in cachedTextEncoder)) { cachedTextEncoder.encodeInto = function (arg, view) { const buf = cachedTextEncoder.encode(arg); view.set(buf); return { read: arg.length, written: buf.length }; };}
let WASM_VECTOR_LEN = 0;
let wasmModule, wasmInstance, wasm;function __wbg_finalize_init(instance, module) { wasmInstance = instance; wasm = instance.exports; wasmModule = module; cachedDataViewMemory0 = null; cachedFloat32ArrayMemory0 = null; cachedUint8ArrayMemory0 = null; wasm.__wbindgen_start(); return wasm;}
async function __wbg_load(module, imports) { if (typeof Response === 'function' && module instanceof Response) { if (!module.ok) { throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`); }
if (typeof WebAssembly.instantiateStreaming === 'function') { try { return await WebAssembly.instantiateStreaming(module, imports); } catch (e) { const validResponse = expectedResponseType(module.type);
if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { 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);
} else { throw e; } } }
const bytes = await module.arrayBuffer(); return await WebAssembly.instantiate(bytes, imports); } else { const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) { return { instance, module }; } else { return instance; } }
function expectedResponseType(type) { switch (type) { case 'basic': case 'cors': case 'default': return true; } return false; }}
function initSync(module) { if (wasm !== undefined) return wasm;
if (module !== undefined) { if (Object.getPrototypeOf(module) === Object.prototype) { ({module} = module) } else { console.warn('using deprecated parameters for `initSync()`; pass a single object instead') } }
const imports = __wbg_get_imports(); if (!(module instanceof WebAssembly.Module)) { module = new WebAssembly.Module(module); } const instance = new WebAssembly.Instance(module, imports); return __wbg_finalize_init(instance, module);}
let __wbg_init_promise;async function __wbg_init(module_or_path) { if (wasm !== undefined) return wasm; if (__wbg_init_promise === undefined) { __wbg_init_promise = __wbg_init_once(module_or_path); __wbg_init_promise.catch(() => { __wbg_init_promise = undefined; }); } return __wbg_init_promise;}
async function __wbg_init_once(module_or_path) {
if (module_or_path !== undefined) { if (Object.getPrototypeOf(module_or_path) === Object.prototype) { ({module_or_path} = module_or_path) } else { console.warn('using deprecated parameters for the initialization function; pass a single object instead') } }
if (module_or_path === undefined) { module_or_path = new URL('eeh_wasm_bg.wasm', import.meta.url); } const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { module_or_path = fetch(module_or_path); }
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);}
export { initSync, __wbg_init as default };123version https://git-lfs.github.com/spec/v1oid sha256:d6db8c0d21d8e2343dfb8d455f14cff147df0d1b5100ff187e2747f63e35c767size 969700123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869// Plays the sentences of one request as they arrive. Each one starts on the sample where the one before it// ends, so there is no gap between them. `context` is an AudioContext; changed() is called whenever `playing`// may have changed.function livePlayer(context, changed = () => {}) { // A sentence with nothing before it to follow starts this many seconds from now, not at once: the browser then // has it in hand before its first sample is due. Asked to start at once, it can start a few milliseconds late // (measured in Firefox: up to 21 ms), and the next sentence would begin before it has ended. const LEAD = 0.05; const sources = new Set(); let open = false; // more sentences of this request may still come let muted = false; // the listener stopped this request: its later sentences stay silent let refused = false; // the browser said no when asked to start the sound let queued = 0; // sentences of this request handed to the browser let next = 0; // the context time at which the next sentence starts
function silence() { for (const source of sources) { source.onended = null; try { source.stop(); } catch (error) { /* an old browser, and the sentence had already ended */ } } sources.clear(); }
return { get playing() { return !muted && (open || sources.size > 0); },
// A new request. Call it from a click or a key press: browsers let a page start sound only there. begin() { silence(); open = true; muted = false; refused = false; queued = 0; next = 0; if (context.state !== "running") Promise.resolve(context.resume()).catch(() => { refused = true; }); changed(); },
// Queue one sentence. It starts when the one before it ends, or right away when that moment has passed. add(samples, rate) { if (muted || !samples.length) return; const buffer = context.createBuffer(1, samples.length, rate); buffer.getChannelData(0).set(samples); const source = context.createBufferSource(); source.buffer = buffer; source.connect(context.destination); source.onended = () => { sources.delete(source); changed(); }; const when = Math.max(next, context.currentTime + LEAD); source.start(when); next = when + samples.length / rate; sources.add(source); queued += 1; },
// No more sentences will come; the queued ones play to the end. False when there is nothing to hear (no // sentence came, or the browser refused the sound): the caller then plays the whole clip itself. A context // that is only slow to start is not a refusal: a short text can be done before the sound is running, and // its sentences play as soon as it is. end() { open = false; const played = muted || (queued > 0 && !(refused && context.state !== "running")); if (!played) silence(); changed(); return played; },
stop() { muted = true; open = false; silence(); changed(); }, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149// Runs eeh (crates/eeh-wasm: the Rust front end and model in WebAssembly) off the main thread. A module worker.// Messages in: {type: "load", weights, dictionary} urls; ".gz" ones are gunzipped// {type: "speak", id, text, voice, speed}// Messages out: status, ready, sentence (a chunk of a sentence's audio, as soon as it is final), done (with the whole clip),// error (plain: true when the message is meant for the reader as it is).// The text is split into sentences in Rust (eeh-frontend), so nothing here knows about Japanese.
import init, { Synthesizer } from "./pkg/eeh_wasm.js";
let synth;
const status = (text, progress) => postMessage({ type: "status", text, progress });
// Bump when the format of the cached files changes.const STORE = "eeh-rust-1";
// The body of a response, reporting how much of it has come (as a fraction of content-length, when it has one).function watched(response, label) { const total = Number(response.headers.get("content-length")) || 0; if (!response.body || !total) return response.body; let received = 0; return response.body.pipeThrough(new TransformStream({ transform(chunk, controller) { received += chunk.length; status(label, Math.min(1, received / total)); controller.enqueue(chunk); }, }));}
// A file of the demo as bytes. Gzipped files (the 36 MB dictionary is 9 MB that way; a host needs no compression// settings) are gunzipped here, and the plain bytes are kept in Cache Storage with the validators of the response:// the next visit asks the server only "has it changed?" (a 304 costs no body) and starts from the stored bytes.// Another origin is not asked (that would need a CORS preflight): its file stays until the address changes.async function asset(address, label) { const url = new URL(address, self.location.href); const key = url.href; let store = null, kept = null; try { store = await caches.open(STORE); kept = await store.match(key); } catch (error) { store = null; }
const headers = {}; if (kept && url.origin === self.location.origin) { const etag = kept.headers.get("x-etag"), modified = kept.headers.get("x-last-modified"); if (etag) headers["If-None-Match"] = etag; if (modified) headers["If-Modified-Since"] = modified; } let response = null; if (!kept || Object.keys(headers).length) { try { response = await fetch(key, { headers }); } catch (error) { if (!kept) throw error; // offline, and kept: use what is stored } } if (kept && (!response || response.status === 304 || (!response.ok && !Object.keys(headers).length))) { return new Uint8Array(await kept.arrayBuffer()); } if (!response.ok) throw new Error(`${key}: ${response.status}`);
let body = watched(response, label); // A host that gzips on its own has been undone by the browser already (content-encoding is set then). if (url.pathname.endsWith(".gz") && !response.headers.get("content-encoding")) { body = body.pipeThrough(new DecompressionStream("gzip")); } const bytes = new Uint8Array(await new Response(body).arrayBuffer()); if (store) { const info = { "x-etag": response.headers.get("etag") || "", "x-last-modified": response.headers.get("last-modified") || "" }; store.put(key, new Response(bytes, { headers: info })).catch(() => {}); } return bytes;}
async function load({ weights, dictionary }) { const started = performance.now(); status("Loading the model and the dictionary", 0); const [files] = await Promise.all([ Promise.all([asset(weights, "Loading the model"), asset(dictionary, "Loading the dictionary")]), init(), ]); const fetched = performance.now(); synth = new Synthesizer(files[0], files[1]); const built = performance.now(); synth.speak("こんにちは。", synth.voices()[0], {}); // warm up const warm = performance.now(); postMessage({ type: "ready", voices: synth.voices(), sampleRate: synth.sampleRate(), times: { files: fetched - started, synthesizer: built - fetched, warmup: warm - built, total: warm - started } });}
// 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// Synthesizer.speak does. A chunk that is played before the rest is made is scaled by a gain that follows the loudest// sample heard so far (down only), since the loudest sample of the clip is not known yet.const PEAK = 0.99;function limitPeak(samples) { let loudest = 0; for (let i = 0; i < samples.length; i++) loudest = Math.max(loudest, Math.abs(samples[i])); if (loudest > PEAK) for (let i = 0; i < samples.length; i++) samples[i] *= PEAK / loudest;}
// Shown when no sentence of a text could be read.const JAPANESE_ONLY = "eeh only reads Japanese for now.";
function speak({ id, text, voice, speed }) { const started = performance.now(); const chunks = []; let index = -1, firstAudio = 0, loudest = 0; try { // speakStream hands over chunks of a sentence as soon as they are final (a model with local acoustic attention // sends the first one long before the sentence is done; one with global attention sends the sentence at once). synth.speakStream(text, voice, { speed, peak: null }, (sentence, audio, sentenceIndex) => { chunks.push(audio); if (!firstAudio) firstAudio = performance.now() - started; // The page plays this chunk at once: a copy under the running gain; the clip keeps the original. const heard = audio.slice(); for (let i = 0; i < heard.length; i++) { loudest = Math.max(loudest, Math.abs(heard[i])); if (loudest > PEAK) heard[i] *= PEAK / loudest; } // The sentence text goes with its first chunk only (the page counts the characters spoken). const first = sentenceIndex !== index; index = sentenceIndex; postMessage({ type: "sentence", id, index, text: first ? sentence : "", audio: heard, sampleRate: synth.sampleRate(), time: performance.now() - started }, [heard.buffer]); return true; }); } catch (error) { const message = String(error && error.message || error); postMessage({ type: "error", id, message: message.startsWith("nothing in the text could be read") ? JAPANESE_ONLY : message, plain: message.startsWith("nothing in the text could be read") }); return; } const audio = new Float32Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0)); let offset = 0; for (const chunk of chunks) { audio.set(chunk, offset); offset += chunk.length; } limitPeak(audio); postMessage({ type: "done", id, audio, sampleRate: synth.sampleRate(), sentences: index + 1, firstAudio, totalTime: performance.now() - started }, [audio.buffer]);}
onmessage = async ({ data }) => { try { if (data.type === "load") await load(data); else if (data.type === "speak") speak(data); } catch (error) { postMessage({ type: "error", id: data.id, message: String(error && error.message || error) }); }};123version https://git-lfs.github.com/spec/v1oid sha256:b2d480c8806b230b113a37a28756748736b975c3aed37d5b27a3e8de7e32c6afsize 35927036123version https://git-lfs.github.com/spec/v1oid sha256:b26ae787c81fd0b8cf71d29c3c0d1c43ab7f99632d658e00c174bd1b4b6e174dsize 13395864123version https://git-lfs.github.com/spec/v1oid sha256:212d59411ad667431bcd9ab4df4dfee88e37cb745e826a76aaa21e0a2342d6c6size 3956896123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270/* eeh C API. Generated by cbindgen from rust/crates/eeh-ffi (generate-header.sh); do not edit. */
#ifndef EEH_H#define EEH_H
#include <stdbool.h>#include <stddef.h>#include <stdint.h>
/** * Result of a call. `EEH_STATUS_OK` is 0. */typedef enum { /** * Success. */ EEH_STATUS_OK = 0, /** * A pointer was null or a string was not UTF-8. */ EEH_STATUS_INVALID_ARGUMENT = 1, /** * No sentence of the text could be read (eeh only reads Japanese for now). */ EEH_STATUS_NOTHING_TO_PRONOUNCE = 2, /** * The voice is not one of the model's. */ EEH_STATUS_UNKNOWN_VOICE = 3, /** * The dictionary is malformed, or the text could not be analysed. */ EEH_STATUS_FRONTEND = 4, /** * The weights are malformed or an option is out of range. */ EEH_STATUS_MODEL = 5, /** * Anything else, e.g. a word too long to speak or non-finite audio. */ EEH_STATUS_OTHER = 6, /** * An internal panic was caught; the call had no effect. */ EEH_STATUS_PANIC = 7,} EehStatus;
/** * An error: a code and a message. Opaque to C; read it with `eeh_error_code` and `eeh_error_message`. */typedef struct EehError EehError;
/** * A synthesizer and the voice names as C strings. */typedef struct EehSynthesizer EehSynthesizer;
/** * Options of a call; `NULL` for all defaults (see `eeh_options_default`). */typedef struct { /** * Speaking rate, 0.25 to 4 (1 = as predicted, larger is faster). */ float speed; /** * Added to log F0 (0.058 is about one semitone). */ float pitch_shift; /** * Scales the pitch movement, 0 to 3 (1 = as predicted). */ float pitch_range; /** * Seed of the noise; sentence `i` uses `seed + i`. */ uint64_t seed; /** * The loudest sample of the audio: louder audio is scaled down to it. Zero or less (or NaN) leaves * the model's output as it is. In `eeh_speak_each` each sentence is limited on its own. */ float peak;} EehOptions;
/** * Called by `eeh_speak_each` for each sentence: its text (NUL-terminated UTF-8) and `len` samples at * `audio`, both valid only during the call. Return `false` to stop. */typedef bool (*EehUtteranceCallback)(const char *text, const float *audio, size_t len, void *user_data);
/** * Called by `eeh_speak_stream` for each chunk of audio: the text of the sentence it belongs to * (NUL-terminated UTF-8), the index of that sentence (from 0) and `len` samples at `audio`, both * pointers valid only during the call. Return `false` to stop. */typedef bool (*EehChunkCallback)(const char *text, size_t index, const float *audio, size_t len, void *user_data);
#ifdef __cplusplusextern "C" {#endif // __cplusplus
/** * The version of the library, e.g. `"0.1.0"`. Static; never freed. */const char *eeh_version(void);
/** * Writes the default options (speed 1, no pitch change, seed 0, peak 0.99) to `*options`. * * # Safety * `options` is null or points to writable memory for an `EehOptions`. */void eeh_options_default(EehOptions *options);
/** * Loads a synthesizer from the bytes of the weights file (safetensors) and of the packed dictionary * (both are copied or parsed during the call; the buffers may be freed afterwards). * * Returns `NULL` on failure, with `*err` set when `err` is not `NULL`. Free the result with * `eeh_synthesizer_free` and the error with `eeh_error_free`. A synthesizer can be used from * several threads at once. * * # Safety * Each buffer is `NULL` or has that many readable bytes; `err` is `NULL` or points to a writable `EehError*`. */EehSynthesizer *eeh_synthesizer_new(const uint8_t *weights, size_t weights_len, const uint8_t *dictionary, size_t dictionary_len, EehError **err);
/** * Frees a synthesizer. `NULL` is fine. No other call may use it at the same time or after. * * # Safety * `synth` is `NULL` or came from `eeh_synthesizer_new` and is not freed twice. */void eeh_synthesizer_free(EehSynthesizer *synth);
/** * Sample rate of the audio in Hz; 0 when `synth` is `NULL`. * * # Safety * `synth` is `NULL` or a live synthesizer. */uint32_t eeh_sample_rate(const EehSynthesizer *synth);
/** * Number of voices of the model; 0 when `synth` is `NULL`. * * # Safety * `synth` is `NULL` or a live synthesizer. */size_t eeh_voice_count(const EehSynthesizer *synth);
/** * Name of voice `index` (e.g. `"F1"`), valid until the synthesizer is freed; `NULL` when out of range. * * # Safety * `synth` is `NULL` or a live synthesizer. */const char *eeh_voice_name(const EehSynthesizer *synth, size_t index);
/** * Speaks `utf8` (NUL-terminated) in `voice` and returns all the audio. * * On success `*audio` points to `*len` samples (mono, `eeh_sample_rate` Hz, `float`) that the caller frees with `eeh_audio_free(*audio, *len)`. * `options` may be `NULL`. Returns `EEH_STATUS_OK` or an error code, with `*err` set when `err` is not * `NULL` (free it with `eeh_error_free`); `*audio` is `NULL` and `*len` 0 on failure. * * # Safety * `synth` is live; `utf8` and `voice` are NUL-terminated strings; `options` is `NULL` or readable; * `audio` and `len` are writable; `err` is `NULL` or points to a writable `EehError*`. */EehStatus eeh_speak(const EehSynthesizer *synth, const char *utf8, const char *voice, const EehOptions *options, float **audio, size_t *len, EehError **err);
/** * Like `eeh_speak`, but hands each sentence to `callback` as soon as it is made (streaming). * * The audio is only valid during the callback. The callback returns `false` to stop early (the result is then * still `EEH_STATUS_OK`). It runs on the calling thread and must not call back into the same * synthesizer's `eeh_synthesizer_free`. * * # Safety * As `eeh_speak`; `callback` is a valid function and `user_data` whatever it expects. */EehStatus eeh_speak_each(const EehSynthesizer *synth, const char *utf8, const char *voice, const EehOptions *options, EehUtteranceCallback callback, void *user_data, EehError **err);
/** * Like `eeh_speak_each`, but hands each sentence to `callback` in chunks, each as soon as its samples * are final (streaming within a sentence: the first sound comes before the sentence is finished). * * With a model whose acoustic attention is local the first chunk holds about `first_frames` frames of * audio (one frame is `hop` = 256 samples, 10.7 ms) and each later one `chunk_frames`; 0 selects the * defaults (12 and 48). With global attention (eeh-1) a sentence is one chunk. The chunks of a * sentence joined equal the audio `eeh_speak_each` delivers for it (within 1e-5), except that the * peak limit (`options->peak`) is applied as a gain that follows the loudest sample heard so far. * The callback returns `false` to stop (the result is then still `EEH_STATUS_OK`); it runs on the * calling thread and must not call `eeh_synthesizer_free` on the same synthesizer. * * # Safety * As `eeh_speak_each`. */EehStatus eeh_speak_stream(const EehSynthesizer *synth, const char *utf8, const char *voice, const EehOptions *options, size_t first_frames, size_t chunk_frames, EehChunkCallback callback, void *user_data, EehError **err);
/** * Frees audio from `eeh_speak`; `len` is the length it returned. `NULL` is fine. * * # Safety * `audio` is `NULL` or the pointer and `len` the length `eeh_speak` returned, not freed twice. */void eeh_audio_free(float *audio, size_t len);
/** * The message of an error (NUL-terminated UTF-8), valid until `eeh_error_free`; `""` for `NULL`. * * # Safety * `error` is `NULL` or a live error. */const char *eeh_error_message(const EehError *error);
/** * The status code of an error; `EEH_STATUS_INVALID_ARGUMENT` for `NULL`. * * # Safety * `error` is `NULL` or a live error. */EehStatus eeh_error_code(const EehError *error);
/** * Frees an error. `NULL` is fine. * * # Safety * `error` is `NULL` or came from this library and is not freed twice. */void eeh_error_free(EehError *error);
#ifdef __cplusplus} // extern "C"#endif // __cplusplus
#endif /* EEH_H */123version https://git-lfs.github.com/spec/v1oid sha256:a5a930c71e308ce805396c7a903ddd4356c87403a81e10c0b02a246115b831f2size 1724800123version https://git-lfs.github.com/spec/v1oid sha256:2dd6fc91879325bc85a50103574f19fda7f9a4063ebb2fb86f8f6dc6cd00aa39size 2487600123version https://git-lfs.github.com/spec/v1oid sha256:2cfb558d5bff705bc49f4b7f5f0d67da797c88d8f16a1f48bc19136220c67040size 1943760123version https://git-lfs.github.com/spec/v1oid sha256:b17a8d80932369f43f8515dd1a4ebc2ad9809ad21c1c462ef3e27f2fbf60e0d2size 809626123version https://git-lfs.github.com/spec/v1oid sha256:00c85da47dcdeb79f8e36e22985ee19735f0568939b4bf393cf96917ec0a87adsize 799857123version https://git-lfs.github.com/spec/v1oid sha256:d89f2ae27d62d3b2f98dcb15b3112eb2232eee2e20d6cc5d948c96150c7a5131size 1067247123version https://git-lfs.github.com/spec/v1oid sha256:fdfa7f0370950eaa85f4c41f6e6434b5b2aace2d2990f391f9283aff0bc4e600size 658476123version https://git-lfs.github.com/spec/v1oid sha256:c3ed37b9007cd375224da29171c212d0746e3863fe0b920465f57ff2c3bea7dfsize 676908123version https://git-lfs.github.com/spec/v1oid sha256:09df9e5c1a703baef390c0d4de1a3ad3a70ec352b22d03b4ab08e83ae36abb6esize 553004123version https://git-lfs.github.com/spec/v1oid sha256:5ab122a1fa0b3511bd07eb053c2d36bef84de3fddab9ce661eb546f8d91b1777size 404524123version https://git-lfs.github.com/spec/v1oid sha256:213eb33c084abdf2146f347b3f219d8161437b4029143593af469dc7c617c058size 741420123version https://git-lfs.github.com/spec/v1oid sha256:cb809dffdcf50c72c93263032315148516fecf65bf5f825dbf63e110192a4dabsize 632876123version https://git-lfs.github.com/spec/v1oid sha256:2074d1bea6bdc2893318908fd1a6fcbbeda8797212a19a3ff278be3eab0df5a6size 677932123version https://git-lfs.github.com/spec/v1oid sha256:2feef3b52a109014ad5fd285659ec1ef89876b1cb461cd2deeb111bd05f60609size 544812123version https://git-lfs.github.com/spec/v1oid sha256:c6bae1809a5bc337d9f39c433586da0c0283d2610f0f01f366f821fba4520afdsize 402476123version https://git-lfs.github.com/spec/v1oid sha256:bcfce563d7a10826e7e8805ed9878498c67903026bb5235cab9757b3b772fdd4size 702508.gitattributes+19
LICENSEAdded+202
README.mdAdded+380
bin/linux-aarch64/eehAdded+3
bin/linux-x86_64/eehAdded+3
bin/macos-arm64/eehAdded+3
demo/404.htmlAdded+8
demo/index.htmlAdded+247
demo/model/eeh-dict.bin.gzAdded+3
demo/model/eeh.safetensors.gzAdded+3
demo/pkg/eeh_wasm.jsAdded+474
demo/pkg/eeh_wasm_bg.wasmAdded+3
demo/player.jsAdded+69
demo/worker.jsAdded+149
eeh-dict.binAdded+3
eeh-f32.safetensorsAdded+3
eeh.safetensorsAdded+3
eval/metrics.jsonlAdded
eval/report.jsonAdded
include/eeh.hAdded+270
lib/linux-aarch64/libeeh_ffi.soAdded+3
lib/linux-x86_64/libeeh_ffi.soAdded+3
lib/macos-arm64/libeeh_ffi.dylibAdded+3
looped.pngAdded

python/eeh-0.2.0-py3-none-macosx_11_0_arm64.whlAdded+3
python/eeh-0.2.0-py3-none-manylinux_2_28_aarch64.whlAdded+3
python/eeh-0.2.0-py3-none-manylinux_2_28_x86_64.whlAdded+3
samples/F1-hello.wavAdded+3
samples/F1-numbers.wavAdded+3
samples/F1-polite.wavAdded+3
samples/F1-question.wavAdded+3
samples/F1-story.wavAdded+3
samples/M1-hello.wavAdded+3
samples/M1-numbers.wavAdded+3
samples/M1-polite.wavAdded+3
samples/M1-question.wavAdded+3
samples/M1-story.wavAdded+3