mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
Merge branch 'xinnan-tech:main' into iot
This commit is contained in:
commit
eae14f20bd
19 changed files with 325 additions and 269 deletions
23
README.md
23
README.md
|
|
@ -75,16 +75,23 @@
|
||||||
|
|
||||||
- **硬件**:一套兼容 `xiaozhi-esp32`
|
- **硬件**:一套兼容 `xiaozhi-esp32`
|
||||||
的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
|
的硬件设备(具体型号请参考 [此处](https://rcnv1t9vps13.feishu.cn/wiki/DdgIw4BUgivWDPkhMj1cGIYCnRf))。
|
||||||
- **服务器**:至少 4 核 CPU、8G 内存的电脑。
|
|
||||||
- **固件编译**:请将后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译固件并烧录到设备上。
|
- **电脑或服务器**:至少 4 核 CPU、8G 内存的电脑。
|
||||||
|
- **固件编译**:请将本后端服务的接口地址更新至 `xiaozhi-esp32` 项目中,再重新编译`xiaozhi-esp32`固件并烧录到设备上。
|
||||||
|
|
||||||
|
如果你没有esp32相关的硬件设备,但是非常想体验该项目,可以使用以下的项目让你的电脑、手机模拟成esp32设备。
|
||||||
|
|
||||||
|
- [小智安卓端](https://github.com/TOM88812/xiaozhi-android-client)
|
||||||
|
- [小智电脑端](https://github.com/Huang-junsen/py-xiaozhi)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 警告 ⚠️
|
## 警告 ⚠️
|
||||||
|
|
||||||
本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。
|
1、本项目为开源软件,本软件与对接的任何第三方API服务商(包括但不限于语音识别、大模型、语音合成等平台)均不存在商业合作关系,不为其服务质量及资金安全提供任何形式的担保。
|
||||||
|
建议使用者优先选择持有相关业务牌照的服务商,并仔细阅读其服务协议及隐私政策。本软件不托管任何账户密钥、不参与资金流转、不承担充值资金损失风险。
|
||||||
|
|
||||||
如果您在公网环境中部署学习本项目,请务必在配置文件 `config.yaml` 中开启防护:
|
2、本项目成立时间较短,还未通过网络安全测评,请勿在生产环境中使用。 如果您在公网环境中部署学习本项目,请务必在配置文件 `config.yaml` 中开启防护:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
server:
|
server:
|
||||||
|
|
@ -302,7 +309,13 @@ TTS 性能排行:
|
||||||
|
|
||||||
### 7、更多问题,可联系我们反馈 💬
|
### 7、更多问题,可联系我们反馈 💬
|
||||||
|
|
||||||

|
我们的联系方式放在[百度网盘中,点击前往](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),提取码是`223y`。
|
||||||
|
|
||||||
|
网盘里有“硬件烧录QQ群”、“开源服务端交流群”、“产品建议联系人” 三张图片,请根据需要选择加入。
|
||||||
|
|
||||||
|
- 硬件烧录QQ群:适用于硬件烧录问题
|
||||||
|
- 开源服务端交流群:适用于服务端问题
|
||||||
|
- 产品建议联系人:适用于产品功能、产品设计等建议
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -278,7 +278,7 @@ _As of February 19, 2025, if my computer were located in Haizhu District, Guangz
|
||||||
|
|
||||||
### 7. For more questions, feel free to contact us for feedback 💬
|
### 7. For more questions, feel free to contact us for feedback 💬
|
||||||
|
|
||||||

|
Our contact information is in [Baidu Netdisk](https://pan.baidu.com/s/1x6USjvP1nTRsZ45XlJu65Q),The extraction code is`223y`。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
12
app.py
12
app.py
|
|
@ -1,17 +1,20 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from config.settings import load_config
|
from config.settings import load_config, check_config_file
|
||||||
from core.websocket_server import WebSocketServer
|
from core.websocket_server import WebSocketServer
|
||||||
from manager.http_server import WebUI
|
from manager.http_server import WebUI
|
||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from core.utils.util import get_local_ip
|
from core.utils.util import get_local_ip, check_ffmpeg_installed
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
|
check_config_file()
|
||||||
|
check_ffmpeg_installed()
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
config = load_config()
|
config = load_config()
|
||||||
|
|
||||||
# 启动 WebSocket 服务器
|
# 启动 WebSocket 服务器
|
||||||
ws_server = WebSocketServer(config)
|
ws_server = WebSocketServer(config)
|
||||||
ws_task = asyncio.create_task(ws_server.start())
|
ws_task = asyncio.create_task(ws_server.start())
|
||||||
|
|
@ -33,7 +36,7 @@ async def main():
|
||||||
logger.bind(tag=TAG).info(f"WebUI server is running at http://{local_ip}:{port}")
|
logger.bind(tag=TAG).info(f"WebUI server is running at http://{local_ip}:{port}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to start WebUI server: {e}")
|
logger.bind(tag=TAG).error(f"Failed to start WebUI server: {e}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 等待 WebSocket 服务器运行
|
# 等待 WebSocket 服务器运行
|
||||||
await ws_task
|
await ws_task
|
||||||
|
|
@ -42,5 +45,6 @@ async def main():
|
||||||
if webui_runner:
|
if webui_runner:
|
||||||
await webui_runner.cleanup()
|
await webui_runner.cleanup()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
|
||||||
22
config.yaml
22
config.yaml
|
|
@ -175,8 +175,10 @@ TTS:
|
||||||
# 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误
|
# 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误
|
||||||
# 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。
|
# 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。
|
||||||
# 地址:https://console.volcengine.com/speech/service/8
|
# 地址:https://console.volcengine.com/speech/service/8
|
||||||
|
api_url: https://openspeech.bytedance.com/api/v1/tts
|
||||||
voice: BV001_streaming
|
voice: BV001_streaming
|
||||||
output_file: tmp/
|
output_file: tmp/
|
||||||
|
authorization: "Bearer;"
|
||||||
appid: 你的火山引擎语音合成服务appid
|
appid: 你的火山引擎语音合成服务appid
|
||||||
access_token: 你的火山引擎语音合成服务access_token
|
access_token: 你的火山引擎语音合成服务access_token
|
||||||
cluster: volcano_tts
|
cluster: volcano_tts
|
||||||
|
|
@ -305,7 +307,18 @@ TTS:
|
||||||
# volume: 50
|
# volume: 50
|
||||||
# speech_rate: 0
|
# speech_rate: 0
|
||||||
# pitch_rate: 0
|
# pitch_rate: 0
|
||||||
|
# 添加 302.ai TTS 配置
|
||||||
|
# token申请地址:https://dash.302.ai/
|
||||||
|
TTS302AI:
|
||||||
|
# 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息
|
||||||
|
# 获取api_keyn路径:https://dash.302.ai/apis/list
|
||||||
|
# 价格,$35/百万字符。火山原版¥450元/万字符
|
||||||
|
type: doubao
|
||||||
|
api_url: https://api.302ai.cn/doubao/tts_hd
|
||||||
|
authorization: "Bearer "
|
||||||
|
voice: "zh_female_wanwanxiaohe_moon_bigtts"
|
||||||
|
output_file: tmp/
|
||||||
|
access_token: "你的302API密钥"
|
||||||
# 模块测试配置
|
# 模块测试配置
|
||||||
module_test:
|
module_test:
|
||||||
test_sentences: # 自定义测试语句
|
test_sentences: # 自定义测试语句
|
||||||
|
|
@ -327,4 +340,9 @@ music:
|
||||||
- "我想听歌"
|
- "我想听歌"
|
||||||
- "我要听歌"
|
- "我要听歌"
|
||||||
- "放点音乐"
|
- "放点音乐"
|
||||||
music_dir: "./music" # 音乐文件存放路径
|
music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件
|
||||||
|
music_ext: # 音乐文件类型,p3格式效率最高
|
||||||
|
- ".mp3"
|
||||||
|
- ".wav"
|
||||||
|
- ".p3"
|
||||||
|
refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,26 @@
|
||||||
import os
|
import os
|
||||||
import argparse
|
import argparse
|
||||||
from ruamel.yaml import YAML
|
from ruamel.yaml import YAML
|
||||||
|
from collections.abc import Mapping
|
||||||
from core.utils.util import read_config, get_project_dir
|
from core.utils.util import read_config, get_project_dir
|
||||||
|
|
||||||
|
default_config_file = "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
def get_config_file():
|
def get_config_file():
|
||||||
default_config_file = "config.yaml"
|
global default_config_file
|
||||||
# 判断是否存在私有的配置文件
|
# 判断是否存在私有的配置文件
|
||||||
|
config_file = default_config_file
|
||||||
if os.path.exists(get_project_dir() + "data/." + default_config_file):
|
if os.path.exists(get_project_dir() + "data/." + default_config_file):
|
||||||
default_config_file = "data/." + default_config_file
|
config_file = "data/." + default_config_file
|
||||||
return default_config_file
|
return config_file
|
||||||
|
|
||||||
|
|
||||||
def load_config():
|
def load_config():
|
||||||
"""加载配置文件"""
|
"""加载配置文件"""
|
||||||
parser = argparse.ArgumentParser(description="Server configuration")
|
parser = argparse.ArgumentParser(description="Server configuration")
|
||||||
default_config_file = get_config_file()
|
config_file = get_config_file()
|
||||||
parser.add_argument("--config_path", type=str, default=default_config_file)
|
parser.add_argument("--config_path", type=str, default=config_file)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
return read_config(args.config_path)
|
return read_config(args.config_path)
|
||||||
|
|
||||||
|
|
@ -27,3 +31,54 @@ def update_config(config):
|
||||||
"""将配置保存到YAML文件"""
|
"""将配置保存到YAML文件"""
|
||||||
with open(get_config_file(), 'w') as f:
|
with open(get_config_file(), 'w') as f:
|
||||||
yaml.dump(config, f)
|
yaml.dump(config, f)
|
||||||
|
|
||||||
|
|
||||||
|
def find_missing_keys(new_config, old_config, parent_key=''):
|
||||||
|
"""
|
||||||
|
递归查找缺失的配置项
|
||||||
|
返回格式:[缺失配置路径]
|
||||||
|
"""
|
||||||
|
missing_keys = []
|
||||||
|
|
||||||
|
if not isinstance(new_config, Mapping):
|
||||||
|
return missing_keys
|
||||||
|
|
||||||
|
for key, value in new_config.items():
|
||||||
|
# 构建当前配置路径
|
||||||
|
full_path = f"{parent_key}.{key}" if parent_key else key
|
||||||
|
|
||||||
|
# 检查键是否存在
|
||||||
|
if key not in old_config:
|
||||||
|
missing_keys.append(full_path)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 递归检查嵌套字典
|
||||||
|
if isinstance(value, Mapping):
|
||||||
|
sub_missing = find_missing_keys(
|
||||||
|
value,
|
||||||
|
old_config[key],
|
||||||
|
parent_key=full_path
|
||||||
|
)
|
||||||
|
missing_keys.extend(sub_missing)
|
||||||
|
|
||||||
|
return missing_keys
|
||||||
|
|
||||||
|
|
||||||
|
def check_config_file():
|
||||||
|
old_config_file = get_config_file()
|
||||||
|
global default_config_file
|
||||||
|
if not old_config_file.startswith('data'):
|
||||||
|
return
|
||||||
|
old_config = read_config(get_project_dir() + old_config_file)
|
||||||
|
new_config = read_config(get_project_dir() + default_config_file)
|
||||||
|
# 查找缺失的配置项
|
||||||
|
missing_keys = find_missing_keys(new_config, old_config)
|
||||||
|
|
||||||
|
if missing_keys:
|
||||||
|
error_msg = "您的配置文件太旧了,缺少了:\n"
|
||||||
|
error_msg += "\n".join(f"- {key}" for key in missing_keys)
|
||||||
|
error_msg += "\n建议您:\n"
|
||||||
|
error_msg += "1、备份data/.config.yaml文件\n"
|
||||||
|
error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"
|
||||||
|
error_msg += "3、将密钥逐个复制到新的配置文件中\n"
|
||||||
|
raise ValueError(error_msg)
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,6 @@ from config.logger import setup_logging
|
||||||
import threading
|
import threading
|
||||||
import websockets
|
import websockets
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from collections import deque
|
|
||||||
from core.utils.util import is_segment
|
|
||||||
from core.utils.dialogue import Message, Dialogue
|
from core.utils.dialogue import Message, Dialogue
|
||||||
from core.handle.textHandle import handleTextMessage
|
from core.handle.textHandle import handleTextMessage
|
||||||
from core.utils.util import get_string_no_punctuation_or_emoji
|
from core.utils.util import get_string_no_punctuation_or_emoji
|
||||||
|
|
@ -21,7 +19,6 @@ from config.private_config import PrivateConfig
|
||||||
from core.auth import AuthMiddleware, AuthenticationError
|
from core.auth import AuthMiddleware, AuthenticationError
|
||||||
from core.utils.auth_code_gen import AuthCodeGenerator
|
from core.utils.auth_code_gen import AuthCodeGenerator
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -45,8 +42,8 @@ class ConnectionHandler:
|
||||||
self.loop = asyncio.get_event_loop()
|
self.loop = asyncio.get_event_loop()
|
||||||
self.stop_event = threading.Event()
|
self.stop_event = threading.Event()
|
||||||
self.tts_queue = queue.Queue()
|
self.tts_queue = queue.Queue()
|
||||||
|
self.audio_play_queue = queue.Queue()
|
||||||
self.executor = ThreadPoolExecutor(max_workers=10)
|
self.executor = ThreadPoolExecutor(max_workers=10)
|
||||||
self.scheduled_tasks = deque()
|
|
||||||
|
|
||||||
# 依赖的组件
|
# 依赖的组件
|
||||||
self.vad = _vad
|
self.vad = _vad
|
||||||
|
|
@ -140,9 +137,14 @@ class ConnectionHandler:
|
||||||
|
|
||||||
await self.loop.run_in_executor(None, self._initialize_components)
|
await self.loop.run_in_executor(None, self._initialize_components)
|
||||||
|
|
||||||
tts_priority = threading.Thread(target=self._priority_thread, daemon=True)
|
# tts 消化线程
|
||||||
|
tts_priority = threading.Thread(target=self._tts_priority_thread, daemon=True)
|
||||||
tts_priority.start()
|
tts_priority.start()
|
||||||
|
|
||||||
|
# 音频播放 消化线程
|
||||||
|
audio_play_priority = threading.Thread(target=self._audio_play_priority_thread, daemon=True)
|
||||||
|
audio_play_priority.start()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async for message in self.websocket:
|
async for message in self.websocket:
|
||||||
await self._route_message(message)
|
await self._route_message(message)
|
||||||
|
|
@ -198,10 +200,8 @@ class ConnectionHandler:
|
||||||
return not self.is_device_verified
|
return not self.is_device_verified
|
||||||
|
|
||||||
def chat(self, query):
|
def chat(self, query):
|
||||||
# 如果设备未验证,就发送验证码
|
|
||||||
if self.isNeedAuth():
|
if self.isNeedAuth():
|
||||||
self.llm_finish_task = True
|
self.llm_finish_task = True
|
||||||
# 创建一个新的事件循环来运行异步函数
|
|
||||||
loop = asyncio.new_event_loop()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
try:
|
try:
|
||||||
|
|
@ -212,49 +212,61 @@ class ConnectionHandler:
|
||||||
|
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
response_message = []
|
response_message = []
|
||||||
start = 0
|
processed_chars = 0 # 跟踪已处理的字符位置
|
||||||
# 提交 LLM 任务
|
|
||||||
try:
|
try:
|
||||||
start_time = time.time() # 记录开始时间
|
start_time = time.time()
|
||||||
llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue())
|
llm_responses = self.llm.response(self.session_id, self.dialogue.get_llm_dialogue())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
|
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
|
||||||
return None
|
return None
|
||||||
# 提交 TTS 任务到线程池
|
|
||||||
self.llm_finish_task = False
|
self.llm_finish_task = False
|
||||||
for content in llm_responses:
|
for content in llm_responses:
|
||||||
response_message.append(content)
|
response_message.append(content)
|
||||||
# 如果中途被打断,就停止生成
|
|
||||||
if self.client_abort:
|
if self.client_abort:
|
||||||
start = len(response_message)
|
|
||||||
break
|
break
|
||||||
|
|
||||||
end_time = time.time() # 记录结束时间
|
end_time = time.time()
|
||||||
self.logger.bind(tag=TAG).debug(f"大模型返回时间时间: {end_time - start_time} 秒, 生成token={content}")
|
self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
|
||||||
if is_segment(response_message):
|
|
||||||
segment_text = "".join(response_message[start:])
|
# 合并当前全部文本并处理未分割部分
|
||||||
segment_text = get_string_no_punctuation_or_emoji(segment_text)
|
full_text = "".join(response_message)
|
||||||
if len(segment_text) > 0:
|
current_text = full_text[processed_chars:] # 从未处理的位置开始
|
||||||
|
|
||||||
|
# 查找最后一个有效标点
|
||||||
|
punctuations = ("。", "?", "!", "?", "!", ";", ";", ":", ":", ",")
|
||||||
|
last_punct_pos = -1
|
||||||
|
for punct in punctuations:
|
||||||
|
pos = current_text.rfind(punct)
|
||||||
|
if pos > last_punct_pos:
|
||||||
|
last_punct_pos = pos
|
||||||
|
|
||||||
|
# 找到分割点则处理
|
||||||
|
if last_punct_pos != -1:
|
||||||
|
segment_text_raw = current_text[:last_punct_pos + 1]
|
||||||
|
segment_text = get_string_no_punctuation_or_emoji(segment_text_raw)
|
||||||
|
if segment_text:
|
||||||
self.recode_first_last_text(segment_text)
|
self.recode_first_last_text(segment_text)
|
||||||
future = self.executor.submit(self.speak_and_play, segment_text)
|
future = self.executor.submit(self.speak_and_play, segment_text)
|
||||||
self.tts_queue.put(future)
|
self.tts_queue.put(future)
|
||||||
start = len(response_message)
|
processed_chars += len(segment_text_raw) # 更新已处理字符位置
|
||||||
|
|
||||||
# 处理剩余的响应
|
# 处理最后剩余的文本
|
||||||
if start < len(response_message):
|
full_text = "".join(response_message)
|
||||||
segment_text = "".join(response_message[start:])
|
remaining_text = full_text[processed_chars:]
|
||||||
if len(segment_text) > 0:
|
if remaining_text:
|
||||||
|
segment_text = get_string_no_punctuation_or_emoji(remaining_text)
|
||||||
|
if segment_text:
|
||||||
self.recode_first_last_text(segment_text)
|
self.recode_first_last_text(segment_text)
|
||||||
future = self.executor.submit(self.speak_and_play, segment_text)
|
future = self.executor.submit(self.speak_and_play, segment_text)
|
||||||
self.tts_queue.put(future)
|
self.tts_queue.put(future)
|
||||||
|
|
||||||
self.llm_finish_task = True
|
self.llm_finish_task = True
|
||||||
# 更新对话
|
|
||||||
self.dialogue.put(Message(role="assistant", content="".join(response_message)))
|
self.dialogue.put(Message(role="assistant", content="".join(response_message)))
|
||||||
self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
|
self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _priority_thread(self):
|
def _tts_priority_thread(self):
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
text = None
|
text = None
|
||||||
try:
|
try:
|
||||||
|
|
@ -276,7 +288,6 @@ class ConnectionHandler:
|
||||||
else:
|
else:
|
||||||
self.logger.bind(tag=TAG).error(f"TTS文件不存在: {tts_file}")
|
self.logger.bind(tag=TAG).error(f"TTS文件不存在: {tts_file}")
|
||||||
opus_datas = []
|
opus_datas = []
|
||||||
duration = 0
|
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
self.logger.bind(tag=TAG).error("TTS 任务超时")
|
self.logger.bind(tag=TAG).error("TTS 任务超时")
|
||||||
continue
|
continue
|
||||||
|
|
@ -285,9 +296,7 @@ class ConnectionHandler:
|
||||||
continue
|
continue
|
||||||
if not self.client_abort:
|
if not self.client_abort:
|
||||||
# 如果没有中途打断就发送语音
|
# 如果没有中途打断就发送语音
|
||||||
asyncio.run_coroutine_threadsafe(
|
self.audio_play_queue.put((opus_datas, text))
|
||||||
sendAudioMessage(self, opus_datas, duration, text), self.loop
|
|
||||||
)
|
|
||||||
if self.tts.delete_audio_file and os.path.exists(tts_file):
|
if self.tts.delete_audio_file and os.path.exists(tts_file):
|
||||||
os.remove(tts_file)
|
os.remove(tts_file)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -299,6 +308,16 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text}{e}")
|
self.logger.bind(tag=TAG).error(f"tts_priority priority_thread: {text}{e}")
|
||||||
|
|
||||||
|
def _audio_play_priority_thread(self):
|
||||||
|
while not self.stop_event.is_set():
|
||||||
|
text = None
|
||||||
|
try:
|
||||||
|
opus_datas, text = self.audio_play_queue.get()
|
||||||
|
future = asyncio.run_coroutine_threadsafe(sendAudioMessage(self, opus_datas, text), self.loop)
|
||||||
|
future.result()
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"audio_play_priority priority_thread: {text}{e}")
|
||||||
|
|
||||||
def speak_and_play(self, text):
|
def speak_and_play(self, text):
|
||||||
if text is None or len(text) <= 0:
|
if text is None or len(text) <= 0:
|
||||||
self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
|
self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
|
||||||
|
|
@ -340,9 +359,3 @@ class ConnectionHandler:
|
||||||
self.client_have_voice_last_time = 0
|
self.client_have_voice_last_time = 0
|
||||||
self.client_voice_stop = False
|
self.client_voice_stop = False
|
||||||
self.logger.bind(tag=TAG).debug("VAD states reset.")
|
self.logger.bind(tag=TAG).debug("VAD states reset.")
|
||||||
|
|
||||||
def stop_all_tasks(self):
|
|
||||||
while self.scheduled_tasks:
|
|
||||||
task = self.scheduled_tasks.popleft()
|
|
||||||
task.cancel()
|
|
||||||
self.scheduled_tasks.clear()
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import json
|
import json
|
||||||
|
import queue
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -9,8 +10,6 @@ async def handleAbortMessage(conn):
|
||||||
logger.bind(tag=TAG).info("Abort message received")
|
logger.bind(tag=TAG).info("Abort message received")
|
||||||
# 设置成打断状态,会自动打断llm、tts任务
|
# 设置成打断状态,会自动打断llm、tts任务
|
||||||
conn.client_abort = True
|
conn.client_abort = True
|
||||||
# 打断屏显任务
|
|
||||||
conn.stop_all_tasks()
|
|
||||||
# 打断客户端说话状态
|
# 打断客户端说话状态
|
||||||
await conn.websocket.send(json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}))
|
await conn.websocket.send(json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id}))
|
||||||
conn.clearSpeakStatus()
|
conn.clearSpeakStatus()
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,10 @@ import random
|
||||||
import difflib
|
import difflib
|
||||||
import re
|
import re
|
||||||
import traceback
|
import traceback
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
from core.handle.sendAudioHandle import send_stt_message
|
||||||
|
from core.utils import p3
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -33,6 +36,24 @@ def _find_best_match(potential_song, music_files):
|
||||||
best_match = music_file
|
best_match = music_file
|
||||||
return best_match
|
return best_match
|
||||||
|
|
||||||
|
class MusicManager:
|
||||||
|
def __init__(self, music_dir, music_ext):
|
||||||
|
self.music_dir = Path(music_dir)
|
||||||
|
self.music_ext = music_ext
|
||||||
|
|
||||||
|
def get_music_files(self):
|
||||||
|
music_files = []
|
||||||
|
for file in self.music_dir.rglob("*"):
|
||||||
|
# 判断是否是文件
|
||||||
|
if file.is_file():
|
||||||
|
# 获取文件扩展名
|
||||||
|
ext = file.suffix.lower()
|
||||||
|
# 判断扩展名是否在列表中
|
||||||
|
if ext in self.music_ext:
|
||||||
|
# music_files.append(str(file.resolve())) # 添加绝对路径
|
||||||
|
# 添加相对路径
|
||||||
|
music_files.append(str(file.relative_to(self.music_dir)))
|
||||||
|
return music_files
|
||||||
|
|
||||||
class MusicHandler:
|
class MusicHandler:
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
|
|
@ -45,10 +66,19 @@ class MusicHandler:
|
||||||
self.music_config.get("music_dir", "./music") # 默认路径修改
|
self.music_config.get("music_dir", "./music") # 默认路径修改
|
||||||
)
|
)
|
||||||
self.music_related_keywords = self.music_config.get("music_commands", [])
|
self.music_related_keywords = self.music_config.get("music_commands", [])
|
||||||
|
self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3"))
|
||||||
|
self.refresh_time = self.music_config.get("refresh_time", 60)
|
||||||
else:
|
else:
|
||||||
self.music_dir = os.path.abspath("./music")
|
self.music_dir = os.path.abspath("./music")
|
||||||
self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌",
|
self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌",
|
||||||
"播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"]
|
"播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"]
|
||||||
|
self.music_ext = (".mp3", ".wav", ".p3")
|
||||||
|
self.refresh_time = 60
|
||||||
|
|
||||||
|
# 获取音乐文件列表
|
||||||
|
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
||||||
|
self.scan_time = time.time()
|
||||||
|
logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}")
|
||||||
|
|
||||||
async def handle_music_command(self, conn, text):
|
async def handle_music_command(self, conn, text):
|
||||||
"""处理音乐播放指令"""
|
"""处理音乐播放指令"""
|
||||||
|
|
@ -57,12 +87,15 @@ class MusicHandler:
|
||||||
|
|
||||||
# 尝试匹配具体歌名
|
# 尝试匹配具体歌名
|
||||||
if os.path.exists(self.music_dir):
|
if os.path.exists(self.music_dir):
|
||||||
music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')]
|
if time.time() - self.scan_time > self.refresh_time:
|
||||||
logger.bind(tag=TAG).debug(f"找到的音乐文件: {music_files}")
|
# 刷新音乐文件列表
|
||||||
|
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
||||||
|
self.scan_time = time.time()
|
||||||
|
logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}")
|
||||||
|
|
||||||
potential_song = _extract_song_name(clean_text)
|
potential_song = _extract_song_name(clean_text)
|
||||||
if potential_song:
|
if potential_song:
|
||||||
best_match = _find_best_match(potential_song, music_files)
|
best_match = _find_best_match(potential_song, self.music_files)
|
||||||
if best_match:
|
if best_match:
|
||||||
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
|
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
|
||||||
await self.play_local_music(conn, specific_file=best_match)
|
await self.play_local_music(conn, specific_file=best_match)
|
||||||
|
|
@ -90,19 +123,30 @@ class MusicHandler:
|
||||||
return
|
return
|
||||||
selected_music = specific_file
|
selected_music = specific_file
|
||||||
else:
|
else:
|
||||||
music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')]
|
if time.time() - self.scan_time > self.refresh_time:
|
||||||
if not music_files:
|
# 刷新音乐文件列表
|
||||||
|
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
||||||
|
self.scan_time = time.time()
|
||||||
|
logger.bind(tag=TAG).debug(f"刷新的音乐文件列表: {self.music_files}")
|
||||||
|
|
||||||
|
if not self.music_files:
|
||||||
logger.bind(tag=TAG).error("未找到MP3音乐文件")
|
logger.bind(tag=TAG).error("未找到MP3音乐文件")
|
||||||
return
|
return
|
||||||
selected_music = random.choice(music_files)
|
selected_music = random.choice(self.music_files)
|
||||||
music_path = os.path.join(self.music_dir, selected_music)
|
music_path = os.path.join(self.music_dir, selected_music)
|
||||||
|
if not os.path.exists(music_path):
|
||||||
|
logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
|
||||||
|
return
|
||||||
text = f"正在播放{selected_music}"
|
text = f"正在播放{selected_music}"
|
||||||
await send_stt_message(conn, text)
|
await send_stt_message(conn, text)
|
||||||
conn.tts_first_text = selected_music
|
conn.tts_first_text = selected_music
|
||||||
conn.tts_last_text = selected_music
|
conn.tts_last_text = selected_music
|
||||||
conn.llm_finish_task = True
|
conn.llm_finish_task = True
|
||||||
opus_packets, duration = conn.tts.wav_to_opus_data(music_path)
|
if music_path.endswith(".p3"):
|
||||||
await sendAudioMessage(conn, opus_packets, duration, selected_music)
|
opus_packets, duration = p3.decode_opus_from_file(music_path)
|
||||||
|
else:
|
||||||
|
opus_packets, duration = conn.tts.wav_to_opus_data(music_path)
|
||||||
|
conn.audio_play_queue.put((opus_packets, selected_music))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
|
logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import asyncio
|
|
||||||
import time
|
import time
|
||||||
from core.utils.util import remove_punctuation_and_length
|
from core.utils.util import remove_punctuation_and_length
|
||||||
from core.handle.sendAudioHandle import schedule_with_interrupt, send_stt_message
|
from core.handle.sendAudioHandle import send_stt_message
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -61,10 +60,7 @@ async def handleCMDMessage(conn, text):
|
||||||
|
|
||||||
async def startToChat(conn, text):
|
async def startToChat(conn, text):
|
||||||
# 异步发送 stt 信息
|
# 异步发送 stt 信息
|
||||||
stt_task = asyncio.create_task(
|
await send_stt_message(conn, text)
|
||||||
schedule_with_interrupt(0, send_stt_message(conn, text))
|
|
||||||
)
|
|
||||||
conn.scheduled_tasks.append(stt_task)
|
|
||||||
conn.executor.submit(conn.chat, text)
|
conn.executor.submit(conn.chat, text)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,49 +8,47 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def isLLMWantToFinish(conn):
|
async def isLLMWantToFinish(last_text):
|
||||||
first_text = conn.tts_first_text
|
|
||||||
last_text = conn.tts_last_text
|
|
||||||
_, last_text_without_punctuation = remove_punctuation_and_length(last_text)
|
_, last_text_without_punctuation = remove_punctuation_and_length(last_text)
|
||||||
if "再见" in last_text_without_punctuation or "拜拜" in last_text_without_punctuation:
|
if "再见" in last_text_without_punctuation or "拜拜" in last_text_without_punctuation:
|
||||||
return True
|
return True
|
||||||
_, first_text_without_punctuation = remove_punctuation_and_length(first_text)
|
|
||||||
if "再见" in first_text_without_punctuation or "拜拜" in first_text_without_punctuation:
|
|
||||||
return True
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, audios, duration, text):
|
async def sendAudioMessage(conn, audios, text):
|
||||||
base_delay = conn.tts_duration
|
# 发送句子开始消息
|
||||||
|
|
||||||
# 发送 tts.start
|
|
||||||
if text == conn.tts_first_text:
|
if text == conn.tts_first_text:
|
||||||
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
||||||
conn.tts_start_speak_time = time.time()
|
conn.tts_start_speak_time = time.perf_counter()
|
||||||
|
await send_tts_message(conn, "sentence_start", text)
|
||||||
|
|
||||||
# 发送 sentence_start(每个音频文件之前发送一次)
|
# 初始化流控参数
|
||||||
sentence_task = asyncio.create_task(
|
frame_duration = 60 # 毫秒
|
||||||
schedule_with_interrupt(base_delay, send_tts_message(conn, "sentence_start", text))
|
start_time = time.perf_counter() # 使用高精度计时器
|
||||||
)
|
play_position = 0 # 已播放的时长(毫秒)
|
||||||
conn.scheduled_tasks.append(sentence_task)
|
|
||||||
|
|
||||||
conn.tts_duration += duration
|
for opus_packet in audios:
|
||||||
|
if conn.client_abort:
|
||||||
|
return
|
||||||
|
|
||||||
# 发送音频数据
|
# 计算当前包的预期发送时间
|
||||||
for idx, opus_packet in enumerate(audios):
|
expected_time = start_time + (play_position / 1000)
|
||||||
|
current_time = time.perf_counter()
|
||||||
|
|
||||||
|
# 等待直到预期时间
|
||||||
|
delay = expected_time - current_time
|
||||||
|
if delay > 0:
|
||||||
|
await asyncio.sleep(delay)
|
||||||
|
|
||||||
|
# 发送音频包
|
||||||
await conn.websocket.send(opus_packet)
|
await conn.websocket.send(opus_packet)
|
||||||
|
play_position += frame_duration # 更新播放位置
|
||||||
|
await send_tts_message(conn, "sentence_end", text)
|
||||||
|
# 发送结束消息(如果是最后一个文本)
|
||||||
if conn.llm_finish_task and text == conn.tts_last_text:
|
if conn.llm_finish_task and text == conn.tts_last_text:
|
||||||
stop_duration = conn.tts_duration - (time.time() - conn.tts_start_speak_time)
|
await send_tts_message(conn, 'stop', None)
|
||||||
stop_task = asyncio.create_task(
|
if await isLLMWantToFinish(text):
|
||||||
schedule_with_interrupt(stop_duration, send_tts_message(conn, 'stop'))
|
await conn.close()
|
||||||
)
|
|
||||||
conn.scheduled_tasks.append(stop_task)
|
|
||||||
if await isLLMWantToFinish(conn):
|
|
||||||
finish_task = asyncio.create_task(
|
|
||||||
schedule_with_interrupt(stop_duration, await conn.close())
|
|
||||||
)
|
|
||||||
conn.scheduled_tasks.append(finish_task)
|
|
||||||
|
|
||||||
|
|
||||||
async def send_tts_message(conn, state, text=None):
|
async def send_tts_message(conn, state, text=None):
|
||||||
|
|
@ -84,12 +82,3 @@ async def send_stt_message(conn, text):
|
||||||
"session_id": conn.session_id}
|
"session_id": conn.session_id}
|
||||||
))
|
))
|
||||||
await send_tts_message(conn, "start")
|
await send_tts_message(conn, "start")
|
||||||
|
|
||||||
|
|
||||||
async def schedule_with_interrupt(delay, coro):
|
|
||||||
"""可中断的延迟调度"""
|
|
||||||
try:
|
|
||||||
await asyncio.sleep(delay)
|
|
||||||
await coro
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
pass
|
|
||||||
|
|
|
||||||
|
|
@ -14,10 +14,9 @@ class TTSProvider(TTSProviderBase):
|
||||||
self.access_token = config.get("access_token")
|
self.access_token = config.get("access_token")
|
||||||
self.cluster = config.get("cluster")
|
self.cluster = config.get("cluster")
|
||||||
self.voice = config.get("voice")
|
self.voice = config.get("voice")
|
||||||
|
self.api_url = config.get("api_url")
|
||||||
self.host = "openspeech.bytedance.com"
|
self.authorization = config.get("authorization")
|
||||||
self.api_url = f"https://{self.host}/api/v1/tts"
|
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
|
||||||
self.header = {"Authorization": f"Bearer;{self.access_token}"}
|
|
||||||
|
|
||||||
def generate_filename(self, extension=".wav"):
|
def generate_filename(self, extension=".wav"):
|
||||||
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,5 @@
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import asyncio
|
|
||||||
from typing import List, Dict, Any
|
|
||||||
|
|
||||||
# 添加项目根目录到Python路径
|
# 添加项目根目录到Python路径
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
|
@ -10,10 +8,6 @@ sys.path.insert(0, project_root)
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import importlib
|
import importlib
|
||||||
from datetime import datetime
|
|
||||||
from core.utils.util import is_segment
|
|
||||||
from core.utils.util import get_string_no_punctuation_or_emoji
|
|
||||||
from core.utils.util import read_config, get_project_dir
|
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -27,117 +21,3 @@ def create_instance(class_name, *args, **kwargs):
|
||||||
return sys.modules[lib_name].LLMProvider(*args, **kwargs)
|
return sys.modules[lib_name].LLMProvider(*args, **kwargs)
|
||||||
|
|
||||||
raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
|
raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
|
||||||
|
|
||||||
|
|
||||||
async def test_single_model(llm_name: str, llm_config: Dict[str, Any], test_prompt: str, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
||||||
"""异步测试单个模型"""
|
|
||||||
try:
|
|
||||||
# 获取实际的LLM类型
|
|
||||||
llm_type = llm_config["type"] if "type" in llm_config else llm_name
|
|
||||||
llm = create_instance(llm_type, llm_config)
|
|
||||||
|
|
||||||
# 开始测试
|
|
||||||
dialogue = []
|
|
||||||
dialogue.append({"role": "system", "content": config.get("prompt")})
|
|
||||||
dialogue.append({"role": "user", "content": test_prompt})
|
|
||||||
|
|
||||||
start_time = datetime.now()
|
|
||||||
llm_responses = llm.response("test", dialogue)
|
|
||||||
response_message = []
|
|
||||||
first_response_time = None
|
|
||||||
total_response_time = None
|
|
||||||
start = 0
|
|
||||||
full_response = ""
|
|
||||||
|
|
||||||
for content in llm_responses:
|
|
||||||
response_message.append(content)
|
|
||||||
full_response += content
|
|
||||||
|
|
||||||
if is_segment(response_message):
|
|
||||||
segment_text = "".join(response_message[start:])
|
|
||||||
segment_text = get_string_no_punctuation_or_emoji(segment_text)
|
|
||||||
if len(segment_text) > 0:
|
|
||||||
if first_response_time is None:
|
|
||||||
first_response_time = (datetime.now() - start_time).total_seconds()
|
|
||||||
start = len(response_message)
|
|
||||||
|
|
||||||
total_response_time = (datetime.now() - start_time).total_seconds()
|
|
||||||
|
|
||||||
return {
|
|
||||||
"name": llm_name,
|
|
||||||
"type": llm_type,
|
|
||||||
"first_response_time": first_response_time,
|
|
||||||
"total_response_time": total_response_time,
|
|
||||||
"response_length": len(full_response),
|
|
||||||
"status": "成功",
|
|
||||||
"response": full_response
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"测试 {llm_name} 时发生错误: {str(e)}")
|
|
||||||
return {
|
|
||||||
"name": llm_name,
|
|
||||||
"type": llm_config.get("type", llm_name),
|
|
||||||
"first_response_time": None,
|
|
||||||
"total_response_time": None,
|
|
||||||
"response_length": 0,
|
|
||||||
"status": f"失败 - {str(e)}",
|
|
||||||
"response": ""
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
"""
|
|
||||||
LLM模型响应速度测试和排行(异步版本)
|
|
||||||
"""
|
|
||||||
config = read_config(get_project_dir() + "config.yaml")
|
|
||||||
test_prompt = "你好小智"
|
|
||||||
|
|
||||||
print("开始并发测试所有模型...")
|
|
||||||
|
|
||||||
# 创建所有模型的测试任务
|
|
||||||
tasks = []
|
|
||||||
for llm_name, llm_config in config["LLM"].items():
|
|
||||||
task = asyncio.create_task(test_single_model(llm_name, llm_config, test_prompt, config))
|
|
||||||
tasks.append(task)
|
|
||||||
|
|
||||||
# 等待所有测试完成
|
|
||||||
test_results = await asyncio.gather(*tasks)
|
|
||||||
|
|
||||||
# 打印测试结果排行榜
|
|
||||||
print("\n========= LLM模型性能测试排行榜 =========")
|
|
||||||
print("测试提示词:", test_prompt)
|
|
||||||
|
|
||||||
# 过滤出成功的结果,并确保数值有效
|
|
||||||
successful_results = [r for r in test_results if r["status"] == "成功" and r["first_response_time"] is not None]
|
|
||||||
|
|
||||||
if successful_results:
|
|
||||||
print("\n1. 首次响应时间排行:")
|
|
||||||
sorted_by_first = sorted(successful_results, key=lambda x: x["first_response_time"])
|
|
||||||
for i, result in enumerate(sorted_by_first, 1):
|
|
||||||
print(f"{i}. {result['name']}({result['type']}) - {result['first_response_time']:.2f}秒")
|
|
||||||
print(f" 响应内容: {result['response'][:50]}...") # 只显示前50个字符
|
|
||||||
|
|
||||||
print("\n2. 总响应时间排行:")
|
|
||||||
sorted_by_total = sorted(successful_results, key=lambda x: x["total_response_time"] or float('inf'))
|
|
||||||
for i, result in enumerate(sorted_by_total, 1):
|
|
||||||
if result["total_response_time"] is not None:
|
|
||||||
print(f"{i}. {result['name']}({result['type']}) - {result['total_response_time']:.2f}秒")
|
|
||||||
|
|
||||||
print("\n3. 响应长度比较:")
|
|
||||||
sorted_by_length = sorted(successful_results, key=lambda x: x["response_length"], reverse=True)
|
|
||||||
for i, result in enumerate(sorted_by_length, 1):
|
|
||||||
print(f"{i}. {result['name']}({result['type']}) - {result['response_length']}字符")
|
|
||||||
else:
|
|
||||||
print("\n没有成功完成测试的模型。")
|
|
||||||
|
|
||||||
if len(test_results) != len(successful_results):
|
|
||||||
print("\n测试失败的模型:")
|
|
||||||
failed_results = [r for r in test_results if r["status"] != "成功" or r["first_response_time"] is None]
|
|
||||||
for result in failed_results:
|
|
||||||
print(f"- {result['name']}({result['type']}): {result['status']}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# 运行异步主函数
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
|
||||||
33
core/utils/p3.py
Normal file
33
core/utils/p3.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import struct
|
||||||
|
|
||||||
|
def decode_opus_from_file(input_file):
|
||||||
|
"""
|
||||||
|
从p3文件中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
|
||||||
|
"""
|
||||||
|
opus_datas = []
|
||||||
|
total_frames = 0
|
||||||
|
sample_rate = 16000 # 文件采样率
|
||||||
|
frame_duration_ms = 60 # 帧时长
|
||||||
|
frame_size = int(sample_rate * frame_duration_ms / 1000)
|
||||||
|
|
||||||
|
with open(input_file, 'rb') as f:
|
||||||
|
while True:
|
||||||
|
# 读取头部(4字节):[1字节类型,1字节保留,2字节长度]
|
||||||
|
header = f.read(4)
|
||||||
|
if not header:
|
||||||
|
break
|
||||||
|
|
||||||
|
# 解包头部信息
|
||||||
|
_, _, data_len = struct.unpack('>BBH', header)
|
||||||
|
|
||||||
|
# 根据头部指定的长度读取 Opus 数据
|
||||||
|
opus_data = f.read(data_len)
|
||||||
|
if len(opus_data) != data_len:
|
||||||
|
raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the file.")
|
||||||
|
|
||||||
|
opus_datas.append(opus_data)
|
||||||
|
total_frames += 1
|
||||||
|
|
||||||
|
# 计算总时长
|
||||||
|
total_duration = (total_frames * frame_duration_ms) / 1000.0
|
||||||
|
return opus_datas, total_duration
|
||||||
|
|
@ -2,8 +2,6 @@ import os
|
||||||
import sys
|
import sys
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import importlib
|
import importlib
|
||||||
from datetime import datetime
|
|
||||||
from core.utils.util import read_config, get_project_dir
|
|
||||||
|
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -16,26 +14,4 @@ def create_instance(class_name, *args, **kwargs):
|
||||||
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
|
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
|
||||||
return sys.modules[lib_name].TTSProvider(*args, **kwargs)
|
return sys.modules[lib_name].TTSProvider(*args, **kwargs)
|
||||||
|
|
||||||
raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确")
|
raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
"""
|
|
||||||
响应速度测试
|
|
||||||
"""
|
|
||||||
config = read_config(get_project_dir() + "config.yaml")
|
|
||||||
tts = create_instance(
|
|
||||||
config["selected_module"]["TTS"]
|
|
||||||
if not 'type' in config["TTS"][config["selected_module"]["TTS"]]
|
|
||||||
else
|
|
||||||
config["TTS"][config["selected_module"]["TTS"]]["type"],
|
|
||||||
config["TTS"][config["selected_module"]["TTS"]],
|
|
||||||
config["delete_audio"]
|
|
||||||
)
|
|
||||||
tts.output_file = get_project_dir() + tts.output_file
|
|
||||||
start = datetime.now()
|
|
||||||
file_path = tts.to_tts("你好,测试,我是人工智能小智")
|
|
||||||
print("语音合成耗时:" + str(datetime.now() - start))
|
|
||||||
start = datetime.now()
|
|
||||||
tts.wav_to_opus_data(file_path)
|
|
||||||
print("语音opus耗时:" + str(datetime.now() - start))
|
|
||||||
|
|
@ -3,6 +3,7 @@ import re
|
||||||
import json
|
import json
|
||||||
import yaml
|
import yaml
|
||||||
import socket
|
import socket
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
|
||||||
def get_project_dir():
|
def get_project_dir():
|
||||||
|
|
@ -34,13 +35,6 @@ def write_json_file(file_path, data):
|
||||||
json.dump(data, file, ensure_ascii=False, indent=4)
|
json.dump(data, file, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
|
||||||
def is_segment(tokens):
|
|
||||||
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":"):
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def is_punctuation_or_emoji(char):
|
def is_punctuation_or_emoji(char):
|
||||||
"""检查字符是否为空格、指定标点或表情符号"""
|
"""检查字符是否为空格、指定标点或表情符号"""
|
||||||
# 定义需要去除的中英文标点(包括全角/半角)
|
# 定义需要去除的中英文标点(包括全角/半角)
|
||||||
|
|
@ -121,3 +115,29 @@ def check_password(password):
|
||||||
|
|
||||||
# 如果满足所有条件,则返回True
|
# 如果满足所有条件,则返回True
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def check_ffmpeg_installed():
|
||||||
|
ffmpeg_installed = False
|
||||||
|
try:
|
||||||
|
# 执行ffmpeg -version命令,并捕获输出
|
||||||
|
result = subprocess.run(
|
||||||
|
['ffmpeg', '-version'],
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
check=True # 如果返回码非零则抛出异常
|
||||||
|
)
|
||||||
|
# 检查输出中是否包含版本信息(可选)
|
||||||
|
output = result.stdout + result.stderr
|
||||||
|
if 'ffmpeg version' in output.lower():
|
||||||
|
ffmpeg_installed = True
|
||||||
|
return False
|
||||||
|
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||||
|
# 命令执行失败或未找到
|
||||||
|
ffmpeg_installed = False
|
||||||
|
if not ffmpeg_installed:
|
||||||
|
error_msg = "您的电脑还没正确安装ffmpeg\n"
|
||||||
|
error_msg += "\n建议您:\n"
|
||||||
|
error_msg += "1、按照项目的安装文档,正确进入conda环境\n"
|
||||||
|
error_msg += "2、查阅安装文档,如何在conda环境中安装ffmpeg\n"
|
||||||
|
raise ValueError(error_msg)
|
||||||
|
|
@ -159,14 +159,31 @@ poetry run python app.py
|
||||||
本项目使用`conda`管理依赖环境。如果不方便安装`conda`,需要根据实际的操作系统安装好`libopus`和`ffmpeg`。
|
本项目使用`conda`管理依赖环境。如果不方便安装`conda`,需要根据实际的操作系统安装好`libopus`和`ffmpeg`。
|
||||||
如果确定使用`conda`,则安装好后,开始执行以下命令。
|
如果确定使用`conda`,则安装好后,开始执行以下命令。
|
||||||
|
|
||||||
|
重要提示!windows 用户,可以通过安装`Anaconda`来管理环境。安装好`Anaconda`后,在`开始`那里搜索`anaconda`相关的关键词,
|
||||||
|
找到`Anaconda Prpmpt`,使用管理员身份运行它。如下图。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
运行之后,如果你能看到命令行窗口前面有一个(base)字样,说明你成功进入了`conda`环境。那么你就可以执行以下命令了。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
```
|
```
|
||||||
conda remove -n xiaozhi-esp32-server --all -y
|
conda remove -n xiaozhi-esp32-server --all -y
|
||||||
conda create -n xiaozhi-esp32-server python=3.10 -y
|
conda create -n xiaozhi-esp32-server python=3.10 -y
|
||||||
conda activate xiaozhi-esp32-server
|
conda activate xiaozhi-esp32-server
|
||||||
conda install conda-forge::libopus -y
|
|
||||||
conda install conda-forge::ffmpeg -y
|
# 添加清华源通道
|
||||||
|
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
|
||||||
|
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
|
||||||
|
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
|
||||||
|
|
||||||
|
conda install libopus -y
|
||||||
|
conda install ffmpeg -y
|
||||||
```
|
```
|
||||||
|
|
||||||
|
请注意,以上命令,不是一股脑执行就成功的,你需要一步步执行,每一步执行完后,都检查一下输出的日志,查看是否成功。
|
||||||
|
|
||||||
## 2.安装本项目依赖
|
## 2.安装本项目依赖
|
||||||
|
|
||||||
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
|
你先要下载本项目源码,源码可以通过`git clone`命令下载,如果你不熟悉`git clone`命令。
|
||||||
|
|
@ -179,7 +196,7 @@ conda install conda-forge::ffmpeg -y
|
||||||
你需要把它重命名成`xiaozhi-esp32-server`,好了请记住这个目录,我们暂且称它为`项目目录`。
|
你需要把它重命名成`xiaozhi-esp32-server`,好了请记住这个目录,我们暂且称它为`项目目录`。
|
||||||
|
|
||||||
```
|
```
|
||||||
# 使用dos或者终端,进入到你的项目目录,执行以下命令
|
# 继续使用conda环境,进入到你的项目目录,执行以下命令
|
||||||
conda activate xiaozhi-esp32-server
|
conda activate xiaozhi-esp32-server
|
||||||
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
@ -250,7 +267,7 @@ LLM:
|
||||||
## 模型文件
|
## 模型文件
|
||||||
|
|
||||||
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
本项目语音识别模型,默认使用`SenseVoiceSmall`模型,进行语音转文字。因为模型较大,需要独立下载,下载后把`model.pt`
|
||||||
文件放在`model/SenseVoiceSmall`
|
文件放在`models/SenseVoiceSmall`
|
||||||
目录下。下面两个下载路线任选一个。
|
目录下。下面两个下载路线任选一个。
|
||||||
|
|
||||||
- 线路一:阿里魔塔下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
- 线路一:阿里魔塔下载[SenseVoiceSmall](https://modelscope.cn/models/iic/SenseVoiceSmall/resolve/master/model.pt)
|
||||||
|
|
|
||||||
BIN
docs/images/conda_env_1.png
Normal file
BIN
docs/images/conda_env_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 781 KiB |
BIN
docs/images/conda_env_2.png
Normal file
BIN
docs/images/conda_env_2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 588 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 363 KiB |
Loading…
Reference in a new issue