main.py 16 KB

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