main.py 24 KB

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