main.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import hashlib
  2. import json
  3. import logging
  4. import os
  5. import uuid
  6. from functools import lru_cache
  7. from pathlib import Path
  8. from pydub import AudioSegment
  9. from pydub.silence import split_on_silence
  10. import requests
  11. from open_webui.config import (
  12. AUDIO_STT_ENGINE,
  13. AUDIO_STT_MODEL,
  14. AUDIO_STT_OPENAI_API_BASE_URL,
  15. AUDIO_STT_OPENAI_API_KEY,
  16. AUDIO_TTS_API_KEY,
  17. AUDIO_TTS_ENGINE,
  18. AUDIO_TTS_MODEL,
  19. AUDIO_TTS_OPENAI_API_BASE_URL,
  20. AUDIO_TTS_OPENAI_API_KEY,
  21. AUDIO_TTS_SPLIT_ON,
  22. AUDIO_TTS_VOICE,
  23. AUDIO_TTS_AZURE_SPEECH_REGION,
  24. AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  25. CACHE_DIR,
  26. CORS_ALLOW_ORIGIN,
  27. WHISPER_MODEL,
  28. WHISPER_MODEL_AUTO_UPDATE,
  29. WHISPER_MODEL_DIR,
  30. AppConfig,
  31. )
  32. from open_webui.constants import ERROR_MESSAGES
  33. from open_webui.env import SRC_LOG_LEVELS, DEVICE_TYPE
  34. from fastapi import Depends, FastAPI, File, HTTPException, Request, UploadFile, status
  35. from fastapi.middleware.cors import CORSMiddleware
  36. from fastapi.responses import FileResponse
  37. from pydantic import BaseModel
  38. from open_webui.utils.utils import get_admin_user, get_verified_user
  39. # Constants
  40. MAX_FILE_SIZE_MB = 25
  41. MAX_FILE_SIZE = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
  42. log = logging.getLogger(__name__)
  43. log.setLevel(SRC_LOG_LEVELS["AUDIO"])
  44. app = FastAPI()
  45. app.add_middleware(
  46. CORSMiddleware,
  47. allow_origins=CORS_ALLOW_ORIGIN,
  48. allow_credentials=True,
  49. allow_methods=["*"],
  50. allow_headers=["*"],
  51. )
  52. app.state.config = AppConfig()
  53. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  54. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  55. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  56. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  57. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  58. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  59. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  60. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  61. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  62. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  63. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  64. app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
  65. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
  66. # setting device type for whisper model
  67. whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
  68. log.info(f"whisper_device_type: {whisper_device_type}")
  69. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  70. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  71. class TTSConfigForm(BaseModel):
  72. OPENAI_API_BASE_URL: str
  73. OPENAI_API_KEY: str
  74. API_KEY: str
  75. ENGINE: str
  76. MODEL: str
  77. VOICE: str
  78. SPLIT_ON: str
  79. AZURE_SPEECH_REGION: str
  80. AZURE_SPEECH_OUTPUT_FORMAT: str
  81. class STTConfigForm(BaseModel):
  82. OPENAI_API_BASE_URL: str
  83. OPENAI_API_KEY: str
  84. ENGINE: str
  85. MODEL: str
  86. class AudioConfigUpdateForm(BaseModel):
  87. tts: TTSConfigForm
  88. stt: STTConfigForm
  89. from pydub import AudioSegment
  90. from pydub.utils import mediainfo
  91. def is_mp4_audio(file_path):
  92. """Check if the given file is an MP4 audio file."""
  93. if not os.path.isfile(file_path):
  94. print(f"File not found: {file_path}")
  95. return False
  96. info = mediainfo(file_path)
  97. if (
  98. info.get("codec_name") == "aac"
  99. and info.get("codec_type") == "audio"
  100. and info.get("codec_tag_string") == "mp4a"
  101. ):
  102. return True
  103. return False
  104. def convert_mp4_to_wav(file_path, output_path):
  105. """Convert MP4 audio file to WAV format."""
  106. audio = AudioSegment.from_file(file_path, format="mp4")
  107. audio.export(output_path, format="wav")
  108. print(f"Converted {file_path} to {output_path}")
  109. @app.get("/config")
  110. async def get_audio_config(user=Depends(get_admin_user)):
  111. return {
  112. "tts": {
  113. "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
  114. "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
  115. "API_KEY": app.state.config.TTS_API_KEY,
  116. "ENGINE": app.state.config.TTS_ENGINE,
  117. "MODEL": app.state.config.TTS_MODEL,
  118. "VOICE": app.state.config.TTS_VOICE,
  119. "SPLIT_ON": app.state.config.TTS_SPLIT_ON,
  120. "AZURE_SPEECH_REGION": app.state.config.TTS_AZURE_SPEECH_REGION,
  121. "AZURE_SPEECH_OUTPUT_FORMAT": app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  122. },
  123. "stt": {
  124. "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
  125. "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
  126. "ENGINE": app.state.config.STT_ENGINE,
  127. "MODEL": app.state.config.STT_MODEL,
  128. },
  129. }
  130. @app.post("/config/update")
  131. async def update_audio_config(
  132. form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)
  133. ):
  134. app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL
  135. app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY
  136. app.state.config.TTS_API_KEY = form_data.tts.API_KEY
  137. app.state.config.TTS_ENGINE = form_data.tts.ENGINE
  138. app.state.config.TTS_MODEL = form_data.tts.MODEL
  139. app.state.config.TTS_VOICE = form_data.tts.VOICE
  140. app.state.config.TTS_SPLIT_ON = form_data.tts.SPLIT_ON
  141. app.state.config.TTS_AZURE_SPEECH_REGION = form_data.tts.AZURE_SPEECH_REGION
  142. app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = (
  143. form_data.tts.AZURE_SPEECH_OUTPUT_FORMAT
  144. )
  145. app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
  146. app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
  147. app.state.config.STT_ENGINE = form_data.stt.ENGINE
  148. app.state.config.STT_MODEL = form_data.stt.MODEL
  149. return {
  150. "tts": {
  151. "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
  152. "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
  153. "API_KEY": app.state.config.TTS_API_KEY,
  154. "ENGINE": app.state.config.TTS_ENGINE,
  155. "MODEL": app.state.config.TTS_MODEL,
  156. "VOICE": app.state.config.TTS_VOICE,
  157. "SPLIT_ON": app.state.config.TTS_SPLIT_ON,
  158. "AZURE_SPEECH_REGION": app.state.config.TTS_AZURE_SPEECH_REGION,
  159. "AZURE_SPEECH_OUTPUT_FORMAT": app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  160. },
  161. "stt": {
  162. "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
  163. "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
  164. "ENGINE": app.state.config.STT_ENGINE,
  165. "MODEL": app.state.config.STT_MODEL,
  166. },
  167. }
  168. @app.post("/speech")
  169. async def speech(request: Request, user=Depends(get_verified_user)):
  170. body = await request.body()
  171. name = hashlib.sha256(body).hexdigest()
  172. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  173. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  174. # Check if the file already exists in the cache
  175. if file_path.is_file():
  176. return FileResponse(file_path)
  177. if app.state.config.TTS_ENGINE == "openai":
  178. headers = {}
  179. headers["Authorization"] = f"Bearer {app.state.config.TTS_OPENAI_API_KEY}"
  180. headers["Content-Type"] = "application/json"
  181. try:
  182. body = body.decode("utf-8")
  183. body = json.loads(body)
  184. body["model"] = app.state.config.TTS_MODEL
  185. body = json.dumps(body).encode("utf-8")
  186. except Exception:
  187. pass
  188. r = None
  189. try:
  190. r = requests.post(
  191. url=f"{app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  192. data=body,
  193. headers=headers,
  194. stream=True,
  195. )
  196. r.raise_for_status()
  197. # Save the streaming content to a file
  198. with open(file_path, "wb") as f:
  199. for chunk in r.iter_content(chunk_size=8192):
  200. f.write(chunk)
  201. with open(file_body_path, "w") as f:
  202. json.dump(json.loads(body.decode("utf-8")), f)
  203. # Return the saved file
  204. return FileResponse(file_path)
  205. except Exception as e:
  206. log.exception(e)
  207. error_detail = "Open WebUI: Server Connection Error"
  208. if r is not None:
  209. try:
  210. res = r.json()
  211. if "error" in res:
  212. error_detail = f"External: {res['error']['message']}"
  213. except Exception:
  214. error_detail = f"External: {e}"
  215. raise HTTPException(
  216. status_code=r.status_code if r != None else 500,
  217. detail=error_detail,
  218. )
  219. elif app.state.config.TTS_ENGINE == "elevenlabs":
  220. payload = None
  221. try:
  222. payload = json.loads(body.decode("utf-8"))
  223. except Exception as e:
  224. log.exception(e)
  225. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  226. voice_id = payload.get("voice", "")
  227. if voice_id not in get_available_voices():
  228. raise HTTPException(
  229. status_code=400,
  230. detail="Invalid voice id",
  231. )
  232. url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
  233. headers = {
  234. "Accept": "audio/mpeg",
  235. "Content-Type": "application/json",
  236. "xi-api-key": app.state.config.TTS_API_KEY,
  237. }
  238. data = {
  239. "text": payload["input"],
  240. "model_id": app.state.config.TTS_MODEL,
  241. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  242. }
  243. try:
  244. r = requests.post(url, json=data, headers=headers)
  245. r.raise_for_status()
  246. # Save the streaming content to a file
  247. with open(file_path, "wb") as f:
  248. for chunk in r.iter_content(chunk_size=8192):
  249. f.write(chunk)
  250. with open(file_body_path, "w") as f:
  251. json.dump(json.loads(body.decode("utf-8")), f)
  252. # Return the saved file
  253. return FileResponse(file_path)
  254. except Exception as e:
  255. log.exception(e)
  256. error_detail = "Open WebUI: Server Connection Error"
  257. if r is not None:
  258. try:
  259. res = r.json()
  260. if "error" in res:
  261. error_detail = f"External: {res['error']['message']}"
  262. except Exception:
  263. error_detail = f"External: {e}"
  264. raise HTTPException(
  265. status_code=r.status_code if r != None else 500,
  266. detail=error_detail,
  267. )
  268. elif app.state.config.TTS_ENGINE == "azure":
  269. payload = None
  270. try:
  271. payload = json.loads(body.decode("utf-8"))
  272. except Exception as e:
  273. log.exception(e)
  274. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  275. region = app.state.config.TTS_AZURE_SPEECH_REGION
  276. language = app.state.config.TTS_VOICE
  277. locale = "-".join(app.state.config.TTS_VOICE.split("-")[:1])
  278. output_format = app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
  279. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1"
  280. headers = {
  281. "Ocp-Apim-Subscription-Key": app.state.config.TTS_API_KEY,
  282. "Content-Type": "application/ssml+xml",
  283. "X-Microsoft-OutputFormat": output_format,
  284. }
  285. data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
  286. <voice name="{language}">{payload["input"]}</voice>
  287. </speak>"""
  288. response = requests.post(url, headers=headers, data=data)
  289. if response.status_code == 200:
  290. with open(file_path, "wb") as f:
  291. f.write(response.content)
  292. return FileResponse(file_path)
  293. else:
  294. log.error(f"Error synthesizing speech - {response.reason}")
  295. raise HTTPException(
  296. status_code=500, detail=f"Error synthesizing speech - {response.reason}"
  297. )
  298. def transcribe(file_path):
  299. print("transcribe", file_path)
  300. filename = os.path.basename(file_path)
  301. file_dir = os.path.dirname(file_path)
  302. id = filename.split(".")[0]
  303. if app.state.config.STT_ENGINE == "":
  304. from faster_whisper import WhisperModel
  305. whisper_kwargs = {
  306. "model_size_or_path": WHISPER_MODEL,
  307. "device": whisper_device_type,
  308. "compute_type": "int8",
  309. "download_root": WHISPER_MODEL_DIR,
  310. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  311. }
  312. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  313. try:
  314. model = WhisperModel(**whisper_kwargs)
  315. except Exception:
  316. log.warning(
  317. "WhisperModel initialization failed, attempting download with local_files_only=False"
  318. )
  319. whisper_kwargs["local_files_only"] = False
  320. model = WhisperModel(**whisper_kwargs)
  321. segments, info = model.transcribe(file_path, beam_size=5)
  322. log.info(
  323. "Detected language '%s' with probability %f"
  324. % (info.language, info.language_probability)
  325. )
  326. transcript = "".join([segment.text for segment in list(segments)])
  327. data = {"text": transcript.strip()}
  328. # save the transcript to a json file
  329. transcript_file = f"{file_dir}/{id}.json"
  330. with open(transcript_file, "w") as f:
  331. json.dump(data, f)
  332. print(data)
  333. return data
  334. elif app.state.config.STT_ENGINE == "openai":
  335. if is_mp4_audio(file_path):
  336. print("is_mp4_audio")
  337. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  338. # Convert MP4 audio file to WAV format
  339. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  340. headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
  341. files = {"file": (filename, open(file_path, "rb"))}
  342. data = {"model": app.state.config.STT_MODEL}
  343. print(files, data)
  344. r = None
  345. try:
  346. r = requests.post(
  347. url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  348. headers=headers,
  349. files=files,
  350. data=data,
  351. )
  352. r.raise_for_status()
  353. data = r.json()
  354. # save the transcript to a json file
  355. transcript_file = f"{file_dir}/{id}.json"
  356. with open(transcript_file, "w") as f:
  357. json.dump(data, f)
  358. print(data)
  359. return data
  360. except Exception as e:
  361. log.exception(e)
  362. error_detail = "Open WebUI: Server Connection Error"
  363. if r is not None:
  364. try:
  365. res = r.json()
  366. if "error" in res:
  367. error_detail = f"External: {res['error']['message']}"
  368. except Exception:
  369. error_detail = f"External: {e}"
  370. raise error_detail
  371. @app.post("/transcriptions")
  372. def transcription(
  373. file: UploadFile = File(...),
  374. user=Depends(get_verified_user),
  375. ):
  376. log.info(f"file.content_type: {file.content_type}")
  377. if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a"]:
  378. raise HTTPException(
  379. status_code=status.HTTP_400_BAD_REQUEST,
  380. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  381. )
  382. try:
  383. ext = file.filename.split(".")[-1]
  384. id = uuid.uuid4()
  385. filename = f"{id}.{ext}"
  386. contents = file.file.read()
  387. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  388. os.makedirs(file_dir, exist_ok=True)
  389. file_path = f"{file_dir}/{filename}"
  390. with open(file_path, "wb") as f:
  391. f.write(contents)
  392. try:
  393. if os.path.getsize(file_path) > MAX_FILE_SIZE: # file is bigger than 25MB
  394. log.debug(f"File size is larger than {MAX_FILE_SIZE_MB}MB")
  395. audio = AudioSegment.from_file(file_path)
  396. audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
  397. compressed_path = f"{file_dir}/{id}_compressed.opus"
  398. audio.export(compressed_path, format="opus", bitrate="32k")
  399. log.debug(f"Compressed audio to {compressed_path}")
  400. file_path = compressed_path
  401. if (
  402. os.path.getsize(file_path) > MAX_FILE_SIZE
  403. ): # Still larger than 25MB after compression
  404. chunks = split_on_silence(
  405. audio, min_silence_len=500, silence_thresh=-40
  406. )
  407. texts = []
  408. for i, chunk in enumerate(chunks):
  409. chunk_file_path = f"{file_dir}/{id}_chunk{i}.{ext}"
  410. chunk.export(chunk_file_path, format=ext)
  411. text = transcribe(chunk_file_path)
  412. texts.append(text)
  413. data = {"text": " ".join(texts)}
  414. else:
  415. data = transcribe(file_path)
  416. else:
  417. data = transcribe(file_path)
  418. return data
  419. except Exception as e:
  420. log.exception(e)
  421. raise HTTPException(
  422. status_code=status.HTTP_400_BAD_REQUEST,
  423. detail=ERROR_MESSAGES.DEFAULT(e),
  424. )
  425. except Exception as e:
  426. log.exception(e)
  427. raise HTTPException(
  428. status_code=status.HTTP_400_BAD_REQUEST,
  429. detail=ERROR_MESSAGES.DEFAULT(e),
  430. )
  431. def get_available_models() -> list[dict]:
  432. if app.state.config.TTS_ENGINE == "openai":
  433. return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  434. elif app.state.config.TTS_ENGINE == "elevenlabs":
  435. headers = {
  436. "xi-api-key": app.state.config.TTS_API_KEY,
  437. "Content-Type": "application/json",
  438. }
  439. try:
  440. response = requests.get(
  441. "https://api.elevenlabs.io/v1/models", headers=headers, timeout=5
  442. )
  443. response.raise_for_status()
  444. models = response.json()
  445. return [
  446. {"name": model["name"], "id": model["model_id"]} for model in models
  447. ]
  448. except requests.RequestException as e:
  449. log.error(f"Error fetching voices: {str(e)}")
  450. return []
  451. @app.get("/models")
  452. async def get_models(user=Depends(get_verified_user)):
  453. return {"models": get_available_models()}
  454. def get_available_voices() -> dict:
  455. """Returns {voice_id: voice_name} dict"""
  456. ret = {}
  457. if app.state.config.TTS_ENGINE == "openai":
  458. ret = {
  459. "alloy": "alloy",
  460. "echo": "echo",
  461. "fable": "fable",
  462. "onyx": "onyx",
  463. "nova": "nova",
  464. "shimmer": "shimmer",
  465. }
  466. elif app.state.config.TTS_ENGINE == "elevenlabs":
  467. try:
  468. ret = get_elevenlabs_voices()
  469. except Exception:
  470. # Avoided @lru_cache with exception
  471. pass
  472. elif app.state.config.TTS_ENGINE == "azure":
  473. try:
  474. region = app.state.config.TTS_AZURE_SPEECH_REGION
  475. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  476. headers = {"Ocp-Apim-Subscription-Key": app.state.config.TTS_API_KEY}
  477. response = requests.get(url, headers=headers)
  478. response.raise_for_status()
  479. voices = response.json()
  480. for voice in voices:
  481. ret[voice["ShortName"]] = (
  482. f"{voice['DisplayName']} ({voice['ShortName']})"
  483. )
  484. except requests.RequestException as e:
  485. log.error(f"Error fetching voices: {str(e)}")
  486. return ret
  487. @lru_cache
  488. def get_elevenlabs_voices() -> dict:
  489. """
  490. Note, set the following in your .env file to use Elevenlabs:
  491. AUDIO_TTS_ENGINE=elevenlabs
  492. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  493. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  494. AUDIO_TTS_MODEL=eleven_multilingual_v2
  495. """
  496. headers = {
  497. "xi-api-key": app.state.config.TTS_API_KEY,
  498. "Content-Type": "application/json",
  499. }
  500. try:
  501. # TODO: Add retries
  502. response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
  503. response.raise_for_status()
  504. voices_data = response.json()
  505. voices = {}
  506. for voice in voices_data.get("voices", []):
  507. voices[voice["voice_id"]] = voice["name"]
  508. except requests.RequestException as e:
  509. # Avoid @lru_cache with exception
  510. log.error(f"Error fetching voices: {str(e)}")
  511. raise RuntimeError(f"Error fetching voices: {str(e)}")
  512. return voices
  513. @app.get("/voices")
  514. async def get_voices(user=Depends(get_verified_user)):
  515. return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}