main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. elif app.state.config.TTS_ENGINE == "azurespeechservice":
  250. payload = None
  251. try:
  252. payload = json.loads(body.decode("utf-8"))
  253. except Exception as e:
  254. log.exception(e)
  255. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  256. import azure.cognitiveservices.speech as speechsdk
  257. config = speechsdk.SpeechConfig(subscription=app.state.config.TTS_API_KEY, region="uksouth")
  258. speaker_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=False, filename=str(file_path))
  259. client = speechsdk.SpeechSynthesizer(speech_config=config, audio_config=speaker_config)
  260. result = client.speak_text(payload["input"])
  261. if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
  262. return FileResponse(file_path)
  263. else:
  264. raise HTTPException(
  265. status_code=500,
  266. detail=f"Error synthesizing speech - {result.reason}")
  267. @app.post("/transcriptions")
  268. def transcribe(
  269. file: UploadFile = File(...),
  270. user=Depends(get_current_user),
  271. ):
  272. log.info(f"file.content_type: {file.content_type}")
  273. if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg"]:
  274. raise HTTPException(
  275. status_code=status.HTTP_400_BAD_REQUEST,
  276. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  277. )
  278. try:
  279. ext = file.filename.split(".")[-1]
  280. id = uuid.uuid4()
  281. filename = f"{id}.{ext}"
  282. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  283. os.makedirs(file_dir, exist_ok=True)
  284. file_path = f"{file_dir}/{filename}"
  285. print(filename)
  286. contents = file.file.read()
  287. with open(file_path, "wb") as f:
  288. f.write(contents)
  289. f.close()
  290. if app.state.config.STT_ENGINE == "":
  291. from faster_whisper import WhisperModel
  292. whisper_kwargs = {
  293. "model_size_or_path": WHISPER_MODEL,
  294. "device": whisper_device_type,
  295. "compute_type": "int8",
  296. "download_root": WHISPER_MODEL_DIR,
  297. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  298. }
  299. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  300. try:
  301. model = WhisperModel(**whisper_kwargs)
  302. except Exception:
  303. log.warning(
  304. "WhisperModel initialization failed, attempting download with local_files_only=False"
  305. )
  306. whisper_kwargs["local_files_only"] = False
  307. model = WhisperModel(**whisper_kwargs)
  308. segments, info = model.transcribe(file_path, beam_size=5)
  309. log.info(
  310. "Detected language '%s' with probability %f"
  311. % (info.language, info.language_probability)
  312. )
  313. transcript = "".join([segment.text for segment in list(segments)])
  314. data = {"text": transcript.strip()}
  315. # save the transcript to a json file
  316. transcript_file = f"{file_dir}/{id}.json"
  317. with open(transcript_file, "w") as f:
  318. json.dump(data, f)
  319. print(data)
  320. return data
  321. elif app.state.config.STT_ENGINE == "openai":
  322. if is_mp4_audio(file_path):
  323. print("is_mp4_audio")
  324. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  325. # Convert MP4 audio file to WAV format
  326. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  327. headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
  328. files = {"file": (filename, open(file_path, "rb"))}
  329. data = {"model": app.state.config.STT_MODEL}
  330. print(files, data)
  331. r = None
  332. try:
  333. r = requests.post(
  334. url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  335. headers=headers,
  336. files=files,
  337. data=data,
  338. )
  339. r.raise_for_status()
  340. data = r.json()
  341. # save the transcript to a json file
  342. transcript_file = f"{file_dir}/{id}.json"
  343. with open(transcript_file, "w") as f:
  344. json.dump(data, f)
  345. print(data)
  346. return data
  347. except Exception as e:
  348. log.exception(e)
  349. error_detail = "Open WebUI: Server Connection Error"
  350. if r is not None:
  351. try:
  352. res = r.json()
  353. if "error" in res:
  354. error_detail = f"External: {res['error']['message']}"
  355. except Exception:
  356. error_detail = f"External: {e}"
  357. raise HTTPException(
  358. status_code=r.status_code if r != None else 500,
  359. detail=error_detail,
  360. )
  361. except Exception as e:
  362. log.exception(e)
  363. raise HTTPException(
  364. status_code=status.HTTP_400_BAD_REQUEST,
  365. detail=ERROR_MESSAGES.DEFAULT(e),
  366. )
  367. def get_available_models() -> list[dict]:
  368. if app.state.config.TTS_ENGINE == "openai":
  369. return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  370. elif app.state.config.TTS_ENGINE == "elevenlabs":
  371. headers = {
  372. "xi-api-key": app.state.config.TTS_API_KEY,
  373. "Content-Type": "application/json",
  374. }
  375. try:
  376. response = requests.get(
  377. "https://api.elevenlabs.io/v1/models", headers=headers, timeout=5
  378. )
  379. response.raise_for_status()
  380. models = response.json()
  381. return [
  382. {"name": model["name"], "id": model["model_id"]} for model in models
  383. ]
  384. except requests.RequestException as e:
  385. log.error(f"Error fetching voices: {str(e)}")
  386. return []
  387. @app.get("/models")
  388. async def get_models(user=Depends(get_verified_user)):
  389. return {"models": get_available_models()}
  390. def get_available_voices() -> dict:
  391. """Returns {voice_id: voice_name} dict"""
  392. ret = {}
  393. if app.state.config.TTS_ENGINE == "openai":
  394. ret = {
  395. "alloy": "alloy",
  396. "echo": "echo",
  397. "fable": "fable",
  398. "onyx": "onyx",
  399. "nova": "nova",
  400. "shimmer": "shimmer",
  401. }
  402. elif app.state.config.TTS_ENGINE == "elevenlabs":
  403. try:
  404. ret = get_elevenlabs_voices()
  405. except Exception:
  406. # Avoided @lru_cache with exception
  407. pass
  408. return ret
  409. @lru_cache
  410. def get_elevenlabs_voices() -> dict:
  411. """
  412. Note, set the following in your .env file to use Elevenlabs:
  413. AUDIO_TTS_ENGINE=elevenlabs
  414. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  415. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  416. AUDIO_TTS_MODEL=eleven_multilingual_v2
  417. """
  418. headers = {
  419. "xi-api-key": app.state.config.TTS_API_KEY,
  420. "Content-Type": "application/json",
  421. }
  422. try:
  423. # TODO: Add retries
  424. response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
  425. response.raise_for_status()
  426. voices_data = response.json()
  427. voices = {}
  428. for voice in voices_data.get("voices", []):
  429. voices[voice["voice_id"]] = voice["name"]
  430. except requests.RequestException as e:
  431. # Avoid @lru_cache with exception
  432. log.error(f"Error fetching voices: {str(e)}")
  433. raise RuntimeError(f"Error fetching voices: {str(e)}")
  434. return voices
  435. @app.get("/voices")
  436. async def get_voices(user=Depends(get_verified_user)):
  437. return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}