main.py 16 KB

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