diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 0052c7cc5..76669e67f 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -73,9 +73,13 @@ public class AgentController { @GetMapping("/list") @Operation(summary = "获取用户智能体列表") @RequiresPermissions("sys:role:normal") - public Result> getUserAgents() { + public Result> getUserAgents( + @RequestParam(value = "keyword", required = false) String keyword, + @RequestParam(value = "searchType", defaultValue = "name") String searchType) { UserDetail user = SecurityUser.getUser(); - List agents = agentService.getUserAgents(user.getId()); + + // 直接调用整合后的getUserAgents方法,无需再区分搜索和普通查询 + List agents = agentService.getUserAgents(user.getId(), keyword, searchType); return new Result>().ok(agents); } @@ -271,4 +275,6 @@ public class AgentController { .body(audioData); } + + } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java index 218ee1ebf..edad88db9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java @@ -1,6 +1,7 @@ package xiaozhi.modules.agent.dto; import java.util.Date; +import java.util.List; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index a9d4e5bb2..22e8a2e07 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -54,9 +54,11 @@ public interface AgentService extends BaseService { * 获取用户智能体列表 * * @param userId 用户ID + * @param keyword 搜索关键词 + * @param searchType 搜索类型(name - 按名称搜索,mac - 按MAC地址搜索) * @return 智能体列表 */ - List getUserAgents(Long userId); + List getUserAgents(Long userId, String keyword, String searchType); /** * 根据智能体ID获取设备数量 @@ -98,4 +100,6 @@ public interface AgentService extends BaseService { * @return 创建的智能体ID */ String createAgent(AgentCreateDTO dto); + + } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 0adf08738..71a4641ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -42,6 +42,7 @@ import xiaozhi.modules.agent.service.AgentPluginMappingService; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.vo.AgentInfoVO; +import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.model.dto.ModelProviderDTO; import xiaozhi.modules.model.dto.VoiceDTO; @@ -88,13 +89,13 @@ public class AgentServiceImpl extends BaseServiceImpl imp agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode()); } } - + // 查询上下文源配置 AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(id); if (contextProviderEntity != null) { agent.setContextProviders(contextProviderEntity.getContextProviders()); } - + // 无需额外查询插件列表,已通过SQL查询出来 return agent; } @@ -127,38 +128,75 @@ public class AgentServiceImpl extends BaseServiceImpl imp } @Override - public List getUserAgents(Long userId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.eq("user_id", userId); - List agents = agentDao.selectList(wrapper); - return agents.stream().map(agent -> { - AgentDTO dto = new AgentDTO(); - dto.setId(agent.getId()); - dto.setAgentName(agent.getAgentName()); - dto.setSystemPrompt(agent.getSystemPrompt()); + public List getUserAgents(Long userId, String keyword, String searchType) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("user_id", userId); - // 获取 TTS 模型名称 - dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); + // 如果有搜索关键词,根据搜索类型添加相应的查询条件 + if (StringUtils.isNotBlank(keyword)) { + if ("mac".equals(searchType)) { + // 按MAC地址搜索:先搜索设备,再获取对应的智能体 + List devices = deviceService.searchDevicesByMacAddress(keyword, userId); - // 获取 LLM 模型名称 - dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); + if (!devices.isEmpty()) { + // 获取设备对应的智能体ID列表 + List agentIds = devices.stream() + .map(DeviceEntity::getAgentId) + .distinct() + .collect(Collectors.toList()); - // 获取 VLLM 模型名称 - dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId())); + if (!agentIds.isEmpty()) { + queryWrapper.in("id", agentIds); + } else { + return new ArrayList<>(); + } + } else { + return new ArrayList<>(); + } + } else { + // 按名称搜索 + queryWrapper.like("agent_name", keyword); + } + } - // 获取记忆模型名称 - dto.setMemModelId(agent.getMemModelId()); + // 执行查询 + List agentEntities = baseDao.selectList(queryWrapper); - // 获取 TTS 音色名称 - dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); + // 转换为DTO并设置所有必要字段 + return agentEntities.stream().map(this::buildAgentDTO).collect(Collectors.toList()); + } - // 获取智能体最近的最后连接时长 - dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId())); + /** + * 将AgentEntity转换为AgentDTO + */ + private AgentDTO buildAgentDTO(AgentEntity agent) { + AgentDTO dto = new AgentDTO(); + dto.setId(agent.getId()); + dto.setAgentName(agent.getAgentName()); + dto.setSystemPrompt(agent.getSystemPrompt()); - // 获取设备数量 - dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); - return dto; - }).collect(Collectors.toList()); + // 获取 TTS 模型名称 + dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); + + // 获取 LLM 模型名称 + dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); + + // 获取 VLLM 模型名称 + dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId())); + + // 获取记忆模型名称 + dto.setMemModelId(agent.getMemModelId()); + + // 获取 TTS 音色名称 + dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); + + // 获取智能体最近的最后连接时长 + dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId())); + + // 获取设备数量 + dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); + + return dto; } @Override @@ -468,4 +506,5 @@ public class AgentServiceImpl extends BaseServiceImpl imp agentPluginMappingService.saveBatch(toInsert); return entity.getId(); } -} + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index 5b56161f9..f4debba9a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -108,4 +108,13 @@ public interface DeviceService extends BaseService { */ String generateWebSocketToken(String clientId, String username) throws Exception; + /** + * 根据MAC地址搜索设备 + * + * @param macAddress MAC地址关键词 + * @param userId 用户ID + * @return 设备列表 + */ + List searchDevicesByMacAddress(String macAddress, Long userId); + } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 5c8076450..ea0d20eb0 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -496,6 +496,14 @@ public class DeviceServiceImpl extends BaseServiceImpl redisUtils.delete(RedisKeys.getAgentDeviceCountById(dto.getAgentId())); } + @Override + public List searchDevicesByMacAddress(String macAddress, Long userId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.like("mac_address", macAddress); + wrapper.eq("user_id", userId); + return deviceDao.selectList(wrapper); + } + /** * 生成MQTT密码签名 * diff --git a/main/manager-api/src/main/resources/db/changelog/202601051433.sql b/main/manager-api/src/main/resources/db/changelog/202601051433.sql new file mode 100644 index 000000000..15f6d5722 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202601051433.sql @@ -0,0 +1,11 @@ +-- 更改FunASRServer说明文档模型为SenseVoiceSmall +UPDATE `ai_model_config` SET +`doc_link` = 'https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_online_zh.md', +`remark` = '独立部署FunASR,使用FunASR的API服务,只需要五句话 +第一句:mkdir -p ./funasr-runtime-resources/models +第二句:sudo docker run -d -p 10096:10095 --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 iic/SenseVoiceSmall-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' WHERE `id` = 'ASR_FunASRServer'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index dd2bdb102..9a8b23cc7 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -480,3 +480,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202512301430.sql + - changeSet: + id: 202601051433 + author: RanChen + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202601051433.sql diff --git a/main/manager-web/src/apis/module/agent.js b/main/manager-web/src/apis/module/agent.js index 4a76514c4..b90c932ce 100644 --- a/main/manager-web/src/apis/module/agent.js +++ b/main/manager-web/src/apis/module/agent.js @@ -382,4 +382,20 @@ export default { }); }).send(); }, + + // 搜索智能体 + searchAgent(keyword, searchType, callback) { + RequestService.sendRequest() + .url(`${getServiceUrl()}/agent/list?keyword=${encodeURIComponent(keyword)}&searchType=${searchType}`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .networkFail(() => { + RequestService.reAjaxFun(() => { + this.searchAgent(keyword, searchType, callback); + }); + }).send(); + }, } diff --git a/main/manager-web/src/components/HeaderBar.vue b/main/manager-web/src/components/HeaderBar.vue index add7e221e..c661f6fc2 100644 --- a/main/manager-web/src/components/HeaderBar.vue +++ b/main/manager-web/src/components/HeaderBar.vue @@ -408,18 +408,8 @@ export default { // 保存搜索历史 this.saveSearchHistory(searchValue); - try { - // 创建不区分大小写的正则表达式 - const regex = new RegExp(searchValue, "i"); - // 触发搜索事件,将正则表达式传递给父组件 - this.$emit("search", regex); - } catch (error) { - console.error("正则表达式创建失败:", error); - this.$message.error({ - message: this.$t("message.error"), - showClose: true, - }); - } + // 触发搜索事件,将搜索关键词传递给父组件 + this.$emit("search", searchValue); // 搜索完成后让输入框失去焦点,从而触发blur事件隐藏搜索历史 if (this.$refs.searchInput) { diff --git a/main/manager-web/src/i18n/de.js b/main/manager-web/src/i18n/de.js index 22512e8c3..2ecfca595 100644 --- a/main/manager-web/src/i18n/de.js +++ b/main/manager-web/src/i18n/de.js @@ -25,7 +25,7 @@ export default { 'header.featureManagement': 'Systemfunktionsverwaltung', 'header.changePassword': 'Passwort ändern', 'header.logout': 'Abmelden', - 'header.searchPlaceholder': 'Nach Namen suchen..', + 'header.searchPlaceholder': 'Namen oder MAC suchen', // McpToolCallDialog component text 'mcpToolCall.title': 'Werkzeugaufruf', diff --git a/main/manager-web/src/i18n/en.js b/main/manager-web/src/i18n/en.js index 9bcc1f7d2..76876b421 100644 --- a/main/manager-web/src/i18n/en.js +++ b/main/manager-web/src/i18n/en.js @@ -25,7 +25,7 @@ export default { 'header.featureManagement': 'System Feature Management', 'header.changePassword': 'Change Password', 'header.logout': 'Logout', - 'header.searchPlaceholder': 'Search by name..', + 'header.searchPlaceholder': 'Search name or mac', // McpToolCallDialog component text 'mcpToolCall.title': 'Tool Call', diff --git a/main/manager-web/src/i18n/vi.js b/main/manager-web/src/i18n/vi.js index c9d9e1cf4..9e6cb17db 100644 --- a/main/manager-web/src/i18n/vi.js +++ b/main/manager-web/src/i18n/vi.js @@ -25,7 +25,7 @@ export default { 'header.featureManagement': 'Cấu hình chức năng hệ thống', 'header.changePassword': 'Đổi mật khẩu', 'header.logout': 'Đăng xuất', - 'header.searchPlaceholder': 'Tìm kiếm theo tên..', + 'header.searchPlaceholder': 'Tìm tên hoặc MAC', // McpToolCallDialog component text 'mcpToolCall.title': 'Gọi công cụ', diff --git a/main/manager-web/src/i18n/zh_CN.js b/main/manager-web/src/i18n/zh_CN.js index 44d8e400f..bc655d32e 100644 --- a/main/manager-web/src/i18n/zh_CN.js +++ b/main/manager-web/src/i18n/zh_CN.js @@ -25,7 +25,7 @@ export default { 'header.featureManagement': '系统功能配置', 'header.changePassword': '修改密码', 'header.logout': '退出登录', - 'header.searchPlaceholder': '输入名称搜索..', + 'header.searchPlaceholder': '输入名称或mac搜索', // McpToolCallDialog组件文本 'mcpToolCall.title': '工具调用', diff --git a/main/manager-web/src/i18n/zh_TW.js b/main/manager-web/src/i18n/zh_TW.js index ca5a52212..c5ea5b19b 100644 --- a/main/manager-web/src/i18n/zh_TW.js +++ b/main/manager-web/src/i18n/zh_TW.js @@ -25,7 +25,7 @@ export default { 'header.featureManagement': '系統功能配置', 'header.changePassword': '修改密碼', 'header.logout': '退出登錄', - 'header.searchPlaceholder': '輸入名稱搜索..', + 'header.searchPlaceholder': '輸入名稱或mac搜索', // McpToolCallDialog组件文本 'mcpToolCall.title': '工具調用', diff --git a/main/manager-web/src/views/OtaManagement.vue b/main/manager-web/src/views/OtaManagement.vue index 4e1bd8d75..dbf41cece 100644 --- a/main/manager-web/src/views/OtaManagement.vue +++ b/main/manager-web/src/views/OtaManagement.vue @@ -173,8 +173,8 @@ export default { fetchFirmwareList() { this.loading = true; const params = { - pageNum: this.currentPage, - pageSize: this.pageSize, + page: this.currentPage, + limit: this.pageSize, firmwareName: this.searchName || "", orderField: "create_date", order: "desc" @@ -299,9 +299,9 @@ export default { } const paramCount = params.length; - this.$confirm(this.$t('otaManagement.confirmBatchDelete', { paramCount }), 'Warning', { - confirmButtonText: 'OK', - cancelButtonText: 'Cancel', + this.$confirm(this.$t('otaManagement.confirmBatchDelete', { paramCount }), this.$t('common.warning'), { + confirmButtonText: this.$t('common.confirm'), + cancelButtonText: this.$t('common.cancel'), type: 'warning', distinguishCancelAndClose: true }).then(() => { diff --git a/main/manager-web/src/views/VoiceCloneManagement.vue b/main/manager-web/src/views/VoiceCloneManagement.vue index 58f808f45..8ce2b5fd5 100644 --- a/main/manager-web/src/views/VoiceCloneManagement.vue +++ b/main/manager-web/src/views/VoiceCloneManagement.vue @@ -211,8 +211,8 @@ export default { fetchVoiceCloneList() { this.loading = true; const params = { - pageNum: this.currentPage, - pageSize: this.pageSize, + page: this.currentPage, + limit: this.pageSize, name: this.searchName || "", orderField: "create_date", order: "desc" diff --git a/main/manager-web/src/views/VoiceResourceManagement.vue b/main/manager-web/src/views/VoiceResourceManagement.vue index cce107e11..c9b40d321 100644 --- a/main/manager-web/src/views/VoiceResourceManagement.vue +++ b/main/manager-web/src/views/VoiceResourceManagement.vue @@ -159,8 +159,8 @@ export default { fetchVoiceCloneList() { this.loading = true; const params = { - pageNum: this.currentPage, - pageSize: this.pageSize, + page: this.currentPage, + limit: this.pageSize, name: this.searchName || "", orderField: "create_date", order: "desc" diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue index fea5af892..07d46f013 100644 --- a/main/manager-web/src/views/home.vue +++ b/main/manager-web/src/views/home.vue @@ -119,26 +119,32 @@ export default { handleDeviceManage() { this.$router.push('/device-management'); }, - handleSearch(regex) { + handleSearch(keyword) { this.isSearching = true; - this.searchRegex = regex; - this.applySearchFilter(); + this.isLoading = true; + // 检测MAC地址格式:包含4个冒号 + const isMac = /^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(keyword) + const searchType = isMac ? 'mac' : 'name'; + Api.agent.searchAgent(keyword, searchType, ({ data }) => { + if (data?.data) { + this.devices = data.data.map(item => ({ + ...item, + agentId: item.id + })); + } + this.isLoading = false; + }, (error) => { + console.error('搜索智能体失败:', error); + this.isLoading = false; + this.$message.error(this.$t('message.searchFailed')); + }); }, handleSearchReset() { this.isSearching = false; - this.searchRegex = null; + // 直接将原始设备列表赋值给显示设备列表,避免重新加载数据 this.devices = [...this.originalDevices]; }, - applySearchFilter() { - if (!this.isSearching || !this.searchRegex) { - this.devices = [...this.originalDevices]; - return; - } - this.devices = this.originalDevices.filter(device => { - return this.searchRegex.test(device.agentName); - }); - }, // 搜索更新智能体列表 handleSearchResult(filteredList) { this.devices = filteredList; // 更新设备列表 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 9009eef84..a3c54c17d 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -296,7 +296,7 @@ ASR: # 第一句: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 & + # 不要退出容器,继续在容器中执行第四句:nohup bash run_server_2pass.sh --download-model-dir /workspace/models --vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx --model-dir iic/SenseVoiceSmall-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 diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index f899d61c1..a9d8d601e 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -60,6 +60,10 @@ class ManageApiClient: # 为每个事件循环创建独立的客户端 if loop_id not in cls._async_clients: + # 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理 + limits = httpx.Limits( + max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接 + ) cls._async_clients[loop_id] = httpx.AsyncClient( base_url=cls.config.get("url"), headers={ @@ -68,6 +72,7 @@ class ManageApiClient: "Authorization": "Bearer " + cls._secret, }, timeout=cls.config.get("timeout", 30), + limits=limits, # 使用限制 ) return cls._async_clients[loop_id] except RuntimeError: @@ -80,21 +85,27 @@ class ManageApiClient: # 确保客户端已创建 client = await cls._ensure_async_client() endpoint = endpoint.lstrip("/") - response = await client.request(method, endpoint, **kwargs) - response.raise_for_status() + response = None + try: + response = await client.request(method, endpoint, **kwargs) + response.raise_for_status() - result = response.json() + result = response.json() - # 处理API返回的业务错误 - if result.get("code") == 10041: - raise DeviceNotFoundException(result.get("msg")) - elif result.get("code") == 10042: - raise DeviceBindException(result.get("msg")) - elif result.get("code") != 0: - raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") + # 处理API返回的业务错误 + if result.get("code") == 10041: + raise DeviceNotFoundException(result.get("msg")) + elif result.get("code") == 10042: + raise DeviceBindException(result.get("msg")) + elif result.get("code") != 0: + raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") - # 返回成功数据 - return result.get("data") if result.get("code") == 0 else None + # 返回成功数据 + return result.get("data") if result.get("code") == 0 else None + finally: + # 确保响应被关闭(即使异常也会执行) + if response is not None: + await response.aclose() @classmethod def _should_retry(cls, exception: Exception) -> bool: diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index ad8b43851..449fbd2db 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -130,6 +130,8 @@ class ConnectionHandler: # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量 self.asr_audio = [] self.asr_audio_queue = queue.Queue() + self.current_speaker = None # 存储当前说话人 + self.current_language_tag = None # 存储当前ASR识别的语言标签 # llm相关变量 self.llm_finish_task = True diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 8879564f3..ec1d3bc71 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -40,6 +40,7 @@ async def resume_vad_detection(conn): async def startToChat(conn, text): # 检查输入是否是JSON格式(包含说话人信息) speaker_name = None + language_tag = None actual_text = text try: @@ -48,6 +49,7 @@ async def startToChat(conn, text): data = json.loads(text) if "speaker" in data and "content" in data: speaker_name = data["speaker"] + language_tag = data["language"] actual_text = data["content"] conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}") @@ -62,6 +64,11 @@ async def startToChat(conn, text): conn.current_speaker = speaker_name else: conn.current_speaker = None + # 保存语种信息到连接对象 + if language_tag: + conn.current_language_tag = language_tag + else: + conn.current_language_tag = "zh" if conn.need_bind: await check_bind_device(conn) diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 6c6969fd4..0eb23d761 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -118,23 +118,45 @@ class ASRProviderBase(ABC): else: speaker_name = voiceprint_result - if raw_text: - logger.bind(tag=TAG).info(f"识别文本: {raw_text}") - if speaker_name: - logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}") + # 判断 ASR 结果类型 + if isinstance(raw_text, dict): + # FunASR 返回的 dict 格式 + if speaker_name: + raw_text["speaker"] = speaker_name + + # 记录识别结果 + if raw_text.get("language"): + logger.bind(tag=TAG).info(f"识别语言: {raw_text['language']}") + if raw_text.get("emotion"): + logger.bind(tag=TAG).info(f"识别情绪: {raw_text['emotion']}") + if raw_text.get("content"): + logger.bind(tag=TAG).info(f"识别文本: {raw_text['content']}") + if speaker_name: + logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}") + + # 转换为 JSON 字符串用于下游 + enhanced_text = json.dumps(raw_text, ensure_ascii=False) + content_for_length_check = raw_text.get("content", "") + else: + # 其他 ASR 返回的纯文本 + if raw_text: + logger.bind(tag=TAG).info(f"识别文本: {raw_text}") + if speaker_name: + logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}") + + # 构建包含说话人信息的JSON字符串 + enhanced_text = self._build_enhanced_text(raw_text, speaker_name) + content_for_length_check = raw_text # 性能监控 total_time = time.monotonic() - total_start_time logger.bind(tag=TAG).debug(f"总处理耗时: {total_time:.3f}s") # 检查文本长度 - text_len, _ = remove_punctuation_and_length(raw_text) + text_len, _ = remove_punctuation_and_length(content_for_length_check) self.stop_ws_connection() if text_len > 0: - # 构建包含说话人信息的JSON字符串 - enhanced_text = self._build_enhanced_text(raw_text, speaker_name) - # 使用自定义模块进行上报 await startToChat(conn, enhanced_text) enqueue_asr_report(conn, enhanced_text, asr_audio_task) @@ -145,7 +167,7 @@ class ASRProviderBase(ABC): logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}") def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str: - """构建包含说话人信息的文本""" + """构建包含说话人信息的文本(仅用于纯文本ASR)""" if speaker_name and speaker_name.strip(): return json.dumps({ "speaker": speaker_name, diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py index 2fd49c36e..bba53f8a8 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_local.py +++ b/main/xiaozhi-server/core/providers/asr/fun_local.py @@ -6,10 +6,10 @@ import shutil import psutil import asyncio +from funasr import AutoModel from config.logger import setup_logging from typing import Optional, Tuple, List -from funasr import AutoModel -from funasr.utils.postprocess_utils import rich_transcription_postprocess +from core.providers.asr.utils import lang_tag_filter from core.providers.asr.base import ASRProviderBase from core.providers.asr.dto.dto import InterfaceType @@ -102,9 +102,9 @@ class ASRProvider(ASRProviderBase): use_itn=True, batch_size_s=60, ) - text = await asyncio.to_thread(rich_transcription_postprocess, result[0]["text"]) + text = lang_tag_filter(result[0]["text"]) logger.bind(tag=TAG).debug( - f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}" + f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}" ) return text, file_path diff --git a/main/xiaozhi-server/core/providers/asr/fun_server.py b/main/xiaozhi-server/core/providers/asr/fun_server.py index 7eb9e7848..c6674df98 100644 --- a/main/xiaozhi-server/core/providers/asr/fun_server.py +++ b/main/xiaozhi-server/core/providers/asr/fun_server.py @@ -1,12 +1,13 @@ -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 +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.utils import lang_tag_filter +from core.providers.asr.dto.dto import InterfaceType TAG = __name__ logger = setup_logging() @@ -151,9 +152,13 @@ class ASRProvider(ASRProviderBase): # Get the result from the receive task result = receive_task.result() - match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result) - if match: - result = match.group(4).strip() + + # match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result) + # if match: + # result = match.group(4).strip() + + # Handle tags + result = lang_tag_filter(result) return ( result, file_path, diff --git a/main/xiaozhi-server/core/providers/asr/utils.py b/main/xiaozhi-server/core/providers/asr/utils.py new file mode 100644 index 000000000..d1f538aeb --- /dev/null +++ b/main/xiaozhi-server/core/providers/asr/utils.py @@ -0,0 +1,79 @@ +import re +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() + +EMOTION_EMOJI_MAP = { + "HAPPY": "🙂", + "SAD": "😔", + "ANGRY": "😡", + "NEUTRAL": "😶", + "FEARFUL": "😰", + "DISGUSTED": "🤢", + "SURPRISED": "😲", + "EMO_UNKNOWN": "😶", # 未知情绪默认用中性表情 +} +# EVENT_EMOJI_MAP = { +# "<|BGM|>": "🎼", +# "<|Speech|>": "", +# "<|Applause|>": "👏", +# "<|Laughter|>": "😀", +# "<|Cry|>": "😭", +# "<|Sneeze|>": "🤧", +# "<|Breath|>": "", +# "<|Cough|>": "🤧", +# } + +def lang_tag_filter(text: str) -> dict | str: + """ + 解析 FunASR 识别结果,按顺序提取标签和纯文本内容 + + Args: + text: ASR 识别的原始文本,可能包含多种标签 + + Returns: + dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签 + str: 纯文本,如果没有标签 + + Examples: + FunASR 输出格式:<|语种|><|情绪|><|事件|><|其他选项|>原文 + >>> lang_tag_filter("<|zh|><|SAD|><|Speech|><|withitn|>你好啊,测试测试。") + {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好啊,测试测试。"} + >>> lang_tag_filter("<|en|><|HAPPY|><|Speech|><|withitn|>Hello hello.") + {"language": "en", "emotion": "HAPPY", "emoji": "🙂", "content": "Hello hello."} + >>> lang_tag_filter("plain text") + "plain text" + """ + # 提取所有标签(按顺序) + tag_pattern = r"<\|([^|]+)\|>" + all_tags = re.findall(tag_pattern, text) + + # 移除所有 <|...|> 格式的标签,获取纯文本 + clean_text = re.sub(tag_pattern, "", text).strip() + + # 如果没有标签,直接返回纯文本 + if not all_tags: + return clean_text + + # 按照 FunASR 的固定顺序提取标签,返回 dict + language = all_tags[0] if len(all_tags) > 0 else "zh" + emotion = all_tags[1] if len(all_tags) > 1 else "NEUTRAL" + # event = all_tags[2] if len(all_tags) > 2 else "Speech" # 事件标签暂不使用 + + result = { + "content": clean_text, + "language": language, + "emotion": emotion, + # "event": event, + } + + # 添加 emoji 映射 + if emotion in EMOTION_EMOJI_MAP: + result["emotion"] = EMOTION_EMOJI_MAP[emotion] + # 事件标签暂不使用 + # if event in EVENT_EMOJI_MAP: + # result["event"] = EVENT_EMOJI_MAP[event] + + return result + diff --git a/main/xiaozhi-server/core/providers/tts/alibl_stream.py b/main/xiaozhi-server/core/providers/tts/alibl_stream.py index c0d187f0b..3130cb57b 100644 --- a/main/xiaozhi-server/core/providers/tts/alibl_stream.py +++ b/main/xiaozhi-server/core/providers/tts/alibl_stream.py @@ -519,4 +519,4 @@ class TTSProvider(TTSProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}") - return [] + return [] \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 4547ad8f9..9339da7ec 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -15,29 +15,6 @@ from pydub import AudioSegment from typing import Callable, Any TAG = __name__ -emoji_map = { - "neutral": "😶", - "happy": "🙂", - "laughing": "😆", - "funny": "😂", - "sad": "😔", - "angry": "😠", - "crying": "😭", - "loving": "😍", - "embarrassed": "😳", - "surprised": "😲", - "shocked": "😱", - "thinking": "🤔", - "winking": "😉", - "cool": "😎", - "relaxed": "😌", - "delicious": "🤤", - "kissy": "😘", - "confident": "😏", - "sleepy": "😴", - "silly": "😜", - "confused": "🙄", -} def get_local_ip():