iobroker.assistant 1.7.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 +7 -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/piAgent.js +5 -22
- package/build/lib/piAgent.js.map +1 -1
- package/build/lib/voice/engines.js +42 -9
- package/build/lib/voice/engines.js.map +1 -1
- package/build/lib/voice/speechLanguage.js +94 -4
- package/build/lib/voice/speechLanguage.js.map +1 -1
- package/build/main.js +49 -23
- package/build/main.js.map +1 -1
- package/io-package.json +71 -29
- package/package.json +3 -2
- 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": {
|
package/build/lib/piAgent.js
CHANGED
|
@@ -23,6 +23,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
23
23
|
exports.PiAgentHarness = exports.PI_AGENT_TIMEOUT_SEC = exports.PI_AGENT_MAX_INSTRUCTIONS = void 0;
|
|
24
24
|
exports.composeInstructions = composeInstructions;
|
|
25
25
|
exports.conversationOf = conversationOf;
|
|
26
|
+
const speechLanguage_1 = require("./voice/speechLanguage");
|
|
26
27
|
/** Longest instructions pi-agent accepts for a conversation; anything beyond is cut there. */
|
|
27
28
|
exports.PI_AGENT_MAX_INSTRUCTIONS = 20000;
|
|
28
29
|
/** Default for `piAgentTimeoutSec`: a tool loop with several reads can take a while. */
|
|
@@ -52,25 +53,13 @@ function composeInstructions(required, optional) {
|
|
|
52
53
|
function conversationOf(source) {
|
|
53
54
|
return (source || 'default').replace(/\//g, '_').slice(0, 100);
|
|
54
55
|
}
|
|
55
|
-
/**
|
|
56
|
-
* An answer as the TTS gets it: the assistant takes the control markers ([[LISTEN]] after a question to confirm,
|
|
57
|
-
* [[DONE]]) out before speaking, so the language is kept under the text without them.
|
|
58
|
-
*/
|
|
59
|
-
function answerKey(text) {
|
|
60
|
-
return String(text || '')
|
|
61
|
-
.replace(/\[\[[A-Z]+\]\]/gi, ' ')
|
|
62
|
-
.replace(/\s+/g, ' ')
|
|
63
|
-
.trim();
|
|
64
|
-
}
|
|
65
|
-
/** How many answers {@link PiAgentHarness.languageOf} remembers. */
|
|
66
|
-
const KEPT_LANGUAGES = 50;
|
|
67
56
|
class PiAgentHarness {
|
|
68
57
|
host;
|
|
69
58
|
instance;
|
|
70
59
|
timeoutMs;
|
|
71
60
|
seq = 0;
|
|
72
61
|
/** Language pi-agent reported per answer text (pi-agent 0.10.1+), for the voice that speaks it. */
|
|
73
|
-
languages = new
|
|
62
|
+
languages = new speechLanguage_1.AnswerLanguages();
|
|
74
63
|
constructor(host,
|
|
75
64
|
/** e.g. `pi-agent.0` */
|
|
76
65
|
instance, timeoutMs = exports.PI_AGENT_TIMEOUT_SEC * 1000) {
|
|
@@ -107,14 +96,8 @@ class PiAgentHarness {
|
|
|
107
96
|
if (!answer) {
|
|
108
97
|
throw new Error(`${this.instance} gave no answer`);
|
|
109
98
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const key = answerKey(answer);
|
|
113
|
-
this.languages.delete(key);
|
|
114
|
-
this.languages.set(key, language);
|
|
115
|
-
if (this.languages.size > KEPT_LANGUAGES) {
|
|
116
|
-
this.languages.delete(this.languages.keys().next().value);
|
|
117
|
-
}
|
|
99
|
+
if (typeof result?.language === 'string') {
|
|
100
|
+
this.languages.remember(answer, result.language);
|
|
118
101
|
}
|
|
119
102
|
return answer;
|
|
120
103
|
}
|
|
@@ -123,7 +106,7 @@ class PiAgentHarness {
|
|
|
123
106
|
* left its mark out). The answer travels as plain text through the tiers; this finds its language again by text.
|
|
124
107
|
*/
|
|
125
108
|
languageOf(answer) {
|
|
126
|
-
return this.languages.
|
|
109
|
+
return this.languages.languageOf(answer);
|
|
127
110
|
}
|
|
128
111
|
}
|
|
129
112
|
exports.PiAgentHarness = PiAgentHarness;
|
package/build/lib/piAgent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"piAgent.js","sourceRoot":"","sources":["../../src/lib/piAgent.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;AAiDH,kDAaC;AAGD,wCAEC;AA/DD,8FAA8F;AACjF,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAE/C,wFAAwF;AAC3E,QAAA,oBAAoB,GAAG,EAAE,CAAC;AAkCvC;;;;;;GAMG;AACH,SAAgB,mBAAmB,CAAC,QAAkB,EAAE,QAAkB;IACtE,MAAM,MAAM,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACvC,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,MAAM,IAAI,GAAG,CAAC,GAAG,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChD,IAAI,IAAI,CAAC,MAAM,IAAI,iCAAyB,EAAE,CAAC;YAC3C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC7B,CAAC;QACD,KAAK,CAAC,GAAG,EAAE,CAAC;QACZ,OAAO,EAAE,CAAC;IACd,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAA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,EAAE,CAAC,CAAC;QAClD,CAAC;QACD,MAAM,MAAM,GAAG,OAAO,MAAM,EAAE,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9E,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,iBAAiB,CAAC,CAAC;QACvD,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,MAAM,EAAE,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAClG,IAAI,4BAA4B,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9C,MAAM,GAAG,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;YAC9B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAC3B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;YAClC,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,cAAc,EAAE,CAAC;gBACvC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAe,CAAC,CAAC;YACxE,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;IAED;;;OAGG;IACI,UAAU,CAAC,MAAc;QAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACvD,CAAC;CACJ;AAjED,wCAiEC","sourcesContent":["/**\n * The adapter `pi-agent` as the cloud tier (\"harness\"): instead of running its own tool loop, the assistant\n * hands the question to a pi-agent instance via `sendTo(<instance>, 'ask', …)`. pi-agent stores every model\n * and tool call as a checkpoint before it runs (an interrupted request continues after a restart, a write is\n * never repeated), enforces its own write permissions and confirmations, and can use the system-wide AI\n * settings of admin — none of which the built-in `LlmAgent` does.\n *\n * Each request source (satellite, `chat`, `telegram:<user>`) gets a conversation of its own in pi-agent\n * (`conversation`), so two rooms do not see each other's follow-ups. The source-independent part of the\n * prompt (style, follow-up marker, memory, device list) goes along as the `instructions` of that\n * conversation; what changes every turn (time, weather, presence) is prepended to the question.\n * pi-agent 0.3.0 and older ignore both fields and answer everything in their root conversation.\n *\n * With \"Confirmation by text in sendTo conversations\", pi-agent answers a write it may not do unasked with a\n * question ending in `[[LISTEN]]`, and the next `ask` of the conversation is the yes or no. `language` makes it\n * ask that question in the language the satellite listens in.\n *\n * pi-agent 0.10.1+ also answers with `language`, the language it wrote the answer in; the voice that speaks the\n * answer is chosen by it ({@link PiAgentHarness.languageOf}).\n */\n\nimport type { ImageInput } from './media';\n\n/** Longest instructions pi-agent accepts for a conversation; anything beyond is cut there. */\nexport const PI_AGENT_MAX_INSTRUCTIONS = 20000;\n\n/** Default for `piAgentTimeoutSec`: a tool loop with several reads can take a while. */\nexport const PI_AGENT_TIMEOUT_SEC = 60;\n\n/** The part of the adapter this module needs (kept small so tests can fake it). */\nexport interface PiAgentHost {\n sendToAsync(instance: string, command: string, message: unknown, options?: { timeout?: number }): Promise<unknown>;\n getForeignStateAsync(id: string): Promise<ioBroker.State | null | undefined>;\n}\n\nexport interface PiAgentRequest {\n /** The text pi-agent answers: context lines + the question. */\n text: string;\n /** Conversation of the caller, e.g. the satellite name. */\n conversation: string;\n /** Instructions of that conversation. */\n instructions: string;\n /**\n * Language the user speaks, e.g. `ru`. pi-agent asks its questions to confirm in it; older versions ask in the\n * system language, and a satellite listening in Russian does not hear a German \"Ja\" (the STT returns nothing).\n */\n language?: string;\n /**\n * Pictures that came with the question (`{ data: base64, mimeType }`, the form of pi-ai's `ImageContent`).\n * Versions of pi-agent before image support ignore them; the text then says that pictures came along.\n */\n images?: ImageInput[];\n /**\n * Only for a request from a voice satellite: its id under `assistant.N.satellites.*`, and the full id of its `tts`\n * state. Writing text there speaks it on that satellite — so pi-agent can answer later where it was asked (a\n * reminder, the end of a background task). Chat and Telegram requests have neither.\n */\n satellite?: string;\n tts?: string;\n}\n\n/**\n * Join instruction blocks, leaving out optional ones from the end until the result fits into pi-agent's\n * limit — pi-agent would cut the text in the middle, and a half device list is worse than none.\n *\n * @param required blocks that always go along (style, follow-up marker)\n * @param optional blocks in order of importance (memory before the device list)\n */\nexport function composeInstructions(required: string[], optional: string[]): { text: string; dropped: number } {\n const blocks = [...required.filter(Boolean)];\n const extra = optional.filter(Boolean);\n let dropped = 0;\n while (extra.length) {\n const text = [...blocks, ...extra].join('\\n\\n');\n if (text.length <= PI_AGENT_MAX_INSTRUCTIONS) {\n return { text, dropped };\n }\n extra.pop();\n dropped++;\n }\n return { text: blocks.join('\\n\\n').slice(0, PI_AGENT_MAX_INSTRUCTIONS), dropped };\n}\n\n/** Conversation name for a request source; pi-agent uses \"/\" as separator in its keys. */\nexport function conversationOf(source: string): string {\n return (source || 'default').replace(/\\//g, '_').slice(0, 100);\n}\n\n/**\n * An answer as the TTS gets it: the assistant takes the control markers ([[LISTEN]] after a question to confirm,\n * [[DONE]]) out before speaking, so the language is kept under the text without them.\n */\nfunction answerKey(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** How many answers {@link PiAgentHarness.languageOf} remembers. */\nconst KEPT_LANGUAGES = 50;\n\nexport class PiAgentHarness {\n private seq = 0;\n /** Language pi-agent reported per answer text (pi-agent 0.10.1+), for the voice that speaks it. */\n private readonly languages = new Map<string, string>();\n\n public constructor(\n private readonly host: PiAgentHost,\n /** e.g. `pi-agent.0` */\n public readonly instance: string,\n private readonly timeoutMs: number = PI_AGENT_TIMEOUT_SEC * 1000,\n ) {}\n\n /**\n * Ask pi-agent. Fails fast when the instance is not running (otherwise the caller would wait for the whole\n * timeout), and turns pi-agent's `{error}` into an exception so the caller can fall back to the local model.\n */\n public async ask(req: PiAgentRequest): Promise<string> {\n const alive = await this.host.getForeignStateAsync(`system.adapter.${this.instance}.alive`);\n if (!alive?.val) {\n throw new Error(`${this.instance} is not running`);\n }\n // Unique per request: pi-agent answers a repeated requestId only once.\n const requestId = `assistant-${Date.now().toString(36)}-${(++this.seq).toString(36)}`;\n const result = (await this.host.sendToAsync(\n this.instance,\n 'ask',\n {\n text: req.text,\n conversation: conversationOf(req.conversation),\n instructions: req.instructions,\n ...(req.language ? { language: req.language } : {}),\n ...(req.images?.length ? { images: req.images } : {}),\n ...(req.satellite ? { satellite: req.satellite } : {}),\n ...(req.tts ? { tts: req.tts } : {}),\n requestId,\n },\n { timeout: this.timeoutMs },\n )) as { answer?: unknown; error?: unknown; language?: unknown } | null | undefined;\n if (result?.error) {\n const error = typeof result.error === 'string' ? result.error : JSON.stringify(result.error);\n throw new Error(`${this.instance}: ${error}`);\n }\n const answer = typeof result?.answer === 'string' ? result.answer.trim() : '';\n if (!answer) {\n throw new Error(`${this.instance} gave no answer`);\n }\n const language = typeof result?.language === 'string' ? result.language.trim().toLowerCase() : '';\n if (/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(language)) {\n const key = answerKey(answer);\n this.languages.delete(key);\n this.languages.set(key, language);\n if (this.languages.size > KEPT_LANGUAGES) {\n this.languages.delete(this.languages.keys().next().value as string);\n }\n }\n return answer;\n }\n\n /**\n * The language pi-agent wrote an answer in (`ru`, `de` …), '' when it did not say (older pi-agent, or the model\n * left its mark out). The answer travels as plain text through the tiers; this finds its language again by text.\n */\n public languageOf(answer: string): string {\n return this.languages.get(answerKey(answer)) || '';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"piAgent.js","sourceRoot":"","sources":["../../src/lib/piAgent.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;;AAkDH,kDAaC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AAC,CAAC,EAAE,CAAC;YACtD,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACpC,SAAS;SACZ,EACD,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,CAC9B,CAAiF,CAAC;QACnF,IAAI,MAAM,EAAE,KAAK,EAAE,CAAC;YAChB,MAAM,KAAK,GAAG,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC7F,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC,CAAC;QAClD,CAAC;QACD,MAAM,MAAM,GAAG,OAAO,MAAM,EAAE,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9E,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,QAAQ,iBAAiB,CAAC,CAAC;QACvD,CAAC;QACD,IAAI,OAAO,MAAM,EAAE,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACvC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;QACrD,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;IAED;;;OAGG;IACI,UAAU,CAAC,MAAc;QAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAC7C,CAAC;CACJ;AA3DD,wCA2DC","sourcesContent":["/**\n * The adapter `pi-agent` as the cloud tier (\"harness\"): instead of running its own tool loop, the assistant\n * hands the question to a pi-agent instance via `sendTo(<instance>, 'ask', …)`. pi-agent stores every model\n * and tool call as a checkpoint before it runs (an interrupted request continues after a restart, a write is\n * never repeated), enforces its own write permissions and confirmations, and can use the system-wide AI\n * settings of admin — none of which the built-in `LlmAgent` does.\n *\n * Each request source (satellite, `chat`, `telegram:<user>`) gets a conversation of its own in pi-agent\n * (`conversation`), so two rooms do not see each other's follow-ups. The source-independent part of the\n * prompt (style, follow-up marker, memory, device list) goes along as the `instructions` of that\n * conversation; what changes every turn (time, weather, presence) is prepended to the question.\n * pi-agent 0.3.0 and older ignore both fields and answer everything in their root conversation.\n *\n * With \"Confirmation by text in sendTo conversations\", pi-agent answers a write it may not do unasked with a\n * question ending in `[[LISTEN]]`, and the next `ask` of the conversation is the yes or no. `language` makes it\n * ask that question in the language the satellite listens in.\n *\n * pi-agent 0.10.1+ also answers with `language`, the language it wrote the answer in; the voice that speaks the\n * answer is chosen by it ({@link PiAgentHarness.languageOf}).\n */\n\nimport type { ImageInput } from './media';\nimport { AnswerLanguages } from './voice/speechLanguage';\n\n/** Longest instructions pi-agent accepts for a conversation; anything beyond is cut there. */\nexport const PI_AGENT_MAX_INSTRUCTIONS = 20000;\n\n/** Default for `piAgentTimeoutSec`: a tool loop with several reads can take a while. */\nexport const PI_AGENT_TIMEOUT_SEC = 60;\n\n/** The part of the adapter this module needs (kept small so tests can fake it). */\nexport interface PiAgentHost {\n sendToAsync(instance: string, command: string, message: unknown, options?: { timeout?: number }): Promise<unknown>;\n getForeignStateAsync(id: string): Promise<ioBroker.State | null | undefined>;\n}\n\nexport interface PiAgentRequest {\n /** The text pi-agent answers: context lines + the question. */\n text: string;\n /** Conversation of the caller, e.g. the satellite name. */\n conversation: string;\n /** Instructions of that conversation. */\n instructions: string;\n /**\n * Language the user speaks, e.g. `ru`. pi-agent asks its questions to confirm in it; older versions ask in the\n * system language, and a satellite listening in Russian does not hear a German \"Ja\" (the STT returns nothing).\n */\n language?: string;\n /**\n * Pictures that came with the question (`{ data: base64, mimeType }`, the form of pi-ai's `ImageContent`).\n * Versions of pi-agent before image support ignore them; the text then says that pictures came along.\n */\n images?: ImageInput[];\n /**\n * Only for a request from a voice satellite: its id under `assistant.N.satellites.*`, and the full id of its `tts`\n * state. Writing text there speaks it on that satellite — so pi-agent can answer later where it was asked (a\n * reminder, the end of a background task). Chat and Telegram requests have neither.\n */\n satellite?: string;\n tts?: string;\n}\n\n/**\n * Join instruction blocks, leaving out optional ones from the end until the result fits into pi-agent's\n * limit — pi-agent would cut the text in the middle, and a half device list is worse than none.\n *\n * @param required blocks that always go along (style, follow-up marker)\n * @param optional blocks in order of importance (memory before the device list)\n */\nexport function composeInstructions(required: string[], optional: string[]): { text: string; dropped: number } {\n const blocks = [...required.filter(Boolean)];\n const extra = optional.filter(Boolean);\n let dropped = 0;\n while (extra.length) {\n const text = [...blocks, ...extra].join('\\n\\n');\n if (text.length <= PI_AGENT_MAX_INSTRUCTIONS) {\n return { text, dropped };\n }\n extra.pop();\n dropped++;\n }\n return { text: blocks.join('\\n\\n').slice(0, PI_AGENT_MAX_INSTRUCTIONS), dropped };\n}\n\n/** Conversation name for a request source; pi-agent uses \"/\" as separator in its keys. */\nexport function conversationOf(source: string): string {\n return (source || 'default').replace(/\\//g, '_').slice(0, 100);\n}\n\nexport class PiAgentHarness {\n private seq = 0;\n /** Language pi-agent reported per answer text (pi-agent 0.10.1+), for the voice that speaks it. */\n private readonly languages = new AnswerLanguages();\n\n public constructor(\n private readonly host: PiAgentHost,\n /** e.g. `pi-agent.0` */\n public readonly instance: string,\n private readonly timeoutMs: number = PI_AGENT_TIMEOUT_SEC * 1000,\n ) {}\n\n /**\n * Ask pi-agent. Fails fast when the instance is not running (otherwise the caller would wait for the whole\n * timeout), and turns pi-agent's `{error}` into an exception so the caller can fall back to the local model.\n */\n public async ask(req: PiAgentRequest): Promise<string> {\n const alive = await this.host.getForeignStateAsync(`system.adapter.${this.instance}.alive`);\n if (!alive?.val) {\n throw new Error(`${this.instance} is not running`);\n }\n // Unique per request: pi-agent answers a repeated requestId only once.\n const requestId = `assistant-${Date.now().toString(36)}-${(++this.seq).toString(36)}`;\n const result = (await this.host.sendToAsync(\n this.instance,\n 'ask',\n {\n text: req.text,\n conversation: conversationOf(req.conversation),\n instructions: req.instructions,\n ...(req.language ? { language: req.language } : {}),\n ...(req.images?.length ? { images: req.images } : {}),\n ...(req.satellite ? { satellite: req.satellite } : {}),\n ...(req.tts ? { tts: req.tts } : {}),\n requestId,\n },\n { timeout: this.timeoutMs },\n )) as { answer?: unknown; error?: unknown; language?: unknown } | null | undefined;\n if (result?.error) {\n const error = typeof result.error === 'string' ? result.error : JSON.stringify(result.error);\n throw new Error(`${this.instance}: ${error}`);\n }\n const answer = typeof result?.answer === 'string' ? result.answer.trim() : '';\n if (!answer) {\n throw new Error(`${this.instance} gave no answer`);\n }\n if (typeof result?.language === 'string') {\n this.languages.remember(answer, result.language);\n }\n return answer;\n }\n\n /**\n * The language pi-agent wrote an answer in (`ru`, `de` …), '' when it did not say (older pi-agent, or the model\n * left its mark out). The answer travels as plain text through the tiers; this finds its language again by text.\n */\n public languageOf(answer: string): string {\n return this.languages.languageOf(answer);\n }\n}\n"]}
|
|
@@ -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 @@
|
|
|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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,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC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AAC","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"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.VoicePerLanguage = exports.LanguageTts = void 0;
|
|
3
|
+
exports.VoicePerLanguage = exports.LanguageTts = exports.AnswerLanguages = void 0;
|
|
4
4
|
exports.baseLanguage = baseLanguage;
|
|
5
5
|
exports.scriptLanguage = scriptLanguage;
|
|
6
6
|
exports.speechLanguage = speechLanguage;
|
|
7
|
+
exports.questionLanguage = questionLanguage;
|
|
7
8
|
exports.voiceFitsLanguage = voiceFitsLanguage;
|
|
8
9
|
exports.parseVoiceTable = parseVoiceTable;
|
|
9
10
|
/** Script of the languages that are not written in Latin letters; everything else is Latin. */
|
|
@@ -113,6 +114,94 @@ function speechLanguage(text, configured, reported) {
|
|
|
113
114
|
// Latin letters while the satellite speaks Russian: English is the best guess
|
|
114
115
|
return byLetters || 'en';
|
|
115
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* Words that say a Latin-script question is English or German. Only words of one of the two: "in", "an", "die",
|
|
119
|
+
* "was", "will", "so", "man" are both and say nothing. Kept to what short spoken commands and questions use.
|
|
120
|
+
*/
|
|
121
|
+
const FUNCTION_WORDS = {
|
|
122
|
+
en: new Set(("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 " +
|
|
123
|
+
'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +
|
|
124
|
+
'does do can could would there all up down timer alarm minutes hours at for be play stop').split(' ')),
|
|
125
|
+
de: new Set(('der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +
|
|
126
|
+
'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +
|
|
127
|
+
'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +
|
|
128
|
+
'kannst spiele spiel').split(' ')),
|
|
129
|
+
};
|
|
130
|
+
/** Function words of `lang` in the words of a text; 0 for a language without a list. */
|
|
131
|
+
function functionWords(words, lang) {
|
|
132
|
+
const list = FUNCTION_WORDS[lang];
|
|
133
|
+
return list ? words.filter(w => list.has(w)).length : 0;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The language a question is asked in, for the fixed answers of the rule NLU ("скажи, сколько сейчас времени" on a
|
|
137
|
+
* German satellite was answered in German). Another script than the configured language's tells it by the letters
|
|
138
|
+
* (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with
|
|
139
|
+
* at least two of them and more than twice as many as of the configured language, so a German command with an
|
|
140
|
+
* English device name stays German and a French question on a French system is not taken for German.
|
|
141
|
+
*
|
|
142
|
+
* @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it
|
|
143
|
+
*/
|
|
144
|
+
function questionLanguage(text, configured) {
|
|
145
|
+
const question = String(text || '');
|
|
146
|
+
const script = dominantScript(question);
|
|
147
|
+
if (!script) {
|
|
148
|
+
return configured;
|
|
149
|
+
}
|
|
150
|
+
if (script !== 'latin') {
|
|
151
|
+
return speechLanguage(question, configured);
|
|
152
|
+
}
|
|
153
|
+
const words = question.toLowerCase().match(/[\p{L}']+/gu) || [];
|
|
154
|
+
const base = baseLanguage(configured);
|
|
155
|
+
let best = '';
|
|
156
|
+
let most = 0;
|
|
157
|
+
for (const lang of ['en', 'de']) {
|
|
158
|
+
const hits = functionWords(words, lang);
|
|
159
|
+
if (hits > most) {
|
|
160
|
+
best = lang;
|
|
161
|
+
most = hits;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {
|
|
165
|
+
return configured;
|
|
166
|
+
}
|
|
167
|
+
return best;
|
|
168
|
+
}
|
|
169
|
+
/** How many answers {@link AnswerLanguages} remembers. */
|
|
170
|
+
const KEPT_LANGUAGES = 50;
|
|
171
|
+
/**
|
|
172
|
+
* The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to
|
|
173
|
+
* the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):
|
|
174
|
+
* the assistant takes them out before speaking.
|
|
175
|
+
*/
|
|
176
|
+
class AnswerLanguages {
|
|
177
|
+
byText = new Map();
|
|
178
|
+
static key(text) {
|
|
179
|
+
return String(text || '')
|
|
180
|
+
.replace(/\[\[[A-Z]+\]\]/gi, ' ')
|
|
181
|
+
.replace(/\s+/g, ' ')
|
|
182
|
+
.trim();
|
|
183
|
+
}
|
|
184
|
+
/** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */
|
|
185
|
+
remember(text, language) {
|
|
186
|
+
const lang = String(language || '')
|
|
187
|
+
.trim()
|
|
188
|
+
.toLowerCase();
|
|
189
|
+
const key = AnswerLanguages.key(text);
|
|
190
|
+
if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
this.byText.delete(key);
|
|
194
|
+
this.byText.set(key, lang);
|
|
195
|
+
if (this.byText.size > KEPT_LANGUAGES) {
|
|
196
|
+
this.byText.delete(this.byText.keys().next().value);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** The language remembered for this answer, '' for none. */
|
|
200
|
+
languageOf(text) {
|
|
201
|
+
return this.byText.get(AnswerLanguages.key(text)) || '';
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
exports.AnswerLanguages = AnswerLanguages;
|
|
116
205
|
/**
|
|
117
206
|
* Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,
|
|
118
207
|
* `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a
|
|
@@ -126,7 +215,7 @@ function voiceFitsLanguage(voice, lang) {
|
|
|
126
215
|
}
|
|
127
216
|
return locale[1] === iso;
|
|
128
217
|
}
|
|
129
|
-
/** 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. */
|
|
130
219
|
function parseVoiceTable(rows) {
|
|
131
220
|
const table = {};
|
|
132
221
|
if (!Array.isArray(rows)) {
|
|
@@ -135,8 +224,9 @@ function parseVoiceTable(rows) {
|
|
|
135
224
|
for (const row of rows) {
|
|
136
225
|
const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');
|
|
137
226
|
const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';
|
|
138
|
-
|
|
139
|
-
|
|
227
|
+
const model = typeof row?.model === 'string' ? row.model.trim() : '';
|
|
228
|
+
if (lang && (voice || model)) {
|
|
229
|
+
table[lang] = { voice, model };
|
|
140
230
|
}
|
|
141
231
|
}
|
|
142
232
|
return table;
|