diff --git a/main.py b/main.py new file mode 100644 index 000000000..eb389a027 --- /dev/null +++ b/main.py @@ -0,0 +1,16 @@ +# 这是一个示例 Python 脚本。 + +# 按 Shift+F10 执行或将其替换为您的代码。 +# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。 + + +def print_hi(name): + # 在下面的代码行中使用断点来调试脚本。 + print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。 + + +# 按装订区域中的绿色按钮以运行脚本。 +if __name__ == '__main__': + print_hi('PyCharm') + +# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 802dcb508..374a3ee0d 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -994,6 +994,19 @@ TTS: # weight: 1 # language_boost: auto # language: "中文" # 指定输出语种,如:中文、英语、日语、韩语等,请根据所选音色支持的语言进行设置,不填则默认为中文 + MinimaxTTS: + # MiniMax 官方 TTS 接口(/v1/t2a_v2),Token Plan 直接使用 + # 开通地址:https://platform.minimaxi.com/ + type: minimax + output_dir: tmp/ + api_key: 你的minimax token plan api key + # host 可选,国内用户保持默认 api.minimaxi.com,海外用户改为 api.minimax.io + # host: api.minimax.io + model: speech-02-turbo + voice_id: female-shaonv + format: mp3 + speed: 1.0 + # language: "中文" # 指定输出语种,如:中文、英语、日语、韩语等,请根据所选音色支持的语言进行设置,不填则默认为中文 AliyunTTS: # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 # 平台地址:https://nls-portal.console.aliyun.com/ diff --git a/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav b/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav new file mode 100644 index 000000000..7d527e0a7 Binary files /dev/null and b/main/xiaozhi-server/config/assets/wakeup_words/d9db46916c443e4aea6c55c6488913cd.wav differ diff --git a/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav b/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav deleted file mode 100644 index 1e7246be4..000000000 Binary files a/main/xiaozhi-server/config/assets/wakeup_words/ed76d459636c2481aec828516c1b4f54.wav and /dev/null differ diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py index 62ae99e7e..ab25d5a49 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_local.py +++ b/main/xiaozhi-server/core/providers/asr/fun_local.py @@ -59,7 +59,7 @@ class ASRProvider(ASRProviderBase): model=self.model_dir, vad_kwargs={"max_single_segment_time": 30000}, disable_update=True, - hub="hf", + hub="ms", # device="cuda:0", # 启用GPU加速 ) @@ -84,9 +84,14 @@ class ASRProvider(ASRProviderBase): use_itn=True, batch_size_s=60, ) - text = lang_tag_filter(result[0]["text"]) + # 兼容不同版本的 FunASR 返回值格式 + raw_text = result[0] + if isinstance(raw_text, dict): + raw_text = raw_text.get("text", "") + text = lang_tag_filter(raw_text) + content = text.get("content", text) if isinstance(text, dict) else text logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}" + f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {content}" ) return text, artifacts.file_path diff --git a/main/xiaozhi-server/core/providers/asr/utils.py b/main/xiaozhi-server/core/providers/asr/utils.py index d1f538aeb..1b78d9720 100644 --- a/main/xiaozhi-server/core/providers/asr/utils.py +++ b/main/xiaozhi-server/core/providers/asr/utils.py @@ -52,14 +52,20 @@ def lang_tag_filter(text: str) -> dict | str: # 移除所有 <|...|> 格式的标签,获取纯文本 clean_text = re.sub(tag_pattern, "", text).strip() - # 如果没有标签,直接返回纯文本 - if not all_tags: + # 过滤掉模型内部特殊 token(如 SPECIAL_TOKEN_19、unk 等) + valid_tags = [ + tag for tag in all_tags + if not tag.startswith("SPECIAL_TOKEN") and not tag.startswith("unk") + ] + + # 如果没有有效标签,直接返回纯文本 + if not valid_tags: return clean_text # 按照 FunASR 的固定顺序提取标签,返回 dict - language = all_tags[0] if len(all_tags) > 0 else "zh" - emotion = all_tags[1] if len(all_tags) > 1 else "NEUTRAL" - # event = all_tags[2] if len(all_tags) > 2 else "Speech" # 事件标签暂不使用 + language = valid_tags[0] if len(valid_tags) > 0 else "zh" + emotion = valid_tags[1] if len(valid_tags) > 1 else "NEUTRAL" + # event = valid_tags[2] if len(valid_tags) > 2 else "Speech" # 事件标签暂不使用 result = { "content": clean_text, diff --git a/main/xiaozhi-server/core/providers/llm/kimi/kimi.py b/main/xiaozhi-server/core/providers/llm/kimi/kimi.py new file mode 100644 index 000000000..a59304999 --- /dev/null +++ b/main/xiaozhi-server/core/providers/llm/kimi/kimi.py @@ -0,0 +1,298 @@ +""" +Kimi k2.6 LLM Provider +- API文档: https://platform.moonshot.cn/ +- 兼容OpenAI API格式,base_url: https://api.moonshot.cn/v1 +- 默认模型: kimi-k2.6 +""" + +import httpx +import openai +from openai.types import CompletionUsage +from config.logger import setup_logging +from core.utils.util import check_model_key +from core.providers.llm.base import LLMProviderBase + +TAG = __name__ +logger = setup_logging() + +# Kimi (moonshot.cn) 思考模式禁用参数 +# THINKING_DISABLED_PARAMS = {"thinking": {"type": "disabled"}} + +# Kimi API 默认配置 +DEFAULT_BASE_URL = "https://api.foxming.com/v1" +DEFAULT_MODEL_NAME = "kimi-k2.6" + + +class LLMProvider(LLMProviderBase): + """ + Kimi k2.6 LLM 提供商 + 基于OpenAI兼容接口实现,支持流式响应和function calling + """ + + def __init__(self, config): + """ + 初始化Kimi LLM Provider + + Args: + config: 配置字典,支持以下字段: + - model_name: 模型名称,默认 "kimi-k2.6" + - api_key: Moonshot API密钥 + - base_url / url: API基础地址,默认 "https://api.moonshot.cn/v1" + - timeout: 超时配置(字典或数值) + - max_tokens: 最大生成token数 + - temperature: 采样温度 + - top_p: 核采样参数 + - frequency_penalty: 频率惩罚 + """ + self.model_name = config.get("model_name", DEFAULT_MODEL_NAME) + self.api_key = config.get("api_key") + + # 支持 base_url 或 url 配置(兼容两种写法) + if "base_url" in config: + self.base_url = config.get("base_url") + elif "url" in config: + self.base_url = config.get("url") + else: + self.base_url = DEFAULT_BASE_URL + + # 超时配置处理(支持字典格式或数值格式) + timeout_config = config.get("timeout") + if isinstance(timeout_config, dict): + custom_timeout = httpx.Timeout( + pool=timeout_config.get("pool", 2.0), + connect=timeout_config.get("connect", 3.0), + write=timeout_config.get("write", 5.0), + read=timeout_config.get("read", 60.0) + ) + elif isinstance(timeout_config, (int, float)) and timeout_config > 0: + custom_timeout = httpx.Timeout(timeout_config) + else: + # 默认5分钟超时 + custom_timeout = httpx.Timeout(300) + + # 可选参数处理(max_tokens, temperature, top_p, frequency_penalty) + param_defaults = { + "max_tokens": int, + "temperature": lambda x: round(float(x), 1), + "top_p": lambda x: round(float(x), 1), + "frequency_penalty": lambda x: round(float(x), 1), + } + + for param, converter in param_defaults.items(): + value = config.get(param) + try: + setattr(self, param, converter(value) if value not in (None, "") else None) + except (ValueError, TypeError): + logger.bind(tag=TAG).warning(f"参数 {param} 值 '{value}' 无效,将使用默认值") + setattr(self, param, None) + + # API密钥有效性检查 + model_key_msg = check_model_key("LLM", self.api_key) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) + + # 创建OpenAI兼容客户端 + self.client = openai.OpenAI( + api_key=self.api_key, + base_url=self.base_url, + timeout=custom_timeout + ) + + logger.bind(tag=TAG).info( + f"Kimi LLM Provider 初始化完成,模型: {self.model_name}," + f"base_url: {self.base_url}" + ) + + @staticmethod + def normalize_dialogue(dialogue): + """ + 自动修复 dialogue 中缺失 content 的消息 + + Args: + dialogue: 对话消息列表 + + Returns: + 修复后的对话消息列表 + """ + for msg in dialogue: + if "role" in msg and "content" not in msg: + msg["content"] = "" + return dialogue + + def _apply_thinking_disabled(self, request_params: dict): + """ + Kimi API 默认禁用思考模式 + 通过 extra_body 参数传递 thinking 配置 + + Args: + request_params: 请求参数字典(会被原地修改) + """ + request_params.setdefault("extra_body", {}).update(THINKING_DISABLED_PARAMS) + logger.bind(tag=TAG).debug("已为 Kimi API 禁用思考模式") + + def _build_request_params(self, dialogue, **kwargs): + """ + 构建OpenAI兼容的请求参数 + + Args: + dialogue: 对话消息列表 + **kwargs: 可选的覆盖参数 + + Returns: + 请求参数字典 + """ + dialogue = self.normalize_dialogue(dialogue) + + request_params = { + "model": self.model_name, + "messages": dialogue, + "stream": True, + } + + optional_params = { + "max_tokens": kwargs.get("max_tokens", self.max_tokens), + "temperature": kwargs.get("temperature", self.temperature), + "top_p": kwargs.get("top_p", self.top_p), + "frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty), + } + + for key, value in optional_params.items(): + if value is not None: + request_params[key] = value + + self._apply_thinking_disabled(request_params) + return request_params + + def response(self, session_id, dialogue, **kwargs): + """ + 流式响应生成器 + + Args: + session_id: 会话ID + dialogue: 对话消息列表 + **kwargs: 可选参数覆盖(max_tokens, temperature, top_p, frequency_penalty) + + Yields: + 文本片段(生成器) + """ + request_params = self._build_request_params(dialogue, **kwargs) + + try: + responses = self.client.chat.completions.create(**request_params) + except openai.AuthenticationError as e: + logger.bind(tag=TAG).error(f"Kimi API 认证失败,请检查API密钥: {e}") + yield "[Kimi API 认证失败,请检查API密钥]" + return + except openai.APIConnectionError as e: + logger.bind(tag=TAG).error(f"Kimi API 连接失败: {e}") + yield "[Kimi API 连接失败,请检查网络]" + return + except openai.RateLimitError as e: + logger.bind(tag=TAG).error(f"Kimi API 请求频率超限: {e}") + yield "[Kimi API 请求频率超限,请稍后再试]" + return + except openai.APIError as e: + logger.bind(tag=TAG).error(f"Kimi API 请求失败: {e}") + yield f"[Kimi API 请求失败: {e}]" + return + except Exception as e: + logger.bind(tag=TAG).error(f"Kimi LLM 未知错误: {e}") + yield f"[Kimi LLM 错误: {e}]" + return + + is_active = True + try: + for chunk in responses: + try: + delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None + content = getattr(delta, "content", "") if delta else "" + except IndexError: + content = "" + + if content: + # 处理 标签:跳过思考过程内容 + if "" in content: + is_active = False + content = content.split("")[0] + if "" in content: + is_active = True + content = content.split("")[-1] + if is_active: + yield content + finally: + responses.close() + + def response_with_functions(self, session_id, dialogue, functions=None, **kwargs): + """ + 支持function calling的流式响应 + + Args: + session_id: 会话ID + dialogue: 对话消息列表 + functions: 工具/函数定义列表 + **kwargs: 可选参数覆盖 + + Yields: + (content, tool_calls) 元组 + """ + dialogue = self.normalize_dialogue(dialogue) + + request_params = { + "model": self.model_name, + "messages": dialogue, + "stream": True, + "tools": functions, + } + + optional_params = { + "max_tokens": kwargs.get("max_tokens", self.max_tokens), + "temperature": kwargs.get("temperature", self.temperature), + "top_p": kwargs.get("top_p", self.top_p), + "frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty), + } + + for key, value in optional_params.items(): + if value is not None: + request_params[key] = value + + self._apply_thinking_disabled(request_params) + + try: + stream = self.client.chat.completions.create(**request_params) + except openai.AuthenticationError as e: + logger.bind(tag=TAG).error(f"Kimi API 认证失败: {e}") + yield "[Kimi API 认证失败]", None + return + except openai.APIConnectionError as e: + logger.bind(tag=TAG).error(f"Kimi API 连接失败: {e}") + yield "[Kimi API 连接失败]", None + return + except openai.RateLimitError as e: + logger.bind(tag=TAG).error(f"Kimi API 请求频率超限: {e}") + yield "[Kimi API 请求频率超限]", None + return + except openai.APIError as e: + logger.bind(tag=TAG).error(f"Kimi API 请求失败: {e}") + yield f"[Kimi API 请求失败: {e}]", None + return + except Exception as e: + logger.bind(tag=TAG).error(f"Kimi LLM function calling 未知错误: {e}") + yield f"[Kimi LLM 错误: {e}]", None + return + + try: + for chunk in stream: + if getattr(chunk, "choices", None): + delta = chunk.choices[0].delta + content = getattr(delta, "content", "") + tool_calls = getattr(delta, "tool_calls", None) + yield content, tool_calls + elif isinstance(getattr(chunk, "usage", None), CompletionUsage): + usage_info = getattr(chunk, "usage", None) + logger.bind(tag=TAG).info( + f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')}," + f"输出 {getattr(usage_info, 'completion_tokens', '未知')}," + f"共计 {getattr(usage_info, 'total_tokens', '未知')}" + ) + finally: + stream.close() \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index ed0b5e978..6462df6d0 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -160,11 +160,22 @@ class LLMProvider(LLMProviderBase): stream = self.client.chat.completions.create(**request_params) + is_active = True try: for chunk in stream: if getattr(chunk, "choices", None): delta = chunk.choices[0].delta content = getattr(delta, "content", "") + # 处理 标签:跳过思考过程内容 + if content: + if "" in content: + is_active = False + content = content.split("")[0] + if "" in content: + is_active = True + content = content.split("")[-1] + if not is_active: + content = "" tool_calls = getattr(delta, "tool_calls", None) yield content, tool_calls elif isinstance(getattr(chunk, "usage", None), CompletionUsage): diff --git a/main/xiaozhi-server/core/providers/tts/mimo_v25.py b/main/xiaozhi-server/core/providers/tts/mimo_v25.py new file mode 100644 index 000000000..2ca8dc2a7 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/mimo_v25.py @@ -0,0 +1,460 @@ +""" +MiMo-V2.5-TTS 语音合成提供商(小米官方 API) +使用小米 MiMo 开放平台的 /chat/completions 接口进行语音合成。 + +API 文档: https://platform.xiaomimimo.com/docs/zh-CN/usage-guide/speech-synthesis-v2.5 +API Key: https://platform.xiaomimimo.com/console/api-keys + +支持的模型: + - mimo-v2.5-tts : 预置音色模式 + - mimo-v2.5-tts-voicedesign : 文本设计音色 + - mimo-v2.5-tts-voiceclone : 音色复刻 + +预置音色列表: + 中文女声: 冰糖、茉莉 + 中文男声: 苏打、白桦 + 英文女声: Mia、Chloe + 英文男声: Milo、Dean + 基础音色: mimo_default + +调用地址: + - 通用: https://api.xiaomimimo.com/v1 + - Token Plan 国内: https://token-plan-cn.xiaomimimo.com/v1 +""" + +import os +import time +import base64 + +from openai import AsyncOpenAI +from openai import APIError as OpenAIAPIError +from openai import APIConnectionError as OpenAIConnectionError +from openai import AuthenticationError as OpenAIAuthError +from openai import RateLimitError as OpenAIRateLimitError + +from config.logger import setup_logging +from core.utils.util import check_model_key +from core.providers.tts.base import TTSProviderBase + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + """MiMo-V2.5-TTS 语音合成提供商(小米官方 API) + + 通过 OpenAI 兼容的 /chat/completions 接口调用 MiMo-V2.5-TTS 服务。 + 目标文本放在 assistant 消息中,风格控制放在 user 消息中。 + + 配置参数: + api_key : API 密钥(必填) + base_url : API 基础 URL(默认: https://token-plan-cn.xiaomimimo.com/v1) + model : TTS 模型名称(默认: mimo-v2.5-tts) + voice : 预置音色 ID(必填,预置模式下) + response_format : 音频输出格式(默认: wav,可选: wav/pcm16/mp3) + style_instruction : 自然语言风格指令(可选,放在 user message 中) + streaming : 是否使用流式调用(默认: false) + output_dir : 输出目录(默认: tmp/) + """ + + # 支持的音频格式 + SUPPORTED_FORMATS = ("wav", "pcm16", "mp3") + + # 预置音色列表 + PRESET_VOICES = { + "mimo_default": "MiMo-默认(因部署集群而异)", + "冰糖": "中文女声", + "茉莉": "中文女声", + "苏打": "中文男声", + "白桦": "中文男声", + "Mia": "英文女声", + "Chloe": "英文女声", + "Milo": "英文男声", + "Dean": "英文男声", + } + + # 支持的模型 + SUPPORTED_MODELS = ( + "mimo-v2.5-tts", + "mimo-v2.5-tts-voicedesign", + "mimo-v2.5-tts-voiceclone", + ) + + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + + # API 认证配置 + self.api_key = config.get("api_key", "") + self.base_url = config.get("base_url", "https://token-plan-cn.xiaomimimo.com/v1") + + # 模型配置 + self.model = config.get("model", "mimo-v2.5-tts") + + # 音色配置 + self.voice = config.get("voice", "") + + # 音频输出格式 + self.response_format = config.get("response_format", "wav") + + # 风格控制(自然语言指令,放在 user message 中) + self.style_instruction = config.get("style_instruction", "") + + # 行为配置 + self.streaming = bool(config.get("streaming", False)) + + # 音色克隆的音频样本路径(仅 voiceclone 模式下使用) + self.clone_audio_file = config.get("clone_audio_file", "") + + # 是否开启文本智能润色(仅 voicedesign 模式下使用) + self.optimize_text_preview = bool(config.get("optimize_text_preview", False)) + + # 请求计数器 + self._request_count = 0 + + # 参数校验 + self._validate_config() + + # 同步 audio_file_type,让 base.py 能正确识别音频格式 + self.audio_file_type = self.response_format + + # 初始化 OpenAI 兼容客户端 + # 小米 API 使用 "api-key" header 而非 "Authorization: Bearer" + self._client = AsyncOpenAI( + api_key="not-used", + base_url=self.base_url, + timeout=60.0, + max_retries=2, + default_headers={"api-key": self.api_key}, + ) + + # 检查 API Key + model_key_msg = check_model_key("TTS", self.api_key) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) + else: + logger.bind(tag=TAG).info( + f"MiMo-V2.5-TTS (小米官方) 初始化完成 | " + f"model={self.model} | voice={self.voice} | " + f"format={self.response_format} | " + f"streaming={self.streaming} | base_url={self.base_url}" + ) + + def _validate_config(self): + """校验并修正配置参数""" + # 校验模型 + if self.model not in self.SUPPORTED_MODELS: + logger.bind(tag=TAG).warning( + f"不支持的模型 '{self.model}',已回退为 'mimo-v2.5-tts'。" + f"支持的模型: {self.SUPPORTED_MODELS}" + ) + self.model = "mimo-v2.5-tts" + + # 校验音频格式 + fmt = self.response_format.lower().strip(".") + if fmt not in self.SUPPORTED_FORMATS: + logger.bind(tag=TAG).warning( + f"不支持的音频格式 '{self.response_format}'," + f"已回退为默认格式 'wav'。支持的格式: {self.SUPPORTED_FORMATS}" + ) + self.response_format = "wav" + else: + self.response_format = fmt + + # 流式模式下必须使用 pcm16 + if self.streaming and self.response_format != "pcm16": + logger.bind(tag=TAG).info( + f"流式模式要求音频格式为 pcm16,已从 '{self.response_format}' 调整为 'pcm16'" + ) + self.response_format = "pcm16" + + # 预置音色模式下必须指定 voice + if self.model == "mimo-v2.5-tts" and not self.voice: + logger.bind(tag=TAG).warning( + f"预置音色模式(model=mimo-v2.5-tts)下,voice 参数为必填项。" + f"可用预置音色: {list(self.PRESET_VOICES.keys())}" + ) + + # 确保输出目录存在 + if self.output_file: + os.makedirs(self.output_file, exist_ok=True) + + def _sanitize_text(self, text: str) -> str: + """清理文本中的非法字符""" + if not text: + return "" + # 过滤控制字符(保留换行和空格) + sanitized = "".join( + ch for ch in text if ch == "\n" or ch == "\r" or ch == "\t" or ("\u0020" <= ch <= "\U0010FFFF") + ) + return sanitized.strip() + + def _build_messages(self, text: str) -> list: + """构建 chat completions 的消息列表 + + 规则: + - assistant message: 必须包含要合成的文本 + - user message: 可选的风格控制指令 + + Args: + text: 要合成的目标文本 + + Returns: + messages 列表 + """ + messages = [] + + # user message: 自然语言风格指令(可选) + # voicedesign 模式下为必填 + if self.style_instruction: + messages.append({ + "role": "user", + "content": self.style_instruction, + }) + + # assistant message: 要合成的文本(必须) + messages.append({ + "role": "assistant", + "content": text, + }) + + return messages + + def _build_audio_param(self) -> dict: + """构建 audio 参数 + + Returns: + audio 参数字典 + """ + audio = { + "format": self.response_format, + } + + if self.model == "mimo-v2.5-tts": + # 预置音色模式 + audio["voice"] = self.voice + elif self.model == "mimo-v2.5-tts-voicedesign": + # 文本设计音色模式 + if self.optimize_text_preview: + audio["optimize_text_preview"] = True + elif self.model == "mimo-v2.5-tts-voiceclone": + # 音色复刻模式 + if self.clone_audio_file and os.path.exists(self.clone_audio_file): + import base64 + mime_type = "audio/mpeg" if self.clone_audio_file.endswith(".mp3") else "audio/wav" + with open(self.clone_audio_file, "rb") as f: + audio_data = base64.b64encode(f.read()).decode("utf-8") + audio["voice"] = f"data:{mime_type};base64,{audio_data}" + else: + logger.bind(tag=TAG).warning( + f"音色复刻模式需要配置有效的 clone_audio_file,当前文件不存在: {self.clone_audio_file}" + ) + + return audio + + def _build_request_params(self, text: str) -> dict: + """构建完整的 API 请求参数 + + Args: + text: 要合成的文本 + + Returns: + 请求参数字典 + """ + params = { + "model": self.model, + "messages": self._build_messages(text), + "audio": self._build_audio_param(), + "stream": self.streaming, + } + return params + + async def text_to_speak(self, text, output_file): + """将文本转换为语音 + + 使用小米 MiMo-V2.5-TTS 的 /chat/completions 接口。 + 支持非流式和流式两种模式(流式目前为兼容模式,实际一次性返回)。 + + Args: + text: 要转换的文本(已由上层做 markdown 清洗和替换词处理) + output_file: 输出文件路径。 + - 为 None 时返回音频 bytes + - 不为 None 时写入文件 + + Returns: + output_file 为 None 时返回音频 bytes;否则不返回值 + + Raises: + ValueError: 参数校验失败 + Exception: API 调用失败 + """ + if not text: + logger.bind(tag=TAG).warning("输入文本为空,跳过语音合成") + return b"" if output_file is None else None + + if not self.api_key: + raise ValueError( + f"{TAG}: api_key 未配置,请前往 https://platform.xiaomimimo.com/console/api-keys 获取" + ) + + # 预置音色模式下必须指定 voice + if self.model == "mimo-v2.5-tts" and not self.voice: + raise ValueError( + f"{TAG}: 预置音色模式下 voice 参数为必填项。" + f"可用音色: {', '.join(self.PRESET_VOICES.keys())}" + ) + + # 清理文本 + clean_text = self._sanitize_text(text) + if not clean_text: + logger.bind(tag=TAG).warning("清理后文本为空,跳过语音合成") + return b"" if output_file is None else None + + # 构建请求参数 + params = self._build_request_params(clean_text) + self._request_count += 1 + req_id = self._request_count + + logger.bind(tag=TAG).info( + f"[请求#{req_id}] 开始语音合成 | text_len={len(clean_text)} | " + f"model={self.model} | voice={self.voice} | format={self.response_format} | " + f"streaming={self.streaming}" + ) + + start_time = time.time() + + try: + if self.streaming: + audio_bytes = await self._speak_streaming(params, req_id, start_time) + else: + audio_bytes = await self._speak_non_streaming(params, req_id, start_time) + + elapsed_ms = (time.time() - start_time) * 1000 + + if audio_bytes: + logger.bind(tag=TAG).info( + f"[请求#{req_id}] 语音合成完成 | 耗时={elapsed_ms:.1f}ms | " + f"音频大小={len(audio_bytes)} bytes" + ) + + if output_file: + with open(output_file, "wb") as f: + f.write(audio_bytes) + logger.bind(tag=TAG).debug( + f"[请求#{req_id}] 音频已写入文件: {output_file}" + ) + else: + return audio_bytes + else: + logger.bind(tag=TAG).warning( + f"[请求#{req_id}] 语音合成返回空数据" + ) + return b"" if output_file is None else None + + except OpenAIAuthError as e: + logger.bind(tag=TAG).error( + f"[请求#{req_id}] API 认证失败,请检查 api_key 是否正确: {e}" + ) + raise Exception(f"{TAG} 认证失败: {e}") + + except OpenAIConnectionError as e: + logger.bind(tag=TAG).error( + f"[请求#{req_id}] API 连接失败,请检查网络或 base_url: {e}" + ) + raise Exception(f"{TAG} 连接失败: {e}") + + except OpenAIRateLimitError as e: + logger.bind(tag=TAG).error( + f"[请求#{req_id}] API 请求频率超限: {e}" + ) + raise Exception(f"{TAG} 请求频率超限: {e}") + + except OpenAIAPIError as e: + logger.bind(tag=TAG).error( + f"[请求#{req_id}] API 调用失败: status={e.status_code} " + f"message={getattr(e, 'message', str(e))}" + ) + raise Exception(f"{TAG} API错误 [{e.status_code}]: {e}") + + except Exception as e: + logger.bind(tag=TAG).error( + f"[请求#{req_id}] 语音合成异常: {e}", exc_info=True + ) + raise Exception(f"{TAG} error: {e}") + + async def _speak_non_streaming(self, params: dict, req_id: int, start_time: float) -> bytes: + """非流式调用:一次性获取完整音频 + + Args: + params: API 请求参数 + req_id: 请求编号 + start_time: 开始时间戳 + + Returns: + 音频 bytes + """ + response = await self._client.chat.completions.create(**params) + + # 从响应中提取音频数据 + message = response.choices[0].message + audio_data = getattr(message, "audio", None) + + if audio_data and hasattr(audio_data, "data"): + audio_bytes = base64.b64decode(audio_data.data) + ttfb_ms = (time.time() - start_time) * 1000 + logger.bind(tag=TAG).debug( + f"[请求#{req_id}] 非流式响应 | 音频大小={len(audio_bytes)} bytes | " + f"TTFB={ttfb_ms:.1f}ms" + ) + return audio_bytes + else: + logger.bind(tag=TAG).warning( + f"[请求#{req_id}] 响应中未找到音频数据,message={message}" + ) + return b"" + + async def _speak_streaming(self, params: dict, req_id: int, start_time: float) -> bytes: + """流式调用:逐块接收音频数据 + + 注意: MiMo-V2.5-TTS 的低延迟流式输出功能暂未上线, + 流式调用接口目前降级为兼容模式,仅在所有推理完成后 + 以流式格式返回一次结果。 + + Args: + params: API 请求参数 + req_id: 请求编号 + start_time: 开始时间戳 + + Returns: + 合并后的音频 bytes + """ + audio_chunks = [] + first_chunk_time = None + + stream = await self._client.chat.completions.create(**params) + + async for chunk in stream: + if not chunk.choices: + continue + + delta = chunk.choices[0].delta + audio = getattr(delta, "audio", None) + + if audio is not None and isinstance(audio, dict) and "data" in audio: + pcm_bytes = base64.b64decode(audio["data"]) + audio_chunks.append(pcm_bytes) + + if first_chunk_time is None: + first_chunk_time = time.time() + ttfb_ms = (first_chunk_time - start_time) * 1000 + logger.bind(tag=TAG).debug( + f"[请求#{req_id}] 流式首包 | TTFB={ttfb_ms:.1f}ms | " + f"chunk_size={len(pcm_bytes)} bytes" + ) + + total_bytes = sum(len(c) for c in audio_chunks) + logger.bind(tag=TAG).debug( + f"[请求#{req_id}] 流式传输完成 | 总数据={total_bytes} bytes | " + f"chunks={len(audio_chunks)}" + ) + + return b"".join(audio_chunks) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/tts/minimax.py b/main/xiaozhi-server/core/providers/tts/minimax.py new file mode 100644 index 000000000..c5c7e2521 --- /dev/null +++ b/main/xiaozhi-server/core/providers/tts/minimax.py @@ -0,0 +1,83 @@ +import json +import requests +from core.utils.util import check_model_key +from core.providers.tts.base import TTSProviderBase +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + + +class TTSProvider(TTSProviderBase): + TTS_PARAM_CONFIG = [ + ("ttsRate", "speed", 0.5, 2, 1, lambda v: round(float(v), 2)), + ] + + def __init__(self, config, delete_audio_file): + super().__init__(config, delete_audio_file) + self.api_key = config.get("api_key") + self.host = config.get("host", "api.minimaxi.com") + self.api_url = f"https://{self.host}/v1/t2a_v2" + self.model = config.get("model", "speech-02-turbo") + if config.get("private_voice"): + self.voice = config.get("private_voice") + else: + self.voice = config.get("voice_id", "female-shaonv") + self.audio_file_type = config.get("format", "pcm") + + # 处理空字符串的情况 + speed = config.get("speed", "1.0") + self.speed = float(speed) if speed else 1.0 + + # 应用百分比调整(如果存在),否则使用公有化配置 + self._apply_percentage_params(config) + + self.output_file = config.get("output_dir", "tmp/") + model_key_msg = check_model_key("TTS", self.api_key) + if model_key_msg: + logger.bind(tag=TAG).error(model_key_msg) + + async def text_to_speak(self, text, output_file): + headers = { + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", + } + payload = { + "model": self.model, + "text": text, + "stream": False, + "output_format": "hex", + "voice_setting": { + "voice_id": self.voice, + "speed": self.speed, + "vol": 1, + "pitch": 0, + }, + "audio_setting": { + "sample_rate": 32000, + "bitrate": 128000, + "format": self.audio_file_type, + "channel": 1, + }, + } + response = requests.post(self.api_url, headers=headers, data=json.dumps(payload)) + if response.status_code == 200: + resp_json = response.json() + base_resp = resp_json.get("base_resp", {}) + if base_resp.get("status_code", 0) != 0: + raise Exception( + f"MiniMax TTS业务错误: {base_resp.get('status_msg', '未知错误')}" + ) + audio_hex = resp_json.get("data", {}).get("audio") + if not audio_hex: + raise Exception("MiniMax TTS返回数据缺少音频内容") + audio_bytes = bytes.fromhex(audio_hex) + if output_file: + with open(output_file, "wb") as f: + f.write(audio_bytes) + else: + return audio_bytes + else: + raise Exception( + f"MiniMax TTS请求失败: {response.status_code} - {response.text}" + ) diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py index 4039f01e4..b6f2e96f3 100644 --- a/main/xiaozhi-server/core/utils/dialogue.py +++ b/main/xiaozhi-server/core/utils/dialogue.py @@ -104,8 +104,6 @@ class Dialogue: if system_message: # 以 为分界点,拆分静态 system prompt 和动态上下文 - # 静态部分(规则、身份等)保持不变,可命中前缀缓存 - # 动态部分(时间、天气、记忆等)作为第二条 system 消息,保持 system 权威性 full_prompt = system_message.content context_match = re.search(r"", full_prompt) if context_match: @@ -115,8 +113,49 @@ class Dialogue: static_part = full_prompt dynamic_part = "" - # 第一段:静态 system prompt(前缀缓存可命中) - dialogue.append({"role": "system", "content": static_part}) + # 合并静态和动态为一条 system 消息 + # 某些 API/中转站不支持多条 system 消息,合并可避免报错 + combined_system = static_part + + # 填充动态上下文 + if dynamic_part: + # 替换时间占位符 + dynamic_part = dynamic_part.replace( + "{{current_time}}", datetime.now().strftime("%H:%M") + ) + + # 填充记忆 + if memory_str is not None: + dynamic_part = re.sub( + r".*?", + f"\n{memory_str}\n", + dynamic_part, + flags=re.DOTALL, + ) + + # 追加说话人信息 + try: + speakers = voiceprint_config.get("speakers", []) + if speakers: + dynamic_part += "\n" + for speaker_str in speakers: + try: + parts = speaker_str.split(",", 2) + if len(parts) >= 2: + name = parts[1].strip() + description = ( + parts[2].strip() if len(parts) >= 3 else "" + ) + dynamic_part += f"\n- {name}:{description}" + except: + pass + dynamic_part += "\n" + except: + pass + + combined_system += dynamic_part + + dialogue.append({"role": "system", "content": combined_system}) # 第二段:few-shot 示例(会话内不变,也是缓存前缀的一部分) non_system_messages = [m for m in self.dialogue if m.role != "system"] @@ -125,45 +164,6 @@ class Dialogue: for m in complete_fewshot: self.getMessages(m, dialogue) - # 第三段:动态上下文 system prompt(时间、记忆、说话人等) - # 保持 system 角色以确保模型权威性,不降级为 user - if system_message and dynamic_part: - # 替换时间占位符 - dynamic_part = dynamic_part.replace( - "{{current_time}}", datetime.now().strftime("%H:%M") - ) - - # 填充记忆 - if memory_str is not None: - dynamic_part = re.sub( - r".*?", - f"\n{memory_str}\n", - dynamic_part, - flags=re.DOTALL, - ) - - # 追加说话人信息 - try: - speakers = voiceprint_config.get("speakers", []) - if speakers: - dynamic_part += "\n" - for speaker_str in speakers: - try: - parts = speaker_str.split(",", 2) - if len(parts) >= 2: - name = parts[1].strip() - description = ( - parts[2].strip() if len(parts) >= 3 else "" - ) - dynamic_part += f"\n- {name}:{description}" - except: - pass - dynamic_part += "\n" - except: - pass - - dialogue.append({"role": "system", "content": dynamic_part}) - # 第四段:实际对话历史(不含 few-shot) actual_messages = [m for m in non_system_messages if not m.is_temporary] complete_actual = self._ensure_tool_calls_complete(actual_messages) diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 9b056c666..467740e0b 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -328,11 +328,14 @@ def audio_bytes_to_data_stream( audio_bytes, file_type, is_opus, callback: Callable[[Any], Any], sample_rate=16000, opus_encoder=None ) -> None: """ - 直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3 + 直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3、pcm/pcm16 """ if file_type == "p3": # 直接用p3解码 return p3.decode_opus_from_bytes_stream(audio_bytes, callback) + elif file_type in ("pcm", "pcm16"): + # PCM 原始数据直接处理,无需 pydub/ffmpeg + pcm_to_data_stream(audio_bytes, is_opus, callback, sample_rate, opus_encoder) else: # 其他格式用pydub audio = AudioSegment.from_file( diff --git a/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/config.yaml b/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/config.yaml new file mode 100644 index 000000000..26bb9d3d2 --- /dev/null +++ b/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/config.yaml @@ -0,0 +1,97 @@ +encoder: SenseVoiceEncoderSmall +encoder_conf: + output_size: 512 + attention_heads: 4 + linear_units: 2048 + num_blocks: 50 + tp_blocks: 20 + dropout_rate: 0.1 + positional_dropout_rate: 0.1 + attention_dropout_rate: 0.1 + input_layer: pe + pos_enc_class: SinusoidalPositionEncoder + normalize_before: true + kernel_size: 11 + sanm_shfit: 0 + selfattention_layer_type: sanm + + +model: SenseVoiceSmall +model_conf: + length_normalized_loss: true + sos: 1 + eos: 2 + ignore_id: -1 + +tokenizer: SentencepiecesTokenizer +tokenizer_conf: + bpemodel: null + unk_symbol: + split_with_space: true + +frontend: WavFrontend +frontend_conf: + fs: 16000 + window: hamming + n_mels: 80 + frame_length: 25 + frame_shift: 10 + lfr_m: 7 + lfr_n: 6 + cmvn_file: null + + +dataset: SenseVoiceCTCDataset +dataset_conf: + index_ds: IndexDSJsonl + batch_sampler: EspnetStyleBatchSampler + data_split_num: 32 + batch_type: token + batch_size: 14000 + max_token_length: 2000 + min_token_length: 60 + max_source_length: 2000 + min_source_length: 60 + max_target_length: 200 + min_target_length: 0 + shuffle: true + num_workers: 4 + sos: ${model_conf.sos} + eos: ${model_conf.eos} + IndexDSJsonl: IndexDSJsonl + retry: 20 + +train_conf: + accum_grad: 1 + grad_clip: 5 + max_epoch: 20 + keep_nbest_models: 10 + avg_nbest_model: 10 + log_interval: 100 + resume: true + validate_interval: 10000 + save_checkpoint_interval: 10000 + +optim: adamw +optim_conf: + lr: 0.00002 +scheduler: warmuplr +scheduler_conf: + warmup_steps: 25000 + +specaug: SpecAugLFR +specaug_conf: + apply_time_warp: false + time_warp_window: 5 + time_warp_mode: bicubic + apply_freq_mask: true + freq_mask_width_range: + - 0 + - 30 + lfr_rate: 6 + num_freq_mask: 1 + apply_time_mask: true + time_mask_width_range: + - 0 + - 12 + num_time_mask: 1 diff --git a/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/configuration.json b/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/configuration.json new file mode 100644 index 000000000..264d8171d --- /dev/null +++ b/main/xiaozhi-server/models/cache/iic/SenseVoiceSmall/configuration.json @@ -0,0 +1,14 @@ +{ + "framework": "pytorch", + "task" : "auto-speech-recognition", + "model": {"type" : "funasr"}, + "pipeline": {"type":"funasr-pipeline"}, + "model_name_in_hub": { + "ms":"", + "hf":""}, + "file_path_metas": { + "init_param":"model.pt", + "config":"config.yaml", + "tokenizer_conf": {"bpemodel": "chn_jpn_yue_eng_ko_spectok.bpe.model"}, + "frontend_conf":{"cmvn_file": "am.mvn"}} +} \ No newline at end of file