lintonxue00 commited on
Commit
64047df
1 Parent(s): 87e1525

Upload ext_voice.py

Browse files
Files changed (1) hide show
  1. ext_voice.py +21 -33
ext_voice.py CHANGED
@@ -21,11 +21,10 @@ from aiohttp import request
21
  from loguru import logger
22
  from nonebot.exception import ActionFailed
23
  import asyncio
 
24
  import requests
25
  import base64
26
  import uuid
27
- import re
28
-
29
 
30
  try:
31
  from ujson import loads as loadJsonS
@@ -148,37 +147,26 @@ class CustomExtension(Extension):
148
 
149
  # todo: 如果需要使用本地的语音合成api,请取消注释下面的代码,并自行改为您的api地址,将填入合成文本的地方改为{text}
150
  # url = f"http://127.0.0.1:23211/to_voice?text={text}"
151
- # 去除base64字符串中的非法字符
152
- def call(self, args, context):
153
- url = args['url']
154
- text = args.get('text')
155
- is_base64 = args.get('is_base64', False)
156
- raw_text = text
157
-
158
- # 下载语音文件
159
- r = requests.get(url)
160
-
161
- # 对base64字符串进行处理
162
- if is_base64:
163
- pattern = re.compile('[^a-zA-Z0-9+/=]')
164
- content = pattern.sub('', r.content.decode())
165
- audio_data = base64.b64decode(content + b'=' * (-len(content) % 4), validate=True)
166
- else:
167
- audio_data = r.content
168
-
169
- # 写入音频文件
170
- file_name = f"{voice_path}{uuid.uuid1()}.ogg"
171
- with open(file_name, "wb") as f:
172
- f.write(audio_data)
173
-
174
- local_url = f"file:///{os.path.abspath(file_name)}"
175
-
176
- if text is not None:
177
- return {
178
- 'voice': local_url, # 语音url
179
- 'text': f"[语音消息] {raw_text}", # 文本
180
- }
181
- return {}
182
 
183
  def __init__(self, custom_config: dict):
184
  super().__init__(ext_config.copy(), custom_config)
 
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
 
29
  try:
30
  from ujson import loads as loadJsonS
 
147
 
148
  # todo: 如果需要使用本地的语音合成api,请取消注释下面的代码,并自行改为您的api地址,将填入合成文本的地方改为{text}
149
  # url = f"http://127.0.0.1:23211/to_voice?text={text}"
150
+
151
+ # 下载语音文件
152
+ r = requests.get(url)
153
+ file_name = f"{voice_path}{uuid.uuid1()}.ogg"
154
+ if is_base64:
155
+ audio_data = base64.b64decode(r.content + b'=' * (-len(r.content) % 4), validate=True)
156
+ else:
157
+ audio_data = r.content
158
+
159
+ with open(file_name, "wb") as f:
160
+ f.write(audio_data)
161
+
162
+ local_url = f"file:///{os.path.abspath(file_name)}"
163
+
164
+ if text is not None:
165
+ return {
166
+ 'voice': local_url, # 语音url
167
+ 'text': f"[语音消息] {raw_text}", # 文本
168
+ }
169
+ return {}
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  def __init__(self, custom_config: dict):
172
  super().__init__(ext_config.copy(), custom_config)