@astrake/producer-voice 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +13 -2
- package/dist/index.cjs +1260 -0
- package/dist/index.d.cts +240 -0
- package/dist/index.d.ts +240 -0
- package/dist/index.js +1197 -0
- package/package.json +38 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1260 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
AzureSpeechVoiceProvider: () => AzureSpeechVoiceProvider,
|
|
34
|
+
CommandVoiceProvider: () => CommandVoiceProvider,
|
|
35
|
+
DEFAULT_NEURAL_VOICES: () => DEFAULT_NEURAL_VOICES,
|
|
36
|
+
EDGE_DEFAULT_VOICES: () => EDGE_DEFAULT_VOICES,
|
|
37
|
+
EdgeNeuralVoiceProvider: () => EdgeNeuralVoiceProvider,
|
|
38
|
+
ElevenLabsVoiceProvider: () => ElevenLabsVoiceProvider,
|
|
39
|
+
GeminiTtsVoiceProvider: () => GeminiTtsVoiceProvider,
|
|
40
|
+
KokoroCliVoiceProvider: () => KokoroCliVoiceProvider,
|
|
41
|
+
OsNativeVoiceProvider: () => OsNativeVoiceProvider,
|
|
42
|
+
PiperCliVoiceProvider: () => PiperCliVoiceProvider,
|
|
43
|
+
PreRecordedVoiceProvider: () => PreRecordedVoiceProvider,
|
|
44
|
+
SarvamBulbulVoiceProvider: () => SarvamBulbulVoiceProvider,
|
|
45
|
+
SyntheticToneVoiceProvider: () => SyntheticToneVoiceProvider,
|
|
46
|
+
VoiceDiskCache: () => VoiceDiskCache,
|
|
47
|
+
applyPronunciationLexicon: () => applyPronunciationLexicon,
|
|
48
|
+
computeAudioZcrStd: () => computeAudioZcrStd,
|
|
49
|
+
createAutoVoiceProvider: () => createAutoVoiceProvider,
|
|
50
|
+
emitCaptionsSrt: () => emitCaptionsSrt,
|
|
51
|
+
emitCaptionsVtt: () => emitCaptionsVtt,
|
|
52
|
+
escapeXml: () => escapeXml,
|
|
53
|
+
estimateWordTimings: () => estimateWordTimings,
|
|
54
|
+
probeSourceAudioSampleRate: () => probeSourceAudioSampleRate,
|
|
55
|
+
readWavDurationMs: () => readWavDurationMs,
|
|
56
|
+
readWavHeaderInfo: () => readWavHeaderInfo,
|
|
57
|
+
resolveEdgeVoiceName: () => resolveEdgeVoiceName,
|
|
58
|
+
resolveNeuralVoiceName: () => resolveNeuralVoiceName,
|
|
59
|
+
transcodeAudioTo48kMonoWav: () => transcodeAudioTo48kMonoWav,
|
|
60
|
+
transcodeAudioTo48kStereoWav: () => transcodeAudioTo48kStereoWav,
|
|
61
|
+
writePcm16MonoWav: () => writePcm16MonoWav
|
|
62
|
+
});
|
|
63
|
+
module.exports = __toCommonJS(index_exports);
|
|
64
|
+
var import_node_child_process4 = require("child_process");
|
|
65
|
+
|
|
66
|
+
// src/providers/azure.ts
|
|
67
|
+
var import_promises2 = __toESM(require("fs/promises"), 1);
|
|
68
|
+
var import_node_path2 = __toESM(require("path"), 1);
|
|
69
|
+
|
|
70
|
+
// src/cache.ts
|
|
71
|
+
var import_node_crypto = __toESM(require("crypto"), 1);
|
|
72
|
+
var import_promises = __toESM(require("fs/promises"), 1);
|
|
73
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
74
|
+
var VoiceDiskCache = class {
|
|
75
|
+
constructor(cacheDir = import_node_path.default.join(process.cwd(), ".producer-cache", "voice")) {
|
|
76
|
+
this.cacheDir = cacheDir;
|
|
77
|
+
}
|
|
78
|
+
cacheDir;
|
|
79
|
+
computeKey(payload) {
|
|
80
|
+
return import_node_crypto.default.createHash("sha256").update(JSON.stringify(payload)).digest("hex");
|
|
81
|
+
}
|
|
82
|
+
async get(key, outWavPath) {
|
|
83
|
+
const cachedWav = import_node_path.default.join(this.cacheDir, `${key}.wav`);
|
|
84
|
+
const cachedMeta = import_node_path.default.join(this.cacheDir, `${key}.json`);
|
|
85
|
+
try {
|
|
86
|
+
const [wavOk, metaRaw] = await Promise.all([
|
|
87
|
+
import_promises.default.access(cachedWav).then(() => true).catch(() => false),
|
|
88
|
+
import_promises.default.readFile(cachedMeta, "utf8").catch(() => null)
|
|
89
|
+
]);
|
|
90
|
+
if (!wavOk || !metaRaw) return null;
|
|
91
|
+
const meta = JSON.parse(metaRaw);
|
|
92
|
+
await import_promises.default.mkdir(import_node_path.default.dirname(outWavPath), { recursive: true });
|
|
93
|
+
await import_promises.default.copyFile(cachedWav, outWavPath);
|
|
94
|
+
return {
|
|
95
|
+
wavPath: outWavPath,
|
|
96
|
+
durationMs: meta.durationMs,
|
|
97
|
+
words: meta.words,
|
|
98
|
+
provenance: {
|
|
99
|
+
...meta.provenance,
|
|
100
|
+
cacheHit: true
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async put(key, outWavPath, durationMs, words, provenance) {
|
|
108
|
+
await import_promises.default.mkdir(this.cacheDir, { recursive: true });
|
|
109
|
+
const cachedWav = import_node_path.default.join(this.cacheDir, `${key}.wav`);
|
|
110
|
+
const cachedMeta = import_node_path.default.join(this.cacheDir, `${key}.json`);
|
|
111
|
+
await import_promises.default.copyFile(outWavPath, cachedWav);
|
|
112
|
+
await import_promises.default.writeFile(cachedMeta, JSON.stringify({ durationMs, words, provenance }, null, 2));
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// src/dsp.ts
|
|
117
|
+
var import_node_child_process = require("child_process");
|
|
118
|
+
var import_node_fs = __toESM(require("fs"), 1);
|
|
119
|
+
function estimateWordTimings(text, durationMs) {
|
|
120
|
+
const words = text.trim().split(/\s+/).filter(Boolean);
|
|
121
|
+
if (words.length === 0) return [];
|
|
122
|
+
const totalChars = words.reduce((acc, w) => acc + Math.max(2, w.length), 0);
|
|
123
|
+
let cursor = 0;
|
|
124
|
+
return words.map((word) => {
|
|
125
|
+
const weight = Math.max(2, word.length) / totalChars;
|
|
126
|
+
const span = durationMs * weight;
|
|
127
|
+
const entry = {
|
|
128
|
+
word,
|
|
129
|
+
startMs: Math.round(cursor),
|
|
130
|
+
endMs: Math.round(cursor + span)
|
|
131
|
+
};
|
|
132
|
+
cursor += span;
|
|
133
|
+
return entry;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function readWavHeaderInfo(wavBytes) {
|
|
137
|
+
if (wavBytes.length < 44 || wavBytes.toString("ascii", 0, 4) !== "RIFF") {
|
|
138
|
+
return {
|
|
139
|
+
sampleRateHz: 0,
|
|
140
|
+
channels: 0,
|
|
141
|
+
bitsPerSample: 0,
|
|
142
|
+
durationMs: 0,
|
|
143
|
+
isSyntheticTag: false
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const channels = wavBytes.readUInt16LE(22);
|
|
147
|
+
const sampleRateHz = wavBytes.readUInt32LE(24);
|
|
148
|
+
const byteRate = wavBytes.readUInt32LE(28);
|
|
149
|
+
const bitsPerSample = wavBytes.readUInt16LE(34);
|
|
150
|
+
let dataSize = wavBytes.length - 44;
|
|
151
|
+
let off = 12;
|
|
152
|
+
let isSyntheticTag = false;
|
|
153
|
+
while (off + 8 <= wavBytes.length) {
|
|
154
|
+
const chunkId = wavBytes.toString("ascii", off, off + 4);
|
|
155
|
+
const chunkSize = wavBytes.readUInt32LE(off + 4);
|
|
156
|
+
if (chunkId === "data") {
|
|
157
|
+
dataSize = chunkSize;
|
|
158
|
+
} else if (chunkId === "LIST" && off + 12 <= wavBytes.length) {
|
|
159
|
+
const slice = wavBytes.subarray(off + 8, Math.min(wavBytes.length, off + 8 + chunkSize));
|
|
160
|
+
if (slice.toString("latin1").includes("astrake-synthetic-tone")) {
|
|
161
|
+
isSyntheticTag = true;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (chunkSize === 0 && off + 8 >= wavBytes.length) break;
|
|
165
|
+
off += 8 + chunkSize + chunkSize % 2;
|
|
166
|
+
}
|
|
167
|
+
const durationMs = byteRate > 0 ? Math.round(dataSize / byteRate * 1e3) : 0;
|
|
168
|
+
return {
|
|
169
|
+
sampleRateHz,
|
|
170
|
+
channels,
|
|
171
|
+
bitsPerSample,
|
|
172
|
+
durationMs,
|
|
173
|
+
isSyntheticTag
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function readWavDurationMs(wavBytes) {
|
|
177
|
+
return readWavHeaderInfo(wavBytes).durationMs;
|
|
178
|
+
}
|
|
179
|
+
function computeAudioZcrStd(wavBytes) {
|
|
180
|
+
const hdr = readWavHeaderInfo(wavBytes);
|
|
181
|
+
if (hdr.sampleRateHz <= 0 || hdr.bitsPerSample !== 16) return void 0;
|
|
182
|
+
let dataOffset = 44;
|
|
183
|
+
let dataLen = Math.max(0, wavBytes.length - 44);
|
|
184
|
+
let off = 12;
|
|
185
|
+
while (off + 8 <= wavBytes.length) {
|
|
186
|
+
const cid = wavBytes.toString("ascii", off, off + 4);
|
|
187
|
+
const csize = wavBytes.readUInt32LE(off + 4);
|
|
188
|
+
if (cid === "data") {
|
|
189
|
+
dataOffset = off + 8;
|
|
190
|
+
dataLen = Math.min(csize, wavBytes.length - dataOffset);
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
off += 8 + csize + csize % 2;
|
|
194
|
+
}
|
|
195
|
+
const ch = Math.max(1, hdr.channels);
|
|
196
|
+
const frameCount = Math.floor(dataLen / (2 * ch));
|
|
197
|
+
const win = Math.max(64, Math.floor(hdr.sampleRateHz * 0.05));
|
|
198
|
+
if (frameCount < win * 2) return void 0;
|
|
199
|
+
const zcrs = [];
|
|
200
|
+
for (let start = 0; start + win <= frameCount; start += win) {
|
|
201
|
+
let prevSign = wavBytes.readInt16LE(dataOffset + start * ch * 2) >= 0;
|
|
202
|
+
let cross = 0;
|
|
203
|
+
for (let i = 1; i < win; i++) {
|
|
204
|
+
const sample = wavBytes.readInt16LE(dataOffset + (start + i) * ch * 2);
|
|
205
|
+
const sign = sample >= 0;
|
|
206
|
+
if (sign !== prevSign) {
|
|
207
|
+
cross++;
|
|
208
|
+
prevSign = sign;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
zcrs.push(cross / win);
|
|
212
|
+
}
|
|
213
|
+
if (zcrs.length < 2) return void 0;
|
|
214
|
+
const mean = zcrs.reduce((a, b) => a + b, 0) / zcrs.length;
|
|
215
|
+
const variance = zcrs.reduce((a, b) => a + (b - mean) ** 2, 0) / zcrs.length;
|
|
216
|
+
return Number(Math.sqrt(variance).toFixed(5));
|
|
217
|
+
}
|
|
218
|
+
function probeSourceAudioSampleRate(srcPath) {
|
|
219
|
+
try {
|
|
220
|
+
const raw = import_node_fs.default.readFileSync(srcPath);
|
|
221
|
+
const hdr = readWavHeaderInfo(raw);
|
|
222
|
+
if (hdr.sampleRateHz > 0) {
|
|
223
|
+
return { sampleRateHz: hdr.sampleRateHz, isSyntheticTag: hdr.isSyntheticTag };
|
|
224
|
+
}
|
|
225
|
+
} catch {
|
|
226
|
+
}
|
|
227
|
+
const res = (0, import_node_child_process.spawnSync)(
|
|
228
|
+
"ffprobe",
|
|
229
|
+
[
|
|
230
|
+
"-v",
|
|
231
|
+
"error",
|
|
232
|
+
"-select_streams",
|
|
233
|
+
"a:0",
|
|
234
|
+
"-show_entries",
|
|
235
|
+
"stream=sample_rate",
|
|
236
|
+
"-of",
|
|
237
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
238
|
+
srcPath
|
|
239
|
+
],
|
|
240
|
+
{ encoding: "utf8", stdio: "pipe" }
|
|
241
|
+
);
|
|
242
|
+
const parsed = Number.parseInt((res.stdout ?? "").trim(), 10);
|
|
243
|
+
return {
|
|
244
|
+
sampleRateHz: Number.isFinite(parsed) && parsed > 0 ? parsed : 0,
|
|
245
|
+
isSyntheticTag: false
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
function writePcm16MonoWav(samples, sampleRate = 48e3, opts) {
|
|
249
|
+
const dataLen = samples.length * 2;
|
|
250
|
+
let listChunk = Buffer.alloc(0);
|
|
251
|
+
if (opts?.softwareTag) {
|
|
252
|
+
const tagBytes = Buffer.from(`${opts.softwareTag}\0`, "ascii");
|
|
253
|
+
const paddedLen = tagBytes.length + tagBytes.length % 2;
|
|
254
|
+
const subChunkSize = 4 + 4 + paddedLen;
|
|
255
|
+
listChunk = Buffer.alloc(8 + 4 + subChunkSize);
|
|
256
|
+
listChunk.write("LIST", 0);
|
|
257
|
+
listChunk.writeUInt32LE(4 + subChunkSize, 4);
|
|
258
|
+
listChunk.write("INFO", 8);
|
|
259
|
+
listChunk.write("ISFT", 12);
|
|
260
|
+
listChunk.writeUInt32LE(tagBytes.length, 16);
|
|
261
|
+
tagBytes.copy(listChunk, 20);
|
|
262
|
+
}
|
|
263
|
+
const buf = Buffer.alloc(44 + dataLen + listChunk.length);
|
|
264
|
+
buf.write("RIFF", 0);
|
|
265
|
+
buf.writeUInt32LE(36 + dataLen + listChunk.length, 4);
|
|
266
|
+
buf.write("WAVE", 8);
|
|
267
|
+
buf.write("fmt ", 12);
|
|
268
|
+
buf.writeUInt32LE(16, 16);
|
|
269
|
+
buf.writeUInt16LE(1, 20);
|
|
270
|
+
buf.writeUInt16LE(1, 22);
|
|
271
|
+
buf.writeUInt32LE(sampleRate, 24);
|
|
272
|
+
buf.writeUInt32LE(sampleRate * 2, 28);
|
|
273
|
+
buf.writeUInt16LE(2, 32);
|
|
274
|
+
buf.writeUInt16LE(16, 34);
|
|
275
|
+
buf.write("data", 36);
|
|
276
|
+
buf.writeUInt32LE(dataLen, 40);
|
|
277
|
+
for (let i = 0; i < samples.length; i++) {
|
|
278
|
+
buf.writeInt16LE(samples[i] ?? 0, 44 + i * 2);
|
|
279
|
+
}
|
|
280
|
+
if (listChunk.length > 0) {
|
|
281
|
+
listChunk.copy(buf, 44 + dataLen);
|
|
282
|
+
}
|
|
283
|
+
return buf;
|
|
284
|
+
}
|
|
285
|
+
function transcodeAudioTo48kMonoWav(srcPath, outWavPath) {
|
|
286
|
+
const res = (0, import_node_child_process.spawnSync)(
|
|
287
|
+
"ffmpeg",
|
|
288
|
+
[
|
|
289
|
+
"-y",
|
|
290
|
+
"-hide_banner",
|
|
291
|
+
"-loglevel",
|
|
292
|
+
"error",
|
|
293
|
+
"-i",
|
|
294
|
+
srcPath,
|
|
295
|
+
"-ar",
|
|
296
|
+
"48000",
|
|
297
|
+
"-ac",
|
|
298
|
+
"1",
|
|
299
|
+
"-c:a",
|
|
300
|
+
"pcm_s16le",
|
|
301
|
+
outWavPath
|
|
302
|
+
],
|
|
303
|
+
{ encoding: "utf8", stdio: "pipe" }
|
|
304
|
+
);
|
|
305
|
+
if (res.status !== 0) {
|
|
306
|
+
throw new Error(`ffmpeg audio normalization failed for ${srcPath}: ${res.stderr}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function transcodeAudioTo48kStereoWav(srcPath, outWavPath) {
|
|
310
|
+
const res = (0, import_node_child_process.spawnSync)(
|
|
311
|
+
"ffmpeg",
|
|
312
|
+
[
|
|
313
|
+
"-y",
|
|
314
|
+
"-hide_banner",
|
|
315
|
+
"-loglevel",
|
|
316
|
+
"error",
|
|
317
|
+
"-i",
|
|
318
|
+
srcPath,
|
|
319
|
+
"-ar",
|
|
320
|
+
"48000",
|
|
321
|
+
"-ac",
|
|
322
|
+
"2",
|
|
323
|
+
"-c:a",
|
|
324
|
+
"pcm_s16le",
|
|
325
|
+
outWavPath
|
|
326
|
+
],
|
|
327
|
+
{ encoding: "utf8", stdio: "pipe" }
|
|
328
|
+
);
|
|
329
|
+
if (res.status !== 0) {
|
|
330
|
+
throw new Error(`ffmpeg stereo normalization failed for ${srcPath}: ${res.stderr}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/lexicon.ts
|
|
335
|
+
function escapeXml(str) {
|
|
336
|
+
return str.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
337
|
+
}
|
|
338
|
+
function escapeRegExp(str) {
|
|
339
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
340
|
+
}
|
|
341
|
+
function resolveLexiconForLocale(locale, lexicons) {
|
|
342
|
+
if (!lexicons) return {};
|
|
343
|
+
const merged = {};
|
|
344
|
+
const base = locale.split("-")[0];
|
|
345
|
+
if (base && lexicons[base]) {
|
|
346
|
+
Object.assign(merged, lexicons[base]);
|
|
347
|
+
}
|
|
348
|
+
if (lexicons[locale]) {
|
|
349
|
+
Object.assign(merged, lexicons[locale]);
|
|
350
|
+
}
|
|
351
|
+
return merged;
|
|
352
|
+
}
|
|
353
|
+
function applyPronunciationLexicon(text, locale, lexicons) {
|
|
354
|
+
const entries = Object.entries(resolveLexiconForLocale(locale, lexicons)).sort(
|
|
355
|
+
([a], [b]) => b.length - a.length
|
|
356
|
+
);
|
|
357
|
+
if (entries.length === 0) {
|
|
358
|
+
return {
|
|
359
|
+
spokenText: text,
|
|
360
|
+
ssmlFragment: escapeXml(text)
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
let spokenText = text;
|
|
364
|
+
const pattern = new RegExp(entries.map(([k]) => escapeRegExp(k)).join("|"), "g");
|
|
365
|
+
spokenText = spokenText.replace(pattern, (matched) => {
|
|
366
|
+
const e = entries.find(([k]) => k === matched)?.[1];
|
|
367
|
+
return e?.spoken ?? matched;
|
|
368
|
+
});
|
|
369
|
+
let ssmlFragment = "";
|
|
370
|
+
let lastIdx = 0;
|
|
371
|
+
pattern.lastIndex = 0;
|
|
372
|
+
let m = pattern.exec(text);
|
|
373
|
+
while (m !== null) {
|
|
374
|
+
ssmlFragment += escapeXml(text.slice(lastIdx, m.index));
|
|
375
|
+
const matched = m[0];
|
|
376
|
+
const entry = entries.find(([k]) => k === matched)?.[1];
|
|
377
|
+
if (entry?.ipa) {
|
|
378
|
+
ssmlFragment += `<phoneme alphabet="ipa" ph="${escapeXml(entry.ipa)}">${escapeXml(matched)}</phoneme>`;
|
|
379
|
+
} else if (entry?.spoken) {
|
|
380
|
+
ssmlFragment += `<sub alias="${escapeXml(entry.spoken)}">${escapeXml(matched)}</sub>`;
|
|
381
|
+
} else {
|
|
382
|
+
ssmlFragment += escapeXml(matched);
|
|
383
|
+
}
|
|
384
|
+
lastIdx = m.index + matched.length;
|
|
385
|
+
m = pattern.exec(text);
|
|
386
|
+
}
|
|
387
|
+
ssmlFragment += escapeXml(text.slice(lastIdx));
|
|
388
|
+
return { spokenText, ssmlFragment };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/types.ts
|
|
392
|
+
var DEFAULT_NEURAL_VOICES = {
|
|
393
|
+
"en-IN": "en-IN-NeerjaNeural",
|
|
394
|
+
"hi-IN": "hi-IN-SwaraNeural",
|
|
395
|
+
"bn-IN": "bn-IN-TanishaaNeural",
|
|
396
|
+
"ta-IN": "ta-IN-PallaviNeural",
|
|
397
|
+
"te-IN": "te-IN-ShrutiNeural",
|
|
398
|
+
"mr-IN": "mr-IN-AarohiNeural",
|
|
399
|
+
"en-US": "en-US-AriaNeural",
|
|
400
|
+
"en-GB": "en-GB-SoniaNeural"
|
|
401
|
+
};
|
|
402
|
+
var EDGE_DEFAULT_VOICES = DEFAULT_NEURAL_VOICES;
|
|
403
|
+
function resolveNeuralVoiceName(locale, voice) {
|
|
404
|
+
if (voice && voice.trim().length > 0) return voice.trim();
|
|
405
|
+
if (locale && DEFAULT_NEURAL_VOICES[locale]) {
|
|
406
|
+
return DEFAULT_NEURAL_VOICES[locale];
|
|
407
|
+
}
|
|
408
|
+
const base = locale?.split("-")[0];
|
|
409
|
+
if (base === "hi") return DEFAULT_NEURAL_VOICES["hi-IN"] ?? "hi-IN-SwaraNeural";
|
|
410
|
+
if (base === "bn") return DEFAULT_NEURAL_VOICES["bn-IN"] ?? "bn-IN-TanishaaNeural";
|
|
411
|
+
return DEFAULT_NEURAL_VOICES["en-IN"] ?? "en-IN-NeerjaNeural";
|
|
412
|
+
}
|
|
413
|
+
var resolveEdgeVoiceName = resolveNeuralVoiceName;
|
|
414
|
+
|
|
415
|
+
// src/providers/azure.ts
|
|
416
|
+
var AzureSpeechVoiceProvider = class {
|
|
417
|
+
id = "azure-speech";
|
|
418
|
+
apiKey;
|
|
419
|
+
region;
|
|
420
|
+
endpoint;
|
|
421
|
+
cache;
|
|
422
|
+
timeoutMs;
|
|
423
|
+
constructor(options = {}) {
|
|
424
|
+
this.apiKey = options.apiKey ?? process.env.AZURE_SPEECH_KEY ?? "";
|
|
425
|
+
this.region = options.region ?? process.env.AZURE_SPEECH_REGION ?? "centralindia";
|
|
426
|
+
this.endpoint = options.endpoint ?? `https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`;
|
|
427
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
428
|
+
this.timeoutMs = options.timeoutMs ?? 2e4;
|
|
429
|
+
}
|
|
430
|
+
async synthesize(req) {
|
|
431
|
+
if (!this.apiKey && this.endpoint.startsWith("https://")) {
|
|
432
|
+
throw new Error(
|
|
433
|
+
"AzureSpeechVoiceProvider requires AZURE_SPEECH_KEY and AZURE_SPEECH_REGION."
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
const voice = resolveNeuralVoiceName(req.locale, req.voice);
|
|
437
|
+
const locale = req.locale ?? "en-IN";
|
|
438
|
+
const speedPct = Math.round(((req.speed ?? 1) - 1) * 100);
|
|
439
|
+
const rateAttr = `${speedPct >= 0 ? "+" : ""}${speedPct}%`;
|
|
440
|
+
const { ssmlFragment } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
441
|
+
const ssml = `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${escapeXml(locale)}"><voice name="${escapeXml(voice)}"><prosody rate="${rateAttr}">${ssmlFragment}</prosody></voice></speak>`;
|
|
442
|
+
const key = this.cache.computeKey({
|
|
443
|
+
provider: this.id,
|
|
444
|
+
voice,
|
|
445
|
+
locale,
|
|
446
|
+
rateAttr,
|
|
447
|
+
ssml
|
|
448
|
+
});
|
|
449
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
450
|
+
if (hit) return hit;
|
|
451
|
+
const controller = new AbortController();
|
|
452
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
453
|
+
let audioBytes;
|
|
454
|
+
try {
|
|
455
|
+
const res = await fetch(this.endpoint, {
|
|
456
|
+
method: "POST",
|
|
457
|
+
headers: {
|
|
458
|
+
"Ocp-Apim-Subscription-Key": this.apiKey,
|
|
459
|
+
"Content-Type": "application/ssml+xml",
|
|
460
|
+
"X-Microsoft-OutputFormat": "riff-48khz-16bit-mono-pcm",
|
|
461
|
+
"User-Agent": "astrake-producer/0.3.2"
|
|
462
|
+
},
|
|
463
|
+
body: ssml,
|
|
464
|
+
signal: controller.signal
|
|
465
|
+
});
|
|
466
|
+
if (!res.ok) {
|
|
467
|
+
const msg = await res.text().catch(() => "");
|
|
468
|
+
throw new Error(`Azure Speech REST ${res.status}: ${msg}`);
|
|
469
|
+
}
|
|
470
|
+
audioBytes = Buffer.from(await res.arrayBuffer());
|
|
471
|
+
} finally {
|
|
472
|
+
clearTimeout(timer);
|
|
473
|
+
}
|
|
474
|
+
await import_promises2.default.mkdir(import_node_path2.default.dirname(req.outWavPath), { recursive: true });
|
|
475
|
+
await import_promises2.default.writeFile(req.outWavPath, audioBytes);
|
|
476
|
+
const durationMs = Math.max(150, readWavDurationMs(audioBytes));
|
|
477
|
+
const words = estimateWordTimings(req.text, durationMs);
|
|
478
|
+
const provenance = {
|
|
479
|
+
providerId: this.id,
|
|
480
|
+
voice,
|
|
481
|
+
locale,
|
|
482
|
+
sourceSampleRateHz: 48e3,
|
|
483
|
+
isSynthetic: false,
|
|
484
|
+
isRoboticFallback: false,
|
|
485
|
+
cacheHit: false
|
|
486
|
+
};
|
|
487
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
488
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
// src/providers/cli.ts
|
|
493
|
+
var import_node_child_process2 = require("child_process");
|
|
494
|
+
var import_promises3 = __toESM(require("fs/promises"), 1);
|
|
495
|
+
var import_node_path3 = __toESM(require("path"), 1);
|
|
496
|
+
var CommandVoiceProvider = class {
|
|
497
|
+
constructor(command, args = []) {
|
|
498
|
+
this.command = command;
|
|
499
|
+
this.args = args;
|
|
500
|
+
}
|
|
501
|
+
command;
|
|
502
|
+
args;
|
|
503
|
+
id = "external-command";
|
|
504
|
+
async synthesize(req) {
|
|
505
|
+
await import_promises3.default.mkdir(import_node_path3.default.dirname(req.outWavPath), { recursive: true });
|
|
506
|
+
const locale = req.locale ?? "en-IN";
|
|
507
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
508
|
+
const res = (0, import_node_child_process2.spawnSync)(this.command, this.args, {
|
|
509
|
+
input: JSON.stringify({ ...req, text: spokenText }),
|
|
510
|
+
encoding: "utf8",
|
|
511
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
512
|
+
});
|
|
513
|
+
if (res.status !== 0) {
|
|
514
|
+
throw new Error(`External voice command failed (${res.status}): ${res.stderr}`);
|
|
515
|
+
}
|
|
516
|
+
const parsed = JSON.parse(res.stdout.trim());
|
|
517
|
+
const wavPath = parsed.wavPath ?? req.outWavPath;
|
|
518
|
+
const probed = probeSourceAudioSampleRate(wavPath);
|
|
519
|
+
const bytes = await import_promises3.default.readFile(wavPath);
|
|
520
|
+
const hdr = readWavHeaderInfo(bytes);
|
|
521
|
+
const durationMs = parsed.durationMs ?? hdr.durationMs;
|
|
522
|
+
const zcrStd = computeAudioZcrStd(bytes);
|
|
523
|
+
return {
|
|
524
|
+
wavPath,
|
|
525
|
+
durationMs,
|
|
526
|
+
words: parsed.words ?? estimateWordTimings(req.text, durationMs),
|
|
527
|
+
provenance: parsed.provenance ?? {
|
|
528
|
+
providerId: this.id,
|
|
529
|
+
voice: req.voice ?? "custom",
|
|
530
|
+
locale,
|
|
531
|
+
sourceSampleRateHz: probed.sampleRateHz || 24e3,
|
|
532
|
+
isSynthetic: false,
|
|
533
|
+
isRoboticFallback: false,
|
|
534
|
+
zcrStd,
|
|
535
|
+
cacheHit: false
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
var KokoroCliVoiceProvider = class {
|
|
541
|
+
id = "kokoro-cli";
|
|
542
|
+
command;
|
|
543
|
+
cache;
|
|
544
|
+
constructor(options = {}) {
|
|
545
|
+
this.command = options.command ?? "kokoro-tts";
|
|
546
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
547
|
+
}
|
|
548
|
+
async synthesize(req) {
|
|
549
|
+
const locale = req.locale ?? "en-IN";
|
|
550
|
+
const voice = req.voice ?? "af_heart";
|
|
551
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
552
|
+
const key = this.cache.computeKey({ provider: this.id, voice, locale, spokenText });
|
|
553
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
554
|
+
if (hit) return hit;
|
|
555
|
+
await import_promises3.default.mkdir(import_node_path3.default.dirname(req.outWavPath), { recursive: true });
|
|
556
|
+
const tmpOut = `${req.outWavPath}.raw.wav`;
|
|
557
|
+
const args = ["--text", spokenText, "--voice", voice, "--output", tmpOut];
|
|
558
|
+
const res = (0, import_node_child_process2.spawnSync)(this.command, args, { encoding: "utf8", stdio: "pipe" });
|
|
559
|
+
if (res.status !== 0) {
|
|
560
|
+
throw new Error(
|
|
561
|
+
`KokoroCliVoiceProvider (${this.command}) failed (${res.status}): ${res.stderr}`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
const probed = probeSourceAudioSampleRate(tmpOut);
|
|
565
|
+
transcodeAudioTo48kMonoWav(tmpOut, req.outWavPath);
|
|
566
|
+
await import_promises3.default.rm(tmpOut, { force: true }).catch(() => void 0);
|
|
567
|
+
const bytes = await import_promises3.default.readFile(req.outWavPath);
|
|
568
|
+
const durationMs = Math.max(150, readWavHeaderInfo(bytes).durationMs);
|
|
569
|
+
const words = estimateWordTimings(req.text, durationMs);
|
|
570
|
+
const provenance = {
|
|
571
|
+
providerId: this.id,
|
|
572
|
+
voice,
|
|
573
|
+
locale,
|
|
574
|
+
sourceSampleRateHz: probed.sampleRateHz || 24e3,
|
|
575
|
+
isSynthetic: false,
|
|
576
|
+
isRoboticFallback: false,
|
|
577
|
+
zcrStd: computeAudioZcrStd(bytes),
|
|
578
|
+
cacheHit: false
|
|
579
|
+
};
|
|
580
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
581
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
var PiperCliVoiceProvider = class {
|
|
585
|
+
id = "piper-cli";
|
|
586
|
+
command;
|
|
587
|
+
modelPath;
|
|
588
|
+
cache;
|
|
589
|
+
constructor(options = {}) {
|
|
590
|
+
this.command = options.command ?? "piper";
|
|
591
|
+
this.modelPath = options.modelPath ?? process.env.PIPER_MODEL_PATH ?? "";
|
|
592
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
593
|
+
}
|
|
594
|
+
async synthesize(req) {
|
|
595
|
+
if (!this.modelPath) {
|
|
596
|
+
throw new Error("PiperCliVoiceProvider requires options.modelPath or PIPER_MODEL_PATH.");
|
|
597
|
+
}
|
|
598
|
+
const locale = req.locale ?? "en-IN";
|
|
599
|
+
const voice = req.voice ?? import_node_path3.default.basename(this.modelPath);
|
|
600
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
601
|
+
const key = this.cache.computeKey({ provider: this.id, voice, locale, spokenText });
|
|
602
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
603
|
+
if (hit) return hit;
|
|
604
|
+
await import_promises3.default.mkdir(import_node_path3.default.dirname(req.outWavPath), { recursive: true });
|
|
605
|
+
const tmpOut = `${req.outWavPath}.raw.wav`;
|
|
606
|
+
const res = (0, import_node_child_process2.spawnSync)(this.command, ["--model", this.modelPath, "--output_file", tmpOut], {
|
|
607
|
+
input: spokenText,
|
|
608
|
+
encoding: "utf8",
|
|
609
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
610
|
+
});
|
|
611
|
+
if (res.status !== 0) {
|
|
612
|
+
throw new Error(
|
|
613
|
+
`PiperCliVoiceProvider (${this.command}) failed (${res.status}): ${res.stderr}`
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
const probed = probeSourceAudioSampleRate(tmpOut);
|
|
617
|
+
transcodeAudioTo48kMonoWav(tmpOut, req.outWavPath);
|
|
618
|
+
await import_promises3.default.rm(tmpOut, { force: true }).catch(() => void 0);
|
|
619
|
+
const bytes = await import_promises3.default.readFile(req.outWavPath);
|
|
620
|
+
const durationMs = Math.max(150, readWavHeaderInfo(bytes).durationMs);
|
|
621
|
+
const words = estimateWordTimings(req.text, durationMs);
|
|
622
|
+
const provenance = {
|
|
623
|
+
providerId: this.id,
|
|
624
|
+
voice,
|
|
625
|
+
locale,
|
|
626
|
+
sourceSampleRateHz: probed.sampleRateHz || 22050,
|
|
627
|
+
isSynthetic: false,
|
|
628
|
+
isRoboticFallback: false,
|
|
629
|
+
zcrStd: computeAudioZcrStd(bytes),
|
|
630
|
+
cacheHit: false
|
|
631
|
+
};
|
|
632
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
633
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
// src/providers/elevenlabs.ts
|
|
638
|
+
var import_node_crypto2 = __toESM(require("crypto"), 1);
|
|
639
|
+
var import_promises4 = __toESM(require("fs/promises"), 1);
|
|
640
|
+
var import_node_os = __toESM(require("os"), 1);
|
|
641
|
+
var import_node_path4 = __toESM(require("path"), 1);
|
|
642
|
+
function alignmentCharsToWords(alignment) {
|
|
643
|
+
const chars = alignment?.characters ?? [];
|
|
644
|
+
const starts = alignment?.character_start_times_seconds ?? [];
|
|
645
|
+
const ends = alignment?.character_end_times_seconds ?? [];
|
|
646
|
+
if (chars.length === 0 || chars.length !== starts.length || chars.length !== ends.length) {
|
|
647
|
+
return [];
|
|
648
|
+
}
|
|
649
|
+
const out = [];
|
|
650
|
+
let cur = "";
|
|
651
|
+
let wStart = -1;
|
|
652
|
+
let wEnd = 0;
|
|
653
|
+
for (let i = 0; i < chars.length; i++) {
|
|
654
|
+
const ch = chars[i] ?? "";
|
|
655
|
+
const sMs = Math.round((starts[i] ?? 0) * 1e3);
|
|
656
|
+
const eMs = Math.round((ends[i] ?? 0) * 1e3);
|
|
657
|
+
if (/\s/.test(ch)) {
|
|
658
|
+
if (cur.length > 0) {
|
|
659
|
+
out.push({ word: cur, startMs: wStart, endMs: Math.max(wStart + 20, wEnd) });
|
|
660
|
+
cur = "";
|
|
661
|
+
wStart = -1;
|
|
662
|
+
}
|
|
663
|
+
} else {
|
|
664
|
+
if (wStart < 0) wStart = sMs;
|
|
665
|
+
wEnd = eMs;
|
|
666
|
+
cur += ch;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (cur.length > 0 && wStart >= 0) {
|
|
670
|
+
out.push({ word: cur, startMs: wStart, endMs: Math.max(wStart + 20, wEnd) });
|
|
671
|
+
}
|
|
672
|
+
return out;
|
|
673
|
+
}
|
|
674
|
+
var ElevenLabsVoiceProvider = class {
|
|
675
|
+
id = "elevenlabs";
|
|
676
|
+
apiKey;
|
|
677
|
+
defaultVoiceId;
|
|
678
|
+
modelId;
|
|
679
|
+
outputFormat;
|
|
680
|
+
endpointBase;
|
|
681
|
+
cache;
|
|
682
|
+
timeoutMs;
|
|
683
|
+
constructor(options = {}) {
|
|
684
|
+
this.apiKey = options.apiKey ?? process.env.ELEVENLABS_API_KEY ?? "";
|
|
685
|
+
this.defaultVoiceId = options.voiceId ?? "21m00Tcm4TlvDq8ikWAM";
|
|
686
|
+
this.modelId = options.modelId ?? "eleven_multilingual_v2";
|
|
687
|
+
this.outputFormat = options.outputFormat ?? "mp3_44100_128";
|
|
688
|
+
this.endpointBase = options.endpointBase ?? "https://api.elevenlabs.io";
|
|
689
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
690
|
+
this.timeoutMs = options.timeoutMs ?? 25e3;
|
|
691
|
+
}
|
|
692
|
+
async synthesize(req) {
|
|
693
|
+
if (!this.apiKey && this.endpointBase.startsWith("https://")) {
|
|
694
|
+
throw new Error("ElevenLabsVoiceProvider requires ELEVENLABS_API_KEY.");
|
|
695
|
+
}
|
|
696
|
+
const voiceId = req.voice && req.voice.trim().length > 0 ? req.voice.trim() : this.defaultVoiceId;
|
|
697
|
+
const locale = req.locale ?? "en-IN";
|
|
698
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
699
|
+
const key = this.cache.computeKey({
|
|
700
|
+
provider: this.id,
|
|
701
|
+
modelId: this.modelId,
|
|
702
|
+
outputFormat: this.outputFormat,
|
|
703
|
+
voiceId,
|
|
704
|
+
spokenText
|
|
705
|
+
});
|
|
706
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
707
|
+
if (hit) return hit;
|
|
708
|
+
const controller = new AbortController();
|
|
709
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
710
|
+
let audioBytes;
|
|
711
|
+
let words = [];
|
|
712
|
+
try {
|
|
713
|
+
const url = `${this.endpointBase.replace(/\/$/, "")}/v1/text-to-speech/${encodeURIComponent(voiceId)}/with-timestamps?output_format=${encodeURIComponent(this.outputFormat)}`;
|
|
714
|
+
const res = await fetch(url, {
|
|
715
|
+
method: "POST",
|
|
716
|
+
headers: {
|
|
717
|
+
"xi-api-key": this.apiKey,
|
|
718
|
+
"Content-Type": "application/json"
|
|
719
|
+
},
|
|
720
|
+
body: JSON.stringify({
|
|
721
|
+
text: spokenText,
|
|
722
|
+
model_id: this.modelId
|
|
723
|
+
}),
|
|
724
|
+
signal: controller.signal
|
|
725
|
+
});
|
|
726
|
+
if (!res.ok) {
|
|
727
|
+
const msg = await res.text().catch(() => "");
|
|
728
|
+
throw new Error(`ElevenLabs REST ${res.status}: ${msg}`);
|
|
729
|
+
}
|
|
730
|
+
const json = await res.json();
|
|
731
|
+
if (!json.audio_base64) {
|
|
732
|
+
throw new Error("ElevenLabs response missing audio_base64");
|
|
733
|
+
}
|
|
734
|
+
audioBytes = Buffer.from(json.audio_base64, "base64");
|
|
735
|
+
words = alignmentCharsToWords(json.alignment);
|
|
736
|
+
} finally {
|
|
737
|
+
clearTimeout(timer);
|
|
738
|
+
}
|
|
739
|
+
await import_promises4.default.mkdir(import_node_path4.default.dirname(req.outWavPath), { recursive: true });
|
|
740
|
+
const isPcmRaw = this.outputFormat.startsWith("pcm_") && audioBytes.subarray(0, 4).toString("ascii") !== "RIFF";
|
|
741
|
+
const tmpRaw = import_node_path4.default.join(
|
|
742
|
+
import_node_os.default.tmpdir(),
|
|
743
|
+
`eleven-${import_node_crypto2.default.randomUUID()}.${this.outputFormat.startsWith("mp3") ? "mp3" : "wav"}`
|
|
744
|
+
);
|
|
745
|
+
let sourceSampleRateHz = 44100;
|
|
746
|
+
if (isPcmRaw) {
|
|
747
|
+
const rateMatch = this.outputFormat.match(/pcm_(\d+)/);
|
|
748
|
+
const pcmRate = rateMatch?.[1] ? Number.parseInt(rateMatch[1], 10) : 44100;
|
|
749
|
+
sourceSampleRateHz = pcmRate;
|
|
750
|
+
const pcmSamples = new Int16Array(
|
|
751
|
+
audioBytes.buffer,
|
|
752
|
+
audioBytes.byteOffset,
|
|
753
|
+
Math.floor(audioBytes.byteLength / 2)
|
|
754
|
+
);
|
|
755
|
+
await import_promises4.default.writeFile(tmpRaw, writePcm16MonoWav(pcmSamples, pcmRate));
|
|
756
|
+
} else {
|
|
757
|
+
await import_promises4.default.writeFile(tmpRaw, audioBytes);
|
|
758
|
+
}
|
|
759
|
+
try {
|
|
760
|
+
if (!isPcmRaw) {
|
|
761
|
+
const probed = probeSourceAudioSampleRate(tmpRaw);
|
|
762
|
+
if (probed.sampleRateHz > 0) sourceSampleRateHz = probed.sampleRateHz;
|
|
763
|
+
}
|
|
764
|
+
transcodeAudioTo48kMonoWav(tmpRaw, req.outWavPath);
|
|
765
|
+
} finally {
|
|
766
|
+
await import_promises4.default.rm(tmpRaw, { force: true }).catch(() => void 0);
|
|
767
|
+
}
|
|
768
|
+
const normBytes = await import_promises4.default.readFile(req.outWavPath);
|
|
769
|
+
const durationMs = Math.max(150, readWavHeaderInfo(normBytes).durationMs);
|
|
770
|
+
if (words.length === 0) {
|
|
771
|
+
words = estimateWordTimings(req.text, durationMs);
|
|
772
|
+
}
|
|
773
|
+
const provenance = {
|
|
774
|
+
providerId: this.id,
|
|
775
|
+
voice: voiceId,
|
|
776
|
+
locale,
|
|
777
|
+
sourceSampleRateHz,
|
|
778
|
+
isSynthetic: false,
|
|
779
|
+
isRoboticFallback: false,
|
|
780
|
+
cacheHit: false
|
|
781
|
+
};
|
|
782
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
783
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
// src/providers/gemini.ts
|
|
788
|
+
var import_node_crypto3 = __toESM(require("crypto"), 1);
|
|
789
|
+
var import_promises5 = __toESM(require("fs/promises"), 1);
|
|
790
|
+
var import_node_os2 = __toESM(require("os"), 1);
|
|
791
|
+
var import_node_path5 = __toESM(require("path"), 1);
|
|
792
|
+
var GeminiTtsVoiceProvider = class {
|
|
793
|
+
id = "gemini-tts";
|
|
794
|
+
apiKey;
|
|
795
|
+
model;
|
|
796
|
+
endpoint;
|
|
797
|
+
cache;
|
|
798
|
+
timeoutMs;
|
|
799
|
+
constructor(options = {}) {
|
|
800
|
+
this.apiKey = options.apiKey ?? process.env.GEMINI_API_KEY ?? "";
|
|
801
|
+
this.model = options.model ?? "gemini-3.8-flash-tts";
|
|
802
|
+
this.endpoint = options.endpoint ?? "https://generativelanguage.googleapis.com/v1beta/interactions";
|
|
803
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
804
|
+
this.timeoutMs = options.timeoutMs ?? 3e4;
|
|
805
|
+
}
|
|
806
|
+
async synthesize(req) {
|
|
807
|
+
if (!this.apiKey && this.endpoint.startsWith("https://")) {
|
|
808
|
+
throw new Error("GeminiTtsVoiceProvider requires GEMINI_API_KEY.");
|
|
809
|
+
}
|
|
810
|
+
const locale = req.locale ?? "en-IN";
|
|
811
|
+
const voice = req.voice && req.voice.trim().length > 0 ? req.voice.trim() : "Kore";
|
|
812
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
813
|
+
const key = this.cache.computeKey({
|
|
814
|
+
provider: this.id,
|
|
815
|
+
model: this.model,
|
|
816
|
+
voice,
|
|
817
|
+
locale,
|
|
818
|
+
style: req.style ?? "",
|
|
819
|
+
spokenText
|
|
820
|
+
});
|
|
821
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
822
|
+
if (hit) return hit;
|
|
823
|
+
const controller = new AbortController();
|
|
824
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
825
|
+
let wavBytes;
|
|
826
|
+
try {
|
|
827
|
+
const res = await fetch(this.endpoint, {
|
|
828
|
+
method: "POST",
|
|
829
|
+
headers: {
|
|
830
|
+
"x-goog-api-key": this.apiKey,
|
|
831
|
+
"Content-Type": "application/json"
|
|
832
|
+
},
|
|
833
|
+
body: JSON.stringify({
|
|
834
|
+
model: this.model,
|
|
835
|
+
input: [
|
|
836
|
+
{
|
|
837
|
+
type: "user_input",
|
|
838
|
+
content: [
|
|
839
|
+
{
|
|
840
|
+
type: "text",
|
|
841
|
+
text: spokenText,
|
|
842
|
+
...req.style ? {
|
|
843
|
+
annotations: [{ type: "speech_metadata", style: req.style }]
|
|
844
|
+
} : {}
|
|
845
|
+
}
|
|
846
|
+
]
|
|
847
|
+
}
|
|
848
|
+
],
|
|
849
|
+
response_format: { type: "audio" },
|
|
850
|
+
generation_config: {
|
|
851
|
+
speech_config: [{ voice }]
|
|
852
|
+
}
|
|
853
|
+
}),
|
|
854
|
+
signal: controller.signal
|
|
855
|
+
});
|
|
856
|
+
if (!res.ok) {
|
|
857
|
+
const msg = await res.text().catch(() => "");
|
|
858
|
+
throw new Error(`Gemini TTS REST ${res.status}: ${msg}`);
|
|
859
|
+
}
|
|
860
|
+
const json = await res.json();
|
|
861
|
+
const b64 = json.output_audio?.data;
|
|
862
|
+
if (!b64) {
|
|
863
|
+
throw new Error("Gemini TTS response missing output_audio.data");
|
|
864
|
+
}
|
|
865
|
+
wavBytes = Buffer.from(b64, "base64");
|
|
866
|
+
} finally {
|
|
867
|
+
clearTimeout(timer);
|
|
868
|
+
}
|
|
869
|
+
const srcInfo = readWavHeaderInfo(wavBytes);
|
|
870
|
+
const sourceSampleRateHz = srcInfo.sampleRateHz > 0 ? srcInfo.sampleRateHz : 24e3;
|
|
871
|
+
await import_promises5.default.mkdir(import_node_path5.default.dirname(req.outWavPath), { recursive: true });
|
|
872
|
+
const tmpRaw = import_node_path5.default.join(import_node_os2.default.tmpdir(), `gemini-tts-${import_node_crypto3.default.randomUUID()}.wav`);
|
|
873
|
+
await import_promises5.default.writeFile(tmpRaw, wavBytes);
|
|
874
|
+
try {
|
|
875
|
+
transcodeAudioTo48kMonoWav(tmpRaw, req.outWavPath);
|
|
876
|
+
} finally {
|
|
877
|
+
await import_promises5.default.rm(tmpRaw, { force: true }).catch(() => void 0);
|
|
878
|
+
}
|
|
879
|
+
const normBytes = await import_promises5.default.readFile(req.outWavPath);
|
|
880
|
+
const durationMs = Math.max(150, readWavHeaderInfo(normBytes).durationMs);
|
|
881
|
+
const words = estimateWordTimings(req.text, durationMs);
|
|
882
|
+
const provenance = {
|
|
883
|
+
providerId: this.id,
|
|
884
|
+
voice,
|
|
885
|
+
locale,
|
|
886
|
+
sourceSampleRateHz,
|
|
887
|
+
isSynthetic: false,
|
|
888
|
+
isRoboticFallback: false,
|
|
889
|
+
cacheHit: false
|
|
890
|
+
};
|
|
891
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
892
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
// src/providers/prerecorded.ts
|
|
897
|
+
var import_promises6 = __toESM(require("fs/promises"), 1);
|
|
898
|
+
var import_node_path6 = __toESM(require("path"), 1);
|
|
899
|
+
var PreRecordedVoiceProvider = class {
|
|
900
|
+
id = "prerecorded";
|
|
901
|
+
pathMap;
|
|
902
|
+
constructor(entries = {}) {
|
|
903
|
+
this.pathMap = new Map(Object.entries(entries));
|
|
904
|
+
}
|
|
905
|
+
async synthesize(req) {
|
|
906
|
+
const src = req.wavPath ?? (req.id ? this.pathMap.get(req.id) : void 0);
|
|
907
|
+
if (!src) {
|
|
908
|
+
throw new Error(
|
|
909
|
+
`PreRecordedVoiceProvider missing audio path for cue "${req.id ?? req.text}"`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
await import_promises6.default.access(src);
|
|
913
|
+
const srcBytes = await import_promises6.default.readFile(src);
|
|
914
|
+
const probed = probeSourceAudioSampleRate(src);
|
|
915
|
+
const zcrStd = computeAudioZcrStd(srcBytes);
|
|
916
|
+
await import_promises6.default.mkdir(import_node_path6.default.dirname(req.outWavPath), { recursive: true });
|
|
917
|
+
if (import_node_path6.default.resolve(src) !== import_node_path6.default.resolve(req.outWavPath)) {
|
|
918
|
+
transcodeAudioTo48kMonoWav(src, req.outWavPath);
|
|
919
|
+
}
|
|
920
|
+
const bytes = await import_promises6.default.readFile(req.outWavPath);
|
|
921
|
+
const hdr = readWavHeaderInfo(bytes);
|
|
922
|
+
const durationMs = Math.max(150, hdr.durationMs);
|
|
923
|
+
const normZcr = zcrStd ?? computeAudioZcrStd(bytes);
|
|
924
|
+
return {
|
|
925
|
+
wavPath: req.outWavPath,
|
|
926
|
+
durationMs,
|
|
927
|
+
words: estimateWordTimings(req.text, durationMs),
|
|
928
|
+
provenance: {
|
|
929
|
+
providerId: this.id,
|
|
930
|
+
voice: import_node_path6.default.basename(src),
|
|
931
|
+
locale: req.locale ?? "en-IN",
|
|
932
|
+
sourceSampleRateHz: probed.sampleRateHz || hdr.sampleRateHz || 48e3,
|
|
933
|
+
isSynthetic: probed.isSyntheticTag || hdr.isSyntheticTag,
|
|
934
|
+
isRoboticFallback: false,
|
|
935
|
+
zcrStd: normZcr,
|
|
936
|
+
cacheHit: false
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
|
|
942
|
+
// src/providers/sarvam.ts
|
|
943
|
+
var import_node_crypto4 = __toESM(require("crypto"), 1);
|
|
944
|
+
var import_promises7 = __toESM(require("fs/promises"), 1);
|
|
945
|
+
var import_node_os3 = __toESM(require("os"), 1);
|
|
946
|
+
var import_node_path7 = __toESM(require("path"), 1);
|
|
947
|
+
var SarvamBulbulVoiceProvider = class {
|
|
948
|
+
id = "sarvam-bulbul";
|
|
949
|
+
apiKey;
|
|
950
|
+
model;
|
|
951
|
+
endpoint;
|
|
952
|
+
cache;
|
|
953
|
+
timeoutMs;
|
|
954
|
+
constructor(options = {}) {
|
|
955
|
+
this.apiKey = options.apiKey ?? process.env.SARVAM_API_KEY ?? "";
|
|
956
|
+
this.model = options.model ?? "bulbul:v2";
|
|
957
|
+
this.endpoint = options.endpoint ?? "https://api.sarvam.ai/text-to-speech";
|
|
958
|
+
this.cache = new VoiceDiskCache(options.cacheDir);
|
|
959
|
+
this.timeoutMs = options.timeoutMs ?? 2e4;
|
|
960
|
+
}
|
|
961
|
+
async synthesize(req) {
|
|
962
|
+
if (!this.apiKey && this.endpoint.startsWith("https://")) {
|
|
963
|
+
throw new Error("SarvamBulbulVoiceProvider requires SARVAM_API_KEY.");
|
|
964
|
+
}
|
|
965
|
+
const locale = req.locale ?? "hi-IN";
|
|
966
|
+
const voice = req.voice && req.voice.trim().length > 0 ? req.voice.trim() : "anushka";
|
|
967
|
+
const pace = Number((req.speed ?? 1).toFixed(2));
|
|
968
|
+
const { spokenText } = applyPronunciationLexicon(req.text, locale, req.lexicons);
|
|
969
|
+
const key = this.cache.computeKey({
|
|
970
|
+
provider: this.id,
|
|
971
|
+
model: this.model,
|
|
972
|
+
voice,
|
|
973
|
+
locale,
|
|
974
|
+
pace,
|
|
975
|
+
spokenText
|
|
976
|
+
});
|
|
977
|
+
const hit = await this.cache.get(key, req.outWavPath);
|
|
978
|
+
if (hit) return hit;
|
|
979
|
+
const controller = new AbortController();
|
|
980
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
981
|
+
let rawWav;
|
|
982
|
+
try {
|
|
983
|
+
const res = await fetch(this.endpoint, {
|
|
984
|
+
method: "POST",
|
|
985
|
+
headers: {
|
|
986
|
+
"Content-Type": "application/json",
|
|
987
|
+
"api-subscription-key": this.apiKey
|
|
988
|
+
},
|
|
989
|
+
body: JSON.stringify({
|
|
990
|
+
text: spokenText,
|
|
991
|
+
language_code: locale,
|
|
992
|
+
model: this.model,
|
|
993
|
+
speaker: voice,
|
|
994
|
+
speech_sample_rate: 48e3,
|
|
995
|
+
pace
|
|
996
|
+
}),
|
|
997
|
+
signal: controller.signal
|
|
998
|
+
});
|
|
999
|
+
if (!res.ok) {
|
|
1000
|
+
const msg = await res.text().catch(() => "");
|
|
1001
|
+
throw new Error(`Sarvam Bulbul REST ${res.status}: ${msg}`);
|
|
1002
|
+
}
|
|
1003
|
+
const json = await res.json();
|
|
1004
|
+
const b64 = json.audios?.[0];
|
|
1005
|
+
if (!b64) {
|
|
1006
|
+
throw new Error("Sarvam Bulbul response missing audios[0]");
|
|
1007
|
+
}
|
|
1008
|
+
rawWav = Buffer.from(b64, "base64");
|
|
1009
|
+
} finally {
|
|
1010
|
+
clearTimeout(timer);
|
|
1011
|
+
}
|
|
1012
|
+
const hdr = readWavHeaderInfo(rawWav);
|
|
1013
|
+
const sourceSampleRateHz = hdr.sampleRateHz > 0 ? hdr.sampleRateHz : 48e3;
|
|
1014
|
+
await import_promises7.default.mkdir(import_node_path7.default.dirname(req.outWavPath), { recursive: true });
|
|
1015
|
+
if (sourceSampleRateHz === 48e3 && hdr.channels === 1 && hdr.bitsPerSample === 16) {
|
|
1016
|
+
await import_promises7.default.writeFile(req.outWavPath, rawWav);
|
|
1017
|
+
} else {
|
|
1018
|
+
const tmpRaw = import_node_path7.default.join(import_node_os3.default.tmpdir(), `sarvam-${import_node_crypto4.default.randomUUID()}.wav`);
|
|
1019
|
+
await import_promises7.default.writeFile(tmpRaw, rawWav);
|
|
1020
|
+
try {
|
|
1021
|
+
transcodeAudioTo48kMonoWav(tmpRaw, req.outWavPath);
|
|
1022
|
+
} finally {
|
|
1023
|
+
await import_promises7.default.rm(tmpRaw, { force: true }).catch(() => void 0);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
const normBytes = await import_promises7.default.readFile(req.outWavPath);
|
|
1027
|
+
const durationMs = Math.max(150, readWavHeaderInfo(normBytes).durationMs);
|
|
1028
|
+
const words = estimateWordTimings(req.text, durationMs);
|
|
1029
|
+
const provenance = {
|
|
1030
|
+
providerId: this.id,
|
|
1031
|
+
voice,
|
|
1032
|
+
locale,
|
|
1033
|
+
sourceSampleRateHz,
|
|
1034
|
+
isSynthetic: false,
|
|
1035
|
+
isRoboticFallback: false,
|
|
1036
|
+
cacheHit: false
|
|
1037
|
+
};
|
|
1038
|
+
await this.cache.put(key, req.outWavPath, durationMs, words, provenance);
|
|
1039
|
+
return { wavPath: req.outWavPath, durationMs, words, provenance };
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
|
|
1043
|
+
// src/captions.ts
|
|
1044
|
+
function emitCaptionsSrt(entries) {
|
|
1045
|
+
const fmt = (ms) => {
|
|
1046
|
+
const clamped = Math.max(0, Math.round(ms));
|
|
1047
|
+
const h = Math.floor(clamped / 36e5);
|
|
1048
|
+
const m = Math.floor(clamped % 36e5 / 6e4);
|
|
1049
|
+
const s = Math.floor(clamped % 6e4 / 1e3);
|
|
1050
|
+
const rem = clamped % 1e3;
|
|
1051
|
+
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")},${String(rem).padStart(3, "0")}`;
|
|
1052
|
+
};
|
|
1053
|
+
return entries.map((e, i) => `${i + 1}
|
|
1054
|
+
${fmt(e.startMs)} --> ${fmt(e.endMs)}
|
|
1055
|
+
${e.text.trim()}
|
|
1056
|
+
`).join("\n");
|
|
1057
|
+
}
|
|
1058
|
+
function emitCaptionsVtt(entries) {
|
|
1059
|
+
const fmt = (ms) => {
|
|
1060
|
+
const clamped = Math.max(0, Math.round(ms));
|
|
1061
|
+
const h = Math.floor(clamped / 36e5);
|
|
1062
|
+
const m = Math.floor(clamped % 36e5 / 6e4);
|
|
1063
|
+
const s = Math.floor(clamped % 6e4 / 1e3);
|
|
1064
|
+
const rem = clamped % 1e3;
|
|
1065
|
+
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(rem).padStart(3, "0")}`;
|
|
1066
|
+
};
|
|
1067
|
+
const body = entries.map((e) => `${fmt(e.startMs)} --> ${fmt(e.endMs)}
|
|
1068
|
+
${e.text.trim()}
|
|
1069
|
+
`).join("\n");
|
|
1070
|
+
return `WEBVTT
|
|
1071
|
+
|
|
1072
|
+
${body}`;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/providers/synthetic.ts
|
|
1076
|
+
var import_node_child_process3 = require("child_process");
|
|
1077
|
+
var import_promises8 = __toESM(require("fs/promises"), 1);
|
|
1078
|
+
var import_node_path8 = __toESM(require("path"), 1);
|
|
1079
|
+
var OsNativeVoiceProvider = class {
|
|
1080
|
+
constructor(options = {}) {
|
|
1081
|
+
this.options = options;
|
|
1082
|
+
}
|
|
1083
|
+
options;
|
|
1084
|
+
id = "os-native";
|
|
1085
|
+
async synthesize(req) {
|
|
1086
|
+
if (process.platform === "win32" && !this.options.allowRoboticFallback) {
|
|
1087
|
+
throw new Error(
|
|
1088
|
+
"Legacy Win32 SAPI speech synthesis (OsNativeVoiceProvider) is blocked by default in v0.3.0 due to robotic quality. Use AzureSpeechVoiceProvider, GeminiTtsVoiceProvider, SarvamBulbulVoiceProvider, ElevenLabsVoiceProvider, KokoroCliVoiceProvider, PiperCliVoiceProvider, or PreRecordedVoiceProvider."
|
|
1089
|
+
);
|
|
1090
|
+
}
|
|
1091
|
+
await import_promises8.default.mkdir(import_node_path8.default.dirname(req.outWavPath), { recursive: true });
|
|
1092
|
+
if (process.platform === "win32") {
|
|
1093
|
+
const rate = Math.max(-10, Math.min(10, Math.round(((req.speed ?? 1) - 1) * 6)));
|
|
1094
|
+
const escapedText = req.text.replace(/'/g, "''");
|
|
1095
|
+
const escapedOut = req.outWavPath.replace(/'/g, "''");
|
|
1096
|
+
const ps = [
|
|
1097
|
+
"Add-Type -AssemblyName System.Speech;",
|
|
1098
|
+
"$s = New-Object System.Speech.Synthesis.SpeechSynthesizer;",
|
|
1099
|
+
`$s.Rate = ${rate};`,
|
|
1100
|
+
req.voice ? `$s.SelectVoice('${req.voice.replace(/'/g, "''")}');` : "",
|
|
1101
|
+
`$s.SetOutputToWaveFile('${escapedOut}');`,
|
|
1102
|
+
`$s.Speak('${escapedText}');`,
|
|
1103
|
+
"$s.Dispose();"
|
|
1104
|
+
].join(" ");
|
|
1105
|
+
const res = (0, import_node_child_process3.spawnSync)("powershell", ["-NoProfile", "-Command", ps], { stdio: "pipe" });
|
|
1106
|
+
if (res.status !== 0) {
|
|
1107
|
+
throw new Error(`Windows SAPI synthesis failed: ${res.stderr?.toString("utf8")}`);
|
|
1108
|
+
}
|
|
1109
|
+
} else if (process.platform === "darwin") {
|
|
1110
|
+
const args = ["-o", req.outWavPath, "--data-format=LEI16@48000"];
|
|
1111
|
+
if (req.voice) args.push("-v", req.voice);
|
|
1112
|
+
args.push(req.text);
|
|
1113
|
+
const res = (0, import_node_child_process3.spawnSync)("say", args, { stdio: "pipe" });
|
|
1114
|
+
if (res.status !== 0) {
|
|
1115
|
+
throw new Error(`macOS say synthesis failed: ${res.stderr?.toString("utf8")}`);
|
|
1116
|
+
}
|
|
1117
|
+
} else {
|
|
1118
|
+
throw new Error(
|
|
1119
|
+
"No built-in WAV synthesizer on Linux in core; use AzureSpeechVoiceProvider, GeminiTtsVoiceProvider, or KokoroCliVoiceProvider."
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
const bytes = await import_promises8.default.readFile(req.outWavPath);
|
|
1123
|
+
const durationMs = Math.max(200, readWavDurationMs(bytes));
|
|
1124
|
+
return {
|
|
1125
|
+
wavPath: req.outWavPath,
|
|
1126
|
+
durationMs,
|
|
1127
|
+
words: estimateWordTimings(req.text, durationMs),
|
|
1128
|
+
provenance: {
|
|
1129
|
+
providerId: this.id,
|
|
1130
|
+
voice: req.voice ?? "os-native",
|
|
1131
|
+
locale: req.locale ?? "en-US",
|
|
1132
|
+
sourceSampleRateHz: 22050,
|
|
1133
|
+
isSynthetic: false,
|
|
1134
|
+
isRoboticFallback: true,
|
|
1135
|
+
cacheHit: false
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
};
|
|
1140
|
+
var SyntheticToneVoiceProvider = class {
|
|
1141
|
+
id = "synthetic-tone";
|
|
1142
|
+
async synthesize(req) {
|
|
1143
|
+
await import_promises8.default.mkdir(import_node_path8.default.dirname(req.outWavPath), { recursive: true });
|
|
1144
|
+
const wordsCount = Math.max(1, req.text.trim().split(/\s+/).filter(Boolean).length);
|
|
1145
|
+
const durationMs = Math.round(wordsCount / 2.5 * 1e3);
|
|
1146
|
+
const sampleRate = 48e3;
|
|
1147
|
+
const totalSamples = Math.round(durationMs / 1e3 * sampleRate);
|
|
1148
|
+
const pcm = new Int16Array(totalSamples);
|
|
1149
|
+
for (let i = 0; i < totalSamples; i++) {
|
|
1150
|
+
const env = Math.sin(Math.PI * i / totalSamples);
|
|
1151
|
+
pcm[i] = Math.round(Math.sin(2 * Math.PI * 220 * i / sampleRate) * 1600 * env);
|
|
1152
|
+
}
|
|
1153
|
+
await import_promises8.default.writeFile(
|
|
1154
|
+
req.outWavPath,
|
|
1155
|
+
writePcm16MonoWav(pcm, sampleRate, { softwareTag: "astrake-synthetic-tone" })
|
|
1156
|
+
);
|
|
1157
|
+
return {
|
|
1158
|
+
wavPath: req.outWavPath,
|
|
1159
|
+
durationMs,
|
|
1160
|
+
words: estimateWordTimings(req.text, durationMs),
|
|
1161
|
+
provenance: {
|
|
1162
|
+
providerId: this.id,
|
|
1163
|
+
voice: "sine-220hz",
|
|
1164
|
+
locale: req.locale ?? "en-IN",
|
|
1165
|
+
sourceSampleRateHz: sampleRate,
|
|
1166
|
+
isSynthetic: true,
|
|
1167
|
+
isRoboticFallback: false,
|
|
1168
|
+
zcrStd: 1e-3,
|
|
1169
|
+
cacheHit: false
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
|
|
1175
|
+
// src/index.ts
|
|
1176
|
+
var EdgeNeuralVoiceProvider = class {
|
|
1177
|
+
constructor(options) {
|
|
1178
|
+
this.options = options;
|
|
1179
|
+
}
|
|
1180
|
+
options;
|
|
1181
|
+
id = "edge-neural-removed";
|
|
1182
|
+
async synthesize() {
|
|
1183
|
+
throw new Error(
|
|
1184
|
+
"EdgeNeuralVoiceProvider (undocumented Bing WS scraping) was removed in v0.3.0 due to HTTP 403 DRM blocks. Configure AZURE_SPEECH_KEY + AZURE_SPEECH_REGION (AzureSpeechVoiceProvider \u2014 free F0 tier gives 500k neural chars/mo with the same en-IN-NeerjaNeural / hi-IN-SwaraNeural voices), GEMINI_API_KEY (GeminiTtsVoiceProvider), SARVAM_API_KEY, ELEVENLABS_API_KEY, or KokoroCliVoiceProvider/PiperCliVoiceProvider."
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
function commandExists(cmd) {
|
|
1189
|
+
const probe = (0, import_node_child_process4.spawnSync)(process.platform === "win32" ? "where" : "which", [cmd], {
|
|
1190
|
+
stdio: "ignore"
|
|
1191
|
+
});
|
|
1192
|
+
return probe.status === 0;
|
|
1193
|
+
}
|
|
1194
|
+
function createAutoVoiceProvider(opts = {}) {
|
|
1195
|
+
const explicit = (opts.provider && opts.provider !== "auto" ? opts.provider : process.env.PRODUCER_VOICE_PROVIDER) ?? "auto";
|
|
1196
|
+
const cacheDir = opts.cacheDir;
|
|
1197
|
+
if (explicit === "azure-speech" || explicit === "auto" && process.env.AZURE_SPEECH_KEY) {
|
|
1198
|
+
return new AzureSpeechVoiceProvider({ cacheDir });
|
|
1199
|
+
}
|
|
1200
|
+
if (explicit === "gemini-tts" || explicit === "auto" && process.env.GEMINI_API_KEY) {
|
|
1201
|
+
return new GeminiTtsVoiceProvider({ cacheDir });
|
|
1202
|
+
}
|
|
1203
|
+
if (explicit === "sarvam-bulbul" || explicit === "auto" && process.env.SARVAM_API_KEY) {
|
|
1204
|
+
return new SarvamBulbulVoiceProvider({ cacheDir });
|
|
1205
|
+
}
|
|
1206
|
+
if (explicit === "elevenlabs" || explicit === "auto" && process.env.ELEVENLABS_API_KEY) {
|
|
1207
|
+
return new ElevenLabsVoiceProvider({ cacheDir });
|
|
1208
|
+
}
|
|
1209
|
+
if (explicit === "kokoro-cli" || explicit === "auto" && commandExists("kokoro-tts")) {
|
|
1210
|
+
return new KokoroCliVoiceProvider({ cacheDir });
|
|
1211
|
+
}
|
|
1212
|
+
if (explicit === "piper-cli" || explicit === "auto" && commandExists("piper") && process.env.PIPER_MODEL_PATH) {
|
|
1213
|
+
return new PiperCliVoiceProvider({ cacheDir });
|
|
1214
|
+
}
|
|
1215
|
+
if (explicit === "external-command") {
|
|
1216
|
+
const cmd = process.env.PRODUCER_VOICE_CMD;
|
|
1217
|
+
if (!cmd) {
|
|
1218
|
+
throw new Error("PRODUCER_VOICE_PROVIDER=external-command requires PRODUCER_VOICE_CMD.");
|
|
1219
|
+
}
|
|
1220
|
+
return new CommandVoiceProvider(cmd);
|
|
1221
|
+
}
|
|
1222
|
+
if (explicit === "prerecorded") {
|
|
1223
|
+
return new PreRecordedVoiceProvider();
|
|
1224
|
+
}
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
"No sanctioned neural TTS provider is configured for un-wav voiceCues. Set AZURE_SPEECH_KEY + AZURE_SPEECH_REGION (free 500k/mo neural tier), GEMINI_API_KEY, SARVAM_API_KEY, ELEVENLABS_API_KEY, or install kokoro-tts / piper locally, or attach studio wavPath files to your voiceCues."
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1230
|
+
0 && (module.exports = {
|
|
1231
|
+
AzureSpeechVoiceProvider,
|
|
1232
|
+
CommandVoiceProvider,
|
|
1233
|
+
DEFAULT_NEURAL_VOICES,
|
|
1234
|
+
EDGE_DEFAULT_VOICES,
|
|
1235
|
+
EdgeNeuralVoiceProvider,
|
|
1236
|
+
ElevenLabsVoiceProvider,
|
|
1237
|
+
GeminiTtsVoiceProvider,
|
|
1238
|
+
KokoroCliVoiceProvider,
|
|
1239
|
+
OsNativeVoiceProvider,
|
|
1240
|
+
PiperCliVoiceProvider,
|
|
1241
|
+
PreRecordedVoiceProvider,
|
|
1242
|
+
SarvamBulbulVoiceProvider,
|
|
1243
|
+
SyntheticToneVoiceProvider,
|
|
1244
|
+
VoiceDiskCache,
|
|
1245
|
+
applyPronunciationLexicon,
|
|
1246
|
+
computeAudioZcrStd,
|
|
1247
|
+
createAutoVoiceProvider,
|
|
1248
|
+
emitCaptionsSrt,
|
|
1249
|
+
emitCaptionsVtt,
|
|
1250
|
+
escapeXml,
|
|
1251
|
+
estimateWordTimings,
|
|
1252
|
+
probeSourceAudioSampleRate,
|
|
1253
|
+
readWavDurationMs,
|
|
1254
|
+
readWavHeaderInfo,
|
|
1255
|
+
resolveEdgeVoiceName,
|
|
1256
|
+
resolveNeuralVoiceName,
|
|
1257
|
+
transcodeAudioTo48kMonoWav,
|
|
1258
|
+
transcodeAudioTo48kStereoWav,
|
|
1259
|
+
writePcm16MonoWav
|
|
1260
|
+
});
|