main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. import requests
  9. from open_webui.config import (
  10. AUDIO_STT_ENGINE,
  11. AUDIO_STT_MODEL,
  12. AUDIO_STT_OPENAI_API_BASE_URL,
  13. AUDIO_STT_OPENAI_API_KEY,
  14. AUDIO_TTS_API_KEY,
  15. AUDIO_TTS_ENGINE,
  16. AUDIO_TTS_MODEL,
  17. AUDIO_TTS_OPENAI_API_BASE_URL,
  18. AUDIO_TTS_OPENAI_API_KEY,
  19. AUDIO_TTS_SPLIT_ON,
  20. AUDIO_TTS_VOICE,
  21. CACHE_DIR,
  22. CORS_ALLOW_ORIGIN,
  23. WHISPER_MODEL,
  24. WHISPER_MODEL_AUTO_UPDATE,
  25. WHISPER_MODEL_DIR,
  26. AppConfig,
  27. )
  28. from open_webui.constants import ERROR_MESSAGES
  29. from open_webui.env import SRC_LOG_LEVELS, DEVICE_TYPE
  30. from fastapi import Depends, FastAPI, File, HTTPException, Request, UploadFile, status
  31. from fastapi.middleware.cors import CORSMiddleware
  32. from fastapi.responses import FileResponse
  33. from pydantic import BaseModel
  34. from open_webui.utils.utils import get_admin_user, get_current_user, get_verified_user
  35. log = logging.getLogger(__name__)
  36. log.setLevel(SRC_LOG_LEVELS["AUDIO"])
  37. app = FastAPI()
  38. app.add_middleware(
  39. CORSMiddleware,
  40. allow_origins=CORS_ALLOW_ORIGIN,
  41. allow_credentials=True,
  42. allow_methods=["*"],
  43. allow_headers=["*"],
  44. )
  45. app.state.config = AppConfig()
  46. app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
  47. app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
  48. app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
  49. app.state.config.STT_MODEL = AUDIO_STT_MODEL
  50. app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
  51. app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
  52. app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
  53. app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
  54. app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
  55. app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
  56. app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
  57. # setting device type for whisper model
  58. whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
  59. log.info(f"whisper_device_type: {whisper_device_type}")
  60. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  61. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  62. class TTSConfigForm(BaseModel):
  63. OPENAI_API_BASE_URL: str
  64. OPENAI_API_KEY: str
  65. API_KEY: str
  66. ENGINE: str
  67. MODEL: str
  68. VOICE: str
  69. SPLIT_ON: str
  70. class STTConfigForm(BaseModel):
  71. OPENAI_API_BASE_URL: str
  72. OPENAI_API_KEY: str
  73. ENGINE: str
  74. MODEL: str
  75. class AudioConfigUpdateForm(BaseModel):
  76. tts: TTSConfigForm
  77. stt: STTConfigForm
  78. from pydub import AudioSegment
  79. from pydub.utils import mediainfo
  80. def is_mp4_audio(file_path):
  81. """Check if the given file is an MP4 audio file."""
  82. if not os.path.isfile(file_path):
  83. print(f"File not found: {file_path}")
  84. return False
  85. info = mediainfo(file_path)
  86. if (
  87. info.get("codec_name") == "aac"
  88. and info.get("codec_type") == "audio"
  89. and info.get("codec_tag_string") == "mp4a"
  90. ):
  91. return True
  92. return False
  93. def convert_mp4_to_wav(file_path, output_path):
  94. """Convert MP4 audio file to WAV format."""
  95. audio = AudioSegment.from_file(file_path, format="mp4")
  96. audio.export(output_path, format="wav")
  97. print(f"Converted {file_path} to {output_path}")
  98. @app.get("/config")
  99. async def get_audio_config(user=Depends(get_admin_user)):
  100. return {
  101. "tts": {
  102. "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
  103. "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
  104. "API_KEY": app.state.config.TTS_API_KEY,
  105. "ENGINE": app.state.config.TTS_ENGINE,
  106. "MODEL": app.state.config.TTS_MODEL,
  107. "VOICE": app.state.config.TTS_VOICE,
  108. "SPLIT_ON": app.state.config.TTS_SPLIT_ON,
  109. },
  110. "stt": {
  111. "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
  112. "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
  113. "ENGINE": app.state.config.STT_ENGINE,
  114. "MODEL": app.state.config.STT_MODEL,
  115. },
  116. }
  117. @app.post("/config/update")
  118. async def update_audio_config(
  119. form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)
  120. ):
  121. app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL
  122. app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY
  123. app.state.config.TTS_API_KEY = form_data.tts.API_KEY
  124. app.state.config.TTS_ENGINE = form_data.tts.ENGINE
  125. app.state.config.TTS_MODEL = form_data.tts.MODEL
  126. app.state.config.TTS_VOICE = form_data.tts.VOICE
  127. app.state.config.TTS_SPLIT_ON = form_data.tts.SPLIT_ON
  128. app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
  129. app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
  130. app.state.config.STT_ENGINE = form_data.stt.ENGINE
  131. app.state.config.STT_MODEL = form_data.stt.MODEL
  132. return {
  133. "tts": {
  134. "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
  135. "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
  136. "API_KEY": app.state.config.TTS_API_KEY,
  137. "ENGINE": app.state.config.TTS_ENGINE,
  138. "MODEL": app.state.config.TTS_MODEL,
  139. "VOICE": app.state.config.TTS_VOICE,
  140. "SPLIT_ON": app.state.config.TTS_SPLIT_ON,
  141. },
  142. "stt": {
  143. "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
  144. "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
  145. "ENGINE": app.state.config.STT_ENGINE,
  146. "MODEL": app.state.config.STT_MODEL,
  147. },
  148. }
  149. @app.post("/speech")
  150. async def speech(request: Request, user=Depends(get_verified_user)):
  151. body = await request.body()
  152. name = hashlib.sha256(body).hexdigest()
  153. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  154. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  155. # Check if the file already exists in the cache
  156. if file_path.is_file():
  157. return FileResponse(file_path)
  158. if app.state.config.TTS_ENGINE == "openai":
  159. headers = {}
  160. headers["Authorization"] = f"Bearer {app.state.config.TTS_OPENAI_API_KEY}"
  161. headers["Content-Type"] = "application/json"
  162. try:
  163. body = body.decode("utf-8")
  164. body = json.loads(body)
  165. body["model"] = app.state.config.TTS_MODEL
  166. body = json.dumps(body).encode("utf-8")
  167. except Exception:
  168. pass
  169. r = None
  170. try:
  171. r = requests.post(
  172. url=f"{app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  173. data=body,
  174. headers=headers,
  175. stream=True,
  176. )
  177. r.raise_for_status()
  178. # Save the streaming content to a file
  179. with open(file_path, "wb") as f:
  180. for chunk in r.iter_content(chunk_size=8192):
  181. f.write(chunk)
  182. with open(file_body_path, "w") as f:
  183. json.dump(json.loads(body.decode("utf-8")), f)
  184. # Return the saved file
  185. return FileResponse(file_path)
  186. except Exception as e:
  187. log.exception(e)
  188. error_detail = "Open WebUI: Server Connection Error"
  189. if r is not None:
  190. try:
  191. res = r.json()
  192. if "error" in res:
  193. error_detail = f"External: {res['error']['message']}"
  194. except Exception:
  195. error_detail = f"External: {e}"
  196. raise HTTPException(
  197. status_code=r.status_code if r != None else 500,
  198. detail=error_detail,
  199. )
  200. elif app.state.config.TTS_ENGINE == "elevenlabs":
  201. payload = None
  202. try:
  203. payload = json.loads(body.decode("utf-8"))
  204. except Exception as e:
  205. log.exception(e)
  206. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  207. voice_id = payload.get("voice", "")
  208. if voice_id not in get_available_voices():
  209. raise HTTPException(
  210. status_code=400,
  211. detail="Invalid voice id",
  212. )
  213. url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
  214. headers = {
  215. "Accept": "audio/mpeg",
  216. "Content-Type": "application/json",
  217. "xi-api-key": app.state.config.TTS_API_KEY,
  218. }
  219. data = {
  220. "text": payload["input"],
  221. "model_id": app.state.config.TTS_MODEL,
  222. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  223. }
  224. try:
  225. r = requests.post(url, json=data, headers=headers)
  226. r.raise_for_status()
  227. # Save the streaming content to a file
  228. with open(file_path, "wb") as f:
  229. for chunk in r.iter_content(chunk_size=8192):
  230. f.write(chunk)
  231. with open(file_body_path, "w") as f:
  232. json.dump(json.loads(body.decode("utf-8")), f)
  233. # Return the saved file
  234. return FileResponse(file_path)
  235. except Exception as e:
  236. log.exception(e)
  237. error_detail = "Open WebUI: Server Connection Error"
  238. if r is not None:
  239. try:
  240. res = r.json()
  241. if "error" in res:
  242. error_detail = f"External: {res['error']['message']}"
  243. except Exception:
  244. error_detail = f"External: {e}"
  245. raise HTTPException(
  246. status_code=r.status_code if r != None else 500,
  247. detail=error_detail,
  248. )
  249. @app.post("/transcriptions")
  250. def transcribe(
  251. file: UploadFile = File(...),
  252. user=Depends(get_current_user),
  253. ):
  254. log.info(f"file.content_type: {file.content_type}")
  255. if file.content_type not in ["audio/mpeg", "audio/wav"]:
  256. raise HTTPException(
  257. status_code=status.HTTP_400_BAD_REQUEST,
  258. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  259. )
  260. try:
  261. ext = file.filename.split(".")[-1]
  262. id = uuid.uuid4()
  263. filename = f"{id}.{ext}"
  264. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  265. os.makedirs(file_dir, exist_ok=True)
  266. file_path = f"{file_dir}/{filename}"
  267. print(filename)
  268. contents = file.file.read()
  269. with open(file_path, "wb") as f:
  270. f.write(contents)
  271. f.close()
  272. if app.state.config.STT_ENGINE == "":
  273. from faster_whisper import WhisperModel
  274. whisper_kwargs = {
  275. "model_size_or_path": WHISPER_MODEL,
  276. "device": whisper_device_type,
  277. "compute_type": "int8",
  278. "download_root": WHISPER_MODEL_DIR,
  279. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  280. }
  281. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  282. try:
  283. model = WhisperModel(**whisper_kwargs)
  284. except Exception:
  285. log.warning(
  286. "WhisperModel initialization failed, attempting download with local_files_only=False"
  287. )
  288. whisper_kwargs["local_files_only"] = False
  289. model = WhisperModel(**whisper_kwargs)
  290. segments, info = model.transcribe(file_path, beam_size=5)
  291. log.info(
  292. "Detected language '%s' with probability %f"
  293. % (info.language, info.language_probability)
  294. )
  295. transcript = "".join([segment.text for segment in list(segments)])
  296. data = {"text": transcript.strip()}
  297. # save the transcript to a json file
  298. transcript_file = f"{file_dir}/{id}.json"
  299. with open(transcript_file, "w") as f:
  300. json.dump(data, f)
  301. print(data)
  302. return data
  303. elif app.state.config.STT_ENGINE == "openai":
  304. if is_mp4_audio(file_path):
  305. print("is_mp4_audio")
  306. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  307. # Convert MP4 audio file to WAV format
  308. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  309. headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
  310. files = {"file": (filename, open(file_path, "rb"))}
  311. data = {"model": app.state.config.STT_MODEL}
  312. print(files, data)
  313. r = None
  314. try:
  315. r = requests.post(
  316. url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  317. headers=headers,
  318. files=files,
  319. data=data,
  320. )
  321. r.raise_for_status()
  322. data = r.json()
  323. # save the transcript to a json file
  324. transcript_file = f"{file_dir}/{id}.json"
  325. with open(transcript_file, "w") as f:
  326. json.dump(data, f)
  327. print(data)
  328. return data
  329. except Exception as e:
  330. log.exception(e)
  331. error_detail = "Open WebUI: Server Connection Error"
  332. if r is not None:
  333. try:
  334. res = r.json()
  335. if "error" in res:
  336. error_detail = f"External: {res['error']['message']}"
  337. except Exception:
  338. error_detail = f"External: {e}"
  339. raise HTTPException(
  340. status_code=r.status_code if r != None else 500,
  341. detail=error_detail,
  342. )
  343. except Exception as e:
  344. log.exception(e)
  345. raise HTTPException(
  346. status_code=status.HTTP_400_BAD_REQUEST,
  347. detail=ERROR_MESSAGES.DEFAULT(e),
  348. )
  349. def get_available_models() -> list[dict]:
  350. if app.state.config.TTS_ENGINE == "openai":
  351. return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  352. elif app.state.config.TTS_ENGINE == "elevenlabs":
  353. headers = {
  354. "xi-api-key": app.state.config.TTS_API_KEY,
  355. "Content-Type": "application/json",
  356. }
  357. try:
  358. response = requests.get(
  359. "https://api.elevenlabs.io/v1/models", headers=headers, timeout=5
  360. )
  361. response.raise_for_status()
  362. models = response.json()
  363. return [
  364. {"name": model["name"], "id": model["model_id"]} for model in models
  365. ]
  366. except requests.RequestException as e:
  367. log.error(f"Error fetching voices: {str(e)}")
  368. return []
  369. @app.get("/models")
  370. async def get_models(user=Depends(get_verified_user)):
  371. return {"models": get_available_models()}
  372. def get_available_voices() -> dict:
  373. """Returns {voice_id: voice_name} dict"""
  374. ret = {}
  375. if app.state.config.TTS_ENGINE == "openai":
  376. ret = {
  377. "alloy": "alloy",
  378. "echo": "echo",
  379. "fable": "fable",
  380. "onyx": "onyx",
  381. "nova": "nova",
  382. "shimmer": "shimmer",
  383. }
  384. elif app.state.config.TTS_ENGINE == "elevenlabs":
  385. try:
  386. ret = get_elevenlabs_voices()
  387. except Exception:
  388. # Avoided @lru_cache with exception
  389. pass
  390. return ret
  391. @lru_cache
  392. def get_elevenlabs_voices() -> dict:
  393. """
  394. Note, set the following in your .env file to use Elevenlabs:
  395. AUDIO_TTS_ENGINE=elevenlabs
  396. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  397. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  398. AUDIO_TTS_MODEL=eleven_multilingual_v2
  399. """
  400. headers = {
  401. "xi-api-key": app.state.config.TTS_API_KEY,
  402. "Content-Type": "application/json",
  403. }
  404. try:
  405. # TODO: Add retries
  406. response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
  407. response.raise_for_status()
  408. voices_data = response.json()
  409. voices = {}
  410. for voice in voices_data.get("voices", []):
  411. voices[voice["voice_id"]] = voice["name"]
  412. except requests.RequestException as e:
  413. # Avoid @lru_cache with exception
  414. log.error(f"Error fetching voices: {str(e)}")
  415. raise RuntimeError(f"Error fetching voices: {str(e)}")
  416. return voices
  417. @app.get("/voices")
  418. async def get_voices(user=Depends(get_verified_user)):
  419. return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}