iobroker.assistant 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/admin/custom/.vite/manifest.json +1 -1
- package/admin/custom/assets/Components-BZeMTVhf.js +2 -0
- package/admin/custom/customComponents.js +1 -1
- package/admin/custom/i18n/de.json +4 -1
- package/admin/custom/i18n/en.json +4 -1
- package/admin/custom/i18n/es.json +4 -1
- package/admin/custom/i18n/fr.json +4 -1
- package/admin/custom/i18n/it.json +4 -1
- package/admin/custom/i18n/nl.json +4 -1
- package/admin/custom/i18n/pl.json +4 -1
- package/admin/custom/i18n/pt.json +4 -1
- package/admin/custom/i18n/ru.json +4 -1
- package/admin/custom/i18n/uk.json +4 -1
- package/admin/custom/i18n/zh-cn.json +4 -1
- package/admin/custom/index.html +1 -1
- package/admin/custom/mf-manifest.json +1 -1
- package/admin/custom/mf-stats.json +1 -1
- package/admin/i18n/de.json +5 -2
- package/admin/i18n/en.json +5 -2
- package/admin/i18n/es.json +5 -2
- package/admin/i18n/fr.json +5 -2
- package/admin/i18n/it.json +5 -2
- package/admin/i18n/nl.json +5 -2
- package/admin/i18n/pl.json +5 -2
- package/admin/i18n/pt.json +5 -2
- package/admin/i18n/ru.json +5 -2
- package/admin/i18n/uk.json +5 -2
- package/admin/i18n/zh-cn.json +5 -2
- package/admin/jsonConfig.json +60 -4
- package/build/lib/voice/engines.js +42 -9
- package/build/lib/voice/engines.js.map +1 -1
- package/build/lib/voice/speechLanguage.js +4 -3
- package/build/lib/voice/speechLanguage.js.map +1 -1
- package/build/main.js +9 -4
- package/build/main.js.map +1 -1
- package/io-package.json +14 -14
- package/package.json +1 -1
- package/admin/custom/assets/Components-DGifJGYx.js +0 -2
package/admin/jsonConfig.json
CHANGED
|
@@ -1199,7 +1199,10 @@
|
|
|
1199
1199
|
"xl": 4
|
|
1200
1200
|
},
|
|
1201
1201
|
"ttsModel": {
|
|
1202
|
-
"type": "
|
|
1202
|
+
"type": "autocompleteSendTo",
|
|
1203
|
+
"command": "getTtsModels",
|
|
1204
|
+
"jsonData": "{\"ttsProvider\":\"openai\"}",
|
|
1205
|
+
"freeSolo": true,
|
|
1203
1206
|
"label": "OpenAI TTS model (optional)",
|
|
1204
1207
|
"help": "Empty = tts-1. Also: tts-1-hd, gpt-4o-mini-tts.",
|
|
1205
1208
|
"hidden": "!data.voiceEnabled || data.ttsProvider !== 'openai'",
|
|
@@ -1498,7 +1501,7 @@
|
|
|
1498
1501
|
"newLine": true,
|
|
1499
1502
|
"type": "table",
|
|
1500
1503
|
"label": "Voice per answer language",
|
|
1501
|
-
"help": "An answer in another language than the satellites listen in (e.g. pi-agent answers a Russian question in Russian) is spoken with the voice of its language, not spelled letter by letter by the voice above. Without a row the provider's default voice for that language is used. Voice names of the speech output provider, e.g. ru → ru_RU-dmitri-medium (Piper), ru-RU-SvetlanaNeural (Azure), Tatyana (AWS).",
|
|
1504
|
+
"help": "An answer in another language than the satellites listen in (e.g. pi-agent answers a Russian question in Russian) is spoken with the voice of its language, not spelled letter by letter by the voice above. Without a row the provider's default voice for that language is used. Voice names of the speech output provider, e.g. ru → ru_RU-dmitri-medium (Piper), ru-RU-SvetlanaNeural (Azure), Tatyana (AWS). The model (OpenAI and OpenRouter only) replaces the TTS model above for this language, e.g. ru → elevenlabs/eleven-multilingual-v2; without a voice another OpenRouter model takes its first voice for the language.",
|
|
1502
1505
|
"hidden": "!data.voiceEnabled",
|
|
1503
1506
|
"xs": 12,
|
|
1504
1507
|
"sm": 12,
|
|
@@ -1506,8 +1509,61 @@
|
|
|
1506
1509
|
"lg": 12,
|
|
1507
1510
|
"xl": 12,
|
|
1508
1511
|
"items": [
|
|
1509
|
-
{
|
|
1510
|
-
|
|
1512
|
+
{
|
|
1513
|
+
"type": "autocomplete",
|
|
1514
|
+
"attr": "language",
|
|
1515
|
+
"title": "Language (e.g. ru)",
|
|
1516
|
+
"width": "14%",
|
|
1517
|
+
"freeSolo": true,
|
|
1518
|
+
"options": [
|
|
1519
|
+
{ "label": "en – English", "value": "en" },
|
|
1520
|
+
{ "label": "de – Deutsch", "value": "de" },
|
|
1521
|
+
{ "label": "ru – Русский", "value": "ru" },
|
|
1522
|
+
{ "label": "uk – Українська", "value": "uk" },
|
|
1523
|
+
{ "label": "fr – Français", "value": "fr" },
|
|
1524
|
+
{ "label": "it – Italiano", "value": "it" },
|
|
1525
|
+
{ "label": "es – Español", "value": "es" },
|
|
1526
|
+
{ "label": "nl – Nederlands", "value": "nl" },
|
|
1527
|
+
{ "label": "pl – Polski", "value": "pl" },
|
|
1528
|
+
{ "label": "pt – Português", "value": "pt" },
|
|
1529
|
+
{ "label": "cs – Čeština", "value": "cs" },
|
|
1530
|
+
{ "label": "sv – Svenska", "value": "sv" },
|
|
1531
|
+
{ "label": "tr – Türkçe", "value": "tr" },
|
|
1532
|
+
{ "label": "el – Ελληνικά", "value": "el" },
|
|
1533
|
+
{ "label": "zh – 中文", "value": "zh" },
|
|
1534
|
+
{ "label": "ja – 日本語", "value": "ja" }
|
|
1535
|
+
]
|
|
1536
|
+
},
|
|
1537
|
+
{
|
|
1538
|
+
"type": "autocompleteSendTo",
|
|
1539
|
+
"attr": "voice",
|
|
1540
|
+
"title": "Voice (optional)",
|
|
1541
|
+
"width": "38%",
|
|
1542
|
+
"command": "getVoices",
|
|
1543
|
+
"jsonData": "{\"ttsProvider\":\"${globalData.ttsProvider}\",\"language\":\"${data.language || globalData.voiceLanguage}\",\"openrouterTtsModel\":\"${data.model || globalData.openrouterTtsModel}\",\"voiceCredentialType\":\"${globalData.voiceCredentialType}\",\"voiceApiKey\":\"${globalData.voiceApiKey}\",\"voiceCredentialId\":\"${globalData.voiceCredentialId}\",\"azureSpeechKey\":\"${globalData.azureSpeechKey}\",\"azureSpeechRegion\":\"${globalData.azureSpeechRegion}\",\"azureCredentialId\":\"${globalData.azureCredentialId}\",\"awsAccessKeyId\":\"${globalData.awsAccessKeyId}\",\"awsSecretAccessKey\":\"${globalData.awsSecretAccessKey}\",\"awsRegion\":\"${globalData.awsRegion}\",\"awsCredentialId\":\"${globalData.awsCredentialId}\"}",
|
|
1544
|
+
"alsoDependsOn": ["language", "model"],
|
|
1545
|
+
"freeSolo": true
|
|
1546
|
+
},
|
|
1547
|
+
{
|
|
1548
|
+
"type": "autocompleteSendTo",
|
|
1549
|
+
"attr": "model",
|
|
1550
|
+
"title": "TTS model (optional)",
|
|
1551
|
+
"width": "38%",
|
|
1552
|
+
"command": "getTtsModels",
|
|
1553
|
+
"jsonData": "{\"ttsProvider\":\"${globalData.ttsProvider}\"}",
|
|
1554
|
+
"freeSolo": true
|
|
1555
|
+
},
|
|
1556
|
+
{
|
|
1557
|
+
"type": "custom",
|
|
1558
|
+
"attr": "_test",
|
|
1559
|
+
"title": "Test",
|
|
1560
|
+
"width": "10%",
|
|
1561
|
+
"i18n": true,
|
|
1562
|
+
"url": "custom/customComponents.js",
|
|
1563
|
+
"name": "ConfigCustomAssistant/Components/VoiceRowTestComponent",
|
|
1564
|
+
"bundlerType": "module",
|
|
1565
|
+
"guiApi": 2
|
|
1566
|
+
}
|
|
1511
1567
|
]
|
|
1512
1568
|
},
|
|
1513
1569
|
"_ffmpegPanel": {
|
|
@@ -143,9 +143,31 @@ function fallbackTts(provider, ctx) {
|
|
|
143
143
|
function voiceKey(provider) {
|
|
144
144
|
return provider === 'vosk' || provider === 'parakeet' ? '' : provider;
|
|
145
145
|
}
|
|
146
|
+
/** Providers whose TTS model can be chosen. */
|
|
147
|
+
function hasTtsModel(provider) {
|
|
148
|
+
return provider === 'openai' || provider === 'openrouter';
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The engine context of one row of the table "voice per language": its voice and model instead of the ones set above.
|
|
152
|
+
* Another OpenRouter model without a voice of its own gets none — the voices belong to the model, the engine then
|
|
153
|
+
* takes the first one of the model for the language.
|
|
154
|
+
*/
|
|
155
|
+
function rowContext(provider, key, lang, row, ctx) {
|
|
156
|
+
const model = hasTtsModel(provider) ? row.model : '';
|
|
157
|
+
const otherModel = provider === 'openrouter' && !!model && model !== (ctx.openrouterTtsModel || openrouter_1.DEFAULT_OPENROUTER_TTS_MODEL);
|
|
158
|
+
const voice = row.voice || (otherModel ? '' : ctx.voices[key]);
|
|
159
|
+
return {
|
|
160
|
+
...ctx,
|
|
161
|
+
// the voice of a row is for its language (Polly names say nothing about it)
|
|
162
|
+
language: lang,
|
|
163
|
+
voices: { ...ctx.voices, [key]: voice },
|
|
164
|
+
ttsModel: provider === 'openai' && model ? model : ctx.ttsModel,
|
|
165
|
+
openrouterTtsModel: provider === 'openrouter' && model ? model : ctx.openrouterTtsModel,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
146
168
|
/**
|
|
147
|
-
* The main provider with the table "voice per language": one engine per row with that voice. The table
|
|
148
|
-
* of the main provider, so the fallback provider does not get it.
|
|
169
|
+
* The main provider with the table "voice per language": one engine per row with that voice and model. The table
|
|
170
|
+
* names voices and models of the main provider, so the fallback provider does not get it.
|
|
149
171
|
*/
|
|
150
172
|
function withLanguageVoices(provider, ctx) {
|
|
151
173
|
const main = cachedTts(provider, ctx);
|
|
@@ -155,13 +177,18 @@ function withLanguageVoices(provider, ctx) {
|
|
|
155
177
|
return main;
|
|
156
178
|
}
|
|
157
179
|
const byLanguage = {};
|
|
158
|
-
for (const [lang,
|
|
180
|
+
for (const [lang, row] of rows) {
|
|
181
|
+
if (row.model && !hasTtsModel(provider)) {
|
|
182
|
+
ctx.log.warn(`TTS model '${row.model}' for '${lang}' ignored: ${provider} has no model choice`);
|
|
183
|
+
if (!row.voice) {
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
159
187
|
try {
|
|
160
|
-
|
|
161
|
-
byLanguage[lang] = cachedTts(provider, { ...ctx, language: lang, voices: { ...ctx.voices, [key]: voice } });
|
|
188
|
+
byLanguage[lang] = cachedTts(provider, rowContext(provider, key, lang, row, ctx));
|
|
162
189
|
}
|
|
163
190
|
catch (e) {
|
|
164
|
-
ctx.log.warn(`Voice '${voice}' for '${lang}' unavailable: ${e.message}`);
|
|
191
|
+
ctx.log.warn(`Voice '${row.voice || row.model}' for '${lang}' unavailable: ${e.message}`);
|
|
165
192
|
}
|
|
166
193
|
}
|
|
167
194
|
return new speechLanguage_1.VoicePerLanguage(main, byLanguage);
|
|
@@ -179,7 +206,8 @@ function cachedTts(provider, ctx) {
|
|
|
179
206
|
? ctx.voices.piper
|
|
180
207
|
: provider === 'openrouter'
|
|
181
208
|
? `${ctx.openrouterTtsModel || openrouter_1.DEFAULT_OPENROUTER_TTS_MODEL}-${ctx.voices.openrouter}`
|
|
182
|
-
:
|
|
209
|
+
: // the model too: another model must not serve the audio of the old one
|
|
210
|
+
`${ctx.ttsModel ? `${ctx.ttsModel}-` : ''}${ctx.voices.openai}`;
|
|
183
211
|
const dir = path.join(ctx.dataDir, 'ttscache', `${provider}-${(voice || 'default').replace(/[^\w.-]/g, '_')}`);
|
|
184
212
|
return new ttsCache_1.CachedTts(buildTtsEngine(provider, ctx), { dir, log: ctx.log, maxChars: ctx.ttsMaxChars });
|
|
185
213
|
}
|
|
@@ -235,8 +263,13 @@ async function listSttModels(provider, language) {
|
|
|
235
263
|
}
|
|
236
264
|
return provider === 'vosk' ? (0, vosk_1.listVoskModels)(language) : [];
|
|
237
265
|
}
|
|
238
|
-
/** TTS
|
|
266
|
+
/** OpenAI TTS models (no list API that tells speech models apart). */
|
|
267
|
+
const OPENAI_TTS_MODELS = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'];
|
|
268
|
+
/** TTS model names for the settings dropdown; the other providers have no model choice. */
|
|
239
269
|
async function listTtsModels(provider) {
|
|
240
|
-
|
|
270
|
+
if (provider === 'openrouter') {
|
|
271
|
+
return (await (0, openrouter_1.listOpenRouterSpeechModels)('speech')).map(m => m.id);
|
|
272
|
+
}
|
|
273
|
+
return provider === 'openai' ? OPENAI_TTS_MODELS : [];
|
|
241
274
|
}
|
|
242
275
|
//# sourceMappingURL=engines.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engines.js","sourceRoot":"","sources":["../../../src/lib/voice/engines.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHA,0CAYC;AA+BD,0CAGC;AAsGD,gCAmBC;AAGD,sCAKC;AAGD,sCAEC;AAzSD;;;;GAIG;AACH,+BAAkD;AAClD,+BAAoE;AACpE,mCAA8D;AAC9D,+BAAuE;AACvE,iCAAiD;AACjD,yCAA6D;AAC7D,mCAAoD;AACpD,6CAOsB;AACtB,gDAAkC;AAElC,yCAAuC;AACvC,yCAAwE;AACxE,iCAAqC;AACrC,qDAAiE;AAoEjE,SAAS,YAAY,CAAC,KAAuB;IACzC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACxE,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,KAAuB;IACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,SAAS,aAAa,CAAC,KAAuB;IAC1C,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACtD,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAuB;IAC9C,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;AACL,CAAC;AAED,SAAgB,eAAe,CAAC,QAAwB,EAAE,GAAkB;IACxE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,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;QACvF,CAAC;QACD;YACI,OAAO,aAAa,CAAC;IAC7B,CAAC;AACL,CAAC;AAED,kHAAkH;AAC3G,KAAK,UAAU,aAAa,CAAC,QAAwB,EAAE,QAAgB;IAC1E,IAAI,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC5B,OAAO,CAAC,MAAM,IAAA,uCAA0B,EAAC,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,IAAA,qBAAc,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/D,CAAC;AAED,8FAA8F;AACvF,KAAK,UAAU,aAAa,CAAC,QAAwB;IACxD,OAAO,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,MAAM,IAAA,uCAA0B,EAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxG,CAAC","sourcesContent":["/**\n * Factory that builds the configured STT/TTS engine. Cloud engines (OpenAI/Azure/AWS) use resolved\n * credentials; local engines (Vosk/Piper) download their models on demand into the data dir.\n * Adding a provider = one new engine class + one `case` here.\n */\nimport { OpenAiStt, type SttEngine } from './stt';\nimport { OpenAiTts, type OpenAiVoice, type TtsEngine } from './tts';\nimport { AzureStt, AzureTts, listAzureVoices } from './azure';\nimport { AwsStt, AwsTts, listPollyVoices, type AwsCreds } from './aws';\nimport { VoskStt, listVoskModels } from './vosk';\nimport { ParakeetStt, type MessageSender } from './parakeet';\nimport { PiperTts, listPiperVoices } from './piper';\nimport {\n OpenRouterStt,\n OpenRouterTts,\n listOpenRouterSpeechModels,\n voicesForLanguage,\n DEFAULT_OPENROUTER_TTS_MODEL,\n type AudioDecoder,\n} from './openrouter';\nimport * as path from 'node:path';\n\nimport { CachedTts } from './ttsCache';\nimport { FallbackStt, FallbackTts, type NamedEngine } from './fallback';\nimport { isoToLocale } from './lang';\nimport { LanguageTts, VoicePerLanguage } from './speechLanguage';\nimport type { VoiceLogger } from './download';\n\nexport type SpeechProvider = 'openai' | 'openrouter' | 'azure' | 'aws' | 'vosk' | 'parakeet' | 'piper';\n\n/** All speech credentials, resolved from config (or the central credential store). */\nexport interface VoiceCredentials {\n openaiKey: string;\n openrouterKey: string;\n azureKey: string;\n azureRegion: string;\n aws: AwsCreds;\n}\n\n/** Provider-specific voice ids (each provider names voices differently). */\nexport interface VoiceNames {\n openai: string; // alloy/echo/…\n azure: string; // e.g. de-DE-KatjaNeural\n aws: string; // e.g. Vicki\n piper: string; // e.g. de_DE-thorsten-medium\n openrouter: string; // depends on the model, e.g. Kore, george\n}\n\n/** Everything the factory needs to build any engine. */\nexport interface EngineContext {\n creds: VoiceCredentials;\n voices: VoiceNames;\n /** Optional second engine, used when the primary one fails ('' = none). */\n sttFallback?: SpeechProvider | '';\n ttsFallback?: SpeechProvider | '';\n /** Writable instance data dir (for the local engines' downloads). */\n dataDir: string;\n log: VoiceLogger;\n /** Local model overrides ('' → default per language). */\n voskModel: string;\n /** OpenAI STT model ('' → 'whisper-1'; e.g. 'gpt-4o-transcribe'). */\n sttModel: string;\n /**\n * OpenAI-compatible transcription server instead of OpenAI ('' = OpenAI), e.g. a local whisper container.\n * It gets `sttServerKey`, never the OpenAI key — that one is only for OpenAI.\n */\n sttBaseUrl?: string;\n /** Key for `sttBaseUrl` ('' = the server needs none). */\n sttServerKey?: string;\n /** OpenAI TTS model ('' → 'tts-1'; e.g. 'gpt-4o-mini-tts'). */\n ttsModel: string;\n /** OpenRouter models ('' → the defaults of openrouter.ts) */\n openrouterSttModel: string;\n openrouterTtsModel: string;\n /** Decoder for compressed speech (OpenRouter models that only return mp3); absent → those models fail */\n decodeAudio?: AudioDecoder;\n /** Longest text that is spoken, in characters; longer ones are cut at a sentence end. 0 = no limit, absent = 400. */\n ttsMaxChars?: number;\n /**\n * Language the satellites listen in (ISO-639-1). A voice set for one language (Polly 'Vicki') is only used for\n * it; an answer in another language gets the default voice of that language.\n */\n language?: string;\n /** Table \"voice per language\" (ISO code → voice of the main TTS provider); absent = the voices above. */\n voicesByLanguage?: Record<string, string>;\n /** Language the answering tier reported for exactly this text (pi-agent `language`); absent → by its letters. */\n reportedLanguage?: (text: string) => string | undefined;\n /** Instance of ioBroker.ai-parakeet for the provider `parakeet`, e.g. 'ai-parakeet.0'. */\n parakeetInstance?: string;\n /** Message bus to other instances (ai-parakeet); absent → `parakeet` cannot be used. */\n sendMessage?: MessageSender;\n}\n\nfunction requireAzure(creds: VoiceCredentials): void {\n if (!creds.azureKey || !creds.azureRegion) {\n throw new Error('Azure speech needs a subscription key and region');\n }\n}\n\nfunction requireAws(creds: VoiceCredentials): void {\n if (!creds.aws.accessKeyId || !creds.aws.secretAccessKey || !creds.aws.region) {\n throw new Error('AWS speech needs an access key id, secret access key and region');\n }\n}\n\nfunction requireOpenAi(creds: VoiceCredentials): void {\n if (!creds.openaiKey) {\n throw new Error('OpenAI speech needs an API key');\n }\n}\n\nfunction requireOpenRouter(creds: VoiceCredentials): void {\n if (!creds.openrouterKey) {\n throw new Error('OpenRouter speech needs an API key');\n }\n}\n\nexport function createSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n const primary: NamedEngine<SttEngine> = { name: provider, engine: buildSttEngine(provider, ctx) };\n const fallback = ctx.sttFallback && ctx.sttFallback !== provider ? ctx.sttFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackStt([primary, { name: fallback, engine: buildSttEngine(fallback, ctx) }], ctx.log);\n } catch (e) {\n ctx.log.warn(`Speech-to-text fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\nfunction buildSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureStt(ctx.creds.azureKey, ctx.creds.azureRegion);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsStt(ctx.creds.aws);\n case 'vosk':\n return new VoskStt(ctx.dataDir, ctx.voskModel, ctx.log);\n case 'parakeet':\n if (!ctx.sendMessage) {\n throw new Error('Parakeet speech recognition is not available here');\n }\n return new ParakeetStt((ctx.parakeetInstance || '').trim(), ctx.sendMessage);\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterStt(ctx.creds.openrouterKey, ctx.openrouterSttModel);\n case 'piper':\n throw new Error('Piper is a text-to-speech engine, not speech-to-text');\n default:\n if (ctx.sttBaseUrl?.trim()) {\n return new OpenAiStt(ctx.sttServerKey || '', ctx.sttModel || undefined, ctx.sttBaseUrl);\n }\n requireOpenAi(ctx.creds);\n return new OpenAiStt(ctx.creds.openaiKey, ctx.sttModel || undefined);\n }\n}\n\nexport function createTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Outermost: every text is spoken in its own language — a German voice spells a Russian answer letter by letter\n return new LanguageTts(fallbackTts(provider, ctx), ctx.reportedLanguage, ctx.log);\n}\n\nfunction fallbackTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Each engine gets the shared behaviour (disk cache, length limit, SSML) and its own cache directory,\n // so a fallback engine's voice can never be served later while the primary one is healthy again.\n const primary: NamedEngine<TtsEngine> = { name: provider, engine: withLanguageVoices(provider, ctx) };\n const fallback = ctx.ttsFallback && ctx.ttsFallback !== provider ? ctx.ttsFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackTts([primary, { name: fallback, engine: cachedTts(fallback, ctx) }], ctx.log);\n } catch (e) {\n // A fallback that cannot even be built (missing key, wrong provider) must not take the main one down.\n ctx.log.warn(`Text-to-speech fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\n/** Key of a provider in {@link VoiceNames}; the speech-to-text-only providers have no voice. */\nfunction voiceKey(provider: SpeechProvider): keyof VoiceNames | '' {\n return provider === 'vosk' || provider === 'parakeet' ? '' : provider;\n}\n\n/**\n * The main provider with the table \"voice per language\": one engine per row with that voice. The table names voices\n * of the main provider, so the fallback provider does not get it.\n */\nfunction withLanguageVoices(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const main = cachedTts(provider, ctx);\n const key = voiceKey(provider);\n const rows = Object.entries(ctx.voicesByLanguage || {});\n if (!key || !rows.length) {\n return main;\n }\n const byLanguage: Record<string, TtsEngine> = {};\n for (const [lang, voice] of rows) {\n try {\n // the voice of a row is for its language (Polly names say nothing about it)\n byLanguage[lang] = cachedTts(provider, { ...ctx, language: lang, voices: { ...ctx.voices, [key]: voice } });\n } catch (e) {\n ctx.log.warn(`Voice '${voice}' for '${lang}' unavailable: ${(e as Error).message}`);\n }\n }\n return new VoicePerLanguage(main, byLanguage);\n}\n\n/**\n * One provider binding plus the shared cache/length/SSML layer. One cache directory per provider+voice —\n * a voice change must not serve audio in the old voice.\n */\nfunction cachedTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const voice =\n provider === 'azure'\n ? ctx.voices.azure\n : provider === 'aws'\n ? ctx.voices.aws\n : provider === 'piper'\n ? ctx.voices.piper\n : provider === 'openrouter'\n ? `${ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL}-${ctx.voices.openrouter}`\n : ctx.voices.openai;\n const dir = path.join(ctx.dataDir, 'ttscache', `${provider}-${(voice || 'default').replace(/[^\\w.-]/g, '_')}`);\n return new CachedTts(buildTtsEngine(provider, ctx), { dir, log: ctx.log, maxChars: ctx.ttsMaxChars });\n}\n\nfunction buildTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureTts(ctx.creds.azureKey, ctx.creds.azureRegion, ctx.voices.azure);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsTts(ctx.creds.aws, ctx.voices.aws, ctx.language);\n case 'piper':\n return new PiperTts(ctx.dataDir, ctx.voices.piper, ctx.log);\n case 'vosk':\n throw new Error('Vosk is a speech-to-text engine, not text-to-speech');\n case 'parakeet':\n throw new Error('Parakeet is a speech-to-text engine, not text-to-speech');\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterTts(\n ctx.creds.openrouterKey,\n ctx.openrouterTtsModel,\n ctx.voices.openrouter,\n ctx.decodeAudio,\n );\n default:\n requireOpenAi(ctx.creds);\n return new OpenAiTts(\n ctx.creds.openaiKey,\n (ctx.voices.openai || 'alloy') as OpenAiVoice,\n ctx.ttsModel || undefined,\n );\n }\n}\n\n/** OpenAI TTS voices are a fixed set (no list API). */\nconst OPENAI_VOICES = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];\n\n/** List the available TTS voices for a provider (for the settings voice dropdown). */\nexport async function listVoices(provider: SpeechProvider, ctx: EngineContext, language: string): Promise<string[]> {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return listAzureVoices(ctx.creds.azureKey, ctx.creds.azureRegion, isoToLocale(language));\n case 'aws':\n requireAws(ctx.creds);\n return listPollyVoices(ctx.creds.aws, isoToLocale(language));\n case 'piper':\n return listPiperVoices();\n case 'openrouter': {\n // public list, no key needed: the voices of the chosen model\n const model = ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL;\n const models = await listOpenRouterSpeechModels('speech');\n return voicesForLanguage(models.find(m => m.id === model)?.voices || [], language);\n }\n default:\n return OPENAI_VOICES;\n }\n}\n\n/** Suggested STT model names for the settings dropdown: the local Vosk catalogue, or the models of OpenRouter. */\nexport async function listSttModels(provider: SpeechProvider, language: string): Promise<string[]> {\n if (provider === 'openrouter') {\n return (await listOpenRouterSpeechModels('transcription')).map(m => m.id);\n }\n return provider === 'vosk' ? listVoskModels(language) : [];\n}\n\n/** TTS model names for the settings dropdown — only OpenRouter has a choice worth listing. */\nexport async function listTtsModels(provider: SpeechProvider): Promise<string[]> {\n return provider === 'openrouter' ? (await listOpenRouterSpeechModels('speech')).map(m => m.id) : [];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"engines.js","sourceRoot":"","sources":["../../../src/lib/voice/engines.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHA,0CAYC;AA+BD,0CAGC;AA2ID,gCAmBC;AAGD,sCAKC;AAMD,sCAKC;AAvVD;;;;GAIG;AACH,+BAAkD;AAClD,+BAAoE;AACpE,mCAA8D;AAC9D,+BAAuE;AACvE,iCAAiD;AACjD,yCAA6D;AAC7D,mCAAoD;AACpD,6CAOsB;AACtB,gDAAkC;AAElC,yCAAuC;AACvC,yCAAwE;AACxE,iCAAqC;AACrC,qDAAqF;AAuErF,SAAS,YAAY,CAAC,KAAuB;IACzC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACxE,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,KAAuB;IACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,SAAS,aAAa,CAAC,KAAuB;IAC1C,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACtD,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAuB;IAC9C,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACvB,MAAM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AiB,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Factory that builds the configured STT/TTS engine. Cloud engines (OpenAI/Azure/AWS) use resolved\n * credentials; local engines (Vosk/Piper) download their models on demand into the data dir.\n * Adding a provider = one new engine class + one `case` here.\n */\nimport { OpenAiStt, type SttEngine } from './stt';\nimport { OpenAiTts, type OpenAiVoice, type TtsEngine } from './tts';\nimport { AzureStt, AzureTts, listAzureVoices } from './azure';\nimport { AwsStt, AwsTts, listPollyVoices, type AwsCreds } from './aws';\nimport { VoskStt, listVoskModels } from './vosk';\nimport { ParakeetStt, type MessageSender } from './parakeet';\nimport { PiperTts, listPiperVoices } from './piper';\nimport {\n OpenRouterStt,\n OpenRouterTts,\n listOpenRouterSpeechModels,\n voicesForLanguage,\n DEFAULT_OPENROUTER_TTS_MODEL,\n type AudioDecoder,\n} from './openrouter';\nimport * as path from 'node:path';\n\nimport { CachedTts } from './ttsCache';\nimport { FallbackStt, FallbackTts, type NamedEngine } from './fallback';\nimport { isoToLocale } from './lang';\nimport { LanguageTts, VoicePerLanguage, type LanguageVoice } from './speechLanguage';\nimport type { VoiceLogger } from './download';\n\nexport type SpeechProvider = 'openai' | 'openrouter' | 'azure' | 'aws' | 'vosk' | 'parakeet' | 'piper';\n\n/** All speech credentials, resolved from config (or the central credential store). */\nexport interface VoiceCredentials {\n openaiKey: string;\n openrouterKey: string;\n azureKey: string;\n azureRegion: string;\n aws: AwsCreds;\n}\n\n/** Provider-specific voice ids (each provider names voices differently). */\nexport interface VoiceNames {\n openai: string; // alloy/echo/…\n azure: string; // e.g. de-DE-KatjaNeural\n aws: string; // e.g. Vicki\n piper: string; // e.g. de_DE-thorsten-medium\n openrouter: string; // depends on the model, e.g. Kore, george\n}\n\n/** Everything the factory needs to build any engine. */\nexport interface EngineContext {\n creds: VoiceCredentials;\n voices: VoiceNames;\n /** Optional second engine, used when the primary one fails ('' = none). */\n sttFallback?: SpeechProvider | '';\n ttsFallback?: SpeechProvider | '';\n /** Writable instance data dir (for the local engines' downloads). */\n dataDir: string;\n log: VoiceLogger;\n /** Local model overrides ('' → default per language). */\n voskModel: string;\n /** OpenAI STT model ('' → 'whisper-1'; e.g. 'gpt-4o-transcribe'). */\n sttModel: string;\n /**\n * OpenAI-compatible transcription server instead of OpenAI ('' = OpenAI), e.g. a local whisper container.\n * It gets `sttServerKey`, never the OpenAI key — that one is only for OpenAI.\n */\n sttBaseUrl?: string;\n /** Key for `sttBaseUrl` ('' = the server needs none). */\n sttServerKey?: string;\n /** OpenAI TTS model ('' → 'tts-1'; e.g. 'gpt-4o-mini-tts'). */\n ttsModel: string;\n /** OpenRouter models ('' → the defaults of openrouter.ts) */\n openrouterSttModel: string;\n openrouterTtsModel: string;\n /** Decoder for compressed speech (OpenRouter models that only return mp3); absent → those models fail */\n decodeAudio?: AudioDecoder;\n /** Longest text that is spoken, in characters; longer ones are cut at a sentence end. 0 = no limit, absent = 400. */\n ttsMaxChars?: number;\n /**\n * Language the satellites listen in (ISO-639-1). A voice set for one language (Polly 'Vicki') is only used for\n * it; an answer in another language gets the default voice of that language.\n */\n language?: string;\n /**\n * Table \"voice per language\" (ISO code → voice and/or model of the main TTS provider); absent = the voices above.\n * A model only for OpenAI and OpenRouter, the others have no choice.\n */\n voicesByLanguage?: Record<string, LanguageVoice>;\n /** Language the answering tier reported for exactly this text (pi-agent `language`); absent → by its letters. */\n reportedLanguage?: (text: string) => string | undefined;\n /** Instance of ioBroker.ai-parakeet for the provider `parakeet`, e.g. 'ai-parakeet.0'. */\n parakeetInstance?: string;\n /** Message bus to other instances (ai-parakeet); absent → `parakeet` cannot be used. */\n sendMessage?: MessageSender;\n}\n\nfunction requireAzure(creds: VoiceCredentials): void {\n if (!creds.azureKey || !creds.azureRegion) {\n throw new Error('Azure speech needs a subscription key and region');\n }\n}\n\nfunction requireAws(creds: VoiceCredentials): void {\n if (!creds.aws.accessKeyId || !creds.aws.secretAccessKey || !creds.aws.region) {\n throw new Error('AWS speech needs an access key id, secret access key and region');\n }\n}\n\nfunction requireOpenAi(creds: VoiceCredentials): void {\n if (!creds.openaiKey) {\n throw new Error('OpenAI speech needs an API key');\n }\n}\n\nfunction requireOpenRouter(creds: VoiceCredentials): void {\n if (!creds.openrouterKey) {\n throw new Error('OpenRouter speech needs an API key');\n }\n}\n\nexport function createSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n const primary: NamedEngine<SttEngine> = { name: provider, engine: buildSttEngine(provider, ctx) };\n const fallback = ctx.sttFallback && ctx.sttFallback !== provider ? ctx.sttFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackStt([primary, { name: fallback, engine: buildSttEngine(fallback, ctx) }], ctx.log);\n } catch (e) {\n ctx.log.warn(`Speech-to-text fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\nfunction buildSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureStt(ctx.creds.azureKey, ctx.creds.azureRegion);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsStt(ctx.creds.aws);\n case 'vosk':\n return new VoskStt(ctx.dataDir, ctx.voskModel, ctx.log);\n case 'parakeet':\n if (!ctx.sendMessage) {\n throw new Error('Parakeet speech recognition is not available here');\n }\n return new ParakeetStt((ctx.parakeetInstance || '').trim(), ctx.sendMessage);\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterStt(ctx.creds.openrouterKey, ctx.openrouterSttModel);\n case 'piper':\n throw new Error('Piper is a text-to-speech engine, not speech-to-text');\n default:\n if (ctx.sttBaseUrl?.trim()) {\n return new OpenAiStt(ctx.sttServerKey || '', ctx.sttModel || undefined, ctx.sttBaseUrl);\n }\n requireOpenAi(ctx.creds);\n return new OpenAiStt(ctx.creds.openaiKey, ctx.sttModel || undefined);\n }\n}\n\nexport function createTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Outermost: every text is spoken in its own language — a German voice spells a Russian answer letter by letter\n return new LanguageTts(fallbackTts(provider, ctx), ctx.reportedLanguage, ctx.log);\n}\n\nfunction fallbackTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Each engine gets the shared behaviour (disk cache, length limit, SSML) and its own cache directory,\n // so a fallback engine's voice can never be served later while the primary one is healthy again.\n const primary: NamedEngine<TtsEngine> = { name: provider, engine: withLanguageVoices(provider, ctx) };\n const fallback = ctx.ttsFallback && ctx.ttsFallback !== provider ? ctx.ttsFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackTts([primary, { name: fallback, engine: cachedTts(fallback, ctx) }], ctx.log);\n } catch (e) {\n // A fallback that cannot even be built (missing key, wrong provider) must not take the main one down.\n ctx.log.warn(`Text-to-speech fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\n/** Key of a provider in {@link VoiceNames}; the speech-to-text-only providers have no voice. */\nfunction voiceKey(provider: SpeechProvider): keyof VoiceNames | '' {\n return provider === 'vosk' || provider === 'parakeet' ? '' : provider;\n}\n\n/** Providers whose TTS model can be chosen. */\nfunction hasTtsModel(provider: SpeechProvider): boolean {\n return provider === 'openai' || provider === 'openrouter';\n}\n\n/**\n * The engine context of one row of the table \"voice per language\": its voice and model instead of the ones set above.\n * Another OpenRouter model without a voice of its own gets none — the voices belong to the model, the engine then\n * takes the first one of the model for the language.\n */\nfunction rowContext(\n provider: SpeechProvider,\n key: keyof VoiceNames,\n lang: string,\n row: LanguageVoice,\n ctx: EngineContext,\n): EngineContext {\n const model = hasTtsModel(provider) ? row.model : '';\n const otherModel =\n provider === 'openrouter' && !!model && model !== (ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL);\n const voice = row.voice || (otherModel ? '' : ctx.voices[key]);\n return {\n ...ctx,\n // the voice of a row is for its language (Polly names say nothing about it)\n language: lang,\n voices: { ...ctx.voices, [key]: voice },\n ttsModel: provider === 'openai' && model ? model : ctx.ttsModel,\n openrouterTtsModel: provider === 'openrouter' && model ? model : ctx.openrouterTtsModel,\n };\n}\n\n/**\n * The main provider with the table \"voice per language\": one engine per row with that voice and model. The table\n * names voices and models of the main provider, so the fallback provider does not get it.\n */\nfunction withLanguageVoices(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const main = cachedTts(provider, ctx);\n const key = voiceKey(provider);\n const rows = Object.entries(ctx.voicesByLanguage || {});\n if (!key || !rows.length) {\n return main;\n }\n const byLanguage: Record<string, TtsEngine> = {};\n for (const [lang, row] of rows) {\n if (row.model && !hasTtsModel(provider)) {\n ctx.log.warn(`TTS model '${row.model}' for '${lang}' ignored: ${provider} has no model choice`);\n if (!row.voice) {\n continue;\n }\n }\n try {\n byLanguage[lang] = cachedTts(provider, rowContext(provider, key, lang, row, ctx));\n } catch (e) {\n ctx.log.warn(`Voice '${row.voice || row.model}' for '${lang}' unavailable: ${(e as Error).message}`);\n }\n }\n return new VoicePerLanguage(main, byLanguage);\n}\n\n/**\n * One provider binding plus the shared cache/length/SSML layer. One cache directory per provider+voice —\n * a voice change must not serve audio in the old voice.\n */\nfunction cachedTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const voice =\n provider === 'azure'\n ? ctx.voices.azure\n : provider === 'aws'\n ? ctx.voices.aws\n : provider === 'piper'\n ? ctx.voices.piper\n : provider === 'openrouter'\n ? `${ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL}-${ctx.voices.openrouter}`\n : // the model too: another model must not serve the audio of the old one\n `${ctx.ttsModel ? `${ctx.ttsModel}-` : ''}${ctx.voices.openai}`;\n const dir = path.join(ctx.dataDir, 'ttscache', `${provider}-${(voice || 'default').replace(/[^\\w.-]/g, '_')}`);\n return new CachedTts(buildTtsEngine(provider, ctx), { dir, log: ctx.log, maxChars: ctx.ttsMaxChars });\n}\n\nfunction buildTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureTts(ctx.creds.azureKey, ctx.creds.azureRegion, ctx.voices.azure);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsTts(ctx.creds.aws, ctx.voices.aws, ctx.language);\n case 'piper':\n return new PiperTts(ctx.dataDir, ctx.voices.piper, ctx.log);\n case 'vosk':\n throw new Error('Vosk is a speech-to-text engine, not text-to-speech');\n case 'parakeet':\n throw new Error('Parakeet is a speech-to-text engine, not text-to-speech');\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterTts(\n ctx.creds.openrouterKey,\n ctx.openrouterTtsModel,\n ctx.voices.openrouter,\n ctx.decodeAudio,\n );\n default:\n requireOpenAi(ctx.creds);\n return new OpenAiTts(\n ctx.creds.openaiKey,\n (ctx.voices.openai || 'alloy') as OpenAiVoice,\n ctx.ttsModel || undefined,\n );\n }\n}\n\n/** OpenAI TTS voices are a fixed set (no list API). */\nconst OPENAI_VOICES = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];\n\n/** List the available TTS voices for a provider (for the settings voice dropdown). */\nexport async function listVoices(provider: SpeechProvider, ctx: EngineContext, language: string): Promise<string[]> {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return listAzureVoices(ctx.creds.azureKey, ctx.creds.azureRegion, isoToLocale(language));\n case 'aws':\n requireAws(ctx.creds);\n return listPollyVoices(ctx.creds.aws, isoToLocale(language));\n case 'piper':\n return listPiperVoices();\n case 'openrouter': {\n // public list, no key needed: the voices of the chosen model\n const model = ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL;\n const models = await listOpenRouterSpeechModels('speech');\n return voicesForLanguage(models.find(m => m.id === model)?.voices || [], language);\n }\n default:\n return OPENAI_VOICES;\n }\n}\n\n/** Suggested STT model names for the settings dropdown: the local Vosk catalogue, or the models of OpenRouter. */\nexport async function listSttModels(provider: SpeechProvider, language: string): Promise<string[]> {\n if (provider === 'openrouter') {\n return (await listOpenRouterSpeechModels('transcription')).map(m => m.id);\n }\n return provider === 'vosk' ? listVoskModels(language) : [];\n}\n\n/** OpenAI TTS models (no list API that tells speech models apart). */\nconst OPENAI_TTS_MODELS = ['tts-1', 'tts-1-hd', 'gpt-4o-mini-tts'];\n\n/** TTS model names for the settings dropdown; the other providers have no model choice. */\nexport async function listTtsModels(provider: SpeechProvider): Promise<string[]> {\n if (provider === 'openrouter') {\n return (await listOpenRouterSpeechModels('speech')).map(m => m.id);\n }\n return provider === 'openai' ? OPENAI_TTS_MODELS : [];\n}\n"]}
|
|
@@ -215,7 +215,7 @@ function voiceFitsLanguage(voice, lang) {
|
|
|
215
215
|
}
|
|
216
216
|
return locale[1] === iso;
|
|
217
217
|
}
|
|
218
|
-
/** Parse the config table "voice per language" into ISO code → voice; rows without
|
|
218
|
+
/** Parse the config table "voice per language" into ISO code → voice and model; rows without either are skipped. */
|
|
219
219
|
function parseVoiceTable(rows) {
|
|
220
220
|
const table = {};
|
|
221
221
|
if (!Array.isArray(rows)) {
|
|
@@ -224,8 +224,9 @@ function parseVoiceTable(rows) {
|
|
|
224
224
|
for (const row of rows) {
|
|
225
225
|
const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');
|
|
226
226
|
const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';
|
|
227
|
-
|
|
228
|
-
|
|
227
|
+
const model = typeof row?.model === 'string' ? row.model.trim() : '';
|
|
228
|
+
if (lang && (voice || model)) {
|
|
229
|
+
table[lang] = { voice, model };
|
|
229
230
|
}
|
|
230
231
|
}
|
|
231
232
|
return table;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AAuDA,oCAKC;AA0BD,wCAkBC;AAUD,wCAkBC;AAuCD,4CAwBC;AA+CD,8CAOC;AAGD,0CAaC;AAvPD,+FAA+F;AAC/F,MAAM,SAAS,GAA2B;IACtC,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;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B,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;IACL,CAAC;IAED,IAAI,CAAC,OAAiB,EAAE,IAAY;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC;CACJ;AAhCD,4CAgCC","sourcesContent":["/**\n * The language an answer is spoken in. The transports hand the TTS the language the satellite listens in, but an\n * answer can be in another one (a question asked in Russian on a German satellite, pi-agent answering in the language\n * of the question). A German voice reads Cyrillic letter by letter (\"kyrillisch a, kyrillisch b …\"), so the TTS\n * takes the language of the text:\n *\n * 1. the language the answering tier reported (pi-agent ≥ 0.10.1 returns `language`), unless the letters contradict it;\n * 2. otherwise the letters: a text in another script than the configured language (Cyrillic, Greek, CJK …) is spoken\n * in the language of that script. Latin letters do not tell German from English: then the configured language\n * stays, unless it is itself written in another script (a Russian satellite answering in Latin letters → English).\n *\n * {@link LanguageTts} applies this in front of every TTS engine; {@link VoicePerLanguage} picks the voice of the\n * table \"voice per language\" for it.\n */\nimport type { TtsEngine, TtsResult } from './tts';\n\ntype Script = 'latin' | 'cyrillic' | 'greek' | 'cjk' | 'hangul' | 'arabic' | 'hebrew';\n\n/** Script of the languages that are not written in Latin letters; everything else is Latin. */\nconst SCRIPT_OF: Record<string, Script> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n el: 'greek',\n zh: 'cjk',\n ja: 'cjk',\n ko: 'hangul',\n ar: 'arabic',\n fa: 'arabic',\n he: 'hebrew',\n};\n\nconst LETTERS: [Script, RegExp][] = [\n ['latin', /[a-zÀ-ɏ]/gi],\n ['cyrillic', /[Ѐ-ӿ]/g],\n ['greek', /[Ͱ-Ͽ]/g],\n ['cjk', /[-ヿ㐀-鿿]/g],\n ['hangul', /[가-ᄀ-ᇿ]/g],\n ['arabic', /[-ۿ]/g],\n ['hebrew', /[-]/g],\n];\n\n/** Fewer letters than this say nothing about the language (\"OK\", \"5 °C\"). */\nconst MIN_LETTERS = 3;\n\n/** Letters only Ukrainian has among the Cyrillic languages. */\nconst UKRAINIAN = /[ґєії]/i;\n/** Kana: Japanese, not Chinese. */\nconst KANA = /[-ヿ]/;\n\n/** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */\nexport function baseLanguage(lang: string | undefined): string {\n return String(lang || '')\n .trim()\n .split(/[-_]/)[0]\n .toLowerCase();\n}\n\nfunction scriptOf(lang: string): Script {\n return SCRIPT_OF[baseLanguage(lang)] || 'latin';\n}\n\n/** The script most letters of the text are in; '' for too few letters. */\nfunction dominantScript(text: string): Script | '' {\n let best: Script | '' = '';\n let most = 0;\n let total = 0;\n for (const [script, re] of LETTERS) {\n const count = (text.match(re) || []).length;\n total += count;\n if (count > most) {\n best = script;\n most = count;\n }\n }\n return total >= MIN_LETTERS ? best : '';\n}\n\n/**\n * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for\n * too few letters.\n */\nexport function scriptLanguage(text: string): string {\n const script = dominantScript(String(text || ''));\n switch (script) {\n case 'cyrillic':\n return UKRAINIAN.test(text) ? 'uk' : 'ru';\n case 'greek':\n return 'el';\n case 'cjk':\n return KANA.test(text) ? 'ja' : 'zh';\n case 'hangul':\n return 'ko';\n case 'arabic':\n return 'ar';\n case 'hebrew':\n return 'he';\n default:\n return '';\n }\n}\n\n/**\n * The language to speak a text in.\n *\n * @param text what is spoken\n * @param configured the language the caller asked for (the satellite's language)\n * @param reported the language the answering tier reported ('' = none)\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function speechLanguage(text: string, configured: string, reported?: string): string {\n const script = dominantScript(String(text || ''));\n const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';\n // a report is believed unless the letters contradict it (a \"de\" mark on a Cyrillic answer)\n if (said && (!script || scriptOf(said) === script)) {\n // the configured language in its own form ('de-DE'): same voice, same cache entry\n return said === baseLanguage(configured) ? configured : said;\n }\n if (!script) {\n return configured;\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Words that say a Latin-script question is English or German. Only words of one of the two: \"in\", \"an\", \"die\",\n * \"was\", \"will\", \"so\", \"man\" are both and say nothing. Kept to what short spoken commands and questions use.\n */\nconst FUNCTION_WORDS: Record<'en' | 'de', ReadonlySet<string>> = {\n en: new Set(\n (\n \"the what what's whats is are it it's its how turn switch please light lights time me my of to and you your \" +\n 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +\n 'does do can could would there all up down timer alarm minutes hours at for be play stop'\n ).split(' '),\n ),\n de: new Set(\n (\n 'der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +\n 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +\n 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +\n 'kannst spiele spiel'\n ).split(' '),\n ),\n};\n\n/** Function words of `lang` in the words of a text; 0 for a language without a list. */\nfunction functionWords(words: string[], lang: string): number {\n const list = FUNCTION_WORDS[lang as 'en' | 'de'];\n return list ? words.filter(w => list.has(w)).length : 0;\n}\n\n/**\n * The language a question is asked in, for the fixed answers of the rule NLU (\"скажи, сколько сейчас времени\" on a\n * German satellite was answered in German). Another script than the configured language's tells it by the letters\n * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with\n * at least two of them and more than twice as many as of the configured language, so a German command with an\n * English device name stays German and a French question on a French system is not taken for German.\n *\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function questionLanguage(text: string, configured: string): string {\n const question = String(text || '');\n const script = dominantScript(question);\n if (!script) {\n return configured;\n }\n if (script !== 'latin') {\n return speechLanguage(question, configured);\n }\n const words = question.toLowerCase().match(/[\\p{L}']+/gu) || [];\n const base = baseLanguage(configured);\n let best = '';\n let most = 0;\n for (const lang of ['en', 'de']) {\n const hits = functionWords(words, lang);\n if (hits > most) {\n best = lang;\n most = hits;\n }\n }\n if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {\n return configured;\n }\n return best;\n}\n\n/** How many answers {@link AnswerLanguages} remembers. */\nconst KEPT_LANGUAGES = 50;\n\n/**\n * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to\n * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):\n * the assistant takes them out before speaking.\n */\nexport class AnswerLanguages {\n private readonly byText = new Map<string, string>();\n\n private static key(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n\n /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */\n remember(text: string, language: string): void {\n const lang = String(language || '')\n .trim()\n .toLowerCase();\n const key = AnswerLanguages.key(text);\n if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {\n return;\n }\n this.byText.delete(key);\n this.byText.set(key, lang);\n if (this.byText.size > KEPT_LANGUAGES) {\n this.byText.delete(this.byText.keys().next().value as string);\n }\n }\n\n /** The language remembered for this answer, '' for none. */\n languageOf(text: string): string {\n return this.byText.get(AnswerLanguages.key(text)) || '';\n }\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice; rows without both are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, string> {\n const table: Record<string, string> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown }[]) {\n const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n if (lang && voice) {\n table[lang] = voice;\n }\n }\n return table;\n}\n\n/** Log of the TTS layer. */\ninterface Logger {\n debug(msg: string): void;\n}\n\n/**\n * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the\n * language the answering tier gave for exactly this text.\n */\nexport class LanguageTts implements TtsEngine {\n constructor(\n private readonly inner: TtsEngine,\n private readonly reported: ((text: string) => string | undefined) | undefined,\n private readonly log: Logger,\n ) {}\n\n /** The language `text` is spoken in when the caller asks for `lang`. */\n languageFor(text: string, lang: string): string {\n const spoken = speechLanguage(text, lang, this.reported?.(text));\n if (spoken !== lang) {\n this.log.debug(`TTS in '${spoken}' instead of '${lang}': \"${String(text).slice(0, 40)}\"`);\n }\n return spoken;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.inner.synthesize(text, this.languageFor(text, lang));\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);\n return this.inner.synthesizeSsml\n ? this.inner.synthesizeSsml(ssml, spoken)\n : this.inner.synthesize(ssml, spoken);\n }\n\n prepare(lang: string): Promise<void> {\n return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);\n }\n}\n\n/**\n * The voices of the table \"voice per language\": one engine per row, the default engine for every other language.\n * Each engine has its own cache (the directory is per voice).\n */\nexport class VoicePerLanguage implements TtsEngine {\n constructor(\n private readonly fallback: TtsEngine,\n private readonly byLanguage: Record<string, TtsEngine>,\n ) {}\n\n private engineFor(lang: string): TtsEngine {\n return this.byLanguage[baseLanguage(lang)] || this.fallback;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.engineFor(lang).synthesize(text, lang);\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const engine = this.engineFor(lang);\n return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);\n }\n\n /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */\n async prepare(lang: string): Promise<void> {\n await this.engineFor(lang).prepare?.(lang);\n for (const [code, engine] of Object.entries(this.byLanguage)) {\n if (code !== baseLanguage(lang)) {\n await engine.prepare?.(code);\n }\n }\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AAuDA,oCAKC;AA0BD,wCAkBC;AAUD,wCAkBC;AAuCD,4CAwBC;AA+CD,8CAOC;AASD,0CAcC;AA9PD,+FAA+F;AAC/F,MAAM,SAAS,GAA2B;IACtC,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,QA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M,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;IACL,CAAC;IAED,IAAI,CAAC,OAAiB,EAAE,IAAY;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC;CACJ;AAhCD,4CAgCC","sourcesContent":["/**\n * The language an answer is spoken in. The transports hand the TTS the language the satellite listens in, but an\n * answer can be in another one (a question asked in Russian on a German satellite, pi-agent answering in the language\n * of the question). A German voice reads Cyrillic letter by letter (\"kyrillisch a, kyrillisch b …\"), so the TTS\n * takes the language of the text:\n *\n * 1. the language the answering tier reported (pi-agent ≥ 0.10.1 returns `language`), unless the letters contradict it;\n * 2. otherwise the letters: a text in another script than the configured language (Cyrillic, Greek, CJK …) is spoken\n * in the language of that script. Latin letters do not tell German from English: then the configured language\n * stays, unless it is itself written in another script (a Russian satellite answering in Latin letters → English).\n *\n * {@link LanguageTts} applies this in front of every TTS engine; {@link VoicePerLanguage} picks the voice of the\n * table \"voice per language\" for it.\n */\nimport type { TtsEngine, TtsResult } from './tts';\n\ntype Script = 'latin' | 'cyrillic' | 'greek' | 'cjk' | 'hangul' | 'arabic' | 'hebrew';\n\n/** Script of the languages that are not written in Latin letters; everything else is Latin. */\nconst SCRIPT_OF: Record<string, Script> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n el: 'greek',\n zh: 'cjk',\n ja: 'cjk',\n ko: 'hangul',\n ar: 'arabic',\n fa: 'arabic',\n he: 'hebrew',\n};\n\nconst LETTERS: [Script, RegExp][] = [\n ['latin', /[a-zÀ-ɏ]/gi],\n ['cyrillic', /[Ѐ-ӿ]/g],\n ['greek', /[Ͱ-Ͽ]/g],\n ['cjk', /[-ヿ㐀-鿿]/g],\n ['hangul', /[가-ᄀ-ᇿ]/g],\n ['arabic', /[-ۿ]/g],\n ['hebrew', /[-]/g],\n];\n\n/** Fewer letters than this say nothing about the language (\"OK\", \"5 °C\"). */\nconst MIN_LETTERS = 3;\n\n/** Letters only Ukrainian has among the Cyrillic languages. */\nconst UKRAINIAN = /[ґєії]/i;\n/** Kana: Japanese, not Chinese. */\nconst KANA = /[-ヿ]/;\n\n/** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */\nexport function baseLanguage(lang: string | undefined): string {\n return String(lang || '')\n .trim()\n .split(/[-_]/)[0]\n .toLowerCase();\n}\n\nfunction scriptOf(lang: string): Script {\n return SCRIPT_OF[baseLanguage(lang)] || 'latin';\n}\n\n/** The script most letters of the text are in; '' for too few letters. */\nfunction dominantScript(text: string): Script | '' {\n let best: Script | '' = '';\n let most = 0;\n let total = 0;\n for (const [script, re] of LETTERS) {\n const count = (text.match(re) || []).length;\n total += count;\n if (count > most) {\n best = script;\n most = count;\n }\n }\n return total >= MIN_LETTERS ? best : '';\n}\n\n/**\n * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for\n * too few letters.\n */\nexport function scriptLanguage(text: string): string {\n const script = dominantScript(String(text || ''));\n switch (script) {\n case 'cyrillic':\n return UKRAINIAN.test(text) ? 'uk' : 'ru';\n case 'greek':\n return 'el';\n case 'cjk':\n return KANA.test(text) ? 'ja' : 'zh';\n case 'hangul':\n return 'ko';\n case 'arabic':\n return 'ar';\n case 'hebrew':\n return 'he';\n default:\n return '';\n }\n}\n\n/**\n * The language to speak a text in.\n *\n * @param text what is spoken\n * @param configured the language the caller asked for (the satellite's language)\n * @param reported the language the answering tier reported ('' = none)\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function speechLanguage(text: string, configured: string, reported?: string): string {\n const script = dominantScript(String(text || ''));\n const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';\n // a report is believed unless the letters contradict it (a \"de\" mark on a Cyrillic answer)\n if (said && (!script || scriptOf(said) === script)) {\n // the configured language in its own form ('de-DE'): same voice, same cache entry\n return said === baseLanguage(configured) ? configured : said;\n }\n if (!script) {\n return configured;\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Words that say a Latin-script question is English or German. Only words of one of the two: \"in\", \"an\", \"die\",\n * \"was\", \"will\", \"so\", \"man\" are both and say nothing. Kept to what short spoken commands and questions use.\n */\nconst FUNCTION_WORDS: Record<'en' | 'de', ReadonlySet<string>> = {\n en: new Set(\n (\n \"the what what's whats is are it it's its how turn switch please light lights time me my of to and you your \" +\n 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +\n 'does do can could would there all up down timer alarm minutes hours at for be play stop'\n ).split(' '),\n ),\n de: new Set(\n (\n 'der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +\n 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +\n 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +\n 'kannst spiele spiel'\n ).split(' '),\n ),\n};\n\n/** Function words of `lang` in the words of a text; 0 for a language without a list. */\nfunction functionWords(words: string[], lang: string): number {\n const list = FUNCTION_WORDS[lang as 'en' | 'de'];\n return list ? words.filter(w => list.has(w)).length : 0;\n}\n\n/**\n * The language a question is asked in, for the fixed answers of the rule NLU (\"скажи, сколько сейчас времени\" on a\n * German satellite was answered in German). Another script than the configured language's tells it by the letters\n * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with\n * at least two of them and more than twice as many as of the configured language, so a German command with an\n * English device name stays German and a French question on a French system is not taken for German.\n *\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function questionLanguage(text: string, configured: string): string {\n const question = String(text || '');\n const script = dominantScript(question);\n if (!script) {\n return configured;\n }\n if (script !== 'latin') {\n return speechLanguage(question, configured);\n }\n const words = question.toLowerCase().match(/[\\p{L}']+/gu) || [];\n const base = baseLanguage(configured);\n let best = '';\n let most = 0;\n for (const lang of ['en', 'de']) {\n const hits = functionWords(words, lang);\n if (hits > most) {\n best = lang;\n most = hits;\n }\n }\n if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {\n return configured;\n }\n return best;\n}\n\n/** How many answers {@link AnswerLanguages} remembers. */\nconst KEPT_LANGUAGES = 50;\n\n/**\n * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to\n * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):\n * the assistant takes them out before speaking.\n */\nexport class AnswerLanguages {\n private readonly byText = new Map<string, string>();\n\n private static key(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n\n /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */\n remember(text: string, language: string): void {\n const lang = String(language || '')\n .trim()\n .toLowerCase();\n const key = AnswerLanguages.key(text);\n if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {\n return;\n }\n this.byText.delete(key);\n this.byText.set(key, lang);\n if (this.byText.size > KEPT_LANGUAGES) {\n this.byText.delete(this.byText.keys().next().value as string);\n }\n }\n\n /** The language remembered for this answer, '' for none. */\n languageOf(text: string): string {\n return this.byText.get(AnswerLanguages.key(text)) || '';\n }\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** A row of the table \"voice per language\": the voice and/or the TTS model ('' = the ones set above). */\nexport interface LanguageVoice {\n voice: string;\n model: string;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice and model; rows without either are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, LanguageVoice> {\n const table: Record<string, LanguageVoice> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown; model?: unknown }[]) {\n const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n const model = typeof row?.model === 'string' ? row.model.trim() : '';\n if (lang && (voice || model)) {\n table[lang] = { voice, model };\n }\n }\n return table;\n}\n\n/** Log of the TTS layer. */\ninterface Logger {\n debug(msg: string): void;\n}\n\n/**\n * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the\n * language the answering tier gave for exactly this text.\n */\nexport class LanguageTts implements TtsEngine {\n constructor(\n private readonly inner: TtsEngine,\n private readonly reported: ((text: string) => string | undefined) | undefined,\n private readonly log: Logger,\n ) {}\n\n /** The language `text` is spoken in when the caller asks for `lang`. */\n languageFor(text: string, lang: string): string {\n const spoken = speechLanguage(text, lang, this.reported?.(text));\n if (spoken !== lang) {\n this.log.debug(`TTS in '${spoken}' instead of '${lang}': \"${String(text).slice(0, 40)}\"`);\n }\n return spoken;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.inner.synthesize(text, this.languageFor(text, lang));\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);\n return this.inner.synthesizeSsml\n ? this.inner.synthesizeSsml(ssml, spoken)\n : this.inner.synthesize(ssml, spoken);\n }\n\n prepare(lang: string): Promise<void> {\n return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);\n }\n}\n\n/**\n * The voices of the table \"voice per language\": one engine per row, the default engine for every other language.\n * Each engine has its own cache (the directory is per voice).\n */\nexport class VoicePerLanguage implements TtsEngine {\n constructor(\n private readonly fallback: TtsEngine,\n private readonly byLanguage: Record<string, TtsEngine>,\n ) {}\n\n private engineFor(lang: string): TtsEngine {\n return this.byLanguage[baseLanguage(lang)] || this.fallback;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.engineFor(lang).synthesize(text, lang);\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const engine = this.engineFor(lang);\n return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);\n }\n\n /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */\n async prepare(lang: string): Promise<void> {\n await this.engineFor(lang).prepare?.(lang);\n for (const [code, engine] of Object.entries(this.byLanguage)) {\n if (code !== baseLanguage(lang)) {\n await engine.prepare?.(code);\n }\n }\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}
|
package/build/main.js
CHANGED
|
@@ -1004,10 +1004,13 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
1004
1004
|
async getVoices(msg) {
|
|
1005
1005
|
try {
|
|
1006
1006
|
// Merge the form's config-shaped fields over the saved config (ttsProvider/language handled apart).
|
|
1007
|
-
|
|
1007
|
+
// 'undefined' is a field the form does not have (a pattern `${globalData.x}` in a table writes it).
|
|
1008
|
+
const overrides = Object.fromEntries(Object.entries(msg).filter(([k, v]) => v !== undefined && v !== 'undefined' && k !== 'ttsProvider' && k !== 'language'));
|
|
1008
1009
|
const cfg = { ...this.config, ...overrides };
|
|
1009
|
-
const provider = msg.ttsProvider
|
|
1010
|
-
|
|
1010
|
+
const provider = (msg.ttsProvider && msg.ttsProvider !== 'undefined' ? msg.ttsProvider : '') ||
|
|
1011
|
+
cfg.ttsProvider ||
|
|
1012
|
+
'openai';
|
|
1013
|
+
const language = (msg.language !== 'undefined' && msg.language) || cfg.voiceLanguage || this.language || '';
|
|
1011
1014
|
const creds = await (0, credentials_1.resolveVoiceCredentials)(this, cfg, await this.speechLlmKey());
|
|
1012
1015
|
return await (0, engines_1.listVoices)(provider, this.voiceContext(cfg, creds), language);
|
|
1013
1016
|
}
|
|
@@ -2728,7 +2731,9 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
2728
2731
|
models =
|
|
2729
2732
|
obj.command === 'getSttModels'
|
|
2730
2733
|
? await (0, engines_1.listSttModels)(msg.sttProvider || cfg.sttProvider || 'openai', language)
|
|
2731
|
-
: await (0, engines_1.listTtsModels)(msg.ttsProvider
|
|
2734
|
+
: await (0, engines_1.listTtsModels)((msg.ttsProvider !== 'undefined' && msg.ttsProvider) ||
|
|
2735
|
+
cfg.ttsProvider ||
|
|
2736
|
+
'openai');
|
|
2732
2737
|
}
|
|
2733
2738
|
catch (e) {
|
|
2734
2739
|
this.log.warn(`${obj.command} failed: ${e.message}`);
|