main.py 6.6 KB

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