@met4citizen/headtts 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mika Suominen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,546 @@
1
+ # <img src="logo.png" width="100"/>&nbsp; HeadTTS
2
+
3
+ **HeadTTS** is a free JavaScript text-to-speech (TTS) solution that
4
+ provides timestamps and Oculus visemes for lip-sync, in addition
5
+ to audio output (WAV/PCM). It uses
6
+ [Kokoro](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX-timestamped)
7
+ neural model and voices, and inference can run entirely in
8
+ the browser (via WebGPU or WASM), or alternatively
9
+ on a Node.js WebSocket/RESTful server (CPU-based).
10
+
11
+ - **Pros**: Free. Doesn't require a server in in-browser mode.
12
+ WebGPU support. Uses neural voices with a StyleTTS 2 model.
13
+ Great for lip-sync use cases and fully compatible with the
14
+ [TalkingHead](https://github.com/met4citizen/TalkingHead).
15
+ MIT licensed, doesn't use eSpeak NG or any other GPL-licensed
16
+ module.
17
+
18
+ - **Cons**: WebGPU is only supported by default in Chrome and Edge
19
+ desktop browsers. Takes time to load (the first time) and uses
20
+ a lot of memory. WebGPU support in onnxruntime-node is still experimental
21
+ and not released, so server-side inference is relatively slow. English
22
+ is currently the only supported language.
23
+
24
+ **If you're using a Chrome or Edge desktop browser, check out the
25
+ [In-browser Demo](https://met4citizen.github.io/HeadTTS/)!**
26
+
27
+ The project uses [websockets/ws](https://github.com/websockets/ws) (MIT License),
28
+ [hugginface/transformers.js](https://github.com/huggingface/transformers.js/)
29
+ (Apache 2.0 License) and
30
+ [onnx-community/Kokoro-82M-v1.0-ONNX-timestamped](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX-timestamped)
31
+ (Apache 2.0 License) as runtime dependencies. For information on
32
+ language modules and dictionaries, see Appendix B. Using
33
+ [jest](https://jestjs.io) for testing.
34
+
35
+ You can find the list of supported English voices and voice samples
36
+ [here](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX-timestamped#voicessamples).
37
+
38
+ ---
39
+
40
+ # In-browser Module: `headtts.mjs`
41
+
42
+ The HeadTTS JavaScript module enables in-browser text-to-speech
43
+ using Module Web Workers and WebGPU/WASM inference. Alternatively, it can
44
+ connect to and use the HeadTTS Node.js WebSocket/RESTful server.
45
+
46
+ Create a new `HeadTTS` class instance:
47
+
48
+ ```javascript
49
+ import { HeadTTS } from "./modules/headtts.mjs";
50
+
51
+ const headtts = new HeadTTS({
52
+ endpoints: ["ws://127.0.0.1:8882", "webgpu"], // Endpoints in order of priority
53
+ languages: ['en-us'], // Language modules to pre-load (in-browser)
54
+ voices: ["af_bella", "am_fenrir"] // Voices to pre-load (in-browser)
55
+ });
56
+ ```
57
+
58
+ <details>
59
+ <summary>Click to see the options.</summary>
60
+
61
+ Option | Description | Default value
62
+ --- | --- | ---
63
+ `endpoints` | List of WebSocket/RESTful servers or backends `webgpu` or `wasm`, in order of priority. If one fails, the next is used. | `["webgpu",`<br>` "wasm"]`
64
+ `audioCtx` | Audio context for creating audio buffers. If `null`, a new one is created. | `null`
65
+ `transformersModule` | URL of the `transformers.js` module to load. | `"https://cdn.jsdelivr.net/npm/`<br>`@huggingface/transformers@3.4.2`<br>`/dist/transformers.min.js"`
66
+ `model` | Kokoro text-to-speech ONNX model (timestamped) used for in-browser inference. | `"onnx-community/`<br>`Kokoro-82M-v1.0-ONNX-timestamped"`
67
+ `dtypeWebgpu` | Data type precision for WebGPU inference: `"fp32"` (recommended), `"fp16"`, `"q8"`, `"q4"`, or `"q4f16"`. | `"fp32"`
68
+ `dtypeWasm` | Data type precision for WASM inference: `"fp32"`, `"fp16"`, `"q8"`, `"q4"`, or `"q4f16"`. | `"q4"`
69
+ `styleDim` | Style embedding dimension for inference. | `256`
70
+ `audioSampleRate` | Audio sample rate in Hz for inference. | `24000`
71
+ `frameRate` | Frame rate in FPS for inference. | `40`
72
+ `languages` | Language modules to be pre-loaded. | [`"en-us"`]
73
+ `dictionaryURL` | URL to language dictionaries. Set to `null` to disable dictionaries. | `"../dictionaries"`
74
+ `voiceURL` | URL for loading voices. | `"https://huggingface.co/`<br>`onnx-community/`<br>`Kokoro-82M-v1.0-ONNX/`<br>`resolve/main/voices"`
75
+ `voices` | Voices to preload (e.g., `["af_bella", "am_fenrir"]`). | `[]`
76
+ `splitSentences` | Whether to split text into sentences. | `true`
77
+ `splitLength` | Maximum length (in characters) of each text chunk. | `500`
78
+ `deltaStart` | Adjustment (in ms) to viseme start times. | `-10`
79
+ `deltaEnd` | Adjustment (in ms) to viseme end times. | `10`
80
+ `defaultVoice` | Default voice to use. | `"af_bella"`
81
+ `defaultLanguage` | Default language to use. | `"en-us"`
82
+ `defaultSpeed` | Speaking speed. Range: 0.25–4. | `1`
83
+ `defaultAudioEncoding` | Default audio format: `"wav"` or `"pcm"` (PCM 16-bit LE). | `"wav"`
84
+ `trace` | Bitmask for debugging subsystems (`0`=none, `255`=all):<br><ul><li>Bit 0 (1): Connection</li><li>Bit 1 (2): Messages</li><li>Bit 2 (4): Events</li><li>Bit 3 (8): G2P</li><li>Bit 4 (16): Language modules</li></ul> | `0`
85
+
86
+ Note: Model related options apply only to in-browser inference.
87
+ If inference is performed on a server, server-specific
88
+ settings will apply instead.
89
+
90
+ </details>
91
+
92
+ Connect to the first supported/available endpoint:
93
+
94
+ ```javascript
95
+ try {
96
+ await headtts.connect();
97
+ } catch(error) {
98
+ console.error(error);
99
+ }
100
+ ```
101
+
102
+ Make an `onmessage` event handler to handle response messages. In this
103
+ example, we use
104
+ [TalkingHead](https://github.com/met4citizen/TalkingHead) instance `head`
105
+ to play the incoming audio and lip-sync data:
106
+
107
+ ```javascript
108
+ // Speak and lipsync
109
+ headtts.onmessage = (message) => {
110
+ if ( message.type === "audio" ) {
111
+ try {
112
+ head.speakAudio( message.data, {}, (word) => {
113
+ console.log(word);
114
+ });
115
+ } catch(error) {
116
+ console.log(error);
117
+ }
118
+ } else if ( message.type === "error" ) {
119
+ console.error("Received error message, error=", message.data.error);
120
+ }
121
+ }
122
+ ```
123
+
124
+ <details>
125
+ <summary>Click to see all the available class events.</summary>
126
+
127
+ Event handler | Description
128
+ --- | ---
129
+ `onstart` | Triggered when the first message is added and all message queues were previously empty.
130
+ `onmessage` | Handles incoming messages of type `audio` or `error`. For details, see the API section.
131
+ `onend` | Triggered when all message queues become empty.
132
+ `onerror` | Handles system or class-level errors. If this handler is not set, such errors are thrown as exceptions. **Note:** Errors related to TTS conversion are sent to the `onmessage` handler (if defined) as messages of type `error`.
133
+
134
+ </details>
135
+
136
+ Setup the voice only when you need it to change:
137
+
138
+ ```javascript
139
+ headtts.setup({
140
+ voice: "af_bella",
141
+ language: "en-us",
142
+ speed: 1,
143
+ audioEncoding: "wav"
144
+ });
145
+ ```
146
+
147
+ Synthesize speech:
148
+
149
+ ```javascript
150
+ headtts.synthesize({
151
+ input: "Test sentence."
152
+ });
153
+ ```
154
+
155
+ The above approach relies on `onmessage` event handler to
156
+ receive and handle response messages and it is the recommended
157
+ approach for real-time use cases. An alternative approach is to
158
+ `await` for all the related audio messages:
159
+
160
+ ```javascript
161
+ try {
162
+ const messages = await headtts.synthesize({
163
+ input: "Some long text..."
164
+ });
165
+ console.log(messages); // [{type: 'audio', data: {…}, ref: 1}, {…}, ...]
166
+ } catch(error) {
167
+ console.error(error);
168
+ }
169
+ ```
170
+
171
+ <details>
172
+ <summary>Click to see all the class method.</summary>
173
+
174
+ Method | Description
175
+ --- | ---
176
+ `connect( settings=null, onprogress=null, onerror=null )` | Connects to the specified set of `endpoints` set in constructor or within the optinal `settings` object. If the `settings` parameter is provided, it forces a reconnection. The `onprogress` callback handles `ProgressEvent` events, while the `onerror` callback handles system-level error events. Returns a promise. **Note:** When connecting to a RESTful server, the method sends a hello message and considers the connection established only if a text response starting with `HeadTTS` is received.
177
+ `clear()` | Clears all work queues and resolves all promises.
178
+ `setup( data, onerror=null )` | Adds a new setup request to the work queue. See the API section for the supported `data` properties. Returns a promise.
179
+ `synthesize( data, onmessage=null, onerror=null )` | Adds a new synthesize request to the work queue. If event handlers are provided, they override other handlers. Returns a promise that resolves with a sorted array of related `audio` or `error` messages.
180
+
181
+ </details>
182
+
183
+ <details>
184
+ <summary>Click to see the available input types for synthesize request.</summary>
185
+
186
+ The `input` parameter can be a string or, alternatively, an array
187
+ of strings or inputs items.
188
+
189
+ Type | Description | Example
190
+ ---|---|---
191
+ `text` |  Speak the text in `value`. This is equivalent to giving a pure string input. | <pre><code>{<br> type: "text",<br> value: "This is an example."<br>}</code></pre>
192
+ `speech` |  Speak the text in `value` with corresponding subtitles in `subtitles` (optional). This type allows the spoken words to be different that the subtitles. | <pre><code>{<br> type: "text",<br> value: "One two three",<br> subtitles: "123"<br>}</code></pre>
193
+ `phonetic` | Speak the model specific phonetic alphabets in `value` with corresponding `subtitles` (optional). | <pre><code>{<br> type: "phonetic",<br> value: "mˈɜɹʧəndˌIz",<br> subtitles: "merchandise"<br>}</code></pre>
194
+ `characters` | Speak the `value` character-by-character with corresponding `subtitles` (optional). Supports also numbers that are read digit-by-digit. | <pre><code>{<br> type: "characters",<br> value: "ABC-123-8",<br> subtitles: "ABC-123-8"<br>}</code></pre>
195
+ `number` | Speak the number in `value` with corresponding `subtitles` (optional). The number should presented as a string. | <pre><code>{<br> type: "number",<br> value: "123.5",<br> subtitles: "123.5"<br>}</code></pre>
196
+ `date` | Speak the date in `value` with corresponding `subtitles` (optional). The date is presented as milliseconds from epoch. | <pre><code>{<br> type: "date",<br> value: Date.now(),<br> subtitles: "02/05/2025"<br>}</code></pre>
197
+ `time` | Speak the time in `value` with corresponding `subtitles` (optional). The time is presented as milliseconds from epoch. | <pre><code>{<br> type: "time",<br> value: Date.now(),<br> subtitles: "6:45 PM"<br>}</code></pre>
198
+ `break` | The length of the break in milliseconds in `value` with corresponding `subtitles` (optional). | <pre><code>{<br> type: "break",<br> value: 2000,<br> subtitles: "..."<br>}</code></pre>
199
+
200
+ *TODO: Add support for `audio` type.*
201
+
202
+ An example using an array of input items:
203
+
204
+ ```javascript
205
+ {
206
+ type: "synthesize",
207
+ id: 14, // Unique request identifier.
208
+ data: {
209
+ input: [
210
+ "There were ",
211
+ { type: "speech", value: "over two hundred ", subtitles: ">200 " },
212
+ "items of",
213
+ { type: "phonetic", value: "mˈɜɹʧəndˌIz ", subtitles: "merchandise " },
214
+ "on sale."
215
+ ]
216
+ }
217
+ }
218
+ ```
219
+
220
+ </details>
221
+
222
+ ---
223
+
224
+ # NodeJS WebSocket/RESTful Server: `headtts-node.mjs`
225
+
226
+ Install using NPM (requires Node.js v20+):
227
+
228
+ ```bash
229
+ npm install @met4citizen/headtts
230
+ ```
231
+
232
+ Start the server:
233
+
234
+ ```bash
235
+ npm start
236
+ ```
237
+
238
+ <details>
239
+ <summary>Click to see the command line options.</summary>
240
+
241
+ Option|Description|Default
242
+ ---|---|---
243
+ `--config [file]` | JSON configuration file name. | `./headtts-node.json`
244
+ `--trace [0-255]` | Bitmask for debugging subsystems (`0`=none, `255`=all):<br><ul><li>Bit 0 (1): Connection</li><li>Bit 1 (2): Messages</li><li>Bit 2 (4): Events</li><li>Bit 3 (8): G2P</li><li>Bit 4 (16): Language modules</li></ul> | `0`
245
+
246
+ An example:
247
+
248
+ ```bash
249
+ node ./modules/headtts-node.mjs --trace 16
250
+ ```
251
+
252
+ </details>
253
+
254
+ <details>
255
+ <summary>Click to see the configuration file options</summary>
256
+
257
+ Property|Description|Default
258
+ ---|---|---
259
+ `server.port` | The port number the server listens on. | `8882`
260
+ `server.certFile` | Path to the certificate file. | `null`
261
+ `server.keyFile` | Path to the certificate key file. | `null`
262
+ `server.websocket` | Enable the WebSocket server. | `true`
263
+ `server.rest` | Enable the RESTful API server. | `true`
264
+ `server.connectionTimeout` | Timeout duration for idle connections in milliseconds. | `20000`
265
+ `server.corsOrigin` | Value for the `Access-Control-Allow-Origin` header. If `null`, CORS will not be enabled. | `*`
266
+ `tts.threads` | Number of text-to-speech worker threads, ranging from 1 to the number of CPU cores. | `1`
267
+ `tts.transformersModule` | Name of the transformers.js module to use. | `"@huggingface/transformers"`
268
+ `tts.model` | The timestamped Kokoro TTS ONNX model. | `"onnx-community/`<br>`Kokoro-82M-v1.0-ONNX-timestamped"`
269
+ `tts.dtype` | The data type precision used for inference. Available options: `"fp32"`, `"fp16"`, `"q8"`, `"q4"`, or `"q4f16"`. | `"fp32"`
270
+ `tts.device` | Computation backend to use. Currently, the only available option for Node.js server is `"cpu"`. | `"cpu"`
271
+ `tts.styleDim` | The embedding dimension for style. | `256`
272
+ `tts.audioSampleRate` | Audio sample rate in Hertz (Hz). | `24000`
273
+ `tts.frameRate` | Frame rate in frames per second (FPS). | `40`
274
+ `tts.languages` | A list of languages to preload. | [`"en-us"`]
275
+ `tts.dictionaryPath` | Path to the language modules. If `null`, dictionaries will not be used. | `"./dictionaries"`
276
+ `tts.voicePath` | Path to the voice files. | `"./voices"`
277
+ `tts.voices` | Array of voices to preload, e.g., `["af_bella","am_fenrir"]`. | `[]`
278
+ `tts.deltaStart` | Adjustment (in ms) to viseme start times. | `-10`
279
+ `tts.deltaEnd` | Adjustment (in ms) to viseme end times. | `10`
280
+ `tts.defaults.voice` | Default voice to use. | `"af_bella"`
281
+ `tts.defaults.language` | Default language to use. Supported options: `"en-us"`. | `"en-us"`
282
+ `tts.defaults.speed` | Speaking speed. Range: 0.25–4. | `1`
283
+ `tts.defaults.audioEncoding` | Default audio encoding format. Supported options are `"wav"` and `"pcm"` (PCM 16bit LE). | `"wav"`
284
+ `trace` | Bitmask for debugging subsystems (`0`=none, `255`=all):<br><ul><li>Bit 0 (1): Connection</li><li>Bit 1 (2): Messages</li><li>Bit 2 (4): Events</li><li>Bit 3 (8): G2P</li><li>Bit 4 (16): Language modules</li></ul> | `0`
285
+
286
+ </details>
287
+
288
+ ---
289
+
290
+ # Appendix A: Server API reference
291
+
292
+ ## WebSocket API
293
+
294
+ Every WebSocket request must have a unique identifier, `id`. The server uses
295
+ a Web Worker thread pool, and because work is done in parallel,
296
+ the order of responses may vary. Therefore, each response includes
297
+ a `ref` property that identifies the original request, allowing
298
+ the order to be restored if necessary. The JS client class handles this
299
+ automatically.
300
+
301
+ ### Request: `setup`
302
+
303
+ ```javascript
304
+ {
305
+ type: "setup",
306
+ id: 12, // Unique request identifier.
307
+ data: {
308
+ voice: "af_bella", // Voice name (optional)
309
+ language: "en-us", // Language (optional)
310
+ speed: 1, // Speed (optional)
311
+ audioEncoding: 'wav' // "wav" or "pcm" (PCM 16bit LE) (optional)
312
+ }
313
+ }
314
+ ```
315
+
316
+ ### Request: `synthesize`
317
+
318
+ ```javascript
319
+ {
320
+ type: "synthesize",
321
+ id: 13, // Unique request identifier.
322
+ data: {
323
+ input: "This is an example." // String or array of input items
324
+ }
325
+ }
326
+ ```
327
+
328
+ The response message for `synthesize` request is either `error` or `audio`.
329
+
330
+ ### Response: `error`
331
+
332
+ ```javascript
333
+ {
334
+ type: "error",
335
+ ref: 13, // Original request id
336
+ data: {
337
+ error: "Error loading voice 'af_bella'."
338
+ }
339
+ }
340
+ ```
341
+
342
+ ### Response: `audio`
343
+
344
+ Returns an audio object metadata that can be passed on the TalkingHead
345
+ `speakAudio` method once the audio content itself has been added.
346
+
347
+ ```javascript
348
+ {
349
+ type: "audio",
350
+ ref: 13,
351
+ data: {
352
+ words: ["This ","is ","an ","example."],
353
+ wtimes: [443, 678, 780, 864],
354
+ wdurations: [192 ,91 ,52 ,868],
355
+ visemes: ["TH", "I", "SS", "I", "SS", "aa", "nn", "SS", "aa", "PP", "PP", "E", "DD"],
356
+ vtimes: [443, 494, 550, 678, 729, 780, 801, 989, 1126, 1175, 1225, 1275, 1354],
357
+ vdurations: [61, 66, 85, 61, 40, 31, 31, 69, 59, 60, 60, 89, 378],
358
+ audioEncoding: "wav"
359
+ }
360
+ }
361
+ ```
362
+
363
+ The actual audio content will be delivered after this message as
364
+ binary data (see the next response message).
365
+
366
+ ### Response: Binary (ArrayBuffer)
367
+
368
+ Binary data as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
369
+ related to the previous `audio` message. Depending on the set audio encoding,
370
+ either a WAV file (`wav`) or a chunk of raw PCM 16bit LE samples (`pcm`).
371
+
372
+ ## RESTful API
373
+
374
+ RESTful server API is a more simple alternative for WebSocket API.
375
+
376
+ ### POST `/v1/synthesize`
377
+
378
+ JSON | Description
379
+ ---|---
380
+ `input` | Input to synthesize. String or an array of input items. For a string of text, maximum 500 characters.
381
+ `voice` | Voice name.
382
+ `language` | Language code.
383
+ `speed` | Speed of speech.
384
+ `audioEncoding` | Either "wav" for WAV file or "pcm" for raw PCM 16bit LE audio.
385
+
386
+ OK response:
387
+
388
+ JSON|Description
389
+ ---|---
390
+ `audio` | AudioBuffer for `"wav"` audio encoding, ArrayBuffer of raw PCM 16bit LE samples for `"pcm"` audio encoding.
391
+ `words` | Array of words.
392
+ `wtimes` | Array of word starting times for `words` in milliseconds.
393
+ `wdurations` | Array of word durations for `words` in milliseconds.
394
+ `visemes` | Array of Oculus viseme IDs: `'aa'`, `'E'`, `'I'`, `'O'`, `'U'`, `'PP'`, `'SS'`, `'TH'`, `'CH'`, `'FF'`, `'kk'`, `'nn'`, `'RR'`, `'DD'`, `'sil'`.
395
+ `vtimes` | Array of viseme starting times for `visemes` in milliseconds.
396
+ `vdurations` | Array of viseme durations for `visemes` in milliseconds.
397
+ `audioEncoding` | Audio encoding: `"wav"` or `"pcm"`.
398
+
399
+ Error response:
400
+
401
+ JSON|Description
402
+ ---|---
403
+ `error` | Error message string
404
+
405
+ ---
406
+
407
+ # Appendix B: Language modules and dictionaries
408
+
409
+ ### American English, `en-us`
410
+
411
+ The American English language module is based on the
412
+ [CMU Pronunciation Dictionary](http://www.speech.cs.cmu.edu/cgi-bin/cmudict)
413
+ from Carnegie Mellon University, containing over 134,000 words and their
414
+ pronunciations. The original dataset is provided under a simplified
415
+ BSD license, allowing free use for any research or commercial purpose.
416
+
417
+ In the [Kokoro](https://github.com/hexgrad/kokoro) TTS model,
418
+ the American English language data was trained using the
419
+ [Misaki](https://github.com/hexgrad/misaki) G2P engine (en).
420
+ Therefore, the original [ARPAbet](https://en.wikipedia.org/wiki/ARPABET)
421
+ phonemes in the CMU dictionary have been converted to
422
+ [IPA](https://en.wikipedia.org/wiki/International_Phonetic_Alphabet)
423
+ and then to Misaki-compatible phonemes by applying the following mapping:
424
+
425
+ - `ɚ` → [ `ɜ`, `ɹ` ], `ˈɝ` → [ `ˈɜ`, `ɹ` ], `ˌɝ` → [ `ˌɜ`, `ɹ` ]
426
+ - `tʃ` → [ `ʧ` ], `dʒ` → [ `ʤ` ]
427
+ - `eɪ` → [ `A` ], `ˈeɪ` → [ `ˈA` ], `ˌeɪ` → [ `ˌA` ]
428
+ - `aɪ` → [ `I` ], `ˈaɪ` → [ `ˈI` ], `ˌaɪ` → [ `ˌI` ]
429
+ - `aʊ` → [ `W` ], `ˈaʊ` → [ `ˈW` ], `ˌaʊ` → [ `ˌW` ]
430
+ - `ɔɪ` → [ `Y` ], `ˈɔɪ` → [ `ˈY` ], `ˌɔɪ` → [ `ˌY` ]
431
+ - `oʊ` → [ `O` ], `ˈoʊ` → [ `ˈO` ], `ˌoʊ` → [ `ˌO` ]
432
+ - `əʊ` → [ `Q` ], `ˈəʊ` → [ `ˈQ` ], `ˌəʊ` → [ `ˌQ` ]
433
+
434
+ Note: During the dataset conversion, some vowels were reduced to reflect
435
+ casual speech since HeadTTS is primarily designed for conversational use.
436
+
437
+ The final dictionary is a plain text file with around 125,000 lines (2,8MB).
438
+ Lines starting with `;;;` are comments. Each other line represents
439
+ one word and its pronunciations. The word and its different possible
440
+ pronunciations are separated by a tab character `\t`. An example entry:
441
+
442
+ ```text
443
+ MERCHANDISE mˈɜɹʧəndˌIz
444
+ ```
445
+
446
+ Out-of-dictionary (OOD) words are converted using a rule-based algorithm based
447
+ on NRL Report 7948, *Automatic Translation of English Text to Phonetics
448
+ by Means of Letter-to-Sound Rules* (Elovitz et al., 1976). The report is
449
+ available [here](https://apps.dtic.mil/sti/pdfs/ADA021929.pdf).
450
+
451
+
452
+ ### Finnish, `fi`
453
+
454
+ > [!IMPORTANT]
455
+ > As of now, Finnish language is not supported by the Kokoro model.
456
+ You can use the `fi` language code with the English voices, but
457
+ the pronunciation will sound rather weird.
458
+
459
+ The phonemization of the Finnish language module is done by
460
+ an in-built algorithm. The algorithm doesn't require a pronunciation
461
+ dictionary, but it uses a compound word dictionary to get the secondary
462
+ stress marks right for compound words.
463
+
464
+ The dictionary used for compound words is based on
465
+ [The Dictionary of Contemporary Finnish](https://en.kotus.fi/dictionaries/#Dictionary-of-Contemporary-Finnish)
466
+ maintained by the Institute for the Languages of Finland. The original
467
+ dataset contains more than 100,000 entries and is open-sourced
468
+ under the CC BY 4.0 license.
469
+
470
+ The pre-processed compound word dictionary is a plain text file with
471
+ around 50,000 entries in 10,000 lines (~350kB). Lines starting
472
+ with `;;;` are comments. Each other line represents the first part
473
+ of a compound word and the first four letters of all possible
474
+ next words, all separated by a tab character `\t`. An example entry:
475
+
476
+ ```text
477
+ ALUMIINI FOLI KATT OKSI PAPE SEOS VENE VUOK
478
+ ```
479
+
480
+ ---
481
+
482
+ # Appendix C: Latency
483
+
484
+ In-browser TTS on WebGPU is 3x times faster than
485
+ real-time and approximately 10x faster than WASM. CPU inference on
486
+ a Node.js server performs surprisingly well, but increasing the thread
487
+ pool size worsens performance, so we need to wait for WebGPU support.
488
+ Quantization makes no significant difference, so I recommend using 32-bit
489
+ floating point precision (fp32) for the best audio quality unless
490
+ memory consumption becomes a concern.
491
+
492
+ Unofficial latency results using my own
493
+ [latency test app](https://github.com/met4citizen/HeadTTS/blob/main/tests/latency.html):
494
+
495
+ TTS Engine | Setup |`FIL`<sup>\[1]</sup>|`FBL`<sup>\[2]</sup>|`RTF`<sup>\[3]</sup>
496
+ ---|---|---|---|---
497
+ HeadTTS, in-browser | Chrome, WebGPU/fp32 | 9.4s | 958ms | 0.30
498
+ HeadTTS, in-browser | Edge, WebGPU/fp32 | 8.7s | 913ms | 0.28
499
+ HeadTTS, in-browser | Chrome, WASM/q4 | 88.4s | 8752ms | 2.87
500
+ HeadTTS, in-browser | Edge, WASM/q4 | 44.8s | 4437ms | 1.46
501
+ HeadTTS, server | WebSocket, CPU/fp32, 1 thread | 6.8s | 712ms | 0.22
502
+ HeadTTS, server | WebSocket, CPU/fp32, 4 threads | 6.0s | 2341ms | 0.20
503
+ HeadTTS, server | REST, CPU/fp32, 1 thread | 7.0s | 793ms | 0.23
504
+ HeadTTS, server | REST, CPU/fp32, 4 threads | 6.5s | 2638ms | 0.21
505
+ ElevenLabs | WebSocket | 4.8s | 977ms | 0.20
506
+ ElevenLabs | REST | 11.3s | 1097ms | 0.46
507
+ ElevenLabs | REST, Flash_v2_5 | 4.8s | 581ms | 0.22
508
+ Microsoft Azure TTS | Speech SDK, WebSocket | 1.1s | 274ms | 0.04
509
+ Google TTS | REST | 0.79s | 67ms | 0.03
510
+
511
+
512
+ <sup>\[1]</sup> *Finish latency*: Total time from sending text input to receiving
513
+ the full audio.
514
+
515
+ <sup>\[2]</sup> *First byte/part/sentence latency*: Time from sending the text input
516
+ to receiving the first playable byte/part/sentence of audio.
517
+ Note: This measure is not comparable across all models, since some
518
+ solutions use streaming, some not.
519
+
520
+ <sup>\[3]</sup> *Real-time factor* = Time to generate full audio / Duration of the full
521
+ audio. If RTF < 1, synthesis is faster than real-time (i.e., good).
522
+
523
+ <details>
524
+ <summary>Click here to see the test setup.</summary>
525
+
526
+ **Test setup**: Macbook Air M2 laptop, 8 cores, 16GB memory,
527
+ macOS Sequoia 15.3.2, Metal2 GPU 10 cores, 300/50 Mbit/s internet connection.
528
+ The latest Google Chrome/Edge desktop browsers.
529
+
530
+ All test cases use WAV or raw PCM 16bit LE format and the "List 1" of the
531
+ [Harvard Sentences](https://www.cs.columbia.edu/~hgs/audio/harvard.html):
532
+
533
+ ```text
534
+ The birch canoe slid on the smooth planks.
535
+ Glue the sheet to the dark blue background.
536
+ It's easy to tell the depth of a well.
537
+ These days a chicken leg is a rare dish.
538
+ Rice is often served in round bowls.
539
+ The juice of lemons makes fine punch.
540
+ The box was thrown beside the parked truck.
541
+ The hogs were fed chopped corn and garbage.
542
+ Four hours of steady work faced us.
543
+ A large size in stockings is hard to sell.
544
+ ```
545
+
546
+ </details>