iobroker.assistant 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,6 +50,7 @@ exports.pcmFromResponse = pcmFromResponse;
50
50
  const openai_1 = __importStar(require("openai"));
51
51
  const llm_1 = require("../llm");
52
52
  const stt_1 = require("./stt");
53
+ const speechLanguage_1 = require("./speechLanguage");
53
54
  /** Speech-to-text model when none is configured: Whisper large v3 turbo, multilingual and the cheapest Whisper */
54
55
  exports.DEFAULT_OPENROUTER_STT_MODEL = 'openai/whisper-large-v3-turbo';
55
56
  /**
@@ -184,16 +185,17 @@ class OpenRouterTts {
184
185
  }
185
186
  /** The configured voice, or the first one the model offers for the language — most models need a voice */
186
187
  async voiceFor(lang) {
187
- if (this.voice) {
188
+ // a locale voice (de-DE-Klaus:MAI-Voice-2) only for its language; Kore, george … speak every language
189
+ if (this.voice && (0, speechLanguage_1.voiceFitsLanguage)(this.voice, lang)) {
188
190
  return this.voice;
189
191
  }
190
192
  try {
191
193
  const models = await listOpenRouterSpeechModels('speech', this.fetchImpl);
192
194
  const voices = models.find(m => m.id === this.model)?.voices || [];
193
- return voicesForLanguage(voices, lang)[0] || '';
195
+ return voicesForLanguage(voices, lang)[0] || this.voice;
194
196
  }
195
197
  catch {
196
- return '';
198
+ return this.voice;
197
199
  }
198
200
  }
199
201
  async synthesize(text, lang) {
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter.js","sourceRoot":"","sources":["../../../src/lib/voice/openrouter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,gEA8BC;AASD,8CAOC;AASD,0CAiBC;AA/HD;;;;;;;;;GASG;AACH,iDAAwC;AACxC,gCAA8D;AAC9D,+BAAiD;AAGjD,kHAAkH;AACrG,QAAA,4BAA4B,GAAG,+BAA+B,CAAC;AAC5E;;;GAGG;AACU,QAAA,4BAA4B,GAAG,8BAA8B,CAAC;AA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AM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACxC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;YAC9C,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,KAAK,EAAE,IAAI;YACX,mGAAmG;YACnG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3B,eAAe,EAAE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;SACJ,CAAC,CAAC;QACtC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;QACnD,IAAI,GAAG,EAAE,CAAC;YACN,OAAO,IAAI,CAAC,MAAO,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,OAAO,eAAe,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;IACzE,CAAC;CACJ;AAvDD,sCAuDC","sourcesContent":["/**\n * Speech over OpenRouter: one key for the speech-to-text and text-to-speech models of many vendors (OpenAI,\n * ElevenLabs, Google, Deepgram, Mistral …) behind the OpenAI audio API at https://openrouter.ai/api/v1.\n * Model ids carry the vendor (`openai/whisper-large-v3-turbo`), and the voices depend on the model — the public\n * model list names them (`supported_voices`), so the settings offer exactly the voices of the chosen model.\n *\n * Differences to OpenAI itself: transcription ignores `prompt` (no vocabulary hints), and speech comes back as\n * `pcm` (most models, the default) or `mp3` (MiniMax only). The PCM rate is not part of the API — OpenRouter\n * documents 24 kHz, the rate of OpenAI, Gemini and Azure — so a rate in the content type wins over that default.\n */\nimport OpenAI, { toFile } from 'openai';\nimport { OPENROUTER_HEADERS, PROVIDER_PRESETS } from '../llm';\nimport { pcmToWav, type SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\n\n/** Speech-to-text model when none is configured: Whisper large v3 turbo, multilingual and the cheapest Whisper */\nexport const DEFAULT_OPENROUTER_STT_MODEL = 'openai/whisper-large-v3-turbo';\n/**\n * Text-to-speech model when none is configured: multilingual, PCM (no decoder needed) and fast — in a test about\n * 0.8 s for a sentence where Gemini TTS took 2.5 s, which a spoken answer waits for.\n */\nexport const DEFAULT_OPENROUTER_TTS_MODEL = 'elevenlabs/eleven-flash-v2.5';\n\n/** Rate of the PCM OpenRouter returns when the content type does not say otherwise */\nconst PCM_RATE = 24000;\n\n/** Vendors whose speech models only return mp3 (they answer `pcm` with a 400) */\nconst MP3_ONLY = ['minimax/'];\n\n/** How long the public model list is kept */\nconst MODEL_LIST_TTL_MS = 60 * 60 * 1000;\n\n/** Decode compressed audio (mp3) to mono 16-bit PCM — ffmpeg in the adapter */\nexport type AudioDecoder = (audio: Buffer) => Promise<TtsResult>;\n\n/** A speech model of OpenRouter */\nexport interface OpenRouterSpeechModel {\n id: string;\n name: string;\n /** Voices of a text-to-speech model, empty when the model names none */\n voices: string[];\n}\n\nfunction client(apiKey: string): OpenAI {\n return new OpenAI({ apiKey, baseURL: PROVIDER_PRESETS.openrouter.baseUrl, defaultHeaders: OPENROUTER_HEADERS });\n}\n\nconst modelLists = new Map<string, { at: number; models: Promise<OpenRouterSpeechModel[]> }>();\n\n/**\n * The speech models of OpenRouter. The list is public (no key), cached for an hour; a failed request is not kept.\n *\n * @param kind `speech` = text-to-speech, `transcription` = speech-to-text\n * @param fetchImpl fetch (tests)\n */\nexport function listOpenRouterSpeechModels(\n kind: 'speech' | 'transcription',\n fetchImpl: typeof fetch = fetch,\n): Promise<OpenRouterSpeechModel[]> {\n const cached = modelLists.get(kind);\n if (cached && Date.now() - cached.at < MODEL_LIST_TTL_MS) {\n return cached.models;\n }\n const models = (async () => {\n const res = await fetchImpl(`${PROVIDER_PRESETS.openrouter.baseUrl}/models?output_modalities=${kind}`, {\n headers: OPENROUTER_HEADERS,\n signal: AbortSignal.timeout(15000),\n });\n if (!res.ok) {\n throw new Error(`OpenRouter model list: HTTP ${res.status}`);\n }\n const body = (await res.json()) as { data?: { id?: unknown; name?: unknown; supported_voices?: unknown }[] };\n return (body.data || [])\n .filter(m => typeof m.id === 'string' && m.id)\n .map(m => ({\n id: m.id as string,\n name: typeof m.name === 'string' ? m.name : (m.id as string),\n voices: Array.isArray(m.supported_voices)\n ? m.supported_voices.filter((v): v is string => typeof v === 'string')\n : [],\n }));\n })();\n modelLists.set(kind, { at: Date.now(), models });\n models.catch(() => modelLists.delete(kind));\n return models;\n}\n\n/**\n * The voices of a text-to-speech model. Voices named after a locale (`de-DE-Klaus:MAI-Voice-2`) are narrowed to\n * the language, if that leaves any; other names (`Kore`, `george`) say nothing about the language.\n *\n * @param voices the voices of the model\n * @param language ISO-639-1 language ('' = all)\n */\nexport function voicesForLanguage(voices: string[], language: string): string[] {\n const lang = (language || '').split('-')[0].toLowerCase();\n if (!lang) {\n return voices;\n }\n const matching = voices.filter(v => new RegExp(`^${lang}[-_][A-Z]{2}\\\\b`).test(v));\n return matching.length ? matching : voices;\n}\n\n/**\n * Raw PCM out of a speech response: WAV is unwrapped, the rate comes from the content type (`audio/pcm;rate=…`)\n * or is the documented 24 kHz.\n *\n * @param audio the response body\n * @param contentType the content type of the response\n */\nexport function pcmFromResponse(audio: Buffer, contentType: string): TtsResult {\n if (audio.length > 44 && audio.toString('latin1', 0, 4) === 'RIFF' && audio.toString('latin1', 8, 12) === 'WAVE') {\n const sampleRate = audio.readUInt32LE(24);\n // the data chunk is not always right after the 16-byte fmt chunk\n let offset = 12;\n while (offset + 8 <= audio.length) {\n const id = audio.toString('latin1', offset, offset + 4);\n const size = audio.readUInt32LE(offset + 4);\n if (id === 'data') {\n return { pcm: audio.subarray(offset + 8, Math.min(audio.length, offset + 8 + size)), sampleRate };\n }\n offset += 8 + size + (size % 2);\n }\n return { pcm: audio.subarray(44), sampleRate };\n }\n const rate = /(?:^|[;\\s])(?:rate|sample_?rate)=(\\d+)/i.exec(contentType || '');\n return { pcm: audio, sampleRate: rate ? Number(rate[1]) : PCM_RATE };\n}\n\n/** Speech-to-text over OpenRouter (OpenAI-compatible multipart upload) */\nexport class OpenRouterStt implements SttEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n\n constructor(apiKey: string, model = '') {\n this.client = client(apiKey);\n this.model = model || DEFAULT_OPENROUTER_STT_MODEL;\n }\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {\n const file = await toFile(pcmToWav(pcm, sampleRate), 'audio.wav', { type: 'audio/wav' });\n // no vocabulary hints: OpenRouter accepts `prompt`, but ignores it\n const res = await this.client.audio.transcriptions.create({\n file,\n model: this.model,\n language: (lang || '').split('-')[0] || undefined,\n });\n return (res.text || '').trim();\n }\n}\n\n/** Text-to-speech over OpenRouter */\nexport class OpenRouterTts implements TtsEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n private readonly voice: string;\n private readonly decode?: AudioDecoder;\n private readonly fetchImpl?: typeof fetch;\n\n /**\n * @param apiKey OpenRouter key\n * @param model model id ('' = {@link DEFAULT_OPENROUTER_TTS_MODEL})\n * @param voice voice of the model ('' = the first voice of the model for the language)\n * @param decode decoder for the models that only return mp3\n * @param fetchImpl fetch for the model list (tests)\n */\n constructor(apiKey: string, model = '', voice = '', decode?: AudioDecoder, fetchImpl?: typeof fetch) {\n this.client = client(apiKey);\n this.model = model || DEFAULT_OPENROUTER_TTS_MODEL;\n this.voice = voice;\n this.decode = decode;\n this.fetchImpl = fetchImpl;\n }\n\n /** The configured voice, or the first one the model offers for the language — most models need a voice */\n private async voiceFor(lang: string): Promise<string> {\n if (this.voice) {\n return this.voice;\n }\n try {\n const models = await listOpenRouterSpeechModels('speech', this.fetchImpl);\n const voices = models.find(m => m.id === this.model)?.voices || [];\n return voicesForLanguage(voices, lang)[0] || '';\n } catch {\n return '';\n }\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n const mp3 = MP3_ONLY.some(prefix => this.model.startsWith(prefix));\n if (mp3 && !this.decode) {\n throw new Error(`${this.model} only returns mp3, which needs ffmpeg`);\n }\n const voice = await this.voiceFor(lang);\n const res = await this.client.audio.speech.create({\n model: this.model,\n input: text,\n // `voice` is required by the OpenAI types; an empty one is left out (a model with a default voice)\n ...(voice ? { voice } : {}),\n response_format: mp3 ? 'mp3' : 'pcm',\n } as OpenAI.Audio.SpeechCreateParams);\n const audio = Buffer.from(await res.arrayBuffer());\n if (mp3) {\n return this.decode!(audio);\n }\n return pcmFromResponse(audio, res.headers.get('content-type') || '');\n }\n}\n"]}
1
+ {"version":3,"file":"openrouter.js","sourceRoot":"","sources":["../../../src/lib/voice/openrouter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,gEA8BC;AASD,8CAOC;AASD,0CAiBC;AAhID;;;;;;;;;GASG;AACH,iDAAwC;AACxC,gCAA8D;AAC9D,+BAAiD;AAEjD,qDAAqD;AAErD,kHAAkH;AACrG,QAAA,4BAA4B,GAAG,+BAA+B,CAAC;AAC5E;;;GAGG;AACU,QAAA,4BAA4B,GAAG,8BAA8B,CAAC;AAE3E,sFAAsF;AACtF,MAAM,QAAQ,GAAG,KAAK,CAAC;AAEvB,iFAAiF;AACjF,MAAM,QAAQ,GAAG,CAAC,UAAU,CAAC,CAAC;AAE9B,6CAA6C;AAC7C,MAAM,iBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAazC,SAAS,MAAM,CAAC,MAAc;IAC1B,OAAO,IAAI,gBAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAgB,CAAC,UAAU,CAAC,OAAO,EAAE,cAAc,EAAE,wBAAkB,EAAE,CAAC,CAAC;AACpH,CAAC;AAED,MAAM,UAAU,GAAG,IAAI,GAAG,EAAoE,CAAC;AAE/F;;;;;GAKG;AACH,SAAgB,0BAA0B,CACtC,IAAgC,EAChC,YAA0B,KAAK;IAE/B,MAAM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M,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;QACnD,IAAI,GAAG,EAAE,CAAC;YACN,OAAO,IAAI,CAAC,MAAO,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QACD,OAAO,eAAe,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;IACzE,CAAC;CACJ;AAxDD,sCAwDC","sourcesContent":["/**\n * Speech over OpenRouter: one key for the speech-to-text and text-to-speech models of many vendors (OpenAI,\n * ElevenLabs, Google, Deepgram, Mistral …) behind the OpenAI audio API at https://openrouter.ai/api/v1.\n * Model ids carry the vendor (`openai/whisper-large-v3-turbo`), and the voices depend on the model — the public\n * model list names them (`supported_voices`), so the settings offer exactly the voices of the chosen model.\n *\n * Differences to OpenAI itself: transcription ignores `prompt` (no vocabulary hints), and speech comes back as\n * `pcm` (most models, the default) or `mp3` (MiniMax only). The PCM rate is not part of the API — OpenRouter\n * documents 24 kHz, the rate of OpenAI, Gemini and Azure — so a rate in the content type wins over that default.\n */\nimport OpenAI, { toFile } from 'openai';\nimport { OPENROUTER_HEADERS, PROVIDER_PRESETS } from '../llm';\nimport { pcmToWav, type SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\nimport { voiceFitsLanguage } from './speechLanguage';\n\n/** Speech-to-text model when none is configured: Whisper large v3 turbo, multilingual and the cheapest Whisper */\nexport const DEFAULT_OPENROUTER_STT_MODEL = 'openai/whisper-large-v3-turbo';\n/**\n * Text-to-speech model when none is configured: multilingual, PCM (no decoder needed) and fast — in a test about\n * 0.8 s for a sentence where Gemini TTS took 2.5 s, which a spoken answer waits for.\n */\nexport const DEFAULT_OPENROUTER_TTS_MODEL = 'elevenlabs/eleven-flash-v2.5';\n\n/** Rate of the PCM OpenRouter returns when the content type does not say otherwise */\nconst PCM_RATE = 24000;\n\n/** Vendors whose speech models only return mp3 (they answer `pcm` with a 400) */\nconst MP3_ONLY = ['minimax/'];\n\n/** How long the public model list is kept */\nconst MODEL_LIST_TTL_MS = 60 * 60 * 1000;\n\n/** Decode compressed audio (mp3) to mono 16-bit PCM — ffmpeg in the adapter */\nexport type AudioDecoder = (audio: Buffer) => Promise<TtsResult>;\n\n/** A speech model of OpenRouter */\nexport interface OpenRouterSpeechModel {\n id: string;\n name: string;\n /** Voices of a text-to-speech model, empty when the model names none */\n voices: string[];\n}\n\nfunction client(apiKey: string): OpenAI {\n return new OpenAI({ apiKey, baseURL: PROVIDER_PRESETS.openrouter.baseUrl, defaultHeaders: OPENROUTER_HEADERS });\n}\n\nconst modelLists = new Map<string, { at: number; models: Promise<OpenRouterSpeechModel[]> }>();\n\n/**\n * The speech models of OpenRouter. The list is public (no key), cached for an hour; a failed request is not kept.\n *\n * @param kind `speech` = text-to-speech, `transcription` = speech-to-text\n * @param fetchImpl fetch (tests)\n */\nexport function listOpenRouterSpeechModels(\n kind: 'speech' | 'transcription',\n fetchImpl: typeof fetch = fetch,\n): Promise<OpenRouterSpeechModel[]> {\n const cached = modelLists.get(kind);\n if (cached && Date.now() - cached.at < MODEL_LIST_TTL_MS) {\n return cached.models;\n }\n const models = (async () => {\n const res = await fetchImpl(`${PROVIDER_PRESETS.openrouter.baseUrl}/models?output_modalities=${kind}`, {\n headers: OPENROUTER_HEADERS,\n signal: AbortSignal.timeout(15000),\n });\n if (!res.ok) {\n throw new Error(`OpenRouter model list: HTTP ${res.status}`);\n }\n const body = (await res.json()) as { data?: { id?: unknown; name?: unknown; supported_voices?: unknown }[] };\n return (body.data || [])\n .filter(m => typeof m.id === 'string' && m.id)\n .map(m => ({\n id: m.id as string,\n name: typeof m.name === 'string' ? m.name : (m.id as string),\n voices: Array.isArray(m.supported_voices)\n ? m.supported_voices.filter((v): v is string => typeof v === 'string')\n : [],\n }));\n })();\n modelLists.set(kind, { at: Date.now(), models });\n models.catch(() => modelLists.delete(kind));\n return models;\n}\n\n/**\n * The voices of a text-to-speech model. Voices named after a locale (`de-DE-Klaus:MAI-Voice-2`) are narrowed to\n * the language, if that leaves any; other names (`Kore`, `george`) say nothing about the language.\n *\n * @param voices the voices of the model\n * @param language ISO-639-1 language ('' = all)\n */\nexport function voicesForLanguage(voices: string[], language: string): string[] {\n const lang = (language || '').split('-')[0].toLowerCase();\n if (!lang) {\n return voices;\n }\n const matching = voices.filter(v => new RegExp(`^${lang}[-_][A-Z]{2}\\\\b`).test(v));\n return matching.length ? matching : voices;\n}\n\n/**\n * Raw PCM out of a speech response: WAV is unwrapped, the rate comes from the content type (`audio/pcm;rate=…`)\n * or is the documented 24 kHz.\n *\n * @param audio the response body\n * @param contentType the content type of the response\n */\nexport function pcmFromResponse(audio: Buffer, contentType: string): TtsResult {\n if (audio.length > 44 && audio.toString('latin1', 0, 4) === 'RIFF' && audio.toString('latin1', 8, 12) === 'WAVE') {\n const sampleRate = audio.readUInt32LE(24);\n // the data chunk is not always right after the 16-byte fmt chunk\n let offset = 12;\n while (offset + 8 <= audio.length) {\n const id = audio.toString('latin1', offset, offset + 4);\n const size = audio.readUInt32LE(offset + 4);\n if (id === 'data') {\n return { pcm: audio.subarray(offset + 8, Math.min(audio.length, offset + 8 + size)), sampleRate };\n }\n offset += 8 + size + (size % 2);\n }\n return { pcm: audio.subarray(44), sampleRate };\n }\n const rate = /(?:^|[;\\s])(?:rate|sample_?rate)=(\\d+)/i.exec(contentType || '');\n return { pcm: audio, sampleRate: rate ? Number(rate[1]) : PCM_RATE };\n}\n\n/** Speech-to-text over OpenRouter (OpenAI-compatible multipart upload) */\nexport class OpenRouterStt implements SttEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n\n constructor(apiKey: string, model = '') {\n this.client = client(apiKey);\n this.model = model || DEFAULT_OPENROUTER_STT_MODEL;\n }\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {\n const file = await toFile(pcmToWav(pcm, sampleRate), 'audio.wav', { type: 'audio/wav' });\n // no vocabulary hints: OpenRouter accepts `prompt`, but ignores it\n const res = await this.client.audio.transcriptions.create({\n file,\n model: this.model,\n language: (lang || '').split('-')[0] || undefined,\n });\n return (res.text || '').trim();\n }\n}\n\n/** Text-to-speech over OpenRouter */\nexport class OpenRouterTts implements TtsEngine {\n private readonly client: OpenAI;\n private readonly model: string;\n private readonly voice: string;\n private readonly decode?: AudioDecoder;\n private readonly fetchImpl?: typeof fetch;\n\n /**\n * @param apiKey OpenRouter key\n * @param model model id ('' = {@link DEFAULT_OPENROUTER_TTS_MODEL})\n * @param voice voice of the model ('' = the first voice of the model for the language)\n * @param decode decoder for the models that only return mp3\n * @param fetchImpl fetch for the model list (tests)\n */\n constructor(apiKey: string, model = '', voice = '', decode?: AudioDecoder, fetchImpl?: typeof fetch) {\n this.client = client(apiKey);\n this.model = model || DEFAULT_OPENROUTER_TTS_MODEL;\n this.voice = voice;\n this.decode = decode;\n this.fetchImpl = fetchImpl;\n }\n\n /** The configured voice, or the first one the model offers for the language — most models need a voice */\n private async voiceFor(lang: string): Promise<string> {\n // a locale voice (de-DE-Klaus:MAI-Voice-2) only for its language; Kore, george … speak every language\n if (this.voice && voiceFitsLanguage(this.voice, lang)) {\n return this.voice;\n }\n try {\n const models = await listOpenRouterSpeechModels('speech', this.fetchImpl);\n const voices = models.find(m => m.id === this.model)?.voices || [];\n return voicesForLanguage(voices, lang)[0] || this.voice;\n } catch {\n return this.voice;\n }\n }\n\n async synthesize(text: string, lang: string): Promise<TtsResult> {\n const mp3 = MP3_ONLY.some(prefix => this.model.startsWith(prefix));\n if (mp3 && !this.decode) {\n throw new Error(`${this.model} only returns mp3, which needs ffmpeg`);\n }\n const voice = await this.voiceFor(lang);\n const res = await this.client.audio.speech.create({\n model: this.model,\n input: text,\n // `voice` is required by the OpenAI types; an empty one is left out (a model with a default voice)\n ...(voice ? { voice } : {}),\n response_format: mp3 ? 'mp3' : 'pcm',\n } as OpenAI.Audio.SpeechCreateParams);\n const audio = Buffer.from(await res.arrayBuffer());\n if (mp3) {\n return this.decode!(audio);\n }\n return pcmFromResponse(audio, res.headers.get('content-type') || '');\n }\n}\n"]}
@@ -135,7 +135,12 @@ class PiperTts {
135
135
  }
136
136
  voiceFor(lang) {
137
137
  const iso = (lang || 'en').split('-')[0].toLowerCase();
138
- return this.voice || DEFAULT_VOICE[iso] || DEFAULT_VOICE.en;
138
+ // The chosen voice speaks one language (de_DE-thorsten-medium: German). An answer in another language gets
139
+ // the default voice of that language; a German voice would spell Cyrillic letters one by one.
140
+ if (this.voice && this.voice.split('_')[0].toLowerCase() === iso) {
141
+ return this.voice;
142
+ }
143
+ return DEFAULT_VOICE[iso] || this.voice || DEFAULT_VOICE.en;
139
144
  }
140
145
  async ensureVoice(voice) {
141
146
  const dir = path.join(this.dataDir, 'piper-voices');
@@ -1 +1 @@
1
- {"version":3,"file":"piper.js","sourceRoot":"","sources":["../../../src/lib/voice/piper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6JA,0CAEC;AA/JD;;;;;;GAMG;AACH,4CAA8B;AAC9B,gDAAkC;AAClC,2DAA2C;AAC3C,yCAA4E;AAG5E,MAAM,aAAa,GAAG,iEAAiE,CAAC;AAExF,mDAAmD;AACnD,SAAS,UAAU;IACf,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IACvB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;YAChB,OAAO,4BAA4B,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,KAAK,KAAK,EAAE,CAAC;YACd,OAAO,2BAA2B,CAAC;QACvC,CAAC;QACD,OAAO,2BAA2B,CAAC;IACvC,CAAC;IACD,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;QACjB,OAAO,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC,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OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;YACxE,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;gBACrB,IAAI,IAAI,KAAK,CAAC,EAAE,CAAC;oBACb,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;AA7FD,4BA6FC;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 return this.voice || DEFAULT_VOICE[iso] || 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":["../../../src/lib/voice/piper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkKA,0CAEC;AApKD;;;;;;GAMG;AACH,4CAA8B;AAC9B,gDAAkC;AAClC,2DAA2C;AAC3C,yCAA4E;AAG5E,MAAM,aAAa,GAAG,iEAAiE,CAAC;AAExF,mDAAmD;AACnD,SAAS,UAAU;IACf,MAAM,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC;IAC3B,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IACvB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;YAChB,OAAO,4BAA4B,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,KAAK,KAAK,EAAE,CAAC;YACd,OAAO,2BAA2B,CAAC;QACvC,CAAC;QACD,OAAO,2BAA2B,CAAC;IACvC,CAAC;IACD,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;QACjB,OAAO,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC,CAAC,wBAAwB,CAAC;IACnF,CAAC;IACD,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QAChB,OAAO,yBAAyB,CAAC;IACrC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED,0EAA0E;AAC1E,MAAM,aAAa,GAA2B;IAC1C,EAAE,EAAE,uBAAuB;IAC3B,EAAE,EAAE,qBAAqB;IACzB,EAAE,EAAE,oBAAoB;IACxB,EAAE,EAAE,oBAAoB;IACxB,EAAE,EAAE,sBAAsB;IAC1B,EAAE,EAAE,uBAAuB;IAC3B,EAAE,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AM,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;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"]}
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VoicePerLanguage = exports.LanguageTts = exports.AnswerLanguages = void 0;
4
+ exports.baseLanguage = baseLanguage;
5
+ exports.scriptLanguage = scriptLanguage;
6
+ exports.speechLanguage = speechLanguage;
7
+ exports.questionLanguage = questionLanguage;
8
+ exports.voiceFitsLanguage = voiceFitsLanguage;
9
+ exports.parseVoiceTable = parseVoiceTable;
10
+ /** Script of the languages that are not written in Latin letters; everything else is Latin. */
11
+ const SCRIPT_OF = {
12
+ ru: 'cyrillic',
13
+ uk: 'cyrillic',
14
+ be: 'cyrillic',
15
+ bg: 'cyrillic',
16
+ sr: 'cyrillic',
17
+ mk: 'cyrillic',
18
+ kk: 'cyrillic',
19
+ el: 'greek',
20
+ zh: 'cjk',
21
+ ja: 'cjk',
22
+ ko: 'hangul',
23
+ ar: 'arabic',
24
+ fa: 'arabic',
25
+ he: 'hebrew',
26
+ };
27
+ const LETTERS = [
28
+ ['latin', /[a-zÀ-ɏ]/gi],
29
+ ['cyrillic', /[Ѐ-ӿ]/g],
30
+ ['greek', /[Ͱ-Ͽ]/g],
31
+ ['cjk', /[぀-ヿ㐀-鿿]/g],
32
+ ['hangul', /[가-힯ᄀ-ᇿ]/g],
33
+ ['arabic', /[؀-ۿ]/g],
34
+ ['hebrew', /[֐-׿]/g],
35
+ ];
36
+ /** Fewer letters than this say nothing about the language ("OK", "5 °C"). */
37
+ const MIN_LETTERS = 3;
38
+ /** Letters only Ukrainian has among the Cyrillic languages. */
39
+ const UKRAINIAN = /[ґєії]/i;
40
+ /** Kana: Japanese, not Chinese. */
41
+ const KANA = /[぀-ヿ]/;
42
+ /** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */
43
+ function baseLanguage(lang) {
44
+ return String(lang || '')
45
+ .trim()
46
+ .split(/[-_]/)[0]
47
+ .toLowerCase();
48
+ }
49
+ function scriptOf(lang) {
50
+ return SCRIPT_OF[baseLanguage(lang)] || 'latin';
51
+ }
52
+ /** The script most letters of the text are in; '' for too few letters. */
53
+ function dominantScript(text) {
54
+ let best = '';
55
+ let most = 0;
56
+ let total = 0;
57
+ for (const [script, re] of LETTERS) {
58
+ const count = (text.match(re) || []).length;
59
+ total += count;
60
+ if (count > most) {
61
+ best = script;
62
+ most = count;
63
+ }
64
+ }
65
+ return total >= MIN_LETTERS ? best : '';
66
+ }
67
+ /**
68
+ * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for
69
+ * too few letters.
70
+ */
71
+ function scriptLanguage(text) {
72
+ const script = dominantScript(String(text || ''));
73
+ switch (script) {
74
+ case 'cyrillic':
75
+ return UKRAINIAN.test(text) ? 'uk' : 'ru';
76
+ case 'greek':
77
+ return 'el';
78
+ case 'cjk':
79
+ return KANA.test(text) ? 'ja' : 'zh';
80
+ case 'hangul':
81
+ return 'ko';
82
+ case 'arabic':
83
+ return 'ar';
84
+ case 'hebrew':
85
+ return 'he';
86
+ default:
87
+ return '';
88
+ }
89
+ }
90
+ /**
91
+ * The language to speak a text in.
92
+ *
93
+ * @param text what is spoken
94
+ * @param configured the language the caller asked for (the satellite's language)
95
+ * @param reported the language the answering tier reported ('' = none)
96
+ * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it
97
+ */
98
+ function speechLanguage(text, configured, reported) {
99
+ const script = dominantScript(String(text || ''));
100
+ const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';
101
+ // a report is believed unless the letters contradict it (a "de" mark on a Cyrillic answer)
102
+ if (said && (!script || scriptOf(said) === script)) {
103
+ // the configured language in its own form ('de-DE'): same voice, same cache entry
104
+ return said === baseLanguage(configured) ? configured : said;
105
+ }
106
+ if (!script) {
107
+ return configured;
108
+ }
109
+ const byLetters = scriptLanguage(text);
110
+ if (scriptOf(configured) === script) {
111
+ // the letters fit the configured language; only Ukrainian letters say more than "Cyrillic"
112
+ return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;
113
+ }
114
+ // Latin letters while the satellite speaks Russian: English is the best guess
115
+ return byLetters || 'en';
116
+ }
117
+ /**
118
+ * Words that say a Latin-script question is English or German. Only words of one of the two: "in", "an", "die",
119
+ * "was", "will", "so", "man" are both and say nothing. Kept to what short spoken commands and questions use.
120
+ */
121
+ const FUNCTION_WORDS = {
122
+ en: new Set(("the what what's whats is are it it's its how turn switch please light lights time me my of to and you your " +
123
+ 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +
124
+ 'does do can could would there all up down timer alarm minutes hours at for be play stop').split(' ')),
125
+ de: new Set(('der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +
126
+ 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +
127
+ 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +
128
+ 'kannst spiele spiel').split(' ')),
129
+ };
130
+ /** Function words of `lang` in the words of a text; 0 for a language without a list. */
131
+ function functionWords(words, lang) {
132
+ const list = FUNCTION_WORDS[lang];
133
+ return list ? words.filter(w => list.has(w)).length : 0;
134
+ }
135
+ /**
136
+ * The language a question is asked in, for the fixed answers of the rule NLU ("скажи, сколько сейчас времени" on a
137
+ * German satellite was answered in German). Another script than the configured language's tells it by the letters
138
+ * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with
139
+ * at least two of them and more than twice as many as of the configured language, so a German command with an
140
+ * English device name stays German and a French question on a French system is not taken for German.
141
+ *
142
+ * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it
143
+ */
144
+ function questionLanguage(text, configured) {
145
+ const question = String(text || '');
146
+ const script = dominantScript(question);
147
+ if (!script) {
148
+ return configured;
149
+ }
150
+ if (script !== 'latin') {
151
+ return speechLanguage(question, configured);
152
+ }
153
+ const words = question.toLowerCase().match(/[\p{L}']+/gu) || [];
154
+ const base = baseLanguage(configured);
155
+ let best = '';
156
+ let most = 0;
157
+ for (const lang of ['en', 'de']) {
158
+ const hits = functionWords(words, lang);
159
+ if (hits > most) {
160
+ best = lang;
161
+ most = hits;
162
+ }
163
+ }
164
+ if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {
165
+ return configured;
166
+ }
167
+ return best;
168
+ }
169
+ /** How many answers {@link AnswerLanguages} remembers. */
170
+ const KEPT_LANGUAGES = 50;
171
+ /**
172
+ * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to
173
+ * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):
174
+ * the assistant takes them out before speaking.
175
+ */
176
+ class AnswerLanguages {
177
+ byText = new Map();
178
+ static key(text) {
179
+ return String(text || '')
180
+ .replace(/\[\[[A-Z]+\]\]/gi, ' ')
181
+ .replace(/\s+/g, ' ')
182
+ .trim();
183
+ }
184
+ /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */
185
+ remember(text, language) {
186
+ const lang = String(language || '')
187
+ .trim()
188
+ .toLowerCase();
189
+ const key = AnswerLanguages.key(text);
190
+ if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {
191
+ return;
192
+ }
193
+ this.byText.delete(key);
194
+ this.byText.set(key, lang);
195
+ if (this.byText.size > KEPT_LANGUAGES) {
196
+ this.byText.delete(this.byText.keys().next().value);
197
+ }
198
+ }
199
+ /** The language remembered for this answer, '' for none. */
200
+ languageOf(text) {
201
+ return this.byText.get(AnswerLanguages.key(text)) || '';
202
+ }
203
+ }
204
+ exports.AnswerLanguages = AnswerLanguages;
205
+ /**
206
+ * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,
207
+ * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a
208
+ * multilingual Azure voice can speak every language.
209
+ */
210
+ function voiceFitsLanguage(voice, lang) {
211
+ const iso = baseLanguage(lang);
212
+ const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());
213
+ if (!iso || !locale || /multilingual/i.test(voice)) {
214
+ return true;
215
+ }
216
+ return locale[1] === iso;
217
+ }
218
+ /** Parse the config table "voice per language" into ISO code → voice; rows without both are skipped. */
219
+ function parseVoiceTable(rows) {
220
+ const table = {};
221
+ if (!Array.isArray(rows)) {
222
+ return table;
223
+ }
224
+ for (const row of rows) {
225
+ const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');
226
+ const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';
227
+ if (lang && voice) {
228
+ table[lang] = voice;
229
+ }
230
+ }
231
+ return table;
232
+ }
233
+ /**
234
+ * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the
235
+ * language the answering tier gave for exactly this text.
236
+ */
237
+ class LanguageTts {
238
+ inner;
239
+ reported;
240
+ log;
241
+ constructor(inner, reported, log) {
242
+ this.inner = inner;
243
+ this.reported = reported;
244
+ this.log = log;
245
+ }
246
+ /** The language `text` is spoken in when the caller asks for `lang`. */
247
+ languageFor(text, lang) {
248
+ const spoken = speechLanguage(text, lang, this.reported?.(text));
249
+ if (spoken !== lang) {
250
+ this.log.debug(`TTS in '${spoken}' instead of '${lang}': "${String(text).slice(0, 40)}"`);
251
+ }
252
+ return spoken;
253
+ }
254
+ synthesize(text, lang) {
255
+ return this.inner.synthesize(text, this.languageFor(text, lang));
256
+ }
257
+ synthesizeSsml(ssml, lang) {
258
+ const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);
259
+ return this.inner.synthesizeSsml
260
+ ? this.inner.synthesizeSsml(ssml, spoken)
261
+ : this.inner.synthesize(ssml, spoken);
262
+ }
263
+ prepare(lang) {
264
+ return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();
265
+ }
266
+ warm(phrases, lang) {
267
+ return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);
268
+ }
269
+ }
270
+ exports.LanguageTts = LanguageTts;
271
+ /**
272
+ * The voices of the table "voice per language": one engine per row, the default engine for every other language.
273
+ * Each engine has its own cache (the directory is per voice).
274
+ */
275
+ class VoicePerLanguage {
276
+ fallback;
277
+ byLanguage;
278
+ constructor(fallback, byLanguage) {
279
+ this.fallback = fallback;
280
+ this.byLanguage = byLanguage;
281
+ }
282
+ engineFor(lang) {
283
+ return this.byLanguage[baseLanguage(lang)] || this.fallback;
284
+ }
285
+ synthesize(text, lang) {
286
+ return this.engineFor(lang).synthesize(text, lang);
287
+ }
288
+ synthesizeSsml(ssml, lang) {
289
+ const engine = this.engineFor(lang);
290
+ return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);
291
+ }
292
+ /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */
293
+ async prepare(lang) {
294
+ await this.engineFor(lang).prepare?.(lang);
295
+ for (const [code, engine] of Object.entries(this.byLanguage)) {
296
+ if (code !== baseLanguage(lang)) {
297
+ await engine.prepare?.(code);
298
+ }
299
+ }
300
+ }
301
+ warm(phrases, lang) {
302
+ return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);
303
+ }
304
+ }
305
+ exports.VoicePerLanguage = VoicePerLanguage;
306
+ //# sourceMappingURL=speechLanguage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speechLanguage.js","sourceRoot":"","sources":["../../../src/lib/voice/speechLanguage.ts"],"names":[],"mappings":";;;AAuDA,oCAKC;AA0BD,wCAkBC;AAUD,wCAkBC;AAuCD,4CAwBC;AA+CD,8CAOC;AAGD,0CAaC;AAvPD,+FAA+F;AAC/F,MAAM,SAAS,GAA2B;IACtC,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAA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,OAAiB,EAAE,IAAY;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC;CACJ;AAhCD,4CAgCC","sourcesContent":["/**\n * The language an answer is spoken in. The transports hand the TTS the language the satellite listens in, but an\n * answer can be in another one (a question asked in Russian on a German satellite, pi-agent answering in the language\n * of the question). A German voice reads Cyrillic letter by letter (\"kyrillisch a, kyrillisch b …\"), so the TTS\n * takes the language of the text:\n *\n * 1. the language the answering tier reported (pi-agent ≥ 0.10.1 returns `language`), unless the letters contradict it;\n * 2. otherwise the letters: a text in another script than the configured language (Cyrillic, Greek, CJK …) is spoken\n * in the language of that script. Latin letters do not tell German from English: then the configured language\n * stays, unless it is itself written in another script (a Russian satellite answering in Latin letters → English).\n *\n * {@link LanguageTts} applies this in front of every TTS engine; {@link VoicePerLanguage} picks the voice of the\n * table \"voice per language\" for it.\n */\nimport type { TtsEngine, TtsResult } from './tts';\n\ntype Script = 'latin' | 'cyrillic' | 'greek' | 'cjk' | 'hangul' | 'arabic' | 'hebrew';\n\n/** Script of the languages that are not written in Latin letters; everything else is Latin. */\nconst SCRIPT_OF: Record<string, Script> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n el: 'greek',\n zh: 'cjk',\n ja: 'cjk',\n ko: 'hangul',\n ar: 'arabic',\n fa: 'arabic',\n he: 'hebrew',\n};\n\nconst LETTERS: [Script, RegExp][] = [\n ['latin', /[a-zÀ-ɏ]/gi],\n ['cyrillic', /[Ѐ-ӿ]/g],\n ['greek', /[Ͱ-Ͽ]/g],\n ['cjk', /[぀-ヿ㐀-鿿]/g],\n ['hangul', /[가-힯ᄀ-ᇿ]/g],\n ['arabic', /[؀-ۿ]/g],\n ['hebrew', /[֐-׿]/g],\n];\n\n/** Fewer letters than this say nothing about the language (\"OK\", \"5 °C\"). */\nconst MIN_LETTERS = 3;\n\n/** Letters only Ukrainian has among the Cyrillic languages. */\nconst UKRAINIAN = /[ґєії]/i;\n/** Kana: Japanese, not Chinese. */\nconst KANA = /[぀-ヿ]/;\n\n/** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */\nexport function baseLanguage(lang: string | undefined): string {\n return String(lang || '')\n .trim()\n .split(/[-_]/)[0]\n .toLowerCase();\n}\n\nfunction scriptOf(lang: string): Script {\n return SCRIPT_OF[baseLanguage(lang)] || 'latin';\n}\n\n/** The script most letters of the text are in; '' for too few letters. */\nfunction dominantScript(text: string): Script | '' {\n let best: Script | '' = '';\n let most = 0;\n let total = 0;\n for (const [script, re] of LETTERS) {\n const count = (text.match(re) || []).length;\n total += count;\n if (count > most) {\n best = script;\n most = count;\n }\n }\n return total >= MIN_LETTERS ? best : '';\n}\n\n/**\n * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for\n * too few letters.\n */\nexport function scriptLanguage(text: string): string {\n const script = dominantScript(String(text || ''));\n switch (script) {\n case 'cyrillic':\n return UKRAINIAN.test(text) ? 'uk' : 'ru';\n case 'greek':\n return 'el';\n case 'cjk':\n return KANA.test(text) ? 'ja' : 'zh';\n case 'hangul':\n return 'ko';\n case 'arabic':\n return 'ar';\n case 'hebrew':\n return 'he';\n default:\n return '';\n }\n}\n\n/**\n * The language to speak a text in.\n *\n * @param text what is spoken\n * @param configured the language the caller asked for (the satellite's language)\n * @param reported the language the answering tier reported ('' = none)\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function speechLanguage(text: string, configured: string, reported?: string): string {\n const script = dominantScript(String(text || ''));\n const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';\n // a report is believed unless the letters contradict it (a \"de\" mark on a Cyrillic answer)\n if (said && (!script || scriptOf(said) === script)) {\n // the configured language in its own form ('de-DE'): same voice, same cache entry\n return said === baseLanguage(configured) ? configured : said;\n }\n if (!script) {\n return configured;\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Words that say a Latin-script question is English or German. Only words of one of the two: \"in\", \"an\", \"die\",\n * \"was\", \"will\", \"so\", \"man\" are both and say nothing. Kept to what short spoken commands and questions use.\n */\nconst FUNCTION_WORDS: Record<'en' | 'de', ReadonlySet<string>> = {\n en: new Set(\n (\n \"the what what's whats is are it it's its how turn switch please light lights time me my of to and you your \" +\n 'on off set tell which where when who open close this that temperature weather today tomorrow now much many ' +\n 'does do can could would there all up down timer alarm minutes hours at for be play stop'\n ).split(' '),\n ),\n de: new Set(\n (\n 'der den dem des das ist wie wer wo welche welcher welches schalte schalt mach mache ein eine einen aus bitte ' +\n 'licht spät uhr und im es mir mein meine ich du sind auf zu wieviel viel wetter heute morgen jetzt gibt ' +\n 'alle stelle stell setze öffne schließe temperatur minuten stunden wecker um nach noch lange sag sage mal ' +\n 'kannst spiele spiel'\n ).split(' '),\n ),\n};\n\n/** Function words of `lang` in the words of a text; 0 for a language without a list. */\nfunction functionWords(words: string[], lang: string): number {\n const list = FUNCTION_WORDS[lang as 'en' | 'de'];\n return list ? words.filter(w => list.has(w)).length : 0;\n}\n\n/**\n * The language a question is asked in, for the fixed answers of the rule NLU (\"скажи, сколько сейчас времени\" on a\n * German satellite was answered in German). Another script than the configured language's tells it by the letters\n * (like {@link speechLanguage}); for Latin letters English and German are told apart by function words — only with\n * at least two of them and more than twice as many as of the configured language, so a German command with an\n * English device name stays German and a French question on a French system is not taken for German.\n *\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function questionLanguage(text: string, configured: string): string {\n const question = String(text || '');\n const script = dominantScript(question);\n if (!script) {\n return configured;\n }\n if (script !== 'latin') {\n return speechLanguage(question, configured);\n }\n const words = question.toLowerCase().match(/[\\p{L}']+/gu) || [];\n const base = baseLanguage(configured);\n let best = '';\n let most = 0;\n for (const lang of ['en', 'de']) {\n const hits = functionWords(words, lang);\n if (hits > most) {\n best = lang;\n most = hits;\n }\n }\n if (!best || best === base || most < 2 || most <= 2 * functionWords(words, base)) {\n return configured;\n }\n return best;\n}\n\n/** How many answers {@link AnswerLanguages} remembers. */\nconst KEPT_LANGUAGES = 50;\n\n/**\n * The language of recent answers, by their text. An answer travels as plain text through the tiers and transports to\n * the TTS; this finds its language again there. The key is the text without control markers ([[LISTEN]], [[DONE]]):\n * the assistant takes them out before speaking.\n */\nexport class AnswerLanguages {\n private readonly byText = new Map<string, string>();\n\n private static key(text: string): string {\n return String(text || '')\n .replace(/\\[\\[[A-Z]+\\]\\]/gi, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n\n /** Remember the language of an answer; anything but an ISO code (`ru`, `en-us`) is ignored. */\n remember(text: string, language: string): void {\n const lang = String(language || '')\n .trim()\n .toLowerCase();\n const key = AnswerLanguages.key(text);\n if (!key || !/^[a-z]{2,3}(-[a-z]{2,4})?$/.test(lang)) {\n return;\n }\n this.byText.delete(key);\n this.byText.set(key, lang);\n if (this.byText.size > KEPT_LANGUAGES) {\n this.byText.delete(this.byText.keys().next().value as string);\n }\n }\n\n /** The language remembered for this answer, '' for none. */\n languageOf(text: string): string {\n return this.byText.get(AnswerLanguages.key(text)) || '';\n }\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice; rows without both are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, string> {\n const table: Record<string, string> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown }[]) {\n const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n if (lang && voice) {\n table[lang] = voice;\n }\n }\n return table;\n}\n\n/** Log of the TTS layer. */\ninterface Logger {\n debug(msg: string): void;\n}\n\n/**\n * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the\n * language the answering tier gave for exactly this text.\n */\nexport class LanguageTts implements TtsEngine {\n constructor(\n private readonly inner: TtsEngine,\n private readonly reported: ((text: string) => string | undefined) | undefined,\n private readonly log: Logger,\n ) {}\n\n /** The language `text` is spoken in when the caller asks for `lang`. */\n languageFor(text: string, lang: string): string {\n const spoken = speechLanguage(text, lang, this.reported?.(text));\n if (spoken !== lang) {\n this.log.debug(`TTS in '${spoken}' instead of '${lang}': \"${String(text).slice(0, 40)}\"`);\n }\n return spoken;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.inner.synthesize(text, this.languageFor(text, lang));\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);\n return this.inner.synthesizeSsml\n ? this.inner.synthesizeSsml(ssml, spoken)\n : this.inner.synthesize(ssml, spoken);\n }\n\n prepare(lang: string): Promise<void> {\n return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);\n }\n}\n\n/**\n * The voices of the table \"voice per language\": one engine per row, the default engine for every other language.\n * Each engine has its own cache (the directory is per voice).\n */\nexport class VoicePerLanguage implements TtsEngine {\n constructor(\n private readonly fallback: TtsEngine,\n private readonly byLanguage: Record<string, TtsEngine>,\n ) {}\n\n private engineFor(lang: string): TtsEngine {\n return this.byLanguage[baseLanguage(lang)] || this.fallback;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.engineFor(lang).synthesize(text, lang);\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const engine = this.engineFor(lang);\n return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);\n }\n\n /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */\n async prepare(lang: string): Promise<void> {\n await this.engineFor(lang).prepare?.(lang);\n for (const [code, engine] of Object.entries(this.byLanguage)) {\n if (code !== baseLanguage(lang)) {\n await engine.prepare?.(code);\n }\n }\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}