diff --git a/homeassistant/components/google_cloud/manifest.json b/homeassistant/components/google_cloud/manifest.json index 80889ad72b97..6d82a4bfa442 100644 --- a/homeassistant/components/google_cloud/manifest.json +++ b/homeassistant/components/google_cloud/manifest.json @@ -11,6 +11,7 @@ "iot_class": "cloud_push", "requirements": [ "google-cloud-texttospeech==2.37.0", - "google-cloud-speech==2.40.0" + "google-cloud-speech==2.40.0", + "sentence-stream==1.3.0" ] } diff --git a/homeassistant/components/google_cloud/tts.py b/homeassistant/components/google_cloud/tts.py index d0098a771fbf..d8a425e26df7 100644 --- a/homeassistant/components/google_cloud/tts.py +++ b/homeassistant/components/google_cloud/tts.py @@ -1,24 +1,30 @@ """Support for the Google Cloud TTS service.""" +from collections.abc import AsyncGenerator import logging from pathlib import Path +import struct from typing import Any, cast, override from google.api_core.exceptions import GoogleAPIError, Unauthenticated from google.api_core.retry import AsyncRetry from google.cloud import texttospeech import probatio +from sentence_stream import async_stream_to_sentences from homeassistant.components.tts import ( CONF_LANG, PLATFORM_SCHEMA as TTS_PLATFORM_SCHEMA, Provider, TextToSpeechEntity, + TTSAudioRequest, + TTSAudioResponse, TtsAudioType, Voice, ) from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType @@ -46,6 +52,8 @@ _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = TTS_PLATFORM_SCHEMA.extend(tts_platform_schema().schema) +STREAMING_SAMPLE_RATE = 24000 + async def async_get_engine( hass: HomeAssistant, @@ -267,6 +275,102 @@ class GoogleCloudTTSEntity(BaseGoogleCloudProvider, TextToSpeechEntity): self._entry.async_start_reauth(self.hass) return None, None + @override + async def async_stream_tts_audio( + self, request: TTSAudioRequest + ) -> TTSAudioResponse: + """Generate speech from an incoming message.""" + try: + options = self._options_schema(request.options) + except probatio.Invalid: + # The non-streaming path logs the invalid options + return await super().async_stream_tts_audio(request) + + # Google only supports streaming for Chirp 3: HD voices and speaking rate + if ( + "Chirp3-HD" not in options[CONF_VOICE] + or options[CONF_PITCH] != DEFAULT_PITCH + or options[CONF_GAIN] != DEFAULT_GAIN + or options[CONF_PROFILES] + or options[CONF_TEXT_TYPE] != "text" + ): + return await super().async_stream_tts_audio(request) + + return TTSAudioResponse( + "wav", + self._async_stream_audio(request.message_gen, request.language, options), + ) + + async def _async_stream_audio( + self, + message_gen: AsyncGenerator[str], + language: str, + options: dict[str, Any], + ) -> AsyncGenerator[bytes]: + """Stream TTS from Google Cloud as WAV.""" + voice = options[CONF_VOICE] + if not voice.startswith(language): + language = voice[:5] + + config = texttospeech.StreamingSynthesizeConfig( + voice=texttospeech.VoiceSelectionParams( + language_code=language, + name=voice, + ), + streaming_audio_config=texttospeech.StreamingAudioConfig( + audio_encoding=texttospeech.AudioEncoding.PCM, + sample_rate_hertz=STREAMING_SAMPLE_RATE, + speaking_rate=( + options[CONF_SPEED] + if options[CONF_SPEED] != DEFAULT_SPEED + else None + ), + ), + ) + + def text_request(text: str) -> texttospeech.StreamingSynthesizeRequest: + # Google concatenates the inputs, so keep the sentences apart + return texttospeech.StreamingSynthesizeRequest( + input=texttospeech.StreamingSynthesisInput(text=f"{text} ") + ) + + async def request_gen() -> AsyncGenerator[ + texttospeech.StreamingSynthesizeRequest + ]: + yield texttospeech.StreamingSynthesizeRequest(streaming_config=config) + # Sending whole sentences avoids long pauses within the speech + async for sentence in async_stream_to_sentences(message_gen): + yield text_request(sentence) + + # WAV readers take a data size of 0 literally, so mark the sizes unknown + yield struct.pack( + "<4sI4s4sIHHIIHH4sI", + b"RIFF", + 0xFFFFFFFF, + b"WAVE", + b"fmt ", + 16, + 1, # PCM + 1, + STREAMING_SAMPLE_RATE, + STREAMING_SAMPLE_RATE * 2, + 2, + 16, + b"data", + 0xFFFFFFFF, + ) + + try: + responses = await self._client.streaming_synthesize(request_gen()) + async for response in responses: + yield response.audio_content + except GoogleAPIError as err: + if isinstance(err, Unauthenticated): + self._entry.async_start_reauth(self.hass) + raise HomeAssistantError( + f"Error occurred during Google Cloud TTS call: {err}" + ) from err + class GoogleCloudTTSProvider(BaseGoogleCloudProvider, Provider): """The Google Cloud TTS API provider.""" diff --git a/requirements_all.txt b/requirements_all.txt index ce290aaa86a2..de16981503eb 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3139,6 +3139,7 @@ sensorpush-ha==1.3.2 sensoterra==2.0.1 # homeassistant.components.elevenlabs +# homeassistant.components.google_cloud sentence-stream==1.3.0 # homeassistant.components.sentry diff --git a/tests/components/google_cloud/conftest.py b/tests/components/google_cloud/conftest.py index 4020242b81b0..1842beea85e9 100644 --- a/tests/components/google_cloud/conftest.py +++ b/tests/components/google_cloud/conftest.py @@ -98,6 +98,7 @@ def mock_api_tts() -> AsyncMock: voices=[ cloud_tts.Voice(language_codes=["en-US"], name="en-US-Standard-A"), cloud_tts.Voice(language_codes=["en-US"], name="en-US-Standard-B"), + cloud_tts.Voice(language_codes=["en-US"], name="en-US-Chirp3-HD-Achernar"), cloud_tts.Voice(language_codes=["en-US"], name="Standard-A"), cloud_tts.Voice(language_codes=["el-GR"], name="el-GR-Standard-A"), ] diff --git a/tests/components/google_cloud/snapshots/test_tts.ambr b/tests/components/google_cloud/snapshots/test_tts.ambr new file mode 100644 index 000000000000..cfc992453b09 --- /dev/null +++ b/tests/components/google_cloud/snapshots/test_tts.ambr @@ -0,0 +1,71 @@ +# serializer version: 1 +# name: test_stream_tts_audio[defaults] + list([ + streaming_config { + voice { + language_code: "en-US" + name: "en-US-Chirp3-HD-Achernar" + } + streaming_audio_config { + audio_encoding: PCM + sample_rate_hertz: 24000 + } + } + , + input { + text: "Hello world. " + } + , + input { + text: "How are you? " + } + , + ]) +# --- +# name: test_stream_tts_audio[language_from_voice] + list([ + streaming_config { + voice { + language_code: "en-US" + name: "en-US-Chirp3-HD-Achernar" + } + streaming_audio_config { + audio_encoding: PCM + sample_rate_hertz: 24000 + } + } + , + input { + text: "Hello world. " + } + , + input { + text: "How are you? " + } + , + ]) +# --- +# name: test_stream_tts_audio[speed] + list([ + streaming_config { + voice { + language_code: "en-US" + name: "en-US-Chirp3-HD-Achernar" + } + streaming_audio_config { + audio_encoding: PCM + sample_rate_hertz: 24000 + speaking_rate: 1.5 + } + } + , + input { + text: "Hello world. " + } + , + input { + text: "How are you? " + } + , + ]) +# --- diff --git a/tests/components/google_cloud/test_tts.py b/tests/components/google_cloud/test_tts.py new file mode 100644 index 000000000000..f296987879fd --- /dev/null +++ b/tests/components/google_cloud/test_tts.py @@ -0,0 +1,260 @@ +"""Tests for the Google Cloud TTS entity.""" + +import asyncio +from collections.abc import AsyncGenerator, AsyncIterator +import io +from typing import Any +from unittest.mock import AsyncMock, patch +import wave + +from google.api_core.exceptions import GoogleAPIError, Unauthenticated +from google.cloud.texttospeech_v1.types import cloud_tts +import pytest +from pytest_homeassistant.common import MockConfigEntry +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components import tts +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError + +TTS_ENTITY_ID = "tts.my_google_cloud_title" +CHIRP_VOICE = "en-US-Chirp3-HD-Achernar" + + +@pytest.fixture +async def setup_integration( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_api_tts_from_service_account_info: AsyncMock, +) -> None: + """Set up the Google Cloud integration.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + +def mock_streaming_synthesize( + mock_api_tts: AsyncMock, + audio_chunks: list[bytes], + error: Exception | None = None, + call_error: Exception | None = None, +) -> list[cloud_tts.StreamingSynthesizeRequest]: + """Mock streaming synthesis and return the list of sent requests.""" + requests: list[cloud_tts.StreamingSynthesizeRequest] = [] + + async def response_gen() -> AsyncGenerator[cloud_tts.StreamingSynthesizeResponse]: + for chunk in audio_chunks: + yield cloud_tts.StreamingSynthesizeResponse(audio_content=chunk) + if error: + raise error + + async def streaming_synthesize( + request_gen: AsyncIterator[cloud_tts.StreamingSynthesizeRequest], + ) -> AsyncGenerator[cloud_tts.StreamingSynthesizeResponse]: + if call_error: + raise call_error + requests.extend([request async for request in request_gen]) + return response_gen() + + mock_api_tts.streaming_synthesize.side_effect = streaming_synthesize + return requests + + +async def message_gen() -> AsyncGenerator[str]: + """Yield a message in chunks that are not on sentence boundaries.""" + yield "Hello wor" + yield "ld. How are" + yield " you?" + + +async def stream_audio( + hass: HomeAssistant, options: dict[str, Any], language: str = "en-US" +) -> bytes: + """Stream a message through the TTS entity and return the audio.""" + stream = tts.async_create_stream(hass, TTS_ENTITY_ID, language, options=options) + stream.async_set_message_stream(message_gen()) + return b"".join([chunk async for chunk in stream.async_stream_result()]) + + +@pytest.mark.usefixtures("setup_integration") +@pytest.mark.parametrize( + ("options", "language"), + [ + pytest.param({}, "en-US", id="defaults"), + pytest.param({"speed": 1.5}, "en-US", id="speed"), + pytest.param({}, "el-GR", id="language_from_voice"), + ], +) +async def test_stream_tts_audio( + hass: HomeAssistant, + mock_api_tts: AsyncMock, + options: dict[str, Any], + language: str, + snapshot: SnapshotAssertion, +) -> None: + """Test streaming synthesis with a Chirp 3: HD voice.""" + requests = mock_streaming_synthesize(mock_api_tts, [bytes(100), bytes(200)]) + + data = await stream_audio( + hass, + { + **options, + "voice": CHIRP_VOICE, + tts.TextToSpeechCommonOption.PREFERRED_FORMAT: "wav", + }, + language, + ) + + with io.BytesIO(data) as wav_io, wave.open(wav_io, "rb") as wav_file: + assert wav_file.getframerate() == 24000 + assert wav_file.getsampwidth() == 2 + assert wav_file.getnchannels() == 1 + assert wav_file.readframes(150) == bytes(300) + assert requests == snapshot + mock_api_tts.synthesize_speech.assert_not_called() + + +@pytest.mark.usefixtures("setup_integration") +async def test_stream_tts_audio_while_message_pending( + hass: HomeAssistant, + mock_api_tts: AsyncMock, +) -> None: + """Test audio is streamed before the whole message is generated.""" + message_finished = asyncio.Event() + + async def pending_message_gen() -> AsyncGenerator[str]: + yield "Hello world. How" + await message_finished.wait() + yield " are you?" + + async def streaming_synthesize( + request_gen: AsyncIterator[cloud_tts.StreamingSynthesizeRequest], + ) -> AsyncGenerator[cloud_tts.StreamingSynthesizeResponse]: + async def response_gen() -> AsyncGenerator[ + cloud_tts.StreamingSynthesizeResponse + ]: + async for request in request_gen: + if request.input.text: + yield cloud_tts.StreamingSynthesizeResponse( + audio_content=bytes(100) + ) + + return response_gen() + + mock_api_tts.streaming_synthesize.side_effect = streaming_synthesize + + stream = tts.async_create_stream( + hass, + TTS_ENTITY_ID, + "en-US", + options={ + "voice": CHIRP_VOICE, + tts.TextToSpeechCommonOption.PREFERRED_FORMAT: "wav", + }, + ) + stream.async_set_message_stream(pending_message_gen()) + audio = stream.async_stream_result() + + assert len(await anext(audio)) == 44 # WAV header + assert await anext(audio) == bytes(100) + + message_finished.set() + assert [chunk async for chunk in audio] == [bytes(100)] + + +@pytest.mark.usefixtures("setup_integration") +@pytest.mark.parametrize( + "options", + [ + pytest.param({}, id="no_voice"), + pytest.param({"voice": "en-US-Standard-A"}, id="standard_voice"), + pytest.param({"voice": CHIRP_VOICE, "pitch": 2.0}, id="pitch"), + pytest.param({"voice": CHIRP_VOICE, "gain": 2.0}, id="gain"), + pytest.param( + {"voice": CHIRP_VOICE, "profiles": ["telephony-class-application"]}, + id="profiles", + ), + pytest.param({"voice": CHIRP_VOICE, "text_type": "ssml"}, id="ssml"), + ], +) +async def test_stream_tts_audio_not_supported( + hass: HomeAssistant, + mock_api_tts: AsyncMock, + options: dict[str, Any], +) -> None: + """Test the message is synthesized at once if streaming is not supported.""" + mock_api_tts.synthesize_speech.return_value = cloud_tts.SynthesizeSpeechResponse( + audio_content=b"mp3 audio" + ) + + data = await stream_audio(hass, options) + + assert data == b"mp3 audio" + mock_api_tts.streaming_synthesize.assert_not_called() + mock_api_tts.synthesize_speech.assert_called_once() + + +@pytest.mark.usefixtures("setup_integration") +@pytest.mark.parametrize( + ("error", "call_error"), + [ + pytest.param(GoogleAPIError("error"), None, id="response"), + pytest.param(None, GoogleAPIError("error"), id="call"), + ], +) +async def test_stream_tts_audio_error( + hass: HomeAssistant, + mock_api_tts: AsyncMock, + error: Exception | None, + call_error: Exception | None, +) -> None: + """Test an error during streaming synthesis.""" + mock_streaming_synthesize(mock_api_tts, [bytes(100)], error, call_error) + + with pytest.raises( + HomeAssistantError, match="Error occurred during Google Cloud TTS call" + ): + await stream_audio( + hass, + { + "voice": CHIRP_VOICE, + tts.TextToSpeechCommonOption.PREFERRED_FORMAT: "wav", + }, + ) + + +@pytest.mark.usefixtures("setup_integration") +async def test_stream_tts_audio_unauthenticated( + hass: HomeAssistant, + mock_api_tts: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauth is started when the credentials are rejected.""" + mock_streaming_synthesize(mock_api_tts, [], call_error=Unauthenticated("error")) + + with ( + patch.object(mock_config_entry, "async_start_reauth") as mock_start_reauth, + pytest.raises(HomeAssistantError), + ): + await stream_audio( + hass, + { + "voice": CHIRP_VOICE, + tts.TextToSpeechCommonOption.PREFERRED_FORMAT: "wav", + }, + ) + + mock_start_reauth.assert_called_once_with(hass) + + +@pytest.mark.usefixtures("setup_integration") +async def test_stream_tts_audio_invalid_options( + hass: HomeAssistant, + mock_api_tts: AsyncMock, +) -> None: + """Test invalid options.""" + with pytest.raises(HomeAssistantError): + await stream_audio(hass, {"voice": "invalid"}) + + mock_api_tts.streaming_synthesize.assert_not_called() + mock_api_tts.synthesize_speech.assert_not_called()