main.py 5.5 KB

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