| 1 |
"""Test for voice functions.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
from datetime import timedelta |
| 5 |
import io |
| 6 |
from unittest.mock import patch |
| 7 |
import wave |
| 8 |
|
| 9 |
import pytest |
| 10 |
import xmltodict |
| 11 |
|
| 12 |
from hass_nabucasa import Cloud, voice |
| 13 |
from hass_nabucasa.auth import Unauthenticated |
| 14 |
|
| 15 |
|
| 16 |
@pytest.fixture(autouse=True) |
| 17 |
def mock_voice_connection_details(aioclient_mock, cloud: Cloud): |
| 18 |
"""Mock voice connection details.""" |
| 19 |
aioclient_mock.get( |
| 20 |
f"https://{cloud.api_server}/voice/connection_details", |
| 21 |
json={ |
| 22 |
"authorized_key": "test-key", |
| 23 |
"endpoint_stt": "stt-url", |
| 24 |
"endpoint_tts": "tts-url", |
| 25 |
"valid": f"{(voice.utcnow() + timedelta(minutes=9)).timestamp()}", |
| 26 |
}, |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
async def test_token_handling( |
| 31 |
cloud: Cloud, aioclient_mock, mock_voice_connection_details |
| 32 |
): |
| 33 |
"""Test handling around token.""" |
| 34 |
assert not cloud.voice._validate_token() |
| 35 |
await cloud.voice._update_token() |
| 36 |
assert cloud.voice._validate_token() |
| 37 |
|
| 38 |
assert cloud.voice._endpoint_stt == "stt-url" |
| 39 |
assert cloud.voice._endpoint_tts == "tts-url" |
| 40 |
assert cloud.voice._token == "test-key" |
| 41 |
|
| 42 |
|
| 43 |
async def test_process_stt(cloud: Cloud, aioclient_mock, mock_voice_connection_details): |
| 44 |
"""Test handling around stt.""" |
| 45 |
aioclient_mock.post( |
| 46 |
"stt-url?language=en-US", |
| 47 |
json={"RecognitionStatus": "Success", "DisplayText": "My Text"}, |
| 48 |
) |
| 49 |
result = await cloud.voice.process_stt( |
| 50 |
stream=b"feet", |
| 51 |
content_type="video=test", |
| 52 |
language="en-US", |
| 53 |
) |
| 54 |
|
| 55 |
assert result.success |
| 56 |
assert result.text == "My Text" |
| 57 |
|
| 58 |
|
| 59 |
async def test_process_stt_bad_language(cloud: Cloud): |
| 60 |
"""Test language handling around stt.""" |
| 61 |
with pytest.raises(voice.VoiceError, match="Language en-BAD not supported"): |
| 62 |
await cloud.voice.process_stt( |
| 63 |
stream=b"feet", |
| 64 |
content_type="video=test", |
| 65 |
language="en-BAD", |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
async def test_process_tts_with_gender( |
| 70 |
cloud: Cloud, |
| 71 |
aioclient_mock, |
| 72 |
mock_voice_connection_details, |
| 73 |
snapshot, |
| 74 |
): |
| 75 |
"""Test handling around tts.""" |
| 76 |
aioclient_mock.post( |
| 77 |
"tts-url", |
| 78 |
content=b"My sound", |
| 79 |
) |
| 80 |
result = await cloud.voice.process_tts( |
| 81 |
text="Text for Saying", |
| 82 |
language="en-US", |
| 83 |
gender=voice.Gender.FEMALE, |
| 84 |
output=voice.AudioOutput.MP3, |
| 85 |
) |
| 86 |
|
| 87 |
assert result == b"My sound" |
| 88 |
assert aioclient_mock.mock_calls[1][3] == { |
| 89 |
"Authorization": "Bearer test-key", |
| 90 |
"Content-Type": "application/ssml+xml", |
| 91 |
"X-Microsoft-OutputFormat": "audio-24khz-48kbitrate-mono-mp3", |
| 92 |
"User-Agent": "hass-nabucasa/tests", |
| 93 |
} |
| 94 |
assert xmltodict.parse(aioclient_mock.mock_calls[1][2]) == snapshot |
| 95 |
|
| 96 |
|
| 97 |
async def test_process_tts_with_voice( |
| 98 |
cloud: Cloud, |
| 99 |
aioclient_mock, |
| 100 |
mock_voice_connection_details, |
| 101 |
snapshot, |
| 102 |
): |
| 103 |
"""Test handling around tts.""" |
| 104 |
aioclient_mock.post( |
| 105 |
"tts-url", |
| 106 |
content=b"My sound", |
| 107 |
) |
| 108 |
result = await cloud.voice.process_tts( |
| 109 |
text="Text for Saying", |
| 110 |
language="nl-NL", |
| 111 |
voice="FennaNeural", |
| 112 |
output=voice.AudioOutput.RAW, |
| 113 |
) |
| 114 |
|
| 115 |
assert result == b"My sound" |
| 116 |
assert aioclient_mock.mock_calls[1][3] == { |
| 117 |
"Authorization": "Bearer test-key", |
| 118 |
"Content-Type": "application/ssml+xml", |
| 119 |
"X-Microsoft-OutputFormat": "raw-16khz-16bit-mono-pcm", |
| 120 |
"User-Agent": "hass-nabucasa/tests", |
| 121 |
} |
| 122 |
assert xmltodict.parse(aioclient_mock.mock_calls[1][2]) == snapshot |
| 123 |
|
| 124 |
|
| 125 |
async def test_process_tts_stream_with_voice(cloud: Cloud, aioclient_mock, snapshot): |
| 126 |
"""Test handling around tts streaming.""" |
| 127 |
with io.BytesIO() as wav_io: |
| 128 |
wav_writer: wave.Wave_write = wave.open(wav_io, "wb") |
| 129 |
with wav_writer: |
| 130 |
wav_writer.setframerate(24000) |
| 131 |
wav_writer.setsampwidth(2) |
| 132 |
wav_writer.setnchannels(1) |
| 133 |
wav_writer.writeframes(b"My sound") |
| 134 |
|
| 135 |
wav_io.seek(0) |
| 136 |
wav_bytes = wav_io.getvalue() |
| 137 |
|
| 138 |
aioclient_mock.post( |
| 139 |
"tts-url", |
| 140 |
content=wav_bytes, |
| 141 |
) |
| 142 |
|
| 143 |
async def text_gen(): |
| 144 |
yield "Text for Say" |
| 145 |
yield "ing. More Text" |
| 146 |
yield " for saying." |
| 147 |
yield "".join(f" Sentence {i}." for i in range(10)) |
| 148 |
|
| 149 |
result = bytearray() |
| 150 |
async for data_chunk in cloud.voice.process_tts_stream( |
| 151 |
text_stream=text_gen(), |
| 152 |
language="nl-NL", |
| 153 |
voice="FennaNeural", |
| 154 |
): |
| 155 |
result.extend(data_chunk) |
| 156 |
|
| 157 |
with io.BytesIO(result) as wav_io: |
| 158 |
wav_reader: wave.Wave_read = wave.open(wav_io, "rb") |
| 159 |
with wav_reader: |
| 160 |
assert wav_reader.getframerate() == 24000 |
| 161 |
assert wav_reader.getsampwidth() == 2 |
| 162 |
assert wav_reader.getnchannels() == 1 |
| 163 |
assert wav_reader.getnframes() == 0 # streaming |
| 164 |
|
| 165 |
audio_bytes = result[44:] # skip header |
| 166 |
|
| 167 |
# 3 audio chunks are produced: |
| 168 |
# 1. First sentence |
| 169 |
# 2. Next 3 sentences. |
| 170 |
# 3. All sentences after that. |
| 171 |
assert audio_bytes == b"My soundMy soundMy sound" |
| 172 |
|
| 173 |
assert aioclient_mock.mock_calls[1][3] == { |
| 174 |
"Authorization": "Bearer test-key", |
| 175 |
"Content-Type": "application/ssml+xml", |
| 176 |
"X-Microsoft-OutputFormat": "riff-24khz-16bit-mono-pcm", |
| 177 |
"User-Agent": "hass-nabucasa/tests", |
| 178 |
} |
| 179 |
assert xmltodict.parse(aioclient_mock.mock_calls[1][2]) == snapshot |
| 180 |
|
| 181 |
|
| 182 |
async def test_process_tts_stream_with_voice_final_sentence( |
| 183 |
cloud: Cloud, aioclient_mock, snapshot |
| 184 |
): |
| 185 |
"""Test handling around tts streaming with final sentence.""" |
| 186 |
with io.BytesIO() as wav_io: |
| 187 |
wav_writer: wave.Wave_write = wave.open(wav_io, "wb") |
| 188 |
with wav_writer: |
| 189 |
wav_writer.setframerate(24000) |
| 190 |
wav_writer.setsampwidth(2) |
| 191 |
wav_writer.setnchannels(1) |
| 192 |
wav_writer.writeframes(b"My sound") |
| 193 |
|
| 194 |
wav_io.seek(0) |
| 195 |
wav_bytes = wav_io.getvalue() |
| 196 |
|
| 197 |
aioclient_mock.post( |
| 198 |
"tts-url", |
| 199 |
content=wav_bytes, |
| 200 |
) |
| 201 |
|
| 202 |
# Use events to force the following order of events: |
| 203 |
# 1. text chunk is emitted with enough for 1 sentence |
| 204 |
# 2. TTS starts |
| 205 |
# 3. final text chunk is emitted *before* TTS finishes |
| 206 |
# 4. final sentence TTS is processed in the next loop |
| 207 |
# |
| 208 |
# We must check that the final sentence is not dropped because the previous |
| 209 |
# TTS is on-going. |
| 210 |
chunk_event = asyncio.Event() |
| 211 |
tts_event = asyncio.Event() |
| 212 |
first_chunk = True |
| 213 |
|
| 214 |
async def process_tts(*args, **kwargs): |
| 215 |
nonlocal first_chunk |
| 216 |
|
| 217 |
if first_chunk: |
| 218 |
first_chunk = False |
| 219 |
await chunk_event.wait() |
| 220 |
chunk_event.clear() |
| 221 |
tts_event.set() |
| 222 |
await chunk_event.wait() |
| 223 |
|
| 224 |
return wav_bytes |
| 225 |
|
| 226 |
async def text_gen(): |
| 227 |
yield "Test 1. \n\nTest" |
| 228 |
chunk_event.set() |
| 229 |
|
| 230 |
yield " 2." |
| 231 |
await tts_event.wait() |
| 232 |
chunk_event.set() |
| 233 |
|
| 234 |
result = bytearray() |
| 235 |
with patch.object(cloud.voice, "process_tts", process_tts): |
| 236 |
async for data_chunk in cloud.voice.process_tts_stream( |
| 237 |
text_stream=text_gen(), |
| 238 |
language="nl-NL", |
| 239 |
voice="FennaNeural", |
| 240 |
): |
| 241 |
result.extend(data_chunk) |
| 242 |
|
| 243 |
with io.BytesIO(result) as wav_io: |
| 244 |
wav_reader: wave.Wave_read = wave.open(wav_io, "rb") |
| 245 |
with wav_reader: |
| 246 |
assert wav_reader.getframerate() == 24000 |
| 247 |
assert wav_reader.getsampwidth() == 2 |
| 248 |
assert wav_reader.getnchannels() == 1 |
| 249 |
assert wav_reader.getnframes() == 0 # streaming |
| 250 |
|
| 251 |
audio_bytes = result[44:] # skip header |
| 252 |
|
| 253 |
assert audio_bytes == b"My soundMy sound" |
| 254 |
|
| 255 |
|
| 256 |
async def test_process_tts_stream_no_text(cloud: Cloud, aioclient_mock): |
| 257 |
"""Test tts streaming returns valid WAV header with no text.""" |
| 258 |
aioclient_mock.post( |
| 259 |
"tts-url", |
| 260 |
content=b"", |
| 261 |
) |
| 262 |
|
| 263 |
async def text_gen(): |
| 264 |
yield "" |
| 265 |
|
| 266 |
result = bytearray() |
| 267 |
async for data_chunk in cloud.voice.process_tts_stream( |
| 268 |
text_stream=text_gen(), |
| 269 |
language="nl-NL", |
| 270 |
voice="FennaNeural", |
| 271 |
): |
| 272 |
result.extend(data_chunk) |
| 273 |
|
| 274 |
assert len(result) == 44 # header only |
| 275 |
|
| 276 |
with io.BytesIO(result) as wav_io: |
| 277 |
wav_reader: wave.Wave_read = wave.open(wav_io, "rb") |
| 278 |
with wav_reader: |
| 279 |
assert wav_reader.getframerate() == 24000 |
| 280 |
assert wav_reader.getsampwidth() == 2 |
| 281 |
assert wav_reader.getnchannels() == 1 |
| 282 |
assert wav_reader.getnframes() == 0 # streaming |
| 283 |
|
| 284 |
|
| 285 |
async def test_process_tts_with_voice_and_style( |
| 286 |
cloud: Cloud, |
| 287 |
aioclient_mock, |
| 288 |
mock_voice_connection_details, |
| 289 |
snapshot, |
| 290 |
): |
| 291 |
"""Test handling around tts.""" |
| 292 |
aioclient_mock.post( |
| 293 |
"tts-url", |
| 294 |
content=b"My sound", |
| 295 |
) |
| 296 |
|
| 297 |
# Voice with variants |
| 298 |
result = await cloud.voice.process_tts( |
| 299 |
text="Text for Saying", |
| 300 |
language="de-DE", |
| 301 |
voice="ConradNeural", |
| 302 |
style="cheerful", |
| 303 |
output=voice.AudioOutput.RAW, |
| 304 |
) |
| 305 |
|
| 306 |
assert result == b"My sound" |
| 307 |
assert aioclient_mock.mock_calls[1][3] == { |
| 308 |
"Authorization": "Bearer test-key", |
| 309 |
"Content-Type": "application/ssml+xml", |
| 310 |
"X-Microsoft-OutputFormat": "raw-16khz-16bit-mono-pcm", |
| 311 |
"User-Agent": "hass-nabucasa/tests", |
| 312 |
} |
| 313 |
assert xmltodict.parse(aioclient_mock.mock_calls[1][2]) == snapshot |
| 314 |
|
| 315 |
with pytest.raises( |
| 316 |
voice.VoiceError, |
| 317 |
match="Unsupported style non-existing-style " |
| 318 |
"for voice ConradNeural in language de-DE", |
| 319 |
): |
| 320 |
await cloud.voice.process_tts( |
| 321 |
text="Text for Saying", |
| 322 |
language="de-DE", |
| 323 |
voice="ConradNeural", |
| 324 |
style="non-existing-style", |
| 325 |
output=voice.AudioOutput.RAW, |
| 326 |
) |
| 327 |
|
| 328 |
# Voice without variants |
| 329 |
result = await cloud.voice.process_tts( |
| 330 |
text="Text for Saying 2", |
| 331 |
language="en-US", |
| 332 |
voice="MichelleNeural", |
| 333 |
output=voice.AudioOutput.RAW, |
| 334 |
) |
| 335 |
|
| 336 |
assert result == b"My sound" |
| 337 |
assert aioclient_mock.mock_calls[1][3] == { |
| 338 |
"Authorization": "Bearer test-key", |
| 339 |
"Content-Type": "application/ssml+xml", |
| 340 |
"X-Microsoft-OutputFormat": "raw-16khz-16bit-mono-pcm", |
| 341 |
"User-Agent": "hass-nabucasa/tests", |
| 342 |
} |
| 343 |
assert xmltodict.parse(aioclient_mock.mock_calls[2][2]) == snapshot |
| 344 |
|
| 345 |
with pytest.raises( |
| 346 |
voice.VoiceError, |
| 347 |
match="Unsupported style non-existing-style " |
| 348 |
"for voice MichelleNeural in language en-US", |
| 349 |
): |
| 350 |
await cloud.voice.process_tts( |
| 351 |
text="Text for Saying 2", |
| 352 |
language="en-US", |
| 353 |
voice="MichelleNeural", |
| 354 |
style="non-existing-style", |
| 355 |
output=voice.AudioOutput.RAW, |
| 356 |
) |
| 357 |
|
| 358 |
|
| 359 |
async def test_process_tts_bad_language(cloud: Cloud): |
| 360 |
"""Test language error handling around tts.""" |
| 361 |
with pytest.raises(voice.VoiceError, match="Unsupported language en-BAD"): |
| 362 |
await cloud.voice.process_tts( |
| 363 |
text="Text for Saying", |
| 364 |
language="en-BAD", |
| 365 |
output=voice.AudioOutput.MP3, |
| 366 |
) |
| 367 |
|
| 368 |
|
| 369 |
async def test_process_tts_bad_voice(cloud: Cloud): |
| 370 |
"""Test voice error handling around tts.""" |
| 371 |
with pytest.raises( |
| 372 |
voice.VoiceError, match="Unsupported voice Not a US voice for language en-US" |
| 373 |
): |
| 374 |
await cloud.voice.process_tts( |
| 375 |
text="Text for Saying", |
| 376 |
language="en-US", |
| 377 |
voice="Not a US voice", |
| 378 |
output=voice.AudioOutput.MP3, |
| 379 |
) |
| 380 |
|
| 381 |
|
| 382 |
async def test_process_tss_429( |
| 383 |
cloud: Cloud, |
| 384 |
mock_voice_connection_details, |
| 385 |
aioclient_mock, |
| 386 |
caplog, |
| 387 |
): |
| 388 |
"""Test handling of voice with 429.""" |
| 389 |
aioclient_mock.post( |
| 390 |
"tts-url", |
| 391 |
status=429, |
| 392 |
) |
| 393 |
|
| 394 |
with pytest.raises( |
| 395 |
voice.VoiceError, match="Error receiving TTS with en-US/JennyNeural: 429 " |
| 396 |
): |
| 397 |
await cloud.voice.process_tts( |
| 398 |
text="Text for Saying", |
| 399 |
language="en-US", |
| 400 |
gender=voice.Gender.FEMALE, |
| 401 |
output=voice.AudioOutput.MP3, |
| 402 |
) |
| 403 |
|
| 404 |
assert len(aioclient_mock.mock_calls) == 4 |
| 405 |
|
| 406 |
assert "Retrying with new token" in caplog.text |
| 407 |
|
| 408 |
|
| 409 |
async def test_process_stt_429( |
| 410 |
cloud: Cloud, |
| 411 |
mock_voice_connection_details, |
| 412 |
aioclient_mock, |
| 413 |
caplog, |
| 414 |
): |
| 415 |
"""Test handling of voice with 429.""" |
| 416 |
aioclient_mock.post( |
| 417 |
"stt-url", |
| 418 |
status=429, |
| 419 |
) |
| 420 |
|
| 421 |
with pytest.raises(voice.VoiceError, match="Error processing en-US speech: 429 "): |
| 422 |
await cloud.voice.process_stt( |
| 423 |
stream=b"feet", |
| 424 |
content_type="video=test", |
| 425 |
language="en-US", |
| 426 |
) |
| 427 |
|
| 428 |
assert len(aioclient_mock.mock_calls) == 4 |
| 429 |
|
| 430 |
assert "Retrying with new token" in caplog.text |
| 431 |
|
| 432 |
|
| 433 |
async def test_process_tts_without_authentication( |
| 434 |
cloud: Cloud, |
| 435 |
): |
| 436 |
"""Test handling of voice without authentication.""" |
| 437 |
|
| 438 |
async def async_check_token(*args, **kwargs): |
| 439 |
"""Mock token check.""" |
| 440 |
raise Unauthenticated("No authentication") |
| 441 |
|
| 442 |
cloud.auth.async_check_token = async_check_token |
| 443 |
|
| 444 |
with ( |
| 445 |
pytest.raises( |
| 446 |
voice.VoiceError, |
| 447 |
match="No authentication", |
| 448 |
), |
| 449 |
): |
| 450 |
await cloud.voice.process_stt( |
| 451 |
stream=b"feet", |
| 452 |
content_type="video=test", |
| 453 |
language="en-US", |
| 454 |
) |