您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

audio_service.py 6.7KB

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