iobroker.assistant 1.15.2 → 1.16.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.
Files changed (41) hide show
  1. package/README.md +4 -4
  2. package/admin/i18n/de.json +5 -1
  3. package/admin/i18n/en.json +5 -1
  4. package/admin/i18n/es.json +5 -1
  5. package/admin/i18n/fr.json +5 -1
  6. package/admin/i18n/it.json +5 -1
  7. package/admin/i18n/nl.json +5 -1
  8. package/admin/i18n/pl.json +5 -1
  9. package/admin/i18n/pt.json +5 -1
  10. package/admin/i18n/ru.json +5 -1
  11. package/admin/i18n/uk.json +5 -1
  12. package/admin/i18n/zh-cn.json +5 -1
  13. package/admin/jsonConfig.json +15 -3
  14. package/build/lib/music.js +7 -2
  15. package/build/lib/music.js.map +1 -1
  16. package/build/lib/quick.js +1 -1
  17. package/build/lib/quick.js.map +1 -1
  18. package/build/lib/voice/aws.js +33 -3
  19. package/build/lib/voice/aws.js.map +1 -1
  20. package/build/lib/voice/azure.js +34 -0
  21. package/build/lib/voice/azure.js.map +1 -1
  22. package/build/lib/voice/fallback.js +4 -0
  23. package/build/lib/voice/fallback.js.map +1 -1
  24. package/build/lib/voice/openrouter.js +4 -0
  25. package/build/lib/voice/openrouter.js.map +1 -1
  26. package/build/lib/voice/piper.js +4 -0
  27. package/build/lib/voice/piper.js.map +1 -1
  28. package/build/lib/voice/speechLanguage.js +87 -0
  29. package/build/lib/voice/speechLanguage.js.map +1 -1
  30. package/build/lib/voice/tts.js +4 -0
  31. package/build/lib/voice/tts.js.map +1 -1
  32. package/build/lib/voice/ttsCache.js +3 -0
  33. package/build/lib/voice/ttsCache.js.map +1 -1
  34. package/build/lib/voice/voiceGender.js +186 -0
  35. package/build/lib/voice/voiceGender.js.map +1 -0
  36. package/build/lib/youtube.js +1 -1
  37. package/build/lib/youtube.js.map +1 -1
  38. package/build/main.js +102 -9
  39. package/build/main.js.map +1 -1
  40. package/io-package.json +14 -14
  41. package/package.json +1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AC;oBACJ,MAAM,CAAC,IAAI,KAAK,CAAC,0BAA0B,IAAI,EAAE,CAAC,CAAC,CAAC;gBACxD,CAAC;YACL,CAAC,CAAC,CAAC;YACH,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAlGD,4BAkGC;AAED,8FAA8F;AAC9F,SAAgB,eAAe;IAC3B,OAAO,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * Local TTS via Piper (https://github.com/rhasspy/piper). The binary + a voice model are downloaded\n * into the instance data dir on first use, then `piper --output_raw` is spawned to synthesise 16-bit\n * PCM. No cloud, no API key.\n *\n * ⚠️ Binary/voice download + spawn are platform-specific — validate on the target device.\n */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { downloadFile, extractArchive, type VoiceLogger } from './download';\nimport type { TtsEngine, TtsResult } from './tts';\n\nconst PIPER_RELEASE = 'https://github.com/rhasspy/piper/releases/download/2023.11.14-2';\n\n/** Release asset for the current platform/arch. */\nfunction piperAsset(): string {\n const p = process.platform;\n const a = process.arch;\n if (p === 'linux') {\n if (a === 'arm64') {\n return 'piper_linux_aarch64.tar.gz';\n }\n if (a === 'arm') {\n return 'piper_linux_armv7l.tar.gz';\n }\n return 'piper_linux_x86_64.tar.gz';\n }\n if (p === 'darwin') {\n return a === 'arm64' ? 'piper_macos_aarch64.tar.gz' : 'piper_macos_x64.tar.gz';\n }\n if (p === 'win32') {\n return 'piper_windows_amd64.zip';\n }\n throw new Error(`Piper: unsupported platform ${p}/${a}`);\n}\n\n/** Reasonable default Piper voice per language (rhasspy/piper-voices). */\nconst DEFAULT_VOICE: Record<string, string> = {\n de: 'de_DE-thorsten-medium',\n en: 'en_US-lessac-medium',\n ru: 'ru_RU-irina-medium',\n fr: 'fr_FR-siwis-medium',\n it: 'it_IT-riccardo-x_low',\n es: 'es_ES-sharvard-medium',\n nl: 'nl_NL-mls-medium',\n pl: 'pl_PL-darkman-medium',\n pt: 'pt_PT-tugão-medium',\n uk: 'uk_UA-ukrainian_tts-medium',\n zh: 'zh_CN-huayan-medium',\n};\n\n/** Build the two voice-file URLs (.onnx + .onnx.json) from a voice name like `de_DE-thorsten-medium`. */\nfunction voiceUrls(voice: string): { onnx: string; json: string } {\n // name = <locale>-<speaker>-<quality>; path = <lang>/<locale>/<speaker>/<quality>/<name>.onnx\n const [locale, speaker, quality] = voice.split('-');\n const lang = locale.split('_')[0].toLowerCase();\n const base = `https://huggingface.co/rhasspy/piper-voices/resolve/main/${lang}/${locale}/${speaker}/${quality}/${voice}`;\n return { onnx: `${base}.onnx`, json: `${base}.onnx.json` };\n}\n\nexport class PiperTts implements TtsEngine {\n private binaryPath = '';\n private ready: Promise<void> | null = null;\n\n constructor(\n private readonly dataDir: string,\n /** Voice name (e.g. de_DE-thorsten-medium); '' → default per language. */\n private readonly voice: string,\n private readonly log: VoiceLogger,\n ) {}\n\n /** Download + unpack the binary once; concurrent calls share one init. */\n private ensure(): Promise<void> {\n if (!this.ready) {\n this.ready = this.doEnsure().catch(e => {\n this.ready = null; // allow a retry on the next call\n throw e;\n });\n }\n return this.ready;\n }\n\n private async doEnsure(): Promise<void> {\n // 1. binary\n const piperDir = path.join(this.dataDir, 'piper');\n const exe = path.join(piperDir, 'piper', process.platform === 'win32' ? 'piper.exe' : 'piper');\n if (!fs.existsSync(exe)) {\n const asset = piperAsset();\n const archive = path.join(piperDir, asset);\n await downloadFile(`${PIPER_RELEASE}/${asset}`, archive, this.log);\n await extractArchive(archive, piperDir, this.log);\n if (process.platform !== 'win32') {\n try {\n fs.chmodSync(exe, 0o755);\n } catch {\n /* best effort */\n }\n }\n }\n this.binaryPath = exe;\n }\n\n private voiceFor(lang: string): string {\n const iso = (lang || 'en').split('-')[0].toLowerCase();\n // The chosen voice speaks one language (de_DE-thorsten-medium: German). An answer in another language gets\n // the default voice of that language; a German voice would spell Cyrillic letters one by one.\n if (this.voice && this.voice.split('_')[0].toLowerCase() === iso) {\n return this.voice;\n }\n return DEFAULT_VOICE[iso] || this.voice || DEFAULT_VOICE.en;\n }\n\n private async ensureVoice(voice: string): Promise<{ onnx: string; sampleRate: number }> {\n const dir = path.join(this.dataDir, 'piper-voices');\n const onnx = path.join(dir, `${voice}.onnx`);\n const json = path.join(dir, `${voice}.onnx.json`);\n const urls = voiceUrls(voice);\n await downloadFile(urls.onnx, onnx, this.log);\n await downloadFile(urls.json, json, this.log);\n let sampleRate = 22050;\n try {\n const cfg = JSON.parse(fs.readFileSync(json, 'utf8')) as { audio?: { sample_rate?: number } };\n sampleRate = cfg.audio?.sample_rate || 22050;\n } catch {\n /* keep default */\n }\n return { onnx, sampleRate };\n }\n\n /** Warm-up: download the Piper binary + the voice for `lang` so the first command isn't slow. */\n async prepare(lang: string): Promise<void> {\n await this.ensure();\n await this.ensureVoice(this.voiceFor(lang));\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n await this.ensure();\n const voice = this.voiceFor(lang);\n const { onnx, sampleRate } = await this.ensureVoice(voice);\n\n return new Promise<TtsResult>((resolve, reject) => {\n const child = spawn(this.binaryPath, ['--model', onnx, '--output_raw'], {\n cwd: path.dirname(this.binaryPath), // finds bundled espeak-ng-data / libs\n });\n const chunks: Buffer[] = [];\n child.stdout.on('data', (d: Buffer) => chunks.push(d));\n child.stderr.on('data', (d: Buffer) => this.log.debug(`piper: ${String(d).trim()}`));\n child.on('error', e => reject(new Error(`piper failed: ${e.message}`)));\n child.on('close', code => {\n if (code === 0) {\n resolve({ pcm: Buffer.concat(chunks), sampleRate });\n } else {\n reject(new Error(`piper exited with code ${code}`));\n }\n });\n child.stdin.end(text);\n });\n }\n}\n\n/** Voices offered in the settings dropdown for Piper (the built-in per-language defaults). */\nexport function listPiperVoices(): string[] {\n return Object.values(DEFAULT_VOICE);\n}\n"]}
1
+ {"version":3,"file":"piper.js","sourceRoot":"","sources":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b,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;gBACxD,CAAC;qBAAM,CAAC;oBACJ,MAAM,CAAC,IAAI,KAAK,CAAC,0BAA0B,IAAI,EAAE,CAAC,CAAC,CAAC;gBACxD,CAAC;YACL,CAAC,CAAC,CAAC;YACH,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAtGD,4BAsGC;AAED,8FAA8F;AAC9F,SAAgB,eAAe;IAC3B,OAAO,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * Local TTS via Piper (https://github.com/rhasspy/piper). The binary + a voice model are downloaded\n * into the instance data dir on first use, then `piper --output_raw` is spawned to synthesise 16-bit\n * PCM. No cloud, no API key.\n *\n * ⚠️ Binary/voice download + spawn are platform-specific — validate on the target device.\n */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { downloadFile, extractArchive, type VoiceLogger } from './download';\nimport type { TtsEngine, TtsResult } from './tts';\nimport { knownVoiceGender, type VoiceGender } from './voiceGender';\n\nconst PIPER_RELEASE = 'https://github.com/rhasspy/piper/releases/download/2023.11.14-2';\n\n/** Release asset for the current platform/arch. */\nfunction piperAsset(): string {\n const p = process.platform;\n const a = process.arch;\n if (p === 'linux') {\n if (a === 'arm64') {\n return 'piper_linux_aarch64.tar.gz';\n }\n if (a === 'arm') {\n return 'piper_linux_armv7l.tar.gz';\n }\n return 'piper_linux_x86_64.tar.gz';\n }\n if (p === 'darwin') {\n return a === 'arm64' ? 'piper_macos_aarch64.tar.gz' : 'piper_macos_x64.tar.gz';\n }\n if (p === 'win32') {\n return 'piper_windows_amd64.zip';\n }\n throw new Error(`Piper: unsupported platform ${p}/${a}`);\n}\n\n/** Reasonable default Piper voice per language (rhasspy/piper-voices). */\nconst DEFAULT_VOICE: Record<string, string> = {\n de: 'de_DE-thorsten-medium',\n en: 'en_US-lessac-medium',\n ru: 'ru_RU-irina-medium',\n fr: 'fr_FR-siwis-medium',\n it: 'it_IT-riccardo-x_low',\n es: 'es_ES-sharvard-medium',\n nl: 'nl_NL-mls-medium',\n pl: 'pl_PL-darkman-medium',\n pt: 'pt_PT-tugão-medium',\n uk: 'uk_UA-ukrainian_tts-medium',\n zh: 'zh_CN-huayan-medium',\n};\n\n/** Build the two voice-file URLs (.onnx + .onnx.json) from a voice name like `de_DE-thorsten-medium`. */\nfunction voiceUrls(voice: string): { onnx: string; json: string } {\n // name = <locale>-<speaker>-<quality>; path = <lang>/<locale>/<speaker>/<quality>/<name>.onnx\n const [locale, speaker, quality] = voice.split('-');\n const lang = locale.split('_')[0].toLowerCase();\n const base = `https://huggingface.co/rhasspy/piper-voices/resolve/main/${lang}/${locale}/${speaker}/${quality}/${voice}`;\n return { onnx: `${base}.onnx`, json: `${base}.onnx.json` };\n}\n\nexport class PiperTts implements TtsEngine {\n private binaryPath = '';\n private ready: Promise<void> | null = null;\n\n constructor(\n private readonly dataDir: string,\n /** Voice name (e.g. de_DE-thorsten-medium); '' → default per language. */\n private readonly voice: string,\n private readonly log: VoiceLogger,\n ) {}\n\n voiceGender(lang: string): Promise<VoiceGender | ''> {\n return Promise.resolve(knownVoiceGender('piper', this.voiceFor(lang)));\n }\n\n /** Download + unpack the binary once; concurrent calls share one init. */\n private ensure(): Promise<void> {\n if (!this.ready) {\n this.ready = this.doEnsure().catch(e => {\n this.ready = null; // allow a retry on the next call\n throw e;\n });\n }\n return this.ready;\n }\n\n private async doEnsure(): Promise<void> {\n // 1. binary\n const piperDir = path.join(this.dataDir, 'piper');\n const exe = path.join(piperDir, 'piper', process.platform === 'win32' ? 'piper.exe' : 'piper');\n if (!fs.existsSync(exe)) {\n const asset = piperAsset();\n const archive = path.join(piperDir, asset);\n await downloadFile(`${PIPER_RELEASE}/${asset}`, archive, this.log);\n await extractArchive(archive, piperDir, this.log);\n if (process.platform !== 'win32') {\n try {\n fs.chmodSync(exe, 0o755);\n } catch {\n /* best effort */\n }\n }\n }\n this.binaryPath = exe;\n }\n\n private voiceFor(lang: string): string {\n const iso = (lang || 'en').split('-')[0].toLowerCase();\n // The chosen voice speaks one language (de_DE-thorsten-medium: German). An answer in another language gets\n // the default voice of that language; a German voice would spell Cyrillic letters one by one.\n if (this.voice && this.voice.split('_')[0].toLowerCase() === iso) {\n return this.voice;\n }\n return DEFAULT_VOICE[iso] || this.voice || DEFAULT_VOICE.en;\n }\n\n private async ensureVoice(voice: string): Promise<{ onnx: string; sampleRate: number }> {\n const dir = path.join(this.dataDir, 'piper-voices');\n const onnx = path.join(dir, `${voice}.onnx`);\n const json = path.join(dir, `${voice}.onnx.json`);\n const urls = voiceUrls(voice);\n await downloadFile(urls.onnx, onnx, this.log);\n await downloadFile(urls.json, json, this.log);\n let sampleRate = 22050;\n try {\n const cfg = JSON.parse(fs.readFileSync(json, 'utf8')) as { audio?: { sample_rate?: number } };\n sampleRate = cfg.audio?.sample_rate || 22050;\n } catch {\n /* keep default */\n }\n return { onnx, sampleRate };\n }\n\n /** Warm-up: download the Piper binary + the voice for `lang` so the first command isn't slow. */\n async prepare(lang: string): Promise<void> {\n await this.ensure();\n await this.ensureVoice(this.voiceFor(lang));\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n await this.ensure();\n const voice = this.voiceFor(lang);\n const { onnx, sampleRate } = await this.ensureVoice(voice);\n\n return new Promise<TtsResult>((resolve, reject) => {\n const child = spawn(this.binaryPath, ['--model', onnx, '--output_raw'], {\n cwd: path.dirname(this.binaryPath), // finds bundled espeak-ng-data / libs\n });\n const chunks: Buffer[] = [];\n child.stdout.on('data', (d: Buffer) => chunks.push(d));\n child.stderr.on('data', (d: Buffer) => this.log.debug(`piper: ${String(d).trim()}`));\n child.on('error', e => reject(new Error(`piper failed: ${e.message}`)));\n child.on('close', code => {\n if (code === 0) {\n resolve({ pcm: Buffer.concat(chunks), sampleRate });\n } else {\n reject(new Error(`piper exited with code ${code}`));\n }\n });\n child.stdin.end(text);\n });\n }\n}\n\n/** Voices offered in the settings dropdown for Piper (the built-in per-language defaults). */\nexport function listPiperVoices(): string[] {\n return Object.values(DEFAULT_VOICE);\n}\n"]}
@@ -10,6 +10,9 @@ exports.voiceFitsLanguage = voiceFitsLanguage;
10
10
  exports.cellLanguage = cellLanguage;
11
11
  exports.normalizeVoiceTable = normalizeVoiceTable;
12
12
  exports.parseVoiceTable = parseVoiceTable;
13
+ exports.cellGender = cellGender;
14
+ exports.parseVoiceGenders = parseVoiceGenders;
15
+ exports.voiceGenderHint = voiceGenderHint;
13
16
  /** Script of the languages that are not written in Latin letters; everything else is Latin. */
14
17
  const SCRIPT_OF = {
15
18
  ru: 'cyrillic',
@@ -315,6 +318,84 @@ function parseVoiceTable(rows) {
315
318
  }
316
319
  return table;
317
320
  }
321
+ /** The gender in a table cell, '' for none. */
322
+ function cellGender(value) {
323
+ const gender = typeof value === 'string' ? value.trim().toLowerCase() : '';
324
+ return gender === 'female' || gender === 'male' ? gender : '';
325
+ }
326
+ /**
327
+ * Parse the column "gender" of the table "voice per language" into ISO code → gender. A row needs no voice for it:
328
+ * language and gender alone tell the gender of the voice set above for that language.
329
+ */
330
+ function parseVoiceGenders(rows) {
331
+ const genders = {};
332
+ if (!Array.isArray(rows)) {
333
+ return genders;
334
+ }
335
+ for (const row of rows) {
336
+ const lang = cellLanguage(row?.language);
337
+ const gender = cellGender(row?.gender);
338
+ if (lang && gender) {
339
+ genders[lang] = gender;
340
+ }
341
+ }
342
+ return genders;
343
+ }
344
+ /** How one speaks of oneself per gender, as an example for the model. */
345
+ const SELF_FORMS = {
346
+ ru: { female: 'я сделала', male: 'я сделал' },
347
+ uk: { female: 'я зробила', male: 'я зробив' },
348
+ be: { female: 'я зрабіла', male: 'я зрабіў' },
349
+ pl: { female: 'zrobiłam', male: 'zrobiłem' },
350
+ cs: { female: 'udělala jsem', male: 'udělal jsem' },
351
+ fr: { female: 'je suis prête', male: 'je suis prêt' },
352
+ es: { female: 'estoy lista', male: 'estoy listo' },
353
+ it: { female: 'sono pronta', male: 'sono pronto' },
354
+ pt: { female: 'obrigada', male: 'obrigado' },
355
+ el: { female: 'είμαι έτοιμη', male: 'είμαι έτοιμος' },
356
+ };
357
+ /** Name of a language in the language of the prompt ('Russisch', 'русский'), the code when Node.js has no name. */
358
+ function languageName(code, inLanguage) {
359
+ try {
360
+ return new Intl.DisplayNames([inLanguage], { type: 'language' }).of(code) || code;
361
+ }
362
+ catch {
363
+ return code;
364
+ }
365
+ }
366
+ /**
367
+ * Instruction for the cloud model (system prompt): the gender of the voice per answer language, so that it speaks of
368
+ * itself in that form. Empty without genders. In the prompt language (de/en/ru), like the other hints.
369
+ *
370
+ * @param genders ISO code → gender of the voice ({@link parseVoiceGenders})
371
+ * @param promptLanguage language of the instructions
372
+ */
373
+ function voiceGenderHint(genders, promptLanguage) {
374
+ const lang = baseLanguage(promptLanguage) === 'ru' ? 'ru' : baseLanguage(promptLanguage) === 'de' ? 'de' : 'en';
375
+ const words = {
376
+ de: { female: 'weiblich', male: 'männlich' },
377
+ en: { female: 'female', male: 'male' },
378
+ ru: { female: 'женский', male: 'мужской' },
379
+ };
380
+ const not = { de: 'nicht', en: 'not', ru: 'а не' }[lang];
381
+ const items = Object.entries(genders).map(([code, gender]) => {
382
+ const forms = SELF_FORMS[code];
383
+ const other = gender === 'female' ? 'male' : 'female';
384
+ const example = forms ? ` («${forms[gender]}», ${not} «${forms[other]}»)` : '';
385
+ return `${languageName(code, lang)} – ${words[lang][gender]}${example}`;
386
+ });
387
+ if (!items.length) {
388
+ return '';
389
+ }
390
+ const list = items.join(', ');
391
+ if (lang === 'ru') {
392
+ return `Пол твоего голоса по языку ответа: ${list}. Говоря о себе на этом языке, используй грамматический род этого голоса, и в текстовых ответах тоже.`;
393
+ }
394
+ if (lang === 'de') {
395
+ return `Geschlecht deiner Stimme je Antwortsprache: ${list}. Wenn du in dieser Sprache von dir selbst sprichst, nimm das grammatische Geschlecht dieser Stimme, auch in Textantworten.`;
396
+ }
397
+ return `The gender of your voice per answer language: ${list}. When you speak of yourself in that language, use the grammatical gender of that voice, in text answers too.`;
398
+ }
318
399
  /**
319
400
  * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the
320
401
  * language the answering tier gave for exactly this text.
@@ -351,6 +432,9 @@ class LanguageTts {
351
432
  warm(phrases, lang) {
352
433
  return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);
353
434
  }
435
+ voiceGender(lang) {
436
+ return this.inner.voiceGender ? this.inner.voiceGender(lang) : Promise.resolve('');
437
+ }
354
438
  }
355
439
  exports.LanguageTts = LanguageTts;
356
440
  /**
@@ -386,6 +470,9 @@ class VoicePerLanguage {
386
470
  warm(phrases, lang) {
387
471
  return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);
388
472
  }
473
+ voiceGender(lang) {
474
+ return this.engineFor(lang).voiceGender?.(lang) ?? Promise.resolve('');
475
+ }
389
476
  }
390
477
  exports.VoicePerLanguage = VoicePerLanguage;
391
478
  //# sourceMappingURL=speechLanguage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AAuDA,oCAKC;AAoDD,wCAkBC;AASD,8CAuBC;AAUD,wCAmBC;AAuCD,4CAwBC;AA+CD,8CAOC;AAYD,oCAGC;AAMD,kDAeC;AAGD,0CAcC;AAvVD,+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,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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/** Grammar words of English and German: a device name hardly has two of them, a sentence has. */\nconst LATIN_GRAMMAR = new Set(\n \"the a an is are was it its it's of to and this that there der die das den dem des ein eine einen ist sind war und es nicht\".split(\n ' ',\n ),\n);\n\n/**\n * Does the text carry words of this language's script? For a language not written in Latin letters a few of its\n * letters are enough: \"Температура (Küche): Kueche Sensor 1: 24 °C\" is a Russian sentence with German names in it,\n * and an English voice would read the Russian words badly. Latin letters alone prove nothing (names, units, brands) —\n * unless they carry the grammar of a sentence: \"The lamp \"Свет\" is on.\" is English with a Russian name.\n */\nfunction hasOwnLetters(text: string, lang: string): boolean {\n const script = scriptOf(lang);\n if (script === 'latin') {\n return false;\n }\n const re = LETTERS.find(([s]) => s === script)?.[1];\n if (!re || (text.match(re) || []).length < MIN_LETTERS) {\n return false;\n }\n const latinWords = text.toLowerCase().match(/[a-zà-ɏ']+/g) || [];\n return latinWords.filter(w => LATIN_GRAMMAR.has(w)).length < 2;\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 * One line for the user turn of a cloud model: \"answer in this language\". The general hint in the system prompt\n * (\"answer in the language of the question\") is not enough for a conversation that ran in another language so far —\n * pi-agent answered a Russian question in German after German turns and a German system prompt.\n *\n * @param lang ISO-639-1 code of the question\n */\nexport function replyLanguageLine(lang: string): string {\n const base = baseLanguage(lang);\n switch (base) {\n case '':\n return '';\n case 'ru':\n return 'Ответь по-русски.';\n case 'uk':\n return 'Відповідай українською.';\n case 'de':\n return 'Antworte auf Deutsch.';\n case 'en':\n return 'Answer in English.';\n default: {\n let name = base;\n try {\n name = new Intl.DisplayNames(['en'], { type: 'language' }).of(base) || base;\n } catch {\n // an unknown code: the code itself\n }\n return `Answer in ${name}.`;\n }\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); Latin names inside a\n // Russian sentence do not contradict \"ru\"\n if (said && (!script || scriptOf(said) === script || hasOwnLetters(text, said))) {\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 || (!said && script !== scriptOf(configured) && hasOwnLetters(text, configured))) {\n return configured; // too few letters, or a sentence of the configured language with Latin names in it\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Words that say a Latin-script question is English or German. Only words of one of the two: \"in\", \"an\", \"die\",\n * \"was\", \"will\", \"so\", \"man\" are both and say nothing. Kept to what short spoken commands and questions use.\n */\nconst FUNCTION_WORDS: Record<'en' | 'de', ReadonlySet<string>> = {\n en: new Set(\n (\n \"the what what's whats is are it it's its how turn switch please light lights time me my of to and you your \" +\n 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +\n 'does do can could would there all up down timer alarm minutes hours at for be play stop'\n ).split(' '),\n ),\n de: new Set(\n (\n 'der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +\n 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +\n 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +\n 'kannst spiele spiel'\n ).split(' '),\n ),\n};\n\n/** Function words of `lang` in the words of a text; 0 for a language without a list. */\nfunction functionWords(words: string[], lang: string): number {\n const list = FUNCTION_WORDS[lang as 'en' | 'de'];\n return list ? words.filter(w => list.has(w)).length : 0;\n}\n\n/**\n * The language a question is asked in, for the fixed answers of the rule NLU (\"скажи, сколько сейчас времени\" on a\n * German satellite was answered in German). Another script than the configured language's tells it by the letters\n * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with\n * at least two of them and more than twice as many as of the configured language, so a German command with an\n * English device name stays German and a French question on a French system is not taken for German.\n *\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function questionLanguage(text: string, configured: string): string {\n const question = String(text || '');\n const script = dominantScript(question);\n if (!script) {\n return configured;\n }\n if (script !== 'latin') {\n return speechLanguage(question, configured);\n }\n const words = question.toLowerCase().match(/[\\p{L}']+/gu) || [];\n const base = baseLanguage(configured);\n let best = '';\n let most = 0;\n for (const lang of ['en', 'de']) {\n const hits = functionWords(words, lang);\n if (hits > most) {\n best = lang;\n most = hits;\n }\n }\n if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {\n return configured;\n }\n return best;\n}\n\n/** How many answers {@link AnswerLanguages} remembers. */\nconst KEPT_LANGUAGES = 50;\n\n/**\n * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to\n * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):\n * the assistant takes them out before speaking.\n */\nexport class AnswerLanguages {\n private readonly byText = new Map<string, string>();\n\n private static key(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n\n /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */\n remember(text: string, language: string): void {\n const lang = String(language || '')\n .trim()\n .toLowerCase();\n const key = AnswerLanguages.key(text);\n if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {\n return;\n }\n this.byText.delete(key);\n this.byText.set(key, lang);\n if (this.byText.size > KEPT_LANGUAGES) {\n this.byText.delete(this.byText.keys().next().value as string);\n }\n }\n\n /** The language remembered for this answer, '' for none. */\n languageOf(text: string): string {\n return this.byText.get(AnswerLanguages.key(text)) || '';\n }\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** A row of the table \"voice per language\": the voice and/or the TTS model ('' = the ones set above). */\nexport interface LanguageVoice {\n voice: string;\n model: string;\n}\n\n/**\n * The language code at the start of a table cell: 'de', 'de-DE' → 'de'. The column was a free text field with\n * suggestions, and picking one saved its label ('de – Deutsch'), so the code is read from the start.\n */\nexport function cellLanguage(value: unknown): string {\n const match = typeof value === 'string' ? /^\\s*([a-z]{2,3})(?![a-z])/i.exec(value) : null;\n return match ? match[1].toLowerCase() : '';\n}\n\n/**\n * The table \"voice per language\" with a code in each language cell, or `null` when every cell has one already.\n * The column is a drop-down now, which shows nothing for 'de – Deutsch' or 'de-DE'.\n */\nexport function normalizeVoiceTable(rows: unknown): unknown[] | null {\n if (!Array.isArray(rows)) {\n return null;\n }\n let changed = false;\n const fixed = rows.map(row => {\n const language = (row as { language?: unknown } | null)?.language;\n const code = cellLanguage(language);\n if (!code || code === language) {\n return row;\n }\n changed = true;\n return { ...(row as object), language: code };\n });\n return changed ? fixed : null;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice and model; rows without either are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, LanguageVoice> {\n const table: Record<string, LanguageVoice> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown; model?: unknown }[]) {\n const lang = cellLanguage(row?.language);\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n const model = typeof row?.model === 'string' ? row.model.trim() : '';\n if (lang && (voice || model)) {\n table[lang] = { voice, model };\n }\n }\n return table;\n}\n\n/** Log of the TTS layer. */\ninterface Logger {\n debug(msg: string): void;\n}\n\n/**\n * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the\n * language the answering tier gave for exactly this text.\n */\nexport class LanguageTts implements TtsEngine {\n constructor(\n private readonly inner: TtsEngine,\n private readonly reported: ((text: string) => string | undefined) | undefined,\n private readonly log: Logger,\n ) {}\n\n /** The language `text` is spoken in when the caller asks for `lang`. */\n languageFor(text: string, lang: string): string {\n const spoken = speechLanguage(text, lang, this.reported?.(text));\n if (spoken !== lang) {\n this.log.debug(`TTS in '${spoken}' instead of '${lang}': \"${String(text).slice(0, 40)}\"`);\n }\n return spoken;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.inner.synthesize(text, this.languageFor(text, lang));\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);\n return this.inner.synthesizeSsml\n ? this.inner.synthesizeSsml(ssml, spoken)\n : this.inner.synthesize(ssml, spoken);\n }\n\n prepare(lang: string): Promise<void> {\n return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);\n }\n}\n\n/**\n * The voices of the table \"voice per language\": one engine per row, the default engine for every other language.\n * Each engine has its own cache (the directory is per voice).\n */\nexport class VoicePerLanguage implements TtsEngine {\n constructor(\n private readonly fallback: TtsEngine,\n private readonly byLanguage: Record<string, TtsEngine>,\n ) {}\n\n private engineFor(lang: string): TtsEngine {\n return this.byLanguage[baseLanguage(lang)] || this.fallback;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.engineFor(lang).synthesize(text, lang);\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const engine = this.engineFor(lang);\n return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);\n }\n\n /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */\n async prepare(lang: string): Promise<void> {\n await this.engineFor(lang).prepare?.(lang);\n for (const [code, engine] of Object.entries(this.byLanguage)) {\n if (code !== baseLanguage(lang)) {\n await engine.prepare?.(code);\n }\n }\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}
1
+ {"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AA0DA,oCAKC;AAoDD,wCAkBC;AASD,8CAuBC;AAUD,wCAmBC;AAuCD,4CAwBC;AA+CD,8CAOC;AAYD,oCAGC;AAMD,kDAeC;AAGD,0CAcC;AAGD,gCAGC;AAMD,8CAaC;AAgCD,0CAyBC;AAzaD,+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;IACZ,EAAE,EAAE,QAAQ;IACZ,EAAE,EAAE,QAAQ;CACf,CAAC;AAEF,MAAM,OAAO,GAAuB;IAChC,CAAC,OAAO,EAAE,YAAY,CAAC;IACvB,CAAC,UAAU,EAAE,QAAQ,CAAC;IACtB,CAAC,OAAO,EAAE,QAAQ,CAAC;IACnB,CAAC,KAAK,EAAE,WAAW,CAAC;IACpB,CAAC,QAAQ,EAAE,WAAW,CAAC;IACvB,CAAC,QAAQ,EAAE,QAAQ,CAAC;IACpB,CAAC,QAAQ,EAAE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CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC;IAED,WAAW,CAAC,IAAY;QACpB,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC3E,CAAC;CACJ;AApCD,4CAoCC","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';\nimport type { VoiceGender } from './voiceGender';\n\nexport type { VoiceGender };\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/** Grammar words of English and German: a device name hardly has two of them, a sentence has. */\nconst LATIN_GRAMMAR = new Set(\n \"the a an is are was it its it's of to and this that there der die das den dem des ein eine einen ist sind war und es nicht\".split(\n ' ',\n ),\n);\n\n/**\n * Does the text carry words of this language's script? For a language not written in Latin letters a few of its\n * letters are enough: \"Температура (Küche): Kueche Sensor 1: 24 °C\" is a Russian sentence with German names in it,\n * and an English voice would read the Russian words badly. Latin letters alone prove nothing (names, units, brands) —\n * unless they carry the grammar of a sentence: \"The lamp \"Свет\" is on.\" is English with a Russian name.\n */\nfunction hasOwnLetters(text: string, lang: string): boolean {\n const script = scriptOf(lang);\n if (script === 'latin') {\n return false;\n }\n const re = LETTERS.find(([s]) => s === script)?.[1];\n if (!re || (text.match(re) || []).length < MIN_LETTERS) {\n return false;\n }\n const latinWords = text.toLowerCase().match(/[a-zà-ɏ']+/g) || [];\n return latinWords.filter(w => LATIN_GRAMMAR.has(w)).length < 2;\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 * One line for the user turn of a cloud model: \"answer in this language\". The general hint in the system prompt\n * (\"answer in the language of the question\") is not enough for a conversation that ran in another language so far —\n * pi-agent answered a Russian question in German after German turns and a German system prompt.\n *\n * @param lang ISO-639-1 code of the question\n */\nexport function replyLanguageLine(lang: string): string {\n const base = baseLanguage(lang);\n switch (base) {\n case '':\n return '';\n case 'ru':\n return 'Ответь по-русски.';\n case 'uk':\n return 'Відповідай українською.';\n case 'de':\n return 'Antworte auf Deutsch.';\n case 'en':\n return 'Answer in English.';\n default: {\n let name = base;\n try {\n name = new Intl.DisplayNames(['en'], { type: 'language' }).of(base) || base;\n } catch {\n // an unknown code: the code itself\n }\n return `Answer in ${name}.`;\n }\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); Latin names inside a\n // Russian sentence do not contradict \"ru\"\n if (said && (!script || scriptOf(said) === script || hasOwnLetters(text, said))) {\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 || (!said && script !== scriptOf(configured) && hasOwnLetters(text, configured))) {\n return configured; // too few letters, or a sentence of the configured language with Latin names in it\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Words that say a Latin-script question is English or German. Only words of one of the two: \"in\", \"an\", \"die\",\n * \"was\", \"will\", \"so\", \"man\" are both and say nothing. Kept to what short spoken commands and questions use.\n */\nconst FUNCTION_WORDS: Record<'en' | 'de', ReadonlySet<string>> = {\n en: new Set(\n (\n \"the what what's whats is are it it's its how turn switch please light lights time me my of to and you your \" +\n 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +\n 'does do can could would there all up down timer alarm minutes hours at for be play stop'\n ).split(' '),\n ),\n de: new Set(\n (\n 'der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +\n 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +\n 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +\n 'kannst spiele spiel'\n ).split(' '),\n ),\n};\n\n/** Function words of `lang` in the words of a text; 0 for a language without a list. */\nfunction functionWords(words: string[], lang: string): number {\n const list = FUNCTION_WORDS[lang as 'en' | 'de'];\n return list ? words.filter(w => list.has(w)).length : 0;\n}\n\n/**\n * The language a question is asked in, for the fixed answers of the rule NLU (\"скажи, сколько сейчас времени\" on a\n * German satellite was answered in German). Another script than the configured language's tells it by the letters\n * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with\n * at least two of them and more than twice as many as of the configured language, so a German command with an\n * English device name stays German and a French question on a French system is not taken for German.\n *\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function questionLanguage(text: string, configured: string): string {\n const question = String(text || '');\n const script = dominantScript(question);\n if (!script) {\n return configured;\n }\n if (script !== 'latin') {\n return speechLanguage(question, configured);\n }\n const words = question.toLowerCase().match(/[\\p{L}']+/gu) || [];\n const base = baseLanguage(configured);\n let best = '';\n let most = 0;\n for (const lang of ['en', 'de']) {\n const hits = functionWords(words, lang);\n if (hits > most) {\n best = lang;\n most = hits;\n }\n }\n if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {\n return configured;\n }\n return best;\n}\n\n/** How many answers {@link AnswerLanguages} remembers. */\nconst KEPT_LANGUAGES = 50;\n\n/**\n * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to\n * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):\n * the assistant takes them out before speaking.\n */\nexport class AnswerLanguages {\n private readonly byText = new Map<string, string>();\n\n private static key(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n\n /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */\n remember(text: string, language: string): void {\n const lang = String(language || '')\n .trim()\n .toLowerCase();\n const key = AnswerLanguages.key(text);\n if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {\n return;\n }\n this.byText.delete(key);\n this.byText.set(key, lang);\n if (this.byText.size > KEPT_LANGUAGES) {\n this.byText.delete(this.byText.keys().next().value as string);\n }\n }\n\n /** The language remembered for this answer, '' for none. */\n languageOf(text: string): string {\n return this.byText.get(AnswerLanguages.key(text)) || '';\n }\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** A row of the table \"voice per language\": the voice and/or the TTS model ('' = the ones set above). */\nexport interface LanguageVoice {\n voice: string;\n model: string;\n}\n\n/**\n * The language code at the start of a table cell: 'de', 'de-DE' → 'de'. The column was a free text field with\n * suggestions, and picking one saved its label ('de – Deutsch'), so the code is read from the start.\n */\nexport function cellLanguage(value: unknown): string {\n const match = typeof value === 'string' ? /^\\s*([a-z]{2,3})(?![a-z])/i.exec(value) : null;\n return match ? match[1].toLowerCase() : '';\n}\n\n/**\n * The table \"voice per language\" with a code in each language cell, or `null` when every cell has one already.\n * The column is a drop-down now, which shows nothing for 'de – Deutsch' or 'de-DE'.\n */\nexport function normalizeVoiceTable(rows: unknown): unknown[] | null {\n if (!Array.isArray(rows)) {\n return null;\n }\n let changed = false;\n const fixed = rows.map(row => {\n const language = (row as { language?: unknown } | null)?.language;\n const code = cellLanguage(language);\n if (!code || code === language) {\n return row;\n }\n changed = true;\n return { ...(row as object), language: code };\n });\n return changed ? fixed : null;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice and model; rows without either are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, LanguageVoice> {\n const table: Record<string, LanguageVoice> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown; model?: unknown }[]) {\n const lang = cellLanguage(row?.language);\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n const model = typeof row?.model === 'string' ? row.model.trim() : '';\n if (lang && (voice || model)) {\n table[lang] = { voice, model };\n }\n }\n return table;\n}\n\n/** The gender in a table cell, '' for none. */\nexport function cellGender(value: unknown): VoiceGender | '' {\n const gender = typeof value === 'string' ? value.trim().toLowerCase() : '';\n return gender === 'female' || gender === 'male' ? gender : '';\n}\n\n/**\n * Parse the column \"gender\" of the table \"voice per language\" into ISO code → gender. A row needs no voice for it:\n * language and gender alone tell the gender of the voice set above for that language.\n */\nexport function parseVoiceGenders(rows: unknown): Record<string, VoiceGender> {\n const genders: Record<string, VoiceGender> = {};\n if (!Array.isArray(rows)) {\n return genders;\n }\n for (const row of rows as { language?: unknown; gender?: unknown }[]) {\n const lang = cellLanguage(row?.language);\n const gender = cellGender(row?.gender);\n if (lang && gender) {\n genders[lang] = gender;\n }\n }\n return genders;\n}\n\n/** How one speaks of oneself per gender, as an example for the model. */\nconst SELF_FORMS: Record<string, Record<VoiceGender, string>> = {\n ru: { female: 'я сделала', male: 'я сделал' },\n uk: { female: 'я зробила', male: 'я зробив' },\n be: { female: 'я зрабіла', male: 'я зрабіў' },\n pl: { female: 'zrobiłam', male: 'zrobiłem' },\n cs: { female: 'udělala jsem', male: 'udělal jsem' },\n fr: { female: 'je suis prête', male: 'je suis prêt' },\n es: { female: 'estoy lista', male: 'estoy listo' },\n it: { female: 'sono pronta', male: 'sono pronto' },\n pt: { female: 'obrigada', male: 'obrigado' },\n el: { female: 'είμαι έτοιμη', male: 'είμαι έτοιμος' },\n};\n\n/** Name of a language in the language of the prompt ('Russisch', 'русский'), the code when Node.js has no name. */\nfunction languageName(code: string, inLanguage: string): string {\n try {\n return new Intl.DisplayNames([inLanguage], { type: 'language' }).of(code) || code;\n } catch {\n return code;\n }\n}\n\n/**\n * Instruction for the cloud model (system prompt): the gender of the voice per answer language, so that it speaks of\n * itself in that form. Empty without genders. In the prompt language (de/en/ru), like the other hints.\n *\n * @param genders ISO code → gender of the voice ({@link parseVoiceGenders})\n * @param promptLanguage language of the instructions\n */\nexport function voiceGenderHint(genders: Record<string, VoiceGender>, promptLanguage: string): string {\n const lang = baseLanguage(promptLanguage) === 'ru' ? 'ru' : baseLanguage(promptLanguage) === 'de' ? 'de' : 'en';\n const words: Record<'de' | 'en' | 'ru', Record<VoiceGender, string>> = {\n de: { female: 'weiblich', male: 'männlich' },\n en: { female: 'female', male: 'male' },\n ru: { female: 'женский', male: 'мужской' },\n };\n const not = { de: 'nicht', en: 'not', ru: 'а не' }[lang];\n const items = Object.entries(genders).map(([code, gender]) => {\n const forms = SELF_FORMS[code];\n const other: VoiceGender = gender === 'female' ? 'male' : 'female';\n const example = forms ? ` («${forms[gender]}», ${not} «${forms[other]}»)` : '';\n return `${languageName(code, lang)} – ${words[lang][gender]}${example}`;\n });\n if (!items.length) {\n return '';\n }\n const list = items.join(', ');\n if (lang === 'ru') {\n return `Пол твоего голоса по языку ответа: ${list}. Говоря о себе на этом языке, используй грамматический род этого голоса, и в текстовых ответах тоже.`;\n }\n if (lang === 'de') {\n return `Geschlecht deiner Stimme je Antwortsprache: ${list}. Wenn du in dieser Sprache von dir selbst sprichst, nimm das grammatische Geschlecht dieser Stimme, auch in Textantworten.`;\n }\n return `The gender of your voice per answer language: ${list}. When you speak of yourself in that language, use the grammatical gender of that voice, in text answers too.`;\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 voiceGender(lang: string): Promise<VoiceGender | ''> {\n return this.inner.voiceGender ? this.inner.voiceGender(lang) : Promise.resolve('');\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 voiceGender(lang: string): Promise<VoiceGender | ''> {\n return this.engineFor(lang).voiceGender?.(lang) ?? Promise.resolve('');\n }\n}\n"]}
@@ -9,6 +9,7 @@ exports.OpenAiTts = void 0;
9
9
  * (Piper / Wyoming) plug in behind the same `TtsEngine` interface later.
10
10
  */
11
11
  const openai_1 = __importDefault(require("openai"));
12
+ const voiceGender_1 = require("./voiceGender");
12
13
  /**
13
14
  * Cloud TTS via the OpenAI speech API. Requests `pcm` output — 24 kHz mono 16-bit signed LE —
14
15
  * so no client-side decoding is needed; the satellite resamples to its speaker rate.
@@ -22,6 +23,9 @@ class OpenAiTts {
22
23
  this.voice = voice;
23
24
  this.model = model;
24
25
  }
26
+ voiceGender() {
27
+ return Promise.resolve((0, voiceGender_1.knownVoiceGender)('openai', this.voice));
28
+ }
25
29
  async synthesize(text, _lang) {
26
30
  const resp = await this.client.audio.speech.create({
27
31
  model: this.model,
@@ -1 +1 @@
1
- {"version":3,"file":"tts.js","sourceRoot":"","sources":["../../../src/lib/voice/tts.ts"],"names":[],"mappings":";;;;;;AAAA;;;GAGG;AACH,oDAA4B;AA6C5B;;;GAGG;AACH,MAAa,SAAS;IACD,MAAM,CAAS;IACf,KAAK,CAAc;IACnB,KAAK,CAAS;IAE/B,YAAY,MAAc,EAAE,QAAqB,OAAO,EAAE,KAAK,GAAG,OAAO;QACrE,IAAI,CAAC,MAAM,GAAG,IAAI,gBAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAY,EAAE,KAAa;QACxC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;YAC/C,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,IAAI;YACX,eAAe,EAAE,KAAK;SACzB,CAAC,CAAC;QACH,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC7E,CAAC;CACJ;AApBD,8BAoBC","sourcesContent":["/**\n * Text-to-speech engines. V1 ships the cloud engine (OpenAI TTS); local engines\n * (Piper / Wyoming) plug in behind the same `TtsEngine` interface later.\n */\nimport OpenAI from 'openai';\n\n/** Who spoke a text — the request details show it (the table \"voice per language\" and the reserve make it vary). */\nexport interface TtsVoice {\n provider: string;\n /** '' or missing = the default voice of the provider or model for the language */\n voice?: string;\n model?: string;\n language: string;\n}\n\nexport interface TtsResult {\n /** Raw mono 16-bit signed LE PCM. */\n pcm: Buffer;\n sampleRate: number;\n /** Set by the engines of `createTtsEngine` */\n spokenBy?: TtsVoice;\n}\n\n/** What a transport reports after it synthesized a reply. */\nexport interface SpokenInfo {\n ms: number;\n audioMs: number;\n by?: TtsVoice;\n}\n\nexport interface TtsEngine {\n synthesize(text: string, lang: string): Promise<TtsResult>;\n /**\n * Speak SSML (`<speak>…</speak>`) — only implemented by engines that understand it (Azure, Polly).\n * Callers go through `CachedTts`, which strips the markup for the engines that do not.\n */\n synthesizeSsml?(ssml: string, lang: string): Promise<TtsResult>;\n /** Optional warm-up (install/download engine + voice for `lang`) so the first request isn't slow. */\n prepare?(lang: string): Promise<void>;\n /**\n * Pre-synthesise phrases into whatever cache this engine has, returning how many were added.\n * Implemented by `CachedTts`; absent on a bare provider binding.\n */\n warm?(phrases: string[], lang: string): Promise<number>;\n}\n\n/** OpenAI TTS voice ids. */\nexport type OpenAiVoice = 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer';\n\n/**\n * Cloud TTS via the OpenAI speech API. Requests `pcm` output — 24 kHz mono 16-bit signed LE —\n * so no client-side decoding is needed; the satellite resamples to its speaker rate.\n */\nexport class OpenAiTts implements TtsEngine {\n private readonly client: OpenAI;\n private readonly voice: OpenAiVoice;\n private readonly model: string;\n\n constructor(apiKey: string, voice: OpenAiVoice = 'alloy', model = 'tts-1') {\n this.client = new OpenAI({ apiKey });\n this.voice = voice;\n this.model = model;\n }\n\n async synthesize(text: string, _lang: string): Promise<TtsResult> {\n const resp = await this.client.audio.speech.create({\n model: this.model,\n voice: this.voice,\n input: text,\n response_format: 'pcm',\n });\n return { pcm: Buffer.from(await resp.arrayBuffer()), sampleRate: 24000 };\n }\n}\n"]}
1
+ {"version":3,"file":"tts.js","sourceRoot":"","sources":["../../../src/lib/voice/tts.ts"],"names":[],"mappings":";;;;;;AAAA;;;GAGG;AACH,oDAA4B;AAC5B,+CAAmE;AAkDnE;;;GAGG;AACH,MAAa,SAAS;IACD,MAAM,CAAS;IACf,KAAK,CAAc;IACnB,KAAK,CAAS;IAE/B,YAAY,MAAc,EAAE,QAAqB,OAAO,EAAE,KAAK,GAAG,OAAO;QACrE,IAAI,CAAC,MAAM,GAAG,IAAI,gBAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,WAAW;QACP,OAAO,OAAO,CAAC,OAAO,CAAC,IAAA,8BAAgB,EAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACnE,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAY,EAAE,KAAa;QACxC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;YAC/C,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,IAAI;YACX,eAAe,EAAE,KAAK;SACzB,CAAC,CAAC;QACH,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC7E,CAAC;CACJ;AAxBD,8BAwBC","sourcesContent":["/**\n * Text-to-speech engines. V1 ships the cloud engine (OpenAI TTS); local engines\n * (Piper / Wyoming) plug in behind the same `TtsEngine` interface later.\n */\nimport OpenAI from 'openai';\nimport { knownVoiceGender, type VoiceGender } from './voiceGender';\n\n/** Who spoke a text — the request details show it (the table \"voice per language\" and the reserve make it vary). */\nexport interface TtsVoice {\n provider: string;\n /** '' or missing = the default voice of the provider or model for the language */\n voice?: string;\n model?: string;\n language: string;\n}\n\nexport interface TtsResult {\n /** Raw mono 16-bit signed LE PCM. */\n pcm: Buffer;\n sampleRate: number;\n /** Set by the engines of `createTtsEngine` */\n spokenBy?: TtsVoice;\n}\n\n/** What a transport reports after it synthesized a reply. */\nexport interface SpokenInfo {\n ms: number;\n audioMs: number;\n by?: TtsVoice;\n}\n\nexport interface TtsEngine {\n synthesize(text: string, lang: string): Promise<TtsResult>;\n /**\n * Speak SSML (`<speak>…</speak>`) — only implemented by engines that understand it (Azure, Polly).\n * Callers go through `CachedTts`, which strips the markup for the engines that do not.\n */\n synthesizeSsml?(ssml: string, lang: string): Promise<TtsResult>;\n /** Optional warm-up (install/download engine + voice for `lang`) so the first request isn't slow. */\n prepare?(lang: string): Promise<void>;\n /**\n * Pre-synthesise phrases into whatever cache this engine has, returning how many were added.\n * Implemented by `CachedTts`; absent on a bare provider binding.\n */\n warm?(phrases: string[], lang: string): Promise<number>;\n /**\n * Gender of the voice that speaks `lang`, '' when not known: from the voice list of the provider (Azure, Polly) or\n * from what is known of the voice ({@link knownVoiceGender}). The assistant speaks of itself in it.\n */\n voiceGender?(lang: string): Promise<VoiceGender | ''>;\n}\n\n/** OpenAI TTS voice ids. */\nexport type OpenAiVoice = 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer';\n\n/**\n * Cloud TTS via the OpenAI speech API. Requests `pcm` output — 24 kHz mono 16-bit signed LE —\n * so no client-side decoding is needed; the satellite resamples to its speaker rate.\n */\nexport class OpenAiTts implements TtsEngine {\n private readonly client: OpenAI;\n private readonly voice: OpenAiVoice;\n private readonly model: string;\n\n constructor(apiKey: string, voice: OpenAiVoice = 'alloy', model = 'tts-1') {\n this.client = new OpenAI({ apiKey });\n this.voice = voice;\n this.model = model;\n }\n\n voiceGender(): Promise<VoiceGender | ''> {\n return Promise.resolve(knownVoiceGender('openai', this.voice));\n }\n\n async synthesize(text: string, _lang: string): Promise<TtsResult> {\n const resp = await this.client.audio.speech.create({\n model: this.model,\n voice: this.voice,\n input: text,\n response_format: 'pcm',\n });\n return { pcm: Buffer.from(await resp.arrayBuffer()), sampleRate: 24000 };\n }\n}\n"]}
@@ -180,6 +180,9 @@ class CachedTts {
180
180
  prepare(lang) {
181
181
  return this.engine.prepare ? this.engine.prepare(lang) : Promise.resolve();
182
182
  }
183
+ voiceGender(lang) {
184
+ return this.engine.voiceGender ? this.engine.voiceGender(lang) : Promise.resolve('');
185
+ }
183
186
  async synthesize(text, lang) {
184
187
  const wanted = this.maxChars > 0 ? truncateForTts(text, this.maxChars) : (text || '').trim();
185
188
  if (wanted.length < (text || '').trim().length) {
@@ -1 +1 @@
1
- {"version":3,"file":"ttsCache.js","sourceRoot":"","sources":["../../../src/lib/voice/ttsCache.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,4CAMC;AAQD,4CAkCC;AASD,wBAEC;AAGD,8BAKC;AAOD,wCAcC;AAtHD;;;;;;;;;;;;;;;;GAgBG;AACH,oDAAsC;AACtC,4CAA8B;AAC9B,gDAAkC;AAIlC,oFAAoF;AACvE,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC3C,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxD,OAAO,SAAS,CAAC;IACrB,CAAC;IACD,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACpC,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACxD,CAAC;A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AC,CAAC;gBAC/B,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;YACzD,CAAC,CAAC,CAAC;YACP,IAAI,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YACxD,IAAI,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACzB,OAAO;YACX,CAAC;YACD,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC1D,IAAI,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACzB,MAAM;gBACV,CAAC;gBACD,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAC1B,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC;YACxB,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,uBAAuB,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QAChF,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,2BAA4B,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;QAC3E,CAAC;IACL,CAAC;CACJ;AA/KD,8BA+KC","sourcesContent":["/**\n * The plumbing every TTS engine benefits from: a disk cache, a length limit, and SSML handling.\n *\n * Wrapped around any {@link TtsEngine}, so each engine stays a thin provider binding:\n * - **cache** — the assistant says the same short things over and over (\"Ok.\", \"Timer abgelaufen\",\n * a trigger's announcement). Synthesising those again on every repeat costs a cloud round-trip and\n * a few hundred milliseconds of latency for audio that is byte-for-byte identical. Only short texts\n * are cached: a long one-off answer will never be asked for twice, so it would only fill the disk.\n * - **length limit** — an LLM can answer with three paragraphs. Spoken at a speaker that is a minute\n * of monologue nobody can interrupt, so the text is cut at the last sentence end that fits.\n * - **SSML** — Azure and Polly can speak `<speak>…</speak>` (pauses, emphasis); OpenAI and the local\n * engines cannot, so there the tags are stripped rather than read out loud.\n *\n * All three come from the Python original (`C:\\iot\\Hannah`, `core/hannah/tts.py`: `_TTSCache`,\n * `_truncate_for_tts`, `_strip_ssml_tags`), including the detail that the sample rate belongs in the\n * cache entry — serving 24 kHz audio as 16 kHz plays it back at the wrong pitch.\n */\nimport * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceLogger } from './download';\n\n/** Hard limit for a spoken text. Hannah's 400 characters ≈ 25 seconds of speech. */\nexport const MAX_TTS_CHARS = 400;\n\n/**\n * The configured length limit for spoken text: a number ≥ 0 (0 = no limit), or undefined for the default\n * ({@link MAX_TTS_CHARS}) — also for installations from before the setting and for a field the user emptied.\n */\nexport function parseTtsMaxChars(value: unknown): number | undefined {\n if (value === '' || value === null || value === undefined) {\n return undefined;\n }\n const n = Math.round(Number(value));\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\n/**\n * Instruction for a model whose answer will be spoken and cut at `limit` characters: answer within it instead\n * of being cut mid-thought. Models cannot count characters, so the limit also comes as a number of sentences.\n * Also asks not to read out state ids and serial numbers — over a speaker they are a minute of digits.\n * Empty when there is no limit.\n */\nexport function spokenLengthHint(limit: number, lang: string): string {\n if (!(limit > 0)) {\n return '';\n }\n const n = Math.max(1, Math.round(limit / 120));\n if (lang === 'ru') {\n const sentences =\n n === 1\n ? 'одно короткое предложение'\n : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)\n ? `${n} коротких предложения`\n : `${n} коротких предложений`;\n return (\n `Твой ответ зачитывается вслух и обрезается после ${limit} символов. Поэтому отвечай не длиннее ${limit} ` +\n `символов (примерно ${sentences}), главное — в начале. Не зачитывай ID состояний, серийные номера и ` +\n 'длинные числа, если пользователь сам об этом не просит. Если нужно сказать больше, кратко подведи итог ' +\n 'и предложи рассказать подробнее.'\n );\n }\n if (lang === 'de') {\n const sentences = n === 1 ? 'einen kurzen Satz' : `${n} kurze Sätze`;\n return (\n `Deine Antwort wird vorgelesen und nach ${limit} Zeichen abgeschnitten. Antworte deshalb in höchstens ` +\n `${limit} Zeichen (etwa ${sentences}), das Wichtigste zuerst. Lies keine State-IDs, Seriennummern oder ` +\n 'langen Zahlen vor, außer der Nutzer fragt ausdrücklich danach. Ist mehr zu sagen, fasse zusammen und ' +\n 'biete an, Details zu nennen.'\n );\n }\n const sentences = n === 1 ? 'one short sentence' : `${n} short sentences`;\n return (\n `Your answer is read aloud and cut off after ${limit} characters. Keep it within ${limit} characters ` +\n `(about ${sentences}), most important point first. Do not read out state ids, serial numbers or long ` +\n 'numbers unless the user asks for them. If there is more to say, summarise and offer the details.'\n );\n}\n\n/** Texts up to this length are worth caching; a longer one is a one-off answer. */\nexport const MAX_CACHE_CHARS = 200;\n\n/** Default budget for the cache directory. ~1 MB per 20 s of 24 kHz 16-bit audio. */\nexport const DEFAULT_CACHE_BYTES = 64 * 1024 * 1024;\n\n/** Does this text ask for SSML? */\nexport function isSsml(text: string): boolean {\n return /^\\s*<speak[\\s>]/i.test(text || '');\n}\n\n/** Drop the XML tags, for an engine that cannot speak SSML (reading them aloud would be worse). */\nexport function stripSsml(text: string): string {\n return (text || '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/**\n * Cut `text` to `maxChars`, preferring the last sentence end in the second half so the result does not\n * stop mid-thought; failing that, the last word boundary plus an ellipsis. SSML is left alone — cutting\n * it would break the markup, and it is written by us, not by a model.\n */\nexport function truncateForTts(text: string, maxChars = MAX_TTS_CHARS): string {\n const t = (text || '').trim();\n if (t.length <= maxChars || isSsml(t)) {\n return t;\n }\n const chunk = t.slice(0, maxChars);\n for (const sep of ['.', '!', '?', '…']) {\n const idx = chunk.lastIndexOf(sep);\n if (idx > maxChars / 2) {\n return chunk.slice(0, idx + 1);\n }\n }\n const lastSpace = chunk.lastIndexOf(' ');\n return `${(lastSpace > 0 ? chunk.slice(0, lastSpace) : chunk).trim()} …`;\n}\n\n/** A cache entry on disk: the sample rate first, so an entry can never be replayed at the wrong pitch. */\nfunction encodeEntry(result: TtsResult): Buffer {\n const head = Buffer.alloc(4);\n head.writeUInt32LE(result.sampleRate, 0);\n return Buffer.concat([head, result.pcm]);\n}\n\nfunction decodeEntry(data: Buffer): TtsResult | null {\n if (data.length < 8) {\n return null;\n }\n const sampleRate = data.readUInt32LE(0);\n // A plausible speech rate; anything else means the file is not one of ours (or is truncated).\n if (sampleRate < 8000 || sampleRate > 48000) {\n return null;\n }\n return { pcm: data.subarray(4), sampleRate };\n}\n\nexport interface TtsCacheOptions {\n /** Directory for this engine's entries (one per provider+voice, so a voice change cannot serve stale audio). */\n dir: string;\n log: VoiceLogger;\n /** Cut texts longer than this before synthesising (0 = no limit). */\n maxChars?: number;\n /** Only cache texts up to this length (0 = cache everything). */\n maxCacheChars?: number;\n /** Prune the oldest entries once the directory exceeds this (0 = no limit). */\n maxBytes?: number;\n /**\n * Provider, voice and model of the engine: every result says it (`spokenBy`), a cached one too. A voice the engine\n * chose itself (OpenRouter without a voice) stays when the clip was not cached.\n */\n by?: { provider: string; voice?: string; model?: string };\n}\n\n/**\n * A {@link TtsEngine} wrapper that truncates, serves repeats from disk and resolves SSML against what the\n * wrapped engine actually supports. Every cache operation is best-effort: a broken or read-only cache\n * directory must never stop the assistant from speaking.\n */\nexport class CachedTts implements TtsEngine {\n private readonly maxChars: number;\n private readonly maxCacheChars: number;\n private readonly maxBytes: number;\n private ready = false;\n\n constructor(\n private readonly engine: TtsEngine,\n private readonly opts: TtsCacheOptions,\n ) {\n this.maxChars = opts.maxChars ?? MAX_TTS_CHARS;\n this.maxCacheChars = opts.maxCacheChars ?? MAX_CACHE_CHARS;\n this.maxBytes = opts.maxBytes ?? DEFAULT_CACHE_BYTES;\n }\n\n prepare(lang: string): Promise<void> {\n return this.engine.prepare ? this.engine.prepare(lang) : Promise.resolve();\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n const wanted = this.maxChars > 0 ? truncateForTts(text, this.maxChars) : (text || '').trim();\n if (wanted.length < (text || '').trim().length) {\n this.opts.log.warn(\n `TTS text shortened from ${text.trim().length} to ${wanted.length} characters ` +\n `(limit ${this.maxChars}: \"Longest spoken answer\" in the Voice tab, 0 = no limit).`,\n );\n }\n const cacheable = this.maxCacheChars === 0 || wanted.length <= this.maxCacheChars;\n const file = cacheable ? this.entryPath(wanted, lang) : '';\n if (file) {\n const hit = this.read(file);\n if (hit) {\n this.opts.log.debug(`TTS cache hit: \"${wanted.slice(0, 40)}\"`);\n return this.tag(hit, lang);\n }\n }\n const result = await this.speak(wanted, lang);\n if (file && result.pcm.length) {\n this.write(file, result);\n }\n return this.tag(result, lang);\n }\n\n private tag(result: TtsResult, lang: string): TtsResult {\n const by = this.opts.by;\n if (!by) {\n return result;\n }\n return {\n ...result,\n spokenBy: {\n provider: by.provider,\n voice: result.spokenBy?.voice || by.voice || undefined,\n model: result.spokenBy?.model || by.model || undefined,\n language: lang,\n },\n };\n }\n\n /** Hand SSML to the engine only if it can speak it; otherwise speak the text without the markup. */\n private speak(text: string, lang: string): Promise<TtsResult> {\n if (!isSsml(text)) {\n return this.engine.synthesize(text, lang);\n }\n if (this.engine.synthesizeSsml) {\n return this.engine.synthesizeSsml(text, lang);\n }\n this.opts.log.debug('TTS engine cannot speak SSML — using the plain text.');\n return this.engine.synthesize(stripSsml(text), lang);\n }\n\n /** Is this text already on disk? Used by the warm-up to skip what it has. */\n has(text: string, lang: string): boolean {\n const wanted = this.maxChars > 0 ? truncateForTts(text, this.maxChars) : (text || '').trim();\n const file = this.entryPath(wanted, lang);\n try {\n return fs.existsSync(file);\n } catch {\n return false;\n }\n }\n\n /** Pre-synthesise frequently spoken phrases, so the first \"Ok.\" of the day is not a cloud call. */\n async warm(phrases: string[], lang: string): Promise<number> {\n let added = 0;\n for (const phrase of phrases) {\n const text = (phrase || '').trim();\n if (!text || this.has(text, lang)) {\n continue;\n }\n try {\n await this.synthesize(text, lang);\n added++;\n } catch (e) {\n this.opts.log.debug(`TTS warm-up failed for \"${text.slice(0, 30)}\": ${(e as Error).message}`);\n break; // the engine is unavailable — no point trying the rest\n }\n }\n if (added) {\n this.opts.log.info(`TTS cache warmed with ${added} phrase(s).`);\n }\n return added;\n }\n\n /** The language is part of the key: the same words are spoken differently in another language. */\n private entryPath(text: string, lang: string): string {\n const key = crypto.createHash('sha256').update(`${lang}\\u0000${text}`).digest('hex').slice(0, 20);\n return path.join(this.opts.dir, `${key}.pcm`);\n }\n\n private read(file: string): TtsResult | null {\n try {\n if (!fs.existsSync(file)) {\n return null;\n }\n const entry = decodeEntry(fs.readFileSync(file));\n if (entry) {\n // Touch it, so pruning drops what nobody asks for rather than what is merely old.\n const now = new Date();\n try {\n fs.utimesSync(file, now, now);\n } catch {\n /* a read-only cache is still a usable cache */\n }\n }\n return entry;\n } catch (e) {\n this.opts.log.debug(`TTS cache read failed: ${(e as Error).message}`);\n return null;\n }\n }\n\n private write(file: string, result: TtsResult): void {\n try {\n if (!this.ready) {\n fs.mkdirSync(this.opts.dir, { recursive: true });\n this.ready = true;\n }\n fs.writeFileSync(file, encodeEntry(result));\n this.prune();\n } catch (e) {\n this.opts.log.debug(`TTS cache write failed: ${(e as Error).message}`);\n }\n }\n\n /** Keep the directory under its budget by dropping the least recently used entries. */\n private prune(): void {\n if (this.maxBytes <= 0) {\n return;\n }\n try {\n const entries = fs\n .readdirSync(this.opts.dir)\n .filter(name => name.endsWith('.pcm'))\n .map(name => {\n const full = path.join(this.opts.dir, name);\n const stat = fs.statSync(full);\n return { full, size: stat.size, used: stat.mtimeMs };\n });\n let total = entries.reduce((sum, e) => sum + e.size, 0);\n if (total <= this.maxBytes) {\n return;\n }\n for (const entry of entries.sort((a, b) => a.used - b.used)) {\n if (total <= this.maxBytes) {\n break;\n }\n fs.unlinkSync(entry.full);\n total -= entry.size;\n }\n this.opts.log.debug(`TTS cache pruned to ${Math.round(total / 1024)} KiB.`);\n } catch (e) {\n this.opts.log.debug(`TTS cache prune failed: ${(e as Error).message}`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"ttsCache.js","sourceRoot":"","sources":["../../../src/lib/voice/ttsCache.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,4CAMC;AAQD,4CAkCC;AASD,wBAEC;AAGD,8BAKC;AAOD,wCAcC;AAvHD;;;;;;;;;;;;;;;;GAgBG;AACH,oDAAsC;AACtC,4CAA8B;AAC9B,gDAAkC;AAKlC,oFAAoF;AACvE,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC3C,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxD,OAAO,SAAS,CAAC;IACrB,CAAC;IACD,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACpC,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,KAAa,EAAE,IAAY;IACxD,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC;QACf,OAAO,EAAE,CAAC;IACd,CAAC;IACD,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAA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OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;YACzD,CAAC,CAAC,CAAC;YACP,IAAI,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;YACxD,IAAI,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACzB,OAAO;YACX,CAAC;YACD,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC1D,IAAI,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACzB,MAAM;gBACV,CAAC;gBACD,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAC1B,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC;YACxB,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,uBAAuB,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QAChF,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,2BAA4B,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;QAC3E,CAAC;IACL,CAAC;CACJ;AAnLD,8BAmLC","sourcesContent":["/**\n * The plumbing every TTS engine benefits from: a disk cache, a length limit, and SSML handling.\n *\n * Wrapped around any {@link TtsEngine}, so each engine stays a thin provider binding:\n * - **cache** — the assistant says the same short things over and over (\"Ok.\", \"Timer abgelaufen\",\n * a trigger's announcement). Synthesising those again on every repeat costs a cloud round-trip and\n * a few hundred milliseconds of latency for audio that is byte-for-byte identical. Only short texts\n * are cached: a long one-off answer will never be asked for twice, so it would only fill the disk.\n * - **length limit** — an LLM can answer with three paragraphs. Spoken at a speaker that is a minute\n * of monologue nobody can interrupt, so the text is cut at the last sentence end that fits.\n * - **SSML** — Azure and Polly can speak `<speak>…</speak>` (pauses, emphasis); OpenAI and the local\n * engines cannot, so there the tags are stripped rather than read out loud.\n *\n * All three come from the Python original (`C:\\iot\\Hannah`, `core/hannah/tts.py`: `_TTSCache`,\n * `_truncate_for_tts`, `_strip_ssml_tags`), including the detail that the sample rate belongs in the\n * cache entry — serving 24 kHz audio as 16 kHz plays it back at the wrong pitch.\n */\nimport * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceGender } from './voiceGender';\nimport type { VoiceLogger } from './download';\n\n/** Hard limit for a spoken text. Hannah's 400 characters ≈ 25 seconds of speech. */\nexport const MAX_TTS_CHARS = 400;\n\n/**\n * The configured length limit for spoken text: a number ≥ 0 (0 = no limit), or undefined for the default\n * ({@link MAX_TTS_CHARS}) — also for installations from before the setting and for a field the user emptied.\n */\nexport function parseTtsMaxChars(value: unknown): number | undefined {\n if (value === '' || value === null || value === undefined) {\n return undefined;\n }\n const n = Math.round(Number(value));\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\n/**\n * Instruction for a model whose answer will be spoken and cut at `limit` characters: answer within it instead\n * of being cut mid-thought. Models cannot count characters, so the limit also comes as a number of sentences.\n * Also asks not to read out state ids and serial numbers — over a speaker they are a minute of digits.\n * Empty when there is no limit.\n */\nexport function spokenLengthHint(limit: number, lang: string): string {\n if (!(limit > 0)) {\n return '';\n }\n const n = Math.max(1, Math.round(limit / 120));\n if (lang === 'ru') {\n const sentences =\n n === 1\n ? 'одно короткое предложение'\n : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)\n ? `${n} коротких предложения`\n : `${n} коротких предложений`;\n return (\n `Твой ответ зачитывается вслух и обрезается после ${limit} символов. Поэтому отвечай не длиннее ${limit} ` +\n `символов (примерно ${sentences}), главное — в начале. Не зачитывай ID состояний, серийные номера и ` +\n 'длинные числа, если пользователь сам об этом не просит. Если нужно сказать больше, кратко подведи итог ' +\n 'и предложи рассказать подробнее.'\n );\n }\n if (lang === 'de') {\n const sentences = n === 1 ? 'einen kurzen Satz' : `${n} kurze Sätze`;\n return (\n `Deine Antwort wird vorgelesen und nach ${limit} Zeichen abgeschnitten. Antworte deshalb in höchstens ` +\n `${limit} Zeichen (etwa ${sentences}), das Wichtigste zuerst. Lies keine State-IDs, Seriennummern oder ` +\n 'langen Zahlen vor, außer der Nutzer fragt ausdrücklich danach. Ist mehr zu sagen, fasse zusammen und ' +\n 'biete an, Details zu nennen.'\n );\n }\n const sentences = n === 1 ? 'one short sentence' : `${n} short sentences`;\n return (\n `Your answer is read aloud and cut off after ${limit} characters. Keep it within ${limit} characters ` +\n `(about ${sentences}), most important point first. Do not read out state ids, serial numbers or long ` +\n 'numbers unless the user asks for them. If there is more to say, summarise and offer the details.'\n );\n}\n\n/** Texts up to this length are worth caching; a longer one is a one-off answer. */\nexport const MAX_CACHE_CHARS = 200;\n\n/** Default budget for the cache directory. ~1 MB per 20 s of 24 kHz 16-bit audio. */\nexport const DEFAULT_CACHE_BYTES = 64 * 1024 * 1024;\n\n/** Does this text ask for SSML? */\nexport function isSsml(text: string): boolean {\n return /^\\s*<speak[\\s>]/i.test(text || '');\n}\n\n/** Drop the XML tags, for an engine that cannot speak SSML (reading them aloud would be worse). */\nexport function stripSsml(text: string): string {\n return (text || '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/**\n * Cut `text` to `maxChars`, preferring the last sentence end in the second half so the result does not\n * stop mid-thought; failing that, the last word boundary plus an ellipsis. SSML is left alone — cutting\n * it would break the markup, and it is written by us, not by a model.\n */\nexport function truncateForTts(text: string, maxChars = MAX_TTS_CHARS): string {\n const t = (text || '').trim();\n if (t.length <= maxChars || isSsml(t)) {\n return t;\n }\n const chunk = t.slice(0, maxChars);\n for (const sep of ['.', '!', '?', '…']) {\n const idx = chunk.lastIndexOf(sep);\n if (idx > maxChars / 2) {\n return chunk.slice(0, idx + 1);\n }\n }\n const lastSpace = chunk.lastIndexOf(' ');\n return `${(lastSpace > 0 ? chunk.slice(0, lastSpace) : chunk).trim()} …`;\n}\n\n/** A cache entry on disk: the sample rate first, so an entry can never be replayed at the wrong pitch. */\nfunction encodeEntry(result: TtsResult): Buffer {\n const head = Buffer.alloc(4);\n head.writeUInt32LE(result.sampleRate, 0);\n return Buffer.concat([head, result.pcm]);\n}\n\nfunction decodeEntry(data: Buffer): TtsResult | null {\n if (data.length < 8) {\n return null;\n }\n const sampleRate = data.readUInt32LE(0);\n // A plausible speech rate; anything else means the file is not one of ours (or is truncated).\n if (sampleRate < 8000 || sampleRate > 48000) {\n return null;\n }\n return { pcm: data.subarray(4), sampleRate };\n}\n\nexport interface TtsCacheOptions {\n /** Directory for this engine's entries (one per provider+voice, so a voice change cannot serve stale audio). */\n dir: string;\n log: VoiceLogger;\n /** Cut texts longer than this before synthesising (0 = no limit). */\n maxChars?: number;\n /** Only cache texts up to this length (0 = cache everything). */\n maxCacheChars?: number;\n /** Prune the oldest entries once the directory exceeds this (0 = no limit). */\n maxBytes?: number;\n /**\n * Provider, voice and model of the engine: every result says it (`spokenBy`), a cached one too. A voice the engine\n * chose itself (OpenRouter without a voice) stays when the clip was not cached.\n */\n by?: { provider: string; voice?: string; model?: string };\n}\n\n/**\n * A {@link TtsEngine} wrapper that truncates, serves repeats from disk and resolves SSML against what the\n * wrapped engine actually supports. Every cache operation is best-effort: a broken or read-only cache\n * directory must never stop the assistant from speaking.\n */\nexport class CachedTts implements TtsEngine {\n private readonly maxChars: number;\n private readonly maxCacheChars: number;\n private readonly maxBytes: number;\n private ready = false;\n\n constructor(\n private readonly engine: TtsEngine,\n private readonly opts: TtsCacheOptions,\n ) {\n this.maxChars = opts.maxChars ?? MAX_TTS_CHARS;\n this.maxCacheChars = opts.maxCacheChars ?? MAX_CACHE_CHARS;\n this.maxBytes = opts.maxBytes ?? DEFAULT_CACHE_BYTES;\n }\n\n prepare(lang: string): Promise<void> {\n return this.engine.prepare ? this.engine.prepare(lang) : Promise.resolve();\n }\n\n voiceGender(lang: string): Promise<VoiceGender | ''> {\n return this.engine.voiceGender ? this.engine.voiceGender(lang) : Promise.resolve('');\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n const wanted = this.maxChars > 0 ? truncateForTts(text, this.maxChars) : (text || '').trim();\n if (wanted.length < (text || '').trim().length) {\n this.opts.log.warn(\n `TTS text shortened from ${text.trim().length} to ${wanted.length} characters ` +\n `(limit ${this.maxChars}: \"Longest spoken answer\" in the Voice tab, 0 = no limit).`,\n );\n }\n const cacheable = this.maxCacheChars === 0 || wanted.length <= this.maxCacheChars;\n const file = cacheable ? this.entryPath(wanted, lang) : '';\n if (file) {\n const hit = this.read(file);\n if (hit) {\n this.opts.log.debug(`TTS cache hit: \"${wanted.slice(0, 40)}\"`);\n return this.tag(hit, lang);\n }\n }\n const result = await this.speak(wanted, lang);\n if (file && result.pcm.length) {\n this.write(file, result);\n }\n return this.tag(result, lang);\n }\n\n private tag(result: TtsResult, lang: string): TtsResult {\n const by = this.opts.by;\n if (!by) {\n return result;\n }\n return {\n ...result,\n spokenBy: {\n provider: by.provider,\n voice: result.spokenBy?.voice || by.voice || undefined,\n model: result.spokenBy?.model || by.model || undefined,\n language: lang,\n },\n };\n }\n\n /** Hand SSML to the engine only if it can speak it; otherwise speak the text without the markup. */\n private speak(text: string, lang: string): Promise<TtsResult> {\n if (!isSsml(text)) {\n return this.engine.synthesize(text, lang);\n }\n if (this.engine.synthesizeSsml) {\n return this.engine.synthesizeSsml(text, lang);\n }\n this.opts.log.debug('TTS engine cannot speak SSML — using the plain text.');\n return this.engine.synthesize(stripSsml(text), lang);\n }\n\n /** Is this text already on disk? Used by the warm-up to skip what it has. */\n has(text: string, lang: string): boolean {\n const wanted = this.maxChars > 0 ? truncateForTts(text, this.maxChars) : (text || '').trim();\n const file = this.entryPath(wanted, lang);\n try {\n return fs.existsSync(file);\n } catch {\n return false;\n }\n }\n\n /** Pre-synthesise frequently spoken phrases, so the first \"Ok.\" of the day is not a cloud call. */\n async warm(phrases: string[], lang: string): Promise<number> {\n let added = 0;\n for (const phrase of phrases) {\n const text = (phrase || '').trim();\n if (!text || this.has(text, lang)) {\n continue;\n }\n try {\n await this.synthesize(text, lang);\n added++;\n } catch (e) {\n this.opts.log.debug(`TTS warm-up failed for \"${text.slice(0, 30)}\": ${(e as Error).message}`);\n break; // the engine is unavailable — no point trying the rest\n }\n }\n if (added) {\n this.opts.log.info(`TTS cache warmed with ${added} phrase(s).`);\n }\n return added;\n }\n\n /** The language is part of the key: the same words are spoken differently in another language. */\n private entryPath(text: string, lang: string): string {\n const key = crypto.createHash('sha256').update(`${lang}\\u0000${text}`).digest('hex').slice(0, 20);\n return path.join(this.opts.dir, `${key}.pcm`);\n }\n\n private read(file: string): TtsResult | null {\n try {\n if (!fs.existsSync(file)) {\n return null;\n }\n const entry = decodeEntry(fs.readFileSync(file));\n if (entry) {\n // Touch it, so pruning drops what nobody asks for rather than what is merely old.\n const now = new Date();\n try {\n fs.utimesSync(file, now, now);\n } catch {\n /* a read-only cache is still a usable cache */\n }\n }\n return entry;\n } catch (e) {\n this.opts.log.debug(`TTS cache read failed: ${(e as Error).message}`);\n return null;\n }\n }\n\n private write(file: string, result: TtsResult): void {\n try {\n if (!this.ready) {\n fs.mkdirSync(this.opts.dir, { recursive: true });\n this.ready = true;\n }\n fs.writeFileSync(file, encodeEntry(result));\n this.prune();\n } catch (e) {\n this.opts.log.debug(`TTS cache write failed: ${(e as Error).message}`);\n }\n }\n\n /** Keep the directory under its budget by dropping the least recently used entries. */\n private prune(): void {\n if (this.maxBytes <= 0) {\n return;\n }\n try {\n const entries = fs\n .readdirSync(this.opts.dir)\n .filter(name => name.endsWith('.pcm'))\n .map(name => {\n const full = path.join(this.opts.dir, name);\n const stat = fs.statSync(full);\n return { full, size: stat.size, used: stat.mtimeMs };\n });\n let total = entries.reduce((sum, e) => sum + e.size, 0);\n if (total <= this.maxBytes) {\n return;\n }\n for (const entry of entries.sort((a, b) => a.used - b.used)) {\n if (total <= this.maxBytes) {\n break;\n }\n fs.unlinkSync(entry.full);\n total -= entry.size;\n }\n this.opts.log.debug(`TTS cache pruned to ${Math.round(total / 1024)} KiB.`);\n } catch (e) {\n this.opts.log.debug(`TTS cache prune failed: ${(e as Error).message}`);\n }\n }\n}\n"]}