audio_service.py 6.1 KB

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