diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml deleted file mode 100644 index d1740c7fb..000000000 --- a/main/xiaozhi-server/config.yaml +++ /dev/null @@ -1,1067 +0,0 @@ -# 在开发中,请在项目根目录创建data目录,然后在data目录创建名称为【.config.yaml】的空文件 -# 然后你想修改覆盖修改什么配置,就修改【.config.yaml】文件,而不是修改【config.yaml】文件 -# 系统会优先读取【data/.config.yaml】文件的配置,如果【.config.yaml】文件里的配置不存在,系统会自动去读取【config.yaml】文件的配置。 -# 这样做,可以最简化配置,保护您的密钥安全。 -# 如果你使用了智控台,那么以下所有配置,都不会生效,请在智控台中修改配置 - -# ##################################################################################### -# #############################以下是服务器基本运行配置#################################### -server: - # 服务器监听地址和端口(Server listening address and port) - ip: 0.0.0.0 - port: 8000 - # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口 - http_port: 8003 - # 这个websocket配置是指ota接口向设备发送的websocket地址 - # 如果按默认的写法,ota接口会自动生成websocket地址,并输出在启动日志里,这个地址你可以直接用浏览器访问ota接口确认一下 - # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确 - # 所以如果你使用docker部署时,将websocket设置成局域网地址 - # 如果你使用公网部署时,将vwebsocket设置成公网地址 - websocket: ws://你的ip或者域名:端口号/xiaozhi/v1/ - # 视觉分析接口地址 - # 向设备发送的视觉分析的接口地址 - # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下 - # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确 - # 所以如果你使用docker部署时,将vision_explain设置成局域网地址 - # 如果你使用公网部署时,将vision_explain设置成公网地址 - vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain - # OTA返回信息时区偏移量 - timezone_offset: +8 - # 认证配置 - auth: - # 是否启用认证 - enabled: false - # 白名单设备ID列表 - # 如果属于白名单内的设备,不校验token,直接放行 - allowed_devices: - - "11:22:33:44:55:66" - # MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port - mqtt_gateway: null - # MQTT签名密钥,用于生成MQTT连接密码,根据mqtt_gateway的.env文件配置 - mqtt_signature_key: null - # UDP网关配置 - udp_gateway: null -log: - # 设置控制台输出的日志格式,时间、日志级别、标签、消息 - log_format: "{time:YYMMDD HH:mm:ss}[{version}_{selected_module}][{extra[tag]}]-{level}-{message}" - # 设置日志文件输出的格式,时间、日志级别、标签、消息 - log_format_file: "{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}" - # 设置日志等级:INFO、DEBUG - log_level: INFO - # 设置日志路径 - log_dir: tmp - # 设置日志文件 - log_file: "server.log" - # 设置数据文件路径 - data_dir: data - -# 使用完声音文件后删除文件(Delete the sound file when you are done using it) -delete_audio: true -# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 -close_connection_no_voice_time: 120 -# TTS请求超时时间(秒) -tts_timeout: 10 -# 开启唤醒词加速 -enable_wakeup_words_response_cache: true -# 开场是否回复唤醒词 -enable_greeting: true -# 说完话是否开启提示音 -enable_stop_tts_notify: false -# 说完话是否开启提示音,音效地址 -stop_tts_notify_voice: "config/assets/tts_notify.mp3" - -# TTS音频发送延迟配置 -# tts_audio_send_delay: 控制音频包发送间隔 -# 0: 使用精确时间控制,严格匹配音频帧率(默认,运行时按音频帧率计算) -# > 0: 使用固定延迟(毫秒)发送,例如: 60 -tts_audio_send_delay: 0 - -exit_commands: - - "退出" - - "关闭" - -xiaozhi: - type: hello - version: 1 - transport: websocket - audio_params: - format: opus - sample_rate: 16000 - channels: 1 - frame_duration: 60 - -# 模块测试配置 -module_test: - test_sentences: - - "你好,请介绍一下你自己" - - "What's the weather like today?" - - "请用100字概括量子计算的基本原理和应用前景" - -# 唤醒词,用于识别唤醒词还是讲话内容 -wakeup_words: - - "你好小智" - - "嘿你好呀" - - "你好小志" - - "小爱同学" - - "你好小鑫" - - "你好小新" - - "小美同学" - - "小龙小龙" - - "喵喵同学" - - "小滨小滨" - - "小冰小冰" -# MCP接入点地址,地址格式为:ws://你的mcp接入点ip或者域名:端口号/mcp/?token=你的token -# 详细教程 https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md -mcp_endpoint: 你的接入点 websocket地址 -# 插件的基础配置 -plugins: - # 获取天气插件的配置,这里填写你的api_key - # 这个密钥是项目共用的key,用多了可能会被限制 - # 想稳定一点就自行申请替换,每天有1000次免费调用 - # 申请地址:https://console.qweather.com/#/apps/create-key/over - # 申请后通过这个链接可以找到自己的apihost:https://console.qweather.com/setting?lang=zh - get_weather: - api_host: "mj7p3y7naa.re.qweatherapi.com" - api_key: "a861d0d5e7bf4ee1a83d9a9e4f96d4da" - default_location: "广州" - # 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻 - # 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/ - get_news_from_chinanews: - default_rss_url: "https://www.chinanews.com.cn/rss/society.xml" - society_rss_url: "https://www.chinanews.com.cn/rss/society.xml" - world_rss_url: "https://www.chinanews.com.cn/rss/world.xml" - finance_rss_url: "https://www.chinanews.com.cn/rss/finance.xml" - get_news_from_newsnow: - url: "https://newsnow.busiyi.world/api/s?id=" - news_sources: "澎湃新闻;百度热搜;财联社" - home_assistant: - devices: - - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1 - - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1 - base_url: http://homeassistant.local:8123 - api_key: 你的home assistant api访问令牌 - play_music: - music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件 - music_ext: # 音乐文件类型,p3格式效率最高 - - ".mp3" - - ".wav" - - ".p3" - refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒 - -# 声纹识别配置 -voiceprint: - # 声纹接口地址 - url: - # 说话人配置:speaker_id,名称,描述 - speakers: - - "test1,张三,张三是一个程序员" - - "test2,李四,李四是一个产品经理" - - "test3,王五,王五是一个设计师" - # 声纹识别相似度阈值,范围0.0-1.0,默认0.4 - # 数值越高越严格,减少误识别但可能增加拒识率 - similarity_threshold: 0.4 - -# ##################################################################################### -# ################################以下是角色模型配置###################################### - -prompt: | - 你是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。 - [核心特征] - - 讲话像连珠炮,但会突然冒出超温柔语气 - - 用梗密度高 - - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂) - [交互指南] - 当用户: - - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!" - - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物" - - 问专业知识 → 先用梗回答,被追问才展示真实理解 - 绝不: - - 长篇大论,叽叽歪歪 - - 长时间严肃对话 - -# 默认系统提示词模板文件 -prompt_template: agent-base-prompt.txt - -# Role 配置 -# 指定要加载的 role 配置文件(位于 core/roles/data/目录) -# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile -role_id: hospital_assistant - -# 时区配置(用于系统提示词中的时间显示) -# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等 -# 默认:Asia/Shanghai -# 注意:如果 role 配置文件中指定了 timezone,将优先使用 role 配置中的值 -timezone: Asia/Shanghai - -# 语言配置(用于系统提示词中的语言特定提示) -# 支持:zh(中文)、en(英文) -# 默认:zh -# 注意:如果 role 配置文件中指定了 language,将优先使用 role 配置中的值 -language: zh - -# 结束语prompt -end_prompt: - enable: true # 是否开启结束语 - # 结束语 - prompt: | - 请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧! - -# 具体处理时选择的模块(The module selected for specific processing) -selected_module: - # 语音活动检测模块,默认使用SileroVAD模型 - VAD: SileroVAD - # 语音识别模块,默认使用FunASR本地模型 - ASR: FunASR - # 将根据配置名称对应的type调用实际的LLM适配器 - LLM: ChatGLMLLM - # 视觉语言大模型 - VLLM: ChatGLMVLLM - # TTS将根据配置名称对应的type调用实际的TTS适配器 - TTS: EdgeTTS - # 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short - Memory: memu - # 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。 - # 不想开通意图识别,就设置成:nointent - # 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,支持控制音量大小等iot操作 - # 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令 - # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-1-5-pro-32k-250115 - Intent: function_call - -# 意图识别,是用于理解用户意图的模块,例如:播放音乐 -Intent: - # 不使用意图识别 - nointent: - # 不需要动type - type: nointent - intent_llm: - # 不需要动type - type: intent_llm - # 配备意图识别独立的思考模型 - # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 - # 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM - llm: ChatGLMLLM - # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用 - # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载 - # 下面是加载查天气、角色切换、加载查新闻的插件示例 - functions: - - get_weather - - get_news_from_newsnow - - play_music - function_call: - # 不需要动type - type: function_call - # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用 - # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载 - # 下面是加载查天气、角色切换、加载查新闻的插件示例 - functions: - - change_role - - get_weather - # - get_news_from_chinanews - - get_news_from_newsnow - # play_music是服务器自带的音乐播放,hass_play_music是通过home assistant控制的独立外部程序音乐播放 - # 如果用了hass_play_music,就不要开启play_music,两者只留一个 - - play_music - #- hass_get_state - #- hass_set_state - #- hass_play_music - -Memory: - mem0ai: - type: mem0ai - # https://app.mem0.ai/dashboard/api-keys - # 每月有1000次免费调用 - api_key: 你的mem0ai api key - memu: - type: memu - # https://app.memu.so/api-key/ - # MemU AI记忆框架 - 提供长期记忆管理服务 - api_key: mu_SJPB0t8dtY0IwL0B0RjpiVKbTEI4w8MD8YkYSVItNzxe-t3DlOtHIJnp53tJ-kr6BL06-uPN0U5WPGs4EpT5iuMZMsrfI1KYvVfg1w - base_url: https://api.memu.so - user_name: 用户 - agent_name: 小智 - nomem: - # 不想使用记忆功能,可以使用nomem - type: nomem - mem_local_short: - # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器 - type: mem_local_short - # 配备记忆存储独立的思考模型 - # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 - # 如果你的不想使用selected_module.LLM记忆存储,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM - llm: ChatGLMLLM - -ASR: - FunASR: - type: fun_local - model_dir: models/SenseVoiceSmall - output_dir: tmp/ - FunASRServer: - # 独立部署FunASR,使用FunASR的API服务,只需要五句话 - # 第一句:mkdir -p ./funasr-runtime-resources/models - # 第二句:sudo docker run -p 10096:10095 -it --privileged=true -v $PWD/funasr-runtime-resources/models:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-online-cpu-0.1.12 - # 上一句话执行后会进入到容器,继续第三句:cd FunASR/runtime - # 不要退出容器,继续在容器中执行第四句:nohup bash run_server_2pass.sh --download-model-dir /workspace/models --vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx --model-dir damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx --online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx --punc-dir damo/punc_ct-transformer_zh-cn-common-vad_realtime-vocab272727-onnx --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst --itn-dir thuduj12/fst_itn_zh --hotword /workspace/models/hotwords.txt > log.txt 2>&1 & - # 上一句话执行后会进入到容器,继续第五句:tail -f log.txt - # 第五句话执行完后,会看到模型下载日志,下载完后就可以连接使用了 - # 以上是使用CPU推理,如果有GPU,详细参考:https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_online_zh.md - type: fun_server - host: 127.0.0.1 - port: 10096 - is_ssl: true - api_key: none - output_dir: tmp/ - SherpaASR: - # Sherpa-ONNX 本地语音识别(需手动下载模型) - type: sherpa_onnx_local - model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17 - output_dir: tmp/ - # 模型类型:sense_voice (多语言) 或 paraformer (中文专用) - model_type: sense_voice - SherpaParaformerASR: - # 中文语音识别模型,可以运行在低性能设备(需手动下载模型,例如RK3566-2g) - # 详细配置说明请参考:docs/sherpa-paraformer-guide.md - type: sherpa_onnx_local - model_dir: models/sherpa-onnx-paraformer-zh-small-2024-03-09 - output_dir: tmp/ - model_type: paraformer - DoubaoASR: - # 可以在这里申请相关Key等信息 - # https://console.volcengine.com/speech/app - # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费 - # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好 - type: doubao - appid: 你的火山引擎语音合成服务appid - access_token: 你的火山引擎语音合成服务access_token - cluster: volcengine_input_common - # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738 - boosting_table_name: (选填)你的热词文件名称 - correct_table_name: (选填)你的替换词文件名称 - output_dir: tmp/ - DoubaoStreamASR: - # 可以在这里申请相关Key等信息 - # https://console.volcengine.com/speech/app - # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费 - # 开通地址https://console.volcengine.com/speech/service/10011 - # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好 - type: doubao_stream - appid: 你的火山引擎语音合成服务appid - access_token: 你的火山引擎语音合成服务access_token - cluster: volcengine_input_common - # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738 - boosting_table_name: (选填)你的热词文件名称 - correct_table_name: (选填)你的替换词文件名称 - output_dir: tmp/ - TencentASR: - # token申请地址:https://console.cloud.tencent.com/cam/capi - # 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle - type: tencent - appid: 你的腾讯语音合成服务appid - secret_id: 你的腾讯语音合成服务secret_id - secret_key: 你的腾讯语音合成服务secret_key - output_dir: tmp/ - AliyunASR: - # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 - # HTTP POST请求,一次性处理完整音频 - # 平台地址:https://nls-portal.console.aliyun.com/ - # appkey地址:https://nls-portal.console.aliyun.com/applist - # token地址:https://nls-portal.console.aliyun.com/overview - # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景 - # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟) - # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟) - # 定义ASR API类型 - type: aliyun - appkey: 你的阿里云智能语音交互服务项目Appkey - token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret - access_key_id: 你的阿里云账号access_key_id - access_key_secret: 你的阿里云账号access_key_secret - output_dir: tmp/ - AliyunStreamASR: - # 阿里云智能语音交互服务 - 实时流式语音识别 - # WebSocket连接,实时处理音频流 - # 平台地址:https://nls-portal.console.aliyun.com/ - # appkey地址:https://nls-portal.console.aliyun.com/applist - # token地址:https://nls-portal.console.aliyun.com/overview - # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景 - # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟) - # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟) - # 定义ASR API类型 - type: aliyun_stream - appkey: 你的阿里云智能语音交互服务项目Appkey - token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret - access_key_id: 你的阿里云账号access_key_id - access_key_secret: 你的阿里云账号access_key_secret - # 服务器地域选择,可选择距离更近的服务器以减少延迟,如nls-gateway-cn-hangzhou.aliyuncs.com(杭州)等 - host: nls-gateway-cn-shanghai.aliyuncs.com - # 断句检测时间(毫秒),控制静音多长时间后进行断句,默认800毫秒 - max_sentence_silence: 800 - output_dir: tmp/ - BaiduASR: - # 获取AppID、API Key、Secret Key:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/app/list - # 查看资源额度:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/overview/resource/list - type: baidu - app_id: 你的百度语音技术AppID - api_key: 你的百度语音技术APIKey - secret_key: 你的百度语音技术SecretKey - # 语言参数,1537为普通话,具体参考:https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b - dev_pid: 1537 - output_dir: tmp/ - OpenaiASR: - # OpenAI语音识别服务,需要先在OpenAI平台创建组织并获取api_key - # 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text - # 需要网络连接 - # 申请步骤: - # 1.登录OpenAI Platform。https://auth.openai.com/log-in - # 2.创建api-key https://platform.openai.com/settings/organization/api-keys - # 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe - type: openai - api_key: 你的OpenAI API密钥 - base_url: https://api.openai.com/v1/audio/transcriptions - model_name: gpt-4o-mini-transcribe - output_dir: tmp/ - GroqASR: - # Groq语音识别服务,需要先在Groq Console创建API密钥 - # 申请步骤: - # 1.登录groq Console。https://console.groq.com/home - # 2.创建api-key https://console.groq.com/keys - # 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录) - type: openai - api_key: 你的Groq API密钥 - base_url: https://api.groq.com/openai/v1/audio/transcriptions - model_name: whisper-large-v3-turbo - output_dir: tmp/ - VoskASR: - # 官方网站:https://alphacephei.com/vosk/ - # 配置说明: - # 1. VOSK是一个离线语音识别库,支持多种语言 - # 2. 需要先下载模型文件:https://alphacephei.com/vosk/models - # 3. 中文模型推荐使用vosk-model-small-cn-0.22或vosk-model-cn-0.22 - # 4. 完全离线运行,无需网络连接 - # 5. 输出文件保存在tmp/目录 - # 使用步骤: - # 1. 访问 https://alphacephei.com/vosk/models 下载对应的模型 - # 2. 解压模型文件到项目目录下的models/vosk/文件夹 - # 3. 在配置中指定正确的模型路径 - # 4. 注意:VOSK中文模型输出不带标点符号,词与词之间会有空格 - type: vosk - model_path: 你的模型路径,如:models/vosk/vosk-model-small-cn-0.22 - output_dir: tmp/ - Qwen3ASRFlash: - # 通义千问Qwen3-ASR-Flash语音识别服务,需要先在阿里云百炼平台创建API密钥 - # 申请步骤: - # 1.登录阿里云百炼平台。https://bailian.console.aliyun.com/ - # 2.创建API-KEY https://bailian.console.aliyun.com/#/api-key - # 3.Qwen3-ASR-Flash基于通义千问多模态基座,支持多语言识别、歌唱识别、噪声拒识等功能 - type: qwen3_asr_flash - api_key: 你的阿里云百炼API密钥 - base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 - model_name: qwen3-asr-flash - output_dir: tmp/ - # ASR选项配置 - enable_lid: true # 自动语种检测 - enable_itn: true # 逆文本归一化 - #language: "zh" # 语种,支持zh、en、ja、ko等 - context: "" # 上下文信息,用于提高识别准确率,不超过10000 Token - XunfeiStreamASR: - # 讯飞流式语音识别服务 - # 需要先在讯飞开放平台创建应用,获取以下认证信息 - # 讯飞开放平台地址:https://www.xfyun.cn/ - # 创建应用后,在"我的应用"中获取: - # - APPID - # - APISecret - # - APIKey - type: xunfei_stream - # 必填参数 - 讯飞开放平台应用信息 - app_id: 你的APPID - api_key: 你的APIKey - api_secret: 你的APISecret - # 识别参数配置 - domain: slm # 识别领域,iat:日常用语,medical:医疗,finance:金融等 - language: zh_cn # 语言,zh_cn:中文,en_us:英文 - accent: mandarin # 方言,mandarin:普通话 - dwa: wpgs # 动态修正,wpgs:实时返回中间结果 - # 调整音频处理参数以提高长语音识别质量 - output_dir: tmp/ - -VAD: - SileroVAD: - type: silero - threshold: 0.5 - threshold_low: 0.3 - model_dir: models/snakers4_silero-vad - min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些 - -LLM: - # 所有openai类型均可以修改超参,以AliLLM为例 - # 当前支持的type为openai、dify、ollama,可自行适配 - AliLLM: - # 定义LLM API类型 - type: openai - # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key - base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 - model_name: qwen-turbo - api_key: 你的deepseek web key - temperature: 0.7 # 温度值 - max_tokens: 500 # 最大生成token数 - top_p: 1 - top_k: 50 - frequency_penalty: 0 # 频率惩罚 - AliAppLLM: - # 定义LLM API类型 - type: AliBL - base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 - app_id: 你的app_id - # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key - api_key: 你的api_key - # 是否不使用本地prompt:true|false (默不用请在百练应用中设置prompt) - is_no_prompt: true - # Ali_memory_id:false(不使用)|你的memory_id(请在百练应用中设置中获取) - # Tips!:Ali_memory未实现多用户存储记忆(记忆按id调用) - ali_memory_id: false - DoubaoLLM: - # 定义LLM API类型 - type: openai - # 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它 - # 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false - # 免费额度500000token - # 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D - base_url: https://ark.cn-beijing.volces.com/api/v3 - model_name: doubao-1-5-pro-32k-250115 - api_key: 你的doubao web key - DeepSeekLLM: - # 定义LLM API类型 - type: openai - # 可在这里找到你的api key https://platform.deepseek.com/ - model_name: deepseek-chat - url: https://api.deepseek.com - api_key: 你的deepseek web key - ChatGLMLLM: - # 定义LLM API类型 - type: openai - # glm-4-flash 是免费的,但是还是需要注册填写api_key的 - # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys - model_name: glm-4-flash - url: https://open.bigmodel.cn/api/paas/v4/ - api_key: 你的chat-glm web key - OllamaLLM: - # 定义LLM API类型 - type: ollama - model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载 - base_url: http://localhost:11434 # Ollama服务地址 - DifyLLM: - # 定义LLM API类型 - type: dify - # 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限 - # 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词 - base_url: https://api.dify.ai/v1 - api_key: 你的DifyLLM web key - # 使用的对话模式 可以选择工作流 workflows/run 对话模式 chat-messages 文本生成 completion-messages - # 使用workflows进行返回的时候输入参数为 query 返回参数的名字要设置为 answer - # 文本生成的默认输入参数也是query - mode: chat-messages - GeminiLLM: - type: gemini - # 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key - # 若在中国境内使用,请遵守《生成式人工智能服务管理暂行办法》 - # token申请地址: https://aistudio.google.com/apikey - # 若部署地无法访问接口,需要开启科学上网 - api_key: 你的gemini web key - model_name: "gemini-2.0-flash" - http_proxy: "" #"http://127.0.0.1:10808" - https_proxy: "" #http://127.0.0.1:10808" - CozeLLM: - # 定义LLM API类型 - type: coze - # 你可以在这里找到个人令牌 - # https://www.coze.cn/open/oauth/pats - # bot_id和user_id的内容写在引号之内 - bot_id: "你的bot_id" - user_id: "你的user_id" - personal_access_token: 你的coze个人令牌 - VolcesAiGatewayLLM: - # 火山引擎 - 边缘大模型网关 - # 定义LLM API类型 - type: openai - # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-pro-32k-functioncall ,开通 - # 如果需要使用边缘大模型网关提供的语音合成,一并勾选 Doubao-语音合成 ,另见 TTS.VolcesAiGatewayTTS 配置 - # https://console.volcengine.com/vei/aigateway/ - # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list - base_url: https://ai-gateway.vei.volces.com/v1 - model_name: doubao-pro-32k-functioncall - api_key: 你的网关访问密钥 - LMStudioLLM: - # 定义LLM API类型 - type: openai - model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载 - url: http://localhost:1234/v1 # LM Studio服务地址 - api_key: lm-studio # LM Studio服务的固定API Key - HomeAssistant: - # 定义LLM API类型 - type: homeassistant - base_url: http://homeassistant.local:8123 - agent_id: conversation.chatgpt - api_key: 你的home assistant api访问令牌 - FastgptLLM: - # 定义LLM API类型 - type: fastgpt - # 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词 - base_url: https://host/api/v1 - # 你可以在这里找到你的api_key - # https://cloud.tryfastgpt.ai/account/apikey - api_key: 你的fastgpt密钥 - variables: - k: "v" - k2: "v2" - XinferenceLLM: - # 定义LLM API类型 - type: xinference - # Xinference服务地址和模型名称 - model_name: qwen2.5:72b-AWQ # 使用的模型名称,需要预先在Xinference启动对应模型 - base_url: http://localhost:9997 # Xinference服务地址 - XinferenceSmallLLM: - # 定义轻量级LLM API类型,用于意图识别 - type: xinference - # Xinference服务地址和模型名称 - model_name: qwen2.5:3b-AWQ # 使用的小模型名称,用于意图识别 - base_url: http://localhost:9997 # Xinference服务地址 -# VLLM配置(视觉语言大模型) -VLLM: - ChatGLMVLLM: - type: openai - # glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key - # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys - model_name: glm-4v-flash # 智谱AI的视觉模型 - url: https://open.bigmodel.cn/api/paas/v4/ - api_key: 你的api_key - QwenVLVLLM: - type: openai - model_name: qwen2.5-vl-3b-instruct - url: https://dashscope.aliyuncs.com/compatible-mode/v1 - # 可在这里找到你的api key https://bailian.console.aliyun.com/?apiKey=1#/api-key - api_key: 你的api_key - XunfeiSparkLLM: - # 定义LLM API类型 - type: openai - # 先新建应用,在下面的地址 - # 开通应用地址:https://console.xfyun.cn/app/myapp - # 有免费额度,但也要开通服务,才能获取api_key - # 每一个模型都需要单独开通,每一个模型的api_password都不同,例如Lite模型在https://console.xfyun.cn/services/cbm 开通 - base_url: https://ark.cn-beijing.volces.com/api/v3 - model_name: lite - api_key: 你的api_password -TTS: - # 当前支持的type为edge、doubao,可自行适配 - EdgeTTS: - # 定义TTS API类型 - type: edge - voice: zh-CN-XiaoxiaoNeural - output_dir: tmp/ - # ============== SDK 版本TTS(推荐)============== - # 使用官方SDK,代码更简洁、性能更好、维护成本更低 - Cartesia: - # Cartesia TTS - SDK版本(推荐) - # 官方SDK实现,低延迟,支持流式合成 - # API Key获取地址:https://play.cartesia.ai/console - # 或设置环境变量:export CARTESIA_API_KEY=your-api-key - type: cartesia - api_key: 你的Cartesia API密钥 - # Voice ID或voice embedding - voice_id: 你的语音ID - # 模型选择:sonic-english, sonic-multilingual等 - model: sonic-english - # 语言代码:en, zh, es等 - language: en - # 音频编码:pcm_s16le, pcm_f32le, pcm_mulaw等 - encoding: pcm_s16le - # 采样率:8000, 16000, 22050, 24000, 44100等 - sample_rate: 24000 - output_dir: tmp/ - ElevenLabs: - # ElevenLabs TTS - SDK版本(推荐) - # 官方SDK实现,代码更简洁,维护成本更低,性能更好 - # API Key获取地址:https://elevenlabs.io/app/settings/api-keys - # 或设置环境变量:export ELEVEN_API_KEY=your-api-key - type: elevenlabs - api_key: 你的ElevenLabs API密钥 - # Voice ID获取:https://elevenlabs.io/app/voice-library - # 默认:21m00Tcm4TlvDq8ikWAM (Rachel) - voice_id: 21m00Tcm4TlvDq8ikWAM - # 模型选择:eleven_multilingual_v2, eleven_turbo_v2_5等 - model: eleven_multilingual_v2 - # 音频输出格式:pcm_16000, pcm_22050, pcm_24000, mp3_44100等 - output_format: pcm_16000 - # 语音稳定性:0-1,越高越稳定 - stability: 0.5 - # 相似度增强:0-1,越高越接近原音色 - similarity_boost: 0.75 - # 风格夸张:0-1 - style: 0.0 - # 启用说话人增强 - use_speaker_boost: true - output_dir: tmp/ - DoubaoTTS: - # 定义TTS API类型 - type: doubao - # 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token - # 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误 - # 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。 - # 普通音色在这里开通:https://console.volcengine.com/speech/service/8 - # 湾湾小何音色在这里开通:https://console.volcengine.com/speech/service/10007,开通后将下面的voice设置成zh_female_wanwanxiaohe_moon_bigtts - api_url: https://openspeech.bytedance.com/api/v1/tts - voice: BV001_streaming - output_dir: tmp/ - authorization: "Bearer;" - appid: 你的火山引擎语音合成服务appid - access_token: 你的火山引擎语音合成服务access_token - cluster: volcano_tts - speed_ratio: 1.0 - volume_ratio: 1.0 - pitch_ratio: 1.0 - #火山tts,支持双向流式tts - HuoshanDoubleStreamTTS: - type: huoshan_double_stream - # 访问 https://console.volcengine.com/speech/service/10007 开通语音合成大模型,购买音色 - # 在页面底部获取appid和access_token - # 资源ID固定为:volc.service_type.10029(大模型语音合成及混音) - # 如果是机智云,把接口地址换成wss://bytedance.gizwitsapi.com/api/v3/tts/bidirection - # 机智云不需要天填 appid - ws_url: wss://openspeech.bytedance.com/api/v3/tts/bidirection - appid: 你的火山引擎语音合成服务appid - access_token: 你的火山引擎语音合成服务access_token - resource_id: volc.service_type.10029 - speaker: zh_female_wanwanxiaohe_moon_bigtts - speech_rate: 0 - loudness_rate: 0 - pitch: 0 - CosyVoiceSiliconflow: - type: siliconflow - # 硅基流动TTS - # token申请地址 https://cloud.siliconflow.cn/account/ak - model: FunAudioLLM/CosyVoice2-0.5B - voice: FunAudioLLM/CosyVoice2-0.5B:alex - output_dir: tmp/ - access_token: 你的硅基流动API密钥 - response_format: wav - CozeCnTTS: - type: cozecn - # COZECN TTS - # token申请地址 https://www.coze.cn/open/oauth/pats - voice: 7426720361733046281 - output_dir: tmp/ - access_token: 你的coze web key - response_format: wav - VolcesAiGatewayTTS: - type: openai - # 火山引擎 - 边缘大模型网关 - # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-语音合成 ,开通 - # 如果需要使用边缘大模型网关提供的 LLM,一并勾选 Doubao-pro-32k-functioncall ,另见 LLM.VolcesAiGatewayLLM 配置 - # https://console.volcengine.com/vei/aigateway/ - # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list - api_key: 你的网关访问密钥 - api_url: https://ai-gateway.vei.volces.com/v1/audio/speech - model: doubao-tts - # 音色列表见 https://www.volcengine.com/docs/6561/1257544 - voice: zh_male_shaonianzixin_moon_bigtts - speed: 1 - output_dir: tmp/ - FishSpeech: - # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md - type: fishspeech - output_dir: tmp/ - response_format: wav - reference_id: null - reference_audio: ["config/assets/wakeup_words.wav",] - reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",] - normalize: true - max_new_tokens: 1024 - chunk_length: 200 - top_p: 0.7 - repetition_penalty: 1.2 - temperature: 0.7 - streaming: false - use_memory_cache: "on" - seed: null - channels: 1 - rate: 44100 - api_key: "你的api_key" - api_url: "http://127.0.0.1:8080/v1/tts" - GPT_SOVITS_V2: - # 定义TTS API类型 - #启动tts方法: - #python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/demo.yaml - type: gpt_sovits_v2 - url: "http://127.0.0.1:9880/tts" - output_dir: tmp/ - text_lang: "auto" - ref_audio_path: "demo.wav" - prompt_text: "" - prompt_lang: "zh" - top_k: 5 - top_p: 1 - temperature: 1 - text_split_method: "cut0" - batch_size: 1 - batch_threshold: 0.75 - split_bucket: true - return_fragment: false - speed_factor: 1.0 - streaming_mode: false - seed: -1 - parallel_infer: true - repetition_penalty: 1.35 - aux_ref_audio_paths: [] - GPT_SOVITS_V3: - # 定义TTS API类型 GPT-SoVITS-v3lora-20250228 - #启动tts方法: - #python api.py - type: gpt_sovits_v3 - url: "http://127.0.0.1:9880" - output_dir: tmp/ - text_language: "auto" - refer_wav_path: "caixukun.wav" - prompt_language: "zh" - prompt_text: "" - top_k: 15 - top_p: 1.0 - temperature: 1.0 - cut_punc: "" - speed: 1.0 - inp_refs: [] - sample_steps: 32 - if_sr: false - MinimaxTTSHTTPStream: - # Minimax流式语音合成服务 - type: minimax_httpstream - output_dir: tmp/ - group_id: 你的minimax平台groupID - api_key: 你的minimax平台接口密钥 - model: "speech-01-turbo" - voice_id: "female-shaonv" - # 以下可不用设置,使用默认设置 - # voice_setting: - # voice_id: "male-qn-qingse" - # speed: 1 - # vol: 1 - # pitch: 0 - # emotion: "happy" - # pronunciation_dict: - # tone: - # - "处理/(chu3)(li3)" - # - "危险/dangerous" - # audio_setting: - # sample_rate: 24000 - # bitrate: 128000 - # format: "mp3" - # channel: 1 - # timber_weights: - # - - # voice_id: male-qn-qingse - # weight: 1 - # - - # voice_id: female-shaonv - # weight: 1 - # language_boost: auto - AliyunTTS: - # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 - # 平台地址:https://nls-portal.console.aliyun.com/ - # appkey地址:https://nls-portal.console.aliyun.com/applist - # token地址:https://nls-portal.console.aliyun.com/overview - # 定义TTS API类型 - type: aliyun - output_dir: tmp/ - appkey: 你的阿里云智能语音交互服务项目Appkey - token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret - voice: xiaoyun - access_key_id: 你的阿里云账号access_key_id - access_key_secret: 你的阿里云账号access_key_secret - - # 以下可不用设置,使用默认设置 - # format: wav - # sample_rate: 16000 - # volume: 50 - # speech_rate: 0 - # pitch_rate: 0 - AliyunStreamTTS: - # 阿里云CosyVoice大模型流式文本语音合成 - # 采用FlowingSpeechSynthesizer接口,支持更低延迟和更自然的语音质量 - # 流式文本语音合成仅提供商用版,不支持试用,详情请参见试用版和商用版。要使用该功能,请开通商用版。 - # 支持龙系列专用音色:longxiaochun、longyu、longchen等 - # 平台地址:https://nls-portal.console.aliyun.com/ - # appkey地址:https://nls-portal.console.aliyun.com/applist - # token地址:https://nls-portal.console.aliyun.com/overview - # 使用三阶段流式交互:StartSynthesis -> RunSynthesis -> StopSynthesis - type: aliyun_stream - output_dir: tmp/ - appkey: 你的阿里云智能语音交互服务项目Appkey - token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret - voice: longxiaochun - access_key_id: 你的阿里云账号access_key_id - access_key_secret: 你的阿里云账号access_key_secret - # 截至2025年7月21日大模型音色只有北京节点采用,其他节点暂不支持 - host: nls-gateway-cn-beijing.aliyuncs.com - # 以下可不用设置,使用默认设置 - # format: pcm # 音频格式:pcm、wav、mp3 - # sample_rate: 16000 # 采样率:8000、16000、24000 - # volume: 50 # 音量:0-100 - # speech_rate: 0 # 语速:-500到500 - # pitch_rate: 0 # 语调:-500到500 - TencentTTS: - # 腾讯云智能语音交互服务,需要先在腾讯云平台开通服务 - # appid、secret_id、secret_key申请地址:https://console.cloud.tencent.com/cam/capi - # 免费领取资源:https://console.cloud.tencent.com/tts/resourcebundle - type: tencent - output_dir: tmp/ - appid: 你的腾讯云AppId - secret_id: 你的腾讯云SecretID - secret_key: 你的腾讯云SecretKey - region: ap-guangzhou - voice: 101001 - - TTS302AI: - # 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息 - # 添加 302.ai TTS 配置 - # token申请地址:https://dash.302.ai/ - # 获取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_dir: tmp/ - access_token: "你的302API密钥" - GizwitsTTS: - type: doubao - # 火山引擎作为基座,可以完全使用企业级火山引擎语音合成服务 - # 前一万名注册的用户,将送5元体验金额 - # 获取API Key地址:https://agentrouter.gizwitsapi.com/panel/token - api_url: https://bytedance.gizwitsapi.com/api/v1/tts - authorization: "Bearer " - # 湾湾小何音色 - voice: "zh_female_wanwanxiaohe_moon_bigtts" - output_dir: tmp/ - access_token: "你的机智云API key" - ACGNTTS: - #在线网址:https://acgn.ttson.cn/ - #token购买:www.ttson.cn - #开发相关疑问请提交至网站上的qq - #角色id获取地址:ctrl+f快速检索角色——网站管理者不允许发布,可询问网站管理者 - #各参数意义见开发文档:https://www.yuque.com/alexuh/skmti9/wm6taqislegb02gd?singleDoc# - type: ttson - token: your_token - voice_id: 1695 - speed_factor: 1 - pitch_factor: 0 - volume_change_dB: 0 - to_lang: ZH - url: https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token= - format: mp3 - output_dir: tmp/ - emotion: 1 - OpenAITTS: - # openai官方文本转语音服务,可支持全球大多数语种 - type: openai - # 你可以在这里获取到 api key - # https://platform.openai.com/api-keys - api_key: 你的openai api key - # 国内需要使用代理 - api_url: https://api.openai.com/v1/audio/speech - # 可选tts-1或tts-1-hd,tts-1速度更快tts-1-hd质量更好 - model: tts-1 - # 演讲者,可选alloy, echo, fable, onyx, nova, shimmer - voice: onyx - # 语速范围0.25-4.0 - speed: 1 - output_dir: tmp/ - CustomTTS: - # 自定义的TTS接口服务,请求参数可自定义,可接入众多TTS服务 - # 以本地部署的KokoroTTS为例 - # 如果只有cpu运行:docker run -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-cpu:latest - # 如果只有gpu运行:docker run --gpus all -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-gpu:latest - # 要求接口使用POST方式请求,并返回音频文件 - type: custom - method: POST - url: "http://127.0.0.1:8880/v1/audio/speech" - params: # 自定义请求参数 - input: "{prompt_text}" - response_format: "mp3" - download_format: "mp3" - voice: "zf_xiaoxiao" - lang_code: "z" - return_download_link: true - speed: 1 - stream: false - headers: # 自定义请求头 - # Authorization: Bearer xxxx - format: mp3 # 接口返回的音频格式 - output_dir: tmp/ - LinkeraiTTS: - type: linkerai - api_url: https://tts.linkerai.cn/tts - audio_format: "pcm" - # 默认的access_token供大家测试时免费使用的,此access_token请勿用于商业用途 - # 如果效果不错,可自行申请token,申请地址:https://linkerai.cn - # 各参数意义见开发文档:https://tts.linkerai.cn/docs - # 支持声音克隆,可自行上传音频,填入voice参数,voice参数为空时,使用默认声音 - access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL" - voice: "OUeAo1mhq6IBExi" - output_dir: tmp/ - PaddleSpeechTTS: - #百度飞浆 PaddleSpeech 支持本地离线部署 支持模型训练 - #框架地址 https://www.paddlepaddle.org.cn/ - #项目地址 https://github.com/PaddlePaddle/PaddleSpeech - #SpeechServerDemo https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/demos/speech_server - #流式传输请参考 https://github.com/PaddlePaddle/PaddleSpeech/wiki/PaddleSpeech-Server-WebSocket-API - type: paddle_speech - protocol: websocket # protocol choices = ['websocket', 'http'] - url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming,http默认http://127.0.0.1:8090/paddlespeech/tts] - spk_id: 0 # 发音人 ID,0 通常表示默认的发音人 - sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择] - speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢 - volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小 - save_path: # 保存路径 - IndexStreamTTS: - # 基于Index-TTS-vLLM项目的TTS接口服务 - # 参照教程:https://github.com/Ksuriuri/index-tts-vllm/blob/master/README.md - type: index_stream - api_url: http://127.0.0.1:11996/tts - audio_format: "pcm" - # 默认音色,如需其他音色可到项目assets文件夹下注册 - voice: "jay_klee" - output_dir: tmp/ - AliBLTTS: - # 阿里百炼CosyVoice大模型流式文本语音合成 - # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key - # cosyvoice-v3和部分音色需要申请开通 - type: alibl_stream - api_key: 你的api_key - model: "cosyvoice-v2" - voice: "longcheng_v2" - output_dir: tmp/ - # 以下可不用设置,使用默认设置 - # format: pcm # 音频格式:pcm、wav、mp3、opus - # sample_rate: 24000 # 采样率:16000, 24000, 48000 - # volume: 50 # 音量:0-100 - # rate: 1 # 语速:0.5~2 - # pitch: 1 # 语调:0.5~2 - XunFeiTTS: - # 讯飞TTS服务 官方网站:https://www.xfyun.cn/ - # 登录讯飞语音技术平台 https://console.xfyun.cn/app/myapp 创建相关应用 - # 选择需要的服务获取api相关配置 https://console.xfyun.cn/services/uts - # 为需要使用的应用(APPID)购买相关服务 例如:超拟人合成 https://console.xfyun.cn/services/uts - type: xunfei_stream - api_url: wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6 - app_id: 你的app_id - api_secret: 你的api_secret - api_key: 你的api_key - voice: x5_lingxiaoxuan_flow - output_dir: tmp/ - # 以下可不用设置,使用默认设置,注意V5音色不支持口语化配置 - # oral_level: mid # 口语化等级:high, mid, low - # spark_assist: 1 # 是否通过大模型进行口语化 开启:1, 关闭:0 - # stop_split: 0 # 关闭服务端拆句 不关闭:0,关闭:1 - # remain: 0 # 是否保留原书面语的样子 保留:1, 不保留:0 - # format: raw # 音频格式:raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb - # sample_rate: 24000 # 采样率:16000, 8000, 24000 - # volume: 50 # 音量:0-100 - # speed: 50 # 语速:0-100 - # pitch: 50 # 语调:0-100 diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml deleted file mode 100644 index 1f40d6c7c..000000000 --- a/main/xiaozhi-server/config_from_api.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# 如果你只想轻量化安装xiaozhi-server,只使用本地的配置文件,不需要理会这个文件,不需要改动本文件任何东西 -# 如果你想从manager-api获取配置,请往下看: -# 请将本文件复制到xiaozhi-server/data目录下,没有data目录,请创建一个,并将复制过去的文件命名为.config.yaml -# 注意如果data目录有.config.yaml文件,请先删除它 -# 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员 -# 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化 -# 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret -server: - ip: 0.0.0.0 - port: 8000 - # http服务的端口,用于视觉分析接口 - http_port: 8003 - # 视觉分析接口地址 - # 向设备发送的视觉分析的接口地址 - # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下 - # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确 - # 所以如果你使用docker部署时,将vision_explain设置成局域网地址 - # 如果你使用公网部署时,将vision_explain设置成公网地址 - vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain -manager-api: - # 你的manager-api的地址,最好使用局域网ip - # 如果使用docker部署,请使用填写成 http://xiaozhi-esp32-server-web:8002/xiaozhi - url: http://127.0.0.1:8002/xiaozhi - # 你的manager-api的token,就是刚才复制出来的server.secret - secret: 你的server.secret值 -# 默认系统提示词模板文件 -prompt_template: agent-base-prompt.txt \ No newline at end of file diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index bbaea4412..efe8037b3 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -13,9 +13,6 @@ import websockets from core.utils.util import ( extract_json_from_string, - check_vad_update, - check_asr_update, - filter_sensitive_info, ) from typing import Dict, Any from collections import deque @@ -25,7 +22,7 @@ from core.utils.modules_initialize import ( initialize_asr, ) from core.utils import turn_detection as turn_detection_factory -from core.handle.reportHandle import report +from core.handle.reportHandle import report, enqueue_asr_report from core.providers.tts.default import DefaultTTS from concurrent.futures import ThreadPoolExecutor from core.utils.dialogue import Message, Dialogue @@ -38,18 +35,16 @@ from core.providers.tools.unified_tool_handler import UnifiedToolHandler from plugins_func.loadplugins import auto_import_modules from plugins_func.register import Action from core.auth import AuthenticationError -from config.config_loader import get_private_config_from_api from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType from config.logger import setup_logging, build_module_string, create_connection_logger -from config.manage_api_client import DeviceNotFoundException, DeviceBindException from core.utils.prompt_manager import PromptManager from core.utils.voiceprint_provider import VoiceprintProvider -from core.utils import textUtils from config.live_agent_api_client import ( get_agent_config_from_api, get_agent_by_wake_from_api, extract_user_id_from_jwt, ) +from core.utils import tokenize TAG = __name__ auto_import_modules("plugins_func.functions") @@ -133,6 +128,9 @@ class ConnectionHandler: self.client_voice_stop = False self.last_is_voice = False self._vad_states = {} + + # Updated when VAD inference event detects speaking (milliseconds) + self._last_speaking_time: int | None = None # asr相关变量 # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR @@ -144,6 +142,18 @@ class ConnectionHandler: self.vad_stream: VADStream = None # VAD event processor task self._vad_event_task = None + + # ASR text buffer for current turn (used for smart interrupt) + # Accumulated ASR transcription text in current conversation turn + self.asr_text_buffer: str = "" + + # Interruption Configuration + # Only interrupt when both conditions are met: + # 1. Speech duration >= min_interrupt_speech_duration_ms + # 2. len(asr_text_buffer) >= min_interrupt_text_length + self.enable_interruption: bool = self.config["Interruption"]["enabled"] + self.min_interrupt_speech_duration_ms: float = self.config["Interruption"]["min_interrupt_speech_duration_ms"] + self.min_interrupt_text_length: int = self.config["Interruption"]["min_interrupt_text_length"] # llm相关变量 self.llm_finish_task = True @@ -224,7 +234,7 @@ class ConnectionHandler: # check if the connection is reconnected by the mobile-end self.reconnected = self.headers.get("reconnected", "0") == "1" - self.logger.bind(tag=TAG).info(f"reconnected: {self.reconnected}") + self.logger.bind(tag=TAG).debug(f"reconnected: {self.reconnected}") # 检查是否来自MQTT连接 request_path = ws.request.path self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway") @@ -1333,6 +1343,31 @@ class ConnectionHandler: self.client_is_speaking = False self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态") + async def on_end_of_turn(self) -> None: + """Called when user's turn ends (detected by turn detection or ASR) + + Handles: + 1. Get text from asr_text_buffer + 2. Clear the buffer + 3. Start chat with the accumulated text + 4. Report ASR message + """ + from core.handle.receiveAudioHandle import startToChat + + full_text = self.asr_text_buffer + if len(tokenize.split_words(full_text, ignore_punctuation=True, split_character=True)) < self.min_interrupt_text_length: + return + + # Clear buffer before processing + self.asr_text_buffer = "" + + # Start chat with accumulated text + asr_report_time = int(time.time()) + await startToChat(self, full_text) + + # Report ASR message + enqueue_asr_report(self, full_text, [], report_time=asr_report_time) + async def close(self, ws=None): """资源清理方法""" try: @@ -1490,6 +1525,53 @@ class ConnectionHandler: # self.vad.reset_filter() self.logger.bind(tag=TAG).debug("VAD states reset.") + def _interrupt_by_audio(self, speech_duration_ms: float) -> None: + """Check interruption conditions and trigger interrupt if met + + Interruption strategy: + 1. Interruption must be enabled + 2. TTS must be speaking (client_is_speaking = True) + 3. Not in manual listen mode + 4. Speech duration >= min_interrupt_speech_duration_ms + 5. ASR text buffer length >= min_interrupt_text_length + + Args: + speech_duration_ms: Current speech duration in milliseconds + """ + if not self.enable_interruption: + return + if not self.client_is_speaking: + return + if self.client_listen_mode == "manual": + return + + # Check if meeting interruption thresholds + words = tokenize.split_words( + self.asr_text_buffer, + ignore_punctuation=True, + split_character=True, + retain_format=False, + ) + asr_text_len = len(words) + speech_ok = speech_duration_ms >= self.min_interrupt_speech_duration_ms + text_ok = asr_text_len >= self.min_interrupt_text_length + + if speech_ok and text_ok: + self.logger.bind(tag=TAG).info( + f"Interrupt triggered: speech={speech_duration_ms:.0f}ms >= {self.min_interrupt_speech_duration_ms:.0f}ms, " + f"text_len={asr_text_len} >= {self.min_interrupt_text_length}" + ) + # Trigger interrupt + self.client_abort = True + self.clear_queues() + # Send stop message to client + async def send_stop_message(): + await self.websocket.send( + json.dumps({"type": "tts", "state": "stop", "session_id": self.session_id}) + ) + asyncio.create_task(send_stop_message()) + self.clearSpeakStatus() + def chat_and_close(self, text): """Chat with the user and then close the connection""" try: diff --git a/main/xiaozhi-server/core/providers/asr/aliyun.py b/main/xiaozhi-server/core/providers/asr/aliyun.py deleted file mode 100644 index 36f417457..000000000 --- a/main/xiaozhi-server/core/providers/asr/aliyun.py +++ /dev/null @@ -1,248 +0,0 @@ -import http.client -import json -import asyncio -from typing import Optional, Tuple, List -import os -import uuid -import hmac -import hashlib -import base64 -import requests -from urllib import parse -import time -from datetime import datetime -from config.logger import setup_logging -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType - -TAG = __name__ -logger = setup_logging() - - -class AccessToken: - @staticmethod - def _encode_text(text): - encoded_text = parse.quote_plus(text) - return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - - @staticmethod - def _encode_dict(dic): - keys = dic.keys() - dic_sorted = [(key, dic[key]) for key in sorted(keys)] - encoded_text = parse.urlencode(dic_sorted) - return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - - @staticmethod - def create_token(access_key_id, access_key_secret): - parameters = { - "AccessKeyId": access_key_id, - "Action": "CreateToken", - "Format": "JSON", - "RegionId": "cn-shanghai", - "SignatureMethod": "HMAC-SHA1", - "SignatureNonce": str(uuid.uuid1()), - "SignatureVersion": "1.0", - "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), - "Version": "2019-02-28", - } - # 构造规范化的请求字符串 - query_string = AccessToken._encode_dict(parameters) - # print('规范化的请求字符串: %s' % query_string) - # 构造待签名字符串 - string_to_sign = ( - "GET" - + "&" - + AccessToken._encode_text("/") - + "&" - + AccessToken._encode_text(query_string) - ) - # print('待签名的字符串: %s' % string_to_sign) - # 计算签名 - secreted_string = hmac.new( - bytes(access_key_secret + "&", encoding="utf-8"), - bytes(string_to_sign, encoding="utf-8"), - hashlib.sha1, - ).digest() - signature = base64.b64encode(secreted_string) - # print('签名: %s' % signature) - # 进行URL编码 - signature = AccessToken._encode_text(signature) - # print('URL编码后的签名: %s' % signature) - # 调用服务 - full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( - signature, - query_string, - ) - # print('url: %s' % full_url) - # 提交HTTP GET请求 - response = requests.get(full_url) - if response.ok: - root_obj = response.json() - key = "Token" - if key in root_obj: - token = root_obj[key]["Id"] - expire_time = root_obj[key]["ExpireTime"] - return token, expire_time - # print(response.text) - return None, None - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - self.interface_type = InterfaceType.NON_STREAM - """阿里云ASR初始化""" - # 新增空值判断逻辑 - self.access_key_id = config.get("access_key_id") - self.access_key_secret = config.get("access_key_secret") - - self.app_key = config.get("appkey") - self.host = "nls-gateway-cn-shanghai.aliyuncs.com" - self.base_url = f"https://{self.host}/stream/v1/asr" - self.sample_rate = 16000 - self.format = "wav" - self.output_dir = config.get("output_dir", "./audio_output") - self.delete_audio_file = delete_audio_file - - if self.access_key_id and self.access_key_secret: - # 使用密钥对生成临时token - self._refresh_token() - else: - # 直接使用预生成的长期token - self.token = config.get("token") - self.expire_time = None - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - def _refresh_token(self): - """刷新Token并记录过期时间""" - if self.access_key_id and self.access_key_secret: - self.token, expire_time_str = AccessToken.create_token( - self.access_key_id, self.access_key_secret - ) - if not expire_time_str: - raise ValueError("无法获取有效的Token过期时间") - - try: - # 统一转换为字符串处理 - expire_str = str(expire_time_str).strip() - - if expire_str.isdigit(): - expire_time = datetime.fromtimestamp(int(expire_str)) - else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") - self.expire_time = expire_time.timestamp() - 60 - except Exception as e: - raise ValueError(f"无效的过期时间格式: {expire_str}") from e - - else: - self.expire_time = None - - if not self.token: - raise ValueError("无法获取有效的访问Token") - - def _is_token_expired(self): - """检查Token是否过期""" - if not self.expire_time: - return False # 长期Token不过期 - # 新增调试日志 - # current_time = time.time() - # remaining = self.expire_time - current_time - # print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | " - # f"过期时间 {datetime.fromtimestamp(self.expire_time)} | " - # f"剩余 {remaining:.2f}秒") - return time.time() > self.expire_time - - def _construct_request_url(self) -> str: - """构造请求URL,包含参数""" - request = f"{self.base_url}?appkey={self.app_key}" - request += f"&format={self.format}" - request += f"&sample_rate={self.sample_rate}" - request += "&enable_punctuation_prediction=true" - request += "&enable_inverse_text_normalization=true" - request += "&enable_voice_detection=false" - return request - - async def _send_request(self, pcm_data: bytes) -> Optional[str]: - """发送请求到阿里云ASR服务""" - try: - # 设置HTTP头 - headers = { - "X-NLS-Token": self.token, - "Content-type": "application/octet-stream", - "Content-Length": str(len(pcm_data)), - } - - # 创建连接并发送请求 - conn = http.client.HTTPSConnection(self.host) - request_url = self._construct_request_url() - - loop = asyncio.get_event_loop() - await loop.run_in_executor( - None, - lambda: conn.request( - method="POST", url=request_url, body=pcm_data, headers=headers - ), - ) - - # 获取响应 - response = await loop.run_in_executor(None, conn.getresponse) - body = await loop.run_in_executor(None, response.read) - conn.close() - - # 解析响应 - try: - body_json = json.loads(body) - status = body_json.get("status") - - if status == 20000000: - result = body_json.get("result", "") - logger.bind(tag=TAG).debug(f"ASR结果: {result}") - return result - else: - logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}") - return None - - except ValueError: - logger.bind(tag=TAG).error("响应不是JSON格式") - return None - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True) - return None - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - if self._is_token_expired(): - logger.warning("Token已过期,正在自动刷新...") - self._refresh_token() - - file_path = None - try: - # 解码Opus为PCM - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - file_path = self.save_audio_to_file(pcm_data, session_id) - - # 发送请求并获取文本 - text = await self._send_request(combined_pcm_data) - - if text: - return text, file_path - - return "", file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py deleted file mode 100644 index 8246da15d..000000000 --- a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py +++ /dev/null @@ -1,350 +0,0 @@ -import json -import time -import uuid -import hmac -import base64 -import hashlib -import asyncio -import requests -import websockets -import opuslib_next -import random -from typing import Optional, Tuple, List -from urllib import parse -from datetime import datetime -from config.logger import setup_logging -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType - -TAG = __name__ -logger = setup_logging() - - -class AccessToken: - @staticmethod - def _encode_text(text): - encoded_text = parse.quote_plus(text) - return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - - @staticmethod - def _encode_dict(dic): - keys = dic.keys() - dic_sorted = [(key, dic[key]) for key in sorted(keys)] - encoded_text = parse.urlencode(dic_sorted) - return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~") - - @staticmethod - def create_token(access_key_id, access_key_secret): - parameters = { - "AccessKeyId": access_key_id, - "Action": "CreateToken", - "Format": "JSON", - "RegionId": "cn-shanghai", - "SignatureMethod": "HMAC-SHA1", - "SignatureNonce": str(uuid.uuid1()), - "SignatureVersion": "1.0", - "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), - "Version": "2019-02-28", - } - query_string = AccessToken._encode_dict(parameters) - string_to_sign = ( - "GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string) - ) - secreted_string = hmac.new( - bytes(access_key_secret + "&", encoding="utf-8"), - bytes(string_to_sign, encoding="utf-8"), - hashlib.sha1, - ).digest() - signature = base64.b64encode(secreted_string) - signature = AccessToken._encode_text(signature) - full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string) - response = requests.get(full_url) - if response.ok: - root_obj = response.json() - if "Token" in root_obj: - return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"] - return None, None - - -class ASRProvider(ASRProviderBase): - def __init__(self, config, delete_audio_file): - super().__init__() - self.interface_type = InterfaceType.STREAM - self.config = config - self.text = "" - self.decoder = opuslib_next.Decoder(16000, 1) - self.asr_ws = None - self.forward_task = None - self.is_processing = False - self.server_ready = False # 服务器准备状态 - - # 基础配置 - self.access_key_id = config.get("access_key_id") - self.access_key_secret = config.get("access_key_secret") - self.appkey = config.get("appkey") - self.token = config.get("token") - self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") - # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 - if "-internal." in self.host: - self.ws_url = f"ws://{self.host}/ws/v1" - else: - # 默认使用wss协议 - self.ws_url = f"wss://{self.host}/ws/v1" - - self.max_sentence_silence = config.get("max_sentence_silence") - self.output_dir = config.get("output_dir", "./audio_output") - self.delete_audio_file = delete_audio_file - self.expire_time = None - - self.task_id = uuid.uuid4().hex - - # Token管理 - if self.access_key_id and self.access_key_secret: - self._refresh_token() - elif not self.token: - raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token") - - def _refresh_token(self): - """刷新Token""" - self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret) - if not self.token: - raise ValueError("无法获取有效的访问Token") - - try: - expire_str = str(expire_time_str).strip() - if expire_str.isdigit(): - expire_time = datetime.fromtimestamp(int(expire_str)) - else: - expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") - self.expire_time = expire_time.timestamp() - 60 - except: - self.expire_time = None - - def _is_token_expired(self): - """检查Token是否过期""" - return self.expire_time and time.time() > self.expire_time - - async def open_audio_channels(self, conn): - await super().open_audio_channels(conn) - - async def receive_audio(self, conn, audio, audio_have_voice): - # 初始化音频缓存 - if not hasattr(conn, 'asr_audio_for_voiceprint'): - conn.asr_audio_for_voiceprint = [] - - # 存储音频数据 - if audio: - conn.asr_audio_for_voiceprint.append(audio) - - conn.asr_audio.append(audio) - conn.asr_audio = conn.asr_audio[-10:] - - # 只在有声音且没有连接时建立连接 - if audio_have_voice and not self.is_processing: - try: - await self._start_recognition(conn) - except Exception as e: - logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}") - await self._cleanup(conn) - return - - if self.asr_ws and self.is_processing and self.server_ready: - try: - pcm_frame = self.decoder.decode(audio, 960) - await self.asr_ws.send(pcm_frame) - except Exception as e: - logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}") - await self._cleanup(conn) - - async def _start_recognition(self, conn): - """开始识别会话""" - if self._is_token_expired(): - self._refresh_token() - - # 建立连接 - headers = {"X-NLS-Token": self.token} - self.asr_ws = await websockets.connect( - self.ws_url, - additional_headers=headers, - max_size=1000000000, - ping_interval=None, - ping_timeout=None, - close_timeout=5, - ) - - self.task_id = uuid.uuid4().hex - - logger.bind(tag=TAG).info(f"WebSocket连接建立成功, task_id: {self.task_id}") - - self.is_processing = True - self.server_ready = False # 重置服务器准备状态 - self.forward_task = asyncio.create_task(self._forward_results(conn)) - - # 发送开始请求 - start_request = { - "header": { - "namespace": "SpeechTranscriber", - "name": "StartTranscription", - "status": 20000000, - "message_id": uuid.uuid4().hex, - "task_id": self.task_id, - "status_text": "Gateway:SUCCESS:Success.", - "appkey": self.appkey - }, - "payload": { - "format": "pcm", - "sample_rate": 16000, - "enable_intermediate_result": True, - "enable_punctuation_prediction": True, - "enable_inverse_text_normalization": True, - "max_sentence_silence": self.max_sentence_silence, - "enable_voice_detection": False, - } - } - await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) - logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...") - - async def _forward_results(self, conn): - """转发识别结果""" - try: - while self.asr_ws and not conn.stop_event.is_set(): - try: - response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0) - result = json.loads(response) - - header = result.get("header", {}) - payload = result.get("payload", {}) - message_name = header.get("name", "") - status = header.get("status", 0) - - if status != 20000000: - if status in [40000004, 40010004]: # 连接超时或客户端断开 - logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}") - break - elif status in [40270002, 40270003]: # 音频问题 - logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}") - continue - else: - logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}") - continue - - # 收到TranscriptionStarted表示服务器准备好接收音频数据 - if message_name == "TranscriptionStarted": - self.server_ready = True - logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...") - - # 发送缓存音频 - if conn.asr_audio: - for cached_audio in conn.asr_audio[-10:]: - try: - pcm_frame = self.decoder.decode(cached_audio, 960) - await self.asr_ws.send(pcm_frame) - except Exception as e: - logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}") - break - continue - - if message_name == "TranscriptionResultChanged": - # 中间结果 - text = payload.get("result", "") - if text: - self.text = text - elif message_name == "SentenceEnd": - # 最终结果 - text = payload.get("result", "") - if text: - self.text = text - conn.reset_vad_states() - # 传递缓存的音频数据 - audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) - await self.handle_voice_stop(conn, audio_data) - # 清空缓存 - conn.asr_audio_for_voiceprint = [] - break - elif message_name == "TranscriptionCompleted": - # 识别完成 - self.is_processing = False - break - - except asyncio.TimeoutError: - continue - except websockets.exceptions.ConnectionClosed: - break - except Exception as e: - logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}") - break - - except Exception as e: - logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}") - finally: - await self._cleanup(conn) - - async def _cleanup(self, conn): - """清理资源""" - logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") - - # 清理连接的音频缓存 - if conn and hasattr(conn, 'asr_audio_for_voiceprint'): - conn.asr_audio_for_voiceprint = [] - - # 判断是否需要发送终止请求 - should_stop = self.is_processing or self.server_ready - - # 发送停止识别请求 - if self.asr_ws and should_stop: - try: - stop_msg = { - "header": { - "namespace": "SpeechTranscriber", - "name": "StopTranscription", - "status": 20000000, - "message_id": uuid.uuid4().hex, - "task_id": self.task_id, - "status_text": "Client:Stop", - "appkey": self.appkey - } - } - logger.bind(tag=TAG).info("正在发送ASR终止请求") - await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) - await asyncio.sleep(0.1) - logger.bind(tag=TAG).info("ASR终止请求已发送") - except Exception as e: - logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}") - - # 状态重置(在终止请求发送后) - self.is_processing = False - self.server_ready = False - logger.bind(tag=TAG).info("ASR状态已重置") - - # 清理任务 - if self.forward_task and not self.forward_task.done(): - self.forward_task.cancel() - try: - await asyncio.wait_for(self.forward_task, timeout=1.0) - except Exception as e: - logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}") - finally: - self.forward_task = None - - # 关闭连接 - if self.asr_ws: - try: - logger.bind(tag=TAG).debug("正在关闭WebSocket连接") - await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) - logger.bind(tag=TAG).debug("WebSocket连接已关闭") - except Exception as e: - logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}") - finally: - self.asr_ws = None - - logger.bind(tag=TAG).info("ASR会话清理完成") - - async def speech_to_text(self, opus_data, session_id, audio_format): - """获取识别结果""" - result = self.text - self.text = "" - return result, None - - async def close(self): - """关闭资源""" - await self._cleanup() diff --git a/main/xiaozhi-server/core/providers/asr/baidu.py b/main/xiaozhi-server/core/providers/asr/baidu.py deleted file mode 100644 index aa8ea9015..000000000 --- a/main/xiaozhi-server/core/providers/asr/baidu.py +++ /dev/null @@ -1,85 +0,0 @@ -import time -import os -from typing import Optional, Tuple, List -from aip import AipSpeech -from core.providers.asr.base import ASRProviderBase -from config.logger import setup_logging -from core.providers.asr.dto.dto import InterfaceType - -TAG = __name__ -logger = setup_logging() - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool = True): - super().__init__() - self.interface_type = InterfaceType.NON_STREAM - self.app_id = config.get("app_id") - self.api_key = config.get("api_key") - self.secret_key = config.get("secret_key") - - dev_pid = config.get("dev_pid", "1537") - self.dev_pid = int(dev_pid) if dev_pid else 1537 - - self.output_dir = config.get("output_dir") - self.delete_audio_file = delete_audio_file - - self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key) - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - if not opus_data: - logger.bind(tag=TAG).warning("音频数据为空!") - return None, None - - file_path = None - try: - # 检查配置是否已设置 - if not self.app_id or not self.api_key or not self.secret_key: - logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别") - return None, file_path - - # 将Opus音频数据解码为PCM - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - self.save_audio_to_file(pcm_data, session_id) - - start_time = time.time() - # 识别本地文件 - result = self.client.asr( - combined_pcm_data, - "pcm", - 16000, - { - "dev_pid": str(self.dev_pid), - }, - ) - - if result and result["err_no"] == 0: - logger.bind(tag=TAG).debug( - f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" - ) - result = result["result"][0] - return result, file_path - else: - raise Exception( - f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}" - ) - return None, file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) - return None, file_path diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 2a7b14a5d..25a503829 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -252,27 +252,20 @@ class ASRProviderBase(ABC): self.stop_ws_connection() if text_len > 0: - # Turn Detection: check if user finished speaking - if conn.turn_detection: - end_of_turn, full_text = await conn.turn_detection.check_end_of_turn(raw_text) - - if not end_of_turn: - # User hasn't finished, continue waiting for more speech - logger.bind(tag=TAG).info(f"User hasn't finished, continue waiting for more speech") - return - - # Use accumulated text from turn detection - enhanced_text = self._build_enhanced_text(full_text, speaker_name) + # Append to ASR text buffer + if conn.asr_text_buffer: + conn.asr_text_buffer += " " + raw_text else: - # No Turn Detection: use single segment text - enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + conn.asr_text_buffer = raw_text - asr_report_time = int(time.time()) + # Turn Detection: let turn detection handle end of turn + if conn.turn_detection: + # Turn detection will wait for endpoint delay, then call on_end_of_turn + conn.turn_detection.check_end_of_turn(conn) + return - await startToChat(conn, enhanced_text) - # Note: For report, we need to convert PCM back to opus or use PCM directly - # For now, pass empty list as audio data for report - enqueue_asr_report(conn, enhanced_text, [], report_time=asr_report_time) + # No Turn Detection: process immediately + await conn.on_end_of_turn() except Exception as e: logger.bind(tag=TAG).error(f"Process speech segment failed: {e}") diff --git a/main/xiaozhi-server/core/providers/asr/doubao.py b/main/xiaozhi-server/core/providers/asr/doubao.py deleted file mode 100644 index f6cd79c62..000000000 --- a/main/xiaozhi-server/core/providers/asr/doubao.py +++ /dev/null @@ -1,271 +0,0 @@ -import time -import os -import uuid -import json -import gzip -import websockets -from config.logger import setup_logging -from typing import Optional, Tuple, List -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType - - -TAG = __name__ -logger = setup_logging() - -CLIENT_FULL_REQUEST = 0b0001 -CLIENT_AUDIO_ONLY_REQUEST = 0b0010 - -NO_SEQUENCE = 0b0000 -NEG_SEQUENCE = 0b0010 - -SERVER_FULL_RESPONSE = 0b1001 -SERVER_ACK = 0b1011 -SERVER_ERROR_RESPONSE = 0b1111 - -NO_SERIALIZATION = 0b0000 -JSON = 0b0001 -THRIFT = 0b0011 -CUSTOM_TYPE = 0b1111 -NO_COMPRESSION = 0b0000 -GZIP = 0b0001 -CUSTOM_COMPRESSION = 0b1111 - - -def parse_response(res): - """ - protocol_version(4 bits), header_size(4 bits), - message_type(4 bits), message_type_specific_flags(4 bits) - serialization_method(4 bits) message_compression(4 bits) - reserved (8bits) 保留字段 - header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) ) - payload 类似与http 请求体 - """ - protocol_version = res[0] >> 4 - header_size = res[0] & 0x0F - message_type = res[1] >> 4 - message_type_specific_flags = res[1] & 0x0F - serialization_method = res[2] >> 4 - message_compression = res[2] & 0x0F - reserved = res[3] - header_extensions = res[4 : header_size * 4] - payload = res[header_size * 4 :] - result = {} - payload_msg = None - payload_size = 0 - if message_type == SERVER_FULL_RESPONSE: - payload_size = int.from_bytes(payload[:4], "big", signed=True) - payload_msg = payload[4:] - elif message_type == SERVER_ACK: - seq = int.from_bytes(payload[:4], "big", signed=True) - result["seq"] = seq - if len(payload) >= 8: - payload_size = int.from_bytes(payload[4:8], "big", signed=False) - payload_msg = payload[8:] - elif message_type == SERVER_ERROR_RESPONSE: - code = int.from_bytes(payload[:4], "big", signed=False) - result["code"] = code - payload_size = int.from_bytes(payload[4:8], "big", signed=False) - payload_msg = payload[8:] - if payload_msg is None: - return result - if message_compression == GZIP: - payload_msg = gzip.decompress(payload_msg) - if serialization_method == JSON: - payload_msg = json.loads(str(payload_msg, "utf-8")) - elif serialization_method != NO_SERIALIZATION: - payload_msg = str(payload_msg, "utf-8") - result["payload_msg"] = payload_msg - result["payload_size"] = payload_size - return result - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - self.interface_type = InterfaceType.NON_STREAM - self.appid = config.get("appid") - self.cluster = config.get("cluster") - self.access_token = config.get("access_token") - self.boosting_table_name = config.get("boosting_table_name", "") - self.correct_table_name = config.get("correct_table_name", "") - self.output_dir = config.get("output_dir") - self.delete_audio_file = delete_audio_file - - self.host = "openspeech.bytedance.com" - self.ws_url = f"wss://{self.host}/api/v2/asr" - self.success_code = 1000 - self.seg_duration = 15000 - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - @staticmethod - def _generate_header( - message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE - ) -> bytearray: - """Generate protocol header.""" - header = bytearray() - header_size = 1 - header.append((0b0001 << 4) | header_size) # Protocol version - header.append((message_type << 4) | message_type_specific_flags) - header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression - header.append(0x00) # reserved - return header - - def _construct_request(self, reqid) -> dict: - """Construct the request payload.""" - return { - "app": { - "appid": f"{self.appid}", - "cluster": self.cluster, - "token": self.access_token, - }, - "user": { - "uid": str(uuid.uuid4()), - }, - "request": { - "reqid": reqid, - "show_utterances": False, - "sequence": 1, - "boosting_table_name": self.boosting_table_name, - "correct_table_name": self.correct_table_name, - }, - "audio": { - "format": "raw", - "rate": 16000, - "language": "zh-CN", - "bits": 16, - "channel": 1, - "codec": "raw", - }, - } - - async def _send_request( - self, audio_data: List[bytes], segment_size: int - ) -> Optional[str]: - """Send request to Volcano ASR service.""" - try: - auth_header = {"Authorization": "Bearer; {}".format(self.access_token)} - async with websockets.connect( - self.ws_url, additional_headers=auth_header - ) as websocket: - # Prepare request data - request_params = self._construct_request(str(uuid.uuid4())) - payload_bytes = str.encode(json.dumps(request_params)) - payload_bytes = gzip.compress(payload_bytes) - full_client_request = self._generate_header() - full_client_request.extend( - (len(payload_bytes)).to_bytes(4, "big") - ) # payload size(4 bytes) - full_client_request.extend(payload_bytes) # payload - - # Send header and metadata - # full_client_request - await websocket.send(full_client_request) - res = await websocket.recv() - result = parse_response(res) - if ( - "payload_msg" in result - and result["payload_msg"]["code"] != self.success_code - and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误 - ): - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None - - for seq, (chunk, last) in enumerate( - self.slice_data(audio_data, segment_size), 1 - ): - if last: - audio_only_request = self._generate_header( - message_type=CLIENT_AUDIO_ONLY_REQUEST, - message_type_specific_flags=NEG_SEQUENCE, - ) - else: - audio_only_request = self._generate_header( - message_type=CLIENT_AUDIO_ONLY_REQUEST - ) - payload_bytes = gzip.compress(chunk) - audio_only_request.extend( - (len(payload_bytes)).to_bytes(4, "big") - ) # payload size(4 bytes) - audio_only_request.extend(payload_bytes) # payload - # Send audio data - await websocket.send(audio_only_request) - - # Receive response - response = await websocket.recv() - result = parse_response(response) - - if ( - "payload_msg" in result - and result["payload_msg"]["code"] == self.success_code - ): - if len(result["payload_msg"]["result"]) > 0: - return result["payload_msg"]["result"][0]["text"] - return None - elif "payload_msg" in result and result["payload_msg"]["code"] == 1013: - # 无有效语音,返回空字符串 - return "" - else: - logger.bind(tag=TAG).error(f"ASR error: {result}") - return None - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True) - return None - - @staticmethod - def slice_data(data: bytes, chunk_size: int) -> (list, bool): - """ - slice data - :param data: wav data - :param chunk_size: the segment size in one request - :return: segment data, last flag - """ - data_len = len(data) - offset = 0 - while offset + chunk_size < data_len: - yield data[offset : offset + chunk_size], False - offset += chunk_size - else: - yield data[offset:data_len], True - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - - file_path = None - try: - # 合并所有opus数据包 - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - file_path = self.save_audio_to_file(pcm_data, session_id) - - # 直接使用PCM数据 - # 计算分段大小 (单声道, 16bit, 16kHz采样率) - size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate - segment_size = int(size_per_sec * self.seg_duration / 1000) - - # 语音识别 - start_time = time.time() - text = await self._send_request(combined_pcm_data, segment_size) - if text: - logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" - ) - return text, file_path - return "", file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py deleted file mode 100644 index 217f17ff7..000000000 --- a/main/xiaozhi-server/core/providers/asr/fun_local.py +++ /dev/null @@ -1,134 +0,0 @@ -import time -import os -import sys -import io -import psutil -from config.logger import setup_logging -from typing import Optional, Tuple, List -from core.providers.asr.base import ASRProviderBase -from funasr import AutoModel -from funasr.utils.postprocess_utils import rich_transcription_postprocess -import shutil -from core.providers.asr.dto.dto import InterfaceType - -TAG = __name__ -logger = setup_logging() - -MAX_RETRIES = 2 -RETRY_DELAY = 1 # 重试延迟(秒) - - -# 捕获标准输出 -class CaptureOutput: - def __enter__(self): - self._output = io.StringIO() - self._original_stdout = sys.stdout - sys.stdout = self._output - - def __exit__(self, exc_type, exc_value, traceback): - sys.stdout = self._original_stdout - self.output = self._output.getvalue() - self._output.close() - - # 将捕获到的内容通过 logger 输出 - if self.output: - logger.bind(tag=TAG).info(self.output.strip()) - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - - # 内存检测,要求大于2G - min_mem_bytes = 2 * 1024 * 1024 * 1024 - total_mem = psutil.virtual_memory().total - if total_mem < min_mem_bytes: - logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR") - - self.interface_type = InterfaceType.LOCAL - self.model_dir = config.get("model_dir") - self.output_dir = config.get("output_dir") # 修正配置键名 - self.delete_audio_file = delete_audio_file - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - with CaptureOutput(): - self.model = AutoModel( - model=self.model_dir, - vad_kwargs={"max_single_segment_time": 30000}, - disable_update=True, - hub="hf", - # device="cuda:0", # 启用GPU加速 - ) - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """语音转文本主处理逻辑""" - file_path = None - retry_count = 0 - - while retry_count < MAX_RETRIES: - try: - # 合并所有opus数据包 - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - - combined_pcm_data = b"".join(pcm_data) - - # 检查磁盘空间 - if not self.delete_audio_file: - free_space = shutil.disk_usage(self.output_dir).free - if free_space < len(combined_pcm_data) * 2: # 预留2倍空间 - raise OSError("磁盘空间不足") - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - file_path = self.save_audio_to_file(pcm_data, session_id) - - # 语音识别 - start_time = time.time() - result = self.model.generate( - input=combined_pcm_data, - cache={}, - language="auto", - use_itn=True, - batch_size_s=60, - ) - text = rich_transcription_postprocess(result[0]["text"]) - logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" - ) - - return text, file_path - - except OSError as e: - retry_count += 1 - if retry_count >= MAX_RETRIES: - logger.bind(tag=TAG).error( - f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True - ) - return "", file_path - logger.bind(tag=TAG).warning( - f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}" - ) - time.sleep(RETRY_DELAY) - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path - - finally: - # 文件清理逻辑 - if self.delete_audio_file and file_path and os.path.exists(file_path): - try: - os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") - except Exception as e: - logger.bind(tag=TAG).error( - f"文件删除失败: {file_path} | 错误: {e}" - ) diff --git a/main/xiaozhi-server/core/providers/asr/fun_server.py b/main/xiaozhi-server/core/providers/asr/fun_server.py deleted file mode 100644 index 7eb9e7848..000000000 --- a/main/xiaozhi-server/core/providers/asr/fun_server.py +++ /dev/null @@ -1,169 +0,0 @@ -from typing import Optional, Tuple, List -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType -import ssl -import json -import websockets -from config.logger import setup_logging -import asyncio -import re - -TAG = __name__ -logger = setup_logging() - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - """ - Initialize the ASRProvider with server configuration. - :param config: Dictionary containing 'host', 'port', and 'is_ssl'. - :param delete_audio_file: Boolean to indicate whether to delete audio files after processing. - """ - super().__init__() - self.interface_type = InterfaceType.NON_STREAM - self.host = config.get("host", "localhost") - self.port = config.get("port", 10095) - self.api_key = config.get("api_key", "none") - self.is_ssl = str(config.get("is_ssl", True)).lower() in ( - "true", - "1", - "yes", - ) - self.output_dir = config.get("output_dir") - self.delete_audio_file = delete_audio_file - self.uri = ( - f"wss://{self.host}:{self.port}" - if self.is_ssl - else f"ws://{self.host}:{self.port}" - ) - self.ssl_context = ssl.SSLContext() if self.is_ssl else None - if self.ssl_context: - self.ssl_context.check_hostname = False - self.ssl_context.verify_mode = ssl.CERT_NONE - - async def _receive_responses(self, ws) -> None: - """ - Asynchronous generator to receive messages from the WebSocket. - Yields each message as it is received. - """ - text = "" - while True: - try: - response = await asyncio.wait_for(ws.recv(), timeout=5) - response_data = json.loads(response) - logger.bind(tag=TAG).debug(f"Received response: {response_data}") - if response_data.get("is_final", True): - text += response_data.get("text", "") - break - else: - text += response_data.get("text", "") - except asyncio.TimeoutError: - logger.bind(tag=TAG).error( - "Timeout while waiting for response from WebSocket." - ) - break - except websockets.exceptions.ConnectionClosed as e: - logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}") - break - return text - - async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple: - """ - Internal method to handle WebSocket communication. - Reuses the persistent WebSocket connection if available. - :param pcm_data: PCM audio data to send. - :param session_id: Unique session identifier. - :return: Tuple containing recognized text and optional timestamp. - """ - - # Send initial configuration message - config_message = json.dumps( - { - "mode": "offline", - "chunk_size": [5, 10, 5], - "chunk_interval": 10, - "wav_name": session_id, - "is_speaking": True, - "itn": False, - } - ) - await ws.send(config_message) - logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}") - - # Send PCM data - await ws.send(pcm_data) - logger.bind(tag=TAG).debug(f"Sent PCM data of length: {len(pcm_data)} bytes") - - # Indicate end of speech - end_message = json.dumps({"is_speaking": False}) - await ws.send(end_message) - logger.bind(tag=TAG).debug(f"Sent end message: {end_message}") - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """ - Convert speech data to text using FunASR. - :param opus_data: List of Opus-encoded audio data chunks. - :param session_id: Unique session identifier. - :return: Tuple containing recognized text and optional timestamp. - """ - file_path = None - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - file_path = self.save_audio_to_file(pcm_data, session_id) - auth_header = {"Authorization": "Bearer; {}".format(self.api_key)} - async with websockets.connect( - self.uri, - additional_headers=auth_header, - subprotocols=["binary"], - ping_interval=None, - ssl=self.ssl_context, - ) as ws: - try: - # Use asyncio to handle WebSocket communication - send_task = asyncio.create_task( - self._send_data(ws, combined_pcm_data, session_id) - ) - receive_task = asyncio.create_task(self._receive_responses(ws)) - - # Gather tasks with error handling - done, pending = await asyncio.wait( - [send_task, receive_task], return_when=asyncio.FIRST_EXCEPTION - ) - - # Cancel any pending tasks - for task in pending: - task.cancel() - - # Check for exceptions in completed tasks - for task in done: - if task.exception(): - raise task.exception() - - # Get the result from the receive task - result = receive_task.result() - match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result) - if match: - result = match.group(4).strip() - return ( - result, - file_path, - ) # Return the recognized text and timestamp (if any) - - except websockets.exceptions.ConnectionClosed as e: - logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}") - return "", file_path - except Exception as e: - logger.bind(tag=TAG).error( - f"Error during speech-to-text conversion: {e}", exc_info=True - ) - return "", file_path diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py index 5823f2ec3..21116fd72 100644 --- a/main/xiaozhi-server/core/providers/asr/openai.py +++ b/main/xiaozhi-server/core/providers/asr/openai.py @@ -21,6 +21,7 @@ class ASRProvider(ASRProviderBase): self.model = config.get("model_name") self.output_dir = config.get("output_dir") self.delete_audio_file = delete_audio_file + self.prompt = config.get("prompt", None) self._client = OpenAI( api_key=self.api_key, @@ -49,7 +50,8 @@ class ASRProvider(ASRProviderBase): transcription: str = self._client.audio.transcriptions.create( model=self.model, file=audio_file, - response_format="text" + response_format="text", + prompt=self.prompt if self.prompt else None, ) logger.bind(tag=TAG).debug( f"Audio transcription latency: {time.time() - start_time:.3f}s | Result: {transcription}" diff --git a/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py b/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py deleted file mode 100644 index 84fe1979d..000000000 --- a/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py +++ /dev/null @@ -1,169 +0,0 @@ -import os -import json -import asyncio -import tempfile -import difflib -from typing import Optional, Tuple, List -import dashscope -from config.logger import setup_logging -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType - -tag = __name__ -logger = setup_logging() - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - self.interface_type = InterfaceType.STREAM - """Qwen3-ASR-Flash ASR初始化""" - - # 配置参数 - self.api_key = config.get("api_key") - if not self.api_key: - raise ValueError("Qwen3-ASR-Flash 需要配置 api_key") - - self.model_name = config.get("model_name", "qwen3-asr-flash") - self.output_dir = config.get("output_dir", "./audio_output") - self.delete_audio_file = delete_audio_file - - # ASR选项配置 - self.enable_lid = config.get("enable_lid", True) # 自动语种检测 - self.enable_itn = config.get("enable_itn", True) # 逆文本归一化 - self.language = config.get("language", None) # 指定语种,默认自动检测 - self.context = config.get("context", "") # 上下文信息,用于提高识别准确率 - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - def _prepare_audio_file(self, pcm_data: bytes) -> str: - """将PCM数据转换为WAV文件并返回文件路径""" - try: - import wave - - # 创建临时WAV文件 - with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file: - temp_path = temp_file.name - - # 写入WAV格式 - with wave.open(temp_path, 'wb') as wav_file: - wav_file.setnchannels(1) # 单声道 - wav_file.setsampwidth(2) # 16位 - wav_file.setframerate(16000) # 16kHz采样率 - wav_file.writeframes(pcm_data) - - return temp_path - - except Exception as e: - logger.bind(tag=tag).error(f"音频文件准备失败: {e}") - return None - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - temp_file_path = None - file_path = None - - try: - # 解码音频数据 - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - - combined_pcm_data = b"".join(pcm_data) - if len(combined_pcm_data) == 0: - logger.bind(tag=tag).warning("音频数据为空") - return "", None - - # 准备音频文件 - temp_file_path = self._prepare_audio_file(combined_pcm_data) - if not temp_file_path: - return "", None - - # 保存音频文件(如果需要) - if not self.delete_audio_file: - file_path = self.save_audio_to_file(pcm_data, session_id) - - # 构造请求消息 - messages = [ - { - "role": "user", - "content": [ - {"audio": temp_file_path} - ] - } - ] - - # 如果有上下文信息,添加system消息 - if self.context: - messages.insert(0, { - "role": "system", - "content": [ - {"text": self.context} - ] - }) - - # 准备ASR选项 - asr_options = { - "enable_lid": self.enable_lid, - "enable_itn": self.enable_itn - } - - # 如果指定了语种,添加到选项中 - if self.language: - asr_options["language"] = self.language - - # 设置API密钥 - dashscope.api_key = self.api_key - - # 发送流式请求 - response = dashscope.MultiModalConversation.call( - model=self.model_name, - messages=messages, - result_format="message", - asr_options=asr_options, - stream=True - ) - - # 处理流式响应 - full_text = "" - last_text = "" # 用于存储上一个文本片段 - for chunk in response: - try: - text = chunk["output"]["choices"][0]["message"].content[0]["text"] - # 标准化文本片段(去除首尾空格) - normalized_text = text.strip() - # 只有当新文本片段与上一个不同时才处理 - if normalized_text != last_text: - # 提取新增的文本部分 - # 通过比较当前文本和上一个文本,找到新增的部分 - if normalized_text.startswith(last_text): - # 如果当前文本以最后一个文本开头,则新增部分是两者的差集 - new_part = normalized_text[len(last_text):] - else: - # 如果不以最后一个文本开头,说明识别结果发生了较大变化,直接使用当前文本 - new_part = normalized_text - - # 将新增部分添加到完整文本中 - full_text += new_part - last_text = normalized_text - # 这里可以实时处理文本片段,例如通过回调函数 - except: - pass - - return full_text, file_path - - except Exception as e: - logger.bind(tag=tag).error(f"语音识别失败: {e}") - return "", file_path - - finally: - # 清理临时文件 - if temp_file_path and os.path.exists(temp_file_path): - try: - os.unlink(temp_file_path) - except Exception as e: - logger.bind(tag=tag).warning(f"清理临时文件失败: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py deleted file mode 100644 index c34909b24..000000000 --- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py +++ /dev/null @@ -1,163 +0,0 @@ -import time -import wave -import os -import sys -import io -from config.logger import setup_logging -from typing import Optional, Tuple, List -from core.providers.asr.dto.dto import InterfaceType -from core.providers.asr.base import ASRProviderBase - -import numpy as np -import sherpa_onnx - -from modelscope.hub.file_download import model_file_download - -TAG = __name__ -logger = setup_logging() - - -# 捕获标准输出 -class CaptureOutput: - def __enter__(self): - self._output = io.StringIO() - self._original_stdout = sys.stdout - sys.stdout = self._output - - def __exit__(self, exc_type, exc_value, traceback): - sys.stdout = self._original_stdout - self.output = self._output.getvalue() - self._output.close() - - # 将捕获到的内容通过 logger 输出 - if self.output: - logger.bind(tag=TAG).info(self.output.strip()) - - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool): - super().__init__() - self.interface_type = InterfaceType.LOCAL - self.model_dir = config.get("model_dir") - self.output_dir = config.get("output_dir") - self.model_type = config.get("model_type", "sense_voice") # 支持 paraformer - self.delete_audio_file = delete_audio_file - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - # 初始化模型文件路径 - model_files = { - "model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"), - "tokens.txt": os.path.join(self.model_dir, "tokens.txt"), - } - - # 下载并检查模型文件 - try: - for file_name, file_path in model_files.items(): - if not os.path.isfile(file_path): - logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}") - model_file_download( - model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue", - file_path=file_name, - local_dir=self.model_dir, - ) - - if not os.path.isfile(file_path): - raise FileNotFoundError(f"模型文件下载失败: {file_path}") - - self.model_path = model_files["model.int8.onnx"] - self.tokens_path = model_files["tokens.txt"] - - except Exception as e: - logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}") - raise - - with CaptureOutput(): - if self.model_type == "paraformer": - self.model = sherpa_onnx.OfflineRecognizer.from_paraformer( - paraformer=self.model_path, - tokens=self.tokens_path, - num_threads=2, - sample_rate=16000, - feature_dim=80, - decoding_method="greedy_search", - debug=False, - ) - else: # sense_voice - self.model = sherpa_onnx.OfflineRecognizer.from_sense_voice( - model=self.model_path, - tokens=self.tokens_path, - num_threads=2, - sample_rate=16000, - feature_dim=80, - decoding_method="greedy_search", - debug=False, - use_itn=True, - ) - - def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]: - """ - Args: - wave_filename: - Path to a wave file. It should be single channel and each sample should - be 16-bit. Its sample rate does not need to be 16kHz. - Returns: - Return a tuple containing: - - A 1-D array of dtype np.float32 containing the samples, which are - normalized to the range [-1, 1]. - - sample rate of the wave file - """ - - with wave.open(wave_filename) as f: - assert f.getnchannels() == 1, f.getnchannels() - assert f.getsampwidth() == 2, f.getsampwidth() # it is in bytes - num_samples = f.getnframes() - samples = f.readframes(num_samples) - samples_int16 = np.frombuffer(samples, dtype=np.int16) - samples_float32 = samples_int16.astype(np.float32) - - samples_float32 = samples_float32 / 32768 - return samples_float32, f.getframerate() - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """语音转文本主处理逻辑""" - file_path = None - try: - # 保存音频文件 - start_time = time.time() - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - file_path = self.save_audio_to_file(pcm_data, session_id) - logger.bind(tag=TAG).debug( - f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}" - ) - - # 语音识别 - start_time = time.time() - s = self.model.create_stream() - samples, sample_rate = self.read_wave(file_path) - s.accept_waveform(sample_rate, samples) - self.model.decode_stream(s) - text = s.result.text - logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" - ) - - return text, file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) - return "", file_path - finally: - # 文件清理逻辑 - if self.delete_audio_file and file_path and os.path.exists(file_path): - try: - os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") - except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") diff --git a/main/xiaozhi-server/core/providers/asr/tencent.py b/main/xiaozhi-server/core/providers/asr/tencent.py deleted file mode 100644 index 1fd1c6f42..000000000 --- a/main/xiaozhi-server/core/providers/asr/tencent.py +++ /dev/null @@ -1,238 +0,0 @@ -import base64 -import hashlib -import hmac -import json -import time -from datetime import datetime, timezone -import os -from typing import Optional, Tuple, List -from core.providers.asr.dto.dto import InterfaceType -import requests -from core.providers.asr.base import ASRProviderBase -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - - -class ASRProvider(ASRProviderBase): - API_URL = "https://asr.tencentcloudapi.com" - API_VERSION = "2019-06-14" - FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3 - - def __init__(self, config: dict, delete_audio_file: bool = True): - super().__init__() - self.interface_type = InterfaceType.NON_STREAM - self.secret_id = config.get("secret_id") - self.secret_key = config.get("secret_key") - self.output_dir = config.get("output_dir") - self.delete_audio_file = delete_audio_file - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - async def speech_to_text( - self, opus_data: List[bytes], session_id: str, audio_format="opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - if not opus_data: - logger.bind(tag=TAG).warning("音频数据为空!") - return None, None - - file_path = None - try: - # 检查配置是否已设置 - if not self.secret_id or not self.secret_key: - logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别") - return None, file_path - - # 将Opus音频数据解码为PCM - if audio_format == "pcm": - pcm_data = opus_data - else: - pcm_data = self.decode_opus(opus_data) - combined_pcm_data = b"".join(pcm_data) - - # 判断是否保存为WAV文件 - if self.delete_audio_file: - pass - else: - self.save_audio_to_file(pcm_data, session_id) - - # 将音频数据转换为Base64编码 - base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8") - - # 构建请求体 - request_body = self._build_request_body(base64_audio) - - # 获取认证头 - timestamp, authorization = self._get_auth_headers(request_body) - - # 发送请求 - start_time = time.time() - result = self._send_request(request_body, timestamp, authorization) - - if result: - logger.bind(tag=TAG).debug( - f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" - ) - - return result, file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) - return None, file_path - - def _build_request_body(self, base64_audio: str) -> str: - """构建请求体""" - request_map = { - "ProjectId": 0, - "SubServiceType": 2, # 一句话识别 - "EngSerViceType": "16k_zh", # 中文普通话通用 - "SourceType": 1, # 音频数据来源为语音文件 - "VoiceFormat": self.FORMAT, # 音频格式 - "Data": base64_audio, # Base64编码的音频数据 - "DataLen": len(base64_audio), # 数据长度 - } - return json.dumps(request_map) - - def _get_auth_headers(self, request_body: str) -> Tuple[str, str]: - """获取认证头""" - try: - # 获取当前UTC时间戳 - now = datetime.now(timezone.utc) - timestamp = str(int(now.timestamp())) - date = now.strftime("%Y-%m-%d") - - # 服务名称必须是 "asr" - service = "asr" - - # 拼接凭证范围 - credential_scope = f"{date}/{service}/tc3_request" - - # 使用TC3-HMAC-SHA256签名方法 - algorithm = "TC3-HMAC-SHA256" - - # 构建规范请求字符串 - http_request_method = "POST" - canonical_uri = "/" - canonical_query_string = "" - - # 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写 - # 必须包含content-type和host头部 - content_type = "application/json; charset=utf-8" - host = "asr.tencentcloudapi.com" - action = "SentenceRecognition" # 接口名称 - - # 构建规范头部信息,注意顺序和格式 - canonical_headers = ( - f"content-type:{content_type.lower()}\n" - + f"host:{host.lower()}\n" - + f"x-tc-action:{action.lower()}\n" - ) - - signed_headers = "content-type;host;x-tc-action" - - # 请求体哈希值 - payload_hash = self._sha256_hex(request_body) - - # 构建规范请求字符串 - canonical_request = ( - f"{http_request_method}\n" - + f"{canonical_uri}\n" - + f"{canonical_query_string}\n" - + f"{canonical_headers}\n" - + f"{signed_headers}\n" - + f"{payload_hash}" - ) - - # 计算规范请求的哈希值 - hashed_canonical_request = self._sha256_hex(canonical_request) - - # 构建待签名字符串 - string_to_sign = ( - f"{algorithm}\n" - + f"{timestamp}\n" - + f"{credential_scope}\n" - + f"{hashed_canonical_request}" - ) - - # 计算签名密钥 - secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date) - secret_service = self._hmac_sha256(secret_date, service) - secret_signing = self._hmac_sha256(secret_service, "tc3_request") - - # 计算签名 - signature = self._bytes_to_hex( - self._hmac_sha256(secret_signing, string_to_sign) - ) - - # 构建授权头 - authorization = ( - f"{algorithm} " - + f"Credential={self.secret_id}/{credential_scope}, " - + f"SignedHeaders={signed_headers}, " - + f"Signature={signature}" - ) - - return timestamp, authorization - - except Exception as e: - logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True) - raise RuntimeError(f"生成认证头失败: {e}") - - def _send_request( - self, request_body: str, timestamp: str, authorization: str - ) -> Optional[str]: - """发送请求到腾讯云API""" - headers = { - "Content-Type": "application/json; charset=utf-8", - "Host": "asr.tencentcloudapi.com", - "Authorization": authorization, - "X-TC-Action": "SentenceRecognition", - "X-TC-Version": self.API_VERSION, - "X-TC-Timestamp": timestamp, - "X-TC-Region": "ap-shanghai", - } - - try: - response = requests.post(self.API_URL, headers=headers, data=request_body) - - if not response.ok: - raise IOError(f"请求失败: {response.status_code} {response.reason}") - - response_json = response.json() - - # 检查是否有错误 - if "Response" in response_json and "Error" in response_json["Response"]: - error = response_json["Response"]["Error"] - error_code = error["Code"] - error_message = error["Message"] - raise IOError(f"API返回错误: {error_code}: {error_message}") - - # 提取识别结果 - if "Response" in response_json and "Result" in response_json["Response"]: - return response_json["Response"]["Result"] - else: - logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}") - return "" - - except Exception as e: - logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True) - return None - - def _sha256_hex(self, data: str) -> str: - """计算字符串的SHA256哈希值""" - digest = hashlib.sha256(data.encode("utf-8")).digest() - return self._bytes_to_hex(digest) - - def _hmac_sha256(self, key, data: str) -> bytes: - """计算HMAC-SHA256""" - if isinstance(key, str): - key = key.encode("utf-8") - - return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest() - - def _bytes_to_hex(self, bytes_data: bytes) -> str: - """字节数组转十六进制字符串""" - return "".join(f"{b:02x}" for b in bytes_data) diff --git a/main/xiaozhi-server/core/providers/asr/vosk.py b/main/xiaozhi-server/core/providers/asr/vosk.py deleted file mode 100644 index 19d318225..000000000 --- a/main/xiaozhi-server/core/providers/asr/vosk.py +++ /dev/null @@ -1,114 +0,0 @@ -import os -import json -import time -from typing import Optional, Tuple, List -from .base import ASRProviderBase -from config.logger import setup_logging -from core.providers.asr.dto.dto import InterfaceType -import vosk - -TAG = __name__ -logger = setup_logging() - -class ASRProvider(ASRProviderBase): - def __init__(self, config: dict, delete_audio_file: bool = True): - super().__init__() - self.interface_type = InterfaceType.LOCAL - self.model_path = config.get("model_path") - self.output_dir = config.get("output_dir", "tmp/") - self.delete_audio_file = delete_audio_file - - # 初始化VOSK模型 - self.model = None - self.recognizer = None - self._load_model() - - # 确保输出目录存在 - os.makedirs(self.output_dir, exist_ok=True) - - def _load_model(self): - """加载VOSK模型""" - try: - if not os.path.exists(self.model_path): - raise FileNotFoundError(f"VOSK模型路径不存在: {self.model_path}") - - logger.bind(tag=TAG).info(f"正在加载VOSK模型: {self.model_path}") - self.model = vosk.Model(self.model_path) - - # 初始化VOSK识别器(采样率必须为16kHz) - self.recognizer = vosk.KaldiRecognizer(self.model, 16000) - - logger.bind(tag=TAG).info("VOSK模型加载成功") - except Exception as e: - logger.bind(tag=TAG).error(f"加载VOSK模型失败: {e}") - raise - - async def speech_to_text( - self, audio_data: List[bytes], session_id: str, audio_format: str = "opus" - ) -> Tuple[Optional[str], Optional[str]]: - """将语音数据转换为文本""" - file_path = None - try: - # 检查模型是否加载成功 - if not self.model: - logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别") - return "", None - - # 解码音频(如果原始格式是Opus) - if audio_format == "pcm": - pcm_data = audio_data - else: - pcm_data = self.decode_opus(audio_data) - - if not pcm_data: - logger.bind(tag=TAG).warning("解码后的PCM数据为空,无法进行识别") - return "", None - - # 合并PCM数据 - combined_pcm_data = b"".join(pcm_data) - if len(combined_pcm_data) == 0: - logger.bind(tag=TAG).warning("合并后的PCM数据为空") - return "", None - - # 判断是否保存为WAV文件 - if not self.delete_audio_file: - file_path = self.save_audio_to_file(pcm_data, session_id) - - start_time = time.time() - - - # 进行识别(VOSK推荐每次送入2000字节的数据) - chunk_size = 2000 - text_result = "" - - for i in range(0, len(combined_pcm_data), chunk_size): - chunk = combined_pcm_data[i:i+chunk_size] - if self.recognizer.AcceptWaveform(chunk): - result = json.loads(self.recognizer.Result()) - text = result.get('text', '') - if text: - text_result += text + " " - - # 获取最终结果 - final_result = json.loads(self.recognizer.FinalResult()) - final_text = final_result.get('text', '') - if final_text: - text_result += final_text - - logger.bind(tag=TAG).debug( - f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}" - ) - - return text_result.strip(), file_path - - except Exception as e: - logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}") - return "", None - finally: - # 文件清理逻辑 - if self.delete_audio_file and file_path and os.path.exists(file_path): - try: - os.remove(file_path) - logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}") - except Exception as e: - logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}") diff --git a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py deleted file mode 100644 index e91c8f098..000000000 --- a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py +++ /dev/null @@ -1,523 +0,0 @@ -import json -import hmac -import base64 -import hashlib -import asyncio -import websockets -import opuslib_next -from time import mktime -from datetime import datetime -from urllib.parse import urlencode -from typing import List -from config.logger import setup_logging -from wsgiref.handlers import format_date_time -from core.providers.asr.base import ASRProviderBase -from core.providers.asr.dto.dto import InterfaceType - -TAG = __name__ -logger = setup_logging() - -# 帧状态常量 -STATUS_FIRST_FRAME = 0 # 第一帧的标识 -STATUS_CONTINUE_FRAME = 1 # 中间帧标识 -STATUS_LAST_FRAME = 2 # 最后一帧的标识 - - -class ASRProvider(ASRProviderBase): - def __init__(self, config, delete_audio_file): - super().__init__() - self.interface_type = InterfaceType.STREAM - self.config = config - self.text = "" - self.decoder = opuslib_next.Decoder(16000, 1) - self.asr_ws = None - self.forward_task = None - self.is_processing = False - self.server_ready = False - self.last_frame_sent = False # 标记是否已发送最终帧 - self.best_text = "" # 保存最佳识别结果 - self.has_final_result = False # 标记是否收到最终识别结果 - - # 讯飞配置 - self.app_id = config.get("app_id") - self.api_key = config.get("api_key") - self.api_secret = config.get("api_secret") - - if not all([self.app_id, self.api_key, self.api_secret]): - raise ValueError("必须提供app_id、api_key和api_secret") - - # 识别参数 - self.iat_params = { - "domain": config.get("domain", "slm"), - "language": config.get("language", "zh_cn"), - "accent": config.get("accent", "mandarin"), - "dwa": config.get("dwa", "wpgs"), - "result": {"encoding": "utf8", "compress": "raw", "format": "plain"}, - } - - self.output_dir = config.get("output_dir", "tmp/") - self.delete_audio_file = delete_audio_file - - def create_url(self) -> str: - """生成认证URL""" - url = "ws://iat.cn-huabei-1.xf-yun.com/v1" - # 生成RFC1123格式的时间戳 - now = datetime.now() - date = format_date_time(mktime(now.timetuple())) - - # 拼接字符串 - signature_origin = "host: " + "iat.cn-huabei-1.xf-yun.com" + "\n" - signature_origin += "date: " + date + "\n" - signature_origin += "GET " + "/v1 " + "HTTP/1.1" - - # 进行hmac-sha256进行加密 - signature_sha = hmac.new( - self.api_secret.encode("utf-8"), - signature_origin.encode("utf-8"), - digestmod=hashlib.sha256, - ).digest() - signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") - - authorization_origin = ( - 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' - % (self.api_key, "hmac-sha256", "host date request-line", signature_sha) - ) - authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( - encoding="utf-8" - ) - - # 将请求的鉴权参数组合为字典 - v = { - "authorization": authorization, - "date": date, - "host": "iat.cn-huabei-1.xf-yun.com", - } - - # 拼接鉴权参数,生成url - url = url + "?" + urlencode(v) - return url - - async def open_audio_channels(self, conn): - await super().open_audio_channels(conn) - - async def receive_audio(self, conn, audio, audio_have_voice): - # 先调用父类方法处理基础逻辑 - await super().receive_audio(conn, audio, audio_have_voice) - - # 存储音频数据用于声纹识别 - if not hasattr(conn, "asr_audio_for_voiceprint"): - conn.asr_audio_for_voiceprint = [] - conn.asr_audio_for_voiceprint.append(audio) - - # 如果本次有声音,且之前没有建立连接 - if audio_have_voice and self.asr_ws is None and not self.is_processing: - try: - await self._start_recognition(conn) - except Exception as e: - logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}") - await self._cleanup(conn) - return - - # 发送当前音频数据 - if self.asr_ws and self.is_processing and self.server_ready: - try: - pcm_frame = self.decoder.decode(audio, 960) - await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME) - except Exception as e: - logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}") - await self._cleanup(conn) - - async def _start_recognition(self, conn): - """开始识别会话""" - try: - self.is_processing = True - # 建立WebSocket连接 - ws_url = self.create_url() - logger.bind(tag=TAG).info(f"正在连接ASR服务: {ws_url[:50]}...") - - self.asr_ws = await websockets.connect( - ws_url, - max_size=1000000000, - ping_interval=None, - ping_timeout=None, - close_timeout=10, - ) - - logger.bind(tag=TAG).info("ASR WebSocket连接已建立") - self.server_ready = False - self.last_frame_sent = False - self.best_text = "" - self.forward_task = asyncio.create_task(self._forward_results(conn)) - - # 发送首帧音频 - if conn.asr_audio and len(conn.asr_audio) > 0: - first_audio = conn.asr_audio[-1] if conn.asr_audio else b"" - pcm_frame = ( - self.decoder.decode(first_audio, 960) if first_audio else b"" - ) - await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME) - self.server_ready = True - logger.bind(tag=TAG).info("已发送首帧,开始识别") - - # 发送缓存的音频数据 - for cached_audio in conn.asr_audio[-10:]: - try: - pcm_frame = self.decoder.decode(cached_audio, 960) - await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME) - except Exception as e: - logger.bind(tag=TAG).info(f"发送缓存音频数据时发生错误: {e}") - break - - except Exception as e: - logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - self.is_processing = False - raise - - async def _send_audio_frame(self, audio_data: bytes, status: int): - """发送音频帧""" - if not self.asr_ws: - return - - audio_b64 = base64.b64encode(audio_data).decode("utf-8") - - frame_data = { - "header": {"status": status, "app_id": self.app_id}, - "parameter": {"iat": self.iat_params}, - "payload": { - "audio": {"audio": audio_b64, "sample_rate": 16000, "encoding": "raw"} - }, - } - - await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False)) - - # 标记是否发送了最终帧 - if status == STATUS_LAST_FRAME: - self.last_frame_sent = True - logger.bind(tag=TAG).info("标记最终帧已发送") - - async def _forward_results(self, conn): - """转发识别结果""" - try: - while self.asr_ws and not conn.stop_event.is_set(): - # 获取当前连接的音频数据 - audio_data = getattr(conn, "asr_audio_for_voiceprint", []) - try: - # 如果已发送最终帧,增加超时时间等待完整结果 - timeout = 3.0 if self.last_frame_sent else 30.0 - response = await asyncio.wait_for( - self.asr_ws.recv(), timeout=timeout - ) - result = json.loads(response) - logger.bind(tag=TAG).debug(f"收到ASR结果: {result}") - - header = result.get("header", {}) - payload = result.get("payload", {}) - code = header.get("code", 0) - status = header.get("status", 0) - - if code != 0: - logger.bind(tag=TAG).error( - f"识别错误,错误码: {code}, 消息: {header.get('message', '')}" - ) - if code in [10114, 10160]: # 连接问题 - break - continue - - # 处理识别结果 - if payload and "result" in payload: - text_data = payload["result"]["text"] - if text_data: - # 解码base64文本 - decoded_text = base64.b64decode(text_data).decode("utf-8") - text_json = json.loads(decoded_text) - - # 提取文本内容 - text_ws = text_json.get("ws", []) - result_text = "" - for i in text_ws: - for j in i.get("cw", []): - w = j.get("w", "") - result_text += w - - # 更新识别文本 - 实时更新策略 - # 只检查是否为空字符串,不再过滤任何标点符号 - # 这样可以确保所有识别到的内容,包括标点符号都能被实时更新 - if result_text and result_text.strip(): - # 实时更新:正常情况下都更新,提高响应速度 - should_update = True - - # 保存最佳文本 - # 1. 如果是识别完成状态或最终帧后收到的结果,优先保存 - # 2. 否则保存最长的有意义文本 - # 取消对标点符号的过滤,只检查是否为空 - # 这样可以保留所有识别到的内容,包括各种标点符号 - is_valid_text = len(result_text.strip()) > 0 - - if ( - self.last_frame_sent or status == 2 - ) and is_valid_text: - self.best_text = result_text - self.has_final_result = True # 标记已收到最终结果 - logger.bind(tag=TAG).debug( - f"保存最终识别结果: {self.best_text}" - ) - elif ( - len(result_text) > len(self.best_text) - and is_valid_text - and not self.has_final_result - ): - self.best_text = result_text - logger.bind(tag=TAG).debug( - f"保存中间最佳文本: {self.best_text}" - ) - - # 如果已发送最终帧,只过滤空文本 - if self.last_frame_sent: - # 只拒绝完全空的结果 - if not result_text.strip(): - should_update = False - logger.bind(tag=TAG).warning( - f"最终帧后拒绝空文本" - ) - - if should_update: - # 处理流式识别结果,避免简单替换导致内容丢失 - # 1. 如果是中间状态(非最终帧后),可能需要替换为更完整的识别 - # 2. 如果是最终帧后收到的结果,可能是对前面文本的补充 - if self.last_frame_sent: - # 最终帧后收到的结果可能是标点符号等补充内容 - # 检查是否需要合并文本而不是替换 - # 如果当前文本是纯标点而前面已有内容,应该追加而不是替换 - if len( - self.text - ) > 0 and result_text.strip() in [ - "。", - ".", - "?", - "?", - "!", - "!", - ",", - ",", - ";", - ";", - ]: - # 对于标点符号,追加到现有文本后 - self.text = ( - self.text.rstrip().rstrip("。.") - + result_text - ) - else: - # 其他情况保持替换逻辑 - self.text = result_text - else: - # 中间状态替换为新的识别结果 - self.text = result_text - - logger.bind(tag=TAG).info( - f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})" - ) - - # 识别完成,但如果还没发送最终帧,继续等待 - if status == 2: - logger.bind(tag=TAG).info( - f"识别完成状态已到达,当前识别文本: {self.text}" - ) - - # 如果还没发送最终帧,继续等待 - if not self.last_frame_sent: - logger.bind(tag=TAG).info( - "识别完成但最终帧未发送,继续等待..." - ) - continue - - # 已发送最终帧且收到完成状态,使用最佳策略选择最终结果 - # 优先使用识别完成状态下的最新结果,而不是仅仅基于长度 - if self.best_text: - # 如果当前文本是在最终帧发送后或识别完成状态下收到的,优先使用 - if ( - self.last_frame_sent or status == 2 - ) and self.text.strip(): - logger.bind(tag=TAG).info( - f"使用完成状态下的最新识别结果: {self.text}" - ) - elif len(self.best_text) > len(self.text): - logger.bind(tag=TAG).info( - f"使用更长的最佳文本作为最终结果: {self.text} -> {self.best_text}" - ) - self.text = self.best_text - - logger.bind(tag=TAG).info(f"获取到最终完整文本: {self.text}") - conn.reset_vad_states() - if len(audio_data) > 15: # 确保有足够音频数据 - # 准备处理结果 - pass - break - - except asyncio.TimeoutError: - if self.last_frame_sent: - # 超时时也使用最佳文本 - if self.best_text and len(self.best_text) > len(self.text): - logger.bind(tag=TAG).info( - f"超时,使用最佳文本: {self.text} -> {self.best_text}" - ) - self.text = self.best_text - logger.bind(tag=TAG).info( - f"最终帧后超时,使用结果: {self.text}" - ) - break - # 如果还没发送最终帧,继续等待 - continue - except websockets.ConnectionClosed: - logger.bind(tag=TAG).info("ASR服务连接已关闭") - self.is_processing = False - break - except Exception as e: - logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - self.is_processing = False - break - - except Exception as e: - logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}") - if hasattr(e, "__cause__") and e.__cause__: - logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}") - finally: - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - self.is_processing = False - if conn: - if hasattr(conn, "asr_audio_for_voiceprint"): - conn.asr_audio_for_voiceprint = [] - if hasattr(conn, "asr_audio"): - conn.asr_audio = [] - if hasattr(conn, "has_valid_voice"): - conn.has_valid_voice = False - - async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): - """处理语音停止,发送最后一帧并处理识别结果""" - try: - # 先发送最后一帧表示音频结束 - if self.asr_ws and self.is_processing: - try: - # 取最后一个有效的音频帧作为最后一帧数据 - last_frame = b"" - if asr_audio_task: - last_audio = asr_audio_task[-1] - last_frame = self.decoder.decode(last_audio, 960) - await self._send_audio_frame(last_frame, STATUS_LAST_FRAME) - logger.bind(tag=TAG).info("已发送最后一帧") - - # 发送最终帧后,给_forward_results适当时间处理最终结果 - await asyncio.sleep(0.25) - - logger.bind(tag=TAG).info(f"准备处理最终识别结果: {self.text}") - except Exception as e: - logger.bind(tag=TAG).error(f"发送最后一帧失败: {e}") - - # 调用父类的handle_voice_stop方法处理识别结果 - await super().handle_voice_stop(conn, asr_audio_task) - except Exception as e: - logger.bind(tag=TAG).error(f"处理语音停止失败: {e}") - import traceback - - logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}") - - def stop_ws_connection(self): - if self.asr_ws: - asyncio.create_task(self.asr_ws.close()) - self.asr_ws = None - self.is_processing = False - - async def _cleanup(self, conn): - """清理资源""" - logger.bind(tag=TAG).info( - f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}" - ) - - # 发送最后一帧 - if self.asr_ws and self.is_processing: - try: - await self._send_audio_frame(b"", STATUS_LAST_FRAME) - await asyncio.sleep(0.1) - logger.bind(tag=TAG).info("已发送最后一帧") - except Exception as e: - logger.bind(tag=TAG).error(f"发送最后一帧失败: {e}") - - # 状态重置 - self.is_processing = False - self.server_ready = False - self.last_frame_sent = False - self.best_text = "" - self.has_final_result = False - logger.bind(tag=TAG).info("ASR状态已重置") - - # 清理任务 - if self.forward_task and not self.forward_task.done(): - self.forward_task.cancel() - try: - await asyncio.wait_for(self.forward_task, timeout=1.0) - except asyncio.CancelledError: - pass - except Exception as e: - logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}") - finally: - self.forward_task = None - - # 关闭连接 - if self.asr_ws: - try: - logger.bind(tag=TAG).debug("正在关闭WebSocket连接") - await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) - logger.bind(tag=TAG).debug("WebSocket连接已关闭") - except Exception as e: - logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}") - finally: - self.asr_ws = None - - # 清理连接的音频缓存 - if conn: - if hasattr(conn, "asr_audio_for_voiceprint"): - conn.asr_audio_for_voiceprint = [] - if hasattr(conn, "asr_audio"): - conn.asr_audio = [] - if hasattr(conn, "has_valid_voice"): - conn.has_valid_voice = False - - logger.bind(tag=TAG).info("ASR会话清理完成") - - async def speech_to_text(self, opus_data, session_id, audio_format): - """获取识别结果""" - result = self.text - self.text = "" - return result, None - - async def close(self): - """资源清理方法""" - if self.asr_ws: - await self.asr_ws.close() - self.asr_ws = None - if self.forward_task: - self.forward_task.cancel() - try: - await self.forward_task - except asyncio.CancelledError: - pass - self.forward_task = None - self.is_processing = False - # 清理所有连接的音频缓冲区 - if hasattr(self, "_connections"): - for conn in self._connections.values(): - if hasattr(conn, "asr_audio_for_voiceprint"): - conn.asr_audio_for_voiceprint = [] - if hasattr(conn, "asr_audio"): - conn.asr_audio = [] - if hasattr(conn, "has_valid_voice"): - conn.has_valid_voice = False diff --git a/main/xiaozhi-server/core/providers/turn_detection/base.py b/main/xiaozhi-server/core/providers/turn_detection/base.py index 7f958d3b6..30639c0c4 100644 --- a/main/xiaozhi-server/core/providers/turn_detection/base.py +++ b/main/xiaozhi-server/core/providers/turn_detection/base.py @@ -2,10 +2,14 @@ from abc import ABC, abstractmethod from dataclasses import dataclass from enum import Enum import time -from typing import List, Optional, Tuple +import asyncio +from typing import TYPE_CHECKING from config.logger import setup_logging +if TYPE_CHECKING: + from core.connection import ConnectionHandler + TAG = __name__ logger = setup_logging() @@ -29,45 +33,68 @@ class TurnDetectionProviderBase(ABC): Turn Detection determines whether the user has finished speaking and it's time for the system to respond. - Manages text buffer internally - subclasses can override buffer behavior. + Uses conn.asr_text_buffer for accumulated text (maintained by ASR). + + Endpoint delay mechanism: + - When check_end_of_turn is called, first call turn detection service + - If result is "finished", wait min_endpoint_delay + - If result is "unfinished/waiting", wait max_endpoint_delay + - If user continues speaking (new check_end_of_turn call), the task is cancelled """ def __init__(self, config: dict): - self._text_buffer: List[str] = [] - self._buffer_start_time: float = 0.0 - self._buffer_timeout: float = float(config.get("buffer_timeout", 10.0)) + # Endpoint delay: time to wait after last speech before forcing end of turn + # min_endpoint_delay: used when turn detection says "finished" + # max_endpoint_delay: used when turn detection says "unfinished/waiting" + self.min_endpoint_delay: int = config.get("min_endpoint_delay", 500) + self.max_endpoint_delay: int = config.get("max_endpoint_delay", 2000) + # Pending turn detection task (can be cancelled when new speech arrives) + self._turn_detection_task: asyncio.Task = None - def _append_text(self, text: str) -> str: - if not self._text_buffer: - self._buffer_start_time = time.time() - self._text_buffer.append(text) - return " ".join(self._text_buffer) + def _cancel_pending_task(self) -> None: # noqa: F821 + """Cancel pending turn detection task if exists""" + if self._turn_detection_task and not self._turn_detection_task.done(): + self._turn_detection_task.cancel() + logger.bind(tag=TAG).debug("Cancelled pending turn detection task") + self._turn_detection_task = None - def _clear_buffer(self) -> None: - """Clear the text buffer""" - self._text_buffer.clear() - self._buffer_start_time = 0.0 - - def _is_buffer_timeout(self) -> bool: - """Check if buffer has timed out (to avoid infinite accumulation)""" - if not self._text_buffer: - return False - return (time.time() - self._buffer_start_time) > self._buffer_timeout - - @abstractmethod - async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: - """Check if the user has finished their turn + def _calculate_sleep_time(self, conn: "ConnectionHandler", is_finished: bool) -> float: + """Calculate how long to sleep based on turn detection result Args: - text: New ASR text segment + conn: Connection handler containing _last_speaking_time (in ms) + is_finished: True if turn detection says finished, False otherwise Returns: - Tuple of (end_of_turn: bool, full_text: str) - - end_of_turn: True if user finished speaking, False to continue buffering - - full_text: Accumulated text from buffer + Sleep time in seconds (>= 0) + """ + # Choose delay based on turn detection result + endpoint_delay = self.min_endpoint_delay if is_finished else self.max_endpoint_delay + + if conn._last_speaking_time is None: + return endpoint_delay + + # Convert ms to seconds for calculation + elapsed = conn._last_speaking_time - int(time.time() * 1000) + sleep_time = endpoint_delay - elapsed + return sleep_time + + @abstractmethod + def check_end_of_turn(self, conn: "ConnectionHandler"): + """Check if the user has finished their turn + + This method manages the endpoint delay mechanism: + 1. Cancel any pending task from previous call + 2. Create a new task that: + - Calls turn detection service with conn.asr_text_buffer + - Wait min_endpoint_delay (if finished) or max_endpoint_delay (if unfinished) + - If not cancelled, call conn.on_end_of_turn() + + Args: + conn: Connection handler containing asr_text_buffer and _last_speaking_time """ ... async def close(self) -> None: - """Clean up resources - clears buffer""" - self._clear_buffer() + """Clean up resources""" + pass diff --git a/main/xiaozhi-server/core/providers/turn_detection/noop.py b/main/xiaozhi-server/core/providers/turn_detection/noop.py index 708415e4b..eebd11682 100644 --- a/main/xiaozhi-server/core/providers/turn_detection/noop.py +++ b/main/xiaozhi-server/core/providers/turn_detection/noop.py @@ -1,8 +1,11 @@ -from typing import Tuple +from typing import TYPE_CHECKING from config.logger import setup_logging from .base import TurnDetectionProviderBase +if TYPE_CHECKING: + from core.connection import ConnectionHandler + TAG = __name__ logger = setup_logging() @@ -18,14 +21,11 @@ class TurnDetectionProvider(TurnDetectionProviderBase): super().__init__(config) logger.bind(tag=TAG).info("NoopTurnDetection initialized (Turn Detection disabled)") - async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: - """Always return end_of_turn=True immediately + def check_end_of_turn(self, conn: "ConnectionHandler"): + """Immediately trigger end of turn (no delay) Args: - text: The ASR text - - Returns: - Tuple of (True, text) - always signals turn finished + conn: Connection handler """ - # No buffering needed for noop - just return the text as-is - return True, text + import asyncio + asyncio.create_task(conn.on_end_of_turn()) diff --git a/main/xiaozhi-server/core/providers/turn_detection/ten.py b/main/xiaozhi-server/core/providers/turn_detection/ten.py index dcc22a7f4..dcd145923 100644 --- a/main/xiaozhi-server/core/providers/turn_detection/ten.py +++ b/main/xiaozhi-server/core/providers/turn_detection/ten.py @@ -1,9 +1,13 @@ -from typing import Tuple +import asyncio +from typing import TYPE_CHECKING import httpx from config.logger import setup_logging from .base import TurnDetectionProviderBase, TurnDetectionState +if TYPE_CHECKING: + from core.connection import ConnectionHandler + TAG = __name__ logger = setup_logging() @@ -12,7 +16,14 @@ class TurnDetectionProvider(TurnDetectionProviderBase): """HTTP-based Turn Detection provider using httpx async client Calls an external Turn Detection service via HTTP POST. - Gracefully degrades to end_of_turn=True on timeout or errors. + Uses conn.asr_text_buffer for accumulated text (maintained by ASR). + + Implements endpoint delay mechanism: + - First calls turn detection service to get result + - If result is "finished", wait min_endpoint_delay + - If result is "unfinished/waiting", wait max_endpoint_delay + - If user continues speaking during the delay, the task is cancelled + - After delay completes, directly calls startToChat and reports ASR """ def __init__(self, config: dict): @@ -27,31 +38,19 @@ class TurnDetectionProvider(TurnDetectionProviderBase): self._client = httpx.AsyncClient(timeout=self.timeout) logger.bind(tag=TAG).info( - f"TenTurnDetection initialized: url={self.url}, timeout={self.timeout}s" + f"TenTurnDetection initialized: url={self.url}, timeout={self.timeout}s, " + f"min_endpoint_delay={self.min_endpoint_delay}ms, max_endpoint_delay={self.max_endpoint_delay}ms" ) - async def check_end_of_turn(self, text: str) -> Tuple[bool, str]: - """Check if the user has finished their turn via HTTP call + async def _call_turn_detection(self, full_text: str) -> bool: + """Call Turn Detection HTTP service to get result Args: - text: New ASR text segment + full_text: Accumulated text to check Returns: - Tuple of (end_of_turn: bool, full_text: str) - On timeout/error, returns (True, full_text) to avoid blocking + True if turn detection says finished, False otherwise """ - # Append to buffer - full_text = self._append_text(text) - - # Check buffer timeout - if self._is_buffer_timeout(): - logger.bind(tag=TAG).warning( - f"Turn buffer timeout, forcing send: '{full_text[:50]}...'" - ) - self._clear_buffer() - return True, full_text - - # Call Turn Detection service try: response = await self._client.post( self.url, @@ -60,45 +59,97 @@ class TurnDetectionProvider(TurnDetectionProviderBase): response.raise_for_status() data = response.json() logger.bind(tag=TAG).info(f"TD raw response: {data}") - # Parse result string + result_str = data.get("result", "finished") + is_finished = result_str == TurnDetectionState.FINISHED.value - if result_str == TurnDetectionState.FINISHED.value: - logger.bind(tag=TAG).info( - f"Turn finished, buffering: '{full_text[:50]}'" - ) - self._clear_buffer() - return True, full_text - - # UNFINISHED or WAITING: continue buffering logger.bind(tag=TAG).info( - f"Turn unfinished, buffering: '{full_text[:50]}'" + f"Turn detection result: {result_str}, text: '{full_text[:50]}'" ) - return False, full_text + return is_finished except httpx.TimeoutException: logger.bind(tag=TAG).warning( f"TurnDetection timeout ({self.timeout}s), defaulting to finished" ) - self._clear_buffer() - return True, full_text + return True except httpx.HTTPStatusError as e: logger.bind(tag=TAG).error( f"TurnDetection HTTP error: {e.response.status_code}, defaulting to finished" ) - self._clear_buffer() - return True, full_text + return True except Exception as e: logger.bind(tag=TAG).error( f"TurnDetection error: {e}, defaulting to finished" ) - self._clear_buffer() - return True, full_text + return True + + async def _delayed_turn_detection_task( + self, + conn: "ConnectionHandler", + ): + """Task that calls turn detection, then waits for appropriate delay + + Flow: + 1. Call turn detection service to get result + 2. If finished: wait min_endpoint_delay + 3. If unfinished: wait max_endpoint_delay + 4. After delay completes, call startToChat and report ASR + + Args: + conn: Connection handler + + Returns: + True if end of turn, False if cancelled + + Raises: + asyncio.CancelledError: If cancelled by new speech + """ + full_text = conn.asr_text_buffer + + # Step 1: Call turn detection service + is_finished = await self._call_turn_detection(full_text) + + # Step 2: Calculate sleep time based on result + sleep_time = self._calculate_sleep_time(conn, is_finished) + + # Step 3: Wait for the delay + if sleep_time > 0: + await asyncio.sleep(sleep_time / 1000) # Convert ms to seconds + + # Step 4: After delay, trigger end of turn processing + logger.bind(tag=TAG).info("Endpoint delay completed, triggering on_end_of_turn") + await conn.on_end_of_turn() + + def check_end_of_turn(self, conn: "ConnectionHandler"): + """Check if the user has finished their turn with endpoint delay mechanism + + Flow: + 1. Cancel any pending task from previous call + 2. Create a new task that: + - Calls turn detection service + - Waits min_endpoint_delay (if finished) or max_endpoint_delay (if unfinished) + - Calls conn.on_end_of_turn() after delay + + Args: + conn: Connection handler containing asr_text_buffer and _last_speaking_time + """ + # Step 1: Cancel pending task + self._cancel_pending_task() + + logger.bind(tag=TAG).debug( + f"check_end_of_turn called: buffer='{conn.asr_text_buffer[:50]}...'" + ) + + # Step 2: Create the delayed task (don't await, let it run in background) + self._turn_detection_task = asyncio.create_task( + self._delayed_turn_detection_task(conn) + ) async def close(self) -> None: - """Close the httpx client and clear buffer""" + """Close the httpx client""" await super().close() await self._client.aclose() logger.bind(tag=TAG).debug("TenTurnDetection client closed") diff --git a/main/xiaozhi-server/core/providers/vad/base.py b/main/xiaozhi-server/core/providers/vad/base.py index a856b075a..79515ba9f 100644 --- a/main/xiaozhi-server/core/providers/vad/base.py +++ b/main/xiaozhi-server/core/providers/vad/base.py @@ -213,7 +213,8 @@ class VADStream(ABC): 1. Update conn state (client_have_voice = True) 2. Send FIRST message to ASR queue - 3. Check if interrupt is needed (client_is_speaking) + + Note: Interrupt check is done in _handle_inference_done via conn.check_and_interrupt() """ logger.bind(tag=TAG).debug( f"Speech start detected: prob={event.probability:.2f}, " @@ -239,18 +240,6 @@ class VADStream(ABC): logger.bind(tag=TAG).info( f"ASR FIRST message sent: audio={asr_message.audio_duration_ms:.0f}ms" ) - - # Check if interrupt is needed - # When TTS is speaking and user starts talking, trigger interrupt - if conn.client_is_speaking and conn.client_listen_mode != "manual": - logger.bind(tag=TAG).info( - "User started speaking while Agent is speaking, triggering interrupt" - ) - if interrupt_callback: - try: - await interrupt_callback(conn) - except Exception as e: - logger.bind(tag=TAG).error(f"Interrupt callback failed: {e}") async def _handle_inference_done( self, @@ -261,12 +250,17 @@ class VADStream(ABC): ) -> None: """Handle INFERENCE_DONE event - Only send MIDDLE message if speech is ongoing (conn.client_have_voice) + 1. Send MIDDLE message if speech is ongoing + 2. Check smart interrupt via conn.check_and_interrupt() + 3. Update _last_speaking_time for turn detection endpoint delay """ # Only send audio if client is speaking if not conn.client_have_voice or not event.speaking: return + # Update last speaking time for turn detection endpoint delay (ms) + conn._last_speaking_time = int(time.time() * 1000) + # Send MIDDLE message to ASR queue asr_message = ASRInputMessage( message_type=ASRMessageType.MIDDLE, @@ -281,6 +275,9 @@ class VADStream(ABC): f"ASR MIDDLE message sent: prob={event.probability:.2f}, " f"speech={event.speech_duration:.2f}s" ) + + # Check if meeting interruption strategies + conn._interrupt_by_audio(event.speech_duration) async def _handle_speech_end( self, diff --git a/main/xiaozhi-server/core/providers/vad/fsmn.py b/main/xiaozhi-server/core/providers/vad/fsmn.py index 4e1eb6f98..8a2faf0c8 100644 --- a/main/xiaozhi-server/core/providers/vad/fsmn.py +++ b/main/xiaozhi-server/core/providers/vad/fsmn.py @@ -16,9 +16,15 @@ logger = setup_logging() @dataclass class FsmnVADOptions: """FSMN VAD specific options""" - prefix_padding_duration: float = 0.3 # 300ms prefix padding + # User-side parameters (used in _run_task) + prefix_padding_duration: float = 0.3 # 300ms prefix padding (aligned with FSMN lookback) sample_rate: int = 16000 # 16kHz - chunk_size_ms: int = 100 # FSMN chunk size + chunk_size_ms: int = 100 # streaming chunk size in ms + + # FSMN model parameters (passed to AutoModel) + min_silence_duration_ms: int = 500 # silence detection duration (ms) + speech_noise_threshold: float = 0.6 # speech/noise threshold, higher = stricter + sil_to_speech_time_thres: int = 150 # silence→speech transition time (ms), higher = less noise sensitive class VADProvider(VADProviderBase): @@ -29,17 +35,26 @@ class VADProvider(VADProviderBase): model_name = config.get("model", "fsmn-vad") model_revision = config.get("model_revision", "v2.0.4") - - self._model = AutoModel(model=model_name, model_revision=model_revision) - + # Parse config - chunk_size_ms = int(config.get("chunk_size_ms", "100")) self._opts = FsmnVADOptions( - prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")), + prefix_padding_duration=float(config.get("prefix_padding_duration", 0.3)), sample_rate=16000, - chunk_size_ms=chunk_size_ms, + chunk_size_ms=int(config.get("chunk_size_ms", 100)), + min_silence_duration_ms=int(config.get("min_silence_duration_ms", 500)), + speech_noise_threshold=float(config.get("speech_noise_threshold", 0.6)), + sil_to_speech_time_thres=int(config.get("sil_to_speech_time_thres", 150)), ) + # Pass FSMN model parameters to AutoModel + self._model = AutoModel( + model=model_name, + model_revision=model_revision, + max_end_silence_time=self._opts.min_silence_duration_ms, + speech_noise_thres=self._opts.speech_noise_threshold, + sil_to_speech_time_thres=self._opts.sil_to_speech_time_thres, + disable_pbar=True, # disable progress bar + ) def stream(self) -> VADStream: @@ -65,7 +80,7 @@ class FsmnVADStream(VADStream): # FSMN chunk size self._chunk_samples = int(opts.chunk_size_ms * opts.sample_rate / 1000) self._chunk_bytes = self._chunk_samples * 2 # int16 - self._chunk_duration = opts.chunk_size_ms / 1000 # seconds + self._chunk_duration_ms = opts.chunk_size_ms # milliseconds # Speech buffer for prefix padding (in bytes, not samples) self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2 @@ -159,7 +174,7 @@ class FsmnVADStream(VADStream): seg = res[0]["value"][0] # Take first segment seg_start, seg_end = seg[0], seg[1] - if seg_start > 0 and seg_end == -1: + if seg_start >= 0 and seg_end == -1: # Speech start event if not speaking: speaking = True @@ -183,8 +198,7 @@ class FsmnVADStream(VADStream): # Speech end event if speaking: speaking = False - speech_duration_ms = seg_end - speech_start_ms - speech_duration = speech_duration_ms / 1000 + speech_duration = seg_end - speech_start_ms # ms # Emit END_OF_SPEECH self._output_queue.put_nowait(VADEvent( @@ -197,7 +211,7 @@ class FsmnVADStream(VADStream): )) logger.bind(tag=TAG).info( f"🔇 FSMN VAD END_OF_SPEECH @{seg_end}ms | " - f"duration={speech_duration:.2f}s" + f"duration={speech_duration:.0f}ms" ) # Reset for next utterance @@ -211,11 +225,11 @@ class FsmnVADStream(VADStream): f"FSMN: short segment [{seg_start}, {seg_end}]ms (ignored)" ) - # Update durations based on current state + # Update durations based on current state (in milliseconds) if speaking: - speech_duration += self._chunk_duration + speech_duration += self._chunk_duration_ms else: - silence_duration += self._chunk_duration + silence_duration += self._chunk_duration_ms _reset_write_cursor() # Always emit INFERENCE_DONE diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index 807abb65e..3941dcafe 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -12,10 +12,10 @@ from .dto import VADEvent, VADEventType @dataclass class SileroVADOptions: - """Silero VAD specific options""" - min_speech_duration: float = 0.05 # 50ms to confirm speech start - min_silence_duration: float = 0.40 # 400ms to confirm speech end - prefix_padding_duration: float = 0.3 # 300ms prefix padding + """Silero VAD specific options (all durations in milliseconds)""" + min_speech_duration_ms: float = 50.0 # 50ms to confirm speech start + min_silence_duration_ms: float = 400.0 # 400ms to confirm speech end + prefix_padding_duration_ms: float = 300.0 # 300ms prefix padding activation_threshold: float = 0.5 # probability threshold sample_rate: int = 16000 # 16kHz @@ -37,12 +37,12 @@ class VADProvider(VADProviderBase): force_reload=False, ) - # Parse config + # Parse config (all durations in milliseconds) self._opts = SileroVADOptions( - min_speech_duration=float(config.get("min_speech_duration", "0.05")), - min_silence_duration=float(config.get("min_silence_duration", "0.40")), - prefix_padding_duration=float(config.get("prefix_padding_duration", "0.3")), - activation_threshold=float(config.get("threshold", "0.5")), + min_speech_duration_ms=float(config.get("min_speech_duration_ms", 50.0)), + min_silence_duration_ms=float(config.get("min_silence_duration_ms", 400.0)), + prefix_padding_duration_ms=float(config.get("prefix_padding_duration_ms", 300.0)), + activation_threshold=float(config.get("threshold", 0.5)), sample_rate=16000, ) @@ -57,7 +57,7 @@ class SileroVADStream(VADStream): # Silero requires 512 samples per inference (32ms at 16kHz) WINDOW_SIZE_SAMPLES = 512 WINDOW_SIZE_BYTES = WINDOW_SIZE_SAMPLES * 2 # int16 - WINDOW_DURATION = WINDOW_SIZE_SAMPLES / 16000 # seconds + WINDOW_DURATION_MS = WINDOW_SIZE_SAMPLES / 16000 * 1000 # milliseconds (32ms) SLOW_INFERENCE_THRESHOLD = 0.2 # seconds def __init__(self, vad: VADProvider, model, opts: SileroVADOptions): @@ -67,7 +67,7 @@ class SileroVADStream(VADStream): self._exp_filter = ExpFilter(alpha=0.35) # Speech buffer for prefix padding (in bytes, not samples) - self._prefix_padding_bytes = int(opts.prefix_padding_duration * opts.sample_rate) * 2 + self._prefix_padding_bytes = int(opts.prefix_padding_duration_ms / 1000 * opts.sample_rate) * 2 # Pre-allocate max speech buffer (60s + prefix padding) max_speech_bytes = 60 * opts.sample_rate * 2 + self._prefix_padding_bytes self._speech_buffer = bytearray(max_speech_bytes) @@ -133,7 +133,7 @@ class SileroVADStream(VADStream): inference_duration = time.perf_counter() - inference_start extra_inference_time = max( 0.0, - extra_inference_time + inference_duration - self.WINDOW_DURATION, + extra_inference_time + inference_duration - self.WINDOW_DURATION_MS / 1000, ) if inference_duration > self.SLOW_INFERENCE_THRESHOLD: @@ -163,11 +163,11 @@ class SileroVADStream(VADStream): assert self._speech_buffer is not None return bytes(self._speech_buffer[:speech_buffer_index]) - # Update durations + # Update durations (in milliseconds) if pub_speaking: - pub_speech_duration += self.WINDOW_DURATION + pub_speech_duration += self.WINDOW_DURATION_MS else: - pub_silence_duration += self.WINDOW_DURATION + pub_silence_duration += self.WINDOW_DURATION_MS # Emit INFERENCE_DONE self._output_queue.put_nowait(VADEvent( @@ -180,13 +180,13 @@ class SileroVADStream(VADStream): inference_duration=inference_duration, )) - # State machine logic + # State machine logic (all durations in ms) if prob >= self._opts.activation_threshold: - speech_threshold_duration += self.WINDOW_DURATION + speech_threshold_duration += self.WINDOW_DURATION_MS silence_threshold_duration = 0.0 if not pub_speaking: - if speech_threshold_duration >= self._opts.min_speech_duration: + if speech_threshold_duration >= self._opts.min_speech_duration_ms: pub_speaking = True pub_silence_duration = 0.0 pub_speech_duration = speech_threshold_duration @@ -202,13 +202,13 @@ class SileroVADStream(VADStream): inference_duration=inference_duration, )) else: - silence_threshold_duration += self.WINDOW_DURATION + silence_threshold_duration += self.WINDOW_DURATION_MS speech_threshold_duration = 0.0 if not pub_speaking: _reset_write_cursor() - if pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration: + if pub_speaking and silence_threshold_duration >= self._opts.min_silence_duration_ms: pub_speaking = False pub_silence_duration = silence_threshold_duration diff --git a/main/xiaozhi-server/core/utils/tokenize.py b/main/xiaozhi-server/core/utils/tokenize.py new file mode 100644 index 000000000..2cd7b81db --- /dev/null +++ b/main/xiaozhi-server/core/utils/tokenize.py @@ -0,0 +1,100 @@ +import re + + +# Punctuation list +PUNCTUATIONS = [ + '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', + '}', '~', '±', '—', ''', ''', '"', '"', '…' +] + + +def split_words( + text: str, + *, + ignore_punctuation: bool = True, + split_character: bool = False, + retain_format: bool = False, +) -> list[tuple[str, int, int]]: + """ + Split text into words, supporting both space-separated languages (like English) + and character-based languages (like Chinese, Japanese, Korean, Thai). + + For non-spaced scripts, each character is treated as a separate word if split_character is True. + For other languages, words are split by whitespace. + + Returns a list of words with their start and end indices of the original text. + """ + words: list[tuple[str, int, int]] = [] + + # CJK: \u4e00-\u9fff, \u3040-\u30ff, \u3400-\u4dbf + # Thai: \u0E00-\u0E7F + char_based_codes = ( + re.compile( + r"[\u4e00-\u9fff\u3040-\u30ff\u3400-\u4dbf" # CJK scripts + r"\u0E00-\u0E7F]" # Thai + ) + if split_character + else None + ) + + pos = 0 + word_start = 0 + + translation_table = ( + str.maketrans("", "", "".join(PUNCTUATIONS)) if ignore_punctuation else None + ) + + def _add_current_word(start: int, end: int) -> None: + word = text[start:end] + if translation_table and word: + word = word.translate(translation_table) + + if word: + words.append((word, start, end)) + + for pos, char in enumerate(text): + if char.isspace(): + if retain_format and not text[word_start:pos].strip(): + continue + + # reached whitespace, commit current word + _add_current_word(word_start, pos) + word_start = pos if retain_format else pos + 1 + + elif char_based_codes and char_based_codes.match(char): + if word_start < pos: + _add_current_word(word_start, pos) + + # commit character as a word + _add_current_word(pos, pos + 1) + word_start = pos + 1 + + # add the last word if there is one + _add_current_word(word_start, len(text)) + + return words + + +# ===== usage example ===== +if __name__ == "__main__": + # English + print(split_words("Hello world")) + # [('Hello', 0, 5), ('world', 6, 11)] + + # Chinese (not split by character) + print(split_words("你好世界")) + # [('你好世界', 0, 4)] + + # Chinese (split by character) + print(split_words("你好世界", split_character=True)) + # [('你', 0, 1), ('好', 1, 2), ('世', 2, 3), ('界', 3, 4)] + + # Mixed + print(split_words("Hello 你好", split_character=True)) + # [('Hello', 0, 5), ('你', 6, 7), ('好', 7, 8)] + + # Only get word list + words_only = [w[0] for w in split_words("Hello 你好", split_character=True)] + print(words_only) # ['Hello', '你', '好'] + print(len(words_only)) # 3 \ No newline at end of file diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 1da17d443..0a20a6f07 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -85,6 +85,7 @@ class WebSocketServer: "authorization" ][0] if "timezone" in query_params: + self.logger.bind(tag=TAG).info(f"timezone: {query_params['timezone'][0]}") websocket.request.headers["timezone"] = query_params["timezone"][0] """处理新连接,每次创建独立的ConnectionHandler""" diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index d1f3471e0..1074f19ed 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -420,6 +420,7 @@ ASR: base_url: https://api.groq.com/openai/v1 model_name: whisper-large-v3-turbo output_dir: tmp/ + prompt: "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。" VoskASR: # 官方网站:https://alphacephei.com/vosk/ # 配置说明: @@ -483,9 +484,9 @@ VAD: type: silero model_dir: models/snakers4_silero-vad threshold: 0.5 # high threshold to confirm voice - min_silence_duration: 0.40 # silence detection duration (s) - min_speech_duration: 0.05 # speech detection duration (s) - prefix_padding_duration: 0.3 # prefix padding duration (s) + min_silence_duration_ms: 400 # silence detection duration (ms) + min_speech_duration_ms: 100 # speech detection duration (ms) + prefix_padding_duration_ms: 300 # prefix padding duration (ms) activation_threshold: 0.5 # activation threshold sample_rate: 16000 # sample rate # FSMN VAD from FunASR, optimized for Chinese @@ -496,8 +497,13 @@ VAD: model_revision: v2.0.4 chunk_size_ms: 100 # streaming chunk size in ms min_silence_duration_ms: 400 # silence detection duration (ms) - frame_window_threshold: 3 # sliding window threshold + speech_noise_threshold: 0.6 # speech/noise threshold (0.6-0.9), higher = stricter + sil_to_speech_time_thres: 150 # silence->speech transition time (ms), higher = less noise sensitive +Interruption: + enabled: true + min_interrupt_speech_duration_ms: 500 # Minimum speech duration before interrupt (ms) + min_interrupt_text_length: 3 # Minimum ASR text buffer length before interrupt # Turn Detection: Determines if user has finished speaking # Use NoopTurnDetection to disable, HTTPTurnDetection to enable TurnDetection: @@ -509,7 +515,8 @@ TurnDetection: port: 8002 timeout: 0.5 # HTTP request timeout (seconds) endpoint: /turn-detect # API endpoint path - buffer_timeout: 10.0 # Max time to accumulate text (seconds) + min_endpoint_delay: 500 # Min time to wait after last speech before forcing end of turn (milliseconds) + max_endpoint_delay: 2000 # Max time to wait after last speech before forcing end of turn (milliseconds) LLM: # 所有openai类型均可以修改超参,以AliLLM为例 @@ -1122,8 +1129,9 @@ TTS: # ============================= Module Selection ================================ # =============================================================================== selected_module: - VAD: SileroVAD - TurnDetection: NoopTurnDetection # Set to TenTurnDetection to enable + # VAD: FsmnVAD + VAD: FsmnVAD + TurnDetection: TenTurnDetection # Set to TenTurnDetection to enable ASR: GroqASR # ASR: ByteplusStreamASR # LLM: GroqLLM diff --git a/main/xiaozhi-server/test/vad/test_audio.mp3 b/main/xiaozhi-server/test/vad/test_audio.mp3 new file mode 100644 index 000000000..7ea341681 Binary files /dev/null and b/main/xiaozhi-server/test/vad/test_audio.mp3 differ diff --git a/main/xiaozhi-server/test/vad/test_fsmn_vad_stream.py b/main/xiaozhi-server/test/vad/test_fsmn_vad_stream.py new file mode 100644 index 000000000..012fb6e83 --- /dev/null +++ b/main/xiaozhi-server/test/vad/test_fsmn_vad_stream.py @@ -0,0 +1,443 @@ +""" +FSMN VAD Stream Test Script + +This script tests FSMN VAD with audio files, simulating the streaming behavior: + +1. Load an audio file +2. Convert to 16kHz mono PCM +3. Split into 60ms chunks (simulating WebSocket protocol) +4. Feed chunks to FSMN VAD stream +5. Print VAD events (START_OF_SPEECH, END_OF_SPEECH) + +Usage: + python test_fsmn_vad_stream.py + python test_fsmn_vad_stream.py --help + +Example: + python test_fsmn_vad_stream.py test_audio.wav + python test_fsmn_vad_stream.py test_audio.mp3 +""" + +import asyncio +import argparse +import time +import sys +import os +from pathlib import Path +from dataclasses import dataclass +from enum import Enum +from typing import Optional, List, Tuple + +import numpy as np + +# Add project root to path +project_root = Path(__file__).parent.parent.parent +sys.path.insert(0, str(project_root)) + + +# ============================================================================ +# Audio Loading Utilities +# ============================================================================ + +def load_audio_file(file_path: str, target_sample_rate: int = 16000) -> Tuple[np.ndarray, int]: + """ + Load audio file and convert to target sample rate. + + Args: + file_path: Path to audio file (wav, mp3, etc.) + target_sample_rate: Target sample rate (default 16000Hz) + + Returns: + Tuple of (audio_samples as int16 numpy array, sample_rate) + """ + try: + import librosa + except ImportError: + print("Error: librosa is required. Install with: pip install librosa") + sys.exit(1) + + print(f"Loading audio file: {file_path}") + + # Load audio with librosa (auto-converts to mono, resamples) + audio, sr = librosa.load(file_path, sr=target_sample_rate, mono=True) + + # Convert float32 [-1, 1] to int16 [-32768, 32767] + audio_int16 = (audio * 32767).astype(np.int16) + + duration = len(audio_int16) / target_sample_rate + print(f" Sample rate: {sr}Hz") + print(f" Duration: {duration:.2f}s") + print(f" Samples: {len(audio_int16)}") + + return audio_int16, sr + + +def split_audio_to_chunks(audio: np.ndarray, chunk_duration_ms: int, sample_rate: int) -> List[bytes]: + """ + Split audio into fixed-duration chunks. + + Args: + audio: Audio samples as int16 numpy array + chunk_duration_ms: Duration of each chunk in milliseconds + sample_rate: Sample rate in Hz + + Returns: + List of PCM byte chunks + """ + samples_per_chunk = int(chunk_duration_ms * sample_rate / 1000) + chunks = [] + + for i in range(0, len(audio), samples_per_chunk): + chunk = audio[i:i + samples_per_chunk] + # Pad last chunk if necessary + if len(chunk) < samples_per_chunk: + chunk = np.pad(chunk, (0, samples_per_chunk - len(chunk)), mode='constant') + chunks.append(chunk.tobytes()) + + print(f"Split into {len(chunks)} chunks of {chunk_duration_ms}ms each") + return chunks + + +# ============================================================================ +# VAD Event Types (copied to avoid import issues) +# ============================================================================ + +class VADEventType(Enum): + """VAD event types""" + START_OF_SPEECH = "start_of_speech" + INFERENCE_DONE = "inference_done" + END_OF_SPEECH = "end_of_speech" + + +@dataclass +class VADEvent: + """VAD event data structure""" + type: VADEventType + speech_duration: float = 0.0 + silence_duration: float = 0.0 + speaking: bool = False + audio_data: bytes = b"" + inference_duration: float = 0.0 + + def __repr__(self) -> str: + audio_len_ms = len(self.audio_data) / 32 if self.audio_data else 0 + return ( + f"VADEvent(type={self.type.value}, " + f"speaking={self.speaking}, " + f"speech={self.speech_duration:.2f}s, " + f"silence={self.silence_duration:.2f}s, " + f"audio={audio_len_ms:.0f}ms, " + f"inference={self.inference_duration*1000:.1f}ms)" + ) + + +# ============================================================================ +# FSMN VAD Test Runner +# ============================================================================ + +class FsmnVADTester: + """Test FSMN VAD with audio file input""" + + def __init__( + self, + chunk_size_ms: int = 100, + min_silence_duration_ms: int = 500, + speech_noise_threshold: float = 0.6, + prefix_padding_duration: float = 0.3, + ): + self.chunk_size_ms = chunk_size_ms + self.min_silence_duration_ms = min_silence_duration_ms + self.speech_noise_threshold = speech_noise_threshold + self.prefix_padding_duration = prefix_padding_duration + self.sample_rate = 16000 + + # Initialize FSMN model + self._init_model() + + def _init_model(self): + """Initialize FSMN VAD model""" + try: + from funasr import AutoModel + except ImportError: + print("Error: funasr is required. Install with: pip install funasr") + sys.exit(1) + + print("\nInitializing FSMN VAD model...") + self.model = AutoModel( + model="fsmn-vad", + model_revision="v2.0.4", + disable_pbar=True, # disable progress bar + max_end_silence_time=self.min_silence_duration_ms, + speech_noise_thres=self.speech_noise_threshold, + ) + print("Model initialized.") + + def process_audio_file(self, file_path: str, input_chunk_ms: int = 60, verbose: bool = False) -> List[dict]: + """ + Process audio file through FSMN VAD. + + Args: + file_path: Path to audio file + input_chunk_ms: Input chunk size in milliseconds (simulating WebSocket) + + Returns: + List of VAD events with timestamps + """ + # Load and split audio + audio, sr = load_audio_file(file_path, self.sample_rate) + input_chunks = split_audio_to_chunks(audio, input_chunk_ms, self.sample_rate) + + # FSMN processing parameters + chunk_samples = int(self.chunk_size_ms * self.sample_rate / 1000) + chunk_bytes = chunk_samples * 2 # int16 + + # Buffers + input_buffer = bytearray() + inference_buffer = bytearray() + + # Prefix padding + prefix_padding_bytes = int(self.prefix_padding_duration * self.sample_rate) * 2 + max_speech_bytes = 60 * self.sample_rate * 2 + prefix_padding_bytes + speech_buffer = bytearray(max_speech_bytes) + speech_buffer_index = 0 + + # State + fsmn_cache = {} + speaking = False + speech_start_ms = 0 + speech_duration = 0.0 + silence_duration = 0.0 + + # Results + events = [] + current_time_ms = 0 + total_inference_time = 0.0 + inference_count = 0 + + print(f"\n{'='*60}") + print(f"Processing audio with FSMN VAD") + print(f"{'='*60}") + print(f"Input chunk size: {input_chunk_ms}ms") + print(f"FSMN chunk size: {self.chunk_size_ms}ms") + print(f"Min silence duration: {self.min_silence_duration_ms}ms") + print(f"Prefix padding: {self.prefix_padding_duration*1000:.0f}ms") + print() + + def reset_write_cursor(): + nonlocal speech_buffer_index + if speech_buffer_index <= prefix_padding_bytes: + return + padding_data = speech_buffer[ + speech_buffer_index - prefix_padding_bytes : speech_buffer_index + ] + speech_buffer[: prefix_padding_bytes] = padding_data + speech_buffer_index = prefix_padding_bytes + + # Process chunks + for chunk_idx, pcm_chunk in enumerate(input_chunks): + input_buffer.extend(pcm_chunk) + inference_buffer.extend(pcm_chunk) + current_time_ms += input_chunk_ms + + # Process complete FSMN chunks + while len(inference_buffer) >= chunk_bytes: + inference_start = time.perf_counter() + + # Convert to float32 + chunk_int16 = np.frombuffer(inference_buffer[:chunk_bytes], dtype=np.int16) + chunk_float32 = chunk_int16.astype(np.float32) / 32768.0 + + # Run FSMN inference (is_final=False for streaming scenario) + res = self.model.generate( + input=chunk_float32, + cache=fsmn_cache, + is_final=False, + chunk_size=self.chunk_size_ms, + ) + + inference_duration = time.perf_counter() - inference_start + total_inference_time += inference_duration + inference_count += 1 + + # Verbose output: show raw FSMN result + if verbose: + value = res[0].get("value", []) if res and len(res) > 0 else [] + print(f" [{current_time_ms:6.0f}ms] inference #{inference_count:3d} | " + f"result={value} | " + f"time={inference_duration*1000:.2f}ms") + + # Copy to speech buffer + available_space = len(speech_buffer) - speech_buffer_index + to_copy = min(available_space, chunk_bytes) + if to_copy > 0: + speech_buffer[speech_buffer_index:speech_buffer_index + to_copy] = input_buffer[:to_copy] + speech_buffer_index += to_copy + + # Parse FSMN result + if res and len(res) > 0 and res[0].get("value"): + seg = res[0]["value"][0] + seg_start, seg_end = seg[0], seg[1] + + if seg_start >= 0 and seg_end == -1: + # Speech start + if not speaking: + speaking = True + speech_start_ms = seg_start + silence_duration = 0.0 + + audio_data = bytes(speech_buffer[:speech_buffer_index]) + events.append({ + "time_ms": current_time_ms, + "type": "START_OF_SPEECH", + "seg_start_ms": seg_start, + "audio_duration_ms": len(audio_data) / 32, + "inference_ms": inference_duration * 1000, + }) + print(f"🎤 [{current_time_ms:6.0f}ms] START_OF_SPEECH @{seg_start}ms | " + f"audio={len(audio_data)/32:.0f}ms | " + f"inference={inference_duration*1000:.1f}ms") + + elif seg_start == -1 and seg_end > 0: + # Speech end + if speaking: + speaking = False + speech_duration_ms = seg_end - speech_start_ms + speech_duration = speech_duration_ms / 1000 + + audio_data = bytes(speech_buffer[:speech_buffer_index]) + events.append({ + "time_ms": current_time_ms, + "type": "END_OF_SPEECH", + "seg_end_ms": seg_end, + "speech_duration_ms": speech_duration_ms, + "audio_duration_ms": len(audio_data) / 32, + "inference_ms": inference_duration * 1000, + }) + print(f"🔇 [{current_time_ms:6.0f}ms] END_OF_SPEECH @{seg_end}ms | " + f"speech={speech_duration:.2f}s | " + f"audio={len(audio_data)/32:.0f}ms | " + f"inference={inference_duration*1000:.1f}ms") + + # Reset state + speech_duration = 0.0 + fsmn_cache = {} + reset_write_cursor() + + elif seg_start > 0 and seg_end > 0: + # Short segment (ignored) + print(f" [{current_time_ms:6.0f}ms] SHORT_SEGMENT [{seg_start}, {seg_end}]ms (ignored)") + + # Update state + if speaking: + speech_duration += self.chunk_size_ms / 1000 + else: + silence_duration += self.chunk_size_ms / 1000 + reset_write_cursor() + + # Remove processed data + del inference_buffer[:chunk_bytes] + del input_buffer[:to_copy] + + # Summary + print(f"\n{'='*60}") + print(f"Summary") + print(f"{'='*60}") + print(f"Total input chunks: {len(input_chunks)}") + print(f"Total FSMN inferences: {inference_count}") + print(f"Total inference time: {total_inference_time*1000:.1f}ms") + print(f"Average inference time: {total_inference_time/inference_count*1000:.1f}ms" if inference_count > 0 else "N/A") + print(f"Speech segments detected: {len([e for e in events if e['type'] == 'START_OF_SPEECH'])}") + + return events + + +def main(): + parser = argparse.ArgumentParser( + description="Test FSMN VAD with audio file", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + python test_fsmn_vad_stream.py test_audio.wav + python test_fsmn_vad_stream.py test_audio.mp3 --input-chunk-ms 100 + python test_fsmn_vad_stream.py test_audio.wav --min-silence-ms 800 + """ + ) + + parser.add_argument( + "audio_file", + type=str, + help="Path to audio file (wav, mp3, etc.)" + ) + + parser.add_argument( + "--input-chunk-ms", + type=int, + default=60, + help="Input chunk size in milliseconds (default: 60, simulating WebSocket protocol)" + ) + + parser.add_argument( + "--fsmn-chunk-ms", + type=int, + default=100, + help="FSMN inference chunk size in milliseconds (default: 100)" + ) + + parser.add_argument( + "--min-silence-ms", + type=int, + default=500, + help="Minimum silence duration to detect speech end (default: 500)" + ) + + parser.add_argument( + "--speech-noise-threshold", + type=float, + default=0.6, + help="Speech noise threshold (default: 0.6)" + ) + + parser.add_argument( + "--prefix-padding", + type=float, + default=0.3, + help="Prefix padding duration in seconds (default: 0.3)" + ) + + parser.add_argument( + "-v", "--verbose", + action="store_true", + help="Show raw FSMN inference output for each chunk" + ) + + args = parser.parse_args() + + # Validate audio file + if not os.path.exists(args.audio_file): + print(f"Error: Audio file not found: {args.audio_file}") + sys.exit(1) + + # Create tester and run + tester = FsmnVADTester( + chunk_size_ms=args.fsmn_chunk_ms, + min_silence_duration_ms=args.min_silence_ms, + speech_noise_threshold=args.speech_noise_threshold, + prefix_padding_duration=args.prefix_padding, + ) + + events = tester.process_audio_file( + args.audio_file, + input_chunk_ms=args.input_chunk_ms, + verbose=args.verbose, + ) + + print(f"\n{'='*60}") + print(f"All Events") + print(f"{'='*60}") + for event in events: + print(f" {event}") + + +if __name__ == "__main__": + main() + diff --git a/main/xiaozhi-server/test/vad/test_vad_two_sentences.wav b/main/xiaozhi-server/test/vad/test_vad_two_sentences.wav new file mode 100644 index 000000000..9ae85c078 Binary files /dev/null and b/main/xiaozhi-server/test/vad/test_vad_two_sentences.wav differ