core/homeassistant/components/google_translate/tts.py

139 lines
2.3 KiB
Python
Raw Normal View History

"""Support for the Google speech service."""
from io import BytesIO
import logging
from gtts import gTTS, gTTSError
import voluptuous as vol
from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
_LOGGER = logging.getLogger(__name__)
SUPPORT_LANGUAGES = [
2019-07-31 19:25:30 +00:00
"af",
"ar",
"bg",
2019-07-31 19:25:30 +00:00
"bn",
"bs",
2019-07-31 19:25:30 +00:00
"ca",
"cs",
"cy",
2019-07-31 19:25:30 +00:00
"da",
"de",
"el",
2019-07-31 19:25:30 +00:00
"en",
"eo",
"es",
"et",
2019-07-31 19:25:30 +00:00
"fi",
"fr",
"gu",
2019-07-31 19:25:30 +00:00
"hi",
"hr",
2019-07-31 19:25:30 +00:00
"hu",
"hy",
2019-07-31 19:25:30 +00:00
"id",
"is",
2019-07-31 19:25:30 +00:00
"it",
"ja",
"jw",
"km",
"kn",
2019-07-31 19:25:30 +00:00
"ko",
"la",
"lv",
"mk",
"ml",
"mr",
"my",
"ne",
"nl",
2019-07-31 19:25:30 +00:00
"no",
"pl",
"pt",
"ro",
"ru",
"si",
2019-07-31 19:25:30 +00:00
"sk",
"sq",
"sr",
"su",
2019-07-31 19:25:30 +00:00
"sv",
"sw",
2019-07-31 19:25:30 +00:00
"ta",
"te",
2019-07-31 19:25:30 +00:00
"th",
"tl",
2019-07-31 19:25:30 +00:00
"tr",
"uk",
"ur",
"vi",
# dialects
"zh-CN",
"zh-cn",
"zh-tw",
"en-us",
"en-ca",
"en-uk",
"en-gb",
"en-au",
"en-gh",
"en-in",
"en-ie",
"en-nz",
"en-ng",
"en-ph",
"en-za",
"en-tz",
"fr-ca",
"fr-fr",
"pt-br",
"pt-pt",
"es-es",
"es-us",
]
2019-07-31 19:25:30 +00:00
DEFAULT_LANG = "en"
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)}
)
async def async_get_engine(hass, config, discovery_info=None):
2017-01-15 13:53:07 +00:00
"""Set up Google speech component."""
return GoogleProvider(hass, config[CONF_LANG])
class GoogleProvider(Provider):
2017-01-15 13:53:07 +00:00
"""The Google speech API provider."""
def __init__(self, hass, lang):
"""Init Google TTS service."""
self.hass = hass
self._lang = lang
2019-07-31 19:25:30 +00:00
self.name = "Google"
@property
def default_language(self):
"""Return the default language."""
return self._lang
@property
def supported_languages(self):
"""Return list of supported languages."""
return SUPPORT_LANGUAGES
def get_tts_audio(self, message, language, options=None):
"""Load TTS from google."""
tts = gTTS(text=message, lang=language)
mp3_data = BytesIO()
try:
tts.write_to_fp(mp3_data)
except gTTSError as exc:
_LOGGER.exception("Error during processing of TTS request %s", exc)
return None, None
return "mp3", mp3_data.getvalue()