Debian Codegraph @

scripts/update_voice_data.py

raw
1 #!/usr/bin/python3
2 """Update the voice data."""
3
4 # ruff: noqa: T201
5
6 import asyncio
7 from pathlib import Path
8 import subprocess
9
10 import aiohttp
11
12 voice_data_path = Path(__file__).parent.parent / "hass_nabucasa/voice_data.py"
13
14 REGION = "westus"
15 LIST_VOICES_URL = (
16 f"https://{REGION}.tts.speech.microsoft.com/cognitiveservices/voices/list"
17 )
18
19
20 def main() -> None:
21 """Run script."""
22 token = None
23
24 while not token:
25 token = input("Please enter your Azure token: ").strip()
26
27 raw_data = asyncio.run(get_data(token))
28
29 data = {}
30 for voice in raw_data:
31 if voice["Status"] != "GA":
32 continue
33 locale = voice["Locale"]
34 voice_id = voice["ShortName"][len(locale) + 1 :]
35 voice_name = voice["DisplayName"]
36 if voice_name.endswith("Neural"):
37 voice_name = voice_name[:-7].strip()
38
39 # Skip variants
40 if ":" in voice_id or "Multilingual" in voice_id:
41 continue
42
43 voice_info = {
44 "name": voice_name,
45 }
46 if style_list := voice.get("StyleList"):
47 voice_info = {
48 "name": voice_name,
49 "variants": style_list,
50 }
51 else:
52 voice_info = voice_name
53
54 data.setdefault(locale, {})[voice_id] = voice_info
55
56 # Sort the data
57 for locale, info in data.items():
58 data[locale] = dict(
59 sorted(
60 info.items(),
61 key=lambda x: x[1]["name"] if isinstance(x[1], dict) else x[1],
62 )
63 )
64 data = dict(sorted(data.items()))
65
66 parts = [
67 '"""',
68 "Available voices for TTS.",
69 "",
70 "Automatically generated file, do not edit this file directly.",
71 "Run python3 -m scripts/update_voice_data.py to update this file.",
72 '"""',
73 "",
74 f"TTS_VOICES: dict[str, dict[str, dict | str]] = {data}",
75 ]
76 voice_data_path.write_text("\n".join(parts))
77 subprocess.run( # noqa: S603
78 ["ruff", "format", voice_data_path], # noqa: S607
79 check=True,
80 stdout=subprocess.DEVNULL,
81 )
82 print("Updated voice_data.py with new voice data.")
83
84
85 async def get_data(token: str) -> dict:
86 """Gather data."""
87 async with aiohttp.ClientSession() as session:
88 voices = await session.get(
89 LIST_VOICES_URL, headers={"Authorization": f"Bearer {token}"}
90 )
91 voices.raise_for_status()
92 return await voices.json()
93
94
95 if __name__ == "__main__":
96 main()