audio.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 = Path(CACHE_DIR).joinpath("./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. print(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. print(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. # print(payload)
  222. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  223. async with aiohttp.ClientSession(
  224. timeout=timeout, trust_env=True
  225. ) as session:
  226. async with session.post(
  227. url=f"{request.app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  228. json=payload,
  229. headers={
  230. "Content-Type": "application/json",
  231. "Authorization": f"Bearer {request.app.state.config.TTS_OPENAI_API_KEY}",
  232. **(
  233. {
  234. "X-OpenWebUI-User-Name": user.name,
  235. "X-OpenWebUI-User-Id": user.id,
  236. "X-OpenWebUI-User-Email": user.email,
  237. "X-OpenWebUI-User-Role": user.role,
  238. }
  239. if ENABLE_FORWARD_USER_INFO_HEADERS
  240. else {}
  241. ),
  242. },
  243. ) as r:
  244. r.raise_for_status()
  245. async with aiofiles.open(file_path, "wb") as f:
  246. await f.write(await r.read())
  247. async with aiofiles.open(file_body_path, "w") as f:
  248. await f.write(json.dumps(payload))
  249. return FileResponse(file_path)
  250. except Exception as e:
  251. log.exception(e)
  252. detail = None
  253. try:
  254. if r.status != 200:
  255. res = await r.json()
  256. if "error" in res:
  257. detail = f"External: {res['error'].get('message', '')}"
  258. except Exception:
  259. detail = f"External: {e}"
  260. raise HTTPException(
  261. status_code=getattr(r, "status", 500),
  262. detail=detail if detail else "Open WebUI: Server Connection Error",
  263. )
  264. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  265. voice_id = payload.get("voice", "")
  266. if voice_id not in get_available_voices(request):
  267. raise HTTPException(
  268. status_code=400,
  269. detail="Invalid voice id",
  270. )
  271. try:
  272. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  273. async with aiohttp.ClientSession(
  274. timeout=timeout, trust_env=True
  275. ) as session:
  276. async with session.post(
  277. f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
  278. json={
  279. "text": payload["input"],
  280. "model_id": request.app.state.config.TTS_MODEL,
  281. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  282. },
  283. headers={
  284. "Accept": "audio/mpeg",
  285. "Content-Type": "application/json",
  286. "xi-api-key": request.app.state.config.TTS_API_KEY,
  287. },
  288. ) as r:
  289. r.raise_for_status()
  290. async with aiofiles.open(file_path, "wb") as f:
  291. await f.write(await r.read())
  292. async with aiofiles.open(file_body_path, "w") as f:
  293. await f.write(json.dumps(payload))
  294. return FileResponse(file_path)
  295. except Exception as e:
  296. log.exception(e)
  297. detail = None
  298. try:
  299. if r.status != 200:
  300. res = await r.json()
  301. if "error" in res:
  302. detail = f"External: {res['error'].get('message', '')}"
  303. except Exception:
  304. detail = f"External: {e}"
  305. raise HTTPException(
  306. status_code=getattr(r, "status", 500),
  307. detail=detail if detail else "Open WebUI: Server Connection Error",
  308. )
  309. elif request.app.state.config.TTS_ENGINE == "azure":
  310. try:
  311. payload = json.loads(body.decode("utf-8"))
  312. except Exception as e:
  313. log.exception(e)
  314. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  315. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  316. language = request.app.state.config.TTS_VOICE
  317. locale = "-".join(request.app.state.config.TTS_VOICE.split("-")[:1])
  318. output_format = request.app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
  319. try:
  320. data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
  321. <voice name="{language}">{payload["input"]}</voice>
  322. </speak>"""
  323. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  324. async with aiohttp.ClientSession(
  325. timeout=timeout, trust_env=True
  326. ) as session:
  327. async with session.post(
  328. f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1",
  329. headers={
  330. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY,
  331. "Content-Type": "application/ssml+xml",
  332. "X-Microsoft-OutputFormat": output_format,
  333. },
  334. data=data,
  335. ) as r:
  336. r.raise_for_status()
  337. async with aiofiles.open(file_path, "wb") as f:
  338. await f.write(await r.read())
  339. async with aiofiles.open(file_body_path, "w") as f:
  340. await f.write(json.dumps(payload))
  341. return FileResponse(file_path)
  342. except Exception as e:
  343. log.exception(e)
  344. detail = None
  345. try:
  346. if r.status != 200:
  347. res = await r.json()
  348. if "error" in res:
  349. detail = f"External: {res['error'].get('message', '')}"
  350. except Exception:
  351. detail = f"External: {e}"
  352. raise HTTPException(
  353. status_code=getattr(r, "status", 500),
  354. detail=detail if detail else "Open WebUI: Server Connection Error",
  355. )
  356. elif request.app.state.config.TTS_ENGINE == "transformers":
  357. payload = None
  358. try:
  359. payload = json.loads(body.decode("utf-8"))
  360. except Exception as e:
  361. log.exception(e)
  362. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  363. import torch
  364. import soundfile as sf
  365. load_speech_pipeline(request)
  366. embeddings_dataset = request.app.state.speech_speaker_embeddings_dataset
  367. speaker_index = 6799
  368. try:
  369. speaker_index = embeddings_dataset["filename"].index(
  370. request.app.state.config.TTS_MODEL
  371. )
  372. except Exception:
  373. pass
  374. speaker_embedding = torch.tensor(
  375. embeddings_dataset[speaker_index]["xvector"]
  376. ).unsqueeze(0)
  377. speech = request.app.state.speech_synthesiser(
  378. payload["input"],
  379. forward_params={"speaker_embeddings": speaker_embedding},
  380. )
  381. sf.write(file_path, speech["audio"], samplerate=speech["sampling_rate"])
  382. async with aiofiles.open(file_body_path, "w") as f:
  383. await f.write(json.dumps(payload))
  384. return FileResponse(file_path)
  385. def transcribe(request: Request, file_path):
  386. print("transcribe", file_path)
  387. filename = os.path.basename(file_path)
  388. file_dir = os.path.dirname(file_path)
  389. id = filename.split(".")[0]
  390. if request.app.state.config.STT_ENGINE == "":
  391. if request.app.state.faster_whisper_model is None:
  392. request.app.state.faster_whisper_model = set_faster_whisper_model(
  393. request.app.state.config.WHISPER_MODEL
  394. )
  395. model = request.app.state.faster_whisper_model
  396. segments, info = model.transcribe(file_path, beam_size=5)
  397. log.info(
  398. "Detected language '%s' with probability %f"
  399. % (info.language, info.language_probability)
  400. )
  401. transcript = "".join([segment.text for segment in list(segments)])
  402. data = {"text": transcript.strip()}
  403. # save the transcript to a json file
  404. transcript_file = f"{file_dir}/{id}.json"
  405. with open(transcript_file, "w") as f:
  406. json.dump(data, f)
  407. log.debug(data)
  408. return data
  409. elif request.app.state.config.STT_ENGINE == "openai":
  410. if is_mp4_audio(file_path):
  411. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  412. # Convert MP4 audio file to WAV format
  413. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  414. r = None
  415. try:
  416. r = requests.post(
  417. url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  418. headers={
  419. "Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
  420. },
  421. files={"file": (filename, open(file_path, "rb"))},
  422. data={"model": request.app.state.config.STT_MODEL},
  423. )
  424. r.raise_for_status()
  425. data = r.json()
  426. # save the transcript to a json file
  427. transcript_file = f"{file_dir}/{id}.json"
  428. with open(transcript_file, "w") as f:
  429. json.dump(data, f)
  430. return data
  431. except Exception as e:
  432. log.exception(e)
  433. detail = None
  434. if r is not None:
  435. try:
  436. res = r.json()
  437. if "error" in res:
  438. detail = f"External: {res['error'].get('message', '')}"
  439. except Exception:
  440. detail = f"External: {e}"
  441. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  442. elif request.app.state.config.STT_ENGINE == "deepgram":
  443. try:
  444. # Determine the MIME type of the file
  445. mime, _ = mimetypes.guess_type(file_path)
  446. if not mime:
  447. mime = "audio/wav" # fallback to wav if undetectable
  448. # Read the audio file
  449. with open(file_path, "rb") as f:
  450. file_data = f.read()
  451. # Build headers and parameters
  452. headers = {
  453. "Authorization": f"Token {request.app.state.config.DEEPGRAM_API_KEY}",
  454. "Content-Type": mime,
  455. }
  456. # Add model if specified
  457. params = {}
  458. if request.app.state.config.STT_MODEL:
  459. params["model"] = request.app.state.config.STT_MODEL
  460. # Make request to Deepgram API
  461. r = requests.post(
  462. "https://api.deepgram.com/v1/listen",
  463. headers=headers,
  464. params=params,
  465. data=file_data,
  466. )
  467. r.raise_for_status()
  468. response_data = r.json()
  469. # Extract transcript from Deepgram response
  470. try:
  471. transcript = response_data["results"]["channels"][0]["alternatives"][
  472. 0
  473. ].get("transcript", "")
  474. except (KeyError, IndexError) as e:
  475. log.error(f"Malformed response from Deepgram: {str(e)}")
  476. raise Exception(
  477. "Failed to parse Deepgram response - unexpected response format"
  478. )
  479. data = {"text": transcript.strip()}
  480. # Save transcript
  481. transcript_file = f"{file_dir}/{id}.json"
  482. with open(transcript_file, "w") as f:
  483. json.dump(data, f)
  484. return data
  485. except Exception as e:
  486. log.exception(e)
  487. detail = None
  488. if r is not None:
  489. try:
  490. res = r.json()
  491. if "error" in res:
  492. detail = f"External: {res['error'].get('message', '')}"
  493. except Exception:
  494. detail = f"External: {e}"
  495. raise Exception(detail if detail else "Open WebUI: Server Connection Error")
  496. def compress_audio(file_path):
  497. if os.path.getsize(file_path) > MAX_FILE_SIZE:
  498. file_dir = os.path.dirname(file_path)
  499. audio = AudioSegment.from_file(file_path)
  500. audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
  501. compressed_path = f"{file_dir}/{id}_compressed.opus"
  502. audio.export(compressed_path, format="opus", bitrate="32k")
  503. log.debug(f"Compressed audio to {compressed_path}")
  504. if (
  505. os.path.getsize(compressed_path) > MAX_FILE_SIZE
  506. ): # Still larger than MAX_FILE_SIZE after compression
  507. raise Exception(ERROR_MESSAGES.FILE_TOO_LARGE(size=f"{MAX_FILE_SIZE_MB}MB"))
  508. return compressed_path
  509. else:
  510. return file_path
  511. @router.post("/transcriptions")
  512. def transcription(
  513. request: Request,
  514. file: UploadFile = File(...),
  515. user=Depends(get_verified_user),
  516. ):
  517. log.info(f"file.content_type: {file.content_type}")
  518. if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a"]:
  519. raise HTTPException(
  520. status_code=status.HTTP_400_BAD_REQUEST,
  521. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  522. )
  523. try:
  524. ext = file.filename.split(".")[-1]
  525. id = uuid.uuid4()
  526. filename = f"{id}.{ext}"
  527. contents = file.file.read()
  528. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  529. os.makedirs(file_dir, exist_ok=True)
  530. file_path = f"{file_dir}/{filename}"
  531. with open(file_path, "wb") as f:
  532. f.write(contents)
  533. try:
  534. try:
  535. file_path = compress_audio(file_path)
  536. except Exception as e:
  537. log.exception(e)
  538. raise HTTPException(
  539. status_code=status.HTTP_400_BAD_REQUEST,
  540. detail=ERROR_MESSAGES.DEFAULT(e),
  541. )
  542. data = transcribe(request, file_path)
  543. file_path = file_path.split("/")[-1]
  544. return {**data, "filename": file_path}
  545. except Exception as e:
  546. log.exception(e)
  547. raise HTTPException(
  548. status_code=status.HTTP_400_BAD_REQUEST,
  549. detail=ERROR_MESSAGES.DEFAULT(e),
  550. )
  551. except Exception as e:
  552. log.exception(e)
  553. raise HTTPException(
  554. status_code=status.HTTP_400_BAD_REQUEST,
  555. detail=ERROR_MESSAGES.DEFAULT(e),
  556. )
  557. def get_available_models(request: Request) -> list[dict]:
  558. available_models = []
  559. if request.app.state.config.TTS_ENGINE == "openai":
  560. available_models = [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  561. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  562. try:
  563. response = requests.get(
  564. "https://api.elevenlabs.io/v1/models",
  565. headers={
  566. "xi-api-key": request.app.state.config.TTS_API_KEY,
  567. "Content-Type": "application/json",
  568. },
  569. timeout=5,
  570. )
  571. response.raise_for_status()
  572. models = response.json()
  573. available_models = [
  574. {"name": model["name"], "id": model["model_id"]} for model in models
  575. ]
  576. except requests.RequestException as e:
  577. log.error(f"Error fetching voices: {str(e)}")
  578. return available_models
  579. @router.get("/models")
  580. async def get_models(request: Request, user=Depends(get_verified_user)):
  581. return {"models": get_available_models(request)}
  582. def get_available_voices(request) -> dict:
  583. """Returns {voice_id: voice_name} dict"""
  584. available_voices = {}
  585. if request.app.state.config.TTS_ENGINE == "openai":
  586. available_voices = {
  587. "alloy": "alloy",
  588. "echo": "echo",
  589. "fable": "fable",
  590. "onyx": "onyx",
  591. "nova": "nova",
  592. "shimmer": "shimmer",
  593. }
  594. elif request.app.state.config.TTS_ENGINE == "elevenlabs":
  595. try:
  596. available_voices = get_elevenlabs_voices(
  597. api_key=request.app.state.config.TTS_API_KEY
  598. )
  599. except Exception:
  600. # Avoided @lru_cache with exception
  601. pass
  602. elif request.app.state.config.TTS_ENGINE == "azure":
  603. try:
  604. region = request.app.state.config.TTS_AZURE_SPEECH_REGION
  605. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  606. headers = {
  607. "Ocp-Apim-Subscription-Key": request.app.state.config.TTS_API_KEY
  608. }
  609. response = requests.get(url, headers=headers)
  610. response.raise_for_status()
  611. voices = response.json()
  612. for voice in voices:
  613. available_voices[voice["ShortName"]] = (
  614. f"{voice['DisplayName']} ({voice['ShortName']})"
  615. )
  616. except requests.RequestException as e:
  617. log.error(f"Error fetching voices: {str(e)}")
  618. return available_voices
  619. @lru_cache
  620. def get_elevenlabs_voices(api_key: str) -> dict:
  621. """
  622. Note, set the following in your .env file to use Elevenlabs:
  623. AUDIO_TTS_ENGINE=elevenlabs
  624. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  625. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  626. AUDIO_TTS_MODEL=eleven_multilingual_v2
  627. """
  628. try:
  629. # TODO: Add retries
  630. response = requests.get(
  631. "https://api.elevenlabs.io/v1/voices",
  632. headers={
  633. "xi-api-key": api_key,
  634. "Content-Type": "application/json",
  635. },
  636. )
  637. response.raise_for_status()
  638. voices_data = response.json()
  639. voices = {}
  640. for voice in voices_data.get("voices", []):
  641. voices[voice["voice_id"]] = voice["name"]
  642. except requests.RequestException as e:
  643. # Avoid @lru_cache with exception
  644. log.error(f"Error fetching voices: {str(e)}")
  645. raise RuntimeError(f"Error fetching voices: {str(e)}")
  646. return voices
  647. @router.get("/voices")
  648. async def get_voices(request: Request, user=Depends(get_verified_user)):
  649. return {
  650. "voices": [
  651. {"id": k, "name": v} for k, v in get_available_voices(request).items()
  652. ]
  653. }