Home Assistant Unofficial Reference 2024.12.1
tts.py
Go to the documentation of this file.
1 """Support for the Pico TTS speech service."""
2 
3 import logging
4 import os
5 import shutil
6 import subprocess
7 import tempfile
8 
9 import voluptuous as vol
10 
11 from homeassistant.components.tts import (
12  CONF_LANG,
13  PLATFORM_SCHEMA as TTS_PLATFORM_SCHEMA,
14  Provider,
15 )
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 SUPPORT_LANGUAGES = ["en-US", "en-GB", "de-DE", "es-ES", "fr-FR", "it-IT"]
20 
21 DEFAULT_LANG = "en-US"
22 
23 PLATFORM_SCHEMA = TTS_PLATFORM_SCHEMA.extend(
24  {vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)}
25 )
26 
27 
28 def get_engine(hass, config, discovery_info=None):
29  """Set up Pico speech component."""
30  if shutil.which("pico2wave") is None:
31  _LOGGER.error("'pico2wave' was not found")
32  return False
33  return PicoProvider(config[CONF_LANG])
34 
35 
36 class PicoProvider(Provider):
37  """The Pico TTS API provider."""
38 
39  def __init__(self, lang):
40  """Initialize Pico TTS provider."""
41  self._lang_lang = lang
42  self.namename = "PicoTTS"
43 
44  @property
45  def default_language(self):
46  """Return the default language."""
47  return self._lang_lang
48 
49  @property
51  """Return list of supported languages."""
52  return SUPPORT_LANGUAGES
53 
54  def get_tts_audio(self, message, language, options):
55  """Load TTS using pico2wave."""
56  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpf:
57  fname = tmpf.name
58 
59  cmd = ["pico2wave", "--wave", fname, "-l", language, "--", message]
60  subprocess.call(cmd)
61  data = None
62  try:
63  with open(fname, "rb") as voice:
64  data = voice.read()
65  except OSError:
66  _LOGGER.error("Error trying to read %s", fname)
67  return (None, None)
68  finally:
69  os.remove(fname)
70 
71  if data:
72  return ("wav", data)
73  return (None, None)
def get_tts_audio(self, message, language, options)
Definition: tts.py:54
None open(self, **Any kwargs)
Definition: lock.py:86
def get_engine(hass, config, discovery_info=None)
Definition: tts.py:28