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 = form_data.tts.AZURE_SPEECH_OUTPUT_FORMAT
  138. app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
  139. app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
  140. app.state.config.STT_ENGINE = form_data.stt.ENGINE
  141. app.state.config.STT_MODEL = form_data.stt.MODEL
  142. return {
  143. "tts": {
  144. "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
  145. "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
  146. "API_KEY": app.state.config.TTS_API_KEY,
  147. "ENGINE": app.state.config.TTS_ENGINE,
  148. "MODEL": app.state.config.TTS_MODEL,
  149. "VOICE": app.state.config.TTS_VOICE,
  150. "SPLIT_ON": app.state.config.TTS_SPLIT_ON,
  151. "AZURE_SPEECH_REGION": app.state.config.TTS_AZURE_SPEECH_REGION,
  152. "AZURE_SPEECH_OUTPUT_FORMAT": app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
  153. },
  154. "stt": {
  155. "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
  156. "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
  157. "ENGINE": app.state.config.STT_ENGINE,
  158. "MODEL": app.state.config.STT_MODEL,
  159. },
  160. }
  161. @app.post("/speech")
  162. async def speech(request: Request, user=Depends(get_verified_user)):
  163. body = await request.body()
  164. name = hashlib.sha256(body).hexdigest()
  165. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  166. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  167. # Check if the file already exists in the cache
  168. if file_path.is_file():
  169. return FileResponse(file_path)
  170. if app.state.config.TTS_ENGINE == "openai":
  171. headers = {}
  172. headers["Authorization"] = f"Bearer {app.state.config.TTS_OPENAI_API_KEY}"
  173. headers["Content-Type"] = "application/json"
  174. try:
  175. body = body.decode("utf-8")
  176. body = json.loads(body)
  177. body["model"] = app.state.config.TTS_MODEL
  178. body = json.dumps(body).encode("utf-8")
  179. except Exception:
  180. pass
  181. r = None
  182. try:
  183. r = requests.post(
  184. url=f"{app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
  185. data=body,
  186. headers=headers,
  187. stream=True,
  188. )
  189. r.raise_for_status()
  190. # Save the streaming content to a file
  191. with open(file_path, "wb") as f:
  192. for chunk in r.iter_content(chunk_size=8192):
  193. f.write(chunk)
  194. with open(file_body_path, "w") as f:
  195. json.dump(json.loads(body.decode("utf-8")), f)
  196. # Return the saved file
  197. return FileResponse(file_path)
  198. except Exception as e:
  199. log.exception(e)
  200. error_detail = "Open WebUI: Server Connection Error"
  201. if r is not None:
  202. try:
  203. res = r.json()
  204. if "error" in res:
  205. error_detail = f"External: {res['error']['message']}"
  206. except Exception:
  207. error_detail = f"External: {e}"
  208. raise HTTPException(
  209. status_code=r.status_code if r != None else 500,
  210. detail=error_detail,
  211. )
  212. elif app.state.config.TTS_ENGINE == "elevenlabs":
  213. payload = None
  214. try:
  215. payload = json.loads(body.decode("utf-8"))
  216. except Exception as e:
  217. log.exception(e)
  218. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  219. voice_id = payload.get("voice", "")
  220. if voice_id not in get_available_voices():
  221. raise HTTPException(
  222. status_code=400,
  223. detail="Invalid voice id",
  224. )
  225. url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
  226. headers = {
  227. "Accept": "audio/mpeg",
  228. "Content-Type": "application/json",
  229. "xi-api-key": app.state.config.TTS_API_KEY,
  230. }
  231. data = {
  232. "text": payload["input"],
  233. "model_id": app.state.config.TTS_MODEL,
  234. "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
  235. }
  236. try:
  237. r = requests.post(url, json=data, headers=headers)
  238. r.raise_for_status()
  239. # Save the streaming content to a file
  240. with open(file_path, "wb") as f:
  241. for chunk in r.iter_content(chunk_size=8192):
  242. f.write(chunk)
  243. with open(file_body_path, "w") as f:
  244. json.dump(json.loads(body.decode("utf-8")), f)
  245. # Return the saved file
  246. return FileResponse(file_path)
  247. except Exception as e:
  248. log.exception(e)
  249. error_detail = "Open WebUI: Server Connection Error"
  250. if r is not None:
  251. try:
  252. res = r.json()
  253. if "error" in res:
  254. error_detail = f"External: {res['error']['message']}"
  255. except Exception:
  256. error_detail = f"External: {e}"
  257. raise HTTPException(
  258. status_code=r.status_code if r != None else 500,
  259. detail=error_detail,
  260. )
  261. elif app.state.config.TTS_ENGINE == "azurespeechservice":
  262. payload = None
  263. try:
  264. payload = json.loads(body.decode("utf-8"))
  265. except Exception as e:
  266. log.exception(e)
  267. raise HTTPException(status_code=400, detail="Invalid JSON payload")
  268. region = app.state.config.TTS_AZURE_SPEECH_REGION
  269. language = app.state.config.TTS_VOICE
  270. locale = "-".join(app.state.config.TTS_VOICE.split("-")[:1])
  271. output_format = app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
  272. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1"
  273. headers = {
  274. 'Ocp-Apim-Subscription-Key': app.state.config.TTS_API_KEY,
  275. 'Content-Type': 'application/ssml+xml',
  276. 'X-Microsoft-OutputFormat': output_format
  277. }
  278. data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
  279. <voice name="{language}">{payload["input"]}</voice>
  280. </speak>"""
  281. response = requests.post(url, headers=headers, data=data)
  282. if response.status_code == 200:
  283. with open(file_path, "wb") as f:
  284. f.write(response.content)
  285. return FileResponse(file_path)
  286. else:
  287. log.error(f"Error synthesizing speech - {response.reason}")
  288. raise HTTPException(
  289. status_code=500,
  290. detail=f"Error synthesizing speech - {response.reason}")
  291. @app.post("/transcriptions")
  292. def transcribe(
  293. file: UploadFile = File(...),
  294. user=Depends(get_current_user),
  295. ):
  296. log.info(f"file.content_type: {file.content_type}")
  297. if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg"]:
  298. raise HTTPException(
  299. status_code=status.HTTP_400_BAD_REQUEST,
  300. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  301. )
  302. try:
  303. ext = file.filename.split(".")[-1]
  304. id = uuid.uuid4()
  305. filename = f"{id}.{ext}"
  306. file_dir = f"{CACHE_DIR}/audio/transcriptions"
  307. os.makedirs(file_dir, exist_ok=True)
  308. file_path = f"{file_dir}/{filename}"
  309. print(filename)
  310. contents = file.file.read()
  311. with open(file_path, "wb") as f:
  312. f.write(contents)
  313. f.close()
  314. if app.state.config.STT_ENGINE == "":
  315. from faster_whisper import WhisperModel
  316. whisper_kwargs = {
  317. "model_size_or_path": WHISPER_MODEL,
  318. "device": whisper_device_type,
  319. "compute_type": "int8",
  320. "download_root": WHISPER_MODEL_DIR,
  321. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  322. }
  323. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  324. try:
  325. model = WhisperModel(**whisper_kwargs)
  326. except Exception:
  327. log.warning(
  328. "WhisperModel initialization failed, attempting download with local_files_only=False"
  329. )
  330. whisper_kwargs["local_files_only"] = False
  331. model = WhisperModel(**whisper_kwargs)
  332. segments, info = model.transcribe(file_path, beam_size=5)
  333. log.info(
  334. "Detected language '%s' with probability %f"
  335. % (info.language, info.language_probability)
  336. )
  337. transcript = "".join([segment.text for segment in list(segments)])
  338. data = {"text": transcript.strip()}
  339. # save the transcript to a json file
  340. transcript_file = f"{file_dir}/{id}.json"
  341. with open(transcript_file, "w") as f:
  342. json.dump(data, f)
  343. print(data)
  344. return data
  345. elif app.state.config.STT_ENGINE == "openai":
  346. if is_mp4_audio(file_path):
  347. print("is_mp4_audio")
  348. os.rename(file_path, file_path.replace(".wav", ".mp4"))
  349. # Convert MP4 audio file to WAV format
  350. convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
  351. headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
  352. files = {"file": (filename, open(file_path, "rb"))}
  353. data = {"model": app.state.config.STT_MODEL}
  354. print(files, data)
  355. r = None
  356. try:
  357. r = requests.post(
  358. url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
  359. headers=headers,
  360. files=files,
  361. data=data,
  362. )
  363. r.raise_for_status()
  364. data = r.json()
  365. # save the transcript to a json file
  366. transcript_file = f"{file_dir}/{id}.json"
  367. with open(transcript_file, "w") as f:
  368. json.dump(data, f)
  369. print(data)
  370. return data
  371. except Exception as e:
  372. log.exception(e)
  373. error_detail = "Open WebUI: Server Connection Error"
  374. if r is not None:
  375. try:
  376. res = r.json()
  377. if "error" in res:
  378. error_detail = f"External: {res['error']['message']}"
  379. except Exception:
  380. error_detail = f"External: {e}"
  381. raise HTTPException(
  382. status_code=r.status_code if r != None else 500,
  383. detail=error_detail,
  384. )
  385. except Exception as e:
  386. log.exception(e)
  387. raise HTTPException(
  388. status_code=status.HTTP_400_BAD_REQUEST,
  389. detail=ERROR_MESSAGES.DEFAULT(e),
  390. )
  391. def get_available_models() -> list[dict]:
  392. if app.state.config.TTS_ENGINE == "openai":
  393. return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
  394. elif app.state.config.TTS_ENGINE == "elevenlabs":
  395. headers = {
  396. "xi-api-key": app.state.config.TTS_API_KEY,
  397. "Content-Type": "application/json",
  398. }
  399. try:
  400. response = requests.get(
  401. "https://api.elevenlabs.io/v1/models", headers=headers, timeout=5
  402. )
  403. response.raise_for_status()
  404. models = response.json()
  405. return [
  406. {"name": model["name"], "id": model["model_id"]} for model in models
  407. ]
  408. except requests.RequestException as e:
  409. log.error(f"Error fetching voices: {str(e)}")
  410. return []
  411. @app.get("/models")
  412. async def get_models(user=Depends(get_verified_user)):
  413. return {"models": get_available_models()}
  414. def get_available_voices() -> dict:
  415. """Returns {voice_id: voice_name} dict"""
  416. ret = {}
  417. if app.state.config.TTS_ENGINE == "openai":
  418. ret = {
  419. "alloy": "alloy",
  420. "echo": "echo",
  421. "fable": "fable",
  422. "onyx": "onyx",
  423. "nova": "nova",
  424. "shimmer": "shimmer",
  425. }
  426. elif app.state.config.TTS_ENGINE == "elevenlabs":
  427. try:
  428. ret = get_elevenlabs_voices()
  429. except Exception:
  430. # Avoided @lru_cache with exception
  431. pass
  432. elif app.state.config.TTS_ENGINE == "azurespeechservice":
  433. try:
  434. region = app.state.config.TTS_AZURE_SPEECH_REGION
  435. url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
  436. headers = {
  437. 'Ocp-Apim-Subscription-Key': app.state.config.TTS_API_KEY
  438. }
  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']] = f"{voice['DisplayName']} ({voice['ShortName']})"
  444. except requests.RequestException as e:
  445. log.error(f"Error fetching voices: {str(e)}")
  446. return ret
  447. @lru_cache
  448. def get_elevenlabs_voices() -> dict:
  449. """
  450. Note, set the following in your .env file to use Elevenlabs:
  451. AUDIO_TTS_ENGINE=elevenlabs
  452. AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
  453. AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
  454. AUDIO_TTS_MODEL=eleven_multilingual_v2
  455. """
  456. headers = {
  457. "xi-api-key": app.state.config.TTS_API_KEY,
  458. "Content-Type": "application/json",
  459. }
  460. try:
  461. # TODO: Add retries
  462. response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
  463. response.raise_for_status()
  464. voices_data = response.json()
  465. voices = {}
  466. for voice in voices_data.get("voices", []):
  467. voices[voice["voice_id"]] = voice["name"]
  468. except requests.RequestException as e:
  469. # Avoid @lru_cache with exception
  470. log.error(f"Error fetching voices: {str(e)}")
  471. raise RuntimeError(f"Error fetching voices: {str(e)}")
  472. return voices
  473. @app.get("/voices")
  474. async def get_voices(user=Depends(get_verified_user)):
  475. return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}