audio.py 23 KB

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