同步远程更改并更新.gitignore,删除不需要的音乐文件,pass远程服务器

This commit is contained in:
maizhiheng 2025-03-07 16:37:08 +08:00
parent c7f705b274
commit a85fca3055
8 changed files with 308 additions and 12 deletions

View file

@ -15,10 +15,10 @@ server:
# 设备的token,可以在编译固件的环节,写入你自己定义的token # 设备的token,可以在编译固件的环节,写入你自己定义的token
# 固件上的token和以下的token如果能对应,才能连接本服务端 # 固件上的token和以下的token如果能对应,才能连接本服务端
tokens: tokens:
- token: "your-token1" # 设备1的token - token: "test-token" # 符合文档建议的强密码策略
name: "your-device-name1" # 设备1标识 name: "xiaozhi001" # 设备1标识
- token: "your-token2" # 设备2的token - token: "test-token" # 设备2的token
name: "your-device-name2" # 设备2标识 name: "xiaozhi002" # 设备2标识
# 可选:设备白名单,如果设置了白名单,那么白名单的机器无论是什么token都可以连接。 # 可选:设备白名单,如果设置了白名单,那么白名单的机器无论是什么token都可以连接。
#allowed_devices: #allowed_devices:
# - "24:0A:C4:1D:3B:F0" # MAC地址列表 # - "24:0A:C4:1D:3B:F0" # MAC地址列表
@ -104,7 +104,7 @@ LLM:
# 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
model_name: qwen-turbo model_name: qwen-turbo
api_key: 你的deepseek web key api_key: sk-9d4aeaf8ab9c41ecbc2f138332bff33b
DeepSeekLLM: DeepSeekLLM:
# 定义LLM API类型 # 定义LLM API类型
type: openai type: openai
@ -119,7 +119,7 @@ LLM:
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
model_name: glm-4-flash model_name: glm-4-flash
url: https://open.bigmodel.cn/api/paas/v4/ url: https://open.bigmodel.cn/api/paas/v4/
api_key: 你的chat-glm web key api_key: 1e5337850ba84989b1caf7a72a4ccf25.i0cQ9GYOa9rNJj3L
OllamaLLM: OllamaLLM:
# 定义LLM API类型 # 定义LLM API类型
type: ollama type: ollama
@ -176,8 +176,8 @@ TTS:
voice: BV001_streaming voice: BV001_streaming
output_file: tmp/ output_file: tmp/
authorization: "Bearer;" authorization: "Bearer;"
appid: 你的火山引擎语音合成服务appid appid: 6032790313
access_token: 你的火山引擎语音合成服务access_token access_token: zfBIDamb9IAniLYsm-TByMkAi9tBVoiM
cluster: volcano_tts cluster: volcano_tts
CosyVoiceSiliconflow: CosyVoiceSiliconflow:
type: siliconflow type: siliconflow
@ -186,8 +186,27 @@ TTS:
model: FunAudioLLM/CosyVoice2-0.5B model: FunAudioLLM/CosyVoice2-0.5B
voice: FunAudioLLM/CosyVoice2-0.5B:alex voice: FunAudioLLM/CosyVoice2-0.5B:alex
output_file: tmp/ output_file: tmp/
access_token: 你的硅基流动API密钥 access_token: sk-xnujjnmkiqyihtxzuyfmidyioshxcjauydhvjrerewrbgfnr
response_format: wav response_format: wav
CosyVoice:
type: cosyvoice
model: "FunAudioLLM/CosyVoice2-0.5B"
voice: "FunAudioLLM/CosyVoice2-0.5B:中文女"
api_url: http://127.0.0.1:9881/tts
mode: 3s极速复刻 # 预训练音色, 3s极速复刻, 跨语种复刻, 自然语言控制
speaker: 中文女 # 预训练音色模式下的说话人 (有效值: 中文女, 中文男, 日语男, 粤语女, 英文女, 英文男, 韩语女)
prompt_audio: data/voice/佩奇-孩子们听到没有快点下来不然你们就吃不到蛋糕咯.mp3 # 3s极速复刻和跨语种复刻模式下的参考音频
prompt_text: 孩子们听到没有快点下来不然你们就吃不到蛋糕咯 # 3s极速复刻模式下的参考文本
instruct_text: 请用开心的语气说话 # 自然语言控制模式下的指令文本
seed: 0 # 随机种子,0表示随机
speed: 1.0 # 语速,1.0为正常语速
stream: false # 是否流式输出
timeout: 120 # 请求超时时间(秒)- 增加到120秒以处理较大的音频文件
max_retries: 3 # 最大重试次数
retry_delay: 2 # 重试间隔(秒)- 增加到2秒以给服务器更多恢复时间
output_file: "tmp/"
access_token: ""
response_format: "wav"
CozeCnTTS: CozeCnTTS:
type: cozecn type: cozecn
# COZECN TTS # COZECN TTS

