audio.py 24 KB

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