main.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from fastapi import (
  2. FastAPI,
  3. Request,
  4. Depends,
  5. HTTPException,
  6. status,
  7. UploadFile,
  8. File,
  9. Form,
  10. )
  11. from fastapi.middleware.cors import CORSMiddleware
  12. from faster_whisper import WhisperModel
  13. from constants import ERROR_MESSAGES
  14. from utils.utils import (
  15. decode_token,
  16. get_current_user,
  17. get_verified_user,
  18. get_admin_user,
  19. )
  20. from utils.misc import calculate_sha256
  21. from config import CACHE_DIR, UPLOAD_DIR, WHISPER_MODEL_NAME
  22. app = FastAPI()
  23. app.add_middleware(
  24. CORSMiddleware,
  25. allow_origins=["*"],
  26. allow_credentials=True,
  27. allow_methods=["*"],
  28. allow_headers=["*"],
  29. )
  30. @app.post("/transcribe")
  31. def transcribe(
  32. file: UploadFile = File(...),
  33. user=Depends(get_current_user),
  34. ):
  35. print(file.content_type)
  36. if file.content_type not in ["audio/mpeg", "audio/wav"]:
  37. raise HTTPException(
  38. status_code=status.HTTP_400_BAD_REQUEST,
  39. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  40. )
  41. try:
  42. filename = file.filename
  43. file_path = f"{UPLOAD_DIR}/{filename}"
  44. contents = file.file.read()
  45. with open(file_path, "wb") as f:
  46. f.write(contents)
  47. f.close()
  48. model_name = WHISPER_MODEL_NAME
  49. model = WhisperModel(
  50. model_name,
  51. device="cpu",
  52. compute_type="int8",
  53. download_root=f"{CACHE_DIR}/whisper/models",
  54. )
  55. segments, info = model.transcribe(file_path, beam_size=5)
  56. print(
  57. "Detected language '%s' with probability %f"
  58. % (info.language, info.language_probability)
  59. )
  60. transcript = "".join([segment.text for segment in list(segments)])
  61. return {"text": transcript}
  62. except Exception as e:
  63. print(e)
  64. raise HTTPException(
  65. status_code=status.HTTP_400_BAD_REQUEST,
  66. detail=ERROR_MESSAGES.DEFAULT(e),
  67. )