View file

@ -20,6 +20,8 @@ def load_config():
"""加载配置文件""" """加载配置文件"""
parser = argparse.ArgumentParser(description="Server configuration") parser = argparse.ArgumentParser(description="Server configuration")
config_file = get_config_file() config_file = get_config_file()
# 打印绝对路径
# print(f"config_file: {os.path.abspath(config_file)}")
parser.add_argument("--config_path", type=str, 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)

View file

@ -293,7 +293,7 @@ class ConnectionHandler:
opus_datas, text_index, tts_file = [], 0, None opus_datas, text_index, tts_file = [], 0, None
try: try:
self.logger.bind(tag=TAG).debug("正在处理TTS任务...") self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
tts_file, text, text_index = future.result(timeout=10) tts_file, text, text_index = future.result(timeout=120)
if text is None or len(text) <= 0: if text is None or len(text) <= 0:
self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty") self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty")
elif tts_file is None: elif tts_file is None:

View file

@ -0,0 +1,262 @@
import os
import uuid
import requests
import aiohttp
import aiofiles
import time
import random
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
from core.utils.util import get_project_dir
logger = setup_logging()
TAG = "CosyVoice"
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# Get configuration parameters
self.api_url = config.get("api_url", "http://127.0.0.1:9881/tts")
self.mode = config.get("mode", "预训练音色") # 预训练音色, 3s极速复刻, 跨语种复刻, 自然语言控制
self.speaker = config.get("speaker", None)
self.response_format = config.get("response_format", "wav")
self.timeout = config.get("timeout", 120) # Increased timeout for larger audio files
self.max_retries = config.get("max_retries", 3) # Maximum number of retries
self.retry_delay = config.get("retry_delay", 1) # Delay between retries in seconds
# Optional parameters
self.prompt_audio = config.get("prompt_audio", None)
self.prompt_text = config.get("prompt_text", None)
self.instruct_text = config.get("instruct_text", None)
self.seed = config.get("seed", 0)
self.speed = config.get("speed", 1.0)
self.stream = config.get("stream", False)
# 获取项目根目录
self.project_dir = get_project_dir()
logger.bind(tag=TAG).info(f"CosyVoice V2 TTS initialized with API URL: {self.api_url}")
logger.bind(tag=TAG).info(f"Mode: {self.mode}, Speaker: {self.speaker}")
# Validate configuration
if self.mode == "预训练音色" and not self.speaker:
logger.bind(tag=TAG).warning("预训练音色模式需要指定speaker参数")
if self.mode == "3s极速复刻" and (not self.prompt_audio or not self.prompt_text):
logger.bind(tag=TAG).warning("3s极速复刻模式需要指定prompt_audio和prompt_text参数")
if self.mode == "跨语种复刻" and not self.prompt_audio:
logger.bind(tag=TAG).warning("跨语种复刻模式需要指定prompt_audio参数")
if self.mode == "自然语言控制" and (not self.speaker or not self.instruct_text):
logger.bind(tag=TAG).warning("自然语言控制模式需要指定speaker和instruct_text参数")
def generate_filename(self, extension=".wav"):
"""Generate a unique filename for the TTS output"""
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
def get_absolute_path(self, file_path):
"""将相对路径转换为绝对路径"""
if not file_path:
return None
# 如果已经是绝对路径,直接返回
if os.path.isabs(file_path):
return file_path
# 否则,将其转换为相对于项目根目录的绝对路径
return os.path.join(self.project_dir, file_path)
async def text_to_speak(self, text, output_file):
"""
将文本转换为语音
:param text: 文本
:param output_file: 输出文件路径
:return: 语音文件路径
"""
prompt_audio_file = None
retry_count = 0
last_error = None
temp_output_file = f"{output_file}.temp"
while retry_count < self.max_retries:
try:
# 准备通用表单数据
data = aiohttp.FormData()
data.add_field('text', text)
data.add_field('mode', self.mode)
# 根据模式添加不同的参数
if self.mode == "预训练音色":
if self.speaker:
data.add_field('speaker', self.speaker)
elif self.mode == "3s极速复刻":
if self.prompt_text:
data.add_field('prompt_text', self.prompt_text)
# 添加音频文件
prompt_audio_path = self.get_absolute_path(self.prompt_audio)
if prompt_audio_path and os.path.exists(prompt_audio_path):
logger.bind(tag=TAG).info(f"使用音频文件: {prompt_audio_path}")
try:
prompt_audio_file = open(prompt_audio_path, 'rb')
data.add_field('prompt_audio',
prompt_audio_file,
filename=os.path.basename(prompt_audio_path),
content_type='audio/mpeg' if prompt_audio_path.lower().endswith('.mp3') else 'audio/wav')
except Exception as e:
logger.bind(tag=TAG).error(f"打开音频文件失败: {prompt_audio_path}, 错误: {str(e)}")
raise FileNotFoundError(f"打开音频文件失败: {prompt_audio_path}, 错误: {str(e)}")
else:
logger.bind(tag=TAG).error(f"提示音频文件不存在: {prompt_audio_path}")
raise FileNotFoundError(f"提示音频文件不存在: {prompt_audio_path}")
elif self.mode == "跨语种复刻":
# 添加音频文件
prompt_audio_path = self.get_absolute_path(self.prompt_audio)
if prompt_audio_path and os.path.exists(prompt_audio_path):
logger.bind(tag=TAG).info(f"使用音频文件: {prompt_audio_path}")
try:
prompt_audio_file = open(prompt_audio_path, 'rb')
data.add_field('prompt_audio',
prompt_audio_file,
filename=os.path.basename(prompt_audio_path),
content_type='audio/mpeg' if prompt_audio_path.lower().endswith('.mp3') else 'audio/wav')
except Exception as e:
logger.bind(tag=TAG).error(f"打开音频文件失败: {prompt_audio_path}, 错误: {str(e)}")
raise FileNotFoundError(f"打开音频文件失败: {prompt_audio_path}, 错误: {str(e)}")
else:
logger.bind(tag=TAG).error(f"提示音频文件不存在: {prompt_audio_path}")
raise FileNotFoundError(f"提示音频文件不存在: {prompt_audio_path}")
elif self.mode == "自然语言控制":
if self.speaker:
data.add_field('speaker', self.speaker)
if self.instruct_text:
data.add_field('instruct_text', self.instruct_text)
# 添加通用参数
data.add_field('seed', str(self.seed))
data.add_field('speed', str(self.speed))
data.add_field('stream', str(self.stream).lower())
# 发送请求
timeout = aiohttp.ClientTimeout(total=self.timeout)
# 强制关闭连接,避免连接池问题
connector = aiohttp.TCPConnector(force_close=True, ssl=False)
# 使用临时文件来避免文件损坏
async with aiohttp.ClientSession(timeout=timeout, connector=connector, trust_env=True) as session:
try:
# 使用chunked传输编码,不设置Content-Length
headers = {
'Accept': 'audio/wav, audio/mpeg, audio/*'
}
async with session.post(
self.api_url,
data=data,
headers=headers,
allow_redirects=False,
chunked=True # 使用分块传输编码
) as response:
if response.status != 200:
error_text = await response.text()
logger.bind(tag=TAG).error(f"CosyVoice TTS API 请求失败: {response.status}, {error_text}")
raise Exception(f"CosyVoice TTS API 请求失败: {response.status}, {error_text}")
# 检查响应头中是否有错误信息
content_type = response.headers.get('Content-Type', '')
if 'application/json' in content_type:
error_json = await response.json()
if 'error' in error_json:
raise Exception(f"API返回错误: {error_json['error']}")
# 使用流式读取响应内容到临时文件
async with aiofiles.open(temp_output_file, 'wb') as f:
# 分块读取响应内容
chunk_size = 8192 # 8KB 块大小
total_bytes = 0
try:
async for chunk in response.content.iter_chunked(chunk_size):
if chunk:
await f.write(chunk)
total_bytes += len(chunk)
except aiohttp.ClientPayloadError as e:
# 处理内容长度不匹配的情况
logger.bind(tag=TAG).warning(f"内容传输中断: {str(e)},已接收 {total_bytes} 字节")
# 如果已经接收了一些数据,我们可以继续处理
if total_bytes > 0:
logger.bind(tag=TAG).info(f"尽管传输中断,但已接收 {total_bytes} 字节的数据,将继续处理")
else:
raise
# 验证文件大小
if total_bytes == 0:
raise Exception("接收到的音频数据为空")
# 检查临时文件是否存在且非空
if not os.path.exists(temp_output_file) or os.path.getsize(temp_output_file) == 0:
raise Exception("生成的临时音频文件为空")
# 将临时文件重命名为最终文件
try:
# 如果目标文件已存在,先删除
if os.path.exists(output_file):
os.remove(output_file)
os.rename(temp_output_file, output_file)
except Exception as e:
logger.bind(tag=TAG).error(f"重命名文件失败: {str(e)}")
# 尝试复制文件内容
try:
with open(temp_output_file, 'rb') as src, open(output_file, 'wb') as dst:
dst.write(src.read())
# 删除临时文件
os.remove(temp_output_file)
except Exception as copy_error:
logger.bind(tag=TAG).error(f"复制文件内容失败: {str(copy_error)}")
raise Exception(f"无法创建输出文件: {str(e)}, 复制失败: {str(copy_error)}")
logger.bind(tag=TAG).info(f"TTS 生成成功,保存到: {output_file},大小: {total_bytes} 字节")
return output_file
except aiohttp.ClientError as e:
logger.bind(tag=TAG).error(f"网络请求错误: {str(e)}")
last_error = Exception(f"网络请求错误: {str(e)}")
# 如果是连接问题,重试
retry_count += 1
if retry_count < self.max_retries:
logger.bind(tag=TAG).warning(f"重试 ({retry_count}/{self.max_retries})...")
time.sleep(self.retry_delay)
continue
raise last_error
except Exception as e:
last_error = e
retry_count += 1
if retry_count < self.max_retries:
logger.bind(tag=TAG).warning(f"TTS 生成失败: {str(e)},重试 ({retry_count}/{self.max_retries})...")
# 添加随机延迟,避免同时重试
time.sleep(self.retry_delay + random.uniform(0, 1))
continue
logger.bind(tag=TAG).error(f"CosyVoice TTS 生成失败: {str(e)}")
raise e
finally:
# 确保关闭文件句柄
if prompt_audio_file:
prompt_audio_file.close()
# 清理临时文件
if os.path.exists(temp_output_file):
try:
os.remove(temp_output_file)
except Exception as e:
logger.bind(tag=TAG).warning(f"清理临时文件失败: {str(e)}")
# 如果所有重试都失败
if last_error:
raise last_error
return None

