main.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. idx = None
  82. try:
  83. body = await request.body()
  84. name = hashlib.sha256(body).hexdigest()
  85. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  86. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  87. # Check if the file already exists in the cache
  88. if file_path.is_file():
  89. return FileResponse(file_path)
  90. headers = {}
  91. headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
  92. headers["Content-Type"] = "application/json"
  93. r = None
  94. try:
  95. r = requests.post(
  96. url=f"{app.state.OPENAI_API_BASE_URL}/audio/speech",
  97. data=body,
  98. headers=headers,
  99. stream=True,
  100. )
  101. r.raise_for_status()
  102. # Save the streaming content to a file
  103. with open(file_path, "wb") as f:
  104. for chunk in r.iter_content(chunk_size=8192):
  105. f.write(chunk)
  106. with open(file_body_path, "w") as f:
  107. json.dump(json.loads(body.decode("utf-8")), f)
  108. # Return the saved file
  109. return FileResponse(file_path)
  110. except Exception as e:
  111. log.exception(e)
  112. error_detail = "Open WebUI: Server Connection Error"
  113. if r is not None:
  114. try:
  115. res = r.json()
  116. if "error" in res:
  117. error_detail = f"External: {res['error']}"
  118. except:
  119. error_detail = f"External: {e}"
  120. raise HTTPException(
  121. status_code=r.status_code if r else 500, detail=error_detail
  122. )
  123. except ValueError:
  124. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  125. @app.post("/transcriptions")
  126. def transcribe(
  127. file: UploadFile = File(...),
  128. user=Depends(get_current_user),
  129. ):
  130. log.info(f"file.content_type: {file.content_type}")
  131. if file.content_type not in ["audio/mpeg", "audio/wav"]:
  132. raise HTTPException(
  133. status_code=status.HTTP_400_BAD_REQUEST,
  134. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  135. )
  136. try:
  137. filename = file.filename
  138. file_path = f"{UPLOAD_DIR}/{filename}"
  139. contents = file.file.read()
  140. with open(file_path, "wb") as f:
  141. f.write(contents)
  142. f.close()
  143. whisper_kwargs = {
  144. "model_size_or_path": WHISPER_MODEL,
  145. "device": whisper_device_type,
  146. "compute_type": "int8",
  147. "download_root": WHISPER_MODEL_DIR,
  148. "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
  149. }
  150. log.debug(f"whisper_kwargs: {whisper_kwargs}")
  151. try:
  152. model = WhisperModel(**whisper_kwargs)
  153. except:
  154. log.warning(
  155. "WhisperModel initialization failed, attempting download with local_files_only=False"
  156. )
  157. whisper_kwargs["local_files_only"] = False
  158. model = WhisperModel(**whisper_kwargs)
  159. segments, info = model.transcribe(file_path, beam_size=5)
  160. log.info(
  161. "Detected language '%s' with probability %f"
  162. % (info.language, info.language_probability)
  163. )
  164. transcript = "".join([segment.text for segment in list(segments)])
  165. return {"text": transcript.strip()}
  166. except Exception as e:
  167. log.exception(e)
  168. raise HTTPException(
  169. status_code=status.HTTP_400_BAD_REQUEST,
  170. detail=ERROR_MESSAGES.DEFAULT(e),
  171. )