iobroker.assistant 1.6.0 → 1.7.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.
@@ -1 +1 @@
1
- {"version":3,"file":"engines.js","sourceRoot":"","sources":["../../../src/lib/voice/engines.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,0CAYC;AA+BD,0CAeC;AAyDD,gCAmBC;AAGD,sCAKC;AAGD,sCAEC;AA9PD;;;;GAIG;AACH,+BAAkD;AAClD,+BAAoE;AACpE,mCAA8D;AAC9D,+BAAuE;AACvE,iCAAiD;AACjD,yCAA6D;AAC7D,mCAAoD;AACpD,6CAOsB;AACtB,gDAAkC;AAElC,yCAAuC;AACvC,yCAAwE;AACxE,iCAAqC;AA2DrC,SAAS,YAAY,CAAC,KAAuB;IACzC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACxE,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,KAAuB;IACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,SAAS,aAAa,CAAC,KAAuB;IAC1C,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACtD,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAuB;IAC9C,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAA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AAM,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;QACvF,CAAC;QACD;YACI,OAAO,aAAa,CAAC;IAC7B,CAAC;AACL,CAAC;AAED,kHAAkH;AAC3G,KAAK,UAAU,aAAa,CAAC,QAAwB,EAAE,QAAgB;IAC1E,IAAI,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC5B,OAAO,CAAC,MAAM,IAAA,uCAA0B,EAAC,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,IAAA,qBAAc,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/D,CAAC;AAED,8FAA8F;AACvF,KAAK,UAAU,aAAa,CAAC,QAAwB;IACxD,OAAO,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,MAAM,IAAA,uCAA0B,EAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxG,CAAC","sourcesContent":["/**\n * Factory that builds the configured STT/TTS engine. Cloud engines (OpenAI/Azure/AWS) use resolved\n * credentials; local engines (Vosk/Piper) download their models on demand into the data dir.\n * Adding a provider = one new engine class + one `case` here.\n */\nimport { OpenAiStt, type SttEngine } from './stt';\nimport { OpenAiTts, type OpenAiVoice, type TtsEngine } from './tts';\nimport { AzureStt, AzureTts, listAzureVoices } from './azure';\nimport { AwsStt, AwsTts, listPollyVoices, type AwsCreds } from './aws';\nimport { VoskStt, listVoskModels } from './vosk';\nimport { ParakeetStt, type MessageSender } from './parakeet';\nimport { PiperTts, listPiperVoices } from './piper';\nimport {\n OpenRouterStt,\n OpenRouterTts,\n listOpenRouterSpeechModels,\n voicesForLanguage,\n DEFAULT_OPENROUTER_TTS_MODEL,\n type AudioDecoder,\n} from './openrouter';\nimport * as path from 'node:path';\n\nimport { CachedTts } from './ttsCache';\nimport { FallbackStt, FallbackTts, type NamedEngine } from './fallback';\nimport { isoToLocale } from './lang';\nimport type { VoiceLogger } from './download';\n\nexport type SpeechProvider = 'openai' | 'openrouter' | 'azure' | 'aws' | 'vosk' | 'parakeet' | 'piper';\n\n/** All speech credentials, resolved from config (or the central credential store). */\nexport interface VoiceCredentials {\n openaiKey: string;\n openrouterKey: string;\n azureKey: string;\n azureRegion: string;\n aws: AwsCreds;\n}\n\n/** Provider-specific voice ids (each provider names voices differently). */\nexport interface VoiceNames {\n openai: string; // alloy/echo/…\n azure: string; // e.g. de-DE-KatjaNeural\n aws: string; // e.g. Vicki\n piper: string; // e.g. de_DE-thorsten-medium\n openrouter: string; // depends on the model, e.g. Kore, george\n}\n\n/** Everything the factory needs to build any engine. */\nexport interface EngineContext {\n creds: VoiceCredentials;\n voices: VoiceNames;\n /** Optional second engine, used when the primary one fails ('' = none). */\n sttFallback?: SpeechProvider | '';\n ttsFallback?: SpeechProvider | '';\n /** Writable instance data dir (for the local engines' downloads). */\n dataDir: string;\n log: VoiceLogger;\n /** Local model overrides ('' → default per language). */\n voskModel: string;\n /** OpenAI STT model ('' → 'whisper-1'; e.g. 'gpt-4o-transcribe'). */\n sttModel: string;\n /**\n * OpenAI-compatible transcription server instead of OpenAI ('' = OpenAI), e.g. a local whisper container.\n * It gets `sttServerKey`, never the OpenAI key — that one is only for OpenAI.\n */\n sttBaseUrl?: string;\n /** Key for `sttBaseUrl` ('' = the server needs none). */\n sttServerKey?: string;\n /** OpenAI TTS model ('' → 'tts-1'; e.g. 'gpt-4o-mini-tts'). */\n ttsModel: string;\n /** OpenRouter models ('' → the defaults of openrouter.ts) */\n openrouterSttModel: string;\n openrouterTtsModel: string;\n /** Decoder for compressed speech (OpenRouter models that only return mp3); absent → those models fail */\n decodeAudio?: AudioDecoder;\n /** Longest text that is spoken, in characters; longer ones are cut at a sentence end. 0 = no limit, absent = 400. */\n ttsMaxChars?: number;\n /** Instance of ioBroker.ai-parakeet for the provider `parakeet`, e.g. 'ai-parakeet.0'. */\n parakeetInstance?: string;\n /** Message bus to other instances (ai-parakeet); absent → `parakeet` cannot be used. */\n sendMessage?: MessageSender;\n}\n\nfunction requireAzure(creds: VoiceCredentials): void {\n if (!creds.azureKey || !creds.azureRegion) {\n throw new Error('Azure speech needs a subscription key and region');\n }\n}\n\nfunction requireAws(creds: VoiceCredentials): void {\n if (!creds.aws.accessKeyId || !creds.aws.secretAccessKey || !creds.aws.region) {\n throw new Error('AWS speech needs an access key id, secret access key and region');\n }\n}\n\nfunction requireOpenAi(creds: VoiceCredentials): void {\n if (!creds.openaiKey) {\n throw new Error('OpenAI speech needs an API key');\n }\n}\n\nfunction requireOpenRouter(creds: VoiceCredentials): void {\n if (!creds.openrouterKey) {\n throw new Error('OpenRouter speech needs an API key');\n }\n}\n\nexport function createSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n const primary: NamedEngine<SttEngine> = { name: provider, engine: buildSttEngine(provider, ctx) };\n const fallback = ctx.sttFallback && ctx.sttFallback !== provider ? ctx.sttFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackStt([primary, { name: fallback, engine: buildSttEngine(fallback, ctx) }], ctx.log);\n } catch (e) {\n ctx.log.warn(`Speech-to-text fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\nfunction buildSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureStt(ctx.creds.azureKey, ctx.creds.azureRegion);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsStt(ctx.creds.aws);\n case 'vosk':\n return new VoskStt(ctx.dataDir, ctx.voskModel, ctx.log);\n case 'parakeet':\n if (!ctx.sendMessage) {\n throw new Error('Parakeet speech recognition is not available here');\n }\n return new ParakeetStt((ctx.parakeetInstance || '').trim(), ctx.sendMessage);\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterStt(ctx.creds.openrouterKey, ctx.openrouterSttModel);\n case 'piper':\n throw new Error('Piper is a text-to-speech engine, not speech-to-text');\n default:\n if (ctx.sttBaseUrl?.trim()) {\n return new OpenAiStt(ctx.sttServerKey || '', ctx.sttModel || undefined, ctx.sttBaseUrl);\n }\n requireOpenAi(ctx.creds);\n return new OpenAiStt(ctx.creds.openaiKey, ctx.sttModel || undefined);\n }\n}\n\nexport function createTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Each engine gets the shared behaviour (disk cache, length limit, SSML) and its own cache directory,\n // so a fallback engine's voice can never be served later while the primary one is healthy again.\n const primary: NamedEngine<TtsEngine> = { name: provider, engine: cachedTts(provider, ctx) };\n const fallback = ctx.ttsFallback && ctx.ttsFallback !== provider ? ctx.ttsFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackTts([primary, { name: fallback, engine: cachedTts(fallback, ctx) }], ctx.log);\n } catch (e) {\n // A fallback that cannot even be built (missing key, wrong provider) must not take the main one down.\n ctx.log.warn(`Text-to-speech fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\n/**\n * One provider binding plus the shared cache/length/SSML layer. One cache directory per provider+voice —\n * a voice change must not serve audio in the old voice.\n */\nfunction cachedTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const voice =\n provider === 'azure'\n ? ctx.voices.azure\n : provider === 'aws'\n ? ctx.voices.aws\n : provider === 'piper'\n ? ctx.voices.piper\n : provider === 'openrouter'\n ? `${ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL}-${ctx.voices.openrouter}`\n : ctx.voices.openai;\n const dir = path.join(ctx.dataDir, 'ttscache', `${provider}-${(voice || 'default').replace(/[^\\w.-]/g, '_')}`);\n return new CachedTts(buildTtsEngine(provider, ctx), { dir, log: ctx.log, maxChars: ctx.ttsMaxChars });\n}\n\nfunction buildTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureTts(ctx.creds.azureKey, ctx.creds.azureRegion, ctx.voices.azure);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsTts(ctx.creds.aws, ctx.voices.aws);\n case 'piper':\n return new PiperTts(ctx.dataDir, ctx.voices.piper, ctx.log);\n case 'vosk':\n throw new Error('Vosk is a speech-to-text engine, not text-to-speech');\n case 'parakeet':\n throw new Error('Parakeet is a speech-to-text engine, not text-to-speech');\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterTts(\n ctx.creds.openrouterKey,\n ctx.openrouterTtsModel,\n ctx.voices.openrouter,\n ctx.decodeAudio,\n );\n default:\n requireOpenAi(ctx.creds);\n return new OpenAiTts(\n ctx.creds.openaiKey,\n (ctx.voices.openai || 'alloy') as OpenAiVoice,\n ctx.ttsModel || undefined,\n );\n }\n}\n\n/** OpenAI TTS voices are a fixed set (no list API). */\nconst OPENAI_VOICES = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];\n\n/** List the available TTS voices for a provider (for the settings voice dropdown). */\nexport async function listVoices(provider: SpeechProvider, ctx: EngineContext, language: string): Promise<string[]> {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return listAzureVoices(ctx.creds.azureKey, ctx.creds.azureRegion, isoToLocale(language));\n case 'aws':\n requireAws(ctx.creds);\n return listPollyVoices(ctx.creds.aws, isoToLocale(language));\n case 'piper':\n return listPiperVoices();\n case 'openrouter': {\n // public list, no key needed: the voices of the chosen model\n const model = ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL;\n const models = await listOpenRouterSpeechModels('speech');\n return voicesForLanguage(models.find(m => m.id === model)?.voices || [], language);\n }\n default:\n return OPENAI_VOICES;\n }\n}\n\n/** Suggested STT model names for the settings dropdown: the local Vosk catalogue, or the models of OpenRouter. */\nexport async function listSttModels(provider: SpeechProvider, language: string): Promise<string[]> {\n if (provider === 'openrouter') {\n return (await listOpenRouterSpeechModels('transcription')).map(m => m.id);\n }\n return provider === 'vosk' ? listVoskModels(language) : [];\n}\n\n/** TTS model names for the settings dropdown — only OpenRouter has a choice worth listing. */\nexport async function listTtsModels(provider: SpeechProvider): Promise<string[]> {\n return provider === 'openrouter' ? (await listOpenRouterSpeechModels('speech')).map(m => m.id) : [];\n}\n"]}
1
+ {"version":3,"file":"engines.js","sourceRoot":"","sources":["../../../src/lib/voice/engines.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHA,0CAYC;AA+BD,0CAGC;AAsGD,gCAmBC;AAGD,sCAKC;AAGD,sCAEC;AAzSD;;;;GAIG;AACH,+BAAkD;AAClD,+BAAoE;AACpE,mCAA8D;AAC9D,+BAAuE;AACvE,iCAAiD;AACjD,yCAA6D;AAC7D,mCAAoD;AACpD,6CAOsB;AACtB,gDAAkC;AAElC,yCAAuC;AACvC,yCAAwE;AACxE,iCAAqC;AACrC,qDAAiE;AAoEjE,SAAS,YAAY,CAAC,KAAuB;IACzC,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACxE,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,KAAuB;IACvC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,iEAAiE,CAAC,CAAC;IACvF,CAAC;AACL,CAAC;AAED,SAAS,aAAa,CAAC,KAAuB;IAC1C,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACtD,CAAC;AACL,CAA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,CAAC,CAAC,CAAC;YAChB,6DAA6D;YAC7D,MAAM,KAAK,GAAG,GAAG,CAAC,kBAAkB,IAAI,yCAA4B,CAAC;YACrE,MAAM,MAAM,GAAG,MAAM,IAAA,uCAA0B,EAAC,QAAQ,CAAC,CAAC;YAC1D,OAAO,IAAA,8BAAiB,EAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;QACvF,CAAC;QACD;YACI,OAAO,aAAa,CAAC;IAC7B,CAAC;AACL,CAAC;AAED,kHAAkH;AAC3G,KAAK,UAAU,aAAa,CAAC,QAAwB,EAAE,QAAgB;IAC1E,IAAI,QAAQ,KAAK,YAAY,EAAE,CAAC;QAC5B,OAAO,CAAC,MAAM,IAAA,uCAA0B,EAAC,eAAe,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,IAAA,qBAAc,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/D,CAAC;AAED,8FAA8F;AACvF,KAAK,UAAU,aAAa,CAAC,QAAwB;IACxD,OAAO,QAAQ,KAAK,YAAY,CAAC,CAAC,CAAC,CAAC,MAAM,IAAA,uCAA0B,EAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxG,CAAC","sourcesContent":["/**\n * Factory that builds the configured STT/TTS engine. Cloud engines (OpenAI/Azure/AWS) use resolved\n * credentials; local engines (Vosk/Piper) download their models on demand into the data dir.\n * Adding a provider = one new engine class + one `case` here.\n */\nimport { OpenAiStt, type SttEngine } from './stt';\nimport { OpenAiTts, type OpenAiVoice, type TtsEngine } from './tts';\nimport { AzureStt, AzureTts, listAzureVoices } from './azure';\nimport { AwsStt, AwsTts, listPollyVoices, type AwsCreds } from './aws';\nimport { VoskStt, listVoskModels } from './vosk';\nimport { ParakeetStt, type MessageSender } from './parakeet';\nimport { PiperTts, listPiperVoices } from './piper';\nimport {\n OpenRouterStt,\n OpenRouterTts,\n listOpenRouterSpeechModels,\n voicesForLanguage,\n DEFAULT_OPENROUTER_TTS_MODEL,\n type AudioDecoder,\n} from './openrouter';\nimport * as path from 'node:path';\n\nimport { CachedTts } from './ttsCache';\nimport { FallbackStt, FallbackTts, type NamedEngine } from './fallback';\nimport { isoToLocale } from './lang';\nimport { LanguageTts, VoicePerLanguage } from './speechLanguage';\nimport type { VoiceLogger } from './download';\n\nexport type SpeechProvider = 'openai' | 'openrouter' | 'azure' | 'aws' | 'vosk' | 'parakeet' | 'piper';\n\n/** All speech credentials, resolved from config (or the central credential store). */\nexport interface VoiceCredentials {\n openaiKey: string;\n openrouterKey: string;\n azureKey: string;\n azureRegion: string;\n aws: AwsCreds;\n}\n\n/** Provider-specific voice ids (each provider names voices differently). */\nexport interface VoiceNames {\n openai: string; // alloy/echo/…\n azure: string; // e.g. de-DE-KatjaNeural\n aws: string; // e.g. Vicki\n piper: string; // e.g. de_DE-thorsten-medium\n openrouter: string; // depends on the model, e.g. Kore, george\n}\n\n/** Everything the factory needs to build any engine. */\nexport interface EngineContext {\n creds: VoiceCredentials;\n voices: VoiceNames;\n /** Optional second engine, used when the primary one fails ('' = none). */\n sttFallback?: SpeechProvider | '';\n ttsFallback?: SpeechProvider | '';\n /** Writable instance data dir (for the local engines' downloads). */\n dataDir: string;\n log: VoiceLogger;\n /** Local model overrides ('' → default per language). */\n voskModel: string;\n /** OpenAI STT model ('' → 'whisper-1'; e.g. 'gpt-4o-transcribe'). */\n sttModel: string;\n /**\n * OpenAI-compatible transcription server instead of OpenAI ('' = OpenAI), e.g. a local whisper container.\n * It gets `sttServerKey`, never the OpenAI key — that one is only for OpenAI.\n */\n sttBaseUrl?: string;\n /** Key for `sttBaseUrl` ('' = the server needs none). */\n sttServerKey?: string;\n /** OpenAI TTS model ('' → 'tts-1'; e.g. 'gpt-4o-mini-tts'). */\n ttsModel: string;\n /** OpenRouter models ('' → the defaults of openrouter.ts) */\n openrouterSttModel: string;\n openrouterTtsModel: string;\n /** Decoder for compressed speech (OpenRouter models that only return mp3); absent → those models fail */\n decodeAudio?: AudioDecoder;\n /** Longest text that is spoken, in characters; longer ones are cut at a sentence end. 0 = no limit, absent = 400. */\n ttsMaxChars?: number;\n /**\n * Language the satellites listen in (ISO-639-1). A voice set for one language (Polly 'Vicki') is only used for\n * it; an answer in another language gets the default voice of that language.\n */\n language?: string;\n /** Table \"voice per language\" (ISO code → voice of the main TTS provider); absent = the voices above. */\n voicesByLanguage?: Record<string, string>;\n /** Language the answering tier reported for exactly this text (pi-agent `language`); absent → by its letters. */\n reportedLanguage?: (text: string) => string | undefined;\n /** Instance of ioBroker.ai-parakeet for the provider `parakeet`, e.g. 'ai-parakeet.0'. */\n parakeetInstance?: string;\n /** Message bus to other instances (ai-parakeet); absent → `parakeet` cannot be used. */\n sendMessage?: MessageSender;\n}\n\nfunction requireAzure(creds: VoiceCredentials): void {\n if (!creds.azureKey || !creds.azureRegion) {\n throw new Error('Azure speech needs a subscription key and region');\n }\n}\n\nfunction requireAws(creds: VoiceCredentials): void {\n if (!creds.aws.accessKeyId || !creds.aws.secretAccessKey || !creds.aws.region) {\n throw new Error('AWS speech needs an access key id, secret access key and region');\n }\n}\n\nfunction requireOpenAi(creds: VoiceCredentials): void {\n if (!creds.openaiKey) {\n throw new Error('OpenAI speech needs an API key');\n }\n}\n\nfunction requireOpenRouter(creds: VoiceCredentials): void {\n if (!creds.openrouterKey) {\n throw new Error('OpenRouter speech needs an API key');\n }\n}\n\nexport function createSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n const primary: NamedEngine<SttEngine> = { name: provider, engine: buildSttEngine(provider, ctx) };\n const fallback = ctx.sttFallback && ctx.sttFallback !== provider ? ctx.sttFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackStt([primary, { name: fallback, engine: buildSttEngine(fallback, ctx) }], ctx.log);\n } catch (e) {\n ctx.log.warn(`Speech-to-text fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\nfunction buildSttEngine(provider: SpeechProvider, ctx: EngineContext): SttEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureStt(ctx.creds.azureKey, ctx.creds.azureRegion);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsStt(ctx.creds.aws);\n case 'vosk':\n return new VoskStt(ctx.dataDir, ctx.voskModel, ctx.log);\n case 'parakeet':\n if (!ctx.sendMessage) {\n throw new Error('Parakeet speech recognition is not available here');\n }\n return new ParakeetStt((ctx.parakeetInstance || '').trim(), ctx.sendMessage);\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterStt(ctx.creds.openrouterKey, ctx.openrouterSttModel);\n case 'piper':\n throw new Error('Piper is a text-to-speech engine, not speech-to-text');\n default:\n if (ctx.sttBaseUrl?.trim()) {\n return new OpenAiStt(ctx.sttServerKey || '', ctx.sttModel || undefined, ctx.sttBaseUrl);\n }\n requireOpenAi(ctx.creds);\n return new OpenAiStt(ctx.creds.openaiKey, ctx.sttModel || undefined);\n }\n}\n\nexport function createTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Outermost: every text is spoken in its own language — a German voice spells a Russian answer letter by letter\n return new LanguageTts(fallbackTts(provider, ctx), ctx.reportedLanguage, ctx.log);\n}\n\nfunction fallbackTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n // Each engine gets the shared behaviour (disk cache, length limit, SSML) and its own cache directory,\n // so a fallback engine's voice can never be served later while the primary one is healthy again.\n const primary: NamedEngine<TtsEngine> = { name: provider, engine: withLanguageVoices(provider, ctx) };\n const fallback = ctx.ttsFallback && ctx.ttsFallback !== provider ? ctx.ttsFallback : '';\n if (!fallback) {\n return primary.engine;\n }\n try {\n return new FallbackTts([primary, { name: fallback, engine: cachedTts(fallback, ctx) }], ctx.log);\n } catch (e) {\n // A fallback that cannot even be built (missing key, wrong provider) must not take the main one down.\n ctx.log.warn(`Text-to-speech fallback '${fallback}' unavailable: ${(e as Error).message}`);\n return primary.engine;\n }\n}\n\n/** Key of a provider in {@link VoiceNames}; the speech-to-text-only providers have no voice. */\nfunction voiceKey(provider: SpeechProvider): keyof VoiceNames | '' {\n return provider === 'vosk' || provider === 'parakeet' ? '' : provider;\n}\n\n/**\n * The main provider with the table \"voice per language\": one engine per row with that voice. The table names voices\n * of the main provider, so the fallback provider does not get it.\n */\nfunction withLanguageVoices(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const main = cachedTts(provider, ctx);\n const key = voiceKey(provider);\n const rows = Object.entries(ctx.voicesByLanguage || {});\n if (!key || !rows.length) {\n return main;\n }\n const byLanguage: Record<string, TtsEngine> = {};\n for (const [lang, voice] of rows) {\n try {\n // the voice of a row is for its language (Polly names say nothing about it)\n byLanguage[lang] = cachedTts(provider, { ...ctx, language: lang, voices: { ...ctx.voices, [key]: voice } });\n } catch (e) {\n ctx.log.warn(`Voice '${voice}' for '${lang}' unavailable: ${(e as Error).message}`);\n }\n }\n return new VoicePerLanguage(main, byLanguage);\n}\n\n/**\n * One provider binding plus the shared cache/length/SSML layer. One cache directory per provider+voice —\n * a voice change must not serve audio in the old voice.\n */\nfunction cachedTts(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n const voice =\n provider === 'azure'\n ? ctx.voices.azure\n : provider === 'aws'\n ? ctx.voices.aws\n : provider === 'piper'\n ? ctx.voices.piper\n : provider === 'openrouter'\n ? `${ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL}-${ctx.voices.openrouter}`\n : ctx.voices.openai;\n const dir = path.join(ctx.dataDir, 'ttscache', `${provider}-${(voice || 'default').replace(/[^\\w.-]/g, '_')}`);\n return new CachedTts(buildTtsEngine(provider, ctx), { dir, log: ctx.log, maxChars: ctx.ttsMaxChars });\n}\n\nfunction buildTtsEngine(provider: SpeechProvider, ctx: EngineContext): TtsEngine {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return new AzureTts(ctx.creds.azureKey, ctx.creds.azureRegion, ctx.voices.azure);\n case 'aws':\n requireAws(ctx.creds);\n return new AwsTts(ctx.creds.aws, ctx.voices.aws, ctx.language);\n case 'piper':\n return new PiperTts(ctx.dataDir, ctx.voices.piper, ctx.log);\n case 'vosk':\n throw new Error('Vosk is a speech-to-text engine, not text-to-speech');\n case 'parakeet':\n throw new Error('Parakeet is a speech-to-text engine, not text-to-speech');\n case 'openrouter':\n requireOpenRouter(ctx.creds);\n return new OpenRouterTts(\n ctx.creds.openrouterKey,\n ctx.openrouterTtsModel,\n ctx.voices.openrouter,\n ctx.decodeAudio,\n );\n default:\n requireOpenAi(ctx.creds);\n return new OpenAiTts(\n ctx.creds.openaiKey,\n (ctx.voices.openai || 'alloy') as OpenAiVoice,\n ctx.ttsModel || undefined,\n );\n }\n}\n\n/** OpenAI TTS voices are a fixed set (no list API). */\nconst OPENAI_VOICES = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'];\n\n/** List the available TTS voices for a provider (for the settings voice dropdown). */\nexport async function listVoices(provider: SpeechProvider, ctx: EngineContext, language: string): Promise<string[]> {\n switch (provider) {\n case 'azure':\n requireAzure(ctx.creds);\n return listAzureVoices(ctx.creds.azureKey, ctx.creds.azureRegion, isoToLocale(language));\n case 'aws':\n requireAws(ctx.creds);\n return listPollyVoices(ctx.creds.aws, isoToLocale(language));\n case 'piper':\n return listPiperVoices();\n case 'openrouter': {\n // public list, no key needed: the voices of the chosen model\n const model = ctx.openrouterTtsModel || DEFAULT_OPENROUTER_TTS_MODEL;\n const models = await listOpenRouterSpeechModels('speech');\n return voicesForLanguage(models.find(m => m.id === model)?.voices || [], language);\n }\n default:\n return OPENAI_VOICES;\n }\n}\n\n/** Suggested STT model names for the settings dropdown: the local Vosk catalogue, or the models of OpenRouter. */\nexport async function listSttModels(provider: SpeechProvider, language: string): Promise<string[]> {\n if (provider === 'openrouter') {\n return (await listOpenRouterSpeechModels('transcription')).map(m => m.id);\n }\n return provider === 'vosk' ? listVoskModels(language) : [];\n}\n\n/** TTS model names for the settings dropdown — only OpenRouter has a choice worth listing. */\nexport async function listTtsModels(provider: SpeechProvider): Promise<string[]> {\n return provider === 'openrouter' ? (await listOpenRouterSpeechModels('speech')).map(m => m.id) : [];\n}\n"]}
@@ -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":";;;;;;;;;;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CAAC,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;QACnE,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,uCAAuC,CAAC,CAAC;QAC1E,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,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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AAE,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;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,4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C,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;YACrF,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,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,C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AAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,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;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,217 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VoicePerLanguage = exports.LanguageTts = void 0;
4
+ exports.baseLanguage = baseLanguage;
5
+ exports.scriptLanguage = scriptLanguage;
6
+ exports.speechLanguage = speechLanguage;
7
+ exports.voiceFitsLanguage = voiceFitsLanguage;
8
+ exports.parseVoiceTable = parseVoiceTable;
9
+ /** Script of the languages that are not written in Latin letters; everything else is Latin. */
10
+ const SCRIPT_OF = {
11
+ ru: 'cyrillic',
12
+ uk: 'cyrillic',
13
+ be: 'cyrillic',
14
+ bg: 'cyrillic',
15
+ sr: 'cyrillic',
16
+ mk: 'cyrillic',
17
+ kk: 'cyrillic',
18
+ el: 'greek',
19
+ zh: 'cjk',
20
+ ja: 'cjk',
21
+ ko: 'hangul',
22
+ ar: 'arabic',
23
+ fa: 'arabic',
24
+ he: 'hebrew',
25
+ };
26
+ const LETTERS = [
27
+ ['latin', /[a-zÀ-ɏ]/gi],
28
+ ['cyrillic', /[Ѐ-ӿ]/g],
29
+ ['greek', /[Ͱ-Ͽ]/g],
30
+ ['cjk', /[぀-ヿ㐀-鿿]/g],
31
+ ['hangul', /[가-힯ᄀ-ᇿ]/g],
32
+ ['arabic', /[؀-ۿ]/g],
33
+ ['hebrew', /[֐-׿]/g],
34
+ ];
35
+ /** Fewer letters than this say nothing about the language ("OK", "5 °C"). */
36
+ const MIN_LETTERS = 3;
37
+ /** Letters only Ukrainian has among the Cyrillic languages. */
38
+ const UKRAINIAN = /[ґєії]/i;
39
+ /** Kana: Japanese, not Chinese. */
40
+ const KANA = /[぀-ヿ]/;
41
+ /** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */
42
+ function baseLanguage(lang) {
43
+ return String(lang || '')
44
+ .trim()
45
+ .split(/[-_]/)[0]
46
+ .toLowerCase();
47
+ }
48
+ function scriptOf(lang) {
49
+ return SCRIPT_OF[baseLanguage(lang)] || 'latin';
50
+ }
51
+ /** The script most letters of the text are in; '' for too few letters. */
52
+ function dominantScript(text) {
53
+ let best = '';
54
+ let most = 0;
55
+ let total = 0;
56
+ for (const [script, re] of LETTERS) {
57
+ const count = (text.match(re) || []).length;
58
+ total += count;
59
+ if (count > most) {
60
+ best = script;
61
+ most = count;
62
+ }
63
+ }
64
+ return total >= MIN_LETTERS ? best : '';
65
+ }
66
+ /**
67
+ * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for
68
+ * too few letters.
69
+ */
70
+ function scriptLanguage(text) {
71
+ const script = dominantScript(String(text || ''));
72
+ switch (script) {
73
+ case 'cyrillic':
74
+ return UKRAINIAN.test(text) ? 'uk' : 'ru';
75
+ case 'greek':
76
+ return 'el';
77
+ case 'cjk':
78
+ return KANA.test(text) ? 'ja' : 'zh';
79
+ case 'hangul':
80
+ return 'ko';
81
+ case 'arabic':
82
+ return 'ar';
83
+ case 'hebrew':
84
+ return 'he';
85
+ default:
86
+ return '';
87
+ }
88
+ }
89
+ /**
90
+ * The language to speak a text in.
91
+ *
92
+ * @param text what is spoken
93
+ * @param configured the language the caller asked for (the satellite's language)
94
+ * @param reported the language the answering tier reported ('' = none)
95
+ * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it
96
+ */
97
+ function speechLanguage(text, configured, reported) {
98
+ const script = dominantScript(String(text || ''));
99
+ const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';
100
+ // a report is believed unless the letters contradict it (a "de" mark on a Cyrillic answer)
101
+ if (said && (!script || scriptOf(said) === script)) {
102
+ // the configured language in its own form ('de-DE'): same voice, same cache entry
103
+ return said === baseLanguage(configured) ? configured : said;
104
+ }
105
+ if (!script) {
106
+ return configured;
107
+ }
108
+ const byLetters = scriptLanguage(text);
109
+ if (scriptOf(configured) === script) {
110
+ // the letters fit the configured language; only Ukrainian letters say more than "Cyrillic"
111
+ return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;
112
+ }
113
+ // Latin letters while the satellite speaks Russian: English is the best guess
114
+ return byLetters || 'en';
115
+ }
116
+ /**
117
+ * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,
118
+ * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a
119
+ * multilingual Azure voice can speak every language.
120
+ */
121
+ function voiceFitsLanguage(voice, lang) {
122
+ const iso = baseLanguage(lang);
123
+ const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());
124
+ if (!iso || !locale || /multilingual/i.test(voice)) {
125
+ return true;
126
+ }
127
+ return locale[1] === iso;
128
+ }
129
+ /** Parse the config table "voice per language" into ISO code → voice; rows without both are skipped. */
130
+ function parseVoiceTable(rows) {
131
+ const table = {};
132
+ if (!Array.isArray(rows)) {
133
+ return table;
134
+ }
135
+ for (const row of rows) {
136
+ const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');
137
+ const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';
138
+ if (lang && voice) {
139
+ table[lang] = voice;
140
+ }
141
+ }
142
+ return table;
143
+ }
144
+ /**
145
+ * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the
146
+ * language the answering tier gave for exactly this text.
147
+ */
148
+ class LanguageTts {
149
+ inner;
150
+ reported;
151
+ log;
152
+ constructor(inner, reported, log) {
153
+ this.inner = inner;
154
+ this.reported = reported;
155
+ this.log = log;
156
+ }
157
+ /** The language `text` is spoken in when the caller asks for `lang`. */
158
+ languageFor(text, lang) {
159
+ const spoken = speechLanguage(text, lang, this.reported?.(text));
160
+ if (spoken !== lang) {
161
+ this.log.debug(`TTS in '${spoken}' instead of '${lang}': "${String(text).slice(0, 40)}"`);
162
+ }
163
+ return spoken;
164
+ }
165
+ synthesize(text, lang) {
166
+ return this.inner.synthesize(text, this.languageFor(text, lang));
167
+ }
168
+ synthesizeSsml(ssml, lang) {
169
+ const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);
170
+ return this.inner.synthesizeSsml
171
+ ? this.inner.synthesizeSsml(ssml, spoken)
172
+ : this.inner.synthesize(ssml, spoken);
173
+ }
174
+ prepare(lang) {
175
+ return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();
176
+ }
177
+ warm(phrases, lang) {
178
+ return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);
179
+ }
180
+ }
181
+ exports.LanguageTts = LanguageTts;
182
+ /**
183
+ * The voices of the table "voice per language": one engine per row, the default engine for every other language.
184
+ * Each engine has its own cache (the directory is per voice).
185
+ */
186
+ class VoicePerLanguage {
187
+ fallback;
188
+ byLanguage;
189
+ constructor(fallback, byLanguage) {
190
+ this.fallback = fallback;
191
+ this.byLanguage = byLanguage;
192
+ }
193
+ engineFor(lang) {
194
+ return this.byLanguage[baseLanguage(lang)] || this.fallback;
195
+ }
196
+ synthesize(text, lang) {
197
+ return this.engineFor(lang).synthesize(text, lang);
198
+ }
199
+ synthesizeSsml(ssml, lang) {
200
+ const engine = this.engineFor(lang);
201
+ return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);
202
+ }
203
+ /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */
204
+ async prepare(lang) {
205
+ await this.engineFor(lang).prepare?.(lang);
206
+ for (const [code, engine] of Object.entries(this.byLanguage)) {
207
+ if (code !== baseLanguage(lang)) {
208
+ await engine.prepare?.(code);
209
+ }
210
+ }
211
+ }
212
+ warm(phrases, lang) {
213
+ return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);
214
+ }
215
+ }
216
+ exports.VoicePerLanguage = VoicePerLanguage;
217
+ //# 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;AAOD,8CAOC;AAGD,0CAaC;AAhJD,+FAA+F;AAC/F,MAAM,SAAS,GAA2B;IACtC,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,UAAU;IACd,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,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,QAAQ,CAAC;CACvB,CAAC;AAEF,6EAA6E;AAC7E,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,+DAA+D;AAC/D,MAAM,SAAS,GAAG,SAAS,CAAC;AAC5B,mCAAmC;AACnC,MAAM,IAAI,GAAG,OAAO,CAAC;AAErB,8EAA8E;AAC9E,SAAgB,YAAY,CAAC,IAAwB;IAC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AC,IAAI,CAAC,EAAE,CAAC;gBAC9B,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;IACL,CAAC;IAED,IAAI,CAAC,OAAiB,EAAE,IAAY;QAChC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC5E,CAAC;CACJ;AAhCD,4CAgCC","sourcesContent":["/**\n * The language an answer is spoken in. The transports hand the TTS the language the satellite listens in, but an\n * answer can be in another one (a question asked in Russian on a German satellite, pi-agent answering in the language\n * of the question). A German voice reads Cyrillic letter by letter (\"kyrillisch a, kyrillisch b …\"), so the TTS\n * takes the language of the text:\n *\n * 1. the language the answering tier reported (pi-agent ≥ 0.10.1 returns `language`), unless the letters contradict it;\n * 2. otherwise the letters: a text in another script than the configured language (Cyrillic, Greek, CJK …) is spoken\n * in the language of that script. Latin letters do not tell German from English: then the configured language\n * stays, unless it is itself written in another script (a Russian satellite answering in Latin letters → English).\n *\n * {@link LanguageTts} applies this in front of every TTS engine; {@link VoicePerLanguage} picks the voice of the\n * table \"voice per language\" for it.\n */\nimport type { TtsEngine, TtsResult } from './tts';\n\ntype Script = 'latin' | 'cyrillic' | 'greek' | 'cjk' | 'hangul' | 'arabic' | 'hebrew';\n\n/** Script of the languages that are not written in Latin letters; everything else is Latin. */\nconst SCRIPT_OF: Record<string, Script> = {\n ru: 'cyrillic',\n uk: 'cyrillic',\n be: 'cyrillic',\n bg: 'cyrillic',\n sr: 'cyrillic',\n mk: 'cyrillic',\n kk: 'cyrillic',\n el: 'greek',\n zh: 'cjk',\n ja: 'cjk',\n ko: 'hangul',\n ar: 'arabic',\n fa: 'arabic',\n he: 'hebrew',\n};\n\nconst LETTERS: [Script, RegExp][] = [\n ['latin', /[a-zÀ-ɏ]/gi],\n ['cyrillic', /[Ѐ-ӿ]/g],\n ['greek', /[Ͱ-Ͽ]/g],\n ['cjk', /[぀-ヿ㐀-鿿]/g],\n ['hangul', /[가-힯ᄀ-ᇿ]/g],\n ['arabic', /[؀-ۿ]/g],\n ['hebrew', /[֐-׿]/g],\n];\n\n/** Fewer letters than this say nothing about the language (\"OK\", \"5 °C\"). */\nconst MIN_LETTERS = 3;\n\n/** Letters only Ukrainian has among the Cyrillic languages. */\nconst UKRAINIAN = /[ґєії]/i;\n/** Kana: Japanese, not Chinese. */\nconst KANA = /[぀-ヿ]/;\n\n/** ISO-639-1 code of a language or locale: 'ru-RU' → 'ru', 'zh-cn' → 'zh'. */\nexport function baseLanguage(lang: string | undefined): string {\n return String(lang || '')\n .trim()\n .split(/[-_]/)[0]\n .toLowerCase();\n}\n\nfunction scriptOf(lang: string): Script {\n return SCRIPT_OF[baseLanguage(lang)] || 'latin';\n}\n\n/** The script most letters of the text are in; '' for too few letters. */\nfunction dominantScript(text: string): Script | '' {\n let best: Script | '' = '';\n let most = 0;\n let total = 0;\n for (const [script, re] of LETTERS) {\n const count = (text.match(re) || []).length;\n total += count;\n if (count > most) {\n best = script;\n most = count;\n }\n }\n return total >= MIN_LETTERS ? best : '';\n}\n\n/**\n * The language a text is written in as far as its letters tell; '' for Latin letters (German or English?) and for\n * too few letters.\n */\nexport function scriptLanguage(text: string): string {\n const script = dominantScript(String(text || ''));\n switch (script) {\n case 'cyrillic':\n return UKRAINIAN.test(text) ? 'uk' : 'ru';\n case 'greek':\n return 'el';\n case 'cjk':\n return KANA.test(text) ? 'ja' : 'zh';\n case 'hangul':\n return 'ko';\n case 'arabic':\n return 'ar';\n case 'hebrew':\n return 'he';\n default:\n return '';\n }\n}\n\n/**\n * The language to speak a text in.\n *\n * @param text what is spoken\n * @param configured the language the caller asked for (the satellite's language)\n * @param reported the language the answering tier reported ('' = none)\n * @returns ISO-639-1 code, or `configured` unchanged when nothing speaks against it\n */\nexport function speechLanguage(text: string, configured: string, reported?: string): string {\n const script = dominantScript(String(text || ''));\n const said = /^[a-z]{2,3}(-[a-z]{2,4})?$/i.test(String(reported || '').trim()) ? baseLanguage(reported) : '';\n // a report is believed unless the letters contradict it (a \"de\" mark on a Cyrillic answer)\n if (said && (!script || scriptOf(said) === script)) {\n // the configured language in its own form ('de-DE'): same voice, same cache entry\n return said === baseLanguage(configured) ? configured : said;\n }\n if (!script) {\n return configured;\n }\n const byLetters = scriptLanguage(text);\n if (scriptOf(configured) === script) {\n // the letters fit the configured language; only Ukrainian letters say more than \"Cyrillic\"\n return byLetters === 'uk' && baseLanguage(configured) !== 'uk' ? 'uk' : configured;\n }\n // Latin letters while the satellite speaks Russian: English is the best guess\n return byLetters || 'en';\n}\n\n/**\n * Can this voice speak the language? Told by the locale at the start of its name (`de_DE-thorsten-medium`,\n * `de-DE-KatjaNeural`, `de-DE-Klaus:MAI-Voice-2`); a name without a locale (OpenAI `alloy`, Gemini `Kore`) and a\n * multilingual Azure voice can speak every language.\n */\nexport function voiceFitsLanguage(voice: string, lang: string): boolean {\n const iso = baseLanguage(lang);\n const locale = /^([a-z]{2,3})[-_][A-Z]{2}(?![a-z])/.exec(String(voice || '').trim());\n if (!iso || !locale || /multilingual/i.test(voice)) {\n return true;\n }\n return locale[1] === iso;\n}\n\n/** Parse the config table \"voice per language\" into ISO code → voice; rows without both are skipped. */\nexport function parseVoiceTable(rows: unknown): Record<string, string> {\n const table: Record<string, string> = {};\n if (!Array.isArray(rows)) {\n return table;\n }\n for (const row of rows as { language?: unknown; voice?: unknown }[]) {\n const lang = baseLanguage(typeof row?.language === 'string' ? row.language : '');\n const voice = typeof row?.voice === 'string' ? row.voice.trim() : '';\n if (lang && voice) {\n table[lang] = voice;\n }\n }\n return table;\n}\n\n/** Log of the TTS layer. */\ninterface Logger {\n debug(msg: string): void;\n}\n\n/**\n * The outermost TTS layer: speaks every text in its own language ({@link speechLanguage}). `reported` looks up the\n * language the answering tier gave for exactly this text.\n */\nexport class LanguageTts implements TtsEngine {\n constructor(\n private readonly inner: TtsEngine,\n private readonly reported: ((text: string) => string | undefined) | undefined,\n private readonly log: Logger,\n ) {}\n\n /** The language `text` is spoken in when the caller asks for `lang`. */\n languageFor(text: string, lang: string): string {\n const spoken = speechLanguage(text, lang, this.reported?.(text));\n if (spoken !== lang) {\n this.log.debug(`TTS in '${spoken}' instead of '${lang}': \"${String(text).slice(0, 40)}\"`);\n }\n return spoken;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.inner.synthesize(text, this.languageFor(text, lang));\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const spoken = this.languageFor(ssml.replace(/<[^>]*>/g, ' '), lang);\n return this.inner.synthesizeSsml\n ? this.inner.synthesizeSsml(ssml, spoken)\n : this.inner.synthesize(ssml, spoken);\n }\n\n prepare(lang: string): Promise<void> {\n return this.inner.prepare ? this.inner.prepare(lang) : Promise.resolve();\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.inner.warm ? this.inner.warm(phrases, lang) : Promise.resolve(0);\n }\n}\n\n/**\n * The voices of the table \"voice per language\": one engine per row, the default engine for every other language.\n * Each engine has its own cache (the directory is per voice).\n */\nexport class VoicePerLanguage implements TtsEngine {\n constructor(\n private readonly fallback: TtsEngine,\n private readonly byLanguage: Record<string, TtsEngine>,\n ) {}\n\n private engineFor(lang: string): TtsEngine {\n return this.byLanguage[baseLanguage(lang)] || this.fallback;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.engineFor(lang).synthesize(text, lang);\n }\n\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const engine = this.engineFor(lang);\n return engine.synthesizeSsml ? engine.synthesizeSsml(ssml, lang) : engine.synthesize(ssml, lang);\n }\n\n /** The configured language and every language of the table: a Piper voice is a download of ~60 MB. */\n async prepare(lang: string): Promise<void> {\n await this.engineFor(lang).prepare?.(lang);\n for (const [code, engine] of Object.entries(this.byLanguage)) {\n if (code !== baseLanguage(lang)) {\n await engine.prepare?.(code);\n }\n }\n }\n\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engineFor(lang).warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}
package/build/main.js CHANGED
@@ -76,6 +76,7 @@ const ttsCache_1 = require("./lib/voice/ttsCache");
76
76
  const captures_1 = require("./lib/voice/captures");
