add ali voice output

增加阿里云语音输出接口
This commit is contained in:
chazzjimel
2023-12-06 00:43:19 +08:00
parent d89b056886
commit 293a03b7c8
3 changed files with 75 additions and 23 deletions

View File

@@ -20,15 +20,11 @@ from voice.ali.ali_api import AliyunTokenGenerator
from voice.ali.ali_api import text_to_speech_aliyun
def textContainsEmoji(text):
# 此正则表达式匹配大多数表情符号和特殊字符
pattern = re.compile(
'[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F700-\U0001F77F\U0001F780-\U0001F7FF\U0001F800-\U0001F8FF\U0001F900-\U0001F9FF\U0001FA00-\U0001FA6F\U0001FA70-\U0001FAFF\U00002702-\U000027B0\U00002600-\U000026FF]')
return bool(pattern.search(text))
class AliVoice(Voice):
def __init__(self):
"""
初始化AliVoice类从配置文件加载必要的配置。
"""
try:
curdir = os.path.dirname(__file__)
config_path = os.path.join(curdir, "config.json")
@@ -43,13 +39,17 @@ class AliVoice(Voice):
except Exception as e:
logger.warn("AliVoice init failed: %s, ignore " % e)
# def voiceToText(self, voice_file):
# pass
def textToVoice(self, text):
"""
将文本转换为语音文件。
:param text: 要转换的文本。
:return: 返回一个Reply对象其中包含转换得到的语音文件或错误信息。
"""
# 清除文本中的非中文、非英文和非基本字符
text = re.sub(r'[^\u4e00-\u9fa5\u3040-\u30FF\uAC00-\uD7AFa-zA-Z0-9'
r'äöüÄÖÜáéíóúÁÉÍÓÚàèìòùÀÈÌÒÙâêîôûÂÊÎÔÛçÇñÑ,。!?,.]', '', text)
# 提取 token_id 值
# 提取有效的token
token_id = self.get_valid_token()
fileName = text_to_speech_aliyun(self.api_url, text, self.appkey, token_id)
if fileName:
@@ -60,6 +60,11 @@ class AliVoice(Voice):
return reply
def get_valid_token(self):
"""
获取有效的阿里云token。
:return: 返回有效的token字符串。
"""
current_time = time.time()
if self.token is None or current_time >= self.token_expire_time:
get_token = AliyunTokenGenerator(self.access_key_id, self.access_key_secret)
@@ -71,4 +76,4 @@ class AliVoice(Voice):
logger.debug(f"新获取的阿里云token{self.token}")
else:
logger.debug("使用缓存的token")
return self.token
return self.token