lintonxue00 commited on
Commit
0b9bf74
1 Parent(s): f989ece

Delete 不知道/回收站/ext_voice.py

Browse files
Files changed (1) hide show
  1. 不知道/回收站/ext_voice.py +0 -180
不知道/回收站/ext_voice.py DELETED
@@ -1,180 +0,0 @@
1
- '''
2
- 启用tecent翻译 可以在YAML 中填入下面的参数
3
- ng_voice_translate_on : True
4
- tencentcloud_common_region : "ap-shanghai"
5
- tencentcloud_common_secretid : "xxxxx"
6
- tencentcloud_common_secretkey : "xxxxx"
7
- ng_voice_tar : 'ja'
8
- '''
9
-
10
- from .Extension import Extension
11
- import urllib, requests, uuid, os, base64
12
- from aiohttp import request
13
- from binascii import b2a_base64
14
- from hashlib import sha1
15
- from hmac import new
16
- from random import randint
17
- from sys import maxsize, version_info
18
- from time import time
19
- from nonebot import get_driver
20
- from aiohttp import request
21
- from loguru import logger
22
- from nonebot.exception import ActionFailed
23
- import asyncio
24
- import re
25
- import requests
26
- import base64
27
- import uuid
28
- import urllib.parse
29
- import os
30
-
31
- try:
32
- from ujson import loads as loadJsonS
33
- except:
34
- from json import loads as loadJsonS
35
-
36
- # 拓展的配置信息,用于ai理解拓展的功能 *必填*
37
- ext_config:dict = {
38
- "name": "voice", # 拓展名称,用于标识拓展
39
- "arguments": {
40
- 'sentence': 'str', # 需要转换的文本
41
- },
42
- # 拓展的描述信息,用于提示ai理解拓展的功能 *必填* 尽量简短 使用英文更节省token
43
- "description": "Send a voice sentence. (usage in response: /#voice&你好#/)",
44
- # 参考词,用于上下文参考使用,为空则每次都会被参考(消耗token)
45
- "refer_word": [],
46
- # 作者信息
47
- "author": "KroMiose",
48
- # 版本
49
- "version": "0.0.2",
50
- # 拓展简介
51
- "intro": "发送语音消息(支持翻译)",
52
- }
53
-
54
-
55
- # 自定义扩展
56
- class CustomExtension(Extension):
57
- async def call(self, arg_dict: dict, ctx_data: dict) -> dict:
58
- """ 当拓展被调用时执行的函数 *由拓展自行实现*
59
-
60
- 参数:
61
- arg_dict: dict, 由ai解析的参数字典 {参数名: 参数值}
62
- """
63
- custom_config:dict = self.get_custom_config() # 获取yaml中的配置信息
64
-
65
- ng_voice_translate_on = custom_config.get('ng_voice_translate_on', False) # 是否启用翻译
66
- tencentcloud_common_region = custom_config.get('tencentcloud_common_region', "ap-shanghai") # 腾讯翻译-地区
67
- tencentcloud_common_secretid = custom_config.get('tencentcloud_common_secretid',"xxxxx") # 腾讯翻译-密钥id
68
- tencentcloud_common_secretkey = custom_config.get('tencentcloud_common_secretkey', "xxxxx") # 腾讯翻译-密钥
69
- ng_voice_tar = custom_config.get('g_voice_tar', 'ja') # 翻译目标语言
70
- is_base64 = custom_config.get('is_base64', False) # 是否使用base64编码
71
-
72
- voice_path = 'voice_cache/'
73
- # 创建缓存文件夹
74
- if not os.path.exists(voice_path):
75
- os.mkdir(voice_path)
76
-
77
- # 获取参数
78
- raw_text = arg_dict.get('sentence', None)
79
-
80
- # 从这里开始翻译
81
-
82
- # 腾讯翻译-签名
83
- config = get_driver().config
84
- async def getReqSign(params: dict) -> str:
85
- common = {
86
- "Action": "TextTranslate",
87
- "Region": f"{tencentcloud_common_region}",
88
- "Timestamp": int(time()),
89
- "Nonce": randint(1, maxsize),
90
- "SecretId": f"{tencentcloud_common_secretid}",
91
- "Version": "2018-03-21",
92
- }
93
- params.update(common)
94
- sign_str = "POSTtmt.tencentcloudapi.com/?"
95
- sign_str += "&".join("%s=%s" % (k, params[k]) for k in sorted(params))
96
- secret_key = tencentcloud_common_secretkey
97
- if version_info[0] > 2:
98
- sign_str = bytes(sign_str, "utf-8")
99
- secret_key = bytes(secret_key, "utf-8")
100
- hashed = new(secret_key, sign_str, sha1)
101
- signature = b2a_base64(hashed.digest())[:-1]
102
- if version_info[0] > 2:
103
- signature = signature.decode()
104
- return signature
105
-
106
-
107
- async def q_translate(message) -> str:
108
- _source_text = message
109
- _source = "auto"
110
- _target = ng_voice_tar
111
- try:
112
- endpoint = "https://tmt.tencentcloudapi.com"
113
- params = {
114
- "Source": _source,
115
- "SourceText": _source_text,
116
- "Target": _target,
117
- "ProjectId": 0,
118
- }
119
- params["Signature"] = await getReqSign(params)
120
- # 加上超时参数
121
- async with request("POST", endpoint, data=params) as resp:
122
- data = loadJsonS(await asyncio.wait_for(resp.read(), timeout=30))["Response"]
123
- message = data["TargetText"]
124
- except ActionFailed as e:
125
- logger.warning(
126
- f"ActionFailed {e.info['retcode']} {e.info['msg'].lower()} {e.info['wording']}"
127
- )
128
- except TimeoutError as e:
129
- logger.warning(
130
- f"TimeoutError {e}"
131
- )
132
- return message
133
-
134
-
135
- # 到这里翻译函数结束
136
-
137
- from nonebot_plugin_naturel_gpt.ext import Extension
138
-
139
- class VoiceExtension(Extension):
140
- def __init__(self, custom_config: dict):
141
- super().__init__(custom_config)
142
-
143
- async def call(self, ext_info: dict, ext_args: dict) -> dict:
144
- voice_path = "./voices/"
145
- if not os.path.exists(voice_path):
146
- os.makedirs(voice_path)
147
-
148
- raw_text = ext_args.get('text', None)
149
- if raw_text is None:
150
- return {}
151
-
152
- ng_voice_translate_on = self.config.get("ng_voice_translate_on", False)
153
- if ng_voice_translate_on:
154
- t_result = await q_translate(raw_text)
155
- else:
156
- t_result = raw_text
157
- text = t_result + '~'
158
- text = urllib.parse.quote(text)
159
-
160
- url = f"https://lintonxue00-vits-umamusume-voice-synthesizer.hf.space/api/tts?text={text}&speaker_id=0"
161
-
162
- r = requests.get(url)
163
- file_name = f"{voice_path}{uuid.uuid1()}.ogg"
164
- audio_data = r.content
165
-
166
- with open(file_name, "wb") as f:
167
- f.write(audio_data)
168
-
169
- local_url = f"file://{os.path.abspath(file_name)}"
170
-
171
- if text is not None:
172
- return {
173
- 'voice': local_url, # 语音url
174
- 'text': f"[语音消息] {raw_text}", # 文本
175
- }
176
- return {}
177
-
178
- def __init__(self, custom_config: dict):
179
- super().__init__(ext_config.copy(), custom_config)
180
-