iobroker.assistant 1.15.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +4 -4
  2. package/admin/i18n/de.json +5 -1
  3. package/admin/i18n/en.json +5 -1
  4. package/admin/i18n/es.json +5 -1
  5. package/admin/i18n/fr.json +5 -1
  6. package/admin/i18n/it.json +5 -1
  7. package/admin/i18n/nl.json +5 -1
  8. package/admin/i18n/pl.json +5 -1
  9. package/admin/i18n/pt.json +5 -1
  10. package/admin/i18n/ru.json +5 -1
  11. package/admin/i18n/uk.json +5 -1
  12. package/admin/i18n/zh-cn.json +5 -1
  13. package/admin/jsonConfig.json +15 -3
  14. package/build/lib/music.js +7 -2
  15. package/build/lib/music.js.map +1 -1
  16. package/build/lib/quick.js +1 -1
  17. package/build/lib/quick.js.map +1 -1
  18. package/build/lib/voice/aws.js +33 -3
  19. package/build/lib/voice/aws.js.map +1 -1
  20. package/build/lib/voice/azure.js +34 -0
  21. package/build/lib/voice/azure.js.map +1 -1
  22. package/build/lib/voice/fallback.js +4 -0
  23. package/build/lib/voice/fallback.js.map +1 -1
  24. package/build/lib/voice/openrouter.js +4 -0
  25. package/build/lib/voice/openrouter.js.map +1 -1
  26. package/build/lib/voice/piper.js +4 -0
  27. package/build/lib/voice/piper.js.map +1 -1
  28. package/build/lib/voice/speechLanguage.js +87 -0
  29. package/build/lib/voice/speechLanguage.js.map +1 -1
  30. package/build/lib/voice/tts.js +4 -0
  31. package/build/lib/voice/tts.js.map +1 -1
  32. package/build/lib/voice/ttsCache.js +3 -0
  33. package/build/lib/voice/ttsCache.js.map +1 -1
  34. package/build/lib/voice/voiceGender.js +186 -0
  35. package/build/lib/voice/voiceGender.js.map +1 -0
  36. package/build/lib/youtube.js +1 -1
  37. package/build/lib/youtube.js.map +1 -1
  38. package/build/main.js +102 -9
  39. package/build/main.js.map +1 -1
  40. package/io-package.json +14 -14
  41. package/package.json +1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qD;SACnE;QACD,EAAE,EAAE;YACA,OAAO,EAAE,UAAU,CAAC,GAAG;YACvB,UAAU,EAAE,cAAc,CAAC,kBAAkB,GAAG,EAAE;YAClD,aAAa,EAAE,sBAAsB,CAAC,IAAI,KAAK,EAAE;YACjD,WAAW,EAAE,0BAA0B,KAAK,GAAG;YAC/C,OAAO,EAAE,aAAa,IAAI,cAAc,CAAC,GAAG;YAC5C,UAAU,EAAE,SAAS,CAAC,eAAe,IAAI,GAAG,GAAG,EAAE;YACjD,aAAa,EAAE,SAAS,CAAC,mBAAmB,KAAK,EAAE;YACnD,WAAW,EAAE,oBAAoB,KAAK,GAAG;YACzC,UAAU,EAAE,GAAG,CAAC,2BAA2B;YAC3C,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,YAAY,IAAI,GAAG;YAClE,aAAa,EAAE,WAAW,IAAI,cAAc,GAAG,EAAE;YACjD,aAAa,EAAE,UAAU,CAAC,mBAAmB,KAAK,EAAE;YACpD,WAAW,EAAE,kCAAkC,KAAK,GAAG;YACvD,gBAAgB,EAAE,6BAA6B,CAAC,IAAI,KAAK,EAAE;YAC3D,SAAS,EAAE,iDAAiD;SAC/D;KACJ,CAAC;IACF,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * Quick commands for the families of the shared catalog (`HELP.md`), understood without a model: \"Ruf Anna an\"\n * (`phone.call`), \"Zeige die Haustür auf dem Küchendisplay\" (`screen.show`), \"Schick mir ein Bild der Haustür\"\n * (`camera.snapshot` → `message.send`). The parsers only split the sentence; which names exist (screens, cameras,\n * recipients) is asked from the instances by the caller, and a sentence whose names fit nothing goes on to the\n * other tiers.\n */\n\nexport type QuickLanguage = 'de' | 'en' | 'ru';\n\n/** A word of the sentence: as written (for names and texts) and lower case (for matching). */\ninterface Word {\n raw: string;\n low: string;\n}\n\nfunction words(text: string): Word[] {\n return [...text.matchAll(/[\\p{L}\\p{N}+#*]+(?:['’-][\\p{L}\\p{N}]+)*/gu)].map(m => ({\n raw: m[0],\n low: m[0].toLowerCase().replace(/ё/g, 'е'),\n }));\n}\n\nconst join = (list: Word[]): string => list.map(w => w.raw).join(' ');\n\n/** Polite words, taken away at the start and the end. */\nconst POLITE = new Set([\n 'bitte',\n 'mal',\n 'doch',\n 'kannst',\n 'du',\n 'könntest',\n 'please',\n 'can',\n 'could',\n 'you',\n 'пожалуйста',\n 'можешь',\n 'ну',\n]);\nconst ARTICLES = new Set(['der', 'die', 'das', 'den', 'dem', 'des', 'ein', 'eine', 'einen', 'einem', 'the', 'a', 'an']);\n\nfunction trimPolite(list: Word[]): Word[] {\n let a = 0;\n let b = list.length;\n while (a < b && POLITE.has(list[a].low)) {\n a++;\n }\n while (b > a && POLITE.has(list[b - 1].low)) {\n b--;\n }\n return list.slice(a, b);\n}\n\nfunction trimArticles(list: Word[]): Word[] {\n let a = 0;\n while (a < list.length && ARTICLES.has(list[a].low)) {\n a++;\n }\n return list.slice(a);\n}\n\n/**\n * A said name fits a known one: the same without case, or every said word is a word of the name up to an ending\n * (\"Anne\"/\"Anna\", \"Küche\"/\"Küchendisplay\" does not, \"кухню\"/\"Кухня\" does).\n *\n * @param said as said\n * @param name as known\n */\nexport function nameFits(said: string, name: string): boolean {\n const a = said\n .toLowerCase()\n .replace(/ё/g, 'е')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n const b = name\n .toLowerCase()\n .replace(/ё/g, 'е')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n if (!a || !b) {\n return false;\n }\n if (a === b || a.replace(/ /g, '') === b.replace(/ /g, '')) {\n return true;\n }\n const saidWords = a.split(' ');\n const nameWords = b.split(' ');\n return saidWords.every(s => nameWords.some(n => sameStem(s, n)));\n}\n\n/** One word for another up to an inflected ending of at most two letters (\"кухню\"/\"кухня\", \"Annas\"/\"Anna\"). */\nfunction sameStem(a: string, b: string): boolean {\n if (a === b) {\n return true;\n }\n const short = a.length < b.length ? a : b;\n const long = a.length < b.length ? b : a;\n if (short.length < 3 || long.length - short.length > 2) {\n return false;\n }\n let common = 0;\n while (common < short.length && short[common] === long[common]) {\n common++;\n }\n return common >= Math.max(3, short.length - 1);\n}\n\n/**\n * The best of several named things for a said name: an exact name, then an exact room, then a fitting name, then a\n * fitting room. Several fit equally → all of them (the caller asks back).\n */\nexport function pickNamed<T extends { id: string; name: string; room?: string }>(items: T[], said: string): T[] {\n const s = said.trim();\n if (!s) {\n return [];\n }\n const low = s.toLowerCase();\n const rules: ((i: T) => boolean)[] = [\n i => i.name.toLowerCase() === low || i.id.toLowerCase() === low,\n i => !!i.room && i.room.toLowerCase() === low,\n i => nameFits(s, i.name),\n i => !!i.room && nameFits(s, i.room),\n ];\n for (const rule of rules) {\n const hits = items.filter(rule);\n if (hits.length) {\n return hits;\n }\n }\n return [];\n}\n\n// ── phone.call ──────────────────────────────────────────────────────────────\n\nexport interface CallCommand {\n /** A name or a number, as said */\n to: string;\n language: QuickLanguage;\n}\n\n/**\n * \"Ruf Anna an\", \"Rufe bitte die Küche an\", \"Anna anrufen\", \"Verbinde mich mit der Tür\", \"Call Anna\", \"Connect me\n * with the door\", \"Позвони Анне\", \"Набери 0171 2345\". Null for anything else (\"Wer hat angerufen?\").\n */\nexport function parseCallCommand(text: string): CallCommand | null {\n const w = trimPolite(words(text));\n if (w.length < 2) {\n return null;\n }\n const first = w[0].low;\n const last = w[w.length - 1].low;\n let target: Word[] | null = null;\n let language: QuickLanguage = 'de';\n if ((first === 'ruf' || first === 'rufe') && last === 'an' && w.length >= 3) {\n target = w.slice(1, -1);\n } else if (last === 'anrufen' && w.length >= 2 && !['wer', 'wen', 'kann', 'soll'].includes(first)) {\n target = w.slice(0, -1);\n } else if (first === 'verbinde' && w[1]?.low === 'mich' && w[2]?.low === 'mit') {\n target = w.slice(3);\n } else if (first === 'telefoniere' && w[1]?.low === 'mit') {\n target = w.slice(2);\n } else if (first === 'waehle' || first === 'wähle') {\n target = w.slice(1);\n } else if (['call', 'phone', 'ring', 'dial'].includes(first)) {\n language = 'en';\n target = w.slice(1);\n } else if (first === 'connect' && w[1]?.low === 'me' && ['with', 'to'].includes(w[2]?.low)) {\n language = 'en';\n target = w.slice(3);\n } else if (['позвони', 'позвонить', 'набери', 'звони', 'вызови'].includes(first)) {\n language = 'ru';\n target = w.slice(1);\n } else if (first === 'соедини' && w[1]?.low === 'меня' && ['с', 'со'].includes(w[2]?.low)) {\n language = 'ru';\n target = w.slice(3);\n }\n if (!target) {\n return null;\n }\n target = trimArticles(trimPolite(target));\n if (!target.length || target.length > 5) {\n return null;\n }\n // \"call me back\", \"ruf mich an\": no target\n if (['me', 'mich', 'uns', 'us', 'мне', 'меня', 'back'].includes(target[0].low)) {\n return null;\n }\n const said = join(target);\n // a number with spaces: \"0171 234 56\"\n const to = /^[+\\d][\\d ]+$/.test(said) ? said.replace(/ /g, '') : said;\n return { to, language };\n}\n\n// ── screen.show ─────────────────────────────────────────────────────────────\n\nexport interface ShowOnCommand {\n /** What to show, as said (\"die Haustür\", \"die Kamera Einfahrt\", \"die Ansicht Wetter\") */\n what: string;\n /** Where, as said (\"Küchendisplay\", \"Wohnzimmer\"); '' = not said */\n screen: string;\n language: QuickLanguage;\n}\n\nconst SHOW_VERBS: Record<string, QuickLanguage> = {\n zeig: 'de',\n zeige: 'de',\n zeigen: 'de',\n show: 'en',\n display: 'en',\n покажи: 'ru',\n показать: 'ru',\n выведи: 'ru',\n отобрази: 'ru',\n};\nconst SHOW_FILLERS = new Set(['mir', 'uns', 'me', 'us', 'мне', 'нам']);\n/** The preposition before the screen: \"auf dem Fernseher\", \"im Wohnzimmer\", \"on the TV\", \"на телевизоре\". */\nconst SCREEN_PREPOSITIONS = new Set(['auf', 'im', 'am', 'on', 'на', 'в', 'во']);\n\n/**\n * \"Zeige die Haustür auf dem Küchendisplay\", \"Zeig mir die Kamera Einfahrt im Wohnzimmer\", \"Show the front door on\n * the TV\", \"Покажи камеру у входа на телевизоре\". The last preposition before a screen splits the sentence (the\n * camera \"an der Haustür\" stays in `what`). Null without a show verb or without anything to show.\n */\nexport function parseShowOnCommand(text: string): ShowOnCommand | null {\n const w = trimPolite(words(text));\n const language = w.length ? SHOW_VERBS[w[0].low] : undefined;\n if (!language) {\n return null;\n }\n let rest = w.slice(1);\n while (rest.length && (SHOW_FILLERS.has(rest[0].low) || POLITE.has(rest[0].low))) {\n rest = rest.slice(1);\n }\n rest = trimPolite(rest);\n let split = -1;\n for (let i = rest.length - 1; i > 0; i--) {\n if (SCREEN_PREPOSITIONS.has(rest[i].low) || (rest[i].low === 'in' && i > 0)) {\n split = i;\n break;\n }\n }\n const whatWords = trimArticles(split > 0 ? rest.slice(0, split) : rest);\n const screenWords = split > 0 ? trimArticles(rest.slice(split + 1)) : [];\n if (!whatWords.length) {\n return null;\n }\n return { what: join(whatWords), screen: join(screenWords), language };\n}\n\n/** What a show request names: a camera, a view or a text; the name is without the kind word. */\nexport interface ShowTarget {\n kind: 'camera' | 'view' | 'text' | 'unknown';\n name: string;\n}\n\nconst CAMERA_WORDS = /^(kamera|kameras|camera|cam|livebild|videobild|камер\\p{L}*|видеокамер\\p{L}*)$/u;\nconst VIEW_WORDS = /^(ansicht|seite|view|page|screen|вид|страниц\\p{L}*|экран)$/u;\nconst TEXT_WORDS = /^(text|nachricht|message|текст|сообщение|надпись)$/u;\nconst LINK_WORDS = new Set(['von', 'vom', 'der', 'des', 'of', 'from', 'the', 'с', 'со', 'у', 'из']);\n\n/**\n * What kind of thing a show request names: \"Kamera Einfahrt\" / \"die Einfahrt-Kamera\" / \"камеру у входа\" = camera,\n * \"die Ansicht Wetter\" = view, \"den Text Essen ist fertig\" = text (as written); else unknown with the whole name\n * (the caller looks it up among cameras and views).\n */\nexport function showTarget(what: string): ShowTarget {\n const w = trimArticles(words(what));\n if (!w.length) {\n return { kind: 'unknown', name: '' };\n }\n if (TEXT_WORDS.test(w[0].low)) {\n // the text as said, punctuation included\n const m = what.match(/^\\s*(?:(?:der|die|das|den|the)\\s+)?\\S+\\s+(.*)$/iu);\n return { kind: 'text', name: (m?.[1] || '').trim() };\n }\n /** The words without the one that says the kind (and \"von\", \"of\", \"у\" …); null when no word says it. */\n const without = (re: RegExp): string | null => {\n const i = w.findIndex(x => re.test(x.low));\n return i < 0 ? null : join(w.filter((x, j) => j !== i && !LINK_WORDS.has(x.low) && !ARTICLES.has(x.low)));\n };\n const camera = without(CAMERA_WORDS);\n if (camera !== null) {\n return { kind: 'camera', name: camera };\n }\n // \"die Einfahrt-Kamera\", \"die Einfahrtkamera\": the word without the kind\n const compound = w.findIndex(x => /^\\p{L}{3,}-?(kamera|camera|cam)$/u.test(x.low));\n if (compound >= 0) {\n const own = w[compound].raw.replace(/-?(kamera|camera|cam)$/iu, '');\n const others = w.filter((x, j) => j !== compound && !LINK_WORDS.has(x.low) && !ARTICLES.has(x.low));\n return {\n kind: 'camera',\n name: join([...others.slice(0, compound), { raw: own, low: own }, ...others.slice(compound)]),\n };\n }\n const view = without(VIEW_WORDS);\n if (view !== null) {\n return { kind: 'view', name: view };\n }\n return { kind: 'unknown', name: join(w) };\n}\n\n// ── camera.snapshot → message.send ──────────────────────────────────────────\n\nexport interface PictureCommand {\n /** `me` = the one who asks, else a name as said */\n recipient: string;\n /** The camera, as said (\"Haustür\", \"Einfahrt\") */\n camera: string;\n /** A word like \"Kamera\" was said: an unknown name gets an honest answer instead of going on */\n cameraWord: boolean;\n language: QuickLanguage;\n}\n\nconst SEND_VERBS: Record<string, QuickLanguage> = {\n schick: 'de',\n schicke: 'de',\n sende: 'de',\n send: 'en',\n text: 'en',\n пришли: 'ru',\n отправь: 'ru',\n скинь: 'ru',\n пошли: 'ru',\n вышли: 'ru',\n};\nconst PICTURE_WORDS =\n /^(bild|bilder|foto|fotos|schnappschuss|snapshot|aufnahme|picture|photo|image|pic|фото|фотку|фотографию|снимок|картинку|изображение|кадр)$/u;\nconst ME = new Set(['mir', 'uns', 'me', 'us', 'мне', 'нам']);\n\n/**\n * \"Schick mir ein Bild der Haustür\", \"Sende Anna ein Foto von der Einfahrt\", \"Send me a picture of the front door\n * camera\", \"Пришли мне фото с камеры у входа\". Null without a send verb and a picture word.\n */\nexport function parsePictureCommand(text: string): PictureCommand | null {\n const w = trimPolite(words(text));\n const language = w.length ? SEND_VERBS[w[0].low] : undefined;\n if (!language) {\n return null;\n }\n const pic = w.findIndex((x, i) => i > 0 && PICTURE_WORDS.test(x.low));\n if (pic < 1) {\n return null;\n }\n const who = trimArticles(w.slice(1, pic)).filter(\n x => !['ein', 'eine', 'einen', 'a', 'an', 'the', 'das'].includes(x.low),\n );\n let recipient = 'me';\n if (who.length && !(who.length === 1 && ME.has(who[0].low))) {\n recipient = join(who.filter(x => !ME.has(x.low)));\n }\n // \"… ein Bild der Haustür per Telegram\": the messenger is not part of the camera\n let tail = w.slice(pic + 1);\n const via = tail.findIndex(x => ['per', 'über', 'ueber', 'via', 'по', 'через'].includes(x.low));\n if (via > 0) {\n tail = tail.slice(0, via);\n }\n while (tail.length && (LINK_WORDS.has(tail[0].low) || ARTICLES.has(tail[0].low))) {\n tail = tail.slice(1);\n }\n if (!tail.length) {\n return null;\n }\n const target = showTarget(join(tail));\n const camera = target.kind === 'camera' || target.kind === 'unknown' ? target.name : join(tail);\n return camera ? { recipient, camera, cameraWord: target.kind === 'camera', language } : null;\n}\n\n// ── Replies ─────────────────────────────────────────────────────────────────\n\nexport type QuickReplyKey =\n | 'calling'\n | 'callFailed'\n | 'unknownCallee'\n | 'whichCallee'\n | 'showing'\n | 'showFailed'\n | 'unknownScreen'\n | 'whichScreen'\n | 'cannotShow'\n | 'pictureSent'\n | 'pictureFailed'\n | 'unknownCamera'\n | 'whichCamera'\n | 'unknownRecipient'\n | 'noControl';\n\nexport interface QuickReplyValues {\n name?: string;\n what?: string;\n names?: string[];\n error?: string;\n}\n\nconst list = (lang: QuickLanguage, names: string[] = []): string => {\n const and = lang === 'de' ? 'oder' : lang === 'ru' ? 'или' : 'or';\n return names.length > 1 ? `${names.slice(0, -1).join(', ')} ${and} ${names[names.length - 1]}` : names[0] || '';\n};\n\n/** The answer of a quick command, in the language of the question. */\nexport function quickReply(language: string, key: QuickReplyKey, v: QuickReplyValues = {}): string {\n const lang: QuickLanguage = language === 'de' || language === 'ru' ? language : 'en';\n const n = v.name || '';\n const what = v.what || '';\n const names = list(lang, v.names);\n const known = names\n ? lang === 'de'\n ? ` Ich kenne: ${names}.`\n : lang === 'ru'\n ? ` Есть: ${names}.`\n : ` I know: ${names}.`\n : '';\n const err = v.error ? `: ${v.error}` : '.';\n const texts: Record<QuickLanguage, Record<QuickReplyKey, string>> = {\n de: {\n calling: `Ich rufe ${n} an.`,\n callFailed: `Der Anruf bei ${n} ging nicht${err}`,\n unknownCallee: `Ich kenne ${n} nicht.${known}`,\n whichCallee: `Wen meinst du: ${names}?`,\n showing: `Ich zeige ${what} auf ${n}.`,\n showFailed: `${n} hat ${what} nicht gezeigt${err}`,\n unknownScreen: `Den Bildschirm ${n} kenne ich nicht.${known}`,\n whichScreen: `Auf welchem Bildschirm: ${names}?`,\n cannotShow: `${n} kann das nicht zeigen.`,\n pictureSent: `Ich habe ${n || 'dir'} das Bild von ${what} geschickt.`,\n pictureFailed: `Das Bild von ${what} kam nicht${err}`,\n unknownCamera: `Die Kamera ${n} kenne ich nicht.${known}`,\n whichCamera: `Welche Kamera meinst du: ${names}?`,\n unknownRecipient: `An ${n} kann ich nichts schicken.${known}`,\n noControl: 'Das Steuern von Geräten ist in den Einstellungen nicht erlaubt.',\n },\n en: {\n calling: `Calling ${n}.`,\n callFailed: `The call to ${n} did not work${err}`,\n unknownCallee: `I don't know ${n}.${known}`,\n whichCallee: `Whom do you mean: ${names}?`,\n showing: `Showing ${what} on ${n}.`,\n showFailed: `${n} did not show ${what}${err}`,\n unknownScreen: `I don't know the screen ${n}.${known}`,\n whichScreen: `On which screen: ${names}?`,\n cannotShow: `${n} cannot show that.`,\n pictureSent: `I sent ${n || 'you'} the picture of ${what}.`,\n pictureFailed: `The picture of ${what} did not come${err}`,\n unknownCamera: `I don't know the camera ${n}.${known}`,\n whichCamera: `Which camera do you mean: ${names}?`,\n unknownRecipient: `I cannot send anything to ${n}.${known}`,\n noControl: 'Controlling devices is not allowed in the settings.',\n },\n ru: {\n calling: `Звоню: ${n}.`,\n callFailed: `Позвонить (${n}) не получилось${err}`,\n unknownCallee: `Не знаю, кто такой ${n}.${known}`,\n whichCallee: `Кого ты имеешь в виду: ${names}?`,\n showing: `Показываю ${what} на экране ${n}.`,\n showFailed: `Экран ${n} не показал ${what}${err}`,\n unknownScreen: `Экран ${n} мне неизвестен.${known}`,\n whichScreen: `На каком экране: ${names}?`,\n cannotShow: `${n} не умеет это показывать.`,\n pictureSent: `Отправила ${n ? `(${n})` : 'тебе'} снимок: ${what}.`,\n pictureFailed: `Снимок (${what}) не пришёл${err}`,\n unknownCamera: `Камера ${n} мне неизвестна.${known}`,\n whichCamera: `Какую камеру ты имеешь в виду: ${names}?`,\n unknownRecipient: `Не могу ничего отправить: ${n}.${known}`,\n noControl: 'Управление устройствами запрещено в настройках.',\n },\n };\n return texts[lang][key];\n}\n"]}
