speechflow 2.0.1 → 2.0.2
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/CHANGELOG.md +6 -0
- package/package.json +4 -4
- package/speechflow-cli/dst/speechflow-node-t2a-supertonic.d.ts +2 -3
- package/speechflow-cli/dst/speechflow-node-t2a-supertonic.js +93 -466
- package/speechflow-cli/dst/speechflow-node-t2a-supertonic.js.map +1 -1
- package/speechflow-cli/dst/speechflow-node-t2t-punctuation.js +1 -2
- package/speechflow-cli/dst/speechflow-node-t2t-punctuation.js.map +1 -1
- package/speechflow-cli/dst/speechflow-node-t2t-spellcheck.js +1 -2
- package/speechflow-cli/dst/speechflow-node-t2t-spellcheck.js.map +1 -1
- package/speechflow-cli/dst/speechflow-node-t2t-summary.js +1 -2
- package/speechflow-cli/dst/speechflow-node-t2t-summary.js.map +1 -1
- package/speechflow-cli/dst/speechflow-node-t2t-translate.js +1 -2
- package/speechflow-cli/dst/speechflow-node-t2t-translate.js.map +1 -1
- package/speechflow-cli/dst/speechflow-util-llm.d.ts +0 -1
- package/speechflow-cli/dst/speechflow-util-llm.js +4 -8
- package/speechflow-cli/dst/speechflow-util-llm.js.map +1 -1
- package/speechflow-cli/dst/test.d.ts +1 -0
- package/speechflow-cli/dst/test.js +18 -0
- package/speechflow-cli/dst/test.js.map +1 -0
- package/speechflow-cli/etc/oxlint.jsonc +3 -1
- package/speechflow-cli/package.json +12 -12
- package/speechflow-cli/src/speechflow-node-t2a-supertonic.ts +103 -577
- package/speechflow-cli/src/speechflow-node-t2t-punctuation.ts +1 -2
- package/speechflow-cli/src/speechflow-node-t2t-spellcheck.ts +1 -2
- package/speechflow-cli/src/speechflow-node-t2t-summary.ts +1 -2
- package/speechflow-cli/src/speechflow-node-t2t-translate.ts +1 -2
- package/speechflow-cli/src/speechflow-util-llm.ts +4 -9
- package/speechflow-cli/src/speechflow-util-queue.ts +1 -1
- package/speechflow-ui-db/dst/index.js +14 -14
- package/speechflow-ui-db/package.json +2 -2
- package/speechflow-ui-st/dst/index.js +32 -32
- package/speechflow-ui-st/package.json +2 -2
|
@@ -42,408 +42,22 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
42
42
|
};
|
|
43
43
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
44
44
|
/* standard dependencies */
|
|
45
|
-
const node_fs_1 = __importDefault(require("node:fs"));
|
|
46
|
-
const node_path_1 = __importDefault(require("node:path"));
|
|
47
45
|
const node_stream_1 = __importDefault(require("node:stream"));
|
|
48
46
|
/* external dependencies */
|
|
49
|
-
const
|
|
50
|
-
const HF = __importStar(require("@huggingface/hub"));
|
|
47
|
+
const Transformers = __importStar(require("@huggingface/transformers"));
|
|
51
48
|
const speex_resampler_1 = __importDefault(require("speex-resampler"));
|
|
52
49
|
const luxon_1 = require("luxon");
|
|
53
|
-
/* @ts-expect-error no type available */
|
|
54
|
-
const ORT = __importStar(require("onnxruntime-node"));
|
|
55
50
|
/* internal dependencies */
|
|
56
51
|
const speechflow_node_1 = __importDefault(require("./speechflow-node"));
|
|
57
52
|
const util = __importStar(require("./speechflow-util"));
|
|
58
|
-
/* convert lengths to binary mask */
|
|
59
|
-
function lengthToMask(lengths, maxLen = null) {
|
|
60
|
-
/* handle empty input */
|
|
61
|
-
if (lengths.length === 0)
|
|
62
|
-
return [];
|
|
63
|
-
/* determine maximum length */
|
|
64
|
-
maxLen = maxLen ?? Math.max(...lengths);
|
|
65
|
-
/* build mask array */
|
|
66
|
-
const mask = [];
|
|
67
|
-
for (let i = 0; i < lengths.length; i++) {
|
|
68
|
-
const row = [];
|
|
69
|
-
for (let j = 0; j < maxLen; j++)
|
|
70
|
-
row.push(j < lengths[i] ? 1.0 : 0.0);
|
|
71
|
-
mask.push([row]);
|
|
72
|
-
}
|
|
73
|
-
return mask;
|
|
74
|
-
}
|
|
75
|
-
/* get latent mask from wav lengths */
|
|
76
|
-
function getLatentMask(wavLengths, baseChunkSize, chunkCompressFactor) {
|
|
77
|
-
/* calculate latent size and lengths */
|
|
78
|
-
const latentSize = baseChunkSize * chunkCompressFactor;
|
|
79
|
-
const latentLengths = wavLengths.map((len) => Math.floor((len + latentSize - 1) / latentSize));
|
|
80
|
-
/* generate mask from latent lengths */
|
|
81
|
-
return lengthToMask(latentLengths);
|
|
82
|
-
}
|
|
83
|
-
/* convert array to ONNX tensor */
|
|
84
|
-
function arrayToTensor(array, dims) {
|
|
85
|
-
/* flatten array and create float32 tensor */
|
|
86
|
-
const flat = array.flat(Infinity);
|
|
87
|
-
return new ORT.Tensor("float32", Float32Array.from(flat), dims);
|
|
88
|
-
}
|
|
89
|
-
/* convert int array to ONNX tensor */
|
|
90
|
-
function intArrayToTensor(array, dims) {
|
|
91
|
-
/* flatten array and create int64 tensor */
|
|
92
|
-
const flat = array.flat(Infinity);
|
|
93
|
-
return new ORT.Tensor("int64", BigInt64Array.from(flat.map(BigInt)), dims);
|
|
94
|
-
}
|
|
95
|
-
/* chunk text into manageable segments */
|
|
96
|
-
function chunkText(text, maxLen = 300) {
|
|
97
|
-
/* validate input type */
|
|
98
|
-
if (typeof text !== "string")
|
|
99
|
-
throw new Error(`chunkText expects a string, got ${typeof text}`);
|
|
100
|
-
/* split by paragraph (two or more newlines) */
|
|
101
|
-
const paragraphs = text.trim().split(/\n\s*\n+/).filter((p) => p.trim());
|
|
102
|
-
/* process each paragraph into chunks */
|
|
103
|
-
const chunks = [];
|
|
104
|
-
for (let paragraph of paragraphs) {
|
|
105
|
-
paragraph = paragraph.trim();
|
|
106
|
-
if (!paragraph)
|
|
107
|
-
continue;
|
|
108
|
-
/* split by sentence boundaries (period, question mark, exclamation mark followed by space)
|
|
109
|
-
but exclude common abbreviations like Mr., Mrs., Dr., etc. and single capital letters like F. */
|
|
110
|
-
const sentences = paragraph.split(/(?<!Mr\.|Mrs\.|Ms\.|Dr\.|Prof\.|Sr\.|Jr\.|Ph\.D\.|etc\.|e\.g\.|i\.e\.|vs\.|Inc\.|Ltd\.|Co\.|Corp\.|St\.|Ave\.|Blvd\.)(?<!\b[A-Z]\.)(?<=[.!?])\s+/);
|
|
111
|
-
/* accumulate sentences into chunks respecting max length */
|
|
112
|
-
let currentChunk = "";
|
|
113
|
-
for (const sentence of sentences) {
|
|
114
|
-
if (currentChunk.length + sentence.length + 1 <= maxLen)
|
|
115
|
-
currentChunk += (currentChunk ? " " : "") + sentence;
|
|
116
|
-
else {
|
|
117
|
-
if (currentChunk)
|
|
118
|
-
chunks.push(currentChunk.trim());
|
|
119
|
-
currentChunk = sentence;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
/* push remaining chunk */
|
|
123
|
-
if (currentChunk)
|
|
124
|
-
chunks.push(currentChunk.trim());
|
|
125
|
-
}
|
|
126
|
-
return chunks;
|
|
127
|
-
}
|
|
128
|
-
/* unicode text processor class */
|
|
129
|
-
class SupertonicTextProcessor {
|
|
130
|
-
indexer;
|
|
131
|
-
/* construct text processor */
|
|
132
|
-
constructor(unicodeIndexerJsonPath) {
|
|
133
|
-
/* load and parse unicode indexer JSON */
|
|
134
|
-
try {
|
|
135
|
-
this.indexer = JSON.parse(node_fs_1.default.readFileSync(unicodeIndexerJsonPath, "utf8"));
|
|
136
|
-
}
|
|
137
|
-
catch (err) {
|
|
138
|
-
throw new Error(`failed to parse unicode indexer JSON "${unicodeIndexerJsonPath}"`, { cause: err });
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
/* preprocess text */
|
|
142
|
-
preprocessText(text) {
|
|
143
|
-
/* normalize text */
|
|
144
|
-
text = text.normalize("NFKD");
|
|
145
|
-
/* remove emojis (wide Unicode range) */
|
|
146
|
-
const emojiPattern = /[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F1E6}-\u{1F1FF}]+/gu;
|
|
147
|
-
text = text.replace(emojiPattern, "");
|
|
148
|
-
/* replace various dashes and symbols */
|
|
149
|
-
const replacements = {
|
|
150
|
-
"–": "-",
|
|
151
|
-
"‑": "-",
|
|
152
|
-
"—": "-",
|
|
153
|
-
"¯": " ",
|
|
154
|
-
"_": " ",
|
|
155
|
-
"\u201C": "\"",
|
|
156
|
-
"\u201D": "\"",
|
|
157
|
-
"\u2018": "'",
|
|
158
|
-
"\u2019": "'",
|
|
159
|
-
"´": "'",
|
|
160
|
-
"`": "'",
|
|
161
|
-
"[": " ",
|
|
162
|
-
"]": " ",
|
|
163
|
-
"|": " ",
|
|
164
|
-
"/": " ",
|
|
165
|
-
"#": " ",
|
|
166
|
-
"→": " ",
|
|
167
|
-
"←": " "
|
|
168
|
-
};
|
|
169
|
-
for (const [k, v] of Object.entries(replacements))
|
|
170
|
-
text = text.replaceAll(k, v);
|
|
171
|
-
/* remove combining diacritics */
|
|
172
|
-
text = text.replace(/[\u0302\u0303\u0304\u0305\u0306\u0307\u0308\u030A\u030B\u030C\u0327\u0328\u0329\u032A\u032B\u032C\u032D\u032E\u032F]/g, "");
|
|
173
|
-
/* remove special symbols */
|
|
174
|
-
text = text.replace(/[♥☆♡©\\]/g, "");
|
|
175
|
-
/* replace known expressions */
|
|
176
|
-
const exprReplacements = {
|
|
177
|
-
"@": " at ",
|
|
178
|
-
"e.g.,": "for example, ",
|
|
179
|
-
"i.e.,": "that is, "
|
|
180
|
-
};
|
|
181
|
-
for (const [k, v] of Object.entries(exprReplacements))
|
|
182
|
-
text = text.replaceAll(k, v);
|
|
183
|
-
/* fix spacing around punctuation */
|
|
184
|
-
text = text.replace(/ ,/g, ",");
|
|
185
|
-
text = text.replace(/ \./g, ".");
|
|
186
|
-
text = text.replace(/ !/g, "!");
|
|
187
|
-
text = text.replace(/ \?/g, "?");
|
|
188
|
-
text = text.replace(/ ;/g, ";");
|
|
189
|
-
text = text.replace(/ :/g, ":");
|
|
190
|
-
text = text.replace(/ '/g, "'");
|
|
191
|
-
/* remove duplicate quotes */
|
|
192
|
-
text = text.replace(/""+/g, "\"");
|
|
193
|
-
text = text.replace(/''+/g, "'");
|
|
194
|
-
text = text.replace(/``+/g, "`");
|
|
195
|
-
/* remove extra spaces */
|
|
196
|
-
text = text.replace(/\s+/g, " ").trim();
|
|
197
|
-
/* if text doesn't end with punctuation, add a period */
|
|
198
|
-
if (!/[.!?;:,'"')\]}…。」』】〉》›»]$/.test(text))
|
|
199
|
-
text += ".";
|
|
200
|
-
return text;
|
|
201
|
-
}
|
|
202
|
-
/* convert text to Unicode values */
|
|
203
|
-
textToUnicodeValues(text) {
|
|
204
|
-
/* convert text characters to unicode code points */
|
|
205
|
-
return Array.from(text).map((char) => char.charCodeAt(0));
|
|
206
|
-
}
|
|
207
|
-
/* process text list */
|
|
208
|
-
call(textList) {
|
|
209
|
-
/* handle empty input */
|
|
210
|
-
if (textList.length === 0)
|
|
211
|
-
return { textIds: [], textMask: [] };
|
|
212
|
-
/* preprocess all texts */
|
|
213
|
-
const processedTexts = textList.map((t) => this.preprocessText(t));
|
|
214
|
-
const textIdsLengths = processedTexts.map((t) => t.length);
|
|
215
|
-
const maxLen = Math.max(...textIdsLengths);
|
|
216
|
-
/* convert texts to indexed token arrays */
|
|
217
|
-
const textIds = [];
|
|
218
|
-
for (let i = 0; i < processedTexts.length; i++) {
|
|
219
|
-
const row = Array.from({ length: maxLen }).fill(0);
|
|
220
|
-
const unicodeVals = this.textToUnicodeValues(processedTexts[i]);
|
|
221
|
-
for (let j = 0; j < unicodeVals.length; j++)
|
|
222
|
-
row[j] = this.indexer[unicodeVals[j]] ?? 0;
|
|
223
|
-
textIds.push(row);
|
|
224
|
-
}
|
|
225
|
-
/* generate text mask from lengths */
|
|
226
|
-
const textMask = lengthToMask(textIdsLengths);
|
|
227
|
-
return { textIds, textMask };
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
/* Supertonic TTS engine class */
|
|
231
|
-
class SupertonicTTS {
|
|
232
|
-
sampleRate;
|
|
233
|
-
/* internal TTS state */
|
|
234
|
-
cfgs;
|
|
235
|
-
textProcessor;
|
|
236
|
-
dpOrt;
|
|
237
|
-
textEncOrt;
|
|
238
|
-
vectorEstOrt;
|
|
239
|
-
vocoderOrt;
|
|
240
|
-
baseChunkSize;
|
|
241
|
-
chunkCompressFactor;
|
|
242
|
-
latentDim;
|
|
243
|
-
/* construct TTS engine */
|
|
244
|
-
constructor(cfgs, textProcessor, dpOrt, textEncOrt, vectorEstOrt, vocoderOrt) {
|
|
245
|
-
/* store configuration and dependencies */
|
|
246
|
-
this.cfgs = cfgs;
|
|
247
|
-
this.textProcessor = textProcessor;
|
|
248
|
-
this.dpOrt = dpOrt;
|
|
249
|
-
this.textEncOrt = textEncOrt;
|
|
250
|
-
this.vectorEstOrt = vectorEstOrt;
|
|
251
|
-
this.vocoderOrt = vocoderOrt;
|
|
252
|
-
/* extract configuration values */
|
|
253
|
-
this.sampleRate = cfgs.ae.sample_rate;
|
|
254
|
-
this.baseChunkSize = cfgs.ae.base_chunk_size;
|
|
255
|
-
this.chunkCompressFactor = cfgs.ttl.chunk_compress_factor;
|
|
256
|
-
this.latentDim = cfgs.ttl.latent_dim;
|
|
257
|
-
}
|
|
258
|
-
/* sample noisy latent vectors */
|
|
259
|
-
sampleNoisyLatent(duration) {
|
|
260
|
-
/* calculate dimensions for latent space */
|
|
261
|
-
const wavLenMax = Math.max(...duration) * this.sampleRate;
|
|
262
|
-
const wavLengths = duration.map((d) => Math.floor(d * this.sampleRate));
|
|
263
|
-
const chunkSize = this.baseChunkSize * this.chunkCompressFactor;
|
|
264
|
-
const latentLen = Math.floor((wavLenMax + chunkSize - 1) / chunkSize);
|
|
265
|
-
const latentDimExpanded = this.latentDim * this.chunkCompressFactor;
|
|
266
|
-
/* generate random noise (pre-allocate arrays for performance) */
|
|
267
|
-
const noisyLatent = Array.from({ length: duration.length });
|
|
268
|
-
for (let b = 0; b < duration.length; b++) {
|
|
269
|
-
const batch = Array.from({ length: latentDimExpanded });
|
|
270
|
-
for (let d = 0; d < latentDimExpanded; d++) {
|
|
271
|
-
const row = Array.from({ length: latentLen });
|
|
272
|
-
for (let t = 0; t < latentLen; t++) {
|
|
273
|
-
/* Box-Muller transform for normal distribution */
|
|
274
|
-
const eps = 1e-10;
|
|
275
|
-
const u1 = Math.max(eps, Math.random());
|
|
276
|
-
const u2 = Math.random();
|
|
277
|
-
row[t] = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2);
|
|
278
|
-
}
|
|
279
|
-
batch[d] = row;
|
|
280
|
-
}
|
|
281
|
-
noisyLatent[b] = batch;
|
|
282
|
-
}
|
|
283
|
-
/* apply mask */
|
|
284
|
-
const latentMask = getLatentMask(wavLengths, this.baseChunkSize, this.chunkCompressFactor);
|
|
285
|
-
for (let b = 0; b < noisyLatent.length; b++) {
|
|
286
|
-
for (let d = 0; d < noisyLatent[b].length; d++) {
|
|
287
|
-
for (let t = 0; t < noisyLatent[b][d].length; t++)
|
|
288
|
-
noisyLatent[b][d][t] *= latentMask[b][0][t];
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
return { noisyLatent, latentMask };
|
|
292
|
-
}
|
|
293
|
-
/* perform inference */
|
|
294
|
-
async infer(textList, style, totalStep, speed) {
|
|
295
|
-
/* validate batch size matches style vectors */
|
|
296
|
-
if (textList.length !== style.ttl.dims[0])
|
|
297
|
-
throw new Error("Number of texts must match number of style vectors");
|
|
298
|
-
/* process text into token IDs and masks */
|
|
299
|
-
const batchSize = textList.length;
|
|
300
|
-
const { textIds, textMask } = this.textProcessor.call(textList);
|
|
301
|
-
const textIdsShape = [batchSize, textIds[0].length];
|
|
302
|
-
const textMaskShape = [batchSize, 1, textMask[0][0].length];
|
|
303
|
-
const textMaskTensor = arrayToTensor(textMask, textMaskShape);
|
|
304
|
-
/* run duration predictor model */
|
|
305
|
-
const dpResult = await this.dpOrt.run({
|
|
306
|
-
text_ids: intArrayToTensor(textIds, textIdsShape),
|
|
307
|
-
style_dp: style.dp,
|
|
308
|
-
text_mask: textMaskTensor
|
|
309
|
-
});
|
|
310
|
-
const predictedDurations = Array.from(dpResult.duration.data);
|
|
311
|
-
/* apply speed factor to duration */
|
|
312
|
-
for (let i = 0; i < predictedDurations.length; i++)
|
|
313
|
-
predictedDurations[i] /= speed;
|
|
314
|
-
/* run text encoder model */
|
|
315
|
-
const textEncResult = await this.textEncOrt.run({
|
|
316
|
-
text_ids: intArrayToTensor(textIds, textIdsShape),
|
|
317
|
-
style_ttl: style.ttl,
|
|
318
|
-
text_mask: textMaskTensor
|
|
319
|
-
});
|
|
320
|
-
const textEmbTensor = textEncResult.text_emb;
|
|
321
|
-
/* sample initial noisy latent vectors */
|
|
322
|
-
const { noisyLatent, latentMask } = this.sampleNoisyLatent(predictedDurations);
|
|
323
|
-
const latentShape = [batchSize, noisyLatent[0].length, noisyLatent[0][0].length];
|
|
324
|
-
const latentMaskShape = [batchSize, 1, latentMask[0][0].length];
|
|
325
|
-
const latentMaskTensor = arrayToTensor(latentMask, latentMaskShape);
|
|
326
|
-
/* prepare step tensors */
|
|
327
|
-
const totalStepArray = Array.from({ length: batchSize }).fill(totalStep);
|
|
328
|
-
const scalarShape = [batchSize];
|
|
329
|
-
const totalStepTensor = arrayToTensor(totalStepArray, scalarShape);
|
|
330
|
-
/* iteratively denoise latent vectors */
|
|
331
|
-
for (let step = 0; step < totalStep; step++) {
|
|
332
|
-
const currentStepArray = Array.from({ length: batchSize }).fill(step);
|
|
333
|
-
/* run vector estimator model */
|
|
334
|
-
const vectorEstResult = await this.vectorEstOrt.run({
|
|
335
|
-
noisy_latent: arrayToTensor(noisyLatent, latentShape),
|
|
336
|
-
text_emb: textEmbTensor,
|
|
337
|
-
style_ttl: style.ttl,
|
|
338
|
-
text_mask: textMaskTensor,
|
|
339
|
-
latent_mask: latentMaskTensor,
|
|
340
|
-
total_step: totalStepTensor,
|
|
341
|
-
current_step: arrayToTensor(currentStepArray, scalarShape)
|
|
342
|
-
});
|
|
343
|
-
const denoisedLatent = Array.from(vectorEstResult.denoised_latent.data);
|
|
344
|
-
/* update latent with the denoised output */
|
|
345
|
-
let idx = 0;
|
|
346
|
-
for (let b = 0; b < noisyLatent.length; b++)
|
|
347
|
-
for (let d = 0; d < noisyLatent[b].length; d++)
|
|
348
|
-
for (let t = 0; t < noisyLatent[b][d].length; t++)
|
|
349
|
-
noisyLatent[b][d][t] = denoisedLatent[idx++];
|
|
350
|
-
}
|
|
351
|
-
/* run vocoder to generate audio waveform */
|
|
352
|
-
const vocoderResult = await this.vocoderOrt.run({
|
|
353
|
-
latent: arrayToTensor(noisyLatent, latentShape)
|
|
354
|
-
});
|
|
355
|
-
const wav = Array.from(vocoderResult.wav_tts.data);
|
|
356
|
-
return { wav, duration: predictedDurations };
|
|
357
|
-
}
|
|
358
|
-
/* synthesize speech from text */
|
|
359
|
-
async synthesize(text, style, totalStep, speed, silenceDuration = 0.3) {
|
|
360
|
-
/* validate single speaker mode */
|
|
361
|
-
if (style.ttl.dims[0] !== 1)
|
|
362
|
-
throw new Error("Single speaker text to speech only supports single style");
|
|
363
|
-
/* chunk text into segments */
|
|
364
|
-
const textList = chunkText(text);
|
|
365
|
-
if (textList.length === 0)
|
|
366
|
-
return { wav: [], duration: 0 };
|
|
367
|
-
/* synthesize each chunk and concatenate with silence */
|
|
368
|
-
const wavParts = [];
|
|
369
|
-
let totalDuration = 0;
|
|
370
|
-
for (const chunk of textList) {
|
|
371
|
-
const { wav, duration } = await this.infer([chunk], style, totalStep, speed);
|
|
372
|
-
/* insert silence between chunks */
|
|
373
|
-
if (wavParts.length > 0) {
|
|
374
|
-
const silenceLen = Math.floor(silenceDuration * this.sampleRate);
|
|
375
|
-
wavParts.push(Array.from({ length: silenceLen }).fill(0));
|
|
376
|
-
totalDuration += silenceDuration;
|
|
377
|
-
}
|
|
378
|
-
wavParts.push(wav);
|
|
379
|
-
totalDuration += duration[0];
|
|
380
|
-
}
|
|
381
|
-
return { wav: wavParts.flat(), duration: totalDuration };
|
|
382
|
-
}
|
|
383
|
-
/* release TTS engine resources */
|
|
384
|
-
async release() {
|
|
385
|
-
/* release all ONNX inference sessions */
|
|
386
|
-
await Promise.all([
|
|
387
|
-
this.dpOrt.release(),
|
|
388
|
-
this.textEncOrt.release(),
|
|
389
|
-
this.vectorEstOrt.release(),
|
|
390
|
-
this.vocoderOrt.release()
|
|
391
|
-
]);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
/* load voice style from JSON file */
|
|
395
|
-
async function loadVoiceStyle(voiceStylePath) {
|
|
396
|
-
/* read and parse voice style JSON */
|
|
397
|
-
let voiceStyle;
|
|
398
|
-
try {
|
|
399
|
-
voiceStyle = JSON.parse(await node_fs_1.default.promises.readFile(voiceStylePath, "utf8"));
|
|
400
|
-
}
|
|
401
|
-
catch (err) {
|
|
402
|
-
throw new Error(`failed to parse voice style JSON "${voiceStylePath}"`, { cause: err });
|
|
403
|
-
}
|
|
404
|
-
/* extract dimensions and data */
|
|
405
|
-
const ttlDims = voiceStyle.style_ttl.dims;
|
|
406
|
-
const dpDims = voiceStyle.style_dp.dims;
|
|
407
|
-
const ttlData = voiceStyle.style_ttl.data.flat(Infinity);
|
|
408
|
-
const dpData = voiceStyle.style_dp.data.flat(Infinity);
|
|
409
|
-
/* create ONNX tensors for style vectors */
|
|
410
|
-
const ttlStyle = new ORT.Tensor("float32", Float32Array.from(ttlData), ttlDims);
|
|
411
|
-
const dpStyle = new ORT.Tensor("float32", Float32Array.from(dpData), dpDims);
|
|
412
|
-
return { ttl: ttlStyle, dp: dpStyle };
|
|
413
|
-
}
|
|
414
|
-
/* load TTS engine from ONNX models */
|
|
415
|
-
async function loadSupertonic(assetsDir) {
|
|
416
|
-
/* load configuration */
|
|
417
|
-
const cfgPath = node_path_1.default.join(assetsDir, "onnx", "tts.json");
|
|
418
|
-
let cfgs;
|
|
419
|
-
try {
|
|
420
|
-
cfgs = JSON.parse(await node_fs_1.default.promises.readFile(cfgPath, "utf8"));
|
|
421
|
-
}
|
|
422
|
-
catch (err) {
|
|
423
|
-
throw new Error(`failed to parse TTS config JSON "${cfgPath}"`, { cause: err });
|
|
424
|
-
}
|
|
425
|
-
/* load text processor */
|
|
426
|
-
const unicodeIndexerPath = node_path_1.default.join(assetsDir, "onnx", "unicode_indexer.json");
|
|
427
|
-
const textProcessor = new SupertonicTextProcessor(unicodeIndexerPath);
|
|
428
|
-
/* load ONNX models */
|
|
429
|
-
const opts = {};
|
|
430
|
-
const [dpOrt, textEncOrt, vectorEstOrt, vocoderOrt] = await Promise.all([
|
|
431
|
-
ORT.InferenceSession.create(node_path_1.default.join(assetsDir, "onnx", "duration_predictor.onnx"), opts),
|
|
432
|
-
ORT.InferenceSession.create(node_path_1.default.join(assetsDir, "onnx", "text_encoder.onnx"), opts),
|
|
433
|
-
ORT.InferenceSession.create(node_path_1.default.join(assetsDir, "onnx", "vector_estimator.onnx"), opts),
|
|
434
|
-
ORT.InferenceSession.create(node_path_1.default.join(assetsDir, "onnx", "vocoder.onnx"), opts)
|
|
435
|
-
]);
|
|
436
|
-
return new SupertonicTTS(cfgs, textProcessor, dpOrt, textEncOrt, vectorEstOrt, vocoderOrt);
|
|
437
|
-
}
|
|
438
|
-
/* ==== SPEECHFLOW NODE IMPLEMENTATION ==== */
|
|
439
53
|
/* SpeechFlow node for Supertonic text-to-speech conversion */
|
|
440
54
|
class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
441
55
|
/* declare official node name */
|
|
442
56
|
static name = "t2a-supertonic";
|
|
443
57
|
/* internal state */
|
|
444
|
-
|
|
445
|
-
style = null;
|
|
58
|
+
tts = null;
|
|
446
59
|
resampler = null;
|
|
60
|
+
sampleRate = 44100;
|
|
447
61
|
closing = false;
|
|
448
62
|
/* construct node */
|
|
449
63
|
constructor(id, cfg, opts, args) {
|
|
@@ -462,73 +76,97 @@ class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
|
462
76
|
async status() {
|
|
463
77
|
return {};
|
|
464
78
|
}
|
|
465
|
-
/* download HuggingFace assets */
|
|
466
|
-
async downloadAssets() {
|
|
467
|
-
/* define HuggingFace repository and required files */
|
|
468
|
-
const assetRepo = "Supertone/supertonic";
|
|
469
|
-
const assetFiles = [
|
|
470
|
-
"voice_styles/F1.json",
|
|
471
|
-
"voice_styles/F2.json",
|
|
472
|
-
"voice_styles/M1.json",
|
|
473
|
-
"voice_styles/M2.json",
|
|
474
|
-
"onnx/tts.json",
|
|
475
|
-
"onnx/duration_predictor.onnx",
|
|
476
|
-
"onnx/text_encoder.onnx",
|
|
477
|
-
"onnx/unicode_indexer.json",
|
|
478
|
-
"onnx/vector_estimator.onnx",
|
|
479
|
-
"onnx/vocoder.onnx"
|
|
480
|
-
];
|
|
481
|
-
/* create asset directories */
|
|
482
|
-
const assetDir = node_path_1.default.join(this.config.cacheDir, "supertonic");
|
|
483
|
-
await (0, mkdirp_1.mkdirp)(node_path_1.default.join(assetDir, "voice_styles"), { mode: 0o750 });
|
|
484
|
-
await (0, mkdirp_1.mkdirp)(node_path_1.default.join(assetDir, "onnx"), { mode: 0o750 });
|
|
485
|
-
/* download missing asset files */
|
|
486
|
-
for (const assetFile of assetFiles) {
|
|
487
|
-
const url = `${assetRepo}/${assetFile}`;
|
|
488
|
-
const file = node_path_1.default.join(assetDir, assetFile);
|
|
489
|
-
const stat = await node_fs_1.default.promises.stat(file).catch((_err) => null);
|
|
490
|
-
if (stat === null || !stat.isFile()) {
|
|
491
|
-
this.log("info", `downloading from HuggingFace "${url}"`);
|
|
492
|
-
const response = await HF.downloadFile({ repo: assetRepo, path: assetFile });
|
|
493
|
-
if (!response)
|
|
494
|
-
throw new Error(`failed to download from HuggingFace "${url}"`);
|
|
495
|
-
const buffer = Buffer.from(await response.arrayBuffer());
|
|
496
|
-
await node_fs_1.default.promises.writeFile(file, buffer);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
return assetDir;
|
|
500
|
-
}
|
|
501
79
|
/* open node */
|
|
502
80
|
async open() {
|
|
503
81
|
this.closing = false;
|
|
504
|
-
/*
|
|
505
|
-
const
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
82
|
+
/* load Supertonic TTS pipeline via transformers.js */
|
|
83
|
+
const model = "onnx-community/Supertonic-TTS-ONNX";
|
|
84
|
+
this.log("info", `loading Supertonic TTS model "${model}"`);
|
|
85
|
+
/* track download progress */
|
|
86
|
+
const progressState = new Map();
|
|
87
|
+
const progressCallback = (progress) => {
|
|
88
|
+
let artifact = model;
|
|
89
|
+
if (typeof progress.file === "string")
|
|
90
|
+
artifact += `:${progress.file}`;
|
|
91
|
+
let percent = 0;
|
|
92
|
+
if (typeof progress.loaded === "number" && typeof progress.total === "number")
|
|
93
|
+
percent = (progress.loaded / progress.total) * 100;
|
|
94
|
+
else if (typeof progress.progress === "number")
|
|
95
|
+
percent = progress.progress;
|
|
96
|
+
if (percent > 0)
|
|
97
|
+
progressState.set(artifact, percent);
|
|
98
|
+
};
|
|
99
|
+
let interval = setInterval(() => {
|
|
100
|
+
for (const [artifact, percent] of progressState) {
|
|
101
|
+
this.log("info", `downloaded ${percent.toFixed(2)}% of artifact "${artifact}"`);
|
|
102
|
+
if (percent >= 100.0)
|
|
103
|
+
progressState.delete(artifact);
|
|
104
|
+
}
|
|
105
|
+
if (progressState.size === 0 && interval !== null) {
|
|
106
|
+
clearInterval(interval);
|
|
107
|
+
interval = null;
|
|
108
|
+
}
|
|
109
|
+
}, 1000);
|
|
110
|
+
/* create TTS pipeline */
|
|
111
|
+
try {
|
|
112
|
+
const tts = Transformers.pipeline("text-to-speech", model, {
|
|
113
|
+
dtype: "fp32",
|
|
114
|
+
progress_callback: progressCallback
|
|
115
|
+
});
|
|
116
|
+
this.tts = await tts;
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
if (interval !== null) {
|
|
120
|
+
clearInterval(interval);
|
|
121
|
+
interval = null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (this.tts === null)
|
|
125
|
+
throw new Error("failed to instantiate Supertonic TTS pipeline");
|
|
126
|
+
/* determine sample rate from model config */
|
|
127
|
+
const config = this.tts.model?.config;
|
|
128
|
+
if (config?.sampling_rate)
|
|
129
|
+
this.sampleRate = config.sampling_rate;
|
|
130
|
+
this.log("info", `loaded Supertonic TTS model (sample rate: ${this.sampleRate}Hz)`);
|
|
517
131
|
/* establish resampler from Supertonic's output sample rate to our standard audio sample rate (48kHz) */
|
|
518
|
-
this.resampler = new speex_resampler_1.default(1, this.
|
|
132
|
+
this.resampler = new speex_resampler_1.default(1, this.sampleRate, this.config.audioSampleRate, 7);
|
|
133
|
+
/* map voice names to speaker embedding URLs */
|
|
134
|
+
const voiceUrls = {
|
|
135
|
+
"M1": "https://huggingface.co/onnx-community/Supertonic-TTS-ONNX/resolve/main/voices/M1.bin",
|
|
136
|
+
"M2": "https://huggingface.co/onnx-community/Supertonic-TTS-ONNX/resolve/main/voices/M2.bin",
|
|
137
|
+
"F1": "https://huggingface.co/onnx-community/Supertonic-TTS-ONNX/resolve/main/voices/F1.bin",
|
|
138
|
+
"F2": "https://huggingface.co/onnx-community/Supertonic-TTS-ONNX/resolve/main/voices/F2.bin"
|
|
139
|
+
};
|
|
140
|
+
const speakerEmbeddings = voiceUrls[this.params.voice];
|
|
141
|
+
if (speakerEmbeddings === undefined)
|
|
142
|
+
throw new Error(`invalid Supertonic voice "${this.params.voice}"`);
|
|
143
|
+
this.log("info", `using voice "${this.params.voice}"`);
|
|
519
144
|
/* perform text-to-speech operation with Supertonic */
|
|
520
145
|
const text2speech = async (text) => {
|
|
521
|
-
/* synthesize speech from text */
|
|
522
146
|
this.log("info", `Supertonic: input: "${text}"`);
|
|
523
|
-
|
|
147
|
+
/* generate speech using transformers.js pipeline */
|
|
148
|
+
const result = await this.tts(text, {
|
|
149
|
+
speaker_embeddings: speakerEmbeddings,
|
|
150
|
+
num_inference_steps: this.params.steps,
|
|
151
|
+
speed: this.params.speed
|
|
152
|
+
});
|
|
153
|
+
/* extract audio samples and sample rate */
|
|
154
|
+
if (!(result.audio instanceof Float32Array))
|
|
155
|
+
throw new Error("unexpected Supertonic result: audio is not a Float32Array");
|
|
156
|
+
if (typeof result.sampling_rate !== "number")
|
|
157
|
+
throw new Error("unexpected Supertonic result: sampling_rate is not a number");
|
|
158
|
+
const samples = result.audio;
|
|
159
|
+
const outputSampleRate = result.sampling_rate;
|
|
160
|
+
if (outputSampleRate !== this.sampleRate)
|
|
161
|
+
this.log("warn", `unexpected sample rate ${outputSampleRate}Hz (expected ${this.sampleRate}Hz)`);
|
|
162
|
+
/* calculate duration */
|
|
163
|
+
const duration = samples.length / outputSampleRate;
|
|
524
164
|
this.log("info", `Supertonic: synthesized ${duration.toFixed(2)}s of audio`);
|
|
525
165
|
/* convert audio samples from PCM/F32 to PCM/I16 */
|
|
526
|
-
const buffer1 =
|
|
527
|
-
for (let i = 0; i < wav.length; i++) {
|
|
528
|
-
const sample = Math.max(-1, Math.min(1, wav[i]));
|
|
529
|
-
buffer1.writeInt16LE(sample * 0x7FFF, i * 2);
|
|
530
|
-
}
|
|
166
|
+
const buffer1 = util.convertF32ToBuf(samples);
|
|
531
167
|
/* resample audio samples from Supertonic sample rate to 48kHz */
|
|
168
|
+
if (this.resampler === null)
|
|
169
|
+
throw new Error("resampler destroyed during TTS processing");
|
|
532
170
|
return this.resampler.processChunk(buffer1);
|
|
533
171
|
};
|
|
534
172
|
/* create transform stream and connect it to the Supertonic TTS */
|
|
@@ -538,7 +176,7 @@ class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
|
538
176
|
readableObjectMode: true,
|
|
539
177
|
decodeStrings: false,
|
|
540
178
|
highWaterMark: 1,
|
|
541
|
-
|
|
179
|
+
transform(chunk, encoding, callback) {
|
|
542
180
|
if (self.closing)
|
|
543
181
|
callback(new Error("stream already destroyed"));
|
|
544
182
|
else if (Buffer.isBuffer(chunk.payload))
|
|
@@ -556,13 +194,7 @@ class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
|
556
194
|
processTimeout = null;
|
|
557
195
|
}
|
|
558
196
|
};
|
|
559
|
-
|
|
560
|
-
if (self.closing) {
|
|
561
|
-
clearProcessTimeout();
|
|
562
|
-
callback(new Error("stream destroyed during processing"));
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
const buffer = await text2speech(chunk.payload);
|
|
197
|
+
text2speech(chunk.payload).then((buffer) => {
|
|
566
198
|
if (self.closing) {
|
|
567
199
|
clearProcessTimeout();
|
|
568
200
|
callback(new Error("stream destroyed during processing"));
|
|
@@ -576,16 +208,13 @@ class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
|
576
208
|
chunkNew.type = "audio";
|
|
577
209
|
chunkNew.payload = buffer;
|
|
578
210
|
chunkNew.timestampEnd = luxon_1.Duration.fromMillis(chunkNew.timestampStart.toMillis() + durationMs);
|
|
579
|
-
/* push chunk and complete transform */
|
|
580
211
|
clearProcessTimeout();
|
|
581
212
|
this.push(chunkNew);
|
|
582
213
|
callback();
|
|
583
|
-
}
|
|
584
|
-
catch (error) {
|
|
585
|
-
/* handle processing errors */
|
|
214
|
+
}).catch((error) => {
|
|
586
215
|
clearProcessTimeout();
|
|
587
216
|
callback(util.ensureError(error, "Supertonic processing failed"));
|
|
588
|
-
}
|
|
217
|
+
});
|
|
589
218
|
}
|
|
590
219
|
},
|
|
591
220
|
final(callback) {
|
|
@@ -602,16 +231,14 @@ class SpeechFlowNodeT2ASupertonic extends speechflow_node_1.default {
|
|
|
602
231
|
await util.destroyStream(this.stream);
|
|
603
232
|
this.stream = null;
|
|
604
233
|
}
|
|
605
|
-
/* destroy voice style */
|
|
606
|
-
if (this.style !== null)
|
|
607
|
-
this.style = null;
|
|
608
234
|
/* destroy resampler */
|
|
609
235
|
if (this.resampler !== null)
|
|
610
236
|
this.resampler = null;
|
|
611
|
-
/* destroy
|
|
612
|
-
if (this.
|
|
613
|
-
|
|
614
|
-
this.
|
|
237
|
+
/* destroy TTS pipeline */
|
|
238
|
+
if (this.tts !== null) {
|
|
239
|
+
/* dispose of the pipeline if possible */
|
|
240
|
+
await this.tts.dispose();
|
|
241
|
+
this.tts = null;
|
|
615
242
|
}
|
|
616
243
|
}
|
|
617
244
|
}
|