-
Notifications
You must be signed in to change notification settings - Fork 1
/
say2file.js
300 lines (273 loc) · 10.1 KB
/
say2file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
const fs = require('node:fs');
const arg = require('arg');
const { Readable } = require('node:stream');
// read .env and .env.defaults
require('dotenv-defaults/config');
const eleven = require('./eleven.js');
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const { get } = require('node:http');
const version = require('./package.json').version;
const IBMKEY = process.env.hasOwnProperty("IBMKEY") ? process.env["IBMKEY"] : null;
const IBMURL = process.env.hasOwnProperty("IBMURL") ? process.env["IBMURL"] : null;
const LABSKEY = eleven.LABSKEY;
const LABSURL = eleven.LABSURL;
function onError(err) {
console.error("Server error:", err.message);
if (err.stack) console.error(err.stack);
process.exit(1); //mandatory return code (as per the Node.js docs)
}
process.on('uncaughtException', onError);
let args;
try {
args = arg({
// Types
'--key': String, // --key <string> or --key=<string>
'--url': String,
'--file': String,
'--out': String,
'--provider': String,
'--type': String,
'--rate': Number,
'--voice': String,
'--split': Boolean,
'--list': Boolean, // list voices
'--model': String, // e.g. e1=eleven_monolingual_v1, m2=eleven_multilingual_v2
'--help': Boolean,
'--verbose': Boolean,
'--version': Boolean,
// Aliases
'-k': '--key',
'-u': '--url',
'-f': '--file',
'-o': '--out',
'-p': '--provider',
'-t': '--type',
'-r': '--rate',
'-w': '--voice',
'-s': '--split',
'-l': '--list',
'-m': '--model',
'-v': '--version',
'-h': '--help',
'-?': '--help'
});
} catch (err) {
console.error(err.message);
process.exit(1);
}
let fileIn = args['--file'];
let fileOut = args['--out'] ?? 'audio';
let provider = args['--provider'] ?? 'eleven';
let isEleven = provider.toLowerCase() === 'eleven' || provider.toLowerCase() === '11';
let fileType = args['--type'] ?? 'mp3';
let rate = args['--rate'] ?? (isEleven ? '192' : '44100');
let voice = args['--voice'] ?? (isEleven ? eleven.DEFAULT_VOICE : 'michael');
let apikey = args['--key'] ?? (isEleven ? LABSKEY : IBMKEY);
let apiURL = args['--url'] ?? (isEleven ? LABSURL : IBMURL);
let isSplit = args['--split'] || false;
let cmdline = args._.join(' ').trim();
let model = args['--model'] ?? (isEleven ? eleven.DEFAULT_MODEL : '');
if (args['--version']) {
console.log("say2file version " + version);
process.exit(1);
}
if (args['--help']) {
console.log("say2file [options] [optional text to convert to audio]");
console.log("Options: --file or -f with filename (input text file)")
console.log(" --split or -s (split the input text file into multiple output files)")
console.log(" --out or -o with rootname (produces rootname.type or rootname-n.type)")
console.log(" --provider or -p with provider(ibm, watson, eleven or 11. default is eleven)")
console.log(" --list or -l (to list available voices)")
console.log(" --key or -k with the API key to use (if not in .env)")
console.log(" --version or -v (show version))")
console.log(" --help or -h or -? (this help))")
console.log("\nAddition options when using the ElevenLabs provider:");
console.log(" --voice or -w (who), choices: default or voice-ID");
console.log(" --model or -m, choices: e1, m1, m2 for english/multilingual");
console.log(" --type or -t with type, choices: mp3 or wav")
console.log(" --rate or -r with rate, mp3 choices: 64, 96, 128, or 192")
console.log(" wav choices: 16000, 22050, 24000, or 44100")
console.log("\nAddition options when using the IBM Watson provider:");
console.log(" --url or -u with the service URL to use (if not in .env)")
console.log(" --voice or -w (who), choices: michael olivia kevin lisa allison henry james kate charlotte craig madison");
console.log(" --type or -t with type, choices: wav, mp3, mpeg, flac, ogg)")
console.log(" --rate or -r with rate, sample rate: default is 44100)")
process.exit(1);
}
async function listElevenVoices()
{
try {
const data = await eleven.listVoices();
if (data?.voices) {
for (let voice of data.voices) {
console.log(` ${voice.voice_id}: "${voice.name}"`);
}
} else {
console.log("ElevenLabs voices: unknown");
}
} catch (err) {
console.log("listElevenVoices: " + err.message);
}
}
async function doWork() {
if (args['--list']) {
let rc = 0;
if (isEleven) {
await listElevenVoices();
} else {
console.log("Use IBM Watson voices: michael olivia kevin lisa allison henry james kate charlotte craig madison dieter erika birgit");
}
process.exit(0);
}
let lines = [];
if (cmdline) {
lines = [cmdline];
} else
if (fileIn) {
let text = fs.readFileSync(fileIn, { encoding: 'utf8', flag: 'r' });
lines = text.split('\n');
} else {
console.log("No input specified.");
process.exit(1); // no work to do
}
lines = lines.filter(line => line.trim().length > 0).filter(line => !line.startsWith('#'));
if (!isSplit) {
lines = [lines.join('\n')];
}
let fullVoice = voice;
if (isEleven) {
if (!voice) {
voice = eleven.DEFAULT_VOICE;
}
if (voice.toLowerCase() === 'paulca') {
voice = eleven.PAULCA_VOICE;
}
eleven.init();
} else {
if (!voice){
voice = 'michael'; // default IBM Watson voice
}
switch (voice.toLowerCase()) {
case 'michael': fullVoice = 'en-US_MichaelV3Voice'; break;
case 'olivia': fullVoice = 'en-US_OliviaV3Voice'; break;
case 'henry': fullVoice = 'en-US_HenryV3Voice'; break;
case 'allison': fullVoice = 'en-US_AllisonV3Voice'; break;
case 'kevin': fullVoice = 'en-US_KevinV3Voice'; break;
case 'lisa': fullVoice = 'en-US_LisaV3Voice'; break;
case 'emily': fullVoice = 'en-US_EmilyV3Voice'; break;
case 'kate': fullVoice = 'en-GB_KateV3Voice'; break;
case 'charlotte': fullVoice = 'en-GB_CharlotteV3Voice'; break;
case 'james': fullVoice = 'en-GB_JamesV3Voice'; break;
case 'craig': fullVoice = 'en-AU_CraigVoice'; break;
case 'madison': fullVoice = 'en-AU_MadisonVoice'; break;
case 'dieter': fullVoice = 'de-DE_DieterV3Voice'; break;
case 'erika': fullVoice = 'de-DE_ErikaV3Voice'; break;
case 'birgit': fullVoice = 'de-DE_BirgitV3Voice'; break;
default: fullVoice = voice;
}
}
let ttsOptions = { }
let ibm = null;
if (isEleven) {
ttsOptions.voice_id = voice;
if (model) {
ttsOptions.model_id = model;
}
if (fileType === 'mp3') {
switch (rate) {
case 64:
ttsOptions.output_format = 'mp3_44100_64'; break;
case 96:
ttsOptions.output_format = 'mp3_44100_96'; break;
case 128:
ttsOptions.output_format = 'mp3_44100_128'; break;
case 192:
default:
ttsOptions.output_format = 'mp3_44100_192'; break;
}
} else {
switch (rate) {
case 16000:
ttsOptions.output_format = 'pcm_16000'; break;
case 22050:
ttsOptions.output_format = 'pcm_22050'; break;
case 24000:
ttsOptions.output_format = 'pcm_24000'; break;
case 44100:
default:
ttsOptions.output_format = 'pcm_44100'; break;
}
}
console.log("Using voice: " + voice + " (" + ttsOptions.output_format + ")");
} else {
const acceptType = (fileType === 'mp3') ? 'audio/mpeg' : 'audio/wav';
ttsOptions = {
voice: fullVoice,
accept: `${acceptType};rate=${rate}`
};
ibm = new TextToSpeechV1({
authenticator: new IamAuthenticator({ apikey: IBMKEY }),
serviceUrl: IBMURL
});
}
let count = 0;
for (let line of lines) {
let text = line.trim();
if (!text) continue;
let options = Object.assign({}, ttsOptions, { text: text });
// Synthesize speech, correct the wav header, then save to disk
// (wav header requires a file length, but this is unknown until after the header is already generated and sent)
// note that `repairWavHeaderStream` will read the whole stream into memory in order to process it.
// the method returns a Promise that resolves with the repaired buffer
if (isEleven) {
eleven.synthesize(options).then(rs => {
count++;
const outFileName = isSplit ? `${fileOut}-${count}.${fileType}` : `${fileOut}.${fileType}`;
if (rs) {
Readable.fromWeb(rs)
.pipe(fs.createWriteStream(outFileName))
.on('finish', () => {
console.log(' --> ' + outFileName);
})
.on('error', error => {
console.error(` *** Error on ${outFileName}:`, error);
});
} else {
console.log(" *** " + outFileName + ": " + "no data");
}
}).catch(err => {
console.log(" *** " + outFileName + ": " + err.message);
});
} else {
ibm.synthesize(ttsOptions)
.then(response => {
const audio = response.result;
return ibm.repairWavHeaderStream(audio);
})
.then(repairedFile => {
count++;
const outFileName = isSplit ? `${fileOut}-${count}.${fileType}` : `${fileOut}.${fileType}`;
fs.writeFileSync(outFileName, repairedFile);
console.log(' --> ' + outFileName);
})
.catch(err => {
console.log(" *** " + outFileName + ": " + err.message);
});
}
}
if (isEleven) {
let user = await eleven.getUser();
if (user?.subscription) {
const s = user.subscription;
const remain = s.character_limit - s.character_count;
let percent = Math.floor((remain / s.character_limit) * 100);
if (percent === 0 && remain > 0) percent = 1;
console.log(`ElevenLabs "${s.tier}" tier: ${remain} (${percent}%) remain of ${s.character_limit} characters.`);
console.log(`ElevenLabs character limit resets: ${new Date(s.next_character_count_reset_unix * 1000)}`);
} else {
console.log("ElevenLabs user: unknown user or invalid API key.");
}
}
}
doWork().then(() => { }).catch(err => { console.error(err); });