audio_service.py 5.7 KB

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