main.py 2.0 KB

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