77
77
  const ffmpegStatic_1 = require("./lib/voice/ffmpegStatic");
78
78
  const piAgent_1 = require("./lib/piAgent");
79
+ const speechLanguage_1 = require("./lib/voice/speechLanguage");
79
80
  const installer_1 = require("./lib/installer");
80
81
  const media_1 = require("./lib/media");
81
82
  const systemAi_1 = require("./lib/systemAi");
@@ -143,6 +144,7 @@ const VOICE_FORM_FIELDS = [
143
144
  'awsCredentialId',
144
145
  'awsVoice',
145
146
  'piperVoice',
147
+ 'ttsVoices',
146
148
  ];
147
149
  /** Of those, the protected ones: the browser never gets them, so an empty value there means "keep the saved one" */
148
150
  const VOICE_FORM_SECRETS = [
@@ -757,6 +759,9 @@ class Assistant extends adapter_core_1.Adapter {
757
759
  openrouterTtsModel: (cfg.openrouterTtsModel || '').trim(),
758
760
  decodeAudio: audio => this.decodeAudioBufferToPcm(audio),
759
761
  ttsMaxChars: (0, ttsCache_1.parseTtsMaxChars)(cfg.ttsMaxChars),
762
+ language: String(cfg.voiceLanguage || this.language || ''),
763
+ voicesByLanguage: (0, speechLanguage_1.parseVoiceTable)(cfg.ttsVoices),
764
+ reportedLanguage: text => this.reportedLanguage(text),
760
765
  parakeetInstance: (cfg.parakeetInstance || '').trim().replace(/^system\.adapter\./, ''),
761
766
  sendMessage: (instance, command, message) => this.askInstance(instance, command, message, PARAKEET_TIMEOUT_MS),
762
767
  };
@@ -3638,6 +3643,13 @@ class Assistant extends adapter_core_1.Adapter {
3638
3643
  }
3639
3644
  /** Per source: whether its last {@link answer} asked the user something (LLM-signalled via [[LISTEN]]). */
3640
3645
  followUps = new Map();
3646
+ /**
3647
+ * The language the answering tier reported for exactly this answer text (pi-agent ≥ 0.10.1 `language`). The
3648
+ * transports hand the TTS only the text, so the TTS looks the language up by it.
3649
+ */
3650
+ reportedLanguage(text) {
3651
+ return this.piAgent?.languageOf(text) || undefined;
3652
+ }
3641
3653
  /** Per source: when the cloud model last asked back about a script (see {@link cloudOnlyReason}). */
3642
3654
  scriptTopics = new Map();
3643
3655
  /**
@@ -4033,7 +4045,25 @@ class Assistant extends adapter_core_1.Adapter {
4033
4045
  // task) — its `tts` state says it there.
4034
4046
  const satellite = this.requestOrigin.getStore()?.satellite || '';
4035
4047
  const tts = satellite ? `${this.namespace}.satellites.${satellite}.tts` : '';
4036
- return await harness.ask({ text, conversation: source, instructions, language, images, satellite, tts });
4048
+ const answer = await harness.ask({
4049
+ text,
4050
+ conversation: source,
4051
+ instructions,
4052
+ language,
4053
+ images,
4054
+ satellite,
4055
+ tts,
4056
+ });
4057
+ const spokenIn = harness.languageOf(answer);
4058
+ if (spokenIn) {
4059
+ // the voice of the satellite may not speak it: the TTS takes a voice of this language
4060
+ this.journal?.step({
4061
+ stage: 'cloud',
4062
+ title: `${harness.instance} answered in '${spokenIn}'`,
4063
+ data: { language: spokenIn },
4064
+ });
4065
+ }
4066
+ return answer;
4037
4067
  }
4038
4068
  catch (e) {
4039
4069
  if (localFallback) {
@@ -7632,6 +7662,10 @@ class Assistant extends adapter_core_1.Adapter {
7632
7662
  const cfg = { ...this.config, sttFallback: '', ttsFallback: '' };
7633
7663
  for (const key of VOICE_FORM_FIELDS) {
7634
7664
  const value = form[key];
7665
+ if (Array.isArray(value)) {
7666
+ cfg[key] = value; // the table "voice per language"
7667
+ continue;
7668
+ }
7635
7669
  if (typeof value !== 'string' || (VOICE_FORM_SECRETS.includes(key) && !value.trim())) {
7636
7670
  continue;
7637
7671
  }