1
+ {"version":3,"file":"quick.js","sourceRoot":"","sources":["../../src/lib/quick.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAkEH,4BAoBC;AAuBD,8BAmBC;AAcD,4CA+CC;AAgCD,gDAwBC;AAkBD,gCAkCC;AAkCD,kDAgCC;AAoCD,gCAmEC;AAtcD,SAAS,KAAK,CAAC,IAAY;IACvB,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,2CAA2C,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC7E,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAA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C,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,YAAY,IAAI,GAAG;YAC1G,aAAa,EAAE,WAAW,IAAI,cAAc,GAAG,EAAE;YACjD,aAAa,EAAE,UAAU,CAAC,mBAAmB,KAAK,EAAE;YACpD,WAAW,EAAE,kCAAkC,KAAK,GAAG;YACvD,gBAAgB,EAAE,6BAA6B,CAAC,IAAI,KAAK,EAAE;YAC3D,SAAS,EAAE,iDAAiD;SAC/D;KACJ,CAAC;IACF,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * Quick commands for the families of the shared catalog (`HELP.md`), understood without a model: \"Ruf Anna an\"\n * (`phone.call`), \"Zeige die Haustür auf dem Küchendisplay\" (`screen.show`), \"Schick mir ein Bild der Haustür\"\n * (`camera.snapshot` → `message.send`). The parsers only split the sentence; which names exist (screens, cameras,\n * recipients) is asked from the instances by the caller, and a sentence whose names fit nothing goes on to the\n * other tiers.\n */\n\nimport type { VoiceGender } from './voice/speechLanguage';\n\nexport type QuickLanguage = 'de' | 'en' | 'ru';\n\n/** A word of the sentence: as written (for names and texts) and lower case (for matching). */\ninterface Word {\n raw: string;\n low: string;\n}\n\nfunction words(text: string): Word[] {\n return [...text.matchAll(/[\\p{L}\\p{N}+#*]+(?:['’-][\\p{L}\\p{N}]+)*/gu)].map(m => ({\n raw: m[0],\n low: m[0].toLowerCase().replace(/ё/g, 'е'),\n }));\n}\n\nconst join = (list: Word[]): string => list.map(w => w.raw).join(' ');\n\n/** Polite words, taken away at the start and the end. */\nconst POLITE = new Set([\n 'bitte',\n 'mal',\n 'doch',\n 'kannst',\n 'du',\n 'könntest',\n 'please',\n 'can',\n 'could',\n 'you',\n 'пожалуйста',\n 'можешь',\n 'ну',\n]);\nconst ARTICLES = new Set(['der', 'die', 'das', 'den', 'dem', 'des', 'ein', 'eine', 'einen', 'einem', 'the', 'a', 'an']);\n\nfunction trimPolite(list: Word[]): Word[] {\n let a = 0;\n let b = list.length;\n while (a < b && POLITE.has(list[a].low)) {\n a++;\n }\n while (b > a && POLITE.has(list[b - 1].low)) {\n b--;\n }\n return list.slice(a, b);\n}\n\nfunction trimArticles(list: Word[]): Word[] {\n let a = 0;\n while (a < list.length && ARTICLES.has(list[a].low)) {\n a++;\n }\n return list.slice(a);\n}\n\n/**\n * A said name fits a known one: the same without case, or every said word is a word of the name up to an ending\n * (\"Anne\"/\"Anna\", \"Küche\"/\"Küchendisplay\" does not, \"кухню\"/\"Кухня\" does).\n *\n * @param said as said\n * @param name as known\n */\nexport function nameFits(said: string, name: string): boolean {\n const a = said\n .toLowerCase()\n .replace(/ё/g, 'е')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n const b = name\n .toLowerCase()\n .replace(/ё/g, 'е')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n if (!a || !b) {\n return false;\n }\n if (a === b || a.replace(/ /g, '') === b.replace(/ /g, '')) {\n return true;\n }\n const saidWords = a.split(' ');\n const nameWords = b.split(' ');\n return saidWords.every(s => nameWords.some(n => sameStem(s, n)));\n}\n\n/** One word for another up to an inflected ending of at most two letters (\"кухню\"/\"кухня\", \"Annas\"/\"Anna\"). */\nfunction sameStem(a: string, b: string): boolean {\n if (a === b) {\n return true;\n }\n const short = a.length < b.length ? a : b;\n const long = a.length < b.length ? b : a;\n if (short.length < 3 || long.length - short.length > 2) {\n return false;\n }\n let common = 0;\n while (common < short.length && short[common] === long[common]) {\n common++;\n }\n return common >= Math.max(3, short.length - 1);\n}\n\n/**\n * The best of several named things for a said name: an exact name, then an exact room, then a fitting name, then a\n * fitting room. Several fit equally → all of them (the caller asks back).\n */\nexport function pickNamed<T extends { id: string; name: string; room?: string }>(items: T[], said: string): T[] {\n const s = said.trim();\n if (!s) {\n return [];\n }\n const low = s.toLowerCase();\n const rules: ((i: T) => boolean)[] = [\n i => i.name.toLowerCase() === low || i.id.toLowerCase() === low,\n i => !!i.room && i.room.toLowerCase() === low,\n i => nameFits(s, i.name),\n i => !!i.room && nameFits(s, i.room),\n ];\n for (const rule of rules) {\n const hits = items.filter(rule);\n if (hits.length) {\n return hits;\n }\n }\n return [];\n}\n\n// ── phone.call ──────────────────────────────────────────────────────────────\n\nexport interface CallCommand {\n /** A name or a number, as said */\n to: string;\n language: QuickLanguage;\n}\n\n/**\n * \"Ruf Anna an\", \"Rufe bitte die Küche an\", \"Anna anrufen\", \"Verbinde mich mit der Tür\", \"Call Anna\", \"Connect me\n * with the door\", \"Позвони Анне\", \"Набери 0171 2345\". Null for anything else (\"Wer hat angerufen?\").\n */\nexport function parseCallCommand(text: string): CallCommand | null {\n const w = trimPolite(words(text));\n if (w.length < 2) {\n return null;\n }\n const first = w[0].low;\n const last = w[w.length - 1].low;\n let target: Word[] | null = null;\n let language: QuickLanguage = 'de';\n if ((first === 'ruf' || first === 'rufe') && last === 'an' && w.length >= 3) {\n target = w.slice(1, -1);\n } else if (last === 'anrufen' && w.length >= 2 && !['wer', 'wen', 'kann', 'soll'].includes(first)) {\n target = w.slice(0, -1);\n } else if (first === 'verbinde' && w[1]?.low === 'mich' && w[2]?.low === 'mit') {\n target = w.slice(3);\n } else if (first === 'telefoniere' && w[1]?.low === 'mit') {\n target = w.slice(2);\n } else if (first === 'waehle' || first === 'wähle') {\n target = w.slice(1);\n } else if (['call', 'phone', 'ring', 'dial'].includes(first)) {\n language = 'en';\n target = w.slice(1);\n } else if (first === 'connect' && w[1]?.low === 'me' && ['with', 'to'].includes(w[2]?.low)) {\n language = 'en';\n target = w.slice(3);\n } else if (['позвони', 'позвонить', 'набери', 'звони', 'вызови'].includes(first)) {\n language = 'ru';\n target = w.slice(1);\n } else if (first === 'соедини' && w[1]?.low === 'меня' && ['с', 'со'].includes(w[2]?.low)) {\n language = 'ru';\n target = w.slice(3);\n }\n if (!target) {\n return null;\n }\n target = trimArticles(trimPolite(target));\n if (!target.length || target.length > 5) {\n return null;\n }\n // \"call me back\", \"ruf mich an\": no target\n if (['me', 'mich', 'uns', 'us', 'мне', 'меня', 'back'].includes(target[0].low)) {\n return null;\n }\n const said = join(target);\n // a number with spaces: \"0171 234 56\"\n const to = /^[+\\d][\\d ]+$/.test(said) ? said.replace(/ /g, '') : said;\n return { to, language };\n}\n\n// ── screen.show ─────────────────────────────────────────────────────────────\n\nexport interface ShowOnCommand {\n /** What to show, as said (\"die Haustür\", \"die Kamera Einfahrt\", \"die Ansicht Wetter\") */\n what: string;\n /** Where, as said (\"Küchendisplay\", \"Wohnzimmer\"); '' = not said */\n screen: string;\n language: QuickLanguage;\n}\n\nconst SHOW_VERBS: Record<string, QuickLanguage> = {\n zeig: 'de',\n zeige: 'de',\n zeigen: 'de',\n show: 'en',\n display: 'en',\n покажи: 'ru',\n показать: 'ru',\n выведи: 'ru',\n отобрази: 'ru',\n};\nconst SHOW_FILLERS = new Set(['mir', 'uns', 'me', 'us', 'мне', 'нам']);\n/** The preposition before the screen: \"auf dem Fernseher\", \"im Wohnzimmer\", \"on the TV\", \"на телевизоре\". */\nconst SCREEN_PREPOSITIONS = new Set(['auf', 'im', 'am', 'on', 'на', 'в', 'во']);\n\n/**\n * \"Zeige die Haustür auf dem Küchendisplay\", \"Zeig mir die Kamera Einfahrt im Wohnzimmer\", \"Show the front door on\n * the TV\", \"Покажи камеру у входа на телевизоре\". The last preposition before a screen splits the sentence (the\n * camera \"an der Haustür\" stays in `what`). Null without a show verb or without anything to show.\n */\nexport function parseShowOnCommand(text: string): ShowOnCommand | null {\n const w = trimPolite(words(text));\n const language = w.length ? SHOW_VERBS[w[0].low] : undefined;\n if (!language) {\n return null;\n }\n let rest = w.slice(1);\n while (rest.length && (SHOW_FILLERS.has(rest[0].low) || POLITE.has(rest[0].low))) {\n rest = rest.slice(1);\n }\n rest = trimPolite(rest);\n let split = -1;\n for (let i = rest.length - 1; i > 0; i--) {\n if (SCREEN_PREPOSITIONS.has(rest[i].low) || (rest[i].low === 'in' && i > 0)) {\n split = i;\n break;\n }\n }\n const whatWords = trimArticles(split > 0 ? rest.slice(0, split) : rest);\n const screenWords = split > 0 ? trimArticles(rest.slice(split + 1)) : [];\n if (!whatWords.length) {\n return null;\n }\n return { what: join(whatWords), screen: join(screenWords), language };\n}\n\n/** What a show request names: a camera, a view or a text; the name is without the kind word. */\nexport interface ShowTarget {\n kind: 'camera' | 'view' | 'text' | 'unknown';\n name: string;\n}\n\nconst CAMERA_WORDS = /^(kamera|kameras|camera|cam|livebild|videobild|камер\\p{L}*|видеокамер\\p{L}*)$/u;\nconst VIEW_WORDS = /^(ansicht|seite|view|page|screen|вид|страниц\\p{L}*|экран)$/u;\nconst TEXT_WORDS = /^(text|nachricht|message|текст|сообщение|надпись)$/u;\nconst LINK_WORDS = new Set(['von', 'vom', 'der', 'des', 'of', 'from', 'the', 'с', 'со', 'у', 'из']);\n\n/**\n * What kind of thing a show request names: \"Kamera Einfahrt\" / \"die Einfahrt-Kamera\" / \"камеру у входа\" = camera,\n * \"die Ansicht Wetter\" = view, \"den Text Essen ist fertig\" = text (as written); else unknown with the whole name\n * (the caller looks it up among cameras and views).\n */\nexport function showTarget(what: string): ShowTarget {\n const w = trimArticles(words(what));\n if (!w.length) {\n return { kind: 'unknown', name: '' };\n }\n if (TEXT_WORDS.test(w[0].low)) {\n // the text as said, punctuation included\n const m = what.match(/^\\s*(?:(?:der|die|das|den|the)\\s+)?\\S+\\s+(.*)$/iu);\n return { kind: 'text', name: (m?.[1] || '').trim() };\n }\n /** The words without the one that says the kind (and \"von\", \"of\", \"у\" …); null when no word says it. */\n const without = (re: RegExp): string | null => {\n const i = w.findIndex(x => re.test(x.low));\n return i < 0 ? null : join(w.filter((x, j) => j !== i && !LINK_WORDS.has(x.low) && !ARTICLES.has(x.low)));\n };\n const camera = without(CAMERA_WORDS);\n if (camera !== null) {\n return { kind: 'camera', name: camera };\n }\n // \"die Einfahrt-Kamera\", \"die Einfahrtkamera\": the word without the kind\n const compound = w.findIndex(x => /^\\p{L}{3,}-?(kamera|camera|cam)$/u.test(x.low));\n if (compound >= 0) {\n const own = w[compound].raw.replace(/-?(kamera|camera|cam)$/iu, '');\n const others = w.filter((x, j) => j !== compound && !LINK_WORDS.has(x.low) && !ARTICLES.has(x.low));\n return {\n kind: 'camera',\n name: join([...others.slice(0, compound), { raw: own, low: own }, ...others.slice(compound)]),\n };\n }\n const view = without(VIEW_WORDS);\n if (view !== null) {\n return { kind: 'view', name: view };\n }\n return { kind: 'unknown', name: join(w) };\n}\n\n// ── camera.snapshot → message.send ──────────────────────────────────────────\n\nexport interface PictureCommand {\n /** `me` = the one who asks, else a name as said */\n recipient: string;\n /** The camera, as said (\"Haustür\", \"Einfahrt\") */\n camera: string;\n /** A word like \"Kamera\" was said: an unknown name gets an honest answer instead of going on */\n cameraWord: boolean;\n language: QuickLanguage;\n}\n\nconst SEND_VERBS: Record<string, QuickLanguage> = {\n schick: 'de',\n schicke: 'de',\n sende: 'de',\n send: 'en',\n text: 'en',\n пришли: 'ru',\n отправь: 'ru',\n скинь: 'ru',\n пошли: 'ru',\n вышли: 'ru',\n};\nconst PICTURE_WORDS =\n /^(bild|bilder|foto|fotos|schnappschuss|snapshot|aufnahme|picture|photo|image|pic|фото|фотку|фотографию|снимок|картинку|изображение|кадр)$/u;\nconst ME = new Set(['mir', 'uns', 'me', 'us', 'мне', 'нам']);\n\n/**\n * \"Schick mir ein Bild der Haustür\", \"Sende Anna ein Foto von der Einfahrt\", \"Send me a picture of the front door\n * camera\", \"Пришли мне фото с камеры у входа\". Null without a send verb and a picture word.\n */\nexport function parsePictureCommand(text: string): PictureCommand | null {\n const w = trimPolite(words(text));\n const language = w.length ? SEND_VERBS[w[0].low] : undefined;\n if (!language) {\n return null;\n }\n const pic = w.findIndex((x, i) => i > 0 && PICTURE_WORDS.test(x.low));\n if (pic < 1) {\n return null;\n }\n const who = trimArticles(w.slice(1, pic)).filter(\n x => !['ein', 'eine', 'einen', 'a', 'an', 'the', 'das'].includes(x.low),\n );\n let recipient = 'me';\n if (who.length && !(who.length === 1 && ME.has(who[0].low))) {\n recipient = join(who.filter(x => !ME.has(x.low)));\n }\n // \"… ein Bild der Haustür per Telegram\": the messenger is not part of the camera\n let tail = w.slice(pic + 1);\n const via = tail.findIndex(x => ['per', 'über', 'ueber', 'via', 'по', 'через'].includes(x.low));\n if (via > 0) {\n tail = tail.slice(0, via);\n }\n while (tail.length && (LINK_WORDS.has(tail[0].low) || ARTICLES.has(tail[0].low))) {\n tail = tail.slice(1);\n }\n if (!tail.length) {\n return null;\n }\n const target = showTarget(join(tail));\n const camera = target.kind === 'camera' || target.kind === 'unknown' ? target.name : join(tail);\n return camera ? { recipient, camera, cameraWord: target.kind === 'camera', language } : null;\n}\n\n// ── Replies ─────────────────────────────────────────────────────────────────\n\nexport type QuickReplyKey =\n | 'calling'\n | 'callFailed'\n | 'unknownCallee'\n | 'whichCallee'\n | 'showing'\n | 'showFailed'\n | 'unknownScreen'\n | 'whichScreen'\n | 'cannotShow'\n | 'pictureSent'\n | 'pictureFailed'\n | 'unknownCamera'\n | 'whichCamera'\n | 'unknownRecipient'\n | 'noControl';\n\nexport interface QuickReplyValues {\n name?: string;\n what?: string;\n names?: string[];\n error?: string;\n /** Gender of the voice: «отправила» or «отправил» ('' = female) */\n gender?: VoiceGender | '';\n}\n\nconst list = (lang: QuickLanguage, names: string[] = []): string => {\n const and = lang === 'de' ? 'oder' : lang === 'ru' ? 'или' : 'or';\n return names.length > 1 ? `${names.slice(0, -1).join(', ')} ${and} ${names[names.length - 1]}` : names[0] || '';\n};\n\n/** The answer of a quick command, in the language of the question. */\nexport function quickReply(language: string, key: QuickReplyKey, v: QuickReplyValues = {}): string {\n const lang: QuickLanguage = language === 'de' || language === 'ru' ? language : 'en';\n const n = v.name || '';\n const what = v.what || '';\n const names = list(lang, v.names);\n const known = names\n ? lang === 'de'\n ? ` Ich kenne: ${names}.`\n : lang === 'ru'\n ? ` Есть: ${names}.`\n : ` I know: ${names}.`\n : '';\n const err = v.error ? `: ${v.error}` : '.';\n const texts: Record<QuickLanguage, Record<QuickReplyKey, string>> = {\n de: {\n calling: `Ich rufe ${n} an.`,\n callFailed: `Der Anruf bei ${n} ging nicht${err}`,\n unknownCallee: `Ich kenne ${n} nicht.${known}`,\n whichCallee: `Wen meinst du: ${names}?`,\n showing: `Ich zeige ${what} auf ${n}.`,\n showFailed: `${n} hat ${what} nicht gezeigt${err}`,\n unknownScreen: `Den Bildschirm ${n} kenne ich nicht.${known}`,\n whichScreen: `Auf welchem Bildschirm: ${names}?`,\n cannotShow: `${n} kann das nicht zeigen.`,\n pictureSent: `Ich habe ${n || 'dir'} das Bild von ${what} geschickt.`,\n pictureFailed: `Das Bild von ${what} kam nicht${err}`,\n unknownCamera: `Die Kamera ${n} kenne ich nicht.${known}`,\n whichCamera: `Welche Kamera meinst du: ${names}?`,\n unknownRecipient: `An ${n} kann ich nichts schicken.${known}`,\n noControl: 'Das Steuern von Geräten ist in den Einstellungen nicht erlaubt.',\n },\n en: {\n calling: `Calling ${n}.`,\n callFailed: `The call to ${n} did not work${err}`,\n unknownCallee: `I don't know ${n}.${known}`,\n whichCallee: `Whom do you mean: ${names}?`,\n showing: `Showing ${what} on ${n}.`,\n showFailed: `${n} did not show ${what}${err}`,\n unknownScreen: `I don't know the screen ${n}.${known}`,\n whichScreen: `On which screen: ${names}?`,\n cannotShow: `${n} cannot show that.`,\n pictureSent: `I sent ${n || 'you'} the picture of ${what}.`,\n pictureFailed: `The picture of ${what} did not come${err}`,\n unknownCamera: `I don't know the camera ${n}.${known}`,\n whichCamera: `Which camera do you mean: ${names}?`,\n unknownRecipient: `I cannot send anything to ${n}.${known}`,\n noControl: 'Controlling devices is not allowed in the settings.',\n },\n ru: {\n calling: `Звоню: ${n}.`,\n callFailed: `Позвонить (${n}) не получилось${err}`,\n unknownCallee: `Не знаю, кто такой ${n}.${known}`,\n whichCallee: `Кого ты имеешь в виду: ${names}?`,\n showing: `Показываю ${what} на экране ${n}.`,\n showFailed: `Экран ${n} не показал ${what}${err}`,\n unknownScreen: `Экран ${n} мне неизвестен.${known}`,\n whichScreen: `На каком экране: ${names}?`,\n cannotShow: `${n} не умеет это показывать.`,\n pictureSent: `${v.gender === 'male' ? 'Отправил' : 'Отправила'} ${n ? `(${n})` : 'тебе'} снимок: ${what}.`,\n pictureFailed: `Снимок (${what}) не пришёл${err}`,\n unknownCamera: `Камера ${n} мне неизвестна.${known}`,\n whichCamera: `Какую камеру ты имеешь в виду: ${names}?`,\n unknownRecipient: `Не могу ничего отправить: ${n}.${known}`,\n noControl: 'Управление устройствами запрещено в настройках.',\n },\n };\n return texts[lang][key];\n}\n"]}
@@ -21,6 +21,23 @@ const DEFAULT_POLLY_VOICE = {
21
21
  pl: 'Ewa',
22
22
  pt: 'Ines',
23
23
  };
