mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'main' into main
This commit is contained in:
commit
733f822914
79 changed files with 10098 additions and 6743 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -182,4 +182,5 @@ uploadfile
|
|||
# Do not ignore env and json files inside manager-mobile
|
||||
!main/manager-mobile/**/env/
|
||||
!main/manager-mobile/**/.env*
|
||||
!main/manager-mobile/**/*.json
|
||||
!main/manager-mobile/**/*.json
|
||||
!main/xiaozhi-server/**/*.json
|
||||
|
|
@ -213,4 +213,31 @@ public interface ErrorCode {
|
|||
int RAG_API_ERROR_API_KEY_NULL = 10172; // RAG配置中api_key为空,请完善配置
|
||||
int RAG_API_ERROR_API_KEY_INVALID = 10173; // RAG配置中api_key包含占位符,请替换为实际的API密钥
|
||||
int RAG_API_ERROR_URL_INVALID = 10174; // RAG配置中base_url格式不正确,请检查协议是否正确
|
||||
int RAG_DATASET_ID_NOT_NULL = 10176; // RAG配置中dataset_id不能为空
|
||||
int RAG_MODEL_ID_NOT_NULL = 10177; // RAG配置中model_id不能为空
|
||||
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // RAG配置中dataset_id和model_id不能为空
|
||||
int RAG_FILE_NAME_NOT_NULL = 10179; // 文件名称不能为空
|
||||
int RAG_FILE_CONTENT_EMPTY = 10180; // 文件内容不能为空
|
||||
|
||||
// 设备相关错误码(补充)
|
||||
int MCA_NOT_NULL = 10175; // mac地址不能为空
|
||||
|
||||
// 音色克隆(补充)
|
||||
int VOICE_CLONE_NAME_NOT_NULL = 10181; // 音色克隆名称不能为空
|
||||
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // 音色克隆音频不存在
|
||||
|
||||
// 智能体模板相关错误码(补充)
|
||||
int AGENT_TEMPLATE_NOT_FOUND = 10183; // 默认智能体未找到
|
||||
|
||||
// 知识库适配器相关错误码
|
||||
int RAG_ADAPTER_TYPE_NOT_SUPPORTED = 10184; // 不支持的适配器类型
|
||||
int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG配置验证失败
|
||||
int RAG_ADAPTER_CREATION_FAILED = 10186; // 适配器创建失败
|
||||
int RAG_ADAPTER_INIT_FAILED = 10187; // 适配器初始化失败
|
||||
int RAG_ADAPTER_CONNECTION_FAILED = 10188; // 适配器连接测试失败
|
||||
int RAG_ADAPTER_OPERATION_FAILED = 10189; // 适配器操作失败
|
||||
int RAG_ADAPTER_NOT_FOUND = 10190; // 适配器未找到
|
||||
int RAG_ADAPTER_CACHE_ERROR = 10191; // 适配器缓存错误
|
||||
int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // 适配器类型未找到
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -139,14 +139,14 @@ public class AgentChatHistoryController {
|
|||
// 从Redis获取agentId和sessionId
|
||||
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
|
||||
if (StringUtils.isBlank(agentSessionInfo)) {
|
||||
throw new RenException("下载链接已过期或无效");
|
||||
throw new RenException(ErrorCode.DOWNLOAD_LINK_EXPIRED);
|
||||
}
|
||||
|
||||
try {
|
||||
// 解析agentId和sessionId
|
||||
String[] parts = agentSessionInfo.split(":");
|
||||
if (parts.length != 2) {
|
||||
throw new RenException("下载链接无效");
|
||||
throw new RenException(ErrorCode.DOWNLOAD_LINK_INVALID);
|
||||
}
|
||||
String agentId = parts[0];
|
||||
String sessionId = parts[1];
|
||||
|
|
|
|||
|
|
@ -395,7 +395,20 @@ public class AgentServiceImpl extends BaseServiceImpl<AgentDao, AgentEntity> imp
|
|||
entity.setIntentModelId(template.getIntentModelId());
|
||||
entity.setSystemPrompt(template.getSystemPrompt());
|
||||
entity.setSummaryMemory(template.getSummaryMemory());
|
||||
entity.setChatHistoryConf(template.getChatHistoryConf());
|
||||
|
||||
// 根据记忆模型类型设置默认的chatHistoryConf值
|
||||
if (template.getMemModelId() != null) {
|
||||
if (template.getMemModelId().equals("Memory_nomem")) {
|
||||
// 无记忆功能的模型,默认不记录聊天记录
|
||||
entity.setChatHistoryConf(0);
|
||||
} else {
|
||||
// 有记忆功能的模型,默认记录文本和语音
|
||||
entity.setChatHistoryConf(2);
|
||||
}
|
||||
} else {
|
||||
entity.setChatHistoryConf(template.getChatHistoryConf());
|
||||
}
|
||||
|
||||
entity.setLangCode(template.getLangCode());
|
||||
entity.setLanguage(template.getLanguage());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
// 查询默认智能体
|
||||
AgentTemplateEntity agent = agentTemplateService.getDefaultTemplate();
|
||||
if (agent == null) {
|
||||
throw new RenException("默认智能体未找到");
|
||||
throw new RenException(ErrorCode.AGENT_TEMPLATE_NOT_FOUND);
|
||||
}
|
||||
|
||||
// 构建模块配置
|
||||
|
|
@ -111,13 +111,13 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
if (StringUtils.isNotBlank(cachedCode)) {
|
||||
throw new RenException(ErrorCode.OTA_DEVICE_NEED_BIND, cachedCode);
|
||||
}
|
||||
throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND, "not found device");
|
||||
throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND);
|
||||
}
|
||||
|
||||
// 获取智能体信息
|
||||
AgentEntity agent = agentService.getAgentById(device.getAgentId());
|
||||
if (agent == null) {
|
||||
throw new RenException("智能体未找到");
|
||||
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
|
||||
}
|
||||
// 获取音色信息
|
||||
String voice = null;
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ public class DeviceController {
|
|||
public Result<String> registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) {
|
||||
String macAddress = deviceRegisterDTO.getMacAddress();
|
||||
if (StringUtils.isBlank(macAddress)) {
|
||||
return new Result<String>().error(ErrorCode.NOT_NULL, "mac地址不能为空");
|
||||
return new Result<String>().error(ErrorCode.MCA_NOT_NULL);
|
||||
}
|
||||
// 生成六位验证码
|
||||
String code = String.valueOf(Math.random()).substring(2, 8);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
package xiaozhi.modules.knowledge.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapterFactory;
|
||||
|
||||
/**
|
||||
* 知识库配置类
|
||||
* 配置知识库相关的Bean
|
||||
*/
|
||||
@Configuration
|
||||
public class KnowledgeBaseConfig {
|
||||
|
||||
/**
|
||||
* 提供KnowledgeBaseAdapterFactory的Bean实例
|
||||
* @return KnowledgeBaseAdapterFactory实例
|
||||
*/
|
||||
@Bean
|
||||
public KnowledgeBaseAdapterFactory knowledgeBaseAdapterFactory() {
|
||||
return new KnowledgeBaseAdapterFactory();
|
||||
}
|
||||
}
|
||||
|
|
@ -77,7 +77,7 @@ public class KnowledgeFilesDTO implements Serializable {
|
|||
return STATUS_UNSTART;
|
||||
}
|
||||
|
||||
// 根据run字段的值直接映射到对应的状态码
|
||||
// RAGFlow根据run字段的值直接映射到对应的状态码
|
||||
switch (run.toUpperCase()) {
|
||||
case "RUNNING":
|
||||
return STATUS_RUNNING;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,200 @@
|
|||
package xiaozhi.modules.knowledge.rag;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import xiaozhi.common.page.PageData;
|
||||
import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO;
|
||||
|
||||
/**
|
||||
* 知识库API适配器抽象基类
|
||||
* 定义通用的知识库操作接口,支持多种后端API实现
|
||||
*/
|
||||
public abstract class KnowledgeBaseAdapter {
|
||||
|
||||
/**
|
||||
* 获取适配器类型标识
|
||||
*
|
||||
* @return 适配器类型(如:ragflow, milvus, pinecone等)
|
||||
*/
|
||||
public abstract String getAdapterType();
|
||||
|
||||
/**
|
||||
* 初始化适配器配置
|
||||
*
|
||||
* @param config 配置参数
|
||||
*/
|
||||
public abstract void initialize(Map<String, Object> config);
|
||||
|
||||
/**
|
||||
* 验证配置是否有效
|
||||
*
|
||||
* @param config 配置参数
|
||||
* @return 验证结果
|
||||
*/
|
||||
public abstract boolean validateConfig(Map<String, Object> config);
|
||||
|
||||
/**
|
||||
* 分页查询文档列表
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param queryParams 查询参数
|
||||
* @param page 页码
|
||||
* @param limit 每页数量
|
||||
* @return 分页数据
|
||||
*/
|
||||
public abstract PageData<KnowledgeFilesDTO> getDocumentList(String datasetId,
|
||||
Map<String, Object> queryParams,
|
||||
Integer page,
|
||||
Integer limit);
|
||||
|
||||
/**
|
||||
* 根据文档ID获取文档详情
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @return 文档详情
|
||||
*/
|
||||
public abstract KnowledgeFilesDTO getDocumentById(String datasetId, String documentId);
|
||||
|
||||
/**
|
||||
* 上传文档到知识库
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param file 上传的文件
|
||||
* @param name 文档名称
|
||||
* @param metaFields 元数据字段
|
||||
* @param chunkMethod 分块方法
|
||||
* @param parserConfig 解析器配置
|
||||
* @return 上传的文档信息
|
||||
*/
|
||||
public abstract KnowledgeFilesDTO uploadDocument(String datasetId,
|
||||
MultipartFile file,
|
||||
String name,
|
||||
Map<String, Object> metaFields,
|
||||
String chunkMethod,
|
||||
Map<String, Object> parserConfig);
|
||||
|
||||
/**
|
||||
* 根据状态分页查询文档列表
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param status 文档解析状态
|
||||
* @param page 页码
|
||||
* @param limit 每页数量
|
||||
* @return 分页数据
|
||||
*/
|
||||
public abstract PageData<KnowledgeFilesDTO> getDocumentListByStatus(String datasetId,
|
||||
Integer status,
|
||||
Integer page,
|
||||
Integer limit);
|
||||
|
||||
/**
|
||||
* 删除文档
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param documentId 文档ID
|
||||
*/
|
||||
public abstract void deleteDocument(String datasetId, String documentId);
|
||||
|
||||
/**
|
||||
* 解析文档(切块)
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param documentIds 文档ID列表
|
||||
* @return 解析结果
|
||||
*/
|
||||
public abstract boolean parseDocuments(String datasetId, List<String> documentIds);
|
||||
|
||||
/**
|
||||
* 列出指定文档的切片
|
||||
*
|
||||
* @param datasetId 知识库ID
|
||||
* @param documentId 文档ID
|
||||
* @param keywords 关键词过滤
|
||||
* @param page 页码
|
||||
* @param pageSize 每页数量
|
||||
* @param chunkId 切片ID
|
||||
* @return 切片列表信息
|
||||
*/
|
||||
public abstract Map<String, Object> listChunks(String datasetId,
|
||||
String documentId,
|
||||
String keywords,
|
||||
Integer page,
|
||||
Integer pageSize,
|
||||
String chunkId);
|
||||
|
||||
/**
|
||||
* 召回测试 - 从知识库中检索相关切片
|
||||
*
|
||||
* @param question 用户查询
|
||||
* @param datasetIds 数据集ID列表
|
||||
* @param documentIds 文档ID列表
|
||||
* @param retrievalParams 检索参数
|
||||
* @return 召回测试结果
|
||||
*/
|
||||
public abstract Map<String, Object> retrievalTest(String question,
|
||||
List<String> datasetIds,
|
||||
List<String> documentIds,
|
||||
Map<String, Object> retrievalParams);
|
||||
|
||||
/**
|
||||
* 测试连接
|
||||
*
|
||||
* @return 连接测试结果
|
||||
*/
|
||||
public abstract boolean testConnection();
|
||||
|
||||
/**
|
||||
* 获取适配器状态信息
|
||||
*
|
||||
* @return 状态信息
|
||||
*/
|
||||
public abstract Map<String, Object> getStatus();
|
||||
|
||||
/**
|
||||
* 获取支持的配置参数
|
||||
*
|
||||
* @return 配置参数说明
|
||||
*/
|
||||
public abstract Map<String, Object> getSupportedConfig();
|
||||
|
||||
/**
|
||||
* 获取默认配置
|
||||
*
|
||||
* @return 默认配置
|
||||
*/
|
||||
public abstract Map<String, Object> getDefaultConfig();
|
||||
|
||||
/**
|
||||
* 创建数据集
|
||||
*
|
||||
* @param createParams 创建参数
|
||||
* @return 数据集ID
|
||||
*/
|
||||
public abstract String createDataset(Map<String, Object> createParams);
|
||||
|
||||
/**
|
||||
* 更新数据集
|
||||
*
|
||||
* @param datasetId 数据集ID
|
||||
* @param updateParams 更新参数
|
||||
*/
|
||||
public abstract void updateDataset(String datasetId, Map<String, Object> updateParams);
|
||||
|
||||
/**
|
||||
* 删除数据集
|
||||
*
|
||||
* @param datasetId 数据集ID
|
||||
*/
|
||||
public abstract void deleteDataset(String datasetId);
|
||||
|
||||
/**
|
||||
* 获取数据集的文档数量
|
||||
*
|
||||
* @param datasetId 数据集ID
|
||||
* @return 文档数量
|
||||
*/
|
||||
public abstract Integer getDocumentCount(String datasetId);
|
||||
}
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
package xiaozhi.modules.knowledge.rag;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import xiaozhi.common.exception.ErrorCode;
|
||||
import xiaozhi.common.exception.RenException;
|
||||
|
||||
/**
|
||||
* 知识库适配器工厂类
|
||||
* 负责创建和管理不同类型的知识库API适配器
|
||||
*/
|
||||
@Slf4j
|
||||
public class KnowledgeBaseAdapterFactory {
|
||||
|
||||
// 注册的适配器类型映射
|
||||
private static final Map<String, Class<? extends KnowledgeBaseAdapter>> adapterRegistry = new HashMap<>();
|
||||
|
||||
// 适配器实例缓存
|
||||
private static final Map<String, KnowledgeBaseAdapter> adapterCache = new ConcurrentHashMap<>();
|
||||
|
||||
static {
|
||||
// 注册内置适配器类型
|
||||
registerAdapter("ragflow", xiaozhi.modules.knowledge.rag.impl.RAGFlowAdapter.class);
|
||||
// 可以在这里注册更多适配器类型
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册新的适配器类型
|
||||
*
|
||||
* @param adapterType 适配器类型标识
|
||||
* @param adapterClass 适配器类
|
||||
*/
|
||||
public static void registerAdapter(String adapterType, Class<? extends KnowledgeBaseAdapter> adapterClass) {
|
||||
if (adapterRegistry.containsKey(adapterType)) {
|
||||
log.warn("适配器类型 '{}' 已存在,将被覆盖", adapterType);
|
||||
}
|
||||
adapterRegistry.put(adapterType, adapterClass);
|
||||
log.info("注册适配器类型: {} -> {}", adapterType, adapterClass.getSimpleName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取适配器实例
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
* @param config 配置参数
|
||||
* @return 适配器实例
|
||||
*/
|
||||
public static KnowledgeBaseAdapter getAdapter(String adapterType, Map<String, Object> config) {
|
||||
String cacheKey = buildCacheKey(adapterType, config);
|
||||
|
||||
// 检查缓存中是否已存在实例
|
||||
if (adapterCache.containsKey(cacheKey)) {
|
||||
log.debug("从缓存获取适配器实例: {}", cacheKey);
|
||||
return adapterCache.get(cacheKey);
|
||||
}
|
||||
|
||||
// 创建新的适配器实例
|
||||
KnowledgeBaseAdapter adapter = createAdapter(adapterType, config);
|
||||
|
||||
// 缓存适配器实例
|
||||
adapterCache.put(cacheKey, adapter);
|
||||
log.info("创建并缓存适配器实例: {}", cacheKey);
|
||||
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取适配器实例(无配置)
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
* @return 适配器实例
|
||||
*/
|
||||
public static KnowledgeBaseAdapter getAdapter(String adapterType) {
|
||||
return getAdapter(adapterType, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有已注册的适配器类型
|
||||
*
|
||||
* @return 适配器类型集合
|
||||
*/
|
||||
public static Set<String> getRegisteredAdapterTypes() {
|
||||
return adapterRegistry.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查适配器类型是否已注册
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
* @return 是否已注册
|
||||
*/
|
||||
public static boolean isAdapterTypeRegistered(String adapterType) {
|
||||
return adapterRegistry.containsKey(adapterType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除适配器缓存
|
||||
*/
|
||||
public static void clearCache() {
|
||||
int cacheSize = adapterCache.size();
|
||||
adapterCache.clear();
|
||||
log.info("清除适配器缓存,共清除 {} 个实例", cacheSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除特定适配器类型的缓存
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
*/
|
||||
public static void removeCacheByType(String adapterType) {
|
||||
int removedCount = 0;
|
||||
for (String cacheKey : adapterCache.keySet()) {
|
||||
if (cacheKey.startsWith(adapterType + "@")) {
|
||||
adapterCache.remove(cacheKey);
|
||||
removedCount++;
|
||||
}
|
||||
}
|
||||
log.info("移除适配器类型 '{}' 的缓存,共移除 {} 个实例", adapterType, removedCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取适配器工厂状态信息
|
||||
*
|
||||
* @return 状态信息
|
||||
*/
|
||||
public static Map<String, Object> getFactoryStatus() {
|
||||
Map<String, Object> status = new HashMap<>();
|
||||
status.put("registeredAdapterTypes", adapterRegistry.keySet());
|
||||
status.put("cachedAdapterCount", adapterCache.size());
|
||||
status.put("cacheKeys", adapterCache.keySet());
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建适配器实例
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
* @param config 配置参数
|
||||
* @return 适配器实例
|
||||
*/
|
||||
private static KnowledgeBaseAdapter createAdapter(String adapterType, Map<String, Object> config) {
|
||||
if (!adapterRegistry.containsKey(adapterType)) {
|
||||
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED,
|
||||
"不支持的适配器类型: " + adapterType);
|
||||
}
|
||||
|
||||
try {
|
||||
Class<? extends KnowledgeBaseAdapter> adapterClass = adapterRegistry.get(adapterType);
|
||||
KnowledgeBaseAdapter adapter = adapterClass.getDeclaredConstructor().newInstance();
|
||||
|
||||
// 初始化适配器
|
||||
if (config != null) {
|
||||
adapter.initialize(config);
|
||||
|
||||
// 验证配置
|
||||
if (!adapter.validateConfig(config)) {
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_VALIDATION_FAILED,
|
||||
"适配器配置验证失败: " + adapterType);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("成功创建适配器实例: {}", adapterType);
|
||||
return adapter;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("创建适配器实例失败: {}", adapterType, e);
|
||||
throw new RenException(ErrorCode.RAG_ADAPTER_CREATION_FAILED,
|
||||
"创建适配器失败: " + adapterType + ", 错误: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建缓存键
|
||||
*
|
||||
* @param adapterType 适配器类型
|
||||
* @param config 配置参数
|
||||
* @return 缓存键
|
||||
*/
|
||||
private static String buildCacheKey(String adapterType, Map<String, Object> config) {
|
||||
if (config == null || config.isEmpty()) {
|
||||
return adapterType + "@default";
|
||||
}
|
||||
|
||||
// 基于配置参数生成缓存键
|
||||
StringBuilder keyBuilder = new StringBuilder(adapterType + "@");
|
||||
|
||||
// 使用配置的哈希值作为缓存键的一部分
|
||||
int configHash = config.hashCode();
|
||||
keyBuilder.append(configHash);
|
||||
|
||||
return keyBuilder.toString();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -35,6 +35,8 @@ import xiaozhi.common.utils.MessageUtils;
|
|||
import xiaozhi.modules.knowledge.dao.KnowledgeBaseDao;
|
||||
import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO;
|
||||
import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity;
|
||||
import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapter;
|
||||
import xiaozhi.modules.knowledge.rag.KnowledgeBaseAdapterFactory;
|
||||
import xiaozhi.modules.knowledge.service.KnowledgeBaseService;
|
||||
import xiaozhi.modules.model.dao.ModelConfigDao;
|
||||
import xiaozhi.modules.model.entity.ModelConfigEntity;
|
||||
|
|
@ -106,7 +108,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
if (pageData != null && pageData.getList() != null) {
|
||||
for (KnowledgeBaseDTO knowledgeBase : pageData.getList()) {
|
||||
try {
|
||||
Integer documentCount = getDocumentCountFromRAGFlow(knowledgeBase.getDatasetId(),
|
||||
Integer documentCount = getDocumentCountFromRAG(knowledgeBase.getDatasetId(),
|
||||
knowledgeBase.getRagModelId());
|
||||
knowledgeBase.setDocumentCount(documentCount);
|
||||
} catch (Exception e) {
|
||||
|
|
@ -146,10 +148,10 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
checkDuplicateKnowledgeBaseName(knowledgeBaseDTO, null);
|
||||
|
||||
String datasetId = null;
|
||||
// 调用RAGFlow API创建数据集
|
||||
// 调用RAG API创建数据集
|
||||
try {
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
|
||||
datasetId = createDatasetInRAGFlow(
|
||||
datasetId = createDatasetInRAG(
|
||||
knowledgeBaseDTO.getName(),
|
||||
knowledgeBaseDTO.getDescription(),
|
||||
ragConfig);
|
||||
|
|
@ -162,13 +164,13 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
KnowledgeBaseEntity existingEntity = knowledgeBaseDao.selectOne(
|
||||
new QueryWrapper<KnowledgeBaseEntity>().eq("dataset_id", datasetId));
|
||||
if (existingEntity != null) {
|
||||
// 如果datasetId已存在,删除RAGFlow中的数据集并抛出异常
|
||||
// 如果datasetId已存在,删除RAG中的数据集并抛出异常
|
||||
try {
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
|
||||
deleteDatasetInRAGFlow(datasetId, ragConfig);
|
||||
deleteDatasetInRAG(datasetId, ragConfig);
|
||||
} catch (Exception deleteException) {
|
||||
// 提供更详细的错误信息,包括异常类型和消息
|
||||
String errorMessage = "删除重复datasetId的RAGFlow数据集失败: " + deleteException.getClass().getSimpleName();
|
||||
String errorMessage = "删除重复datasetId的RAG数据集失败: " + deleteException.getClass().getSimpleName();
|
||||
if (deleteException.getMessage() != null) {
|
||||
errorMessage += " - " + deleteException.getMessage();
|
||||
}
|
||||
|
|
@ -219,17 +221,17 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
// 先校验RAG配置
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
|
||||
|
||||
// 调用RAGFlow API更新数据集
|
||||
updateDatasetInRAGFlow(
|
||||
// 调用RAG API更新数据集
|
||||
updateDatasetInRAG(
|
||||
knowledgeBaseDTO.getDatasetId(),
|
||||
knowledgeBaseDTO.getName(),
|
||||
knowledgeBaseDTO.getDescription(),
|
||||
ragConfig);
|
||||
|
||||
log.info("RAGFlow API更新成功,datasetId: {}", knowledgeBaseDTO.getDatasetId());
|
||||
log.info("RAG API更新成功,datasetId: {}", knowledgeBaseDTO.getDatasetId());
|
||||
} catch (Exception e) {
|
||||
// 提供更详细的错误信息,包括异常类型和消息
|
||||
String errorMessage = "更新RAGFlow数据集失败: " + e.getClass().getSimpleName();
|
||||
String errorMessage = "更新RAG数据集失败: " + e.getClass().getSimpleName();
|
||||
if (e.getMessage() != null) {
|
||||
errorMessage += " - " + e.getMessage();
|
||||
}
|
||||
|
|
@ -237,7 +239,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
throw e;
|
||||
}
|
||||
} else {
|
||||
log.warn("datasetId或ragModelId为空,跳过RAGFlow更新");
|
||||
log.warn("datasetId或ragModelId为空,跳过RAG更新");
|
||||
}
|
||||
|
||||
KnowledgeBaseEntity entity = ConvertUtils.sourceToTarget(knowledgeBaseDTO, KnowledgeBaseEntity.class);
|
||||
|
|
@ -288,19 +290,19 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
log.info("找到记录: ID={}, datasetId={}, ragModelId={}",
|
||||
entity.getId(), entity.getDatasetId(), entity.getRagModelId());
|
||||
|
||||
// 先调用RAGFlow API删除数据集
|
||||
// 先调用RAG API删除数据集
|
||||
boolean apiDeleteSuccess = false;
|
||||
if (StringUtils.isNotBlank(entity.getDatasetId()) && StringUtils.isNotBlank(entity.getRagModelId())) {
|
||||
try {
|
||||
log.info("开始调用RAGFlow API删除数据集");
|
||||
log.info("开始调用RAG API删除数据集");
|
||||
// 在删除前进行RAG配置校验
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(entity.getRagModelId());
|
||||
deleteDatasetInRAGFlow(entity.getDatasetId(), ragConfig);
|
||||
log.info("RAGFlow API删除调用完成");
|
||||
deleteDatasetInRAG(entity.getDatasetId(), ragConfig);
|
||||
log.info("RAG API删除调用完成");
|
||||
apiDeleteSuccess = true;
|
||||
} catch (Exception e) {
|
||||
// 提供更详细的错误信息,包括异常类型和消息
|
||||
String errorMessage = "删除RAGFlow数据集失败: " + e.getClass().getSimpleName();
|
||||
String errorMessage = "删除RAG数据集失败: " + e.getClass().getSimpleName();
|
||||
if (e.getMessage() != null) {
|
||||
errorMessage += " - " + e.getMessage();
|
||||
}
|
||||
|
|
@ -308,7 +310,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
throw e;
|
||||
}
|
||||
} else {
|
||||
log.warn("datasetId或ragModelId为空,跳过RAGFlow删除");
|
||||
log.warn("datasetId或ragModelId为空,跳过RAG删除");
|
||||
apiDeleteSuccess = true; // 没有RAG数据集,视为成功
|
||||
}
|
||||
|
||||
|
|
@ -356,7 +358,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
@Override
|
||||
public Map<String, Object> getRAGConfigByDatasetId(String datasetId) {
|
||||
if (StringUtils.isBlank(datasetId)) {
|
||||
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空");
|
||||
throw new RenException(ErrorCode.RAG_DATASET_ID_NOT_NULL);
|
||||
}
|
||||
|
||||
// 根据datasetId查询知识库信息
|
||||
|
|
@ -370,7 +372,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
String ragModelId = knowledgeBase.getRagModelId();
|
||||
if (StringUtils.isBlank(ragModelId)) {
|
||||
log.warn("知识库datasetId为{}未配置ragModelId", datasetId);
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "知识库未配置RAG模型");
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
|
||||
}
|
||||
|
||||
// 获取并返回RAG配置
|
||||
|
|
@ -403,7 +405,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
*/
|
||||
private void validateRagConfig(Map<String, Object> config) {
|
||||
if (config == null) {
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "RAG配置为空,请检查配置");
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
|
||||
}
|
||||
|
||||
// 从配置中提取必要的参数
|
||||
|
|
@ -432,292 +434,133 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
}
|
||||
|
||||
/**
|
||||
* 调用RAGFlow API创建数据集
|
||||
* 从RAG配置中提取适配器类型
|
||||
*
|
||||
* @param config RAG配置
|
||||
* @return 适配器类型
|
||||
*/
|
||||
private String createDatasetInRAGFlow(String name, String description, Map<String, Object> ragConfig) {
|
||||
String datasetId = null;
|
||||
String baseUrl = (String) ragConfig.get("base_url");
|
||||
String apiKey = (String) ragConfig.get("api_key");
|
||||
|
||||
log.info("开始调用RAGFlow API创建数据集, name: {}", name);
|
||||
log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置");
|
||||
|
||||
// 构建请求URL
|
||||
String url = baseUrl + "/api/v1/datasets";
|
||||
log.debug("请求URL: {}", url);
|
||||
|
||||
// 构建请求体
|
||||
Map<String, Object> requestBody = new HashMap<>();
|
||||
String username = SecurityUser.getUser().getUsername();
|
||||
requestBody.put("name", username + "_" + name);
|
||||
if (StringUtils.isNotBlank(description)) {
|
||||
requestBody.put("description", description);
|
||||
}
|
||||
log.debug("请求体: {}", requestBody);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("Authorization", "Bearer " + apiKey);
|
||||
|
||||
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
// 发送POST请求
|
||||
log.info("发送POST请求到RAGFlow API...");
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
|
||||
} catch (Exception e) {
|
||||
String errorMessage = url + e.getMessage();
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
private String extractAdapterType(Map<String, Object> config) {
|
||||
if (config == null) {
|
||||
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
|
||||
}
|
||||
|
||||
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
|
||||
log.debug("RAGFlow API响应内容: {}", response.getBody());
|
||||
// 从配置中提取适配器类型
|
||||
String adapterType = (String) config.get("type");
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody();
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
// 验证适配器类型是否存在且非空
|
||||
if (StringUtils.isBlank(adapterType)) {
|
||||
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_FOUND);
|
||||
}
|
||||
|
||||
// 解析响应体,提取datasetId
|
||||
String responseBody = response.getBody();
|
||||
if (StringUtils.isNotBlank(responseBody)) {
|
||||
try {
|
||||
// 解析RAGFlow API响应,支持多种可能的字段名
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
|
||||
|
||||
log.debug("RAGFlow API响应解析结果: {}", responseMap);
|
||||
|
||||
// 首先检查响应码
|
||||
Integer code = (Integer) responseMap.get("code");
|
||||
String message = (String) responseMap.get("message");
|
||||
if (code != null && code == 0) {
|
||||
// 响应码为0表示成功,从data字段中获取datasetId
|
||||
Object dataObj = responseMap.get("data");
|
||||
if (dataObj instanceof Map) {
|
||||
Map<String, Object> dataMap = (Map<String, Object>) dataObj;
|
||||
datasetId = (String) dataMap.get("id");
|
||||
|
||||
if (StringUtils.isBlank(datasetId)) {
|
||||
// 如果id字段为空,尝试其他可能的字段名
|
||||
datasetId = (String) dataMap.get("dataset_id");
|
||||
datasetId = (String) dataMap.get("datasetId");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 如果响应码不为0,说明API调用失败
|
||||
String errorMessage = "RAGFlow API调用失败,响应码: " + code + ", 消息: "
|
||||
+ (message != null ? message : "未知错误");
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
|
||||
log.info("从RAGFlow API响应中解析出datasetId: {}", datasetId);
|
||||
log.debug("完整响应内容: {}", responseBody);
|
||||
} catch (IOException e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage);
|
||||
} catch (Exception e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
|
||||
String finalErrorMessage = responseBody;
|
||||
if (e.getMessage() != null) {
|
||||
finalErrorMessage += ",解析错误: " + errorMessage;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
|
||||
}
|
||||
// 验证适配器类型是否已注册
|
||||
if (!KnowledgeBaseAdapterFactory.isAdapterTypeRegistered(adapterType)) {
|
||||
throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_SUPPORTED,
|
||||
"不支持的适配器类型: " + adapterType);
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(datasetId)) {
|
||||
log.error("无法从RAGFlow API响应中获取datasetId,响应内容: {}", responseBody);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应中未包含datasetId");
|
||||
}
|
||||
log.info("RAGFlow数据集创建成功,datasetId: {}", datasetId);
|
||||
|
||||
return datasetId;
|
||||
return adapterType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用RAGFlow API更新数据集
|
||||
* 使用适配器创建数据集
|
||||
*/
|
||||
private void updateDatasetInRAGFlow(String datasetId, String name, String description,
|
||||
private String createDatasetInRAG(String name, String description, Map<String, Object> ragConfig) {
|
||||
log.info("开始使用适配器创建数据集, name: {}", name);
|
||||
|
||||
try {
|
||||
// 从RAG配置中提取适配器类型
|
||||
String adapterType = extractAdapterType(ragConfig);
|
||||
|
||||
// 使用适配器工厂获取适配器实例
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
|
||||
|
||||
// 构建数据集创建参数
|
||||
Map<String, Object> createParams = new HashMap<>();
|
||||
String username = SecurityUser.getUser().getUsername();
|
||||
createParams.put("name", username + "_" + name);
|
||||
if (StringUtils.isNotBlank(description)) {
|
||||
createParams.put("description", description);
|
||||
}
|
||||
|
||||
// 调用适配器的创建数据集方法
|
||||
String datasetId = adapter.createDataset(createParams);
|
||||
|
||||
log.info("数据集创建成功,datasetId: {}", datasetId);
|
||||
return datasetId;
|
||||
|
||||
} catch (Exception e) {
|
||||
// 直接传递底层适配器的详细错误信息
|
||||
log.error("创建数据集失败", e);
|
||||
if (e instanceof RenException) {
|
||||
throw (RenException) e;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用适配器更新数据集
|
||||
*/
|
||||
private void updateDatasetInRAG(String datasetId, String name, String description,
|
||||
Map<String, Object> ragConfig) {
|
||||
String baseUrl = (String) ragConfig.get("base_url");
|
||||
String apiKey = (String) ragConfig.get("api_key");
|
||||
log.info("开始使用适配器更新数据集,datasetId: {}, name: {}", datasetId, name);
|
||||
|
||||
log.info("开始调用RAGFlow API更新数据集,datasetId: {}, name: {}", datasetId, name);
|
||||
log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置");
|
||||
|
||||
// 构建请求URL
|
||||
String url = baseUrl + "/api/v1/datasets/" + datasetId;
|
||||
log.debug("请求URL: {}", url);
|
||||
// 构建请求体
|
||||
Map<String, Object> requestBody = new HashMap<>();
|
||||
requestBody.put("dataset_id", datasetId);
|
||||
String username = SecurityUser.getUser().getUsername();
|
||||
requestBody.put("name", username + "_" + name);
|
||||
if (StringUtils.isNotBlank(description)) {
|
||||
requestBody.put("description", description);
|
||||
}
|
||||
log.debug("请求体: {}", requestBody);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("Authorization", "Bearer " + apiKey);
|
||||
|
||||
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
// 发送PUT请求
|
||||
log.info("发送PUT请求到RAGFlow API...");
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
|
||||
} catch (Exception e) {
|
||||
String errorMessage = url + e.getMessage();
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
// 从RAG配置中提取适配器类型
|
||||
String adapterType = extractAdapterType(ragConfig);
|
||||
|
||||
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
|
||||
log.debug("RAGFlow API响应内容: {}", response.getBody());
|
||||
// 使用适配器工厂获取适配器实例
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody();
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
|
||||
// 解析响应体,验证操作是否真正成功
|
||||
String responseBody = response.getBody();
|
||||
if (responseBody != null) {
|
||||
try {
|
||||
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
|
||||
Integer code = (Integer) responseMap.get("code");
|
||||
String message = (String) responseMap.get("message");
|
||||
|
||||
if (code != null && code != 0) {
|
||||
String errorMessage = "RAGFlow API调用失败,响应码: " + code + ", 消息: "
|
||||
+ (message != null ? message : "未知错误");
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage);
|
||||
} catch (Exception e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
|
||||
String finalErrorMessage = responseBody;
|
||||
if (e.getMessage() != null) {
|
||||
finalErrorMessage += ",解析错误: " + errorMessage;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
|
||||
// 构建数据集更新参数
|
||||
Map<String, Object> updateParams = new HashMap<>();
|
||||
String username = SecurityUser.getUser().getUsername();
|
||||
updateParams.put("name", username + "_" + name);
|
||||
if (StringUtils.isNotBlank(description)) {
|
||||
updateParams.put("description", description);
|
||||
}
|
||||
|
||||
// 调用适配器的更新数据集方法
|
||||
adapter.updateDataset(datasetId, updateParams);
|
||||
|
||||
log.info("数据集更新成功,datasetId: {}", datasetId);
|
||||
|
||||
} catch (Exception e) {
|
||||
// 直接传递底层适配器的详细错误信息
|
||||
log.error("更新数据集失败", e);
|
||||
if (e instanceof RenException) {
|
||||
throw (RenException) e;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
log.info("RAGFlow数据集更新成功,datasetId: {}", datasetId);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用RAGFlow API删除数据集
|
||||
* 使用适配器删除数据集
|
||||
*/
|
||||
private void deleteDatasetInRAGFlow(String datasetId, Map<String, Object> ragConfig) {
|
||||
String baseUrl = (String) ragConfig.get("base_url");
|
||||
String apiKey = (String) ragConfig.get("api_key");
|
||||
private void deleteDatasetInRAG(String datasetId, Map<String, Object> ragConfig) {
|
||||
log.info("开始使用适配器删除数据集,datasetId: {}", datasetId);
|
||||
|
||||
log.info("开始调用RAGFlow API删除数据集,datasetId: {}", datasetId);
|
||||
log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置");
|
||||
|
||||
// 构建请求URL
|
||||
String url = baseUrl + "/api/v1/datasets";
|
||||
log.debug("请求URL: {}", url);
|
||||
|
||||
// 构建请求体
|
||||
Map<String, Object> requestBody = new HashMap<>();
|
||||
requestBody.put("ids", List.of(datasetId));
|
||||
log.debug("请求体: {}", requestBody);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("Authorization", "Bearer " + apiKey);
|
||||
|
||||
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
|
||||
|
||||
// 发送DELETE请求
|
||||
log.info("发送DELETE请求到RAGFlow API...");
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class);
|
||||
// 从RAG配置中提取适配器类型
|
||||
String adapterType = extractAdapterType(ragConfig);
|
||||
|
||||
// 使用适配器工厂获取适配器实例
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
|
||||
|
||||
// 调用适配器的删除数据集方法
|
||||
adapter.deleteDataset(datasetId);
|
||||
|
||||
log.info("数据集删除成功,datasetId: {}", datasetId);
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMessage = url + e.getMessage();
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
|
||||
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
|
||||
log.debug("RAGFlow API响应内容: {}", response.getBody());
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody();
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
|
||||
// 解析响应体,验证操作是否真正成功
|
||||
String responseBody = response.getBody();
|
||||
if (responseBody != null) {
|
||||
try {
|
||||
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
|
||||
Integer code = (Integer) responseMap.get("code");
|
||||
String message = (String) responseMap.get("message");
|
||||
|
||||
if (code != null && code != 0) {
|
||||
String errorMessage = "RAGFlow API调用失败,响应码: " + code + ", 消息: "
|
||||
+ (message != null ? message : "未知错误");
|
||||
log.error(errorMessage);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage);
|
||||
} catch (Exception e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
|
||||
String finalErrorMessage = responseBody;
|
||||
if (e.getMessage() != null) {
|
||||
finalErrorMessage += ",解析错误: " + errorMessage;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
|
||||
// 直接传递底层适配器的详细错误信息
|
||||
log.error("删除数据集失败", e);
|
||||
if (e instanceof RenException) {
|
||||
throw (RenException) e;
|
||||
}
|
||||
throw new RenException(ErrorCode.RAG_API_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
log.info("RAGFlow数据集删除成功,datasetId: {}", datasetId);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -725,7 +568,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
*/
|
||||
private Map<String, Object> getValidatedRAGConfig(String ragModelId) {
|
||||
if (StringUtils.isBlank(ragModelId)) {
|
||||
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "ragModelId不能为空");
|
||||
throw new RenException(ErrorCode.RAG_MODEL_ID_NOT_NULL);
|
||||
}
|
||||
|
||||
Map<String, Object> ragConfig = getRAGConfig(ragModelId);
|
||||
|
|
@ -763,9 +606,9 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
}
|
||||
|
||||
/**
|
||||
* 从RAGFlow API获取知识库的文档数量
|
||||
* 从适配器获取知识库的文档数量
|
||||
*/
|
||||
private Integer getDocumentCountFromRAGFlow(String datasetId, String ragModelId) {
|
||||
private Integer getDocumentCountFromRAG(String datasetId, String ragModelId) {
|
||||
if (StringUtils.isBlank(datasetId) || StringUtils.isBlank(ragModelId)) {
|
||||
log.warn("datasetId或ragModelId为空,无法获取文档数量");
|
||||
return 0;
|
||||
|
|
@ -773,79 +616,29 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
|
|||
|
||||
log.info("开始获取知识库 {} 的文档数量", datasetId);
|
||||
|
||||
// 获取RAG配置
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(ragModelId);
|
||||
String baseUrl = (String) ragConfig.get("base_url");
|
||||
String apiKey = (String) ragConfig.get("api_key");
|
||||
|
||||
// 构建请求URL - 调用RAGFlow API获取文档列表,但不返回文档详情,只获取总数
|
||||
String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents?page=1&size=1";
|
||||
log.debug("请求URL: {}", url);
|
||||
|
||||
// 设置请求头
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("Authorization", "Bearer " + apiKey);
|
||||
|
||||
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
|
||||
|
||||
// 发送GET请求
|
||||
log.info("发送GET请求到RAGFlow API获取文档数量...");
|
||||
ResponseEntity<String> response;
|
||||
try {
|
||||
response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
|
||||
// 获取RAG配置
|
||||
Map<String, Object> ragConfig = getValidatedRAGConfig(ragModelId);
|
||||
|
||||
// 从RAG配置中提取适配器类型
|
||||
String adapterType = extractAdapterType(ragConfig);
|
||||
|
||||
// 使用适配器工厂获取适配器实例
|
||||
KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig);
|
||||
|
||||
// 调用适配器的获取文档数量方法
|
||||
Integer documentCount = adapter.getDocumentCount(datasetId);
|
||||
|
||||
log.info("获取知识库 {} 的文档数量成功: {}", datasetId, documentCount);
|
||||
return documentCount;
|
||||
|
||||
} catch (Exception e) {
|
||||
String errorMessage = url + e.getMessage();
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 获取知识库文档数量失败";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
return 0;
|
||||
}
|
||||
|
||||
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
|
||||
return 0;
|
||||
}
|
||||
|
||||
String responseBody = response.getBody();
|
||||
log.debug("RAGFlow API响应内容: {}", responseBody);
|
||||
|
||||
// 解析响应
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
|
||||
Integer code = (Integer) responseMap.get("code");
|
||||
|
||||
if (code != null && code == 0) {
|
||||
Object dataObj = responseMap.get("data");
|
||||
if (dataObj instanceof Map) {
|
||||
Map<String, Object> dataMap = (Map<String, Object>) dataObj;
|
||||
Object totalObj = dataMap.get("total");
|
||||
if (totalObj instanceof Integer) {
|
||||
Integer documentCount = (Integer) totalObj;
|
||||
log.info("获取知识库 {} 的文档数量成功: {}", datasetId, documentCount);
|
||||
return documentCount;
|
||||
} else if (totalObj instanceof Long) {
|
||||
Long documentCount = (Long) totalObj;
|
||||
log.info("获取知识库 {} 的文档数量成功: {}", datasetId, documentCount);
|
||||
return documentCount.intValue();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
} catch (Exception e) {
|
||||
// 构建详细的错误信息,包含异常类型和消息
|
||||
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败";
|
||||
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
|
||||
log.error(errorMessage, e);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -19,4 +19,15 @@ public class VoiceDTO implements Serializable {
|
|||
|
||||
@Schema(description = "音色名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "音频播放地址")
|
||||
private String voiceDemo;
|
||||
|
||||
// 添加双参数构造函数,保持向后兼容
|
||||
public VoiceDTO(String id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.voiceDemo = null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -100,7 +100,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||
converter.setObjectMapper(mapper);
|
||||
return converter;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 国际化配置 - 根据请求头中的Accept-Language设置语言环境
|
||||
*/
|
||||
|
|
@ -113,14 +113,14 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||
if (acceptLanguage == null || acceptLanguage.isEmpty()) {
|
||||
return Locale.getDefault();
|
||||
}
|
||||
|
||||
|
||||
// 解析Accept-Language请求头中的首选语言
|
||||
String[] languages = acceptLanguage.split(",");
|
||||
if (languages.length > 0) {
|
||||
// 提取第一个语言代码,去除可能的质量值(q=...)
|
||||
String[] parts = languages[0].split(";" + "\\s*");
|
||||
String primaryLanguage = parts[0].trim();
|
||||
|
||||
|
||||
// 根据前端发送的语言代码直接创建Locale对象
|
||||
if (primaryLanguage.equals("zh-CN")) {
|
||||
return Locale.SIMPLIFIED_CHINESE;
|
||||
|
|
@ -128,15 +128,25 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||
return Locale.TRADITIONAL_CHINESE;
|
||||
} else if (primaryLanguage.equals("en-US")) {
|
||||
return Locale.US;
|
||||
} else if (primaryLanguage.equals("de-DE")) {
|
||||
return Locale.GERMANY;
|
||||
} else if (primaryLanguage.equals("vi-VN")) {
|
||||
return Locale.forLanguageTag("vi-VN");
|
||||
} else if (primaryLanguage.startsWith("zh")) {
|
||||
// 对于其他中文变体,默认使用简体中文
|
||||
return Locale.SIMPLIFIED_CHINESE;
|
||||
} else if (primaryLanguage.startsWith("en")) {
|
||||
// 对于其他英文变体,默认使用美式英语
|
||||
return Locale.US;
|
||||
} else if (primaryLanguage.startsWith("de")) {
|
||||
// 对于其他德语变体,默认使用德语
|
||||
return Locale.GERMANY;
|
||||
} else if (primaryLanguage.startsWith("vi")) {
|
||||
// 对于其他越南语变体,默认使用越南语
|
||||
return Locale.forLanguageTag("vi-VN");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果没有匹配的语言,使用默认语言
|
||||
return Locale.getDefault();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -133,7 +133,11 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
|||
timbreEntities = new ArrayList<>();
|
||||
}
|
||||
List<VoiceDTO> voiceDTOs = timbreEntities.stream()
|
||||
.map(entity -> new VoiceDTO(entity.getId(), entity.getName()))
|
||||
.map(entity -> {
|
||||
VoiceDTO dto = new VoiceDTO(entity.getId(), entity.getName());
|
||||
dto.setVoiceDemo(entity.getVoiceDemo());
|
||||
return dto;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 获取当前登录用户ID
|
||||
|
|
@ -146,6 +150,8 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
|||
VoiceDTO voiceDTO = new VoiceDTO();
|
||||
voiceDTO.setId(entity.getId());
|
||||
voiceDTO.setName(MessageUtils.getMessage(ErrorCode.VOICE_CLONE_PREFIX) + entity.getName());
|
||||
// 保留从数据库查询到的voiceDemo字段
|
||||
voiceDTO.setVoiceDemo(entity.getVoiceDemo());
|
||||
redisUtils.set(RedisKeys.getTimbreNameById(voiceDTO.getId()), voiceDTO.getName(),
|
||||
RedisUtils.NOT_EXPIRE);
|
||||
voiceDTOs.add(0, voiceDTO);
|
||||
|
|
@ -205,6 +211,9 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
|||
if (list.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new VoiceDTO(list.get(0).getId(), list.get(0).getName());
|
||||
TimbreEntity entity = list.get(0);
|
||||
VoiceDTO dto = new VoiceDTO(entity.getId(), entity.getName());
|
||||
dto.setVoiceDemo(entity.getVoiceDemo());
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
|
@ -107,10 +107,10 @@ public class VoiceCloneController {
|
|||
String name = params.get("name");
|
||||
|
||||
if (id == null || id.isEmpty()) {
|
||||
return new Result<String>().error(ErrorCode.IDENTIFIER_NOT_NULL, "唯一标识不能为空");
|
||||
return new Result<String>().error(ErrorCode.IDENTIFIER_NOT_NULL);
|
||||
}
|
||||
if (name == null) {
|
||||
return new Result<String>().error(ErrorCode.NOT_NULL, "名称不能为空");
|
||||
if (name == null || name.isEmpty()) {
|
||||
return new Result<String>().error(ErrorCode.VOICE_CLONE_NAME_NOT_NULL);
|
||||
}
|
||||
// 检查权限
|
||||
checkPermission(id);
|
||||
|
|
@ -119,7 +119,7 @@ public class VoiceCloneController {
|
|||
redisUtils.delete(RedisKeys.getTimbreNameById(id));
|
||||
return new Result<String>();
|
||||
} catch (Exception e) {
|
||||
return new Result<String>().error(ErrorCode.UPDATE_DATA_FAILED, "更新失败: " + e.getMessage());
|
||||
return new Result<String>().error(ErrorCode.UPDATE_DATA_FAILED, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -131,7 +131,7 @@ public class VoiceCloneController {
|
|||
checkPermission(id);
|
||||
byte[] audioData = voiceCloneService.getVoiceData(id);
|
||||
if (audioData == null) {
|
||||
return new Result<String>().error(ErrorCode.RESOURCE_NOT_FOUND, "音频不存在");
|
||||
return new Result<String>().error(ErrorCode.VOICE_CLONE_AUDIO_NOT_FOUND);
|
||||
}
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
redisUtils.set(RedisKeys.getVoiceCloneAudioIdKey(uuid), id);
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl<VoiceCloneDao, VoiceC
|
|||
wrapper.eq("model_id", dto.getModelId());
|
||||
Long count = baseDao.selectCount(wrapper);
|
||||
if (count > 0) {
|
||||
throw new RenException(ErrorCode.VOICE_ID_ALREADY_EXISTS, "音色ID " + voiceId + " 已存在");
|
||||
throw new RenException(ErrorCode.VOICE_ID_ALREADY_EXISTS);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -164,6 +164,9 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl<VoiceCloneDao, VoiceC
|
|||
if (entity.getUserId() != null) {
|
||||
dto.setUserName(sysUserService.getByUserId(entity.getUserId()).getUsername());
|
||||
}
|
||||
|
||||
// 确保trainStatus字段被正确设置,前端需要这个字段来判断是否为克隆音频
|
||||
dto.setTrainStatus(entity.getTrainStatus());
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
|
@ -197,6 +200,9 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl<VoiceCloneDao, VoiceC
|
|||
if (entity.getUserId() != null) {
|
||||
dto.setUserName(sysUserService.getByUserId(entity.getUserId()).getUsername());
|
||||
}
|
||||
|
||||
// 确保trainStatus字段被正确设置,前端需要这个字段来判断是否为克隆音频
|
||||
dto.setTrainStatus(entity.getTrainStatus());
|
||||
|
||||
// 设置是否有音频数据
|
||||
dto.setHasVoice(entity.getVoice() != null);
|
||||
|
|
|
|||
|
|
@ -160,11 +160,11 @@
|
|||
10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6
|
||||
10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230
|
||||
10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230
|
||||
10154=\u8BAD\u7EC3\u5931\u8D25
|
||||
10154=\u8BAD\u7EC3\u5931\u8D25: {0}
|
||||
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E
|
||||
10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
|
||||
10157=\u8BF7\u6C42\u5931\u8D25
|
||||
10158=\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801{0}
|
||||
10158=\u514B\u9686\u97F3\u8272:
|
||||
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
|
||||
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934
|
||||
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
|
||||
|
|
@ -173,7 +173,29 @@
|
|||
10164=RAG\u914D\u7F6E\u672A\u627E\u5230
|
||||
10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF
|
||||
10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230
|
||||
10167=\u0052\u0041\u0047\u8c03\u7528\u5931\u8d25\uFF0C{0}
|
||||
10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0}
|
||||
10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25
|
||||
10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55
|
||||
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
|
||||
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
|
||||
10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
|
||||
10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
|
||||
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728
|
||||
10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230
|
||||
10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u7C7B\u578B
|
||||
10185=RAG\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25
|
||||
10186=\u9002\u914D\u5668\u521B\u5EFA\u5931\u8D25
|
||||
10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25
|
||||
10188=\u9002\u914D\u5668\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25
|
||||
10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u8D25
|
||||
10190=\u9002\u914D\u5668\u672A\u627E\u5230
|
||||
10191=\u9002\u914D\u5668\u7F13\u5B58\u9519\u8BEF
|
||||
10192=\u9002\u914D\u5668\u7C7B\u578B\u672A\u627E\u5230
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
#Deutsch
|
||||
500=Server interne Ausnahme
|
||||
401=Nicht autorisiert
|
||||
403=Zugriff verweigert, keine Berechtigungen
|
||||
10001={0} darf nicht leer sein
|
||||
10002=Der Datensatz existiert bereits in der Datenbank
|
||||
10003=Parameter abrufen fehlgeschlagen
|
||||
10004=Die Kontonummer oder das Passwort ist falsch
|
||||
10005=Konto wurde deaktiviert
|
||||
10006=Eindeutige ID darf nicht leer sein
|
||||
10007=Der Bestätigungscode ist falsch
|
||||
10008=Zuerst Untermenü oder Schaltfläche löschen
|
||||
10009=Das ursprüngliche Passwort ist falsch
|
||||
10010=Das Konto oder Passwort ist falsch, Sie können es noch {0} Mal versuchen
|
||||
|
||||
10011=Die übergeordnete Abteilung hat eine falsche Wahl getroffen
|
||||
10012=Oberes Menü kann nicht sich selbst sein
|
||||
10013=Datenberechtigungsschnittstelle, die nur ein Map-Typ-Parameter sein kann
|
||||
10014=Bitte löschen Sie zuerst die untergeordnete Abteilung
|
||||
10015=Bitte löschen Sie zuerst den Benutzer unter der Abteilung
|
||||
10016=Bereitstellung fehlgeschlagen, kein Prozess
|
||||
10017=Das ModellDiagramm ist falsch, bitte überprüfen
|
||||
10018=Export fehlgeschlagen, Modell-ID ist {0}
|
||||
|
||||
10019=Bitte laden Sie eine Datei hoch
|
||||
10020=Token darf nicht leer sein
|
||||
10021=Token ist ungültig, bitte melden Sie sich erneut an
|
||||
10022=Das Konto wurde gesperrt
|
||||
10023=Bitte laden Sie Dateien im Format zip, bar, bpmn, bpmn20.xml hoch
|
||||
|
||||
10024=Datei-Upload fehlgeschlagen {0}
|
||||
10025=SMS-Sendung fehlgeschlagen {0}
|
||||
10026=E-Mail-Vorlage existiert nicht
|
||||
|
||||
10027=Redis-Dienstausnahme
|
||||
10028=Zeitgesteuerte Aufgabe fehlgeschlagen
|
||||
10029=Darf keine illegalen Zeichen enthalten
|
||||
|
||||
10030=Das Passwort hat weniger als {0} Ziffern
|
||||
10031=Das Passwort muss gleichzeitig aus Zahlen, Groß- und Kleinbuchstaben sowie Sonderzeichen bestehen
|
||||
10032=Ausnahme beim Löschen dieser Daten
|
||||
10033=Gerätebestätigungscode Fehler
|
||||
|
||||
10034=Parameterwert darf nicht leer sein
|
||||
10035=Parametertyp darf nicht leer sein
|
||||
10036=Nicht unterstützter Parametertyp
|
||||
10037=Parameterwert muss eine gültige Zahl sein
|
||||
10038=Parameterwert muss true oder false sein
|
||||
10039=Parameterwert muss ein gültiges JSON-Array-Format sein
|
||||
10040=Parameterwert muss ein gültiges JSON-Format sein
|
||||
|
||||
10041=Gerät nicht gefunden
|
||||
10042={0}
|
||||
10043=Löschen der Daten fehlgeschlagen
|
||||
10044=Benutzer nicht angemeldet
|
||||
10045=WebSocket-Verbindung fehlgeschlagen oder Zeitüberschreitung
|
||||
10046=Stimmabdruck speichern fehlgeschlagen, bitte Administrator kontaktieren
|
||||
10047=Tägliches SendeLimit erreicht
|
||||
10048=Altes Passwort ist falsch
|
||||
10049=Das eingestellte LLM ist nicht openai oder ollama
|
||||
10050=Token-Generierung fehlgeschlagen
|
||||
10051=Ressource nicht gefunden
|
||||
10052=Standard-Agent nicht gefunden
|
||||
10053=Agent nicht gefunden
|
||||
10054=Stimmabdruck-Schnittstelle nicht konfiguriert, bitte konfigurieren Sie zuerst die Stimmabdruck-Schnittstellenadresse (server.voice_print) in der Parameterkonfiguration
|
||||
10055=SMS-Sendung fehlgeschlagen
|
||||
10056=SMS-Verbindung konnte nicht hergestellt werden
|
||||
10057=Stimmabdruck für Agent konnte nicht erstellt werden
|
||||
10058=Stimmabdruck für Agent konnte nicht aktualisiert werden
|
||||
10059=Stimmabdruck für Agent konnte nicht gelöscht werden
|
||||
10060=Sendung zu häufig, bitte versuchen Sie es nach {0} Sekunden erneut
|
||||
10061=Aktivierungscode darf nicht leer sein
|
||||
10062=Aktivierungscode Fehler
|
||||
10063=Gerät bereits aktiviert
|
||||
10064=Dieses Modell ist das Standardmodell, bitte setzen Sie zuerst ein anderes Modell als Standard
|
||||
10065=Hinzufügen der Daten fehlgeschlagen
|
||||
10066=Aktualisieren der Daten fehlgeschlagen
|
||||
10067=Grafischer Bestätigungscode Fehler
|
||||
10068=Mobilregistrierung nicht aktiviert, SMS-Bestätigungscode-Funktion kann nicht verwendet werden
|
||||
10069=Benutzername ist keine Handynummer, bitte erneut eingeben
|
||||
10070=Diese Handynummer wurde bereits registriert
|
||||
10071=Die eingegebene Handynummer ist nicht registriert
|
||||
10072=Normale Benutzerregistrierung derzeit nicht erlaubt
|
||||
10073=Mobilregistrierung nicht aktiviert, Passwort-Wiederherstellungsfunktion kann nicht verwendet werden
|
||||
10074=Das Format der eingegebenen Handynummer ist falsch
|
||||
10075=Der eingegebene SMS-Bestätigungscode ist falsch
|
||||
10076=Wörterbuchtyp existiert nicht
|
||||
10077=Wörterbuchtypcode ist dupliziert
|
||||
10078=Lesen der Ressource fehlgeschlagen
|
||||
10079=LLM-Modell und Absichtserkennung, Parameterauswahl stimmt nicht überein
|
||||
10080=Dieser Stimmabdruck gehört zu {0}, der bereits registriert ist, bitte wählen Sie eine andere Stimme
|
||||
10081=Fehler beim Löschen des Stimmabdrucks aufgetreten
|
||||
10082=Änderung nicht erlaubt, diese Stimme wurde bereits als Stimmabdruck registriert ({0})
|
||||
10083=Fehler beim Ändern des Stimmabdrucks, bitte Administrator kontaktieren
|
||||
10084=Stimmabdruck-Schnittstellenadresse Fehler, bitte gehen Sie zur Parameterverwaltung, um die Stimmabdruck-Schnittstellenadresse zu ändern
|
||||
10085=Audiodaten gehören nicht zu diesem Agent
|
||||
10086=Audiodaten sind leer, bitte überprüfen Sie hochgeladene Daten
|
||||
10087=Stimmabdruck-Registrierung fehlgeschlagen, Anfrage nicht erfolgreich
|
||||
10088=Stimmabdruck-Registrierung fehlgeschlagen, Anfrageverarbeitung fehlgeschlagen
|
||||
10089=Stimmabdruck-Stornierung fehlgeschlagen, Anfrage nicht erfolgreich
|
||||
10090=Stimmabdruck-Stornierung fehlgeschlagen, Anfrageverarbeitung fehlgeschlagen
|
||||
10091=Modellanbieter existiert nicht
|
||||
10092=Das konfigurierte LLM existiert nicht
|
||||
10093=Diese Modellkonfiguration wird von Agent {0} referenziert und kann nicht gelöscht werden
|
||||
10094=Dieses LLM-Modell wird von der Absichtserkennungskonfiguration referenziert und kann nicht gelöscht werden
|
||||
10095=Ungültige Serveroperation
|
||||
10096=Server WebSocket-Adresse nicht konfiguriert
|
||||
10097=Ziel-WebSocket-Adresse existiert nicht
|
||||
10098=WebSocket-Adressliste darf nicht leer sein
|
||||
10099=WebSocket-Adresse darf nicht localhost oder 127.0.0.1 verwenden
|
||||
10100=WebSocket-Adressformat ist falsch
|
||||
10101=WebSocket-Verbindungstest fehlgeschlagen
|
||||
10102=OTA-Adresse darf nicht leer sein
|
||||
10103=OTA-Adresse darf nicht localhost oder 127.0.0.1 verwenden
|
||||
10104=OTA-Adresse muss mit http oder https beginnen
|
||||
10105=OTA-Adresse muss mit /ota/ enden
|
||||
10106=OTA-Schnittstellenzugriff fehlgeschlagen
|
||||
10107=OTA-Schnittstelle Rückgabeinhaltformat ist falsch
|
||||
10108=OTA-Schnittstellenvalidierung fehlgeschlagen
|
||||
10109=MCP-Adresse darf nicht leer sein
|
||||
10110=MCP-Adresse darf nicht localhost oder 127.0.0.1 verwenden
|
||||
10111=Keine gültige MCP-Adresse
|
||||
10112=MCP-Schnittstellenzugriff fehlgeschlagen
|
||||
10113=MCP-Schnittstelle Rückgabeinhaltformat ist falsch
|
||||
10114=MCP-Schnittstellenvalidierung fehlgeschlagen
|
||||
10115=Stimmabdruck-Schnittstellenadresse darf nicht leer sein
|
||||
10116=Stimmabdruck-Schnittstellenadresse darf nicht localhost oder 127.0.0.1 verwenden
|
||||
10117=Keine gültige Stimmabdruck-Schnittstellenadresse
|
||||
10118=Stimmabdruck-Schnittstellenadresse muss mit http oder https beginnen
|
||||
10119=Stimmabdruck-Schnittstellenzugriff fehlgeschlagen
|
||||
10120=Stimmabdruck-Schnittstelle Rückgabeinhaltformat ist falsch
|
||||
10121=Stimmabdruck-Schnittstellenvalidierung fehlgeschlagen
|
||||
10122=MQTT-Geheimnis darf nicht leer sein
|
||||
10123=Ihr MQTT-Geheimnis ist nicht sicher, es muss mindestens 8 Zeichen lang sein und muss sowohl Groß- als auch Kleinbuchstaben enthalten
|
||||
10124=Ihr MQTT-Geheimnis ist nicht sicher, MQTT-Geheimnis muss sowohl Groß- als auch Kleinbuchstaben enthalten
|
||||
10125=Ihr MQTT-Geheimnis enthält schwaches Passwort
|
||||
10128=Wörterbuchlabel ist dupliziert
|
||||
10129=SM2-Schlüssel nicht konfiguriert
|
||||
10130=SM2-Entschlüsselung fehlgeschlagen
|
||||
10131=modelType und provideCode dürfen nicht leer sein
|
||||
10132=Keine Berechtigung, den Chat-Verlauf dieses Agents anzuzeigen
|
||||
10133=Sitzungs-ID darf nicht leer sein
|
||||
10134=Agent-ID darf nicht leer sein
|
||||
10135=Chat-Verlauf-Download fehlgeschlagen
|
||||
10136=Download-Link abgelaufen oder ungültig
|
||||
10137=Download-Link ungültig
|
||||
10138=Benutzer
|
||||
10139=Agent
|
||||
10140=Audio-Datei darf nicht leer sein
|
||||
10141=Nur Audio-Dateien werden unterstützt
|
||||
10142=Audio-Dateigröße darf 10MB nicht überschreiten
|
||||
10143=Upload fehlgeschlagen
|
||||
10144=Stimmenklon-Datensatz existiert nicht
|
||||
10145=Stimmressourceninformationen dürfen nicht leer sein
|
||||
10146=TTS-Plattformname darf nicht leer sein
|
||||
10147=Stimmen-ID darf nicht leer sein
|
||||
10148=Kontoinhaber darf nicht leer sein
|
||||
10149=Zu löschende Stimmressourcen-ID darf nicht leer sein
|
||||
10150=Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten
|
||||
10151=Bitte laden Sie zuerst eine Audio-Datei hoch
|
||||
10152=Modellkonfiguration nicht gefunden
|
||||
10153=Modelltyp nicht gefunden
|
||||
10154=Training fehlgeschlagen: {0}
|
||||
10155=Huoshan Engine-Konfiguration fehlt
|
||||
10156=Antwortformat Fehler, BaseResp-Feld fehlt
|
||||
10157=Anfrage fehlgeschlagen
|
||||
10158=Stimme klonen:
|
||||
10159=Stimmen-ID existiert bereits
|
||||
10160=Huoshan Engine-Stimmen-ID-Formatfehler, muss mit S_ beginnen
|
||||
10161=Mac-Adresse existiert bereits
|
||||
10162=Modellanbieter existiert nicht
|
||||
10163=Wissensbasis-Datensatz existiert nicht
|
||||
10164=RAG-Konfiguration nicht gefunden
|
||||
10165=RAG-Konfigurationstyp Fehler
|
||||
10166=Standard-RAG-Konfiguration nicht gefunden
|
||||
10167=RAG-API-Aufruf fehlgeschlagen: {0}
|
||||
10168=Datei-Upload fehlgeschlagen
|
||||
10169=Keine Berechtigung, diese Wissensbasis zu bearbeiten
|
||||
10170=Wissensbasis-Name existiert bereits
|
||||
10171=RAG-Konfiguration base_url darf nicht leer sein
|
||||
10172=RAG-Konfiguration api_key darf nicht leer sein
|
||||
10173=RAG-Konfiguration api_key darf keinen Platzhalter enthalten, bitte ersetzen Sie mit tatsächlichem API-Schlüssel
|
||||
10174=RAG-Konfiguration base_url-Formatfehler, muss mit http oder https beginnen
|
||||
10175=Mac-Adresse darf nicht leer sein
|
||||
10176=RAG-Konfiguration dataset_id darf nicht leer sein
|
||||
10177=RAG-Konfiguration model_id darf nicht leer sein
|
||||
10178=RAG-Konfiguration dataset_id und model_id dürfen nicht leer sein
|
||||
10179=Dateiname darf nicht leer sein
|
||||
10180=Dateiinhalt darf nicht leer sein
|
||||
10181=Stimmenklon-Name darf nicht leer sein
|
||||
10182=Stimmenklon-Audio nicht gefunden
|
||||
10183=Standard-Agent-Vorlage nicht gefunden
|
||||
10184=Nicht unterstützter Adaptertyp
|
||||
10185=RAG-Konfigurationsvalidierung fehlgeschlagen
|
||||
10186=Adapter-Erstellung fehlgeschlagen
|
||||
10187=Adapter-Initialisierung fehlgeschlagen
|
||||
10188=Adapter-Verbindungstest fehlgeschlagen
|
||||
10189=Adapter-Operation fehlgeschlagen
|
||||
10190=Adapter nicht gefunden
|
||||
10191=Adapter-Cache-Fehler
|
||||
10192=Adaptertyp nicht gefunden
|
||||
|
|
@ -181,3 +181,21 @@
|
|||
10172=RAG configuration api_key cannot be empty
|
||||
10173=RAG configuration api_key cannot contain placeholder, please replace with actual API key
|
||||
10174=RAG configuration base_url format error, must start with http or https
|
||||
10175=Mac address cannot be empty
|
||||
10176=RAG configuration dataset_id cannot be empty
|
||||
10177=RAG configuration model_id cannot be empty
|
||||
10178=RAG configuration dataset_id and model_id cannot be empty
|
||||
10179=File name cannot be empty
|
||||
10180=File content cannot be empty
|
||||
10181=Voice clone name cannot be empty
|
||||
10182=Voice clone audio not found
|
||||
10183=Default agent template not found
|
||||
10184=Unsupported adapter type
|
||||
10185=RAG configuration validation failed
|
||||
10186=Adapter creation failed
|
||||
10187=Adapter initialization failed
|
||||
10188=Adapter connection test failed
|
||||
10189=Adapter operation failed
|
||||
10190=Adapter not found
|
||||
10191=Adapter cache error
|
||||
10192=Adapter type not found
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
#Tiếng Việt
|
||||
500=Ngoại lệ nội bộ máy chủ
|
||||
401=Không được ủy quyền
|
||||
403=Truy cập bị từ chối, không có quyền
|
||||
10001={0} không thể để trống
|
||||
10002=Bản ghi đã tồn tại trong cơ sở dữ liệu
|
||||
10003=Không thể lấy tham số
|
||||
10004=Số tài khoản hoặc mật khẩu không chính xác
|
||||
10005=Tài khoản đã bị vô hiệu hóa
|
||||
10006=ID duy nhất không thể để trống
|
||||
10007=Mã xác minh không chính xác
|
||||
10008=Trước tiên hãy xóa menu con hoặc nút
|
||||
10009=Mật khẩu gốc không chính xác
|
||||
10010=Tài khoản hoặc mật khẩu không chính xác, bạn có thể thử thêm {0} lần nữa
|
||||
|
||||
10011=Phòng ban cấp trên đã lựa chọn sai
|
||||
10012=Menu trên không thể là chính nó
|
||||
10013=Giao diện quyền dữ liệu, chỉ có thể là tham số kiểu Map
|
||||
10014=Vui lòng xóa phòng ban cấp dưới trước
|
||||
10015=Vui lòng xóa người dùng thuộc phòng ban trước
|
||||
10016=Triển khai thất bại, không có quy trình
|
||||
10017=Biểu đồ mô hình không chính xác, vui lòng kiểm tra
|
||||
10018=Xuất thất bại, ID mô hình là {0}
|
||||
|
||||
10019=Vui lòng tải lên tệp
|
||||
10020=Token không thể để trống
|
||||
10021=Token không hợp lệ, vui lòng đăng nhập lại
|
||||
10022=Tài khoản đã bị khóa
|
||||
10023=Vui lòng tải lên tệp ở định dạng zip, bar, bpmn, bpmn20.xml
|
||||
|
||||
10024=Tải lên tệp {0} thất bại
|
||||
10025=Gửi SMS {0} thất bại
|
||||
10026=Mẫu email không tồn tại
|
||||
|
||||
10027=Ngoại lệ dịch vụ Redis
|
||||
10028=Tác vụ hẹn giờ thất bại
|
||||
10029=Không thể chứa ký tự không hợp lệ
|
||||
|
||||
10030=Mật khẩu ít hơn {0} chữ số
|
||||
10031=Mật khẩu phải bao gồm số, chữ hoa, chữ thường và ký tự đặc biệt cùng một lúc
|
||||
10032=Ngoại lệ khi xóa dữ liệu này
|
||||
10033=Lỗi mã xác minh thiết bị
|
||||
|
||||
10034=Giá trị tham số không thể để trống
|
||||
10035=Loại tham số không thể để trống
|
||||
10036=Loại tham số không được hỗ trợ
|
||||
10037=Giá trị tham số phải là số hợp lệ
|
||||
10038=Giá trị tham số phải là true hoặc false
|
||||
10039=Giá trị tham số phải là định dạng mảng JSON hợp lệ
|
||||
10040=Giá trị tham số phải là định dạng JSON hợp lệ
|
||||
|
||||
10041=Không tìm thấy thiết bị
|
||||
10042={0}
|
||||
10043=Xóa dữ liệu thất bại
|
||||
10044=Người dùng chưa đăng nhập
|
||||
10045=Kết nối WebSocket thất bại hoặc hết thời gian chờ
|
||||
10046=Không thể lưu dấu giọng nói, vui lòng liên hệ quản trị viên
|
||||
10047=Đạt đến giới hạn gửi hàng ngày
|
||||
10048=Mật khẩu cũ không chính xác
|
||||
10049=LLM được đặt không phải là openai hoặc ollama
|
||||
10050=Không thể tạo token
|
||||
10051=Không tìm thấy tài nguyên
|
||||
10052=Không tìm thấy agent mặc định
|
||||
10053=Không tìm thấy agent
|
||||
10054=Giao diện dấu giọng nói chưa được cấu hình, vui lòng cấu hình địa chỉ giao diện dấu giọng nói (server.voice_print) trong cấu hình tham số trước
|
||||
10055=Gửi SMS thất bại
|
||||
10056=Không thể thiết lập kết nối SMS
|
||||
10057=Không thể tạo dấu giọng nói cho agent
|
||||
10058=Không thể cập nhật dấu giọng nói cho agent
|
||||
10059=Không thể xóa dấu giọng nói cho agent
|
||||
10060=Gửi quá thường xuyên, vui lòng thử lại sau {0} giây
|
||||
10061=Mã kích hoạt không thể để trống
|
||||
10062=Lỗi mã kích hoạt
|
||||
10063=Thiết bị đã được kích hoạt
|
||||
10064=Mô hình này là mô hình mặc định, vui lòng đặt mô hình khác làm mặc định trước
|
||||
10065=Thêm dữ liệu thất bại
|
||||
10066=Cập nhật dữ liệu thất bại
|
||||
10067=Lỗi mã xác minh đồ họa
|
||||
10068=Đăng ký di động không được bật, không thể sử dụng chức năng mã xác minh SMS
|
||||
10069=Tên người dùng không phải là số điện thoại di động, vui lòng nhập lại
|
||||
10070=Số điện thoại di động này đã được đăng ký
|
||||
10071=Số điện thoại di động đã nhập không được đăng ký
|
||||
10072=Hiện không cho phép đăng ký người dùng thông thường
|
||||
10073=Đăng ký di động không được bật, không thể sử dụng chức năng truy xuất mật khẩu
|
||||
10074=Định dạng số điện thoại di động đã nhập không chính xác
|
||||
10075=Mã xác minh SMS đã nhập không chính xác
|
||||
10076=Loại từ điển không tồn tại
|
||||
10077=Mã loại từ điển bị trùng lặp
|
||||
10078=Đọc tài nguyên thất bại
|
||||
10079=Mô hình LLM và nhận dạng ý định, lựa chọn tham số không khớp
|
||||
10080=Dấu giọng nói này thuộc về {0} đã đăng ký, vui lòng chọn giọng nói khác
|
||||
10081=Đã xảy ra lỗi khi xóa dấu giọng nói
|
||||
10082=Không cho phép sửa đổi, giọng nói này đã được đăng ký làm dấu giọng nói ({0})
|
||||
10083=Lỗi sửa đổi dấu giọng nói, vui lòng liên hệ quản trị viên
|
||||
10084=Lỗi địa chỉ giao diện dấu giọng nói, vui lòng vào quản lý tham số để sửa đổi địa chỉ giao diện dấu giọng nói
|
||||
10085=Dữ liệu âm thanh không thuộc về agent này
|
||||
10086=Dữ liệu âm thanh trống, vui lòng kiểm tra dữ liệu đã tải lên
|
||||
10087=Đăng ký dấu giọng nói thất bại, yêu cầu không thành công
|
||||
10088=Đăng ký dấu giọng nói thất bại, xử lý yêu cầu thất bại
|
||||
10089=Hủy dấu giọng nói thất bại, yêu cầu không thành công
|
||||
10090=Hủy dấu giọng nói thất bại, xử lý yêu cầu thất bại
|
||||
10091=Nhà cung cấp mô hình không tồn tại
|
||||
10092=LLM được cấu hình không tồn tại
|
||||
10093=Cấu hình mô hình này được tham chiếu bởi agent {0} và không thể xóa
|
||||
10094=Mô hình LLM này được tham chiếu bởi cấu hình nhận dạng ý định và không thể xóa
|
||||
10095=Thao tác máy chủ không hợp lệ
|
||||
10096=Địa chỉ WebSocket máy chủ chưa được cấu hình
|
||||
10097=Địa chỉ WebSocket mục tiêu không tồn tại
|
||||
10098=Danh sách địa chỉ WebSocket không thể để trống
|
||||
10099=Địa chỉ WebSocket không thể sử dụng localhost hoặc 127.0.0.1
|
||||
10100=Định dạng địa chỉ WebSocket không chính xác
|
||||
10101=Kiểm tra kết nối WebSocket thất bại
|
||||
10102=Địa chỉ OTA không thể để trống
|
||||
10103=Địa chỉ OTA không thể sử dụng localhost hoặc 127.0.0.1
|
||||
10104=Địa chỉ OTA phải bắt đầu bằng http hoặc https
|
||||
10105=Địa chỉ OTA phải kết thúc bằng /ota/
|
||||
10106=Truy cập giao diện OTA thất bại
|
||||
10107=Định dạng nội dung trả về giao diện OTA không chính xác
|
||||
10108=Xác thực giao diện OTA thất bại
|
||||
10109=Địa chỉ MCP không thể để trống
|
||||
10110=Địa chỉ MCP không thể sử dụng localhost hoặc 127.0.0.1
|
||||
10111=Không phải địa chỉ MCP hợp lệ
|
||||
10112=Truy cập giao diện MCP thất bại
|
||||
10113=Định dạng nội dung trả về giao diện MCP không chính xác
|
||||
10114=Xác thực giao diện MCP thất bại
|
||||
10115=Địa chỉ giao diện dấu giọng nói không thể để trống
|
||||
10116=Địa chỉ giao diện dấu giọng nói không thể sử dụng localhost hoặc 127.0.0.1
|
||||
10117=Không phải địa chỉ giao diện dấu giọng nói hợp lệ
|
||||
10118=Địa chỉ giao diện dấu giọng nói phải bắt đầu bằng http hoặc https
|
||||
10119=Truy cập giao diện dấu giọng nói thất bại
|
||||
10120=Định dạng nội dung trả về giao diện dấu giọng nói không chính xác
|
||||
10121=Xác thực giao diện dấu giọng nói thất bại
|
||||
10122=Bí mật MQTT không thể để trống
|
||||
10123=Bí mật MQTT của bạn không an toàn, cần ít nhất 8 ký tự và phải chứa cả chữ hoa và chữ thường
|
||||
10124=Bí mật MQTT của bạn không an toàn, bí mật MQTT phải chứa cả chữ hoa và chữ thường
|
||||
10125=Bí mật MQTT của bạn chứa mật khẩu yếu
|
||||
10128=Nhãn từ điển bị trùng lặp
|
||||
10129=Khóa SM2 chưa được cấu hình
|
||||
10130=Giải mã SM2 thất bại
|
||||
10131=modelType và provideCode không thể để trống
|
||||
10132=Không có quyền xem lịch sử trò chuyện của agent này
|
||||
10133=ID phiên không thể để trống
|
||||
10134=ID agent không thể để trống
|
||||
10135=Tải xuống lịch sử trò chuyện thất bại
|
||||
10136=Liên kết tải xuống đã hết hạn hoặc không hợp lệ
|
||||
10137=Liên kết tải xuống không hợp lệ
|
||||
10138=Người dùng
|
||||
10139=Agent
|
||||
10140=Tệp âm thanh không thể để trống
|
||||
10141=Chỉ hỗ trợ tệp âm thanh
|
||||
10142=Kích thước tệp âm thanh không thể vượt quá 10MB
|
||||
10143=Tải lên thất bại
|
||||
10144=Bản ghi nhân bản giọng nói không tồn tại
|
||||
10145=Thông tin tài nguyên giọng nói không thể để trống
|
||||
10146=Tên nền tảng TTS không thể để trống
|
||||
10147=ID giọng nói không thể để trống
|
||||
10148=Tài khoản chủ sở hữu không thể để trống
|
||||
10149=ID tài nguyên giọng nói cần xóa không thể để trống
|
||||
10150=Bạn không có quyền thao tác bản ghi này
|
||||
10151=Vui lòng tải lên tệp âm thanh trước
|
||||
10152=Không tìm thấy cấu hình mô hình
|
||||
10153=Không tìm thấy loại mô hình
|
||||
10154=Đào tạo thất bại: {0}
|
||||
10155=Thiếu cấu hình Huoshan Engine
|
||||
10156=Lỗi định dạng phản hồi, thiếu trường BaseResp
|
||||
10157=Yêu cầu thất bại
|
||||
10158=Nhân bản âm sắc:
|
||||
10159=ID giọng nói đã tồn tại
|
||||
10160=Lỗi định dạng ID giọng nói Huoshan Engine, phải bắt đầu bằng S_
|
||||
10161=Địa chỉ Mac đã tồn tại
|
||||
10162=Nhà cung cấp mô hình không tồn tại
|
||||
10163=Bản ghi cơ sở kiến thức không tồn tại
|
||||
10164=Không tìm thấy cấu hình RAG
|
||||
10165=Lỗi loại cấu hình RAG
|
||||
10166=Không tìm thấy cấu hình RAG mặc định
|
||||
10167=Gọi API RAG thất bại: {0}
|
||||
10168=Tải lên tệp thất bại
|
||||
10169=Không có quyền thao tác cơ sở kiến thức này
|
||||
10170=Tên cơ sở kiến thức đã tồn tại
|
||||
10171=Cấu hình RAG base_url không thể để trống
|
||||
10172=Cấu hình RAG api_key không thể để trống
|
||||
10173=Cấu hình RAG api_key không thể chứa trình giữ chỗ, vui lòng thay thế bằng khóa API thực tế
|
||||
10174=Lỗi định dạng cấu hình RAG base_url, phải bắt đầu bằng http hoặc https
|
||||
10175=Địa chỉ Mac không thể để trống
|
||||
10176=Cấu hình RAG dataset_id không thể để trống
|
||||
10177=Cấu hình RAG model_id không thể để trống
|
||||
10178=Cấu hình RAG dataset_id và model_id không thể để trống
|
||||
10179=Tên tệp không thể để trống
|
||||
10180=Nội dung tệp không thể để trống
|
||||
10181=Tên nhân bản giọng nói không thể để trống
|
||||
10182=Không tìm thấy âm thanh nhân bản giọng nói
|
||||
10183=Không tìm thấy mẫu agent mặc định
|
||||
10184=Loại bộ chuyển đổi không được hỗ trợ
|
||||
10185=Kiểm tra cấu hình RAG thất bại
|
||||
10186=Tạo bộ chuyển đổi thất bại
|
||||
10187=Khởi tạo bộ chuyển đổi thất bại
|
||||
10188=Kiểm tra kết nối bộ chuyển đổi thất bại
|
||||
10189=Thao tác bộ chuyển đổi thất bại
|
||||
10190=Không tìm thấy bộ chuyển đổi
|
||||
10191=Lỗi bộ nhớ đệm bộ chuyển đổi
|
||||
10192=Không tìm thấy loại bộ chuyển đổi
|
||||
|
|
@ -160,11 +160,11 @@
|
|||
10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6
|
||||
10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230
|
||||
10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230
|
||||
10154=\u8BAD\u7EC3\u5931\u8D25
|
||||
10154=\u8BAD\u7EC3\u5931\u8D25: {0}
|
||||
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E
|
||||
10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
|
||||
10157=\u8BF7\u6C42\u5931\u8D25
|
||||
10158=\u514B\u9686\u8272\u97F3:
|
||||
10158=\u514B\u9686\u97F3\u8272:
|
||||
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
|
||||
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934
|
||||
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
|
||||
|
|
@ -173,11 +173,29 @@
|
|||
10164=RAG\u914D\u7F6E\u672A\u627E\u5230
|
||||
10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF
|
||||
10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230
|
||||
10167=\u0052\u0041\u0047\u8c03\u7528\u5931\u8d25\uFF0C{0}
|
||||
10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0}
|
||||
10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25
|
||||
10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55
|
||||
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
|
||||
10171=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10172=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10173=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
|
||||
10174=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
|
||||
10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
|
||||
10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
|
||||
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728
|
||||
10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230
|
||||
10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u7C7B\u578B
|
||||
10185=RAG\u914D\u7F6E\u9A8C\u8BC1\u5931\u8D25
|
||||
10186=\u9002\u914D\u5668\u521B\u5EFA\u5931\u8D25
|
||||
10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u8D25
|
||||
10188=\u9002\u914D\u5668\u8FDE\u63A5\u6D4B\u8BD5\u5931\u8D25
|
||||
10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u8D25
|
||||
10190=\u9002\u914D\u5668\u672A\u627E\u5230
|
||||
10191=\u9002\u914D\u5668\u7F13\u5B58\u9519\u8BEF
|
||||
10192=\u9002\u914D\u5668\u7C7B\u578B\u672A\u627E\u5230
|
||||
|
|
@ -164,7 +164,7 @@
|
|||
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11appid\u6216access_token
|
||||
10156=\u97FF\u61C9\u683C\u5F0F\u932F\u8AA4\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
|
||||
10157=\u8ACB\u6C42\u5931\u6557
|
||||
10158=\u514B\u9686\u8A9E\u97F3:
|
||||
10158=\u514b\u9686\u97f3\u8272:
|
||||
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
|
||||
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u932F\u8AA4\uFF0C\u5FC5\u9808\u4EE5S_\u958B\u982D
|
||||
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
|
||||
|
|
@ -181,3 +181,21 @@
|
|||
10172=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10173=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
|
||||
10174=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
|
||||
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10176=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10177=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10178=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
|
||||
10179=\u6587\u4ef6\u540d\u7a31\u4e0d\u80fd\u70ba\u7a7a
|
||||
10180=\u6587\u4ef6\u5185\u5bb9\u4e0d\u80fd\u70ba\u7a7a
|
||||
10181=\u97f3\u8272\u514b\u9686\u540d\u7a31\u4e0d\u80fd\u70ba\u7a7a
|
||||
10182=\u97f3\u8272\u514b\u9686\u97f3\u983b\u4e0d\u5b58\u5728
|
||||
10183=\u9ed8\u8ba4\u667a\u80fd\u4f53\u672a\u627e\u5230
|
||||
10184=\u4E0D\u652F\u6301\u7684\u9002\u914D\u5668\u985E\u578B
|
||||
10185=RAG\u914D\u7F6E\u9A57\u8B49\u5931\u6557
|
||||
10186=\u9002\u914D\u5668\u5275\u5EFA\u5931\u6557
|
||||
10187=\u9002\u914D\u5668\u521D\u59CB\u5316\u5931\u6557
|
||||
10188=\u9002\u914D\u5668\u9023\u63A5\u6E2C\u8A66\u5931\u6557
|
||||
10189=\u9002\u914D\u5668\u64CD\u4F5C\u5931\u6557
|
||||
10190=\u9002\u914D\u5668\u672A\u627E\u5230
|
||||
10191=\u9002\u914D\u5668\u7F13\u5B58\u932F\u8AA4
|
||||
10192=\u9002\u914D\u5668\u985E\u578B\u672A\u627E\u5230
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
#Deutsch
|
||||
id.require=ID darf nicht leer sein
|
||||
id.null=ID muss leer sein
|
||||
|
||||
sort.number=Der Sortierwert darf nicht kleiner als 0 sein
|
||||
page.number=Der Seitenwert darf nicht kleiner als 0 sein
|
||||
limit.number=Der Limit-Wert darf nicht kleiner als 0 sein
|
||||
|
||||
sysdict.type.require=Der Wörterbuchtyp darf nicht leer sein
|
||||
sysdict.name.require=Der Wörterbuchname darf nicht leer sein
|
||||
sysdict.label.require=Wörterbuch-Label darf nicht leer sein
|
||||
|
||||
sysparams.paramcode.require=Parameter-Code darf nicht leer sein
|
||||
sysparams.paramvalue.require=Parameter-Werte dürfen nicht leer sein
|
||||
sysparams.valuetype.require=Werttyp darf nicht leer sein
|
||||
sysparams.valuetype.pattern=Werttyp muss string, number, boolean oder array sein
|
||||
|
||||
sysuser.username.require=Der Benutzername darf nicht leer sein
|
||||
sysuser.password.require=Das Passwort darf nicht leer sein
|
||||
sysuser.realname.require=Der echte Name darf nicht leer sein
|
||||
sysuser.gender.range=Geschlecht liegt im Bereich von 0 bis 2
|
||||
sysuser.email.error=Falsches E-Mail-Format
|
||||
sysuser.deptId.require=Abteilungen dürfen nicht leer sein
|
||||
sysuser.status.range=Status liegt im Bereich von 0 bis 1
|
||||
sysuser.captcha.require=Das Captcha darf nicht leer sein
|
||||
sysuser.uuid.require=Der eindeutige Identifikator darf nicht leer sein
|
||||
|
||||
timbre.languages.require=Die Sprache des Klangs darf nicht leer sein
|
||||
timbre.name.require=Der Name des Klangs darf nicht leer sein
|
||||
timbre.ttsModelId.require=Die TTS-Modell-ID des Klangs darf nicht leer sein
|
||||
timbre.ttsVoice.require=Die TTS-Stimme des Klangs darf nicht leer sein
|
||||
|
||||
ota.device.not.found=Gerät nicht gefunden
|
||||
ota.device.need.bind={0}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
# Tiếng Việt
|
||||
id.require=ID không được để trống
|
||||
id.null=ID phải để trống
|
||||
|
||||
sort.number=Giá trị sắp xếp không thể nhỏ hơn 0
|
||||
page.number=Giá trị trang không thể nhỏ hơn 0
|
||||
limit.number=Giá trị giới hạn không thể nhỏ hơn 0
|
||||
|
||||
sysdict.type.require=Loại từ điển không được để trống
|
||||
sysdict.name.require=Tên từ điển không được để trống
|
||||
sysdict.label.require=Thẻ từ điển không được để trống
|
||||
|
||||
sysparams.paramcode.require=Mã tham số không được để trống
|
||||
sysparams.paramvalue.require=Giá trị tham số không được để trống
|
||||
sysparams.valuetype.require=Loại giá trị không được để trống
|
||||
sysparams.valuetype.pattern=Loại giá trị phải là chuỗi, số, boolean hoặc mảng
|
||||
|
||||
sysuser.username.require=Tên người dùng không được để trống
|
||||
sysuser.password.require=Mật khẩu không được để trống
|
||||
sysuser.realname.require=Tên thật không được để trống
|
||||
sysuser.gender.range=Giới tính phải từ 0 đến 2
|
||||
sysuser.email.error=Định dạng email không chính xác
|
||||
sysuser.deptId.require=Phòng ban không được để trống
|
||||
sysuser.status.range=Trạng thái phải từ 0 đến 1
|
||||
sysuser.captcha.require=Mã xác thực không được để trống
|
||||
sysuser.uuid.require=Định danh duy nhất không được để trống
|
||||
|
||||
timbre.languages.require=Ngôn ngữ của âm sắc không được để trống
|
||||
timbre.name.require=Tên âm sắc không được để trống
|
||||
timbre.ttsModelId.require=ID mô hình TTS của âm sắc không được để trống
|
||||
timbre.ttsVoice.require=Giọng TTS của âm sắc không được để trống
|
||||
|
||||
ota.device.not.found=Không tìm thấy thiết bị
|
||||
ota.device.need.bind={0}
|
||||
|
|
@ -3,8 +3,8 @@ id.require=ID\u4E0D\u80FD\u4E3A\u7A7A
|
|||
id.null=ID\u5FC5\u987B\u4E3A\u7A7A
|
||||
|
||||
sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0
|
||||
page.number=\u9801\u6578\u4E0D\u80FD\u5C0F\u4E8E0
|
||||
limit.number=\u5217\u6578\u4E0D\u80FD\u5C0F\u4E8E0
|
||||
page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0
|
||||
limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0
|
||||
|
||||
sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A
|
||||
sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
|
|
@ -25,10 +25,10 @@ sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1
|
|||
sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A
|
||||
sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A
|
||||
|
||||
timbre.languages.require=\u97F3\u8272\u7684\u8A9E\u8A00\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||
timbre.name.require=\u97F3\u8272\u7684\u540D\u7A31\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u9375\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A
|
||||
timbre.languages.require=\u97F3\u8272\u7684\u8BED\u8A00\u4E0D\u80FD\u4E3A\u7A7A
|
||||
timbre.name.require=\u97F3\u8272\u7684\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
|
||||
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u80FD\u4E3A\u7A7A
|
||||
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A
|
||||
|
||||
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
|
||||
ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230
|
||||
ota.device.need.bind={0}
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
<mapper namespace="xiaozhi.modules.voiceclone.dao.VoiceCloneDao">
|
||||
<select id="getTrainSuccess" resultType="xiaozhi.modules.model.dto.VoiceDTO">
|
||||
select id, name
|
||||
select id, name, voice_id as voiceDemo
|
||||
from ai_voice_clone
|
||||
where model_id = #{modelId} and user_id = #{userId} and train_status = 2
|
||||
</select>
|
||||
|
|
|
|||
440
main/manager-mobile/src/i18n/de.ts
Normal file
440
main/manager-mobile/src/i18n/de.ts
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
// Deutsch Sprachpaket
|
||||
export default {
|
||||
// TabBar
|
||||
'tabBar.home': 'Startseite',
|
||||
'tabBar.deviceConfig': 'Netzwerkkonfig',
|
||||
'tabBar.settings': 'System',
|
||||
// Einstellungsseitentitel
|
||||
'settings.title': 'Einstellungen',
|
||||
// Anmeldeseite
|
||||
'login.pageTitle': 'Anmelden',
|
||||
'login.navigationTitle': 'Anmelden',
|
||||
'login.fetchConfigError': 'Konfiguration konnte nicht abgerufen werden:',
|
||||
'login.selectLanguage': 'Sprache auswählen',
|
||||
'login.selectLanguageTip': 'Vi',
|
||||
'login.welcomeBack': 'Willkommen zurück',
|
||||
'login.pleaseLogin': 'Bitte melden Sie sich an',
|
||||
'login.enterUsername': 'Bitte Benutzernamen eingeben',
|
||||
'login.enterPassword': 'Bitte Passwort eingeben',
|
||||
'login.enterCaptcha': 'Bitte Bestätigungscode eingeben',
|
||||
'login.loginButton': 'Anmelden',
|
||||
'login.loggingIn': 'Wird angemeldet...',
|
||||
'login.noAccount': 'Registrieren',
|
||||
'login.enterPhone': 'Bitte Handynummer eingeben',
|
||||
'login.selectCountry': 'Land/Region auswählen',
|
||||
'login.confirm': 'Bestätigen',
|
||||
'login.serverSetting': 'Server-Einstellungen',
|
||||
'login.requiredUsername': 'Benutzername darf nicht leer sein',
|
||||
'login.requiredPassword': 'Passwort darf nicht leer sein',
|
||||
'login.requiredCaptcha': 'Bestätigungscode darf nicht leer sein',
|
||||
'login.requiredMobile': 'Bitte gültige Handynummer eingeben',
|
||||
'login.captchaError': 'Grafischer Bestätigungscode Fehler',
|
||||
'login.forgotPassword': 'Passwort vergessen',
|
||||
|
||||
// Registrierungsseite
|
||||
'register.pageTitle': 'Registrieren',
|
||||
'register.createAccount': 'Konto erstellen',
|
||||
'register.enterUsername': 'Bitte Benutzernamen eingeben',
|
||||
'register.enterPassword': 'Bitte Passwort eingeben',
|
||||
'register.confirmPassword': 'Bitte Passwort bestätigen',
|
||||
'register.enterPhone': 'Bitte Handynummer eingeben',
|
||||
'register.enterCode': 'Bitte Bestätigungscode eingeben',
|
||||
'register.getCode': 'Code erhalten',
|
||||
'register.agreeTerms': 'Ich habe gelesen und stimme zu',
|
||||
'register.terms': 'Nutzungsbedingungen',
|
||||
'register.privacy': 'Datenschutzrichtlinie',
|
||||
'register.registerButton': 'Registrieren',
|
||||
'register.registering': 'Wird registriert...',
|
||||
'register.haveAccount': 'Bereits ein Konto?',
|
||||
'register.loginNow': 'Jetzt anmelden',
|
||||
'register.selectCountry': 'Land/Region auswählen',
|
||||
'register.confirm': 'Bestätigen',
|
||||
'register.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet',
|
||||
|
||||
// Startseite
|
||||
'home.pageTitle': 'Startseite',
|
||||
'home.createAgent': 'Agent erstellen',
|
||||
'home.agentName': 'Agent',
|
||||
'home.modelInfo': 'Modell-Info',
|
||||
'home.lastActive': 'Zuletzt aktiv',
|
||||
'home.greeting': 'Hallo Jarvis',
|
||||
'home.subtitle': 'Lassen Sie uns',
|
||||
'home.wonderfulDay': 'einen wunderbaren Tag haben!',
|
||||
'home.emptyState': 'Keine Agenten verfügbar',
|
||||
'home.deviceManagement': 'Geräteverwaltung',
|
||||
'home.lastConversation': 'Letzte Konversation:',
|
||||
'home.delete': 'Löschen',
|
||||
'home.createFirstAgent': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Agenten zu erstellen',
|
||||
'home.dialogTitle': 'Agent erstellen',
|
||||
'home.inputPlaceholder': 'z.B. Kundenservice-Assistent, Sprachassistent, Wissens-F&A',
|
||||
'home.createError': 'Bitte Agenten-Namen eingeben',
|
||||
'home.createNow': 'Jetzt erstellen',
|
||||
'home.justNow': 'Gerade eben',
|
||||
'home.minutesAgo': 'Minuten her',
|
||||
'home.hoursAgo': 'Stunden her',
|
||||
'home.daysAgo': 'Tage her',
|
||||
|
||||
// Agentenseite
|
||||
'agent.pageTitle': 'Agent',
|
||||
'agent.roleConfig': 'Rollenkonfiguration',
|
||||
'agent.deviceManagement': 'Geräteverwaltung',
|
||||
'agent.chatHistory': 'Chat-Verlauf',
|
||||
'agent.voiceprintManagement': 'Stimmabdruckverwaltung',
|
||||
'agent.editTitle': 'Agent bearbeiten',
|
||||
'agent.toolsTitle': 'Funktionen bearbeiten',
|
||||
'agent.voiceActivityDetection': 'Sprachaktivitätserkennung',
|
||||
'agent.speechRecognition': 'Spracherkennung',
|
||||
'agent.largeLanguageModel': 'Großes Sprachmodell',
|
||||
'agent.save': 'Speichern',
|
||||
'agent.cancel': 'Abbrechen',
|
||||
// Agenten-Bearbeitungsseite
|
||||
'agent.basicInfo': 'Grundinformationen',
|
||||
'agent.agentName': 'Agentenname',
|
||||
'agent.inputAgentName': 'Bitte Agenten-Namen eingeben',
|
||||
'agent.roleMode': 'Rollenmodus',
|
||||
'agent.roleDescription': 'Rollenbeschreibung',
|
||||
'agent.inputRoleDescription': 'Bitte Rollenbeschreibung eingeben',
|
||||
'agent.modelConfig': 'Modellkonfiguration',
|
||||
'agent.vad': 'Sprachaktivitätserkennung',
|
||||
'agent.asr': 'Spracherkennung',
|
||||
'agent.llm': 'Großes Sprachmodell',
|
||||
'agent.vllm': 'Vision-Sprachmodell',
|
||||
'agent.intent': 'Absichtserkennung',
|
||||
'agent.memory': 'Speicher',
|
||||
'agent.voiceSettings': 'Stimmeinstellungen',
|
||||
'agent.tts': 'Text-zu-Sprache',
|
||||
'agent.voiceprint': 'Agenten-Stimme',
|
||||
'agent.plugins': 'Plugins',
|
||||
'agent.editFunctions': 'Funktionen bearbeiten',
|
||||
'agent.historyMemory': 'Verlaufsspeicher',
|
||||
'agent.memoryContent': 'Speicherinhalt',
|
||||
'agent.saving': 'Wird gespeichert...',
|
||||
'agent.saveSuccess': 'Erfolgreich gespeichert',
|
||||
'agent.saveFail': 'Speichern fehlgeschlagen',
|
||||
'agent.loadFail': 'Laden fehlgeschlagen',
|
||||
'agent.pleaseInputAgentName': 'Bitte Agenten-Namen eingeben',
|
||||
'agent.pleaseInputRoleDescription': 'Bitte Rollenbeschreibung eingeben',
|
||||
'agent.pleaseSelect': 'Bitte auswählen',
|
||||
|
||||
// Chat-Verlauf Seite
|
||||
'chatHistory.getChatSessions': 'Chat-Sitzungsliste abrufen',
|
||||
'chatHistory.noSelectedAgent': 'Kein Agent ausgewählt',
|
||||
'chatHistory.getChatSessionsFailed': 'Chat-Sitzungsliste konnte nicht abgerufen werden:',
|
||||
'chatHistory.unknownTime': 'Unbekannte Zeit',
|
||||
'chatHistory.justNow': 'Gerade eben',
|
||||
'chatHistory.minutesAgo': 'Vor {minutes} Minuten',
|
||||
'chatHistory.hoursAgo': 'Vor {hours} Stunden',
|
||||
'chatHistory.daysAgo': 'Vor {days} Tagen',
|
||||
'chatHistory.conversationRecord': 'Konversationsaufzeichnung',
|
||||
'chatHistory.totalChats': 'Insgesamt {count} Chats',
|
||||
'chatHistory.loading': 'Lädt...',
|
||||
'chatHistory.noMoreData': 'Keine weiteren Daten',
|
||||
'chatHistory.noChatRecords': 'Keine Chat-Aufzeichnungen',
|
||||
'chatHistory.chatRecordsDescription': 'Konversationsaufzeichnungen mit Agenten werden hier angezeigt',
|
||||
// Chat-Verlauf Detailseite
|
||||
'chatHistory.pageTitle': 'Chat-Details',
|
||||
'chatHistory.assistantName': 'Intelligenter Assistent',
|
||||
'chatHistory.userName': 'Benutzer',
|
||||
'chatHistory.aiAssistantName': 'KI-Assistent',
|
||||
'chatHistory.loadFailed': 'Chat-Verlauf konnte nicht geladen werden',
|
||||
'chatHistory.parameterError': 'Seitenparameter Fehler',
|
||||
'chatHistory.invalidAudioId': 'Ungültige Audio-ID',
|
||||
'chatHistory.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen',
|
||||
'chatHistory.playAudioFailed': 'Audio konnte nicht abgespielt werden',
|
||||
|
||||
// Geräteverwaltungsseite
|
||||
'device.pageTitle': 'Geräteverwaltung',
|
||||
'device.noDevices': 'Keine Geräte verfügbar',
|
||||
'device.macAddress': 'MAC-Adresse',
|
||||
'device.firmwareVersion': 'Firmware-Version',
|
||||
'device.lastConnected': 'Letzte Konversation',
|
||||
'device.otaUpdate': 'OTA-Update',
|
||||
'device.unbind': 'Entbinden',
|
||||
'device.confirmUnbind': 'Bestätigen',
|
||||
'device.bindDevice': 'Neues Gerät binden',
|
||||
'device.deviceType': 'Gerätetyp',
|
||||
'device.loading': 'Lädt...',
|
||||
'device.neverConnected': 'Nie verbunden',
|
||||
'device.justNow': 'Gerade eben',
|
||||
'device.minutesAgo': 'Vor {minutes} Minuten',
|
||||
'device.hoursAgo': 'Vor {hours} Stunden',
|
||||
'device.daysAgo': 'Vor {days} Tagen',
|
||||
'device.otaAutoUpdateEnabled': 'OTA Auto-Update aktiviert',
|
||||
'device.otaAutoUpdateDisabled': 'OTA Auto-Update deaktiviert',
|
||||
'device.operationFailed': 'Operation fehlgeschlagen, bitte erneut versuchen',
|
||||
'device.deviceUnbound': 'Gerät entbunden',
|
||||
'device.unbindFailed': 'Entbinden fehlgeschlagen, bitte erneut versuchen',
|
||||
'device.unbindDevice': 'Gerät entbinden',
|
||||
'device.confirmUnbindDevice': 'Sind Sie sicher, dass Sie Gerät "{macAddress}" entbinden möchten?',
|
||||
'device.cancel': 'Abbrechen',
|
||||
'device.noDevice': 'Kein Gerät',
|
||||
'device.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus',
|
||||
'device.deviceBindSuccess': 'Gerät erfolgreich gebunden!',
|
||||
'device.bindFailed': 'Binden fehlgeschlagen, bitte prüfen Sie ob der Bestätigungscode korrekt ist',
|
||||
'device.enterDeviceCode': 'Bitte Geräte-Bestätigungscode eingeben',
|
||||
'device.bindNow': 'Jetzt binden',
|
||||
'device.lastConnection': 'Letzte Verbindung',
|
||||
'device.clickToBindFirstDevice': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihr erstes Gerät zu binden',
|
||||
|
||||
// Allgemein
|
||||
'common.success': 'Erfolg',
|
||||
'common.fail': 'Fehlgeschlagen',
|
||||
'common.loading': 'Lädt...',
|
||||
'common.confirm': 'Bestätigen',
|
||||
'common.cancel': 'Abbrechen',
|
||||
'common.delete': 'Löschen',
|
||||
'common.edit': 'Bearbeiten',
|
||||
'common.add': 'Hinzufügen',
|
||||
'common.pleaseSelect': 'Bitte auswählen',
|
||||
'common.unknownError': 'Unbekannter Fehler',
|
||||
'common.networkError': 'Netzwerkfehler',
|
||||
|
||||
// Passwort-Wiederherstellungsseite
|
||||
'retrievePassword.title': 'Passwort zurücksetzen',
|
||||
'retrievePassword.subtitle': 'Stellen Sie Ihr Kontopasswort über Handynummer wieder her',
|
||||
'retrievePassword.mobileRequired': 'Bitte Handynummer eingeben',
|
||||
'retrievePassword.inputCorrectMobile': 'Bitte gültige Handynummer eingeben',
|
||||
'retrievePassword.captchaRequired': 'Bitte grafischen Bestätigungscode eingeben',
|
||||
'retrievePassword.mobileCaptchaRequired': 'Bitte SMS-Bestätigungscode eingeben',
|
||||
'retrievePassword.newPasswordRequired': 'Bitte neues Passwort eingeben',
|
||||
'retrievePassword.confirmNewPasswordRequired': 'Bitte neues Passwort bestätigen',
|
||||
'retrievePassword.passwordsNotMatch': 'Passwörter stimmen nicht überein',
|
||||
'retrievePassword.mobilePlaceholder': 'Bitte Handynummer eingeben',
|
||||
'retrievePassword.captchaPlaceholder': 'Bitte grafischen Bestätigungscode eingeben',
|
||||
'retrievePassword.mobileCaptchaPlaceholder': 'Bitte SMS-Bestätigungscode eingeben',
|
||||
'retrievePassword.newPasswordPlaceholder': 'Bitte neues Passwort eingeben',
|
||||
'retrievePassword.confirmNewPasswordPlaceholder': 'Bitte neues Passwort bestätigen',
|
||||
'retrievePassword.getMobileCaptcha': 'Code erhalten',
|
||||
'retrievePassword.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet',
|
||||
'retrievePassword.passwordUpdateSuccess': 'Passwort erfolgreich zurückgesetzt',
|
||||
'retrievePassword.resetButton': 'Passwort zurücksetzen',
|
||||
'retrievePassword.goToLogin': 'Zurück zur Anmeldung',
|
||||
|
||||
// SM2-Verschlüsselungsbezogene Fehlermeldungen
|
||||
'sm2.publicKeyNotConfigured': 'SM2 öffentlicher Schlüssel nicht konfiguriert, bitte Administrator kontaktieren',
|
||||
'sm2.encryptionFailed': 'Passwortverschlüsselung fehlgeschlagen',
|
||||
'sm2.keyGenerationFailed': 'Schlüsselpaar-Generierung fehlgeschlagen',
|
||||
'sm2.invalidPublicKey': 'Ungültiges öffentliches Schlüsselformat',
|
||||
'sm2.encryptionError': 'Fehler bei der Verschlüsselung aufgetreten',
|
||||
'sm2.publicKeyRetry': 'Öffentlichen Schlüssel erneut abrufen...',
|
||||
'sm2.publicKeyRetryFailed': 'Wiederholter Abruf des öffentlichen Schlüssels fehlgeschlagen',
|
||||
|
||||
// Stimmabdruckseite
|
||||
'voiceprint.noSelectedAgent': 'Kein Agent ausgewählt',
|
||||
'voiceprint.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus',
|
||||
'voiceprint.fetchHistoryFailed': 'Chat-Verlauf konnte nicht abgerufen werden',
|
||||
'voiceprint.clickToSelectVector': 'Klicken zum Auswählen des Stimmabdruck-Vektors',
|
||||
'voiceprint.pleaseInputName': 'Bitte Namen eingeben',
|
||||
'voiceprint.pleaseSelectVector': 'Bitte Stimmabdruck-Vektor auswählen',
|
||||
'voiceprint.addSuccess': 'Erfolgreich hinzugefügt',
|
||||
'voiceprint.addFailed': 'Hinzufügen des Sprechers fehlgeschlagen',
|
||||
'voiceprint.editSuccess': 'Erfolgreich bearbeitet',
|
||||
'voiceprint.editFailed': 'Bearbeiten des Sprechers fehlgeschlagen',
|
||||
'voiceprint.deleteConfirmMsg': 'Sind Sie sicher, dass Sie diesen Sprecher löschen möchten?',
|
||||
'voiceprint.deleteConfirmTitle': 'Löschen bestätigen',
|
||||
'voiceprint.deleteSuccess': 'Erfolgreich gelöscht',
|
||||
'voiceprint.loading': 'Lädt...',
|
||||
'voiceprint.delete': 'Löschen',
|
||||
'voiceprint.emptyTitle': 'Keine Stimmabdruck-Daten',
|
||||
'voiceprint.emptyDesc': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Sprecher hinzuzufügen',
|
||||
'voiceprint.addSpeaker': 'Sprecher hinzufügen',
|
||||
'voiceprint.voiceVector': 'Stimmabdruck-Vektor',
|
||||
'voiceprint.name': 'Name',
|
||||
'voiceprint.description': 'Beschreibung',
|
||||
'voiceprint.pleaseInputDescription': 'Bitte Beschreibung eingeben',
|
||||
'voiceprint.cancel': 'Abbrechen',
|
||||
'voiceprint.save': 'Speichern',
|
||||
'voiceprint.editSpeaker': 'Sprecher bearbeiten',
|
||||
'voiceprint.selectVector': 'Stimmabdruck-Vektor auswählen',
|
||||
'voiceprint.voiceprintInterfaceNotConfigured': 'Stimmabdruck-Schnittstelle nicht konfiguriert',
|
||||
|
||||
// Einstellungsseite
|
||||
'settings.pageTitle': 'Einstellungen',
|
||||
'settings.navigationTitle': 'Einstellungen',
|
||||
'settings.networkSettings': 'Netzwerkeinstellungen',
|
||||
'settings.serverApiUrl': 'Server-API-URL',
|
||||
'settings.validServerUrl': 'Bitte gültige Serveradresse eingeben (beginnt mit http oder https und endet mit /xiaozhi)',
|
||||
'settings.saveSettings': 'Einstellungen speichern',
|
||||
'settings.resetDefault': 'Auf Standard zurücksetzen',
|
||||
'settings.restartApp': 'App neu starten',
|
||||
'settings.restartNow': 'Jetzt neu starten',
|
||||
'settings.restartLater': 'Später',
|
||||
// Über uns
|
||||
'settings.aboutApp': 'Über XiaoZhi Konsole',
|
||||
'settings.aboutContent': 'XiaoZhi Konsole\n\nEine plattformübergreifende mobile Management-App, erstellt mit Vue.js 3 + uni-app, bietet Geräteverwaltung, Agentenkonfiguration und andere Funktionen für xiaozhi ESP32 Smart Hardware.\n\n© 2025 xiaozhi-esp32-server {version}',
|
||||
'settings.restartSuccess': 'Gespeichert, Sie können die App später manuell neu starten',
|
||||
'settings.serverUrlSavedAndCacheCleared': 'Server-URL gespeichert und Cache geleert',
|
||||
'settings.resetToDefaultAndCacheCleared': 'Auf Standard zurückgesetzt und Cache geleert',
|
||||
'settings.resetSuccess': 'Zurücksetzen erfolgreich',
|
||||
'settings.enterServerUrl': 'Bitte Server-URL eingeben',
|
||||
'settings.clearCacheFailed': 'Cache konnte nicht geleert werden',
|
||||
'settings.cacheManagement': 'Cache-Verwaltung',
|
||||
'settings.totalCacheSize': 'Gesamte Cache-Größe',
|
||||
'settings.appDataSize': 'Gesamte App-Datengröße',
|
||||
'settings.cacheClear': 'Cache leeren',
|
||||
'settings.clearAllCache': 'Alle Cache-Daten löschen',
|
||||
'settings.clearCache': 'Cache leeren',
|
||||
'settings.modifyWillClearCache': 'Änderungen werden Cache leeren',
|
||||
'settings.appInfo': 'App-Info',
|
||||
'settings.aboutUs': 'Über uns',
|
||||
'settings.appVersion': 'App-Version & Team-Info',
|
||||
'settings.confirmClear': 'Löschen bestätigen',
|
||||
'settings.confirmClearMessage': 'Sind Sie sicher, dass Sie den gesamten Cache löschen möchten? Dies löscht alle Daten einschließlich Anmeldestatus und erfordert erneute Anmeldung.',
|
||||
'settings.cacheCleared': 'Cache erfolgreich geleert, leite zur Anmeldeseite weiter',
|
||||
'settings.languageSettings': 'Spracheinstellungen',
|
||||
'settings.language': 'Sprache',
|
||||
'settings.selectLanguage': 'Sprache auswählen',
|
||||
'settings.languageChanged': 'Sprache erfolgreich geändert',
|
||||
|
||||
// Nachrichten
|
||||
'message.loginSuccess': 'Anmeldung erfolgreich!',
|
||||
'message.loginFail': 'Anmeldung fehlgeschlagen',
|
||||
'message.registerSuccess': 'Registrierung erfolgreich',
|
||||
'message.registerFail': 'Registrierung fehlgeschlagen',
|
||||
'message.saveSuccess': 'Erfolgreich gespeichert',
|
||||
'message.saveFail': 'Speichern fehlgeschlagen',
|
||||
'message.deleteSuccess': 'Erfolgreich gelöscht',
|
||||
'message.deleteFail': 'Löschen fehlgeschlagen',
|
||||
'message.bindSuccess': 'Binden erfolgreich',
|
||||
'message.bindFail': 'Binden fehlgeschlagen',
|
||||
'message.unbindSuccess': 'Entbinden erfolgreich',
|
||||
'message.unbindFail': 'Entbinden fehlgeschlagen',
|
||||
'message.networkError': 'Netzwerkfehler, bitte Verbindung prüfen',
|
||||
'message.serverError': 'Serverfehler, bitte später erneut versuchen',
|
||||
'message.invalidAddress': 'Ungültige Adresse, bitte prüfen ob Server gestartet oder Netzwerkverbindung normal ist',
|
||||
'message.languageChanged': 'Sprache geändert',
|
||||
'message.passwordError': 'Konto oder Passwort Fehler',
|
||||
'message.phoneRegistered': 'Diese Handynummer wurde bereits registriert',
|
||||
|
||||
// Agenten-Werkzeuge Seite
|
||||
'agent.tools.pageTitle': 'Agenten-Werkzeuge',
|
||||
'agent.tools.unselected': 'Nicht ausgewählt',
|
||||
'agent.tools.selected': 'Ausgewählt',
|
||||
'agent.tools.noMorePlugins': 'Keine weiteren Plugins',
|
||||
'agent.tools.pleaseSelectPlugin': 'Bitte Plugin-Funktion auswählen',
|
||||
'agent.tools.builtInPlugins': 'Eingebaute Plugins',
|
||||
'agent.tools.mcpAccessPoint': 'MCP-Zugangspunkt',
|
||||
'agent.tools.copy': 'Kopieren',
|
||||
'agent.tools.noTools': 'Keine Werkzeuge verfügbar',
|
||||
'agent.tools.parameterConfig': 'Parameterkonfiguration',
|
||||
'agent.tools.noParamsNeeded': 'Keine Parameter benötigt',
|
||||
'agent.tools.pleaseInput': 'Bitte eingeben',
|
||||
'agent.tools.inputOneItemPerLine': 'Ein Element pro Zeile eingeben',
|
||||
'agent.tools.pleaseInputValidJson': 'Bitte gültiges JSON-Format eingeben',
|
||||
'agent.tools.enableFunction': 'Funktion aktivieren',
|
||||
'agent.tools.toggleFunction': 'Diese Funktion ein- oder ausschalten',
|
||||
'agent.tools.jsonFormatError': 'JSON-Format Fehler',
|
||||
'agent.tools.noMcpAddressToCopy': 'Keine MCP-Adresse zum Kopieren',
|
||||
'agent.tools.mcpAddressCopied': 'MCP-Adresse in Zwischenablage kopiert',
|
||||
'agent.tools.copyFailed': 'Kopieren fehlgeschlagen, bitte erneut versuchen',
|
||||
'agent.tools.defaultValue': 'Standardwert',
|
||||
'agent.tools.notSelected': 'Nicht ausgewählt',
|
||||
'agent.tools.clickToConfigure': 'Klicken zum Konfigurieren',
|
||||
'agent.tools.mcpEndpoint': 'MCP-Endpunkt',
|
||||
'agent.tools.eachLineOneItem': 'Ein Element pro Zeile eingeben',
|
||||
|
||||
// Gerätekonfigurationsseite
|
||||
'deviceConfig.pageTitle': 'Gerätekonfiguration',
|
||||
'deviceConfig.wifiConfig': 'WiFi-Konfiguration',
|
||||
'deviceConfig.ultrasonicConfig': 'Ultraschall-Konfiguration',
|
||||
'deviceConfig.selectConfigMethod': 'Konfigurationsmethode auswählen',
|
||||
'deviceConfig.networkConfig': 'Netzwerkkonfiguration',
|
||||
'deviceConfig.selectedNetwork': 'Ausgewähltes Netzwerk',
|
||||
'deviceConfig.signal': 'Signal',
|
||||
'deviceConfig.openNetwork': 'Offenes Netzwerk',
|
||||
'deviceConfig.encryptedNetwork': 'Verschlüsseltes Netzwerk',
|
||||
'deviceConfig.password': 'Passwort',
|
||||
'deviceConfig.pleaseEnterPassword': 'Bitte WiFi-Passwort eingeben',
|
||||
'deviceConfig.startConfig': 'Konfiguration starten',
|
||||
'deviceConfig.connectToXiaozhiHotspot': 'Bitte verbinden Sie sich zuerst mit dem xiaozhi Hotspot',
|
||||
'deviceConfig.detecting': 'Erkennen...',
|
||||
'deviceConfig.reDetect': 'Erneut erkennen',
|
||||
'deviceConfig.alreadyConnected': 'Mit xiaozhi Hotspot verbunden',
|
||||
'deviceConfig.refreshStatus': 'Status aktualisieren',
|
||||
'deviceConfig.wifiNetworks': 'WiFi-Netzwerke',
|
||||
'deviceConfig.selectWifiNetwork': 'WiFi-Netzwerk auswählen',
|
||||
'deviceConfig.refreshScan': 'Scan aktualisieren',
|
||||
'deviceConfig.noWifiNetworks': 'Keine WiFi-Netzwerke verfügbar',
|
||||
'deviceConfig.clickToRefreshScan': 'Bitte Scan aktualisieren klicken',
|
||||
'deviceConfig.signalStrong': 'Starkes Signal',
|
||||
'deviceConfig.signalGood': 'Gutes Signal',
|
||||
'deviceConfig.signalFair': 'Mittleres Signal',
|
||||
'deviceConfig.signalWeak': 'Schwaches Signal',
|
||||
'deviceConfig.channel': 'Kanal',
|
||||
'deviceConfig.about': 'ungefähr',
|
||||
'deviceConfig.seconds': 'Sekunden',
|
||||
'deviceConfig.generating': 'Wird generiert...',
|
||||
'deviceConfig.playing': 'Wird abgespielt...',
|
||||
'deviceConfig.generateAndPlaySoundWave': 'Schallwelle generieren und abspielen',
|
||||
'deviceConfig.playSoundWave': 'Schallwelle abspielen',
|
||||
'deviceConfig.stopPlaying': 'Abspielen stoppen',
|
||||
'deviceConfig.autoLoopPlaySoundWave': 'Schallwelle automatisch wiederholt abspielen',
|
||||
'deviceConfig.configAudioFile': 'Konfigurations-Audio-Datei',
|
||||
'deviceConfig.duration': 'Dauer',
|
||||
'deviceConfig.ultrasonicConfigInstructions': 'Ultraschall-Konfigurationsanleitung',
|
||||
'deviceConfig.ensureWifiNetworkSelectedAndPasswordEntered': 'Stellen Sie sicher, dass WiFi-Netzwerk ausgewählt und Passwort eingegeben ist',
|
||||
'deviceConfig.clickGenerateAndPlaySoundWave': 'Klicken Sie auf Schallwelle generieren und abspielen, das System kodiert Konfigurationsinformationen in Audio',
|
||||
'deviceConfig.bringPhoneCloseToXiaozhiDevice': 'Bringen Sie das Telefon in die Nähe des xiaozhi Geräts (1-2 Meter Entfernung)',
|
||||
'deviceConfig.duringAudioPlaybackXiaozhiWillReceive': 'Während der Audio-Wiedergabe empfängt xiaozhi und dekodiert Konfigurationsinformationen',
|
||||
'deviceConfig.afterConfigSuccessDeviceWillConnect': 'Nach erfolgreicher Konfiguration verbindet sich das Gerät automatisch mit dem WiFi-Netzwerk',
|
||||
'deviceConfig.usesAfskModulation': 'Verwendet AFSK-Modulationstechnologie, überträgt Daten durch 1800Hz und 1500Hz Frequenzen',
|
||||
'deviceConfig.ensureModeratePhoneVolume': 'Bitte stellen Sie sicher, dass die Telefonlautstärke moderat ist, um Umgebungsgeräuschstörungen zu vermeiden',
|
||||
'deviceConfig.generatingUltrasonicConfigAudio': 'Ultraschall-Konfigurationsaudio wird generiert',
|
||||
'deviceConfig.configData': 'Konfigurationsdaten',
|
||||
'deviceConfig.dataBytesLength': 'Datenbytes-Länge',
|
||||
'deviceConfig.bitStreamLength': 'Bitstrom-Länge',
|
||||
'deviceConfig.base64Length': 'Base64-Länge',
|
||||
'deviceConfig.audioFileTooLarge': 'Audio-Datei zu groß, bitte SSID oder Passwortlänge kürzen',
|
||||
'deviceConfig.audioGenerationSuccess': 'Audio-Generierung erfolgreich',
|
||||
'deviceConfig.samplePoints': 'Abtastpunkte',
|
||||
'deviceConfig.soundWaveGenerationSuccess': 'Schallwellen-Generierung erfolgreich',
|
||||
'deviceConfig.audioGenerationFailed': 'Audio-Generierung fehlgeschlagen',
|
||||
'deviceConfig.soundWaveGenerationFailed': 'Schallwellen-Generierung fehlgeschlagen',
|
||||
'deviceConfig.pleaseGenerateAudioFirst': 'Bitte generieren Sie zuerst Audio',
|
||||
'deviceConfig.startPlayingUltrasonicConfigAudio': 'Ultraschall-Konfigurationsaudio wird abgespielt',
|
||||
'deviceConfig.ultrasonicAudioStartedPlaying': 'Ultraschall-Audio wurde gestartet',
|
||||
'deviceConfig.startPlayingConfigSoundWave': 'Konfigurations-Schallwelle wurde gestartet',
|
||||
'deviceConfig.ultrasonicAudioPlaybackEnded': 'Ultraschall-Audio-Wiedergabe beendet',
|
||||
'deviceConfig.audioPlaybackFailed': 'Audio-Wiedergabe fehlgeschlagen',
|
||||
'deviceConfig.audioResourceBusy': 'Audio-Ressource beschäftigt, bitte später erneut versuchen',
|
||||
'deviceConfig.audioFormatNotSupported': 'Audio-Format nicht unterstützt, möglicherweise ein Data-URI-Problem',
|
||||
'deviceConfig.audioFileError': 'Audio-Datei-Fehler',
|
||||
'deviceConfig.cleaningUpAudioContext': 'Audio-Kontext wird bereinigt',
|
||||
'deviceConfig.cleaningUpAudioContextFailed': 'Audio-Kontext-Bereinigung fehlgeschlagen',
|
||||
'deviceConfig.stoppedPlayingUltrasonicAudio': 'Ultraschall-Audio-Wiedergabe gestoppt',
|
||||
'deviceConfig.stoppedPlaying': 'Wiedergabe gestoppt',
|
||||
'deviceConfig.configMethod': 'Konfigurationsmethode',
|
||||
'deviceConfig.enterWifiPassword': 'Bitte WiFi-Passwort eingeben',
|
||||
'deviceConfig.xiaozhi': 'xiaozhi',
|
||||
'deviceConfig.connectXiaozhiHotspot': 'Bitte verbinden Sie sich mit dem xiaozhi Hotspot',
|
||||
'deviceConfig.wifiScanResponse': 'WiFi-Scan-Antwort',
|
||||
'deviceConfig.scanSuccess': 'Scan erfolgreich',
|
||||
'deviceConfig.networks': 'Netzwerke',
|
||||
'deviceConfig.wifiScanFailed': 'WiFi-Scan fehlgeschlagen',
|
||||
'deviceConfig.scanFailedCheckConnection': 'Scan fehlgeschlagen, bitte Verbindung prüfen',
|
||||
'deviceConfig.checking': 'Wird geprüft',
|
||||
'deviceConfig.reCheck': 'Erneut prüfen',
|
||||
'deviceConfig.connectedXiaozhiHotspot': 'Mit xiaozhi Hotspot verbunden',
|
||||
'deviceConfig.wifiNetwork': 'WiFi-Netzwerk',
|
||||
'deviceConfig.scanning': 'Wird gescannt',
|
||||
'deviceConfig.cancel': 'Abbrechen',
|
||||
'deviceConfig.clickRefreshScan': 'Bitte Scan aktualisieren klicken',
|
||||
'deviceConfig.esp32ConnectionCheckFailed': 'ESP32-Verbindungsprüfung fehlgeschlagen',
|
||||
'deviceConfig.startWifiConfig': 'WiFi-Konfiguration wird gestartet',
|
||||
'deviceConfig.configSuccess': 'Konfiguration erfolgreich',
|
||||
'deviceConfig.deviceWillConnectTo': 'Gerät wird sich verbinden mit',
|
||||
'deviceConfig.deviceWillRestart': 'Gerät wird neu starten',
|
||||
'deviceConfig.pleaseDisconnectXiaozhiHotspot': 'Bitte trennen Sie sich vom xiaozhi Hotspot',
|
||||
'deviceConfig.configFailed': 'Konfiguration fehlgeschlagen',
|
||||
'deviceConfig.wifiConfigFailed': 'WiFi-Konfiguration fehlgeschlagen',
|
||||
'deviceConfig.pleaseCheckNetworkConnection': 'Bitte Netzwerkverbindung prüfen',
|
||||
'deviceConfig.startWifiConfigButton': 'Konfiguration starten',
|
||||
'deviceConfig.wifiConfigInstructions': 'WiFi-Konfigurationsanleitung',
|
||||
'deviceConfig.phoneConnectXiaozhiHotspot': 'Telefon mit xiaozhi Hotspot verbinden',
|
||||
'deviceConfig.selectTargetWifiNetwork': 'Ziel-WiFi-Netzwerk auswählen',
|
||||
'deviceConfig.enterWifiPasswordIfNeeded': 'WiFi-Passwort eingeben falls benötigt',
|
||||
'deviceConfig.clickStartConfigAndWait': 'Konfiguration starten klicken und warten',
|
||||
'deviceConfig.afterConfigSuccessDeviceWillRestart': 'Nach erfolgreicher Konfiguration startet Gerät automatisch neu',
|
||||
'deviceConfig.audioPlaybackError': 'Audio-Wiedergabe-Fehler',
|
||||
'deviceConfig.playbackFailed': 'Wiedergabe fehlgeschlagen',
|
||||
}
|
||||
|
|
@ -3,15 +3,19 @@ import { useLangStore } from '@/store/lang'
|
|||
import type { Language } from '@/store/lang'
|
||||
|
||||
// 导入各个语言的翻译文件
|
||||
import zhCN from './zh_CN'
|
||||
import zh_CN from './zh_CN'
|
||||
import en from './en'
|
||||
import zhTW from './zh_TW'
|
||||
import zh_TW from './zh_TW'
|
||||
import de from './de'
|
||||
import vi from './vi'
|
||||
|
||||
// 语言包映射
|
||||
const messages = {
|
||||
zh_CN: zhCN,
|
||||
zh_CN: zh_CN,
|
||||
en,
|
||||
zh_TW: zhTW,
|
||||
zh_TW: zh_TW,
|
||||
de,
|
||||
vi,
|
||||
}
|
||||
|
||||
// 当前使用的语言
|
||||
|
|
@ -61,10 +65,12 @@ export function getCurrentLanguage(): Language {
|
|||
}
|
||||
|
||||
// 获取支持的语言列表
|
||||
export function getSupportedLanguages(): {code: Language, name: string}[] {
|
||||
export function getSupportedLanguages(): { code: Language, name: string }[] {
|
||||
return [
|
||||
{ code: 'zh_CN', name: '简体中文' },
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'zh_TW', name: '繁體中文' },
|
||||
{ code: 'de', name: 'Deutsch' },
|
||||
{ code: 'vi', name: 'Tiếng Việt' },
|
||||
]
|
||||
}
|
||||
440
main/manager-mobile/src/i18n/vi.ts
Normal file
440
main/manager-mobile/src/i18n/vi.ts
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
// Gói ngôn ngữ tiếng Việt
|
||||
export default {
|
||||
// TabBar
|
||||
'tabBar.home': 'Trang chủ',
|
||||
'tabBar.deviceConfig': 'Cấu hình mạng',
|
||||
'tabBar.settings': 'Hệ thống',
|
||||
// Tiêu đề trang cài đặt
|
||||
'settings.title': 'Cài đặt',
|
||||
// Trang đăng nhập
|
||||
'login.pageTitle': 'Đăng nhập',
|
||||
'login.navigationTitle': 'Đăng nhập',
|
||||
'login.fetchConfigError': 'Không thể tải cấu hình:',
|
||||
'login.selectLanguage': 'Chọn ngôn ngữ',
|
||||
'login.selectLanguageTip': 'de',
|
||||
'login.welcomeBack': 'Chào mừng trở lại',
|
||||
'login.pleaseLogin': 'Vui lòng đăng nhập vào tài khoản của bạn',
|
||||
'login.enterUsername': 'Vui lòng nhập tên đăng nhập',
|
||||
'login.enterPassword': 'Vui lòng nhập mật khẩu',
|
||||
'login.enterCaptcha': 'Vui lòng nhập mã xác minh',
|
||||
'login.loginButton': 'Đăng nhập',
|
||||
'login.loggingIn': 'Đang đăng nhập...',
|
||||
'login.noAccount': 'Đăng ký',
|
||||
'login.enterPhone': 'Vui lòng nhập số điện thoại',
|
||||
'login.selectCountry': 'Chọn quốc gia/vùng',
|
||||
'login.confirm': 'Xác nhận',
|
||||
'login.serverSetting': 'Cài đặt máy chủ',
|
||||
'login.requiredUsername': 'Tên đăng nhập không thể để trống',
|
||||
'login.requiredPassword': 'Mật khẩu không thể để trống',
|
||||
'login.requiredCaptcha': 'Mã xác minh không thể để trống',
|
||||
'login.requiredMobile': 'Vui lòng nhập số điện thoại hợp lệ',
|
||||
'login.captchaError': 'Lỗi mã xác minh đồ họa',
|
||||
'login.forgotPassword': 'Quên mật khẩu',
|
||||
|
||||
// Trang đăng ký
|
||||
'register.pageTitle': 'Đăng ký',
|
||||
'register.createAccount': 'Tạo tài khoản',
|
||||
'register.enterUsername': 'Vui lòng nhập tên đăng nhập',
|
||||
'register.enterPassword': 'Vui lòng nhập mật khẩu',
|
||||
'register.confirmPassword': 'Vui lòng xác nhận mật khẩu',
|
||||
'register.enterPhone': 'Vui lòng nhập số điện thoại',
|
||||
'register.enterCode': 'Vui lòng nhập mã xác minh',
|
||||
'register.getCode': 'Lấy mã',
|
||||
'register.agreeTerms': 'Tôi đã đọc và đồng ý với',
|
||||
'register.terms': 'Thỏa thuận người dùng',
|
||||
'register.privacy': 'Chính sách bảo mật',
|
||||
'register.registerButton': 'Đăng ký',
|
||||
'register.registering': 'Đang đăng ký...',
|
||||
'register.haveAccount': 'Đã có tài khoản?',
|
||||
'register.loginNow': 'Đăng nhập ngay',
|
||||
'register.selectCountry': 'Chọn quốc gia/vùng',
|
||||
'register.confirm': 'Xác nhận',
|
||||
'register.captchaSendSuccess': 'Đã gửi mã xác minh thành công',
|
||||
|
||||
// Trang chủ
|
||||
'home.pageTitle': 'Trang chủ',
|
||||
'home.createAgent': 'Tạo đại lý',
|
||||
'home.agentName': 'Đại lý',
|
||||
'home.modelInfo': 'Thông tin mô hình',
|
||||
'home.lastActive': 'Hoạt động lần cuối',
|
||||
'home.greeting': 'Xin chào Jarvis',
|
||||
'home.subtitle': 'Hãy cùng có',
|
||||
'home.wonderfulDay': 'một ngày tuyệt vời!',
|
||||
'home.emptyState': 'Không có đại lý nào',
|
||||
'home.deviceManagement': 'Quản lý thiết bị',
|
||||
'home.lastConversation': 'Cuộc trò chuyện cuối:',
|
||||
'home.delete': 'Xóa',
|
||||
'home.createFirstAgent': 'Nhấp vào nút + ở góc dưới bên phải để tạo đại lý đầu tiên của bạn',
|
||||
'home.dialogTitle': 'Tạo đại lý',
|
||||
'home.inputPlaceholder': 'ví dụ: Trợ lý chăm sóc khách hàng, Trợ lý giọng nói, Hỏi đáp kiến thức',
|
||||
'home.createError': 'Vui lòng nhập tên đại lý',
|
||||
'home.createNow': 'Tạo ngay',
|
||||
'home.justNow': 'Vừa xong',
|
||||
'home.minutesAgo': 'phút trước',
|
||||
'home.hoursAgo': 'giờ trước',
|
||||
'home.daysAgo': 'ngày trước',
|
||||
|
||||
// Trang đại lý
|
||||
'agent.pageTitle': 'Đại lý',
|
||||
'agent.roleConfig': 'Cấu hình vai trò',
|
||||
'agent.deviceManagement': 'Quản lý thiết bị',
|
||||
'agent.chatHistory': 'Lịch sử trò chuyện',
|
||||
'agent.voiceprintManagement': 'Quản lý dấu giọng nói',
|
||||
'agent.editTitle': 'Chỉnh sửa đại lý',
|
||||
'agent.toolsTitle': 'Chỉnh sửa tính năng',
|
||||
'agent.voiceActivityDetection': 'Phát hiện hoạt động giọng nói',
|
||||
'agent.speechRecognition': 'Nhận dạng giọng nói',
|
||||
'agent.largeLanguageModel': 'Mô hình ngôn ngữ lớn',
|
||||
'agent.save': 'Lưu',
|
||||
'agent.cancel': 'Hủy',
|
||||
// Trang chỉnh sửa đại lý
|
||||
'agent.basicInfo': 'Thông tin cơ bản',
|
||||
'agent.agentName': 'Tên đại lý',
|
||||
'agent.inputAgentName': 'Vui lòng nhập tên đại lý',
|
||||
'agent.roleMode': 'Chế độ vai trò',
|
||||
'agent.roleDescription': 'Mô tả vai trò',
|
||||
'agent.inputRoleDescription': 'Vui lòng nhập mô tả vai trò',
|
||||
'agent.modelConfig': 'Cấu hình mô hình',
|
||||
'agent.vad': 'Phát hiện hoạt động giọng nói',
|
||||
'agent.asr': 'Nhận dạng giọng nói',
|
||||
'agent.llm': 'Mô hình ngôn ngữ lớn',
|
||||
'agent.vllm': 'Mô hình ngôn ngữ thị giác',
|
||||
'agent.intent': 'Nhận dạng ý định',
|
||||
'agent.memory': 'Bộ nhớ',
|
||||
'agent.voiceSettings': 'Cài đặt giọng nói',
|
||||
'agent.tts': 'Văn bản thành giọng nói',
|
||||
'agent.voiceprint': 'Giọng nói đại lý',
|
||||
'agent.plugins': 'Plugin',
|
||||
'agent.editFunctions': 'Chỉnh sửa tính năng',
|
||||
'agent.historyMemory': 'Bộ nhớ lịch sử',
|
||||
'agent.memoryContent': 'Nội dung bộ nhớ',
|
||||
'agent.saving': 'Đang lưu...',
|
||||
'agent.saveSuccess': 'Lưu thành công',
|
||||
'agent.saveFail': 'Lưu thất bại',
|
||||
'agent.loadFail': 'Tải thất bại',
|
||||
'agent.pleaseInputAgentName': 'Vui lòng nhập tên đại lý',
|
||||
'agent.pleaseInputRoleDescription': 'Vui lòng nhập mô tả vai trò',
|
||||
'agent.pleaseSelect': 'Vui lòng chọn',
|
||||
|
||||
// Trang lịch sử trò chuyện
|
||||
'chatHistory.getChatSessions': 'Lấy danh sách phiên trò chuyện',
|
||||
'chatHistory.noSelectedAgent': 'Chưa chọn đại lý',
|
||||
'chatHistory.getChatSessionsFailed': 'Không thể lấy danh sách phiên trò chuyện:',
|
||||
'chatHistory.unknownTime': 'Thời gian không xác định',
|
||||
'chatHistory.justNow': 'Vừa xong',
|
||||
'chatHistory.minutesAgo': '{minutes} phút trước',
|
||||
'chatHistory.hoursAgo': '{hours} giờ trước',
|
||||
'chatHistory.daysAgo': '{days} ngày trước',
|
||||
'chatHistory.conversationRecord': 'Bản ghi trò chuyện',
|
||||
'chatHistory.totalChats': 'Tổng cộng {count} cuộc trò chuyện',
|
||||
'chatHistory.loading': 'Đang tải...',
|
||||
'chatHistory.noMoreData': 'Không còn dữ liệu',
|
||||
'chatHistory.noChatRecords': 'Không có bản ghi trò chuyện',
|
||||
'chatHistory.chatRecordsDescription': 'Bản ghi trò chuyện với đại lý sẽ hiển thị ở đây',
|
||||
// Trang chi tiết lịch sử trò chuyện
|
||||
'chatHistory.pageTitle': 'Chi tiết trò chuyện',
|
||||
'chatHistory.assistantName': 'Trợ lý thông minh',
|
||||
'chatHistory.userName': 'Người dùng',
|
||||
'chatHistory.aiAssistantName': 'Trợ lý AI',
|
||||
'chatHistory.loadFailed': 'Không thể tải lịch sử trò chuyện',
|
||||
'chatHistory.parameterError': 'Lỗi tham số trang',
|
||||
'chatHistory.invalidAudioId': 'ID âm thanh không hợp lệ',
|
||||
'chatHistory.audioPlayFailed': 'Phát âm thanh thất bại',
|
||||
'chatHistory.playAudioFailed': 'Không thể phát âm thanh',
|
||||
|
||||
// Trang quản lý thiết bị
|
||||
'device.pageTitle': 'Quản lý thiết bị',
|
||||
'device.noDevices': 'Không có thiết bị nào',
|
||||
'device.macAddress': 'Địa chỉ MAC',
|
||||
'device.firmwareVersion': 'Phiên bản firmware',
|
||||
'device.lastConnected': 'Cuộc trò chuyện cuối',
|
||||
'device.otaUpdate': 'Cập nhật OTA',
|
||||
'device.unbind': 'Hủy liên kết',
|
||||
'device.confirmUnbind': 'Xác nhận',
|
||||
'device.bindDevice': 'Liên kết thiết bị mới',
|
||||
'device.deviceType': 'Loại thiết bị',
|
||||
'device.loading': 'Đang tải...',
|
||||
'device.neverConnected': 'Chưa kết nối',
|
||||
'device.justNow': 'Vừa xong',
|
||||
'device.minutesAgo': '{minutes} phút trước',
|
||||
'device.hoursAgo': '{hours} giờ trước',
|
||||
'device.daysAgo': '{days} ngày trước',
|
||||
'device.otaAutoUpdateEnabled': 'Đã bật cập nhật OTA tự động',
|
||||
'device.otaAutoUpdateDisabled': 'Đã tắt cập nhật OTA tự động',
|
||||
'device.operationFailed': 'Thao tác thất bại, vui lòng thử lại',
|
||||
'device.deviceUnbound': 'Đã hủy liên kết thiết bị',
|
||||
'device.unbindFailed': 'Hủy liên kết thất bại, vui lòng thử lại',
|
||||
'device.unbindDevice': 'Hủy liên kết thiết bị',
|
||||
'device.confirmUnbindDevice': 'Bạn có chắc chắn muốn hủy liên kết thiết bị "{macAddress}"?',
|
||||
'device.cancel': 'Hủy',
|
||||
'device.noDevice': 'Không có thiết bị',
|
||||
'device.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước',
|
||||
'device.deviceBindSuccess': 'Liên kết thiết bị thành công!',
|
||||
'device.bindFailed': 'Liên kết thất bại, vui lòng kiểm tra mã xác minh có đúng không',
|
||||
'device.enterDeviceCode': 'Vui lòng nhập mã xác minh thiết bị',
|
||||
'device.bindNow': 'Liên kết ngay',
|
||||
'device.lastConnection': 'Kết nối cuối',
|
||||
'device.clickToBindFirstDevice': 'Nhấp vào nút + ở góc dưới bên phải để liên kết thiết bị đầu tiên của bạn',
|
||||
|
||||
// Chung
|
||||
'common.success': 'Thành công',
|
||||
'common.fail': 'Thất bại',
|
||||
'common.loading': 'Đang tải...',
|
||||
'common.confirm': 'Xác nhận',
|
||||
'common.cancel': 'Hủy',
|
||||
'common.delete': 'Xóa',
|
||||
'common.edit': 'Chỉnh sửa',
|
||||
'common.add': 'Thêm',
|
||||
'common.pleaseSelect': 'Vui lòng chọn',
|
||||
'common.unknownError': 'Lỗi không xác định',
|
||||
'common.networkError': 'Lỗi mạng',
|
||||
|
||||
// Trang khôi phục mật khẩu
|
||||
'retrievePassword.title': 'Đặt lại mật khẩu',
|
||||
'retrievePassword.subtitle': 'Khôi phục mật khẩu tài khoản qua số điện thoại',
|
||||
'retrievePassword.mobileRequired': 'Vui lòng nhập số điện thoại',
|
||||
'retrievePassword.inputCorrectMobile': 'Vui lòng nhập số điện thoại hợp lệ',
|
||||
'retrievePassword.captchaRequired': 'Vui lòng nhập mã xác minh đồ họa',
|
||||
'retrievePassword.mobileCaptchaRequired': 'Vui lòng nhập mã xác minh SMS',
|
||||
'retrievePassword.newPasswordRequired': 'Vui lòng nhập mật khẩu mới',
|
||||
'retrievePassword.confirmNewPasswordRequired': 'Vui lòng xác nhận mật khẩu mới',
|
||||
'retrievePassword.passwordsNotMatch': 'Mật khẩu không khớp',
|
||||
'retrievePassword.mobilePlaceholder': 'Vui lòng nhập số điện thoại',
|
||||
'retrievePassword.captchaPlaceholder': 'Vui lòng nhập mã xác minh đồ họa',
|
||||
'retrievePassword.mobileCaptchaPlaceholder': 'Vui lòng nhập mã xác minh SMS',
|
||||
'retrievePassword.newPasswordPlaceholder': 'Vui lòng nhập mật khẩu mới',
|
||||
'retrievePassword.confirmNewPasswordPlaceholder': 'Vui lòng xác nhận mật khẩu mới',
|
||||
'retrievePassword.getMobileCaptcha': 'Lấy mã',
|
||||
'retrievePassword.captchaSendSuccess': 'Đã gửi mã xác minh thành công',
|
||||
'retrievePassword.passwordUpdateSuccess': 'Đặt lại mật khẩu thành công',
|
||||
'retrievePassword.resetButton': 'Đặt lại mật khẩu',
|
||||
'retrievePassword.goToLogin': 'Quay lại đăng nhập',
|
||||
|
||||
// Thông báo lỗi liên quan đến mã hóa SM2
|
||||
'sm2.publicKeyNotConfigured': 'Khóa công khai SM2 chưa được cấu hình, vui lòng liên hệ quản trị viên',
|
||||
'sm2.encryptionFailed': 'Mã hóa mật khẩu thất bại',
|
||||
'sm2.keyGenerationFailed': 'Tạo cặp khóa thất bại',
|
||||
'sm2.invalidPublicKey': 'Định dạng khóa công khai không hợp lệ',
|
||||
'sm2.encryptionError': 'Đã xảy ra lỗi khi mã hóa',
|
||||
'sm2.publicKeyRetry': 'Đang thử lấy lại khóa công khai...',
|
||||
'sm2.publicKeyRetryFailed': 'Thử lấy lại khóa công khai thất bại',
|
||||
|
||||
// Trang dấu giọng nói
|
||||
'voiceprint.noSelectedAgent': 'Chưa chọn đại lý',
|
||||
'voiceprint.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước',
|
||||
'voiceprint.fetchHistoryFailed': 'Không thể tải lịch sử trò chuyện',
|
||||
'voiceprint.clickToSelectVector': 'Nhấp để chọn vector dấu giọng nói',
|
||||
'voiceprint.pleaseInputName': 'Vui lòng nhập tên',
|
||||
'voiceprint.pleaseSelectVector': 'Vui lòng chọn vector dấu giọng nói',
|
||||
'voiceprint.addSuccess': 'Thêm thành công',
|
||||
'voiceprint.addFailed': 'Thêm người nói thất bại',
|
||||
'voiceprint.editSuccess': 'Chỉnh sửa thành công',
|
||||
'voiceprint.editFailed': 'Chỉnh sửa người nói thất bại',
|
||||
'voiceprint.deleteConfirmMsg': 'Bạn có chắc chắn muốn xóa người nói này?',
|
||||
'voiceprint.deleteConfirmTitle': 'Xác nhận xóa',
|
||||
'voiceprint.deleteSuccess': 'Xóa thành công',
|
||||
'voiceprint.loading': 'Đang tải...',
|
||||
'voiceprint.delete': 'Xóa',
|
||||
'voiceprint.emptyTitle': 'Không có dữ liệu dấu giọng nói',
|
||||
'voiceprint.emptyDesc': 'Nhấp vào nút + ở góc dưới bên phải để thêm người nói đầu tiên của bạn',
|
||||
'voiceprint.addSpeaker': 'Thêm người nói',
|
||||
'voiceprint.voiceVector': 'Vector dấu giọng nói',
|
||||
'voiceprint.name': 'Tên',
|
||||
'voiceprint.description': 'Mô tả',
|
||||
'voiceprint.pleaseInputDescription': 'Vui lòng nhập mô tả',
|
||||
'voiceprint.cancel': 'Hủy',
|
||||
'voiceprint.save': 'Lưu',
|
||||
'voiceprint.editSpeaker': 'Chỉnh sửa người nói',
|
||||
'voiceprint.selectVector': 'Chọn vector dấu giọng nói',
|
||||
'voiceprint.voiceprintInterfaceNotConfigured': 'Giao diện dấu giọng nói chưa được cấu hình',
|
||||
|
||||
// Trang cài đặt
|
||||
'settings.pageTitle': 'Cài đặt',
|
||||
'settings.navigationTitle': 'Cài đặt',
|
||||
'settings.networkSettings': 'Cài đặt mạng',
|
||||
'settings.serverApiUrl': 'URL API máy chủ',
|
||||
'settings.validServerUrl': 'Vui lòng nhập địa chỉ máy chủ hợp lệ (bắt đầu bằng http hoặc https và kết thúc bằng /xiaozhi)',
|
||||
'settings.saveSettings': 'Lưu cài đặt',
|
||||
'settings.resetDefault': 'Đặt lại mặc định',
|
||||
'settings.restartApp': 'Khởi động lại ứng dụng',
|
||||
'settings.restartNow': 'Khởi động lại ngay',
|
||||
'settings.restartLater': 'Để sau',
|
||||
// Về chúng tôi
|
||||
'settings.aboutApp': 'Về Bảng điều khiển XiaoZhi',
|
||||
'settings.aboutContent': 'Bảng điều khiển XiaoZhi\n\nỨng dụng quản lý di động đa nền tảng được xây dựng với Vue.js 3 + uni-app, cung cấp quản lý thiết bị, cấu hình đại lý và các chức năng khác cho phần cứng thông minh xiaozhi ESP32.\n\n© 2025 xiaozhi-esp32-server {version}',
|
||||
'settings.restartSuccess': 'Đã lưu, bạn có thể tự khởi động lại ứng dụng sau',
|
||||
'settings.serverUrlSavedAndCacheCleared': 'Đã lưu URL máy chủ và xóa bộ nhớ cache',
|
||||
'settings.resetToDefaultAndCacheCleared': 'Đã đặt lại mặc định và xóa bộ nhớ cache',
|
||||
'settings.resetSuccess': 'Đặt lại thành công',
|
||||
'settings.enterServerUrl': 'Vui lòng nhập URL máy chủ',
|
||||
'settings.clearCacheFailed': 'Không thể xóa bộ nhớ cache',
|
||||
'settings.cacheManagement': 'Quản lý bộ nhớ cache',
|
||||
'settings.totalCacheSize': 'Tổng kích thước bộ nhớ cache',
|
||||
'settings.appDataSize': 'Tổng kích thước dữ liệu ứng dụng',
|
||||
'settings.cacheClear': 'Xóa bộ nhớ cache',
|
||||
'settings.clearAllCache': 'Xóa tất cả dữ liệu bộ nhớ cache',
|
||||
'settings.clearCache': 'Xóa bộ nhớ cache',
|
||||
'settings.modifyWillClearCache': 'Thay đổi sẽ xóa bộ nhớ cache',
|
||||
'settings.appInfo': 'Thông tin ứng dụng',
|
||||
'settings.aboutUs': 'Về chúng tôi',
|
||||
'settings.appVersion': 'Phiên bản ứng dụng & Thông tin nhóm',
|
||||
'settings.confirmClear': 'Xác nhận xóa',
|
||||
'settings.confirmClearMessage': 'Bạn có chắc chắn muốn xóa toàn bộ bộ nhớ cache? Điều này sẽ xóa tất cả dữ liệu bao gồm trạng thái đăng nhập và yêu cầu đăng nhập lại.',
|
||||
'settings.cacheCleared': 'Đã xóa bộ nhớ cache thành công, đang chuyển hướng đến trang đăng nhập',
|
||||
'settings.languageSettings': 'Cài đặt ngôn ngữ',
|
||||
'settings.language': 'Ngôn ngữ',
|
||||
'settings.selectLanguage': 'Chọn ngôn ngữ',
|
||||
'settings.languageChanged': 'Đã thay đổi ngôn ngữ thành công',
|
||||
|
||||
// Thông báo
|
||||
'message.loginSuccess': 'Đăng nhập thành công!',
|
||||
'message.loginFail': 'Đăng nhập thất bại',
|
||||
'message.registerSuccess': 'Đăng ký thành công',
|
||||
'message.registerFail': 'Đăng ký thất bại',
|
||||
'message.saveSuccess': 'Lưu thành công',
|
||||
'message.saveFail': 'Lưu thất bại',
|
||||
'message.deleteSuccess': 'Xóa thành công',
|
||||
'message.deleteFail': 'Xóa thất bại',
|
||||
'message.bindSuccess': 'Liên kết thành công',
|
||||
'message.bindFail': 'Liên kết thất bại',
|
||||
'message.unbindSuccess': 'Hủy liên kết thành công',
|
||||
'message.unbindFail': 'Hủy liên kết thất bại',
|
||||
'message.networkError': 'Lỗi mạng, vui lòng kiểm tra kết nối',
|
||||
'message.serverError': 'Lỗi máy chủ, vui lòng thử lại sau',
|
||||
'message.invalidAddress': 'Địa chỉ không hợp lệ, vui lòng kiểm tra máy chủ đã khởi động hoặc kết nối mạng bình thường',
|
||||
'message.languageChanged': 'Đã thay đổi ngôn ngữ',
|
||||
'message.passwordError': 'Lỗi tài khoản hoặc mật khẩu',
|
||||
'message.phoneRegistered': 'Số điện thoại này đã được đăng ký',
|
||||
|
||||
// Trang công cụ đại lý
|
||||
'agent.tools.pageTitle': 'Công cụ đại lý',
|
||||
'agent.tools.unselected': 'Chưa chọn',
|
||||
'agent.tools.selected': 'Đã chọn',
|
||||
'agent.tools.noMorePlugins': 'Không còn plugin',
|
||||
'agent.tools.pleaseSelectPlugin': 'Vui lòng chọn chức năng plugin',
|
||||
'agent.tools.builtInPlugins': 'Plugin tích hợp',
|
||||
'agent.tools.mcpAccessPoint': 'Điểm truy cập MCP',
|
||||
'agent.tools.copy': 'Sao chép',
|
||||
'agent.tools.noTools': 'Không có công cụ nào',
|
||||
'agent.tools.parameterConfig': 'Cấu hình tham số',
|
||||
'agent.tools.noParamsNeeded': 'Không cần tham số',
|
||||
'agent.tools.pleaseInput': 'Vui lòng nhập',
|
||||
'agent.tools.inputOneItemPerLine': 'Nhập một mục mỗi dòng',
|
||||
'agent.tools.pleaseInputValidJson': 'Vui lòng nhập định dạng JSON hợp lệ',
|
||||
'agent.tools.enableFunction': 'Bật chức năng',
|
||||
'agent.tools.toggleFunction': 'Bật hoặc tắt chức năng này',
|
||||
'agent.tools.jsonFormatError': 'Lỗi định dạng JSON',
|
||||
'agent.tools.noMcpAddressToCopy': 'Không có địa chỉ MCP để sao chép',
|
||||
'agent.tools.mcpAddressCopied': 'Đã sao chép địa chỉ MCP vào bộ nhớ tạm',
|
||||
'agent.tools.copyFailed': 'Sao chép thất bại, vui lòng thử lại',
|
||||
'agent.tools.defaultValue': 'Giá trị mặc định',
|
||||
'agent.tools.notSelected': 'Chưa chọn',
|
||||
'agent.tools.clickToConfigure': 'Nhấp để cấu hình',
|
||||
'agent.tools.mcpEndpoint': 'Điểm cuối MCP',
|
||||
'agent.tools.eachLineOneItem': 'Nhập một mục mỗi dòng',
|
||||
|
||||
// Trang cấu hình thiết bị
|
||||
'deviceConfig.pageTitle': 'Cấu hình thiết bị',
|
||||
'deviceConfig.wifiConfig': 'Cấu hình WiFi',
|
||||
'deviceConfig.ultrasonicConfig': 'Cấu hình siêu âm',
|
||||
'deviceConfig.selectConfigMethod': 'Chọn phương pháp cấu hình',
|
||||
'deviceConfig.networkConfig': 'Cấu hình mạng',
|
||||
'deviceConfig.selectedNetwork': 'Mạng đã chọn',
|
||||
'deviceConfig.signal': 'Tín hiệu',
|
||||
'deviceConfig.openNetwork': 'Mạng mở',
|
||||
'deviceConfig.encryptedNetwork': 'Mạng mã hóa',
|
||||
'deviceConfig.password': 'Mật khẩu',
|
||||
'deviceConfig.pleaseEnterPassword': 'Vui lòng nhập mật khẩu WiFi',
|
||||
'deviceConfig.startConfig': 'Bắt đầu cấu hình',
|
||||
'deviceConfig.connectToXiaozhiHotspot': 'Vui lòng kết nối với điểm phát sóng xiaozhi trước',
|
||||
'deviceConfig.detecting': 'Đang phát hiện...',
|
||||
'deviceConfig.reDetect': 'Phát hiện lại',
|
||||
'deviceConfig.alreadyConnected': 'Đã kết nối với điểm phát sóng xiaozhi',
|
||||
'deviceConfig.refreshStatus': 'Làm mới trạng thái',
|
||||
'deviceConfig.wifiNetworks': 'Mạng WiFi',
|
||||
'deviceConfig.selectWifiNetwork': 'Chọn mạng WiFi',
|
||||
'deviceConfig.refreshScan': 'Làm mới quét',
|
||||
'deviceConfig.noWifiNetworks': 'Không có mạng WiFi nào',
|
||||
'deviceConfig.clickToRefreshScan': 'Vui lòng nhấp Làm mới quét',
|
||||
'deviceConfig.signalStrong': 'Tín hiệu mạnh',
|
||||
'deviceConfig.signalGood': 'Tín hiệu tốt',
|
||||
'deviceConfig.signalFair': 'Tín hiệu trung bình',
|
||||
'deviceConfig.signalWeak': 'Tín hiệu yếu',
|
||||
'deviceConfig.channel': 'Kênh',
|
||||
'deviceConfig.about': 'khoảng',
|
||||
'deviceConfig.seconds': 'giây',
|
||||
'deviceConfig.generating': 'Đang tạo...',
|
||||
'deviceConfig.playing': 'Đang phát...',
|
||||
'deviceConfig.generateAndPlaySoundWave': 'Tạo và phát sóng âm',
|
||||
'deviceConfig.playSoundWave': 'Phát sóng âm',
|
||||
'deviceConfig.stopPlaying': 'Dừng phát',
|
||||
'deviceConfig.autoLoopPlaySoundWave': 'Tự động lặp phát sóng âm',
|
||||
'deviceConfig.configAudioFile': 'Tệp âm thanh cấu hình',
|
||||
'deviceConfig.duration': 'Thời lượng',
|
||||
'deviceConfig.ultrasonicConfigInstructions': 'Hướng dẫn cấu hình siêu âm',
|
||||
'deviceConfig.ensureWifiNetworkSelectedAndPasswordEntered': 'Đảm bảo mạng WiFi được chọn và mật khẩu đã nhập',
|
||||
'deviceConfig.clickGenerateAndPlaySoundWave': 'Nhấp Tạo và phát sóng âm, hệ thống sẽ mã hóa thông tin cấu hình thành âm thanh',
|
||||
'deviceConfig.bringPhoneCloseToXiaozhiDevice': 'Đưa điện thoại lại gần thiết bị xiaozhi (khoảng cách 1-2 mét)',
|
||||
'deviceConfig.duringAudioPlaybackXiaozhiWillReceive': 'Trong khi phát âm thanh, xiaozhi sẽ nhận và giải mã thông tin cấu hình',
|
||||
'deviceConfig.afterConfigSuccessDeviceWillConnect': 'Sau khi cấu hình thành công, thiết bị sẽ tự động kết nối với mạng WiFi',
|
||||
'deviceConfig.usesAfskModulation': 'Sử dụng công nghệ điều chế AFSK, truyền dữ liệu qua tần số 1800Hz và 1500Hz',
|
||||
'deviceConfig.ensureModeratePhoneVolume': 'Vui lòng đảm bảo âm lượng điện thoại vừa phải để tránh nhiễu tiếng ồn môi trường',
|
||||
'deviceConfig.generatingUltrasonicConfigAudio': 'Đang tạo âm thanh cấu hình siêu âm',
|
||||
'deviceConfig.configData': 'Dữ liệu cấu hình',
|
||||
'deviceConfig.dataBytesLength': 'Độ dài byte dữ liệu',
|
||||
'deviceConfig.bitStreamLength': 'Độ dài luồng bit',
|
||||
'deviceConfig.base64Length': 'Độ dài base64',
|
||||
'deviceConfig.audioFileTooLarge': 'Tệp âm thanh quá lớn, vui lòng rút ngắn SSID hoặc độ dài mật khẩu',
|
||||
'deviceConfig.audioGenerationSuccess': 'Tạo âm thanh thành công',
|
||||
'deviceConfig.samplePoints': 'Điểm mẫu',
|
||||
'deviceConfig.soundWaveGenerationSuccess': 'Tạo sóng âm thành công',
|
||||
'deviceConfig.audioGenerationFailed': 'Tạo âm thanh thất bại',
|
||||
'deviceConfig.soundWaveGenerationFailed': 'Tạo sóng âm thất bại',
|
||||
'deviceConfig.pleaseGenerateAudioFirst': 'Vui lòng tạo âm thanh trước',
|
||||
'deviceConfig.startPlayingUltrasonicConfigAudio': 'Bắt đầu phát âm thanh cấu hình siêu âm',
|
||||
'deviceConfig.ultrasonicAudioStartedPlaying': 'Đã bắt đầu phát âm thanh siêu âm',
|
||||
'deviceConfig.startPlayingConfigSoundWave': 'Đã bắt đầu phát sóng âm cấu hình',
|
||||
'deviceConfig.ultrasonicAudioPlaybackEnded': 'Kết thúc phát âm thanh siêu âm',
|
||||
'deviceConfig.audioPlaybackFailed': 'Phát âm thanh thất bại',
|
||||
'deviceConfig.audioResourceBusy': 'Tài nguyên âm thanh bận, vui lòng thử lại sau',
|
||||
'deviceConfig.audioFormatNotSupported': 'Định dạng âm thanh không được hỗ trợ, có thể là vấn đề URI dữ liệu',
|
||||
'deviceConfig.audioFileError': 'Lỗi tệp âm thanh',
|
||||
'deviceConfig.cleaningUpAudioContext': 'Đang dọn dẹp ngữ cảnh âm thanh',
|
||||
'deviceConfig.cleaningUpAudioContextFailed': 'Không thể dọn dẹp ngữ cảnh âm thanh',
|
||||
'deviceConfig.stoppedPlayingUltrasonicAudio': 'Đã dừng phát âm thanh siêu âm',
|
||||
'deviceConfig.stoppedPlaying': 'Đã dừng phát',
|
||||
'deviceConfig.configMethod': 'Phương pháp cấu hình',
|
||||
'deviceConfig.enterWifiPassword': 'Vui lòng nhập mật khẩu WiFi',
|
||||
'deviceConfig.xiaozhi': 'xiaozhi',
|
||||
'deviceConfig.connectXiaozhiHotspot': 'Vui lòng kết nối với điểm phát sóng xiaozhi',
|
||||
'deviceConfig.wifiScanResponse': 'Phản hồi quét WiFi',
|
||||
'deviceConfig.scanSuccess': 'Quét thành công',
|
||||
'deviceConfig.networks': 'mạng',
|
||||
'deviceConfig.wifiScanFailed': 'Quét WiFi thất bại',
|
||||
'deviceConfig.scanFailedCheckConnection': 'Quét thất bại, vui lòng kiểm tra kết nối',
|
||||
'deviceConfig.checking': 'Đang kiểm tra',
|
||||
'deviceConfig.reCheck': 'Kiểm tra lại',
|
||||
'deviceConfig.connectedXiaozhiHotspot': 'Đã kết nối với điểm phát sóng xiaozhi',
|
||||
'deviceConfig.wifiNetwork': 'Mạng WiFi',
|
||||
'deviceConfig.scanning': 'Đang quét',
|
||||
'deviceConfig.cancel': 'Hủy',
|
||||
'deviceConfig.clickRefreshScan': 'Vui lòng nhấp Làm mới quét',
|
||||
'deviceConfig.esp32ConnectionCheckFailed': 'Kiểm tra kết nối ESP32 thất bại',
|
||||
'deviceConfig.startWifiConfig': 'Đang bắt đầu cấu hình WiFi',
|
||||
'deviceConfig.configSuccess': 'Cấu hình thành công',
|
||||
'deviceConfig.deviceWillConnectTo': 'Thiết bị sẽ kết nối với',
|
||||
'deviceConfig.deviceWillRestart': 'Thiết bị sẽ khởi động lại',
|
||||
'deviceConfig.pleaseDisconnectXiaozhiHotspot': 'Vui lòng ngắt kết nối khỏi điểm phát sóng xiaozhi',
|
||||
'deviceConfig.configFailed': 'Cấu hình thất bại',
|
||||
'deviceConfig.wifiConfigFailed': 'Cấu hình WiFi thất bại',
|
||||
'deviceConfig.pleaseCheckNetworkConnection': 'Vui lòng kiểm tra kết nối mạng',
|
||||
'deviceConfig.startWifiConfigButton': 'Bắt đầu cấu hình',
|
||||
'deviceConfig.wifiConfigInstructions': 'Hướng dẫn cấu hình WiFi',
|
||||
'deviceConfig.phoneConnectXiaozhiHotspot': 'Điện thoại kết nối với điểm phát sóng xiaozhi',
|
||||
'deviceConfig.selectTargetWifiNetwork': 'Chọn mạng WiFi mục tiêu',
|
||||
'deviceConfig.enterWifiPasswordIfNeeded': 'Nhập mật khẩu WiFi nếu cần',
|
||||
'deviceConfig.clickStartConfigAndWait': 'Nhấp Bắt đầu cấu hình và chờ',
|
||||
'deviceConfig.afterConfigSuccessDeviceWillRestart': 'Sau khi cấu hình thành công, thiết bị sẽ tự động khởi động lại',
|
||||
'deviceConfig.audioPlaybackError': 'Lỗi phát âm thanh',
|
||||
'deviceConfig.playbackFailed': 'Phát thất bại',
|
||||
}
|
||||
|
|
@ -46,13 +46,9 @@ export default {
|
|||
'retrievePassword.mobileCaptchaPlaceholder': '請輸入手機驗證碼',
|
||||
'retrievePassword.newPasswordPlaceholder': '請輸入新密碼',
|
||||
'retrievePassword.confirmNewPasswordPlaceholder': '請確認新密碼',
|
||||
'retrievePassword.confirmPasswordPlaceholder': '請確認新密碼',
|
||||
'retrievePassword.captchaSendSuccess': '驗證碼發送成功',
|
||||
'retrievePassword.passwordUpdateSuccess': '密碼更新成功',
|
||||
'retrievePassword.getCaptcha': '獲取驗證碼',
|
||||
'retrievePassword.getMobileCaptcha': '獲取驗證碼',
|
||||
'retrievePassword.resend': '重新發送',
|
||||
'retrievePassword.resetPasswordButton': '重置密碼',
|
||||
'retrievePassword.captchaSendSuccess': '驗證碼發送成功',
|
||||
'retrievePassword.passwordUpdateSuccess': '密碼重置成功',
|
||||
'retrievePassword.resetButton': '重置密碼',
|
||||
'retrievePassword.goToLogin': '返回登錄',
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
import { ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
|
||||
// 支持的语言类型
|
||||
export type Language = 'zh_CN' | 'en' | 'zh_TW'
|
||||
export type Language = 'zh_CN' | 'en' | 'zh_TW' | 'de' | 'vi'
|
||||
|
||||
export interface LangStore {
|
||||
currentLang: Language
|
||||
|
|
|
|||
|
|
@ -200,6 +200,13 @@ export default {
|
|||
confirm() {
|
||||
this.saving = true;
|
||||
|
||||
// 校验模型ID不能为纯文字或空格
|
||||
if (this.formData.id && !this.validateModelId(this.formData.id)) {
|
||||
this.$message.error(this.$t('modelConfigDialog.invalidModelId'));
|
||||
this.saving = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.formData.supplier) {
|
||||
this.$message.error(this.$t('addModelDialog.requiredSupplier'));
|
||||
this.saving = false;
|
||||
|
|
@ -254,6 +261,38 @@ export default {
|
|||
this.providerFields = [];
|
||||
this.currentProvider = null;
|
||||
},
|
||||
|
||||
// 校验模型ID:不能为纯文字或空格
|
||||
validateModelId(modelId) {
|
||||
if (!modelId || typeof modelId !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 去除首尾空格
|
||||
const trimmedId = modelId.trim();
|
||||
|
||||
// 检查是否为空或纯空格
|
||||
if (trimmedId === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否只包含字母(纯文字)
|
||||
if (/^[a-zA-Z]+$/.test(trimmedId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否包含空格
|
||||
if (/\s/.test(trimmedId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 允许字母、数字、下划线、连字符
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(trimmedId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -238,6 +238,10 @@ export default {
|
|||
return this.$t("language.zhTW");
|
||||
case "en":
|
||||
return this.$t("language.en");
|
||||
case "de":
|
||||
return this.$t("language.de");
|
||||
case "vi":
|
||||
return this.$t("language.vi");
|
||||
default:
|
||||
return this.$t("language.zhCN");
|
||||
}
|
||||
|
|
@ -261,6 +265,14 @@ export default {
|
|||
label: this.$t("language.en"),
|
||||
value: "en",
|
||||
},
|
||||
{
|
||||
label: this.$t("language.de"),
|
||||
value: "de",
|
||||
},
|
||||
{
|
||||
label: this.$t("language.vi"),
|
||||
value: "vi",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
1265
main/manager-web/src/i18n/de.js
Normal file
1265
main/manager-web/src/i18n/de.js
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -639,10 +639,12 @@ export default {
|
|||
'language.zhCN': '中文简体',
|
||||
'language.zhTW': '中文繁體',
|
||||
'language.en': 'English',
|
||||
'language.de': 'Deutsch',
|
||||
'language.vi': 'Tiếng Việt',
|
||||
|
||||
// Home page text
|
||||
'home.addAgent': 'Add Agent',
|
||||
'home.greeting': 'Hi Jarvis',
|
||||
'home.greeting': 'Hi XiaoZhi',
|
||||
'home.wish': "Let's have a wonderful day!",
|
||||
'home.languageModel': 'LLM',
|
||||
'home.voiceModel': 'TTS',
|
||||
|
|
@ -847,6 +849,7 @@ export default {
|
|||
'modelConfigDialog.setDefault': 'Set as Default',
|
||||
'modelConfigDialog.modelId': 'Model ID',
|
||||
'modelConfigDialog.enterModelId': 'If not filled in, it will be generated automatically',
|
||||
'modelConfigDialog.invalidModelId': 'Model ID cannot be pure text or spaces, please use letters, numbers, underscores, or hyphens',
|
||||
'modelConfigDialog.modelName': 'Model Name',
|
||||
'modelConfigDialog.enterModelName': 'Please enter model name',
|
||||
'modelConfigDialog.modelCode': 'Model Code',
|
||||
|
|
@ -992,7 +995,6 @@ export default {
|
|||
'agentTemplateManagement.templateName': 'Template Name',
|
||||
'agentTemplateManagement.action': 'Action',
|
||||
'agentTemplateManagement.createTemplate': 'Create Template',
|
||||
'templateQuickConfig.newTemplate': 'New Template',
|
||||
'agentTemplateManagement.editTemplate': 'Edit Template',
|
||||
'agentTemplateManagement.deleteTemplate': 'Delete Template',
|
||||
'agentTemplateManagement.deleteSuccess': 'Template deleted successfully',
|
||||
|
|
@ -1011,7 +1013,6 @@ export default {
|
|||
'agentTemplateManagement.deleteFailed': 'Template deletion failed',
|
||||
'agentTemplateManagement.batchDeleteFailed': 'Template batch deletion failed',
|
||||
'agentTemplateManagement.deleteBackendError': 'Deletion failed, please check if the backend service is normal',
|
||||
'agentTemplateManagement.deleteCancelled': 'Deletion cancelled',
|
||||
|
||||
// templateQuickConfig
|
||||
'templateQuickConfig.title': 'Module Quick Configuration',
|
||||
|
|
@ -1021,13 +1022,14 @@ export default {
|
|||
'templateQuickConfig.agentSettings.systemPromptPlaceholder': 'Please enter ntroduction',
|
||||
'templateQuickConfig.saveConfig': 'Save Configuration',
|
||||
'templateQuickConfig.resetConfig': 'Reset Configuration',
|
||||
'templateQuickConfig.configSaved': 'Configuration saved successfully',
|
||||
'templateQuickConfig.configReset': 'Configuration has been reset',
|
||||
'templateQuickConfig.saveSuccess': 'Configuration saved successfully',
|
||||
'templateQuickConfig.resetSuccess': 'Configuration reset successfully',
|
||||
'templateQuickConfig.confirmReset': 'Are you sure you want to reset the configuration?',
|
||||
'templateQuickConfig.saveFailed': 'Configuration save failed',
|
||||
'templateQuickConfig.confirm': 'Confirm',
|
||||
'templateQuickConfig.cancel': 'Cancel',
|
||||
'templateQuickConfig.templateNotFound': 'Template not found',
|
||||
'templateQuickConfig.newTemplate': 'New Template',
|
||||
'warning': 'Warning',
|
||||
'info': 'Info',
|
||||
'common.networkError': 'Network request failed',
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import VueI18n from 'vue-i18n';
|
|||
import zhCN from './zh_CN';
|
||||
import zhTW from './zh_TW';
|
||||
import en from './en';
|
||||
import de from './de';
|
||||
import vi from './vi';
|
||||
|
||||
Vue.use(VueI18n);
|
||||
|
||||
|
|
@ -19,6 +21,12 @@ const getDefaultLanguage = () => {
|
|||
}
|
||||
return 'zh_CN';
|
||||
}
|
||||
if (browserLang.indexOf('de') === 0) {
|
||||
return 'de';
|
||||
}
|
||||
if (browserLang.indexOf('vi') === 0) {
|
||||
return 'vi';
|
||||
}
|
||||
return 'en';
|
||||
};
|
||||
|
||||
|
|
@ -28,7 +36,9 @@ const i18n = new VueI18n({
|
|||
messages: {
|
||||
'zh_CN': zhCN,
|
||||
'zh_TW': zhTW,
|
||||
'en': en
|
||||
'en': en,
|
||||
'de': de,
|
||||
'vi': vi
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
1265
main/manager-web/src/i18n/vi.js
Normal file
1265
main/manager-web/src/i18n/vi.js
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -639,6 +639,8 @@ export default {
|
|||
'language.zhCN': '中文简体',
|
||||
'language.zhTW': '中文繁體',
|
||||
'language.en': 'English',
|
||||
'language.de': 'Deutsch',
|
||||
'language.vi': 'Tiếng Việt',
|
||||
|
||||
// 首页文本
|
||||
'home.addAgent': '添加智能体',
|
||||
|
|
@ -847,6 +849,7 @@ export default {
|
|||
'modelConfigDialog.setDefault': '设为默认',
|
||||
'modelConfigDialog.modelId': '模型ID',
|
||||
'modelConfigDialog.enterModelId': '未填写将自动生成模型ID',
|
||||
'modelConfigDialog.invalidModelId': '模型ID不能为纯文字或空格,请使用字母、数字、下划线或连字符组合',
|
||||
'modelConfigDialog.modelName': '模型名称',
|
||||
'modelConfigDialog.enterModelName': '请输入模型名称',
|
||||
'modelConfigDialog.modelCode': '模型编码',
|
||||
|
|
@ -991,8 +994,6 @@ export default {
|
|||
'agentTemplateManagement.title': '默认角色管理',
|
||||
'agentTemplateManagement.templateName': '模板名称',
|
||||
'agentTemplateManagement.action': '操作',
|
||||
'templateQuickConfig.saveSuccess': '配置保存成功',
|
||||
'templateQuickConfig.saveFailed': '配置保存失败',
|
||||
'agentTemplateManagement.createTemplate': '创建模板',
|
||||
'agentTemplateManagement.editTemplate': '编辑模板',
|
||||
'agentTemplateManagement.deleteTemplate': '删除模板',
|
||||
|
|
@ -1021,13 +1022,14 @@ export default {
|
|||
'templateQuickConfig.agentSettings.systemPromptPlaceholder': '请输入角色介绍',
|
||||
'templateQuickConfig.saveConfig': '保存配置',
|
||||
'templateQuickConfig.resetConfig': '重置配置',
|
||||
'templateQuickConfig.saveSuccess': '保存成功',
|
||||
'templateQuickConfig.resetSuccess': '重置成功',
|
||||
'templateQuickConfig.confirmReset': '确定要重置配置吗?',
|
||||
'templateQuickConfig.saveFailed': '配置保存失败',
|
||||
'templateQuickConfig.confirm': '确定',
|
||||
'templateQuickConfig.cancel': '取消',
|
||||
'templateQuickConfig.templateNotFound': '未找到指定模板',
|
||||
'templateQuickConfig.newTemplate': '新模板',
|
||||
'templateQuickConfig.saveSuccess': '保存成功',
|
||||
'templateQuickConfig.resetSuccess': '重置成功',
|
||||
'warning': '警告',
|
||||
'info': '提示',
|
||||
'common.networkError': '网络请求失败',
|
||||
|
|
|
|||
|
|
@ -639,6 +639,8 @@ export default {
|
|||
'language.zhCN': '中文简体',
|
||||
'language.zhTW': '中文繁體',
|
||||
'language.en': 'English',
|
||||
'language.de': 'Deutsch',
|
||||
'language.vi': 'Tiếng Việt',
|
||||
|
||||
// 首頁文本
|
||||
'home.addAgent': '添加智能體',
|
||||
|
|
@ -847,6 +849,7 @@ export default {
|
|||
'modelConfigDialog.setDefault': '設為默認',
|
||||
'modelConfigDialog.modelId': '模型ID',
|
||||
'modelConfigDialog.enterModelId': '未填冩將自動生成模型ID',
|
||||
'modelConfigDialog.invalidModelId': '模型ID不能為純文字或空格,請使用字母、數字、底線或連字符組合',
|
||||
'modelConfigDialog.modelName': '模型名稱',
|
||||
'modelConfigDialog.enterModelName': '請輸入模型名稱',
|
||||
'modelConfigDialog.modelCode': '模型編碼',
|
||||
|
|
@ -992,6 +995,7 @@ export default {
|
|||
'agentTemplateManagement.templateName': '模板名稱',
|
||||
'agentTemplateManagement.action': '操作',
|
||||
'templateQuickConfig.saveSuccess': '配置保存成功',
|
||||
'templateQuickConfig.resetSuccess': '配置重置成功',
|
||||
'templateQuickConfig.saveFailed': '配置保存失敗',
|
||||
'agentTemplateManagement.createTemplate': '建立模板',
|
||||
'agentTemplateManagement.editTemplate': '編輯模板',
|
||||
|
|
@ -1021,8 +1025,6 @@ export default {
|
|||
'templateQuickConfig.agentSettings.systemPromptPlaceholder': '請輸入角色介紹',
|
||||
'templateQuickConfig.saveConfig': '保存配置',
|
||||
'templateQuickConfig.resetConfig': '重置配置',
|
||||
'templateQuickConfig.configSaved': '配置保存成功',
|
||||
'templateQuickConfig.configReset': '配置已重置',
|
||||
'templateQuickConfig.confirmReset': '確定要重置配置嗎?',
|
||||
'templateQuickConfig.confirm': '確定',
|
||||
'templateQuickConfig.cancel': '取消',
|
||||
|
|
|
|||
|
|
@ -15,4 +15,8 @@ select:-webkit-autofill:focus {
|
|||
|
||||
.el-footer {
|
||||
height: 35px !important; /* 使用 !important 确保覆盖默认样式 */
|
||||
}
|
||||
|
||||
.el-icon-video-play, .el-icon-video-pause {
|
||||
font-size: 18px !important;
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@
|
|||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column :label="$t('voiceClone.Details')" align="center" width="80">
|
||||
<el-table-column :label="$t('voiceClone.Details')" align="center" width="120">
|
||||
<template slot-scope="scope">
|
||||
<el-tooltip :content="getTooltipContent(scope.row)" placement="top">
|
||||
<el-button size="mini" type="text" icon="el-icon-info"
|
||||
|
|
|
|||
|
|
@ -21,6 +21,8 @@
|
|||
font-size: 25px;
|
||||
text-align: left;
|
||||
color: #3d4566;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.login-welcome {
|
||||
|
|
@ -36,11 +38,11 @@
|
|||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
right: 18%;
|
||||
right: 15%;
|
||||
background-color: #fff;
|
||||
border-radius: 20px;
|
||||
padding: 35px 0;
|
||||
width: 450px;
|
||||
width: 550px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -49,6 +49,12 @@
|
|||
<el-dropdown-item @click.native="changeLanguage('en')">
|
||||
{{ $t("language.en") }}
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item @click.native="changeLanguage('de')">
|
||||
{{ $t("language.de") }}
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item @click.native="changeLanguage('vi')">
|
||||
{{ $t("language.vi") }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
|
|
@ -177,6 +183,10 @@ export default {
|
|||
return this.$t("language.zhTW");
|
||||
case "en":
|
||||
return this.$t("language.en");
|
||||
case "de":
|
||||
return this.$t("language.de");
|
||||
case "vi":
|
||||
return this.$t("language.vi");
|
||||
default:
|
||||
return this.$t("language.zhCN");
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
10
main/xiaozhi-server/.claude/settings.local.json
Normal file
10
main/xiaozhi-server/.claude/settings.local.json
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(tree:*)",
|
||||
"Bash(find:*)"
|
||||
],
|
||||
"deny": [],
|
||||
"ask": []
|
||||
}
|
||||
}
|
||||
|
|
@ -56,6 +56,7 @@
|
|||
3. **洞察需求:** 结合上下文**深入理解用户真实意图**后再决定调用,避免无意义调用。
|
||||
4. **独立任务:** 除`<context>`已涵盖信息外,用户每个要求(即使相似)都视为**独立任务**,需调用工具获取最新数据,**不可偷懒复用历史结果**。
|
||||
5. **不确定时:** **切勿猜测或编造答案**。若不确定相关操作,可引导用户澄清或告知能力限制。
|
||||
6. **多工具调用:** 当用户要求执行多个任务时,你会调用多个工具(数量不定)。**重要:在获取到所有工具结果后,你必须依次总结每个工具的查询结果**,不要遗漏任何一个。例如用户问"设备当前状态,某某地方的天气和社会新闻",你要先说设备状态,再说天气情况,最后说新闻内容。
|
||||
- **重要例外(无需调用):**
|
||||
- `查询"现在的时间"、"今天的日期/星期几"、"今天农历"、"{{local_address}}的天气/未来天气"` -> **直接使用`<context>`信息回复**。
|
||||
- **需要调用的情况(示例):**
|
||||
|
|
|
|||
|
|
@ -487,8 +487,7 @@ LLM:
|
|||
temperature: 0.7
|
||||
max_tokens: 500 # Maximum number of generated tokens
|
||||
top_p: 1
|
||||
top_k: 50
|
||||
frequency_penalty: 0 # frequency penalty
|
||||
frequency_penalty: 0 # 频率惩罚
|
||||
AliAppLLM:
|
||||
# Define LLM API type
|
||||
type: AliBL
|
||||
|
|
|
|||
|
|
@ -723,11 +723,12 @@ class ConnectionHandler:
|
|||
self.dialogue.update_system_message(self.prompt)
|
||||
|
||||
def chat(self, query, depth=0):
|
||||
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
|
||||
self.llm_finish_task = False
|
||||
if query is not None:
|
||||
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
|
||||
|
||||
# 为最顶层时新建会话ID和发送FIRST请求
|
||||
if depth == 0:
|
||||
self.llm_finish_task = False
|
||||
self.sentence_id = str(uuid.uuid4().hex)
|
||||
self.dialogue.put(Message(role="user", content=query))
|
||||
self.tts.tts_text_queue.put(
|
||||
|
|
@ -738,9 +739,23 @@ class ConnectionHandler:
|
|||
)
|
||||
)
|
||||
|
||||
# 设置最大递归深度,避免无限循环,可根据实际需求调整
|
||||
MAX_DEPTH = 5
|
||||
force_final_answer = False # 标记是否强制最终回答
|
||||
|
||||
if depth >= MAX_DEPTH:
|
||||
self.logger.bind(tag=TAG).debug(f"已达到最大工具调用深度 {MAX_DEPTH},将强制基于现有信息回答")
|
||||
force_final_answer = True
|
||||
# 添加系统指令,要求 LLM 基于现有信息回答
|
||||
self.dialogue.put(Message(
|
||||
role="user",
|
||||
content="[系统提示] 已达到最大工具调用次数限制,请你基于目前已经获取的所有信息,直接给出最终答案。不要再尝试调用任何工具。"
|
||||
))
|
||||
|
||||
# Define intent functions
|
||||
functions = None
|
||||
if self.intent_type == "function_call" and hasattr(self, "func_handler"):
|
||||
# 达到最大深度时,禁用工具调用,强制 LLM 直接回答
|
||||
if self.intent_type == "function_call" and hasattr(self, "func_handler") and not force_final_answer:
|
||||
functions = self.func_handler.get_functions()
|
||||
response_message = []
|
||||
|
||||
|
|
@ -775,9 +790,8 @@ class ConnectionHandler:
|
|||
|
||||
# 处理流式响应
|
||||
tool_call_flag = False
|
||||
function_name = None
|
||||
function_id = None
|
||||
function_arguments = ""
|
||||
# 支持多个并行工具调用 - 使用列表存储
|
||||
tool_calls_list = [] # 格式: [{"id": "", "name": "", "arguments": ""}]
|
||||
content_arguments = ""
|
||||
self.client_abort = False
|
||||
emotion_flag = True
|
||||
|
|
@ -798,12 +812,7 @@ class ConnectionHandler:
|
|||
|
||||
if tools_call is not None and len(tools_call) > 0:
|
||||
tool_call_flag = True
|
||||
if tools_call[0].id is not None and tools_call[0].id != "":
|
||||
function_id = tools_call[0].id
|
||||
if tools_call[0].function.name is not None and tools_call[0].function.name != "":
|
||||
function_name = tools_call[0].function.name
|
||||
if tools_call[0].function.arguments is not None:
|
||||
function_arguments += tools_call[0].function.arguments
|
||||
self._merge_tool_calls(tool_calls_list, tools_call)
|
||||
else:
|
||||
content = response
|
||||
|
||||
|
|
@ -829,16 +838,17 @@ class ConnectionHandler:
|
|||
# 处理function call
|
||||
if tool_call_flag:
|
||||
bHasError = False
|
||||
if function_id is None:
|
||||
# 处理基于文本的工具调用格式
|
||||
if len(tool_calls_list) == 0 and content_arguments:
|
||||
a = extract_json_from_string(content_arguments)
|
||||
if a is not None:
|
||||
try:
|
||||
content_arguments_json = json.loads(a)
|
||||
function_name = content_arguments_json["name"]
|
||||
function_arguments = json.dumps(
|
||||
content_arguments_json["arguments"], ensure_ascii=False
|
||||
)
|
||||
function_id = str(uuid.uuid4().hex)
|
||||
tool_calls_list.append({
|
||||
"id": str(uuid.uuid4().hex),
|
||||
"name": content_arguments_json["name"],
|
||||
"arguments": json.dumps(content_arguments_json["arguments"], ensure_ascii=False)
|
||||
})
|
||||
except Exception as e:
|
||||
bHasError = True
|
||||
response_message.append(a)
|
||||
|
|
@ -849,30 +859,41 @@ class ConnectionHandler:
|
|||
self.logger.bind(tag=TAG).error(
|
||||
f"function call error: {content_arguments}"
|
||||
)
|
||||
if not bHasError:
|
||||
|
||||
if not bHasError and len(tool_calls_list) > 0:
|
||||
# 如需要大模型先处理一轮,添加相关处理后的日志情况
|
||||
if len(response_message) > 0:
|
||||
text_buff = "".join(response_message)
|
||||
self.tts_MessageText = text_buff
|
||||
self.dialogue.put(Message(role="assistant", content=text_buff))
|
||||
response_message.clear()
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
|
||||
)
|
||||
function_call_data = {
|
||||
"name": function_name,
|
||||
"id": function_id,
|
||||
"arguments": function_arguments,
|
||||
}
|
||||
|
||||
# 使用统一工具处理器处理所有工具调用
|
||||
result = asyncio.run_coroutine_threadsafe(
|
||||
self.func_handler.handle_llm_function_call(
|
||||
self, function_call_data
|
||||
),
|
||||
self.loop,
|
||||
).result()
|
||||
self._handle_function_result(result, function_call_data, depth=depth)
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"检测到 {len(tool_calls_list)} 个工具调用"
|
||||
)
|
||||
|
||||
# 收集所有工具调用的 Future
|
||||
futures_with_data = []
|
||||
for tool_call_data in tool_calls_list:
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
f"function_name={tool_call_data['name']}, function_id={tool_call_data['id']}, function_arguments={tool_call_data['arguments']}"
|
||||
)
|
||||
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self.func_handler.handle_llm_function_call(self, tool_call_data),
|
||||
self.loop,
|
||||
)
|
||||
futures_with_data.append((future, tool_call_data))
|
||||
|
||||
# 等待协程结束(实际等待时长为最慢的那个)
|
||||
tool_results = []
|
||||
for future, tool_call_data in futures_with_data:
|
||||
result = future.result()
|
||||
tool_results.append((result, tool_call_data))
|
||||
|
||||
# 统一处理所有工具调用结果
|
||||
if tool_results:
|
||||
self._handle_function_result(tool_results, depth=depth)
|
||||
|
||||
# 存储对话内容
|
||||
if len(response_message) > 0:
|
||||
|
|
@ -887,64 +908,61 @@ class ConnectionHandler:
|
|||
content_type=ContentType.ACTION,
|
||||
)
|
||||
)
|
||||
self.llm_finish_task = True
|
||||
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
lambda: json.dumps(
|
||||
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
|
||||
self.llm_finish_task = True
|
||||
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
|
||||
self.logger.bind(tag=TAG).debug(
|
||||
lambda: json.dumps(
|
||||
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def _handle_function_result(self, result, function_call_data, depth):
|
||||
if result.action == Action.RESPONSE: # 直接回复前端
|
||||
text = result.response
|
||||
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
|
||||
self.dialogue.put(Message(role="assistant", content=text))
|
||||
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
|
||||
text = result.result
|
||||
if text is not None and len(text) > 0:
|
||||
function_id = function_call_data["id"]
|
||||
function_name = function_call_data["name"]
|
||||
function_arguments = function_call_data["arguments"]
|
||||
self.dialogue.put(
|
||||
Message(
|
||||
role="assistant",
|
||||
tool_calls=[
|
||||
{
|
||||
"id": function_id,
|
||||
"function": {
|
||||
"arguments": (
|
||||
"{}"
|
||||
if function_arguments == ""
|
||||
else function_arguments
|
||||
),
|
||||
"name": function_name,
|
||||
},
|
||||
"type": "function",
|
||||
"index": 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
)
|
||||
def _handle_function_result(self, tool_results, depth):
|
||||
need_llm_tools = []
|
||||
|
||||
self.dialogue.put(
|
||||
Message(
|
||||
role="tool",
|
||||
tool_call_id=(
|
||||
str(uuid.uuid4()) if function_id is None else function_id
|
||||
for result, tool_call_data in tool_results:
|
||||
if result.action in [Action.RESPONSE, Action.NOTFOUND, Action.ERROR]: # 直接回复前端
|
||||
text = result.response if result.response else result.result
|
||||
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
|
||||
self.dialogue.put(Message(role="assistant", content=text))
|
||||
elif result.action == Action.REQLLM:
|
||||
# 收集需要 LLM 处理的工具
|
||||
need_llm_tools.append((result, tool_call_data))
|
||||
else:
|
||||
pass
|
||||
|
||||
if need_llm_tools:
|
||||
all_tool_calls = [
|
||||
{
|
||||
"id": tool_call_data["id"],
|
||||
"function": {
|
||||
"arguments": (
|
||||
"{}"
|
||||
if tool_call_data["arguments"] == ""
|
||||
else tool_call_data["arguments"]
|
||||
),
|
||||
content=text,
|
||||
"name": tool_call_data["name"],
|
||||
},
|
||||
"type": "function",
|
||||
"index": idx,
|
||||
}
|
||||
for idx, (_, tool_call_data) in enumerate(need_llm_tools)
|
||||
]
|
||||
self.dialogue.put(Message(role="assistant", tool_calls=all_tool_calls))
|
||||
|
||||
for result, tool_call_data in need_llm_tools:
|
||||
text = result.result
|
||||
if text is not None and len(text) > 0:
|
||||
self.dialogue.put(
|
||||
Message(
|
||||
role="tool",
|
||||
tool_call_id=str(uuid.uuid4()) if tool_call_data["id"] is None else tool_call_data["id"],
|
||||
content=text,
|
||||
)
|
||||
)
|
||||
)
|
||||
self.chat(text, depth=depth + 1)
|
||||
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
|
||||
text = result.response if result.response else result.result
|
||||
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
|
||||
self.dialogue.put(Message(role="assistant", content=text))
|
||||
else:
|
||||
pass
|
||||
|
||||
self.chat(None, depth=depth + 1)
|
||||
|
||||
def _report_worker(self):
|
||||
"""聊天记录上报工作线程"""
|
||||
|
|
@ -1144,3 +1162,31 @@ class ConnectionHandler:
|
|||
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
|
||||
finally:
|
||||
self.logger.bind(tag=TAG).info("超时检查任务已退出")
|
||||
|
||||
def _merge_tool_calls(self, tool_calls_list, tools_call):
|
||||
"""合并工具调用列表
|
||||
|
||||
Args:
|
||||
tool_calls_list: 已收集的工具调用列表
|
||||
tools_call: 新的工具调用
|
||||
"""
|
||||
for tool_call in tools_call:
|
||||
tool_index = getattr(tool_call, 'index', None)
|
||||
if tool_index is None:
|
||||
if tool_call.function.name:
|
||||
# 有 function_name,说明是新的工具调用
|
||||
tool_index = len(tool_calls_list)
|
||||
else:
|
||||
tool_index = len(tool_calls_list) - 1 if tool_calls_list else 0
|
||||
|
||||
# 确保列表有足够的位置
|
||||
if tool_index >= len(tool_calls_list):
|
||||
tool_calls_list.append({"id": "", "name": "", "arguments": ""})
|
||||
|
||||
# 更新工具调用信息
|
||||
if tool_call.id:
|
||||
tool_calls_list[tool_index]["id"] = tool_call.id
|
||||
if tool_call.function.name:
|
||||
tool_calls_list[tool_index]["name"] = tool_call.function.name
|
||||
if tool_call.function.arguments:
|
||||
tool_calls_list[tool_index]["arguments"] += tool_call.function.arguments
|
||||
|
|
@ -22,8 +22,8 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
|||
if sentenceType is not SentenceType.MIDDLE:
|
||||
conn.logger.bind(tag=TAG).info(f"Send audio message: {sentenceType}, {text}")
|
||||
|
||||
# Send end message (if last text)
|
||||
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
||||
# 发送结束消息(如果是最后一个文本)
|
||||
if sentenceType == SentenceType.LAST:
|
||||
await send_tts_message(conn, "stop", None)
|
||||
conn.client_is_speaking = False
|
||||
if conn.close_after_chat:
|
||||
|
|
@ -145,6 +145,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
|||
else:
|
||||
# Send opus packets directly without adding headers
|
||||
await conn.websocket.send(audios)
|
||||
conn.client_is_speaking = True
|
||||
|
||||
# Update flow control status
|
||||
flow_control["packet_count"] += 1
|
||||
|
|
@ -168,6 +169,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
|||
else:
|
||||
# Send the pre-buffered packet directly without adding headers
|
||||
await conn.websocket.send(audios[i])
|
||||
conn.client_is_speaking = True
|
||||
remaining_audios = audios[pre_buffer_frames:]
|
||||
|
||||
# Play remaining audio frames
|
||||
|
|
@ -201,6 +203,8 @@ async def sendAudio(conn, audios, frame_duration=60):
|
|||
# Send opus packets directly without adding headers
|
||||
await conn.websocket.send(opus_packet)
|
||||
|
||||
conn.client_is_speaking = True
|
||||
|
||||
play_position += frame_duration
|
||||
|
||||
|
||||
|
|
@ -255,5 +259,4 @@ async def send_stt_message(conn, text):
|
|||
await conn.websocket.send(
|
||||
json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id})
|
||||
)
|
||||
conn.client_is_speaking = True
|
||||
await send_tts_message(conn, "start")
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ class ASRProviderBase(ABC):
|
|||
conn.asr_audio.clear()
|
||||
conn.reset_vad_states()
|
||||
|
||||
if len(asr_audio_task) > 15 or conn.client_listen_mode == "manual":
|
||||
if len(asr_audio_task) > 15:
|
||||
await self.handle_voice_stop(conn, asr_audio_task)
|
||||
|
||||
# 处理语音停止
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ class LLMProvider(LLMProviderBase):
|
|||
"max_tokens": int,
|
||||
"temperature": lambda x: round(float(x), 1),
|
||||
"top_p": lambda x: round(float(x), 1),
|
||||
"top_k": int,
|
||||
"frequency_penalty": lambda x: round(float(x), 1),
|
||||
}
|
||||
|
||||
|
|
@ -39,7 +40,7 @@ class LLMProvider(LLMProviderBase):
|
|||
setattr(self, param, None)
|
||||
|
||||
logger.debug(
|
||||
f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
|
||||
f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.top_k}, {self.frequency_penalty}"
|
||||
)
|
||||
|
||||
model_key_msg = check_model_key("LLM", self.api_key)
|
||||
|
|
@ -70,6 +71,7 @@ class LLMProvider(LLMProviderBase):
|
|||
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||
"temperature": kwargs.get("temperature", self.temperature),
|
||||
"top_p": kwargs.get("top_p", self.top_p),
|
||||
"top_k": kwargs.get("top_k", self.top_k),
|
||||
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||
}
|
||||
|
||||
|
|
@ -114,6 +116,7 @@ class LLMProvider(LLMProviderBase):
|
|||
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||
"temperature": kwargs.get("temperature", self.temperature),
|
||||
"top_p": kwargs.get("top_p", self.top_p),
|
||||
"top_k": kwargs.get("top_k", self.top_k),
|
||||
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,10 +10,13 @@ import concurrent.futures
|
|||
from contextlib import AsyncExitStack
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from mcp import ClientSession, StdioServerParameters
|
||||
from mcp import ClientSession, StdioServerParameters, Implementation
|
||||
from mcp.client.session import SamplingFnT, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.client.sse import sse_client
|
||||
from mcp.client.streamable_http import streamablehttp_client
|
||||
from mcp.shared.session import ProgressFnT
|
||||
|
||||
from config.logger import setup_logging
|
||||
from core.utils.util import sanitize_tool_name
|
||||
|
||||
|
|
@ -41,13 +44,25 @@ class ServerMCPClient:
|
|||
self.tools_dict: Dict[str, Any] = {}
|
||||
self.name_mapping: Dict[str, str] = {}
|
||||
|
||||
async def initialize(self):
|
||||
async def initialize(self, read_timeout_seconds: timedelta | None = None,
|
||||
sampling_callback: SamplingFnT | None = None,
|
||||
elicitation_callback: ElicitationFnT | None = None,
|
||||
list_roots_callback: ListRootsFnT | None = None,
|
||||
logging_callback: LoggingFnT | None = None,
|
||||
message_handler: MessageHandlerFnT | None = None,
|
||||
client_info: Implementation | None = None):
|
||||
"""初始化MCP客户端连接"""
|
||||
if self._worker_task:
|
||||
return
|
||||
|
||||
self._worker_task = asyncio.create_task(
|
||||
self._worker(), name="ServerMCPClientWorker"
|
||||
self._worker(read_timeout_seconds=read_timeout_seconds,
|
||||
sampling_callback=sampling_callback,
|
||||
elicitation_callback=elicitation_callback,
|
||||
list_roots_callback=list_roots_callback,
|
||||
logging_callback=logging_callback,
|
||||
message_handler=message_handler,
|
||||
client_info=client_info), name="ServerMCPClientWorker"
|
||||
)
|
||||
await self._ready_evt.wait()
|
||||
|
||||
|
|
@ -97,12 +112,15 @@ class ServerMCPClient:
|
|||
for name, tool in self.tools_dict.items()
|
||||
]
|
||||
|
||||
async def call_tool(self, name: str, args: dict) -> Any:
|
||||
async def call_tool(self, name: str, arguments: dict, read_timeout_seconds: timedelta | None = None, progress_callback: ProgressFnT | None = None, *, meta: dict[str, Any] | None = None) -> Any:
|
||||
"""调用指定工具
|
||||
|
||||
Args:
|
||||
name: 工具名称
|
||||
args: 工具参数
|
||||
arguments: 工具参数
|
||||
read_timeout_seconds:
|
||||
progress_callback: 进度回调函数
|
||||
meta:
|
||||
|
||||
Returns:
|
||||
Any: 工具执行结果
|
||||
|
|
@ -115,7 +133,7 @@ class ServerMCPClient:
|
|||
|
||||
real_name = self.name_mapping.get(name, name)
|
||||
loop = self._worker_task.get_loop()
|
||||
coro = self.session.call_tool(real_name, args)
|
||||
coro = self.session.call_tool(real_name, arguments=arguments, read_timeout_seconds=read_timeout_seconds, progress_callback=progress_callback, meta=meta)
|
||||
|
||||
if loop is asyncio.get_running_loop():
|
||||
return await coro
|
||||
|
|
@ -144,7 +162,13 @@ class ServerMCPClient:
|
|||
# 所有检查都通过,连接正常
|
||||
return True
|
||||
|
||||
async def _worker(self):
|
||||
async def _worker(self, read_timeout_seconds: timedelta | None = None,
|
||||
sampling_callback: SamplingFnT | None = None,
|
||||
elicitation_callback: ElicitationFnT | None = None,
|
||||
list_roots_callback: ListRootsFnT | None = None,
|
||||
logging_callback: LoggingFnT | None = None,
|
||||
message_handler: MessageHandlerFnT | None = None,
|
||||
client_info: Implementation | None = None):
|
||||
"""MCP客户端工作协程"""
|
||||
async with AsyncExitStack() as stack:
|
||||
try:
|
||||
|
|
@ -208,7 +232,13 @@ class ServerMCPClient:
|
|||
ClientSession(
|
||||
read_stream=read_stream,
|
||||
write_stream=write_stream,
|
||||
read_timeout_seconds=timedelta(seconds=15),
|
||||
read_timeout_seconds=read_timeout_seconds,
|
||||
sampling_callback=sampling_callback,
|
||||
elicitation_callback=elicitation_callback,
|
||||
list_roots_callback=list_roots_callback,
|
||||
logging_callback=logging_callback,
|
||||
message_handler=message_handler,
|
||||
client_info=client_info
|
||||
)
|
||||
)
|
||||
await self.session.initialize()
|
||||
|
|
|
|||
|
|
@ -3,7 +3,14 @@
|
|||
import asyncio
|
||||
import os
|
||||
import json
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Any, List
|
||||
|
||||
from mcp import Implementation
|
||||
from mcp.client.session import SamplingFnT, ElicitationFnT, ListRootsFnT, LoggingFnT, MessageHandlerFnT
|
||||
from mcp.shared.session import ProgressFnT
|
||||
from mcp.types import LoggingMessageNotificationParams
|
||||
|
||||
from config.config_loader import get_project_dir
|
||||
from config.logger import setup_logging
|
||||
from .mcp_client import ServerMCPClient
|
||||
|
|
@ -56,7 +63,7 @@ class ServerMCPManager:
|
|||
# 初始化服务端MCP客户端
|
||||
logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}")
|
||||
client = ServerMCPClient(srv_config)
|
||||
await client.initialize()
|
||||
await client.initialize(logging_callback=self.logging_callback)
|
||||
self.clients[name] = client
|
||||
client_tools = client.get_available_tools()
|
||||
self.tools.extend(client_tools)
|
||||
|
|
@ -109,7 +116,7 @@ class ServerMCPManager:
|
|||
# 带重试机制的工具调用
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return await target_client.call_tool(tool_name, arguments)
|
||||
return await target_client.call_tool(tool_name, arguments, progress_callback=self.progress_callback)
|
||||
except Exception as e:
|
||||
# 最后一次尝试失败时直接抛出异常
|
||||
if attempt == max_retries - 1:
|
||||
|
|
@ -131,7 +138,7 @@ class ServerMCPManager:
|
|||
config = self.load_config()
|
||||
if client_name in config:
|
||||
client = ServerMCPClient(config[client_name])
|
||||
await client.initialize()
|
||||
await client.initialize(logging_callback=self.logging_callback)
|
||||
self.clients[client_name] = client
|
||||
target_client = client
|
||||
logger.bind(tag=TAG).info(
|
||||
|
|
@ -159,3 +166,11 @@ class ServerMCPManager:
|
|||
except (asyncio.TimeoutError, Exception) as e:
|
||||
logger.bind(tag=TAG).error(f"关闭服务端MCP客户端 {name} 时出错: {e}")
|
||||
self.clients.clear()
|
||||
|
||||
# 可选回调方法
|
||||
|
||||
async def logging_callback(self, params: LoggingMessageNotificationParams):
|
||||
logger.bind(tag=TAG).info(f"[Server Log - {params.level.upper()}] {params.data}")
|
||||
|
||||
async def progress_callback(self, progress: float, total: float | None, message: str | None) -> None:
|
||||
logger.bind(tag=TAG).info(f"[Progress {progress}/{total}]: {message}")
|
||||
|
|
@ -33,8 +33,6 @@ class WebSocketServer:
|
|||
self._intent = modules["intent"] if "intent" in modules else None
|
||||
self._memory = modules["memory"] if "memory" in modules else None
|
||||
|
||||
self.active_connections = set()
|
||||
|
||||
auth_config = self.config["server"].get("auth", {})
|
||||
self.auth_enable = auth_config.get("enabled", False)
|
||||
# 设备白名单
|
||||
|
|
@ -98,14 +96,11 @@ class WebSocketServer:
|
|||
self._intent,
|
||||
self, # 传入server实例
|
||||
)
|
||||
self.active_connections.add(handler)
|
||||
try:
|
||||
await handler.handle_connection(websocket)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}")
|
||||
finally:
|
||||
# 确保从活动连接集合中移除
|
||||
self.active_connections.discard(handler)
|
||||
# 强制关闭连接(如果还没有关闭的话)
|
||||
try:
|
||||
# 安全地检查WebSocket状态并关闭
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,503 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>小智语音服务测试</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background-color: #f5f5f5;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
button {
|
||||
padding: 8px 15px;
|
||||
margin-right: 10px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background-color: #4285f4;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #3367d6;
|
||||
}
|
||||
button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
#status {
|
||||
font-weight: bold;
|
||||
}
|
||||
#scriptStatus {
|
||||
position: fixed;
|
||||
top: 10px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
display: block;
|
||||
z-index: 100;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
#scriptStatus.info {
|
||||
background-color: #e8f0fe;
|
||||
color: #4285f4;
|
||||
border-left: 4px solid #4285f4;
|
||||
}
|
||||
#scriptStatus.success {
|
||||
background-color: #e6f4ea;
|
||||
color: #0f9d58;
|
||||
border-left: 4px solid #0f9d58;
|
||||
}
|
||||
#scriptStatus.error {
|
||||
background-color: #fce8e6;
|
||||
color: #db4437;
|
||||
border-left: 4px solid #db4437;
|
||||
}
|
||||
#debugInfo {
|
||||
margin-top: 20px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
padding: 10px;
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
display: none;
|
||||
}
|
||||
#showDebug {
|
||||
margin-top: 10px;
|
||||
background-color: #f5f5f5;
|
||||
color: #444;
|
||||
font-size: 12px;
|
||||
}
|
||||
#audioMeter {
|
||||
margin-top: 10px;
|
||||
height: 20px;
|
||||
background-color: #eee;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
display: none;
|
||||
}
|
||||
#audioLevel {
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
background-color: #4285f4;
|
||||
transition: width 0.1s;
|
||||
}
|
||||
.conversation {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
padding: 10px;
|
||||
background-color: white;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.message {
|
||||
margin-bottom: 10px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
max-width: 80%;
|
||||
}
|
||||
.user {
|
||||
background-color: #e2f2ff;
|
||||
margin-left: auto;
|
||||
margin-right: 10px;
|
||||
text-align: right;
|
||||
}
|
||||
.server {
|
||||
background-color: #f0f0f0;
|
||||
margin-right: auto;
|
||||
margin-left: 10px;
|
||||
}
|
||||
#serverUrl {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
width: 60%;
|
||||
margin-right: 10px;
|
||||
}
|
||||
#messageInput {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
width: 70%;
|
||||
margin-right: 10px;
|
||||
}
|
||||
.section {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>小智语音服务测试</h2>
|
||||
|
||||
<div id="scriptStatus" class="info">正在加载Opus库...</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>WebSocket连接 <span id="connectionStatus">未连接</span></h3>
|
||||
<div style="display: flex; align-items: center; margin-bottom: 10px;">
|
||||
<input type="text" id="serverUrl" value="ws://127.0.0.1:8000/xiaozhi/v1/" placeholder="WebSocket服务器地址">
|
||||
<button id="connectButton">连接</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>录音测试</h3>
|
||||
<button id="initAudio" style="background-color: #34a853;">初始化音频</button>
|
||||
<button id="testMic" style="background-color: #fbbc05;">测试麦克风</button>
|
||||
<p></p>
|
||||
<button id="start" disabled>开始录音</button>
|
||||
<button id="stop" disabled>停止录音</button>
|
||||
<button id="play" disabled>播放录音</button>
|
||||
<p>录音状态: <span id="status">待机,正在初始化...</span></p>
|
||||
<div id="audioMeter">
|
||||
<div id="audioLevel"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>文本消息</h3>
|
||||
<div style="display: flex; align-items: center;">
|
||||
<input type="text" id="messageInput" placeholder="输入消息..." disabled>
|
||||
<button id="sendTextButton" disabled>发送</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>会话记录</h3>
|
||||
<div id="conversation" class="conversation"></div>
|
||||
</div>
|
||||
|
||||
<button id="showDebug">显示/隐藏调试信息</button>
|
||||
<div id="debugInfo"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 定义全局变量以跟踪库加载状态
|
||||
window.opusLoaded = false;
|
||||
window.startButton = document.getElementById("start");
|
||||
window.stopButton = document.getElementById("stop");
|
||||
window.playButton = document.getElementById("play");
|
||||
window.statusLabel = document.getElementById("status");
|
||||
window.debugInfo = document.getElementById("debugInfo");
|
||||
window.audioContextReady = false;
|
||||
window.testMicActive = false;
|
||||
|
||||
// 显示/隐藏调试信息
|
||||
document.getElementById("showDebug").addEventListener("click", function() {
|
||||
if (debugInfo.style.display === "none" || !debugInfo.style.display) {
|
||||
debugInfo.style.display = "block";
|
||||
this.textContent = "隐藏调试信息";
|
||||
} else {
|
||||
debugInfo.style.display = "none";
|
||||
this.textContent = "显示调试信息";
|
||||
}
|
||||
});
|
||||
|
||||
// 添加初始化音频按钮事件
|
||||
document.getElementById("initAudio").addEventListener("click", function() {
|
||||
initializeAudioSystem();
|
||||
});
|
||||
|
||||
// 添加测试麦克风按钮事件
|
||||
document.getElementById("testMic").addEventListener("click", function() {
|
||||
if (window.testMicActive) {
|
||||
stopMicTest();
|
||||
} else {
|
||||
startMicTest();
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化音频系统
|
||||
function initializeAudioSystem() {
|
||||
try {
|
||||
log("初始化音频系统...");
|
||||
// 创建临时AudioContext来触发用户授权
|
||||
const tempContext = new (window.AudioContext || window.webkitAudioContext)({
|
||||
sampleRate: 16000,
|
||||
latencyHint: 'interactive'
|
||||
});
|
||||
|
||||
// 创建振荡器并播放短促的声音
|
||||
const oscillator = tempContext.createOscillator();
|
||||
const gain = tempContext.createGain();
|
||||
gain.gain.value = 0.1; // 很小的音量
|
||||
oscillator.connect(gain);
|
||||
gain.connect(tempContext.destination);
|
||||
oscillator.frequency.value = 440; // A4
|
||||
oscillator.start();
|
||||
|
||||
// 0.2秒后停止
|
||||
setTimeout(() => {
|
||||
oscillator.stop();
|
||||
// 关闭上下文
|
||||
tempContext.close().then(() => {
|
||||
log("音频系统初始化成功", "success");
|
||||
updateScriptStatus("音频系统已激活", "success");
|
||||
document.getElementById("initAudio").disabled = true;
|
||||
document.getElementById("initAudio").textContent = "音频已初始化";
|
||||
window.audioContextReady = true;
|
||||
|
||||
// 如果Opus已加载,启用开始录音按钮
|
||||
if (window.opusLoaded) {
|
||||
startButton.disabled = false;
|
||||
}
|
||||
});
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
log("初始化音频系统失败: " + err.message, "error");
|
||||
updateScriptStatus("初始化音频失败: " + err.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// 测试麦克风
|
||||
function startMicTest() {
|
||||
const audioMeter = document.getElementById("audioMeter");
|
||||
const audioLevel = document.getElementById("audioLevel");
|
||||
const testMicBtn = document.getElementById("testMic");
|
||||
|
||||
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
||||
log("浏览器不支持麦克风访问", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
log("开始麦克风测试...");
|
||||
audioMeter.style.display = "block";
|
||||
testMicBtn.textContent = "停止测试";
|
||||
testMicBtn.style.backgroundColor = "#ea4335";
|
||||
window.testMicActive = true;
|
||||
|
||||
// 创建音频上下文
|
||||
const testContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||
window.testContext = testContext;
|
||||
|
||||
// 获取麦克风权限
|
||||
navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true
|
||||
}
|
||||
})
|
||||
.then(stream => {
|
||||
log("已获取麦克风访问权限", "success");
|
||||
|
||||
// 保存流以便稍后关闭
|
||||
window.testStream = stream;
|
||||
|
||||
// 创建音频分析器
|
||||
const source = testContext.createMediaStreamSource(stream);
|
||||
const analyser = testContext.createAnalyser();
|
||||
analyser.fftSize = 256;
|
||||
source.connect(analyser);
|
||||
|
||||
// 创建音量显示更新函数
|
||||
const bufferLength = analyser.frequencyBinCount;
|
||||
const dataArray = new Uint8Array(bufferLength);
|
||||
|
||||
function updateMeter() {
|
||||
if (!window.testMicActive) return;
|
||||
|
||||
analyser.getByteFrequencyData(dataArray);
|
||||
|
||||
// 计算音量级别 (0-100)
|
||||
let sum = 0;
|
||||
for (let i = 0; i < bufferLength; i++) {
|
||||
sum += dataArray[i];
|
||||
}
|
||||
const average = sum / bufferLength;
|
||||
const level = Math.min(100, Math.max(0, average * 2));
|
||||
|
||||
// 更新音量计
|
||||
audioLevel.style.width = level + "%";
|
||||
|
||||
// 如果有声音,记录日志
|
||||
if (level > 10) {
|
||||
log(`检测到声音: ${level.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
// 循环更新
|
||||
window.testMicAnimationFrame = requestAnimationFrame(updateMeter);
|
||||
}
|
||||
|
||||
// 开始更新
|
||||
updateMeter();
|
||||
})
|
||||
.catch(err => {
|
||||
log("麦克风测试失败: " + err.message, "error");
|
||||
window.testMicActive = false;
|
||||
testMicBtn.textContent = "测试麦克风";
|
||||
testMicBtn.style.backgroundColor = "#fbbc05";
|
||||
audioMeter.style.display = "none";
|
||||
});
|
||||
}
|
||||
|
||||
// 停止麦克风测试
|
||||
function stopMicTest() {
|
||||
const audioMeter = document.getElementById("audioMeter");
|
||||
const testMicBtn = document.getElementById("testMic");
|
||||
|
||||
log("停止麦克风测试");
|
||||
window.testMicActive = false;
|
||||
testMicBtn.textContent = "测试麦克风";
|
||||
testMicBtn.style.backgroundColor = "#fbbc05";
|
||||
|
||||
// 停止分析器动画
|
||||
if (window.testMicAnimationFrame) {
|
||||
cancelAnimationFrame(window.testMicAnimationFrame);
|
||||
}
|
||||
|
||||
// 停止麦克风流
|
||||
if (window.testStream) {
|
||||
window.testStream.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
// 关闭测试上下文
|
||||
if (window.testContext) {
|
||||
window.testContext.close();
|
||||
}
|
||||
|
||||
// 隐藏音量计
|
||||
audioMeter.style.display = "none";
|
||||
}
|
||||
|
||||
// 添加调试日志
|
||||
function log(message, type = "info") {
|
||||
console.log(message);
|
||||
const time = new Date().toLocaleTimeString();
|
||||
const entry = document.createElement("div");
|
||||
entry.textContent = `[${time}] ${message}`;
|
||||
|
||||
if (type === "error") {
|
||||
entry.style.color = "#db4437";
|
||||
} else if (type === "success") {
|
||||
entry.style.color = "#0f9d58";
|
||||
}
|
||||
|
||||
debugInfo.appendChild(entry);
|
||||
debugInfo.scrollTop = debugInfo.scrollHeight;
|
||||
}
|
||||
|
||||
// 更新脚本状态显示
|
||||
function updateScriptStatus(message, type) {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) {
|
||||
statusElement.textContent = message;
|
||||
statusElement.className = type;
|
||||
statusElement.style.display = 'block';
|
||||
}
|
||||
log(message, type);
|
||||
}
|
||||
|
||||
// 检查Opus库是否已加载
|
||||
function checkOpusLoaded() {
|
||||
try {
|
||||
// 检查Module是否存在(本地库导出的全局变量)
|
||||
if (typeof Module === 'undefined') {
|
||||
log("Module对象不存在", "error");
|
||||
throw new Error('Opus库未加载,Module对象不存在');
|
||||
}
|
||||
|
||||
// 记录Module对象结构以便调试
|
||||
log("Module对象结构: " + Object.keys(Module).join(", "));
|
||||
|
||||
// 尝试使用全局Module函数
|
||||
if (typeof Module._opus_decoder_get_size === 'function') {
|
||||
window.ModuleInstance = Module;
|
||||
log('Opus库加载成功(使用全局Module)', "success");
|
||||
updateScriptStatus('Opus库加载成功', 'success');
|
||||
|
||||
// 启用开始录音按钮
|
||||
startButton.disabled = false;
|
||||
statusLabel.textContent = "待机";
|
||||
|
||||
// 3秒后隐藏状态
|
||||
setTimeout(() => {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
}, 3000);
|
||||
|
||||
window.opusLoaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 尝试使用Module.instance
|
||||
if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') {
|
||||
window.ModuleInstance = Module.instance;
|
||||
log('Opus库加载成功(使用Module.instance)', "success");
|
||||
updateScriptStatus('Opus库加载成功', 'success');
|
||||
|
||||
// 启用开始录音按钮
|
||||
startButton.disabled = false;
|
||||
statusLabel.textContent = "待机";
|
||||
|
||||
// 3秒后隐藏状态
|
||||
setTimeout(() => {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
}, 3000);
|
||||
|
||||
window.opusLoaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查是否有其他导出方式
|
||||
log("Module上可用方法: " + Object.getOwnPropertyNames(Module).filter(prop => typeof Module[prop] === 'function').join(", "));
|
||||
|
||||
if (typeof Module.onRuntimeInitialized === 'function' || typeof Module.onRuntimeInitialized === 'undefined') {
|
||||
log("Module.onRuntimeInitialized 尚未执行,等待模块初始化完成...");
|
||||
// Module可能未完成初始化,注册回调
|
||||
Module.onRuntimeInitialized = function() {
|
||||
log("Opus库运行时初始化完成,重新检查");
|
||||
checkOpusLoaded();
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error('Opus解码函数未找到,可能Module结构不正确');
|
||||
} catch (err) {
|
||||
log(`Opus库加载失败: ${err.message}`, "error");
|
||||
updateScriptStatus(`Opus库加载失败: ${err.message}`, 'error');
|
||||
statusLabel.textContent = "错误:Opus库加载失败";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后检查浏览器能力和Opus库
|
||||
window.addEventListener('load', function() {
|
||||
log("页面加载完成,开始初始化...");
|
||||
updateScriptStatus('正在初始化录音环境...', 'info');
|
||||
|
||||
// 延迟一小段时间再检查,确保库有时间加载
|
||||
setTimeout(function checkAndRetry() {
|
||||
if (!checkOpusLoaded()) {
|
||||
// 如果加载失败,5秒后重试
|
||||
log("Opus库加载失败,5秒后重试...");
|
||||
updateScriptStatus('Opus库加载失败,正在重试...', 'error');
|
||||
setTimeout(checkAndRetry, 5000);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// 防止按钮误操作
|
||||
document.getElementById("stop").disabled = true;
|
||||
document.getElementById("play").disabled = true;
|
||||
</script>
|
||||
<script src="./../libopus.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
main/xiaozhi-server/test/css/bg.png
Normal file
BIN
main/xiaozhi-server/test/css/bg.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 185 B |
998
main/xiaozhi-server/test/css/test_page.css
Normal file
998
main/xiaozhi-server/test/css/test_page.css
Normal file
|
|
@ -0,0 +1,998 @@
|
|||
/* ==================== 全局样式 ==================== */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0px;
|
||||
background-image: url('bg.png');
|
||||
}
|
||||
|
||||
/* ==================== 容器布局 ==================== */
|
||||
.container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
border-radius: 10px;
|
||||
padding: 0px;
|
||||
}
|
||||
|
||||
/* 两栏布局 */
|
||||
.two-column-layout {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
align-items: stretch;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.two-column-layout>.section {
|
||||
flex: 1;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ==================== 通用区块样式 ==================== */
|
||||
.section {
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
padding: 10px;
|
||||
border-radius: 15px;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
margin: 0;
|
||||
color: #000;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
/* ==================== 通用按钮样式 ==================== */
|
||||
button {
|
||||
padding: 8px 15px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background-color: #007aff;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* 切换按钮和连接按钮 */
|
||||
.toggle-button,
|
||||
.connect-button {
|
||||
margin-left: auto;
|
||||
padding: 4px 12px;
|
||||
font-size: 14px;
|
||||
border-radius: 20px;
|
||||
cursor: pointer;
|
||||
height: 28px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.toggle-button {
|
||||
border: 1px solid #007aff;
|
||||
background-color: #fff;
|
||||
color: #007aff;
|
||||
}
|
||||
|
||||
.connect-button {
|
||||
box-shadow: 0px 0px 10px 2px rgba(0, 122, 255, 0.28);
|
||||
}
|
||||
|
||||
/* ==================== 设备配置面板 ==================== */
|
||||
.config-panel {
|
||||
display: block;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
/* MCP工具面板默认隐藏 */
|
||||
#mcpToolsPanel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#mcpToolsPanel.expanded {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.control-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* 配置行 */
|
||||
.config-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 配置项 */
|
||||
.config-item {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
margin-bottom: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.config-item label {
|
||||
white-space: nowrap;
|
||||
min-width: 70px;
|
||||
text-align: left;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.config-item input {
|
||||
flex: 1;
|
||||
width: 0;
|
||||
flex-grow: 1;
|
||||
padding: 6px;
|
||||
font-size: 12px;
|
||||
border: 1px solid #b1c9f8;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.config-item input:disabled {
|
||||
background-color: #fff;
|
||||
border-color: #fff;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ==================== 连接信息面板 ==================== */
|
||||
.connection-controls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.connection-controls input {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.connection-controls button {
|
||||
white-space: nowrap;
|
||||
padding: 8px 15px;
|
||||
}
|
||||
|
||||
#serverUrl,
|
||||
#otaUrl {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#otaUrl {
|
||||
border: 1px solid #b1c9f8;
|
||||
}
|
||||
|
||||
#serverUrl {
|
||||
border: 1px solid #fafafa;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
/* 连接状态 */
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin-left: 0px;
|
||||
padding: 0 15px;
|
||||
height: 28px;
|
||||
line-height: 28px;
|
||||
}
|
||||
|
||||
.connection-status span {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.connection-status .status {
|
||||
background-color: #fef2f2;
|
||||
color: #b91c1c;
|
||||
font-size: 12px;
|
||||
padding: 0px 8px;
|
||||
border-radius: 20px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
/* 已连接状态 */
|
||||
.connection-status .status.connected {
|
||||
background-color: #ecfdf3;
|
||||
color: #15803d;
|
||||
}
|
||||
|
||||
/* 会话状态 - 离线中 */
|
||||
.connection-status .status.offline {
|
||||
background-color: #fef2f2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
/* 会话状态 - 聆听中 */
|
||||
.connection-status .status.listening {
|
||||
background-color: #ecfdf3;
|
||||
color: #15803d;
|
||||
}
|
||||
|
||||
/* 会话状态 - 说话中 */
|
||||
.connection-status .status.speaking {
|
||||
background-color: #fff7ed;
|
||||
color: #c2410c;
|
||||
animation: pulse-speaking 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse-speaking {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
/* LLM状态emoji样式 */
|
||||
span.connection-status.llm-emoji {
|
||||
display: block !important;
|
||||
text-align: center !important;
|
||||
width: 100% !important;
|
||||
margin: 0 auto !important;
|
||||
}
|
||||
|
||||
.llm-emoji .status {
|
||||
font-size: 14px !important;
|
||||
padding: 8px 20px !important;
|
||||
}
|
||||
|
||||
.emoji-large {
|
||||
font-size: 2em !important;
|
||||
vertical-align: middle;
|
||||
display: inline-block;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* ==================== 标签页样式 ==================== */
|
||||
.tabs {
|
||||
display: flex;
|
||||
margin-bottom: 20px;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 10px 20px;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
position: relative;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
color: #007aff;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
color: #007aff;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.tab.active::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -1px;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background-color: #007aff;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* ==================== 文本消息输入 ==================== */
|
||||
.message-input {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
#messageInput {
|
||||
flex-grow: 1;
|
||||
padding: 8px 20px 8px 20px;
|
||||
border: 1px solid #b1c9f8;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
#messageInput:disabled {
|
||||
border: 1px solid #fafafa;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
#sendTextButton,
|
||||
#recordButton {
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
/* ==================== 语音消息控制 ==================== */
|
||||
.audio-controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.audio-visualizer {
|
||||
height: 60px;
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 15px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.record-button {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
.record-button:hover {
|
||||
background-color: #c53929;
|
||||
}
|
||||
|
||||
.record-button.recording {
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
50% {
|
||||
background-color: #ff6659;
|
||||
}
|
||||
|
||||
100% {
|
||||
background-color: #db4437;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================== 会话记录和日志 ==================== */
|
||||
.flex-container {
|
||||
display: flex;
|
||||
margin-top: 10px;
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
/* 会话记录容器 */
|
||||
.conversation {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #ddd;
|
||||
border-right: none;
|
||||
border-radius: 5px 0px 0px 5px;
|
||||
padding: 10px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 消息气泡 */
|
||||
.message {
|
||||
margin-bottom: 10px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
width: fit-content;
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
.user {
|
||||
background-color: #fff;
|
||||
margin-left: auto;
|
||||
margin-right: 10px;
|
||||
text-align: right;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.server {
|
||||
background-color: #95ec69;
|
||||
margin-right: auto;
|
||||
margin-left: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
/* 日志容器 */
|
||||
#logContainer {
|
||||
margin-top: 0;
|
||||
padding: 10px;
|
||||
border-radius: 0px 5px 5px 0px;
|
||||
font-family: monospace;
|
||||
height: 300px;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
margin: 5px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.log-info {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.log-error {
|
||||
color: #db4437;
|
||||
}
|
||||
|
||||
.log-success {
|
||||
color: #0f9d58;
|
||||
}
|
||||
|
||||
/* ==================== MCP 工具管理 ==================== */
|
||||
.mcp-tools-container {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.mcp-tool-card {
|
||||
background-color: white;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.mcp-tool-card:hover {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.mcp-tool-card.disabled {
|
||||
opacity: 0.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.mcp-tool-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.mcp-tool-name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.mcp-tool-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.mcp-tool-description {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.mcp-tool-info {
|
||||
background-color: #f9f9f9;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 4px;
|
||||
padding: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.mcp-tool-info-row {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.mcp-tool-info-label {
|
||||
color: #999;
|
||||
min-width: 60px;
|
||||
}
|
||||
|
||||
.mcp-tool-info-value {
|
||||
color: #333;
|
||||
font-family: 'Courier New', monospace;
|
||||
}
|
||||
|
||||
/* MCP 属性项 */
|
||||
.mcp-property-item {
|
||||
background-color: white;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 5px;
|
||||
padding: 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.mcp-property-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.mcp-property-name {
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.mcp-property-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.mcp-property-row-full {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.mcp-small-label {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.mcp-small-input {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.mcp-checkbox-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mcp-error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 15px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.mcp-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.mcp-badge-required {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
}
|
||||
|
||||
.mcp-badge-optional {
|
||||
background-color: #e3f2fd;
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
/* ==================== 脚本加载状态 ==================== */
|
||||
.script-status {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.script-loaded {
|
||||
background-color: #0f9d58;
|
||||
}
|
||||
|
||||
.script-loading {
|
||||
background-color: #f4b400;
|
||||
}
|
||||
|
||||
.script-error {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
.script-list {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
background-color: #f9f9f9;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#scriptStatus.success {
|
||||
background-color: #e6f4ea;
|
||||
color: #0f9d58;
|
||||
border-left: 4px solid #0f9d58;
|
||||
}
|
||||
|
||||
#scriptStatus.error {
|
||||
background-color: #fce8e6;
|
||||
color: #db4437;
|
||||
border-left: 4px solid #db4437;
|
||||
}
|
||||
|
||||
#scriptStatus.warning {
|
||||
background-color: #fef7e0;
|
||||
color: #f4b400;
|
||||
border-left: 4px solid #f4b400;
|
||||
}
|
||||
|
||||
/* ==================== File协议警告 ==================== */
|
||||
#fileProtocolWarning {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#fileProtocolWarning h2 {
|
||||
color: #ff4d4d;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
#fileProtocolWarning pre {
|
||||
background-color: green;
|
||||
font-size: 18px;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
overflow-x: auto;
|
||||
margin: 15px 0;
|
||||
}
|
||||
|
||||
#fileProtocolWarning button {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
font-size: 16px;
|
||||
margin: 10px 2px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#fileProtocolWarning button:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
|
||||
/* ==================== 响应式布局 ==================== */
|
||||
|
||||
/* 大屏幕 (宽度 > 1200px) */
|
||||
@media (min-width: 1201px) {
|
||||
.container {
|
||||
max-width: 80%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 中等屏幕 (宽度 <= 1200px) */
|
||||
@media (max-width: 1200px) {
|
||||
.container {
|
||||
max-width: 95%;
|
||||
padding: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 平板设备 (宽度 <= 1060px) */
|
||||
@media (max-width: 1060px) {
|
||||
|
||||
/* 两栏布局改为单栏 */
|
||||
.two-column-layout {
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.two-column-layout>.section {
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
/* 连接状态标签调整 */
|
||||
.connection-status {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-left: 0px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
/* 会话记录和日志容器改为上下布局 */
|
||||
.flex-container {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.conversation,
|
||||
#logContainer {
|
||||
border-radius: 5px;
|
||||
border: 1px solid #ddd;
|
||||
max-height: 200px;
|
||||
}
|
||||
|
||||
.conversation {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
/* MCP 属性行改为单列 */
|
||||
.mcp-property-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* 移动设备 (宽度 <= 768px) */
|
||||
@media (max-width: 768px) {
|
||||
body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 100%;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
/* 调整区块内边距 */
|
||||
.section {
|
||||
padding: 8px;
|
||||
margin-top: 8px;
|
||||
margin-bottom: 8px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
/* 调整标题字体 */
|
||||
.section h2 {
|
||||
font-size: 13px;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
/* 配置行改为单列 */
|
||||
.config-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 按钮调整 */
|
||||
.toggle-button,
|
||||
.connect-button {
|
||||
padding: 3px 10px;
|
||||
font-size: 12px;
|
||||
height: 24px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 输入框 */
|
||||
#serverUrl,
|
||||
#otaUrl,
|
||||
#messageInput {
|
||||
font-size: 14px;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
/* 配置项标签 */
|
||||
.config-item label {
|
||||
min-width: 60px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.config-item input {
|
||||
font-size: 13px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
/* 标签页 */
|
||||
.tab {
|
||||
padding: 8px 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 消息气泡 */
|
||||
.message {
|
||||
max-width: 90%;
|
||||
font-size: 14px;
|
||||
padding: 6px 10px;
|
||||
}
|
||||
|
||||
/* 日志容器 */
|
||||
#logContainer {
|
||||
font-size: 11px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* 连接状态 */
|
||||
.connection-status {
|
||||
margin-left: 0;
|
||||
padding: 5px 0;
|
||||
height: auto;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.connection-status .status {
|
||||
font-size: 11px;
|
||||
padding: 0px 6px;
|
||||
}
|
||||
|
||||
/* 音频可视化 */
|
||||
.audio-visualizer {
|
||||
height: 50px;
|
||||
}
|
||||
|
||||
/* MCP 工具卡片 */
|
||||
.mcp-tool-card {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.mcp-tool-name {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.mcp-tool-description {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.mcp-tool-info {
|
||||
font-size: 11px;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.mcp-tool-info-row {
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.mcp-tool-info-label {
|
||||
min-width: auto;
|
||||
}
|
||||
|
||||
/* 消息输入框 */
|
||||
.message-input {
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
/* 会话记录高度调整 */
|
||||
.conversation,
|
||||
#logContainer {
|
||||
max-height: 180px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 小型移动设备 (宽度 <= 480px) */
|
||||
@media (max-width: 480px) {
|
||||
.container {
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
.section {
|
||||
padding: 6px;
|
||||
margin-top: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 更紧凑的按钮 */
|
||||
.toggle-button,
|
||||
.connect-button {
|
||||
padding: 2px 8px;
|
||||
font-size: 11px;
|
||||
height: 22px;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.config-item label {
|
||||
min-width: 50px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.config-item input {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 标签页 */
|
||||
.tab {
|
||||
padding: 6px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 消息气泡 */
|
||||
.message {
|
||||
max-width: 95%;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 会话记录 */
|
||||
.conversation,
|
||||
#logContainer {
|
||||
max-height: 150px;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* 连接状态文字更小 */
|
||||
.connection-status .status {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* MCP 工具 */
|
||||
.mcp-tool-name {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.mcp-tool-description {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
50
main/xiaozhi-server/test/js/app.js
Normal file
50
main/xiaozhi-server/test/js/app.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// 主应用入口
|
||||
import { log } from './utils/logger.js';
|
||||
import { checkOpusLoaded, initOpusEncoder } from './core/audio/opus-codec.js';
|
||||
import { getUIController } from './ui/controller.js';
|
||||
import { getAudioPlayer } from './core/audio/player.js';
|
||||
import { initMcpTools } from './core/mcp/tools.js';
|
||||
|
||||
// 应用类
|
||||
class App {
|
||||
constructor() {
|
||||
this.uiController = null;
|
||||
this.audioPlayer = null;
|
||||
}
|
||||
|
||||
// 初始化应用
|
||||
async init() {
|
||||
log('正在初始化应用...', 'info');
|
||||
|
||||
// 初始化UI控制器
|
||||
this.uiController = getUIController();
|
||||
this.uiController.init();
|
||||
|
||||
// 检查Opus库
|
||||
checkOpusLoaded();
|
||||
|
||||
// 初始化Opus编码器
|
||||
initOpusEncoder();
|
||||
|
||||
// 初始化音频播放器
|
||||
this.audioPlayer = getAudioPlayer();
|
||||
await this.audioPlayer.start();
|
||||
|
||||
// 初始化MCP工具
|
||||
initMcpTools();
|
||||
|
||||
log('应用初始化完成', 'success');
|
||||
}
|
||||
}
|
||||
|
||||
// 创建并启动应用
|
||||
const app = new App();
|
||||
|
||||
// DOM加载完成后初始化
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => app.init());
|
||||
} else {
|
||||
app.init();
|
||||
}
|
||||
|
||||
export default app;
|
||||
85
main/xiaozhi-server/test/js/config/manager.js
Normal file
85
main/xiaozhi-server/test/js/config/manager.js
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
// 配置管理模块
|
||||
|
||||
// 生成随机MAC地址
|
||||
function generateRandomMac() {
|
||||
const hexDigits = '0123456789ABCDEF';
|
||||
let mac = '';
|
||||
for (let i = 0; i < 6; i++) {
|
||||
if (i > 0) mac += ':';
|
||||
for (let j = 0; j < 2; j++) {
|
||||
mac += hexDigits.charAt(Math.floor(Math.random() * 16));
|
||||
}
|
||||
}
|
||||
return mac;
|
||||
}
|
||||
|
||||
// 加载配置
|
||||
export function loadConfig() {
|
||||
const deviceMacInput = document.getElementById('deviceMac');
|
||||
const deviceNameInput = document.getElementById('deviceName');
|
||||
const clientIdInput = document.getElementById('clientId');
|
||||
const tokenInput = document.getElementById('token');
|
||||
const otaUrlInput = document.getElementById('otaUrl');
|
||||
|
||||
// 从localStorage加载MAC地址,如果没有则生成新的
|
||||
let savedMac = localStorage.getItem('xz_tester_deviceMac');
|
||||
if (!savedMac) {
|
||||
savedMac = generateRandomMac();
|
||||
localStorage.setItem('xz_tester_deviceMac', savedMac);
|
||||
}
|
||||
deviceMacInput.value = savedMac;
|
||||
|
||||
// 从localStorage加载其他配置
|
||||
const savedDeviceName = localStorage.getItem('xz_tester_deviceName');
|
||||
if (savedDeviceName) {
|
||||
deviceNameInput.value = savedDeviceName;
|
||||
}
|
||||
|
||||
const savedClientId = localStorage.getItem('xz_tester_clientId');
|
||||
if (savedClientId) {
|
||||
clientIdInput.value = savedClientId;
|
||||
}
|
||||
|
||||
const savedToken = localStorage.getItem('xz_tester_token');
|
||||
if (savedToken) {
|
||||
tokenInput.value = savedToken;
|
||||
}
|
||||
|
||||
const savedOtaUrl = localStorage.getItem('xz_tester_otaUrl');
|
||||
if (savedOtaUrl) {
|
||||
otaUrlInput.value = savedOtaUrl;
|
||||
}
|
||||
}
|
||||
|
||||
// 保存配置
|
||||
export function saveConfig() {
|
||||
const deviceMacInput = document.getElementById('deviceMac');
|
||||
const deviceNameInput = document.getElementById('deviceName');
|
||||
const clientIdInput = document.getElementById('clientId');
|
||||
const tokenInput = document.getElementById('token');
|
||||
|
||||
localStorage.setItem('xz_tester_deviceMac', deviceMacInput.value);
|
||||
localStorage.setItem('xz_tester_deviceName', deviceNameInput.value);
|
||||
localStorage.setItem('xz_tester_clientId', clientIdInput.value);
|
||||
localStorage.setItem('xz_tester_token', tokenInput.value);
|
||||
}
|
||||
|
||||
// 获取配置值
|
||||
export function getConfig() {
|
||||
const deviceMac = document.getElementById('deviceMac').value.trim();
|
||||
return {
|
||||
deviceId: deviceMac, // 使用MAC地址作为deviceId
|
||||
deviceName: document.getElementById('deviceName').value.trim(),
|
||||
deviceMac: deviceMac,
|
||||
clientId: document.getElementById('clientId').value.trim(),
|
||||
token: document.getElementById('token').value.trim()
|
||||
};
|
||||
}
|
||||
|
||||
// 保存连接URL
|
||||
export function saveConnectionUrls() {
|
||||
const otaUrl = document.getElementById('otaUrl').value.trim();
|
||||
const wsUrl = document.getElementById('serverUrl').value.trim();
|
||||
localStorage.setItem('xz_tester_otaUrl', otaUrl);
|
||||
localStorage.setItem('xz_tester_wsUrl', wsUrl);
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { log } from './utils/logger.js';
|
||||
import { updateScriptStatus } from './document.js'
|
||||
import { log } from '../../utils/logger.js';
|
||||
import { updateScriptStatus } from '../../ui/dom-helper.js'
|
||||
|
||||
|
||||
// 检查Opus库是否已加载
|
||||
262
main/xiaozhi-server/test/js/core/audio/player.js
Normal file
262
main/xiaozhi-server/test/js/core/audio/player.js
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
// 音频播放模块
|
||||
import { log } from '../../utils/logger.js';
|
||||
import BlockingQueue from '../../utils/blocking-queue.js';
|
||||
import { createStreamingContext } from './stream-context.js';
|
||||
|
||||
// 音频播放器类
|
||||
export class AudioPlayer {
|
||||
constructor() {
|
||||
// 音频参数
|
||||
this.SAMPLE_RATE = 16000;
|
||||
this.CHANNELS = 1;
|
||||
this.FRAME_SIZE = 960;
|
||||
this.MIN_AUDIO_DURATION = 0.12;
|
||||
|
||||
// 状态
|
||||
this.audioContext = null;
|
||||
this.opusDecoder = null;
|
||||
this.streamingContext = null;
|
||||
this.queue = new BlockingQueue();
|
||||
this.isPlaying = false;
|
||||
}
|
||||
|
||||
// 获取或创建AudioContext
|
||||
getAudioContext() {
|
||||
if (!this.audioContext) {
|
||||
this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
|
||||
sampleRate: this.SAMPLE_RATE,
|
||||
latencyHint: 'interactive'
|
||||
});
|
||||
log('创建音频上下文,采样率: ' + this.SAMPLE_RATE + 'Hz', 'debug');
|
||||
}
|
||||
return this.audioContext;
|
||||
}
|
||||
|
||||
// 初始化Opus解码器
|
||||
async initOpusDecoder() {
|
||||
if (this.opusDecoder) return this.opusDecoder;
|
||||
|
||||
try {
|
||||
if (typeof window.ModuleInstance === 'undefined') {
|
||||
if (typeof Module !== 'undefined') {
|
||||
window.ModuleInstance = Module;
|
||||
log('使用全局Module作为ModuleInstance', 'info');
|
||||
} else {
|
||||
throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在');
|
||||
}
|
||||
}
|
||||
|
||||
const mod = window.ModuleInstance;
|
||||
|
||||
this.opusDecoder = {
|
||||
channels: this.CHANNELS,
|
||||
rate: this.SAMPLE_RATE,
|
||||
frameSize: this.FRAME_SIZE,
|
||||
module: mod,
|
||||
decoderPtr: null,
|
||||
|
||||
init: function () {
|
||||
if (this.decoderPtr) return true;
|
||||
|
||||
const decoderSize = mod._opus_decoder_get_size(this.channels);
|
||||
log(`Opus解码器大小: ${decoderSize}字节`, 'debug');
|
||||
|
||||
this.decoderPtr = mod._malloc(decoderSize);
|
||||
if (!this.decoderPtr) {
|
||||
throw new Error("无法分配解码器内存");
|
||||
}
|
||||
|
||||
const err = mod._opus_decoder_init(
|
||||
this.decoderPtr,
|
||||
this.rate,
|
||||
this.channels
|
||||
);
|
||||
|
||||
if (err < 0) {
|
||||
this.destroy();
|
||||
throw new Error(`Opus解码器初始化失败: ${err}`);
|
||||
}
|
||||
|
||||
log("Opus解码器初始化成功", 'success');
|
||||
return true;
|
||||
},
|
||||
|
||||
decode: function (opusData) {
|
||||
if (!this.decoderPtr) {
|
||||
if (!this.init()) {
|
||||
throw new Error("解码器未初始化且无法初始化");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = this.module;
|
||||
|
||||
const opusPtr = mod._malloc(opusData.length);
|
||||
mod.HEAPU8.set(opusData, opusPtr);
|
||||
|
||||
const pcmPtr = mod._malloc(this.frameSize * 2);
|
||||
|
||||
const decodedSamples = mod._opus_decode(
|
||||
this.decoderPtr,
|
||||
opusPtr,
|
||||
opusData.length,
|
||||
pcmPtr,
|
||||
this.frameSize,
|
||||
0
|
||||
);
|
||||
|
||||
if (decodedSamples < 0) {
|
||||
mod._free(opusPtr);
|
||||
mod._free(pcmPtr);
|
||||
throw new Error(`Opus解码失败: ${decodedSamples}`);
|
||||
}
|
||||
|
||||
const decodedData = new Int16Array(decodedSamples);
|
||||
for (let i = 0; i < decodedSamples; i++) {
|
||||
decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i];
|
||||
}
|
||||
|
||||
mod._free(opusPtr);
|
||||
mod._free(pcmPtr);
|
||||
|
||||
return decodedData;
|
||||
} catch (error) {
|
||||
log(`Opus解码错误: ${error.message}`, 'error');
|
||||
return new Int16Array(0);
|
||||
}
|
||||
},
|
||||
|
||||
destroy: function () {
|
||||
if (this.decoderPtr) {
|
||||
this.module._free(this.decoderPtr);
|
||||
this.decoderPtr = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (!this.opusDecoder.init()) {
|
||||
throw new Error("Opus解码器初始化失败");
|
||||
}
|
||||
|
||||
return this.opusDecoder;
|
||||
|
||||
} catch (error) {
|
||||
log(`Opus解码器初始化失败: ${error.message}`, 'error');
|
||||
this.opusDecoder = null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 启动音频缓冲
|
||||
async startAudioBuffering() {
|
||||
log("开始音频缓冲...", 'info');
|
||||
|
||||
this.initOpusDecoder().catch(error => {
|
||||
log(`预初始化Opus解码器失败: ${error.message}`, 'warning');
|
||||
});
|
||||
|
||||
const timeout = 400;
|
||||
while (true) {
|
||||
const packets = await this.queue.dequeue(
|
||||
6,
|
||||
timeout,
|
||||
(count) => {
|
||||
log(`缓冲超时,当前缓冲包数: ${count},开始播放`, 'info');
|
||||
}
|
||||
);
|
||||
if (packets.length) {
|
||||
log(`已缓冲 ${packets.length} 个音频包,开始播放`, 'info');
|
||||
this.streamingContext.pushAudioBuffer(packets);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
const data = await this.queue.dequeue(99, 30);
|
||||
if (data.length) {
|
||||
this.streamingContext.pushAudioBuffer(data);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 播放已缓冲的音频
|
||||
async playBufferedAudio() {
|
||||
try {
|
||||
this.audioContext = this.getAudioContext();
|
||||
|
||||
if (!this.opusDecoder) {
|
||||
log('初始化Opus解码器...', 'info');
|
||||
try {
|
||||
this.opusDecoder = await this.initOpusDecoder();
|
||||
if (!this.opusDecoder) {
|
||||
throw new Error('解码器初始化失败');
|
||||
}
|
||||
log('Opus解码器初始化成功', 'success');
|
||||
} catch (error) {
|
||||
log('Opus解码器初始化失败: ' + error.message, 'error');
|
||||
this.isPlaying = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.streamingContext) {
|
||||
this.streamingContext = createStreamingContext(
|
||||
this.opusDecoder,
|
||||
this.audioContext,
|
||||
this.SAMPLE_RATE,
|
||||
this.CHANNELS,
|
||||
this.MIN_AUDIO_DURATION
|
||||
);
|
||||
}
|
||||
|
||||
this.streamingContext.decodeOpusFrames();
|
||||
this.streamingContext.startPlaying();
|
||||
|
||||
} catch (error) {
|
||||
log(`播放已缓冲的音频出错: ${error.message}`, 'error');
|
||||
this.isPlaying = false;
|
||||
this.streamingContext = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 添加音频数据到队列
|
||||
enqueueAudioData(opusData) {
|
||||
if (opusData.length > 0) {
|
||||
this.queue.enqueue(opusData);
|
||||
} else {
|
||||
log('收到空音频数据帧,可能是结束标志', 'warning');
|
||||
if (this.isPlaying && this.streamingContext) {
|
||||
this.streamingContext.endOfStream = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 预加载解码器
|
||||
async preload() {
|
||||
log('预加载Opus解码器...', 'info');
|
||||
try {
|
||||
await this.initOpusDecoder();
|
||||
log('Opus解码器预加载成功', 'success');
|
||||
} catch (error) {
|
||||
log(`Opus解码器预加载失败: ${error.message},将在需要时重试`, 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
// 启动播放系统
|
||||
async start() {
|
||||
await this.preload();
|
||||
this.playBufferedAudio();
|
||||
this.startAudioBuffering();
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例
|
||||
let audioPlayerInstance = null;
|
||||
|
||||
export function getAudioPlayer() {
|
||||
if (!audioPlayerInstance) {
|
||||
audioPlayerInstance = new AudioPlayer();
|
||||
}
|
||||
return audioPlayerInstance;
|
||||
}
|
||||
420
main/xiaozhi-server/test/js/core/audio/recorder.js
Normal file
420
main/xiaozhi-server/test/js/core/audio/recorder.js
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
// 音频录制模块
|
||||
import { log } from '../../utils/logger.js';
|
||||
import { initOpusEncoder } from './opus-codec.js';
|
||||
import { getAudioPlayer } from './player.js';
|
||||
|
||||
// 音频录制器类
|
||||
export class AudioRecorder {
|
||||
constructor() {
|
||||
this.isRecording = false;
|
||||
this.audioContext = null;
|
||||
this.analyser = null;
|
||||
this.audioProcessor = null;
|
||||
this.audioProcessorType = null;
|
||||
this.audioSource = null;
|
||||
this.opusEncoder = null;
|
||||
this.pcmDataBuffer = new Int16Array();
|
||||
this.audioBuffers = [];
|
||||
this.totalAudioSize = 0;
|
||||
this.visualizationRequest = null;
|
||||
this.recordingTimer = null;
|
||||
this.websocket = null;
|
||||
|
||||
// 回调函数
|
||||
this.onRecordingStart = null;
|
||||
this.onRecordingStop = null;
|
||||
this.onVisualizerUpdate = null;
|
||||
}
|
||||
|
||||
// 设置WebSocket实例
|
||||
setWebSocket(ws) {
|
||||
this.websocket = ws;
|
||||
}
|
||||
|
||||
// 获取AudioContext实例
|
||||
getAudioContext() {
|
||||
const audioPlayer = getAudioPlayer();
|
||||
return audioPlayer.getAudioContext();
|
||||
}
|
||||
|
||||
// 初始化编码器
|
||||
initEncoder() {
|
||||
if (!this.opusEncoder) {
|
||||
this.opusEncoder = initOpusEncoder();
|
||||
}
|
||||
return this.opusEncoder;
|
||||
}
|
||||
|
||||
// PCM处理器代码
|
||||
getAudioProcessorCode() {
|
||||
return `
|
||||
class AudioRecorderProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.buffers = [];
|
||||
this.frameSize = 960;
|
||||
this.buffer = new Int16Array(this.frameSize);
|
||||
this.bufferIndex = 0;
|
||||
this.isRecording = false;
|
||||
|
||||
this.port.onmessage = (event) => {
|
||||
if (event.data.command === 'start') {
|
||||
this.isRecording = true;
|
||||
this.port.postMessage({ type: 'status', status: 'started' });
|
||||
} else if (event.data.command === 'stop') {
|
||||
this.isRecording = false;
|
||||
|
||||
if (this.bufferIndex > 0) {
|
||||
const finalBuffer = this.buffer.slice(0, this.bufferIndex);
|
||||
this.port.postMessage({
|
||||
type: 'buffer',
|
||||
buffer: finalBuffer
|
||||
});
|
||||
this.bufferIndex = 0;
|
||||
}
|
||||
|
||||
this.port.postMessage({ type: 'status', status: 'stopped' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
if (!this.isRecording) return true;
|
||||
|
||||
const input = inputs[0][0];
|
||||
if (!input) return true;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
if (this.bufferIndex >= this.frameSize) {
|
||||
this.port.postMessage({
|
||||
type: 'buffer',
|
||||
buffer: this.buffer.slice(0)
|
||||
});
|
||||
this.bufferIndex = 0;
|
||||
}
|
||||
|
||||
this.buffer[this.bufferIndex++] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767)));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('audio-recorder-processor', AudioRecorderProcessor);
|
||||
`;
|
||||
}
|
||||
|
||||
// 创建音频处理器
|
||||
async createAudioProcessor() {
|
||||
this.audioContext = this.getAudioContext();
|
||||
|
||||
try {
|
||||
if (this.audioContext.audioWorklet) {
|
||||
const blob = new Blob([this.getAudioProcessorCode()], { type: 'application/javascript' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
await this.audioContext.audioWorklet.addModule(url);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
const audioProcessor = new AudioWorkletNode(this.audioContext, 'audio-recorder-processor');
|
||||
|
||||
audioProcessor.port.onmessage = (event) => {
|
||||
if (event.data.type === 'buffer') {
|
||||
this.processPCMBuffer(event.data.buffer);
|
||||
}
|
||||
};
|
||||
|
||||
log('使用AudioWorklet处理音频', 'success');
|
||||
|
||||
const silent = this.audioContext.createGain();
|
||||
silent.gain.value = 0;
|
||||
audioProcessor.connect(silent);
|
||||
silent.connect(this.audioContext.destination);
|
||||
return { node: audioProcessor, type: 'worklet' };
|
||||
} else {
|
||||
log('AudioWorklet不可用,使用ScriptProcessorNode作为回退方案', 'warning');
|
||||
return this.createScriptProcessor();
|
||||
}
|
||||
} catch (error) {
|
||||
log(`创建音频处理器失败: ${error.message},尝试回退方案`, 'error');
|
||||
return this.createScriptProcessor();
|
||||
}
|
||||
}
|
||||
|
||||
// 创建ScriptProcessor作为回退
|
||||
createScriptProcessor() {
|
||||
try {
|
||||
const frameSize = 4096;
|
||||
const scriptProcessor = this.audioContext.createScriptProcessor(frameSize, 1, 1);
|
||||
|
||||
scriptProcessor.onaudioprocess = (event) => {
|
||||
if (!this.isRecording) return;
|
||||
|
||||
const input = event.inputBuffer.getChannelData(0);
|
||||
const buffer = new Int16Array(input.length);
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
buffer[i] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767)));
|
||||
}
|
||||
|
||||
this.processPCMBuffer(buffer);
|
||||
};
|
||||
|
||||
const silent = this.audioContext.createGain();
|
||||
silent.gain.value = 0;
|
||||
scriptProcessor.connect(silent);
|
||||
silent.connect(this.audioContext.destination);
|
||||
|
||||
log('使用ScriptProcessorNode作为回退方案成功', 'warning');
|
||||
return { node: scriptProcessor, type: 'processor' };
|
||||
} catch (fallbackError) {
|
||||
log(`回退方案也失败: ${fallbackError.message}`, 'error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理PCM缓冲数据
|
||||
processPCMBuffer(buffer) {
|
||||
if (!this.isRecording) return;
|
||||
|
||||
const newBuffer = new Int16Array(this.pcmDataBuffer.length + buffer.length);
|
||||
newBuffer.set(this.pcmDataBuffer);
|
||||
newBuffer.set(buffer, this.pcmDataBuffer.length);
|
||||
this.pcmDataBuffer = newBuffer;
|
||||
|
||||
const samplesPerFrame = 960;
|
||||
|
||||
while (this.pcmDataBuffer.length >= samplesPerFrame) {
|
||||
const frameData = this.pcmDataBuffer.slice(0, samplesPerFrame);
|
||||
this.pcmDataBuffer = this.pcmDataBuffer.slice(samplesPerFrame);
|
||||
|
||||
this.encodeAndSendOpus(frameData);
|
||||
}
|
||||
}
|
||||
|
||||
// 编码并发送Opus数据
|
||||
encodeAndSendOpus(pcmData = null) {
|
||||
if (!this.opusEncoder) {
|
||||
log('Opus编码器未初始化', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (pcmData) {
|
||||
const opusData = this.opusEncoder.encode(pcmData);
|
||||
|
||||
if (opusData && opusData.length > 0) {
|
||||
this.audioBuffers.push(opusData.buffer);
|
||||
this.totalAudioSize += opusData.length;
|
||||
|
||||
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
||||
try {
|
||||
this.websocket.send(opusData.buffer);
|
||||
log(`发送Opus帧,大小:${opusData.length}字节`, 'debug');
|
||||
} catch (error) {
|
||||
log(`WebSocket发送错误: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log('Opus编码失败,无有效数据返回', 'error');
|
||||
}
|
||||
} else {
|
||||
if (this.pcmDataBuffer.length > 0) {
|
||||
const samplesPerFrame = 960;
|
||||
if (this.pcmDataBuffer.length < samplesPerFrame) {
|
||||
const paddedBuffer = new Int16Array(samplesPerFrame);
|
||||
paddedBuffer.set(this.pcmDataBuffer);
|
||||
this.encodeAndSendOpus(paddedBuffer);
|
||||
} else {
|
||||
this.encodeAndSendOpus(this.pcmDataBuffer.slice(0, samplesPerFrame));
|
||||
}
|
||||
this.pcmDataBuffer = new Int16Array(0);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log(`Opus编码错误: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 开始录音
|
||||
async start() {
|
||||
if (this.isRecording) return false;
|
||||
|
||||
try {
|
||||
if (!this.initEncoder()) {
|
||||
log('无法启动录音: Opus编码器初始化失败', 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
log('请至少录制1-2秒钟的音频,确保采集到足够数据', 'info');
|
||||
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
sampleRate: 16000,
|
||||
channelCount: 1
|
||||
}
|
||||
});
|
||||
|
||||
this.audioContext = this.getAudioContext();
|
||||
|
||||
if (this.audioContext.state === 'suspended') {
|
||||
await this.audioContext.resume();
|
||||
}
|
||||
|
||||
const processorResult = await this.createAudioProcessor();
|
||||
if (!processorResult) {
|
||||
log('无法创建音频处理器', 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
this.audioProcessor = processorResult.node;
|
||||
this.audioProcessorType = processorResult.type;
|
||||
|
||||
this.audioSource = this.audioContext.createMediaStreamSource(stream);
|
||||
this.analyser = this.audioContext.createAnalyser();
|
||||
this.analyser.fftSize = 2048;
|
||||
|
||||
this.audioSource.connect(this.analyser);
|
||||
this.audioSource.connect(this.audioProcessor);
|
||||
|
||||
this.pcmDataBuffer = new Int16Array();
|
||||
this.audioBuffers = [];
|
||||
this.totalAudioSize = 0;
|
||||
this.isRecording = true;
|
||||
|
||||
if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) {
|
||||
this.audioProcessor.port.postMessage({ command: 'start' });
|
||||
}
|
||||
|
||||
// 发送监听开始消息
|
||||
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
||||
const listenMessage = {
|
||||
type: 'listen',
|
||||
mode: 'manual',
|
||||
state: 'start'
|
||||
};
|
||||
|
||||
log(`发送录音开始消息: ${JSON.stringify(listenMessage)}`, 'info');
|
||||
this.websocket.send(JSON.stringify(listenMessage));
|
||||
} else {
|
||||
log('WebSocket未连接,无法发送开始消息', 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 开始可视化
|
||||
if (this.onVisualizerUpdate) {
|
||||
const dataArray = new Uint8Array(this.analyser.frequencyBinCount);
|
||||
this.startVisualization(dataArray);
|
||||
}
|
||||
|
||||
// 启动录音计时器
|
||||
let recordingSeconds = 0;
|
||||
this.recordingTimer = setInterval(() => {
|
||||
recordingSeconds += 0.1;
|
||||
if (this.onRecordingStart) {
|
||||
this.onRecordingStart(recordingSeconds);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
log('开始PCM直接录音', 'success');
|
||||
return true;
|
||||
} catch (error) {
|
||||
log(`直接录音启动错误: ${error.message}`, 'error');
|
||||
this.isRecording = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 开始可视化
|
||||
startVisualization(dataArray) {
|
||||
const draw = () => {
|
||||
this.visualizationRequest = requestAnimationFrame(() => draw());
|
||||
|
||||
if (!this.isRecording) return;
|
||||
|
||||
this.analyser.getByteFrequencyData(dataArray);
|
||||
|
||||
if (this.onVisualizerUpdate) {
|
||||
this.onVisualizerUpdate(dataArray);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
}
|
||||
|
||||
// 停止录音
|
||||
stop() {
|
||||
if (!this.isRecording) return false;
|
||||
|
||||
try {
|
||||
this.isRecording = false;
|
||||
|
||||
if (this.audioProcessor) {
|
||||
if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) {
|
||||
this.audioProcessor.port.postMessage({ command: 'stop' });
|
||||
}
|
||||
|
||||
this.audioProcessor.disconnect();
|
||||
this.audioProcessor = null;
|
||||
}
|
||||
|
||||
if (this.audioSource) {
|
||||
this.audioSource.disconnect();
|
||||
this.audioSource = null;
|
||||
}
|
||||
|
||||
if (this.visualizationRequest) {
|
||||
cancelAnimationFrame(this.visualizationRequest);
|
||||
this.visualizationRequest = null;
|
||||
}
|
||||
|
||||
if (this.recordingTimer) {
|
||||
clearInterval(this.recordingTimer);
|
||||
this.recordingTimer = null;
|
||||
}
|
||||
|
||||
// 编码并发送剩余的数据
|
||||
this.encodeAndSendOpus();
|
||||
|
||||
// 发送结束信号
|
||||
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
||||
const emptyOpusFrame = new Uint8Array(0);
|
||||
this.websocket.send(emptyOpusFrame);
|
||||
|
||||
const stopMessage = {
|
||||
type: 'listen',
|
||||
mode: 'manual',
|
||||
state: 'stop'
|
||||
};
|
||||
|
||||
this.websocket.send(JSON.stringify(stopMessage));
|
||||
log('已发送录音停止信号', 'info');
|
||||
}
|
||||
|
||||
if (this.onRecordingStop) {
|
||||
this.onRecordingStop();
|
||||
}
|
||||
|
||||
log('停止PCM直接录音', 'success');
|
||||
return true;
|
||||
} catch (error) {
|
||||
log(`直接录音停止错误: ${error.message}`, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取分析器
|
||||
getAnalyser() {
|
||||
return this.analyser;
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例
|
||||
let audioRecorderInstance = null;
|
||||
|
||||
export function getAudioRecorder() {
|
||||
if (!audioRecorderInstance) {
|
||||
audioRecorderInstance = new AudioRecorder();
|
||||
}
|
||||
return audioRecorderInstance;
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import BlockingQueue from './utils/BlockingQueue.js';
|
||||
import { log } from './utils/logger.js';
|
||||
import BlockingQueue from '../../utils/blocking-queue.js';
|
||||
import { log } from '../../utils/logger.js';
|
||||
|
||||
// 音频流播放上下文类
|
||||
export class StreamingContext {
|
||||
|
|
@ -48,8 +48,8 @@ export class StreamingContext {
|
|||
convertInt16ToFloat32(int16Data) {
|
||||
const float32Data = new Float32Array(int16Data.length);
|
||||
for (let i = 0; i < int16Data.length; i++) {
|
||||
// 将[-32768,32767]范围转换为[-1,1]
|
||||
float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF);
|
||||
// 将[-32768,32767]范围转换为[-1,1],统一使用32768.0避免不对称失真
|
||||
float32Data[i] = int16Data[i] / 32768.0;
|
||||
}
|
||||
return float32Data;
|
||||
}
|
||||
|
|
@ -97,18 +97,26 @@ export class StreamingContext {
|
|||
|
||||
// 开始播放音频
|
||||
async startPlaying() {
|
||||
let scheduledEndTime = this.audioContext.currentTime; // 跟踪已调度音频的结束时间
|
||||
|
||||
while (true) {
|
||||
// 如果累积了至少0.3秒的音频,开始播放
|
||||
const minSamples = this.sampleRate * this.minAudioDuration * 3;
|
||||
// 初始缓冲:等待足够的样本再开始播放
|
||||
const minSamples = this.sampleRate * this.minAudioDuration * 2;
|
||||
if (!this.playing && this.queue.length < minSamples) {
|
||||
await this.getQueue(minSamples);
|
||||
}
|
||||
this.playing = true;
|
||||
while (this.playing && this.queue.length) {
|
||||
// 创建新的音频缓冲区
|
||||
const minPlaySamples = Math.min(this.queue.length, this.sampleRate);
|
||||
const currentSamples = this.queue.splice(0, minPlaySamples);
|
||||
|
||||
// 持续播放队列中的音频,每次播放一个小块
|
||||
while (this.playing && this.queue.length > 0) {
|
||||
// 每次播放120ms的音频(2个Opus包)
|
||||
const playDuration = 0.12;
|
||||
const targetSamples = Math.floor(this.sampleRate * playDuration);
|
||||
const actualSamples = Math.min(this.queue.length, targetSamples);
|
||||
|
||||
if (actualSamples === 0) break;
|
||||
|
||||
const currentSamples = this.queue.splice(0, actualSamples);
|
||||
const audioBuffer = this.audioContext.createBuffer(this.channels, currentSamples.length, this.sampleRate);
|
||||
audioBuffer.copyToChannel(new Float32Array(currentSamples), 0);
|
||||
|
||||
|
|
@ -116,28 +124,28 @@ export class StreamingContext {
|
|||
this.source = this.audioContext.createBufferSource();
|
||||
this.source.buffer = audioBuffer;
|
||||
|
||||
// 创建增益节点用于平滑过渡
|
||||
const gainNode = this.audioContext.createGain();
|
||||
// 精确调度播放时间
|
||||
const currentTime = this.audioContext.currentTime;
|
||||
const startTime = Math.max(scheduledEndTime, currentTime);
|
||||
|
||||
// 应用淡入淡出效果避免爆音
|
||||
const fadeDuration = 0.02; // 20毫秒
|
||||
gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
|
||||
gainNode.gain.linearRampToValueAtTime(1, this.audioContext.currentTime + fadeDuration);
|
||||
// 直接连接到输出
|
||||
this.source.connect(this.audioContext.destination);
|
||||
|
||||
log(`调度播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / this.sampleRate).toFixed(2)} 秒`, 'debug');
|
||||
this.source.start(startTime);
|
||||
|
||||
// 更新下一个音频块的调度时间
|
||||
const duration = audioBuffer.duration;
|
||||
if (duration > fadeDuration * 2) {
|
||||
gainNode.gain.setValueAtTime(1, this.audioContext.currentTime + duration - fadeDuration);
|
||||
gainNode.gain.linearRampToValueAtTime(0, this.audioContext.currentTime + duration);
|
||||
scheduledEndTime = startTime + duration;
|
||||
this.lastPlayTime = startTime;
|
||||
|
||||
// 如果队列中数据不足,等待新数据
|
||||
if (this.queue.length < targetSamples) {
|
||||
break;
|
||||
}
|
||||
|
||||
// 连接节点并开始播放
|
||||
this.source.connect(gainNode);
|
||||
gainNode.connect(this.audioContext.destination);
|
||||
|
||||
this.lastPlayTime = this.audioContext.currentTime;
|
||||
log(`开始播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / this.sampleRate).toFixed(2)} 秒`, 'info');
|
||||
this.source.start();
|
||||
}
|
||||
|
||||
// 等待新数据
|
||||
await this.getQueue(minSamples);
|
||||
}
|
||||
}
|
||||
477
main/xiaozhi-server/test/js/core/mcp/tools.js
Normal file
477
main/xiaozhi-server/test/js/core/mcp/tools.js
Normal file
|
|
@ -0,0 +1,477 @@
|
|||
import { log } from '../../utils/logger.js';
|
||||
|
||||
// ==========================================
|
||||
// MCP 工具管理逻辑
|
||||
// ==========================================
|
||||
|
||||
// 全局变量
|
||||
let mcpTools = [];
|
||||
let mcpEditingIndex = null;
|
||||
let mcpProperties = [];
|
||||
let websocket = null; // 将从外部设置
|
||||
|
||||
/**
|
||||
* 设置 WebSocket 实例
|
||||
* @param {WebSocket} ws - WebSocket 连接实例
|
||||
*/
|
||||
export function setWebSocket(ws) {
|
||||
websocket = ws;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 MCP 工具
|
||||
*/
|
||||
export async function initMcpTools() {
|
||||
// 加载默认工具数据
|
||||
const defaultMcpTools = await fetch("js/config/default-mcp-tools.json").then(res => res.json());
|
||||
|
||||
const savedTools = localStorage.getItem('mcpTools');
|
||||
if (savedTools) {
|
||||
try {
|
||||
mcpTools = JSON.parse(savedTools);
|
||||
} catch (e) {
|
||||
log('加载MCP工具失败,使用默认工具', 'warning');
|
||||
mcpTools = [...defaultMcpTools];
|
||||
}
|
||||
} else {
|
||||
mcpTools = [...defaultMcpTools];
|
||||
}
|
||||
|
||||
renderMcpTools();
|
||||
setupMcpEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染工具列表
|
||||
*/
|
||||
function renderMcpTools() {
|
||||
const container = document.getElementById('mcpToolsContainer');
|
||||
const countSpan = document.getElementById('mcpToolsCount');
|
||||
|
||||
countSpan.textContent = `${mcpTools.length} 个工具`;
|
||||
|
||||
if (mcpTools.length === 0) {
|
||||
container.innerHTML = '<div style="text-align: center; padding: 30px; color: #999;">暂无工具,点击下方按钮添加新工具</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = mcpTools.map((tool, index) => {
|
||||
const paramCount = tool.inputSchema.properties ? Object.keys(tool.inputSchema.properties).length : 0;
|
||||
const requiredCount = tool.inputSchema.required ? tool.inputSchema.required.length : 0;
|
||||
const hasMockResponse = tool.mockResponse && Object.keys(tool.mockResponse).length > 0;
|
||||
|
||||
return `
|
||||
<div class="mcp-tool-card">
|
||||
<div class="mcp-tool-header">
|
||||
<div class="mcp-tool-name">${tool.name}</div>
|
||||
<div class="mcp-tool-actions">
|
||||
<button onclick="window.mcpModule.editMcpTool(${index})"
|
||||
style="padding: 4px 10px; border: none; border-radius: 4px; background-color: #2196f3; color: white; cursor: pointer; font-size: 12px;">
|
||||
✏️ 编辑
|
||||
</button>
|
||||
<button onclick="window.mcpModule.deleteMcpTool(${index})"
|
||||
style="padding: 4px 10px; border: none; border-radius: 4px; background-color: #f44336; color: white; cursor: pointer; font-size: 12px;">
|
||||
🗑️ 删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mcp-tool-description">${tool.description}</div>
|
||||
<div class="mcp-tool-info">
|
||||
<div class="mcp-tool-info-row">
|
||||
<span class="mcp-tool-info-label">参数数量:</span>
|
||||
<span class="mcp-tool-info-value">${paramCount} 个 ${requiredCount > 0 ? `(${requiredCount} 个必填)` : ''}</span>
|
||||
</div>
|
||||
<div class="mcp-tool-info-row">
|
||||
<span class="mcp-tool-info-label">模拟返回:</span>
|
||||
<span class="mcp-tool-info-value">${hasMockResponse ? '✅ 已配置: ' + JSON.stringify(tool.mockResponse) : '⚪ 使用默认'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染参数列表
|
||||
*/
|
||||
function renderMcpProperties() {
|
||||
const container = document.getElementById('mcpPropertiesContainer');
|
||||
|
||||
if (mcpProperties.length === 0) {
|
||||
container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999; font-size: 14px;">暂无参数,点击下方按钮添加参数</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = mcpProperties.map((prop, index) => `
|
||||
<div class="mcp-property-item">
|
||||
<div class="mcp-property-header">
|
||||
<span class="mcp-property-name">${prop.name}</span>
|
||||
<button type="button" onclick="window.mcpModule.deleteMcpProperty(${index})"
|
||||
style="padding: 3px 8px; border: none; border-radius: 3px; background-color: #f44336; color: white; cursor: pointer; font-size: 11px;">
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
<div class="mcp-property-row">
|
||||
<div>
|
||||
<label class="mcp-small-label">参数名称 *</label>
|
||||
<input type="text" class="mcp-small-input" value="${prop.name}"
|
||||
onchange="window.mcpModule.updateMcpProperty(${index}, 'name', this.value)" required>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mcp-small-label">数据类型 *</label>
|
||||
<select class="mcp-small-input" onchange="window.mcpModule.updateMcpProperty(${index}, 'type', this.value)">
|
||||
<option value="string" ${prop.type === 'string' ? 'selected' : ''}>字符串</option>
|
||||
<option value="integer" ${prop.type === 'integer' ? 'selected' : ''}>整数</option>
|
||||
<option value="number" ${prop.type === 'number' ? 'selected' : ''}>数字</option>
|
||||
<option value="boolean" ${prop.type === 'boolean' ? 'selected' : ''}>布尔值</option>
|
||||
<option value="array" ${prop.type === 'array' ? 'selected' : ''}>数组</option>
|
||||
<option value="object" ${prop.type === 'object' ? 'selected' : ''}>对象</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
${(prop.type === 'integer' || prop.type === 'number') ? `
|
||||
<div class="mcp-property-row">
|
||||
<div>
|
||||
<label class="mcp-small-label">最小值</label>
|
||||
<input type="number" class="mcp-small-input" value="${prop.minimum !== undefined ? prop.minimum : ''}"
|
||||
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'minimum', this.value ? parseFloat(this.value) : undefined)">
|
||||
</div>
|
||||
<div>
|
||||
<label class="mcp-small-label">最大值</label>
|
||||
<input type="number" class="mcp-small-input" value="${prop.maximum !== undefined ? prop.maximum : ''}"
|
||||
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'maximum', this.value ? parseFloat(this.value) : undefined)">
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
<div class="mcp-property-row-full">
|
||||
<label class="mcp-small-label">参数描述</label>
|
||||
<input type="text" class="mcp-small-input" value="${prop.description || ''}"
|
||||
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'description', this.value)">
|
||||
</div>
|
||||
<label class="mcp-checkbox-label">
|
||||
<input type="checkbox" ${prop.required ? 'checked' : ''}
|
||||
onchange="window.mcpModule.updateMcpProperty(${index}, 'required', this.checked)">
|
||||
必填参数
|
||||
</label>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加参数
|
||||
*/
|
||||
function addMcpProperty() {
|
||||
mcpProperties.push({
|
||||
name: `param_${mcpProperties.length + 1}`,
|
||||
type: 'string',
|
||||
required: false,
|
||||
description: ''
|
||||
});
|
||||
renderMcpProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新参数
|
||||
*/
|
||||
function updateMcpProperty(index, field, value) {
|
||||
if (field === 'name') {
|
||||
const isDuplicate = mcpProperties.some((p, i) => i !== index && p.name === value);
|
||||
if (isDuplicate) {
|
||||
alert('参数名称已存在,请使用不同的名称');
|
||||
renderMcpProperties();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
mcpProperties[index][field] = value;
|
||||
|
||||
if (field === 'type' && value !== 'integer' && value !== 'number') {
|
||||
delete mcpProperties[index].minimum;
|
||||
delete mcpProperties[index].maximum;
|
||||
renderMcpProperties();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除参数
|
||||
*/
|
||||
function deleteMcpProperty(index) {
|
||||
mcpProperties.splice(index, 1);
|
||||
renderMcpProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置事件监听
|
||||
*/
|
||||
function setupMcpEventListeners() {
|
||||
const toggleBtn = document.getElementById('toggleMcpTools');
|
||||
const panel = document.getElementById('mcpToolsPanel');
|
||||
const addBtn = document.getElementById('addMcpToolBtn');
|
||||
const modal = document.getElementById('mcpToolModal');
|
||||
const closeBtn = document.getElementById('closeMcpModalBtn');
|
||||
const cancelBtn = document.getElementById('cancelMcpBtn');
|
||||
const form = document.getElementById('mcpToolForm');
|
||||
const addPropertyBtn = document.getElementById('addMcpPropertyBtn');
|
||||
|
||||
toggleBtn.addEventListener('click', () => {
|
||||
const isExpanded = panel.classList.contains('expanded');
|
||||
panel.classList.toggle('expanded');
|
||||
toggleBtn.textContent = isExpanded ? '展开' : '收起';
|
||||
});
|
||||
|
||||
addBtn.addEventListener('click', () => openMcpModal());
|
||||
closeBtn.addEventListener('click', closeMcpModal);
|
||||
cancelBtn.addEventListener('click', closeMcpModal);
|
||||
addPropertyBtn.addEventListener('click', addMcpProperty);
|
||||
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) closeMcpModal();
|
||||
});
|
||||
|
||||
form.addEventListener('submit', handleMcpSubmit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开模态框
|
||||
*/
|
||||
function openMcpModal(index = null) {
|
||||
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
|
||||
if (isConnected) {
|
||||
alert('WebSocket 已连接,无法编辑工具');
|
||||
return;
|
||||
}
|
||||
|
||||
mcpEditingIndex = index;
|
||||
const errorContainer = document.getElementById('mcpErrorContainer');
|
||||
errorContainer.innerHTML = '';
|
||||
|
||||
if (index !== null) {
|
||||
document.getElementById('mcpModalTitle').textContent = '编辑工具';
|
||||
const tool = mcpTools[index];
|
||||
document.getElementById('mcpToolName').value = tool.name;
|
||||
document.getElementById('mcpToolDescription').value = tool.description;
|
||||
document.getElementById('mcpMockResponse').value = tool.mockResponse ? JSON.stringify(tool.mockResponse, null, 2) : '';
|
||||
|
||||
mcpProperties = [];
|
||||
const schema = tool.inputSchema;
|
||||
if (schema.properties) {
|
||||
Object.keys(schema.properties).forEach(key => {
|
||||
const prop = schema.properties[key];
|
||||
mcpProperties.push({
|
||||
name: key,
|
||||
type: prop.type || 'string',
|
||||
minimum: prop.minimum,
|
||||
maximum: prop.maximum,
|
||||
description: prop.description || '',
|
||||
required: schema.required && schema.required.includes(key)
|
||||
});
|
||||
});
|
||||
}
|
||||
} else {
|
||||
document.getElementById('mcpModalTitle').textContent = '添加工具';
|
||||
document.getElementById('mcpToolForm').reset();
|
||||
mcpProperties = [];
|
||||
}
|
||||
|
||||
renderMcpProperties();
|
||||
document.getElementById('mcpToolModal').style.display = 'block';
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭模态框
|
||||
*/
|
||||
function closeMcpModal() {
|
||||
document.getElementById('mcpToolModal').style.display = 'none';
|
||||
mcpEditingIndex = null;
|
||||
document.getElementById('mcpToolForm').reset();
|
||||
mcpProperties = [];
|
||||
document.getElementById('mcpErrorContainer').innerHTML = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理表单提交
|
||||
*/
|
||||
function handleMcpSubmit(e) {
|
||||
e.preventDefault();
|
||||
const errorContainer = document.getElementById('mcpErrorContainer');
|
||||
errorContainer.innerHTML = '';
|
||||
|
||||
const name = document.getElementById('mcpToolName').value.trim();
|
||||
const description = document.getElementById('mcpToolDescription').value.trim();
|
||||
const mockResponseText = document.getElementById('mcpMockResponse').value.trim();
|
||||
|
||||
// 检查名称重复
|
||||
const isDuplicate = mcpTools.some((tool, index) =>
|
||||
tool.name === name && index !== mcpEditingIndex
|
||||
);
|
||||
|
||||
if (isDuplicate) {
|
||||
showMcpError('工具名称已存在,请使用不同的名称');
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析模拟返回结果
|
||||
let mockResponse = null;
|
||||
if (mockResponseText) {
|
||||
try {
|
||||
mockResponse = JSON.parse(mockResponseText);
|
||||
} catch (e) {
|
||||
showMcpError('模拟返回结果不是有效的 JSON 格式: ' + e.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 构建 inputSchema
|
||||
const inputSchema = {
|
||||
type: "object",
|
||||
properties: {},
|
||||
required: []
|
||||
};
|
||||
|
||||
mcpProperties.forEach(prop => {
|
||||
const propSchema = { type: prop.type };
|
||||
|
||||
if (prop.description) {
|
||||
propSchema.description = prop.description;
|
||||
}
|
||||
|
||||
if ((prop.type === 'integer' || prop.type === 'number')) {
|
||||
if (prop.minimum !== undefined && prop.minimum !== '') {
|
||||
propSchema.minimum = prop.minimum;
|
||||
}
|
||||
if (prop.maximum !== undefined && prop.maximum !== '') {
|
||||
propSchema.maximum = prop.maximum;
|
||||
}
|
||||
}
|
||||
|
||||
inputSchema.properties[prop.name] = propSchema;
|
||||
|
||||
if (prop.required) {
|
||||
inputSchema.required.push(prop.name);
|
||||
}
|
||||
});
|
||||
|
||||
if (inputSchema.required.length === 0) {
|
||||
delete inputSchema.required;
|
||||
}
|
||||
|
||||
const tool = { name, description, inputSchema, mockResponse };
|
||||
|
||||
if (mcpEditingIndex !== null) {
|
||||
mcpTools[mcpEditingIndex] = tool;
|
||||
log(`已更新工具: ${name}`, 'success');
|
||||
} else {
|
||||
mcpTools.push(tool);
|
||||
log(`已添加工具: ${name}`, 'success');
|
||||
}
|
||||
|
||||
saveMcpTools();
|
||||
renderMcpTools();
|
||||
closeMcpModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示错误
|
||||
*/
|
||||
function showMcpError(message) {
|
||||
const errorContainer = document.getElementById('mcpErrorContainer');
|
||||
errorContainer.innerHTML = `<div class="mcp-error">${message}</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑工具
|
||||
*/
|
||||
function editMcpTool(index) {
|
||||
openMcpModal(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除工具
|
||||
*/
|
||||
function deleteMcpTool(index) {
|
||||
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
|
||||
if (isConnected) {
|
||||
alert('WebSocket 已连接,无法编辑工具');
|
||||
return;
|
||||
}
|
||||
if (confirm(`确定要删除工具 "${mcpTools[index].name}" 吗?`)) {
|
||||
const toolName = mcpTools[index].name;
|
||||
mcpTools.splice(index, 1);
|
||||
saveMcpTools();
|
||||
renderMcpTools();
|
||||
log(`已删除工具: ${toolName}`, 'info');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存工具
|
||||
*/
|
||||
function saveMcpTools() {
|
||||
localStorage.setItem('mcpTools', JSON.stringify(mcpTools));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取工具列表
|
||||
*/
|
||||
export function getMcpTools() {
|
||||
return mcpTools.map(tool => ({
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行工具调用
|
||||
*/
|
||||
export function executeMcpTool(toolName, toolArgs) {
|
||||
const tool = mcpTools.find(t => t.name === toolName);
|
||||
|
||||
if (!tool) {
|
||||
log(`未找到工具: ${toolName}`, 'error');
|
||||
return {
|
||||
success: false,
|
||||
error: `未知工具: ${toolName}`
|
||||
};
|
||||
}
|
||||
|
||||
// 如果有模拟返回结果,使用它
|
||||
if (tool.mockResponse) {
|
||||
// 替换模板变量
|
||||
let responseStr = JSON.stringify(tool.mockResponse);
|
||||
|
||||
// 替换 ${paramName} 格式的变量
|
||||
if (toolArgs) {
|
||||
Object.keys(toolArgs).forEach(key => {
|
||||
const regex = new RegExp(`\\$\\{${key}\\}`, 'g');
|
||||
responseStr = responseStr.replace(regex, toolArgs[key]);
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const response = JSON.parse(responseStr);
|
||||
log(`工具 ${toolName} 执行成功,返回模拟结果: ${responseStr}`, 'success');
|
||||
return response;
|
||||
} catch (e) {
|
||||
log(`解析模拟返回结果失败: ${e.message}`, 'error');
|
||||
return tool.mockResponse;
|
||||
}
|
||||
}
|
||||
|
||||
// 没有模拟返回结果,返回默认成功消息
|
||||
log(`工具 ${toolName} 执行成功,返回默认结果`, 'success');
|
||||
return {
|
||||
success: true,
|
||||
message: `工具 ${toolName} 执行成功`,
|
||||
tool: toolName,
|
||||
arguments: toolArgs
|
||||
};
|
||||
}
|
||||
|
||||
// 暴露全局方法供 HTML 内联事件调用
|
||||
window.mcpModule = {
|
||||
updateMcpProperty,
|
||||
deleteMcpProperty,
|
||||
editMcpTool,
|
||||
deleteMcpTool
|
||||
};
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { otaStatusStyle } from './document.js';
|
||||
import { log } from './utils/logger.js';
|
||||
import { otaStatusStyle } from '../../ui/dom-helper.js';
|
||||
import { log } from '../../utils/logger.js';
|
||||
|
||||
// WebSocket 连接
|
||||
export async function webSocketConnect(otaUrl, config) {
|
||||
372
main/xiaozhi-server/test/js/core/network/websocket.js
Normal file
372
main/xiaozhi-server/test/js/core/network/websocket.js
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
// WebSocket消息处理模块
|
||||
import { log } from '../../utils/logger.js';
|
||||
import { addMessage } from '../../ui/dom-helper.js';
|
||||
import { webSocketConnect } from './ota-connector.js';
|
||||
import { getConfig, saveConnectionUrls } from '../../config/manager.js';
|
||||
import { getAudioPlayer } from '../audio/player.js';
|
||||
import { getAudioRecorder } from '../audio/recorder.js';
|
||||
import { getMcpTools, executeMcpTool, setWebSocket as setMcpWebSocket } from '../mcp/tools.js';
|
||||
|
||||
// WebSocket处理器类
|
||||
export class WebSocketHandler {
|
||||
constructor() {
|
||||
this.websocket = null;
|
||||
this.onConnectionStateChange = null;
|
||||
this.onRecordButtonStateChange = null;
|
||||
this.onSessionStateChange = null;
|
||||
this.onSessionEmotionChange = null;
|
||||
this.currentSessionId = null;
|
||||
this.isRemoteSpeaking = false;
|
||||
}
|
||||
|
||||
// 发送hello握手消息
|
||||
async sendHelloMessage() {
|
||||
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return false;
|
||||
|
||||
try {
|
||||
const config = getConfig();
|
||||
|
||||
const helloMessage = {
|
||||
type: 'hello',
|
||||
device_id: config.deviceId,
|
||||
device_name: config.deviceName,
|
||||
device_mac: config.deviceMac,
|
||||
token: config.token,
|
||||
features: {
|
||||
mcp: true
|
||||
}
|
||||
};
|
||||
|
||||
log('发送hello握手消息', 'info');
|
||||
this.websocket.send(JSON.stringify(helloMessage));
|
||||
|
||||
return new Promise(resolve => {
|
||||
const timeout = setTimeout(() => {
|
||||
log('等待hello响应超时', 'error');
|
||||
log('提示: 请尝试点击"测试认证"按钮进行连接排查', 'info');
|
||||
resolve(false);
|
||||
}, 5000);
|
||||
|
||||
const onMessageHandler = (event) => {
|
||||
try {
|
||||
const response = JSON.parse(event.data);
|
||||
if (response.type === 'hello' && response.session_id) {
|
||||
log(`服务器握手成功,会话ID: ${response.session_id}`, 'success');
|
||||
clearTimeout(timeout);
|
||||
this.websocket.removeEventListener('message', onMessageHandler);
|
||||
resolve(true);
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略非JSON消息
|
||||
}
|
||||
};
|
||||
|
||||
this.websocket.addEventListener('message', onMessageHandler);
|
||||
});
|
||||
} catch (error) {
|
||||
log(`发送hello消息错误: ${error.message}`, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理文本消息
|
||||
handleTextMessage(message) {
|
||||
if (message.type === 'hello') {
|
||||
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
|
||||
} else if (message.type === 'tts') {
|
||||
this.handleTTSMessage(message);
|
||||
} else if (message.type === 'audio') {
|
||||
log(`收到音频控制消息: ${JSON.stringify(message)}`, 'info');
|
||||
} else if (message.type === 'stt') {
|
||||
log(`识别结果: ${message.text}`, 'info');
|
||||
addMessage(`${message.text}`, true);
|
||||
} else if (message.type === 'llm') {
|
||||
log(`大模型回复: ${message.text}`, 'info');
|
||||
|
||||
// 如果包含表情,更新sessionStatus表情
|
||||
if (message.text && /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u.test(message.text)) {
|
||||
// 提取表情符号
|
||||
const emojiMatch = message.text.match(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u);
|
||||
if (emojiMatch && this.onSessionEmotionChange) {
|
||||
this.onSessionEmotionChange(emojiMatch[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// 只有当文本不仅仅是表情时,才添加到对话中
|
||||
// 移除文本中的表情后检查是否还有内容
|
||||
const textWithoutEmoji = message.text ? message.text.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim() : '';
|
||||
if (textWithoutEmoji) {
|
||||
addMessage(message.text);
|
||||
}
|
||||
} else if (message.type === 'mcp') {
|
||||
this.handleMCPMessage(message);
|
||||
} else {
|
||||
log(`未知消息类型: ${message.type}`, 'info');
|
||||
addMessage(JSON.stringify(message, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
// 处理TTS消息
|
||||
handleTTSMessage(message) {
|
||||
if (message.state === 'start') {
|
||||
log('服务器开始发送语音', 'info');
|
||||
this.currentSessionId = message.session_id;
|
||||
this.isRemoteSpeaking = true;
|
||||
if (this.onSessionStateChange) {
|
||||
this.onSessionStateChange(true);
|
||||
}
|
||||
} else if (message.state === 'sentence_start') {
|
||||
log(`服务器发送语音段: ${message.text}`, 'info');
|
||||
if (message.text) {
|
||||
addMessage(message.text);
|
||||
}
|
||||
} else if (message.state === 'sentence_end') {
|
||||
log(`语音段结束: ${message.text}`, 'info');
|
||||
} else if (message.state === 'stop') {
|
||||
log('服务器语音传输结束', 'info');
|
||||
this.isRemoteSpeaking = false;
|
||||
if (this.onRecordButtonStateChange) {
|
||||
this.onRecordButtonStateChange(false);
|
||||
}
|
||||
if (this.onSessionStateChange) {
|
||||
this.onSessionStateChange(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理MCP消息
|
||||
handleMCPMessage(message) {
|
||||
const payload = message.payload || {};
|
||||
log(`服务器下发: ${JSON.stringify(message)}`, 'info');
|
||||
|
||||
if (payload.method === 'tools/list') {
|
||||
const tools = getMcpTools();
|
||||
|
||||
const replyMessage = JSON.stringify({
|
||||
"session_id": message.session_id || "",
|
||||
"type": "mcp",
|
||||
"payload": {
|
||||
"jsonrpc": "2.0",
|
||||
"id": payload.id,
|
||||
"result": {
|
||||
"tools": tools
|
||||
}
|
||||
}
|
||||
});
|
||||
log(`客户端上报: ${replyMessage}`, 'info');
|
||||
this.websocket.send(replyMessage);
|
||||
log(`回复MCP工具列表: ${tools.length} 个工具`, 'info');
|
||||
|
||||
} else if (payload.method === 'tools/call') {
|
||||
const toolName = payload.params?.name;
|
||||
const toolArgs = payload.params?.arguments;
|
||||
|
||||
log(`调用工具: ${toolName} 参数: ${JSON.stringify(toolArgs)}`, 'info');
|
||||
|
||||
const result = executeMcpTool(toolName, toolArgs);
|
||||
|
||||
const replyMessage = JSON.stringify({
|
||||
"session_id": message.session_id || "",
|
||||
"type": "mcp",
|
||||
"payload": {
|
||||
"jsonrpc": "2.0",
|
||||
"id": payload.id,
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": JSON.stringify(result)
|
||||
}
|
||||
],
|
||||
"isError": false
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
log(`客户端上报: ${replyMessage}`, 'info');
|
||||
this.websocket.send(replyMessage);
|
||||
} else if (payload.method === 'initialize') {
|
||||
log(`收到工具初始化请求: ${JSON.stringify(payload.params)}`, 'info');
|
||||
} else {
|
||||
log(`未知的MCP方法: ${payload.method}`, 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
// 处理二进制消息
|
||||
async handleBinaryMessage(data) {
|
||||
try {
|
||||
let arrayBuffer;
|
||||
if (data instanceof ArrayBuffer) {
|
||||
arrayBuffer = data;
|
||||
log(`收到ArrayBuffer音频数据,大小: ${data.byteLength}字节`, 'debug');
|
||||
} else if (data instanceof Blob) {
|
||||
arrayBuffer = await data.arrayBuffer();
|
||||
log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug');
|
||||
} else {
|
||||
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const opusData = new Uint8Array(arrayBuffer);
|
||||
const audioPlayer = getAudioPlayer();
|
||||
audioPlayer.enqueueAudioData(opusData);
|
||||
} catch (error) {
|
||||
log(`处理二进制消息出错: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 连接WebSocket服务器
|
||||
async connect() {
|
||||
const config = getConfig();
|
||||
log('正在检查OTA状态...', 'info');
|
||||
saveConnectionUrls();
|
||||
|
||||
try {
|
||||
const otaUrl = document.getElementById('otaUrl').value.trim();
|
||||
const ws = await webSocketConnect(otaUrl, config);
|
||||
if (ws === undefined) {
|
||||
return false;
|
||||
}
|
||||
this.websocket = ws;
|
||||
|
||||
// 设置接收二进制数据的类型为ArrayBuffer
|
||||
this.websocket.binaryType = 'arraybuffer';
|
||||
|
||||
// 设置 MCP 模块的 WebSocket 实例
|
||||
setMcpWebSocket(this.websocket);
|
||||
|
||||
// 设置录音器的WebSocket
|
||||
const audioRecorder = getAudioRecorder();
|
||||
audioRecorder.setWebSocket(this.websocket);
|
||||
|
||||
this.setupEventHandlers();
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
log(`连接错误: ${error.message}`, 'error');
|
||||
if (this.onConnectionStateChange) {
|
||||
this.onConnectionStateChange(false);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 设置事件处理器
|
||||
setupEventHandlers() {
|
||||
this.websocket.onopen = async () => {
|
||||
const url = document.getElementById('serverUrl').value;
|
||||
log(`已连接到服务器: ${url}`, 'success');
|
||||
|
||||
if (this.onConnectionStateChange) {
|
||||
this.onConnectionStateChange(true);
|
||||
}
|
||||
|
||||
// 连接成功后,默认状态为聆听中
|
||||
this.isRemoteSpeaking = false;
|
||||
if (this.onSessionStateChange) {
|
||||
this.onSessionStateChange(false);
|
||||
}
|
||||
|
||||
await this.sendHelloMessage();
|
||||
};
|
||||
|
||||
this.websocket.onclose = () => {
|
||||
log('已断开连接', 'info');
|
||||
|
||||
if (this.onConnectionStateChange) {
|
||||
this.onConnectionStateChange(false);
|
||||
}
|
||||
|
||||
const audioRecorder = getAudioRecorder();
|
||||
audioRecorder.stop();
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
log(`WebSocket错误: ${error.message || '未知错误'}`, 'error');
|
||||
|
||||
if (this.onConnectionStateChange) {
|
||||
this.onConnectionStateChange(false);
|
||||
}
|
||||
};
|
||||
|
||||
this.websocket.onmessage = (event) => {
|
||||
try {
|
||||
if (typeof event.data === 'string') {
|
||||
const message = JSON.parse(event.data);
|
||||
this.handleTextMessage(message);
|
||||
} else {
|
||||
this.handleBinaryMessage(event.data);
|
||||
}
|
||||
} catch (error) {
|
||||
log(`WebSocket消息处理错误: ${error.message}`, 'error');
|
||||
if (typeof event.data === 'string') {
|
||||
addMessage(event.data);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 断开连接
|
||||
disconnect() {
|
||||
if (!this.websocket) return;
|
||||
|
||||
this.websocket.close();
|
||||
const audioRecorder = getAudioRecorder();
|
||||
audioRecorder.stop();
|
||||
}
|
||||
|
||||
// 发送文本消息
|
||||
sendTextMessage(text) {
|
||||
if (text === '' || !this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 如果对方正在说话,先发送打断消息
|
||||
if (this.isRemoteSpeaking && this.currentSessionId) {
|
||||
const abortMessage = {
|
||||
session_id: this.currentSessionId,
|
||||
type: 'abort',
|
||||
reason: 'wake_word_detected'
|
||||
};
|
||||
this.websocket.send(JSON.stringify(abortMessage));
|
||||
log('发送打断消息', 'info');
|
||||
}
|
||||
|
||||
const listenMessage = {
|
||||
type: 'listen',
|
||||
mode: 'manual',
|
||||
state: 'detect',
|
||||
text: text
|
||||
};
|
||||
|
||||
this.websocket.send(JSON.stringify(listenMessage));
|
||||
log(`发送文本消息: ${text}`, 'info');
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
log(`发送消息错误: ${error.message}`, 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取WebSocket实例
|
||||
getWebSocket() {
|
||||
return this.websocket;
|
||||
}
|
||||
|
||||
// 检查是否已连接
|
||||
isConnected() {
|
||||
return this.websocket && this.websocket.readyState === WebSocket.OPEN;
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例
|
||||
let wsHandlerInstance = null;
|
||||
|
||||
export function getWebSocketHandler() {
|
||||
if (!wsHandlerInstance) {
|
||||
wsHandlerInstance = new WebSocketHandler();
|
||||
}
|
||||
return wsHandlerInstance;
|
||||
}
|
||||
274
main/xiaozhi-server/test/js/ui/controller.js
Normal file
274
main/xiaozhi-server/test/js/ui/controller.js
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
// UI控制模块
|
||||
import { loadConfig, saveConfig } from '../config/manager.js';
|
||||
import { getAudioRecorder } from '../core/audio/recorder.js';
|
||||
import { getWebSocketHandler } from '../core/network/websocket.js';
|
||||
|
||||
// UI控制器类
|
||||
export class UIController {
|
||||
constructor() {
|
||||
this.isEditing = false;
|
||||
this.visualizerCanvas = null;
|
||||
this.visualizerContext = null;
|
||||
}
|
||||
|
||||
// 初始化
|
||||
init() {
|
||||
this.visualizerCanvas = document.getElementById('audioVisualizer');
|
||||
this.visualizerContext = this.visualizerCanvas.getContext('2d');
|
||||
|
||||
this.initVisualizer();
|
||||
this.initEventListeners();
|
||||
loadConfig();
|
||||
}
|
||||
|
||||
// 初始化可视化器
|
||||
initVisualizer() {
|
||||
this.visualizerCanvas.width = this.visualizerCanvas.clientWidth;
|
||||
this.visualizerCanvas.height = this.visualizerCanvas.clientHeight;
|
||||
this.visualizerContext.fillStyle = '#fafafa';
|
||||
this.visualizerContext.fillRect(0, 0, this.visualizerCanvas.width, this.visualizerCanvas.height);
|
||||
}
|
||||
|
||||
// 更新状态显示
|
||||
updateStatusDisplay(element, text) {
|
||||
element.textContent = text;
|
||||
element.removeAttribute('style');
|
||||
element.classList.remove('connected');
|
||||
if (text.includes('已连接')) {
|
||||
element.classList.add('connected');
|
||||
}
|
||||
console.log('更新状态:', text, '类列表:', element.className, '样式属性:', element.getAttribute('style'));
|
||||
}
|
||||
|
||||
// 更新连接状态UI
|
||||
updateConnectionUI(isConnected) {
|
||||
const connectionStatus = document.getElementById('connectionStatus');
|
||||
const otaStatus = document.getElementById('otaStatus');
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
const sendTextButton = document.getElementById('sendTextButton');
|
||||
const recordButton = document.getElementById('recordButton');
|
||||
|
||||
if (isConnected) {
|
||||
this.updateStatusDisplay(connectionStatus, '● WS已连接');
|
||||
this.updateStatusDisplay(otaStatus, '● OTA已连接');
|
||||
connectButton.textContent = '断开';
|
||||
messageInput.disabled = false;
|
||||
sendTextButton.disabled = false;
|
||||
recordButton.disabled = false;
|
||||
} else {
|
||||
this.updateStatusDisplay(connectionStatus, '● WS未连接');
|
||||
this.updateStatusDisplay(otaStatus, '● OTA未连接');
|
||||
connectButton.textContent = '连接';
|
||||
messageInput.disabled = true;
|
||||
sendTextButton.disabled = true;
|
||||
recordButton.disabled = true;
|
||||
// 断开连接时,会话状态变为离线
|
||||
this.updateSessionStatus(null);
|
||||
}
|
||||
}
|
||||
|
||||
// 更新录音按钮状态
|
||||
updateRecordButtonState(isRecording, seconds = 0) {
|
||||
const recordButton = document.getElementById('recordButton');
|
||||
if (isRecording) {
|
||||
recordButton.textContent = `停止录音 ${seconds.toFixed(1)}秒`;
|
||||
recordButton.classList.add('recording');
|
||||
} else {
|
||||
recordButton.textContent = '开始录音';
|
||||
recordButton.classList.remove('recording');
|
||||
}
|
||||
recordButton.disabled = false;
|
||||
}
|
||||
|
||||
// 更新会话状态UI
|
||||
updateSessionStatus(isSpeaking) {
|
||||
const sessionStatus = document.getElementById('sessionStatus');
|
||||
if (!sessionStatus) return;
|
||||
|
||||
if (isSpeaking === null) {
|
||||
// 离线状态
|
||||
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智离线中';
|
||||
sessionStatus.className = 'status offline';
|
||||
} else if (isSpeaking) {
|
||||
// 说话中
|
||||
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智说话中';
|
||||
sessionStatus.className = 'status speaking';
|
||||
} else {
|
||||
// 聆听中
|
||||
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智聆听中';
|
||||
sessionStatus.className = 'status listening';
|
||||
}
|
||||
}
|
||||
|
||||
// 更新会话表情
|
||||
updateSessionEmotion(emoji) {
|
||||
const sessionStatus = document.getElementById('sessionStatus');
|
||||
if (!sessionStatus) return;
|
||||
|
||||
// 获取当前文本内容,提取非表情部分
|
||||
let currentText = sessionStatus.textContent;
|
||||
// 移除现有的表情符号
|
||||
currentText = currentText.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim();
|
||||
// 使用 innerHTML 添加带样式的表情
|
||||
sessionStatus.innerHTML = `<span class="emoji-large">${emoji}</span> ${currentText}`;
|
||||
}
|
||||
|
||||
// 绘制音频可视化效果
|
||||
drawVisualizer(dataArray) {
|
||||
this.visualizerContext.fillStyle = '#fafafa';
|
||||
this.visualizerContext.fillRect(0, 0, this.visualizerCanvas.width, this.visualizerCanvas.height);
|
||||
|
||||
const barWidth = (this.visualizerCanvas.width / dataArray.length) * 2.5;
|
||||
let barHeight;
|
||||
let x = 0;
|
||||
|
||||
for (let i = 0; i < dataArray.length; i++) {
|
||||
barHeight = dataArray[i] / 2;
|
||||
|
||||
// 创建渐变色:从紫色到蓝色到青色
|
||||
const hue = 200 + (barHeight / this.visualizerCanvas.height) * 60; // 200-260度,从青色到紫色
|
||||
const saturation = 80 + (barHeight / this.visualizerCanvas.height) * 20; // 饱和度 80-100%
|
||||
const lightness = 45 + (barHeight / this.visualizerCanvas.height) * 15; // 亮度 45-60%
|
||||
|
||||
this.visualizerContext.fillStyle = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
|
||||
this.visualizerContext.fillRect(x, this.visualizerCanvas.height - barHeight, barWidth, barHeight);
|
||||
|
||||
x += barWidth + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化事件监听器
|
||||
initEventListeners() {
|
||||
const wsHandler = getWebSocketHandler();
|
||||
const audioRecorder = getAudioRecorder();
|
||||
|
||||
// 设置WebSocket回调
|
||||
wsHandler.onConnectionStateChange = (isConnected) => {
|
||||
this.updateConnectionUI(isConnected);
|
||||
};
|
||||
|
||||
wsHandler.onRecordButtonStateChange = (isRecording) => {
|
||||
this.updateRecordButtonState(isRecording);
|
||||
};
|
||||
|
||||
wsHandler.onSessionStateChange = (isSpeaking) => {
|
||||
this.updateSessionStatus(isSpeaking);
|
||||
};
|
||||
|
||||
wsHandler.onSessionEmotionChange = (emoji) => {
|
||||
this.updateSessionEmotion(emoji);
|
||||
};
|
||||
|
||||
// 设置录音器回调
|
||||
audioRecorder.onRecordingStart = (seconds) => {
|
||||
this.updateRecordButtonState(true, seconds);
|
||||
};
|
||||
|
||||
audioRecorder.onRecordingStop = () => {
|
||||
this.updateRecordButtonState(false);
|
||||
};
|
||||
|
||||
audioRecorder.onVisualizerUpdate = (dataArray) => {
|
||||
this.drawVisualizer(dataArray);
|
||||
};
|
||||
|
||||
// 连接按钮
|
||||
const connectButton = document.getElementById('connectButton');
|
||||
let isConnecting = false;
|
||||
|
||||
const handleConnect = async () => {
|
||||
if (isConnecting) return;
|
||||
|
||||
if (wsHandler.isConnected()) {
|
||||
wsHandler.disconnect();
|
||||
} else {
|
||||
isConnecting = true;
|
||||
await wsHandler.connect();
|
||||
isConnecting = false;
|
||||
}
|
||||
};
|
||||
|
||||
connectButton.addEventListener('click', handleConnect);
|
||||
|
||||
// 设备配置面板编辑/确定切换
|
||||
const toggleButton = document.getElementById('toggleConfig');
|
||||
const deviceMacInput = document.getElementById('deviceMac');
|
||||
const deviceNameInput = document.getElementById('deviceName');
|
||||
const clientIdInput = document.getElementById('clientId');
|
||||
const tokenInput = document.getElementById('token');
|
||||
|
||||
toggleButton.addEventListener('click', () => {
|
||||
this.isEditing = !this.isEditing;
|
||||
|
||||
deviceMacInput.disabled = !this.isEditing;
|
||||
deviceNameInput.disabled = !this.isEditing;
|
||||
clientIdInput.disabled = !this.isEditing;
|
||||
tokenInput.disabled = !this.isEditing;
|
||||
|
||||
toggleButton.textContent = this.isEditing ? '确定' : '编辑';
|
||||
|
||||
if (!this.isEditing) {
|
||||
saveConfig();
|
||||
}
|
||||
});
|
||||
|
||||
// 标签页切换
|
||||
const tabs = document.querySelectorAll('.tab');
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', () => {
|
||||
tabs.forEach(t => t.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
|
||||
|
||||
tab.classList.add('active');
|
||||
const tabContent = document.getElementById(`${tab.dataset.tab}Tab`);
|
||||
tabContent.classList.add('active');
|
||||
|
||||
if (tab.dataset.tab === 'voice') {
|
||||
setTimeout(() => {
|
||||
this.initVisualizer();
|
||||
}, 50);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 发送文本消息
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
const sendTextButton = document.getElementById('sendTextButton');
|
||||
|
||||
const sendMessage = () => {
|
||||
const message = messageInput.value.trim();
|
||||
if (message && wsHandler.sendTextMessage(message)) {
|
||||
messageInput.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
sendTextButton.addEventListener('click', sendMessage);
|
||||
messageInput.addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') sendMessage();
|
||||
});
|
||||
|
||||
// 录音按钮
|
||||
const recordButton = document.getElementById('recordButton');
|
||||
recordButton.addEventListener('click', () => {
|
||||
if (audioRecorder.isRecording) {
|
||||
audioRecorder.stop();
|
||||
} else {
|
||||
audioRecorder.start();
|
||||
}
|
||||
});
|
||||
|
||||
// 窗口大小变化
|
||||
window.addEventListener('resize', () => this.initVisualizer());
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例
|
||||
let uiControllerInstance = null;
|
||||
|
||||
export function getUIController() {
|
||||
if (!uiControllerInstance) {
|
||||
uiControllerInstance = new UIController();
|
||||
}
|
||||
return uiControllerInstance;
|
||||
}
|
||||
|
|
@ -12,19 +12,19 @@ const logContainer = document.getElementById('logContainer');
|
|||
let visualizerCanvas = document.getElementById('audioVisualizer');
|
||||
|
||||
// ota 是否连接成功,修改成对应的样式
|
||||
export function otaStatusStyle (flan) {
|
||||
if(flan){
|
||||
document.getElementById('otaStatus').textContent = 'ota已连接';
|
||||
export function otaStatusStyle(flan) {
|
||||
if (flan) {
|
||||
document.getElementById('otaStatus').textContent = 'OTA已连接';
|
||||
document.getElementById('otaStatus').style.color = 'green';
|
||||
}else{
|
||||
document.getElementById('otaStatus').textContent = 'ota未连接';
|
||||
} else {
|
||||
document.getElementById('otaStatus').textContent = 'OTA未连接';
|
||||
document.getElementById('otaStatus').style.color = 'red';
|
||||
}
|
||||
}
|
||||
|
||||
// ota 是否连接成功,修改成对应的样式
|
||||
export function getLogContainer (flan) {
|
||||
return logContainer;
|
||||
export function getLogContainer(flan) {
|
||||
return logContainer;
|
||||
}
|
||||
|
||||
// 更新Opus库状态显示
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { getLogContainer } from '../document.js'
|
||||
import { getLogContainer } from '../ui/dom-helper.js'
|
||||
|
||||
const logContainer = getLogContainer();
|
||||
// 日志记录函数
|
||||
|
|
|
|||
|
|
@ -1,670 +0,0 @@
|
|||
const SAMPLE_RATE = 16000;
|
||||
const CHANNELS = 1;
|
||||
const FRAME_SIZE = 960; // 对应于60ms帧大小 (16000Hz * 0.06s = 960 samples)
|
||||
const OPUS_APPLICATION = 2049; // OPUS_APPLICATION_AUDIO
|
||||
const BUFFER_SIZE = 4096;
|
||||
|
||||
let audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: SAMPLE_RATE });
|
||||
let mediaStream, mediaSource, audioProcessor;
|
||||
let recordedPcmData = []; // 存储原始PCM数据
|
||||
let recordedOpusData = []; // 存储Opus编码后的数据
|
||||
let opusEncoder, opusDecoder;
|
||||
let isRecording = false;
|
||||
|
||||
const startButton = document.getElementById("start");
|
||||
const stopButton = document.getElementById("stop");
|
||||
const playButton = document.getElementById("play");
|
||||
const statusLabel = document.getElementById("status");
|
||||
|
||||
startButton.addEventListener("click", startRecording);
|
||||
stopButton.addEventListener("click", stopRecording);
|
||||
playButton.addEventListener("click", playRecording);
|
||||
|
||||
// 初始化Opus编码器与解码器
|
||||
async function initOpus() {
|
||||
if (typeof window.ModuleInstance === 'undefined') {
|
||||
if (typeof Module !== 'undefined') {
|
||||
// 尝试使用全局Module
|
||||
window.ModuleInstance = Module;
|
||||
console.log('使用全局Module作为ModuleInstance');
|
||||
} else {
|
||||
console.error("Opus库未加载,ModuleInstance和Module对象都不存在");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const mod = window.ModuleInstance;
|
||||
|
||||
// 创建编码器
|
||||
opusEncoder = {
|
||||
channels: CHANNELS,
|
||||
sampleRate: SAMPLE_RATE,
|
||||
frameSize: FRAME_SIZE,
|
||||
maxPacketSize: 4000,
|
||||
module: mod,
|
||||
|
||||
// 初始化编码器
|
||||
init: function() {
|
||||
// 获取编码器大小
|
||||
const encoderSize = mod._opus_encoder_get_size(this.channels);
|
||||
console.log(`Opus编码器大小: ${encoderSize}字节`);
|
||||
|
||||
// 分配内存
|
||||
this.encoderPtr = mod._malloc(encoderSize);
|
||||
if (!this.encoderPtr) {
|
||||
throw new Error("无法分配编码器内存");
|
||||
}
|
||||
|
||||
// 初始化编码器
|
||||
const err = mod._opus_encoder_init(
|
||||
this.encoderPtr,
|
||||
this.sampleRate,
|
||||
this.channels,
|
||||
OPUS_APPLICATION
|
||||
);
|
||||
|
||||
if (err < 0) {
|
||||
throw new Error(`Opus编码器初始化失败: ${err}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
// 编码方法
|
||||
encode: function(pcmData) {
|
||||
const mod = this.module;
|
||||
|
||||
// 为PCM数据分配内存
|
||||
const pcmPtr = mod._malloc(pcmData.length * 2); // Int16 = 2字节
|
||||
|
||||
// 将数据复制到WASM内存
|
||||
for (let i = 0; i < pcmData.length; i++) {
|
||||
mod.HEAP16[(pcmPtr >> 1) + i] = pcmData[i];
|
||||
}
|
||||
|
||||
// 为Opus编码数据分配内存
|
||||
const maxEncodedSize = this.maxPacketSize;
|
||||
const encodedPtr = mod._malloc(maxEncodedSize);
|
||||
|
||||
// 编码
|
||||
const encodedBytes = mod._opus_encode(
|
||||
this.encoderPtr,
|
||||
pcmPtr,
|
||||
this.frameSize,
|
||||
encodedPtr,
|
||||
maxEncodedSize
|
||||
);
|
||||
|
||||
if (encodedBytes < 0) {
|
||||
mod._free(pcmPtr);
|
||||
mod._free(encodedPtr);
|
||||
throw new Error(`Opus编码失败: ${encodedBytes}`);
|
||||
}
|
||||
|
||||
// 复制编码后的数据
|
||||
const encodedData = new Uint8Array(encodedBytes);
|
||||
for (let i = 0; i < encodedBytes; i++) {
|
||||
encodedData[i] = mod.HEAPU8[encodedPtr + i];
|
||||
}
|
||||
|
||||
// 释放内存
|
||||
mod._free(pcmPtr);
|
||||
mod._free(encodedPtr);
|
||||
|
||||
return encodedData;
|
||||
},
|
||||
|
||||
// 销毁方法
|
||||
destroy: function() {
|
||||
if (this.encoderPtr) {
|
||||
this.module._free(this.encoderPtr);
|
||||
this.encoderPtr = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 创建解码器
|
||||
opusDecoder = {
|
||||
channels: CHANNELS,
|
||||
rate: SAMPLE_RATE,
|
||||
frameSize: FRAME_SIZE,
|
||||
module: mod,
|
||||
|
||||
// 初始化解码器
|
||||
init: function() {
|
||||
// 获取解码器大小
|
||||
const decoderSize = mod._opus_decoder_get_size(this.channels);
|
||||
console.log(`Opus解码器大小: ${decoderSize}字节`);
|
||||
|
||||
// 分配内存
|
||||
this.decoderPtr = mod._malloc(decoderSize);
|
||||
if (!this.decoderPtr) {
|
||||
throw new Error("无法分配解码器内存");
|
||||
}
|
||||
|
||||
// 初始化解码器
|
||||
const err = mod._opus_decoder_init(
|
||||
this.decoderPtr,
|
||||
this.rate,
|
||||
this.channels
|
||||
);
|
||||
|
||||
if (err < 0) {
|
||||
throw new Error(`Opus解码器初始化失败: ${err}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
// 解码方法
|
||||
decode: function(opusData) {
|
||||
const mod = this.module;
|
||||
|
||||
// 为Opus数据分配内存
|
||||
const opusPtr = mod._malloc(opusData.length);
|
||||
mod.HEAPU8.set(opusData, opusPtr);
|
||||
|
||||
// 为PCM输出分配内存
|
||||
const pcmPtr = mod._malloc(this.frameSize * 2); // Int16 = 2字节
|
||||
|
||||
// 解码
|
||||
const decodedSamples = mod._opus_decode(
|
||||
this.decoderPtr,
|
||||
opusPtr,
|
||||
opusData.length,
|
||||
pcmPtr,
|
||||
this.frameSize,
|
||||
0 // 不使用FEC
|
||||
);
|
||||
|
||||
if (decodedSamples < 0) {
|
||||
mod._free(opusPtr);
|
||||
mod._free(pcmPtr);
|
||||
throw new Error(`Opus解码失败: ${decodedSamples}`);
|
||||
}
|
||||
|
||||
// 复制解码后的数据
|
||||
const decodedData = new Int16Array(decodedSamples);
|
||||
for (let i = 0; i < decodedSamples; i++) {
|
||||
decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i];
|
||||
}
|
||||
|
||||
// 释放内存
|
||||
mod._free(opusPtr);
|
||||
mod._free(pcmPtr);
|
||||
|
||||
return decodedData;
|
||||
},
|
||||
|
||||
// 销毁方法
|
||||
destroy: function() {
|
||||
if (this.decoderPtr) {
|
||||
this.module._free(this.decoderPtr);
|
||||
this.decoderPtr = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化编码器和解码器
|
||||
if (opusEncoder.init() && opusDecoder.init()) {
|
||||
console.log("Opus 编码器和解码器初始化成功。");
|
||||
return true;
|
||||
} else {
|
||||
console.error("Opus 初始化失败");
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Opus 初始化失败:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 将Float32音频数据转换为Int16音频数据
|
||||
function convertFloat32ToInt16(float32Data) {
|
||||
const int16Data = new Int16Array(float32Data.length);
|
||||
for (let i = 0; i < float32Data.length; i++) {
|
||||
// 将[-1,1]范围转换为[-32768,32767]
|
||||
const s = Math.max(-1, Math.min(1, float32Data[i]));
|
||||
int16Data[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
|
||||
}
|
||||
return int16Data;
|
||||
}
|
||||
|
||||
// 将Int16音频数据转换为Float32音频数据
|
||||
function convertInt16ToFloat32(int16Data) {
|
||||
const float32Data = new Float32Array(int16Data.length);
|
||||
for (let i = 0; i < int16Data.length; i++) {
|
||||
// 将[-32768,32767]范围转换为[-1,1]
|
||||
float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF);
|
||||
}
|
||||
return float32Data;
|
||||
}
|
||||
|
||||
function startRecording() {
|
||||
if (isRecording) return;
|
||||
|
||||
// 确保有权限并且AudioContext是活跃的
|
||||
if (audioContext.state === 'suspended') {
|
||||
audioContext.resume().then(() => {
|
||||
console.log("AudioContext已恢复");
|
||||
continueStartRecording();
|
||||
}).catch(err => {
|
||||
console.error("恢复AudioContext失败:", err);
|
||||
statusLabel.textContent = "无法激活音频上下文,请再次点击";
|
||||
});
|
||||
} else {
|
||||
continueStartRecording();
|
||||
}
|
||||
}
|
||||
|
||||
// 实际开始录音的逻辑
|
||||
function continueStartRecording() {
|
||||
// 重置录音数据
|
||||
recordedPcmData = [];
|
||||
recordedOpusData = [];
|
||||
window.audioDataBuffer = new Int16Array(0); // 重置缓冲区
|
||||
|
||||
// 初始化Opus
|
||||
initOpus().then(success => {
|
||||
if (!success) {
|
||||
statusLabel.textContent = "Opus初始化失败";
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("开始录音,参数:", {
|
||||
sampleRate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
frameSize: FRAME_SIZE,
|
||||
bufferSize: BUFFER_SIZE
|
||||
});
|
||||
|
||||
// 请求麦克风权限
|
||||
navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
sampleRate: SAMPLE_RATE,
|
||||
channelCount: CHANNELS,
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true
|
||||
}
|
||||
})
|
||||
.then(stream => {
|
||||
console.log("获取到麦克风流,实际参数:", stream.getAudioTracks()[0].getSettings());
|
||||
|
||||
// 检查流是否有效
|
||||
if (!stream || !stream.getAudioTracks().length || !stream.getAudioTracks()[0].enabled) {
|
||||
throw new Error("获取到的音频流无效");
|
||||
}
|
||||
|
||||
mediaStream = stream;
|
||||
mediaSource = audioContext.createMediaStreamSource(stream);
|
||||
|
||||
// 创建ScriptProcessor(虽然已弃用,但兼容性好)
|
||||
// 在降级到ScriptProcessor之前尝试使用AudioWorklet
|
||||
createAudioProcessor().then(processor => {
|
||||
if (processor) {
|
||||
console.log("使用AudioWorklet处理音频");
|
||||
audioProcessor = processor;
|
||||
// 连接音频处理链
|
||||
mediaSource.connect(audioProcessor);
|
||||
audioProcessor.connect(audioContext.destination);
|
||||
} else {
|
||||
console.log("回退到ScriptProcessor");
|
||||
// 创建ScriptProcessor节点
|
||||
audioProcessor = audioContext.createScriptProcessor(BUFFER_SIZE, CHANNELS, CHANNELS);
|
||||
|
||||
// 处理音频数据
|
||||
audioProcessor.onaudioprocess = processAudioData;
|
||||
|
||||
// 连接音频处理链
|
||||
mediaSource.connect(audioProcessor);
|
||||
audioProcessor.connect(audioContext.destination);
|
||||
}
|
||||
|
||||
// 更新UI
|
||||
isRecording = true;
|
||||
statusLabel.textContent = "录音中...";
|
||||
startButton.disabled = true;
|
||||
stopButton.disabled = false;
|
||||
playButton.disabled = true;
|
||||
}).catch(error => {
|
||||
console.error("创建音频处理器失败:", error);
|
||||
statusLabel.textContent = "创建音频处理器失败";
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("获取麦克风失败:", error);
|
||||
statusLabel.textContent = "获取麦克风失败: " + error.message;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 创建AudioWorklet处理器
|
||||
async function createAudioProcessor() {
|
||||
try {
|
||||
// 尝试使用更现代的AudioWorklet API
|
||||
if ('AudioWorklet' in window && 'AudioWorkletNode' in window) {
|
||||
// 定义AudioWorklet处理器代码
|
||||
const workletCode = `
|
||||
class OpusRecorderProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.buffers = [];
|
||||
this.frameSize = ${FRAME_SIZE};
|
||||
this.buffer = new Float32Array(this.frameSize);
|
||||
this.bufferIndex = 0;
|
||||
this.isRecording = false;
|
||||
|
||||
this.port.onmessage = (event) => {
|
||||
if (event.data.command === 'start') {
|
||||
this.isRecording = true;
|
||||
} else if (event.data.command === 'stop') {
|
||||
this.isRecording = false;
|
||||
// 发送最后的缓冲区
|
||||
if (this.bufferIndex > 0) {
|
||||
const finalBuffer = this.buffer.slice(0, this.bufferIndex);
|
||||
this.port.postMessage({ buffer: finalBuffer });
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
if (!this.isRecording) return true;
|
||||
|
||||
// 获取输入数据
|
||||
const input = inputs[0][0]; // mono channel
|
||||
if (!input || input.length === 0) return true;
|
||||
|
||||
// 将输入数据添加到缓冲区
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
this.buffer[this.bufferIndex++] = input[i];
|
||||
|
||||
// 当缓冲区填满时,发送给主线程
|
||||
if (this.bufferIndex >= this.frameSize) {
|
||||
this.port.postMessage({ buffer: this.buffer.slice() });
|
||||
this.bufferIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('opus-recorder-processor', OpusRecorderProcessor);
|
||||
`;
|
||||
|
||||
// 创建Blob URL
|
||||
const blob = new Blob([workletCode], { type: 'application/javascript' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
// 加载AudioWorklet模块
|
||||
await audioContext.audioWorklet.addModule(url);
|
||||
|
||||
// 创建AudioWorkletNode
|
||||
const workletNode = new AudioWorkletNode(audioContext, 'opus-recorder-processor');
|
||||
|
||||
// 处理从AudioWorklet接收的消息
|
||||
workletNode.port.onmessage = (event) => {
|
||||
if (event.data.buffer) {
|
||||
// 使用与ScriptProcessor相同的处理逻辑
|
||||
processAudioData({
|
||||
inputBuffer: {
|
||||
getChannelData: () => event.data.buffer
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 启动录音
|
||||
workletNode.port.postMessage({ command: 'start' });
|
||||
|
||||
// 保存停止函数
|
||||
workletNode.stopRecording = () => {
|
||||
workletNode.port.postMessage({ command: 'stop' });
|
||||
};
|
||||
|
||||
console.log("AudioWorklet 音频处理器创建成功");
|
||||
return workletNode;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("创建AudioWorklet失败,将使用ScriptProcessor:", error);
|
||||
}
|
||||
|
||||
// 如果AudioWorklet不可用或失败,返回null以便回退到ScriptProcessor
|
||||
return null;
|
||||
}
|
||||
|
||||
// 处理音频数据
|
||||
function processAudioData(e) {
|
||||
// 获取输入缓冲区
|
||||
const inputBuffer = e.inputBuffer;
|
||||
|
||||
// 获取第一个通道的Float32数据
|
||||
const inputData = inputBuffer.getChannelData(0);
|
||||
|
||||
// 添加调试信息
|
||||
const nonZeroCount = Array.from(inputData).filter(x => Math.abs(x) > 0.001).length;
|
||||
console.log(`接收到音频数据: ${inputData.length} 个样本, 非零样本数: ${nonZeroCount}`);
|
||||
|
||||
// 如果全是0,可能是麦克风没有正确获取声音
|
||||
if (nonZeroCount < 5) {
|
||||
console.warn("警告: 检测到大量静音样本,请检查麦克风是否正常工作");
|
||||
// 继续处理,以防有些样本确实是静音
|
||||
}
|
||||
|
||||
// 存储PCM数据用于调试
|
||||
recordedPcmData.push(new Float32Array(inputData));
|
||||
|
||||
// 转换为Int16数据供Opus编码
|
||||
const int16Data = convertFloat32ToInt16(inputData);
|
||||
|
||||
// 如果收集到的数据不是FRAME_SIZE的整数倍,需要进行处理
|
||||
// 创建静态缓冲区来存储不足一帧的数据
|
||||
if (!window.audioDataBuffer) {
|
||||
window.audioDataBuffer = new Int16Array(0);
|
||||
}
|
||||
|
||||
// 合并之前缓存的数据和新数据
|
||||
const combinedData = new Int16Array(window.audioDataBuffer.length + int16Data.length);
|
||||
combinedData.set(window.audioDataBuffer);
|
||||
combinedData.set(int16Data, window.audioDataBuffer.length);
|
||||
|
||||
// 处理完整帧
|
||||
const frameCount = Math.floor(combinedData.length / FRAME_SIZE);
|
||||
console.log(`可编码的完整帧数: ${frameCount}, 缓冲区总大小: ${combinedData.length}`);
|
||||
|
||||
for (let i = 0; i < frameCount; i++) {
|
||||
const frameData = combinedData.subarray(i * FRAME_SIZE, (i + 1) * FRAME_SIZE);
|
||||
|
||||
try {
|
||||
console.log(`编码第 ${i+1}/${frameCount} 帧, 帧大小: ${frameData.length}`);
|
||||
const encodedData = opusEncoder.encode(frameData);
|
||||
if (encodedData) {
|
||||
console.log(`编码成功: ${encodedData.length} 字节`);
|
||||
recordedOpusData.push(encodedData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Opus编码帧 ${i+1} 失败:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存剩余不足一帧的数据
|
||||
const remainingSamples = combinedData.length % FRAME_SIZE;
|
||||
if (remainingSamples > 0) {
|
||||
window.audioDataBuffer = combinedData.subarray(frameCount * FRAME_SIZE);
|
||||
console.log(`保留 ${remainingSamples} 个样本到下一次处理`);
|
||||
} else {
|
||||
window.audioDataBuffer = new Int16Array(0);
|
||||
}
|
||||
}
|
||||
|
||||
function stopRecording() {
|
||||
if (!isRecording) return;
|
||||
|
||||
// 处理剩余的缓冲数据
|
||||
if (window.audioDataBuffer && window.audioDataBuffer.length > 0) {
|
||||
console.log(`停止录音,处理剩余的 ${window.audioDataBuffer.length} 个样本`);
|
||||
// 如果剩余数据不足一帧,可以通过补零的方式凑成一帧
|
||||
if (window.audioDataBuffer.length < FRAME_SIZE) {
|
||||
const paddedFrame = new Int16Array(FRAME_SIZE);
|
||||
paddedFrame.set(window.audioDataBuffer);
|
||||
// 剩余部分填充为0
|
||||
for (let i = window.audioDataBuffer.length; i < FRAME_SIZE; i++) {
|
||||
paddedFrame[i] = 0;
|
||||
}
|
||||
try {
|
||||
console.log(`编码最后一帧(补零): ${paddedFrame.length} 样本`);
|
||||
const encodedData = opusEncoder.encode(paddedFrame);
|
||||
if (encodedData) {
|
||||
recordedOpusData.push(encodedData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("最后一帧Opus编码失败:", error);
|
||||
}
|
||||
} else {
|
||||
// 如果数据超过一帧,按正常流程处理
|
||||
processAudioData({
|
||||
inputBuffer: {
|
||||
getChannelData: () => convertInt16ToFloat32(window.audioDataBuffer)
|
||||
}
|
||||
});
|
||||
}
|
||||
window.audioDataBuffer = null;
|
||||
}
|
||||
|
||||
// 如果使用的是AudioWorklet,调用其特定的停止方法
|
||||
if (audioProcessor && typeof audioProcessor.stopRecording === 'function') {
|
||||
audioProcessor.stopRecording();
|
||||
}
|
||||
|
||||
// 停止麦克风
|
||||
if (mediaStream) {
|
||||
mediaStream.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
// 断开音频处理链
|
||||
if (audioProcessor) {
|
||||
try {
|
||||
audioProcessor.disconnect();
|
||||
if (mediaSource) mediaSource.disconnect();
|
||||
} catch (error) {
|
||||
console.warn("断开音频处理链时出错:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// 更新UI
|
||||
isRecording = false;
|
||||
statusLabel.textContent = "已停止录音,收集了 " + recordedOpusData.length + " 帧Opus数据";
|
||||
startButton.disabled = false;
|
||||
stopButton.disabled = true;
|
||||
playButton.disabled = recordedOpusData.length === 0;
|
||||
|
||||
console.log("录制完成:",
|
||||
"PCM帧数:", recordedPcmData.length,
|
||||
"Opus帧数:", recordedOpusData.length);
|
||||
}
|
||||
|
||||
function playRecording() {
|
||||
if (!recordedOpusData.length) {
|
||||
statusLabel.textContent = "没有可播放的录音";
|
||||
return;
|
||||
}
|
||||
|
||||
// 将所有Opus数据解码为PCM
|
||||
let allDecodedData = [];
|
||||
|
||||
for (const opusData of recordedOpusData) {
|
||||
try {
|
||||
// 解码为Int16数据
|
||||
const decodedData = opusDecoder.decode(opusData);
|
||||
|
||||
if (decodedData && decodedData.length > 0) {
|
||||
// 将Int16数据转换为Float32
|
||||
const float32Data = convertInt16ToFloat32(decodedData);
|
||||
|
||||
// 添加到总解码数据中
|
||||
allDecodedData.push(...float32Data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Opus解码失败:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有解码出数据,返回
|
||||
if (allDecodedData.length === 0) {
|
||||
statusLabel.textContent = "解码失败,无法播放";
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建音频缓冲区
|
||||
const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE);
|
||||
audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0);
|
||||
|
||||
// 创建音频源并播放
|
||||
const source = audioContext.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(audioContext.destination);
|
||||
source.start();
|
||||
|
||||
// 更新UI
|
||||
statusLabel.textContent = "正在播放...";
|
||||
playButton.disabled = true;
|
||||
|
||||
// 播放结束后恢复UI
|
||||
source.onended = () => {
|
||||
statusLabel.textContent = "播放完毕";
|
||||
playButton.disabled = false;
|
||||
};
|
||||
}
|
||||
|
||||
// 模拟服务端返回的Opus数据进行解码播放
|
||||
function playOpusFromServer(opusData) {
|
||||
// 这个函数展示如何处理服务端返回的opus数据
|
||||
// opusData应该是一个包含opus帧的数组
|
||||
|
||||
if (!opusDecoder) {
|
||||
initOpus().then(success => {
|
||||
if (success) {
|
||||
decodeAndPlayOpusData(opusData);
|
||||
} else {
|
||||
statusLabel.textContent = "Opus解码器初始化失败";
|
||||
}
|
||||
});
|
||||
} else {
|
||||
decodeAndPlayOpusData(opusData);
|
||||
}
|
||||
}
|
||||
|
||||
function decodeAndPlayOpusData(opusData) {
|
||||
let allDecodedData = [];
|
||||
|
||||
for (const frame of opusData) {
|
||||
try {
|
||||
const decodedData = opusDecoder.decode(frame);
|
||||
if (decodedData && decodedData.length > 0) {
|
||||
const float32Data = convertInt16ToFloat32(decodedData);
|
||||
allDecodedData.push(...float32Data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("服务端Opus数据解码失败:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (allDecodedData.length === 0) {
|
||||
statusLabel.textContent = "服务端数据解码失败";
|
||||
return;
|
||||
}
|
||||
|
||||
const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE);
|
||||
audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0);
|
||||
|
||||
const source = audioContext.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(audioContext.destination);
|
||||
source.start();
|
||||
|
||||
statusLabel.textContent = "正在播放服务端数据...";
|
||||
source.onended = () => statusLabel.textContent = "服务端数据播放完毕";
|
||||
}
|
||||
|
|
@ -1,464 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Opus 编解码测试</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background-color: #f5f5f5;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
button {
|
||||
padding: 8px 15px;
|
||||
margin-right: 10px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background-color: #4285f4;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #3367d6;
|
||||
}
|
||||
button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
#status {
|
||||
font-weight: bold;
|
||||
}
|
||||
#scriptStatus {
|
||||
position: fixed;
|
||||
top: 10px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
display: block;
|
||||
z-index: 100;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
#scriptStatus.info {
|
||||
background-color: #e8f0fe;
|
||||
color: #4285f4;
|
||||
border-left: 4px solid #4285f4;
|
||||
}
|
||||
#scriptStatus.success {
|
||||
background-color: #e6f4ea;
|
||||
color: #0f9d58;
|
||||
border-left: 4px solid #0f9d58;
|
||||
}
|
||||
#scriptStatus.error {
|
||||
background-color: #fce8e6;
|
||||
color: #db4437;
|
||||
border-left: 4px solid #db4437;
|
||||
}
|
||||
#debugInfo {
|
||||
margin-top: 20px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
padding: 10px;
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
display: none;
|
||||
}
|
||||
#showDebug {
|
||||
margin-top: 10px;
|
||||
background-color: #f5f5f5;
|
||||
color: #444;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>Opus 编解码录音播放测试</h2>
|
||||
|
||||
<div id="scriptStatus" class="info">正在加载Opus库...</div>
|
||||
|
||||
<div>
|
||||
<button id="initAudio" style="background-color: #34a853;">初始化音频</button>
|
||||
<button id="testMic" style="background-color: #fbbc05;">测试麦克风</button>
|
||||
<p></p>
|
||||
<button id="start" disabled>开始录音</button>
|
||||
<button id="stop" disabled>停止录音</button>
|
||||
<button id="play" disabled>播放录音</button>
|
||||
<p>录音状态: <span id="status">待机,正在初始化...</span></p>
|
||||
<button id="showDebug">显示/隐藏调试信息</button>
|
||||
<div id="debugInfo"></div>
|
||||
<div id="audioMeter" style="margin-top: 10px; height: 20px; background-color: #eee; border-radius: 4px; overflow: hidden; display: none;">
|
||||
<div id="audioLevel" style="height: 100%; width: 0%; background-color: #4285f4; transition: width 0.1s;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Opus解码库 - 这个库会设置一个全局Module变量 -->
|
||||
<script>
|
||||
// 定义全局变量以跟踪库加载状态
|
||||
window.opusLoaded = false;
|
||||
window.startButton = document.getElementById("start");
|
||||
window.stopButton = document.getElementById("stop");
|
||||
window.playButton = document.getElementById("play");
|
||||
window.statusLabel = document.getElementById("status");
|
||||
window.debugInfo = document.getElementById("debugInfo");
|
||||
window.audioContextReady = false;
|
||||
window.testMicActive = false;
|
||||
|
||||
// 显示/隐藏调试信息
|
||||
document.getElementById("showDebug").addEventListener("click", function() {
|
||||
if (debugInfo.style.display === "none" || !debugInfo.style.display) {
|
||||
debugInfo.style.display = "block";
|
||||
this.textContent = "隐藏调试信息";
|
||||
} else {
|
||||
debugInfo.style.display = "none";
|
||||
this.textContent = "显示调试信息";
|
||||
}
|
||||
});
|
||||
|
||||
// 添加初始化音频按钮事件
|
||||
document.getElementById("initAudio").addEventListener("click", function() {
|
||||
initializeAudioSystem();
|
||||
});
|
||||
|
||||
// 添加测试麦克风按钮事件
|
||||
document.getElementById("testMic").addEventListener("click", function() {
|
||||
if (window.testMicActive) {
|
||||
stopMicTest();
|
||||
} else {
|
||||
startMicTest();
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化音频系统
|
||||
function initializeAudioSystem() {
|
||||
try {
|
||||
log("初始化音频系统...");
|
||||
// 创建临时AudioContext来触发用户授权
|
||||
const tempContext = new (window.AudioContext || window.webkitAudioContext)({
|
||||
sampleRate: 16000,
|
||||
latencyHint: 'interactive'
|
||||
});
|
||||
|
||||
// 创建振荡器并播放短促的声音
|
||||
const oscillator = tempContext.createOscillator();
|
||||
const gain = tempContext.createGain();
|
||||
gain.gain.value = 0.1; // 很小的音量
|
||||
oscillator.connect(gain);
|
||||
gain.connect(tempContext.destination);
|
||||
oscillator.frequency.value = 440; // A4
|
||||
oscillator.start();
|
||||
|
||||
// 0.2秒后停止
|
||||
setTimeout(() => {
|
||||
oscillator.stop();
|
||||
// 关闭上下文
|
||||
tempContext.close().then(() => {
|
||||
log("音频系统初始化成功", "success");
|
||||
updateScriptStatus("音频系统已激活", "success");
|
||||
document.getElementById("initAudio").disabled = true;
|
||||
document.getElementById("initAudio").textContent = "音频已初始化";
|
||||
window.audioContextReady = true;
|
||||
|
||||
// 如果Opus已加载,启用开始录音按钮
|
||||
if (window.opusLoaded) {
|
||||
startButton.disabled = false;
|
||||
}
|
||||
});
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
log("初始化音频系统失败: " + err.message, "error");
|
||||
updateScriptStatus("初始化音频失败: " + err.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// 测试麦克风
|
||||
function startMicTest() {
|
||||
const audioMeter = document.getElementById("audioMeter");
|
||||
const audioLevel = document.getElementById("audioLevel");
|
||||
const testMicBtn = document.getElementById("testMic");
|
||||
|
||||
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
||||
log("浏览器不支持麦克风访问", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
log("开始麦克风测试...");
|
||||
audioMeter.style.display = "block";
|
||||
testMicBtn.textContent = "停止测试";
|
||||
testMicBtn.style.backgroundColor = "#ea4335";
|
||||
window.testMicActive = true;
|
||||
|
||||
// 创建音频上下文
|
||||
const testContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||
window.testContext = testContext;
|
||||
|
||||
// 获取麦克风权限
|
||||
navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true
|
||||
}
|
||||
})
|
||||
.then(stream => {
|
||||
log("已获取麦克风访问权限", "success");
|
||||
|
||||
// 保存流以便稍后关闭
|
||||
window.testStream = stream;
|
||||
|
||||
// 创建音频分析器
|
||||
const source = testContext.createMediaStreamSource(stream);
|
||||
const analyser = testContext.createAnalyser();
|
||||
analyser.fftSize = 256;
|
||||
source.connect(analyser);
|
||||
|
||||
// 创建音量显示更新函数
|
||||
const bufferLength = analyser.frequencyBinCount;
|
||||
const dataArray = new Uint8Array(bufferLength);
|
||||
|
||||
function updateMeter() {
|
||||
if (!window.testMicActive) return;
|
||||
|
||||
analyser.getByteFrequencyData(dataArray);
|
||||
|
||||
// 计算音量级别 (0-100)
|
||||
let sum = 0;
|
||||
for (let i = 0; i < bufferLength; i++) {
|
||||
sum += dataArray[i];
|
||||
}
|
||||
const average = sum / bufferLength;
|
||||
const level = Math.min(100, Math.max(0, average * 2));
|
||||
|
||||
// 更新音量计
|
||||
audioLevel.style.width = level + "%";
|
||||
|
||||
// 如果有声音,记录日志
|
||||
if (level > 10) {
|
||||
log(`检测到声音: ${level.toFixed(1)}%`);
|
||||
}
|
||||
|
||||
// 循环更新
|
||||
window.testMicAnimationFrame = requestAnimationFrame(updateMeter);
|
||||
}
|
||||
|
||||
// 开始更新
|
||||
updateMeter();
|
||||
})
|
||||
.catch(err => {
|
||||
log("麦克风测试失败: " + err.message, "error");
|
||||
window.testMicActive = false;
|
||||
testMicBtn.textContent = "测试麦克风";
|
||||
testMicBtn.style.backgroundColor = "#fbbc05";
|
||||
audioMeter.style.display = "none";
|
||||
});
|
||||
}
|
||||
|
||||
// 停止麦克风测试
|
||||
function stopMicTest() {
|
||||
const audioMeter = document.getElementById("audioMeter");
|
||||
const testMicBtn = document.getElementById("testMic");
|
||||
|
||||
log("停止麦克风测试");
|
||||
window.testMicActive = false;
|
||||
testMicBtn.textContent = "测试麦克风";
|
||||
testMicBtn.style.backgroundColor = "#fbbc05";
|
||||
|
||||
// 停止分析器动画
|
||||
if (window.testMicAnimationFrame) {
|
||||
cancelAnimationFrame(window.testMicAnimationFrame);
|
||||
}
|
||||
|
||||
// 停止麦克风流
|
||||
if (window.testStream) {
|
||||
window.testStream.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
// 关闭测试上下文
|
||||
if (window.testContext) {
|
||||
window.testContext.close();
|
||||
}
|
||||
|
||||
// 隐藏音量计
|
||||
audioMeter.style.display = "none";
|
||||
}
|
||||
|
||||
// 初始化AudioContext
|
||||
function initAudioContext() {
|
||||
try {
|
||||
window.AudioContext = window.AudioContext || window.webkitAudioContext;
|
||||
if (!window.AudioContext) {
|
||||
throw new Error("浏览器不支持AudioContext");
|
||||
}
|
||||
|
||||
// 我们在app.js中会创建AudioContext,这里只检查兼容性
|
||||
log("AudioContext API 可用");
|
||||
return true;
|
||||
} catch (err) {
|
||||
log("AudioContext初始化失败: " + err.message, "error");
|
||||
updateScriptStatus("AudioContext初始化失败,录音功能不可用", "error");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查麦克风权限
|
||||
function checkMicrophonePermission() {
|
||||
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
||||
log("浏览器不支持getUserMedia API", "error");
|
||||
updateScriptStatus("浏览器不支持录音功能", "error");
|
||||
return false;
|
||||
}
|
||||
|
||||
log("getUserMedia API 可用");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 添加调试日志
|
||||
function log(message, type = "info") {
|
||||
console.log(message);
|
||||
const time = new Date().toLocaleTimeString();
|
||||
const entry = document.createElement("div");
|
||||
entry.textContent = `[${time}] ${message}`;
|
||||
|
||||
if (type === "error") {
|
||||
entry.style.color = "#db4437";
|
||||
} else if (type === "success") {
|
||||
entry.style.color = "#0f9d58";
|
||||
}
|
||||
|
||||
debugInfo.appendChild(entry);
|
||||
debugInfo.scrollTop = debugInfo.scrollHeight;
|
||||
}
|
||||
|
||||
// 更新脚本状态显示
|
||||
function updateScriptStatus(message, type) {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) {
|
||||
statusElement.textContent = message;
|
||||
statusElement.className = type;
|
||||
statusElement.style.display = 'block';
|
||||
}
|
||||
log(message, type);
|
||||
}
|
||||
|
||||
// 检查Opus库是否已加载
|
||||
function checkOpusLoaded() {
|
||||
try {
|
||||
// 检查Module是否存在(本地库导出的全局变量)
|
||||
if (typeof Module === 'undefined') {
|
||||
log("Module对象不存在", "error");
|
||||
throw new Error('Opus库未加载,Module对象不存在');
|
||||
}
|
||||
|
||||
// 记录Module对象结构以便调试
|
||||
log("Module对象结构: " + Object.keys(Module).join(", "));
|
||||
|
||||
// 尝试使用全局Module函数
|
||||
if (typeof Module._opus_decoder_get_size === 'function') {
|
||||
window.ModuleInstance = Module;
|
||||
log('Opus库加载成功(使用全局Module)', "success");
|
||||
updateScriptStatus('Opus库加载成功', 'success');
|
||||
|
||||
// 启用开始录音按钮
|
||||
startButton.disabled = false;
|
||||
statusLabel.textContent = "待机";
|
||||
|
||||
// 3秒后隐藏状态
|
||||
setTimeout(() => {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
}, 3000);
|
||||
|
||||
window.opusLoaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 尝试使用Module.instance
|
||||
if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') {
|
||||
window.ModuleInstance = Module.instance;
|
||||
log('Opus库加载成功(使用Module.instance)', "success");
|
||||
updateScriptStatus('Opus库加载成功', 'success');
|
||||
|
||||
// 启用开始录音按钮
|
||||
startButton.disabled = false;
|
||||
statusLabel.textContent = "待机";
|
||||
|
||||
// 3秒后隐藏状态
|
||||
setTimeout(() => {
|
||||
const statusElement = document.getElementById('scriptStatus');
|
||||
if (statusElement) statusElement.style.display = 'none';
|
||||
}, 3000);
|
||||
|
||||
window.opusLoaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查是否有其他导出方式
|
||||
log("Module上可用方法: " + Object.getOwnPropertyNames(Module).filter(prop => typeof Module[prop] === 'function').join(", "));
|
||||
|
||||
if (typeof Module.onRuntimeInitialized === 'function' || typeof Module.onRuntimeInitialized === 'undefined') {
|
||||
log("Module.onRuntimeInitialized 尚未执行,等待模块初始化完成...");
|
||||
// Module可能未完成初始化,注册回调
|
||||
Module.onRuntimeInitialized = function() {
|
||||
log("Opus库运行时初始化完成,重新检查");
|
||||
checkOpusLoaded();
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new Error('Opus解码函数未找到,可能Module结构不正确');
|
||||
} catch (err) {
|
||||
log(`Opus库加载失败: ${err.message}`, "error");
|
||||
updateScriptStatus(`Opus库加载失败: ${err.message}`, 'error');
|
||||
statusLabel.textContent = "错误:Opus库加载失败";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后检查浏览器能力和Opus库
|
||||
window.addEventListener('load', function() {
|
||||
log("页面加载完成,开始初始化...");
|
||||
updateScriptStatus('正在初始化录音环境...', 'info');
|
||||
|
||||
// 检查浏览器能力
|
||||
const audioContextSupported = initAudioContext();
|
||||
const microphoneSupported = checkMicrophonePermission();
|
||||
|
||||
if (!audioContextSupported || !microphoneSupported) {
|
||||
log("浏览器不支持必要API,无法进行录音", "error");
|
||||
updateScriptStatus('浏览器不支持录音功能', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
log("检查环境完成,开始加载Opus库");
|
||||
updateScriptStatus('正在加载Opus库...', 'info');
|
||||
|
||||
// 延迟一小段时间再检查,确保库有时间加载
|
||||
setTimeout(function checkAndRetry() {
|
||||
if (!checkOpusLoaded()) {
|
||||
// 如果加载失败,5秒后重试
|
||||
log("Opus库加载失败,5秒后重试...");
|
||||
updateScriptStatus('Opus库加载失败,正在重试...', 'error');
|
||||
setTimeout(checkAndRetry, 5000);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// 防止按钮误操作
|
||||
document.getElementById("stop").disabled = true;
|
||||
document.getElementById("play").disabled = true;
|
||||
</script>
|
||||
<script src="./../libopus.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,425 +0,0 @@
|
|||
body {
|
||||
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
background-color: white;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
padding: 10px 20px 10px 20px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #333;
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 5px;
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
margin-top: 0;
|
||||
color: #444;
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
.section h2 .toggle-button {
|
||||
margin-left: auto;
|
||||
padding: 4px 12px;
|
||||
font-size: 12px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
height: 28px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.device-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin-left: 20px;
|
||||
padding: 0 15px;
|
||||
background-color: #f9f9f9;
|
||||
border-radius: 4px;
|
||||
height: 28px;
|
||||
line-height: 28px;
|
||||
}
|
||||
|
||||
.device-info span {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.device-info strong {
|
||||
color: #333;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.config-panel {
|
||||
display: none;
|
||||
transition: all 0.3s ease;
|
||||
margin-top: 5px;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.config-panel.expanded {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.control-panel {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 8px 15px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
background-color: #4285f4;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #3367d6;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#serverUrl,
|
||||
#otaUrl {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.message-input {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
#messageInput {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#nfcCardId {
|
||||
flex-grow: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.conversation {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
padding: 10px;
|
||||
background-color: white;
|
||||
flex: 1;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 10px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
.user {
|
||||
background-color: #e2f2ff;
|
||||
margin-left: auto;
|
||||
margin-right: 10px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.server {
|
||||
background-color: #f0f0f0;
|
||||
margin-right: auto;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.status {
|
||||
color: #666;
|
||||
font-style: italic;
|
||||
font-size: 14px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.audio-controls {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.audio-visualizer {
|
||||
height: 60px;
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.record-button {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
.record-button:hover {
|
||||
background-color: #c53929;
|
||||
}
|
||||
|
||||
.record-button.recording {
|
||||
animation: pulse 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
50% {
|
||||
background-color: #ff6659;
|
||||
}
|
||||
|
||||
100% {
|
||||
background-color: #db4437;
|
||||
}
|
||||
}
|
||||
|
||||
#logContainer {
|
||||
margin-top: 0;
|
||||
padding: 10px;
|
||||
background-color: #f0f0f0;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
height: 300px;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
margin: 5px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.log-info {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.log-error {
|
||||
color: #db4437;
|
||||
}
|
||||
|
||||
.log-success {
|
||||
color: #0f9d58;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -60%);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
}
|
||||
|
||||
.script-status {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.script-loaded {
|
||||
background-color: #0f9d58;
|
||||
}
|
||||
|
||||
.script-loading {
|
||||
background-color: #f4b400;
|
||||
}
|
||||
|
||||
.script-error {
|
||||
background-color: #db4437;
|
||||
}
|
||||
|
||||
.script-list {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
background-color: #f9f9f9;
|
||||
border-radius: 5px;
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#scriptStatus.success {
|
||||
background-color: #e6f4ea;
|
||||
color: #0f9d58;
|
||||
border-left: 4px solid #0f9d58;
|
||||
}
|
||||
|
||||
#scriptStatus.error {
|
||||
background-color: #fce8e6;
|
||||
color: #db4437;
|
||||
border-left: 4px solid #db4437;
|
||||
}
|
||||
|
||||
#scriptStatus.warning {
|
||||
background-color: #fef7e0;
|
||||
color: #f4b400;
|
||||
border-left: 4px solid #f4b400;
|
||||
}
|
||||
|
||||
/* 标签页样式 */
|
||||
.tabs {
|
||||
display: flex;
|
||||
margin-bottom: 20px;
|
||||
border-bottom: 2px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 10px 20px;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: 16px;
|
||||
color: #666;
|
||||
position: relative;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
color: #4285f4;
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
color: #4285f4;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.tab.active::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -2px;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background-color: #4285f4;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab-content.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.flex-container {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.config-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.config-item label {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
margin-right: 10px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.config-item input {
|
||||
flex-grow: 1;
|
||||
padding: 6px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.control-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.connection-controls {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.connection-controls input {
|
||||
flex: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 5px;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.connection-controls button {
|
||||
white-space: nowrap;
|
||||
padding: 8px 15px;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin-left: 20px;
|
||||
padding: 0 15px;
|
||||
background-color: #f9f9f9;
|
||||
border-radius: 4px;
|
||||
height: 28px;
|
||||
line-height: 28px;
|
||||
}
|
||||
|
||||
.connection-status span {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.connection-status .status {
|
||||
color: #333;
|
||||
font-weight: 500;
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue