| 1 |
"""Voice handler with Azure.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from collections.abc import AsyncGenerator, AsyncIterable |
| 7 |
from datetime import datetime |
| 8 |
from enum import StrEnum |
| 9 |
import io |
| 10 |
import logging |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
import wave |
| 13 |
from xml.etree import ElementTree as ET |
| 14 |
|
| 15 |
from aiohttp.hdrs import ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT |
| 16 |
import attr |
| 17 |
from sentence_stream import SentenceBoundaryDetector |
| 18 |
|
| 19 |
from .utils import utc_from_timestamp, utcnow |
| 20 |
from .voice_api import VoiceApiError |
| 21 |
from .voice_data import TTS_VOICES |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from . import Cloud, _ClientT |
| 25 |
|
| 26 |
|
| 27 |
_LOGGER = logging.getLogger(__name__) |
| 28 |
|
| 29 |
|
| 30 |
class VoiceError(Exception): |
| 31 |
"""General Voice error.""" |
| 32 |
|
| 33 |
|
| 34 |
class VoiceTokenError(VoiceError): |
| 35 |
"""Error with token handling.""" |
| 36 |
|
| 37 |
|
| 38 |
class VoiceReturnError(VoiceError): |
| 39 |
"""Backend error for voice.""" |
| 40 |
|
| 41 |
|
| 42 |
class Gender(StrEnum): |
| 43 |
"""Gender Type for voices.""" |
| 44 |
|
| 45 |
MALE = "male" |
| 46 |
FEMALE = "female" |
| 47 |
|
| 48 |
|
| 49 |
class AudioOutput(StrEnum): |
| 50 |
"""Gender Type for voices.""" |
| 51 |
|
| 52 |
MP3 = "mp3" |
| 53 |
RAW = "raw" |
| 54 |
WAV = "wav" |
| 55 |
|
| 56 |
|
| 57 |
STT_LANGUAGES = [ |
| 58 |
"af-ZA", |
| 59 |
"am-ET", |
| 60 |
"ar-AE", |
| 61 |
"ar-BH", |
| 62 |
"ar-DZ", |
| 63 |
"ar-EG", |
| 64 |
"ar-IL", |
| 65 |
"ar-IQ", |
| 66 |
"ar-JO", |
| 67 |
"ar-KW", |
| 68 |
"ar-LB", |
| 69 |
"ar-LY", |
| 70 |
"ar-MA", |
| 71 |
"ar-OM", |
| 72 |
"ar-PS", |
| 73 |
"ar-QA", |
| 74 |
"ar-SA", |
| 75 |
"ar-SY", |
| 76 |
"ar-TN", |
| 77 |
"ar-YE", |
| 78 |
"az-AZ", |
| 79 |
"bg-BG", |
| 80 |
"bn-IN", |
| 81 |
"bs-BA", |
| 82 |
"ca-ES", |
| 83 |
"cs-CZ", |
| 84 |
"cy-GB", |
| 85 |
"da-DK", |
| 86 |
"de-AT", |
| 87 |
"de-CH", |
| 88 |
"de-DE", |
| 89 |
"el-GR", |
| 90 |
"en-AU", |
| 91 |
"en-CA", |
| 92 |
"en-GB", |
| 93 |
"en-GH", |
| 94 |
"en-HK", |
| 95 |
"en-IE", |
| 96 |
"en-IN", |
| 97 |
"en-KE", |
| 98 |
"en-NG", |
| 99 |
"en-NZ", |
| 100 |
"en-PH", |
| 101 |
"en-SG", |
| 102 |
"en-TZ", |
| 103 |
"en-US", |
| 104 |
"en-ZA", |
| 105 |
"es-AR", |
| 106 |
"es-BO", |
| 107 |
"es-CL", |
| 108 |
"es-CO", |
| 109 |
"es-CR", |
| 110 |
"es-CU", |
| 111 |
"es-DO", |
| 112 |
"es-EC", |
| 113 |
"es-ES", |
| 114 |
"es-GQ", |
| 115 |
"es-GT", |
| 116 |
"es-HN", |
| 117 |
"es-MX", |
| 118 |
"es-NI", |
| 119 |
"es-PA", |
| 120 |
"es-PE", |
| 121 |
"es-PR", |
| 122 |
"es-PY", |
| 123 |
"es-SV", |
| 124 |
"es-US", |
| 125 |
"es-UY", |
| 126 |
"es-VE", |
| 127 |
"et-EE", |
| 128 |
"eu-ES", |
| 129 |
"fa-IR", |
| 130 |
"fi-FI", |
| 131 |
"fil-PH", |
| 132 |
"fr-BE", |
| 133 |
"fr-CA", |
| 134 |
"fr-CH", |
| 135 |
"fr-FR", |
| 136 |
"ga-IE", |
| 137 |
"gl-ES", |
| 138 |
"gu-IN", |
| 139 |
"he-IL", |
| 140 |
"hi-IN", |
| 141 |
"hr-HR", |
| 142 |
"hu-HU", |
| 143 |
"hy-AM", |
| 144 |
"id-ID", |
| 145 |
"is-IS", |
| 146 |
"it-CH", |
| 147 |
"it-IT", |
| 148 |
"ja-JP", |
| 149 |
"jv-ID", |
| 150 |
"ka-GE", |
| 151 |
"kk-KZ", |
| 152 |
"km-KH", |
| 153 |
"kn-IN", |
| 154 |
"ko-KR", |
| 155 |
"lo-LA", |
| 156 |
"lt-LT", |
| 157 |
"lv-LV", |
| 158 |
"mk-MK", |
| 159 |
"ml-IN", |
| 160 |
"mn-MN", |
| 161 |
"mr-IN", |
| 162 |
"ms-MY", |
| 163 |
"mt-MT", |
| 164 |
"my-MM", |
| 165 |
"nb-NO", |
| 166 |
"ne-NP", |
| 167 |
"nl-BE", |
| 168 |
"nl-NL", |
| 169 |
"pl-PL", |
| 170 |
"ps-AF", |
| 171 |
"pt-BR", |
| 172 |
"pt-PT", |
| 173 |
"ro-RO", |
| 174 |
"ru-RU", |
| 175 |
"si-LK", |
| 176 |
"sk-SK", |
| 177 |
"sl-SI", |
| 178 |
"so-SO", |
| 179 |
"sq-AL", |
| 180 |
"sr-RS", |
| 181 |
"sv-SE", |
| 182 |
"sw-KE", |
| 183 |
"sw-TZ", |
| 184 |
"ta-IN", |
| 185 |
"te-IN", |
| 186 |
"th-TH", |
| 187 |
"tr-TR", |
| 188 |
"uk-UA", |
| 189 |
"uz-UZ", |
| 190 |
"vi-VN", |
| 191 |
"wuu-CN", |
| 192 |
"yue-CN", |
| 193 |
"zh-CN", |
| 194 |
"zh-CN-shandong", |
| 195 |
"zh-CN-sichuan", |
| 196 |
"zh-HK", |
| 197 |
"zh-TW", |
| 198 |
"zu-ZA", |
| 199 |
] |
| 200 |
|
| 201 |
# Old. Do not update anymore. |
| 202 |
MAP_VOICE = { |
| 203 |
("af-ZA", Gender.FEMALE): "AdriNeural", |
| 204 |
("af-ZA", Gender.MALE): "WillemNeural", |
| 205 |
("am-ET", Gender.FEMALE): "MekdesNeural", |
| 206 |
("am-ET", Gender.MALE): "AmehaNeural", |
| 207 |
("ar-DZ", Gender.FEMALE): "AminaNeural", |
| 208 |
("ar-DZ", Gender.MALE): "IsmaelNeural", |
| 209 |
("ar-BH", Gender.FEMALE): "LailaNeural", |
| 210 |
("ar-BH", Gender.MALE): "AliNeural", |
| 211 |
("ar-EG", Gender.FEMALE): "SalmaNeural", |
| 212 |
("ar-EG", Gender.MALE): "ShakirNeural", |
| 213 |
("ar-IQ", Gender.FEMALE): "RanaNeural", |
| 214 |
("ar-IQ", Gender.MALE): "BasselNeural", |
| 215 |
("ar-JO", Gender.FEMALE): "SanaNeural", |
| 216 |
("ar-JO", Gender.MALE): "TaimNeural", |
| 217 |
("ar-KW", Gender.FEMALE): "NouraNeural", |
| 218 |
("ar-KW", Gender.MALE): "FahedNeural", |
| 219 |
("ar-LY", Gender.FEMALE): "ImanNeural", |
| 220 |
("ar-LY", Gender.MALE): "OmarNeural", |
| 221 |
("ar-MA", Gender.FEMALE): "MounaNeural", |
| 222 |
("ar-MA", Gender.MALE): "JamalNeural", |
| 223 |
("ar-QA", Gender.FEMALE): "AmalNeural", |
| 224 |
("ar-QA", Gender.MALE): "MoazNeural", |
| 225 |
("ar-SA", Gender.FEMALE): "ZariyahNeural", |
| 226 |
("ar-SA", Gender.MALE): "HamedNeural", |
| 227 |
("ar-SY", Gender.FEMALE): "AmanyNeural", |
| 228 |
("ar-SY", Gender.MALE): "LaithNeural", |
| 229 |
("ar-TN", Gender.FEMALE): "ReemNeural", |
| 230 |
("ar-TN", Gender.MALE): "HediNeural", |
| 231 |
("ar-AE", Gender.FEMALE): "FatimaNeural", |
| 232 |
("ar-AE", Gender.MALE): "HamdanNeural", |
| 233 |
("ar-YE", Gender.FEMALE): "MaryamNeural", |
| 234 |
("ar-YE", Gender.MALE): "SalehNeural", |
| 235 |
("bn-BD", Gender.FEMALE): "NabanitaNeural", |
| 236 |
("bn-BD", Gender.MALE): "PradeepNeural", |
| 237 |
("bn-IN", Gender.FEMALE): "TanishaaNeural", |
| 238 |
("bn-IN", Gender.MALE): "BashkarNeural", |
| 239 |
("bg-BG", Gender.FEMALE): "KalinaNeural", |
| 240 |
("bg-BG", Gender.MALE): "BorislavNeural", |
| 241 |
("my-MM", Gender.FEMALE): "NilarNeural", |
| 242 |
("my-MM", Gender.MALE): "ThihaNeural", |
| 243 |
("ca-ES", Gender.FEMALE): "JoanaNeural", |
| 244 |
("ca-ES", Gender.MALE): "EnricNeural", |
| 245 |
("zh-HK", Gender.FEMALE): "HiuMaanNeural", |
| 246 |
("zh-HK", Gender.MALE): "WanLungNeural", |
| 247 |
("zh-CN", Gender.FEMALE): "XiaoxiaoNeural", |
| 248 |
("zh-CN", Gender.MALE): "YunyangNeural", |
| 249 |
("zh-TW", Gender.FEMALE): "HsiaoChenNeural", |
| 250 |
("zh-TW", Gender.MALE): "YunJheNeural", |
| 251 |
("hr-HR", Gender.FEMALE): "GabrijelaNeural", |
| 252 |
("hr-HR", Gender.MALE): "SreckoNeural", |
| 253 |
("cs-CZ", Gender.FEMALE): "VlastaNeural", |
| 254 |
("cs-CZ", Gender.MALE): "AntoninNeural", |
| 255 |
("da-DK", Gender.FEMALE): "ChristelNeural", |
| 256 |
("da-DK", Gender.MALE): "JeppeNeural", |
| 257 |
("nl-BE", Gender.FEMALE): "DenaNeural", |
| 258 |
("nl-BE", Gender.MALE): "ArnaudNeural", |
| 259 |
("nl-NL", Gender.FEMALE): "ColetteNeural", |
| 260 |
("nl-NL", Gender.MALE): "MaartenNeural", |
| 261 |
("en-AU", Gender.FEMALE): "NatashaNeural", |
| 262 |
("en-AU", Gender.MALE): "WilliamNeural", |
| 263 |
("en-CA", Gender.FEMALE): "ClaraNeural", |
| 264 |
("en-CA", Gender.MALE): "LiamNeural", |
| 265 |
("en-HK", Gender.FEMALE): "YanNeural", |
| 266 |
("en-HK", Gender.MALE): "SamNeural", |
| 267 |
("en-IN", Gender.FEMALE): "NeerjaNeural", |
| 268 |
("en-IN", Gender.MALE): "PrabhatNeural", |
| 269 |
("en-IE", Gender.FEMALE): "EmilyNeural", |
| 270 |
("en-IE", Gender.MALE): "ConnorNeural", |
| 271 |
("en-KE", Gender.FEMALE): "AsiliaNeural", |
| 272 |
("en-KE", Gender.MALE): "ChilembaNeural", |
| 273 |
("en-NZ", Gender.FEMALE): "MollyNeural", |
| 274 |
("en-NZ", Gender.MALE): "MitchellNeural", |
| 275 |
("en-NG", Gender.FEMALE): "EzinneNeural", |
| 276 |
("en-NG", Gender.MALE): "AbeoNeural", |
| 277 |
("en-PH", Gender.FEMALE): "RosaNeural", |
| 278 |
("en-PH", Gender.MALE): "JamesNeural", |
| 279 |
("en-SG", Gender.FEMALE): "LunaNeural", |
| 280 |
("en-SG", Gender.MALE): "WayneNeural", |
| 281 |
("en-ZA", Gender.FEMALE): "LeahNeural", |
| 282 |
("en-ZA", Gender.MALE): "LukeNeural", |
| 283 |
("en-TZ", Gender.FEMALE): "ImaniNeural", |
| 284 |
("en-TZ", Gender.MALE): "ElimuNeural", |
| 285 |
("en-GB", Gender.FEMALE): "LibbyNeural", |
| 286 |
("en-GB", Gender.MALE): "RyanNeural", |
| 287 |
("en-US", Gender.FEMALE): "JennyNeural", |
| 288 |
("en-US", Gender.MALE): "GuyNeural", |
| 289 |
("et-EE", Gender.FEMALE): "AnuNeural", |
| 290 |
("et-EE", Gender.MALE): "KertNeural", |
| 291 |
("fil-PH", Gender.FEMALE): "BlessicaNeural", |
| 292 |
("fil-PH", Gender.MALE): "AngeloNeural", |
| 293 |
("fi-FI", Gender.FEMALE): "SelmaNeural", |
| 294 |
("fi-FI", Gender.MALE): "HarriNeural", |
| 295 |
("fr-BE", Gender.FEMALE): "CharlineNeural", |
| 296 |
("fr-BE", Gender.MALE): "GerardNeural", |
| 297 |
("fr-CA", Gender.FEMALE): "SylvieNeural", |
| 298 |
("fr-CA", Gender.MALE): "AntoineNeural", |
| 299 |
("fr-FR", Gender.FEMALE): "DeniseNeural", |
| 300 |
("fr-FR", Gender.MALE): "HenriNeural", |
| 301 |
("fr-CH", Gender.FEMALE): "ArianeNeural", |
| 302 |
("fr-CH", Gender.MALE): "FabriceNeural", |
| 303 |
("gl-ES", Gender.FEMALE): "SabelaNeural", |
| 304 |
("gl-ES", Gender.MALE): "RoiNeural", |
| 305 |
("de-AT", Gender.FEMALE): "IngridNeural", |
| 306 |
("de-AT", Gender.MALE): "JonasNeural", |
| 307 |
("de-DE", Gender.FEMALE): "KatjaNeural", |
| 308 |
("de-DE", Gender.MALE): "ConradNeural", |
| 309 |
("de-CH", Gender.FEMALE): "LeniNeural", |
| 310 |
("de-CH", Gender.MALE): "JanNeural", |
| 311 |
("el-GR", Gender.FEMALE): "AthinaNeural", |
| 312 |
("el-GR", Gender.MALE): "NestorasNeural", |
| 313 |
("gu-IN", Gender.FEMALE): "DhwaniNeural", |
| 314 |
("gu-IN", Gender.MALE): "NiranjanNeural", |
| 315 |
("he-IL", Gender.FEMALE): "HilaNeural", |
| 316 |
("he-IL", Gender.MALE): "AvriNeural", |
| 317 |
("hi-IN", Gender.FEMALE): "SwaraNeural", |
| 318 |
("hi-IN", Gender.MALE): "MadhurNeural", |
| 319 |
("hu-HU", Gender.FEMALE): "NoemiNeural", |
| 320 |
("hu-HU", Gender.MALE): "TamasNeural", |
| 321 |
("is-IS", Gender.FEMALE): "GudrunNeural", |
| 322 |
("is-IS", Gender.MALE): "GunnarNeural", |
| 323 |
("id-ID", Gender.FEMALE): "GadisNeural", |
| 324 |
("id-ID", Gender.MALE): "ArdiNeural", |
| 325 |
("ga-IE", Gender.FEMALE): "OrlaNeural", |
| 326 |
("ga-IE", Gender.MALE): "ColmNeural", |
| 327 |
("it-IT", Gender.FEMALE): "ElsaNeural", |
| 328 |
("it-IT", Gender.MALE): "DiegoNeural", |
| 329 |
("ja-JP", Gender.FEMALE): "NanamiNeural", |
| 330 |
("ja-JP", Gender.MALE): "KeitaNeural", |
| 331 |
("jv-ID", Gender.FEMALE): "SitiNeural", |
| 332 |
("jv-ID", Gender.MALE): "DimasNeural", |
| 333 |
("kn-IN", Gender.FEMALE): "SapnaNeural", |
| 334 |
("kn-IN", Gender.MALE): "GaganNeural", |
| 335 |
("kk-KZ", Gender.FEMALE): "AigulNeural", |
| 336 |
("kk-KZ", Gender.MALE): "DauletNeural", |
| 337 |
("km-KH", Gender.FEMALE): "SreymomNeural", |
| 338 |
("km-KH", Gender.MALE): "PisethNeural", |
| 339 |
("ko-KR", Gender.FEMALE): "SunHiNeural", |
| 340 |
("ko-KR", Gender.MALE): "InJoonNeural", |
| 341 |
("lo-LA", Gender.FEMALE): "KeomanyNeural", |
| 342 |
("lo-LA", Gender.MALE): "ChanthavongNeural", |
| 343 |
("lv-LV", Gender.FEMALE): "EveritaNeural", |
| 344 |
("lv-LV", Gender.MALE): "NilsNeural", |
| 345 |
("lt-LT", Gender.FEMALE): "OnaNeural", |
| 346 |
("lt-LT", Gender.MALE): "LeonasNeural", |
| 347 |
("mk-MK", Gender.FEMALE): "MarijaNeural", |
| 348 |
("mk-MK", Gender.MALE): "AleksandarNeural", |
| 349 |
("ms-MY", Gender.FEMALE): "YasminNeural", |
| 350 |
("ms-MY", Gender.MALE): "OsmanNeural", |
| 351 |
("ml-IN", Gender.FEMALE): "SobhanaNeural", |
| 352 |
("ml-IN", Gender.MALE): "MidhunNeural", |
| 353 |
("mt-MT", Gender.FEMALE): "GraceNeural", |
| 354 |
("mt-MT", Gender.MALE): "JosephNeural", |
| 355 |
("mr-IN", Gender.FEMALE): "AarohiNeural", |
| 356 |
("mr-IN", Gender.MALE): "ManoharNeural", |
| 357 |
("nb-NO", Gender.FEMALE): "IselinNeural", |
| 358 |
("nb-NO", Gender.MALE): "FinnNeural", |
| 359 |
("ps-AF", Gender.FEMALE): "LatifaNeural", |
| 360 |
("ps-AF", Gender.MALE): "GulNawazNeural", |
| 361 |
("fa-IR", Gender.FEMALE): "DilaraNeural", |
| 362 |
("fa-IR", Gender.MALE): "FaridNeural", |
| 363 |
("pl-PL", Gender.FEMALE): "AgnieszkaNeural", |
| 364 |
("pl-PL", Gender.MALE): "MarekNeural", |
| 365 |
("pt-BR", Gender.FEMALE): "FranciscaNeural", |
| 366 |
("pt-BR", Gender.MALE): "AntonioNeural", |
| 367 |
("pt-PT", Gender.FEMALE): "RaquelNeural", |
| 368 |
("pt-PT", Gender.MALE): "DuarteNeural", |
| 369 |
("ro-RO", Gender.FEMALE): "AlinaNeural", |
| 370 |
("ro-RO", Gender.MALE): "EmilNeural", |
| 371 |
("ru-RU", Gender.FEMALE): "SvetlanaNeural", |
| 372 |
("ru-RU", Gender.MALE): "DmitryNeural", |
| 373 |
("sr-RS", Gender.FEMALE): "SophieNeural", |
| 374 |
("sr-RS", Gender.MALE): "NicholasNeural", |
| 375 |
("si-LK", Gender.FEMALE): "ThiliniNeural", |
| 376 |
("si-LK", Gender.MALE): "SameeraNeural", |
| 377 |
("sk-SK", Gender.FEMALE): "ViktoriaNeural", |
| 378 |
("sk-SK", Gender.MALE): "LukasNeural", |
| 379 |
("sl-SI", Gender.FEMALE): "PetraNeural", |
| 380 |
("sl-SI", Gender.MALE): "RokNeural", |
| 381 |
("so-SO", Gender.FEMALE): "UbaxNeural", |
| 382 |
("so-SO", Gender.MALE): "MuuseNeural", |
| 383 |
("es-AR", Gender.FEMALE): "ElenaNeural", |
| 384 |
("es-AR", Gender.MALE): "TomasNeural", |
| 385 |
("es-BO", Gender.FEMALE): "SofiaNeural", |
| 386 |
("es-BO", Gender.MALE): "MarceloNeural", |
| 387 |
("es-CL", Gender.FEMALE): "CatalinaNeural", |
| 388 |
("es-CL", Gender.MALE): "LorenzoNeural", |
| 389 |
("es-CO", Gender.FEMALE): "SalomeNeural", |
| 390 |
("es-CO", Gender.MALE): "GonzaloNeural", |
| 391 |
("es-CR", Gender.FEMALE): "MariaNeural", |
| 392 |
("es-CR", Gender.MALE): "JuanNeural", |
| 393 |
("es-CU", Gender.FEMALE): "BelkysNeural", |
| 394 |
("es-CU", Gender.MALE): "ManuelNeural", |
| 395 |
("es-DO", Gender.FEMALE): "RamonaNeural", |
| 396 |
("es-DO", Gender.MALE): "EmilioNeural", |
| 397 |
("es-EC", Gender.FEMALE): "AndreaNeural", |
| 398 |
("es-EC", Gender.MALE): "LuisNeural", |
| 399 |
("es-SV", Gender.FEMALE): "LorenaNeural", |
| 400 |
("es-SV", Gender.MALE): "RodrigoNeural", |
| 401 |
("es-GQ", Gender.FEMALE): "TeresaNeural", |
| 402 |
("es-GQ", Gender.MALE): "JavierNeural", |
| 403 |
("es-GT", Gender.FEMALE): "MartaNeural", |
| 404 |
("es-GT", Gender.MALE): "AndresNeural", |
| 405 |
("es-HN", Gender.FEMALE): "KarlaNeural", |
| 406 |
("es-HN", Gender.MALE): "CarlosNeural", |
| 407 |
("es-MX", Gender.FEMALE): "DaliaNeural", |
| 408 |
("es-MX", Gender.MALE): "JorgeNeural", |
| 409 |
("es-NI", Gender.FEMALE): "YolandaNeural", |
| 410 |
("es-NI", Gender.MALE): "FedericoNeural", |
| 411 |
("es-PA", Gender.FEMALE): "MargaritaNeural", |
| 412 |
("es-PA", Gender.MALE): "RobertoNeural", |
| 413 |
("es-PY", Gender.FEMALE): "TaniaNeural", |
| 414 |
("es-PY", Gender.MALE): "MarioNeural", |
| 415 |
("es-PE", Gender.FEMALE): "CamilaNeural", |
| 416 |
("es-PE", Gender.MALE): "AlexNeural", |
| 417 |
("es-PR", Gender.FEMALE): "KarinaNeural", |
| 418 |
("es-PR", Gender.MALE): "VictorNeural", |
| 419 |
("es-ES", Gender.FEMALE): "ElviraNeural", |
| 420 |
("es-ES", Gender.MALE): "AlvaroNeural", |
| 421 |
("es-UY", Gender.FEMALE): "ValentinaNeural", |
| 422 |
("es-UY", Gender.MALE): "MateoNeural", |
| 423 |
("es-US", Gender.FEMALE): "PalomaNeural", |
| 424 |
("es-US", Gender.MALE): "AlonsoNeural", |
| 425 |
("es-VE", Gender.FEMALE): "PaolaNeural", |
| 426 |
("es-VE", Gender.MALE): "SebastianNeural", |
| 427 |
("su-ID", Gender.FEMALE): "TutiNeural", |
| 428 |
("su-ID", Gender.MALE): "JajangNeural", |
| 429 |
("sw-KE", Gender.FEMALE): "ZuriNeural", |
| 430 |
("sw-KE", Gender.MALE): "RafikiNeural", |
| 431 |
("sw-TZ", Gender.FEMALE): "RehemaNeural", |
| 432 |
("sw-TZ", Gender.MALE): "DaudiNeural", |
| 433 |
("sv-SE", Gender.FEMALE): "SofieNeural", |
| 434 |
("sv-SE", Gender.MALE): "MattiasNeural", |
| 435 |
("ta-IN", Gender.FEMALE): "PallaviNeural", |
| 436 |
("ta-IN", Gender.MALE): "ValluvarNeural", |
| 437 |
("ta-SG", Gender.FEMALE): "VenbaNeural", |
| 438 |
("ta-SG", Gender.MALE): "AnbuNeural", |
| 439 |
("ta-LK", Gender.FEMALE): "SaranyaNeural", |
| 440 |
("ta-LK", Gender.MALE): "KumarNeural", |
| 441 |
("te-IN", Gender.FEMALE): "ShrutiNeural", |
| 442 |
("te-IN", Gender.MALE): "MohanNeural", |
| 443 |
("th-TH", Gender.FEMALE): "AcharaNeural", |
| 444 |
("th-TH", Gender.MALE): "NiwatNeural", |
| 445 |
("tr-TR", Gender.FEMALE): "EmelNeural", |
| 446 |
("tr-TR", Gender.MALE): "AhmetNeural", |
| 447 |
("uk-UA", Gender.FEMALE): "PolinaNeural", |
| 448 |
("uk-UA", Gender.MALE): "OstapNeural", |
| 449 |
("ur-IN", Gender.FEMALE): "GulNeural", |
| 450 |
("ur-IN", Gender.MALE): "SalmanNeural", |
| 451 |
("ur-PK", Gender.FEMALE): "UzmaNeural", |
| 452 |
("ur-PK", Gender.MALE): "AsadNeural", |
| 453 |
("uz-UZ", Gender.FEMALE): "MadinaNeural", |
| 454 |
("uz-UZ", Gender.MALE): "SardorNeural", |
| 455 |
("vi-VN", Gender.FEMALE): "HoaiMyNeural", |
| 456 |
("vi-VN", Gender.MALE): "NamMinhNeural", |
| 457 |
("cy-GB", Gender.FEMALE): "NiaNeural", |
| 458 |
("cy-GB", Gender.MALE): "AledNeural", |
| 459 |
("zu-ZA", Gender.FEMALE): "ThandoNeural", |
| 460 |
("zu-ZA", Gender.MALE): "ThembaNeural", |
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
@attr.s |
| 465 |
class STTResponse: |
| 466 |
"""Response of STT.""" |
| 467 |
|
| 468 |
success: bool = attr.ib() |
| 469 |
text: str | None = attr.ib() |
| 470 |
|
| 471 |
|
| 472 |
class Voice: |
| 473 |
"""Class to help manage azure STT and TTS.""" |
| 474 |
|
| 475 |
def __init__(self, cloud: Cloud[_ClientT]) -> None: |
| 476 |
"""Initialize azure voice.""" |
| 477 |
self.cloud = cloud |
| 478 |
self._token: str | None = None |
| 479 |
self._endpoint_tts: str | None = None |
| 480 |
self._endpoint_stt: str | None = None |
| 481 |
self._valid: datetime | None = None |
| 482 |
|
| 483 |
def _validate_token(self) -> bool: |
| 484 |
"""Validate token outside of coroutine.""" |
| 485 |
return self.cloud.valid_subscription and bool( |
| 486 |
self._valid and utcnow() < self._valid |
| 487 |
) |
| 488 |
|
| 489 |
async def _update_token(self) -> None: |
| 490 |
"""Update token details.""" |
| 491 |
if not self.cloud.valid_subscription: |
| 492 |
raise VoiceTokenError("Invalid subscription") |
| 493 |
|
| 494 |
try: |
| 495 |
details = await self.cloud.voice_api.connection_details() |
| 496 |
except VoiceApiError as err: |
| 497 |
raise VoiceTokenError(err) from err |
| 498 |
|
| 499 |
self._token = details["authorized_key"] |
| 500 |
self._endpoint_stt = details["endpoint_stt"] |
| 501 |
self._endpoint_tts = details["endpoint_tts"] |
| 502 |
self._valid = utc_from_timestamp(float(details["valid"])) |
| 503 |
|
| 504 |
async def process_stt( |
| 505 |
self, |
| 506 |
*, |
| 507 |
stream: AsyncIterable[bytes], |
| 508 |
content_type: str, |
| 509 |
language: str, |
| 510 |
force_token_renewal: bool = False, |
| 511 |
) -> STTResponse: |
| 512 |
"""Stream Audio to Azure cognitive instance.""" |
| 513 |
if language not in STT_LANGUAGES: |
| 514 |
raise VoiceError(f"Language {language} not supported") |
| 515 |
|
| 516 |
if force_token_renewal or not self._validate_token(): |
| 517 |
await self._update_token() |
| 518 |
|
| 519 |
# Send request |
| 520 |
async with self.cloud.websession.post( |
| 521 |
f"{self._endpoint_stt}?language={language}&profanity=raw", |
| 522 |
headers={ |
| 523 |
CONTENT_TYPE: content_type, |
| 524 |
AUTHORIZATION: f"Bearer {self._token}", |
| 525 |
ACCEPT: "application/json;text/xml", |
| 526 |
USER_AGENT: self.cloud.client.client_name, |
| 527 |
}, |
| 528 |
data=stream, |
| 529 |
expect100=True, |
| 530 |
chunked=True, |
| 531 |
) as resp: |
| 532 |
if resp.status == 429 and not force_token_renewal: |
| 533 |
# By checking the force_token_renewal argument, we limit retries to 1. |
| 534 |
_LOGGER.info("Retrying with new token") |
| 535 |
return await self.process_stt( |
| 536 |
stream=stream, |
| 537 |
content_type=content_type, |
| 538 |
language=language, |
| 539 |
force_token_renewal=True, |
| 540 |
) |
| 541 |
if resp.status not in (200, 201): |
| 542 |
raise VoiceReturnError( |
| 543 |
f"Error processing {language} speech: " |
| 544 |
f"{resp.status} {await resp.text()}", |
| 545 |
) |
| 546 |
data = await resp.json() |
| 547 |
|
| 548 |
# Parse Answer |
| 549 |
return STTResponse( |
| 550 |
data["RecognitionStatus"] == "Success", |
| 551 |
data.get("DisplayText"), |
| 552 |
) |
| 553 |
|
| 554 |
async def process_tts( |
| 555 |
self, |
| 556 |
*, |
| 557 |
text: str, |
| 558 |
language: str, |
| 559 |
output: AudioOutput, |
| 560 |
voice: str | None = None, |
| 561 |
gender: Gender | None = None, |
| 562 |
force_token_renewal: bool = False, |
| 563 |
style: str | None = None, |
| 564 |
) -> bytes: |
| 565 |
"""Get Speech from text over Azure.""" |
| 566 |
if (language_info := TTS_VOICES.get(language)) is None: |
| 567 |
raise VoiceError(f"Unsupported language {language}") |
| 568 |
|
| 569 |
# Backwards compatibility for old config |
| 570 |
if voice is None and gender is not None: |
| 571 |
voice = MAP_VOICE.get((language, gender)) |
| 572 |
|
| 573 |
# If no voice picked, pick first one. |
| 574 |
if voice is None: |
| 575 |
voice = next(iter(language_info)) |
| 576 |
|
| 577 |
if (voice_info := language_info.get(voice)) is None: |
| 578 |
raise VoiceError(f"Unsupported voice {voice} for language {language}") |
| 579 |
|
| 580 |
if style and ( |
| 581 |
isinstance(voice_info, str) or style not in voice_info.get("variants", []) |
| 582 |
): |
| 583 |
raise VoiceError( |
| 584 |
f"Unsupported style {style} for voice {voice} in language {language}" |
| 585 |
) |
| 586 |
|
| 587 |
if force_token_renewal or not self._validate_token(): |
| 588 |
await self._update_token() |
| 589 |
|
| 590 |
# SSML |
| 591 |
xml_body = ET.Element( |
| 592 |
"speak", |
| 593 |
attrib={ |
| 594 |
"version": "1.0", |
| 595 |
"xmlns": "http://www.w3.org/2001/10/synthesis", |
| 596 |
"xmlns:mstts": "https://www.w3.org/2001/mstts", |
| 597 |
"{http://www.w3.org/XML/1998/namespace}lang": language, |
| 598 |
}, |
| 599 |
) |
| 600 |
|
| 601 |
# Add <voice> element |
| 602 |
voice_el = ET.SubElement( |
| 603 |
xml_body, "voice", attrib={"name": f"{language}-{voice}"} |
| 604 |
) |
| 605 |
|
| 606 |
if style: |
| 607 |
express_el = ET.SubElement( |
| 608 |
voice_el, |
| 609 |
"mstts:express-as", |
| 610 |
attrib={ |
| 611 |
"style": style, |
| 612 |
}, |
| 613 |
) |
| 614 |
|
| 615 |
target_el = express_el |
| 616 |
else: |
| 617 |
target_el = voice_el |
| 618 |
|
| 619 |
target_el.text = text[:2048] |
| 620 |
|
| 621 |
# We can not get here without this being set, but mypy does not know that. |
| 622 |
assert self._endpoint_tts is not None |
| 623 |
|
| 624 |
if output == AudioOutput.RAW: |
| 625 |
output_header = "raw-16khz-16bit-mono-pcm" |
| 626 |
elif output == AudioOutput.WAV: |
| 627 |
output_header = "riff-24khz-16bit-mono-pcm" |
| 628 |
else: |
| 629 |
output_header = "audio-24khz-48kbitrate-mono-mp3" |
| 630 |
|
| 631 |
# Send request |
| 632 |
async with self.cloud.websession.post( |
| 633 |
self._endpoint_tts, |
| 634 |
headers={ |
| 635 |
CONTENT_TYPE: "application/ssml+xml", |
| 636 |
AUTHORIZATION: f"Bearer {self._token}", |
| 637 |
"X-Microsoft-OutputFormat": output_header, |
| 638 |
USER_AGENT: self.cloud.client.client_name, |
| 639 |
}, |
| 640 |
data=ET.tostring(xml_body), |
| 641 |
) as resp: |
| 642 |
if resp.status == 429 and not force_token_renewal: |
| 643 |
# By checking the force_token_renewal argument, we limit retries to 1. |
| 644 |
_LOGGER.info("Retrying with new token") |
| 645 |
return await self.process_tts( |
| 646 |
text=text, |
| 647 |
language=language, |
| 648 |
output=output, |
| 649 |
voice=voice, |
| 650 |
gender=gender, |
| 651 |
force_token_renewal=True, |
| 652 |
) |
| 653 |
if resp.status not in (200, 201): |
| 654 |
raise VoiceReturnError( |
| 655 |
f"Error receiving TTS with {language}/{voice}: " |
| 656 |
f"{resp.status} {await resp.text()}", |
| 657 |
) |
| 658 |
return await resp.read() |
| 659 |
|
| 660 |
async def process_tts_stream( |
| 661 |
self, |
| 662 |
*, |
| 663 |
text_stream: AsyncIterable[str], |
| 664 |
language: str, |
| 665 |
voice: str | None = None, |
| 666 |
gender: Gender | None = None, |
| 667 |
style: str | None = None, |
| 668 |
) -> AsyncGenerator[bytes]: |
| 669 |
"""Get streaming Speech from text over Azure.""" |
| 670 |
boundary_detector = SentenceBoundaryDetector() |
| 671 |
sentences: list[str] = [] |
| 672 |
sentences_ready = asyncio.Event() |
| 673 |
sentences_complete = False |
| 674 |
wav_header_sent = False |
| 675 |
|
| 676 |
async def _add_sentences() -> None: |
| 677 |
nonlocal sentences_complete |
| 678 |
|
| 679 |
try: |
| 680 |
# Text chunks may not be on word or sentence boundaries |
| 681 |
async for text_chunk in text_stream: |
| 682 |
for sentence in boundary_detector.add_chunk(text_chunk): |
| 683 |
if not sentence.strip(): |
| 684 |
continue |
| 685 |
|
| 686 |
sentences.append(sentence) |
| 687 |
|
| 688 |
if not sentences: |
| 689 |
continue |
| 690 |
|
| 691 |
sentences_ready.set() |
| 692 |
|
| 693 |
# Final sentence |
| 694 |
if text := boundary_detector.finish(): |
| 695 |
sentences.append(text) |
| 696 |
finally: |
| 697 |
sentences_complete = True |
| 698 |
sentences_ready.set() |
| 699 |
|
| 700 |
_add_sentences_task = asyncio.create_task(_add_sentences()) |
| 701 |
|
| 702 |
# Process new sentences as they're available, but synthesize the first |
| 703 |
# one immediately. While that's playing, synthesize (up to) the next 3 |
| 704 |
# sentences. After that, synthesize all completed sentences as they're |
| 705 |
# available. |
| 706 |
sentence_schedule = [1, 3] |
| 707 |
while True: |
| 708 |
await sentences_ready.wait() |
| 709 |
|
| 710 |
if not sentences_complete: |
| 711 |
# Don't wait again if no more sentences are coming |
| 712 |
sentences_ready.clear() |
| 713 |
|
| 714 |
if not sentences: |
| 715 |
if sentences_complete: |
| 716 |
# Exit TTS loop |
| 717 |
break |
| 718 |
|
| 719 |
# More sentences may be coming |
| 720 |
continue |
| 721 |
|
| 722 |
new_sentences = sentences[:] |
| 723 |
sentences.clear() |
| 724 |
|
| 725 |
while new_sentences: |
| 726 |
if sentence_schedule: |
| 727 |
max_sentences = sentence_schedule.pop(0) |
| 728 |
sentences_to_process = new_sentences[:max_sentences] |
| 729 |
new_sentences = new_sentences[len(sentences_to_process) :] |
| 730 |
else: |
| 731 |
# Process all available sentences together |
| 732 |
sentences_to_process = new_sentences[:] |
| 733 |
new_sentences.clear() |
| 734 |
|
| 735 |
# Combine all new sentences completed to this point |
| 736 |
text = " ".join(sentences_to_process).strip() |
| 737 |
|
| 738 |
if not text: |
| 739 |
continue |
| 740 |
|
| 741 |
# Synthesize audio while text chunks are still being accumulated |
| 742 |
wav_bytes = await self.process_tts( |
| 743 |
text=text, |
| 744 |
language=language, |
| 745 |
output=AudioOutput.WAV, |
| 746 |
voice=voice, |
| 747 |
gender=gender, |
| 748 |
style=style, |
| 749 |
) |
| 750 |
header_bytes, audio_bytes = _split_wav_header(wav_bytes) |
| 751 |
if not wav_header_sent: |
| 752 |
# Send WAV header once, then stream audio |
| 753 |
yield header_bytes |
| 754 |
wav_header_sent = True |
| 755 |
|
| 756 |
yield audio_bytes |
| 757 |
|
| 758 |
if not wav_header_sent: |
| 759 |
# Send empty WAV header if no audio data was received. |
| 760 |
# Without this, downstream audio processing will fail. |
| 761 |
yield _make_wav_header(rate=24000, width=2, channels=1) |
| 762 |
|
| 763 |
|
| 764 |
def _split_wav_header(wav_bytes: bytes) -> tuple[bytes, bytes]: |
| 765 |
"""Split WAV into (header, audio) tuple.""" |
| 766 |
with io.BytesIO(wav_bytes) as wav_io: |
| 767 |
wav_reader: wave.Wave_read = wave.open(wav_io, "rb") # noqa: SIM115 |
| 768 |
with wav_reader: |
| 769 |
return ( |
| 770 |
_make_wav_header( |
| 771 |
rate=wav_reader.getframerate(), |
| 772 |
width=wav_reader.getsampwidth(), |
| 773 |
channels=wav_reader.getnchannels(), |
| 774 |
), |
| 775 |
wav_reader.readframes(wav_reader.getnframes()), |
| 776 |
) |
| 777 |
|
| 778 |
|
| 779 |
def _make_wav_header(rate: int, width: int, channels: int) -> bytes: |
| 780 |
"""Return WAV header with nframes = 0 for streaming.""" |
| 781 |
with io.BytesIO() as wav_io: |
| 782 |
wav_writer: wave.Wave_write = wave.open(wav_io, "wb") # noqa: SIM115 |
| 783 |
with wav_writer: |
| 784 |
wav_writer.setframerate(rate) |
| 785 |
wav_writer.setsampwidth(width) |
| 786 |
wav_writer.setnchannels(channels) |
| 787 |
|
| 788 |
wav_io.seek(0) |
| 789 |
return wav_io.getvalue() |