main.py 18 KB

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