audio_service.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import io
  2. from typing import Optional
  3. from werkzeug.datastructures import FileStorage
  4. from core.model_manager import ModelManager
  5. from core.model_runtime.entities.model_entities import ModelType
  6. from models.model import App, AppMode, AppModelConfig
  7. from services.errors.audio import (
  8. AudioTooLargeServiceError,
  9. NoAudioUploadedServiceError,
  10. ProviderNotSupportSpeechToTextServiceError,
  11. ProviderNotSupportTextToSpeechServiceError,
  12. UnsupportedAudioTypeServiceError,
  13. )
  14. FILE_SIZE = 30
  15. FILE_SIZE_LIMIT = FILE_SIZE * 1024 * 1024
  16. ALLOWED_EXTENSIONS = ['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm', 'amr']
  17. class AudioService:
  18. @classmethod
  19. def transcript_asr(cls, app_model: App, file: FileStorage, end_user: Optional[str] = None):
  20. if app_model.mode in [AppMode.ADVANCED_CHAT.value, AppMode.WORKFLOW.value]:
  21. workflow = app_model.workflow
  22. if workflow is None:
  23. raise ValueError("Speech to text is not enabled")
  24. features_dict = workflow.features_dict
  25. if 'speech_to_text' not in features_dict or not features_dict['speech_to_text'].get('enabled'):
  26. raise ValueError("Speech to text is not enabled")
  27. else:
  28. app_model_config: AppModelConfig = app_model.app_model_config
  29. if not app_model_config.speech_to_text_dict['enabled']:
  30. raise ValueError("Speech to text is not enabled")
  31. if file is None:
  32. raise NoAudioUploadedServiceError()
  33. extension = file.mimetype
  34. if extension not in [f'audio/{ext}' for ext in ALLOWED_EXTENSIONS]:
  35. raise UnsupportedAudioTypeServiceError()
  36. file_content = file.read()
  37. file_size = len(file_content)
  38. if file_size > FILE_SIZE_LIMIT:
  39. message = f"Audio size larger than {FILE_SIZE} mb"
  40. raise AudioTooLargeServiceError(message)
  41. model_manager = ModelManager()
  42. model_instance = model_manager.get_default_model_instance(
  43. tenant_id=app_model.tenant_id,
  44. model_type=ModelType.SPEECH2TEXT
  45. )
  46. if model_instance is None:
  47. raise ProviderNotSupportSpeechToTextServiceError()
  48. buffer = io.BytesIO(file_content)
  49. buffer.name = 'temp.mp3'
  50. return {"text": model_instance.invoke_speech2text(file=buffer, user=end_user)}
  51. @classmethod
  52. def transcript_tts(cls, app_model: App, text: str, streaming: bool,
  53. voice: Optional[str] = None, end_user: Optional[str] = None):
  54. if app_model.mode in [AppMode.ADVANCED_CHAT.value, AppMode.WORKFLOW.value]:
  55. workflow = app_model.workflow
  56. if workflow is None:
  57. raise ValueError("TTS is not enabled")
  58. features_dict = workflow.features_dict
  59. if 'text_to_speech' not in features_dict or not features_dict['text_to_speech'].get('enabled'):
  60. raise ValueError("TTS is not enabled")
  61. voice = features_dict['text_to_speech'].get('voice') if voice is None else voice
  62. else:
  63. text_to_speech_dict = app_model.app_model_config.text_to_speech_dict
  64. if not text_to_speech_dict.get('enabled'):
  65. raise ValueError("TTS is not enabled")
  66. voice = text_to_speech_dict.get('voice') if voice is None else voice
  67. model_manager = ModelManager()
  68. model_instance = model_manager.get_default_model_instance(
  69. tenant_id=app_model.tenant_id,
  70. model_type=ModelType.TTS
  71. )
  72. if model_instance is None:
  73. raise ProviderNotSupportTextToSpeechServiceError()
  74. try:
  75. return model_instance.invoke_tts(
  76. content_text=text.strip(),
  77. user=end_user,
  78. streaming=streaming,
  79. tenant_id=app_model.tenant_id,
  80. voice=voice
  81. )
  82. except Exception as e:
  83. raise e
  84. @classmethod
  85. def transcript_tts_voices(cls, tenant_id: str, language: str):
  86. model_manager = ModelManager()
  87. model_instance = model_manager.get_default_model_instance(
  88. tenant_id=tenant_id,
  89. model_type=ModelType.TTS
  90. )
  91. if model_instance is None:
  92. raise ProviderNotSupportTextToSpeechServiceError()
  93. try:
  94. return model_instance.get_tts_voices(language)
  95. except Exception as e:
  96. raise e