You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

audio_service.py 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import io
  2. import logging
  3. import uuid
  4. from collections.abc import Generator
  5. from typing import Optional
  6. from flask import Response, stream_with_context
  7. from werkzeug.datastructures import FileStorage
  8. from constants import AUDIO_EXTENSIONS
  9. from core.model_manager import ModelManager
  10. from core.model_runtime.entities.model_entities import ModelType
  11. from extensions.ext_database import db
  12. from models.enums import MessageStatus
  13. from models.model import App, AppMode, AppModelConfig, Message
  14. from services.errors.audio import (
  15. AudioTooLargeServiceError,
  16. NoAudioUploadedServiceError,
  17. ProviderNotSupportSpeechToTextServiceError,
  18. ProviderNotSupportTextToSpeechServiceError,
  19. UnsupportedAudioTypeServiceError,
  20. )
  21. from services.workflow_service import WorkflowService
  22. FILE_SIZE = 30
  23. FILE_SIZE_LIMIT = FILE_SIZE * 1024 * 1024
  24. logger = logging.getLogger(__name__)
  25. class AudioService:
  26. @classmethod
  27. def transcript_asr(cls, app_model: App, file: FileStorage, end_user: Optional[str] = None):
  28. if app_model.mode in {AppMode.ADVANCED_CHAT.value, AppMode.WORKFLOW.value}:
  29. workflow = app_model.workflow
  30. if workflow is None:
  31. raise ValueError("Speech to text is not enabled")
  32. features_dict = workflow.features_dict
  33. if "speech_to_text" not in features_dict or not features_dict["speech_to_text"].get("enabled"):
  34. raise ValueError("Speech to text is not enabled")
  35. else:
  36. app_model_config: AppModelConfig = app_model.app_model_config
  37. if not app_model_config.speech_to_text_dict["enabled"]:
  38. raise ValueError("Speech to text is not enabled")
  39. if file is None:
  40. raise NoAudioUploadedServiceError()
  41. extension = file.mimetype
  42. if extension not in [f"audio/{ext}" for ext in AUDIO_EXTENSIONS]:
  43. raise UnsupportedAudioTypeServiceError()
  44. file_content = file.read()
  45. file_size = len(file_content)
  46. if file_size > FILE_SIZE_LIMIT:
  47. message = f"Audio size larger than {FILE_SIZE} mb"
  48. raise AudioTooLargeServiceError(message)
  49. model_manager = ModelManager()
  50. model_instance = model_manager.get_default_model_instance(
  51. tenant_id=app_model.tenant_id, model_type=ModelType.SPEECH2TEXT
  52. )
  53. if model_instance is None:
  54. raise ProviderNotSupportSpeechToTextServiceError()
  55. buffer = io.BytesIO(file_content)
  56. buffer.name = "temp.mp3"
  57. return {"text": model_instance.invoke_speech2text(file=buffer, user=end_user)}
  58. @classmethod
  59. def transcript_tts(
  60. cls,
  61. app_model: App,
  62. text: Optional[str] = None,
  63. voice: Optional[str] = None,
  64. end_user: Optional[str] = None,
  65. message_id: Optional[str] = None,
  66. is_draft: bool = False,
  67. ):
  68. from app import app
  69. def invoke_tts(text_content: str, app_model: App, voice: Optional[str] = None, is_draft: bool = False):
  70. with app.app_context():
  71. if voice is None:
  72. if app_model.mode in {AppMode.ADVANCED_CHAT.value, AppMode.WORKFLOW.value}:
  73. if is_draft:
  74. workflow = WorkflowService().get_draft_workflow(app_model=app_model)
  75. else:
  76. workflow = app_model.workflow
  77. if (
  78. workflow is None
  79. or "text_to_speech" not in workflow.features_dict
  80. or not workflow.features_dict["text_to_speech"].get("enabled")
  81. ):
  82. raise ValueError("TTS is not enabled")
  83. voice = workflow.features_dict["text_to_speech"].get("voice")
  84. else:
  85. if not is_draft:
  86. if app_model.app_model_config is None:
  87. raise ValueError("AppModelConfig not found")
  88. text_to_speech_dict = app_model.app_model_config.text_to_speech_dict
  89. if not text_to_speech_dict.get("enabled"):
  90. raise ValueError("TTS is not enabled")
  91. voice = text_to_speech_dict.get("voice")
  92. model_manager = ModelManager()
  93. model_instance = model_manager.get_default_model_instance(
  94. tenant_id=app_model.tenant_id, model_type=ModelType.TTS
  95. )
  96. try:
  97. if not voice:
  98. voices = model_instance.get_tts_voices()
  99. if voices:
  100. voice = voices[0].get("value")
  101. if not voice:
  102. raise ValueError("Sorry, no voice available.")
  103. else:
  104. raise ValueError("Sorry, no voice available.")
  105. return model_instance.invoke_tts(
  106. content_text=text_content.strip(), user=end_user, tenant_id=app_model.tenant_id, voice=voice
  107. )
  108. except Exception as e:
  109. raise e
  110. if message_id:
  111. try:
  112. uuid.UUID(message_id)
  113. except ValueError:
  114. return None
  115. message = db.session.query(Message).filter(Message.id == message_id).first()
  116. if message is None:
  117. return None
  118. if message.answer == "" and message.status == MessageStatus.NORMAL:
  119. return None
  120. else:
  121. response = invoke_tts(text_content=message.answer, app_model=app_model, voice=voice, is_draft=is_draft)
  122. if isinstance(response, Generator):
  123. return Response(stream_with_context(response), content_type="audio/mpeg")
  124. return response
  125. else:
  126. if text is None:
  127. raise ValueError("Text is required")
  128. response = invoke_tts(text_content=text, app_model=app_model, voice=voice, is_draft=is_draft)
  129. if isinstance(response, Generator):
  130. return Response(stream_with_context(response), content_type="audio/mpeg")
  131. return response
  132. @classmethod
  133. def transcript_tts_voices(cls, tenant_id: str, language: str):
  134. model_manager = ModelManager()
  135. model_instance = model_manager.get_default_model_instance(tenant_id=tenant_id, model_type=ModelType.TTS)
  136. if model_instance is None:
  137. raise ProviderNotSupportTextToSpeechServiceError()
  138. try:
  139. return model_instance.get_tts_voices(language)
  140. except Exception as e:
  141. raise e