@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.
@@ -0,0 +1,381 @@
1
+ import * as utils from "./utils.mjs";
2
+
3
+ // Dynamic imports
4
+ let StyleTextToSpeech2Model;
5
+ let AutoTokenizer;
6
+ let Tensor;
7
+
8
+ // Status flags
9
+ let filesProgress;
10
+ let isReady = false;
11
+ let isProcessing = false;
12
+ let isTraceConnection = false;
13
+ let isTraceG2P = false;
14
+ let isTraceLanguage = false;
15
+
16
+ // Other globals
17
+ let model = null; // Model
18
+ let tokenizer = null; // Tokenizer
19
+ const languages = new Map(); // Language modules
20
+ const voices = new Map(); // Voices
21
+ let settings = {}; // Settings
22
+ const queue = []; // Text-to-speech work queue
23
+
24
+ // Different event handler for Node.js and browsers
25
+ let eventHandler;
26
+ let fileReader;
27
+ const isNode = typeof import.meta !== 'undefined' &&
28
+ typeof import.meta.url === 'string' &&
29
+ import.meta.url.startsWith('file://');
30
+ if (isNode) {
31
+ const { readFile } = await import ('node:fs/promises');
32
+ fileReader = readFile;
33
+ const { parentPort } = await import('node:worker_threads');
34
+ eventHandler = parentPort;
35
+ } else {
36
+ eventHandler = self;
37
+ }
38
+
39
+ /**
40
+ * Event handler.
41
+ *
42
+ * @param {MessageEvent} ev Message event
43
+ */
44
+ eventHandler.onmessage = async (ev) => {
45
+ const message = ev.data;
46
+ if ( message.type === 'synthesize' ) {
47
+ queue.push(message);
48
+ process();
49
+ } else if ( message.type === 'setup' ) {
50
+ const o = message.data;
51
+ if ( typeof o === 'object' && !Array.isArray(o) && o !== null ) {
52
+ Object.assign(settings, o);
53
+ }
54
+ } else if ( message.type === 'connect' ) {
55
+ const o = message.data;
56
+ if ( typeof o === 'object' && !Array.isArray(o) && o !== null ) {
57
+ Object.assign(settings, o);
58
+ isTraceConnection = settings.trace & utils.traceMask.connection;
59
+ isTraceG2P = settings.trace & utils.traceMask.g2p;
60
+ isTraceLanguage = settings.trace & utils.traceMask.language;
61
+ }
62
+ connect();
63
+ } else {
64
+ console.error('HeadTTS Worker: Unknown message type "' + message.type + '".');
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Calculate and report progress
70
+ *
71
+ * @param {ProgressEvent} ev Progress event
72
+ */
73
+ function progress(ev) {
74
+
75
+ // Update data
76
+ if ( ev.status === 'progress' ) {
77
+ if ( !filesProgress.hasOwnProperty(ev.file) ) {
78
+ filesProgress[ev.file] = { loaded: 0, total: 0 };
79
+ }
80
+ filesProgress[ev.file].loaded = ev.loaded;
81
+ filesProgress[ev.file].total = ev.total;
82
+
83
+ // Calculate progress
84
+ let loaded = 0;
85
+ let total = 0;
86
+ for( let key in filesProgress ) {
87
+ loaded += filesProgress[key].loaded;
88
+ total += filesProgress[key].total;
89
+ }
90
+
91
+ // Update progress
92
+ eventHandler.postMessage({
93
+ type: "progress",
94
+ data: {
95
+ loaded: loaded,
96
+ total: total,
97
+ lengthComputable: ( total && (total > 0) && (total >= loaded) )
98
+ }
99
+ });
100
+
101
+ }
102
+
103
+ }
104
+
105
+ /**
106
+ * Set up the model and pre-load voices.
107
+ */
108
+ async function connect() {
109
+
110
+ if ( isTraceConnection ) {
111
+ utils.trace( 'Loading model "' + settings.transformersModule + '" started.' );
112
+ }
113
+
114
+ // Load modules dynamically
115
+ try {
116
+ ({ StyleTextToSpeech2Model, AutoTokenizer, Tensor } = await import(settings.transformersModule));
117
+ } catch(error) {
118
+ console.error("HeadTTS Worker: Importing modules failed, error=", error);
119
+ throw new Error("Importing modules failed.");
120
+ }
121
+
122
+ if ( isTraceConnection ) {
123
+ utils.trace( 'Loading model "' + settings.transformersModule + '" ended.' );
124
+ }
125
+
126
+ try {
127
+
128
+ // Clear progress data
129
+ filesProgress = {};
130
+
131
+ let voices = settings.voices || [];
132
+ const results = await Promise.all([
133
+ StyleTextToSpeech2Model.from_pretrained( settings.model, {
134
+ dtype: settings.dtype,
135
+ device: settings.device,
136
+ progress_callback: progress
137
+ }),
138
+ AutoTokenizer.from_pretrained( settings.model, {
139
+ progress_callback: progress
140
+ }),
141
+ ...settings.voices.map( async (x) => {
142
+ try {
143
+ loadVoice(x);
144
+ } catch(error) {
145
+ // Ignore errors on pre-load
146
+ }
147
+ }),
148
+ ...settings.languages.map( async (x) => {
149
+ try {
150
+ loadLanguage(x);
151
+ } catch(error) {
152
+ // Ignore errors on pre-load
153
+ }
154
+ })
155
+ ]);
156
+ model = results[0];
157
+ tokenizer = results[1];
158
+ } catch(error) {
159
+ console.error("HeadTTS Worker: Loading models failed, error=", error, " settings=", settings);
160
+ throw new Error("Loading models failed.");
161
+ }
162
+
163
+ // Ready
164
+ isReady = true;
165
+ eventHandler.postMessage({ type: "ready" });
166
+
167
+ // Process
168
+ process();
169
+ }
170
+
171
+ /**
172
+ * Load a specific language module.
173
+ *
174
+ * @param {string} lang Language, e.g. "en-us"
175
+ * @return {Object} Language module instance.
176
+ */
177
+ async function loadLanguage(lang) {
178
+ if ( languages.has(lang) ) {
179
+ return languages.get(lang);
180
+ } else {
181
+ if ( isTraceConnection ) {
182
+ utils.trace( 'Importing language "' + lang + '".' );
183
+ }
184
+ let Language;
185
+ ({ Language } = await import("./language-" + lang.toLowerCase() + ".mjs"));
186
+ const language = new Language({
187
+ trace: isTraceLanguage
188
+ });
189
+ if ( isNode && settings.dictionaryPath ) {
190
+ if ( !settings.dictionaryPath.endsWith("/") ) {
191
+ settings.dictionaryPath += "/";
192
+ }
193
+ await language.loadDictionary( settings.dictionaryPath + lang.toLowerCase() + ".txt");
194
+ } else if ( !isNode && settings.dictionaryURL ) {
195
+ if ( !settings.dictionaryURL.endsWith("/") ) {
196
+ settings.dictionaryURL += "/";
197
+ }
198
+ await language.loadDictionary( settings.dictionaryURL + lang.toLowerCase() + ".txt");
199
+ }
200
+ languages.set( lang, language );
201
+ return language;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Load a specific voice.
207
+ *
208
+ * @param {string} s Voice name.
209
+ * @return {ArrayBuffer} Voice data.
210
+ */
211
+ async function loadVoice(s) {
212
+ if ( voices.has(s) ) {
213
+ return voices.get(s);
214
+ } else {
215
+ let voice;
216
+ [ voice ] = await Promise.all([
217
+ (async () => {
218
+ let url, path, response, buffer;
219
+ if ( isNode && settings.voicePath ) {
220
+ path = settings.voicePath + (settings.voicePath.endsWith("/") ? "" : "/") + s + ".bin";
221
+ if ( isTraceConnection ) {
222
+ utils.trace( 'Loading voice "' + path + '".' );
223
+ }
224
+ response = await fileReader(path);
225
+ buffer = response.buffer.slice(response.byteOffset, response.byteOffset + response.byteLength);
226
+ return buffer;
227
+ } else if ( !isNode && settings.voiceURL ) {
228
+ const url = new URL(settings.voiceURL);
229
+ url.pathname += (url.pathname.endsWith("/") ? "" : "/") + s + ".bin";
230
+ if ( isTraceConnection ) {
231
+ utils.trace( 'Loading voice "' + url + '".' );
232
+ }
233
+ response = await fetch(url);
234
+ if ( response.ok ) {
235
+ buffer = await response.arrayBuffer();
236
+ return buffer;
237
+ }
238
+ }
239
+ throw new Error('HeadTTS Worker: Error loading voice "' + s + '".');
240
+ })()
241
+ ]);
242
+ voices.set( s, voice );
243
+ return voice;
244
+ }
245
+ }
246
+
247
+
248
+ /**
249
+ * Calculate starting times and durations for TalkingHead words and visemes.
250
+ *
251
+ * @param {Object} o TalkingHead audio object to be updated
252
+ * @param {number[]} ds Token durations in frames
253
+ */
254
+ function updateTimestamps(o,ds) {
255
+
256
+ // Calculate starting times in milliseconds
257
+ const scaler = 1000 / settings.frameRate; // From frames to milliseconds
258
+ const times = [];
259
+ let t = 0;
260
+ let len = ds.length;
261
+ for( let i=0; i<len; i++ ) {
262
+ times.push( Math.round(t) );
263
+ t += scaler * ds[i];
264
+ }
265
+ times.push( Math.round(t) ); // Last entry
266
+
267
+ // Calculate word times and durations (+1 because of $)
268
+ len = o.words.length;
269
+ for( let i=0; i<len; i++ ) {
270
+ const start = times[o.wtimes[i]+1] + settings.deltaStart;
271
+ const end = times[o.wdurations[i]+1] + settings.deltaEnd;
272
+ const duration = end - start;
273
+ o.wtimes[i] = start;
274
+ o.wdurations[i] = duration;
275
+ }
276
+
277
+ // Calculate visemes times and durations (+1 because of $)
278
+ len = o.visemes.length;
279
+ for( let i=0; i<len; i++ ) {
280
+ const start = times[o.vtimes[i]+1] + settings.deltaStart;
281
+ const end = times[o.vdurations[i]+1] + settings.deltaEnd;
282
+ const duration = end - start;
283
+ o.vtimes[i] = start;
284
+ o.vdurations[i] = duration;
285
+ }
286
+
287
+ }
288
+
289
+
290
+ /**
291
+ * Process the work queue: phonemize the text, tokenize phonemes, load voice,
292
+ * run inference, encode audio, and post the response message.
293
+ */
294
+ async function process() {
295
+ if ( isProcessing || !isReady ) return;
296
+ isProcessing = true;
297
+ while( queue.length ) {
298
+ const item = queue[0];
299
+ queue.shift();
300
+ const d = item.data;
301
+
302
+ // Generate tokens/phonemes and initialize TalkingHead audio object
303
+ let language;
304
+ try {
305
+ language = await loadLanguage(d.language);
306
+ } catch(error) {
307
+ console.error("HeadTTS Worker: Error loading language module, error=", error, " item=", item);
308
+ item.ref = item.id;
309
+ delete item.id;
310
+ item.type = "error";
311
+ item.data = { error: "Error loading language module '" + d.language + "'." };
312
+ eventHandler.postMessage(item);
313
+ continue;
314
+ }
315
+ const { phonemes, metadata } = language.generate(d.input);
316
+ if ( isTraceG2P ) {
317
+ if ( typeof d.input === "string" ) {
318
+ utils.trace( "G2P: " + d.input );
319
+ } else if ( Array.isArray(d.input) ) {
320
+ d.input.forEach( x => {
321
+ if ( typeof x === "string" ) {
322
+ utils.trace( "G2P: " + x );
323
+ } else {
324
+ utils.trace( "G2P: { type=" + x.type + ", value=" + x.value + " }" );
325
+ }
326
+ });
327
+ }
328
+ utils.trace( "G2P: => " + phonemes.join("") + ", metadata=", metadata );
329
+ }
330
+
331
+ // Generate input IDs and run the model
332
+ const { input_ids } = tokenizer(phonemes.join(""), {
333
+ truncation: true
334
+ });
335
+ const num_tokens = Math.min(Math.max(input_ids.size - 2, 0), 509);
336
+ let voice;
337
+ try {
338
+ voice = await loadVoice(d.voice);
339
+ } catch(error) {
340
+ console.error("HeadTTS Worker: Error loading voice, error=", error, " item=", item);
341
+ item.ref = item.id;
342
+ delete item.id;
343
+ item.type = "error";
344
+ item.data = { error: "Error loading voice '" + d.voice + "'." };
345
+ eventHandler.postMessage(item);
346
+ continue;
347
+ }
348
+ const data = new Float32Array(voice);
349
+ const offset = num_tokens * settings.styleDim;
350
+ const voiceData = data.slice(offset, offset + settings.styleDim);
351
+ const inputs = {
352
+ input_ids,
353
+ style: new Tensor("float32", voiceData, [1, settings.styleDim]),
354
+ speed: new Tensor("float32", [d.speed], [1]),
355
+ };
356
+ const { waveform, durations } = await model(inputs);
357
+
358
+ // Generate timestamps from durations
359
+ const durationsFrames = Array.from(durations.data);
360
+ updateTimestamps( metadata, durationsFrames );
361
+
362
+ // Encode audio
363
+ if ( d.audioEncoding === "pcm" ) {
364
+ metadata.audio = utils.encodeAudio(waveform.data, settings.audioSampleRate, false);
365
+ metadata.audioEncoding = "pcm";
366
+ } else {
367
+ metadata.audio = utils.encodeAudio(waveform.data, settings.audioSampleRate, true);
368
+ metadata.audioEncoding = "wav";
369
+ }
370
+
371
+ // Sent the TalkingHead object to the original caller
372
+ item.ref = item.id;
373
+ delete item.id;
374
+ item.type = "audio";
375
+ item.data = metadata;
376
+ eventHandler.postMessage(item, [metadata.audio]);
377
+
378
+ }
379
+ isProcessing = false;
380
+
381
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@met4citizen/headtts",
3
+ "version": "0.2.0",
4
+ "description": "HeadTTS: A free Javascript text-to-speech with timestamps and visemes.",
5
+ "main": "modules/headtts.mjs",
6
+ "type": "module",
7
+ "files": [
8
+ "README.md",
9
+ "LICENSE",
10
+ "headttsd.json",
11
+ "modules/",
12
+ "dictionaries/"
13
+ ],
14
+ "dependencies": {
15
+ "@huggingface/transformers": "^3.5.1",
16
+ "ws": "^8.18.1"
17
+ },
18
+ "scripts": {
19
+ "start": "node ./modules/headtts-node.mjs",
20
+ "test": "node --experimental-vm-modules node_modules/.bin/jest",
21
+ "postinstall": "mkdir -p -m 777 ./node_modules/@huggingface/transformers/.cache"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/met4citizen/HeadTTS.git"
26
+ },
27
+ "keywords": [
28
+ "talkinghead",
29
+ "lip-sync",
30
+ "text-to-speech",
31
+ "timestamps",
32
+ "visemes",
33
+ "kokoro"
34
+ ],
35
+ "author": "Mika Suominen",
36
+ "license": "MIT",
37
+ "bugs": {
38
+ "url": "https://github.com/met4citizen/HeadTTS/issues"
39
+ },
40
+ "homepage": "https://github.com/met4citizen/HeadTTS#readme",
41
+ "devDependencies": {
42
+ "jest": "^29.7.0"
43
+ }
44
+ }