audio_service.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import io
  2. from typing import Optional
  3. from core.model_manager import ModelManager
  4. from core.model_runtime.entities.model_entities import ModelType
  5. from services.errors.audio import (AudioTooLargeServiceError, NoAudioUploadedServiceError,
  6. ProviderNotSupportSpeechToTextServiceError,
  7. ProviderNotSupportTextToSpeechServiceError, UnsupportedAudioTypeServiceError)
  8. from werkzeug.datastructures import FileStorage
  9. FILE_SIZE = 15
  10. FILE_SIZE_LIMIT = FILE_SIZE * 1024 * 1024
  11. ALLOWED_EXTENSIONS = ['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm', 'amr']
  12. class AudioService:
  13. @classmethod
  14. def transcript_asr(cls, tenant_id: str, file: FileStorage, end_user: Optional[str] = None):
  15. if file is None:
  16. raise NoAudioUploadedServiceError()
  17. extension = file.mimetype
  18. if extension not in [f'audio/{ext}' for ext in ALLOWED_EXTENSIONS]:
  19. raise UnsupportedAudioTypeServiceError()
  20. file_content = file.read()
  21. file_size = len(file_content)
  22. if file_size > FILE_SIZE_LIMIT:
  23. message = f"Audio size larger than {FILE_SIZE} mb"
  24. raise AudioTooLargeServiceError(message)
  25. model_manager = ModelManager()
  26. model_instance = model_manager.get_default_model_instance(
  27. tenant_id=tenant_id,
  28. model_type=ModelType.SPEECH2TEXT
  29. )
  30. if model_instance is None:
  31. raise ProviderNotSupportSpeechToTextServiceError()
  32. buffer = io.BytesIO(file_content)
  33. buffer.name = 'temp.mp3'
  34. return {"text": model_instance.invoke_speech2text(file=buffer, user=end_user)}
  35. @classmethod
  36. def transcript_tts(cls, tenant_id: str, text: str, streaming: bool, end_user: Optional[str] = None):
  37. model_manager = ModelManager()
  38. model_instance = model_manager.get_default_model_instance(
  39. tenant_id=tenant_id,
  40. model_type=ModelType.TTS
  41. )
  42. if model_instance is None:
  43. raise ProviderNotSupportTextToSpeechServiceError()
  44. try:
  45. return model_instance.invoke_tts(content_text=text.strip(), user=end_user, streaming=streaming)
  46. except Exception as e:
  47. raise e