Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for ElevenLabs text-to-speech integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from elevenlabs.client import AsyncElevenLabs
9 from elevenlabs.core import ApiError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import (
13  ConfigEntry,
14  ConfigFlow,
15  ConfigFlowResult,
16  OptionsFlow,
17 )
18 from homeassistant.const import CONF_API_KEY
19 from homeassistant.core import HomeAssistant
20 from homeassistant.helpers.httpx_client import get_async_client
22  SelectOptionDict,
23  SelectSelector,
24  SelectSelectorConfig,
25 )
26 
27 from .const import (
28  CONF_CONFIGURE_VOICE,
29  CONF_MODEL,
30  CONF_OPTIMIZE_LATENCY,
31  CONF_SIMILARITY,
32  CONF_STABILITY,
33  CONF_STYLE,
34  CONF_USE_SPEAKER_BOOST,
35  CONF_VOICE,
36  DEFAULT_MODEL,
37  DEFAULT_OPTIMIZE_LATENCY,
38  DEFAULT_SIMILARITY,
39  DEFAULT_STABILITY,
40  DEFAULT_STYLE,
41  DEFAULT_USE_SPEAKER_BOOST,
42  DOMAIN,
43 )
44 
45 USER_STEP_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): str})
46 
47 
48 _LOGGER = logging.getLogger(__name__)
49 
50 
52  hass: HomeAssistant, api_key: str
53 ) -> tuple[dict[str, str], dict[str, str]]:
54  """Get available voices and models as dicts."""
55  httpx_client = get_async_client(hass)
56  client = AsyncElevenLabs(api_key=api_key, httpx_client=httpx_client)
57  voices = (await client.voices.get_all()).voices
58  models = await client.models.get_all()
59  voices_dict = {
60  voice.voice_id: voice.name
61  for voice in sorted(voices, key=lambda v: v.name or "")
62  if voice.name
63  }
64  models_dict = {
65  model.model_id: model.name
66  for model in sorted(models, key=lambda m: m.name or "")
67  if model.name and model.can_do_text_to_speech
68  }
69  return voices_dict, models_dict
70 
71 
72 class ElevenLabsConfigFlow(ConfigFlow, domain=DOMAIN):
73  """Handle a config flow for ElevenLabs text-to-speech."""
74 
75  VERSION = 1
76 
77  async def async_step_user(
78  self, user_input: dict[str, Any] | None = None
79  ) -> ConfigFlowResult:
80  """Handle the initial step."""
81  errors: dict[str, str] = {}
82  if user_input is not None:
83  try:
84  voices, _ = await get_voices_models(self.hass, user_input[CONF_API_KEY])
85  except ApiError:
86  errors["base"] = "invalid_api_key"
87  else:
88  return self.async_create_entryasync_create_entryasync_create_entry(
89  title="ElevenLabs",
90  data=user_input,
91  options={CONF_MODEL: DEFAULT_MODEL, CONF_VOICE: list(voices)[0]},
92  )
93  return self.async_show_formasync_show_formasync_show_form(
94  step_id="user", data_schema=USER_STEP_SCHEMA, errors=errors
95  )
96 
97  @staticmethod
99  config_entry: ConfigEntry,
100  ) -> OptionsFlow:
101  """Create the options flow."""
102  return ElevenLabsOptionsFlow(config_entry)
103 
104 
106  """ElevenLabs options flow."""
107 
108  def __init__(self, config_entry: ConfigEntry) -> None:
109  """Initialize options flow."""
110  self.api_key: str = config_entry.data[CONF_API_KEY]
111  # id -> name
112  self.voices: dict[str, str] = {}
113  self.modelsmodels: dict[str, str] = {}
114  self.modelmodel: str | None = None
115  self.voicevoice: str | None = None
116 
117  async def async_step_init(
118  self, user_input: dict[str, Any] | None = None
119  ) -> ConfigFlowResult:
120  """Manage the options."""
121  if not self.voices or not self.modelsmodels:
122  self.voices, self.modelsmodels = await get_voices_models(self.hass, self.api_key)
123 
124  assert self.modelsmodels and self.voices
125 
126  if user_input is not None:
127  self.modelmodel = user_input[CONF_MODEL]
128  self.voicevoice = user_input[CONF_VOICE]
129  configure_voice = user_input.pop(CONF_CONFIGURE_VOICE)
130  if configure_voice:
131  return await self.async_step_voice_settingsasync_step_voice_settings()
132  return self.async_create_entryasync_create_entry(
133  title="ElevenLabs",
134  data=user_input,
135  )
136 
137  schema = self.elevenlabs_config_option_schemaelevenlabs_config_option_schema()
138  return self.async_show_formasync_show_form(
139  step_id="init",
140  data_schema=schema,
141  )
142 
143  def elevenlabs_config_option_schema(self) -> vol.Schema:
144  """Elevenlabs options schema."""
145  return self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
146  vol.Schema(
147  {
148  vol.Required(
149  CONF_MODEL,
150  ): SelectSelector(
152  options=[
153  SelectOptionDict(label=model_name, value=model_id)
154  for model_id, model_name in self.modelsmodels.items()
155  ]
156  )
157  ),
158  vol.Required(
159  CONF_VOICE,
160  ): SelectSelector(
162  options=[
163  SelectOptionDict(label=voice_name, value=voice_id)
164  for voice_id, voice_name in self.voices.items()
165  ]
166  )
167  ),
168  vol.Required(CONF_CONFIGURE_VOICE, default=False): bool,
169  }
170  ),
171  self.config_entryconfig_entryconfig_entry.options,
172  )
173 
175  self, user_input: dict[str, Any] | None = None
176  ) -> ConfigFlowResult:
177  """Handle voice settings."""
178  assert self.voices and self.modelsmodels
179  if user_input is not None:
180  user_input[CONF_MODEL] = self.modelmodel
181  user_input[CONF_VOICE] = self.voicevoice
182  return self.async_create_entryasync_create_entry(
183  title="ElevenLabs",
184  data=user_input,
185  )
186  return self.async_show_formasync_show_form(
187  step_id="voice_settings",
188  data_schema=self.elevenlabs_config_options_voice_schemaelevenlabs_config_options_voice_schema(),
189  )
190 
191  def elevenlabs_config_options_voice_schema(self) -> vol.Schema:
192  """Elevenlabs options voice schema."""
193  return vol.Schema(
194  {
195  vol.Optional(
196  CONF_STABILITY,
197  default=self.config_entryconfig_entryconfig_entry.options.get(
198  CONF_STABILITY, DEFAULT_STABILITY
199  ),
200  ): vol.All(
201  vol.Coerce(float),
202  vol.Range(min=0, max=1),
203  ),
204  vol.Optional(
205  CONF_SIMILARITY,
206  default=self.config_entryconfig_entryconfig_entry.options.get(
207  CONF_SIMILARITY, DEFAULT_SIMILARITY
208  ),
209  ): vol.All(
210  vol.Coerce(float),
211  vol.Range(min=0, max=1),
212  ),
213  vol.Optional(
214  CONF_OPTIMIZE_LATENCY,
215  default=self.config_entryconfig_entryconfig_entry.options.get(
216  CONF_OPTIMIZE_LATENCY, DEFAULT_OPTIMIZE_LATENCY
217  ),
218  ): vol.All(int, vol.Range(min=0, max=4)),
219  vol.Optional(
220  CONF_STYLE,
221  default=self.config_entryconfig_entryconfig_entry.options.get(CONF_STYLE, DEFAULT_STYLE),
222  ): vol.All(
223  vol.Coerce(float),
224  vol.Range(min=0, max=1),
225  ),
226  vol.Optional(
227  CONF_USE_SPEAKER_BOOST,
228  default=self.config_entryconfig_entryconfig_entry.options.get(
229  CONF_USE_SPEAKER_BOOST, DEFAULT_USE_SPEAKER_BOOST
230  ),
231  ): bool,
232  }
233  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:79
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:119
ConfigFlowResult async_step_voice_settings(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:176
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
None config_entry(self, ConfigEntry value)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
tuple[dict[str, str], dict[str, str]] get_voices_models(HomeAssistant hass, str api_key)
Definition: config_flow.py:53
httpx.AsyncClient get_async_client(HomeAssistant hass, bool verify_ssl=True)
Definition: httpx_client.py:41