Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """The ElevenLabs text-to-speech integration."""
2 
3 from __future__ import annotations
4 
5 from dataclasses import dataclass
6 
7 from elevenlabs import Model
8 from elevenlabs.client import AsyncElevenLabs
9 from elevenlabs.core import ApiError
10 
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import CONF_API_KEY, Platform
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import ConfigEntryError
15 from homeassistant.helpers.httpx_client import get_async_client
16 
17 from .const import CONF_MODEL
18 
19 PLATFORMS: list[Platform] = [Platform.TTS]
20 
21 
22 async def get_model_by_id(client: AsyncElevenLabs, model_id: str) -> Model | None:
23  """Get ElevenLabs model from their API by the model_id."""
24  models = await client.models.get_all()
25  for maybe_model in models:
26  if maybe_model.model_id == model_id:
27  return maybe_model
28  return None
29 
30 
31 @dataclass(kw_only=True, slots=True)
33  """ElevenLabs data type."""
34 
35  client: AsyncElevenLabs
36  model: Model
37 
38 
39 type EleventLabsConfigEntry = ConfigEntry[ElevenLabsData]
40 
41 
42 async def async_setup_entry(hass: HomeAssistant, entry: EleventLabsConfigEntry) -> bool:
43  """Set up ElevenLabs text-to-speech from a config entry."""
44  entry.add_update_listener(update_listener)
45  httpx_client = get_async_client(hass)
46  client = AsyncElevenLabs(
47  api_key=entry.data[CONF_API_KEY], httpx_client=httpx_client
48  )
49  model_id = entry.options[CONF_MODEL]
50  try:
51  model = await get_model_by_id(client, model_id)
52  except ApiError as err:
53  raise ConfigEntryError("Auth failed") from err
54 
55  if model is None or (not model.languages):
56  raise ConfigEntryError("Model could not be resolved")
57 
58  entry.runtime_data = ElevenLabsData(client=client, model=model)
59  await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
60 
61  return True
62 
63 
65  hass: HomeAssistant, entry: EleventLabsConfigEntry
66 ) -> bool:
67  """Unload a config entry."""
68  return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
69 
70 
71 async def update_listener(
72  hass: HomeAssistant, config_entry: EleventLabsConfigEntry
73 ) -> None:
74  """Handle options update."""
75  await hass.config_entries.async_reload(config_entry.entry_id)
None update_listener(HomeAssistant hass, EleventLabsConfigEntry config_entry)
Definition: __init__.py:73
Model|None get_model_by_id(AsyncElevenLabs client, str model_id)
Definition: __init__.py:22
bool async_setup_entry(HomeAssistant hass, EleventLabsConfigEntry entry)
Definition: __init__.py:42
bool async_unload_entry(HomeAssistant hass, EleventLabsConfigEntry entry)
Definition: __init__.py:66
httpx.AsyncClient get_async_client(HomeAssistant hass, bool verify_ssl=True)
Definition: httpx_client.py:41