audio.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. import hashlib
  2. import json
  3. import logging
  4. import os
  5. import uuid
  6. from functools import lru_cache
  7. from pathlib import Path
  8. from pydub import AudioSegment
  9. from pydub.silence import split_on_silence
  10. import aiohttp
  11. import aiofiles
  12. import requests
  13. import mimetypes
  14. from fastapi import (
  15. Depends,
  16. FastAPI,
  17. File,
  18. HTTPException,
  19. Request,
  20. UploadFile,
  21. status,
  22. APIRouter,
  23. )
  24. from fastapi.middleware.cors import CORSMiddleware
  25. from fastapi.responses import FileResponse
  26. from pydantic import BaseModel
  27. from open_webui.utils.auth import get_admin_user, get_verified_user
  28. from open_webui.config import (
  29. WHISPER_MODEL_AUTO_UPDATE,
  30. WHISPER_MODEL_DIR,
  31. CACHE_DIR,
  32. )
  33. from open_webui.constants import ERROR_MESSAGES
  34. from open_webui.env import (
  35. AIOHTTP_CLIENT_TIMEOUT,
  36. ENV,
  37. SRC_LOG_LEVELS,
  38. DEVICE_TYPE,
  39. ENABLE_FORWARD_USER_INFO_HEADERS,
  40. )
  41. router = APIRouter()
  42. # Constants
  43. MAX_FILE_SIZE_MB = 25
  44. MAX_FILE_SIZE = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
  45. AZURE_MAX_FILE_SIZE_MB = 200
  46. AZURE_MAX_FILE_SIZE = AZURE_MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
  47. log = logging.getLogger(__name__)
  48. log.setLevel(SRC_LOG_LEVELS["AUDIO"])
  49. SPEECH_CACHE_DIR = CACHE_DIR / "audio" / "speech"
  50. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  51. ##########################################
  52. #
  53. # Utility functions
  54. #
  55. ##########################################
  56. from pydub import AudioSegment
  57. from pydub.utils import mediainfo
  58. def get_audio_format(file_path):
  59. """Check if the given file needs to be converted to a different format."""
  60. if not os.path.isfile(file_path):
  61. log.error(f"File not found: {file_path}")
  62. return False
  63. info = mediainfo(file_path)
  64. if (
  65. info.get("codec_name") == "aac"
  66. and info.get("codec_type") == "audio"
  67. and info.get("codec_tag_string") == "mp4a"
  68. ):
  69. return "mp4"
  70. elif info.get("format_name") == "ogg":
  71. return "ogg"
  72. elif info.get("format_name") == "matroska,webm":
  73. return "webm"
  74. return None
  75. def convert_audio_to_wav(file_path, output_path, conversion_type):
  76. """Convert MP4/OGG audio file to WAV format."""
  77. audio = AudioSegment.from_file(file_path, format=conversion_type)
  78. audio.export(output_path, format="wav")
  79. log.info(f"Converted {file_path} to {output_path}")
  80. def set_faster_whisper_model(model: str, auto_update: bool = False):
  81. whisper_model = None
  82. if model:
  83. from faster_whisper import WhisperModel
  84. faster_whisper_kwargs = {
  85. "model_size_or_path": model,
  86. "device": DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu",
  87. "compute_type": "int8",
  88. "download_root": WHISPER_MODEL_DIR,
  89. "local_files_only": not auto_update,
  90. }
  91. try:
  92. whisper_model = WhisperModel(**faster_whisper_kwargs)
  93. except Exception:
  94. log.warning(
  95. "WhisperModel initialization failed, attempting download with local_files_only=False"
  96. )
  97. faster_whisper_kwargs["local_files_only"] = False
  98. whisper_model = WhisperModel(**faster_whisper_kwargs)
  99. return whisper_model
  100. ##########################################
  101. #
  102. # Audio API
  103. #
  104. ##########################################
  105. class TTSConfigForm(BaseModel):
  106. OPENAI_API_BASE_URL: str
  107. OPENAI_API_KEY: str
  108. API_KEY: str
  109. ENGINE: str
  110. MODEL: str
  111. VOICE: str
  112. SPLIT_ON: str
  113. AZURE_SPEECH_REGION: str
  114. AZURE_SPEECH_OUTPUT_FORMAT: str
  115. class STTConfigForm(BaseModel):
  116. OPENAI_API_BASE_URL: str
  117. OPENAI_API_KEY: str
  118. ENGINE: str
  119. MODEL: str
  120. WHISPER_MODEL: str
  121. DEEPGRAM_API_KEY: str
  122. AZURE_API_KEY: str
  123. AZURE_REGION: str
  124. AZURE_LOCALES: str
  125. class AudioConfigUpdateForm(BaseModel):
  126. tts: TTSConfigForm
  127. stt: STTConfigForm
  128. @router.get("/config")
  129. async def get_audio_config(request: Request, user=Depends(get_admin_user)):
  130. return {
  131. "tts": {
  132. "OPENAI_API_BASE_URL": request.app.state.config.TTS_OPENAI_API_BASE_URL,
  133. "OPENAI_API_KEY": request.app.state.config.TTS_OPENAI_API_KEY,
  134. "API_KEY": request.app.state.config.TTS_API_KEY,
  135. "ENGINE": request.app.state.config.TTS_ENGINE,
  136. "MODEL": request.app.state.config.TTS_MODEL,
  137. "VOICE": request.app.state.config.TTS_VOICE,
  138. "SPLIT_ON": request.app.state.config.TTS_SPLIT_ON,
  139. "AZURE_SPEECH_REGION": request.app.state.config.TTS_AZURE_SPEECH_REGION,
  140. "AZURE_SPEECH_OUTPUT_FORMAT": request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  141. },
  142. "stt": {
  143. "OPENAI_API_BASE_URL": request.app.state.config.STT_OPENAI_API_BASE_URL,
  144. "OPENAI_API_KEY": request.app.state.config.STT_OPENAI_API_KEY,
  145. "ENGINE": request.app.state.config.STT_ENGINE,
  146. "MODEL": request.app.state.config.STT_MODEL,
  147. "WHISPER_MODEL": request.app.state.config.WHISPER_MODEL,
  148. "DEEPGRAM_API_KEY": request.app.state.config.DEEPGRAM_API_KEY,
  149. "AZURE_API_KEY": request.app.state.config.AUDIO_STT_AZURE_API_KEY,
  150. "AZURE_REGION": request.app.state.config.AUDIO_STT_AZURE_REGION,
  151. "AZURE_LOCALES": request.app.state.config.AUDIO_STT_AZURE_LOCALES,
  152. },
  153. }
  154. @router.post("/config/update")
  155. async def update_audio_config(
  156. request: Request, form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)
  157. ):
  158. request.app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL
  159. request.app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY
  160. request.app.state.config.TTS_API_KEY = form_data.tts.API_KEY
  161. request.app.state.config.TTS_ENGINE = form_data.tts.ENGINE
  162. request.app.state.config.TTS_MODEL = form_data.tts.MODEL
  163. request.app.state.config.TTS_VOICE = form_data.tts.VOICE
  164. request.app.state.config.TTS_SPLIT_ON = form_data.tts.SPLIT_ON
  165. request.app.state.config.TTS_AZURE_SPEECH_REGION = form_data.tts.AZURE_SPEECH_REGION
  166. request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = (
  167. form_data.tts.AZURE_SPEECH_OUTPUT_FORMAT
  168. )
  169. request.app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
  170. request.app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
  171. request.app.state.config.STT_ENGINE = form_data.stt.ENGINE
  172. request.app.state.config.STT_MODEL = form_data.stt.MODEL
  173. request.app.state.config.WHISPER_MODEL = form_data.stt.WHISPER_MODEL
  174. request.app.state.config.DEEPGRAM_API_KEY = form_data.stt.DEEPGRAM_API_KEY
  175. request.app.state.config.AUDIO_STT_AZURE_API_KEY = form_data.stt.AZURE_API_KEY
  176. request.app.state.config.AUDIO_STT_AZURE_REGION = form_data.stt.AZURE_REGION
  177. request.app.state.config.AUDIO_STT_AZURE_LOCALES = form_data.stt.AZURE_LOCALES
  178. if request.app.state.config.STT_ENGINE == "":
  179. request.app.state.faster_whisper_model = set_faster_whisper_model(
  180. form_data.stt.WHISPER_MODEL, WHISPER_MODEL_AUTO_UPDATE
  181. )
  182. return {
  183. "tts": {
  184. "OPENAI_API_BASE_URL": request.app.state.config.TTS_OPENAI_API_BASE_URL,
  185. "OPENAI_API_KEY": request.app.state.config.TTS_OPENAI_API_KEY,
  186. "API_KEY": request.app.state.config.TTS_API_KEY,
  187. "ENGINE": request.app.state.config.TTS_ENGINE,
  188. "MODEL": request.app.state.config.TTS_MODEL,
  189. "VOICE": request.app.state.config.TTS_VOICE,
  190. "SPLIT_ON": request.app.state.config.TTS_SPLIT_ON,
  191. "AZURE_SPEECH_REGION": request.app.state.config.TTS_AZURE_SPEECH_REGION,
  192. "AZURE_SPEECH_OUTPUT_FORMAT": request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  193. },
  194. "stt": {
  195. "OPENAI_API_BASE_URL": request.app.state.config.STT_OPENAI_API_BASE_URL,
  196. "OPENAI_API_KEY": request.app.state.config.STT_OPENAI_API_KEY,
  197. "ENGINE": request.app.state.config.STT_ENGINE,
  198. "MODEL": request.app.state.config.STT_MODEL,
  199. "WHISPER_MODEL": request.app.state.config.WHISPER_MODEL,
  200. "DEEPGRAM_API_KEY": request.app.state.config.DEEPGRAM_API_KEY,
  201. "AZURE_API_KEY": request.app.state.config.AUDIO_STT_AZURE_API_KEY,
  202. "AZURE_REGION": request.app.state.config.AUDIO_STT_AZURE_REGION,
  203. "AZURE_LOCALES": request.app.state.config.AUDIO_STT_AZURE_LOCALES,
  204. },
  205. }
  206. def load_speech_pipeline(request):
  207. from transformers import pipeline
  208. from datasets import load_dataset
  209. if request.app.state.speech_synthesiser is None:
  210. request.app.state.speech_synthesiser = pipeline(
  211. "text-to-speech", "microsoft/speecht5_tts"
  212. )
  213. if request.app.state.speech_speaker_embeddings_dataset is None:
  214. request.app.state.speech_speaker_embeddings_dataset = load_dataset(
  215. "Matthijs/cmu-arctic-xvectors", split="validation"
  216. )
  217. @router.post("/speech")
  218. async def speech(request: Request, user=Depends(get_verified_user)):
  219. body = await request.body()
  220. name = hashlib.sha256(
  221. body
  222. + str(request.app.state.config.TTS_ENGINE).encode("utf-8")
  223. + str(request.app.state.config.TTS_MODEL).encode("utf-8")
  224. ).hexdigest()
  225. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  226. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  227. # Check if the file already exists in the cache
  228. if file_path.is_file():
  229. return FileResponse(file_path)
  230. payload = None
  231. try:
  232. payload = json.loads(body.decode("utf-8"))
  233. except Exception as e:
  234. log.exception(e)
  235. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  236. if request.app.state.config.TTS_ENGINE == "openai":
  237. payload["model"] = request.app.state.config.TTS_MODEL
  238. try:
  239. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  240. async with aiohttp.ClientSession(
  241. timeout=timeout, trust_env=True
  242. ) as session:
  243. async with session.post(
  244. url=f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  245. json=payload,
  246. headers={
  247. "Content-Type": "application/json",
  248. "Authorization": f"Bearer {request.app.state.config.TTS_OPENAI_API_KEY}",
  249. **(
  250. {
  251. "X-OpenWebUI-User-Name": user.name,
  252. "X-OpenWebUI-User-Id": user.id,
  253. "X-OpenWebUI-User-Email": user.email,
  254. "X-OpenWebUI-User-Role": user.role,
  255. }
  256. if ENABLE_FORWARD_USER_INFO_HEADERS
  257. else {}
  258. ),
  259. },
  260. ) as r:
  261. r.raise_for_status()
  262. async with aiofiles.open(file_path, "wb") as f:
  263. await f.write(await r.read())
  264. async with aiofiles.open(file_body_path, "w") as f:
  265. await f.write(json.dumps(payload))
  266. return FileResponse(file_path)
  267. except Exception as e:
  268. log.exception(e)
  269. detail = None
  270. try:
  271. if r.status != 200:
  272. res = await r.json()
  273. if "error" in res:
  274. detail = f"External: {res['error'].get('message', '')}"
  275. except Exception:
  276. detail = f"External: {e}"
  277. raise HTTPException(
  278. status_code=getattr(r, "status", 500) if r else 500,
  279. detail=detail if detail else "Open WebUI: Server Connection Error",
  280. )
  281. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  282. voice_id = payload.get("voice", "")
  283. if voice_id not in get_available_voices(request):
  284. raise HTTPException(
  285. status_code=400,
  286. detail="Invalid voice id",
  287. )
  288. try:
  289. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  290. async with aiohttp.ClientSession(
  291. timeout=timeout, trust_env=True
  292. ) as session:
  293. async with session.post(
  294. f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
  295. json={
  296. "text": payload["input"],
  297. "model_id": request.app.state.config.TTS_MODEL,
  298. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  299. },
  300. headers={
  301. "Accept": "audio/mpeg",
  302. "Content-Type": "application/json",
  303. "xi-api-key": request.app.state.config.TTS_API_KEY,
  304. },
  305. ) as r:
  306. r.raise_for_status()
  307. async with aiofiles.open(file_path, "wb") as f:
  308. await f.write(await r.read())
  309. async with aiofiles.open(file_body_path, "w") as f:
  310. await f.write(json.dumps(payload))
  311. return FileResponse(file_path)
  312. except Exception as e:
  313. log.exception(e)
  314. detail = None
  315. try:
  316. if r.status != 200:
  317. res = await r.json()
  318. if "error" in res:
  319. detail = f"External: {res['error'].get('message', '')}"
  320. except Exception:
  321. detail = f"External: {e}"
  322. raise HTTPException(
  323. status_code=getattr(r, "status", 500) if r else 500,
  324. detail=detail if detail else "Open WebUI: Server Connection Error",
  325. )
  326. elif request.app.state.config.TTS_ENGINE == "azure":
  327. try:
  328. payload = json.loads(body.decode("utf-8"))
  329. except Exception as e:
  330. log.exception(e)
  331. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  332. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  333. language = request.app.state.config.TTS_VOICE
  334. locale = "-".join(request.app.state.config.TTS_VOICE.split("-")[:1])
  335. output_format = request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
  336. try:
  337. data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
  338. <voice name="{language}">{payload["input"]}</voice>
  339. </speak>"""
  340. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  341. async with aiohttp.ClientSession(
  342. timeout=timeout, trust_env=True
  343. ) as session:
  344. async with session.post(
  345. f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1",
  346. headers={
  347. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY,
  348. "Content-Type": "application/ssml+xml",
  349. "X-Microsoft-OutputFormat": output_format,
  350. },
  351. data=data,
  352. ) as r:
  353. r.raise_for_status()
  354. async with aiofiles.open(file_path, "wb") as f:
  355. await f.write(await r.read())
  356. async with aiofiles.open(file_body_path, "w") as f:
  357. await f.write(json.dumps(payload))
  358. return FileResponse(file_path)
  359. except Exception as e:
  360. log.exception(e)
  361. detail = None
  362. try:
  363. if r.status != 200:
  364. res = await r.json()
  365. if "error" in res:
  366. detail = f"External: {res['error'].get('message', '')}"
  367. except Exception:
  368. detail = f"External: {e}"
  369. raise HTTPException(
  370. status_code=getattr(r, "status", 500) if r else 500,
  371. detail=detail if detail else "Open WebUI: Server Connection Error",
  372. )
  373. elif request.app.state.config.TTS_ENGINE == "transformers":
  374. payload = None
  375. try:
  376. payload = json.loads(body.decode("utf-8"))
  377. except Exception as e:
  378. log.exception(e)
  379. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  380. import torch
  381. import soundfile as sf
  382. load_speech_pipeline(request)
  383. embeddings_dataset = request.app.state.speech_speaker_embeddings_dataset
  384. speaker_index = 6799
  385. try:
  386. speaker_index = embeddings_dataset["filename"].index(
  387. request.app.state.config.TTS_MODEL
  388. )
  389. except Exception:
  390. pass
  391. speaker_embedding = torch.tensor(
  392. embeddings_dataset[speaker_index]["xvector"]
  393. ).unsqueeze(0)
  394. speech = request.app.state.speech_synthesiser(
  395. payload["input"],
  396. forward_params={"speaker_embeddings": speaker_embedding},
  397. )
  398. sf.write(file_path, speech["audio"], samplerate=speech["sampling_rate"])
  399. async with aiofiles.open(file_body_path, "w") as f:
  400. await f.write(json.dumps(payload))
  401. return FileResponse(file_path)
  402. def transcribe(request: Request, file_path):
  403. log.info(f"transcribe: {file_path}")
  404. filename = os.path.basename(file_path)
  405. file_dir = os.path.dirname(file_path)
  406. id = filename.split(".")[0]
  407. if request.app.state.config.STT_ENGINE == "":
  408. if request.app.state.faster_whisper_model is None:
  409. request.app.state.faster_whisper_model = set_faster_whisper_model(
  410. request.app.state.config.WHISPER_MODEL
  411. )
  412. model = request.app.state.faster_whisper_model
  413. segments, info = model.transcribe(file_path, beam_size=5)
  414. log.info(
  415. "Detected language '%s' with probability %f"
  416. % (info.language, info.language_probability)
  417. )
  418. transcript = "".join([segment.text for segment in list(segments)])
  419. data = {"text": transcript.strip()}
  420. # save the transcript to a json file
  421. transcript_file = f"{file_dir}/{id}.json"
  422. with open(transcript_file, "w") as f:
  423. json.dump(data, f)
  424. log.debug(data)
  425. return data
  426. elif request.app.state.config.STT_ENGINE == "openai":
  427. audio_format = get_audio_format(file_path)
  428. if audio_format:
  429. os.rename(file_path, file_path.replace(".wav", f".{audio_format}"))
  430. # Convert unsupported audio file to WAV format
  431. convert_audio_to_wav(
  432. file_path.replace(".wav", f".{audio_format}"),
  433. file_path,
  434. audio_format,
  435. )
  436. r = None
  437. try:
  438. r = requests.post(
  439. url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  440. headers={
  441. "Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
  442. },
  443. files={"file": (filename, open(file_path, "rb"))},
  444. data={"model": request.app.state.config.STT_MODEL},
  445. )
  446. r.raise_for_status()
  447. data = r.json()
  448. # save the transcript to a json file
  449. transcript_file = f"{file_dir}/{id}.json"
  450. with open(transcript_file, "w") as f:
  451. json.dump(data, f)
  452. return data
  453. except Exception as e:
  454. log.exception(e)
  455. detail = None
  456. if r is not None:
  457. try:
  458. res = r.json()
  459. if "error" in res:
  460. detail = f"External: {res['error'].get('message', '')}"
  461. except Exception:
  462. detail = f"External: {e}"
  463. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  464. elif request.app.state.config.STT_ENGINE == "deepgram":
  465. try:
  466. # Determine the MIME type of the file
  467. mime, _ = mimetypes.guess_type(file_path)
  468. if not mime:
  469. mime = "audio/wav" # fallback to wav if undetectable
  470. # Read the audio file
  471. with open(file_path, "rb") as f:
  472. file_data = f.read()
  473. # Build headers and parameters
  474. headers = {
  475. "Authorization": f"Token {request.app.state.config.DEEPGRAM_API_KEY}",
  476. "Content-Type": mime,
  477. }
  478. # Add model if specified
  479. params = {}
  480. if request.app.state.config.STT_MODEL:
  481. params["model"] = request.app.state.config.STT_MODEL
  482. # Make request to Deepgram API
  483. r = requests.post(
  484. "https://api.deepgram.com/v1/listen",
  485. headers=headers,
  486. params=params,
  487. data=file_data,
  488. )
  489. r.raise_for_status()
  490. response_data = r.json()
  491. # Extract transcript from Deepgram response
  492. try:
  493. transcript = response_data["results"]["channels"][0]["alternatives"][
  494. 0
  495. ].get("transcript", "")
  496. except (KeyError, IndexError) as e:
  497. log.error(f"Malformed response from Deepgram: {str(e)}")
  498. raise Exception(
  499. "Failed to parse Deepgram response - unexpected response format"
  500. )
  501. data = {"text": transcript.strip()}
  502. # Save transcript
  503. transcript_file = f"{file_dir}/{id}.json"
  504. with open(transcript_file, "w") as f:
  505. json.dump(data, f)
  506. return data
  507. except Exception as e:
  508. log.exception(e)
  509. detail = None
  510. if r is not None:
  511. try:
  512. res = r.json()
  513. if "error" in res:
  514. detail = f"External: {res['error'].get('message', '')}"
  515. except Exception:
  516. detail = f"External: {e}"
  517. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  518. elif request.app.state.config.STT_ENGINE == "azure":
  519. # Check file exists and size
  520. if not os.path.exists(file_path):
  521. raise HTTPException(status_code=400, detail="Audio file not found")
  522. # Check file size (Azure has a larger limit of 200MB)
  523. file_size = os.path.getsize(file_path)
  524. if file_size > AZURE_MAX_FILE_SIZE:
  525. raise HTTPException(
  526. status_code=400,
  527. detail=f"File size exceeds Azure's limit of {AZURE_MAX_FILE_SIZE_MB}MB",
  528. )
  529. api_key = request.app.state.config.AUDIO_STT_AZURE_API_KEY
  530. region = request.app.state.config.AUDIO_STT_AZURE_REGION
  531. locales = request.app.state.config.AUDIO_STT_AZURE_LOCALES
  532. # IF NO LOCALES, USE DEFAULTS
  533. if len(locales) < 2:
  534. locales = [
  535. "en-US",
  536. "es-ES",
  537. "es-MX",
  538. "fr-FR",
  539. "hi-IN",
  540. "it-IT",
  541. "de-DE",
  542. "en-GB",
  543. "en-IN",
  544. "ja-JP",
  545. "ko-KR",
  546. "pt-BR",
  547. "zh-CN",
  548. ]
  549. locales = ",".join(locales)
  550. if not api_key or not region:
  551. raise HTTPException(
  552. status_code=400,
  553. detail="Azure API key and region are required for Azure STT",
  554. )
  555. r = None
  556. try:
  557. # Prepare the request
  558. data = {
  559. "definition": json.dumps(
  560. {
  561. "locales": locales.split(","),
  562. "diarization": {"maxSpeakers": 3, "enabled": True},
  563. }
  564. if locales
  565. else {}
  566. )
  567. }
  568. url = f"https://{region}.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2024-11-15"
  569. # Use context manager to ensure file is properly closed
  570. with open(file_path, "rb") as audio_file:
  571. r = requests.post(
  572. url=url,
  573. files={"audio": audio_file},
  574. data=data,
  575. headers={
  576. "Ocp-Apim-Subscription-Key": api_key,
  577. },
  578. )
  579. r.raise_for_status()
  580. response = r.json()
  581. # Extract transcript from response
  582. if not response.get("combinedPhrases"):
  583. raise ValueError("No transcription found in response")
  584. # Get the full transcript from combinedPhrases
  585. transcript = response["combinedPhrases"][0].get("text", "").strip()
  586. if not transcript:
  587. raise ValueError("Empty transcript in response")
  588. data = {"text": transcript}
  589. # Save transcript to json file (consistent with other providers)
  590. transcript_file = f"{file_dir}/{id}.json"
  591. with open(transcript_file, "w") as f:
  592. json.dump(data, f)
  593. log.debug(data)
  594. return data
  595. except (KeyError, IndexError, ValueError) as e:
  596. log.exception("Error parsing Azure response")
  597. raise HTTPException(
  598. status_code=500,
  599. detail=f"Failed to parse Azure response: {str(e)}",
  600. )
  601. except requests.exceptions.RequestException as e:
  602. log.exception(e)
  603. detail = None
  604. try:
  605. if r is not None and r.status_code != 200:
  606. res = r.json()
  607. if "error" in res:
  608. detail = f"External: {res['error'].get('message', '')}"
  609. except Exception:
  610. detail = f"External: {e}"
  611. raise HTTPException(
  612. status_code=getattr(r, "status_code", 500) if r else 500,
  613. detail=detail if detail else "Open WebUI: Server Connection Error",
  614. )
  615. def compress_audio(file_path):
  616. if os.path.getsize(file_path) > MAX_FILE_SIZE:
  617. file_dir = os.path.dirname(file_path)
  618. audio = AudioSegment.from_file(file_path)
  619. audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
  620. compressed_path = f"{file_dir}/{id}_compressed.opus"
  621. audio.export(compressed_path, format="opus", bitrate="32k")
  622. log.debug(f"Compressed audio to {compressed_path}")
  623. if (
  624. os.path.getsize(compressed_path) > MAX_FILE_SIZE
  625. ): # Still larger than MAX_FILE_SIZE after compression
  626. raise Exception(ERROR_MESSAGES.FILE_TOO_LARGE(size=f"{MAX_FILE_SIZE_MB}MB"))
  627. return compressed_path
  628. else:
  629. return file_path
  630. @router.post("/transcriptions")
  631. def transcription(
  632. request: Request,
  633. file: UploadFile = File(...),
  634. user=Depends(get_verified_user),
  635. ):
  636. log.info(f"file.content_type: {file.content_type}")
  637. supported_filetypes = ("audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a")
  638. if not file.content_type.startswith(supported_filetypes):
  639. raise HTTPException(
  640. status_code=status.HTTP_400_BAD_REQUEST,
  641. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  642. )
  643. try:
  644. ext = file.filename.split(".")[-1]
  645. id = uuid.uuid4()
  646. filename = f"{id}.{ext}"
  647. contents = file.file.read()
  648. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  649. os.makedirs(file_dir, exist_ok=True)
  650. file_path = f"{file_dir}/{filename}"
  651. with open(file_path, "wb") as f:
  652. f.write(contents)
  653. try:
  654. try:
  655. file_path = compress_audio(file_path)
  656. except Exception as e:
  657. log.exception(e)
  658. raise HTTPException(
  659. status_code=status.HTTP_400_BAD_REQUEST,
  660. detail=ERROR_MESSAGES.DEFAULT(e),
  661. )
  662. data = transcribe(request, file_path)
  663. file_path = file_path.split("/")[-1]
  664. return {**data, "filename": file_path}
  665. except Exception as e:
  666. log.exception(e)
  667. raise HTTPException(
  668. status_code=status.HTTP_400_BAD_REQUEST,
  669. detail=ERROR_MESSAGES.DEFAULT(e),
  670. )
  671. except Exception as e:
  672. log.exception(e)
  673. raise HTTPException(
  674. status_code=status.HTTP_400_BAD_REQUEST,
  675. detail=ERROR_MESSAGES.DEFAULT(e),
  676. )
  677. def get_available_models(request: Request) -> list[dict]:
  678. available_models = []
  679. if request.app.state.config.TTS_ENGINE == "openai":
  680. # Use custom endpoint if not using the official OpenAI API URL
  681. if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith(
  682. "https://api.openai.com"
  683. ):
  684. try:
  685. response = requests.get(
  686. f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/models"
  687. )
  688. response.raise_for_status()
  689. data = response.json()
  690. available_models = data.get("models", [])
  691. except Exception as e:
  692. log.error(f"Error fetching models from custom endpoint: {str(e)}")
  693. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  694. else:
  695. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  696. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  697. try:
  698. response = requests.get(
  699. "https://api.elevenlabs.io/v1/models",
  700. headers={
  701. "xi-api-key": request.app.state.config.TTS_API_KEY,
  702. "Content-Type": "application/json",
  703. },
  704. timeout=5,
  705. )
  706. response.raise_for_status()
  707. models = response.json()
  708. available_models = [
  709. {"name": model["name"], "id": model["model_id"]} for model in models
  710. ]
  711. except requests.RequestException as e:
  712. log.error(f"Error fetching voices: {str(e)}")
  713. return available_models
  714. @router.get("/models")
  715. async def get_models(request: Request, user=Depends(get_verified_user)):
  716. return {"models": get_available_models(request)}
  717. def get_available_voices(request) -> dict:
  718. """Returns {voice_id: voice_name} dict"""
  719. available_voices = {}
  720. if request.app.state.config.TTS_ENGINE == "openai":
  721. # Use custom endpoint if not using the official OpenAI API URL
  722. if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith(
  723. "https://api.openai.com"
  724. ):
  725. try:
  726. response = requests.get(
  727. f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/voices"
  728. )
  729. response.raise_for_status()
  730. data = response.json()
  731. voices_list = data.get("voices", [])
  732. available_voices = {voice["id"]: voice["name"] for voice in voices_list}
  733. except Exception as e:
  734. log.error(f"Error fetching voices from custom endpoint: {str(e)}")
  735. available_voices = {
  736. "alloy": "alloy",
  737. "echo": "echo",
  738. "fable": "fable",
  739. "onyx": "onyx",
  740. "nova": "nova",
  741. "shimmer": "shimmer",
  742. }
  743. else:
  744. available_voices = {
  745. "alloy": "alloy",
  746. "echo": "echo",
  747. "fable": "fable",
  748. "onyx": "onyx",
  749. "nova": "nova",
  750. "shimmer": "shimmer",
  751. }
  752. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  753. try:
  754. available_voices = get_elevenlabs_voices(
  755. api_key=request.app.state.config.TTS_API_KEY
  756. )
  757. except Exception:
  758. # Avoided @lru_cache with exception
  759. pass
  760. elif request.app.state.config.TTS_ENGINE == "azure":
  761. try:
  762. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  763. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  764. headers = {
  765. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY
  766. }
  767. response = requests.get(url, headers=headers)
  768. response.raise_for_status()
  769. voices = response.json()
  770. for voice in voices:
  771. available_voices[voice["ShortName"]] = (
  772. f"{voice['DisplayName']} ({voice['ShortName']})"
  773. )
  774. except requests.RequestException as e:
  775. log.error(f"Error fetching voices: {str(e)}")
  776. return available_voices
  777. @lru_cache
  778. def get_elevenlabs_voices(api_key: str) -> dict:
  779. """
  780. Note, set the following in your .env file to use Elevenlabs:
  781. AUDIO_TTS_ENGINE=elevenlabs
  782. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  783. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  784. AUDIO_TTS_MODEL=eleven_multilingual_v2
  785. """
  786. try:
  787. # TODO: Add retries
  788. response = requests.get(
  789. "https://api.elevenlabs.io/v1/voices",
  790. headers={
  791. "xi-api-key": api_key,
  792. "Content-Type": "application/json",
  793. },
  794. )
  795. response.raise_for_status()
  796. voices_data = response.json()
  797. voices = {}
  798. for voice in voices_data.get("voices", []):
  799. voices[voice["voice_id"]] = voice["name"]
  800. except requests.RequestException as e:
  801. # Avoid @lru_cache with exception
  802. log.error(f"Error fetching voices: {str(e)}")
  803. raise RuntimeError(f"Error fetching voices: {str(e)}")
  804. return voices
  805. @router.get("/voices")
  806. async def get_voices(request: Request, user=Depends(get_verified_user)):
  807. return {
  808. "voices": [
  809. {"id": k, "name": v} for k, v in get_available_voices(request).items()
  810. ]
  811. }