audio.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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():
  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(body).hexdigest()
  197. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  198. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  199. # Check if the file already exists in the cache
  200. if file_path.is_file():
  201. return FileResponse(file_path)
  202. payload = None
  203. try:
  204. payload = json.loads(body.decode("utf-8"))
  205. except Exception as e:
  206. log.exception(e)
  207. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  208. if request.app.state.config.TTS_ENGINE == "openai":
  209. payload["model"] = request.app.state.config.TTS_MODEL
  210. try:
  211. async with aiohttp.ClientSession() as session:
  212. async with session.post(
  213. url=f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  214. data=payload,
  215. headers={
  216. "Content-Type": "application/json",
  217. "Authorization": f"Bearer {request.app.state.config.TTS_OPENAI_API_KEY}",
  218. **(
  219. {
  220. "X-OpenWebUI-User-Name": user.name,
  221. "X-OpenWebUI-User-Id": user.id,
  222. "X-OpenWebUI-User-Email": user.email,
  223. "X-OpenWebUI-User-Role": user.role,
  224. }
  225. if ENABLE_FORWARD_USER_INFO_HEADERS
  226. else {}
  227. ),
  228. },
  229. ) as r:
  230. r.raise_for_status()
  231. async with aiofiles.open(file_path, "wb") as f:
  232. await f.write(await r.read())
  233. async with aiofiles.open(file_body_path, "w") as f:
  234. await f.write(json.dumps(json.loads(body.decode("utf-8"))))
  235. return FileResponse(file_path)
  236. except Exception as e:
  237. log.exception(e)
  238. detail = None
  239. try:
  240. if r.status != 200:
  241. res = await r.json()
  242. if "error" in res:
  243. detail = f"External: {res['error'].get('message', '')}"
  244. except Exception:
  245. detail = f"External: {e}"
  246. raise HTTPException(
  247. status_code=getattr(r, "status", 500),
  248. detail=detail if detail else "Open WebUI: Server Connection Error",
  249. )
  250. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  251. voice_id = payload.get("voice", "")
  252. if voice_id not in get_available_voices():
  253. raise HTTPException(
  254. status_code=400,
  255. detail="Invalid voice id",
  256. )
  257. try:
  258. async with aiohttp.ClientSession() as session:
  259. async with session.post(
  260. f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
  261. json={
  262. "text": payload["input"],
  263. "model_id": request.app.state.config.TTS_MODEL,
  264. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  265. },
  266. headers={
  267. "Accept": "audio/mpeg",
  268. "Content-Type": "application/json",
  269. "xi-api-key": request.app.state.config.TTS_API_KEY,
  270. },
  271. ) as r:
  272. r.raise_for_status()
  273. async with aiofiles.open(file_path, "wb") as f:
  274. await f.write(await r.read())
  275. async with aiofiles.open(file_body_path, "w") as f:
  276. await f.write(json.dumps(json.loads(body.decode("utf-8"))))
  277. return FileResponse(file_path)
  278. except Exception as e:
  279. log.exception(e)
  280. detail = None
  281. try:
  282. if r.status != 200:
  283. res = await r.json()
  284. if "error" in res:
  285. detail = f"External: {res['error'].get('message', '')}"
  286. except Exception:
  287. detail = f"External: {e}"
  288. raise HTTPException(
  289. status_code=getattr(r, "status", 500),
  290. detail=detail if detail else "Open WebUI: Server Connection Error",
  291. )
  292. elif request.app.state.config.TTS_ENGINE == "azure":
  293. try:
  294. payload = json.loads(body.decode("utf-8"))
  295. except Exception as e:
  296. log.exception(e)
  297. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  298. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  299. language = request.app.state.config.TTS_VOICE
  300. locale = "-".join(request.app.state.config.TTS_VOICE.split("-")[:1])
  301. output_format = request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
  302. try:
  303. data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
  304. <voice name="{language}">{payload["input"]}</voice>
  305. </speak>"""
  306. async with aiohttp.ClientSession() as session:
  307. async with session.post(
  308. f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1",
  309. headers={
  310. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY,
  311. "Content-Type": "application/ssml+xml",
  312. "X-Microsoft-OutputFormat": output_format,
  313. },
  314. data=data,
  315. ) as r:
  316. r.raise_for_status()
  317. async with aiofiles.open(file_path, "wb") as f:
  318. await f.write(await r.read())
  319. return FileResponse(file_path)
  320. except Exception as e:
  321. log.exception(e)
  322. detail = None
  323. try:
  324. if r.status != 200:
  325. res = await r.json()
  326. if "error" in res:
  327. detail = f"External: {res['error'].get('message', '')}"
  328. except Exception:
  329. detail = f"External: {e}"
  330. raise HTTPException(
  331. status_code=getattr(r, "status", 500),
  332. detail=detail if detail else "Open WebUI: Server Connection Error",
  333. )
  334. elif request.app.state.config.TTS_ENGINE == "transformers":
  335. payload = None
  336. try:
  337. payload = json.loads(body.decode("utf-8"))
  338. except Exception as e:
  339. log.exception(e)
  340. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  341. import torch
  342. import soundfile as sf
  343. load_speech_pipeline()
  344. embeddings_dataset = request.app.state.speech_speaker_embeddings_dataset
  345. speaker_index = 6799
  346. try:
  347. speaker_index = embeddings_dataset["filename"].index(
  348. request.app.state.config.TTS_MODEL
  349. )
  350. except Exception:
  351. pass
  352. speaker_embedding = torch.tensor(
  353. embeddings_dataset[speaker_index]["xvector"]
  354. ).unsqueeze(0)
  355. speech = request.app.state.speech_synthesiser(
  356. payload["input"],
  357. forward_params={"speaker_embeddings": speaker_embedding},
  358. )
  359. sf.write(file_path, speech["audio"], samplerate=speech["sampling_rate"])
  360. with open(file_body_path, "w") as f:
  361. json.dump(json.loads(body.decode("utf-8")), f)
  362. return FileResponse(file_path)
  363. def transcribe(request: Request, file_path):
  364. print("transcribe", file_path)
  365. filename = os.path.basename(file_path)
  366. file_dir = os.path.dirname(file_path)
  367. id = filename.split(".")[0]
  368. if request.app.state.config.STT_ENGINE == "":
  369. if request.app.state.faster_whisper_model is None:
  370. request.app.state.faster_whisper_model = set_faster_whisper_model(
  371. request.app.state.config.WHISPER_MODEL
  372. )
  373. model = request.app.state.faster_whisper_model
  374. segments, info = model.transcribe(file_path, beam_size=5)
  375. log.info(
  376. "Detected language '%s' with probability %f"
  377. % (info.language, info.language_probability)
  378. )
  379. transcript = "".join([segment.text for segment in list(segments)])
  380. data = {"text": transcript.strip()}
  381. # save the transcript to a json file
  382. transcript_file = f"{file_dir}/{id}.json"
  383. with open(transcript_file, "w") as f:
  384. json.dump(data, f)
  385. log.debug(data)
  386. return data
  387. elif request.app.state.config.STT_ENGINE == "openai":
  388. if is_mp4_audio(file_path):
  389. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  390. # Convert MP4 audio file to WAV format
  391. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  392. r = None
  393. try:
  394. r = requests.post(
  395. url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  396. headers={
  397. "Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
  398. },
  399. files={"file": (filename, open(file_path, "rb"))},
  400. data={"model": request.app.state.config.STT_MODEL},
  401. )
  402. r.raise_for_status()
  403. data = r.json()
  404. # save the transcript to a json file
  405. transcript_file = f"{file_dir}/{id}.json"
  406. with open(transcript_file, "w") as f:
  407. json.dump(data, f)
  408. return data
  409. except Exception as e:
  410. log.exception(e)
  411. detail = None
  412. if r is not None:
  413. try:
  414. res = r.json()
  415. if "error" in res:
  416. detail = f"External: {res['error'].get('message', '')}"
  417. except Exception:
  418. detail = f"External: {e}"
  419. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  420. def compress_audio(file_path):
  421. if os.path.getsize(file_path) > MAX_FILE_SIZE:
  422. file_dir = os.path.dirname(file_path)
  423. audio = AudioSegment.from_file(file_path)
  424. audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
  425. compressed_path = f"{file_dir}/{id}_compressed.opus"
  426. audio.export(compressed_path, format="opus", bitrate="32k")
  427. log.debug(f"Compressed audio to {compressed_path}")
  428. if (
  429. os.path.getsize(compressed_path) > MAX_FILE_SIZE
  430. ): # Still larger than MAX_FILE_SIZE after compression
  431. raise Exception(ERROR_MESSAGES.FILE_TOO_LARGE(size=f"{MAX_FILE_SIZE_MB}MB"))
  432. return compressed_path
  433. else:
  434. return file_path
  435. @router.post("/transcriptions")
  436. def transcription(
  437. request: Request,
  438. file: UploadFile = File(...),
  439. user=Depends(get_verified_user),
  440. ):
  441. log.info(f"file.content_type: {file.content_type}")
  442. if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a"]:
  443. raise HTTPException(
  444. status_code=status.HTTP_400_BAD_REQUEST,
  445. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  446. )
  447. try:
  448. ext = file.filename.split(".")[-1]
  449. id = uuid.uuid4()
  450. filename = f"{id}.{ext}"
  451. contents = file.file.read()
  452. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  453. os.makedirs(file_dir, exist_ok=True)
  454. file_path = f"{file_dir}/{filename}"
  455. with open(file_path, "wb") as f:
  456. f.write(contents)
  457. try:
  458. try:
  459. file_path = compress_audio(file_path)
  460. except Exception as e:
  461. log.exception(e)
  462. raise HTTPException(
  463. status_code=status.HTTP_400_BAD_REQUEST,
  464. detail=ERROR_MESSAGES.DEFAULT(e),
  465. )
  466. data = transcribe(request, file_path)
  467. file_path = file_path.split("/")[-1]
  468. return {**data, "filename": file_path}
  469. except Exception as e:
  470. log.exception(e)
  471. raise HTTPException(
  472. status_code=status.HTTP_400_BAD_REQUEST,
  473. detail=ERROR_MESSAGES.DEFAULT(e),
  474. )
  475. except Exception as e:
  476. log.exception(e)
  477. raise HTTPException(
  478. status_code=status.HTTP_400_BAD_REQUEST,
  479. detail=ERROR_MESSAGES.DEFAULT(e),
  480. )
  481. def get_available_models(request: Request) -> list[dict]:
  482. available_models = []
  483. if request.app.state.config.TTS_ENGINE == "openai":
  484. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  485. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  486. try:
  487. response = requests.get(
  488. "https://api.elevenlabs.io/v1/models",
  489. headers={
  490. "xi-api-key": request.app.state.config.TTS_API_KEY,
  491. "Content-Type": "application/json",
  492. },
  493. timeout=5,
  494. )
  495. response.raise_for_status()
  496. models = response.json()
  497. available_models = [
  498. {"name": model["name"], "id": model["model_id"]} for model in models
  499. ]
  500. except requests.RequestException as e:
  501. log.error(f"Error fetching voices: {str(e)}")
  502. return available_models
  503. @router.get("/models")
  504. async def get_models(request: Request, user=Depends(get_verified_user)):
  505. return {"models": get_available_models(request)}
  506. def get_available_voices(request) -> dict:
  507. """Returns {voice_id: voice_name} dict"""
  508. available_voices = {}
  509. if request.app.state.config.TTS_ENGINE == "openai":
  510. available_voices = {
  511. "alloy": "alloy",
  512. "echo": "echo",
  513. "fable": "fable",
  514. "onyx": "onyx",
  515. "nova": "nova",
  516. "shimmer": "shimmer",
  517. }
  518. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  519. try:
  520. available_voices = get_elevenlabs_voices(
  521. api_key=request.app.state.config.TTS_API_KEY
  522. )
  523. except Exception:
  524. # Avoided @lru_cache with exception
  525. pass
  526. elif request.app.state.config.TTS_ENGINE == "azure":
  527. try:
  528. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  529. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  530. headers = {
  531. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY
  532. }
  533. response = requests.get(url, headers=headers)
  534. response.raise_for_status()
  535. voices = response.json()
  536. for voice in voices:
  537. available_voices[voice["ShortName"]] = (
  538. f"{voice['DisplayName']} ({voice['ShortName']})"
  539. )
  540. except requests.RequestException as e:
  541. log.error(f"Error fetching voices: {str(e)}")
  542. return available_voices
  543. @lru_cache
  544. def get_elevenlabs_voices(api_key: str) -> dict:
  545. """
  546. Note, set the following in your .env file to use Elevenlabs:
  547. AUDIO_TTS_ENGINE=elevenlabs
  548. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  549. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  550. AUDIO_TTS_MODEL=eleven_multilingual_v2
  551. """
  552. try:
  553. # TODO: Add retries
  554. response = requests.get(
  555. "https://api.elevenlabs.io/v1/voices",
  556. headers={
  557. "xi-api-key": api_key,
  558. "Content-Type": "application/json",
  559. },
  560. )
  561. response.raise_for_status()
  562. voices_data = response.json()
  563. voices = {}
  564. for voice in voices_data.get("voices", []):
  565. voices[voice["voice_id"]] = voice["name"]
  566. except requests.RequestException as e:
  567. # Avoid @lru_cache with exception
  568. log.error(f"Error fetching voices: {str(e)}")
  569. raise RuntimeError(f"Error fetching voices: {str(e)}")
  570. return voices
  571. @router.get("/voices")
  572. async def get_voices(request: Request, user=Depends(get_verified_user)):
  573. return {
  574. "voices": [
  575. {"id": k, "name": v} for k, v in get_available_voices(request).items()
  576. ]
  577. }