iobroker.assistant 1.7.0 → 1.8.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 +4 -0
- package/build/lib/piAgent.js +5 -22
- package/build/lib/piAgent.js.map +1 -1
- package/build/lib/voice/speechLanguage.js +90 -1
- package/build/lib/voice/speechLanguage.js.map +1 -1
- package/build/main.js +40 -19
- package/build/main.js.map +1 -1
- package/io-package.json +58 -16
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -237,6 +237,10 @@ train it twice.
|
|
|
237
237
|
Placeholder for the next version (at the beginning of the line):
|
|
238
238
|
### **WORK IN PROGRESS**
|
|
239
239
|
-->
|
|
240
|
+
### 1.8.0 (2026-11-13)
|
|
241
|
+
* (@GermanBluefox) Added the short form of the web component manifests (tag, name, icon, size) to `common.webComponents`, so that hosts like Aura can list the components before the adapter is installed; the build writes it with `iob-web-components sync-io-package`
|
|
242
|
+
* (@GermanBluefox) The built-in answers (time, devices, timers, weather …) come in the language the question was asked in, not always in the voice language: "скажи, сколько сейчас времени" on a German satellite is answered in Russian, "what time is it" in English and with an English voice
|
|
243
|
+
|
|
240
244
|
### 1.7.0 (2026-11-12)
|
|
241
245
|
* (@sadam6752-tech) A Piper voice set for one language is only used for it, a Russian answer on a German satellite gets a Russian voice instead of being spelled letter by letter; the language pi-agent 0.10.1 reports for an answer is used for its voice (#27)
|
|
242
246
|
* (@GermanBluefox) The language of an answer is taken for every voice: UDP and Wyoming satellites, announcements and the voice test too, and Azure, AWS and OpenRouter voices set for one language are only used for it. New table "Voice per answer language" in the Voice tab (e.g. ru → ru_RU-dmitri-medium); Piper loads its voices at the start. The language pi-agent reports is also found for its questions to confirm, and a mark that the letters contradict is not believed
|
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,I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C;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;AAGD,wCAEC;AAjED,2DAAyD;AAEzD,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,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,iCAAyB,CAAC,EAAE,OAAO,EAAE,CAAC;AACtF,CAAC;AAED,0FAA0F;AAC1F,SAAgB,cAAc,CAAC,MAAc;IACzC,OAAO,CAAC,MAAM,IAAI,SAAS,CAAC,C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rD,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"]}
|
|
@@ -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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AAuDA,oCAKC;AA0BD,wCAkBC;AAUD,wCAkBC;AAOD,8CAOC;AAGD,0CAaC;AAhJD,+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,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C,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvD,CAAC;IAED,cAAc,CAAC,IAAY,EAAE,IAAY;QACrC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;QACpC,OAAO,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACrG,CAAC;IAED,sGAAsG;IACtG,KAAK,CAAC,OAAO,CAAC,IAAY;QACtB,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;QAC3C,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAC3D,IAAI,IAAI,KAAK,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC9B,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 * 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;AAGD,0CAaC;AAvPD,+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,QAAQ;IACZ,EAAE,EAAE,QAAQ;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O,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"]}
|
package/build/main.js
CHANGED
|
@@ -3423,9 +3423,12 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3423
3423
|
attachments() {
|
|
3424
3424
|
return this.requestOrigin.getStore()?.attachments ?? NO_ATTACHMENTS;
|
|
3425
3425
|
}
|
|
3426
|
-
/**
|
|
3426
|
+
/**
|
|
3427
|
+
* Language of fixed replies: the language the request being answered was asked in, else the voice language, else
|
|
3428
|
+
* the system language.
|
|
3429
|
+
*/
|
|
3427
3430
|
answerLanguage() {
|
|
3428
|
-
return String(this.config.voiceLanguage || this.language || 'en');
|
|
3431
|
+
return this.requestOrigin.getStore()?.language || String(this.config.voiceLanguage || this.language || 'en');
|
|
3429
3432
|
}
|
|
3430
3433
|
/**
|
|
3431
3434
|
* Speech recognition for an `ask` that carries a recording instead of text. `audio` is base64; `format` says what
|
|
@@ -3490,10 +3493,19 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3490
3493
|
const satellite = fromSatellite ? this.knownSatelliteId(origin.satellite || source, origin.room || '') : '';
|
|
3491
3494
|
// The journal shows "[picture] What is in this picture?", like the conversation history
|
|
3492
3495
|
const shown = (0, media_1.historyText)(question, attachments.images.length, !!attachments.video);
|
|
3493
|
-
|
|
3496
|
+
const configured = String(this.config.voiceLanguage || this.language || 'en');
|
|
3497
|
+
// "скажи, сколько сейчас времени" on a German satellite: the time comes in Russian
|
|
3498
|
+
const language = (0, speechLanguage_1.questionLanguage)(question, configured);
|
|
3499
|
+
return this.requestOrigin.run({ source, room: origin.room || '', voice, satellite, attachments, language }, () => this.journal
|
|
3494
3500
|
? this.journal.run(shown, source, origin, () => {
|
|
3495
3501
|
this.traceSpeechInput(question, origin);
|
|
3496
3502
|
this.traceAttachments(attachments);
|
|
3503
|
+
if (language !== configured) {
|
|
3504
|
+
this.journal?.step({
|
|
3505
|
+
stage: 'request',
|
|
3506
|
+
title: `Question in '${language}', not '${configured}': fixed answers in '${language}'`,
|
|
3507
|
+
});
|
|
3508
|
+
}
|
|
3497
3509
|
return this.answerTracked(question, source);
|
|
3498
3510
|
})
|
|
3499
3511
|
: this.answerTracked(question, source));
|
|
@@ -3577,6 +3589,13 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3577
3589
|
result = this.doneText();
|
|
3578
3590
|
}
|
|
3579
3591
|
}
|
|
3592
|
+
// An answer to a question in another language than the satellite's: its voice is told by this (an English
|
|
3593
|
+
// answer on a German satellite has the same letters, see LanguageTts)
|
|
3594
|
+
const language = this.answerLanguage();
|
|
3595
|
+
if (result &&
|
|
3596
|
+
(0, speechLanguage_1.baseLanguage)(language) !== (0, speechLanguage_1.baseLanguage)(String(this.config.voiceLanguage || this.language || 'en'))) {
|
|
3597
|
+
this.answerLanguages.remember(result, language);
|
|
3598
|
+
}
|
|
3580
3599
|
this.journal?.step({
|
|
3581
3600
|
stage: 'answer',
|
|
3582
3601
|
title: toned
|
|
@@ -3634,11 +3653,11 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3634
3653
|
return '';
|
|
3635
3654
|
}
|
|
3636
3655
|
const limit = (0, ttsCache_1.parseTtsMaxChars)(this.config.ttsMaxChars) ?? ttsCache_1.MAX_TTS_CHARS;
|
|
3637
|
-
return (0, ttsCache_1.spokenLengthHint)(limit,
|
|
3656
|
+
return (0, ttsCache_1.spokenLengthHint)(limit, this.answerLanguage());
|
|
3638
3657
|
}
|
|
3639
3658
|
/** What [[DONE]] says where no beep can be played */
|
|
3640
3659
|
doneText() {
|
|
3641
|
-
const lang =
|
|
3660
|
+
const lang = this.answerLanguage();
|
|
3642
3661
|
return lang === 'ru' ? 'Готово.' : lang === 'de' ? 'Erledigt.' : 'Done.';
|
|
3643
3662
|
}
|
|
3644
3663
|
/** Per source: whether its last {@link answer} asked the user something (LLM-signalled via [[LISTEN]]). */
|
|
@@ -3648,8 +3667,10 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3648
3667
|
* transports hand the TTS only the text, so the TTS looks the language up by it.
|
|
3649
3668
|
*/
|
|
3650
3669
|
reportedLanguage(text) {
|
|
3651
|
-
return this.piAgent?.languageOf(text) || undefined;
|
|
3670
|
+
return this.piAgent?.languageOf(text) || this.answerLanguages.languageOf(text) || undefined;
|
|
3652
3671
|
}
|
|
3672
|
+
/** Answers given in the language of a question other than the configured one (see {@link answerTracked}). */
|
|
3673
|
+
answerLanguages = new speechLanguage_1.AnswerLanguages();
|
|
3653
3674
|
/** Per source: when the cloud model last asked back about a script (see {@link cloudOnlyReason}). */
|
|
3654
3675
|
scriptTopics = new Map();
|
|
3655
3676
|
/**
|
|
@@ -3745,7 +3766,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3745
3766
|
* LLM. Localized (de/en/ru) spoken-style reply; uses the host's local timezone via {@link Intl}.
|
|
3746
3767
|
*/
|
|
3747
3768
|
executeTimeIntent(intent) {
|
|
3748
|
-
const lang =
|
|
3769
|
+
const lang = this.answerLanguage();
|
|
3749
3770
|
const locale = lang === 'de' ? 'de-DE' : lang === 'ru' ? 'ru-RU' : 'en-GB';
|
|
3750
3771
|
const now = new Date();
|
|
3751
3772
|
if (intent.action === 'dateQuery') {
|
|
@@ -3844,7 +3865,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
3844
3865
|
this.log.info(`Ring stopped by voice (${n} session(s)).`);
|
|
3845
3866
|
this.journal?.note({ tier: 'stop' });
|
|
3846
3867
|
this.journal?.step({ stage: 'stop', title: `Stop word: silenced ${n} ringing timer/alarm(s)` });
|
|
3847
|
-
const lang =
|
|
3868
|
+
const lang = this.answerLanguage();
|
|
3848
3869
|
return lang === 'ru' ? 'Хорошо.' : lang === 'de' ? 'Ok.' : 'Okay.';
|
|
3849
3870
|
}
|
|
3850
3871
|
// An open question from `askUser` claims the next utterance of that source as its answer — before
|
|
@@ -4133,7 +4154,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
4133
4154
|
}
|
|
4134
4155
|
/** Reply when nothing local understood the request and there is no cloud LLM (provider "none"). */
|
|
4135
4156
|
localOnlyFallback() {
|
|
4136
|
-
const lang =
|
|
4157
|
+
const lang = this.answerLanguage();
|
|
4137
4158
|
if (lang === 'ru') {
|
|
4138
4159
|
return 'Извини, этого я не поняла. Без облачной языковой модели я понимаю только простые команды для устройств, таймеры и будильники.';
|
|
4139
4160
|
}
|
|
@@ -4895,7 +4916,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
4895
4916
|
if (!device || !intent.stateId) {
|
|
4896
4917
|
throw new Error('deferred intent without a device');
|
|
4897
4918
|
}
|
|
4898
|
-
const lang =
|
|
4919
|
+
const lang = this.answerLanguage();
|
|
4899
4920
|
const pick = (rus, ger, eng) => lang === 'ru' ? rus : lang === 'de' ? ger : eng;
|
|
4900
4921
|
const room = intent.room || device.room;
|
|
4901
4922
|
const where = room ? ` (${room})` : '';
|
|
@@ -5059,7 +5080,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5059
5080
|
if (!res.report) {
|
|
5060
5081
|
throw new Error(res.error || 'no weather report');
|
|
5061
5082
|
}
|
|
5062
|
-
const lang =
|
|
5083
|
+
const lang = this.answerLanguage();
|
|
5063
5084
|
const text = (0, weather_1.buildWeatherAnswer)(res.report, lang, intent.when);
|
|
5064
5085
|
if (!text) {
|
|
5065
5086
|
throw new Error(`the weather report has no data for '${intent.when || 'now'}'`);
|
|
@@ -5072,7 +5093,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5072
5093
|
* of an ESPHome device, the `volume` message of a UDP satellite.
|
|
5073
5094
|
*/
|
|
5074
5095
|
async executeVolumeIntent(intent, source) {
|
|
5075
|
-
const lang =
|
|
5096
|
+
const lang = this.answerLanguage();
|
|
5076
5097
|
const satId = intent.room ? this.resolveSatelliteId(intent.room) : this.announceTargetForSource(source);
|
|
5077
5098
|
const absolute = typeof intent.value === 'number' ? intent.value : null;
|
|
5078
5099
|
const delta = intent.delta || 0;
|
|
@@ -5135,7 +5156,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5135
5156
|
}
|
|
5136
5157
|
/** Localized "this part did not work" sentence for a failed part of a combined command. */
|
|
5137
5158
|
nluFailureText(intent) {
|
|
5138
|
-
const lang =
|
|
5159
|
+
const lang = this.answerLanguage();
|
|
5139
5160
|
const what = intent.device?.name ? ` (${intent.device.name})` : '';
|
|
5140
5161
|
return lang === 'ru'
|
|
5141
5162
|
? `Одну команду${what} выполнить не удалось.`
|
|
@@ -5329,7 +5350,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5329
5350
|
return '';
|
|
5330
5351
|
}
|
|
5331
5352
|
// Respond in the assistant's interaction language (voice language, else system).
|
|
5332
|
-
const lang =
|
|
5353
|
+
const lang = this.answerLanguage();
|
|
5333
5354
|
const ru = lang === 'ru';
|
|
5334
5355
|
const de = lang === 'de';
|
|
5335
5356
|
const pick = (rus, ger, eng) => (ru ? rus : de ? ger : eng);
|
|
@@ -5398,7 +5419,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5398
5419
|
if (!mcp) {
|
|
5399
5420
|
throw new Error('mcp not ready');
|
|
5400
5421
|
}
|
|
5401
|
-
const lang =
|
|
5422
|
+
const lang = this.answerLanguage();
|
|
5402
5423
|
const ru = lang === 'ru';
|
|
5403
5424
|
const de = lang === 'de';
|
|
5404
5425
|
const pick = (rus, ger, eng) => (ru ? rus : de ? ger : eng);
|
|
@@ -5445,7 +5466,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5445
5466
|
if (!mcp) {
|
|
5446
5467
|
throw new Error('mcp not ready');
|
|
5447
5468
|
}
|
|
5448
|
-
const lang =
|
|
5469
|
+
const lang = this.answerLanguage();
|
|
5449
5470
|
const ru = lang === 'ru';
|
|
5450
5471
|
const de = lang === 'de';
|
|
5451
5472
|
const pick = (rus, ger, eng) => (ru ? rus : de ? ger : eng);
|
|
@@ -5908,7 +5929,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
5908
5929
|
if (!mgr) {
|
|
5909
5930
|
return '';
|
|
5910
5931
|
}
|
|
5911
|
-
const lang =
|
|
5932
|
+
const lang = this.answerLanguage();
|
|
5912
5933
|
const ru = lang === 'ru';
|
|
5913
5934
|
const de = lang === 'de';
|
|
5914
5935
|
const pick = (rus, ger, eng) => (ru ? rus : de ? ger : eng);
|
|
@@ -6177,7 +6198,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
6177
6198
|
if (!mgr) {
|
|
6178
6199
|
return '';
|
|
6179
6200
|
}
|
|
6180
|
-
const lang =
|
|
6201
|
+
const lang = this.answerLanguage();
|
|
6181
6202
|
const ru = lang === 'ru';
|
|
6182
6203
|
const de = lang === 'de';
|
|
6183
6204
|
const pick = (rus, ger, eng) => (ru ? rus : de ? ger : eng);
|
|
@@ -6440,7 +6461,7 @@ class Assistant extends adapter_core_1.Adapter {
|
|
|
6440
6461
|
* hear me". An already running TV is answered only after the player acknowledged the command.
|
|
6441
6462
|
*/
|
|
6442
6463
|
async playYouTube(query, kind, playerName) {
|
|
6443
|
-
const lang =
|
|
6464
|
+
const lang = this.answerLanguage();
|
|
6444
6465
|
const player = this.youtubePlayerFor(playerName);
|
|
6445
6466
|
if (!player) {
|
|
6446
6467
|
const names = this.youtubePlayers.map(p => p.name).join(', ');
|