main.py 5.0 KB

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