main.py 16 KB

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