main.py 22 KB

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