main.py 22 KB

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