Download tts_websocket_server.py from bluece/ttkkk: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/bluece/ttkkk/resolve/main/tts_websocket_server.py
- Command line
-
hf download hf://spaces/bluece/ttkkk/tts_websocket_server.py
-
curl -L -o tts_websocket_server.py https://huggingface.co/spaces/bluece/ttkkk/resolve/main/tts_websocket_server.py
18.6 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| WebSocket 服务器,提供 CosyVoice 的文本转语音功能 | |
| 支持通过 WebSocket 将文本转换为语音并实时流式传输 | |
| 支持上传参考音频、保存音色ID、列出和使用已保存音色 | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import base64 | |
| import sys | |
| import time | |
| import uuid | |
| import hashlib | |
| from typing import Dict, List, Any | |
| import numpy as np | |
| import websockets | |
| import torch | |
| # 配置日志 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger("cosyvoice-websocket") | |
| class TTSWebsocketServer: | |
| def __init__(self, host: str = "0.0.0.0", port: int = 7860): | |
| self.host = host | |
| self.port = port | |
| self.model = None | |
| self.prompt_speech = None | |
| self.sample_rate = 16000 | |
| self.initialized = False | |
| self.mock_mode = False # 是否使用模拟模式 | |
| self.active_connections = [] # 活动连接列表 | |
| self.voice_ids = {} # 保存的声音ID信息 | |
| self.voice_ids_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "saved_voice_ids.json") | |
| self._load_voice_ids() | |
| def _load_voice_ids(self): | |
| """加载保存的声音ID信息""" | |
| if os.path.exists(self.voice_ids_file): | |
| try: | |
| with open(self.voice_ids_file, 'r', encoding='utf-8') as f: | |
| self.voice_ids = json.load(f) | |
| logger.info(f"已加载{len(self.voice_ids)}个声音ID") | |
| except Exception as e: | |
| logger.error(f"加载声音ID文件失败: {e}") | |
| self.voice_ids = {} | |
| else: | |
| logger.info("声音ID文件不存在,创建新文件") | |
| self._save_voice_ids() | |
| def _save_voice_ids(self): | |
| """保存声音ID信息""" | |
| try: | |
| with open(self.voice_ids_file, 'w', encoding='utf-8') as f: | |
| json.dump(self.voice_ids, f, ensure_ascii=False, indent=2) | |
| logger.info(f"已保存{len(self.voice_ids)}个声音ID") | |
| except Exception as e: | |
| logger.error(f"保存声音ID文件失败: {e}") | |
| async def _initialize_model(self): | |
| """初始化模型(仅在第一次使用时)""" | |
| if self.initialized: | |
| return | |
| try: | |
| logger.info("正在初始化模型...") | |
| # 设置Python路径 | |
| cosyvoice_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'CosyVoice') | |
| if cosyvoice_path not in sys.path: | |
| sys.path.append(cosyvoice_path) | |
| # 检查是否有实际模型文件 | |
| model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'CosyVoice/pretrained_models/CosyVoice2-0.5B') | |
| model_file = os.path.join(model_dir, 'model.pt') | |
| if not os.path.exists(model_file): | |
| logger.warning("模型文件不存在,使用模拟模式") | |
| self.mock_mode = True | |
| self.initialized = True | |
| return | |
| # 导入CosyVoice | |
| try: | |
| from cosyvoice.cli.cosyvoice import CosyVoice2 | |
| from cosyvoice.utils.file_utils import load_wav | |
| # 初始化模型 | |
| self.model = CosyVoice2(model_dir, load_jit=False, load_trt=False, load_vllm=False, fp16=True) | |
| # 加载示例提示音频 | |
| prompt_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'CosyVoice/asset/zero_shot_prompt.wav') | |
| self.prompt_speech = load_wav(prompt_file, 16000) | |
| self.sample_rate = self.model.sample_rate | |
| self.initialized = True | |
| logger.info("模型初始化完成") | |
| except Exception as e: | |
| logger.error(f"导入CosyVoice模块失败: {str(e)}") | |
| self.mock_mode = True | |
| self.initialized = True | |
| except Exception as e: | |
| logger.error(f"模型初始化失败: {str(e)}") | |
| self.mock_mode = True | |
| self.initialized = True | |
| def _generate_mock_audio(self, text, duration=2.0): | |
| """生成模拟的音频数据用于测试""" | |
| # 创建一个简单的正弦波 | |
| t = np.linspace(0, duration, int(self.sample_rate * duration), False) | |
| # 生成一个440Hz的音调 | |
| audio = 0.5 * np.sin(2 * np.pi * 440 * t) | |
| # 转换为16位整数 | |
| audio = (audio * 32767).astype(np.int16) | |
| return audio | |
| def _generate_voice_id(self, reference_file, reference_text): | |
| """生成唯一的声音ID""" | |
| timestamp = str(time.time()) | |
| random_str = str(uuid.uuid4()) | |
| id_source = f"{reference_file}_{reference_text}_{timestamp}_{random_str}" | |
| hash_obj = hashlib.md5(id_source.encode()) | |
| short_hash = hash_obj.hexdigest()[:8] | |
| return f"voice_{short_hash}" | |
| async def _save_voice(self, websocket, message): | |
| """保存新的声音ID""" | |
| try: | |
| # 获取参数 | |
| audio_data = message.get("audio_data", "") | |
| reference_text = message.get("reference_text", "") | |
| voice_name = message.get("voice_name", "") | |
| if not audio_data or not reference_text or not voice_name: | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": "缺少必要参数" | |
| })) | |
| return | |
| # 确保模型已初始化 | |
| if not self.initialized: | |
| await websocket.send(json.dumps({"type": "info", "message": "正在初始化模型,请稍候..."})) | |
| await self._initialize_model() | |
| # 解码音频数据 | |
| try: | |
| binary_data = base64.b64decode(audio_data) | |
| audio_array = np.frombuffer(binary_data, dtype=np.int16) | |
| audio_tensor = torch.from_numpy(audio_array).float() / 32768.0 | |
| audio_tensor = audio_tensor.unsqueeze(0) # 添加批次维度 | |
| except Exception as e: | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": f"解码音频数据失败: {str(e)}" | |
| })) | |
| return | |
| if self.mock_mode: | |
| # 模拟模式:生成一个假的声音ID | |
| voice_id = self._generate_voice_id("mock_file", reference_text) | |
| # 保存声音ID信息 | |
| self.voice_ids[voice_id] = { | |
| "name": voice_name, | |
| "gender": "Unknown", | |
| "locale": "zh-CN", | |
| "created_at": time.strftime('%Y-%m-%d %H:%M:%S'), | |
| "reference_text": reference_text | |
| } | |
| self._save_voice_ids() | |
| await websocket.send(json.dumps({ | |
| "type": "voice_saved", | |
| "voice_id": voice_id, | |
| "message": "声音已保存(模拟模式)" | |
| })) | |
| else: | |
| try: | |
| # 生成唯一声音ID | |
| voice_id = self._generate_voice_id("uploaded_file", reference_text) | |
| # 将参考音频特征添加到模型 | |
| self.model.add_zero_shot_spk(reference_text, audio_tensor, voice_id) | |
| # 保存声音特征 | |
| self.model.save_spkinfo() | |
| # 保存声音ID信息 | |
| self.voice_ids[voice_id] = { | |
| "name": voice_name, | |
| "gender": "Unknown", | |
| "locale": "zh-CN", | |
| "created_at": time.strftime('%Y-%m-%d %H:%M:%S'), | |
| "reference_text": reference_text | |
| } | |
| self._save_voice_ids() | |
| await websocket.send(json.dumps({ | |
| "type": "voice_saved", | |
| "voice_id": voice_id, | |
| "message": "声音已保存" | |
| })) | |
| except Exception as e: | |
| logger.error(f"保存声音失败: {str(e)}") | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": f"保存声音失败: {str(e)}" | |
| })) | |
| except Exception as e: | |
| logger.error(f"处理保存声音请求时出错: {str(e)}") | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": f"处理请求时出错: {str(e)}" | |
| })) | |
| async def _handle_tts_request(self, websocket, message): | |
| """处理 TTS 请求""" | |
| try: | |
| # 获取请求参数 | |
| text = message.get("text", "") | |
| if not text: | |
| await websocket.send(json.dumps({"type": "error", "message": "缺少文本参数"})) | |
| return | |
| voice_id = message.get("voice_id", None) | |
| if not voice_id: | |
| await websocket.send(json.dumps({"type": "error", "message": "缺少声音ID参数"})) | |
| return | |
| logger.info(f"TTS 请求: text='{text[:30]}...', voice_id='{voice_id}'") | |
| # 确保模型已初始化 | |
| if not self.initialized: | |
| await websocket.send(json.dumps({"type": "info", "message": "正在初始化模型,请稍候..."})) | |
| await self._initialize_model() | |
| # 发送开始信息 | |
| await websocket.send(json.dumps({"type": "start", "message": "开始生成语音"})) | |
| # 使用模拟模式或真实模型生成语音 | |
| if self.mock_mode: | |
| # 模拟模式:生成简单的音频 | |
| logger.info("使用模拟模式生成音频") | |
| # 根据文本长度确定音频长度 | |
| duration = len(text) * 0.1 # 每个字符0.1秒 | |
| if duration < 1.0: | |
| duration = 1.0 | |
| # 分段生成音频,模拟流式输出 | |
| segment_duration = 1.0 # 每段1秒 | |
| segments = int(duration / segment_duration) | |
| for i in range(segments): | |
| # 生成模拟音频 | |
| audio_data = self._generate_mock_audio(text, segment_duration) | |
| # 将音频数据转换为bytes | |
| audio_bytes = audio_data.tobytes() | |
| audio_b64 = base64.b64encode(audio_bytes).decode('utf-8') | |
| # 发送音频数据 | |
| await websocket.send(json.dumps({ | |
| "type": "audio", | |
| "data": audio_b64, | |
| "sample_rate": self.sample_rate | |
| })) | |
| # 模拟处理延迟 | |
| await asyncio.sleep(0.2) | |
| # 发送完成信息 | |
| await websocket.send(json.dumps({"type": "end", "message": "语音生成完成"})) | |
| else: | |
| # 使用CosyVoice生成语音 | |
| try: | |
| # 使用zero_shot模式生成语音 | |
| results = self.model.inference_zero_shot( | |
| text, "", None, | |
| zero_shot_spk_id=voice_id, | |
| stream=True | |
| ) | |
| # 处理生成结果 | |
| audio_received = False | |
| for result in results: | |
| if 'tts_speech' in result: | |
| audio_received = True | |
| audio_data = result['tts_speech'] | |
| # 将音频数据转换为base64编码 | |
| audio_bytes = audio_data.numpy().tobytes() | |
| audio_b64 = base64.b64encode(audio_bytes).decode('utf-8') | |
| # 发送音频数据 | |
| await websocket.send(json.dumps({ | |
| "type": "audio", | |
| "data": audio_b64, | |
| "sample_rate": self.sample_rate | |
| })) | |
| if not audio_received: | |
| logger.error(f"未收到音频数据") | |
| await websocket.send(json.dumps({"type": "error", "message": "未生成音频数据"})) | |
| return | |
| # 发送完成信息 | |
| await websocket.send(json.dumps({"type": "end", "message": "语音生成完成"})) | |
| except Exception as e: | |
| logger.error(f"生成语音时出错: {str(e)}") | |
| await websocket.send(json.dumps({"type": "error", "message": f"生成语音时出错: {str(e)}"})) | |
| except Exception as e: | |
| logger.error(f"处理 TTS 请求时出错: {str(e)}") | |
| await websocket.send(json.dumps({"type": "error", "message": f"处理请求时出错: {str(e)}"})) | |
| async def _list_voices(self, websocket): | |
| """获取所有可用的语音列表""" | |
| try: | |
| # 确保模型已初始化 | |
| if not self.initialized: | |
| await websocket.send(json.dumps({"type": "info", "message": "正在初始化模型,请稍候..."})) | |
| await self._initialize_model() | |
| if self.mock_mode: | |
| # 模拟模式:返回保存的声音ID | |
| voice_list = [] | |
| for voice_id, info in self.voice_ids.items(): | |
| voice_list.append({ | |
| "ShortName": voice_id, | |
| "FriendlyName": info.get("name", voice_id), | |
| "Gender": info.get("gender", "Unknown"), | |
| "Locale": info.get("locale", "zh-CN") | |
| }) | |
| if not voice_list: | |
| # 如果没有保存的声音ID,添加一些模拟声音 | |
| mock_voices = [ | |
| {"ShortName": "zh-CN-XiaoxiaoNeural", "FriendlyName": "小小 (模拟)", "Gender": "Female", "Locale": "zh-CN"}, | |
| {"ShortName": "zh-CN-YunxiNeural", "FriendlyName": "云溪 (模拟)", "Gender": "Male", "Locale": "zh-CN"} | |
| ] | |
| voice_list.extend(mock_voices) | |
| await websocket.send(json.dumps({"type": "voices", "data": voice_list})) | |
| else: | |
| try: | |
| # 获取模型中可用的声音ID | |
| model_voices = self.model.list_available_spks() | |
| # 构建语音信息列表 | |
| voice_list = [] | |
| for voice_id in model_voices: | |
| info = self.voice_ids.get(voice_id, {}) | |
| voice_list.append({ | |
| "ShortName": voice_id, | |
| "FriendlyName": info.get("name", voice_id), | |
| "Gender": info.get("gender", "Unknown"), | |
| "Locale": info.get("locale", "zh-CN") | |
| }) | |
| await websocket.send(json.dumps({"type": "voices", "data": voice_list})) | |
| except Exception as e: | |
| logger.error(f"获取声音ID列表失败: {str(e)}") | |
| await websocket.send(json.dumps({"type": "error", "message": f"获取声音ID列表失败: {str(e)}"})) | |
| except Exception as e: | |
| logger.error(f"获取语音列表时出错: {str(e)}") | |
| await websocket.send(json.dumps({"type": "error", "message": f"获取语音列表时出错: {str(e)}"})) | |
| async def _handle_connection(self, websocket): | |
| """处理新的 WebSocket 连接""" | |
| self.active_connections.append(websocket) | |
| try: | |
| logger.info(f"新的WebSocket连接: {websocket.remote_address}") | |
| async for message in websocket: | |
| try: | |
| data = json.loads(message) | |
| action = data.get("action", "") | |
| if action == "tts": | |
| await self._handle_tts_request(websocket, data) | |
| elif action == "list_voices": | |
| await self._list_voices(websocket) | |
| elif action == "save_voice": | |
| await self._save_voice(websocket, data) | |
| else: | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": f"未知操作: {action}" | |
| })) | |
| except json.JSONDecodeError: | |
| await websocket.send(json.dumps({ | |
| "type": "error", | |
| "message": "无效的 JSON 数据" | |
| })) | |
| except websockets.exceptions.ConnectionClosed: | |
| logger.info("客户端断开连接") | |
| except Exception as e: | |
| logger.error(f"处理WebSocket连接时出错: {str(e)}") | |
| finally: | |
| if websocket in self.active_connections: | |
| self.active_connections.remove(websocket) | |
| async def start_server(self): | |
| """启动 WebSocket 服务器""" | |
| server = await websockets.serve( | |
| self._handle_connection, | |
| self.host, | |
| self.port | |
| ) | |
| logger.info(f"WebSocket 服务器启动在 ws://{self.host}:{self.port}") | |
| # 保持服务器运行 | |
| await server.wait_closed() | |
| if __name__ == "__main__": | |
| server = TTSWebsocketServer() | |
| try: | |
| asyncio.run(server.start_server()) | |
| except KeyboardInterrupt: | |
| logger.info("服务器已关闭") |