24
+ /** The default voices are all female (Polly's voice list); used when the list cannot be read. */
25
+ const DEFAULT_POLLY_GENDER = Object.fromEntries(Object.values(DEFAULT_POLLY_VOICE).map(voice => [voice, 'female']));
26
+ /** Voice id (lower case) → gender of every Polly voice, all pages of DescribeVoices. */
27
+ async function pollyGenders(client) {
28
+ const genders = new Map();
29
+ let token;
30
+ do {
31
+ const res = await client.send(new client_polly_1.DescribeVoicesCommand(token ? { NextToken: token } : {}));
32
+ for (const v of res.Voices || []) {
33
+ if (v.Id && (v.Gender === 'Female' || v.Gender === 'Male')) {
34
+ genders.set(v.Id.toLowerCase(), v.Gender === 'Female' ? 'female' : 'male');
35
+ }
36
+ }
37
+ token = res.NextToken;
38
+ } while (token);
39
+ return genders;
40
+ }
24
41
  /** ~100 ms of 16 kHz mono 16-bit PCM per Transcribe audio chunk. */
25
42
  const STT_CHUNK_BYTES = 3200;
26
43
  /** List available Polly voice ids, optionally filtered by language (locale, e.g. 'de-DE'). */
@@ -93,12 +110,25 @@ class AwsTts {
93
110
  synthesizeSsml(ssml, lang) {
94
111
  return this.speak(ssml, lang, 'ssml');
95
112
  }
96
- async speak(text, lang, textType) {
113
+ /** The voice that speaks `lang`: the set voice only for its language — Vicki reads no Russian, Tatyana does. */
114
+ voiceFor(lang) {
97
115
  const iso = (lang || 'en').split('-')[0].toLowerCase();
98
116
  const home = (this.language || '').split('-')[0].toLowerCase();
99
- // the set voice only for its language: Vicki reads no Russian, Tatyana does
100
117
  const own = this.voice && (!home || iso === home || !DEFAULT_POLLY_VOICE[iso]) ? this.voice : '';
101
- const voice = own || DEFAULT_POLLY_VOICE[iso] || this.voice || 'Joanna';
118
+ return own || DEFAULT_POLLY_VOICE[iso] || this.voice || 'Joanna';
119
+ }
120
+ /** Gender of every Polly voice (one DescribeVoices), once. */
121
+ genders = null;
122
+ async voiceGender(lang) {
123
+ const voice = this.voiceFor(lang);
124
+ this.genders ??= pollyGenders(this.client).catch(() => {
125
+ this.genders = null; // try again next time
126
+ return new Map();
127
+ });
128
+ return (await this.genders).get(voice.toLowerCase()) || DEFAULT_POLLY_GENDER[voice] || '';
129
+ }
130
+ async speak(text, lang, textType) {
131
+ const voice = this.voiceFor(lang);
102
132
  const resp = await this.client.send(new client_polly_1.SynthesizeSpeechCommand({
103
133
  Text: text,
104
134
  TextType: textType,
@@ -1 +1 @@
1
- {"version":3,"file":"aws.js","sourceRoot":"","sources":["../../../src/lib/voice/aws.ts"],"names":[],"mappings":";;;AA4CA,0CASC;AArDD;;;GAGG;AACH,wDAM+B;AAC/B,sFAK8C;AAC9C,iCAAqC;AAUrC,2EAA2E;AAC3E,MAAM,mBAAmB,GAA2B;IAChD,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,QAAQ;IACZ,EAAE,EAAE,SAAS;IACb,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,QAAQ;IACZ,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,MAAM;CACb,CAAC;AAEF,oEAAoE;AACpE,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,8FAA8F;AACvF,K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,CAAC,CACL,CAAC;QACF,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACtD,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,oBAAoB,EAAE,CAAC;QAC5D,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC1D,CAAC;CACJ;AA9CD,wBA8CC","sourcesContent":["/**\n * AWS speech engines: STT via Amazon Transcribe (streaming) and TTS via Amazon Polly.\n * Credentials: accessKeyId + secretAccessKey + region.\n */\nimport {\n PollyClient,\n SynthesizeSpeechCommand,\n DescribeVoicesCommand,\n type VoiceId,\n type LanguageCode as PollyLanguageCode,\n} from '@aws-sdk/client-polly';\nimport {\n TranscribeStreamingClient,\n StartStreamTranscriptionCommand,\n type AudioStream,\n type LanguageCode,\n} from '@aws-sdk/client-transcribe-streaming';\nimport { isoToLocale } from './lang';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\n\nexport interface AwsCreds {\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n}\n\n/** Reasonable default Polly voice per language when none is configured. */\nconst DEFAULT_POLLY_VOICE: Record<string, string> = {\n de: 'Vicki',\n en: 'Joanna',\n ru: 'Tatyana',\n fr: 'Lea',\n it: 'Bianca',\n es: 'Lucia',\n nl: 'Laura',\n pl: 'Ewa',\n pt: 'Ines',\n};\n\n/** ~100 ms of 16 kHz mono 16-bit PCM per Transcribe audio chunk. */\nconst STT_CHUNK_BYTES = 3200;\n\n/** List available Polly voice ids, optionally filtered by language (locale, e.g. 'de-DE'). */\nexport async function listPollyVoices(creds: AwsCreds, languageCode: string): Promise<string[]> {\n const client = new PollyClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n const res = await client.send(\n new DescribeVoicesCommand(languageCode ? { LanguageCode: languageCode as PollyLanguageCode } : {}),\n );\n return (res.Voices || []).map(v => v.Id).filter((id): id is VoiceId => !!id);\n}\n\nexport class AwsStt implements SttEngine {\n private readonly client: TranscribeStreamingClient;\n\n constructor(creds: AwsCreds) {\n this.client = new TranscribeStreamingClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n }\n\n // Note: the SttEngine `hints` vocabulary is intentionally not applied here. Amazon Transcribe biases\n // only via a *custom vocabulary* that must be created/registered ahead of time (CreateVocabulary) and\n // referenced by name — there is no inline per-request word list for streaming. So we skip biasing for AWS.\n async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {\n // Must be an async generator: Transcribe's AudioStream is an AsyncIterable.\n // eslint-disable-next-line @typescript-eslint/require-await\n async function* audio(): AsyncGenerator<AudioStream> {\n for (let off = 0; off < pcm.length; off += STT_CHUNK_BYTES) {\n yield { AudioEvent: { AudioChunk: pcm.subarray(off, off + STT_CHUNK_BYTES) } };\n }\n }\n\n const resp = await this.client.send(\n new StartStreamTranscriptionCommand({\n LanguageCode: isoToLocale(lang) as LanguageCode,\n MediaSampleRateHertz: sampleRate,\n MediaEncoding: 'pcm',\n AudioStream: audio(),\n }),\n );\n\n let text = '';\n for await (const event of resp.TranscriptResultStream || []) {\n for (const result of event.TranscriptEvent?.Transcript?.Results || []) {\n const transcript = result.Alternatives?.[0]?.Transcript;\n if (!result.IsPartial && transcript) {\n text += (text ? ' ' : '') + transcript;\n }\n }\n }\n return text.trim();\n }\n}\n\nexport class AwsTts implements TtsEngine {\n private readonly client: PollyClient;\n\n constructor(\n creds: AwsCreds,\n /** Polly VoiceId (e.g. 'Vicki', 'Tatyana'); empty → default per language. */\n private readonly voice: string,\n /** Language the voice is set for ('' = every language); Polly voice ids do not tell it. */\n private readonly language = '',\n ) {\n this.client = new PollyClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.speak(text, lang, 'text');\n }\n\n /** Polly speaks SSML natively (`TextType: 'ssml'`), so pauses and emphasis survive. */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n return this.speak(ssml, lang, 'ssml');\n }\n\n private async speak(text: string, lang: string, textType: 'text' | 'ssml'): Promise<TtsResult> {\n const iso = (lang || 'en').split('-')[0].toLowerCase();\n const home = (this.language || '').split('-')[0].toLowerCase();\n // the set voice only for its language: Vicki reads no Russian, Tatyana does\n const own = this.voice && (!home || iso === home || !DEFAULT_POLLY_VOICE[iso]) ? this.voice : '';\n const voice = own || DEFAULT_POLLY_VOICE[iso] || this.voice || 'Joanna';\n const resp = await this.client.send(\n new SynthesizeSpeechCommand({\n Text: text,\n TextType: textType,\n OutputFormat: 'pcm', // 16-bit signed 1-channel little-endian\n SampleRate: '16000',\n VoiceId: voice as VoiceId,\n }),\n );\n if (!resp.AudioStream) {\n throw new Error('Polly returned no audio stream');\n }\n const bytes = await resp.AudioStream.transformToByteArray();\n return { pcm: Buffer.from(bytes), sampleRate: 16000 };\n }\n}\n"]}
1
+ {"version":3,"file":"aws.js","sourceRoot":"","sources":["../../../src/lib/voice/aws.ts"],"names":[],"mappings":";;;AAkEA,0CASC;AA3ED;;;GAGG;AACH,wDAM+B;AAC/B,sFAK8C;AAC9C,iCAAqC;AAWrC,2EAA2E;AAC3E,MAAM,mBAAmB,GAA2B;IAChD,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,QAAQ;IACZ,EAAE,EAAE,SAAS;IACb,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,QAAQ;IACZ,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,OAAO;IACX,EAAE,EAAE,KAAK;IACT,EAAE,EAAE,MAAM;CACb,CAAC;AAEF,iGAAiG;AACjG,MAAM,oBAAoB,GAAgC,MAAM,CAAC,WAAW,CACxE,MAAM,CAAC,MAAM,CAAC,m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,CAAC;IAC9F,CAAC;IAEO,KAAK,CAAC,KAAK,CAAC,IAAY,EAAE,IAAY,EAAE,QAAyB;QACrE,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAClC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAC/B,IAAI,sCAAuB,CAAC;YACxB,IAAI,EAAE,IAAI;YACV,QAAQ,EAAE,QAAQ;YAClB,YAAY,EAAE,KAAK,EAAE,wCAAwC;YAC7D,UAAU,EAAE,OAAO;YACnB,OAAO,EAAE,KAAgB;SAC5B,CAAC,CACL,CAAC;QACF,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACtD,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,oBAAoB,EAAE,CAAC;QAC5D,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC1D,CAAC;CACJ;AA9DD,wBA8DC","sourcesContent":["/**\n * AWS speech engines: STT via Amazon Transcribe (streaming) and TTS via Amazon Polly.\n * Credentials: accessKeyId + secretAccessKey + region.\n */\nimport {\n PollyClient,\n SynthesizeSpeechCommand,\n DescribeVoicesCommand,\n type VoiceId,\n type LanguageCode as PollyLanguageCode,\n} from '@aws-sdk/client-polly';\nimport {\n TranscribeStreamingClient,\n StartStreamTranscriptionCommand,\n type AudioStream,\n type LanguageCode,\n} from '@aws-sdk/client-transcribe-streaming';\nimport { isoToLocale } from './lang';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceGender } from './voiceGender';\n\nexport interface AwsCreds {\n accessKeyId: string;\n secretAccessKey: string;\n region: string;\n}\n\n/** Reasonable default Polly voice per language when none is configured. */\nconst DEFAULT_POLLY_VOICE: Record<string, string> = {\n de: 'Vicki',\n en: 'Joanna',\n ru: 'Tatyana',\n fr: 'Lea',\n it: 'Bianca',\n es: 'Lucia',\n nl: 'Laura',\n pl: 'Ewa',\n pt: 'Ines',\n};\n\n/** The default voices are all female (Polly's voice list); used when the list cannot be read. */\nconst DEFAULT_POLLY_GENDER: Record<string, VoiceGender> = Object.fromEntries(\n Object.values(DEFAULT_POLLY_VOICE).map(voice => [voice, 'female' as const]),\n);\n\n/** Voice id (lower case) → gender of every Polly voice, all pages of DescribeVoices. */\nasync function pollyGenders(client: PollyClient): Promise<Map<string, VoiceGender>> {\n const genders = new Map<string, VoiceGender>();\n let token: string | undefined;\n do {\n const res = await client.send(new DescribeVoicesCommand(token ? { NextToken: token } : {}));\n for (const v of res.Voices || []) {\n if (v.Id && (v.Gender === 'Female' || v.Gender === 'Male')) {\n genders.set(v.Id.toLowerCase(), v.Gender === 'Female' ? 'female' : 'male');\n }\n }\n token = res.NextToken;\n } while (token);\n return genders;\n}\n\n/** ~100 ms of 16 kHz mono 16-bit PCM per Transcribe audio chunk. */\nconst STT_CHUNK_BYTES = 3200;\n\n/** List available Polly voice ids, optionally filtered by language (locale, e.g. 'de-DE'). */\nexport async function listPollyVoices(creds: AwsCreds, languageCode: string): Promise<string[]> {\n const client = new PollyClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n const res = await client.send(\n new DescribeVoicesCommand(languageCode ? { LanguageCode: languageCode as PollyLanguageCode } : {}),\n );\n return (res.Voices || []).map(v => v.Id).filter((id): id is VoiceId => !!id);\n}\n\nexport class AwsStt implements SttEngine {\n private readonly client: TranscribeStreamingClient;\n\n constructor(creds: AwsCreds) {\n this.client = new TranscribeStreamingClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n }\n\n // Note: the SttEngine `hints` vocabulary is intentionally not applied here. Amazon Transcribe biases\n // only via a *custom vocabulary* that must be created/registered ahead of time (CreateVocabulary) and\n // referenced by name — there is no inline per-request word list for streaming. So we skip biasing for AWS.\n async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {\n // Must be an async generator: Transcribe's AudioStream is an AsyncIterable.\n // eslint-disable-next-line @typescript-eslint/require-await\n async function* audio(): AsyncGenerator<AudioStream> {\n for (let off = 0; off < pcm.length; off += STT_CHUNK_BYTES) {\n yield { AudioEvent: { AudioChunk: pcm.subarray(off, off + STT_CHUNK_BYTES) } };\n }\n }\n\n const resp = await this.client.send(\n new StartStreamTranscriptionCommand({\n LanguageCode: isoToLocale(lang) as LanguageCode,\n MediaSampleRateHertz: sampleRate,\n MediaEncoding: 'pcm',\n AudioStream: audio(),\n }),\n );\n\n let text = '';\n for await (const event of resp.TranscriptResultStream || []) {\n for (const result of event.TranscriptEvent?.Transcript?.Results || []) {\n const transcript = result.Alternatives?.[0]?.Transcript;\n if (!result.IsPartial && transcript) {\n text += (text ? ' ' : '') + transcript;\n }\n }\n }\n return text.trim();\n }\n}\n\nexport class AwsTts implements TtsEngine {\n private readonly client: PollyClient;\n\n constructor(\n creds: AwsCreds,\n /** Polly VoiceId (e.g. 'Vicki', 'Tatyana'); empty → default per language. */\n private readonly voice: string,\n /** Language the voice is set for ('' = every language); Polly voice ids do not tell it. */\n private readonly language = '',\n ) {\n this.client = new PollyClient({\n region: creds.region,\n credentials: { accessKeyId: creds.accessKeyId, secretAccessKey: creds.secretAccessKey },\n });\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.speak(text, lang, 'text');\n }\n\n /** Polly speaks SSML natively (`TextType: 'ssml'`), so pauses and emphasis survive. */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n return this.speak(ssml, lang, 'ssml');\n }\n\n /** The voice that speaks `lang`: the set voice only for its language — Vicki reads no Russian, Tatyana does. */\n private voiceFor(lang: string): string {\n const iso = (lang || 'en').split('-')[0].toLowerCase();\n const home = (this.language || '').split('-')[0].toLowerCase();\n const own = this.voice && (!home || iso === home || !DEFAULT_POLLY_VOICE[iso]) ? this.voice : '';\n return own || DEFAULT_POLLY_VOICE[iso] || this.voice || 'Joanna';\n }\n\n /** Gender of every Polly voice (one DescribeVoices), once. */\n private genders: Promise<Map<string, VoiceGender>> | null = null;\n\n async voiceGender(lang: string): Promise<VoiceGender | ''> {\n const voice = this.voiceFor(lang);\n this.genders ??= pollyGenders(this.client).catch(() => {\n this.genders = null; // try again next time\n return new Map<string, VoiceGender>();\n });\n return (await this.genders).get(voice.toLowerCase()) || DEFAULT_POLLY_GENDER[voice] || '';\n }\n\n private async speak(text: string, lang: string, textType: 'text' | 'ssml'): Promise<TtsResult> {\n const voice = this.voiceFor(lang);\n const resp = await this.client.send(\n new SynthesizeSpeechCommand({\n Text: text,\n TextType: textType,\n OutputFormat: 'pcm', // 16-bit signed 1-channel little-endian\n SampleRate: '16000',\n VoiceId: voice as VoiceId,\n }),\n );\n if (!resp.AudioStream) {\n throw new Error('Polly returned no audio stream');\n }\n const bytes = await resp.AudioStream.transformToByteArray();\n return { pcm: Buffer.from(bytes), sampleRate: 16000 };\n }\n}\n"]}
@@ -57,6 +57,27 @@ async function listAzureVoices(key, region, locale) {
57
57
  synth.close();
58
58
  }
59
59
  }
60
+ /** The gender of an Azure voice ('de-DE-KatjaNeural') from the voice list of its locale. */
61
+ async function azureVoiceGender(key, region, voice) {
62
+ const speechConfig = sdk.SpeechConfig.fromSubscription(key, region);
63
+ const synth = new sdk.SpeechSynthesizer(speechConfig, null);
64
+ try {
65
+ const locale = /^[a-z]{2,3}-[A-Z]{2}/.exec(voice)?.[0] || '';
66
+ const res = await synth.getVoicesAsync(locale);
67
+ if (res.reason !== sdk.ResultReason.VoicesListRetrieved) {
68
+ throw new Error(res.errorDetails || 'Azure voice list failed');
69
+ }
70
+ const info = res.voices.find(v => v.shortName.toLowerCase() === voice.toLowerCase());
71
+ return info?.gender === sdk.SynthesisVoiceGender.Female
72
+ ? 'female'
73
+ : info?.gender === sdk.SynthesisVoiceGender.Male
74
+ ? 'male'
75
+ : '';
76
+ }
77
+ finally {
78
+ synth.close();
79
+ }
80
+ }
60
81
  /** Azure STT via `recognizeOnceAsync` fed from a PCM push stream (one short utterance). */
61
82
  class AzureStt {
62
83
  key;
@@ -118,6 +139,19 @@ class AzureTts {
118
139
  this.region = region;
119
140
  this.voice = voice;
120
141
  }
142
+ /** The gender of the set voice from Azure's voice list, once; '' for Azure's own voice of the language. */
143
+ gender = null;
144
+ voiceGender(lang) {
145
+ // without a voice that speaks the language Azure picks its own — which one, its API does not tell
146
+ if (!this.voice || !(0, speechLanguage_1.voiceFitsLanguage)(this.voice, lang)) {
147
+ return Promise.resolve('');
148
+ }
149
+ this.gender ??= azureVoiceGender(this.key, this.region, this.voice).catch(() => {
150
+ this.gender = null; // try again next time
151
+ return '';
152
+ });
153
+ return this.gender;
154
+ }
121
155
  synthesize(text, lang) {
122
156
  return this.speak(lang, (synth, resolve, reject) => synth.speakTextAsync(text, resolve, reject));
123
157
  }
@@ -1 +1 @@
1
- {"version":3,"file":"azure.js","sourceRoot":"","sources":["../../../src/lib/voice/azure.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,0CAYC;AAvBD;;;GAGG;AACH,4EAA8D;AAC9D,iCAAqC;AACrC,qDAAqD;AAIrD,yGAAyG;AAClG,KAAK,UAAU,eAAe,CAAC,GAAW,EAAE,MAAc,EAAE,MAAc;IAC7E,MAAM,YAAY,GAAG,GAAG,CAAC,YAAY,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACpE,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,iBAAiB,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;IAC5D,IAAI,CAAC;QACD,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,cAAc,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;QACrD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,YAAY,C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,CAAC;QAC5D,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,IAAI,OAAO,CAA4B,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBAC5E,GAAG,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;YACH,IAAI,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,YAAY,CAAC,0BAA0B,EAAE,CAAC;gBAChE,OAAO,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;YACrE,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,qBAAqB,MAAM,CAAC,YAAY,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QACjF,CAAC;gBAAS,CAAC;YACP,KAAK,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;IACL,CAAC;CACJ;AAhDD,4BAgDC","sourcesContent":["/**\n * Azure Cognitive Services Speech engines (STT + TTS).\n * Credentials: a subscription key + region (e.g. 'westeurope').\n */\nimport * as sdk from 'microsoft-cognitiveservices-speech-sdk';\nimport { isoToLocale } from './lang';\nimport { voiceFitsLanguage } from './speechLanguage';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\n\n/** List available Azure voices (short names like 'de-DE-KatjaNeural'), optionally filtered by locale. */\nexport async function listAzureVoices(key: string, region: string, locale: string): Promise<string[]> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(key, region);\n const synth = new sdk.SpeechSynthesizer(speechConfig, null);\n try {\n const res = await synth.getVoicesAsync(locale || '');\n if (res.reason === sdk.ResultReason.VoicesListRetrieved) {\n return res.voices.map(v => v.shortName);\n }\n throw new Error(res.errorDetails || 'Azure voice list failed');\n } finally {\n synth.close();\n }\n}\n\n/** Azure STT via `recognizeOnceAsync` fed from a PCM push stream (one short utterance). */\nexport class AzureStt implements SttEngine {\n constructor(\n private readonly key: string,\n private readonly region: string,\n ) {}\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(this.key, this.region);\n speechConfig.speechRecognitionLanguage = isoToLocale(lang);\n\n const format = sdk.AudioStreamFormat.getWaveFormatPCM(sampleRate, 16, 1);\n const pushStream = sdk.AudioInputStream.createPushStream(format);\n // The push stream needs a standalone ArrayBuffer (not the pooled Node Buffer view).\n const chunk = new ArrayBuffer(pcm.byteLength);\n new Uint8Array(chunk).set(pcm);\n pushStream.write(chunk);\n pushStream.close();\n\n const recognizer = new sdk.SpeechRecognizer(speechConfig, sdk.AudioConfig.fromStreamInput(pushStream));\n // A phrase list softly boosts recognition of the given domain vocabulary (device/room names) without\n // restricting the recognizer to only those words.\n if (hints?.length) {\n const phraseList = sdk.PhraseListGrammar.fromRecognizer(recognizer);\n for (const h of hints) {\n const term = (h || '').trim();\n if (term) {\n phraseList.addPhrase(term);\n }\n }\n }\n try {\n const result = await new Promise<sdk.SpeechRecognitionResult>((resolve, reject) => {\n recognizer.recognizeOnceAsync(resolve, reject);\n });\n if (result.reason === sdk.ResultReason.RecognizedSpeech) {\n return result.text.trim();\n }\n if (result.reason === sdk.ResultReason.Canceled) {\n const details = sdk.CancellationDetails.fromResult(result);\n throw new Error(`Azure STT canceled: ${details.errorDetails || details.reason}`);\n }\n return '';\n } finally {\n recognizer.close();\n }\n }\n}\n\n/** Azure TTS to raw 24 kHz mono 16-bit PCM (no server-side playback). */\nexport class AzureTts implements TtsEngine {\n constructor(\n private readonly key: string,\n private readonly region: string,\n /** Full Azure voice name (e.g. 'de-DE-KatjaNeural'); empty → pick by language. */\n private readonly voice: string,\n ) {}\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.speak(lang, (synth, resolve, reject) => synth.speakTextAsync(text, resolve, reject));\n }\n\n /** Azure speaks SSML natively, so pauses and emphasis survive. */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n return this.speak(lang, (synth, resolve, reject) => synth.speakSsmlAsync(ssml, resolve, reject));\n }\n\n private async speak(\n lang: string,\n run: (\n synth: sdk.SpeechSynthesizer,\n resolve: (r: sdk.SpeechSynthesisResult) => void,\n reject: (e: unknown) => void,\n ) => void,\n ): Promise<TtsResult> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(this.key, this.region);\n speechConfig.speechSynthesisOutputFormat = sdk.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm;\n // the set voice only for its language (de-DE-KatjaNeural reads no Russian); otherwise Azure's voice for it\n if (this.voice && voiceFitsLanguage(this.voice, lang)) {\n speechConfig.speechSynthesisVoiceName = this.voice;\n } else {\n speechConfig.speechSynthesisLanguage = isoToLocale(lang);\n }\n\n // audioConfig=null → synthesise to memory only, no default-speaker output.\n const synth = new sdk.SpeechSynthesizer(speechConfig, null);\n try {\n const result = await new Promise<sdk.SpeechSynthesisResult>((resolve, reject) => {\n run(synth, resolve, reject);\n });\n if (result.reason === sdk.ResultReason.SynthesizingAudioCompleted) {\n return { pcm: Buffer.from(result.audioData), sampleRate: 24000 };\n }\n throw new Error(`Azure TTS failed: ${result.errorDetails || result.reason}`);\n } finally {\n synth.close();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"azure.js","sourceRoot":"","sources":["../../../src/lib/voice/azure.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,0CAYC;AAxBD;;;GAGG;AACH,4EAA8D;AAC9D,iCAAqC;AACrC,qDAAqD;AAKrD,yGAAyG;AAClG,KAAK,UAAU,eAAe,CAAC,GAAW,EAAE,MAAc,EAAE,MAAc;IAC7E,MAAM,YAAY,GAAG,GAAG,CAAC,YAAY,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACpE,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,iBAAiB,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;IAC5D,IAAI,CAAC;Q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 'westeurope').\n */\nimport * as sdk from 'microsoft-cognitiveservices-speech-sdk';\nimport { isoToLocale } from './lang';\nimport { voiceFitsLanguage } from './speechLanguage';\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceGender } from './voiceGender';\n\n/** List available Azure voices (short names like 'de-DE-KatjaNeural'), optionally filtered by locale. */\nexport async function listAzureVoices(key: string, region: string, locale: string): Promise<string[]> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(key, region);\n const synth = new sdk.SpeechSynthesizer(speechConfig, null);\n try {\n const res = await synth.getVoicesAsync(locale || '');\n if (res.reason === sdk.ResultReason.VoicesListRetrieved) {\n return res.voices.map(v => v.shortName);\n }\n throw new Error(res.errorDetails || 'Azure voice list failed');\n } finally {\n synth.close();\n }\n}\n\n/** The gender of an Azure voice ('de-DE-KatjaNeural') from the voice list of its locale. */\nasync function azureVoiceGender(key: string, region: string, voice: string): Promise<VoiceGender | ''> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(key, region);\n const synth = new sdk.SpeechSynthesizer(speechConfig, null);\n try {\n const locale = /^[a-z]{2,3}-[A-Z]{2}/.exec(voice)?.[0] || '';\n const res = await synth.getVoicesAsync(locale);\n if (res.reason !== sdk.ResultReason.VoicesListRetrieved) {\n throw new Error(res.errorDetails || 'Azure voice list failed');\n }\n const info = res.voices.find(v => v.shortName.toLowerCase() === voice.toLowerCase());\n return info?.gender === sdk.SynthesisVoiceGender.Female\n ? 'female'\n : info?.gender === sdk.SynthesisVoiceGender.Male\n ? 'male'\n : '';\n } finally {\n synth.close();\n }\n}\n\n/** Azure STT via `recognizeOnceAsync` fed from a PCM push stream (one short utterance). */\nexport class AzureStt implements SttEngine {\n constructor(\n private readonly key: string,\n private readonly region: string,\n ) {}\n\n async transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(this.key, this.region);\n speechConfig.speechRecognitionLanguage = isoToLocale(lang);\n\n const format = sdk.AudioStreamFormat.getWaveFormatPCM(sampleRate, 16, 1);\n const pushStream = sdk.AudioInputStream.createPushStream(format);\n // The push stream needs a standalone ArrayBuffer (not the pooled Node Buffer view).\n const chunk = new ArrayBuffer(pcm.byteLength);\n new Uint8Array(chunk).set(pcm);\n pushStream.write(chunk);\n pushStream.close();\n\n const recognizer = new sdk.SpeechRecognizer(speechConfig, sdk.AudioConfig.fromStreamInput(pushStream));\n // A phrase list softly boosts recognition of the given domain vocabulary (device/room names) without\n // restricting the recognizer to only those words.\n if (hints?.length) {\n const phraseList = sdk.PhraseListGrammar.fromRecognizer(recognizer);\n for (const h of hints) {\n const term = (h || '').trim();\n if (term) {\n phraseList.addPhrase(term);\n }\n }\n }\n try {\n const result = await new Promise<sdk.SpeechRecognitionResult>((resolve, reject) => {\n recognizer.recognizeOnceAsync(resolve, reject);\n });\n if (result.reason === sdk.ResultReason.RecognizedSpeech) {\n return result.text.trim();\n }\n if (result.reason === sdk.ResultReason.Canceled) {\n const details = sdk.CancellationDetails.fromResult(result);\n throw new Error(`Azure STT canceled: ${details.errorDetails || details.reason}`);\n }\n return '';\n } finally {\n recognizer.close();\n }\n }\n}\n\n/** Azure TTS to raw 24 kHz mono 16-bit PCM (no server-side playback). */\nexport class AzureTts implements TtsEngine {\n constructor(\n private readonly key: string,\n private readonly region: string,\n /** Full Azure voice name (e.g. 'de-DE-KatjaNeural'); empty → pick by language. */\n private readonly voice: string,\n ) {}\n\n /** The gender of the set voice from Azure's voice list, once; '' for Azure's own voice of the language. */\n private gender: Promise<VoiceGender | ''> | null = null;\n\n voiceGender(lang: string): Promise<VoiceGender | ''> {\n // without a voice that speaks the language Azure picks its own — which one, its API does not tell\n if (!this.voice || !voiceFitsLanguage(this.voice, lang)) {\n return Promise.resolve('');\n }\n this.gender ??= azureVoiceGender(this.key, this.region, this.voice).catch(() => {\n this.gender = null; // try again next time\n return '' as const;\n });\n return this.gender;\n }\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return this.speak(lang, (synth, resolve, reject) => synth.speakTextAsync(text, resolve, reject));\n }\n\n /** Azure speaks SSML natively, so pauses and emphasis survive. */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n return this.speak(lang, (synth, resolve, reject) => synth.speakSsmlAsync(ssml, resolve, reject));\n }\n\n private async speak(\n lang: string,\n run: (\n synth: sdk.SpeechSynthesizer,\n resolve: (r: sdk.SpeechSynthesisResult) => void,\n reject: (e: unknown) => void,\n ) => void,\n ): Promise<TtsResult> {\n const speechConfig = sdk.SpeechConfig.fromSubscription(this.key, this.region);\n speechConfig.speechSynthesisOutputFormat = sdk.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm;\n // the set voice only for its language (de-DE-KatjaNeural reads no Russian); otherwise Azure's voice for it\n if (this.voice && voiceFitsLanguage(this.voice, lang)) {\n speechConfig.speechSynthesisVoiceName = this.voice;\n } else {\n speechConfig.speechSynthesisLanguage = isoToLocale(lang);\n }\n\n // audioConfig=null → synthesise to memory only, no default-speaker output.\n const synth = new sdk.SpeechSynthesizer(speechConfig, null);\n try {\n const result = await new Promise<sdk.SpeechSynthesisResult>((resolve, reject) => {\n run(synth, resolve, reject);\n });\n if (result.reason === sdk.ResultReason.SynthesizingAudioCompleted) {\n return { pcm: Buffer.from(result.audioData), sampleRate: 24000 };\n }\n throw new Error(`Azure TTS failed: ${result.errorDetails || result.reason}`);\n } finally {\n synth.close();\n }\n }\n}\n"]}
@@ -95,6 +95,10 @@ class FallbackTts {
95
95
  warm(phrases, lang) {
96
96
  return this.engines[0]?.engine.warm?.(phrases, lang) ?? Promise.resolve(0);
97
97
  }
98
+ /** The voice of the primary: the fallback only speaks during an outage. */
99
+ voiceGender(lang) {
100
+ return this.engines[0]?.engine.voiceGender?.(lang) ?? Promise.resolve('');
101
+ }
98
102
  }
99
103
  exports.FallbackTts = FallbackTts;
100
104
  //# sourceMappingURL=fallback.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fallback.js","sour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CAAC,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC/E,CAAC;CACJ;AApCD,kCAoCC","sourcesContent":["/**\n * A second speech engine behind the first one, so an outage does not take the voice away.\n *\n * The usual setup is a cloud engine with a local one behind it: when OpenAI/Azure/AWS is unreachable, the\n * API key expired or the quota ran out, Vosk and Piper keep the house answering — worse sounding, but\n * answering. That is the whole value: without it, the assistant goes mute exactly when the internet does.\n *\n * The idea comes from the Python original (`C:\\iot\\Hannah`, `core/hannah/stt.py`, which chains\n * aws → azure → remote → local); here it is one explicit fallback rather than an open chain, because a\n * household configures at most two speech providers and a longer chain would mostly be a way to wait\n * several timeouts in a row.\n *\n * Any failure of the primary moves on to the fallback: the alternative would be classifying provider\n * errors into \"retryable\" and \"not\", which is guesswork across three SDKs — and a request the primary\n * cannot answer is one the user still wants answered.\n *\n * Speech-to-text also moves on when the primary returns no text at all. A satellite only sends audio it took\n * for speech, and models differ in what they make of it: Nemotron returned nothing for a quiet\n * \"Мессенджер. Да, да.\" that Whisper recognised. The price is a second request for a false wake.\n */\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceLogger } from './download';\n\n/** One named engine in the chain. */\nexport interface NamedEngine<T> {\n name: string;\n engine: T;\n}\n\n/**\n * Run `attempt` over the engines in order; the last error survives if all of them fail. A result that\n * `useful` rejects also moves on to the next engine; if none does better, the first such result is returned.\n */\nasync function overEngines<T, R>(\n engines: NamedEngine<T>[],\n what: string,\n log: VoiceLogger,\n attempt: (engine: T) => Promise<R>,\n useful?: (result: R) => boolean,\n): Promise<R> {\n let last: Error | undefined;\n let unused: { result: R } | undefined;\n for (const [index, entry] of engines.entries()) {\n try {\n const result = await attempt(entry.engine);\n const next = engines[index + 1];\n if (useful && !useful(result)) {\n unused ??= { result };\n if (next) {\n log.info(`${what}: ${entry.name} returned nothing — trying ${next.name}.`);\n }\n continue;\n }\n if (index > 0) {\n log.info(`${what}: answered by the fallback engine (${entry.name}).`);\n }\n return result;\n } catch (e) {\n last = e as Error;\n const next = engines[index + 1];\n log[next ? 'warn' : 'error'](\n `${what}: ${entry.name} failed (${last.message})${next ? ` — trying ${next.name}` : ''}.`,\n );\n }\n }\n if (unused) {\n return unused.result;\n }\n throw last ?? new Error(`${what}: no engine configured`);\n}\n\n/** Speech-to-text with one fallback engine. */\nexport class FallbackStt implements SttEngine {\n constructor(\n private readonly engines: NamedEngine<SttEngine>[],\n private readonly log: VoiceLogger,\n ) {}\n\n transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n return overEngines(\n this.engines,\n 'Speech-to-text',\n this.log,\n e => e.transcribe(pcm, sampleRate, lang, hints),\n text => !!text.trim(),\n );\n }\n\n /** Prepare every engine: the fallback is useless if its model is only downloaded once it is needed. */\n async prepare(lang: string): Promise<void> {\n for (const entry of this.engines) {\n try {\n await entry.engine.prepare?.(lang);\n } catch (e) {\n this.log.warn(`Speech-to-text: preparing ${entry.name} failed (${(e as Error).message}).`);\n }\n }\n }\n}\n\n/** Text-to-speech with one fallback engine. */\nexport class FallbackTts implements TtsEngine {\n constructor(\n private readonly engines: NamedEngine<TtsEngine>[],\n private readonly log: VoiceLogger,\n ) {}\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return overEngines(this.engines, 'Text-to-speech', this.log, e => e.synthesize(text, lang));\n }\n\n /**\n * SSML only goes to engines that can speak it; if none can, the primary's plain-text path handles it\n * (its cache wrapper strips the markup).\n */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const capable = this.engines.filter(e => !!e.engine.synthesizeSsml);\n if (!capable.length) {\n return this.synthesize(ssml, lang);\n }\n return overEngines(capable, 'Text-to-speech (SSML)', this.log, e => e.synthesizeSsml!(ssml, lang));\n }\n\n async prepare(lang: string): Promise<void> {\n for (const entry of this.engines) {\n try {\n await entry.engine.prepare?.(lang);\n } catch (e) {\n this.log.warn(`Text-to-speech: preparing ${entry.name} failed (${(e as Error).message}).`);\n }\n }\n }\n\n /** Warm only the primary's cache: the fallback is for an outage, not for everyday phrases. */\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engines[0]?.engine.warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n}\n"]}
1
+ {"version":3,"file":"fallback.js","sourceRoot":"","sources":["../../../src/lib/voice/fallback.ts"],"names":[],"mappings":";;;AA+BA;;;GAGG;AACH,KAAK,UAAU,WAAW,CACtB,OAAyB,EACzB,IAAY,EACZ,GAAgB,EAChB,OAAkC,EAClC,MAA+B;IAE/B,IAAI,IAAuB,CAAC;IAC5B,IAAI,MAAiC,CAAC;IACtC,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;QAC7C,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC3C,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;YAChC,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5B,MAAM,KAAK,EAAE,MAAM,EAAE,CAAC;gBACtB,IAAI,IAAI,EAAE,CAAC;oBACP,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,KAAK,KAAK,CAAC,IAAI,8BAA8B,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;gBAC/E,CAAC;gBACD,SAAS;YACb,CAAC;YACD,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;gBACZ,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,sCAAsC,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,MAAM,CAAC;QAClB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,IAAI,GAAG,CAAU,CAAC;YAClB,MAAM,IAAI,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AAI,CAAC,GAAG,CAAC,IAAI,CAAC,6BAA6B,KAAK,CAAC,IAAI,YAAa,CAAW,CAAC,OAAO,IAAI,CAAC,CAAC;YAC/F,CAAC;QACL,CAAC;IACL,CAAC;IAED,8FAA8F;IAC9F,IAAI,CAAC,OAAiB,EAAE,IAAY;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAC/E,CAAC;IAED,2EAA2E;IAC3E,WAAW,CAAC,IAAY;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAC9E,CAAC;CACJ;AAzCD,kCAyCC","sourcesContent":["/**\n * A second speech engine behind the first one, so an outage does not take the voice away.\n *\n * The usual setup is a cloud engine with a local one behind it: when OpenAI/Azure/AWS is unreachable, the\n * API key expired or the quota ran out, Vosk and Piper keep the house answering — worse sounding, but\n * answering. That is the whole value: without it, the assistant goes mute exactly when the internet does.\n *\n * The idea comes from the Python original (`C:\\iot\\Hannah`, `core/hannah/stt.py`, which chains\n * aws → azure → remote → local); here it is one explicit fallback rather than an open chain, because a\n * household configures at most two speech providers and a longer chain would mostly be a way to wait\n * several timeouts in a row.\n *\n * Any failure of the primary moves on to the fallback: the alternative would be classifying provider\n * errors into \"retryable\" and \"not\", which is guesswork across three SDKs — and a request the primary\n * cannot answer is one the user still wants answered.\n *\n * Speech-to-text also moves on when the primary returns no text at all. A satellite only sends audio it took\n * for speech, and models differ in what they make of it: Nemotron returned nothing for a quiet\n * \"Мессенджер. Да, да.\" that Whisper recognised. The price is a second request for a false wake.\n */\nimport type { SttEngine } from './stt';\nimport type { TtsEngine, TtsResult } from './tts';\nimport type { VoiceGender } from './voiceGender';\nimport type { VoiceLogger } from './download';\n\n/** One named engine in the chain. */\nexport interface NamedEngine<T> {\n name: string;\n engine: T;\n}\n\n/**\n * Run `attempt` over the engines in order; the last error survives if all of them fail. A result that\n * `useful` rejects also moves on to the next engine; if none does better, the first such result is returned.\n */\nasync function overEngines<T, R>(\n engines: NamedEngine<T>[],\n what: string,\n log: VoiceLogger,\n attempt: (engine: T) => Promise<R>,\n useful?: (result: R) => boolean,\n): Promise<R> {\n let last: Error | undefined;\n let unused: { result: R } | undefined;\n for (const [index, entry] of engines.entries()) {\n try {\n const result = await attempt(entry.engine);\n const next = engines[index + 1];\n if (useful && !useful(result)) {\n unused ??= { result };\n if (next) {\n log.info(`${what}: ${entry.name} returned nothing — trying ${next.name}.`);\n }\n continue;\n }\n if (index > 0) {\n log.info(`${what}: answered by the fallback engine (${entry.name}).`);\n }\n return result;\n } catch (e) {\n last = e as Error;\n const next = engines[index + 1];\n log[next ? 'warn' : 'error'](\n `${what}: ${entry.name} failed (${last.message})${next ? ` — trying ${next.name}` : ''}.`,\n );\n }\n }\n if (unused) {\n return unused.result;\n }\n throw last ?? new Error(`${what}: no engine configured`);\n}\n\n/** Speech-to-text with one fallback engine. */\nexport class FallbackStt implements SttEngine {\n constructor(\n private readonly engines: NamedEngine<SttEngine>[],\n private readonly log: VoiceLogger,\n ) {}\n\n transcribe(pcm: Buffer, sampleRate: number, lang: string, hints?: string[]): Promise<string> {\n return overEngines(\n this.engines,\n 'Speech-to-text',\n this.log,\n e => e.transcribe(pcm, sampleRate, lang, hints),\n text => !!text.trim(),\n );\n }\n\n /** Prepare every engine: the fallback is useless if its model is only downloaded once it is needed. */\n async prepare(lang: string): Promise<void> {\n for (const entry of this.engines) {\n try {\n await entry.engine.prepare?.(lang);\n } catch (e) {\n this.log.warn(`Speech-to-text: preparing ${entry.name} failed (${(e as Error).message}).`);\n }\n }\n }\n}\n\n/** Text-to-speech with one fallback engine. */\nexport class FallbackTts implements TtsEngine {\n constructor(\n private readonly engines: NamedEngine<TtsEngine>[],\n private readonly log: VoiceLogger,\n ) {}\n\n synthesize(text: string, lang: string): Promise<TtsResult> {\n return overEngines(this.engines, 'Text-to-speech', this.log, e => e.synthesize(text, lang));\n }\n\n /**\n * SSML only goes to engines that can speak it; if none can, the primary's plain-text path handles it\n * (its cache wrapper strips the markup).\n */\n synthesizeSsml(ssml: string, lang: string): Promise<TtsResult> {\n const capable = this.engines.filter(e => !!e.engine.synthesizeSsml);\n if (!capable.length) {\n return this.synthesize(ssml, lang);\n }\n return overEngines(capable, 'Text-to-speech (SSML)', this.log, e => e.synthesizeSsml!(ssml, lang));\n }\n\n async prepare(lang: string): Promise<void> {\n for (const entry of this.engines) {\n try {\n await entry.engine.prepare?.(lang);\n } catch (e) {\n this.log.warn(`Text-to-speech: preparing ${entry.name} failed (${(e as Error).message}).`);\n }\n }\n }\n\n /** Warm only the primary's cache: the fallback is for an outage, not for everyday phrases. */\n warm(phrases: string[], lang: string): Promise<number> {\n return this.engines[0]?.engine.warm?.(phrases, lang) ?? Promise.resolve(0);\n }\n\n /** The voice of the primary: the fallback only speaks during an outage. */\n voiceGender(lang: string): Promise<VoiceGender | ''> {\n return this.engines[0]?.engine.voiceGender?.(lang) ?? Promise.resolve('');\n }\n}\n"]}
@@ -51,6 +51,7 @@ const openai_1 = __importStar(require("openai"));
51
51
  const llm_1 = require("../llm");
52
52
  const stt_1 = require("./stt");
53
53
  const speechLanguage_1 = require("./speechLanguage");
54
+ const voiceGender_1 = require("./voiceGender");
54
55
  /** Speech-to-text model when none is configured: Whisper large v3 turbo, multilingual and the cheapest Whisper */
55
56
  exports.DEFAULT_OPENROUTER_STT_MODEL = 'openai/whisper-large-v3-turbo';
56
57
  /**
@@ -198,6 +199,9 @@ class OpenRouterTts {
198
199
  return this.voice;
199
200
  }
200
201
  }
202
+ async voiceGender(lang) {
203
+ return (0, voiceGender_1.knownVoiceGender)('openrouter', await this.voiceFor(lang), this.model);
204
+ }
201
205
  async synthesize(text, lang) {
202
206
  const mp3 = MP3_ONLY.some(prefix => this.model.startsWith(prefix));
203
207
  if (mp3 && !this.decode) {
@@ -1 +1 @@
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,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,EAAE,GAAG,iBAAiB,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC,MAAM,CAAC;IACzB,CAAC;IACD,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE;QACvB,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,G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uFAAuF;QACvF,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC;IACzG,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';\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 const result = mp3 ? await this.decode!(audio) : pcmFromResponse(audio, res.headers.get('content-type') || '');\n // the voice really asked for: without one set, the first of the model for the language\n return { ...result, spokenBy: { provider: 'openrouter', model: this.model, voice, language: lang } };\n }\n}\n"]}
1
+ {"version":3,"file":"openrouter.js","sourceRoot":"","sources":["../../../src/lib/voice/openrouter.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,gEA8BC;AASD,8CAOC;AASD,0CAiBC;AAjID;;;;;;;;;GASG;AACH,iDAAwC;AACxC,gCAA8D;AAC9D,+BAAiD;AAEjD,qDAAqD;AACrD,+CAAmE;AAEnE,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,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,EAAE,GAAG,iBAAiB,EAAE,CAAC;QACvD,OAAO,MAAM,CAAC,MAAM,CAAC;IACzB,CAAC;IACD,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,EAAE;QACvB,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,GAAG,sBAAgB,CAAC,U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CAAC,MAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC;QAC/G,uFAAuF;QACvF,OAAO,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC;IACzG,CAAC;CACJ;AA3DD,sCA2DC","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';\nimport { knownVoiceGender, type VoiceGender } from './voiceGender';\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 voiceGender(lang: string): Promise<VoiceGender | ''> {\n return knownVoiceGender('openrouter', await this.voiceFor(lang), this.model);\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 const result = mp3 ? await this.decode!(audio) : pcmFromResponse(audio, res.headers.get('content-type') || '');\n // the voice really asked for: without one set, the first of the model for the language\n return { ...result, spokenBy: { provider: 'openrouter', model: this.model, voice, language: lang } };\n }\n}\n"]}
@@ -46,6 +46,7 @@ const fs = __importStar(require("node:fs"));
46
46
  const path = __importStar(require("node:path"));
47
47
  const node_child_process_1 = require("node:child_process");
48
48
  const download_1 = require("./download");
49
+ const voiceGender_1 = require("./voiceGender");
49
50
  const PIPER_RELEASE = 'https://github.com/rhasspy/piper/releases/download/2023.11.14-2';
50
51
  /** Release asset for the current platform/arch. */
51
52
  function piperAsset() {
@@ -103,6 +104,9 @@ class PiperTts {
103
104
  this.voice = voice;
104
105
  this.log = log;
105
106
  }
107
+ voiceGender(lang) {
108
+ return Promise.resolve((0, voiceGender_1.knownVoiceGender)('piper', this.voiceFor(lang)));
109
+ }
106
110
  /** Download + unpack the binary once; concurrent calls share one init. */
107
111
  ensure() {
108
112
  if (!this.ready) {