audio.py 28 KB

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