main.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import os
  2. import logging
  3. from fastapi import (
  4. FastAPI,
  5. Request,
  6. Depends,
  7. HTTPException,
  8. status,
  9. UploadFile,
  10. File,
  11. Form,
  12. )
  13. from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
  14. from fastapi.middleware.cors import CORSMiddleware
  15. from faster_whisper import WhisperModel
  16. from pydantic import BaseModel
  17. import requests
  18. import hashlib
  19. from pathlib import Path
  20. import json
  21. from constants import ERROR_MESSAGES
  22. from utils.utils import (
  23. decode_token,
  24. get_current_user,
  25. get_verified_user,
  26. get_admin_user,
  27. )
  28. from utils.misc import calculate_sha256
  29. from config import (
  30. SRC_LOG_LEVELS,
  31. CACHE_DIR,
  32. UPLOAD_DIR,
  33. WHISPER_MODEL,
  34. WHISPER_MODEL_DIR,
  35. WHISPER_MODEL_AUTO_UPDATE,
  36. DEVICE_TYPE,
  37. AUDIO_OPENAI_API_BASE_URL,
  38. AUDIO_OPENAI_API_KEY,
  39. AUDIO_OPENAI_API_MODEL,
  40. AUDIO_OPENAI_API_SPEAKER
  41. )
  42. log = logging.getLogger(__name__)
  43. log.setLevel(SRC_LOG_LEVELS["AUDIO"])
  44. app = FastAPI()
  45. app.add_middleware(
  46. CORSMiddleware,
  47. allow_origins=["*"],
  48. allow_credentials=True,
  49. allow_methods=["*"],
  50. allow_headers=["*"],
  51. )
  52. app.state.OPENAI_API_BASE_URL = AUDIO_OPENAI_API_BASE_URL
  53. app.state.OPENAI_API_KEY = AUDIO_OPENAI_API_KEY
  54. app.state.OPENAI_API_MODEL = AUDIO_OPENAI_API_MODEL
  55. app.state.OPENAI_API_SPEAKER = AUDIO_OPENAI_API_SPEAKER
  56. # setting device type for whisper model
  57. whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
  58. log.info(f"whisper_device_type: {whisper_device_type}")
  59. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  60. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  61. class OpenAIConfigUpdateForm(BaseModel):
  62. url: str
  63. key: str
  64. model: str
  65. speaker: str
  66. @app.get("/config")
  67. async def get_openai_config(user=Depends(get_admin_user)):
  68. return {
  69. "OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
  70. "OPENAI_API_KEY": app.state.OPENAI_API_KEY,
  71. "OPENAI_API_MODEL": app.state.OPENAI_API_MODEL,
  72. "OPENAI_API_SPEAKER": app.state.OPENAI_API_SPEAKER
  73. }
  74. @app.post("/config/update")
  75. async def update_openai_config(
  76. form_data: OpenAIConfigUpdateForm, user=Depends(get_admin_user)
  77. ):
  78. if form_data.key == "":
  79. raise HTTPException(status_code=400, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
  80. app.state.OPENAI_API_BASE_URL = form_data.url
  81. app.state.OPENAI_API_KEY = form_data.key
  82. app.state.OPENAI_API_MODEL = form_data.model
  83. app.state.OPENAI_API_SPEAKER = form_data.speaker
  84. return {
  85. "status": True,
  86. "OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
  87. "OPENAI_API_KEY": app.state.OPENAI_API_KEY,
  88. "OPENAI_API_MODEL": app.state.OPENAI_API_MODEL,
  89. "OPENAI_API_SPEAKER": app.state.OPENAI_API_SPEAKER,
  90. }
  91. @app.post("/speech")
  92. async def speech(request: Request, user=Depends(get_verified_user)):
  93. body = await request.body()
  94. name = hashlib.sha256(body).hexdigest()
  95. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  96. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  97. # Check if the file already exists in the cache
  98. if file_path.is_file():
  99. return FileResponse(file_path)
  100. headers = {}
  101. headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
  102. headers["Content-Type"] = "application/json"
  103. r = None
  104. try:
  105. r = requests.post(
  106. url=f"{app.state.OPENAI_API_BASE_URL}/audio/speech",
  107. data=body,
  108. headers=headers,
  109. stream=True,
  110. )
  111. r.raise_for_status()
  112. # Save the streaming content to a file
  113. with open(file_path, "wb") as f:
  114. for chunk in r.iter_content(chunk_size=8192):
  115. f.write(chunk)
  116. with open(file_body_path, "w") as f:
  117. json.dump(json.loads(body.decode("utf-8")), f)
  118. # Return the saved file
  119. return FileResponse(file_path)
  120. except Exception as e:
  121. log.exception(e)
  122. error_detail = "Open WebUI: Server Connection Error"
  123. if r is not None:
  124. try:
  125. res = r.json()
  126. if "error" in res:
  127. error_detail = f"External: {res['error']['message']}"
  128. except:
  129. error_detail = f"External: {e}"
  130. raise HTTPException(
  131. status_code=r.status_code if r != None else 500,
  132. detail=error_detail,
  133. )
  134. @app.post("/transcriptions")
  135. def transcribe(
  136. file: UploadFile = File(...),
  137. user=Depends(get_current_user),
  138. ):
  139. log.info(f"file.content_type: {file.content_type}")
  140. if file.content_type not in ["audio/mpeg", "audio/wav"]:
  141. raise HTTPException(
  142. status_code=status.HTTP_400_BAD_REQUEST,
  143. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  144. )
  145. try:
  146. filename = file.filename
  147. file_path = f"{UPLOAD_DIR}/{filename}"
  148. contents = file.file.read()
  149. with open(file_path, "wb") as f:
  150. f.write(contents)
  151. f.close()
  152. whisper_kwargs = {
  153. "model_size_or_path": WHISPER_MODEL,
  154. "device": whisper_device_type,
  155. "compute_type": "int8",
  156. "download_root": WHISPER_MODEL_DIR,
  157. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  158. }
  159. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  160. try:
  161. model = WhisperModel(**whisper_kwargs)
  162. except:
  163. log.warning(
  164. "WhisperModel initialization failed, attempting download with local_files_only=False"
  165. )
  166. whisper_kwargs["local_files_only"] = False
  167. model = WhisperModel(**whisper_kwargs)
  168. segments, info = model.transcribe(file_path, beam_size=5)
  169. log.info(
  170. "Detected language '%s' with probability %f"
  171. % (info.language, info.language_probability)
  172. )
  173. transcript = "".join([segment.text for segment in list(segments)])
  174. return {"text": transcript.strip()}
  175. except Exception as e:
  176. log.exception(e)
  177. raise HTTPException(
  178. status_code=status.HTTP_400_BAD_REQUEST,
  179. detail=ERROR_MESSAGES.DEFAULT(e),
  180. )