View file

@ -1,5 +1,7 @@
import asyncio import asyncio
import websockets import websockets
import ssl
import os
from config.logger import setup_logging from config.logger import setup_logging
from core.connection import ConnectionHandler from core.connection import ConnectionHandler
from core.handle.musicHandler import MusicHandler from core.handle.musicHandler import MusicHandler
@ -59,12 +61,23 @@ class WebSocketServer:
host = server_config["ip"] host = server_config["ip"]
port = server_config["port"] port = server_config["port"]
self.logger.bind(tag=TAG).info("Server is running at ws://{}:{}", get_local_ip(), port) # 创建 SSL 上下文
ssl_context = None
if server_config.get("use_ssl", True): # 默认启用 SSL
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
cert_path = os.path.join("data", "server.crt")
key_path = os.path.join("data", "server.key")
ssl_context.load_cert_chain(cert_path, key_path)
protocol = "wss" if ssl_context else "ws"
self.logger.bind(tag=TAG).info("Server is running at {}://{}:{}", protocol, get_local_ip(), port)
self.logger.bind(tag=TAG).info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======") self.logger.bind(tag=TAG).info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======")
async with websockets.serve( async with websockets.serve(
self._handle_connection, self._handle_connection,
host, host,
port port,
ssl=ssl_context
): ):
await asyncio.Future() await asyncio.Future()