main.py 19 KB

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