@met4citizen/headtts 0.3.1 → 1.0.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # <img src="logo.png" width="100"/>&nbsp; HeadTTS
2
2
 
3
3
  **HeadTTS** is a free JavaScript text-to-speech (TTS) solution that
4
- provides timestamps and Oculus visemes for lip-sync, in addition
4
+ provides phoneme-level timestamps and Oculus visemes for lip-sync, in addition
5
5
  to audio output (WAV/PCM). It uses
6
6
  [Kokoro](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX-timestamped)
7
7
  neural model and voices, and inference can run entirely in
@@ -16,7 +16,7 @@ MIT licensed, doesn't use eSpeak NG or any other GPL-licensed
16
16
  module.
17
17
 
18
18
  - **Cons**: WebGPU is only supported by default in Chrome and Edge
19
- desktop browsers. Takes time to load (the first time) and uses
19
+ desktop browsers. Takes time to load on first load and uses
20
20
  a lot of memory. WebGPU support in onnxruntime-node is still experimental
21
21
  and not released, so server-side inference is relatively slow. English
22
22
  is currently the only supported language.
@@ -25,7 +25,7 @@ is currently the only supported language.
25
25
  [In-browser Demo](https://met4citizen.github.io/HeadTTS/)!**
26
26
 
27
27
  The project uses [websockets/ws](https://github.com/websockets/ws) (MIT License),
28
- [hugginface/transformers.js](https://github.com/huggingface/transformers.js/)
28
+ [hugginface/transformers.js (with ONNX Runtime)](https://github.com/huggingface/transformers.js/)
29
29
  (Apache 2.0 License) and
30
30
  [onnx-community/Kokoro-82M-v1.0-ONNX-timestamped](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX-timestamped)
31
31
  (Apache 2.0 License) as runtime dependencies. For information on
@@ -56,7 +56,7 @@ const headtts = new HeadTTS({
56
56
  ```
57
57
 
58
58
  <details>
59
- <summary>CLICK HERE to see all the options.</summary>
59
+ <summary>CLICK HERE to see all the OPTIONS.</summary>
60
60
 
61
61
  Option | Description | Default value
62
62
  --- | --- | ---
@@ -115,6 +115,8 @@ headtts.onmessage = (message) => {
115
115
  } catch(error) {
116
116
  console.log(error);
117
117
  }
118
+ } else if ( message.type === "custom" ) {
119
+ console.error("Received custom message, data=", message.data);
118
120
  } else if ( message.type === "error" ) {
119
121
  console.error("Received error message, error=", message.data.error);
120
122
  }
@@ -122,18 +124,18 @@ headtts.onmessage = (message) => {
122
124
  ```
123
125
 
124
126
  <details>
125
- <summary>CLICK HERE to see all the available class events.</summary>
127
+ <summary>CLICK HERE to see all the available class EVENTS.</summary>
126
128
 
127
129
  Event handler | Description
128
130
  --- | ---
129
131
  `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.
132
+ `onmessage` | Handles incoming messages of type `audio`, `error` and `custom`. For details, see the API section.
131
133
  `onend` | Triggered when all message queues become empty.
132
134
  `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
135
 
134
136
  </details>
135
137
 
136
- Setup the voice only when you need it to change:
138
+ Setup the voice:
137
139
 
138
140
  ```javascript
139
141
  headtts.setup({
@@ -144,7 +146,11 @@ headtts.setup({
144
146
  });
145
147
  ```
146
148
 
147
- Synthesize speech:
149
+ The HeadTTS client is stateful, so you don't need to call setup again
150
+ unless you want to change a setting. For example, if you want to increase
151
+ the speed, simply call `headtts.setup({ speed: 1.5 })`.
152
+
153
+ Synthesize speech using the current voice setup:
148
154
 
149
155
  ```javascript
150
156
  headtts.synthesize({
@@ -168,28 +174,16 @@ try {
168
174
  }
169
175
  ```
170
176
 
171
- <details>
172
- <summary>CLICK HERE 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>
177
+ The `input` property can be a string or, alternatively, an array
178
+ of strings or inputs items.
182
179
 
183
180
  <details>
184
- <summary>CLICK HERE 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.
181
+ <summary>CLICK HERE to see the available input ITEM TYPES.</summary>
188
182
 
189
183
  Type | Description | Example
190
184
  ---|---|---
191
185
  `text` |  Speak the text in `value`. This is equivalent to giving a pure string input. | <pre>{<br> type: "text",<br> value: "This is an example."<br>}</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>{<br> type: "text",<br> value: "One two three",<br> subtitles: "123"<br>}</pre>
186
+ `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>{<br> type: "speech",<br> value: "One two three",<br> subtitles: "123"<br>}</pre>
193
187
  `phonetic` | Speak the model specific phonetic alphabets in `value` with corresponding `subtitles` (optional). | <pre>{<br> type: "phonetic",<br> value: "mˈɜɹʧəndˌIz",<br> subtitles: "merchandise"<br>}</pre>
194
188
  `characters` | Speak the `value` character-by-character with corresponding `subtitles` (optional). Supports also numbers that are read digit-by-digit. | <pre>{<br> type: "characters",<br> value: "ABC-123-8",<br> subtitles: "ABC-123-8"<br>}</pre>
195
189
  `number` | Speak the number in `value` with corresponding `subtitles` (optional). The number should presented as a string. | <pre>{<br> type: "number",<br> value: "123.5",<br> subtitles: "123.5"<br>}</pre>
@@ -219,6 +213,33 @@ An example using an array of input items:
219
213
 
220
214
  </details>
221
215
 
216
+ You can add a custom message to the message queue using
217
+ the `custom` method:
218
+
219
+ ```javascript
220
+ headtts.custom({
221
+ emoji: "😀"
222
+ });
223
+ ```
224
+
225
+ Custom messages can be used, for example, to synchronize
226
+ speech with animations, emojis, facial expressions, poses,
227
+ and/or gestures. You need to implement the custom
228
+ functionality yourself within the message handler.
229
+
230
+ <details>
231
+ <summary>CLICK HERE to see all the class METHODS.</summary>
232
+
233
+ Method | Description
234
+ --- | ---
235
+ `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.
236
+ `clear()` | Clears all work queues and resolves all promises.
237
+ `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.
238
+ `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 messages of type `"audio"` or `"error"`.
239
+ `custom( data, onmessage=null, onerror=null )` | Adds a new custom message to the work queue. If event handlers are provided, they override other handlers. Returns a promise that resolves with the related message of the type `"custom"`.
240
+
241
+ </details>
242
+
222
243
  ---
223
244
 
224
245
  # NodeJS WebSocket/RESTful Server: `headtts-node.mjs`
@@ -238,7 +259,7 @@ npm start
238
259
  ```
239
260
 
240
261
  <details>
241
- <summary>CLICK HERE to see the command line options.</summary>
262
+ <summary>CLICK HERE to see the COMMAND LINE OPTIONS.</summary>
242
263
 
243
264
  Option|Description|Default
244
265
  ---|---|---
@@ -254,7 +275,7 @@ node ./modules/headtts-node.mjs --trace 16
254
275
  </details>
255
276
 
256
277
  <details>
257
- <summary>CLICK HERE to see the configuration file options</summary>
278
+ <summary>CLICK HERE to see the configurable PROPERTIES.</summary>
258
279
 
259
280
  Property|Description|Default
260
281
  ---|---|---
@@ -374,6 +395,9 @@ either a WAV file (`wav`) or a chunk of raw PCM 16bit LE samples (`pcm`).
374
395
  ## RESTful API
375
396
 
376
397
  RESTful server API is a more simple alternative for WebSocket API.
398
+ The REST server is stateless, so voice parameters must be included
399
+ for each POST message. If you are using the HeadTTS client class,
400
+ it handles this internally.
377
401
 
378
402
  ### POST `/v1/synthesize`
379
403
 
@@ -523,7 +547,7 @@ solutions use streaming, some not.
523
547
  audio. If RTF < 1, synthesis is faster than real-time (i.e., good).
524
548
 
525
549
  <details>
526
- <summary>CLICK HERE here to see the test setup.</summary>
550
+ <summary>CLICK HERE here to see the TEST SETUP.</summary>
527
551
 
528
552
  **Test setup**: Macbook Air M2 laptop, 8 cores, 16GB memory,
529
553
  macOS Sequoia 15.3.2, Metal2 GPU 10 cores, 300/50 Mbit/s internet connection.
@@ -134,14 +134,16 @@ for( let i=0; i<config.tts.threads; i++ ) {
134
134
  if ( isTraceMessages ) {
135
135
  utils.trace( "OUT: -> REST Client, Error", message.data );
136
136
  }
137
- res.writeHead(422, { 'Content-Type': 'application/json' });
137
+ res.statusCode = 422;
138
+ res.setHeader('Content-Type', 'application/json');
138
139
  res.end(JSON.stringify(message.data));
139
140
  } else if ( message.type === "audio" ){
140
141
  if ( isTraceMessages ) {
141
142
  utils.trace( "OUT: -> REST Client, Audio", message.data );
142
143
  }
143
144
  message.data.audio = Buffer.from(message.data.audio).toString('base64');
144
- res.writeHead(200, { 'Content-Type': 'application/json' });
145
+ res.statusCode = 200;
146
+ res.setHeader('Content-Type', 'application/json');
145
147
  res.end(JSON.stringify(message.data));
146
148
  }
147
149
  }
@@ -249,7 +251,7 @@ function restHandler(req,res) {
249
251
 
250
252
  // Handle preflight (OPTIONS) requests
251
253
  if (req.method === 'OPTIONS') {
252
- res.writeHead(200);
254
+ res.statusCode = 200;
253
255
  return res.end();
254
256
  }
255
257
 
@@ -302,7 +304,8 @@ function restHandler(req,res) {
302
304
  if ( isTraceMessages ) {
303
305
  utils.trace( "OUT: -> REST Client, Error", err.message || "Internal error." );
304
306
  }
305
- res.writeHead(400, { 'Content-Type': 'application/json' });
307
+ res.statusCode = 400;
308
+ res.setHeader('Content-Type', 'application/json');
306
309
  res.end(JSON.stringify({
307
310
  error: (err.message || "Internal error.")
308
311
  }));
@@ -312,20 +315,20 @@ function restHandler(req,res) {
312
315
  if ( isTraceMessages ) {
313
316
  utils.trace( "OUT: -> REST Client, HELLO" );
314
317
  }
315
- res.writeHead(200);
318
+ res.statusCode = 200;
316
319
  res.end('HeadTTS v0.1.0');
317
320
  } else {
318
321
  if ( isTraceMessages ) {
319
322
  utils.trace( "OUT: REST -> Client Error, Not found." );
320
323
  }
321
- res.writeHead(404);
324
+ res.statusCode = 404;
322
325
  res.end('Not Found');
323
326
  }
324
327
  } else {
325
328
  if ( isTraceMessages ) {
326
329
  utils.trace( "OUT: -> REST Client, Error Not found." );
327
330
  }
328
- res.writeHead(404);
331
+ res.statusCode = 404;
329
332
  res.end('Not Found');
330
333
  }
331
334
  }
@@ -748,6 +748,45 @@ class HeadTTS {
748
748
  return Promise.all(deferredPromises);
749
749
  }
750
750
 
751
+ /**
752
+ * Add a new "custom" message to the IN work queue.
753
+ *
754
+ * @param {Object} data Setup request message
755
+ * @param {function} [onmessage=null] Callback for audio messages overriding event handler
756
+ * @param {function} [onerror=null] Callback for Error events overriding event handler
757
+ */
758
+ async custom( data, onmessage=null, onerror=null ) {
759
+ const isTraceMessages = this.settings.trace & utils.traceMask.messages;
760
+ if ( isTraceMessages ) {
761
+ utils.trace( "CUSTOM: APP -> HeadTTS, data=",data);
762
+ }
763
+
764
+ // Check data item
765
+ const events = [onerror, this.onerror];
766
+ if ( !data ) this.emit("error", new Error("Data not set."), events, true );
767
+
768
+ // New custom item
769
+ const item = {
770
+ message: {
771
+ type: "custom",
772
+ id: this.messageId++,
773
+ data: data
774
+ },
775
+ status: 0,
776
+ onmessage: onmessage,
777
+ onerror: onerror,
778
+ started: performance.now(),
779
+ deferred: new utils.Deferred()
780
+ };
781
+ this.queueIn.push(item);
782
+
783
+ // Process
784
+ this.processIn(onerror);
785
+
786
+ // Return the promise of the setup request
787
+ return item.deferred.promise;
788
+ }
789
+
751
790
  /**
752
791
  * Processes the IN work queue (fifo), sends the requests, and adds
753
792
  * the items to the OUT work queue to wait for responses.
@@ -780,6 +819,20 @@ class HeadTTS {
780
819
  }
781
820
  item.deferred.resolve();
782
821
 
822
+ } else if ( item.message.type === "custom" ) {
823
+
824
+ // Marked ready and add to output queue
825
+ item.status = 2;
826
+ this.items.set( item.message.id, item );
827
+ this.queueOut.push(item);
828
+
829
+ // Emit start event, if out queue was empty
830
+ if ( this.queueOut.length === 1 ) {
831
+ this.emit("start", null, [this.onstart]);
832
+ }
833
+
834
+ this.processOut();
835
+
783
836
  } else {
784
837
 
785
838
  // Add to output queue to wait for response
@@ -787,7 +840,7 @@ class HeadTTS {
787
840
  this.queueOut.push(item);
788
841
 
789
842
 
790
- // Emit event, if out queue was empty
843
+ // Emit start event, if out queue was empty
791
844
  if ( this.queueOut.length === 1 ) {
792
845
  this.emit("start", null, [this.onstart]);
793
846
  }
@@ -957,7 +1010,7 @@ class HeadTTS {
957
1010
  Object.assign(message.data, item.metadata || {});
958
1011
  const type = message.type;
959
1012
 
960
- if ( type === "audio" ) {
1013
+ if ( type === "audio" || type === "custom" ) {
961
1014
  this.emit("message", message, [item.onmessage, this.onmessage] );
962
1015
  item.deferred.resolve(message);
963
1016
  } else if ( type === "error" ) {
@@ -966,7 +1019,7 @@ class HeadTTS {
966
1019
  item.deferred.resolve(message);
967
1020
  }
968
1021
 
969
- // Emit event
1022
+ // Emit end event
970
1023
  if ( this.queueOut.length === 0 && this.queueIn.length === 0 ) {
971
1024
  this.emit("end",null,[this.onend]);
972
1025
  }
@@ -250,9 +250,8 @@ class LanguageBase {
250
250
  break;
251
251
 
252
252
  case "break":
253
- // TODO: Figure out better way to add breaks
254
- let cnt = Math.max(2, Math.min( part.value / 500, 10 ));
255
- part.phonemes = Array(cnt).fill(".").join("") + " ";
253
+ part.phonemes = " ";
254
+ part.silence = part.value;
256
255
  break;
257
256
 
258
257
  // Leave other types to language specific implementation
@@ -363,7 +362,7 @@ class LanguageBase {
363
362
  * start and end indices respectively.
364
363
  *
365
364
  * @param {string|Object[]} input Input element
366
- * @return {Object} `phonemes` array and TalkingHead `metadata` template
365
+ * @return {Object} `phonemes` array, TalkingHead `metadata` template, and `silences`
367
366
  */
368
367
  generate(input) {
369
368
 
@@ -373,6 +372,7 @@ class LanguageBase {
373
372
  words: [], wtimes: [], wdurations: [],
374
373
  visemes: [], vtimes: [], vdurations: []
375
374
  };
375
+ const silences = [];
376
376
 
377
377
  if ( this.settings.trace ) {
378
378
  utils.trace( 'Generate start, input=', input );
@@ -452,15 +452,22 @@ class LanguageBase {
452
452
  }
453
453
  }
454
454
  metadata.wdurations.push( phonemes.length );
455
+ if ( part.hasOwnProperty("silence") ) {
456
+ silences.push( [ phonemes.length, part.silence ] );
457
+ }
455
458
 
456
459
  });
457
460
 
458
461
  if ( this.settings.trace ) {
459
- utils.trace( 'Generate end, output=', { phonemes, metadata } );
462
+ utils.trace( 'Generate end, output=', {
463
+ phonemes: utils.deepCopy(phonemes),
464
+ metadata: utils.deepCopy(metadata),
465
+ silences: utils.deepCopy(silences)
466
+ });
460
467
  }
461
468
 
462
469
  // Output
463
- return { phonemes, metadata };
470
+ return { phonemes, metadata, silences };
464
471
 
465
472
  }
466
473
 
package/modules/utils.mjs CHANGED
@@ -46,6 +46,15 @@ export const traceMask = {
46
46
  language: 16
47
47
  };
48
48
 
49
+ /**
50
+ * Make a deep copy
51
+ * @param {any} o Object
52
+ * @return {any} Copy of the object.
53
+ */
54
+ export function deepCopy(o) {
55
+ return JSON.parse(JSON.stringify(o));
56
+ }
57
+
49
58
  /**
50
59
  * Write console trace.
51
60
  *
@@ -204,3 +213,45 @@ export function pcmToAudioBuffer(buf,samplerate,ctx) {
204
213
  audio.copyToChannel( floats, 0 , 0 );
205
214
  return audio;
206
215
  }
216
+
217
+ /**
218
+ * Inserts new segments of silence into a Float32Array of audio samples.
219
+ *
220
+ * @param {Float32Array} samples The original audio samples
221
+ * @param {number} sampleRate The sample rate of the audio in Hz (e.g., 44100)
222
+ * @param {number[][]} silences Sorted array of [time, duration] in milliseconds
223
+ * @returns {Float32Array} A new Float32Array with silence segments inserted.
224
+ */
225
+ export function insertSilences(samples, samplerate, silences) {
226
+
227
+ // Convert times and durations to number of samples
228
+ let nNewSamples = 0; // Total new samples
229
+ silences.forEach( x => {
230
+ x[0] = Math.floor((x[0] / 1000) * samplerate);
231
+ x[1] = Math.floor((x[1] / 1000) * samplerate);
232
+ nNewSamples += x[1];
233
+ });
234
+
235
+ // New Float32Array
236
+ const result = new Float32Array( samples.length + nNewSamples );
237
+
238
+ // Copy existing samples
239
+ let readPos = 0;
240
+ let writePos = 0;
241
+ silences.forEach( x => {
242
+ const start = Math.min(x[0], samples.length);
243
+ const len = start - readPos;
244
+ if (len > 0) {
245
+ result.set(samples.subarray(readPos, start), writePos);
246
+ readPos += len;
247
+ writePos += len;
248
+ }
249
+ writePos += x[1]; // Add silence
250
+ });
251
+ if (readPos < samples.length) {
252
+ result.set(samples.subarray(readPos), writePos);
253
+ }
254
+
255
+ return result;
256
+ }
257
+
@@ -250,8 +250,9 @@ async function loadVoice(s) {
250
250
  *
251
251
  * @param {Object} o TalkingHead audio object to be updated
252
252
  * @param {number[]} ds Token durations in frames
253
+ * @param {number[][]} silences Sorted array of [index,duration] of silences.
253
254
  */
254
- function updateTimestamps(o,ds) {
255
+ function updateTimestamps(o,ds,silences) {
255
256
 
256
257
  // Calculate starting times in milliseconds
257
258
  const scaler = 1000 / settings.frameRate; // From frames to milliseconds
@@ -264,6 +265,16 @@ function updateTimestamps(o,ds) {
264
265
  }
265
266
  times.push( Math.round(t) ); // Last entry
266
267
 
268
+ // Shift times based on silent periods and
269
+ // convert phoneme indexes to original starting times
270
+ const shifts = silences.map( x => [x[0]+1,x[1]] );
271
+ silences.forEach( x => x[0] = times[x[0]] - 20 );
272
+ shifts.forEach( x => {
273
+ for( let i=x[0]; i<times.length; i++ ) {
274
+ times[i] += x[1];
275
+ }
276
+ });
277
+
267
278
  // Calculate word times and durations (+1 because of $)
268
279
  len = o.words.length;
269
280
  for( let i=0; i<len; i++ ) {
@@ -312,7 +323,7 @@ async function process() {
312
323
  eventHandler.postMessage(item);
313
324
  continue;
314
325
  }
315
- const { phonemes, metadata } = language.generate(d.input);
326
+ const { phonemes, metadata, silences } = language.generate(d.input);
316
327
  if ( isTraceG2P ) {
317
328
  if ( typeof d.input === "string" ) {
318
329
  utils.trace( "G2P: " + d.input );
@@ -357,14 +368,19 @@ async function process() {
357
368
 
358
369
  // Generate timestamps from durations
359
370
  const durationsFrames = Array.from(durations.data);
360
- updateTimestamps( metadata, durationsFrames );
371
+ updateTimestamps( metadata, durationsFrames, silences );
361
372
 
362
373
  // Encode audio
374
+ const samplerate = settings.audioSampleRate;
375
+ let samples = waveform.data;
376
+ if ( silences.length ) {
377
+ samples = utils.insertSilences(samples, samplerate, silences)
378
+ }
363
379
  if ( d.audioEncoding === "pcm" ) {
364
- metadata.audio = utils.encodeAudio(waveform.data, settings.audioSampleRate, false);
380
+ metadata.audio = utils.encodeAudio(samples, samplerate, false);
365
381
  metadata.audioEncoding = "pcm";
366
382
  } else {
367
- metadata.audio = utils.encodeAudio(waveform.data, settings.audioSampleRate, true);
383
+ metadata.audio = utils.encodeAudio(samples, samplerate, true);
368
384
  metadata.audioEncoding = "wav";
369
385
  }
370
386
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@met4citizen/headtts",
3
- "version": "0.3.1",
3
+ "version": "1.0.0",
4
4
  "description": "HeadTTS: A free Javascript text-to-speech with timestamps and visemes.",
5
5
  "main": "modules/headtts.mjs",
6
6
  "type": "module",