-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
/
Copy pathtts.py
169 lines (138 loc) · 4.92 KB
/
tts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""Support for the Google speech service."""
from __future__ import annotations
from io import BytesIO
import logging
from typing import Any
from gtts import gTTS, gTTSError
import voluptuous as vol
from homeassistant.components.tts import (
CONF_LANG,
PLATFORM_SCHEMA as TTS_PLATFORM_SCHEMA,
Provider,
TextToSpeechEntity,
TtsAudioType,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import (
CONF_TLD,
DEFAULT_LANG,
DEFAULT_TLD,
MAP_LANG_TLD,
SUPPORT_LANGUAGES,
SUPPORT_TLD,
)
_LOGGER = logging.getLogger(__name__)
SUPPORT_OPTIONS = ["tld"]
PLATFORM_SCHEMA = TTS_PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES),
vol.Optional(CONF_TLD, default=DEFAULT_TLD): vol.In(SUPPORT_TLD),
}
)
async def async_get_engine(
hass: HomeAssistant,
config: ConfigType,
discovery_info: DiscoveryInfoType | None = None,
) -> GoogleProvider:
"""Set up Google speech component."""
return GoogleProvider(hass, config[CONF_LANG], config[CONF_TLD])
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Google Translate speech platform via config entry."""
default_language = config_entry.data[CONF_LANG]
default_tld = config_entry.data[CONF_TLD]
async_add_entities([GoogleTTSEntity(config_entry, default_language, default_tld)])
class GoogleTTSEntity(TextToSpeechEntity):
"""The Google speech API entity."""
def __init__(self, config_entry: ConfigEntry, lang: str, tld: str) -> None:
"""Init Google TTS service."""
if lang in MAP_LANG_TLD:
self._lang = MAP_LANG_TLD[lang].lang
self._tld = MAP_LANG_TLD[lang].tld
else:
self._lang = lang
self._tld = tld
self._attr_name = f"Google Translate {self._lang} {self._tld}"
self._attr_unique_id = config_entry.entry_id
@property
def default_language(self) -> str:
"""Return the default language."""
return self._lang
@property
def supported_languages(self) -> list[str]:
"""Return list of supported languages."""
return SUPPORT_LANGUAGES
@property
def supported_options(self) -> list[str]:
"""Return a list of supported options."""
return SUPPORT_OPTIONS
def get_tts_audio(
self, message: str, language: str, options: dict[str, Any] | None = None
) -> TtsAudioType:
"""Load TTS from google."""
tld = self._tld
if language in MAP_LANG_TLD:
tld_language = MAP_LANG_TLD[language]
tld = tld_language.tld
language = tld_language.lang
if options is not None and "tld" in options:
tld = options["tld"]
tts = gTTS(text=message, lang=language, tld=tld)
mp3_data = BytesIO()
try:
tts.write_to_fp(mp3_data)
except gTTSError as exc:
_LOGGER.debug(
"Error during processing of TTS request %s", exc, exc_info=True
)
raise HomeAssistantError(exc) from exc
return "mp3", mp3_data.getvalue()
class GoogleProvider(Provider):
"""The Google speech API provider."""
def __init__(self, hass: HomeAssistant, lang: str, tld: str) -> None:
"""Init Google TTS service."""
self.hass = hass
if lang in MAP_LANG_TLD:
self._lang = MAP_LANG_TLD[lang].lang
self._tld = MAP_LANG_TLD[lang].tld
else:
self._lang = lang
self._tld = tld
self.name = "Google Translate"
@property
def default_language(self) -> str:
"""Return the default language."""
return self._lang
@property
def supported_languages(self) -> list[str]:
"""Return list of supported languages."""
return SUPPORT_LANGUAGES
@property
def supported_options(self) -> list[str]:
"""Return a list of supported options."""
return SUPPORT_OPTIONS
def get_tts_audio(
self, message: str, language: str, options: dict[str, Any]
) -> TtsAudioType:
"""Load TTS from google."""
tld = self._tld
if language in MAP_LANG_TLD:
tld = MAP_LANG_TLD[language].tld
language = MAP_LANG_TLD[language].lang
if "tld" in options:
tld = options["tld"]
tts = gTTS(text=message, lang=language, tld=tld)
mp3_data = BytesIO()
try:
tts.write_to_fp(mp3_data)
except gTTSError:
_LOGGER.exception("Error during processing of TTS request")
return None, None
return "mp3", mp3_data.getvalue()