mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'xinnan-tech:main' into main
This commit is contained in:
commit
d8d47538b7
29 changed files with 329 additions and 129 deletions
|
|
@ -73,9 +73,13 @@ public class AgentController {
|
|||
@GetMapping("/list")
|
||||
@Operation(summary = "获取用户智能体列表")
|
||||
@RequiresPermissions("sys:role:normal")
|
||||
public Result<List<AgentDTO>> getUserAgents() {
|
||||
public Result<List<AgentDTO>> getUserAgents(
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@RequestParam(value = "searchType", defaultValue = "name") String searchType) {
|
||||
UserDetail user = SecurityUser.getUser();
|
||||
List<AgentDTO> agents = agentService.getUserAgents(user.getId());
|
||||
|
||||
// 直接调用整合后的getUserAgents方法,无需再区分搜索和普通查询
|
||||
List<AgentDTO> agents = agentService.getUserAgents(user.getId(), keyword, searchType);
|
||||
return new Result<List<AgentDTO>>().ok(agents);
|
||||
}
|
||||
|
||||
|
|
@ -271,4 +275,6 @@ public class AgentController {
|
|||
.body(audioData);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -54,9 +54,11 @@ public interface AgentService extends BaseService<AgentEntity> {
|
|||
* 获取用户智能体列表
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param keyword 搜索关键词
|
||||
* @param searchType 搜索类型(name - 按名称搜索,mac - 按MAC地址搜索)
|
||||
* @return 智能体列表
|
||||
*/
|
||||
List<AgentDTO> getUserAgents(Long userId);
|
||||
List<AgentDTO> getUserAgents(Long userId, String keyword, String searchType);
|
||||
|
||||
/**
|
||||
* 根据智能体ID获取设备数量
|
||||
|
|
@ -98,4 +100,6 @@ public interface AgentService extends BaseService<AgentEntity> {
|
|||
* @return 创建的智能体ID
|
||||
*/
|
||||
String createAgent(AgentCreateDTO dto);
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<AgentDao, AgentEntity> 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<AgentDao, AgentEntity> imp
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<AgentDTO> getUserAgents(Long userId) {
|
||||
QueryWrapper<AgentEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("user_id", userId);
|
||||
List<AgentEntity> 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<AgentDTO> getUserAgents(Long userId, String keyword, String searchType) {
|
||||
QueryWrapper<AgentEntity> 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<DeviceEntity> devices = deviceService.searchDevicesByMacAddress(keyword, userId);
|
||||
|
||||
// 获取 LLM 模型名称
|
||||
dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId()));
|
||||
if (!devices.isEmpty()) {
|
||||
// 获取设备对应的智能体ID列表
|
||||
List<String> 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<AgentEntity> 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<AgentDao, AgentEntity> imp
|
|||
agentPluginMappingService.saveBatch(toInsert);
|
||||
return entity.getId();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -108,4 +108,13 @@ public interface DeviceService extends BaseService<DeviceEntity> {
|
|||
*/
|
||||
String generateWebSocketToken(String clientId, String username) throws Exception;
|
||||
|
||||
/**
|
||||
* 根据MAC地址搜索设备
|
||||
*
|
||||
* @param macAddress MAC地址关键词
|
||||
* @param userId 用户ID
|
||||
* @return 设备列表
|
||||
*/
|
||||
List<DeviceEntity> searchDevicesByMacAddress(String macAddress, Long userId);
|
||||
|
||||
}
|
||||
|
|
@ -496,6 +496,14 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
|||
redisUtils.delete(RedisKeys.getAgentDeviceCountById(dto.getAgentId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceEntity> searchDevicesByMacAddress(String macAddress, Long userId) {
|
||||
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.like("mac_address", macAddress);
|
||||
wrapper.eq("user_id", userId);
|
||||
return deviceDao.selectList(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成MQTT密码签名
|
||||
*
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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ụ',
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export default {
|
|||
'header.featureManagement': '系统功能配置',
|
||||
'header.changePassword': '修改密码',
|
||||
'header.logout': '退出登录',
|
||||
'header.searchPlaceholder': '输入名称搜索..',
|
||||
'header.searchPlaceholder': '输入名称或mac搜索',
|
||||
|
||||
// McpToolCallDialog组件文本
|
||||
'mcpToolCall.title': '工具调用',
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export default {
|
|||
'header.featureManagement': '系統功能配置',
|
||||
'header.changePassword': '修改密碼',
|
||||
'header.logout': '退出登錄',
|
||||
'header.searchPlaceholder': '輸入名稱搜索..',
|
||||
'header.searchPlaceholder': '輸入名稱或mac搜索',
|
||||
|
||||
// McpToolCallDialog组件文本
|
||||
'mcpToolCall.title': '工具調用',
|
||||
|
|
|
|||
|
|
@ -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(() => {
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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; // 更新设备列表
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
79
main/xiaozhi-server/core/providers/asr/utils.py
Normal file
79
main/xiaozhi-server/core/providers/asr/utils.py
Normal file
|
|
@ -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
|
||||
|
||||
|
|
@ -519,4 +519,4 @@ class TTSProvider(TTSProviderBase):
|
|||
|
||||
except Exception as e:
|
||||
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
|
||||
return []
|
||||
return []
|
||||
|
|
@ -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():
|
||||
|
|
|
|||
Loading…
Reference in a new issue