audio.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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(
  414. file_path,
  415. beam_size=5,
  416. vad_filter=request.app.state.config.WHISPER_VAD_FILTER,
  417. )
  418. log.info(
  419. "Detected language '%s' with probability %f"
  420. % (info.language, info.language_probability)
  421. )
  422. transcript = "".join([segment.text for segment in list(segments)])
  423. data = {"text": transcript.strip()}
  424. # save the transcript to a json file
  425. transcript_file = f"{file_dir}/{id}.json"
  426. with open(transcript_file, "w") as f:
  427. json.dump(data, f)
  428. log.debug(data)
  429. return data
  430. elif request.app.state.config.STT_ENGINE == "openai":
  431. audio_format = get_audio_format(file_path)
  432. if audio_format:
  433. os.rename(file_path, file_path.replace(".wav", f".{audio_format}"))
  434. # Convert unsupported audio file to WAV format
  435. convert_audio_to_wav(
  436. file_path.replace(".wav", f".{audio_format}"),
  437. file_path,
  438. audio_format,
  439. )
  440. r = None
  441. try:
  442. r = requests.post(
  443. url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  444. headers={
  445. "Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
  446. },
  447. files={"file": (filename, open(file_path, "rb"))},
  448. data={"model": request.app.state.config.STT_MODEL},
  449. )
  450. r.raise_for_status()
  451. data = r.json()
  452. # save the transcript to a json file
  453. transcript_file = f"{file_dir}/{id}.json"
  454. with open(transcript_file, "w") as f:
  455. json.dump(data, f)
  456. return data
  457. except Exception as e:
  458. log.exception(e)
  459. detail = None
  460. if r is not None:
  461. try:
  462. res = r.json()
  463. if "error" in res:
  464. detail = f"External: {res['error'].get('message', '')}"
  465. except Exception:
  466. detail = f"External: {e}"
  467. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  468. elif request.app.state.config.STT_ENGINE == "deepgram":
  469. try:
  470. # Determine the MIME type of the file
  471. mime, _ = mimetypes.guess_type(file_path)
  472. if not mime:
  473. mime = "audio/wav" # fallback to wav if undetectable
  474. # Read the audio file
  475. with open(file_path, "rb") as f:
  476. file_data = f.read()
  477. # Build headers and parameters
  478. headers = {
  479. "Authorization": f"Token {request.app.state.config.DEEPGRAM_API_KEY}",
  480. "Content-Type": mime,
  481. }
  482. # Add model if specified
  483. params = {}
  484. if request.app.state.config.STT_MODEL:
  485. params["model"] = request.app.state.config.STT_MODEL
  486. # Make request to Deepgram API
  487. r = requests.post(
  488. "https://api.deepgram.com/v1/listen",
  489. headers=headers,
  490. params=params,
  491. data=file_data,
  492. )
  493. r.raise_for_status()
  494. response_data = r.json()
  495. # Extract transcript from Deepgram response
  496. try:
  497. transcript = response_data["results"]["channels"][0]["alternatives"][
  498. 0
  499. ].get("transcript", "")
  500. except (KeyError, IndexError) as e:
  501. log.error(f"Malformed response from Deepgram: {str(e)}")
  502. raise Exception(
  503. "Failed to parse Deepgram response - unexpected response format"
  504. )
  505. data = {"text": transcript.strip()}
  506. # Save transcript
  507. transcript_file = f"{file_dir}/{id}.json"
  508. with open(transcript_file, "w") as f:
  509. json.dump(data, f)
  510. return data
  511. except Exception as e:
  512. log.exception(e)
  513. detail = None
  514. if r is not None:
  515. try:
  516. res = r.json()
  517. if "error" in res:
  518. detail = f"External: {res['error'].get('message', '')}"
  519. except Exception:
  520. detail = f"External: {e}"
  521. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  522. elif request.app.state.config.STT_ENGINE == "azure":
  523. # Check file exists and size
  524. if not os.path.exists(file_path):
  525. raise HTTPException(status_code=400, detail="Audio file not found")
  526. # Check file size (Azure has a larger limit of 200MB)
  527. file_size = os.path.getsize(file_path)
  528. if file_size > AZURE_MAX_FILE_SIZE:
  529. raise HTTPException(
  530. status_code=400,
  531. detail=f"File size exceeds Azure's limit of {AZURE_MAX_FILE_SIZE_MB}MB",
  532. )
  533. api_key = request.app.state.config.AUDIO_STT_AZURE_API_KEY
  534. region = request.app.state.config.AUDIO_STT_AZURE_REGION
  535. locales = request.app.state.config.AUDIO_STT_AZURE_LOCALES
  536. # IF NO LOCALES, USE DEFAULTS
  537. if len(locales) < 2:
  538. locales = [
  539. "en-US",
  540. "es-ES",
  541. "es-MX",
  542. "fr-FR",
  543. "hi-IN",
  544. "it-IT",
  545. "de-DE",
  546. "en-GB",
  547. "en-IN",
  548. "ja-JP",
  549. "ko-KR",
  550. "pt-BR",
  551. "zh-CN",
  552. ]
  553. locales = ",".join(locales)
  554. if not api_key or not region:
  555. raise HTTPException(
  556. status_code=400,
  557. detail="Azure API key and region are required for Azure STT",
  558. )
  559. r = None
  560. try:
  561. # Prepare the request
  562. data = {
  563. "definition": json.dumps(
  564. {
  565. "locales": locales.split(","),
  566. "diarization": {"maxSpeakers": 3, "enabled": True},
  567. }
  568. if locales
  569. else {}
  570. )
  571. }
  572. url = f"https://{region}.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2024-11-15"
  573. # Use context manager to ensure file is properly closed
  574. with open(file_path, "rb") as audio_file:
  575. r = requests.post(
  576. url=url,
  577. files={"audio": audio_file},
  578. data=data,
  579. headers={
  580. "Ocp-Apim-Subscription-Key": api_key,
  581. },
  582. )
  583. r.raise_for_status()
  584. response = r.json()
  585. # Extract transcript from response
  586. if not response.get("combinedPhrases"):
  587. raise ValueError("No transcription found in response")
  588. # Get the full transcript from combinedPhrases
  589. transcript = response["combinedPhrases"][0].get("text", "").strip()
  590. if not transcript:
  591. raise ValueError("Empty transcript in response")
  592. data = {"text": transcript}
  593. # Save transcript to json file (consistent with other providers)
  594. transcript_file = f"{file_dir}/{id}.json"
  595. with open(transcript_file, "w") as f:
  596. json.dump(data, f)
  597. log.debug(data)
  598. return data
  599. except (KeyError, IndexError, ValueError) as e:
  600. log.exception("Error parsing Azure response")
  601. raise HTTPException(
  602. status_code=500,
  603. detail=f"Failed to parse Azure response: {str(e)}",
  604. )
  605. except requests.exceptions.RequestException as e:
  606. log.exception(e)
  607. detail = None
  608. try:
  609. if r is not None and r.status_code != 200:
  610. res = r.json()
  611. if "error" in res:
  612. detail = f"External: {res['error'].get('message', '')}"
  613. except Exception:
  614. detail = f"External: {e}"
  615. raise HTTPException(
  616. status_code=getattr(r, "status_code", 500) if r else 500,
  617. detail=detail if detail else "Open WebUI: Server Connection Error",
  618. )
  619. def compress_audio(file_path):
  620. if os.path.getsize(file_path) > MAX_FILE_SIZE:
  621. file_dir = os.path.dirname(file_path)
  622. audio = AudioSegment.from_file(file_path)
  623. audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
  624. compressed_path = f"{file_dir}/{id}_compressed.opus"
  625. audio.export(compressed_path, format="opus", bitrate="32k")
  626. log.debug(f"Compressed audio to {compressed_path}")
  627. if (
  628. os.path.getsize(compressed_path) > MAX_FILE_SIZE
  629. ): # Still larger than MAX_FILE_SIZE after compression
  630. raise Exception(ERROR_MESSAGES.FILE_TOO_LARGE(size=f"{MAX_FILE_SIZE_MB}MB"))
  631. return compressed_path
  632. else:
  633. return file_path
  634. @router.post("/transcriptions")
  635. def transcription(
  636. request: Request,
  637. file: UploadFile = File(...),
  638. user=Depends(get_verified_user),
  639. ):
  640. log.info(f"file.content_type: {file.content_type}")
  641. supported_filetypes = ("audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a")
  642. if not file.content_type.startswith(supported_filetypes):
  643. raise HTTPException(
  644. status_code=status.HTTP_400_BAD_REQUEST,
  645. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  646. )
  647. try:
  648. ext = file.filename.split(".")[-1]
  649. id = uuid.uuid4()
  650. filename = f"{id}.{ext}"
  651. contents = file.file.read()
  652. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  653. os.makedirs(file_dir, exist_ok=True)
  654. file_path = f"{file_dir}/{filename}"
  655. with open(file_path, "wb") as f:
  656. f.write(contents)
  657. try:
  658. try:
  659. file_path = compress_audio(file_path)
  660. except Exception as e:
  661. log.exception(e)
  662. raise HTTPException(
  663. status_code=status.HTTP_400_BAD_REQUEST,
  664. detail=ERROR_MESSAGES.DEFAULT(e),
  665. )
  666. data = transcribe(request, file_path)
  667. file_path = file_path.split("/")[-1]
  668. return {**data, "filename": file_path}
  669. except Exception as e:
  670. log.exception(e)
  671. raise HTTPException(
  672. status_code=status.HTTP_400_BAD_REQUEST,
  673. detail=ERROR_MESSAGES.DEFAULT(e),
  674. )
  675. except Exception as e:
  676. log.exception(e)
  677. raise HTTPException(
  678. status_code=status.HTTP_400_BAD_REQUEST,
  679. detail=ERROR_MESSAGES.DEFAULT(e),
  680. )
  681. def get_available_models(request: Request) -> list[dict]:
  682. available_models = []
  683. if request.app.state.config.TTS_ENGINE == "openai":
  684. # Use custom endpoint if not using the official OpenAI API URL
  685. if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith(
  686. "https://api.openai.com"
  687. ):
  688. try:
  689. response = requests.get(
  690. f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/models"
  691. )
  692. response.raise_for_status()
  693. data = response.json()
  694. available_models = data.get("models", [])
  695. except Exception as e:
  696. log.error(f"Error fetching models from custom endpoint: {str(e)}")
  697. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  698. else:
  699. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  700. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  701. try:
  702. response = requests.get(
  703. "https://api.elevenlabs.io/v1/models",
  704. headers={
  705. "xi-api-key": request.app.state.config.TTS_API_KEY,
  706. "Content-Type": "application/json",
  707. },
  708. timeout=5,
  709. )
  710. response.raise_for_status()
  711. models = response.json()
  712. available_models = [
  713. {"name": model["name"], "id": model["model_id"]} for model in models
  714. ]
  715. except requests.RequestException as e:
  716. log.error(f"Error fetching voices: {str(e)}")
  717. return available_models
  718. @router.get("/models")
  719. async def get_models(request: Request, user=Depends(get_verified_user)):
  720. return {"models": get_available_models(request)}
  721. def get_available_voices(request) -> dict:
  722. """Returns {voice_id: voice_name} dict"""
  723. available_voices = {}
  724. if request.app.state.config.TTS_ENGINE == "openai":
  725. # Use custom endpoint if not using the official OpenAI API URL
  726. if not request.app.state.config.TTS_OPENAI_API_BASE_URL.startswith(
  727. "https://api.openai.com"
  728. ):
  729. try:
  730. response = requests.get(
  731. f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/voices"
  732. )
  733. response.raise_for_status()
  734. data = response.json()
  735. voices_list = data.get("voices", [])
  736. available_voices = {voice["id"]: voice["name"] for voice in voices_list}
  737. except Exception as e:
  738. log.error(f"Error fetching voices from custom endpoint: {str(e)}")
  739. available_voices = {
  740. "alloy": "alloy",
  741. "echo": "echo",
  742. "fable": "fable",
  743. "onyx": "onyx",
  744. "nova": "nova",
  745. "shimmer": "shimmer",
  746. }
  747. else:
  748. available_voices = {
  749. "alloy": "alloy",
  750. "echo": "echo",
  751. "fable": "fable",
  752. "onyx": "onyx",
  753. "nova": "nova",
  754. "shimmer": "shimmer",
  755. }
  756. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  757. try:
  758. available_voices = get_elevenlabs_voices(
  759. api_key=request.app.state.config.TTS_API_KEY
  760. )
  761. except Exception:
  762. # Avoided @lru_cache with exception
  763. pass
  764. elif request.app.state.config.TTS_ENGINE == "azure":
  765. try:
  766. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  767. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  768. headers = {
  769. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY
  770. }
  771. response = requests.get(url, headers=headers)
  772. response.raise_for_status()
  773. voices = response.json()
  774. for voice in voices:
  775. available_voices[voice["ShortName"]] = (
  776. f"{voice['DisplayName']} ({voice['ShortName']})"
  777. )
  778. except requests.RequestException as e:
  779. log.error(f"Error fetching voices: {str(e)}")
  780. return available_voices
  781. @lru_cache
  782. def get_elevenlabs_voices(api_key: str) -> dict:
  783. """
  784. Note, set the following in your .env file to use Elevenlabs:
  785. AUDIO_TTS_ENGINE=elevenlabs
  786. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  787. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  788. AUDIO_TTS_MODEL=eleven_multilingual_v2
  789. """
  790. try:
  791. # TODO: Add retries
  792. response = requests.get(
  793. "https://api.elevenlabs.io/v1/voices",
  794. headers={
  795. "xi-api-key": api_key,
  796. "Content-Type": "application/json",
  797. },
  798. )
  799. response.raise_for_status()
  800. voices_data = response.json()
  801. voices = {}
  802. for voice in voices_data.get("voices", []):
  803. voices[voice["voice_id"]] = voice["name"]
  804. except requests.RequestException as e:
  805. # Avoid @lru_cache with exception
  806. log.error(f"Error fetching voices: {str(e)}")
  807. raise RuntimeError(f"Error fetching voices: {str(e)}")
  808. return voices
  809. @router.get("/voices")
  810. async def get_voices(request: Request, user=Depends(get_verified_user)):
  811. return {
  812. "voices": [
  813. {"id": k, "name": v} for k, v in get_available_voices(request).items()
  814. ]
  815. }