main.py 23 KB

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