@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,425 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import { readFileSync } from 'node:fs';
4
+ import process from 'node:process';
5
+ import { cpus } from 'node:os';
6
+ import { Worker } from 'node:worker_threads';
7
+ import { WebSocketServer } from 'ws';
8
+ import * as utils from "./utils.mjs";
9
+
10
+
11
+ /**
12
+ * Check if a specific command line option/flag was set.
13
+ *
14
+ * @param {string} key Option/flag name
15
+ * @return {boolean} True, if command line option was set.
16
+ */
17
+ function isOptionSet(key) {
18
+ return process.argv.includes('--'+key);
19
+ }
20
+
21
+ /**
22
+ * Get the value of the given command line option.
23
+ *
24
+ * @param {string} key Option/flag name
25
+ * @return {string} Value after the option flag or null if not set.
26
+ */
27
+ function getOptionValue(key) {
28
+ for( let i=0; i<(process.argv.length-1); i++ ) {
29
+ const arg = process.argv[i];
30
+ if ( arg === '--'+key ) return process.argv[i+1].slice();
31
+ }
32
+ return null;
33
+ }
34
+
35
+
36
+ // Default config
37
+ const config = {
38
+
39
+ server: {
40
+ port: 8882,
41
+ certFile: null,
42
+ keyFile: null,
43
+ websocket: true,
44
+ rest: true,
45
+ connectionTimeout: 20000,
46
+ corsOrigin: "*"
47
+ },
48
+
49
+ tts: {
50
+ threads: 1,
51
+ model: "onnx-community/Kokoro-82M-v1.0-ONNX-timestamped",
52
+ dtype: "fp32",
53
+ device: "cpu",
54
+ styleDim: 256,
55
+ frameRate: 40,
56
+ audioSampleRate: 24000,
57
+
58
+ languages: ['en-us'],
59
+ dictionaryPath: "./dictionaries",
60
+ voicePath: "./voices",
61
+ voices: ["af_bella"],
62
+
63
+ deltaStart: -10,
64
+ deltaEnd: 0,
65
+
66
+ defaults: {
67
+ voice: "af_bella",
68
+ language: "en-us",
69
+ speed: 1,
70
+ audioEncoding: "wav"
71
+ }
72
+ },
73
+
74
+ trace: 0
75
+
76
+ };
77
+
78
+
79
+ // Read JSON configuration file
80
+ const file = getOptionValue("config") || "./headtts-node.json";
81
+ const json = readFileSync(file, 'utf8');
82
+ const trace = parseInt(getOptionValue("trace"));
83
+ const o = JSON.parse(json);
84
+ Object.assign(config.server, o.server);
85
+ Object.assign(config.tts, o.tts);
86
+ config.trace = Number.isNaN(trace) ? o.trace : trace;
87
+
88
+ // Trace
89
+ const isTraceConnection = config.trace & utils.traceMask.connection;
90
+ const isTraceMessages = config.trace & utils.traceMask.messages;
91
+ const isTraceEvents = config.trace & utils.traceMask.events;
92
+ if ( isTraceConnection ) {
93
+ utils.trace( "CONFIG:", config);
94
+ }
95
+
96
+
97
+ // TODO: Check all configuration file parameters and values
98
+ if ( config.tts.threads < 1 || config.tts.threads > cpus().length ) {
99
+ console.error("Parameter 'threads' must be between 1 and the number of CPU cores (" + cpus().length + ").");
100
+ process.exit(1);
101
+ }
102
+
103
+ // Item queue
104
+ const queue = [];
105
+ let threadId = 0;
106
+
107
+ // WebSocket Connections
108
+ const mapWebSocket = new Map();
109
+ const mapRest = new Map();
110
+ let websocketId = 0;
111
+ let restId = 0;
112
+
113
+ const workers = new Array(config.tts.threads);
114
+ const statuses = new Array(config.tts.threads);
115
+ for( let i=0; i<config.tts.threads; i++ ) {
116
+ const worker = new Worker('./modules/worker-tts.mjs', { type: "module" });
117
+
118
+ workers[i] = worker;
119
+ statuses[i] = 0;
120
+
121
+ // Web Worker message handler
122
+ worker.on("message", (message) => {
123
+ if ( isTraceMessages ) {
124
+ utils.trace( "IN: <- Worker", message );
125
+ }
126
+
127
+ if ( message.hasOwnProperty("rest") ) {
128
+
129
+ // REST response
130
+ const res = mapRest.get(message.rest);
131
+ if ( res ) {
132
+ mapRest.delete(message.rest);
133
+ if ( message.type === "error" ) {
134
+ if ( isTraceMessages ) {
135
+ utils.trace( "OUT: -> REST Client, Error", message.data );
136
+ }
137
+ res.writeHead(422, { 'Content-Type': 'application/json' });
138
+ res.end(JSON.stringify(message.data));
139
+ } else if ( message.type === "audio" ){
140
+ if ( isTraceMessages ) {
141
+ utils.trace( "OUT: -> REST Client, Audio", message.data );
142
+ }
143
+ message.data.audio = Buffer.from(message.data.audio).toString('base64');
144
+ res.writeHead(200, { 'Content-Type': 'application/json' });
145
+ res.end(JSON.stringify(message.data));
146
+ }
147
+ }
148
+
149
+ } else if ( message.hasOwnProperty("websocket") ) {
150
+
151
+ // WebSocket response
152
+ const ws = mapWebSocket.get(message.websocket);
153
+ if ( ws ) {
154
+ if ( message.type === "error" ) {
155
+ if ( isTraceMessages ) {
156
+ utils.trace( "OUT: -> WebSocket Client, Error", message.data );
157
+ }
158
+ ws.send( JSON.stringify( message ) );
159
+ } else if ( message.type === "audio" ) {
160
+ if ( isTraceMessages ) {
161
+ utils.trace( "OUT: -> WebSocket Client, Audio", message.data );
162
+ }
163
+ const audio = message.data.audio;
164
+ delete message.data.audio;
165
+ ws.send( JSON.stringify( message ) );
166
+ ws.send( audio );
167
+ }
168
+ }
169
+
170
+ }
171
+ if ( queue.length ) {
172
+ const o = queue.shift();
173
+ if ( isTraceMessages ) {
174
+ utils.trace( "OUT: -> Worker", o );
175
+ }
176
+ worker.postMessage(o);
177
+ } else {
178
+ statuses[i] = 0;
179
+ }
180
+ });
181
+
182
+ // Web Worker error handler
183
+ worker.on("error", (error) => {
184
+ if ( isTraceMessages ) {
185
+ utils.trace( "IN: <- Worker, Error", error );
186
+ }
187
+ console.error(error);
188
+ });
189
+
190
+ // Setup Web Worker
191
+ const data = {};
192
+ [ "transformersModule", "model", "dtype", "device", "styleDim", "frameRate",
193
+ "languages", "dictionaryPath", "voicePath", "voices", "audioSampleRate",
194
+ "deltaStart", "deltaEnd", "trace" ].forEach( x => data[x] = config.tts[x] );
195
+ const message = {
196
+ type: "connect",
197
+ data: data
198
+ };
199
+ worker.postMessage( message );
200
+
201
+ }
202
+
203
+ // Server configuration
204
+ const port = config.server.port;
205
+ const isWebsocket = config.server.websocket;
206
+ const isRest = config.server.rest;
207
+ const isSecure = config.server.certFile && config.server.keyFile;
208
+ let handler;
209
+ if ( isRest ) {
210
+ handler = restHandler;
211
+ }
212
+ let wss;
213
+
214
+ // Start server
215
+ if ( isSecure ) {
216
+ const httpsServer = https.createServer({
217
+ cert: readFileSync(config.server.certFile, 'utf8'),
218
+ key: readFileSync(config.server.keyFile, 'utf8')
219
+ }, handler);
220
+ if ( isWebsocket ) {
221
+ wss = new WebSocketServer({ server: httpsServer });
222
+ }
223
+ httpsServer.listen(port, () => {
224
+ console.info("HeadTTS-Node SECURE server running on port " + port + ".");
225
+ });
226
+ } else {
227
+ const httpServer = http.createServer(handler);
228
+ if ( isWebsocket ) {
229
+ wss = new WebSocketServer({ server: httpServer });
230
+ }
231
+ httpServer.listen(port, () => {
232
+ console.info("HeadTTS-Node server running on port " + port + "." );
233
+ });
234
+ }
235
+
236
+ // REST handler
237
+ function restHandler(req,res) {
238
+
239
+ if ( isTraceMessages ) {
240
+ utils.trace( "IN: <- REST Client", req.method, req.url );
241
+ }
242
+
243
+ // Set CORS headers
244
+ if ( config.server.corsOrigin ) {
245
+ res.setHeader('Access-Control-Allow-Origin', config.server.corsOrigin);
246
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
247
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
248
+ }
249
+
250
+ // Handle preflight (OPTIONS) requests
251
+ if (req.method === 'OPTIONS') {
252
+ res.writeHead(200);
253
+ return res.end();
254
+ }
255
+
256
+ // POST messages
257
+ if (req.method === 'POST') {
258
+
259
+ // Synthesize
260
+ if ( req.url === '/v1/synthesize') {
261
+
262
+ let body = '';
263
+ req.on('data', chunk => (body += chunk));
264
+ req.on('end', () => {
265
+
266
+ if ( isTraceMessages ) {
267
+ utils.trace( "IN: Body=", body );
268
+ }
269
+
270
+ try {
271
+ const o = JSON.parse(body); // Parse JSON
272
+ // TODO: Check JSON and send 400 if errors
273
+
274
+ // Callback mechanism
275
+ const id = ++restId;
276
+ mapRest.set( id, res );
277
+
278
+ // Message
279
+ const message = {
280
+ type: "synthesize",
281
+ id: id,
282
+ data: {
283
+ input: (o.input || ""),
284
+ voice: (o.voice || config.tts.defaults.voice),
285
+ language: (o.language || config.tts.defaults.language),
286
+ speed: (o.speed || config.tts.defaults.speed),
287
+ audioEncoding: (o.audioEncoding || config.tts.defaults.audioEncoding)
288
+ },
289
+ rest: id
290
+ }
291
+ queue.push(message);
292
+ for( let i=0; i<config.tts.threads; i++ ) {
293
+ threadId = (threadId + 1) % config.tts.threads;
294
+ if ( statuses[threadId] === 0 ) {
295
+ const o = queue.shift();
296
+ workers[threadId].postMessage(o);
297
+ statuses[threadId] = 1;
298
+ break;
299
+ }
300
+ }
301
+ } catch (err) {
302
+ if ( isTraceMessages ) {
303
+ utils.trace( "OUT: -> REST Client, Error", err.message || "Internal error." );
304
+ }
305
+ res.writeHead(400, { 'Content-Type': 'application/json' });
306
+ res.end(JSON.stringify({
307
+ error: (err.message || "Internal error.")
308
+ }));
309
+ }
310
+ });
311
+ } else if ( req.url === '/v1/hello' ) {
312
+ if ( isTraceMessages ) {
313
+ utils.trace( "OUT: -> REST Client, HELLO" );
314
+ }
315
+ res.writeHead(200);
316
+ res.end('HeadTTS v0.1.0');
317
+ } else {
318
+ if ( isTraceMessages ) {
319
+ utils.trace( "OUT: REST -> Client Error, Not found." );
320
+ }
321
+ res.writeHead(404);
322
+ res.end('Not Found');
323
+ }
324
+ } else {
325
+ if ( isTraceMessages ) {
326
+ utils.trace( "OUT: -> REST Client, Error Not found." );
327
+ }
328
+ res.writeHead(404);
329
+ res.end('Not Found');
330
+ }
331
+ }
332
+
333
+
334
+ // WEBSOCKET
335
+ if ( wss ) {
336
+ // Set binary type
337
+ wss.binaryType = "arraybuffer";
338
+
339
+ // New connections
340
+ wss.on("connection", (ws,req) => {
341
+
342
+ if ( isTraceConnection ) {
343
+ utils.trace( "CONNECTION: WebSocket", req.connection );
344
+ }
345
+
346
+ // Client setup
347
+ const ttsSetup = Object.assign({}, config.tts.defaults);
348
+
349
+ const id = ++websocketId;
350
+ mapWebSocket.set( id, ws );
351
+ console.info("New connection (" + id + ") from " + req.connection.remoteAddress + "." );
352
+
353
+ // Timeout
354
+ let timerTimeout = setTimeout(() => {
355
+ ws.close();
356
+ }, config.server.connectionTimeout);
357
+
358
+ // WebSocket message handler
359
+ ws.on("message", (data, isBinary) => {
360
+ clearTimeout(timerTimeout);
361
+ timerTimeout = setTimeout(() => {
362
+ ws.close();
363
+ }, config.server.connectionTimeout);
364
+
365
+ try {
366
+ if ( isBinary ) {
367
+ console.error('Received binary message.');
368
+ } else {
369
+ const message = JSON.parse( data.toString() );
370
+ if ( isTraceMessages ) {
371
+ utils.trace( "IN: <- WebSocket Client (" + id + ")", message );
372
+ }
373
+ message.websocket = id;
374
+ if ( message.type === "setup" ) {
375
+ // TODO: Check setup values
376
+ Object.assign(ttsSetup, message.data);
377
+ } else {
378
+
379
+ // Set values
380
+ if ( message.type === "synthesize" ) {
381
+ message.data.voice = ttsSetup.voice.slice();
382
+ message.data.language = ttsSetup.language.slice();
383
+ message.data.speed = ttsSetup.speed;
384
+ message.data.audioEncoding = ttsSetup.audioEncoding.slice();
385
+ }
386
+
387
+ queue.push(message);
388
+ for( let i=0; i<config.tts.threads; i++ ) {
389
+ threadId = (threadId + 1) % config.tts.threads;
390
+ if ( statuses[threadId] === 0 ) {
391
+ const o = queue.shift();
392
+ workers[threadId].postMessage(o);
393
+ statuses[threadId] = 1;
394
+ break;
395
+ }
396
+ }
397
+ }
398
+ }
399
+ } catch(error) {
400
+ console.error('JSON parse failed: ' + error);
401
+ }
402
+
403
+ });
404
+
405
+ // WebSocket error handler
406
+ ws.on("error", (error) => {
407
+ console.error(error);
408
+ ws.close();
409
+ });
410
+
411
+ // WebSocket connection closed
412
+ ws.on("close", (event) => {
413
+ mapWebSocket.delete(id);
414
+ console.info("Connection (" + id + ") closed to " + req.connection.remoteAddress + "." );
415
+ });
416
+
417
+ });
418
+
419
+ // Server closed, terminate web workers
420
+ wss.on("close", () => {
421
+ for( let i=0; i<config.tts.threads; i++ ) {
422
+ workers[i].terminate();
423
+ }
424
+ });
425
+ }